id
stringlengths 5
27
| question
stringlengths 19
69.9k
| title
stringlengths 1
150
| tags
stringlengths 1
118
| accepted_answer
stringlengths 4
29.9k
⌀ |
---|---|---|---|---|
_cstheory.11007 | Let $G$ be a graph embedded on an orientable compact surface of genus $g$ so that the embedding is cellular. Consider the dual of the graph $G^*$. Let $C_1$ and $C_2$ be disjoint cycles in $G^*$ that are homotopic to each other and let $E_1$ and $E_2$ be their corresponding edge sets in $G$ respectively. Is $G \setminus (E_1 \cup E_2)$ a disconnected graph? | Does a pair of disjoint homotopic cycles in the dual separate the graph? | graph theory;co.combinatorics;topological graph theory | Yes. Let me write $\Sigma$ for the surface on which $G$ and $G^*$ are embedded.Because the cycles $C_1$ and $C_2$ are homotopic, they are also in the same $\mathbb{Z}_2$-homology class. So by definition, the symmetric difference $C_1\oplus C_2$ is the boundary of the union of some subset of faces of $G^*$; call this union of faces $U$. (In fact, either $U$ or its complement $\Sigma\setminus U$ must be an annulus, but this isn't important.)Because $C_1$ and $C_2$ are disjoint, the symmetric difference $C_1\oplus C_2$ is equal to the union $C_1\cup C_2$. In particular, we have $C_1\oplus C_2\ne \varnothing$, which implies that both $U$ and its complement $\Sigma\setminus U$ are non-empty. In other words, the subsurface $\Sigma \setminus (C_1\cup C_2)$ is disconnected.Any path in $G$ can be viewed as a path in $\Sigma$ that avoids the vertices of $G^*$, and vice versa (up to homotopy). Thus, the (graph) components of $G\setminus (E_1\cup E_2)$ correspond bijectively to the (surface) components of $\Sigma \setminus (C_1\cup C_2)$. We conclude that $G\setminus (E_1\cup E_2)$ is disconnected.The assumption that $\Sigma$ is orientable is never used. |
_unix.175089 | While trying to know where is NMon job configured to run; I do find that it's NOT listed on Crontab (using crontab -l).BUT - the job is currently running as expected, which is weird.See the following output for psserver# ps -ef | grep nmonroot 67043538 1 0 00:01:32 - 0:00 /usr/bin/topas_nmon -x -F /usr/local/log/server.nmon -tA -s 180 -c 480 -youtput_dir=/usr/local/log/server.nmon -ystart_time=00:01:31,Dec20,2014So? where it's configured to be executed; there must be another place rather than crontab.My server is running AIX 6.1- Thanks! :) | Where is NMon cron job for AIX? | cron;performance;aix | null |
_unix.341730 | When I write programs for my own FPGA, I must select UART to emulate a terminal and for my FPGA design but I don't know exactly what that means. I believe that UART is a basic serial transmission protocol, isn't it? And is that the protocol between the program and the terminal and therefore I must choose UART from my programming environment? | What is the relation between UART and the tty? | terminal;tty;protocols;uart | A UART (Universal Asynchronous Receiver Transmitter) is not a protocol, it's a piece of hardware capable of receiving and transmitting data over a serial interface. I presume you are selecting some design block for your FPGA design implementing an UART. |
_softwareengineering.187556 | There is an issue which appears while running the application. It is not an Exception, but the desired UI change is not been implemented.While debugging to find the code which should be changed to fix this problem, the UI changes can be seen correctly, To be specific, if we put one breakpoint in the class where it is called, and press the Continue in NetBeans, the problem occurs. But if we step over to the next lines and try to see the state at the end of the debug, the component seems to work perfectly.How can these kind of issues be resolved? | While running an application the error occurs, while debugging it doesn't | debugging | null |
_cstheory.5346 | The Turing machine (TM) is an abstract model for effective implementation of (finite algorithmic) calculation. TM is defined over some alphabet of symbols L and reading data performs a finite sequence of operations on these symbols in the manner described a kind of mapping, let's call it the transition mapping. TM has a certain inner state q which may be one element of a finite set Q. Transition mapping T specifies that if the machine reads in the current cell the symbol x from L.changes it to a symbol x ', and next data would be read from right (R) or left (L) cell. During this operation the state machine will change q to q '. We say that TM is defined as structure $ TM(L,Q,T,\{ START \},\{ STOP \}) $. But for this discussion it would be easier to say that we define certain sets as $ L'= L + \{ L,P \} $ and $ Q' = Q + \{ START,STOP \} $ and then we obtain symmetric $ T`: L' \times Q' -> L' \times Q' $. Then we omit any primes when it possible, and we define TM as $ TM(L,Q,T) $. We may describe states of TM as $ q_{ij} $ where $ i = 0...N $, $ j = L,P $ and $ q_{0L} =q_{0P} =START $, $ q_{NL} =q_{NP} =STOP $. Transition function is defined such that for given $ q_{ij} $ and symbol $ a_k $ from alphabet $ L $ machine in state $ q_{ij} $ reads $ a_k $ and goes to state $ q_{nm} $ and writes symbol $ a_s $ on the tape. That is:$ T'(q_{ij}, a_k) = T(q_i, a_s,) = (q_n, a_s, x) $ where $a_k, a_s \in L $ and $x \in \{ L,P \}$We may ask when $T(q_{ij}, a_k)$ defines any ordering relation on $ L \times Q $ or on $Q$ or even on $ L \times Q \times {L,P} $ ?Of course in general there is no such possibility, but in certain situation we may for example has $T(q_{ij}, a_k)$ such that for any $j,k$, $T(q_{ij}, a_k) = (q_{ nm }, a_s)$ and $i \leq n $. In such situation T defines partial order. In such situation $ Q $ may be a lattice with relation generated by order generated by transition function T.Are there any interesting facts about TM with such (or similar) property?Remark/MotivationI wonder if certain relation of this type,may give us algebraic structure on LxQ set. When the answer is yes, we may ask if TM will stop his computation for every data for example. Of course there are is in some way trivial examples of such transition function T. But suppose what if structure generated by T' is much more complicated for example if it is lattice. I suppose in certain situations it may be not trivial ( trivial one is when You have STOP and START as bounding extrema, and all other states are at the same level) So when it occurs, TM has certain and nontrivial data flow through it graph of states. And structure of it ( eg. lattice) may give us a tool for proving specific properties. | Turing Machine which generates order on the set of its states | reference request;turing machines;lattice | null |
_cs.53395 | In my CS computer organization textbook, there's this blurb on the advantage of assembly over a high-level language.Another major advantage of assembly language is the ability to exploit specialized instructions - for example, string copy or pattern-matching instructions. Compilers, in most cases, cannot determine that a program loop can be replaced by a single instruction. However, the programmer who wrote the loop can replace it easily with a single instruction.How can a loop be replaced by string copy or pattern matching? Can somebody give an example on specialized instructions that are not available in a high-level language and how a specialized instruction can replace a loop? | Examples of specialized instructions of assembly language not available in compilers? | programming languages;compilers | Some machines have complex processor instructions that can do the same job as a loop with a simple body. For example, x86 processors have an instruction scasb instruction that searches for a byte value; the C strlen function, which searches for a null byte and can be written in C aswhile (*p != 0) p++;can be written in x86 assembly asrepne scasbAnother example is bit counting. Many processors have instructions to do things like finding the number of bits that are set in a word, or finding the index of the lowest-order set bit in a word. However, most programming languages have no operator or function for that, so the programmer has to write a loop likebit_count = 0;while (n != 0) { if (n & 1) ++bit_count; n = n >> 1;}whereas recent x86_64 processors have an instruction for that:popcntSome C compilers provide extensions to the standard language that give access to this instruction (and compile to a loop-based form if such an instruction doesn't exist on the target machine).Yet another example is instructions that accelerate some common cryptographic algorithms (e.g. AES-NI on recent x86 processors). Unlike the previous two, this example is of interest only to the rarefied world of cryptography implementers, so compiler writers are less inclined to provide ways to generate those instructions apart from inline assembly.Your textbook seems somewhat dated to me. Loop instructions hard-wired in processors are a very CISC feature that most modern processors don't have, the notable exception being the x86 architecture where it is implemented in microcode for backward compatibility. Compilers have become better at understanding what a piece of code including a simple loop does, and converting them to optimized machine instructions. The statement Compilers, in most cases, cannot determine that a program loop can be replaced by a single instruction is not always true for 21st century compilers. It is sometimes true; for example I can't seem to get GCC to recognize my naive popcnt implementation above. |
_cs.68478 | I would like to confirm below understanding, A binary tree is a tree data structure in which each node has at most two children, which are referred to as the left child and the right child.Insertion:In binary trees, a new node before insert has to specify 1) whose child it is going to be 2) mention whether new node goes as left/right child. For example(below image),To add a new node to leaf node, a new node should also mention whether new node goes as left/right child.Deletion:For deletion, only certain nodes in a binary tree can be removed unambiguously.Suppose that the node to delete is node A. If A has no children, deletion is accomplished by setting the child of A's parent to null. If A has one child, set the parent of A's child to A's parent and set the child of A's parent to A's child.In a binary tree, a node with two children cannot be deleted unambiguously.Is this understanding correct ? | Operation on binary tree | data structures;binary trees | null |
_codereview.90190 | Some people complain about if - statements and I really appreciate that attitude. Actually I plan to abandon the entire keyword in order to awesomize my code, which is:Algorithm.java:package net.coderodde.noxx;import java.util.Arrays;import java.util.Random;/** * This is algorithm. It works as .. there is no need for .. - statements. * It proves that there is no need for .. - statements. */public class Algorithm { /** * ..less algorithm for finding the index of a maximum integer in an array. * * @param array the array to search. * @return the index of the maximum element or -1 if the array is * <code>null</code> or has length zero. */ public static final int indexOfMaximum(final int[] array) { int max; int index; // Here supposed check whether array is null or empty, but we are not // supposed to use ..-statements. Use exceptions instead! try { max = array[0]; index = 0; } catch (final NullPointerException | ArrayIndexOutOfBoundsException ex) { return -1; } for (int i = 1; i < array.length; ++i) { // Why not to use for's test condition instead of ..? for (int j = 0; j < testIsGreater(array[i], max); ++j) { max = array[i]; index = i; } } return index; } /** * Life is so much easier now without .. . */ private static int testIsGreater(final int element, final int max) { return element - max; } public static void main(final String... args) { final Random rnd = new Random(); final int[] array = new int[10]; for (int i = 0; i < array.length; ++i) { array[i] = rnd.nextInt(1301) - 300; } final int index = indexOfMaximum(array); final int check = Arrays.stream(array).max().getAsInt(); System.out.println(Maximum integer: + array[index] + and + check); }}AlgorithmTest.java:package net.coderodde.noxx;import static net.coderodde.noxx.Algorithm.indexOfMaximum;import org.junit.Test;import static org.junit.Assert.*;public class AlgorithmTest { /** * My tests use .. neither! Ain't this keeewl?? */ @Test public void testIndexOfMaximum() { int[] array = new int[0]; assertEquals(-1, indexOfMaximum(array)); assertEquals(-1, indexOfMaximum(null)); array = new int[]{3, 2, 1, 4, 5, 1 }; assertEquals(4, indexOfMaximum(array)); array = new int[]{3}; assertEquals(0, indexOfMaximum(array)); array = new int[]{3, 4, 1, 7}; assertEquals(3, indexOfMaximum(array)); } }So is it kewl to awesomize the code this way? | Finding the maximum of an array without using explicit conditionals | java | Some people complain about .. - statements and I really appreciate that attitude. Actually I plan to abandon the entire keyword in order to awesomize my codeI'm wondering what complaints you're referring to.In any case, I don't think you succeeded in awesomizing,but rather in suckifying.// Here supposed check whether array is null or empty, but we are not// supposed to use ..-statements. Use exceptions instead!try { max = array[0]; index = 0;} catch (final NullPointerException | ArrayIndexOutOfBoundsException ex) { return -1;}The statement in the comment is plain wrong.You are supposed to use if statement to check for nulls and array bounds.(Recommended reading: Item 57 in Effective Java by Joshua Bloch.)Exceptional logic shouldn't be used for normal program flow.What you're doing here is essentially input validation,which fits well within the bounds of normal program flow.Just use an if statement.// Why not to use for's test condition instead of ..?for (int j = 0; j < testIsGreater(array[i], max); ++j) { max = array[i]; index = i;}Because this is horrible code,obfuscating an otherwise simple logic,and looping unnecessarily./** * Life is so much easier now without .. . */private static int testIsGreater(final int element, final int max) { return element - max;}Is life really easier? Harder to read, with no benefits whatsoever, so no it isn't.Also a poor name for a function. isGreater would have been better.Related discussions:https://stackoverflow.com/questions/299068/how-slow-are-java-exceptionshttps://stackoverflow.com/questions/12265451/ask-forgiveness-not-permission-explain |
_webmaster.61423 | I implemented the unavailable_after tag in my pages like the below and set to unavailable after 3 days but in Google Webmaster Tools I got 404 for that page.<META NAME=GOOGLEBOT CONTENT=unavailable_after: 05-May-2014 15:00:00 EST>How do I know Googlebot visit(crawl) my pages again to read this tag (or) how long Googlebot will take to crawl the pages again ? please give me a suggestion!.Note: I set unavailable_after tag for certain content types(not whole website) with highest priority(1.0) in XML sitemap. | How do I find when Googlebot will visit(crawl) my pages again? | seo;google search console;googlebot | Googlebot recrawls pages with a frequency based on how popular they are and how often they have changed in the past. CNN's home page gets crawled every few minutes. A PageRank 0 page near the back of an unpopular blog may only get crawled monthly.As a general rule of thumb, I allow two to three weeks for all the pages on my site to get recrawled when I make changes.I don't believe that Googlebot actually uses the crawl priority or change date in XML sitemaps to trigger recrawls. The only way that I know to force Google to crawl a page is to use the Fetch as Google feature in Webmaster Tools. That tool has a limit of 1000 pages that have to be submitted manually one by one.See: How to request Google to re-crawl my website? |
_softwareengineering.287150 | How does a Kernel provides different functionality to OS? Does it use the BIOS routines or use special device drivers for this, or something else? If uses BIOS how does it come to know which routine performs what because different BIOS vendors have different coding? If not then what's the use for BIOS routines? | Relation between Kernel & BIOS routines | operating systems;kernel;bios | null |
_unix.298181 | So I've installed Syncthing and I'm running in a lot of problems getting this program to run as root on boot. For some reason it always runs as the default user ( thom ), but I boot into root and tell it to run as root. The command looks like this:sudo start-stop-daemon --start --quiet --background --chuid root --exec /usr/bin/syncthing -- --no-browserAnd is placed inside rc.local. Running rc.local manually AFTER booting works fine, the booting itself is not working. This is the only program thus far that's consistently running as the wrong user. Perhaps someone can help point out what exactly I'm doing wrong? | Command ran as wrong user on boot while explicitly being told to run as root | users;startup;daemon | null |
_unix.56082 | Currently, I have both the gajim and skype windows visible as both icons (in systray) and window labels (in mytasklist). How can I remove that latter so that it is not shown since I do not need two instances of the same thing cluttering my wibox. | Awesome wibox: remove tag label | awesome | To have a window not appear in the tasklist, you have to set skip_taskbar to true for the client.As you want to do that for specific applications, probably the best way is to add a client rule to your rc.lua:awful.rules.rules = { { rule = { class = {Gajim,Skype} }, properties = { skip_taskbar = true } }, -- other rules ...}You may have to change the values for class. To get the window class of a X program, call xprop WM_CLASS from a terminal, then click on the window you want to match. This should output 2 values (e.g. WM_CLASS(STRING) = Zsh, URxvt). The second one is the one for class. The first one can be matched with instance and may be used to differentiate between windows from the same program.See also Awesome Wiki for more on rules and Awesome API docs for a list of properties you can set with rules. |
_cogsci.8633 | Are there any studies on the possibility of visually recognizing someone's personality?When I say visually recognizing I mean things like clothes, accessories, body attitude, visible behavior, vehicles driven etc.When I say personality I mean things like Big 5 traits, personal motivations (money, love, attention, etc) and life goals (die rich, have a happy family, have high career, etc).For instance, I realized that big seller personalities (loves money, loves attention, will lie for any sale, loves to manipulate) would wear (or want) a gold watch. So when you see someone wearing a gold watch there is a high chance the person is a big seller-personality.In general, I would claim that everyone spends the most money, the most time and the most attention on what is most important to them. But what is the most important owned properties for different personalities? | Studies on visually recognizable personality traits? | personality;sensation;recognition | I am currently reading a book called Snoop, written by researcher Sam Gosling (I recommend this very interesting book!). He's doing just the kind of research I am looking for, and thus I've found tons of research documents on these things:Our research focuses on the following issues:Everyday manifestations of personality Which cues are reliably linked to what individuals are like?Everyday person perception Which cues do individuals use to form their impressions of others?Consensus Do observers agree with one another in their impressions of others?Accuracy Are observers impressions of others accurate?Stereotype use how do stereotypes hinder or promote consensus and accuracy? - http://gosling.psy.utexas.edu/current-research/everyday-manifestations-of-personality/http://gosling.psy.utexas.edu/publications/The expression and perception of personality in everyday lifeBack, M. D., Stopfer, J. M., Vazire, S., Gaddis, S., Schmukle, S. C., Egloff, B., & Gosling, S. D. (2010). Facebook profiles reflect actual personality not self-idealization. Psychological Science, 21, 372-374.Carney, D. R., Jost, J. T., Gosling, S. D., & Potter, J. (2008). The secret lives of liberals and conservatives: Personality profiles, interaction styles, and the things they leave behind. Political Psychology, 29, 807-840.Gebauer, J. E., Bleidorn, W., Gosling, S. D., Rentfrow, P. J., Lamb, M. E., & Potter, J. (in press). Cross-Cultural Variations in Big Five Relations with Religiosity: A Socio-Cultural Motives Perspective. Journal of Personality and Social Psychology.Gosling, S. D., Augustine, A. A., Vazire, S., Holtzman, N., & Gaddis, S. (2011). Manifestations of personality in Online Social Networks: Self-reported Facebook-related behaviors and observable profile information. Cyberpsychology, Behavior, and Social Networking, 14, 483-488. [DOI: 10.1089/cyber.2010.0087]Gosling, S. D., Gaddis, S., & Vazire, S. (2008). First impressions based on the environments we create and inhabit. In N. Ambady, & J. J. Skowronski (Eds.), First Impressions (pp. 334-356). New York: Guilford.Gosling, S. D., Gifford, R., & McCunn, L. (2013). The selection, creation, and perception of interior spaces: An environmental psychology approach. In G. Brooker & L. Weinthal (Eds.), The Handbook of Interior Design (pp. 278-290). Oxford, UK: Berg.Gosling, S. D., Ko, S. J., Mannarelli, T., & Morris, M. E. (2002). A Room with a cue: Judgments of personality based on offices and bedrooms. Journal of Personality and Social Psychology, 82, 379-398. [Available in pdf]Gosling, S. D., Sandy, C. J., & Potter, J. (2010). Personalities of self-identified dog people and cat people. Anthrozos, 23, 213-222.Graham, L. T., & Gosling, S. D. (2012). Impressions of World of Warcraft players personalities based on their usernames: Interobserver consensus but no accuracy. Journal of Research in Personality, 46, 599-603.Graham, L. T., & Gosling, S. D. (2013). Personality profiles associated with different motivations for playing World of Warcraft. Cyberpsychology, Behavior, and Social Networking, 16, 189-193.Graham, L. T., & Sandy, C. J., & Gosling, S. D. (2011). Manifestations of individual differences in physical and virtual environments. In T. Chamorro-Premuzic, S. von Stumm, & A. Furnham (Eds.), Handbook of Individual Differences (pp. 773-800). Oxford: Wiley-Blackwell.Mehl, M. R., Gosling, S. D., & Pennebaker, J. W. (2006). Personality in its natural habitat: Manifestations and implicit folk theories of personality in daily life. Journal of Personality and Social Psychology, 90, 862-877.Naumann, L. P., Vazire, S., Rentfrow, P. J., & Gosling, S. D. (2009). Personality judgments based on physical appearance. Personality and Social Psychology Bulletin, 35, 1661-1671Obschonka, M., Schmitt-Rodermund, E., Silbereisen, R. K., Gosling, S. D., & Potter, J. (2013). The regional distribution and correlates of an entrepreneurship-prone personality profile in the United States, Germany, and the United Kingdom: A socioecological perspective. Journal of Personality and Social Psychology, 105, 104-122. [DOI: 10.1037/a0032275]Rentfrow, P. J., Goldberg, L. R., Stillwell, D. J., Kosinski, M., Gosling, S. D., & Levitin, D. J. (2012). The song remains the same: A replication and extension of the MUSIC model. Music Perception, 30,161-185. [DOI: 10.1525/MP.2012.30.2.161]Rentfrow, P. J., & Gosling, S. D. (2003). The do re mis of everyday life: The structure and personality correlates of music preferences. Journal of Personality and Social Psychology, 84, 1236-1256. [Available in pdf]Rentfrow, P. J., & Gosling, S. D. (2006). Message in a Ballad: The role of music preferences in interpersonal perception. Psychological Science, 17, 236-242. [Available in pdf]Rentfrow, P. J., & Gosling, S. D. (2007). The content and validity of music-genre stereotypes among college students. Psychology of Music, 35, 306-326.Rentfrow, P. J., Gosling, S. D., Jokela, M., Stillwell, D. J., Kosinski, M., & Potter, J. (2013). Divided We Stand: Three Psychological Regions of the United States and their Political, Economic, Social, and Health Correlates. Journal of Personality and Social Psychology, 105, 996-1012. [DOI: 10.1037/a0034434]Rentfrow, P. J., Gosling, S. D., & Potter, J. (2008). A theory of the emergence, persistence, and expression of geographic variation in psychological characteristics. Perspectives on Psychological Science, 3, 339-369.Sandy, C. J., Gosling, S. D., & Durant, J. (2013). Predicting Consumer Behavior and Media Preferences: The Comparative Validity of Personality Traits and Demographic Variables. Psychology and Marketing, 30, 937-949. [DOI: 10.1002/mar.20657]Swann, W. B., Jr., Rentfrow, P. J., & Gosling, S. D. (2003). The precarious couple effect: Verbally inhibited men + critical, disinhibited women = bad chemistry. Journal of Personality and Social Psychology, 85, 1095-1106. [Available in pdf]Vazire, S., Naumann, L. P., Rentfrow, P. J., & Gosling, S. D. (2009). Smiling reflects different emotions in men and women. Behavioral and Brain Sciences, 32, 403-405.Vazire, S., Naumann, L. P., Rentfrow, P. J., & Gosling, S. D. (2008). Portrait of a narcissist: Manifestations of narcissism in physical appearance. Journal of Research in Personality, 42, 1439-1447.Vazire, S. & Gosling, S. D. (2004). e-perceptions: Personality impressions based on personal websites. Journal of Personality and Social Psychology, 87, 123-132. [Available in pdf]Wilson, R. E., Gosling, S. D., & Graham, L. T. (2012). A review of Facebook research in the social sciences. Perspectives on Psychological Science, 7, 203-220. [DOI 10.1177/1745691612442904]Anderson, C. P., Ames, D. R., & Gosling, S. D. (2008) Punishing hubris: The perils of status self-enhancement in teams and organizations. Personality and Social Psychology Bulletin, 34, 90-101.Erdle, S., Gosling, S. D., & Potter, J. (2009). Does self-esteem account for the higher-order factors of the Big Five? Journal of Research in Personality, 43, 921-922.Gosling, S. D., Sandy, C. J., & Potter, J. (2010). Personalities of self-identified dog people and cat people. Anthrozos, 23, 213-222.Gosling, S. D., & Srivastava, S. (2011). Changes in perceptions of George W. Bushs personality in the wake of the September 11 2001 World Trade Center attacks. Acta de Investigacin Psicolgica, 3, 486-490.Jost, J. T., Hawkins, C. B., Nosek, B. A., Hennes, E. P., Stern, C., Gosling, S. D., & Graham, J. (2014). Belief in a Just God (and a Just Society): A System Justification Perspective on Religious Ideology. Journal of Theoretical and Philosophical Psychology, 34, 56-81. [Translated to: Jost, J. T., Hawkins, C. B., Nosek, B. A., Hennes, E. P., Stern, C., Gosling, S. D., & Graham, J. (in press). Creencia en un dios justo: La Religin como una forma de Justificacin del Sistema. Psicologia Politica, 47, 55-89.]Mathieu, M. T., & Gosling, S. D. (2012). The accuracy or inaccuracy of affective forecasts depends on how the question is framed: A meta-analysis of past studies. Psychological Science, 23, 161-162. [DOI: 10.1177/0956797611427044]Pennebaker, J. W., Gosling, S. D., & Ferrell, J. (2013). Daily online testing in large classes: Boosting college performance while reducing achievement gaps. PLOS ONE, 9, e79774. [doi:10.1371/journal.pone.0079774]Ramrez-Esparza, N., Gosling, S. D., & Pennebaker, J. W. (2008). Paradox lost: Unraveling the puzzle of Simpatia. Journal of Cross-Cultural Psychology, 39, 685-702.Robins, R. W., Tracy, J. L., Trzesniewski, K. H., Potter, J., & Gosling, S. D. (2001). Personality correlates of self-esteem. Journal of Research in Personality, 35, 463-482. [Available in pdf]Vazire, S., Naumann, L. P., Rentfrow, P. J., & Gosling, S. D. (2009). Smiling reflects different emotions in men and women. Behavioral and Brain Sciences, 32, 403-405.Wood, D., Gosling, S. D., & Potter, J. (2007). Normality evaluations and their relation to personality traits and well-being. Journal of Personality and Social Psychology, 93, 861-879. |
_unix.333116 | I'm using Linux Mint 18 Sarah MATE 32 bit and I'm trying to download Game Maker Studio off of Wine 1.6.2. It was named GMStudio-Installer-1.4.1763.exe.At first the installation process went perfectly, but Game Maker Studio didn't work. Then Wine wasn't working anymore. So I uninstalled it and reinstalled Wine. Then I tried it again but it said (exactly):Installation failed.This software requires Windows Framework 3.5.* or higherNo version of Windows Framework is installed.Please update your computer at https://windowsupdate.microsoft.com/.Now I can't install anything off of Wine anymore.I looked up what to do on WineHQ, but no luck. | Wine not working for Linux Mint 18 Sarah. Trying to run Game Maker Studio, with no luck | linux mint;wine;programming | Run the following command as root:rm -r /home/[enter your username here]/.wineThis will remove the entire Wine system.Now reinstall Wine. This will depend on your package manager.Finally, rebuild Wine by running winecfg as your normal user. |
_codereview.4473 | Im running a photocontest and making a list of winners with one winner each day. My loop is running very slow. It seams to be the toList() that is time consuming. Any suggestions on how to make it run faster?foreach (var date in dates) { var voteList = _images.Select(image => new ImageWinnerVotes { ID = image.ID, Image = image.ImagePath, Thumbnail = image.ThumbnailImagePath, Title = image.Name, Url = GetFriendlyUrl(image.ID), Date = image.CreatedDate, WinnerDateString = date.Date.ToString(dd/MM), WinnerDate = date.Date, TotalVotes = (votes.Where(vote => vote.ItemId == image.ID)).Count(), Name = image.Fields[Name].ToString(), Votes = (votes.Where( vote => vote.ItemId == image.ID && vote.Date.DayOfYear == date.Date.DayOfYear)).Count() }).ToList(); voteList = voteList.OrderByDescending(v => v.Votes).ToList(); var j = 0; var findingWinner = true; while(findingWinner) { var inWinnersList = false; if (winnersList.Count() != 0) { if(!winnersList.Contains(voteList.ElementAt(j))) { winnersList.Add(voteList.ElementAt(j)); findingWinner = false; } } else { winnersList.Add(voteList.ElementAt(j)); findingWinner = false; } j++; } } | Linq in foreach with c# | c#;linq | null |
_codereview.27067 | In my controller I had the idea to do something like the following:// retrieve fields from form$firstname = $form->getInput('firstname');$lastname = $form->getInput('lastname');[...]// create Member object$member = new Member($firstname, $lastname, [...]);// save Member in DB$this->_daoFactory->get('Member')->save($member);In this example, the DAO factory would create an instance of the MemberDAO class, which (I guess) acts like a data mapper? And allows me to save the Member object in DB, to update a Member, get a Member from id, and other db requests probably.What do you think about this code?Thank you for your review! | Is this a good way for Controller to interact with Model ? (MVC) | php;mvc | null |
_unix.203330 | I want to add toolbar buttons to KDE titlebars to avoid using the menu for certain tasks. As an example I want to be able to get a screen to stay on top until I disable it. eg. KDE titlebars have a menu item More Actions -> Keep Above Others.How would I add a button to enable or disable it with one click? | How can I add a toolbar button to KDE titlebars? | kde;toolbar | One solution would be to assign a keyboard shortcut for that kwin action. Open systemsettings => shortcuts and gestures and choose Global Keyboard Shortcuts in the left panel, and on the right pane select KWin at the KDE component dropdown menu.And for the button, if you only want to trigger built-in functions, that is pretty easy to add, you can also configure that in systemsettings => workspace appearance. Click on Configure Buttons ... at the bottom, and enable Use custom titlebar button positions. Then simply drag&drop the actions to the place where you want it on the titlebar, and add spacers as needed.See also http://www.linuxbsdos.com/2012/07/04/how-to-custmize-kdes-window-titlebar-buttons/ for a detailed description with screenshots.If you want to add custom actions, you might need to have a look into the KWin scripting facilities:https://techbase.kde.org/Development/Tutorials/KWin/Scriptinghttps://techbase.kde.org/Development/Tutorials/KWin/Scripting/API_4.9How can I run a kwin script from the command line?If you would really want to add a custom button to the titlebar, you would need to customize or create the window decoration in an existing or new theme for that. |
_softwareengineering.250844 | I'm looking for a book to learn how to implement interpreters for programming languages. Thing is there are much more 'compiler books' than 'interpreter books'. So my question is: can I read a book that teaches how to build compilers, to learn how to build interpreters (at a very beginner level)? Is this a good idea? If so, what do I need to keep in mind while reading? | Is a book that teaches how to build compilers good for learning to implement interpreters? | learning;books;compiler;interpreters | Absolutely - an interpreter is just a one line at a time compiler. It performs much the same task, that of taking some form of human-understandable source code and turning it into something a computer processor can understand. A compiler will do this for entire source file(s), whereas an interpreter will do this on an as-read basis. You will need to handle a few differences around loading source as needed, and handling parsing source files to find the next line to read, but otherwise you'll be implementing a compiler fundamentally. |
_softwareengineering.194615 | I'm developing a WordPress theme and am planning to sell it myself. I was thinking of having a 14- or 30-day refund policy for customers, but my concern is that people can essentially get the theme for free, if they: 1) buy it, 2) download the files, and then 3) request a refund. Then they would have both the theme and their money back.I've been looking into software refund policies and noticed there are a few different schools of thoughts on providing customer refunds:School of Thought #1 - Provide refunds. If your software is good quality, not many people will request a refund. My response: But in my case, even if users think the theme is high quality, they can still request a refund and also keep the theme. I have also put a lot of work into the development and testing of the theme, so it is quality work.School of Thought #2 - Provide refunds, but some customers will abuse the refund process, so have an activation code and only provide refunds to people who have not activated the software. My response: This sounds like a good idea, but there isn't an activation mechanism for themes in WordPress, so I don't know how I could implement it.School of Thought #3 - No refunds. My response: This seems really inflexible. I'm not against refunding customer payments for good reason, but I don't want to give away my work, either.Have you heard of any other good options in setting up a refund policy? | Setting up a refund policy for a commercial WordPress theme | customer relations | Have a read of Joel On Software's blog post about 7 steps to customer service.In particular, Step 7 is apropos to your concerns.They run with a 90 day policy for requesting refunds, and per the article, it's cost them 2%. Joel Spolsky also creates a correlation between the customers feeling empowered in the transaction; being nice to customer service reps; and no real abuse of their refund system.The entire article is well worth reading, and I think you'll pick up some gems as you build your business. |
_webapps.27288 | Strangely enough, I couldn't find any info about this, which I would have thought is a common problem.I want to share a folder with another person I work with. I want to give them the same permissions as I have, not just edit. I want to make them owners of that folder. Is that possible at all? | How to Set Several Owners for a Google Drive Folder | google drive | Only one person can own a folder in Google Drive. You can allow access to other people, but there can be only one owner.http://support.google.com/drive/bin/answer.py?hl=en&answer=2494886 |
_cs.33890 | I know that the general consensus among CS researchers is that non-relativizing techniques will be needed to separate P and NP. However, if there is an oracle language $A \in \textbf{P}$ such that ${\textbf{P}}^A \neq {\textbf{NP}}^A$ would that necessarily imply ${\textbf{P}} \neq {\textbf{NP}}$? I read somewhere that it would be enough, but I'm not sure.On the one hand, since any NDTM can be supplemented with a polynomial-time deterministic subroutine for $A$, having oracle access to it should not give an NDTM any more power. On the other hand though, aren't oracle TM's able to make queries about strings of any length in the oracle language? In that case, we could not jump to the conclusion that P does not equal NP, because according to my understanding, polynomial-time Turing machines (whether deterministic or non-deterministic) cannot be influenced by strings of length exponential in the length of the input string. | Can oracle arguments separate P and NP? | complexity theory;p vs np;oracle machines | null |
_unix.6433 | Were I root, I could simply create a dummy user/group, set file permissions accordingly and execute the process as that user. However I am not, so is there any way to achieve this without being root? | How to jail a process without being root? | permissions;not root user;jails | More similar Qs with more answers worth attention: https://stackoverflow.com/q/3859710/94687https://stackoverflow.com/q/4410447/94687https://stackoverflow.com/q/4249063/94687https://stackoverflow.com/q/1019707/94687some of the answers there point to specific solutions not yet mentioned here. (Actually, there are quite a few jailing tools with different implementation, but many of them are either not secure by design (like fakeroot, LD_PRELOAD-based), or not complete (like fakeroot-ng, ptrace-based), or would require root (chroot, or plash mentioned at http://joey.kitenet.net/blog/entry/fakechroot_warning_label). These are just examples; I thought of listing them all side-by-side, with indication of these 2 features (can be trusted?, requires root to set up?), perhaps at http://en.wikipedia.org/wiki/Operating_system-level_virtualization#Implementations.)In general, the answers there cover the full described range of possibilities and even more: virtual machines/OS(the answer mentioning virtual machines/OS)kernel extension (like SELinux)(mentioned in comments here), chrootchroot-based helpers (which however must be setUID root, because chroot requires root; or perhaps chroot could work in an isolated namespace--see below):[to tell a little more about them!]Known chroot-based isolation tools:hasher with its hsh-run and hsh-shell commands. (Hasher was designed for building software in a safe and repeatable manner.)schroot mentioned in another answer...ptraceAnother trustworthy isolation solution (besides a seccomp-based one) would be the complete syscall-interception through ptrace, as explained in the manpage for fakeroot-ng:Unlike previous implementations, fakeroot-ng uses a technology that leaves the traced process no choice regarding whether it will use fakeroot-ng's services or not. Compiling a program statically, directly calling the kernel and manipulating ones own address space are all techniques that can be trivially used to bypass LD_PRELOAD based control over a process, and do not apply to fakeroot-ng. It is, theoretically, possible to mold fakeroot-ng in such a way as to have total control over the traced process.While it is theoretically possible, it has not been done. Fakeroot-ng does assume certain nicely behaved assumptions about the process being traced, and a process that break those assumptions may be able to, if not totally escape then at least circumvent some of the fake environment imposed on it by fakeroot-ng. As such, you are strongly warned against using fakeroot-ng as a security tool. Bug reports that claim that a process can deliberatly (as opposed to inadvertly) escape fake root-ng's control will either be closed as not a bug or marked as low priority.It is possible that this policy be rethought in the future. For the time being, however, you have been warned.Still, as you can read it, fakeroot-ng itself is not designed for this purpose.(BTW, I wonder why they have chosen to use the seccomp-based approach for Chromium rather than a ptrace-based...)Of the tools not mentioned above, I have noted Geordi for myself, because I liked that the controlling program is written in Haskell.Known ptrace-based isolation tools:Geordiprootfakeroot-ng... (see also How to achieve the effect of chroot in userspace in Linux (without being root)?)seccompOne known way to achieve isolation is through the seccomp sandboxing approach used in Google Chromium. But this approach supposes that you write a helper which would process some (the allowed ones) of the intercepted file access and other syscalls; and also, of course, make effort to intercept the syscalls and redirect them to the helper (perhaps, it would even mean such a thing as replacing the intercepted syscalls in the code of the controlled process; so, it doesn't sound to be quite simple; if you are interested, you'd better read the details rather than just my answer).More related info (from Wikipedia):http://en.wikipedia.org/wiki/Seccomphttp://code.google.com/p/seccompsandbox/wiki/overviewLWN article: Google's Chromium sandbox, Jake Edge, August 2009seccomp-nurse, a sandboxing framework based on seccomp.(The last item seems to be interesting if one is looking for a general seccomp-based solution outside of Chromium. There is also a blog post worth reading from the author of seccomp-nurse: SECCOMP as a Sandboxing solution ?.)The illustration of this approach from the seccomp-nurse project:A flexible seccomp possible in the future of Linux?There used to appear in 2009 also suggestions to patch the Linux kernel so that there is more flexibility to the seccomp mode--so that many of the acrobatics that we currently need could be avoided. (Acrobatics refers to the complications of writing a helper that has to execute many possibly innocent syscalls on behalf of the jailed process and of substituting the possibly innocent syscalls in the jailed process.) An LWN article wrote to this point:One suggestion that came out was to add a new mode to seccomp. The API was designed with the idea that different applications might have different security requirements; it includes a mode value which specifies the restrictions that should be put in place. Only the original mode has ever been implemented, but others can certainly be added. Creating a new mode which allowed the initiating process to specify which system calls would be allowed would make the facility more useful for situations like the Chrome sandbox.Adam Langley (also of Google) has posted a patch which does just that. The new mode 2 implementation accepts a bitmask describing which system calls are accessible. If one of those is prctl(), then the sandboxed code can further restrict its own system calls (but it cannot restore access to system calls which have been denied). All told, it looks like a reasonable solution which could make life easier for sandbox developers.That said, this code may never be merged because the discussion has since moved on to other possibilities.This flexible seccomp would bring the possibilities of Linux closer to providing the desired feature in the OS, without the need to write helpers that complicated.(A blog posting with basically the same content as this answer: http://geofft.mit.edu/blog/sipb/33.)namespaces (unshare)Isolating through namespaces (unshare-based solutions) -- not mentioned here -- e.g., unsharing mount-points (combined with FUSE?) could perhaps be a part of a working solution for you wanting to confine filesystem accesses of your untrusted processes. More on namespaces, now, as their implementation has been completed (this isolation technique is also known under the nme Linux Containers, or LXC, isn't it?..):One of the overall goals of namespaces is to support the implementation of containers, a tool for lightweight virtualization (as well as other purposes).It's even possible to create a new user namespace, so that a process can have a normal unprivileged user ID outside a user namespace while at the same time having a user ID of 0 inside the namespace. This means that the process has full root privileges for operations inside the user namespace, but is unprivileged for operations outside the namespace.For real working commands to do this, see the answers at:Is there a linux vfs tool that allows bind a directory in different location (like mount --bind) in user space?Simulate chroot with unshareand special user-space programming/compilingBut well, of course, the desired jail guarantees are implementable by programming in user-space (without additional support for this feature from the OS; maybe that's why this feature hasn't been included in the first place in the design of OSes); with more or less complications.The mentioned ptrace- or seccomp-based sandboxing can be seen as some variants of implementing the guarantees by writing a sandbox-helper that would control your other processes, which would be treated as black boxes, arbitrary Unix programs.Another approach could be to use programming techniques that can care about the effects that must be disallowed. (It must be you who writes the programs then; they are not black boxes anymore.) To mention one, using a pure programming language (which would force you to program without side-effects) like Haskell will simply make all the effects of the program explicit, so the programmer can easily make sure there will be no disallowed effects.I guess, there are sandboxing facilities available for those programming in some other language, e.g., Java.Cf. Sandboxed Haskell project proposal.NaCl--not mentioned here--belongs to this group, doesn't it?Some pages accumulating info on this topic were also pointed at in the answers there:page on Google Chrome's sandboxing methods for Linuxsandboxing.org group |
_webapps.1092 | Is there any way to export all the Facebook historical data from your profile (contacts, photos, videos, posts, links, comments, etc.) to a local storage? | How do I export content from Facebook? | facebook;data liberation | This web app describes steps to achieve what you're looking for I think.UpdateIt appears this addon was removed. It used to be called ArchiveFacebook, but I don't see it on the mozilla site anymore. |
_softwareengineering.261349 | I am using MVP for creating an android application, which takes data from server and sets to activity. I am forced to create one presenter for each view.Each view is unique because each view has different textviews/labels.The presenter will read values from model and call setter method for each control in view.For second view, I will need different presenter, as I need to call some other setter methods on the view interface. This means view - presenter will have one to one relationship.Is it ok for view - presenter to have one to one relation in MVP or my approach is not correct? EDIT: I will be using one presenter for each view because I have to. Because each presenter will implement the functionality unique for each view. However that poses reusability problem. The presenters have a lot of common code. eg calling helper to load data from URL etc. So I am planning to use either the abstract factory pattern or the strategy pattern. The problem with abstract factory pattern is , if tomorrow my presenter need to extend another class, it cannot be done because i m coding in java. So is it advisable to use abstract factory pattern in java , for the presenter group? | How can one presenter be used for multiple views in MVP | android;mvp;factory method | Yes, it is fine.Applying MVP design pattern means having MVP triplets (model-presenter-view) per every (even a bit complex) item to display. The logic goes to the model, and the presenter is there just to glue things. |
_webmaster.24235 | We are located in Israel and suppose to receive payments from all over the world, but mostly from North America and Western Europe.Can one recommend a developer friendly, reliable and simple service which I can use? (hint: PayPal is a wrong answer!)I wish Stripe were serving customers outside of US, but this is not the case yet. | I am looking for a developers friendly, simple credit card processing service for a business outside of the US. Any recommendations? | ecommerce;creditcard | Have a look at Moneybookers, http://www.moneybookers.com/ads/merchant-account/ecommerce-payment-system/I'm using their services between my different bank accounts since a couple of year and you can trust them. You can even have a Master Card linked to your account.Hope it help |
_unix.42824 | My desktop is usually very responsive, even under heavy load. But when I copy files to a USB drive, it always locks up after some time. By lock up, I mean:Moving focus from one window to another can take 10-20sSwitching desktops can take 10-20sVideos don't update anymore (in YouTube, the audio continues to play, only the video freezes)The system load isn't exceptionally high when this happens. Sometimes, I see a lot of white on xosview indicating that the kernel is busy somewhere.At first glance, it looks as if copying files to the USB drive would interfere somehow with compiz but I can't imagine what the connection could be.Here is the output of htop:Here is the output of iostat -c -z -t -x -d 1 during a 2 minute hang:19.07.2012 20:38:22avg-cpu: %user %nice %system %iowait %steal %idle 1,27 0,00 0,38 37,52 0,00 60,84Device: rrqm/s wrqm/s r/s w/s rkB/s wkB/s avgrq-sz avgqu-sz await r_await w_await svctm %utilsdg 0,00 2,00 0,00 216,00 0,00 109248,00 1011,56 247,75 677,69 0,00 677,69 4,63 100,00As you can see, only the external harddisk is active. Here is the complete log: http://pastebin.com/YNWTAkh4The hang started at 20:38:01 and ended at 20:40:19.Software information:openSUSE 12.1KDE 4.7.xFilesystems: reiserfs and btrfs on my internal harddisk, btrfs on the USB drive | Why does my desktop lock up when I copy lots of files to a USB drive? | linux;kde;btrfs | My first guess was btrfs since the I/O processes of this file system sometimes take over. But it wouldn't explain why X locks up.Looking at the interrupts, I see this:# cat /proc/interrupts CPU0 CPU1 CPU2 CPU3 CPU4 CPU5 CPU6 CPU7 0: 179 0 0 0 0 0 0 0 IR-IO-APIC-edge timer 1: 6 0 0 0 0 0 0 0 IR-IO-APIC-edge i8042 8: 1 0 0 0 0 0 0 0 IR-IO-APIC-edge rtc0 9: 0 0 0 0 0 0 0 0 IR-IO-APIC-fasteoi acpi 12: 10 0 0 0 0 0 0 0 IR-IO-APIC-edge i8042 16: 3306384 0 0 0 0 0 0 0 IR-IO-APIC-fasteoi ehci_hcd:usb1, nvidia, mei, eth1Well, duh. The USB driver uses the same IRQ as the graphics card and it is first in the chain. If it locks up (because the file system does something expensive), the graphics card starves (and the network, too). |
_unix.198537 | I'm try to make a new virtual machine but virtualbox have this error in end step :Failed to create a new session.Callee RC: NS_ERROR_FACTORY_NOT_REGISTERED (0x80040154)and in terminal this shwn for me: $ virtualbox WARNING: The vboxdrv kernel module is not loaded. Either there is no module available for the current kernel (3.16.3-1-ARCH) or it failed to load. Please reinstall the kernel module virtualbox-host-modules or if you don't use our stock kernel compile the modules with sudo dkms autoinstall You will not be able to start VMs until this problem is fixed.Qt WARNING: libpng warning: iCCP: known incorrect sRGB profileQt WARNING: libpng warning: iCCP: known incorrect sRGB profileQt WARNING: libpng warning: iCCP: known incorrect sRGB profileQt WARNING: libpng warning: iCCP: known incorrect sRGB profileQt WARNING: libpng warning: iCCP: known incorrect sRGB profileQt WARNING: libpng warning: iCCP: known incorrect sRGB profileQt WARNING: libpng warning: iCCP: known incorrect sRGB profileQt WARNING: libpng warning: iCCP: known incorrect sRGB profileQt WARNING: libpng warning: iCCP: known incorrect sRGB profileQt WARNING: libpng warning: iCCP: known incorrect sRGB profileQt WARNING: libpng warning: iCCP: known incorrect sRGB profileQt WARNING: libpng warning: iCCP: known incorrect sRGB profileQt WARNING: libpng warning: iCCP: known incorrect sRGB profileQt WARNING: libpng warning: iCCP: known incorrect sRGB profileQt WARNING: libpng warning: iCCP: known incorrect sRGB profileQt WARNING: libpng warning: iCCP: known incorrect sRGB profileQt WARNING: libpng warning: iCCP: known incorrect sRGB profileQt WARNING: libpng warning: iCCP: known incorrect sRGB profileQt WARNING: libpng warning: iCCP: known incorrect sRGB profileQt WARNING: libpng warning: iCCP: known incorrect sRGB profileQt WARNING: libpng warning: iCCP: known incorrect sRGB profileQt WARNING: libpng warning: iCCP: known incorrect sRGB profileQt WARNING: libpng warning: iCCP: known incorrect sRGB profileQt WARNING: libpng warning: iCCP: known incorrect sRGB profileCallee RC: NS_ERROR_FACTORY_NOT_REGISTERED (0x80040154) | virtualbox can not create new virtual machine | arch linux;kernel;virtualbox;virtualization | null |
_codereview.2751 | Last weekend I was writing a short PHP function that accepts a starting move and returns valid knight squares for that move.<?php/* get's starting move and returns valid knight moves */echo GetValidKnightSquares('e4');function GetValidKnightSquares($strStartingMove) { $cb_rows = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5, 'f' => 6, 'g' => 7, 'h' => 8); $valids = array(array(-1, -2), array(-2, -1), array(-2, 1), array(-1, 2), array(1, 2), array(2, 1), array(2, -1), array(1, -2)); $row = substr($strStartingMove, 0, 1); $col = substr($strStartingMove, 1, 1); $current_row = $cb_rows[$row]; if(!in_array($current_row, $cb_rows)) { die(Hey, use chars from a to h only!); } $current_col = $col; if($current_col > 8) { die(Hey, use numbers from 1 to 8 only!); } $valid_moves = ''; foreach ($valids as $valid) { $new_valid_row = $current_row + $valid[0]; $new_valid_col = $current_col + $valid[1]; if(($new_valid_row <= 8 && $new_valid_row > 0) && ($new_valid_col <= 8 && $new_valid_col > 0)) { $row_char = array_search($new_valid_row, $cb_rows); $valid_moves .= $row_char . $new_valid_col ; } } return Valid knight moves for knight on $strStartingMove are: $valid_moves;} ?>Could you please take a look at it and share your thoughts about it? The code can also be found here.I was kinda 'criticized' about the code. One guy said it's messy, too long and not 'clever' enough. So I needed second opinion on it, a code review if you like. I think there is a place for improvement (always), but for me this was the first time I've coded something related with Chess. I've found something like this that caught my attention:if ((abs(newX-currentX)==1 and abs(newY-currentY)==2) or (abs(newX-currentX)==2 and abs(newY-currentY)==1)) { /* VALID MOVE FOR A KNIGHT */}else { /* INVALID MOVE FOR A KNIGHT */} | Need help with valid knight moves in Chess | php | null |
_vi.10479 | I know that for options and mappings I can use verbose (set|map) XXX(?)? to find out which script has set an option or a mapping at last. However, this does not work for variables and the let command. At the same time using let g: only shows me the function or line etc. where a variable was set but not the scriptfile.Is there any way to get to achieve this? | How to figure out which script set a variable? | variables | null |
_softwareengineering.178030 | I have an app with the following three tablesEmail (emailNumber, Address)Recipients (reportNumber, emailNumber, lastChangeTime, status)Report (reportNumber, reportName)I have a C# application that uses inline queries for data selection.I have a select query that selects all reports and their Recipients. Recipients are selected as comma separacted string.During updating, I need to check concurrency. Currently I am using MAX(lastChangeTime) for each reportNumber. This is selected as maxTime. Before update, it checks that the lastChangeTime <= maxTime. --//It works fineOne of my co-developers asked why not use GETDATE() as maxTime rather than using a MAX operation. That is also working. Here what we are checking is the records are not updated after the record selection time.Is there any pitfalls in using GETDATE() for this purpose? | Concurrency checking with Last Change Time | c#;sql;concurrency | null |
_cogsci.13873 | Are there any studies on the effects of long term imprisonment on cognitive abilities? I'm looking for something which focuses on cognitive impairment rather than other psychological issues. | Cognitive impairment in long term prisoners | cognitive psychology | null |
_codereview.141932 | I need to compress some text, I'm wondering if my program could be made more efficient. The only things I could think of would be the 'import re' and turning the filename input and read part as a function.import refrom ast import literal_eval################## Compression #####################def comp(): while True: try: fileName=input('Please input text file name in current directory: ')+'.txt' a=open(fileName) break except: print('No Such text file in current directory name: '+fileName) content = a.read() a.close() p = re.compile(r'[\w]+|[\W]') split = p.findall(content) b = [] wordList = [] for word in split: try: r = wordList.index(word) + 1 except ValueError: wordList.append(word) r = len(wordList) b.append(r) f=open('compressed.txt', 'w') f=open('compressed.txt', 'r+') f.write(str(wordList)+'\n'+str(b)) f.close()###################################################################### De-Compression ##################def decomp(): while True: try: fileName=input('Please input text file name in current directory: ')+'.txt' a=open(fileName) break except: print('No Such text file in current directory name: '+fileName) words = literal_eval(a.readline().rstrip('\n')) pos = literal_eval(a.readline()) temp = [] for index in pos: temp.append(words[index-1]) sentence = ''.join(temp) print(sentence)#################################################### | Compress and decompress a string from a file | python;python 3.x;file;compression;import | null |
_unix.277687 | I'm trying to recover from an accidental format of ext4 1TB HDD. I tried virtually all linux tools (extundelete, ext3grep, ext4magic, testdisk, photorec, and others).Some that worked: testdisk, photorec and foremost. They recovered some 300000 files, but they didn't recover the hdd folder structure which is very important to me because I had many projects and important documents in this HDD.They just recovered files and put them in folders divided by extension or some in a unique folder. extundelete couldn't find anything. ext3grep and ext4magic crashed.I'm trying for more than a week to find a tool that recover folder structure with no luck.Is this possible ? I mean recover files inside the correct folder structure ?HistoryI accidentally formated it and immediately shutted down the computer. It was a data only HDD with no file system files in it. So I initially thought I had a good chance of recovering it. But I'm start to think I'll have to deal with organizing thousands of files.I have searched many forums, and help sites like this and couldn't find anything that works. In order to recover from it I bought a Blackarmor NAS with 6TB space. So I have plenty of room to any recovery operation.All utilites mentioned above, as long as all the recovered files were recovered not from the unit itself, but from an image I've made with dd.The HDD itself is physically OK. No damaged sectors or malfunctions.Any advice welcome.UpdateAt this point I'm not getting anywhere so I sent the physical HDD to a data recovery company. Any advice about recovering files and folder structure can only be based now on the image I have. | Recover formated ext4 partition with file structure | data recovery;ext4 | null |
_cstheory.8758 | The paper Symbolic Finite State Transducers, Algorithms and Applications by Bjorner et al (to appear at POPL 2012) describes one type of finite-state, infinite-alphabet automata/transducers by using predicates from any decidable theory as the alphabet. The paper also references quite a few others including:Automata and logics for words and trees over an infinite alphabet by Segoufin, Finite memory automata by Kaminski and Francez, FOCS 1990I'm wondering whether there's a good survey on different infinite alphabet automata models. | Survey on infinite alphabet automata? | reference request;fl.formal languages;automata theory;survey | null |
_codereview.154603 | I am parsing ICD-10 codes and have achieved a result that satisfies my base case, but I'm worried about how fragile my method is:import xml.etree.ElementTree as ET# A sample of the larger XML file I'm parsingdata = '''<diag><name>A00</name><desc>Cholera</desc><diag> <name>A00.0</name> <desc>Cholera due to Vibrio cholerae 01, biovar cholerae</desc> <inclusionTerm> <note>Classical cholera</note> </inclusionTerm></diag><diag> <name>A00.1</name> <desc>Cholera due to Vibrio cholerae 01, biovar eltor</desc> <inclusionTerm> <note>Cholera eltor</note> </inclusionTerm></diag><diag> <name>A00.9</name> <desc>Cholera, unspecified</desc></diag></diag>'''# Create the treetree = ET.ElementTree(ET.fromstring(data))# the `iter` method returns all tags in a given tree# I'm just grouping the tags and texts heredef get_all_elements(tree): return [(elem.tag, elem.text) for elem in tree.iter()]# This will return the desired elements from my treedef parse_elements(tree): # First, get all of the elements in the tree elements = get_all_elements(tree) to_return = {} # This is what I think is too fragile. I'm basically looking # ahead for each element to see whether the next two elements # match the diag -> name -> desc sequence. But this indexing seems # to be too fragile at scale. for idx, elem in enumerate(elements): if 'diag' in elem and 'name' in elements[idx+1] and 'desc' in elements[idx+2]: name = elements[idx+1] desc = elements[idx+2] to_return[name[1]] = desc[1] return to_returnres = parse_elements(tree)Let's see what's in res:for k,v in res.items(): print(name (code): , k, \n desc: , v)name (code): A00.9 desc: Cholera, unspecifiedname (code): A00.0 desc: Cholera due to Vibrio cholerae 01, biovar choleraename (code): A00 desc: Choleraname (code): A00.1 desc: Cholera due to Vibrio cholerae 01, biovar eltorSo, I achieve my desired output, but I keep thinking there much be a better way to parse this XML. Unfortunately there's no <diag><subdiag></subdiag></diag>-type of hierarchy. Even subdiagnoses are labeled with the <diag> tag. I suppose the above is my attempt at recursion -- although I have found true recursion tough with the current tag-naming. At the end of the day, I just need the name: desc pairs.Edit:There's also this approach:names = [x.text for x in ET.fromstring(data).findall('.//name')]descs = [x.text for x in ET.fromstring(data).findall('.//desc')]res = zip(names, descs)But I don't think this approach scales well, as the number of elements in names and descs differed by about 1000 when I tested this on the larger XML file. There were mismatches between codes and descriptions when I validated on actual codes. | Parsing XML to get all elem.tag: elem.text pairs | python;xml | Since the latter approach resulted into broken mismatched pairs, looks like there are codes with no descriptions.If you want to capture only the diagnosis codes that have descriptions (existing desc nodes), you can enforce this rule with the following XPath expression:.//diag[name and desc]The problem though is that xml.etree.ElementTree supports a limited set of XPath features and for this particular expression to work, you need to switch to lxml.etree. But, it will come with a performance boost, better memory usage and a richer functionality. It's worth it.You can also simplify the way you extract codes by using findtext() and a dictionary comprehension:from pprint import pprintimport lxml.etree as ETdata = your XML hereroot = ET.fromstring(data)result = {diag.findtext(name): diag.findtext(desc) for diag in root.xpath(.//diag[name and desc])}pprint(result) |
_unix.360888 | I'm debugging an app for a client and I found the information from the DB which could be solution. I ask the client to extract it but unfortunately the client sent me the raw data in hexadecimal...I ask the client to resend me the plain text from the DB tools but awaiting their response I'm looking for a bash solution.I know the encoded data is a UTF-8 encoded string: is there a way to decode it with Unix tools? | How to get UTF8 from a hex variable? | ubuntu;character encoding | With xxd (usually shipped with vim)$echo 5374c3a97068616e650a | xxd -p -rStphaneIf your locale's charset (see output of locale charmap) is not UTF-8 (but can represent all the characters in the encoded string), add a | iconv -f UTF-8.If it cannot represent all the characters, you could try | iconv -f UTF-8 -t //TRANSLIT to get an approximation. |
_unix.285338 | What is the meaning of the ? sign in the following command?find /foo/path -name \? | find: meaning of the \? sign as a value of the name parameter | command line;find;wildcards | The ? is part of a mechanism called pathname expansion in the shell.Colloquially, the shell mechanism is called globing. The basic glob makes use just of three characters: * ? and [ that build patterns. An asterisk * means:Any character in any quantity (any string).A question mark (?) means:Any character one time.The square braces define a character list [ ], and mean:Only the characters inside the list counted once. There may exist negated lists.Those characters are used in a similar way in the command find. In find, they are called patterns.That means that there are two entities using the same characters to perform the same task (globing). One has to be told to ignore those characters. The usual way to tell the shell to avoid interpretation of special characters is to quote them. Either with 'single quotes', double quotes or with a backslash:'?'?\?That is why the patterns for find are quoted:find /path/foo -name \?What that line means is:List all files and directories starting from the directory /path/foo that have a name of only one character wide.about /Note that ? in find's pattern expansion may match a /.A pattern in find can match a / as specified by POSIX inside the operands section for the find command:-path pattern The primary shall evaluate as true if the current pathname matches pattern using the pattern matching notation described in Pattern Matching Notation. The additional rules in Patterns Used for Filename Expansion do not apply as this is a matching operation, not an expansion.Again: additional rules ... for Filename Expansion (as in a shell) do not apply as this is a matching operation, not an expansion.To show that this is true:$ mkdir test; cd test$ mkdir -p a/b/c/d$ find a -path 'a?b'a/b$ find . -path './a?b?c?d'./a/b/c/dOf course, the -name option of find will match the basename of a file. That, by definition, could not have a / as is not possible to match a / in a basename. |
_datascience.17204 | Here is a simple example:In a 3D space, if point A is the geocenter of a planet, point B is its north pole, and point C has a fixed latitude/longitude on the planet surface. Then the position of point C can be inferred from the position of A and B (using geodetic projection).Now assuming that I have thousands of points in the space, their incomplete relations are in a big multipgraph. I would like to deduce the position of a point that is initially unknown. What is the best algorithm to search search through all its relations and try to deduce it? | What is the best algorithm for deterministic belief propagation? | graphs;graphical model | null |
_reverseengineering.175 | I've seen this referenced in a couple of other questions on this site. But what's a FLIRT signature in IDA Pro? And when would I create my own for use? | What is a FLIRT signature? | ida;flirt signatures | FLIRT stands for Fast Library Identification and Recognition Technology.Peter explained the basics, but here's a white paper about how it's implemented:https://www.hex-rays.com/products/ida/tech/flirt/in_depth.shtmlTo address those issues, we created a database of all the functions from all libraries we wanted to recognize. IDA now checks, at each byte of the program being disassembled, whether this byte can mark the start of a standard library function. The information required by the recognition algorithm is kept in a signature file. Each function is represented by a pattern. Patterns are first 32 bytes of a function where all variant bytes are marked.It's somewhat old (from IDA 3.6) but the basics still apply.To create your own signatures, you'll need FLAIR tools, which can be downloaded separately.(FLAIR means Fast Library Acquisition for Identification and Recognition)The IDA Pro book has a chapter on FLIRT and using FLAIR tools. |
_codereview.9193 | In my time off I thought I'd implement some idiomatic data structures, starting with a linked list. Here's my current version: #include <iostream>using namespace std;struct node{int data;node *next;};void traverseList(node *head){ for(node *iterator = head ; iterator ; iterator = iterator->next) { cout << iterator->data << endl; } }int length(node *head){ int count = 0; for(node *iterator = head ; iterator ; iterator = iterator->next, count++) {} return count;}int main(){ //create the head of the list, assign it data node *head = new node; head->data = 0; //create a {1,2,3} list node *first = new node; node *second = new node; node *third = new node; //assign appropriate data first->data = 1; second->data = 2; third->data = 3; //assign pointees first->next = second; second->next = third; third->next = 0; //give the head the pointee head->next = first; traverseList(head); int listLength = length(head); printf(List Length: %d\n, listLength); return 0;}I've already changed the while loops I originally used (e.g.):void traverseList(node *head){ if(head != 0){ while(head->next !=0){ cout << head->data << endl; head = head->next; } //one extra for the node at the end cout << head->data << endl; }}to the for loops above. Is there anything else I should keep in mind? I'm following the Stanford CS linked list basics and problem set. | Linked List review | c++ | This is C++, not C. Therefore, your linked list class should contain the methods for operating on the list, and it shouldn't expose implementation details like nodes. For traversing the list, provide iterators. You should also make it a template so that it can be used with any typeThat's the general picture. More specifically:If you insist on traversing with a dedicated function for it, make it take a function (or functor!) so that anything can be done with the nodes.You've not created any mechanism for deleting the nodes. Your class should do that in its destructor.You're not doing a lot of error checking that you should be. That's not as relevant when you turn it into a class, but making sure head isn't null is very important. You're doing that in traverse now, but length also needs it.To summarise, if the user of your class sees a single pointer, you can be sure you're doing it wrong. |
_unix.87484 | After installing updates on Fedora 19 (kernel 10.3.7-200.fc19.x86_64) the DE freezes whenever I log in. Using the virtual consoles doesn't work.One time I even got this kernel panic:http://i.stack.imgur.com/h5q5n.jpgI have other kernels to try (10.3.5 and 10.3.3) and on them I don't get the freezes or the kernelpanics.Can you help me? | Kernel Panic after Fedora 19 Update | fedora;kernel;kernel panic;freeze | null |
_unix.88579 | In modern web browsers and other software with text content, Space scrolls down more or less a screenful. ShiftSpace scrolls up in everything but less.How can one use ShiftSpace to scroll up in less? Or alternatively, is there another pager (POSIX compatibility is my only requirement) that could do the job?I was told some terminal emulators, and some terminal UI libraries (ncurses?), don't recognize ShiftSpace. Is that a valid issue? | Shift-Space in less | terminal;less;pager | null |
_unix.352708 | I have the ~/.ssh/config file I'm using to manage different keys from different hosts.However, each time a new key is added, I'll need to also manually add this to ssh agent via ssh-add for separate reasons.Is there a way this can be achieved automatically? if yes, how?P.S: If it's any useful, I'm also using a macbook (osx) | Is it possible to auto copy keys from ssh config to ssh agent? how? | ssh;osx;ssh agent | null |
_codereview.128737 | I'm creating a counter picker for a game called League of Legends, and for this I need to compare effects of abilities, which each champion has. For this I'm using 4 lists of champions, the returnList, the banned champion list, the enemy champions list, annd the allied champion lists. However, seeing that the returnlist, where the champions get there points, contains around 120 instances, which all have 5 abilities, which in turn have around 5 effects each, I feel that my current solution of nesting foreach loops might be really slow. I was wondering how I could best optimise thisforeach (CounterChampion champion1 in enemyList){ foreach (CounterAbility ability1 in champion1.Abilities) { foreach (string effects1 in ability1.Effects) { foreach (CounterChampion champion2 in returnList) { foreach (string effects2 in champion2.Abilities.SelectMany(ability2 => ability2.Effects)) { if (CounterEffectExists(effects2, effects1, CounterEffect.EffectType.Counters)) { champion2.AddPoints(1); } if (CounterEffectExists(effects1, effects2, CounterEffect.EffectType.Counters)) { champion2.AddPoints(-1); } } } } }}foreach (CounterChampion champion1 in banList){ foreach (CounterAbility ability1 in champion1.Abilities) { foreach (string effects1 in ability1.Effects) { foreach (CounterChampion champion2 in returnList) { foreach (string effects2 in champion2.Abilities.SelectMany(ability2 => ability2.Effects)) { if (CounterEffectExists(effects1, effects2, CounterEffect.EffectType.Counters)) { champion2.AddPoints(1); } } } } }}foreach (CounterChampion champion1 in allyList){ foreach (CounterAbility ability1 in champion1.Abilities) { foreach (string effects1 in ability1.Effects) { foreach (CounterChampion champion2 in returnList) { foreach (string effects2 in champion2.Abilities.SelectMany(ability2 => ability2.Effects)) { if (CounterEffectExists(effects2, effects1, CounterEffect.EffectType.WorksWith)) { champion2.AddPoints(1); } if (CounterEffectExists(effects1, effects2, CounterEffect.EffectType.WorksWith)) { champion2.AddPoints(1); } } } } }}returnList.Sort( delegate (CounterChampion c1, CounterChampion c2) { return c1.GetPoints().CompareTo(c2.GetPoints()) * -1; });return returnList; | Optimise nested loops used to compare champions which have abilities which have effects | c#;performance | Well the inner loop is something like 120*5*5 => 1200 cycles and I really don't know if it can become an issue with today's PC power. But improvements can always be made, and reading your code, I see that some lines are duplicated : foreach (CounterChampion champion2 in returnList) { foreach (string effects2 in champion2.Abilities.SelectMany(ability2 => ability2.Effects)) {As as first step toward performance and code structuration, I suggest to compute the ability/effect in returnList once, and reuse it after. Typically, you may have something like this :class EffectByChampion{ CounterChampion Champion, List<string> Effects}then you may fill the following list ONCEList<EffectByChampion>and after you may reuse it 3 times through your existing code with : foreach (string effects1 in ability1.Effects) { foreach(EffectByChampion effectByChampion in EffectByChampionList) { foreach(string effects2 in effectByChampion)This way, you have 3 foreach loops removed. Hope this help ! |
_codereview.164086 | I have a registration form. Step 1 user creates an account. As user creates an account I need to authenticate user with the created account. in my account.service.ts I have following. Is this the best way to handle this? and how can improve this to handle errors from 2 different http calls? public createAccount(reg: CreateUserRequestModel): Observable<any> { return this.apiService.post('api/register/account', reg) .flatMap(()=>{ return this.authenticationService.authenticate(reg.emailAddress, reg.password) }).map((response)=>{ return response.json() }) .catch((error: any) => { return Observable.throw(error.json()); }); } | Angular 2 / rxjs chaining HTTP calls | http;typescript;rxjs;angular 2+ | null |
_unix.175801 | Can someone tell me a command that will find my external ip for a freebsd 10 system. | How to find public ip for a freebsd system | freebsd;ip | Personally, I use wtfismyip.com which returns pure text and does not need parsing:$ wget -qO - http://wtfismyip.com/text123.456.78.9 |
_webapps.107839 | I have a document in Word Online. When the document is downloaded to the desktop to be opened with regular Word, it seems that all comments are stripped from it. Is there a way to download a document from Word Online without losing comments? | Downloading Word Online documents strips comments? | word online | null |
_webapps.98554 | I am a school secretary. I created a master schedule in sheets. Based on that schedule, I sent a separate sheet to each teacher to create their own personal schedule. I created tabs and cut and paste each personal schedule into a specific tab/sheet labeled with that teacher's name. I did not want to cut and paste. I wanted to insert their actual document as a tab in the master file. How would I go about doing that? | Insert document as tab in master spreadsheet | google spreadsheets | null |
_webmaster.21597 | Many popular JS/CSS frameworks are offered via Google's Libraries API (jQuery, Dojo, MooTools etc.). Yahoo also hosts it's own YUI toolkit, as do many others.Do any high volume/traffic sites actually rely on these externally-hosted resources (without hosting their own copies)? It seems like a great service to leverage, although in my experience I've often encountered these libraries packaged along with the projects I've worked on.What's the most common practice here? Moreover, is it safe and reliable (based on experience) to use these externally? | Is it common, or smart, for high-traffic sites use externally-hosted js/css frameworks? | google;web hosting;jquery;yahoo | It is quite common, and for high traffic websites certainly using a Content Delivery Network is sound advice, it takes the strain off your main server whilst making sure users get static content quickly.There is the added benefit that if I visit site A that uses say the Google hosted jQuery and then visit site B that does the same, I will have cached it from site a and will not need to download it again.The downside is that you are relying on other networks having the same uptime you do, the Amazon outages have proved that nothing has 100% uptime. |
_webapps.58321 | Why does Gmail frequently ask for my password? It rarely did this until I changed my password. | Why does Gmail frequently ask for my password? It started when I changed my password | gmail | null |
_softwareengineering.246276 | At work, one of my projects is mostly about taking data passed in from an external client and persisting it in a database. It's a Java enterprise app using JPA and most of our logic revolves around CRUD operations. The majority of our bugs involve JPA in one way or another. Example 1: If you click the save button twice, JPA might try to insert the same entity into the database a second time, causing a primary key violation.Example 2: You retrieve an entity from the database, edit it and try to update its data. JPA may try to create a new instance instead of updating the old one. Often the solution is needing to add/remove/change a JPA annotation. Other times it has to do with modifying the DAO logic. I can't figure out how to get confidence in our code using unit tests and TDD. I'm not sure if it's because unit tests and TDD are a bad fit, or if I'm approaching the problem wrong.Unit tests seem like a bad fit because I can only discover these problems at runtime and I need to deploy to an app server to reproduce the issues. Usually the database needs to be involved which I consider to be outside the definition of a unit test: These are integration tests.TDD seems like a bad fit because the deploy + test feedback loop is so slow it makes me very unproductive. The deploy + test feedback loop takes over 3 minutes, and that's just if I run the tests specifically about the code I'm writing. To run all the integration tests takes 30+ minutes.There is code outside this mold and I always unit test that whenever I can. But the majority of our bugs and the biggest time sinks always involve JPA or the database.There is another question that is similar, but if I followed the advice I'd be wrapping the most unstable part of my code (the JPA) and testing everything but it. In the context of my question, I'd be in the same bad situation. What's the next step after wrapping the JPA? IMO that question is (perhaps) a step to answer my question, but not an answer to it. | How can I use unit tests and TDD to test an app that relies mostly on database CRUD operations? | java;unit testing;tdd;jpa | null |
_unix.339210 | I was able to locale libnl (and few of its child) in /usr/lib64. I'd like to install libnl3-devel-3.2.29-2.fc25.x86_64.rpm there BUT my current version of libnl is an earlier version (3.2.27..) So I'm having trouble ...dnf libnl is not working...I'm doing all this to install aircrack-ng Could you help me install it (especially libnl-3-dev and libnl-genl-3-dev) ? | How to update libnl in Fedora? | software installation | You did not mentioned which distro you have; is it Fedora 24 ? I have Fedora 25. I ran just now dnf update, and after it completed (it took about 20 minutes), running rpm -q libnl3 gives libnl3-3.2.29-2.fc25.x86_64, which is what you want.I need to add that before running dnf update I had libnl3-3.2.28-3.fc25.x86_64 and not 3.2.27 as you. Regarding libnl-3-dev and libnl-genl-3-dev: these are Ubuntu/Debian packages, not Fedora/CentOs packages. I installed the parallel libnl3-devel Fedora package (again on this F25 machine) by dnf install libnl3-devel, and it installed libnl3-devel-3.2.29-2.fc25.x86_64. Not sure about libnl-genl-3-dev.Rami Rosen |
_webapps.43238 | Is it possible to host a website for example in Amazon Cloud and have my domain point there, but have the same domain installed with Gmail for mail support? | Is it possible to host in the cloud but have email in Gmail? | gmail;amazon;amazon ec2 | null |
_softwareengineering.133368 | If in a web app, let's say an app that has a table with stored street address (Strings), the admin of the app will be adding data often to grow his archive.The table (MySQL) has a primary key with AUTO_INC.The web app allows the users to add addresses themselves. Once a user enters an address say X, ALL of the users of the application will be able to see the address X when searching for available addresses.What if, since address is a string, a user stores inappropriate content(like bad words, for example)? This might offend some users and push them to stop using the app.So I was thinking of what would be better:Storing user input in a separate table (pending input), until the admin approves them and then they're moved the official table?Or store the inputs in same table of the admin's inputs table, but put a temporary flag on each entered record (by the users) so that they are only visible to that user until the admin approves them?On a side note, is it logical to limit each user to have a specific amount of input addresses per day that they can add (some spammers might fill the table with thousands of useless records)? | Is it bad practice to store user input in the same table where the admin stores data? | web applications;database design;user experience | I would always put data of the same type in one table and rather add some simple columns with flags in a single table. This will make adding new features to your system in a later stage probably much easier to accomplish. Especially if other developers will be working on the project.The problem with a limited amount of submissions by users, is that you limit the most active users. You can follow the StackExchange philosophy. The first time a user adds an address, it first needs to be approved. Then you can create a trusted base of users, and there is no reason to restrict those users at all. Don't make it to complicated however. Dividing users in new users and trusted users should be enough, if you also add some opportunity for regular users to report spam-input with a simple button. Do not make your system more restricted than necessary, that will scare of potential active users. |
_webmaster.86984 | A Google Analytics account I have access to seems to completely ignore visits from handheld devices.I originally noticed as the traffic count from handheld was only 15, compared to the thousands received on desktop. I've visited the site from tablets and mobiles while viewing Realtime, and it doesn't show up.I was worried that it was classing these visits as desktop, but it actually seems that they just aren't getting tracked at all.I've also noticed that the URL structure is different to anything I've seen before. Instead of domain.com/services, it's services/domain.com - which is a 404 page. However it does appear that Analytics is tracking visits to the actual page, just displaying the URL incorrectly. Could these two issues be connected? | Google Analytics Not Tracking Mobile Visitors | google analytics;google tag manager | null |
_cs.47622 | I am confused in finding RAW dependencies whether we have to find only in adjacent instructions or non-adjacent also.consider the following assembly code I1: ADD R1 , R2, R2; I2: ADD R3, R2, R1;I3: SUB R4, R1 , R5;I4: ADD R3, R3, R4;FIND THE NUMBER OF READ AFTER WRITE(RAW) DEPENDENCIES IN THE Above Code.I am getting 2 dependency I2-I1 and I4-I3. | Read After Write(RAW) hazard | computer architecture;cpu pipelines | null |
_webapps.14178 | I am using Firefox. Whenever I typemy questions on stackexchangesites, there will be automatic spellchecking. Does this function comesfrom Firefox, or from stackexchangesites, or somewhere else?If it comes form Firefox, why isthere no spell checking when I typein some other websites? Just offyour head, in what cases, there willbe spell checking and in what casesthere will be no?American English and British Englishmay spell some words in differentways. For example, if I typeoptimization, it will beautomatically underscored to let meknow the spelling is wrong. How canI make the spell checking tool torecognize American English spelling?Thanks and regards! | Where does the spell checking function comes from? | spell check | As I type this answer on webapps.stackexchange.com, Firefox is providing the spell checking.It depends on the website. I suspect that any site that uses standard textarea tags will allow Firefox to spell-check it. Google Docs, on the other hand, uses its own custom spell checker.Right-click a misspelled word. Select Languages and make sure English / United States is selected. If you don't see it there, select Add Dictionaries... and install the English (US) dictionary. |
_unix.144371 | I would like to run xkbcomp upon a user login in order to modify its keyboard. The command works fine from a terminal after login. The system is an unmodified Fedora 20 Desktop Edition.I tried to add the command (with full paths) to gnome-session-properties$HOME/.xinitrcI also added an additional entry to /etc/xdg/autostart/:[Desktop Entry]Type=ApplicationName=Programmers on AZERTYExec=/usr/bin/xkbcomp /home/w/azerty_prog.xkb $DISPLAYX-GNOME-Autostart-enabled=trueNone of these work, the keyboard is not modified (I do not know where logs are located). Where should I add this entry? | How to start a command upon login in GNOME? | gnome;login;xkb | null |
_unix.237269 | I can echo to /dev/tty1: echo hello > /dev/tty1I can display an image (while booting or not): fbi -T 1 -noverbose -a test.pngI can display the image after printing hello to the console, but I can not print anything after displaying an image. How can I print to the console after displayin an image? | How to echo tty1 after displaying an image via fbi? | tty;fbi | null |
_codereview.27901 | Resharper thinks I should change thiswhile (dockPanel.Contents.Count() > 0)to the following:while (dockPanel.Contents.Any())Without thinking twice about it, I switched to the any version because .Any() is more readable for me. But a coworker of mine sees the change and asked why I did it. I explained that this improves readability but his objection was the following:Any is an ambiguous word.People may not be familiar with LINQ, so they might not be aware of what Any does at first glance.Count > 0 is universal. You don't have to know C# to find out what you're trying to do.The confusion is probably compounded by the fact that I'm working overseas. People here speak little to no English here.Which method should I stick with? | List Any vs Count, which one is better for readability? | c# | For me, it's about intent. What does your code's business logic say if you read it in English (or your native language)?It usually comes to me as If there are any employees who are in the management role, then show a particular option panel.And that means .Any(). Not .Count(). Very few times will I find myself using .Count() unless the underlying rule talks about more than one or more than two of something.As a bonus, .Any() can be a performance enhancement because it may not have to iterate the collection to get the number of things. It just has to hit one of them. Or, for, say, LINQ-to-Entities, the generated SQL will be IF EXISTS(...) rather than SELECT COUNT ... or even SELECT * .... |
_webapps.86782 | I periodically send out emails to our team to check in on from entries that have a specific field set to No. And after they complete a certain task then need to change that entry to Yes. The easiest way I've found to do this is to have them go to the form edit URL and just change the last question themselves.However, to make it easier, I would like to auto-fill that change that final questions to a Yes instead of a No through the Edit URL.Is this possible? If this is not possible, any suggestions for a more user-friendly way to edit a response? If I could generate a link that runs a script with a unique identifier that would work as well, or even a link that causes the specific spreadsheet cell to change would work too. | Can I auto-fill an answer on a form edit URL? | google forms | I figured that out rather quickly.If you take your form URL:docs.google.com/a/mydomain/forma/d/uniqueFormString/viewform?edit2=uniqueEditStringGet your elements number and value by getting a pre-filled URL. ie. &entry.688631299=Yes and insert it right after the viewform? and append a & after your elements number and value.The URL should look like: docs.google.com/a/mydomain/forma/d/uniqueFormString/viewform?&entry.688631299=Yes&edit2=uniqueEditStringGo to that URL and the specific question will be changed. Now if I could just figure out how to auto-submit the form to make it even easier. |
_webmaster.74681 | Whenever I create a Responsive Website I usually create 2 menus: 1 hidden and used for mobile and the other displayed as the main menu, then hidden to show the mobile menu. Whenever it comes to SEO and spiders navigating the website do I get dinged for having duplicate menus? Is there anything I can do to indicate to the spider that this menu is for mobile and this is the main? The end reason why I have 2 different menus are because of location, usually the main menu is in some kind of bar underneath the logo etc, but the mobile menu I want on top of everything, so above the logo etc. | SEO - Responsive Website and Duplicated Menus | seo;web crawlers;googlebot;navigation | You have nothing to worry about. You can use display: none; to switch menus. Search engines are much better at understanding JS and CSS. As long as you are not intentionally trying to manipulate things to get a better ranking. Using display: none; to hide big blocks of text will get you penalized. So if you are only using to hide your desktop menu on mobile and visa verse you are not in any danger. Take a look a this old thread from StackExchange: How bad is it to use display: none in CSS?Google is actually quite fond of responsive design and prefers it to a separate mobile site.Here is a good article on SEO of Responsive DesignAlso, check out this article/video:Matt Cutts (Google), said that you dont have to worry about there being a down side, related to SEO, when using a responsive design approach for mobile web sites. |
_webapps.9191 | On two computers now, I have a strange recurring visual formatting bug when accessing Gmail using Firefox. One email, usually towards the bottom of the page, has a blue block over the date. I have reloaded multiple times and cleared out the gmail cookies. I have even cleared out the entire cache, but the problem persists. Any ideas what is causing this? | Fix formatting issue with Gmail on Firefox | gmail;firefox | Typical, no sooner do I post the issue, than I work out what was causing it. It was the google calendar gadget from the google labs settings page. The badly formatted email was in line with the top of the gadget. |
_unix.165160 | Let's say you want to cat the contents of a really big file, but want to view it a few bits at a time. Let's say one were to do the following:$ cat /dev/sda1 | lessAs a programmer of languages such as Java and ActionScript, when I look at that code I imagine Bash first running the command cat /dev/sda1 (loading everything the command returns into RAM), and then running the command less which has access to that really big pseudo-variable represented as -.Is that the way Bash does things (meaning that command is a really bad idea if the file is larger than the amount of RAM on your system, and you should use another command), or does it have a way of optimising the piping of large amounts of data? | How does Bash pipe large amounts of data? | bash;pipe;less | null |
_codereview.116846 | I'm using BFS to see if a given path exists in a graph:static class Node{ int data; Node next; public Node(int data){ this.data = data; }}//Adjency List to store the reference to head of each Node/Verticestatic class AdjList implements Iterable<Integer>{ Node head; public void add(int to){ if(head==null){ head = new Node(to); }else{ Node temp = head; while(temp.next!=null) temp = temp.next; temp.next = new Node(to); } } //Used to iterate over the adjacency list while BFS @Override public Iterator<Integer> iterator(){ Iterator<Integer> it = new Iterator<Integer>(){ Node temp = head; @Override public boolean hasNext(){ return temp!=null; } @Override public Integer next(){ Node toRet = temp; temp = temp.next; return toRet.data; } @Override public void remove(){ throw new UnsupportedOperationException(); } }; return it; }}static class Graph{ AdjList[] lists; int numberOfNodes; public Graph(int numberOfNodes){ lists = new AdjList[numberOfNodes]; this.numberOfNodes = numberOfNodes; for(int i=0; i<numberOfNodes; i++){ lists[i] = new AdjList(); } } //Adds edge from/to vertice public void addEdge(int from, int to){ lists[from].add(to); } public boolean BFS(int from, int to){ LinkedList<Integer> queue = new LinkedList<>(); queue.add(from); boolean[] visited = new boolean[numberOfNodes]; visited[from]= true; while(!queue.isEmpty()){ if(visited[to]==true) return true; int curr = queue.poll(); System.out.print(curr + ); Iterator<Integer> iter = lists[curr].iterator(); while(iter.hasNext()){ int currVal = iter.next(); if(visited[currVal]==false){ queue.add(currVal); visited[currVal]=true; } } } return false; }}public static void main(String[] args) { Graph myGraph = new Graph(3); myGraph.addEdge(0, 1); myGraph.addEdge(1,2); myGraph.addEdge(2,1); System.out.println(Path from 2 to 0 exists : + Boolean.valueOf(myGraph.BFS(2,0)));}I could've used DFS for the same purpose which requires lesser memory than BFS, but since my Graph was pretty small, it wouldn't have made much of a difference. Apart from that, under what circumstances should I prefer either of them? | Check if a given path exists in a graph | java;graph | Regarding the code, I'd have only 2 suggestions:Use brackets even for single-line ifs. It improves readability and makes the code less error prone.Try not to shorten member names too much (like iter or it for example). It improves readability.As for the chosen algorithm and possible alternative I'd suggest Iterative Deepening DFS. It has the best of both Depth-First Search and Breadth-First Search - it's complete, finds the optimal solution, and doesn't use too much space.Let me know if anything's unclear. |
_webmaster.43077 | I am based in Europe and I would like to test my website as if I am located in New York.I have some specific features that will be visible based on cities. | How can I change the location of my ip address to specific citiies/places when browsing? | ip address | null |
_unix.264783 | I want to install a teamspeak on my root server, but after downloading the tar file, I cannot extract it.I use the commandtar -xzvf teamspeak3-server_linux_amd64-3.0.12.2.tar.bz2I also know that you don't need the hyphen/dash before the xzvf but I use it.Still I get a message that says the file doesn't exist although it is listed when I check with lsI get this error:tar (child): v: Funktion open fehlgeschlagen: Datei oder Verzeichnis nicht gefun dentar (child): Error is not recoverable: exiting nowtar: Child returned status 2tar: Error is not recoverable: exiting now | Why does my tar not work? | linux;tar | The z option is for .tar.gz (gzipped) files.bzip2'd files (the .bz2 suffix) use a different tar option: j.Trytar -xjvf teamspeak3-server_linux_amd64-3.0.12.2.tar.bz2or (auto-detection has been around a couple of years)tar -xvf teamspeak3-server_linux_amd64-3.0.12.2.tar.bz2Further reading:Compression support |
_unix.12865 | I have a CentOS server with RAID5. Every time RAID5 re-syncs my server stop working. The hosting company stopped the httpd service so that RAID5 can re-sync itself, a process which can take as long as 3-4 hours.The problem reoccurs frequently, so the Hosting company swaped my server hardware and I migrated to new hardware. I still have this problem (on the new server).Is this something normal in RAID5? How can we solve this issue permanently? If every time RAID5 wants to re-sync my server overloads and my website will not be accessible, then RAID5 sucks.I would really appreciate if you can suggest a solution for this disaster.Here is /proc/mdstat report:root@host [~]# watch 'cat /proc/mdstat'Every 2.0s: cat /proc/mdstat Mon May 9 01:25:30 2011Personalities : [raid1]md0 : active raid1 xvda1[0] xvdb1[1] 104320 blocks [2/2] [UU]md1 : active raid1 xvda2[0] xvdb2[1] 2096384 blocks [2/2] [UU]md2 : active raid1 xvda5[0] xvdb5[1] 484086528 blocks [2/2] [UU] [=====>...............] resync = 29.5% (142978880/484086528) finish=77.7min speed=73108K/secunused devices: <none> | Problem with RAID5 | centos;raid5 | RAID should only resync after a server crash or replacing a failed disk. It's always recommended to use a UPS and set the system to shutdown on low-battery so that a resync won't be required on reboot. NUT or acpupsd can talk to many UPSes and initiaite a shutdown before the UPS is drained. If the server is resyncing outside of a crash, you probably have a hardware issue. Check the kernel log at /var/log/kern.log or by running dmesg. I also recommend setting up mdadm to email the adminstrator and running smartd on all disk drives similarly set up to email the administrator. I receive an email about half the time before I see a failed disk. If you are having unavoidable crashes, you should enable a write-intent bitmap on the RAID. This keeps a journal of where the disk is being written to and avoids a full re-sync on reboot. Enable it with:mdadm -G /dev/md0 --bitmap=internal |
_unix.175806 | I'm on OS X Yosemite, ran this code:unsigned long num_;sysctl((int[]){CTL_HW, HW_PHYSMEM}, 2, &num_, &len, NULL, 0);printf(AMT MEM: , %lu\n, num_);and getting back 140735340871680Which doesn't make sense: (in IPython 3)In [3]: mem / (1024 ** 3)mem / (1024 ** 3)Out[3]: 131070.0Since I have 16 GB of physical memory. I looked at the header for sysctl.h and see#define HW_PHYSMEM 5 /* int: total memory */#define HW_USERMEM 6 /* int: non-kernel memory */So now this really doesn't make sense, I could believe the figure if I passed HW_USERMEM, but I specially asked for total memory. What gives?Did I do some stupid math mistake in the Python code? | Accounting for missing memory from sysctl | osx;memory | Did I do some stupid math mistake in the Python code?Actually, it's your C code that's wrong.The most direct fix to your code is this:#include <stdio.h>#include <sys/sysctl.h>int main(void){ int64_t bytes; size_t len = sizeof(bytes); sysctl({ CTL_HW, HW_PHYSMEM64 }, 2, &bytes, &len, NULL, 0); int megs = bytes / 1024 / 1024; printf(AMT MEM: %d MiB\n, megs);}If you use HW_PHYSMEM instead, it only works on machines with up to 2 GiB of RAM, since it is storing a count of bytes into a variable that is assumed to be 32 bits in size. The change to a 64-bit argument requires a new sysctl value to avoid breaking backwards compatibility. This is why OpenBSD's sysctl(3) man page says HW_PHYSMEM is obsolete.I took a few liberties in the code above. I'm doing part of the math in the C code so I can read the output without feeding it through a calculator. I also fixed several integer type warnings and renamed the num_ variable to bytes for clarity.That code runs fine on some of the BSDs, but not on OS X or FreeBSD.On looking at the OS X man page, it seems they want you to use sysctlbyname(3) instead. This works fine here on Yosemite:#include <stdio.h>#include <sys/sysctl.h>int main(void){ int64_t bytes; size_t len = sizeof(bytes); sysctlbyname(hw.memsize, &bytes, &len, NULL, 0); int megs = bytes / 1024 / 1024; printf(AMT MEM: %d MiB\n, megs);}I have 16 GiB of physical RAM, and it correctly reports 16384 MiB.If you try that on FreeBSD, though, you get 0 as an answer. A bit of poking around says that it wants hw.physmem instead.And once again we hit a wall, because trying that sysctlbyname value on OS X gives the sort of bogus results you found.Therefore, the bottom-line answer is that all of this is highly system-specific. If you need it to be cross-platform, you will need a lot of #ifdefs.Footnotes:Sorry, I don't have my powers of 2 memorized into the billions yet. :)Tested on OpenBSD 5.5 and NetBSD 6.0.1. |
_softwareengineering.242811 | I used to analyse performance of programmers in my team by looking at the issues they have closed. Many of the issues are of course bugs. And here another important performance aspect comes - who introduced the bugs. I am wondering, if creating a custom field in the issue tracking system Blamed for reporting the person who generated the problem, is a good practice.One one hand it seems ok to me to promote personal responsibility for quality and this could reduce the additional work we have due to careless programming. On the other hand this is negative, things are sometimes vague and sometimes there is a reason such us this thing had to be done very quickly due to a client's.... What to you think? | Is it good practice to analyse who introduced each bug? | code quality;issue tracking;bug report | null |
_codereview.54933 | This is a continuation of this question, v3 can be found hereTaking into account the advise given by Loki, an implementation of the threadpool using a std::condition_variable to control when threads wakeup is presented below. Using this, the test program eventually deadlocks, the time before deadlock occurs is directly related to the number of tasks in pre-allocation. This must mean that there is a problem in waking the threads when work has arrived, but I cannot identify why it is happening.This behaviour has currently been disabled by the USE_YIELD pre-compiler define.threadpool.hpp#ifndef THREADPOOL_H#define THREADPOOL_H#include <atomic>#include <condition_variable>#include <functional>#include <future>#include <mutex>#include <thread>#include <vector>#include <boost/lockfree/queue.hpp>#define USE_YIELDclass threadpool{public: // constructors // // calls threadpool(size_t concurrency) with: // // concurrency - std::thread::hardware_concurrency() threadpool(); // calls threadpool(size_t concurrency, size_t queue_size) with: // // concurrency - concurrency // queue_size - 128, arbitary value, should be sufficient for most // use cases. threadpool(size_t concurrency); // creates a threadpool with a specific number of threads and // a maximum number of queued tasks. // // Argument // concurrency - the guaranteed number of threads used in the // threadpool, ie. maximum number of tasks worked // on concurrently. // queue_size - the maximum number of tasks that can be queued // for completion, currently running tasks do not // count towards this total. threadpool(size_t concurrency, size_t queue_size); // destructor // // Will complete any currently running task as normal, then // signal to any other tasks that they were not able to run // through a std::runtime_error exception ~threadpool(); threadpool(const threadpool &) = delete; threadpool(threadpool &&) = delete; threadpool & operator=(const threadpool &) = delete; threadpool & operator=(threadpool &&) = delete; // run // // Runs the given function on one of the thread pool // threads in First In First Out (FIFO) order // // Argument // task - function or functor to be called on the // thread pool. // // Result // signals when the task has completed with either // success or an exception. Also results in an // exception if the thread pool is destroyed before // execution has begun. std::future<void> run(std::function<void()> && task);private: struct task_package { public: std::promise<void> completion_promise; std::function<void()> task; }; // Have to use 'task_package *' since a trivial destructor is // required, 'task_package' and 'std::unique_ptr<task_package>' // do not satisfy. boost::lockfree::queue<task_package *> tasks; std::vector<std::thread> threads; std::atomic<bool> shutdown_flag;#ifndef USE_YIELD volatile bool wakeup_flag; std::condition_variable wakeup_signal; std::mutex wakeup_mutex;#endif inline bool pop_task(std::unique_ptr<task_package> & out);};#endifthreadpool.cpp#include threadpool.hpp#include <algorithm>#include <exception>#include <utility>template<typename T>constexpr T zero(T){ return 0;}threadpool::threadpool() : threadpool(std::thread::hardware_concurrency()){ };threadpool::threadpool(size_t concurrency) : threadpool(concurrency, 128){ };threadpool::threadpool(size_t concurrency, size_t queue_size) : tasks(queue_size), shutdown_flag(false), threads()#ifndef USE_YIELD ,wakeup_flag(false), wakeup_signal(), wakeup_mutex()#endif{ // This is more efficient than creating the 'threads' vector with // size constructor and populating with std::generate since // std::thread objects will be constructed only to be replaced threads.reserve(concurrency); for (auto a = zero(concurrency); a < concurrency; ++a) { // emplace_back so thread is constructed in place threads.emplace_back([this]() { // checks whether parent threadpool is being destroyed, // if it is, stop running. while (!shutdown_flag.load()) { auto current_task_package = std::unique_ptr<task_package>{nullptr}; // use pop_task so we only ever have one reference to the // task_package if (pop_task(current_task_package)) { try { current_task_package->task(); current_task_package->completion_promise.set_value(); } catch (...) { // try and tell the owner that something bad has happened... try { // ...but this can also throw, so stay protected current_task_package->completion_promise.set_exception(std::current_exception()); } catch (...) { } } } else { // rather than spinning, give up thread time to other things#ifdef USE_YIELD std::this_thread::yield();#else auto lock = std::unique_lock<std::mutex>(wakeup_mutex); wakeup_flag = false; wakeup_signal.wait(lock, [this](){ return wakeup_flag; });#endif } } }); }};threadpool::~threadpool(){ // signal that threads should not perform any new work shutdown_flag.store(true);#ifndef USE_YIELD { std::lock_guard<std::mutex> lock(wakeup_mutex); wakeup_flag = true; wakeup_signal.notify_all(); }#endif // wait for work to complete then destroy thread for (auto && thread : threads) { thread.join(); } auto current_task_package = std::unique_ptr<task_package>{nullptr}; // signal to each uncomplete task that it will not complete due to // threadpool destruction while (pop_task(current_task_package)) { try { auto except = std::runtime_error(Could not perform task before threadpool destruction); current_task_package->completion_promise.set_exception(std::make_exception_ptr(except)); } catch (...) { } }};std::future<void> threadpool::run(std::function<void()> && task){ auto promise = std::promise<void>{}; auto future = promise.get_future(); // ensures no memory leak if push throws (it shouldn't but to be safe) auto package = std::make_unique<task_package>(); package->completion_promise = std::move(promise); package->task = std::forward<std::function<void()> >(task); tasks.push(package.get()); // no longer in danger, can revoke ownership so // tasks is not left with dangling reference package.release();#ifndef USE_YIELD { std::lock_guard<std::mutex> lock(wakeup_mutex); wakeup_flag = true; wakeup_signal.notify_all(); }#endif return future;};inline bool threadpool::pop_task(std::unique_ptr<task_package> & out){ task_package * temp_ptr = nullptr; if (tasks.pop(temp_ptr)) { out = std::unique_ptr<task_package>(temp_ptr); return true; } return false;}main.cpp#include <iostream>#include <chrono>#include <queue>#include <numeric>#include threadpool.hppthreadpool pool1;threadpool pool2;// pool3 is used as a parasite, increasing the number threads it uses// pronounces the negative effect of spinningthreadpool pool3(4 * std::thread::hardware_concurrency());std::atomic_flag cout_flag = ATOMIC_FLAG_INIT;int main(){ auto results1 = std::queue< std::future<void> >(); auto results2 = std::queue< std::future<void> >(); auto lambda1 = []() { while (cout_flag.test_and_set(std::memory_order_acquire)) ; std::cout << running on pool1 threadid: << std::this_thread::get_id() << std::endl; cout_flag.clear(std::memory_order_release); }; auto lambda2 = []() { while (cout_flag.test_and_set(std::memory_order_acquire)) ; std::cout << running on pool2 threadid: << std::this_thread::get_id() << std::endl; cout_flag.clear(std::memory_order_release); }; auto times = std::vector<std::chrono::nanoseconds>{}; times.reserve(10000); for (int j = 0; j < 10000; ++j) { cout_flag.test_and_set(std::memory_order_acquire); std::cout << round << j << std::endl; for (unsigned u = 0; u < 3; ++u) { results1.push(pool1.run(lambda1)); results2.push(pool2.run(lambda2)); } int i = 0; auto start = std::chrono::steady_clock::now(); cout_flag.clear(std::memory_order_release); // main loop while (i++ < 100) { auto & future1 = results1.front(); future1.get(); results1.pop(); results1.push(pool1.run(lambda1)); auto & future2 = results2.front(); future2.get(); results2.pop(); results2.push(pool2.run(lambda2)); } while (!results1.empty()) { results1.front().get(); results1.pop(); } while (!results2.empty()) { results2.front().get(); results2.pop(); } auto finish = std::chrono::steady_clock::now(); times.push_back(finish - start); } auto average = std::accumulate(std::begin(times), std::end(times), std::chrono::nanoseconds{}) / (206 * times.size()); std::cout << Average time per task: << static_cast<double>(average.count()) / 1000 << us << std::endl;}Are there any issues, improvements or fixes to the non-yield code that you can see? | Platform independant thread pool v2 | c++;multithreading;thread safety;reinventing the wheel;c++14 | OK some fixes to stop you getting trapped:You were getting stuck because you could notify_all() and wake the threads in the condition variable. Then after the notification another thread can set wakeup_flag to false thus trapping the threads in the condition variable.ExampleThread 1: is at the line:auto lock = std::unique_lock(wakeup_mutex);But is unscheduled before it starts executing this line (for another processes).Thread 2: (the main thread) now enters the destructor (set shutdown_flag) and the then locks mutex wakeup_mutex.Thread 1: Even if thread 1 wakes up now. It can not proceed because of the lock.Thread 2: Proceeds. Sets wakeup_flag to true and notify_all() waiking all threads on the condition variable; thus releasing them. It releases the lock. and continues in the destructor.Thread 1: Can now proceed. It set wakeup_flag to false. And then wait() on the condition variable. It will never be woken up as it missed the notify_all().Thread 3/4/5/6/7/8: Wake up (as they were waiting on condition variable and did receive the notify_all()). So they start to execute. But before they are released they all check wakeup_flag which is now false so go back to waiting on the condition variable.The same scenario can apply to run(). In the above scenario replace destructor and run() and you get jobs left on the queue with nobody working on them.Don't use another variable wakeup_flag to keep the state where you should run in. You already have two of these. tasks.empty() and shutdown_flag. These should be what you test against. auto lock = std::unique_lock<std::mutex>(wakeup_mutex); wakeup_signal.wait(lock, [this]() { return !tasks.empty() // Wake if there are jobs || shutdown_flag.load(); // Or we are shutting down });Once you do this you don't need to wake all the threads when you add a new task. Just wake one of them.std::future<void> threadpool::run(std::function<void()> && task) { // STUFF // Don't need this anymore (as you are not manipulating state) // std::lock_guard<std::mutex> lock(wakeup_mutex); wakeup_signal.notify_one(); // Changed from notify_all |
_unix.188007 | Upgrading kernel manually on Ubuntu 14.04 can cause trouble with NVIDIA drivers? (one of the troubles could be booting to black screen)I had lot of trouble with installing NVIDIA graphics drivers and getting it work, I had to reinstall my Ubuntu 14.04 four times.Few reasons were installing nvidia*.run file and booting to black screen, or installing Intel Graphics for Linux and booting to black screen etc. I am tired of solving those problems.I am want to know if there could be any problem before upgrading Linux kernel. Any advice would help | Is it safe to upgrade kernel manually on a system which is using NVIDIA drivers? | linux kernel;kernel modules;nvidia | Not always, newer versions of kernel may not be able to build DKMS modules with nvidia because of which nvidia drivers may not work when booted with that kernel.As of 25 April 2015 I tried to install Linux kernel v4 which failed to work with nvidia so I had to remove it. |
_codereview.64887 | For the queries mentioned in link in 3 parts, the first two parts have been addressed, as mentioned below:Part I (6 points)list/DList.java contains a skeleton of a doubly-linked list class. Fill in themethod implementations.Note: node is passed in these methods so that user of class DList can avoid slow \$O(n)\$ method to access each successive element.Answer to Part I: Filled in methods insertFront() insertBack() front() back() next() prev() insertAfter() insertBefore() remove() in the below code.Part II (1 point)Our ADT is not as well protected as we would like. There are several ways by which a hostile (or stupid) application can corrupt our DList (i.e., make itviolate an invariant) through method calls alone.Answer to Part II: Added a member protected DList listp in class DListNode to make sure that user passes the node which is actually part of the list instead of some junk node. This is one way list can be avoided from corruption. Please find class DListNode below./* DList.java */package list;/** * A DList is a mutable doubly-linked list ADT. Its implementation is * circularly-linked and employs a sentinel (dummy) node at the head * of the list. * * DO NOT CHANGE ANY METHOD PROTOTYPES IN THIS FILE. */public class DList { /** * head references the sentinel node. * size is the number of items in the list. (The sentinel node does not * store an item.) * * DO NOT CHANGE THE FOLLOWING FIELD DECLARATIONS. */ protected DListNode head; protected int size; /* DList invariants: * 1) head != null. * 2) For any DListNode x in a DList, x.next != null. * 3) For any DListNode x in a DList, x.prev != null. * 4) For any DListNode x in a DList, if x.next == y, then y.prev == x. * 5) For any DListNode x in a DList, if x.prev == y, then y.next == x. * 6) size is the number of DListNodes, NOT COUNTING the sentinel, * that can be accessed from the sentinel (head) by a sequence of * next references. */ /** * newNode() calls the DListNode constructor. Use this class to allocate * new DListNodes rather than calling the DListNode constructor directly. * That way, only this method needs to be overridden if a subclass of DList * wants to use a different kind of node. * @param item the item to store in the node. * @param prev the node previous to this node. * @param next the node following this node. */ protected DListNode newNode(Object item, DListNode prev, DListNode next, DList listp) { return new DListNode(item, prev, next, listp); } /** * DList() constructor for an empty DList. */ public DList() { this.head = new DListNode(Integer.MIN_VALUE, null, null, null); this.head.next = this.head; this.head.prev = this.head; this.head.listp = this; this.size = 0; } /** * isEmpty() returns true if this DList is empty, false otherwise. * @return true if this DList is empty, false otherwise. * Performance: runs in O(1) time. */ public boolean isEmpty() { return size == 0; } /** * length() returns the length of this DList. * @return the length of this DList. * Performance: runs in O(1) time. */ public int length() { return size; } /** * insertFront() inserts an item at the front of this DList. * @param item is the item to be inserted. * Performance: runs in O(1) time. */ public void insertFront(Object item) { this.head.next = newNode(item, this.head, this.head.next, this); if(this.size==0){ this.head.prev = this.head.next; }else{ this.head.next.next.prev = this.head.next; } this.size++; } /** * insertBack() inserts an item at the back of this DList. * @param item is the item to be inserted. * Performance: runs in O(1) time. */ public void insertBack(Object item) { this.head.prev = newNode(item, this.head.prev, this.head, this); if(this.size == 0){ this.head.next = this.head.prev; }else{ this.head.prev.prev.next = this.head.prev; } this.size++; } /** * front() returns the node at the front of this DList. If the DList is * empty, return null. * * Do NOT return the sentinel under any circumstances! * * @return the node at the front of this DList. * Performance: runs in O(1) time. */ public Object front() { if(this.size >0){ return this.head.next.item; }else{ return null; } } /** * back() returns the node at the back of this DList. If the DList is * empty, return null. * * Do NOT return the sentinel under any circumstances! * * @return the node at the back of this DList. * Performance: runs in O(1) time. */ public Object back() { if(this.size > 0){ return this.head.prev.item; }else{ return null; } } /** * next() returns the node following node in this DList. If node is * null, or node is the last node in this DList, return null. * * Just to make sure that passed node is part of the list that we are * working with, listp is added as member of node * Do NOT return the sentinel under any circumstances! * * @param node the node whose successor is sought. * @return the node following node. * Performance: runs in O(1) time. */ public DListNode next(DListNode node) { if((node.next != this.head) && (node.listp == this)){ return node.next; }else{ return null; } } /** * prev() returns the node prior to node in this DList. If node is * null, or node is the first node in this DList, return null. * * Do NOT return the sentinel under any circumstances! * * @param node the node whose predecessor is sought. * @return the node prior to node. * Performance: runs in O(1) time. */ public DListNode prev(DListNode node) { if((node.prev != this.head) && (node.listp == this)){ return node.prev; }else{ return null; } } /** * insertAfter() inserts an item in this DList immediately following node. * If node is null, do nothing. * @param item the item to be inserted. * @param node the node to insert the item after. * Performance: runs in O(1) time. */ public void insertAfter(Object item, DListNode node) { if((node != null) && (node.listp == this)){ node.next = new DListNode(item, node, node.next, this); node.next.next.prev = node.next; } } /** * insertBefore() inserts an item in this DList immediately before node. * If node is null, do nothing. * @param item the item to be inserted. * @param node the node to insert the item before. * Performance: runs in O(1) time. */ public void insertBefore(Object item, DListNode node) { if((node != null) && (node.listp == this)){ node.prev = new DListNode(item, node.prev, node, this); node.prev.prev.next = node.prev; } } /** * remove() removes node from this DList. If node is null, do nothing. * Performance: runs in O(1) time. */ public void remove(DListNode node) { if((node != null) && (node.listp == this)){ node.prev.next = node.next; node.next.prev = node.prev; } } /** * toString() returns a String representation of this DList. * * DO NOT CHANGE THIS METHOD. * * @return a String representation of this DList. * Performance: runs in O(n) time, where n is the length of the list. */ public String toString() { String result = [ ; DListNode current = head.next; while (current != head) { result = result + current.item + ; current = current.next; } return result + ]; }}/* DListNode.java */package list;/** * A DListNode is a node in a DList (doubly-linked list). */public class DListNode { /** * item references the item stored in the current node. * prev references the previous node in the DList. * next references the next node in the DList. * * DO NOT CHANGE THE FOLLOWING FIELD DECLARATIONS. */ public Object item; protected DListNode prev; protected DListNode next; protected DList listp; /** * DListNode() constructor. * @param i the item to store in the node. * @param p the node previous to this node. * @param n the node following this node. */ DListNode(Object i, DListNode p, DListNode n, DList listp) { this.item = i; this.prev = p; this.next = n; this.listp = listp; }}My question:As part of code changes for Part I, do you think the query mentioned as Part I is addressed?As part of code changes for Part II, does the observation and solution to avoid corruption of class DList looks correct? | Doubly circular linked list implementation with successive update in O(1) | java;linked list;homework;circular list | null |
_unix.303429 | Currently, I am trying to change the brightness of my Ubuntu system. This is my first time using Ubuntu. I couldn't change the brightness using the fn key. This is because my keyboard don't have the fn key. So i found out through the online source that it is possible to change the brightness my modifying the value of the acpi_video0/brightness file. I tried changing it. It seems that the value can be changed but in the screen has no effect. I have also tried changing commands in the GRUB file but its still the same. My Ubuntu system is too dim now. I need to increase it somehow. *-display description: VGA compatible controller product: Intel Corporation vendor: Intel Corporation physical id: 2 bus info: pci@0000:00:02.0 version: 06 width: 64 bits clock: 33MHz capabilities: pciexpress msi pm vga_controller bus_master cap_list rom configuration: driver=i915_bpo latency=0 resources: irq:324 memory:de000000-deffffff memory:c0000000-cfffffff ioport:f000(size=64) | acpi_video0 brightness no effect on the screen | ubuntu;acpi;brightness | null |
_softwareengineering.198379 | I am currently working on creating a toolkit for work and I've gotten to the point where I'm wondering about error reporting. Basically all of my tools, which consist of a grouping of classes, will eventually be ran from a main method. Many of these tools will be doing operations on file like reading them in and converting them into some sort of array of objects or writing an object array to a file in a certain format. Whenever you are dealing with data that your program didn't create there is always room for error and those errors need to be known.With that said what would be a good method to document all of the errors that occur during the processing and allow them to be retrieved later? Considering that I may want to send these error information out later I don't think that Log4J would be a good fit. I was considering using a string builder in each of my processing classes and append all error to that builder and retrieve it later at my leisure. I was also thinking of using some sort of arrayList or something that would hold the different types of errors but I'm a bit at a loss. Does anyone have any good methods of doing this? | Standard Java Error Reporting | java | It sounds like you are trying to enable remote logging. Log4J is a fine fit for this. What you can do in the most basic way possible is open up a socket that sends data to a message queue. This message queue will have a listener attached to it that can handle the different log messages it receives. This data can later be persisted into a database which you can than query against to generate reports. Using StringBuilder makes very little to no sense, because it sounds like you are trying to just consume a bunch of space on the host system.FROM THE COMMENTS Correct, once these errors are fixed I no longer need them. Is it standard practice to funnel all errors from applications into a single database? I don't mind keeping the data if this is the correct method of doing so however only the newest information will be looked atIt is more a standard practice to keep a dedicated audit log, depending on your policy / legal requirements this can be anywhere from 90 days to 2 years. This enables you to go back and prove that steps were taken to mitigate compliance issues, track down malicious activity, etc. While it is true that logs are only good for a limited period of time, it is greatly beneficial to see audit logs when you are trying to track down a recurring issue in the system. |
_unix.212573 | There seem to be several options for setxkbmap such as -option caps:backspace which makes caps a backspace. However I cannot seem to find an option that makes backspace an escape key. How do I create a single setxkbmap command that changes the backspace key to an escape key? | How can I make backspace act as escape using setxkbmap? | keyboard shortcuts;xkb | You'll have to define a new option.First, make a new symbol file e.g. /usr/share/X11/xkb/symbols/bksp with the following content:partial alphanumeric_keysxkb_symbols bksp_escape { key <BKSP> { [ Escape ] };};Then create the new option like this:bksp:bksp_escape = +bksp(bksp_escape)(where bksp is the name of the symbol file and bksp_escape is the group name that was defined in this file) and add it to the options list in the rules set you're using - assuming evdev - so place it in /usr/share/X11/xkb/rules/evdev under ! option = symbols:! option = symbols bksp:bksp_escape = +bksp(bksp_escape) ........... grp:shift_toggle = +group(shifts_toggle) altwin:menu = +altwin(menu)Add it also to /usr/share/X11/xkb/rules/evdev.lst (with a short description) under ! option (e.g. right before ctrl):! option ........ bksp Backspace key behavior bksp:bksp_escape Backspace as Escape ctrl Ctrl key position ctrl:nocaps Caps Lock as CtrlYou can then run, as a regular user:setxkbmap -layout us -option bksp:bksp_escapeto enable the option and make BKSP behave as ESC.You can also verify if:setxkbmap -queryreports:rules: evdevmodel: pc104layout: usoptions: bksp:bksp_escapeand ifsetxkbmap -printoutputs:xkb_keymap { xkb_keycodes { include evdev+aliases(qwerty) }; xkb_types { include complete }; xkb_compat { include complete }; xkb_symbols { include pc+us+inet(evdev)+bksp(bksp_escape) }; xkb_geometry { include pc(pc104) };};In Gnome 3 you can make the option permanent via dconf (or gsettings in terminal) e.g. add 'bksp:bksp_escape' to the org>gnome>desktop>input-sources>xkb-options key (note that in dconf values are separated by comma+space).Finally, note that both evdev and evdev.lst will be overwritten on future upgrades (but not your custom bksp symbol file) so you'll have to edit them again each time the package that owns them is upgraded (on archlinux it's xkeyboard-config). It's easier to write a script that does that, e.g.sed '/! option[[:blank:]]*=[[:blank:]]*symbols/a\ bksp:bksp_escape = +bksp(bksp_escape)' /usr/share/X11/xkb/rules/evdevsed '/! option/a\ bksp Backspace key behavior\ bksp:bksp_escape Backspace as Escape' /usr/share/X11/xkb/rules/evdev.lstIf you're happy with the result use sed -i (or -i.bak if you want to make backup copies) to actually edit those files in-place. |
_codereview.54290 | import java.util.Arrays;public class BinarySearch { // this class should not be instantiated private BinarySearch() { } // searches for the integer key in the sorted array a[] // @param key the search key // @param a the array of integers, must be sorted in ascending order // @return index of key in array a[] if present; -1 if not present public static int rank(int key, int[] a) { int lo = 0; int hi = a.length - 1; while (lo <= hi) { // key is in a[lo..hi] or not present int mid = lo + (hi - lo) / 2; if (key < a[mid]) hi = mid - 1; else if (key > a[mid]) lo = mid + 1; else return mid; } return 1; } // reads in a sequence of integers from the whitelist file, specified as a command line argument. reads in integers from standard input and prints to standard output // those integers that do not appear in the file. public static void main(String[] args){ // read the integers from a file In in = new In(args[0]); int[] whitelist = in.readAllInts(); // sort the array Arrays.sort(whitelist); // read integer key from standard input; print if not in whitelist while (!StdIn.isEmpty()) { int key = StdIn.readInt(); if (rank(key, whitelist) == -1) StdOut.println(key); } }} | Is this a reasonable binary search implementation? | java;algorithm;reinventing the wheel;binary search | Your implentation can search integers, we expect to search in an array of any comparable objects.I think you have a bug if the element is not found. It will return 1 instead of -1 / throwing an exception. Add unit tests.Also, Java is now open source, you can compare your implementation with the one from the JDK (Arrays.binarySearch).Also, in code style:it is recommended to use {} in if block, even if they are one-liner |
_cstheory.8316 | I'm looking to link a problem I'm working on to a known NP-hard problem. I think I can model my problem as a resource constrained shortest path problem. However, the structure of my graph is not completely arbitrary. Thus, it will be useful to know when RCSP becomes hard. Is it hard for a DAG, for a planar DAG, for a DAG with bounded degree? Any help would be greatly appreciated! | On which classes of graphs is resource constrained shortest path (RCSP) NP-hard? | cc.complexity theory;graph algorithms;np hardness;optimization | I don't know if you're still interested in this (old) question, and if I understood well the resource constraints you gave in the comment; however it seems that your problem (which is slightly different from usual RCSP problems) is NP-complete for planar (undirected or directed or directed acyclic) graphs of max-degree 3.The easy reduction is from 3-SAT. Given a formula $\varphi$ with $n$ variables $x_1,...x_n$ and $m$ clauses $C_1,...C_m$:add a resource constraint set $M_k^+$ with two vertices for each positive literal $x_k$ in $\varphi$ and a resource constraint set $M_k^-$ with two vertices for each negative literal $\bar{x}_k$ in $\varphi$;start building a graph from a source node $s$ and for each variable $x_i$ split the path in two lines: the upper one traverses one vertex of all the $M_k^-$ that correspond to a negative literal $\bar{x}_k$; the lower one traverses one vertex of all the $M_k^+$ that correspond to a positive literal $x_k$;then for each $C_j$ split the path in 3 lines that traverse in parallel the 3 vertices corresponding to the literals of $C_j$ and that are picked from the corresponding $M_k^+$ or $M_k^-$;finally add a sink node $t$.A path from $s$ to $t$ exists if and only if the original formula is satisfiable (i.e. without loss of generality you can ask for a path of length $\leq |V|$).Informally when traversing the variable section $x_i$, if you pick the upper line (true assignment) then you must use one of the vertices of all the $M_k^-$ resource constraint sets that also contain a vertex that can be used later to traverse (satisfy) a clause containing $\bar{x}_i$. If you pick the lower line (false assignment) then you must use one of the vertices of all the $M_k^+$ resource constraint sets that also contain a vertex that can be used later to traverse (satisfy) a clause containing $x_i$. When traversing each clause at least one of the three vertices must be contained in a $M_k$ that has not be used yet (i.e. at least one of them can be used to satisfy the clause).The following figure should make the reduction clearer. The resource constraint sets $M_k$ are represented with distinct colors (and for every color there are exactly 2 vertices).$C_1 = x_1 \lor \bar{x}_2 \lor x_3$$C_2 = x_2 \lor \bar{x}_3 \lor x_4$$C_3 = \bar{x}_1 \lor x_3 \lor \bar{x}_2$You can also easily make the graph directed, acyclic and bipartite. Let me know if you need further details (or if I completely misunderstood the problem :-).As noted by Saaed the problem is fixed-parameter tractable with respect to $k$ (just consider all possible subsets of constrained nodes and for each combination run the shortest path algorithm). |
_codereview.154087 | Background(these are the bits technically not for review, but feel free to point out any minor points)An Entity class can be identified by a name and at least one alias:public final class Entity { private final String name; private final Set<String> aliases; public Entity(String name) { this(name, name); } public Entity(String name, String... aliases) { if (aliases == null || aliases.length == 0) { throw new IllegalArgumentException(At least one alias expected.); } this.name = name; this.aliases = ImmutableSet.copyOf(aliases); } public String getName() { return name; } public Set<String> getAliases() { return aliases; }}A Container interface describes how to find by a name or an alias:public interface Container { Optional<Entity> findByName(String name); Optional<Entity> findByAlias(String name);}For the purpose of the comparison below, it is safe to assume that an Entity can be uniquely identified by a name or alias in a Container.Lookup implementation #1This performs the mapping and comparison on-the-fly. AdvantagesMethod implementations can be read fluentlyOpens up the possibility of additional searching criteria by using a different BiPredicate, e.g. using String::equalsIgnoreCase for a case-insensitive name searchUnsure aboutPerformance, is it optimal? public final class EntityContainer implements Container { private final Set<Entity> entities; public EntityContainer(Entity... entities) { if (entities == null || entities.length == 0) { throw new IllegalArgumentException(At least one entity expected.); } this.entities = ImmutableSet.copyOf(entities); } @Override public Optional<Entity> findByName(String name) { return findBy(Entity::getName, Object::equals, name); } @Override public Optional<Entity> findByAlias(String alias) { return findBy(Entity::getAliases, Set::contains, alias); } private <X, Y> Optional<Entity> findBy(Function<Entity, ? extends X> mapper, BiPredicate<X, Y> biPredicate, Y lookupValue) { return Optional.ofNullable(lookupValue) .flatMap(y -> entities.stream() .filter(Objects::nonNull) .filter(x -> biPredicate.test(mapper.apply(x), y)) .findAny()); }}Lookup implementation #2This relies on a good-ol' Map to perform the lookup. AdvantagesLookupUtils can be readily applied to generate other similar lookup Maps.Using LookupUtils can make the lookup more defensive than the first approach (see below) public final class AnotherEntityContainer implements Container { private final Set<Entity> entities; private final Map<String, Entity> byNames; private final Map<String, Entity> byAliases; public AnotherEntityContainer(Entity... entities) { if (entities == null || entities.length == 0) { throw new IllegalArgumentException(At least one entity expected.); } this.entities = ImmutableSet.copyOf(entities); this.byNames = LookupUtils.mapBy(Entity::getName, entities); this.byAliases = LookupUtils.mapByMulti(Entity::getAliases, entities); } @Override public Optional<Entity> findByName(String name) { return ofNullable(byNames.get(name)); } @Override public Optional<Entity> findByAlias(String alias) { return ofNullable(byAliases.get(alias)); }}Implementation of LookupUtilspublic final class LookupUtils { private LookupUtils() { // empty } public static <K, V> Map<K, V> mapBy(Function<? super V, ? extends K> mapper, V... values) { return mapBy(values == null ? empty() : stream(values), mapper, v -> v); } public static <K, V> Map<K, V> mapByMulti(Function<? super V, ? extends Set<K>>mapper, V... values) { return mapBy(values == null ? Stream.<Entry<K, V>>empty() : stream(values).flatMap(x -> mapper.apply(x).stream().collect( toMap(k -> k, v -> x)).entrySet().stream()), Entry::getKey, Entry::getValue); } private static <T, K, V> Map<K, V> mapBy(Stream<T> stream, Function<? super T, ? extends K> keyMapper, Function<? super T, ? extends V> valueMapper) { Map<K, V> result = stream.filter(Objects::nonNull).collect( collectingAndThen(toMap(keyMapper, valueMapper), Collections::unmodifiableMap)); if (result.isEmpty()) { throw new IllegalStateException(Empty result map unexpected.); } if (result.containsKey(null)) { throw new IllegalStateException(null keys unexpected.); } return result; }}The tests for an empty map or null keys are to make it a requirement that lookup maps shouldn't be empty by definition, and to follow the recommendation from Guava. Implicitly, duplicate keys will also throw an IllegalStateException courtesy of Collectors.toMap(Function, Function). May I know which would be more preferable in terms of:ReadabilityMaintainability/understandingPerformance, for some definition of it (taking in mind 'premature optimization is the root of all evil')Does it matter (i.e. will the answer change) if lookups are performed extensively?Does it matter if there is a million aliases and names, or if there's only hundreds of them? | Comparison of lookup methods | java;comparative review;lookup | The first solution is a lot more compact making it almost automatically a lot easier to comprehend and maintain. However, performance will be far better with the Map variant. The stream variants won't be able to do any optimization and will need to check the predicate against all elements.If you already know that this class will become a performance bottleneck (and it could easily become one with a higher number of entities combined with a high number of look-ups) then a more complicated solution is certainly waranted to get acceptable performance. |
_scicomp.20407 | Let $$T=1, K=100, S_0=100, \sigma=0.05, r=0.15. $$Define $\nu:=\frac{2r}{\sigma^2}-1$and $$H(y,z)=\frac{z e^{\pi^2 /4y}}{\pi \sqrt{\pi y}}\int_0^{\infty} e^{-z \cosh(u) -u^2/(4y)} \sinh(u) \sin(\frac{\pi u}{2y})du$$then next define $$ f(y,z)=\left( \frac{z}{S_0}\right)^{\nu/2}\frac{1}{4KT}\exp\left(-\frac{2(S0+z)}{KT\sigma^2}-\frac{\nu^2\sigma^2y}{8} \right) \times H(\frac{\sigma^2y}{8},\frac{4\sqrt{S_0 z}}{KT\sigma^2}) $$and $$ g(y,z)=z\frac{e^{-ry}-e^{-rT}}{rT} $$I would like to compute the following double integral $$ I=\int_0^{\infty}\left[\int_0^T g(y,z)f(y,z)dy\right]dz. $$When I tried this with Maple, please see the picture below,it ran out of memory.I would like to ask whether there is a way to compute the above integral? What should I do to compute the integral? | How to compute this double integral? | linear algebra;finite element;numerical analysis;discretization | null |
_webmaster.13401 | I have about 20 domains to manage. Some registered to the client (i impersonated him) and other register by me, under different name and address (over the years).I like to get ALL THE DOMAINS under one roof, one easy to manage all the registration and order in one place..what do you suggest...once in my life, i have try doteasy, which make domain managing super easy, but i don't like the prices... | Domain manager to consolidate many domain here and there | domains | Pick a company which looks like it's going to be around for a few years and move all the domains to that company. Make sure that you have written agreements with the clients who you impersonated so that it's clear who owns the domain. If you used their contact details then when the domain transfer request comes through they are going to receive it and may wonder what's happening. |
_codereview.13510 | I have created a very simple script that will create two columns which are populated by an array. It works, but I am certain that the way that I have gone about it is not the best way. I have been searching for simple, sample scripts which would aide me in understanding how to best approach this, but all of them have been too specific to their application.This is what I have made:$assets = array('Bag', 'Charger', 'Power Cable', 'Video Cable', 'Mouse', 'Keyboard', 'Test', 'Test 2', 'Test 3');$assets_count = count($assets);$halfway_raw = $assets_count / 2;$halfway = round($halfway_raw, 0) - 1;echo '<ul class=col-1>';for($i = 0; $i < $assets_count; $i++) { if($i == $halfway) { echo '<li>' . $assets[$i] . '</li>'; echo '</ul>'; echo '<ul class=col-2>'; } else { echo '<li>' . $assets[$i] . '</li>'; }}echo '</ul>';I'm looking for something that scales easily and is obviously as small as possible, which I don't think my script is. | Dynamic two-column list, Vertical Wrap | php;algorithm;html | Well, this is more concise, and it should be easy enough to scale:<?php$assets = array('Bag', 'Charger', 'Power Cable', 'Video Cable', 'Mouse', 'Keyboard', 'Test', 'Test 2', 'Test 3');$half = ceil(count($assets)/2);$columns = array( array_slice($assets, 0, $half), // first half array_slice($assets, $half) // second half);foreach( $columns as $index => $column ) { $index += 1; echo <ul class=\col-$index\><li> . implode(</li><li>, $column) . </li></ul>;}?>Basically, it's using more built-in PHP functions and constructs (array_slice, implode, foreach) but is functionally identical to the original. |
_softwareengineering.212326 | A HashMap allows only one null key. Is it because it allows only unique keys? Or is there another reason? | Why does HashMap allow only one null key? | java;map | Why is it confusing? The javadoc for HashMap.put clearly states:Associates the specified value with the specified key in this map. If the map previously contained a mapping for the key, the old value is replaced.It clearly states what happens when you do a put with a key which was already in the map. The specific case of key == null behaves in the same way: you can't have two different mappings for the null key (just like you can't for any other key). It's not a special case, for the context of your question. |
_unix.272666 | I've got an ASUS RT-AC66u running an OpenVPN server working fine. But on my debian server I have to add a route or else I get no responses. Just curious if there is a way to add the route to the router for persistence there, versus putting the command in /etc/network/interfaces as a post-up/pre-down rule. On debian I've added this:route add -net 10.14.0.0 netmask 255.255.255.0 gw 192.168.192.2I tried adding basically the same thing to the ASUS (not realizing that obviously shouldn't work) and broke any connection until I removed it. Would the proper syntax for it be?net 192.168.192.0 netmask 255.255.255.0 gw put.vpn.gw.here | How Would I Appropriated Add this Route? | networking;routing;openvpn | null |
_unix.136282 | For an embedded Linux system, if I have two or more network interfaces, how do I ensure that they always get the same interface names every bootIn other words, I want, for example, eth0 to always map to one physical Ethernet port, eth1 to the next, etc.My Linux distribution is home-grown, and I use devtmpfs for populating /dev. I use busybox for init (and most everything else), along with custom init scripts for system startup and shutdown.I do not need hotplug facilities of mdev or udev -- I'm referring to fixed Ethernet ports. | How do you ensure physical network interfaces always get the same interface name across reboots on an embedded Linux system? | linux;networking;embedded;ethernet | This works for me with Linux 3.9.0 on an x86_64 architecture.#!/bin/sh# This assumes the interfaces come up with default names of eth*.# The interface names may not be correct at this point, however.# This is just a way to get the PCI addresses of all the active# interfaces.PCIADDRLIST=for dir in /sys/class/net/eth* ; do [ -e $dir/device ] && { PCIADDRLIST=`readlink -f $dir/device` ${PCIADDRLIST} }done# Now assign the interface names from an ordered list that maps# to the PCI addresses of each interface.# IFNAMES could come from some config file. dummy is needed because of# my limited tr- and awk-fu.IFNAMES=eth0 eth1 eth2 dummyfor dir in `echo ${PCIADDRLIST} | tr \n | sort` ; do [ -e $dir/net/*/address ] && { MACADDR=`cat $dir/net/*/address` IFNAME=`echo $IFNAMES | awk '{print $1}'` IFNAMES=`echo $IFNAMES | awk '{ for (i=2; i<=NF; i++) printf %s , $i; }'` echo -n $IFNAME nameif $IFNAME mac=$MACADDR }done |
_webmaster.28292 | I am trying to find a Content Mangement/social interaction script that requires a person to be a part of a group. Specifically:My daughter is a cheerleader and there are a number of cheer groups she is involved in and also has friends in many others. A lot of them could use some kind of website where they can share information between their team members and coach. The coach being the controller of the group and who can join etc. Group Leader? One can only join the group if invited or given a password or some such security. There would be multipel groups or in this case multiple cheer squads who were registered as groups and the cheerleaders a part of their group. The coach or group leader would have control of the group calender and they may have their own calendars and be messaging between them and/or other social interactions. IN a perfect world they could modify their own pages individualy. Communication could go globally or only to the group and a friends or buddy system. I think you get the idea. I really like OCportal and what it does and can do but it does not have the group funcitionality I am looking for. Perhaps I am just going to need to see about getting aprogrammer to write an add on for me if ther is nothing like this out there. But if you know of any I would appreciate being pointed in that direction. | I am looking for a script where users can create groups cms/social interaction site | looking for a script;content;social networks | null |
_codereview.84988 | The following code reads a file, splits its data, replaces some characters in the data, and then joins the data again (I added more details in the comments):// read plain text file and make content available in datafs.readFile(filename, 'utf8', function(err, data) { if (err) throw err // turn the data into an array data = data.split('\n\n') // make a clone of the array to be used in the if statements. var tree = data.slice() for (var i = 0; i < tree.length; ++i) { // turn #s into heading tags if #s are present if (tree[i].match(/^#/g)) { data[i] = data[i] .replace(/^#### (.*)/gm, '<h4>$1</h4>') .replace(/^### (.*)/gm, '<h3>$1</h3>') .replace(/^## (.*)/gm, '<h2>$1</h2>') .replace(/^# (.*)/gm, '<h1>$1</h1>') } // smarten or ' if present if (tree[i].match(/|'/g)) { data[i] = data[i] .replace(/(?=\b|\*|')/g, '') .replace(/(?!\b|\*|')/g, '') .replace(/'(?!\b|\*)|(?=\b)'(?=\b)/g, '') .replace(/'(?=\b|\*)/g, '') } // turn -- into if present if (tree[i].match(/--/g)) { data[i] = data[i] .replace(/\b--(\b)*/g, '') } // turn * or ** into italics and bold if present if (tree[i].match(/\*\*|\*/g)) { data[i] = data[i] .replace(/\*\*([^\*|\s]+)\*\*/g, '<strong>$1</strong>') .replace(/\*([^\*|\s]+)\*/g, '<em>$1</em>') } // surround every element with p tags if the // element doesn't start with an #. Also if the previous element of // the element is # or * * * add the p tag with the class ni if (tree[i].match(/^[^#]/g)) { if (tree[i - 1] && (tree[i - 1].match(/^#/g) || tree[i - 1] === * * *)) { data[i] = '<p class=ni>' + data[i] + '</p>' } else { data[i] = '<p>' + data[i] + '</p>' } } } // lastly, put the array together again to the saved as HTML data = data.join('\n\n') saveHtml(data)})Example input:# Title'Single quotes'Double Quotes* * *ParagraphsOutput:<h1>Title</h1><p class=ni>Single quotes</p><p>Double Quotes</p><p>* * *</p><p class=ni>Paragraphs</p>Is there a cleaner way to write those if statements? Or at least create a function so that there is less code in that fs.readFile block? | Converting file from Markdown-like markup into HTML using repeated substitutions | javascript;strings;regex;io;markdown | Here's what I would do (note: in ES6, though it is trivial to convert back to ES5). It doesn't match your code perfectly, but it should get get the point across. Essentially I extract everything out into smaller methods and then have a method that can perform batch replacements. It's not shorter nor really any less complex, but it is (to me) easier to read and follow.Notes:I'd normally comment this like crazy so that I could remember what the regexps do, but in this example I haven't. Almost all of them are your regexp's, and the ones that are different aren't so different that they won't be obvious to you.I prefer HTML Entities for things like double quotes and dashes. I'm not worrying about the p class=ni stuff, but it would be trivial to add.ES6 Code:function massReplace(text, replacementArray) { let results = text; for (let [regex, replacement] of replacementArray) { results = results.replace(regex, replacement); } return results;}function transformHeadings(text, orig) { if (orig.match(/^#{1,6}\s/)) { return massReplace(text, [ [/^###### (.*)/gm, '<h6>$1</h6>'], [/^##### (.*)/gm, '<h5>$1</h5>'], [/^#### (.*)/gm, '<h4>$1</h4>'], [/^### (.*)/gm, '<h3>$1</h3>'], [/^## (.*)/gm, '<h2>$1</h2>'], [/^# (.*)/gm, '<h1>$1</h1>'] ] ); }}function transformQuotes(text, orig) { if (orig.match(/|'/)) { return massReplace(text, [ [/(?=\b|\*|')/g, '“'], [/(?!\b|\*|')/g, '”'], [/'(?!\b|\*)|(?=\b)'(?=\b)/g, '‘'], [/'(?=\b|\*)/g, '’'] ] ); }}function transformStyling(text, orig) { if (orig.match(/\*\*|\*/)) { return massReplace(text, [ [ /\*\*([^\*|\s]+)\*\*/g, '<strong>$1</strong>'], [ /\*([^\*|\s]+)\*/g, '<em>$1</em>' ] ]); }}function transformDashes(text, orig) { if (orig.match(/\-\-/)) { return massReplace (text, [ [ /\-\-/g, '—' ] ]); }}function transformParagraphs(text, orig) { if (!orig.match(/^#{1,6} (.*)/)) { return `<p>${text}</p>`; }}function transformToHTML(markdownSource) { let data = markdownSource.split('\n\n'), orig = data.slice(), transforms = [ transformHeadings, transformQuotes, transformDashes, transformStyling, transformParagraphs ]; for (let i = 0, l = orig.length; i < l; ++i) { for (let transform of transforms) { let result; if ((result = transform(data[i], orig[i])) !== undefined) { data[i] = result; } } } return data.join('\n');}NOTE: For engines that don't support destructuring (looking at you, io.js), use this method instead:function massReplace(text, replacementArray) { let results = text; for (let replacementArrayItem of replacementArray) { let regex = replacementArrayItem[0], replacement = replacementArrayItem[1]; results = results.replace(regex, replacement); } return results;} |
_cstheory.5434 | I need to translate a training algorithm that involves sums and multiplications of probabilities to actual code. For that I need some sort of scaling procedure that allows me to avoid underflows, that is, misleading 0 probabilities.A typical method is to apply the logs of probabilities but because of the sums this is not readily possible for my case. Another approach I saw in Rabiner's tutorial on HMMs, was his scaling procedure only dependent on t (time) applied to the forward algorithm and (the other way around) the backward algorithm, that when combined cancel each other to obtain the desired trained probabilities.My questionI wonder if there are books or text resources explaining common approaches to tackle the underflow problem that results in working with continuous multiplications of probabilities. Do you know any? I hope I can get some ideas from that. | Scaling procedures to address false 0's after multiplying probabilities | pr.probability;na.numerical analysis | A simplee trick (explained here) that let you use the $\log$ approach even when you must sum probabilities.Problem: $\log(\exp(a) + \exp(b))$ can lead to an underflow, to avoid it you can use this formula:$\log(x + y) = \log(x) + \log(1.0 + \exp( \log(y) - \log(x) ) )$Or use another approach:$\log(\exp(a) + \exp(b)) = \log( \exp(a - C) + \exp(b - C)) + C$Setting $C = \max(a,b)$For example: $\log(e^{-120}+e^{-121}) = \log(e^{-120}(e^0 + e^{-1}))= \log(e^0+e^{-1})-120$ |
_computerscience.1801 | Thinking about hybrid raytracing, hence the following question:Suppose I have two solid spheres $s_1$ and $s_2$. We know their centres and radii, and we know that they have some overlapping volume in space.We have a typical 3D graphics setup: assume eye is at the origin, and we are projecting the spheres onto a view plane at $z = f$ for some positive $f$. The spheres are beyond the view plane and don't intersect it.Let $c$ be the circle in space that is points on the surface of both spheres, i.e. the visible (from some angles) 'join' of their overlapping volumes.I want to calculate if any of $c$ is visible when projected onto our view plane. It might not be, if $s_1$ or $s_2$ get completely in the way.Any ideas for approaching this? | Sphere intersection occlusion (for hybrid raytracing) | raytracing;3d;occlusion | Given that I didn't miss anything, you can probably cut this down to a problem in the 2D space. Viewing onto the plane defined by the center points of the spheres and your camera origin, the scene looks like this:The spheres become circles with the center points $C_1$ and $C_2$, and the intersection circle is now only 2 points with only the closer one $P$ being interesting. The camera/eye is arbitrarily set to the point $E$.Calculating if one point on the spheres is visible or not is easy: Simply check whether or not the angles at point $P$ between $E$ and $C_1$ respectively $E$ and $C_2$ are both greater (or equal to) 90 degree1.If $P$ is visible, some part (e.g. at least that point) of the intersection circle is visible. Otherwise the whole intersection circle must be occluded by one of your spheres, namely the one which creates an angle of less than 90 degree.Here is how it looks if $P$ is not visible from $E$:You can clearly see how that point is occluded by the circle around $C_2$ and that the angle between $E$ and $C_2$ in $P$ is less than 90 degree.1 Having an angle of exactly 90 degree means that the line between $E$ and $P$ just touches the respective circle/sphere in point $P$ as a tangent. |
_webapps.62881 | How can I exclude a given label from a search, effectively finding all the email that do not have that label applied? I've searched Google, SuperUser, and the Gmail Advanced search support page to no avail.Here are the searches I've tried, none of which work:!label:workNOT label:worknot label:work-label:workThe reason this may not be a duplicate: After some more experimentation it seems that the - operator would work, except that it doesn't exclude entire conversations if any one message in the conversation has the label. I need my search to exclude any conversation in which one or more messages has the specified label.How can I achieve this behavior?Per Gianni Di Noia's advice, I tried making a filter that matches emails labeled work and then re-applies the label work. Unfortunately, after some testing with another email account I have I found that this does not work because it is never triggered. Filters are triggered based on the properties of the incoming email, not on the conversation to which Gmail assigns that email. Google warned me of this even before I did my testing: | Exclude label from a Gmail search? | gmail;gmail labels;gmail search | null |
_unix.317115 | When copying drives on a raid, I used the following command from within each drive I am copying from:find . -print -depth | cpio -pdm /dbb0where dbb0 is the new directory that I want. From some directories this works, on others it hangs permanently. The permissions on all drives seem to be fine, I am having trouble figuring out what could theoretically cause this. | cpio sometimes hangs up | command line;find;cpio | null |
_unix.279876 | My question is from Delimiter in word splittingWhy does Bash not respond when I hit Tab key?What other keys does Bash eat? | Why does bash's readline eat tab? | bash | null |
_webapps.69571 | I would like to change ownership of a shared Google Calendar that is embedded on our website, however nobody knows who owns the Calendar. How can we determine the owner knowing just the HTML embed code? | How to determine the owner of an embedded Google Calendar? | google calendar | null |
_unix.45470 | I am trying to set the Java system property jsse.enableSNIExtension to false, but when I try running this java just outputs help information:java -Djsse.enableSNIExtension=false What am I doing wrong? | How to set jsse.enableSNIExtension to false when running Java programs? | java | You forgot the name of the class to run. Normally Java programs are run like this:$ java MainClass$ java -jar foobar.jarYou can use -D to set system properties, but you still need the class or JAR to run:$ java -Djsse.enableSNIExtension=false MainClass$ java -Djsse.enableSNIExtension=false -jar foobar.jarAs far as I know you can't set system properties permanently; even if you did it programmatically it would only be for that run, so you need to keep passing the -D flag each time you run whatever it is that's not working |
_webapps.71265 | I signed up for Instagram and it said I already had an account with that email address. I didn't remember signing up but thought maybe I had done it a while ago. I reset my password and logged in.It turned out someone else had signed up using my Gmail address. They had like 2 or 3 pictures posted. I wasn't really sure what to do, since it was my email address they used (its a @gmail.com - I get a decent amount of email for people with my name).The problem is that they linked their Facebook account to Instagram. I also linked my Facebook account. I get notifications of my Facebook friends joining Instagram but it's this other person's Facebook account. In the Instagram app it only shows my Facebook as a linked account. How can I get this other Facebook account detached from my Instagram account? | How do you disconnect Facebook accounts from Instagram? | facebook;instagram | null |
_softwareengineering.234747 | I'm trying to understand how the Dependency Inversion Principle differs from the program to an interface, not an implementation principle.I understand what Program to an interface, not an implementation means. I also understand how it allows for more flexible and maintainable designs.But I don't understand how the Dependency Inversion Principle is different from the Program to an interface, not an implementation principle.I read about DIP in several places on the web, and it didn't clear up my confusion. I still don't see how the two principles differ from each other. Thanks for your help. | Dependency Inversion Principle vs Program to an interface, not an implementation | design;object oriented;principles | null |
_softwareengineering.312132 | I'm implementing the view transformation part of a graphics pipeline (basically a matrix which translates coordinates from world coordinates to camera coordinates given a camera position and direction).Other than the simple case where the point has the same coordinates if the camera is at [0, 0, 0] pointing towards [0, 0, 1] I can't seem to come up with any obvious test cases. Essentially it seems like there's no way of describing what should happen other than the implementation itself.Any ideas? | How do you write unit tests when you need the implementation to come up with examples? | graphics | null |
_unix.1578 | I'd like to edit the Grub menu that comes up, to move one line and remove others.I have an Inspiron 1420 that came with Ubuntu 7.10. When it needed a new drive, I installed Windows 7, the original OS, and then it seemed that 10.04 wanted its own partition. I probably should have checked exactly what I was doing first (famous last words).What I'd like to do is remove the 7.10 lines entirely, so I can blow away everything in that partition and use it as /home for 10.04. I'd also like to move the Windows 7 line up to second from the top, so booting in Windows would be a quick two keystrokes rather than following the line all the way down. Hitting the Grub edit key came up with unclear instructions, and since this is the boot loader I'd kind of rather not screw it up too bad.So, what's the best way to do this? | Editing grub menu | ubuntu;grub2;grub legacy;boot menu | null |
_unix.370559 | I am trying to create a device that accept input and generate special output. To make it simple, say I want to create a device which accepts any input (like /dev/zero) and writes 00 ff 00 ff 00 ff ... whenever read by another program. Is it possible and easy to be achieved in C or in Python? | How to create a device file and simulate behaviors of the Pseudo-devices? | python;devices;c | null |
_vi.8852 | In insert mode, when you hit ctrlp on a partially written word, a menu pops up with possible matches for completion.How can I customize those matches ?(I have a ruby-clangc gem that I want to use with the ruby-neovim gem in order to write my completion plugin for C/C++ code) | How to customize the entries in the completion menu? | vimscript;vimrc;autocompletion;neovim | About ctrlp, the doc says:Find previous match for words that start with the keyword in front of the cursor, looking in places specified with the 'complete' option. The found keyword is inserted in front of the cursor.You can then look at :h'complete'to learn how to modify the behavior of the completion.You'll see that you have several options to make the search of the matchrestricted to the current buffer, using the other loaded buffers or even lookingfor the spell dictionaries.To modify the setting simply add a line like this in your .vimrc:set complete=.,w,b,uNow for your completion plugin what you are looking for is a custom comlete function. Vims allows you to write such a function, for more information you should refer this question and to the doc::h complete-functions:h 'completefunc'I think you might also be interested in reading :h ins-completion which explains how the different completion modes of Vim works. (There are about ten different completion modes used to complete different items, learning them can be long but it should make your completion pretty efficient in the end) |
Subsets and Splits