id
stringlengths 5
27
| question
stringlengths 19
69.9k
| title
stringlengths 1
150
| tags
stringlengths 1
118
| accepted_answer
stringlengths 4
29.9k
⌀ |
---|---|---|---|---|
_webapps.21671 | By default, I get about 12 labels displayed.If I hover the mouse over the lower part of the pane, the labels unfold and all additional labels are revealed.I'd like to know if it's possible to have them all displayed by default (without the annoying javascript fold-up/unfold trick). | Can Gmail be configured to display ALL labels on the right pane? | gmail;gmail labels | null |
_codereview.142932 | I made a simple linked list in C with the following functionalities:Create(creates the list); Find(searches for an element in the list); Insert(inserts a value at the beginning of the list); Destroy(destroys the entire list). It only uses integers (for simplicity), and I want to know for possible errors and how to improve it in general.The node structure:typedef struct sllist{ int val; struct sllist* next;}sllnode;The functions:#include <stdio.h>#include <stdlib.h>#include node.c/* *Creates the linked list with a single value*/sllnode *create(int value){ sllnode *node; node = (sllnode *) malloc(sizeof(sllnode)); if (node == NULL) { puts(Memory error); return NULL; } node->val = value; node->next = NULL; return node;}/* *Searches for an element in the list. *Returns 1 if its found or 0 if not*/int find(sllnode *head, int value){ sllnode *trav = head; do { if (trav->val == value) { return 1; } else { trav = trav->next; } } while (trav != NULL); return 0;}/* *Inserts a value at the beginning of the list*/sllnode *insert(sllnode *head, int value){ sllnode *new_node = (sllnode *) malloc(sizeof(sllnode)); if (new_node == NULL) { puts(Memory error); return NULL; } new_node->val = value; new_node->next = head; head = new_node; return head;}/* *Destroys (i.e frees) the whole list*/void *destroy(sllnode *head){ sllnode *temp = head; while (temp != NULL) { free(temp); temp = temp->next; } free(head);}int main(void){ return 0;} | Linked List simple implementation | beginner;c;linked list;pointers | Including a C fileConvention is that all shared stuff is declared in .h files.Minor 1In destroy(), you have the return type void*. Remove the pointer star and it's fine.Minor 2sllnode *create(int value){ sllnode *node; node = (sllnode *) malloc(sizeof(sllnode)); if (node == NULL) { puts(Memory error); return NULL; } ...It's a bad idea to abuse standard output from within algorithms/data structures. After all, everything that may go wrong is that there is no memory enough for the new node; returning NULL may well indicate that situation.Minor 3node = (sllnode *) malloc(sizeof(sllnode));More idiomatic C isnode = malloc(sizeof *node);Minor 4You append the new nodes in reversed direction. Basically this is a (linked) stack and not a list.Minor 5while (temp != NULL){ free(temp); temp = temp->next;}Don't do this. Instead have something like while (temp) { next_node = temp->next; free(temp); temp = next_node;}Summa summarumFor a starter, I had this in mind:#include <stdio.h>#include <stdlib.h>typedef struct linked_list_node { int value; struct linked_list_node* next;} linked_list_node;typedef struct { linked_list_node* head; linked_list_node* tail;} linked_list;void linked_list_init(linked_list* list){ if (!list) { return; } list->head = NULL; list->tail = NULL;}void linked_list_free(linked_list* list){ linked_list_node* current_node; linked_list_node* next_node; if (!list) { return; } current_node = list->head; while (current_node) { next_node = current_node->next; free(current_node); current_node = next_node; }}int linked_list_append(linked_list* list, int value){ linked_list_node* new_node; if (!list) { return 1; } new_node = malloc(sizeof *new_node); if (!new_node) { return 1; } new_node->value = value; if (list->head) { list->tail->next = new_node; } else { list->head = new_node; } list->tail = new_node; return 0;}int linked_list_index_of(linked_list* list, int value){ int index; linked_list_node* node; if (!list) { return -2; } for (node = list->head, index = 0; node; node = node->next, index++) { if (node->value == value) { return index; } } return -1;}int main() { int i; linked_list my_list; linked_list_init(&my_list); for (i = 0; i < 10; ++i) { linked_list_append(&my_list, i); } printf(%d %d\n, linked_list_index_of(&my_list, 4), linked_list_index_of(&my_list, 100)); linked_list_free(&my_list); return 0;}Hope that helps. |
_scicomp.26668 | I have an optimization problem that I'm trying to cast as a linear program. However, I have an objective function of the form$$\begin{array}{ll} \text{maximize} & a_1 x_1 - a_2 \lvert x_1\rvert\\ \text{subject to} & \color{gray}{\text{(constraints)}}\end{array}$$I tried doing the classic linear reformulation using a replacement variable $x_1'$ and adding the constraints:$$x_1 - x'_1 \le 0$$$$-x_1 - x'_1 \le 0$$The problem that I ran into is that the solutions seem to be constraining $x_1$ to positive values, even when they obviously should be negative. Looking at the docs I have on this, it seems that this is because the assumption is that all values of it will be maximized or minimized in the same direction and if you break this assumption then you're forced to utilize the M/ILP method with binary determiners in order to solve this.I haven't found any discussion on the limitation of using the variables $x_1$ and $x'_1$ in the objective function. Is it possible to do what I want without resorting to ILP? | Is it possible to use both the absolute value and the actual value of a variable in a linear objective function? | optimization;linear programming | $$\begin{array}{ll} \text{maximize} & a_1 x - a_2 | x |\\ \text{subject to} & \color{gray}{\text{(linear constraints)}}\end{array}$$where $a_1, a_2 \in \mathbb R$ are given. Writing as a minimization problem,$$\begin{array}{ll} \text{minimize} & a_2 | x | - a_1 x\\ \text{subject to} & \color{gray}{\text{(linear constraints)}}\end{array}$$The objective function to be minimized is$$f (x) := a_2 |x| - a_1 x = \begin{cases} -(a_1 + a_2) \, x & \text{if } x \leq 0\\ \,\,\,\,(a_2 - a_1) \, x & \text{if } x \geq 0\end{cases}$$If $a_1, a_2 \geq 0$, then $f$ is convex. In that case, the epigraph of $f$ is also convex and can be defined by the intersection of half-spaces, as follows$$\left\{ (x,y) \in \mathbb R^2 \mid y \geq (a_2 - a_1) \, x \land y \geq -(a_1 + a_2) \, x \right\}$$and we have the following linear program in $x, y \in \mathbb R$$$\begin{array}{ll} \text{minimize} & \,\,\,\, y\\ \text{subject to} & \,\,\,\,(a_2 - a_1) \, x - y \leq 0\\ & -(a_1 + a_2) \, x - y \leq 0\\ & \,\,\,\,\,\color{gray}{\text{(linear constraints on } x)}\end{array}$$ |
_unix.123367 | I set up Dovecot and Postfix, but when I try to authenticate with Thunderbird, it gives this error: Thunderbird failed to find the settings for your email account.==> /var/log/dovecot-info.log <==Apr 06 10:42:16 auth: Debug: auth client connected (pid=13243)Apr 06 10:42:16 imap-login: Info: Disconnected (no auth attempts): rip=76.xx.xx.xx, lip=172.31.15.65, TLS: SSL_read() failed: error:14094412:SSL routines:SSL3_READ_BYTES:sslv3 alert bad certificate: SSL alert number 42==> /var/log/maillog <==Apr 6 10:42:16 ip-172-31-15-65 postfix/smtpd[13238]: lost connection after UNKNOWN from user-xxxxxx.cable.mindspring.com[76.xx.xx.xxx]Apr 6 10:42:16 ip-172-31-15-65 postfix/smtpd[13238]: disconnect from user-xxxxxx.cable.mindspring.com[76.xx.xx.xx]I can connect with telnet.Here is the Thunderbird error. | Thunderbird fails to connect to Dovecot and Postfix | postfix;ssl;thunderbird;dovecot | There MUST be a bug in Thunderbird. Even though I imported the server's certificate and added an exception, and it validates with openssl client, Thunderbird still fails. I was able to get it to work by using non-encrypted port numbers, but at least it uses STARTTLS to enable encryption anyways. I must star this to remember it a year from now.$ openssl s_client -connect olixxxxx.xxx:993CONNECTED(00000003)... lots of certificate info ...* OK [CAPABILITY IMAP4rev1 LITERAL+ SASL-IR LOGIN-REFERRALS ID ENABLE IDLE AUTH=PLAIN] Dovecot ready.. login staxxxxxx xxxxxxxxpasswordxxxxxxxxxxxx. OK [CAPABILITY IMAP4rev1 LITERAL+ SASL-IR LOGIN-REFERRALS ID ENABLE IDLE SORT SORT=DISPLAY THREAD=REFERENCES THREAD=REFS MULTIAPPEND UNSELECT CHILDREN NAMESPACE UIDPLUS LIST-EXTENDED I18NLEVEL=1 CONDSTORE QRESYNC ESEARCH ESORT SEARCHRES WITHIN CONTEXT=SEARCH LIST-STATUS] Logged in. logout* BYE Logging out |
_reverseengineering.13131 | Before I begin I want to say for whatever reason the site wouldn't let me post this unless I didn't have the coding so I just linked it instead of it being here.This is most likely the most stupid post on this website but I really want to figure out how to do this. Anyway I am trying to read the Call of Duty: Black Ops 3 code because I am interested in it. So what I did is I extracted the files from the .EXE into another folder. The files have the extensions .rsrc, .data, .idata,m .interpr, .pdata, .rdata, .reloc, .rsrc_1, .text, .tls, _RDATA, and there is a certificate. Anyway whenever I try to open any of these files it shows just tons of non legible text. There is some but not very much. Here is a part of the .text just so you can see what I am talking about.http://pastebin.com/2tzAM7xmThat one just looks like straight up Japanese or something. The more common thing I see is something like this though. This is a part from the .datahttp://pastebin.com/qZtS5R8CAny help on how to get these files to a way to read them? Again sorry for being dumb. | Trying To Read Code From Call of Duty | windows;executable;exe | null |
_cseducators.628 | In some CS courses (especially undergraduate and high school courses) the tests and the final exam are written on paper without the use of a computer.But if the students are in a CS course, shouldn't they be allowed to use the computer? If some mistakes are difficult enough to not be noticeable while writing code on a computer, they are nearly impossible to be found while writing code on paper.So, my question is, are there any advantages in doing written tests on paper, and is this the best approach? | Should CS students be doing their tests on paper? | high school;grading;undergraduate | Edit: This relatively high voted answer seems to be confusing to some, as it does not seem to give a clear answer. TL;DR: yes, doing tests on paper is usual at least in my university, at least many years ago. My anecdotal experience means to give a background where this might be coming from, together with the title CS!=coding. The last section at the end gives my opinion on why it is a good thing.CS != codingYou also have to acknowledge that CS is not coding; coding is not CS. You can have great coders who have not the faintest idea about CS (and vice versa: rubdos mentions the example of Alan Turing himself, who died around the time the first programming languages were invented). I can't remember whether in my CS studies I ever wrote actual real world code in a test. Lambda calculus, sure, and other formal stuff (more like mathematic formulae/proofs than programming).I do clearly remember that coding/programming was not part of the curriculum. It was assumed that people who went to study CS already were able to program. At that time, Java 1 was around the corner, and my university offered a voluntary 2-week Java crash course before the actual semester started. I did not take part (having a few other real world programming languages under my belt at that time), and never missed it. There was a bit of programming during some practical courses, but here also the profs assumed that everything we needed to know we'd pick up ourselves. And right they were.Funnily enough, one of my profs was very active in the Java community, and used it to motivate proofs in temporal logic / correctness. But that was very much theoretical, about concepts and principles - coding had nothing to do with it whatsoever. It was more about how do you create a compiler instead of how to you write a program. That's what university level CS is about, after all.Hence, as it was not part of the curriculum (being assumed to be known as a matter of course), no need to ask about it in a test; hence no reason to use a computer in tests, not any more than in any other field.EDIT: this answer is my experience from university level CS education; it somewhat applies to earlier levels as well, in my opinion - it is more important to teach the principles than the actual coding; and a test would be better served with checking that they understand roughly what it's all about instead of writing perfect syntactic code with a pencil. I'd rather have a pupil explain what a basic design pattern is, instead of showing the actual code for a simple for loop. Programming languages come and go, principles stay (adjust to your own curriculum of course). |
_codereview.124470 | The following is my first try at this classical interview question. It is quiet different from the solutions Gayle Laakmann provides in her book, and in another question on stackoverflow, someone initially mentioned there are better ways to do it.I think my solution should run in O(n) time and use O(n) space. Would better Big O performance be possible? This question claims to do it in O(1) space, but edits the list in place, which in my opinion is not a valid solution (A function checking something should always leave the something unchanged).Are there any other things I should change, especially concerning C++ style? I guess I could be using a stack instead of a vector to save the iterators, would that be of any advantage?#include <forward_list>#include <iostream>#include <cstdlib>#include <vector>template<typename T>bool isPalindrome(const std::forward_list<T>& lf){ auto iter = lf.begin(); std::vector<decltype(iter)> bv; // <-- Correct usage? while(iter!= lf.end()) { bv.push_back(iter++); } int istop = bv.size()/2 + bv.size()%2; iter = lf.begin(); for(int i = bv.size()-1; i>=istop; i--, iter++) { if( *iter != *(bv[i])) return false; } return true;}int main(int argc, char* argv[]){ std::forward_list<int> list = {0,1,2,1,0}; std::cout << Is palindrome: << isPalindrome(list) << std::endl; return 1;}This should compile in any compiler using C++11 / C++14. | Checking if a single linked list is a palindrome in C++ | c++;c++11;linked list;palindrome | null |
_unix.120424 | I'm looking to lock down our Solaris 10, RHEL 5, and SLES 11.2 servers. It has come to my attention that some of the users have no passphrase for their SSH keys. Is there a way I can check for this with a script?UpdateBelow I have posted the script I wrote from the answer @tylerl gave me. I'm posting this incase someone else needs this info in the future. There is most likely better ways to do this, but this works. I still need to write additional scripts for the accounts that are not automounted. Thanks everyone for all the help#!/bin/bash# This script is for checking for a blank passphrase. Meaning no passphrase to secure your SSH key.# Script most be run as root.# Example: sudo ./check-sshkeysmount share:/vol/home /mntls /mnt >/tmp/lsfor s in `cat /tmp/ls`do echo -e \e[1m User $s \033[0m if ls /mnt/$s/.ssh/id_rsa 2>/dev/null then grep ENCRYPTED /mnt/$s/.ssh/id_rsa || echo -e No RSApassphrase else echo RSA key not foundfiif ls /mnt/$s/.ssh/id_dsa 2>/dev/null then grep ENCRYPTED /mnt/$s/.ssh/id_dsa || echo -e No DSApassphrase else echo DSA key not foundfidonerm /tmp/lsumount /mnt | Is there a way to check a users SSH key to see if the passphrase is blank | ssh;ssh agent | If you're checking from the server that people are connecting to, then no dice. The SSH key has to be decrypted in memory before use, which means to the server they look the same. Unless you can get a copy of the actual key file, you're sunk.But if you're on the machine people are connecting from, well then it's trivial -- just look at the key file.Passwords on SSH keys are used to encrypt the key, and the file indicates whether encryption is used as well as what type.An encypted private key looks like this:-----BEGIN RSA PRIVATE KEY-----Proc-Type: 4,ENCRYPTEDDEK-Info: AES-128-CBC,259001658E2E5C2618A9648EA35122F4GFzPnlYdGYVTmK5t45xv/m0Nok9czOuFNNuS+Sm5vzGaOa7LBMtRNJgWFBCGsfFlwouThpuKxV+ArgmzPa9hnEmy18QW0sbza8SKm/3Hbqi8XwCliz2xP2xS+iGSkYDt...LAB/DZasuYBSsVadfemDsmrRvUz7/4eJZTxoEvwNQtAWhTS8j9RbRPee4rk1fwew-----END RSA PRIVATE KEY-----While an unencrypted one looks like this:-----BEGIN RSA PRIVATE KEY-----MIIEpAIBAAKCAQEAtdKjJa18HbagmuMvb/gDCpXXYPVqRsXDdwTcG3YY5RlJtdxYTJD+626tLTyuzzw6ZsGJtScrSjm2Jp5uUrDXnkek39Zxj24bTM9k/tZBeAQubrwO....I8u05jPL1WZmre5SVexfFEvAGqMdiWLvURpnQkI7Wn6nXJjEbUOdGQ==-----END RSA PRIVATE KEY-----The trained eye might notice that the second line contains the word ENCRYPTED. That's your clue. If the file contains the word ENCRYPTED then it is, if it doesn't then it's not. So here's your script:grep -L ENCRYPTED /home/*/.ssh/id_rsamodify to suit your environment, but you get the idea. Obviously people could fool your script by put the word ENCRYPTED down at the bottom of the file, but we're assuming that they wont. |
_unix.29182 | Somehow, I am finding it difficult to understand tweaking around * parameters with cron.I wanted a job to run every hour and I used the below setting:* */1 * * *But it does not seem to do the job. Could someone please explain the meaning of above and what is needed for the job? | Meaning of * */1 * * * cron entry? | cron | * means every.*/n means every nth. (So */1 means every 1.)If you want to run it only once each hour, you have to set the first item to something else then *, for example 20 * * * * to run it every hour at minute 20.Or if you have permission to write /etc/cron.hourly/ (or whatever it is on your system), then you could place a script there. |
_webmaster.28033 | I'm having a bad .htaccess day!I want a user to be able to type the URL mysite.com/aboutinstead of mysite.com/about.htmlOn .htaccess file I have:RewriteEngine OnRewriteCond %{SCRIPT_FILENAME} !-fRewriteCond %{SCRIPT_FILENAME} !-dRewriteRule ^/(.*)$ /$1.html [NC,L]But this simply does not work?I will add though that if i try this further inside the site e.g.mysite.com/pages/contactWorks perfectly whether I have the above code in the .htaccess or notWhat am I doing wrong? | .htaccess - lose the file .html extension | htaccess;mod rewrite | just avoid slashes before both matching patterns and destination.So,RewriteEngine OnRewriteBase /RewriteCond %{SCRIPT_FILENAME} !-fRewriteCond %{SCRIPT_FILENAME} !-dRewriteRule ^(.*)$ $1.html [NC,L]should work perfectly. |
_unix.163779 | I'm trying to see a list of all the rules in IPtables in a Debian 7 server.when I try:iptables -L -nI only get one rule (which I entered 5 minutes ago).I have many others, for port 80, mysql and others which all work, but I can't see them anywhere.Any idea how could that be done?Thanks/* edit */I'm adding some input I get from the different commandsiptables -t nat -L -nChain PREROUTING (policy ACCEPT)target prot opt source destinationChain INPUT (policy ACCEPT)target prot opt source destinationChain OUTPUT (policy ACCEPT)target prot opt source destinationChain POSTROUTING (policy ACCEPT)target prot opt source destinationWhen I tryiptables -L -v -n --line-nChain INPUT (policy ACCEPT 43535 packets, 58M bytes)num pkts bytes target prot opt in out source destination1 126 56529 ACCEPT tcp -- eth0 * 0.0.0.0/0 0.0.0.0/0 tcp spt:443 state ESTABLISHEDChain FORWARD (policy ACCEPT 0 packets, 0 bytes)num pkts bytes target prot opt in out source destinationChain OUTPUT (policy ACCEPT 30151 packets, 7365K bytes)num pkts bytes target prot opt in out source destinationiptables-save# Generated by iptables-save v1.4.14 on Thu Oct 23 08:58:32 2014*raw:PREROUTING ACCEPT [17972:25607074]:OUTPUT ACCEPT [12416:1953400]COMMIT# Completed on Thu Oct 23 08:58:32 2014# Generated by iptables-save v1.4.14 on Thu Oct 23 08:58:32 2014*mangle:PREROUTING ACCEPT [19071:27028289]:INPUT ACCEPT [19071:27028289]:FORWARD ACCEPT [0:0]:OUTPUT ACCEPT [13114:2110189]:POSTROUTING ACCEPT [13114:2110189]COMMIT# Completed on Thu Oct 23 08:58:32 2014# Generated by iptables-save v1.4.14 on Thu Oct 23 08:58:32 2014*security:INPUT ACCEPT [19514:27565428]:FORWARD ACCEPT [0:0]:OUTPUT ACCEPT [13405:2178341]COMMIT# Completed on Thu Oct 23 08:58:32 2014# Generated by iptables-save v1.4.14 on Thu Oct 23 08:58:32 2014*nat:PREROUTING ACCEPT [141:11461]:INPUT ACCEPT [141:11461]:OUTPUT ACCEPT [11:1030]:POSTROUTING ACCEPT [11:1030]COMMIT# Completed on Thu Oct 23 08:58:32 2014# Generated by iptables-save v1.4.14 on Thu Oct 23 08:58:32 2014*filter:INPUT ACCEPT [43596:58181078]:FORWARD ACCEPT [0:0]:OUTPUT ACCEPT [30216:7394285]-A INPUT -i eth0 -p tcp -m tcp --sport 443 -m state --state ESTABLISHED -j ACCEP TCOMMIT# Completed on Thu Oct 23 08:58:32 2014 | How to get all IPtables rules | debian;iptables | Netfilter encourages to use iptables-save command since it will provide you a detailed view of your built-in chains and those you've defined yourself. If you want to get a human readable view you can use iptables -L -v -n --line-n |
_opensource.5056 | When creating a new project today, am I allowed to license my software using the older version of licenses such as GPLv2 (vs. GPLv3), or BSD 4 clause (vs BSD 3 clause).ORAm I only allowed to use the latest version of these licenses instead? | Using older versions of licenses in new projects | licensing;license recommendation | You can use any version of any license you please. You are the author. You do what you want.No FOSS license could say something to the contrary, including no such license could restrict you to use other licenses or other version of a license for your original work .Practically each new version of common FOSS licenses is in itself a new license. Most versioned licenses have terms that may allow to use a newer version of a license for code using a previous version, but not always. This is a permission in all cases, never a restriction.In some cases such as the GPL family the relationships between all these versions can start being .... it's complicated!. |
_unix.341765 | Is there to a way to disable such thing because it gets annoying after a while. I have looked up disable options but they all involve setting the password and such. | password with default keyring everytime I open up google chrome for fedora? | fedora | null |
_webmaster.90807 | I have been searching around, but not sure of all the facts I need. Let me explain.I have stayed out of the SMTP game for a while and have become ignorant of the newer developments.Prior to my current IP address, it was a commercial IP address from a Sprint pool out of Florida. It was never challenged when I sent e-mails. But since CenturyLink has taken over Embarq after the merge with Sprint (land line), my DSLAM was changed and the IP address updated to a subscriber line (which I am paying for I assure you - another fight for another day). Since then, I have only sent two e-mails and both to Yahoo! addresses - one just a while ago. The first one failed because I was using my internal DNS for some funky stuff and it needed resetting. I am now using CenturyLinks DNS. However, I never set up SPF and DKIM and though I should.Okay. That is a lie. I just set up a SPF record - after sending the e-mail. Smart huh? However, while poking around my server, DKIM is not installed and therefore not available at this point. And I am thinking, Sheesh! Do I really have to do this?And that is my question to you. Since my server worked fine before, I am sure I need more today. Is the SPF record enough for Yahoo!, GMail, and others?? Do I really need DKIM? I ask this keeping in mind that there are blacklists that list my IP address block as a subscriber block. This is what would stop my e-mail from going through with some larger ISPs normally and why I never worked too hard. This is an important fact. I need to negate enough negative scores that the subscriber check may not matter if at all possible. Not sure it is.I would not care except that two of my friends are on Yahoo! and I just responded to one today. As well, being a Landlord that is advertising on apartments guide, rentals, and other online sites, I noticed that all users so far are using Yahoo! and GMail. Nor do I blame them!! So I guess I should care a little.[Update]As it turns out, my e-mail was accepted by Yahoo!, however, I cannot say whether it went into a spam bucket or not. I do not have a notice from Yahoo! saying if my e-mail is rejected as spam or otherwise. I am still concerned with Yahoo! and other e-mail services such as GMail. I almost never send e-mail, but when I do it is often very important. | Are SPF and DKIM records needed when the SMTP IP is marked as a subscriber block? | dns;email;spf;dkim | null |
_cs.71570 | In order to find the recurrence function of The Height in Heap, the following figure is drawn.Question 1: How can we compute the height if Right subtree in form of Log in base 3, and why do we have the height of Left subtree as log in base 3/2?Question 2: it is stated that:for a complete binary tree to have the maximum height the last level should be half full.i don't grasp the logic behind this line.why? | The Height of subtree in Heap | data structures;binary trees;discrete mathematics;heaps | null |
_cs.16531 | I have a huge list of strings. The goal is to make a database of relevant words.Of course in the context of what I work with, relevance is something akin to the organization I work with. For e.g. if it is a automobile manufacturing industry they'd buy products like Automotive assembly equipmentRadial tyresEtcIf it were an aircraft manufacturing industry:Fabricated Aluminium BodyHydraulic FluidSkydrolJet FuelEtc...Issue is that I might come across so many spelling mistakes, abbreviations, and variations.So what is a technique I can prepare a database of words like these when I have nothing to start with, except a huge list of strings. | techniques for finding relevant words in a huge list of strings | algorithms | null |
_scicomp.2567 | I need to compute the Matrix Permanents of several $64 \times 64$, zero-one matrices. I have tried using the built in functions in both Sage and Maple, but both programs return out of memory errors. I have also tried several MatLab implementations, but they tend to run very slowly, on the order of days or weeks. I am wondering whether anyone has any suggestions (functions, programs, methods) of how I might compute these matrix permanents. I have access to Sage, Maple, and MatLab, and I also do a fair amount of work in Python. The matrices themselves have between 16-24 ones per row/column in the densest case and 6-8 ones per row/column in the sparsest case. | Computing Permanents of $64 \times 64$ Matrices | linear algebra;matrices | The wikipedia article you link to has several references to computing the permanent for unweighted graphs, which is exactly what you have in your case. It might be worthwhile exploring these directions.In general, looking at the definition of the permanent, the difficulty is that there are many permutations for 64 indices -- 64! in fact, quite an unwieldy number, about $10^{89}$. If we ignore this fact for a moment, computing the weight of each permutation is probably difficult for Matlab/Sage/Maple/... if you store the matrix as floating point numbers, but it should be reasonably straightforward if you wrote such a code in C/C++ and store the 0/1 entries as booleans. You then only need to compute the product of each weight as long as the factor is 'true', and terminate the computation if you hit a 'false', continuing with the next permutation. This is akin to a branch and bound algorithm. But that doesn't get you around the problem that there are so many permutations. The only approaches I can see working for this are (i) use symmetries in and other knowledge about your matrices to reduce the number of interesting permutations to a more manageable size, and (ii) following up on the connection to graphs, in particular that the permanent of a 0/1 matrix equals the number of cycle covers. I'm not a graph expert but there may be specialized algorithms for computing cycle covers. |
_unix.118517 | I have xterm with tmux open upon startup of X11 with the following line in my xinitrc file: xterm -e tmux &However the -e tmux causes all windows to assume the geometry of the first -geometry attribute in the file, even if I separately define the geometry of the xterm window. Enclosing in quotes or grave accents does not remedy the situation.If I use tmux before starting X11 (i.e. execute then exit tmux), then the xterm window opens at the default geometry as it should. Restarting X11 causes the problem to return.Suggestions will be greatly appreciated.My entire xinitrc file:xsetroot -solid blackxstatbar &xconsole -geometry -20-40 &xterm -e tmux &exec cwmAt the moment all windows are at -20-40. I'm running OpenBSD 5.4 on amd64 hardware. | xinitrc: starting xterm with tmux causes all windows to share same geometry | xorg;x11;tmux;window manager;window geometry | null |
_webmaster.45483 | For my Windows testing, I am using XP, since that is what I have, and I am testing with Firefox and IE. I noticed that the Times, Georgia and Utopia fonts all look pretty bad in Firefox. I've noticed that on Digg (yes it still exists) they load a nice-looking font after the page loads, so there is an ugly font that switches to a nice font. On FB and Reddit the font remains ugly. | What's the best body text font for Windows XP? | fonts;firefox;windows | The fonts on various websites should offer the same experience than any other operating systems, of course they are never pixel perfect since the rendering engines vary.But with this said it shouldn't be as bad as you say it is and I imagine that something else is causing font problems on your screen, one thing it could be comes to mind and that is early versions of XP by default does not ship with anti-aliased enabled on their fonts (ClearType), I recommend you read how to enable ClearType Fonts in XP. Also in regards of Digg working fine, this is most likely because they use a font called 'Source Sans Pro' which is a TypeKit Font and it's likely processing without the need of ClearType Fonts, since I believe the format is not TrueType. |
_softwareengineering.148317 | In the project, I found a file, math.c, with a big GPL header and ...//------------------------------------------------------------------------------/// Returns the minimum value between two integers./// \param a First integer to compare./// \param b Second integer to compare.//------------------------------------------------------------------------------unsigned int min(unsigned int a, unsigned int b){ if (a < b) { return a; } else { return b; }}OK, cool so I need to get min value and ... this file!? So I need to open the whole project because of it? Or do I need to reinvent mathematics?I don't believe it's just insane, so the question is: when we can just remove the GPL header?Must I be a weirdo and do it?:unsigned int min( unsigned intJEIOfuihFHIYEFHyigHUEFGEGEJEIOFJOIGHE,unsigned int hyrthrtRERG ) { if(JEIOfuihFHIYEFHyigHUEFGEGEJEIOFJOIGHE< hyrthrtRERG ) { return JEIOfuihFHIYEFHyigHUEFGEGEJEIOFJOIGHE; }else {return hyrthrtRERG ; } }Seriously, do they want me to write code like the above? | What do I need to do to NOT steal Hello World code with a GPL license? | licensing;c;gpl | Unlike many of the user here, I would simply suggest: Copy it!Make sure the formatting of the code fits your coding standard and also you should probably remove or rewrite the comment. No one will ever know you copied it - when a piece of code is this simple, you might as well have written it from scratch. If your coding standard somehow requires the function to look exactly as it does in the snippet, so be it - as long as it looks as it would look if you had written it from scratch. Think about it, this is hardly(!) the first time this exact piece has been written - when something is this trivial, there is little reason not to copy it, if you do not feel like writing it yourself.Even having this discussion seems a little superfluous to me - we need to be pragmatic if we are to get any real work done! |
_cs.62476 | Does computer convert every stuff using Ascii or UTF?Meaning if there is a mathematical calculation including 65 (as a number) will it convert it into binary (00100001)?And then how it differentiate it with 'A', whose code point is also 65 with code 00100001? | Binary Equivalent vs. Computer code(Ascii or UTF) | arithmetic | null |
_unix.42437 | I was unable to remove a file anymore with thunar:How should I create the Trash folder ? | Can't find or create trash while deleting files | xfce;thunar | My trash works on xfce and here's what my directory structure looks like in ~/.local/share which is the only place I have located a Trash folder:drwx------ 4 myuser myuser 4096 Jun 18 10:12 Trash drwx------ 3 myuser myuser 4096 Jun 18 10:12 files drwx------ 2 myuser myuser 4096 Jun 18 10:12 infoBased on this...mkdir ~/.local/share/Trashmkdir ~/.local/share/Trash/filesmkdir ~/.local/share/Trash/infoand chmod -R 700 ~/.local/share/Trashlooks right to me. |
_unix.240956 | I need to be able to export some variables from a file, so that I can use it in my BASH script. the file content is something like this:my.variable.var1=a-long-ling.with.lot_of_different:characters:and_numbersmy.variable.another.var2=another-long-ling.with.lot_of_different:characters:and_numbersmy.variable.number3=yet_another_long-ling.with.lot_of_different:characters:and_numbersFirst I tried sourcing it using source as they are and got the error message saying: command not found. I tried using export, which gave me error message saying: not a valid identifier.I think I can only export if I change my variable from my.variable.var1 to my_variable_var1.I am able to do this by cutting the line at = and then replacing all .s with _s and then adding the variables back.So my question is, is it possible to change:my.variable.var1=a-long-ling.with.lot_of_different:characters:and_numbersmy.variable.another.var2=another-long-ling.with.lot_of_different:characters:and_numbersmy.variable.number3=yet_another_long-ling.with.lot_of_different:characters:and_numberstomy_variable_var1=a-long-ling.with.lot_of_different:characters:and_numbersmy_variable_another_var2=another-long-ling.with.lot_of_different:characters:and_numbersmy_variable_number3=yet_another_long-ling.with.lot_of_different:characters:and_numbersusing any of those cool 'one liners'? Would love to use that, plus a good learning. | Replace all instances of a character if it occurres before another character | bash;text processing | With sed:sed -e :1 -e 's/^\([^=]*\)\./\1_/;t1'That is replace a sequence of characters other than . at the beginning of the line followed by . by that same sequence and _, and repeat the process until it no longer matches.With awk:awk -F = -v OFS== '{gsub(/\./, _, $1); print}'Now, in case the right hand side of the = contains characters special to the shell (\$&();'#~<>...`, space, tab, other blanks...), you may want to quote it:sed s/'/'\\\\''/g;:1' s/^\([^=]*\)\./\1_/;t1' s/=/='/;s/\$/'/Or:awk -F = -v q=' -v OFS== ' {gsub(q, q \\ q q) gsub(/\./, _, $1) $2 = q $2 print $0 q}' |
_unix.208953 | I am using Debian. df -h shows me that I'm using around 275GB: Filesystem Size Used Avail Use% Mounted onrootfs 315G 274G 26G 92% /udev 10M 0 10M 0% /devtmpfs 6.4G 200K 6.4G 1% /run/dev/disk/by-label/DOROOT 315G 274G 26G 92% /tmpfs 5.0M 0 5.0M 0% /run/locktmpfs 13G 4.0K 13G 1% /run/shmI want to work out where the 274GB has gone. Following the answers here, I can see that around 50GB is being used by the filesystem: $ du -h / --max-depth 3...51G /I also happen to know that I have a large Postgres database, so I can go and check how much space it's using: $ psql => SELECT pg_database.datname, pg_database_size(pg_database.datname), pg_size_pretty(pg_database_size(pg_database.datname)) FROM pg_database ORDER BY pg_database_size DESC; datname | pg_database_size | pg_size_pretty-------------+------------------+---------------- mydatabase | 230809349908 | 215 GB postgres | 6688532 | 6532 kB template1 | 6570500 | 6417 kB template0 | 6562308 | 6409 kBSo there's about 215GB being used by Postgres, and about 50GB by the filesystem. But how can I check where the remaining 10GB has gone?It's not a big deal, but I'm just curious to know how one might track this down. | Understanding where disk space has gone? | debian;disk usage | null |
_unix.64556 | Am confused so thought of asking a question.According to this Red Hat Becomes Open Sources First $1 Billion Baby, it is opensourced so my question is:Where can I download the Opensource version? All web links provided point to RHEL; it is commercial isn't it? Am I missing something? | Is Red Hat Linux licensed | rhel;free software;licenses;open source | What you are missing are two components: the service/support and the fact that they (Red Hat) provide ready (binary) packages.CentOS does as well and they strive to be binary compatible, down to every single last bug. As far as I know only a few aspects of CentOS differ from the respective RHEL release, mostly because of copyright and/or trademark issues. CentOS compiles the sources and at least publicly Redhat even like (not just acknowledge) the fact. Red Hat still makes big business providing the support and service around their distro.Also read: http://en.wikipedia.org/wiki/Red_Hat_Enterprise_Linux_derivatives |
_scicomp.3044 | I have a system of equations $$ S_{m}(\xi) +P_{m}(\xi)=f(\xi)$$where $\xi$ can be choosen arbitrary in some domain in $\mathbb{C}$, $f$ is known, $P_m$ is a polynomial of degree at most $m$. Here $S_{m}$ is a generic function from $\mathbb{C}$ to $\mathbb{C}$ but for me it is sufficient to know it's values in only $(m+1)$ mutually distinct points.Taking $(m+1)$ mutually distinct points $\xi_0, \ldots, \xi_m$ we can invert the Vandermonde matrix and hence write coefficients of $P_m$ as linear combination of $S_m(\xi_k)$,$k=0,\ldots,m$. Introducing this result back in equations we get a linear system on $S_{m}(\xi_k)$. So theoretically we can find $S_{m}(\xi_k)$. But is there some way to do it practically? | How to solve numerically such system of equations | linear algebra;numerics | null |
_unix.361993 | I ended up making this script on a DD-WRT router that is creating two unwanted files and I can't seem to understand why. I'm not a scripting genius, especially with bash, so any help would be appreciated.#!/bin/shsleep 30mkdir /tmp/myvpn; cd /tmp/myvpn# ... doing stuff...while [ 1 ]do r1=`wget -q http://ipinfo.io/ip` > /dev/null r2=`$(wget -q http://ipinfo.io/$r1/country)` > /dev/null if [ $r2 -eq XX ] then echo XX OK > /tmp/myvpn/result_check_vpn.txt else echo XX NOK > /tmp/myvpn/result_check_vpn.txt killall -q openvpn sleep 5 openvpn --config /tmp/openvpncl/openvpn.conf --route-up /tmp/myvpn/route-up.sh --down-pre /tmp/myvpn/route-down.sh --daemon sleep 25 sh /proc/net/ip_conntrack_flush fisleep 180doneThis script creates two unwanted files in /tmp/myvpn called country and ip. I must be doing something wrong.Basically the script tries to check if the VPN is established right by checking if I effectively changed country (it is necessary for me to perform this check). | Bash script creating unwanted files | shell script;wget | The files are being created by these two commands:r1=`wget -q http://ipinfo.io/ip` > /dev/nullr2=`$(wget -q http://ipinfo.io/$r1/country)` > /dev/nullOK, the second is a syntax error, but I asume that's a typo. The wget command's format is:wget http://www.example.com/fileIt will then download file and save it in the current directory. Since you haven't told us what you expected to happen, I will guess that you wanted to save the file contents in the variables. If so, you need to tell wget to print to standard output using -O -:r1=$(wget -qO - http://ipinfo.io/ip)r2=$(wget -qO - http://ipinfo.io/$r1/country) You can't redirect the output (> /dev/null) of course, since that means nothing is printed. |
_codereview.57619 | I looked at a bunch of AngularJS directives checking for uniqueness of a username and decided to try for the simplest implementation. It does what I want but may not really be 'idiomatic' Angular.Here is the form element:<input type=text name=username ng-model=form.username unique-username= required/><span class=hide-while-in-focus ng-show=thisform.username.$error.unique>Username taken!</span>Here's the directive:.directive('uniqueUsername', function($http) { return { restrict: 'A', require: 'ngModel', link: function (scope, element, attrs, ngModel) { element.bind('blur', function (e) { ngModel.$setValidity('unique', true); $http.get(/api/checkUnique/ + element.val()).success(function(data) { if (data) { ngModel.$setValidity('unique', false); } }); }); } };})And the ExpressJS call:if (data) { console.log(found + data.username); return res.send(data.username);}else { console.log(not found); return res.send(404);}I would appreciate any feedback on why this is good or bad and if possible a revision that uses $scope.watch on the model. | Angular directive for unique username | javascript;angular.js | null |
_codereview.127718 | I'm trying to learn programming with python by myself and I've made a hangman game for exercise purposes.import randomwords = ['egypt', 'automobile', 'world', 'python', 'miniority', 'treehouse', 'friend', 'program' , 'people']def start(): print Hello! Welcome to a tiny hangman game that I made for exercise purposes. raw_input('Press enter to continue') key = random.randint(0,(len(words)-1)) global word word = words[key] global word_template word_template = '_' * len(word) word_template = list(word_template) guesser()def draw(int): if int == 0: print _________ print | | print | print | print | print | print | elif int == 1: print _________ print | | print | 0 print | print | print | print | elif int == 2: print _________ print | | print | 0 print | | print | print | print | elif int == 3: print _________ print | | print | 0 print | /| print | print | print | elif int == 4: print _________ print | | print | 0 print | /|\\ print | print | print | elif int == 5: print _________ print | | print | 0 print | /|\\ print | / print | print | elif int == 6: print _________ print | | print | 0 print | /|\\ print | / \\ print | print | def guesser(): global counter counter = 0 checker = list(word) guesses = [] while counter < 6: draw(counter) print word_template print '\nYour previous letters are:', guesses print 'You have ',(6 - counter), 'guesses left.' choice = raw_input('Choose a letter: ') if choice in guesses: print \nYou made that guess before! elif choice in checker: if checker.count(choice) == 1: pointer = checker.index(choice) word_template[pointer] = checker[pointer] checker[pointer] = 1 guesses.append(choice) print \nThat's a hit! if list(word) == word_template: win() else: continue elif checker.count(choice) > 1: for i in range(0, checker.count(choice)): pointer = checker.index(choice) word_template[pointer] = checker[pointer] checker[pointer] = 1 guesses.append(choice) print \nWOW! That was a multiple hit! if list(word) == word_template: win() else: continue elif choice not in checker: guesses.append(choice) counter += 1 print '\nMiss!' if counter == 6: draw(counter) print 'Sorry, you lose :(' print 'The word was:', word retry()def win(): print \nYou won! print You found the word:, word retry()def retry(): print Do you want to play again? choice = raw_input('Type retry for restart, Ctrl + C for exit:') if choice == 'retry': start() else: print Sorry, I can't understand. retry()start()Is there any flaws on my logic and what can you suggest me to improve my code? | Hangman from a beginner | python;beginner;python 2.7;hangman | Avoid global variablesInstead of using global variables,it would be better to reorganize the code so that values are passed around in function parameters as necessary.Don't use int as variable nameint is the name of a built-in type.Don't use it as a variable name.It prevents the rest of the code from using it,and it's confusing for readers.Don't use recursive menuIn the current implementation the menu uses recursive logic:start calls guesser, which will call win or retry,which will again call start, or retry, and so on. This is all very confusing, and leads to a long stack.Rewrite this to use a loop for the game menu instead of recursion.Use the print functionI know you tagged your question with python-2.7, but with the simple change of print something to print(something) you get something that works just as well, and you're one step closer to compatibility with Python 3, and building a good habit. |
_codereview.7133 | I have a small program where I have a background thread that plays sound, so it needs to run really fast, but it also needs to do a small amount of memory management. I didn't want to use normal new and delete in a time critical area, so I threw this together, but set it up so I could reuse it elsewhere. template <typename T, unsigned int capacity>class MemoryPool{public: MemoryPool() { for (unsigned int i = 0; i < capacity; i++) { myUnusedMemory[i] = &myMemory[i]; } } void* operator new(std::size_t size) { return myUnusedMemory[myUnusedIndex--]; } void operator delete(void* ptr) { myUnusedMemory[++myUnusedIndex] = (T*)ptr; }private: static int myUnusedIndex; static T myMemory[capacity]; static T* myUnusedMemory[capacity];};template <typename T, unsigned int capacity> int MemoryPool<T, capacity>::myUnusedIndex = capacity-1;template <typename T, unsigned int capacity> T MemoryPool<T, capacity>::myMemory[capacity];template <typename T, unsigned int capacity> T* MemoryPool<T, capacity>::myUnusedMemory[capacity];The intended usage is something like this:struct Sound : public ag::util::MemoryPool<Sound, 100>{ // ...};Now when calling new Sound() I get one from my memory pool, which should be super fast. The only things that I can think of that could be improved are making operator new throw an exception when at capacity. I think I might be able to do away with typename T. The only reason it's needed is so that myMemory knows the size of its elements, but I feel like there's another solution here. | Super simple templated memory pool in C++ | c++;memory management | null |
_cstheory.10972 | Is there an example of a class of graphs for which the vertex coloring problem is in P but the independent set is problem is NP complete? | graphs where vertex coloring is in P but independent set is NP complete | cc.complexity theory;graph theory;complexity classes | A perhaps more general statement (with an easy proof) is that the following problem is already NP-complete:Input: A graph G, a 3-coloring of G, an integer k.Question: Does G have an independent set of size k?This can be proven by a reduction from Independent Set. Observe that if we take a graph G, pick some edge, and subdivide it twice (i.e. replace edge {u,v} by a path u,x,y,v where x and y have degree two) then the independence number of G increases by exactly one. (You can add exactly one of x or y to any set which was independent in G, and the reverse is not difficult either.) So the question if graph G with m edges has an independent set of size k, is equivalent to the question whether G', which is the result of subdividing all edges in G twice, has an independent set of size k + m. But note that it is easy to get a 3-coloring of G', by partitioning G' into three independent sets as follows: one contains the vertices which were also in G, and the other two classes each contain exactly one of the two subdivider vertices for each edge. Hence this procedure constructs a graph G' with a 3-coloring of it, such that computing its independence number gives you the independence number of the original graph G. |
_reverseengineering.14954 | I read here that CAT.NET and FxCop are dead. As far as I understand, the successor Roslyn requires a visual studio project and source code. Is there a tool that reads in a compiled .NET program and offers an API to do static data flow analysis? | Is there a static data flow analysis tool for .net assemblies? | static analysis;.net | null |
_vi.9803 | I'm referring to this.Are there package managers that pull scripts from it by name? I ask because I notice that the version of my plugin contained in it is extremely old, and I'm wondering whether I should try to get it updated to the latest version. | Who manages the vim-scripts project on Github, and how is it used? | plugin system;git | null |
_opensource.4873 | I've read this book that has tips on how to live healthy. Forget the fact that there are many like it out there, that's not the point, and it's not about specific book. Now I am just curious how does that process work.If I were to create an app that uses principles from that book, or any other for that matter, would that be infringing on the book? I mean could the writer of that book be able to sue and stuff like that?I know that would 100% happen if I were writing a book but does it cover wide variety of things like apps? I am not saying that I want to write in the app that those were my principles, not at all; just use those principles to calculate things. Sure, in millions of apps today no-one is likely to notice it, but I would like to know is this considered illegal or do book copyrights even cover apps? | Can we use principles from a book to create an application? | licensing;copyright | null |
_unix.263277 | If I have both /usr/bin/perl and /usr/local/bin/perl available on a system, which one should I use? | Which of /usr/bin/perl or /usr/local/bin/perl should be used? | perl;executable | null |
_unix.236230 | I have a text file that is organized as follows:Group 1asdsdsdsdf.html jeffxcvxcvxcvx.html bobvrgeiuvhif.html sueGroup 2iwdowijdoi.html marypokpompojm.html dougndkjfsjfbs.html lisaI need a bash script that creates a directory named after each group. And then a text file inside named for each person in that group with their corresponding link on the first line.I have managed to be able create the directories, the named text files, and a file with only the links. But I don't know how to echo each link into each name file or how to sort them by group.I'm sure there are better ways to accomplish the small amount that I have.#!/bin/bashgrep Group list.txt > groupsgrep -v Group list.txt > links_nameswhile read file; do mkdir ${file}; done < groupswhile read line; do export name=`echo $line | awk '{print $2}'`touch $name; done < links_nameswhile read line; do export link=`echo $line | awk '{print $1}'`echo $link >> links ; done < links_namesrm {groups,links_names,links} | Bash script to echo the first positional of each line into file with name of the second | bash;awk;scripting;grep | With awk:awk '/^Group/{g=$0; system(mkdir \g\); next} g&&$0{print $1 >g/$2}' file/^Group/ if the line starts with the string Group...g=$0 set the variable g to the group name, for example Group 1.system(...) call the command mkdir with the system function to create that directory (notice the additional quotes to deal with spaces in group names).g&&$0 if the variable g is defined and the line is not empty...print $1 >g/$2 write the value in the first field $1 (the link) to a file in the directory g name by the value of the second field $2 (the name).The test:$ cat Group\ 2/dougpokpompojm.html |
_unix.39831 | I want to add another alias to my aliases file for the directory I'm currently in (Present Working Directory)I've tried printf alias aaa=cd + pwd >> myfileIt's close, but I end up getting:alias aaa=durrantm@Castle2012-Ubuntu-laptop01:~/Dropnot/webs/rails_v3/linkerinstead of:alias aaa=cd ~/Dropnot/webs/rails_v3/linker/In other words, my machine-user name are there and I don't want them, I want the pwd at time of execution | How can I add an alias for my pwd to an existing file? | shell;alias;cd command | Try this instead:echo alias aaa='cd \$PWD\' >> ~/.bash_aliases |
_codereview.143769 | Here is my class that handle all MarshMallow Permissions I prefer separate it class as I will call its methods in all my apps.At first I get used to check permission by this way:private void CheckPermissionGranted() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, CHECK_PERMISSION_CODE); return; } }}and here is my class to handle all permissions: import android.Manifest;import android.app.Activity;import android.content.pm.PackageManager;import android.support.v4.app.ActivityCompat;import android.support.v4.content.ContextCompat;import android.widget.Toast;/** * Created by mina on 10/9/2016. */public class MarshMallowPermission { public static final int RECORD_PERMISSION_REQUEST_CODE = 1; public static final int WRITE_EXTERNAL_STORAGE_PERMISSION_REQUEST_CODE = 2; public static final int READ_EXTERNAL_STORAGE_PERMISSION_REQUEST_CODE = 3; public static final int CAMERA_PERMISSION_REQUEST_CODE = 4; Activity activity; public MarshMallowPermission(Activity activity) { this.activity = activity; } public boolean checkPermissionForRecord(){ int result = ContextCompat.checkSelfPermission(activity, Manifest.permission.RECORD_AUDIO); if (result == PackageManager.PERMISSION_GRANTED){ return true; } else { return false; } } public boolean checkPermissionForWriteExternalStorage(){ int result = ContextCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE); if (result == PackageManager.PERMISSION_GRANTED){ return true; } else { return false; } } public boolean checkPermissionForReadExternalStorage(){ int result = ContextCompat.checkSelfPermission(activity, Manifest.permission.READ_EXTERNAL_STORAGE); if (result == PackageManager.PERMISSION_GRANTED){ return true; } else { return false; } } public boolean checkPermissionForCamera(){ int result = ContextCompat.checkSelfPermission(activity, Manifest.permission.CAMERA); if (result == PackageManager.PERMISSION_GRANTED){ return true; } else { return false; } } public void requestPermissionForRecord(){ if (ActivityCompat.shouldShowRequestPermissionRationale(activity, Manifest.permission.RECORD_AUDIO)){ Toast.makeText(activity, Microphone permission needed for recording. Please allow in App Settings for additional functionality., Toast.LENGTH_LONG).show(); } else { ActivityCompat.requestPermissions(activity,new String[]{Manifest.permission.RECORD_AUDIO},RECORD_PERMISSION_REQUEST_CODE); } } public void requestPermissionForWriteExternalStorage(){ if (ActivityCompat.shouldShowRequestPermissionRationale(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE)){ Toast.makeText(activity, External Storage permission needed. Please allow in App Settings for additional functionality., Toast.LENGTH_LONG).show(); } else { ActivityCompat.requestPermissions(activity,new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},WRITE_EXTERNAL_STORAGE_PERMISSION_REQUEST_CODE); } } public void requestPermissionForReadExternalStorage(){ if (ActivityCompat.shouldShowRequestPermissionRationale(activity, Manifest.permission.READ_EXTERNAL_STORAGE)){ Toast.makeText(activity, External Storage permission needed. Please allow in App Settings for additional functionality., Toast.LENGTH_LONG).show(); } else { ActivityCompat.requestPermissions(activity,new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},READ_EXTERNAL_STORAGE_PERMISSION_REQUEST_CODE); } } public void requestPermissionForCamera(){ if (ActivityCompat.shouldShowRequestPermissionRationale(activity, Manifest.permission.CAMERA)){ Toast.makeText(activity, Camera permission needed. Please allow in App Settings for additional functionality., Toast.LENGTH_LONG).show(); } else { ActivityCompat.requestPermissions(activity,new String[]{Manifest.permission.CAMERA},CAMERA_PERMISSION_REQUEST_CODE); } }}I check permission when use click button to upload Image from Camera or image library private void selectImage() { final CharSequence[] items = {str_camera, str_image_lib, str_cancel}; AlertDialog.Builder builder = new AlertDialog.Builder(UploadActivity.this); builder.setTitle(Add Files!); builder.setItems(items, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int item) { if (items[item].equals(str_camera)) { if (!marshMallowPermission.checkPermissionForCamera()) { marshMallowPermission.requestPermissionForCamera(); return; } dispatchTakePictureIntent(); } else if (items[item].equals(str_image_lib)) { if (!marshMallowPermission.checkPermissionForReadExternalStorage()) { marshMallowPermission.requestPermissionForReadExternalStorage(); return; } enableBrowseFile(); } else if (items[item].equals(str_cancel)) { dialog.dismiss(); } } }); builder.show();}if permission not granted I request permission , if granted I call methods that required this permission to run@Overridepublic void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { switch (requestCode) { case MarshMallowPermission.READ_EXTERNAL_STORAGE_PERMISSION_REQUEST_CODE: if (grantResults[0] == PackageManager.PERMISSION_GRANTED) { enableBrowseFile(); } else { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { marshMallowPermission.requestPermissionForReadExternalStorage(); } } break; case MarshMallowPermission.CAMERA_PERMISSION_REQUEST_CODE: if (grantResults[0] == PackageManager.PERMISSION_GRANTED) { dispatchTakePictureIntent(); } else { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { marshMallowPermission.requestPermissionForCamera(); } } break; }} | Android class to handle MarshMallowPermission | java;android;authorization | null |
_codereview.57518 | I wrote an Ajax function, which should be used in a framework to interact with a webserver.The (self-written) Java-Webserver can be used to fetch files and folder-contents, create files and folders, and delete them./** * Performs an Ajax-Request * @param {string} method HTTP-Method * @param {string} url * @param {string} postData optional; HTTP-body * @param {string} contentType optional; default: multipart/form-data * @param {object} authentication optional; loginCredentials for basicAuth; {user: userName, password: password} * @param {function} callback optional; called, if the operation succeeded; * Parameter: (string) response-body * @param {function} errorCallback optional; called, if the operation failed; * Parameter: 1 = (number) statusCode; (==0, if the given parameters were invalid) * 2 = (string) statusText; (or errorMessage, if statusCode == 0) */function ajax(method, url, postData, contentType, authentication, callback, errorCallback) { if(typeof(errorCallback) != 'function'){ errorCallback = function(){}; //Dummy-function to reduce code } //Validate the input parameters if([GET, HEAD, POST, PUT, DELETE].indexOf(method) < 0){ return errorCallback(0, Invalid method); } if(postData && [HEAD, POST].indexOf(method) < 0){ //Other methods don't support postData return errorCallback(0, Invalid method for postData); } //Get a cross-browser XML-HTTP-Object: var req = createXMLHTTPObject(); if (!req) { return errorCallback(0, Ajax is not supported); //Oops! Something bad happened } req.open(method, url, true); //async = true //Manipulate header-fields: //req.setRequestHeader('User-Agent','XMLHTTP/1.0'); if(postData){ if(contentType){ req.setRequestHeader('Content-type', contentType); }else{ req.setRequestHeader('Content-type', 'multipart/form-data'); } //key-value pairs with binary data or big payloads: // multipart/form-data //key-value pairs with few non-alphanumerical symbols: // application/x-www-form-urlencoded //binary data: // application/octet-stream } if(authentication){ req.setRequestHeader(Authorization, Basic + btoa(authentication.user + : + authentication.password)); //btoa() = encode string to base64 } req.overrideMimeType(text/plain; charset=utf-8); //The browser must not execute javascript-files, if they're loaded with this method //Prepare execution: req.onreadystatechange = function () { if (req.readyState != 4) { return; } if (req.status != 200 && req.status != 304) { return errorCallback(req.status, req.statusText); } if(typeof(callback) == 'function'){ callback(req.response); } } if (req.readyState == 4){ return; } req.send(postData);}The createXMLHTTPObject()-Method returns either an XMLHttpRequest-Object, or an ActiveXObject-Object to reach cross-browser compatibility.The whole function should be cross-browser compatible, but doesn't have to support older browsers, as the Framework itself depends upon HTML5.The code is based on this exampleAs I'm not 100% familiar with the HTTP-Protocol, I have the following questions:Did I forget an important part of HTTP/RESTful services that might be needed in a framework?Can there be efficiency-improvements?Are there any other bugs/inconsistencies/possible improvements? | Ajax for RESTful web service | javascript;optimization;ajax;http | Support for JSONP and CORS is a must for any modern web framework.APIwise, I think you'd want to reduce the arguments to your method to a single object, similar to how jQuery does it. It gives an opportunity to give defaults, and simplifies it from the API perspective. As it stands, it will be painful to use, in that you need to remember a lot of arguments. A simple GET ajax with your's:ajax('GET', 'index.html', null, null null function(evt) { console.log(Success!)})vs jQUery or similar:ajax({method:'GET', url:'index.html'}, success:function(evt) { console.log(Success!)}) |
_softwareengineering.262571 | I am not new to programming, but I am one that started a few years ago, and I do love templates.But in the before times, how did people deal with situations where they needed compile-time code generation like templates? I'm guessing horrible, horrible macros (at least that's how I'd do it), but googling the above question only gets me pages and pages of template tutorials.There are many arguments against using templates, and while it typically boils down to readability, YAGNI, and complaining about how poorly it is implemented, there is not a lot out there on the alternatives with similar power. When I do need to do some sort of compile-time generics and do want to keep my code DRY, how does/did one avoid using templates? | What did people do before templates in C++? | c++;history;templates | Besides the void * pointer which is covered in Robert's answer, a technique like this was used (Disclaimer: 20 year old memory):#define WANTIMP#define TYPE int#include collection.h#undef TYPE#define TYPE string#include collection.h#undef TYPEint main() { Collection_int lstInt; Collection_string lstString;}Where I have forgotten the exact preprocessor magic inside collection.h, but it was something like this:class Collection_ ## TYPE {public: Collection() {} void Add(TYPE value);private: TYPE *list; size_t n; size_t a;}#ifdef WANTIMPvoid Collection_ ## TYPE ::Add(TYPE value)#endif |
_unix.336390 | I have a program I installed as root called terminus. It has an executable which is symlinked as follows:/usr/local/bin/terminus -> /root/vendor/bin/terminusand that file is symlinked:/root/vendor/bin/terminus -> ../pantheon-systems/terminus/bin/terminusI'm trying to give my jenkins user access to the terminus command (/usr/local/bin/terminus)When I try which terminus as root, it gives me /usr/local/bin/terminus. When I try this as the jenkins user it doesn't give me anything.I tried chown -R jenkins:nogroup terminus from /usr/local/bin to no avail. What can I do to give the jenkins user access to the terminus command?This is the output of cat /etc/passwd for jenkins:jenkins:x:112:116:Jenkins,,,:/var/lib/jenkins:/bin/bash This is the output of cat /etc/group for jenkins:jenkins:x:116: | How can I get my jenkins user permission to run a program installed by root? | permissions;users;permission denied | null |
_unix.368241 | I have a Debian 9 host. I can ssh into my Raspberry Pi and other servers with no issue. I have openSUSE installed as a virtual machine in VirtualBox. I can ssh into that virtual machine with no issue. To set this up in VirtualBox, I went to: Settings > Network > Advanced > Port Forwarding > Name: ssh, Protocol: TCP, Host IP: (blank), Host Port: (random high port number), Guest IP: (blank), Guest Port: 22. This is for Adapter 1 and it is Attached to: NAT. These instructions are on a few different forum posts. I have done the same thing for my CentOS virtual machine but with a different Host Port (random high port number). I have made sure the sshd service is running with sudo systemctl status sshd. However, I am unable to ssh into the CentOS virtual machine. I receive the following error (last line below):~$ ssh -p 1820 [email protected] -vOpenSSH_7.4p1 Debian-10, OpenSSL 1.0.2k 26 Jan 2017debug1: Reading configuration data /etc/ssh/ssh_configdebug1: /etc/ssh/ssh_config line 19: Applying options for *debug1: Connecting to 127.0.0.1 [127.0.0.1] port 1820.debug1: Connection established.debug1: key_load_public: No such file or directorydebug1: identity file /home/brock/.ssh/id_rsa type -1debug1: key_load_public: No such file or directorydebug1: identity file /home/brock/.ssh/id_rsa-cert type -1debug1: key_load_public: No such file or directorydebug1: identity file /home/brock/.ssh/id_dsa type -1debug1: key_load_public: No such file or directorydebug1: identity file /home/brock/.ssh/id_dsa-cert type -1debug1: key_load_public: No such file or directorydebug1: identity file /home/brock/.ssh/id_ecdsa type -1debug1: key_load_public: No such file or directorydebug1: identity file /home/brock/.ssh/id_ecdsa-cert type -1debug1: key_load_public: No such file or directorydebug1: identity file /home/brock/.ssh/id_ed25519 type -1debug1: key_load_public: No such file or directorydebug1: identity file /home/brock/.ssh/id_ed25519-cert type -1debug1: Enabling compatibility mode for protocol 2.0debug1: Local version string SSH-2.0-OpenSSH_7.4p1 Debian-10ssh_exchange_identification: read: Connection reset by peerThe issue has to do with how CentOS is configured for its networking or ssh. The CentOS VM has no issue connecting to the internet. It seems this could be an easy test for someone with VirtualBox. The CentOS minimal iso is 680 MB.Here is the /var/log/secure output for today when I've tried to ssh in with both my user and root.May 31 00:58:03 localhost sshd[1141]: Server listening on 0.0.0.0 port 22.May 31 00:58:03 localhost sshd[1141]: Server listening on :: port 22.May 31 00:58:14 localhost login: pam_unix(login:session): session opened for user root by LOGIN(uid=0)May 31 00:58:14 localhost login: ROOT LOGIN ON tty1May 31 00:58:22 localhost polkitd[656]: Registered Authentication Agent for unix-process:2529:3738 (system bus name :1.30 [/usr/bin/pkttyagent --notify-fd 5 --fallback], object path /org/freedesktop/PolicyKit1/AuthenticationAgent, locale en_US.UTF-8)May 31 00:58:23 localhost login: pam_unix(login:session): session closed for user rootMay 31 00:58:23 localhost polkitd[656]: Unregistered Authentication Agent for unix-process:2529:3738 (system bus name :1.30, object path /org/freedesktop/PolicyKit1/AuthenticationAgent, locale en_US.UTF-8) (disconnected from bus)May 31 00:58:25 localhost gdm-launch-environment]: pam_unix(gdm-launch-environment:session): session opened for user gdm by (uid=0)May 31 00:58:27 localhost polkitd[656]: Registered Authentication Agent for unix-session:c1 (system bus name :1.55 [gnome-shell --mode=gdm], object path /org/freedesktop/PolicyKit1/AuthenticationAgent, locale en_US.UTF-8)May 31 00:58:39 localhost gdm-password]: pam_unix(gdm-password:session): session opened for user jbc by (unknown)(uid=0)May 31 00:58:40 localhost gdm-launch-environment]: pam_unix(gdm-launch-environment:session): session closed for user gdmMay 31 00:58:40 localhost polkitd[656]: Unregistered Authentication Agent for unix-session:c1 (system bus name :1.55, object path /org/freedesktop/PolicyKit1/AuthenticationAgent, locale en_US.UTF-8) (disconnected from bus)May 31 00:58:40 localhost polkitd[656]: Registered Authentication Agent for unix-session:2 (system bus name :1.69 [/usr/libexec/xfce-polkit], object path /org/freedesktop/PolicyKit1/AuthenticationAgent, locale en_US.UTF-8)May 31 00:59:30 localhost sudo: jbc : user NOT in sudoers ; TTY=pts/0 ; PWD=/home/jbc ; USER=root ; COMMAND=/bin/yum remove --purge chromiumMay 31 00:59:42 localhost su: pam_unix(su-l:session): session opened for user root by jbc(uid=1000)May 31 01:15:18 localhost polkitd[656]: Registered Authentication Agent for unix-process:4582:105315 (system bus name :1.86 [/usr/bin/pkttyagent --notify-fd 5 --fallback], object path /org/freedesktop/PolicyKit1/AuthenticationAgent, locale en_US.UTF-8)May 31 12:58:19 localhost polkitd[659]: Loading rules from directory /etc/polkit-1/rules.dMay 31 12:58:19 localhost polkitd[659]: Loading rules from directory /usr/share/polkit-1/rules.dMay 31 12:58:19 localhost polkitd[659]: Finished loading, compiling and executing 4 rulesMay 31 12:58:19 localhost polkitd[659]: Acquired the name org.freedesktop.PolicyKit1 on the system busMay 31 12:58:29 localhost sshd[1139]: Server listening on 0.0.0.0 port 22.May 31 12:58:29 localhost sshd[1139]: Server listening on :: port 22.May 31 12:58:52 localhost login: pam_unix(login:session): session opened for user jbc by LOGIN(uid=0)May 31 12:58:52 localhost login: LOGIN ON tty1 BY jbcMay 31 13:02:01 localhost polkitd[659]: Registered Authentication Agent for unix-process:2581:22909 (system bus name :1.34 [/usr/bin/pkttyagent --notify-fd 5 --fallback], object path /org/freedesktop/PolicyKit1/AuthenticationAgent, locale en_US.UTF-8)May 31 13:02:04 localhost polkitd[659]: Operator of unix-process:2581:22909 successfully authenticated as unix-user:root to gain TEMPORARY authorization for action org.freedesktop.systemd1.manage-units for system-bus-name::1.35 [init 5] (owned by unix-user:jbc)May 31 13:02:05 localhost polkitd[659]: Unregistered Authentication Agent for unix-process:2581:22909 (system bus name :1.34, object path /org/freedesktop/PolicyKit1/AuthenticationAgent, locale en_US.UTF-8) (disconnected from bus)May 31 13:02:05 localhost login: pam_unix(login:session): session closed for user jbcMay 31 13:02:06 localhost gdm-launch-environment]: pam_unix(gdm-launch-environment:session): session opened for user gdm by (uid=0)May 31 13:02:09 localhost polkitd[659]: Registered Authentication Agent for unix-session:c1 (system bus name :1.64 [gnome-shell --mode=gdm], object path /org/freedesktop/PolicyKit1/AuthenticationAgent, locale en_US.UTF-8)May 31 13:02:15 localhost gdm-password]: pam_unix(gdm-password:session): session opened for user jbc by (unknown)(uid=0)May 31 13:02:16 localhost gdm-launch-environment]: pam_unix(gdm-launch-environment:session): session closed for user gdmMay 31 13:02:16 localhost polkitd[659]: Unregistered Authentication Agent for unix-session:c1 (system bus name :1.64, object path /org/freedesktop/PolicyKit1/AuthenticationAgent, locale en_US.UTF-8) (disconnected from bus)May 31 13:02:17 localhost polkitd[659]: Registered Authentication Agent for unix-session:4 (system bus name :1.78 [/usr/libexec/xfce-polkit], object path /org/freedesktop/PolicyKit1/AuthenticationAgent, locale en_US.UTF-8)May 31 13:02:33 localhost su: pam_unix(su-l:session): session opened for user root by jbc(uid=1000)May 31 13:03:18 localhost polkitd[659]: Registered Authentication Agent for unix-process:4348:30623 (system bus name :1.87 [/usr/bin/pkttyagent --notify-fd 5 --fallback], object path /org/freedesktop/PolicyKit1/AuthenticationAgent, locale en_US.UTF-8)May 31 13:03:18 localhost polkitd[659]: Unregistered Authentication Agent for unix-process:4348:30623 (system bus name :1.87, object path /org/freedesktop/PolicyKit1/AuthenticationAgent, locale en_US.UTF-8) (disconnected from bus)Also, /var/log/secure ssh related:[root@localhost ~]# cat /var/log/secure | grep May 31 | grep sshMay 31 00:58:03 localhost sshd[1141]: Server listening on 0.0.0.0 port 22.May 31 00:58:03 localhost sshd[1141]: Server listening on :: port 22.May 31 12:58:29 localhost sshd[1139]: Server listening on 0.0.0.0 port 22.May 31 12:58:29 localhost sshd[1139]: Server listening on :: port 22. | Cannot ssh into VirtualBox CentOS 7 guest from Debian host | centos;ssh;virtualbox;sshd | null |
_unix.259276 | There are certain domains pointing to my server.# example.comexample.com goes to 20.20.20.20I want to deny ssh access using this domain names. I want my server to only accept ssh connections on 20.20.20.20. How can I configure this?What I have tried# /etc/ssh/sshd_configUseDNS noExample:If user1 connects to 20.20.20.20 then it should show the login, otherwise it should just drop all connections.I am on a Debian Distribution. | Disallow ssh on domain names | ssh | null |
_unix.105059 | I have a pretty strange thing I'm seeing as I run 8 GPG encryption jobs with GNU parallel:The command I've run is this:find . -type f -not -iname *.gpg | sort |parallel --gnu -j 8 --workdir $PWD ' echo Encrypting {}... ; gpg --encrypt --recipient [email protected] {}'Why do the jobs seem to start and stop and start and stop rather than simply occupying all of the CPU time? | Parallel pausing and resuming? | gpg;parallel | null |
_webmaster.65197 | My website is in beta stage. I am using a temporary self-signed SSL certificate with a short expiry date. Beta users have to add the exception on their browser to access HTTPS on my website. Subsequently, I will be replacing the certificate with a trusted one from a Certificate Authority.Upon replacement of the self-signed certificate with a trusted certificate, do these beta users need to do anything to access my site on HTTPS, such as deleting the self-signed certificate on their browser manually? | What happens when a temporary self-signed SSL certificate is replaced with a trusted certificate? | security certificate | When you get a genuine certificate, you can replace your self-signed certificate and not worry about your users. Any user that had previously accepted the self signed certificate will be able to view the site with the genuine certificate without taking any special actions. They will not have to delete their acceptance of the self-signed certificate. |
_unix.20335 | I want to create a small script for my Linux system that would do some simple things on PC boot. The script is most likely going to be Python, but maybe I'll resort to C or shell.The problem is that I'm a Windows developer, and the tutorials on the web look suspicious.Some of them close all file descriptors, some don't, some implement restart, force-restart, some don't. With later ones seemingly being against the spec. Then there is the whole gid thing, that confuses me.So basically, I don't know which script base I can use for a stable daemon, and which ones are works-on-my-machine-so-it's-correct type.Then I stumbled upon http://manpages.ubuntu.com/manpages/hardy/man1/daemon.1.html which seems to be an official process that creates daemons, SAFELY. But then again, it's scripts in init.d that do the start-up, if I understand correctly, not existing processes.Then there is nice which should be used for long running tasks, if I got it right, and probably some other gotchas.So I'm lost here. Can anyone give me a few warnings, don'ts and maybe an idea where to look for the information online?P.S. The script I'm going to call will have to call processes, does that mean the daemon will fork for each of them? | What's the cleanest way to schedule autoexec.bat like command in Linux? | linux;startup;daemon | Well, it seems that the new way to do things in most recent distros is to use Upstart - http://upstart.ubuntu.com/cookbook/This should allow paralleled task execution as well as clean syntax. SystemV init procedures through init.d and rc.d are supposedly there only for backwards compatibility.Reading through the manual seems that Upstart is very powerful and clean solution, but I still have a lot to study. |
_cs.52510 | I am learning about finite automata for the first time. I am having trouble understanding the purpose of -transitions in an NFA, which seem to be crucial to counting the number of states in an NFA and therefore an equivalent DFA.Here is an example question that confuses me: What is the minimum number of states a DFA recognizing the language of a(bc)*d can have?To answer this question, I first drew this NFA (dashed line indicates acceptance):Because I think the above NFA is already a DFA, I thought the answer was 5.However, the correct NFA and equivalent DFA look like this:Which means the answer is 4. I understand why these are correct. But, I have some questions:1) Is my original drawing actually an NFA? If not, why?2) If the original drawing is an NFA, does it describe the language a(bc)*d? If not, why?3) If the original drawing is an NFA that describes the language a(bc)*d, is it also a DFA? If not, why? 4) If the original drawing is an NFA and DFA that describes the language a(bc)*d, why should I have known to draw the NFA with -transitions instead? | How Can I Recognize When to Use -Transitions in an NFA? | automata;finite automata;nondeterminism | Your first drawing is a DFA (and thus an NFA) and does match the language described. The NFA with $\varepsilon$ transitions is a fairly natural (and mechanical) translation of the regular expression, but other than that, it isn't inherently more correct than the NFA you started with.The only confusion I see here other than uncertainty is once you validated that your NFA was a DFA you seemed to have just taken it for granted that it was minimal. Starting from your DFA, you could have noticed that S4 has the same out-transitions as S2 and that they might possibly be joined. Doing so would have immediately produced the final DFA. |
_unix.152379 | This question is closely related to How to correctly start an application from a shell but tries to tackle a more specific problem. How can I spawn an application from a shell and thereby making it a child of another process. Here is what I mean exemplified with two graphics:systemd-+-acpid |-bash---chromium-+-chrome-sandbox---chromium-+-chrome-sandbox---nacl_helper | | `-chromium---5*[chromium-+-{Chrome_ChildIOT}] | | |-{Compositor}] | | |-{HTMLParserThrea}] | | |-{OptimizingCompi}] | | `-3*[{v8:SweeperThrea}]] | |-chromium | |-chromium-+-chromium | | |-{Chrome_ChildIOT} | | `-{Watchdog} | |-{AudioThread} | |-3*[{BrowserBlocking}] | |-{BrowserWatchdog} | |-5*[{CachePoolWorker}] | |-{Chrome_CacheThr} | |-{Chrome_DBThread} | |-{Chrome_FileThre} | |-{Chrome_FileUser} | |-{Chrome_HistoryT} | |-{Chrome_IOThread} | |-{Chrome_ProcessL} | |-{Chrome_SafeBrow} | |-{CrShutdownDetec} | |-{IndexedDB} | |-{LevelDBEnv} | |-{NSS SSL ThreadW} | |-{NetworkChangeNo} | |-2*[{Proxy resolver}] | |-{WorkerPool/1201} | |-{WorkerPool/2059} | |-{WorkerPool/2579} | |-{WorkerPool/2590} | |-{WorkerPool/2592} | |-{WorkerPool/2608} | |-{WorkerPool/2973} | |-{WorkerPool/2974} | |-{chromium} | |-{extension_crash} | |-{gpu-process_cra} | |-{handle-watcher-} | |-{inotify_reader} | |-{ppapi_crash_upl} | `-{renderer_crash_} |-2*[dbus-daemon] |-dbus-launch |-dhcpcd |-firefox-+-4*[{Analysis Helper}] | |-{Cache I/O} | |-{Cache2 I/O} | |-{Cert Verify} | |-3*[{DOM Worker}] | |-{Gecko_IOThread} | |-{HTML5 Parser} | |-{Hang Monitor} | |-{Image Scaler} | |-{JS GC Helper} | |-{JS Watchdog} | |-{Proxy R~olution} | |-{Socket Thread} | |-{Timer} | |-{URL Classifier} | |-{gmain} | |-{localStorage DB} | |-{mozStorage #1} | |-{mozStorage #2} | |-{mozStorage #3} | |-{mozStorage #4} | `-{mozStorage #5} |-gpg-agent |-login---bash---startx---xinit-+-Xorg.bin-+-xf86-video-inte | | `-{Xorg.bin} | `-dwm-+-dwmstatus | `-xterm---bash-+-bash | `-pstree |-systemd---(sd-pam) |-systemd-journal |-systemd-logind |-systemd-udevd |-wpa_actiond `-wpa_supplicantThe process tree shows chromium and firefox as children of the init process that starts at boot and has PID 1. But what I want to achieve is to start firefox and chromium as children of dwm. Hence, I want a similar behaviour to what you can see under the weston part of the following process tree where firefox has weston-desktop as its parent:systemd-+-acpid |-bash---chromium-+-chrome-sandbox---chromium-+-chrome-sandbox---nacl_helper | | `-chromium-+-3*[chromium-+-{Chrome_ChildIOT}] | | | |-{Compositor}] | | | |-{HTMLParserThrea}] | | | |-{OptimizingCompi}] | | | `-3*[{v8:SweeperThrea}]] | | `-4*[chromium-+-{Chrome_ChildIOT}] | | |-{CompositorRaste}] | | |-{Compositor}] | | |-{HTMLParserThrea}] | | |-{OptimizingCompi}] | | `-3*[{v8:SweeperThrea}]] | |-{AudioThread} | |-3*[{BrowserBlocking}] | |-{BrowserWatchdog} | |-5*[{CachePoolWorker}] | |-{Chrome_CacheThr} | |-{Chrome_DBThread} | |-{Chrome_FileThre} | |-{Chrome_FileUser} | |-{Chrome_HistoryT} | |-{Chrome_IOThread} | |-{Chrome_ProcessL} | |-{Chrome_SafeBrow} | |-{Chrome_SyncThre} | |-{CrShutdownDetec} | |-{IndexedDB} | |-{NSS SSL ThreadW} | |-{NetworkChangeNo} | |-2*[{Proxy resolver}] | |-{WorkerPool/2315} | |-{WorkerPool/2316} | |-{WorkerPool/2481} | |-{chromium} | |-{extension_crash} | |-{gpu-process_cra} | |-{handle-watcher-} | |-{inotify_reader} | |-{renderer_crash_} | `-{sandbox_ipc_thr} |-2*[dbus-daemon] |-dbus-launch |-dhcpcd |-gpg-agent |-login---bash---startx---xinit-+-Xorg.bin-+-xf86-video-inte | | `-{Xorg.bin} | `-dwm-+-dwmstatus | `-xterm---bash |-login---bash---weston-launch---weston-+-Xwayland---4*[{Xwayland}] | |-weston-desktop--+-firefox-+-firefox | | | |-4*[{Analysis Helper}] | | | |-{Cache2 I/O} | | | |-{Cert Verify} | | | |-{DNS Resolver #1} | | | |-{DNS Resolver #2} | | | |-2*[{DOM Worker}] | | | |-{Gecko_IOThread} | | | |-{HTML5 Parser} | | | |-{Hang Monitor} | | | |-{Image Scaler} | | | |-{ImageDecoder #1} | | | |-{ImageDecoder #2} | | | |-{ImageDecoder #3} | | | |-{JS GC Helper} | | | |-{JS Watchdog} | | | |-{Socket Thread} | | | |-{Timer} | | | |-{URL Classifier} | | | |-{gmain} | | | |-{localStorage DB} | | | |-{mozStorage #1} | | | |-{mozStorage #2} | | | |-{mozStorage #3} | | | |-{mozStorage #4} | | | `-{mozStorage #5} | | `-weston-terminal---bash---pstree | `-weston-keyboard |-systemd---(sd-pam) |-systemd-journal |-systemd-logind |-systemd-udevd |-tmux---bash |-wpa_actiond `-wpa_supplicantOne possible solution would be to use nsenter from util-linux. I could enter the namespace of the dwm process and fork a new firefox process which would then be the child of dwm. However, that seems like a lot of work. Is there some easier way to do this? | Is reparenting from the shell possible? | process;exec;namespace | You can not start a process as the child of the shell, and then reparent it so another process becomes it's parent.So you need to use a parent process that explicitly starts the children.init with PID 1 is an exception, processes can become it's child as it collects processes that lost their original parent process.(With upstart, there can be multiple init processes, they do not share the PID 1, but otherwise the roles are very similar.)(See also PR_SET_CHILD_SUBREAPER in man 2 prctl) |
_unix.145918 | Do the upstream PHP servers have to run the same server software?If I have the following Nginx configuration upstream myapp1 { server srv1.example.com; server srv2.example.com; }Assuming we have shared back-end database and identical web sites, could I use Apache on srv1 and PHP-FPM on srv2 to compare the two under identical real-world load? | Nginx loadbalancing between PHP-FPM and Apache | nginx | null |
_unix.253447 | I am looking for a one liner for this if it is possible.I have a sequence like thisCCGGTCTCTTCCGGTTCTGTCTTTTCGCTGGI want to get the output where I scan the sequence base by base and then take 20 bp from that. SO the output should be something like thisCCGGTCTCTTCCGGTTCTGTCGGTCTCTTCCGGTTCTGTCGGTCTCTTCCGGTTCTGTCTand so on..The length should always be 20 bpI wrote a perl code and it worked. Looking for one liner if some one can help using awk or sed??while(<>){ chomp; for my $i(0..length($_)){ my $str = substr($_,$i,20); next if(length($str) < 20); print $str,\n; }}Let me know | scanning a sequence and outputting a sub sequence | text processing | If you're already familiar with Perl, why not use it? Perl excels at one-liners:$ perl -F'' -lane 'for($i=0;$i<=$#F-20;$i++){print @F[$i..$i+20]}' fileCCGGTCTCTTCCGGTTCTGTCCGGTCTCTTCCGGTTCTGTCTGGTCTCTTCCGGTTCTGTCTTGTCTCTTCCGGTTCTGTCTTTTCTCTTCCGGTTCTGTCTTTTCTCTTCCGGTTCTGTCTTTTCTCTTCCGGTTCTGTCTTTTCGCTTCCGGTTCTGTCTTTTCGCTTCCGGTTCTGTCTTTTCGCTTCCGGTTCTGTCTTTTCGCTGCCGGTTCTGTCTTTTCGCTGGExplanationThe -a switch makes perl act like awk, splitting its input lines on the value given by -F and saving them in @F. Since -F here is empty, the result is that the @F array's elements are the characters of the line. The -l switch turns on chomp automatically and also adds a \n to each print call. The script itself simply increments a counter ($i) from 0 until the length of the array ($#F) and does so as long as $i is less than or equal to the array's length minus 20, to only get sequences of the right size. It then prints the array slice from the current value of $i until $i+20. If you run this with -MO=Deparse to analyze what its doing, you can see that it runs:$ perl -MO=Deparse -F'' -lane 'for($i=0;$i<=$#F-20;$i++){print @F[$i..$i+20]}' fileBEGIN { $/ = \n; $\ = \n; }LINE: while (defined($_ = <ARGV>)) { chomp $_; our @F = split(//, $_, 0); for ($i = 0; $i <= $#F - 20; ++$i) { print @F[$i .. $i + 20]; }}-e syntax OK |
_unix.66786 | I have created a script that kills processes if CPU and/or memory usage hits 80%. It creates a list of killed processes when this happens. What can I do to improve it?while [ 1 ];do echoecho checking for run-away process ...CPU_USAGE=$(uptime | cut -d, -f4 | cut -d: -f2 | cut -d -f2 | sed -e s/\.//g)CPU_USAGE_THRESHOLD=800PROCESS=$(ps aux r)TOPPROCESS=$(ps -eo pid -eo pcpu -eo command | sort -k 2 -r | grep -v PID | head -n 1)if [ $CPU_USAGE -gt $CPU_USAGE_THRESHOLD] ; then kill -9 $(ps -eo pid | sort -k 1 -r | grep -v PID | head -n 1) #original kill -9 $(ps -eo pcpu | sort -k 1 -r | grep -v %CPU | head -n 1) kill -9 $TOPPROCESS echo system overloading! echo Top-most process killed $TOPPROCESS echo CPU USAGE is at $CPU_LOADelse fi exit 0 sleep 1; done | Bash script that automatically kills processes when CPU/memory usage gets too high | bash;shell script;memory;cpu;cpu usage | I'm guessing the problem you want to solve is that you have some process running on your box which sometimes misbehaves, and sits forever pegging a core.The first thing you want to do is to attempt to fix the program that goes crazy. That is by far the best solution. I'm going to assume that isn't possible, or you need a quick kluge to keep your box running until its fixed.You, at minimum, want to limit your script to only hit the one program you're concerned about. It'd be best if permissions limited your script like this (e.g., your script runs as user X, the only other thing running as X is the program).Even better would be to use something like ulimit -t to limit the amount of total CPU time that the program can use. Similarly, if it consumes all memory, check ulimit -v. The kernel enforces these limits; see the bash manpage (it's a shell built-in) and the setrlimit(2) manpage for details.If the problem isn't a process running amok, but is instead just too many processes running, then implement some form of locking to prevent more than X from running (orthis should be getting familiarulimit -u). You may also consider changing the scheduler priority of those processes (using nice or renice), or for even more drastic, using sched_setscheduler to change the policy to SCHED_IDLE. If you need even more control, take a look a control groups (cgroups). Depending on the kernel you're running, you can actually limit the amount of CPU time, memory, I/O, etc. that a whole group of processes together consume. Control groups are quite flexible; they can likely do whatever you're trying to do, without any fragile kluges. The Arch Linux Wiki has an intro to cgroups that's worth reading, as is Neil Brown's cgroups series at LWN. |
_cs.13400 | I realize non-deterministic pushdown automata can be an improvement over deterministic ones as they can choose among several states and there are some context-free languages which cannot be accepted by a deterministic pushdown.Still, I do not understand how exactly they choose. For palindormes for example every source I found just says the automaton guesses the middle of the word. What does that mean?I can think of several possible meanings:It goes into one state randomly and therefore might not accept aword, which actually is in the languageIt somehow goesevery possible way, so if the first one is wrong it tests if anyof the other might be rightThere is some mechanism I am notaware of, that chooses the middle of the word and is therefore notrandom, but the automaton always finds the right middle.This is just an example; what I want to know is how it works for any automaton that has several following states for one and the same state before it. | Push Down Automatons guess - what does that mean? | automata;pushdown automata;nondeterminism | Quite simply, the mechanism is magic. The idea of non-determinism is that it simply knows which way it should take in order to accept the word, and it goes that way. If there are multiple ways, it goes one of them.Non-determinism can't be implemented as such in real hardware. We simulate it using techniques such as backtracking. But it's primarily a theoretical device, which can be used to simplify the presentation of certain concepts.For the palindrome, you can think about it in two ways. Either there's a magical power that lets your machine say this is the middle of the word, time to switch from pushing to popping, or after reading each letter, it says I'm going to fork a new process which that this letter is the middle of the word, and see if it finds it's a palindrome. Then in this other thread, I'll keep trying, assuming this isn't the middle of the word.Another way to think of it is as infinite parallelism. So an equivalent model would be that, instead of choosing a new path, it simultaneously tries both paths, branching off new processes, succeeding if any are in a final state after reading the whole word. Again, this can't be built using real hardware, but can be modelled with non-determinism.The interesting thing about nondeterminism is that for finite-automata and Turing machines, it doesn't increase their computational power at all, just their efficiency. |
_softwareengineering.187965 | I'm trying to see if these two open source licenses give protection of trademarks to the originator. I have read both licenses but they only seem to talk about their own trademark i.e. 'Apache'. | Will the Apache License or the GPL License protect my trademarks? | open source;gpl;apache license;trademark | null |
_unix.222415 | I encountered some strange behavior on a machine that uses a replicated block device (via DRBD) along with OCFS2 to allow concurrent mounts on multiple machines. The issue, in short, is that new files and directories created within this filesystem do not respect the umask.Please consider the following:$> cd /mountpoint$> umask0002$> mkdir testdir$> touch test.txt$> su#> umask0022#> mkdir testdir2#> touch test2.txt#> ls -l-rw-rw-rw- (...) test2.txtdrwxrwxrwx (...) testdirdrwxrwxrwx (...) testdir2-rw-rw-rw- (...) test.txt#> getfacl .# file: .# owner: me# group: meuser::rwxgroup::r-xother::r-x#> cat /etc/mtab(...)/dev/drbd0 /mountpoint ocfs2 rw,_netdev,heartbeat=local 0 0Hopefully the above is sufficient to know that there are no ACLs in play. This happens for both privileged and unprivileged users, and it does not occur outside of the OCFS2 filesystem.So far my research on the topic has turned up no known issues with OCFS2 (or DRBD for that matter). Are there other tests I can run to narrow down the issue? Is anyone aware of why this might be taking place? Thank you for your time.[I would have tagged under ocfs2, but that tag does not yet exist.] | Umask not respected in OCFS2 filesystem | umask;drbd | It appears this wouldn't be the first time ocfs2 has had a bug like that. http://comments.gmane.org/gmane.comp.file-systems.ocfs2.user/3439. That was 2009, so it surely got fixed eventually, and yours is probably a different bug with the same symptom. I'd report it to ocfs2's bug tracker, which appears to be at https://oss.oracle.com/bugzilla/buglist.cgi?product=OCFS2 |
_unix.348596 | I have a Yubikey 4 Nano. With a Debian Jessie live cd and a modified /etc/libccid_Info.plist (see here ) as well as libccid, pcscd and a few other packages installed I'm able to use it with e.g. pkcs-tool, pcks11-tool etc...However, I use FAI to deploy machines and FAI is using debootstrap to install a Jessie base system. For some reason this system with the same plist file and the same set of packages is not working with the Yubikey. When running pkcs-tool --list-readersI get the outputNo smart cart readers foundI don't expect anyone to say Eureka with once in this case, but do you have any suggestion for how I can proceed to find out what's the difference between these systems, USB/pcsc-wise?There is a slightly difference in kernel version between the two systems; the Jessie live CD has kernel 3.16.36-1+deb8u1 and the FAI installed version has 3.16.39-1.Running dmesg I can see that the Yubikey is found and recognized in both cases, but in the FAI case, pcscd is not running at boot (status failed, so it was unable to start). I can start it manually, however and it keeps running then, but I still cannot find any smart card readers after doing so. | How can i find out why my Yubikey is working on a Debian Jessie live cd but not with FAI/debootstrap? | debian;drivers;smartcard;yubikey | null |
_unix.315795 | I have a server that is infected with Ebury rootkit, that doesn't show the infected files, and the process listening for connections when it is being checked over SSH for any signs of infection, but shows them normally when checking over Salt or local session.I had servers with Ebury infection before, and was always able to see suspicious files and processes when checking over SSH, but on this variant I can't, and I am wondering why exactly.Info on suspicious files and processes:Server has an atd process listening for connections using Unix domain sockets, and when it is checked over Salt, or local session, netstat shows the the process listening.$ salt -L server cmd.run netstat -plan | grep -w atdserver: unix 2 [ ACC ] STREAM LISTENING 55898 5264/atd @/tmp/dbus-GeTBbBytfBWhen I check the server over SSH, netstat comes back clean, as it should on non-infected servers.root@server [~]# netstat -plan | grep -w atdroot@server [~]#When checking for standard files that are used by Ebury, over Salt or local session, I can see the following returned.$ salt -L server cmd.run rpm -qf /lib64/tls/libkeyutils.so.1.5 /lib64/tls/libkeyutils.so.1server: file /lib64/tls/libkeyutils.so.1.5 is not owned by any package file /lib64/tls/libkeyutils.so.1 is not owned by any packageWhen checking over SSH, files are reported as non-existent.root@server [~]# rpm -qf /lib64/tls/libkeyutils.so.1.5 /lib64/tls/libkeyutils.so.1error: file /lib64/tls/libkeyutils.so.1.5: No such file or directoryerror: file /lib64/tls/libkeyutils.so.1: No such file or directoryroot@server [~]#When checking disk space used by folder containing suspicous files, I get different results returned on Salt and local session, then over SSHSalt and local session:root@salt-master-vps [~]$ salt -L server cmd.run du -shc /lib64/tls/; du -shc /lib64/tls/*;server: 56K /lib64/tls/ 56K total 0 /lib64/tls/libkeyutils.so.1 52K /lib64/tls/libkeyutils.so.1.5 52K totalOver SSHroot@server [~]# du -shc /lib64/tls/; du -shc /lib64/tls/*;4.0K /lib64/tls/4.0K totaldu: cannot access `/lib64/tls/*': No such file or directory0 totalroot@server [~]#Trying to find the file over inode number, over Salt and local:$ salt -L server cmd.run find /lib64/tls -inum 213647535server: /lib64/tls/libkeyutils.so.1.5Over SSH:root@server [~]# find /lib64/tls -inum 213647535root@server [~]#Checking loaded libraries of various executables over Salt and local session:$ salt -L server cmd.run ldd /usr/bin/wget | grep tlsserver: libkeyutils.so.1 => /lib64/tls/libkeyutils.so.1 (0x0000003b96200000)Check over SSH, doesn't show suspicous files loadedroot@server [~]# ldd /usr/bin/wget | grep tlsroot@server [~]#Checking PID of atd with lsof, over Salt and local session, shows listener (@/tmp/dbus-GeTBbBytfB) and suspicious file /lib64/tls/libkeyutils.so.1.5:$ salt -L server cmd.run lsof -p 5264server: COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME atd 5264 root cwd DIR 8,4 4096 2 / atd 5264 root rtd DIR 8,4 4096 2 / atd 5264 root txt REG 8,4 23968 232524937 /usr/sbin/atd atd 5264 root mem REG 8,4 113952 213647527 /lib64/libresolv-2.12.so atd 5264 root mem REG 8,4 10312 213647581 /lib64/libfreebl3.so atd 5264 root mem REG 8,4 43392 213647547 /lib64/libcrypt-2.12.so atd 5264 root mem REG 8,4 145864 213647601 /lib64/libaudit.so.1.0.0 atd 5264 root mem REG 8,4 91096 213647529 /lib64/libz.so.1.2.3 atd 5264 root mem REG 8,4 22536 213647519 /lib64/libdl-2.12.so atd 5264 root mem REG 8,4 1928936 213647514 /lib64/libc-2.12.so atd 5264 root mem REG 8,4 14584 213647675 /lib64/libpam_misc.so.0.82.0 atd 5264 root mem REG 8,4 55848 213647656 /lib64/libpam.so.0.82.2 atd 5264 root mem REG 8,4 122056 213647396 /lib64/libselinux.so.1 atd 5264 root mem REG 8,4 50720 213647535 /lib64/tls/libkeyutils.so.1.5 atd 5264 root mem REG 8,4 1967392 232527760 /usr/lib64/libcrypto.so.1.0.1e atd 5264 root mem REG 8,4 157072 213647475 /lib64/ld-2.12.so atd 5264 root 0u CHR 1,3 0t0 4245 /dev/null atd 5264 root 1u CHR 1,3 0t0 4245 /dev/null atd 5264 root 2u CHR 1,3 0t0 4245 /dev/null atd 5264 root 3u unix 0xffff88042a2180c0 0t0 55898 @/tmp/dbus-GeTBbBytfBWhen checking over SSH, no suspicous file, and listener using unix socket is shown as can't identify protocolroot@server [~]# lsof -p 5264COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAMEatd 5264 root cwd DIR 8,4 4096 2 /atd 5264 root rtd DIR 8,4 4096 2 /atd 5264 root txt REG 8,4 23968 232524937 /usr/sbin/atdatd 5264 root mem REG 8,4 113952 213647527 /lib64/libresolv-2.12.soatd 5264 root mem REG 8,4 10312 213647581 /lib64/libfreebl3.soatd 5264 root mem REG 8,4 43392 213647547 /lib64/libcrypt-2.12.soatd 5264 root mem REG 8,4 145864 213647601 /lib64/libaudit.so.1.0.0atd 5264 root mem REG 8,4 91096 213647529 /lib64/libz.so.1.2.3atd 5264 root mem REG 8,4 22536 213647519 /lib64/libdl-2.12.soatd 5264 root mem REG 8,4 1928936 213647514 /lib64/libc-2.12.soatd 5264 root mem REG 8,4 14584 213647675 /lib64/libpam_misc.so.0.82.0atd 5264 root mem REG 8,4 55848 213647656 /lib64/libpam.so.0.82.2atd 5264 root mem REG 8,4 122056 213647396 /lib64/libselinux.so.1atd 5264 root mem REG 8,4 1967392 232527760 /usr/lib64/libcrypto.so.1.0.1eatd 5264 root mem REG 8,4 157072 213647475 /lib64/ld-2.12.soatd 5264 root 0u CHR 1,3 0t0 4245 /dev/nullatd 5264 root 1u CHR 1,3 0t0 4245 /dev/nullatd 5264 root 2u CHR 1,3 0t0 4245 /dev/nullatd 5264 root 3u sock 0,6 0t0 55898 can't identify protocolroot@server [~]#File does get shown over SSH, when I check with ldconfigroot@server [~]# /sbin/ldconfig -p | grep /lib64/tls/libkeyutils.so.1 libkeyutils.so.1 (libc6,x86-64, hwcap: 0x8000000000000000) => /lib64/tls/libkeyutils.so.1root@server [~]#I am wondering if anyone can explain, why is it that I can't see the files and processes when connected over SSH, but I can when checking on local terminal session and over Salt?Why is disk usage of the folder shown differently over SSH?Why are loaded libraries not visible over SSH?Also, did anyone else encounter this behavior?All the previous instances of Ebury infection, I encountered till now, were visible over SSH when checking processes and files. | Ebury infection, suspicious processes and files visible over Salt or local session, but not over SSH | ssh;malware | null |
_scicomp.16281 | I'm trying to make an animation of a travelling sine wave (amplitude vs. position) would anyon here happen to know how to do so? | Simulating a traveling sine wave | c++;wave propagation | null |
_codereview.138774 | I'm trying to recreate a printer in Java. I'm fairly new to programming so I'm using huge if/else blocks inside a single function to dictate the logic of the program. I'm noticing this is creating a mass of code inside the same function.I was wondering if there was a more eloquent/efficient way of doing this Printer class.Logic for the printer isn't too important, but just to show anyway: one is a double sided printer one isn't, and logic is in charge of checking toner levels and making sure pages printed are in line with printer being double sided or not.package com.company;public class Printer {private String name;private double tonerLevel = 100;private int ammountOfPaper;private int numberOfPagesPrinted;private boolean isDoubleSided;public Printer(String name, double tonerLevel, int ammountOfPaper, boolean isDoubleSided) { this.name = name; if(tonerLevel >= 0 && tonerLevel <= 100) { this.tonerLevel = tonerLevel; } this.ammountOfPaper = ammountOfPaper; this.isDoubleSided = isDoubleSided;}private boolean isOutOfToner(double numberToPrint) { if((tonerLevel - (numberToPrint / 2) < 0)) { return true; } else { return false; }}private boolean isOutOfPaper(double numberToPrint) { if(((ammountOfPaper - numberToPrint) < 0)) { return true; } else { return false; }}private boolean twoSideNoPaperEven(double numberToPrint) { if((ammountOfPaper - ((int) numberToPrint / 2)) < 0 ) { return true; } else { return false; }}private boolean twoSideNoPaperOdd(double numberToPrint) { if(((ammountOfPaper - ((int) numberToPrint / 2)) - 1) < 0) { return true; } else { return false; }}public void printPages(double numberToPrint) { if(isDoubleSided == false) { if(tonerLevel == 0) { System.out.println(Out of toner); } if(ammountOfPaper == 0) { System.out.println(Out of Paper); } if(isOutOfToner(numberToPrint) && (tonerLevel != 0)) { double difference = tonerLevel * 2; numberToPrint = difference; ammountOfPaper -= numberToPrint; System.out.println(Will run out of toner after this print, able to print + (int) numberToPrint + pages); tonerLevel = 0; } if(isOutOfPaper(numberToPrint) && (ammountOfPaper != 0)) { double different = ammountOfPaper - numberToPrint; numberToPrint = numberToPrint + different; System.out.println(Will run out of paper after this print, printing + (int) numberToPrint + pages); ammountOfPaper = 0; } else if(!isOutOfToner(numberToPrint) && (!isOutOfPaper(numberToPrint))) { ammountOfPaper -= numberToPrint; tonerLevel = tonerLevel - (numberToPrint / 2); showPages(numberToPrint); } } else if(isDoubleSided = true) { if (numberToPrint % 2 == 0) { if(tonerLevel == 0) { System.out.println(Out of Toner); } if(ammountOfPaper == 0) { System.out.println(Out of Paper); } if(twoSideNoPaperEven(numberToPrint) && (ammountOfPaper != 0)) { ammountOfPaper -= numberToPrint / 2; System.out.println(There is no Paper); } else if(!twoSideNoPaperEven(numberToPrint)) { tonerLevel = tonerLevel - (numberToPrint / 2); ammountOfPaper -= numberToPrint / 2; showPages(numberToPrint); } } else { if(tonerLevel == 0) { System.out.println(Out of Toner); } if(ammountOfPaper == 0) { System.out.println(Out of Paper); } if(twoSideNoPaperOdd(numberToPrint) && (ammountOfPaper != 0)) { System.out.println(There is no paper); ammountOfPaper = (ammountOfPaper - ((int) numberToPrint / 2)) - 1; ammountOfPaper = 0; } else if(!twoSideNoPaperOdd(numberToPrint)) { tonerLevel = tonerLevel - (numberToPrint / 2); ammountOfPaper = (ammountOfPaper - ((int) numberToPrint / 2)) - 1; showPages(numberToPrint); } } } }public void showPages(double numberToPrint) { System.out.println(Printing + (int) numberToPrint + Pages, paper remaining is: + this.ammountOfPaper + Toner level is: + this.tonerLevel);}public void refillToner() { tonerLevel = 100;}public void refillPaper(int paper) { if(paper > 50) { System.out.println(Cannot put in more paper); } else { this.ammountOfPaper += paper; }}public int getAmmountOfPaper() { return ammountOfPaper;}public double getTonerLevel() { return tonerLevel;}public void setTonerLevel(double tonerLevel) { this.tonerLevel = tonerLevel;}public void setAmmountOfPaper(int ammountOfPaper) { this.ammountOfPaper = ammountOfPaper;} | Simulating a printer | java;simulation | I'd just like to add something that I haven't seen mentioned by others (or maybe I skipped it), but take for example this piece of code:public void printPages(double numberToPrint) { // ... if(tonerLevel == 0) { System.out.println(Out of toner); } if(ammountOfPaper == 0) { System.out.println(Out of Paper); } if(isOutOfToner(numberToPrint) && (tonerLevel != 0)) { double difference = tonerLevel * 2; numberToPrint = difference; ammountOfPaper -= numberToPrint; System.out.println(Will run out of toner after this print, able to print + (int) numberToPrint + pages); tonerLevel = 0; } if(isOutOfPaper(numberToPrint) && (ammountOfPaper != 0)) { double different = ammountOfPaper - numberToPrint; numberToPrint = numberToPrint + different; System.out.println(Will run out of paper after this print, printing + (int) numberToPrint + pages); ammountOfPaper = 0; } else if(!isOutOfToner(numberToPrint) && (!isOutOfPaper(numberToPrint))) { ammountOfPaper -= numberToPrint; tonerLevel = tonerLevel - (numberToPrint / 2); showPages(numberToPrint); } // ...}You're checking your parameters twice, when you could return after a faulty state of the printer has been acknowledged (i.e. out of paper; we surely can't print without paper). So you could do something like this:private boolean canPrint(int numberToPrint) { if (tonerLevel == 0) { System.out.println(Out of toner); return false; } else if (ammountOfPaper == 0) { System.out.println(Out of Paper); return false; } else if (!hasEnoughToner(numberToPrint)) { // Maybe print a message to let the user know why you're not printing return false; } else if (!hasEnoughPaper(numberToPrint)) { // Maybe print a message to let the user know why you're not printing return false; } return true;}private void print(int numberToPrint) { if (canPrint(numberToPrint)) { ammountOfPaper -= numberToPrint; tonerLevel = tonerLevel - (numberToPrint / 2); showPages(numberToPrint); }}I have avoided the parts of code where you mention when you will run out of paper or toner after the print, because I am in a hurry, but you get the point.Basically, once you know the state of something, you shouldn't have to come back to that. If the state is fatal (i.e. no paper), you can return from your method, as there is nothing that you can really print. This way, you can check your conditions only once and be done with them.Hope this helps. :) |
_codereview.142114 | I have the following method in a Controller in Laravel 5.3.The method is supposed to be in two other controllers and all three Controller methods will receive the needed arguments in different ways.I'm unsure if this would be a good fit for a Service Container or how I should handle it.public function newSurvey(Request $request){ // Some validation for the input $delay = 0; if( $request->has('delay') ) { $delay = $request->get('delay') * 60; } if($request->has('template')) { $template = $this->application->templates()->where('slug', $request->get('template'))->first(); } else { if(count($this->application->templates) == 0) { return response()->json(['error' => 'You need to create a Survey Template to send out new Surveys'], 422); } $template = $this->application->templates()->where('default', true)->first(); } if(!$person = $this->application->persons->where('email', mb_strtolower($request->get('email')))->first()) { $person = new Person(); $person->name = $request->get('name'); $person->email = mb_strtolower($request->get('email')); $person->key = Uuid::uuid4()->toString(); $this->application->persons()->save($person); } if(!$person->active) { return response()->json(['error' => 'Recipient is inactive and cannot be contacted anymore'], 422); } if($person->updated_at->diffInDays(Carbon::now()) < $this->application->cooldown) { return response()->json(['error' => 'Recipient has already received a survey wihtin the cooldown period'], 422); } $person->touch(); $survey = new Survey([ 'key' => Uuid::uuid4()->toString(), 'template_id' => $template->id, 'person_id' => $person->id, 'name' => $request->get('name', null), 'email' => $request->get('email'), 'order' => $request->get('order', null), 'segment' => $request->get('segment', null), ]); $this->application->surveys()->save($survey); $when = \Carbon\Carbon::now()->addSeconds($delay); Mail::to($survey->email, $survey->name)->later($when, new NewSurvey($survey)); return response()->json(['survey_id' => $survey->key], 200);} | Maintainability with lots of lookups, checks and inserts | php;laravel | null |
_unix.244594 | I'm running tomcat on main website using nginx proxy pass, now I want to install wordpress on the same domain as a sub-directory like this.domain.com/blogI used below config in nginx. location /blog { root /home/blog/html; index index.php index.htm index.html; try_files $uri $uri/ /blog/index.php?$args; } location ~ \.php$ { root /home/blog/html; try_files $uri =404; fastcgi_buffers 16 16k; fastcgi_buffer_size 32k; fastcgi_read_timeout 200; fastcgi_split_path_info ^(.+\.php)(/.+)$; fastcgi_pass unix:/var/run/blog-php-fpm.sock; fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; include fastcgi_params; } location ~* ^.+.(jpg|jpeg|gif|css|png|js|ico|xml)$ { access_log off; log_not_found off; expires 30d; }When I visit domain.com/blog the wordpress installation page will go like thishttp://domain.com/wp-admin/setup-config.phphow can I properly install wordpress with tomcat?. | WordPress subdirectory installation with Tomcat using nginx webserver | nginx;wordpress | null |
_webapps.107890 | YouTube has now disabled the creation of Annotations, and instead has given us End Screens and Cards, but I can't see how to recreate this particular look with either.Is this an advertisement? If so, what type? It doesn't seem to appear in their advertising documentation, either (which states that overlay advertisements are 480x70). | What is this advertisement on the bottom-left of a YouTube video? | video;youtube | This is a call to action overlay (which is different from an overlay ad). CTA overlays are available in advertisements (if a video ever has been used as a video ad, any CTA overlays that have been inserted during the campaing remain on it afterwards), for non-profit accounts and for twitch live notifications. |
_codereview.129655 | I am trying to prototype a simple structure for a Web crawler in Java. Until now the prototype is just trying to do the below:Initialize a Queue with list of starting URLsTake out a URL from Queue and submit to a new ThreadDo some work and then add that URL to a Set of already visited URLsFor the Queue of starting URLs, I am using a ConcurrentLinkedQueue for synchronizing. For Set of already visited URLs, I am using Collections.synchronizedSet(new HashSet<URL>())To spawn new Threads I am using ExecutorService.Please review if the design is optimized and if multi-threading is implemented correctly here.In the block of code in CrawlerTask:synchronized (crawler) { if (!crawler.getUrlVisited().contains(url)) { new Scraper().scrape(url); crawler.addURLToVisited(url); } }I think that the lock on crawler object will let only 1 Thread proceed at a time (since the object is passed to every Callable), which does not confirm with the multi-threaded design here.Starting class for the application:public class CrawlerApp { private static Crawler crawler; public static void main(String[] args) { crawler = new Crawler(); initializeApp(); startCrawling(); } private static void startCrawling() { WorkerManager workers = WorkerManager.getInstance(); while (!crawler.getUrlHorizon().isEmpty()) { URL url = crawler.getUrlHorizon().poll(); if(!crawler.getUrlVisited().contains(url)){ Future future = workers.getExecutor().submit(new CrawlerTask(url, crawler)); } } try { workers.getExecutor().shutdown(); workers.getExecutor().awaitTermination(5, TimeUnit.SECONDS); } catch (InterruptedException e) { e.printStackTrace(); } } private static void initializeApp() { Properties config = new Properties(); try { config.load(CrawlerApp.class.getClassLoader().getResourceAsStream(url-horizon.properties)); String[] horizon = config.getProperty(urls).split(,); for (String link : horizon) { URL url = new URL(); url.setURL(link); crawler.getUrlHorizon().add(url); } } catch (IOException e) { e.printStackTrace(); } }}Crawler.java which maintains the Queue of URLs and Set of already visited URLs.public class Crawler { private volatile ConcurrentLinkedQueue<URL> urlHorizon = new ConcurrentLinkedQueue<URL>(); public void setUrlHorizon(ConcurrentLinkedQueue<URL> urlHorizon) { this.urlHorizon = urlHorizon; } public ConcurrentLinkedQueue<URL> getUrlHorizon() { return urlHorizon; } private volatile Set<URL> urlVisited = Collections.synchronizedSet(new HashSet<URL>()); public void setUrlVisited(Set<URL> urlVisited) { this.urlVisited = urlVisited; } public Set<URL> getUrlVisited() { return urlVisited; } public void addURLToVisited(URL url) { if (getUrlVisited().contains(url)) { System.out.println(Duplicate found in already visited: + url.getURL()); return; } else { System.out.println(Adding to visited set: + url.getURL()); getUrlVisited().add(url); } }}URL.java is just a class with private String url and overriden hashCode() and equals().Also, Scraper.scrape() just has dummy implementation until now:public void scrape(URL url){ System.out.println(Done scrapping:+url.getURL()); }WorkerManager to create Threads:public class WorkerManager { private static final Integer WORKER_LIMIT = 10; private final ExecutorService executor = Executors.newFixedThreadPool(WORKER_LIMIT); public ExecutorService getExecutor() { return executor; } private static volatile WorkerManager instance = null; private WorkerManager() { } public static WorkerManager getInstance() { if (instance == null) { synchronized (WorkerManager.class) { if (instance == null) { instance = new WorkerManager(); } } } return instance; } public Future createWorker(Callable call) { return executor.submit(call); }}CrawlerTask which is run in a separate Thread for every URL:public class CrawlerTask implements Callable { public CrawlerTask(URL url, Crawler crawler) { this.url = url; this.crawler = crawler; } URL url; Crawler crawler; private void crawlTask() { synchronized (crawler) { if (!crawler.getUrlVisited().contains(url)) { new Scraper().scrape(url); crawler.addURLToVisited(url); } } } @Override public Object call() throws Exception { crawlTask(); return null; }} | Skeleton of a Multi-threaded web crawler in Java | java;multithreading | null |
_webapps.40524 | Sometimes when I save, it hangs. Data is lost, without any way to recover (I've tried to 'save as' during the hang). I am on Chrome 24.0.1312.57 on Mac OS X 10.8.2. I hope the following bit from console helps. Uncaught TypeError: Cannot read property 'error' of undefined diagramly.min.js:1801 30 Uncaught TypeError: Object [object Object] has no method 'scrollCellVisible' diagramly.min.js:1593Thanks! | Draw.io: Hangs on save (sometimes) and progress is lost | draw.io;save | null |
_webmaster.108881 | One of my client has URL parameters on the main category pages on the website (e.g. www.example.com/category?utm_parameter)for some tracking. Will adding these parameters to GWT as Let Googlebot decide impact the performance organically for the main URLs? as there are no duplicate pages. Should these be blocked? | How should UTM parameters be configured in Google Search Console URL parameters tool? | seo;google search console;google search;url parameters | null |
_webmaster.16086 | After Googling our company name to our horror we've found someone on Yelp.co.uk has reviewed our company. On the SERP your eye is immediately drawn to the 2 star review some complete stranger has written, which to be honest is pure slander! The most infuriating thing is the person who reviewed our company has never even been a client/customer.It's a bit like me reviewing a restaurant having never eaten or even been in there!We've sent her a private message on Yelp to remove the review and also sent a complaint to Yelp themselves but have yet to get a reply. We've resisted going mad at the reviewer and also requested that she re-review us having just relaunched our new website (it still riles us that she's not even a client though!).We've had genuine customers/clients review us on Yelp yet this 2 star review remains on Google's SERP. Roughly how long would it take to for our new reviews to over take this review?Does anyone have any suggestions as to how we can push the review off the 1st page of Google's SERP or any creative ways in which we can tackle this issue? | Ideas to tackle unwanted bad press/review on Google's SERP? | seo;google | Yelp came back to us and removed the bad review as it breached the content guidelines. I can't help but think it was the stern words I used in the request!Anyways, the moral of the story I guess is to contact the site the bad review/press is on and get them to directly remove the article in question.The second moral is Google your own company name to stop any bad press as quickly as possible... especially if it's pure slander like this was. |
_unix.235067 | I have a file config.ini:repo_path=ssh://git@localhost:10022/root/dir_path=/home/vagrant/workspace/and a 'script.sh' to export and concatenate from that file as follow:while read -r line; do export $line; done <config.inirepo_name=$1repo_path=$repo_path$repo_name'.git'dir_path=$dir_path/$repo_nameecho $repo_pathecho $dir_pathso when i run the script: ./script.sh sampleoutput:sample.gitlocalhost:10022/root//sampleagrant/workspace/expected output:ssh://git@localhost:10022/root/sample.git/home/vagrant/workspace/sample | concatenate string in shell | bash;shell script | A plausible explanation is that you have an embedded carriage return in your data.sample.gitlocalhost:10022/root/^^^^^^^^^^That is to say the string is the following (using C language string literal notation):ssh://git@localhost:10022/root/\rsample.gitNote the \r denoting a carriage returnWhen you send this to the terminal, the carriage return causes the cursor to move to the beginning of the line, so that sample.git overwrites the ssh://... prefix.To debug this sort of mysterious output problem, you can pipe the output of the command to a binary dump utility like od:echo $strange | od -t c # see characters with backslash notation, or -t x1 for hex |
_codereview.35226 | My question is for validation of my code (any loop holes / bugs) and guidance the best methodology to implement for my requirement.I am developing a Python application that will have many classes. We need to communicate in between each class - pass data. It would be very clumsy if across all classes I create a setter/getter method and refer them across different classes, hence I prefer to pass a container object in between all of them:class One def __init__(self, container):class Two def __init__(self, container):Now obviously I want that this container object should be a Singleton object - only one instance to pass multiple data structures. Below is my code for same [class declaration for Container class]:import abcclass Container(object): __metaclass__ = abc.ABCMeta __data1 = 0 __data2 = 0 @abc.abstractmethod def dummy(): raise NotImplementedError() def __init__(self): self.__data1 = 0 self.__data2 = 1 def SetData(self,value): self.__data1 = value def GetData(self): return self.__data1class Singleton(Container): _instances = {} def __new__(class_, *args, **kwargs): if class_ not in class_._instances: class_._instances[class_] = super(Singleton, class_).__new__(class_, *args, **kwargs) return class_._instances[class_] def dummy(): passNow in my application, I would not be able to create an another separate instance of Container [abstract class] / Singleton class. So I can pass the object of Singleton like as mentioned below:class One: def __init__(self, container) self.value = container.GetData() ................................ container.SetData(9) Two(container)class Two: def __init__(self, container) self.value = container.GetData() ................................ container.SetData(19) ................................class Three: def __init__(self, container) self.container = Singleton() ................................ container.GetData() # will return value 19 only container.SetData(19) ................................if __name__ == __main__: container = Singleton() container.SetData(9) One(container)Please comment on my approach and modifications required if any. This code will be pushed in production box - so I want to double check my implementation. | Creating a singleton container class for intrer-class messaging | python;classes;singleton;container | null |
_codereview.20749 | Here's the situation. I'm writing a simple game and I had two main actors: GameController and GridView.GridView is a UIView subclass displaying a grid with which the user interacts. It defines its custom delegate protocol (GridViewDelegate) for handling callbacks such as gridView:didSelectTile and others.GameController is the game controller (duh!) which instantiate a GridView and set itself as a delegate, therefore implementing the GridViewDelegate protocol.So far so good, then I decided to add HUD components on top of the grid (a score, a timer and other stuff). The most reasonable choice seemed to wrap such HUD components along with the grid into a new UIView subclass called GameBoard.And here comes the design issue: I need the controller to talk to the GridView and I think there's two reasonable options here.Expose a gridView property and do something like[self.gameBoard.gridView doStuff];Forward the invocation made to GameBoard directly to GridView overriding the forwardInvocation: method of GameBoardThe first options looks like the most convenient, but I cannot get myself into liking it, due to the Law of Demeter.So I decided to go for the second approach and do something like// The GameBoard serves a proxy between the GameContoller and the GridView- (void)forwardInvocation:(NSInvocation *)anInvocation { if ([self.gridView respondsToSelector:anInvocation.selector]) { [anInvocation invokeWithTarget:self.gridView]; } else { [super forwardInvocation:anInvocation]; }}// This method is necessary for the above forwardInvocation to work- (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector { NSMethodSignature * signature = [super methodSignatureForSelector:aSelector]; if (!signature) { signature = [self.gridView methodSignatureForSelector:aSelector]; } return signature;}It works as expected, but I'd like to have a second opinion on my design choice.I generally tend to avoid overusing of the dynamic features of Objective-C, but it looked like an elegant way to achieve my result fulfilling the Law of Demeter. | Code review of forward invocation | objective c | I think you trying to overengineer solution a bit. First of all View should not do any stuff at all. View is just a View, sheet of paper. Maximum of view's responsibility is layouting himself. So controller should take care of other view-related stuff. In this case I probably prefer to think about gridView as legitimate subview of GameBoard. I really doubt Demetra suffering when you doing something like [self.view.titleLabel sizeToFit]. So my advice is to use [self.gameBoard.gridView doStuff]; as simplest and straightforward solution. |
_unix.324453 | I have an oracle Linux 6.8 that eht3 has IP but when reload the network service with root permission got these things:Shutting down interface eth3: [ OK ]Shutting down loopback interface: [ OK ]Bringing up loopback interface: [ OK ]awk: cmd. line:1: $1 == alias && $2 == eth0\ { alias = $3; } awk:cmd. line:1: ^ unterminated string Bringing upinterface eth3: Determining if ip address (blublublu) is already in use for device eth3...What for is this awk command? | Is this network reload error? | awk;network interface | null |
_cs.16661 | Given an orthogonal polygon (a polygon whose sides are parallel to the axes), I want to find the smallest set of interior-disjoint squares, whose union equals the polygon.I found several references to slightly different problems, such as:Covering an orthogonal polygon with squares - similar to my problem, but the covering squares are allowed to overlap. This problem has a polynomial solution (Aupperle, Conn, Keil and O'Rourke, 1988; Bar-Yehuda and Ben-Hanoch, 1996).Tiling/decomposing/partitioning an orthogonal polygon to rectangles. This problem has a polynomial solution (Keil, 2000; Eppstein, 2009).Covering an orthogonal polygon with rectangles - this problem is known to be NP-complete (Culberson and Reckhow, 1988).I am looking for an algorithm for minimal tiling with squares. | Tiling an orthogonal polygon with squares | algorithms;computational geometry;tiling | I will try to show this problem is NP-hard, by reduction from $\text{Planar-}3\text{-SAT}$.Reduction from $\text{Planar-}3\text{-SAT}$Some basic GadgetsGadgets are internal configurations of geometry that will allow us to construct gates for use in a circuit, to which we will reduce $\text{Planar-}3\text{-SAT}$.4X3-gadgetThis gadget has two valid minimal-square-partition-states: LeftA 4X3-gadget.Middle and right:Two possible minimal-square-partition-states.5X4-gadgetThis gadget, is exactly like a 4X3-gadget, just with larger dimensions. LeftA 5X4-gadget.Middle and right:Two possible minimal-square-partition-states.endpoint-gadgetAn endpoint-gadget is a 5X4-gadget. It is frequently used as an endpoint/pin of a gate. One of the two states of an endpoint can be valued as true, and the other false. An endpoint marks the two ends, one as $T$ and the other as $F$. The end that is covered by the large square is the value of the endpoint.Left: Wireframe of endpoint-gadget. Center:True-valued endpoint. Right: False-valued endpoint.i-wire gadgetAn i-wire gadget is short for implication wire.Rules:An i-wire gadget consists of a odd-length rectangle of a length of more than $2$ and a width of $2$. An i-wire gadget can have $3$ minimal-square-partition-states, pushed from one side, the other, or neither; an i-wire in this third state shall be called locally unconstrainted.Example:Figure 7: An i-wire gadget of length $7$, and width $2$.Here is how it is used: Figure 8,9, Left: wireframe i-wire across two endpoints. Right: Union.Now, if one endpoint is in the right state, it forces the other endpoint into a pushed-position. Example: Left: Square partition diagram; left switch is down, pushes all the squares down the i-wire and finally, pushes the other switch (endpoint). Right: Square partition diagram; left endpoint is full, pushes all the squares down the i-wire, and forces the endpoint on left to be up. This is essentially a logical implication. Consider down to be true, then we have $A \implies \neg B$. We can also do $A \implies B$ by simply flipping the endpoint on the right.However, this leaves the unconstrainted case:If we combine two i-wires, we can get a two-way implication, essentially a boolean (in)equality: So, two i-wires can carry a full equality relationship, much like a circuit - in fact, it is a circuit. We will use these pairs to construct a usable wire.Each i-wire gadget contributes $\frac{l-1}{2}+2$ partition-squares to the minimal-square-partition, save for the shared-corners with other gadgets.i-wires can be oriented as needed.wireA wire consists a pair of i-wires that are connected to the same gates at each endpoint. The i-wires are colored red and green.The pair must be separated by $3$ spaces (convention).Each gate pin will have a green and red contact; a wire must correctly connect.Invariant rule: one i-wire be pushed in the opposite direction of the other i-wire, each gate assumes this, and makes certain of this (unless otherwise noted).Since each wire contains a two-way implication, it carries the values from gate to gate like a wire in a circuit.Every wire must be connected to a gate at both ends.. Failing this can ruin the assumptions of some gates that I describe, and the invariant rule above; however, gates that have endpoints across the leads are safe - you can connect stray wires to these endpoints without worrying about it ruining the gate.wires must be of odd-length, including the leads to any circuit it connects to; however I will describe an odd-skip-gate below that allows an even-lengthed wire to become odd-lengthed.Pictures:Above: A wire. Left and right: Two possible minimal-square-partition-states of a wire. Note that if the wire is only this length, it will not be able to shift off to the right or left, and will have to break one square into smaller pieces.wires can be oriented as needed.bend-gate: Bending a wire Left: Wire-frame view. Right: Union view.Note the use of the 4X3-gadget. It is used to fix the red lead to odd length.Following are the two possible minimal-square-partition-states of the bend: Left and right:Two possible minimal-square-square-partition-states of a bending wire.The gate can be oriented as needed. Obviously, this gate can be mirrored to work for the other direction.Skewing a wireIt is easy to shift a wire over. Wireframe illustration:named-value-gateA named-value-gate is essentially an endpoint as a gate with one wire contact:odd-skip-gate: Odd skipping a wireSometimes it is inconvenient to only have odd-length wires. For example:As you can see, that little bit of extension is a bit annoying. Here is a corresponding solution, using the 4X3-gate:So, turning this into a gate, we get the odd-skip-gate (in wireframe):The gate can be oriented as needed.twist-gate: Twisting a wireSomtimes you get the red and black i-wires on the wrong sides for use with a gate. In this case, a twist-gate is provided, to twist the red and black i-wires to the opposite sides.Wireframe illustration:Convince yourself it works: Start from $A$, follow the push-arrows, everything else should be forced and consistent.The gate can be oriented as needed.split-gate: Splitting a wireSplitting a wire, wireframe:Convince yourself that it works:Figure:Start from $A$, follow the push-arrows. Everything should be forced and consistent.Figure:Start from $A$, follow the push-arrows. Everything should be forced and consistent.Note: Every wire coming in and out of the splitter absolutely must connect to an endpoint somewhere, in order to maintain the invariant. Alternatively, you can add endpoints to each of the pairs of leads of the splitter.The gate can be oriented as needed.not-gateThe not gate takes a wire and outputs a wire that has the reverse implications. It is basically a twist-gate, except that it relabels the colorings of the wires. The not-gate looks like this:And a view of the two possible states: The gate can be oriented as needed.clause-gateFor the clause-gate, we first introduce the clause-gadget:Left to right: 1 clause-gadget. 2-4: $3$ different minimal-square-partition-states. This is what the gate looks like:We can demonstrate the different states of this gate (explanation underneath all $3$ illustrations):Explanation:Start at the clause-gadget and follow the arrows.Non-arrow-lines mean that it is part of a circuit, but it is not forced into a state by the gate.The state of the clause-gadget forces one of the endpoints to be valued true.As you can see, at least one of the inputs will have to be valued as true. This is exactly what a $3\text{-CNF}$ clause requires.The gate can be oriented as needed.ReductionLet $\Phi(\mathbf x)$ be a $\text{Planar-}3\text{-SAT}$ formula, where$$\Phi\left(\mathbf x\right)={\huge\wedge}_i^n C_i,\\C=\left\{(x_j \vee x_k \vee x_l)\right\}$$A visual aid (original source: Terrain Guarding is NP-Hard (PDF), reproduced in tikz):Then:For each variable $x_i\in\mathbf x$, place two named-variable-gates next to each-other, name one of them $x_i$ and the other $\neg x_i$.Connect the gates to each-other with a not-gate, so that they logically negate each-other's values.Place the variables' gates' polygons at their locations in the planar-embedding.For each clause, place a clause-gate at the clause's location in the planar-embedding.Using the gates described above, connect all the variables to their clauses.Run a minimum-square-paritioning-algorithm on the resulting union of the all of gate's polygons (the entire circuit).If the algorithm returns the sum of all the gate's minimal-square-partition-state sizes (subtracting for shared-corners) then it is satisfiable. If it is not satisfiable, it will force a constrained gadget to split into smaller squares, thus increasing the number of squares required to partition the circuit.Why it worksEach gadget has a minimal-square-partition-state size; that is, a minimal-square-partition of that gadget is a certain size.Some gadgets have several states with this size; each of these states are valid minimal-square-partitions.When gadgets are combined only in the corners, the sum of the minimal-square-partition-states of the gadgets is *still the minimUM-square-partition-state of the union of them; you can see this intuitively: joining at the corner does not give ample space for a square to expand/connect with a square from another gadget.While combining gadgets at the corner does not decrease the total minimum-square-partition size, it does relate and constrain the gadgets with each-other.With the gates shown above, you can constrain the states enough, so that if the logical formula is unsatisfiable, then one or more gadets will have to break into even smaller squares, and increase the minimum-square-partition size.graph sourcessquaretilings1.tex (writelatex)squaretilings2.tex (writelatex)clausegate.tex (writelatex)You can also see larger images by removing the s, m, l, suffixes of the imgur urls. For example, You can see a larger image of this: http://i.stack.imgur.com/6CKlGs.jpg by going to http://i.stack.imgur.com/6CKlG.jpg. Notice the missing s before the .jpg. |
_scicomp.20265 | I'm using scipy.odeint to solve Fisher-Kolmogorov equation:\begin{equation}u_t = u_{xx}+u(1-u)\end{equation}The code can be found here.From Ablowitz and Zeppetella we know that the analytical solution reads:\begin{equation}u(x,t)=\frac{1}{1+e^{{(-\frac{5}{6} t+ \frac{\sqrt{6}x}{6}})^2}}\end{equation}Now, if we compare the analytical solution to the numerical solution obtained with ODE integrator we get the following: Red: Analytical, Blue: OdeIntBy default scipy.odeint uses Dirichlet boundary conditions. I would like to know the following:1) What kind of boundary conditions should I use for odeInt to compare to the analytical solution?2) How should I include these boundary conditions using scipy.odeint? | Scipy OdeInt solver with Neumann boundary conditions | pde;python;boundary conditions;scipy | null |
_unix.47942 | How can I trim a file (well input stream) so that I only get the lines ranging from the first occurrence of pattern foo to the last occurrence of pattern bar?For instance consider the following input :A linelikefoothis foobarsomethingsomething elsefoobarandtherestI expect this output:foothis foobarsomethingsomething elsefoobar | How to get all lines between first and last occurrences of patterns? | text processing;sed | sed -n '/foo/{:a;N;/^\n/s/^\n//;/bar/{p;s/.*//;};ba};'The sed pattern matching /first/,/second/ reads lines one by one. When some line matches to /first/ it remembers it and looks forward for the first match for the /second/ pattern. In the same time it applies all activities specified for that pattern. After that process starts again and again up to the end of file.That's not that we need. We need to look up to the last matching of /second/ pattern. Therefore we build construction that looks just for the first entry /foo/. When found the cycle a starts. We add new line to the match buffer with N and check if it matches to the pattern /bar/. If it does, we just print it and clear the match buffer and janyway jump to the begin of cycle with ba.Also we need to delete newline symbol after buffer clean up with /^\n/s/^\n//. I'm sure there is much better solution, unfortunately it didn't come to my mind.Hope everything is clear. |
_cs.63769 | I'm reading a book at the moment about logic gates and Boolean simplification. There is a part which I can't seem to follow.I can easily work out that $A \vee (\neg A \wedge B) \equiv A \vee B$ using a truth table as it's easy to see. However, I can't seem to turn $A \vee (\neg A \wedge B)$ into $A \vee B$ using steps such as distributive / absorption etc.Can someone talk me through the steps that you would take to simplify this? | Proving that $A \vee (\neg A \wedge B) \equiv A \vee B$ | logic;arithmetic;boolean algebra | Note that$\qquad A \lor (B \land C) \equiv (A \lor B) \land (A \lor C)$;you can multiply out. Add in$\qquad (A \lor \lnot A) \land B \equiv B$and you are done. |
_datascience.6894 | I'm performing a logistic regression in R.I wanted to know if the function predict.glm outputs $p$ (probability of event occurring) or log odds i.e. $log(p/1-p)$? | For logistic regression, Predict.glm() outputs $p$ or $ln(p/1-p)$? | r;logistic regression | It returns the log odds. You can see that with this basic example,# Create a perfect correlated data.data <- data.frame(x = c(1,0,1,0), y = c(T, F, T, F))# Estimate the model.model <- glm(y ~ x, data)# Show predictions.predict(model)## 1 2 3 4 ## 23.56607 -23.56607 23.56607 -23.56607# Compute the inverse of the log odd to come to your prediction. boot::inv.logit(predict(model))## 1 2 3 4 ##1.000000e+00 5.826215e-11 1.000000e+00 5.826215e-11 If logit would return probabilities you could not take the inverse to come to your predicted values. |
_unix.18632 | I am currently calculating percentages in LibreOffice Calc using the function =PART/TOTAL where PART and TOTAL are cell coordinates of a same column.Dragging-down the formula won't do, because the coordinate of the TOTAL cell will change along with the PART's.Ideally, I want to process this quickly, in a way that the coordinates of the PART changes while the TOTAL's would remain the same.How can I do that? Is there a function for this? | How to calculate percentages in LibreOffice Calc? | libreoffice | Modify the formula from, say, =A1/A2 to =A1/$A$2 before copying it, so that the denominator will not change. |
_hardwarecs.1577 | I am going to upgrade my PC over Christmas, and right now I'm trying to pick out a PSU. I would like it to be fully modular, 80+ gold or better efficiency and preferably cheap. I found the Antec HCP750 Platinum and it looks awesome. It's very cheap (as far as platinum rated fully modular PSUs go), and has plenty of wattage. However, now I'm wondering if it has too many watts. My maximum estimated wattage is 457, and the Antec PSU goes up to 750. That seems like a good thing in case I ever wanted to, say add additional video cards or more powerful video cards. Are there any downsides that I'm unaware of to having significantly more power in your PSU than your pc will actually draw? (Electricity bill, longevity of parts... etc.) Should I go for something more reasonable, like a 500-600W? | How far above my power draw should a PSU be? | gaming;pc;power supply | For a 80-Plus Platinum power supply, efficiencies are between around 5% of one another between the 20 to 100% range of load(88-92, give or take a percent). It tops at around 70% load. Having more than required is certainly not a bad thing. PSU's like the HCP are rated to deliver their full wattage at fairly high temperatures, and 300W is enough for any card.So go ahead, you're good to make the purchase. Hardware reviewers use oversized power supplies all the time, and nothing happens to them. |
_webapps.107246 | Is it possible to automatically add an event reference to file names, for files uploaded using Cognito Forms? | Rename Cognito Form uploaded files | cognito forms | null |
_softwareengineering.203867 | I want to create my own website that would allow me to acess a database in the server and do inserts and lookups in a user friendly way. I am a seasoned user of linux and C/C++, and also have experience with Python and sqlite3, but i don't have any experience in Web development, so i have no idea where to start.I have researched online and the best i came up with was an Apache/Nginx server together with an fcig or wscgi and Django, so that i would have database and python integration through a Django App.Can someone tell me if this is the way to go or if there is some easier (or better) way to accomplish what i want? | Python/Database Website development | web development;python;database;server | Since you know Python already I see no reason not to go for Django. It should be fairly easy to set up and try out a quick project to see if you like it. Like with everything there's a learning curve, but from what I've seen the tutorials and documentation to get you up and running is rather good. |
_cs.62852 | Thanks in advance for the help.I have the following problem which, for lack of a better description, I'm referring to as the problem I've listed in the title.Specifically I have a knapsack problem where I must exactly fill the knapsack. Additionally, the order in which I place the elements into the knapsack affects the strength of the solution (but not the volume of the individual elements). The function that is used to evaluate the strength, or goodness, of the packing is non linear and very complex. Because of this, I have a model that I will use to repeatedly simulate my evaluation function to get an idea of the strength of each solution rather than directly evaluating my evaluation function (sort of like a surrogate function).For example, suppose I have a knapsack of size ten. The following would be possible solutions assuming integers are the elements that I can place into the knapsack (for all intents in purposes my actual problem can be visualized in this manner): [5,5], [3,3,4], [4,3,3], etc.What I'm interested in is two-fold. First, does this problem reduce to any well studied problems from which I could read up more on how they are solved? I'm currently thinking about using some kind of heuristic search to solve this problem, such as a Genetic Algorithm (I don't have to have the optimal solution, though I would like the best that I can get). Second and somewhat related to the first, what work if any has been done on problems that fit the description that I have given above? The knapsack problem is a very well studied problem and I would find it hard to believe if there hasn't been any work done on problems that fit my current one. Unfortunately though, while I've found work somewhat related to my problem, I haven't been able to find anything that directly reduces to my problem. | Solving an ordered knapsack problem exactly with a non linear (blackbox) evaluation function | terminology;optimization;reference request;heuristics;knapsack problems | null |
_reverseengineering.8822 | I can't get IDA to connect with a debugging server on OS X. This is what keeps happening:$ ll ~/.bin/mac_server*-rwxr-sr-x 1 Ron procmod 657K May 5 22:29 mac_server*-rwxr-sr-x 1 Ron procmod 666K May 5 22:29 mac_serverx64*$ mac_serverx64IDA Mac OS X 64-bit remote debug server(MT) v1.17. Hex-Rays (c) 2004-2014Listening on port #23946...=========================================================[1] Accepting connection from 172.16.91.129...Current group=procmodCurrent group=procmodCurrent group=procmodCurrent group=procmodCurrent group=procmodCurrent group=procmodCurrent group=procmodCurrent group=procmodCurrent group=procmodCurrent group=procmod[1] Closing connection from 172.16.91.129...I'm running IDA Pro 6.6 on Windows and mac_server on OS X Yosemite 10.3. Did I miss something crucial? | Connecting to mac_server with IDA Pro on Windows | ida;osx | null |
_softwareengineering.202496 | I am developing an iPhone app, which I am integrating with PayPal.I did it successfully using PayPal library. I am testing it on sandbox mode. When I transfer money from one account to the other account, it displays a message send to server for verification.Is there a real need to store this PayPal transaction id and other details on our server? | PayPal proof of payment - is there a need to store it at our server? | ios;iphone;objective c;payment | null |
_unix.39544 | I can type:dirname ~/home/blah/file.zipfor instance, and this works fine alone, but when I use this syntax as the parameter for some command it always reads 'dirname' as the desired directory. i.e.:cd dirname ~/home/blah/file.zipbash: cd: dirname: No such file or directoryBasically, how do I get 'dirname file' to be read as one entity? | Say I have a file's path, how do I reference that file's directory from the command line? | bash;directory | cd $(dirname ~/home/blah/file.zip)$( is a form of command substitution. The BashGuide Wiki has some good information about this process. |
_codereview.1496 | I have the following code for reading HTK feature files. The code below is working completely correct (verified it with unit tests and the output of the original HTK toolkit).from HTK_model import FLOAT_TYPEfrom numpy import arrayfrom struct import unpackdef feature_reader(file_name): with open(file_name, 'rb') as in_f: #There are four standard headers. Sample period is not used num_samples = unpack('>i', in_f.read(4))[0] sample_period = unpack('>i', in_f.read(4))[0] sample_size = unpack('>h', in_f.read(2))[0] param_kind = unpack('>h', in_f.read(2))[0] compressed = bool(param_kind & 02000) #If compression is used, two matrices are defined. In that case the values are shorts, and the real values are: # (x+B)/A A = B = 0 if compressed: A = array([unpack('>f',in_f.read(4))[0] for _ in xrange(sample_size/2)], dtype=FLOAT_TYPE) B = array([unpack('>f',in_f.read(4))[0] for _ in xrange(sample_size/2)], dtype=FLOAT_TYPE) #The first 4 samples were the matrices num_samples -= 4 for _ in xrange(0,num_samples): if compressed: yield ((array( unpack('>' + ('h' * (sample_size//2)),in_f.read(sample_size)) ,dtype=FLOAT_TYPE) + B) / A) else: yield (array( unpack('>' + ('f' * (sample_size//4)),in_f.read(sample_size)), dtype=FLOAT_TYPE))How can I speed up this code, are there things I should improve in the code? | Reading a binary file containing periodic samples | python;performance;file;numpy;serialization | data = in_f.read(12) num_samples, sample_period, sample_size, param_kind = unpack('>iihh', data) A = B = 0 if compressed: A = array('f') A.fromfile(in_f, sample_size/2) B = array('f') B.fromfile(in_f, sample_size/2) #The first 4 samples were the matrices num_samples -= 4And so on |
_datascience.6925 | How did the phrase big data come about? What were some of the new challenges that arose? How does big data differ from a small amount of data and how do we distinguish the two? | What are some challenges with big data? | bigdata | null |
_unix.385959 | I've got a Lenovo Thinkpad P71 with the NVidia Quadro P3000, that has the Discrete Graphics setting on the BIOS, and I'm using the proprietary drivers on Debian 9.For some reason, the brightness keys do not work (Fn+F5/Fn+F6)I've tried adding Option RegistryDwords EnableBrightnessControl=1 to my xorg.conf, adding pcie_aspm=force, acpi_osi=, acpi_osi=Linux, and acpi_backlight=vendor (individually) to my kernel parameters, doing update-grub, and rebooting, but nothing seems to work.Currently, my kernel parameters are quiet splash acpi_osi= and I have EnableBrightnessControl=1 on my xorg.conf, and the brightness keys appear to work, but won't go past what appears to be 10% on the pop-up, and the actual brightness doesn't actually adjust.In /sys/class/backlight/thinkpad_screen/ I have brightness, bl_power, max_brightness, and actual_brightness, but adjusting these does not work, and when I try using the Fn+F5/F6 keys, the values are reset to 0. (except for max_brightness, which stays at 15)Additionally, xbacklight only works when I don't have acpi_osi= in my kernel parameters. | Brightness key issue on Lenovo P71 | acpi;thinkpad;brightness;backlight | null |
_unix.73955 | When I write ls -la the output is :tusharmakkar08-Satellite-C660 tusharmakkar08 # ls -latotal 88drwxr-x---+ 10 root root 4096 Apr 18 19:43 .drwxr-xr-x 4 root root 4096 Mar 18 17:35 ..drwxr-xr-x 4 root root 32768 Jan 1 1970 CFB1-5DDAdrwxrwxrwx 2 root root 4096 Feb 23 00:09 FA38015738011473drwxrwxrwx 2 root root 4096 Apr 17 14:00 Localdrwxrwxrwx 2 root root 4096 Mar 19 05:04 Local\040Disk1drwxrwxrwx 2 root root 4096 Apr 18 19:43 Local\134x20Disk1drwxrwxrwx 2 root root 4096 Feb 23 00:09 Local Diskdrwxrwxrwx 1 root root 24576 Apr 19 15:15 Local\x20Disk1drwxrwxrwx 2 root root 4096 Feb 23 00:08 PENDRIVENow I want to change the permissions of CFB1-5DDA .. but i am unable to do so .When I writechmod 777 CFB1-5DDAstill the permissions remain unchanged.The output of sudo blkid -c /dev/nullis tusharmakkar08-Satellite-C660 tusharmakkar08 # sudo blkid -c /dev/null/dev/sda2: UUID=FA38015738011473 TYPE=ntfs /dev/sda3: LABEL=Local Disk UUID=01CD72098BB21B70 TYPE=ntfs /dev/sda4: UUID=2ca94bc3-eb3e-41cf-ad06-293cf89791f2 TYPE=ext4 /dev/sda5: UUID=CFB1-5DDA TYPE=vfatThe output of cat /etc/fstab istusharmakkar08-Satellite-C660 tusharmakkar08 # cat /etc/fstab# /etc/fstab: static file system information.## #Entry for /dev/sda4 :UUID=2ca94bc3-eb3e-41cf-ad06-293cf89791f2 / ext4 defaults 01#Entry for /dev/sda2 :UUID=FA38015738011473 /media/sda2 ntfs-3g defaults,locale=en_IN 0 0#Entry for /dev/sda5 :UUID=CFB1-5DDA /media/tusharmakkar08/CFB1-5DDA vfat defaults 0 0/dev/sda3 /media/tusharmakkar08/Local\134x20Disk1 fuseblk defaults,nosuid,nodev,allow_other,blksize=4096 0 0/dev/sda3 /media/tusharmakkar08/Local\x20Disk1 ntfs-3g defaults,nosuid,nodev,locale=en_IN 0 0#/dev/sda3 /media/tusharmakkar08/Local\134x20Disk1 ntfs defaults,nls=utf8,umask=0222,nosuid,nodev 0 0And the output of mountistusharmakkar08-Satellite-C660 tusharmakkar08 # mount/dev/sda4 on / type ext4 (rw)proc on /proc type proc (rw,noexec,nosuid,nodev)sysfs on /sys type sysfs (rw,noexec,nosuid,nodev)none on /sys/fs/fuse/connections type fusectl (rw)none on /sys/kernel/debug type debugfs (rw)none on /sys/kernel/security type securityfs (rw)udev on /dev type devtmpfs (rw,mode=0755)devpts on /dev/pts type devpts (rw,noexec,nosuid,gid=5,mode=0620)tmpfs on /run type tmpfs (rw,noexec,nosuid,size=10%,mode=0755)none on /run/lock type tmpfs (rw,noexec,nosuid,nodev,size=5242880)none on /run/shm type tmpfs (rw,nosuid,nodev)none on /run/user type tmpfs (rw,noexec,nosuid,nodev,size=104857600,mode=0755)cgroup on /sys/fs/cgroup type tmpfs (rw,relatime,mode=755)cgroup on /sys/fs/cgroup/cpuset type cgroup (rw,relatime,cpuset)cgroup on /sys/fs/cgroup/cpu type cgroup (rw,relatime,cpu)cgroup on /sys/fs/cgroup/cpuacct type cgroup (rw,relatime,cpuacct)cgroup on /sys/fs/cgroup/memory type cgroup (rw,relatime,memory)cgroup on /sys/fs/cgroup/devices type cgroup (rw,relatime,devices)cgroup on /sys/fs/cgroup/freezer type cgroup (rw,relatime,freezer)cgroup on /sys/fs/cgroup/blkio type cgroup (rw,relatime,blkio)cgroup on /sys/fs/cgroup/perf_event type cgroup (rw,relatime,perf_event)/dev/sda2 on /media/sda2 type fuseblk (rw,nosuid,nodev,allow_other,blksize=4096)/dev/sda5 on /media/tusharmakkar08/CFB1-5DDA type vfat (rw)/dev/sda3 on /media/tusharmakkar08/Local\x20Disk1 type fuseblk (rw,nosuid,nodev,allow_other,blksize=4096)binfmt_misc on /proc/sys/fs/binfmt_misc type binfmt_misc (rw,noexec,nosuid,nodev)gvfsd-fuse on /run/user/tusharmakkar08/gvfs type fuse.gvfsd-fuse (rw,nosuid,nodev,user=tusharmakkar08) | Unable to change permissions of file system root | permissions;mount;chmod;vfat | chmod 777 CFB1-5DDA fails because CFB1-5DDA is a mount point and the mounted file system is vfat. So you are trying to write meta data to a file system which the file system does not support (i.e. cannot store). Simple as that.strace chmod 777 CFB1-5DDA shows you the kernel error.In order to change the access rights you have to change the mount (-o remount or umount; mount). |
_reverseengineering.16046 | I am currently learning ARM assembly by trying to reverse a broken printer. I retrieved the firmware from the on board NAND flash and I am now trying to make some sense of it.However, I get stuck at the very beginning: the interrupt table. From documentation I read on the web, the interrupt table is a table that contains instructions (most often LDR PC instructions) that load a direct memory address into the PC. The interrupt table is a sequence of these instructions all directly next to each other (this might not be the most technical correct explanation, but that is how I understand it, please correct me if I am wrong). In the underneath table these instructions would be: e5 9f f0 18 which I believe is a ldr pc, [pc, #24] instruction.In the firmware I retrieved, after every two vectors, there is a byte with value 89. I do not know why it is there and what it does. I couldn't find it anything on the web that shows something similar (or I am looking for the wrong thing). What would be the function of this byte?From how I understand it, the address 0x8e0 will be loaded into PC and the CPU will run from there, however, this means ignoring the four 89 bytes. If the bytes should be taking into account, than the CPU would jump to 9f f0 18 89, but this is outside of the binary.I believe the CPU is big endian and probably an Armv7, but it is an unknown Marvel chip, so I am not 100% sure.This is the hexdump of the interrupt table:00000000 e5 9f f0 18 e5 9f f0 18 89 e5 9f f0 18 e5 9f f0 |................|00000010 18 89 e5 9f f0 18 e5 9f f0 18 89 e5 9f f0 18 e5 |................|00000020 9f f0 18 89 00 00 08 e0 00 00 00 04 ac 00 00 00 |................|00000030 08 00 00 00 0c db 00 00 00 10 00 00 00 14 db 00 |................|Why are the four 89 bytes there and is my assumption that the CPU will jump to 0x8e0 correct? | Strange bytes in interrupt table | firmware;arm | null |
_unix.79849 | From (Solaris 11.1 with current patches, m4000 128GB) syslog:Jun 17 10:06:14 sun-m4k-03 sendmail[4993]: [ID 702911 mail.warning] gethostbyaddr(10.128.4.50) failed: 1The ip is valid from the commandline:ping 10.128.4.5010.128.4.50 is alivenslookup appears to reverse the octets when doing a lookup: nslookup 10.128.4.50Server: 10.128.8.18Address: 10.128.8.18#53** server can't find 50.4.128.10.in-addr.arpa.: NXDOMAINTried a search on the internet - no luck | Solaris 11 nslookup reverses ip | dns | This is correct. Reverse DNS lookups are performed by querying the PTR record for the IP address in the .in-addr.arpa domain. DNS names have the least significant/least broad component first, so octets of the IP address, which are written with the most significant/most broad component first, are put in the reverse order so that each class of network can have a DNS zones.If you want to support reverse DNS lookups on private IP addresses, you will have to configure a zone for 10.in-addr.arpa. to hold the PTR record for 50.4.128.10.in-addr.arpa.. |
_unix.231391 | Yeah this is counterclock-wise from anything I've found around. In before anything: I'm running Arch Linux x64, Cinnamon 2.6.13, 4.1.6-1 kernel, no crypt hooks.I've just made a test filesystem using dm-crypt/cryptsetup and it's all good. I didn't want to mount it on startup (because, well, it's supposed to require a password and being requested), however Cinnamon is doing this since I restarted it.This is my crypttab and fstab. No inclusion. I did nothing about it.root@darksol ~]# cat /etc/crypttab # crypttab: mappings for encrypted partitions## Each mapped device will be created in /dev/mapper, so your /etc/fstab# should use the /dev/mapper/<name> paths for encrypted devices.## The Arch specific syntax has been deprecated, see crypttab(5) for the# new supported syntax.## NOTE: Do not list your root (/) partition here, it must be set up# beforehand by the initramfs (/etc/mkinitcpio.conf).# <name> <device> <password> <options># home UUID=b8ad5c18-f445-495d-9095-c9ec4f9d2f37 /etc/mypassword1# data1 /dev/sda3 /etc/mypassword2# data2 /dev/sda5 /etc/cryptfs.key# swap /dev/sdx4 /dev/urandom swap,cipher=aes-cbc-essiv:sha256,size=256# vol /dev/sdb7 none[root@darksol ~]# cat /etc/fstab # UUID=dbc726d2-05b9-416f-806d-30d464196a1c/dev/mapper/linuxvg-arch_root_lv / ext4 rw,relatime,data=ordered 0 1# UUID=a63436fe-fa6b-480b-a94a-883c4b2a59e8/dev/mapper/linuxvg-arch_usr_lv /usr ext4 rw,relatime,data=ordered 0 2# UUID=d19aa437-d73f-4d61-a8f2-66126768c36a/dev/mapper/linuxvg-opt_lv /opt ext4 rw,relatime,data=ordered 0 2# UUID=4bb50d46-c92b-4298-8aea-169c11fa3566/dev/mapper/linuxvg-home_lv /home ext4 rw,relatime,data=ordered 0 2# UUID=bb02e9a7-4da3-41ff-acbe-e92b5d8f177a/dev/sda2 none swap defaults 0 0And so this is a peek at ~/.cinnamon (for my user of course) and glass.log.last [root@darksol .cinnamon]# cat glass.log.last info t=2015-09-22T16:36:08.840Z Cinnamon.AppSystem.get_default() started in 23 ms info t=2015-09-22T16:36:16.790Z loading user theme: /home/meistache/.themes/Manjaro Maia Plasma 5/cinnamon/cinnamon.css info t=2015-09-22T16:36:16.822Z added icon directory: /home/meistache/.themes/Manjaro Maia Plasma 5/cinnamon info t=2015-09-22T16:36:16.922Z PlacesManager: Updating devices info t=2015-09-22T16:36:17.000Z loaded at Tue Sep 22 2015 13:36:17 GMT-0300 (BRT) info t=2015-09-22T16:36:17.523Z Loaded applet [email protected] in 522 ms info t=2015-09-22T16:36:17.529Z Role locked: windowlist info t=2015-09-22T16:36:17.529Z Loaded applet [email protected] in 6 ms info t=2015-09-22T16:36:42.544Z Loaded applet [email protected] in 25013 ms info t=2015-09-22T16:36:42.549Z Loaded applet [email protected] in 5 ms info t=2015-09-22T16:36:42.555Z Loaded applet [email protected] in 6 ms [root@darksol .cinnamon]# pwd/home/meistache/.cinnamon [root@darksol .cinnamon]# It looks like it's something coded on Cinnamon engine for the PlacesManager method in which I may never ever be able to manage as user/superuser. I do need to report this as a feature request to Cinnamon devs but I'm wondering if anyone had this experience and got some workaround? Thanks in advance! | How to NOT mount dm-crypt device on Cinnamon startup | arch linux;cinnamon;dm crypt | null |
_scicomp.696 | I'm looking to use the finite element method with B-splines as my function basis. Which C/C++ libraries have good B-spline support?Specifically, I'm looking for an implementation of a stable algorithm, even if it's slow. I plan to precompute a lot of the inner products I need and store them in a file somewhere if the b-spline calculation gets slow enough to be bothersome. | Which libraries have good implementations of Basis splines? | finite element;libraries;basis set;c;c++ | null |
_unix.325028 | Is there any information on pairing and connecting the new XBox One Wireless controller released with the S?The controller is seenI can pair the controllerI add it to the trust listwhen I attempt a connect to the controller, I get a bluez error.there's little information other than Failed to ConnectAlso, I don't enough rep to add a /xpad tag, so if anyone with more can help me out with that, that's be appreciated. | XBox One Bluetooth Controller Connect | raspberry pi;bluez | null |
_cogsci.4846 | From Jonah Lehrer's book How We Decide, he mentions the experiments with rats and Yale undergraduates.I found the paper that (presumably) matches the experiment of rats.Brunswik, E. (1939). Probability as a determiner of rat behavior. Journal of Experimental Psychology, 25, 175197. [Reprinted in Hammond, K. R., & Stewart, T. R., 2001]But the results seem to be somewhat different from what he described.Could anyone tell me where I can find the paper about Yale graduates performing the maze task?Here's the excerpt from the book,Look, for example, at this elegant little experiment: A rat was put in a T-shaped maze with a few morsels of food placed on either the far right or the far left side of the enclosure. The placement of the food was random, but the dice were rigged: over the long run, the food was placed on the left side 60 percent of the time. How did the rat respond? It quickly realized that the left side was more rewarding. As a result, it always went to the left of the maze, which resulted in a 60 percent success rate. The rat didn't strive for perfection. It didn't search for a unified theory of the T-shaped maze. It just accepted the inherent uncertainty of the reward and learned to settle for the option that usually gave the best outcome. The experiment was repeated with Yale undergraduates. Unlike the rat, the students, with their elaborate networks of dopamine neurons, stubbornly searched for the elusive pattern that determined the placement of the reward. They made predictions and then tried to learn from their prediction errors. The problem was that there was nothing to predict; the apparent randomness was real. Because the students refused to settle for a 60 percent success rate, they ended up with a 52 percent success rate. Although most of the students were convinced that they were making progress toward identifying the underlying algorithm, they were, in actuality, outsmarted by a rat. | Solving T-shaped maze (probability learning): differences between rats and humans | reference request;learning;performance | I was unable to find this in a scientific paper, and it is not clear from the sources I did locate that this work was ever actually published. However, I found other sources that reference this work and several similar studies comparing humans to rats. The study you mention is also referenced briefly in Tetlock's (2005) book on political judgment; a discussion of Tetlock's interpretation of the results can be seen on University of Pennsylvania's Language Log (2005). That blog post also indicates the experiments are discussed to some extent in a textbook by Gallistel (1993); finding that book may provide more information. A paper by Spragg (1934) describes exploring anticipatory responses in both rats and human (student) subjects. Overall and Brown (1959) examined decision making behavior in rats and humans (students) using a maze task. Gallistel, Charles R. (1993). The organization of learning (Learning,development, and conceptual change). A Bradford Book: 662 pages.ISBN-13: 978-0262570985Language Log. (December 11,2005). Rats beat Yalies? Doing better bygetting less information? Retrieved fromhttp://itre.cis.upenn.edu/~myl/languagelog/archives/002700.htmlOverall, J. E., & Brown, W. L. (1959). A comparison of thedecision-behavior of rats and of human subjects. The American Journalof Psychology, 72(2) 258-261.Spragg, S. S. (1934). Anticipatory responses in the maze. Journal ofComparative Psychology, 18(1), 51-73.Tetlock, P. (2005). Expert political judgment: How good is it? Howcan we know?. Princeton University Press. ISBN-13: 978-0691128719 |
_unix.36819 | I'm looking for a simple way to utilize regex in a UNIX shell script where not every system will have perl extensions built into grep. What is really helpful about perl regex here is back/forward references which I haven't found a way to use effectively in sed. I've quickly come up with the following 1 liner:tail --bytes=+K something.log| perl -e 'while (my $line = <STDIN>){if ($line =~ /$ARGV[0]/){print $line};}' 'my regex'Q1. Is this a safe way to do things for perl?Q2. Should I just resort to writing the entire script in perl instead? | Is it a good idea to supplement shell script with perl purely for use of regex? | shell script;grep;sed;aix;perl | I don't understand why your perl snippet is written this way. You could write the regexp directly inside the script:perl -e 'while (my $line = <STDIN>) {if ($line =~ /my regex/) {print $line}}'which allows you to take advantage of the -n option (as a bonus, you get proper error reporting in case there's an input error). Further using perl idioms:perl -ne 'print if /my regex/'Sed has backreferences, but perl's extended regexes are more powerful, there are things you can't do with sed (sed doesn't even have complete regexes: alternation \| is not a standard feature, though many implementations have it).Most of what you can do with traditional tools, you can do easily in perl. For example, if you want to skip the first K-1 bytes, you can writeperl -ne 'BEGIN {read ARGV, , 42-1}; 'If you want portability, a lot of text processing tasks can be done in awk, but awk doesn't have backreferences at all, so extracting text from a string can be clumsy. |
_webmaster.105830 | Running my site through Niel Patel's SEO Tester gives me multiple errors on <h4> elements being too short.Thing is, the elements are too short (length = 0) because those headers are on a scrolling display banner, and will each only display for four seconds at a time.Is there another way I should mark these headers? Should I just ignore these warnings | Penalties for missing Header tags | seo;headers | Strict rules about what should be in heading tags is an SEO strategy from five years ago. Even then empty <h4> tags wouldn't have caused any SEO problems. Google has long said that it doesn't penalize for poor HTML code, nor does it reward validating code.These days Google is rendering pages to see the content. I've seen evidence that it doesn't even matter if you use heading tags. Styling a <div> or <span> with large bold text at the top of the page is just as good as using an <h1> for Google. |
_codereview.120269 | Trying to print the closest sibling in a BST. How can I improve on this algorithm in terms of space/time efficiency? Please point out any potential bugs too! I'd appreciate that.import java.util.ArrayList; import java.util.List; public class ClosestSibling { public static void printClosestSibling(Node node, List<Node> levelNodes) { if (node == null) return; levelNodes.add(node); while (!levelNodes.isEmpty() || !(levelNodes.size()==0)) { printSiblings(levelNodes); levelNodes=replaceWithChildNodes(levelNodes); } } public static List<Node> replaceWithChildNodes(List<Node> levelNodes) { List<Node> newLevelNodes = new ArrayList<Node>(); for (Node node : levelNodes) { if (node.left != null) { newLevelNodes.add(node.left); } if (node.right != null) { newLevelNodes.add(node.right); } } return newLevelNodes; } public static void printSiblings(List<Node> levelnodes) { for (int i = 0; i < levelnodes.size() - 1; i++) { System.out.println(levelnodes.get(i).data + : + levelnodes.get(i + 1).data); } System.out.println(levelnodes.get(levelnodes.size()-1).data + : + null); } public static void main(String[] args) { BinarySearchTree bst = new BinarySearchTree(); bst.root = bst.addNode(10, bst.root); bst.addNode(20, bst.root); bst.addNode(5, bst.root); bst.addNode(2, bst.root); bst.addNode(40, bst.root); bst.addNode(15, bst.root); bst.addNode(8, bst.root); System.out.println(); bst.printTree(bst.root); System.out.println(); printClosestSibling(bst.root, new ArrayList<Node>()); } } | Finding Closest Sibling in a BST efficiently | java;interview questions | while (!levelNodes.isEmpty() || !(levelNodes.size()==0)) {This is duplicate code; isEmpty checks for size() == 0.System.out.println(levelnodes.get(levelnodes.size()-1).data + : + null);Here, in printSiblings, you can get IndexOutOfBoundsException if the list is empty.I also don't understand why printClosestSibling takes a List<Node> argument. Either you want to take 1 node to print the closestSibling of, in which case you should remove the argument and accept a single node, or you want to take a list of nodes, in which case I'd recommend overloading:public static void printClosestSibling(Node... nodes){ printClosestSibling(Arrays.asList(nodes));}public static void printClosestSibling(List<Node> nodes){ ...}Keep in mind that you need to also deal with the fact that levelNodes could contain null. You would get NullPointerException right now. Either explain via the documentation, or fail-fast and check the list of nodes for null before running your entire algorithm. |
_softwareengineering.77479 | I just started a new job a couple months ago at a small company where I am currently leading all development efforts present and future. I personally have years of experience in software design and development from mostly Java but also a .NET perspective. I picked up .NET later in my career with great ease and required literally no training to hit the ground running, and on top of that it helped me to truly grasp and appreciate the universality of many best practices and common themes by seeing two different perspectives to solving the same problem.My boss has a startup company on the side, and without divulging too much information, he had a need of a moderately sophisticated web application that integrates into Google Maps to build routes.He contracted out the web application to which they overpromised, majorly underdelivered, and ran over the deadline, he is currently in a fight to try and recover at least some of the money he invested. He has the source code for the site as it is right now but has a laundry list of things he would like fixed and added before he goes live with it.He asked me if I would like to do this on the side for some extra cash but the problem is that the site was written in Python using Django, which I have no experience in whatsoever. I told him that I am really not the best person for this because I know virtually nothing about Python or Django and would have to learn it from scratch. I feel it wouldn't be fair for me to bill him hourly for my time if I am using that time learning a language and platform.Based on the summary of my experience level how difficult or how much time would you guess it would take for me to pick this up? If you think its a waste of time could anybody recommend a suggestion for where to find experienced Python web developers? Money is a concern for him right now so he doesn't have the biggest budget anymore. | How difficult is Python and Django to pick up for a Java/.NET web developer? | web development;python;django | Python is about as easy to learn as a language could be, which is one of the main selling points of the language. As someone that is very experienced in OO languages, you are in a great position to start. The only fundamental differences between Python and Java/C# areDuck-typing / lack of type safety.First class functions.I understand why you feel that you are not the best man for the job, and you may not make as much progress in your first week as others. On the other hand, your boss trusts you, and he's just been burned by some untrustworthy folks that knew Python better than you.If you are worried about abusing your bosses trust, offer to give him N hours pro bono. (You decide what N is.) At the end of that time you can decide if you are worth the hourly rate. In the worst case, you will have a much better sense of Python/Django at the end of that time. |
_cogsci.4141 | It seems to me that the structure of the conscious mind has some strong similarities to the way our visual field functions. The visual field has a strong and detailedfocus at the center, and this is what generally commands our attention,while at the same time the visual resolution decreases outward from thatcenter and its content occupies less of our attention, to the point thatour peripheral vision will alert us to movements but has little to dowith what we are recognizing consciously.This is similar to the way we think. We have a central focus,which is the conscious thought, but that object of thought has manyassociations or links to other thought objects, and they form a ringaround the focus, just out of view (ie. in the immediate unconsciouszone). Those primary associations also have their own associationsthat form a secondary ring, deeper into the unconscious, with furtherrings extending outward representing decreasing levels of actionpotential.It makes sense to me that the conscious mind would be patterned on thefunctional model of the visual field which is much older and morefundamental.Thus, my question: Does the structure of consciousness mimic that of the visual process? | Does the structure of consciousness mimic that of the visual process? | cognitive psychology;vision;consciousness | null |
_unix.277064 | How to make a script, which will write a string signal caught after sending 'interrupt signal' (after pressing ^C on the console, where the script was executed). On top of that after pressing third time CTRL-C it will ask user, if it should end (yes/no). If answer is no it will end. | Script which reacts to interrupt signal | scripting | null |
_softwareengineering.241255 | Let's say I have a system. In this system I have a number of operations I can do, but all of these operations have to happen as a batch at a certain time, while calls to activate and deactivate these operations can come in at any time. No matter how many times the doOperation1() method/function is called the operation is done only once in the batch. To implement this, I could use flags like doOperation1 and doOperation2 but this seems like it would become difficult to maintain. Is there a design pattern, or something similar, that addresses this situation? | Flags with deferred use | design;design patterns | You may want to look at the Visitor Pattern. It allows you to decouple operations from the objects they work on. If you extend this pattern, to place those operations into a queue, and then process the queue as a batch, this may work. |
_webapps.74517 | In Microsoft Excel I frequently use the keyboard shortcut Ctrl+' (apostrophe) to copy the value from the cell above the current one. The same keystrokes in Google Sheets instead toggles the display of formula and I cannot find an equivalent shortcut to copy the value from the cell above. Any ideas please? | Equivalent of Ctrl+Apostrophe in Google Sheets | google spreadsheets | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.