id
stringlengths 5
27
| question
stringlengths 19
69.9k
| title
stringlengths 1
150
| tags
stringlengths 1
118
| accepted_answer
stringlengths 4
29.9k
⌀ |
---|---|---|---|---|
_unix.97620 | Linux has the magic sysrq key to reboot frozen machines remotely, and it works over the serial console, but what about FreeBSD? Is there a way to send a control-alt-delete to FreeBSD servers on serial consoles? | how to reboot a frozen FreeBSD server from the serial console? | freebsd;reboot;serial console;magic sysrq | Assuming you have a kernel with the debugger option compiled in you can use ControlAltEscape. From there you can call boot(0) or panic.Chapter 10 of the FreeBSD developers handbook explains this in a lot more detail. So much for more or less the same as SysReq via a keyboard. On the serial console, you need to send the break signal and have the options BREAK_TO_DEBUGGER enabled. But it is not the default since there are a lot of serial adapters around that gratuitously generate a BREAK condition, for example when pulling the cable. |
_cstheory.7222 | $(n + 1)$ points are required to uniquely determine a polynomial of degree $n$; for instance, two points in a plane determine exactly one line.How many points are required to uniquely determine a computable function $f : N \rightarrow N$, given the length of a program that computes $f$ in a fixed language? (i.e. a bound on the Kolmogorov complexity of $f$).The idea is that, at least theoretically, one could prove the correctness of a program by making enough tests.If one has a program $P$ of length $L$ that computes $f$, there is a bound on the number of functions that can be computed with a source length of at most $L$.Therefore one would only need to prove that:$f$ can be computed with a source length $\leq L$$P$ does not compute any other function computable in $L$ bytes or less (by testing)This idea has probably no practical consequences (the bounds are surely bound to be exponential). | Can testing show the absence of bugs? | cc.complexity theory;computability | null |
_cstheory.16860 | It is known that minimizing the size of a regular expression is PSPACE-complete even if we have a DFA as the language's specification. What are the results if the language is finite? One can consider this problem in two models:The input is all the strings in the language, and we measure the input size by the sum of the length of all strings.The input is a DFA, and we measure the input size by the number of states of the DFA. Kleene star is not useful in the finite case, so only $()$, $|$ and $\cdot$(concatenation) are used in the expression. Of course, the length of a regular expression seems arbitrary. Instead, one can give weight to each operation(include adding parenthesis), and ask to minimize the weight of the regular expression. Edit: As adrianN noted, it's related to grammar based codes. It's NP-complete to produce the minimum length context free grammar to describe a finite set. It's not clear why minimum size context free grammar can imply much about minimum size regular expression. Maybe a clever rewrite rule can related these two, and prove that in the first model, the problem is in NP. | minimizing size of regular expression for finite sets | cc.complexity theory;reference request;fl.formal languages;regular expressions;dfa | The following argument is essentially from (1): The decision versions of the two problems are contained in the second level of the polynomial hierarchy (more precisely: in the complexity class $\Sigma^P_2$), as follows. Guess a regular expression of size at most $k$, and check if it is equivalent to the given deterministic finite automaton (respectively: to the language given as a list of words). I believe that no further results regarding your problems are known. For a similar-looking optimization problem, where the objective is to find a minimum equivalent nondeterministic finite automaton instead of a regular expression, the following results are known:For input described as DFA, the minimum equivalent NFA problem is ${\bf DP}$-hard, see (1). Here, ${\bf DP}$ stands for difference polynomial time; this is the Sigma complexity class at the second level of the Boolean hierarchy. For input described as a list of words, the minimum equivalent NFA problem is ${\bf NP}$-hard, see (2).For $L \subseteq \{0,1\}^m$ and input described as a truth table, the minimum equivalent NFA problem is ${\bf NP}$-complete, see (2).Beware: Unlike the setting of infinite languages, I do not see a straightforward reduction from the NFA minimization case to the problems from your question.References:(1) Hermann Gruber and Markus Holzer. Computational Complexity of NFA Minimization for Finite and Unary Languages. In: 1st International Conference on Language and Automata Theory and Applications (LATA 2007), pp. 261-272, 2007.(2) Hermann Gruber and Markus Holzer. Inapproximability of Nondeterministic State and Transition Complexity Assuming P <> NP. In: 11th International Conference on Developments in Language Theory (DLT 2007), LNCS 4588, pp. 205-216, 2007. Edit:I think that grammar based codes are not so closely related: in that setup, the given language is a singleton set. But for such a singleton language $L=\{w\}$, the minimum size regular expression is (trivially) given by $w$. |
_unix.256409 | Updated: Clarify line number requirement, some verbosity reductionsFrom the command line, is there a way to:check a file of English textto find repeat-word typos,along with line numbers where they are found,in order to help correct them?Example 1Currently, to help finish an article or other piece of English writing, aspell -c text.txt is helpful for catching spelling errors. But, not helpful when the error is an unintentional consecutive repetition of a word.highlander_typo.txt:There can be only one one.Running aspell:$ aspell -c highlander_typo.txtProbably since aspell is a spell-checker, not a grammar-checker, so repeat word typos are beyond its intended feature scope. Thus the result is this file passes aspell's check because nothing is wrong in terms of individual word spelling.The correct sentence is There can be only one., the second one is an unintended repeat-word typo.Example 2But a different situation is for example kylie_minogue.txt:La la laHere the repetition is not a typo, as these are part of an artist's song lyrics.So the solution should not presume and fix anything by itself, otherwise it could overwrite intentional repeated words.Example 3: Multi-linejefferson_typo.txt:He has has refused his Assent to Laws, the most wholesome and necessaryfor the public good.He has forbidden his Governors to pass Laws of immediate andand pressing importance, unless suspended in their operation till hisAssent should be be obtained; and when so suspended, he has utterlyneglected to attend to them.Modified from The Declaration of IndependenceIn the above six lines,1: He has has refused should be He has refused, the second has is a repeat-word typo5: should be be obtained should be should be obtained, the second be is a repeat-word typoHowever, did you notice a third repeat-word typo?3: ... immediate and4: and pressing ...This is also a repeat-word typo because though they are on separate lines they are still part of the same English sentence, the trailing end of the line above has a word that is accidentally added at the start of the next line. Rather tricky to detect by eye due to the repetition being on opposite sides of a passage of text.Intended outputan interactive program with a process similar to aspell -c yet able to detect repeat-words, or,a script or combination of commands able to extract line numbers and the suspected repeat words. This info makes it easier to use an editor such as vim to jump to the repeat words and make fixes where appropriate.Using above multi-line jefferson_typo.txt, the desired output would be something like:1: has has3: and4: and5: be beor:1: He [has has] refused his Assent to Laws, the most wholesome and necessary3: He has forbidden his Governors to pass Laws of immediate [and]4: [and] pressing importance, unless suspended in their operation till his5: Assent should [be be] obtained; and when so suspended, he has utterlyI am actually not entirely sure how to display the difficult case of inter-line or cross-line repeat-word, such as the and repetition above, so don't worry if your solution doesn't resemble this exactly.But I hope that, like the above, it shows:relevant original input's line numbersome way to draw attention to what repeated, especially helpful if the line of text is also quite long.if the full line is displayed to give context (credit: @Wildcard), then there needs to be a way to somehow render the repeated word or words distinctively. The example shown here marks the repetition by enclosing them within ASCII characters [ ]. Alternatively, perhaps mimic grep --colors=always to colorize the line's matches for display in a color terminalOther considerationstext, should stay as plain text filesno GUI solutions please, just textual. ssh -X X11 forwarding not reliably available and need to edit over sshUnsuccessful attemptsTo try to find duplicates, uniq came to mind, so the plan was to first determine how to get repeat-word recognition to work on a single line at first.In order to use uniq we would need to first convert words on a line, to becoming one word per line.$ tr ' ' '\n' < highlander_typo.txtTherecanbeonlyoneone.Unfortunately:$ tr ' ' '\n' < highlander_typo.txt | uniq -DNothing.This is because for -D option, which normally reveals duplicates, input has to be exactly a duplicate line. Unfortunately the period . at the end of the repeated word one negates this. It just looks like a different line. Not sure how I would work around arbitrary punctuation marks such as this period, and somehow add it back after tr processing.This was unsuccessful. But if it were successful, next there would need to be a way to include this line's line number, since the input file could have hundreds of lines and it would help to indicate which line of the input file, that the repeat-word was detected on.This single-line code processing would perhaps be part of a parent loop in order to do some kind of line-by-line multi-line processing and thus be able to process all lines in a file, but unfortunately getting past even single-line repeat-word recognition has been problematic. | Command line method to find repeat-word typos, with line numbers | bash;command line;text processing;awk;aspell | Edited: added install and demoYou need to take care of at least some edge cases, likerepeated words at the end (and beginning) of the line.search should be case insensitive, because of frequent errors like The the apple.probably you want to restrict search only to word constituent to not match something like ( ( a + b) + c ) (repeated opening parentheses.only full words should match to eliminate the thesisWhen it comes to human language Unicode characters inside words should properly interpretedAll in all I recommend pcregrep solution:pcregrep -Min --color=auto '\b([^[:space:]]+)[[:space:]]+\1\b' fileObviously color and line number (n option) is optional, but usually nice to have.InstallOn Debian-based distributions you can install via:$ sudo apt-get install pcregrepExampleRun the command on jefferson_typo.txt to see:$ pcregrep -Min --color=auto '\b([^[:space:]]+)[[:space:]]+\1\b' jefferson_typo.txt1:He has has refused his Assent to Laws, the most wholesome and necessary3:He has forbidden his Governors to pass Laws of immediate andand pressing importance, unless suspended in their operation till his5:Assent should be be obtained; and when so suspended, he has utterlyThe above is just a text capture, but on a color-supported terminal, matches are colorized:has hasandandbe be |
_scicomp.11652 | How do we define the matrix for GMRES, if we do not want to solve the boundary elements but only the interior ones.I am using pentagonal elements so in a row there are 6 elements (cell itself + 5 fluxes) which means that in a row boundary elements are also accounted. But I need to make the matrix square according to the code here and I do not want to solve for boundary elements? What should I do? | GMRES: Making the matrix square without solving for boundaries | sparse;c++;boundary conditions;matrix;gmres | null |
_datascience.10538 | I have an average rating of all votes as well as the total number of votes for all episodes of the TV show Always Sunny. Is it mathematically sound to?: 1) multiply each average rating by the total votes cast for that episode2) take the array of all those values and normalize it so the lowest is 0 and the highest is 103) use that new value as the actual rating | What's the best way to rank aggregate imdb rating data? | dataset;data cleaning;ranking | null |
_unix.58067 | Possible Duplicate:Why is my variable being localized in one while read loop, but not in another seemingly similar loop I have a bash script that scraps URLs to feed a MySQL database. In my loop, I have a variable called query that gets filled ok, but when I try to output it, it always says it's empty!#!/bin/bash# get path to here[ -L $0 ] && P1=$(readlink $0) || P1=$0P2=$(dirname $P1)# slugify the name of the city into URL formatfunction slugify() { slug=$@ echo $slug | tr '[A-Z]' '[a-z]' | sed 's/\s/-/g'}echo Getting list of cities from csv filei=$(( 0 )) # lines readg=$(( 0 )) # curl OKf=$(( 0 )) # number of pages not found# total number of cities in CSV filelines=$(wc -l $P2/docs/cities.csv | cut -d' ' -f1)# Reading CSV file line by linewhile read ROWdo # getting city iso_code city_iso_code=$(echo $ROW | cut -d, -f1| sed -e 's/.$//' | sed 's/^FR\([^A-Z0-9]\+\)//') # getting city name city_name=$(echo $ROW | cut -d, -f3 | sed s/'/\\\'/g | sed -e 's/.$//') # stop after 1 good result to see if everything ok # [[ $city_name == A* ]] || { [ $g -gt 1 ] && { echo 'Done for today' # THIS IS WHERE query is empty when it should not!! echo Query: <$query> exit } # slugify city name city_slug=$(slugify $city_name) # construct url to fetch city_url=http://******/****$city_slug.html # visual teller echo -en \r$g ok, $f not found | $city_name | $city_url # check if page exists, if so scrap it, else fill the Not found page # I realize I am doing 2 curl Calls for every request :( [ $(curl -s -o /dev/null -w %{http_code} $city_url) -eq 200 ] && { # increment the total of OK g=$(( g + 1 )) # getting contents and scrapping it curl 2>/dev/null $city_url | sed 's/</\n/g' | grep 'td id=r' | cut -d'>' -f 2 | sed s/'/\\\'/g | while read street do # constructing query query=$query insert into cc_streets (city_iso_code,street_name) values ('FR $city_iso_code','$street'); done } || { # not found f=$(( f + 1 )) notfound=$notfoundFR $city_iso_code,$city_name,$city_url } i=$(( i + 1 ))done < $P2/docs/cities.csvSo in the WHILE loop,when I echo 'Done for today', and try to output the variable query, it says it's empty, but I know the query variable gets filled alright if I echo query in the second WHILE, so query gets reset at one moment in the loop but I can't quite get when. Anybody has a clue as why it does not work? Thanks for your insight! | question about a 'while' logics error | bash | null |
_unix.48416 | I want to creat a script to run an another script with a several parameterexp=([1]=bloc [2]=ins [3]=rep [4]=op)for j in ${!exp[*]}do arr=([1]=mem [2]=gen [3]=usr) for i in ${!arr[*]} do var=bash createGnuploat.sh ${exp[j]} ../Result/ 0 ${arr[i]} ${exp[j]} $var donedoneAnd i have this error :run.sh: line 9: =bash createGnuploat.sh op ../Result/ 0: Aucun fichier ou dossier de ce typeWhat's problem please ? | run bash in script | bash;shell script;quoting | If you need to store a command in a variable, don't use a string, that just can't work. See Bash FAQ #50. Use a function or an array.Your line is parsed as the assignment var=bash createGnuploat.sh ${exp[j]} ../Result/ 0 followed by the two words ${arr[i]} (which will be taken as a command name) and ${exp[j]} (which will be the first and only argument to the command). Check the syntax highlighting in your question or in your editor, it shows what is inside the quoted string.Always use double quotes around variable substitutions, e.g. $foo. Otherwise the value of the variable is split into words that are interpreted as glob patterns. (Omit the double quotes in the 0.01% of the cases where this is desired behavior.) For an array, use ${foo[@]} to have each element of the array in a separate word (${foo[*]} is a single word with the elements of the array separated by spaces; if you leave out the quotes, then each element is broken into separate words that are interpreted as glob patterns).Here's your snippet rewritten using a function:create_plot () { bash createGnuploat.sh ${exp[$2]} ../Result/ 0 ${arr[$1]} ${exp[$2]}}for j in ${!exp[@]}do arr=([1]=mem [2]=gen [3]=usr) for i in ${!arr[@]} do create_plot $i $j donedoneFor the rare cases where it makes sense to use an array variable instead of a function:for j in ${!exp[@]}do arr=([1]=mem [2]=gen [3]=usr) for i in ${!arr[@]} do var=(bash createGnuploat.sh ${exp[j]} ../Result/ 0 ${arr[i]} ${exp[j]}) ${var[@]} donedone |
_unix.10706 | Okay, so I'm trying to setup a login for logging in with ssh, using a public key. First, I am using puttygen to generate a rsa-ssh2 public key using a passphrase. I followed the directions and generated the key. I saved the private key in its own file for putty and puttygen also generated the public key.In putty I set it up to use the private key file and use rsa-ssh2 etc...So I c/p'd my houtput ssh2 public key stuff from puttygen and on the server, I put that into username/.ssh/authorized_keysSo I tried to then login through putty and first it prompted me for my username instead of asking for passphrase, and then when I entered it in (I tried both username and passphrase) it said my public key was invalid. I thought maybe I somehow c/p'd or formatted the info into authorized_keys wrong, so I went back and double checked. I made sure it was all on one line, properly spaced etc...I also checked in the following file /etc/ssh/ssh_config and I have the following:IdentityFile ~/.ssh/id_rsaI tried renaming my authorized_keys file to id_rsa and no joy.I tried changing that line in ssh_config to IdentityFile ~/.ssh/authorized_keys...and no joy.I went back to thinking maybe my public key was malformed or that putty wasn't configured properly so I asked a friend to make a temp account for me on his server and add my public key and I was able to login through putty just fine...when I connected to his server, it prompted me for the passphrase for my key and logged me in just fine. So he suggested I look at that stuff above but no joy and he doesn't know what else to check soo...I guess I'm appealing to the experts here :Pthoughts? | setting up ssh public key | ssh;authentication | null |
_codereview.158679 | Is this a good Singleton implementation? Is there anything I should be aware of? If so, how can it be improved?template <class T>class Singleton{public: static T& getInstance() { static T instance; return instance; }protected: Singleton() {} ~Singleton() {}private: Singleton(Singleton const&); void operator=(Singleton const&);};Usage example:#include <stdio.h>class A : public Singleton<A> {public: A() { a = 100; } int get_a() { return a; } void set_a(int v) { a = v; }private: int a;};A& s = A::getInstance();void free1() { printf(%d\n, s.get_a());}void free2() { s.set_a(200);}void free3() { printf(--> %d, s.get_a());}void main() { free1(); free2(); free3();}Let's consider an alternative to avoid the usage of Singletons, instead having:class A : public Singleton<A>let's say it becomes:class Aand let's say we define a global variable:A g_s = A();and then this global variable will be accessed by other files using external, would that bring some sort of benefit?external A g_s; | C++ singleton using templates | c++;singleton | null |
_softwareengineering.209520 | I'm currently in the process of modelling a generic form of RNA and RNA transcription and I'm having difficulty finding a proper OO modeling of this area.Human RNA has 4 types of Nucleotides (A, G, U, and C). An RNA strand is just a string of these 4 types. eg, AAGACAUUCUA...What I'm trying to model is more generic in the sense that I want to be able to decide the number of Nucleotide types at runtime. So, my object model needs to be able to represent an arbitrary number Nucleotide types.Initially, I thought I'd just have a Nucleotide class which had a int TypeId member. This way, I could have a sequence of Nucleotide instances of arbitrary types... but this doesn't feel right.I'm not a huge fan of storing type in a variable. I'm also not comfortable with what is essentially definition information being set on every instance (instead of being defined in the a class).So, how do I get around this? Here's what I've come up with so far:On a previous project, we would have Singleton objects which represented another object's type. The other object would simply reference the singleton and that was it. It prevented us from having multiple instantiations of the definition of our types. Not too great IMO.I remember Entity Framework generating Dynamic Proxies at runtime. I could so something similar. I could have a NucleotideBase base class and, at runtime, define derived classes. I believe this is possible through reflection. I'm not sure what the performance impact is with this approach, but I would assume it's all just one-time overhead when defining the classes.Are there better, more OO, approaches? | How to model an arbitrary number of types | object oriented;modeling | If a nucleotide has no significant behavior, and if its type information can be represented compactly (for example, a single character), then it doesn't deserve a separate class at all. Simply represent each nucleotide as a character (or whatever).If, however, a nucleotide has behavior, then I would model this with singletons, one instance per nucleotide type.Since there is no difference in behavior in nucleotides, they are simple value objects. A nucleotide instance should be immutable, so that all nucleotides of a given type can be represented by a single instance.I would like to use the nucleotide's symbol as its type; this would be the sole instance variable of a Nucleotide.A nucleotide factory can keep track of the singleton instances of nucleotide, creating a new instance when a new nucleotide type is asked for, or returning an existing instance otherwise. Depending upon the language, it may be convenient for this factory to be implemented in static methods of the nucleotide class. |
_unix.344317 | I need to install a .deb package on a raspberryPi that doesn't have connectivity. When I try to install such package using:sudo dpkg -i <name>.deb I get the error:dpkg: dependency problems prevent configuration of rtl8192eu-dkms: rtl8192eu-dkms depends on dkms (>= 1.95); however: package dkms is not installed.dpkg: error processing package rtl8192eu-dkms (--install) dependency problems - leaving unconfigurederrors were encountered while processing: rtl8192eu-dkmsI do have another windows machine that I could download files from, but where do I get those files? | Raspbian/Debian - Install .deb offline | debian;raspbian;dkms | You must install dkms and all its dependencies at the same time or before installing rtl8192eu-dkms. For example: dpkg -i rtl8192eu-dkms.deb dkms.deb or dpkg -i dkms.deb && dpkg -i rtl8192eu-dkms.deb. |
_unix.233589 | Disclaimer: Total Linux noob.I came across a Bash script with with the following command:$ mkdir -p /root/.sshI know what mkdir -p does, but, what is /root/? I thought root was '/'? | Command Explanation: mkdir -p /root/.ssh | directory;root | null |
_unix.372110 | I have a program which manages processes. It is designed for managing long-running processes, and when one of its processes exits, even successfully, then the whole process manager closes.For example, I have this config file for the process manager:foo: foo --do-foobar: bar --do-barThe foo command might exit 0, causing the whole process manager (and thus also the command bar --do-bar) to close.Avoiding submitting a change to said process manager, or using a different one, I'm thinking I can fool it into not exiting by adding another innocuous command to the end of my command which will cause it to stall, and thus the process manager will not close. Some ideas that come to mind are calling && ruby or && read to make the command stall.So, returning to my previous example, I would change my config file to:foo: foo --do-foo && readbar: bar --do-barThen, even if foo --do-foo exited 0, the command would stall because I called read, and then the process manager would not close.Are either ruby or read innocuous and/or cheap commands to run to trick my process manager? Or is there an even simpler command that I could run to make the process stall and consume very few / none system resources? | Easy way to create a meaningless, cheap, long-running process? | process;command | null |
_unix.99211 | I am able to connect remotely to the machine using SSH, but I cannot ping www.google.com through the machine.I did the following to make sure SSH was enabled (well I know it is, as I am using PuTTy):# svcs sshSTATE STIME FMRIonline 9:56:08 svc:/network/ssh:defaultThe machine name is:# uname -aSunOS solaris 5.11 11.1 i86pc i386 i86pcAnd the precise version is:# cat /etc/releaseOracle Solaris 11.1 X86Copyright (c) 1983, 2012, Oracle and/or its affiliates. All rights reserved.Assembled 19 September 2012I am trying to install gcc, but it cannot contact valid package repository:# pkg install gcc-45pkg: 0/1 catalogs successfully updated:Unable to contact valid package repositoryEncountered the following error(s):Unable to contact any configured publishers.This is likely a network configuration problem.Framework error: code: 6 reason: Couldn't resolve host 'pkg.oracle.com'URL: 'http://pkg.oracle.com/solaris/release' (happened 4 times)I don't understand that SSH can work, but my internet is not open.This is what ifconfig -a returns:# ifconfig -alo0: flags=2001000849<UP,LOOPBACK,RUNNING,MULTICAST,IPv4,VIRTUAL> mtu 8232 index 1 inet 127.0.0.1 netmask ff000000net0: flags=1000843<UP,BROADCAST,RUNNING,MULTICAST,IPv4> mtu 1500 index 2 inet 10.0.11.17 netmask ff000000 broadcast 10.255.255.255 ether 8:0:27:7:ad:7lo0: flags=2002000849<UP,LOOPBACK,RUNNING,MULTICAST,IPv6,VIRTUAL> mtu 8252 index 1 inet6 ::1/128net0: flags=20002004841<UP,RUNNING,MULTICAST,DHCP,IPv6> mtu 1500 index 2 inet6 fe80::a00:27ff:fe07:ad07/10 ether 8:0:27:7:ad:7net0 IPv4 is the correct IP address that I am using for SSH. The only way I could (possibly) get round it, is if I could edit the gateway and the DNS IP addresses.Any help to get this machine to see the internet, would be greatly appreciated. | Cannot Connect to Internet but can SSH into Solaris x86 (vs. 11) | networking;solaris | The message couldn't resolve host in the output to the pkg command suggests some fundamental misconfiguration of the network stack on the Solaris box. Given that you can connect to it over ssh from another machine on the LAN, we know its networking stack is initialised, and that it is passing packets correctly. The problem is therefore most likely to be due to a name resolution failure, or a missing gateway specification.The simplest way to find out which problem is causing your lack of service, is just to try to ping a machine on the Internet by its IP address. A successful response means that routing is fine, and we then need to look at the name resolution settings on the box. If the ping fails, however, it should give you a reason why.$ ping 8.8.8.8ping: sendto No route to hostIn this case, as you reported above in the comments, ping fails with a message that the network stack couldn't find a route to the remote host. On Solaris, there should be a file, /etc/defaultrouter, which contains the LAN IP address of your gateway machine. If that file doesn't exist, or contains the wrong IP address, that is the cause of your problem. Fix the file, and run route add default 10.0.11.1 to install the new default route in the IP stack now.When it boots, the system will automatically configure a default gateway based on the contents of /etc/defaultrouter - there should be no need to run the route add again manually. |
_reverseengineering.8154 | On Linux the strace.so pintool gives a good overview on how system calls are intercepted in PIN. One could monitor the value of EAX to see which system call is being invoked(and mprotect and writes could be intercepted in the fashion).How could we do something similar for Windows? I see that the int 2e interrupt is used to trap into the kernel and that the system calls numbers are given at here. Is NtWriteFile the analogue of write? Also is NtProtectVirtualMemory the analogue of mprotect? | pintool to intercept writes and VirtualProtect | operating systems;pintool;system call | Pintools on Windows can also aid you in instrumenting system calls. Also, if its discovered that the cpu supports sysenter/syscall, those are used in place of int 2e. However, this has no bearing on whether or not instrumentation can take place.To answer your second question, yes, NtReadFile, NtWriteFile and NtDeviceIoControlFile are the *nix equivalent of read/write/ioctl. |
_webapps.30282 | Background: Forwarding custom domain's email to and from GmailI've got a personal Gmail account that I've had for many years at [email protected]. Of course, the address isn't example, it's something I set up on a whim years ago. Now, I've got [email protected] via email forwarding in Namecheap, and would like to use that for all my future professional and public interactions. What I've done so far: Email forwarding and Send Mail AsI used Namecheap's domain configuration for All Host Records to use their Free Email Forwarding option, and added byname as the User Name and [email protected] as the Forwarded To address. I'd like to use Namecheap's email forwarding, as it's super easy, but I'm open to running my own mail server, as long as it, too, forwards mail to and from Gmail.Then, I set up the [email protected] account to send mail as [email protected] through Settings Accounts and Import Send Mail As, and I've tried this with Treat as an alias both set and cleared. The mail gets delivered, and shows that the sender is the [email protected] address, and clicking reply populates this address in the to field as it should. This is all well and good for 99% of the population. What's not workingUnfortunately, showing the original message from within Gmail reveals that the Sender, Return-Path, Received-SPF, and Authentication-Results all contain [email protected]. Why is this information leaked? Is this something I should be concerned about? Finally, and most importantly, how can I send mail from my new address and use Gmail as the mail server without leaking the Gmail address? | How can I remove all traces of my original Gmail address from a send mail as alias? | gmail;email;domain;email forwarding | null |
_cstheory.27450 | I'm faced with the problem of maintaining the strong components of a directed graph under insertions/deletions of edges and vertices.As noted in one of the answers to a closely-related question here, the literature in this area is rather fragmented and hard for a newcomer such as myself to approach.For example, the paper by Holm et al. appears to focus on undirected graphs, and it's unclear to me whether any of their results can be adapted to work with digraphs. Other papers I've found focus on either the incremental or decremental cases, rather than the fully-dynamic case.My need arises in a real-world software engineering scenario, so I would actually be fine with an approach that yields no worst-case asymptotic advantage over the naive idea of running an SCC algorithm from scratch for each update, so long as it performs well in practice.I'd prefer not to reinvent the wheel, but I also don't have endless hours to wade through the literature, so hopefully someone here can save me some time.Thanks in advance! | Fully dynamic algorithms for strong components of a directed graph | graph algorithms | null |
_unix.238482 | The first 2 lines in dd stats have the following format:a+b records inc+d records outWhy 2 numeric values? What does this plus sign mean?It's usually a+0, but sometimes when I use bigger block size, dd prints 0+b records out | What does the two numbers mean respectively in dd's a+b records stats? | dd | It means full blocks of that bs size plus extra blocks with size smaller than the bs.pushd $(mktemp -d)dd if=/dev/zero of=1 bs=64M count=1 # and you get a 1+0dd if=1 of=/dev/null bs=16M # 4+0dd if=1 of=/dev/null bs=20M # 3+1dd if=1 of=/dev/null bs=80M # 0+1_crap=$PWD; popd; rm -rf $_crap; unset _crap# frostschutz's caseyes | dd of=/dev/null bs=64M count=1 # 0+1Edit: frostschutz's answer mentions another case to generate non-full blocks. Worth reading. See also https://unix.stackexchange.com/a/17357/73443. |
_cs.56823 | I am studying with Game theory right now. In Nim game, in any turn, a player can move any number of stones from any one pile. I am wondering what might be the winning strategy of first player if in any move, a player can pick any number of stones from one or more piles? In this case, how the xor = 0 rule will work? Both are playing optimally. | Winning strategy of Nim game when picking from multiple piles is allowed | algorithms;game theory | The answer assumes that you have to take the same amount of stones from each pile that you choose. Otherwise the first player always wins as long as the piles are not all empty.The rule xor = 0 doesn't work. In particular, there is a winning position with xor = 0 (easy exercise; be creative). In order to analyze the game, you can compute which positions are winning and which are losing recursively (surely you have been shown how to do that in your course). Then you can look at which positions are winning and which are losing, and try to guess a rule; you will then need to prove that your rule works.In this particular case, however, the analysis will be quite difficult. The case of two piles is known as Wythoff's game, and is already pretty non-trivial to analyze. |
_unix.257599 | I found simmilar problem here: Missing mdadm raid5 array reassembles as raid0 after powerout, but mine is a bit different.Here too my raid5 reassembles as raid0, but i don't see any of my devices marked as spare in mdadm -E /dev/sdX1 output: /dev/sdb1: Magic : a92b4efc Version : 1.2 Feature Map : 0x0 Array UUID : 9b244d41:0b94c8f7:0da323ac:f2a873ec Name : bekap:0 (local to host bekap) Creation Time : Wed Oct 9 16:03:25 2013 Raid Level : raid5 Raid Devices : 3 Avail Dev Size : 5860268032 (2794.39 GiB 3000.46 GB) Array Size : 5860267008 (5588.79 GiB 6000.91 GB) Used Dev Size : 5860267008 (2794.39 GiB 3000.46 GB) Data Offset : 262144 sectors Super Offset : 8 sectors Unused Space : before=262064 sectors, after=1024 sectors State : active Device UUID : f8405c86:85d8bade:8a74b0f5:fec08e3f Update Time : Sat Jan 16 04:41:05 2016 Checksum : da1a9cb2 - correct Events : 134111 Layout : left-symmetric Chunk Size : 512K Device Role : Active device 0 Array State : AA. ('A' == active, '.' == missing, 'R' == replacing)/dev/sdc1: Magic : a92b4efc Version : 1.2 Feature Map : 0x0 Array UUID : 9b244d41:0b94c8f7:0da323ac:f2a873ec Name : bekap:0 (local to host bekap) Creation Time : Wed Oct 9 16:03:25 2013 Raid Level : raid5 Raid Devices : 3 Avail Dev Size : 5860268032 (2794.39 GiB 3000.46 GB) Array Size : 5860267008 (5588.79 GiB 6000.91 GB) Used Dev Size : 5860267008 (2794.39 GiB 3000.46 GB) Data Offset : 262144 sectors Super Offset : 8 sectors Unused Space : before=262064 sectors, after=1024 sectors State : active Device UUID : d704efde:067523c1:a6de1be2:e752323f Update Time : Sat Jan 16 04:41:05 2016 Checksum : 124f919 - correct Events : 134111 Layout : left-symmetric Chunk Size : 512K Device Role : Active device 1 Array State : AA. ('A' == active, '.' == missing, 'R' == replacing)/dev/sdd1: Magic : a92b4efc Version : 1.2 Feature Map : 0x0 Array UUID : 9b244d41:0b94c8f7:0da323ac:f2a873ec Name : bekap:0 (local to host bekap) Creation Time : Wed Oct 9 16:03:25 2013 Raid Level : raid5 Raid Devices : 3 Avail Dev Size : 5860268032 (2794.39 GiB 3000.46 GB) Array Size : 5860267008 (5588.79 GiB 6000.91 GB) Used Dev Size : 5860267008 (2794.39 GiB 3000.46 GB) Data Offset : 262144 sectors Super Offset : 8 sectors Unused Space : before=262064 sectors, after=1024 sectors State : clean Device UUID : c52383f7:910118d3:e808a29f:b4edad2c Update Time : Mon Dec 28 10:46:40 2015 Checksum : d69974b5 - correct Events : 52676 Layout : left-symmetric Chunk Size : 512K Device Role : Active device 2 Array State : AAA ('A' == active, '.' == missing, 'R' == replacing)But they are marked as S (which as far as I know stands for spare) in /proc/mdstat (and there are no personalities for md0):Personalities : md0 : inactive sdb1[0](S) sdd1[3](S) sdc1[1](S) 8790402048 blocks super 1.2unused devices: <none>Here is mdadm -D /dev/md0 output:/dev/md0: Version : 1.2 Raid Level : raid0 Total Devices : 3 Persistence : Superblock is persistent State : inactive Name : bekap:0 (local to host bekap) UUID : 9b244d41:0b94c8f7:0da323ac:f2a873ec Events : 134111 Number Major Minor RaidDevice - 8 17 - /dev/sdb1 - 8 33 - /dev/sdc1 - 8 49 - /dev/sdd1So I'm a bit confused why it can't reassemble this array if it has two (I would say good devices) out of three. I'm not sure if mdadm -D /dev/md0 showed it as raid0 since the failure or if I just messed it up while trying to reassemble the array (I tried mdadm --stop /dev/md0 and mdadm --assemble --scan --verbose and mdadm --assemble --scan --verbose /dev/md0 /dev/sdb1 /dev/sdc1 or something simmilar - I can try to get exact commands if it is necessary).So, my question: can I remove sdd1 from array, then assemble md0 without it and then add sdd1 again? Or should I use --assemble --force --run as mentioned in the linked question? Or something else? I'm quite unexperienced with linux raid and mdadm. Thanks a lot. | raid5 array reassembles as raid0 | mdadm;software raid;raid5;raid0 | Ok, just to conclude this - basically, what was said in that link helped, here are my exact commands: mdadm --assemble --force /dev/md0 /dev/sdb1 /dev/sdc1mdadm --add /dev/md0 /dev/sdd1 (--re-add didn't work), after this it started resyncing - took about 20 hoursThen, since there is lvm over:lvchange -ay data/datafsck /dev/data/dataThanks for help. |
_cs.70749 | I want to use Vertex Cover as a known NP Complete Problem for the reduction. The claim is that If a have a vertex cover in graph G with size $\le$ k, I will have a clique cover in $G\prime$ with total number of cliques $\le$ kI want to reduce vertex cover problem to clique cover problem in the following way:For each edge in graph G, I will create a corresponding vertex in $G\prime$. In the picture, each e$_i$ in G corresponds to v$_i$ in $G\prime$ for 1$\le$i$\le$5Two vertices in $G\prime$ will be connected by an edge if their corresponding two edges in G have one vertex in common. For example, there is an edge between v$_1$ to v$_2$ as their corresponding edges e$_1$ and e$_2$ have one vertex in common which is a.Each clique in $G\prime$ corresponds to a vertex in G and that vertex belongs to the vertex cover. For example, for the graph in picture I have vertex cover {a,c}. With vertex a, I get a clique {v$_1$, v$_2$, v$_5$} and with vertex c, I get clique {v$_3$, v$_4$} in $G\prime$.Now I don't know how to prove No instance in opposite direction: If $G\prime$ doesn't have a clique cover with $\le$ k cliques (i.e it needs at least k+1 cliques), G doesn't have a vertex cover size which is $\le$ k.Can anybody shed some light on this issue? | Prove that clique cover is NP Complete | np complete;reductions | null |
_softwareengineering.230998 | I recently took a software processes course and this is my first time attempting OO design on my own. I am trying to follow OO design principles and C++ conventions. I attempted and gave up on MVC for this application, but I am trying to decouple my classes such that they can be easily unit-tested and so that I can easily change the GUI library used and/or the target OS. At this time, I have finished designing classes but have not yet started implementing methods.The function of the software is to log all packets sent and received, and display them on the screen (like WireShark, but for one local process only). The software accomplishes this by hooking the send() and recv() functions in winsock32.dll, or some other pair of analogous functions depending on what the intended Target is. The hooks add packets to SendPacketList/RecvPacketList. The GuiLogic class starts a thread which checks for new packets. When new packets are found, it utilizes the PacketFilter class to determine the formatting for the new packet, and then sends it to MainWindow, a native win32 window (with intent to later port to Qt).1Full size image of UML class diagramHere are my classes in skeleton/header form (this is my actual code):class PacketModel{protected: std::vector<byte> data; int id;public: PacketModel(); PacketModel(byte* data, unsigned int size); PacketModel(int id, byte* data, unsigned int size); int GetLen(); bool IsValid(); //len >= sizeof(opcode_t) opcode_t GetOpcode(); byte* GetData(); //returns &(data[0]) bool GetData(byte* outdata, int maxlen); void SetData(byte* pdata, int len); int GetId(); void SetId(int id); bool ParseData(char* instr); bool StringRepr(char* outstr); byte& operator[] (const int index);};class SendPacket : public PacketModel{protected: byte* returnAddy;public: byte* GetReturnAddy(); void SetReturnAddy(byte* addy);};class RecvPacket : public PacketModel{protected: byte* callAddy;public: byte* GetCallAddy(); void SetCallAddy(byte* addy);};//problem: packets may be added to list at any time by any number of threads//solution: critical section associated with each packet listclass Synch{public: void Enter(); void Leave();};template<class PacketType> class PacketList{private: static const int MAX_STORED_PACKETS = 1000;public: static const int DEFAULT_SHOWN_PACKETS = 100;private: vector<PacketType> list; Synch synch; //wrapper for critical sectionpublic: void AddPacket(PacketType* packet); PacketType* GetPacket(int id); int TotalPackets();};class SendPacketList : PacketList<SendPacket>{};class RecvPacketList : PacketList<RecvPacket>{};class Target //one socket{ bool Send(SendPacket* packet); bool Inject(RecvPacket* packet); bool InitSendHook(SendPacketList* sendList); bool InitRecvHook(RecvPacketList* recvList);};class FilterModel{private: opcode_t opcode; int colorID; bool bFilter; char name[41];};class FilterFile{private: FilterModel filter;public: void Save(); void Load(); FilterModel* GetFilter(opcode_t opcode);};class PacketFilter{private: FilterFile filters;public: bool IsFiltered(opcode_t opcode); bool GetName(opcode_t opcode, char* namestr); //return false if name does not exist COLORREF GetColor(opcode_t opcode); //return default color if no custom color};class GuiLogic{private: SendPacketList sendList; RecvPacketList recvList; PacketFilter packetFilter; void GetPacketRepr(PacketModel* packet); void ReadNew(); void AddToWindow();public: void Refresh(); //called from thread void GetPacketInfo(int id); //called from MainWindow};I'm looking for a general review of my OO design, use of UML, and use of C++ features. I especially just want to know if I'm doing anything considerably wrong.From what I've read, design review is on-topic for this site (and off-topic for the Code Review site).Any sort of feedback is greatly appreciated. Thanks for reading this. | Is this proper OO design for C++? | design;c++;object oriented;object oriented design | null |
_unix.137693 | This is my bash script.#!/bin/bashoo=`cat /etc/httpd/conf/httpd.conf`;cat > /a.txt << EOF$ooEOFit simply reads /etc/httpd/conf/httpd.conf and writes it to /a.txt, the problem has been when this is executed via web scripts with sudo command.. for some reason not everything is written to the a.txt filebut when executed via command line.. everything is written just fine to a.txtso perhaps i should send this to a background process by adding:> /dev/null 2>&1to it. but how can this be done? i tried#!/bin/bashoo=`cat /etc/httpd/conf/httpd.conf`;cat > /a.txt << EOF$ooEOF > /dev/null 2>&1this did not work. | How to fork a cat command? | bash;cat;fork | Maybe this example is just extremely oversimplified, but I'm having trouble seeing why you wouldn't just run:cp /etc/httpd/conf/httpd.conf /a.txtThat is, there's already a command that simply reads from one file and creates another with its contents, and it's called cp. The only real difference would be if /a.txt already existed and you were trying to retain its permissions, or some such - but even then, you'd want to just do:cat /etc/httpd/conf/httpd.conf >/a.txt |
_unix.158255 | I have the following iptables rule:iptables -t mangle -A PREROUTING -p udp -m udp --dport 10000 -j MARK --set-xmark 0x4/0xffffffffwhich sets fwmark 4 on all udp packets with destination port 10000. I forward it to a tunnel (without any nat) with policy-based routing:[root@localhost ~]# ip rule0: from all fwmark 0x4/0x4 lookup 87 32765: from all lookup local 32766: from all lookup main 32767: from all lookup default [root@localhost ~]# ip route show table 87default dev tunnel scope link Everything works correctly if the packet comes from a normal NIC (eth0 etc.), but packets that travel on the loopback interface (lo, for example packets generated with socat -u - UDP:localhost:10000) seem to skip the routing decision after the PREROUTING chain, and get received by the local host (which in fact replies with an ICMP port unreachable packet over the lo interface).Is this expected behavior? If so how can I workaround that? I need packets not to have different paths for different input devices, as I want to use lo to test my more complex iptables ruleset (that is, an extra rule with nat won't be a solution for me). | Forwarding packets from loopback interface with policy-based routing | iptables;routing;port forwarding;tunneling | null |
_unix.106782 | I've been using similar config for years:Section InputClass Identifier keyboard-all MatchIsKeyboard on Driver evdev Option XkbLayout us,ru,de Option XkbVariant ,winkeys, Option XkbOptions terminate:ctrl_alt_bksp,grp:ctrl_shift_toggleEndSectionAfter updating to a newer version of my distro both right Ctrl+Shift and left Ctrl+Shift switch keyboard layout only in one direction us -> ru -> de. It used to work like this before:Right Ctrl+Shift: us -> ru -> deLeft Ctrl+Shift: us -> de -> ru (reverse order)Is there any way to restore the old behavior? | Keyboard layout switch (Ctrl+Shift) in a new xorg | xorg;keyboard layout;xkb | Ok, so here is where the story starts: https://bugs.freedesktop.org/show_bug.cgi?id=42931It seems that someone didn't like the old behavior so it was changed to one-directional.Although man-page in my xkeyboard-config-2.6 doesn't have all the options supported, there are _bidir switch options, which you can use. Thus to restore the old behavior your config (or corresponding setxkbmap command) should look like this:Section InputClass Identifier keyboard-all MatchIsKeyboard on Driver evdev Option XkbLayout us,ru,de Option XkbVariant ,winkeys, Option XkbOptions terminate:ctrl_alt_bksp,grp:ctrl_shift_toggle_bidirEndSection |
_unix.38857 | I use Ubuntu on VMware to learn how to use Linux. I used rm on some folders and mistakenly deleted some files from /etc. I have some very important files on it. Is there a way to retrieve that files, for example using Knoppix? If yes, how I can do it? | Retrieve deleted files on Linux VM guest | linux;ubuntu;data recovery;vmware | null |
_unix.14640 | I know I have done this before, so I'm sure it's possible, I just forget how to do it. There's a way to tell convert to grab a specific page of a PDF, and I'd like to keep the format of that page as PDF. | Use convert to grab a specific page from a PDF file? | pdf;imagemagick | ImageMagick is a tool for bitmap images, which most PDFs aren't. If you use it, it will rasterize the data, which is often not desirable.Pdftk can extract one or more pages from a PDF file.pdftk A=input.pdf cat A42 A43 output pages_42_43.pdfIf you have a LaTeX installation with PDFLaTeX, you can use pdfpages. There's a shell wrapper for pdfpages, pdfjam.pdfjam -o pages_42_43.pdf input.pdf 42,43Another possibility (overkill here, but useful for requirements more complex that one page) is Python with the PyPdf library.#!/usr/bin/env pythonimport copy, sysfrom pyPdf import PdfFileWriter, PdfFileReaderinput = PdfFileReader(sys.stdin)output = PdfFileWriter()for i in [42, 43]: output.addPage(input.getPage(i))output.write(sys.stdout) |
_webmaster.24558 | Related - SEO for naming imagesIn an effort to increase the perceived speed of a heavy homepage, I'm loading a number of the heavier images via javascript on document.ready. I'm using a blank gif as a placeholder src in my img tags with all of the appropriate alt and title tags. When the document is ready, then, I simply swap out the src for the img tags with the real image that I want displayed.All of the images are named SEO appropriate names and alt and title tags are filled with (non-keyword-stuffed) SEO appropriate content.Will this technique have any impact, positive or negative, on how Google perceives and scores the page? | Will delay loading images hurt SEO? | seo;images;ranking | It shouldn't have any effect on the page itself, but by using blank images you won't get any rankings in Image Search.I would first look at reducing the file size of the images on the homepage if possible, e.g. via PNGcrush or using lower-quality JPEGs. Any non-content images can be moved to CSS sprites and loaded as one background image to save on HTTP requests. |
_codereview.151864 | I'm learning Haskell, and there was quicksort implementation, so I thought that I could implement it in a similar way in JavaScript. The result:const quicksort = ([x, ...xs], compareFn = (a, b) => a - b) => { // If x is undefined, the array is empty if (x === undefined) return []; const smallerSorted = quicksort(xs.filter(a => compareFn(a, x) <= 0), compareFn); const biggerSorted = quicksort(xs.filter(a => compareFn(a, x) > 0), compareFn); return [...smallerSorted, x, ...biggerSorted];};// Example usage:console.log(quicksort( Array.from({ length: 10 }).map(_ => Math.floor(Math.random() * 100))));console.log(quicksort( Array.from('a quick brown fox jumped over a lazy dog'), (a, b) => a.charCodeAt(0) - b.charCodeAt(0)).join(''));.as-console-wrapper { max-height: 100% !important; }I realize that calling filter() twice might be inefficient, so I made an alternative version, using the _.partition() function from Lodash:const quicksort = ([x, ...xs], compareFn = (a, b) => a - b) => { // If x is undefined, the array is empty if (x === undefined) return []; const [smallerSorted, biggerSorted] = _.partition( xs, a => compareFn(a, x) <= 0 ).map(arr => quicksort(arr, compareFn)); return [...smallerSorted, x, ...biggerSorted];}; | Quicksort in JavaScript using destructuring and spread syntax | javascript;reinventing the wheel;comparative review;ecmascript 6;quick sort | null |
_webmaster.1689 | I've noticed more and more sites have gone to a fixed-width layout, where resizing the browser window just causes scrollbars to appear, as opposed to a flexible layout, where resizing the browser causes the components of the page to scrunch together.The StackExchange sites like this one are an example of the fixed layout. GMail and iGoogle are examples of the flexible layout. What are the reasons for choosing one over the other? | Fixed width vs dynamic width | website design | More complex designs can be very difficult to realize with variable width layout. So I imagine that plays a role.There is also the fact that it is not comfortable to read text that is very wide. The column size on StackExchange sites is quite manageable and easy to read. With a variable width layout, you can not just extend the main text body across without it becoming illegible. Even Google limits the width of their search results.Of course if you have a site where space is at a premium (like Google Docs and Google Maps) you really want to go with a variable width scheme to use all the available space. |
_codereview.149183 | This sample code is correct and no error however this only good if you only have few hundreds or thousand datas but if you have million queries this takes time how we can improve this algorithm namespace :auto_status do desc Add Status to the Tracking code Automaticaly task make_status: :environment do @product_trackers = ProductTracker.all @statuses = Status.all @date = DateTime.now.utc @product_trackers.each do |product_tracker| if (Status.where(product_tracker_id: product_tracker.id).count == 1 && (((Time.parse(DateTime.now.to_s) - Time.parse(Status.where(product_tracker_id: product_tracker.id).first.created_at.to_s))/1.days).round) == 1) @links = Status.new @links.order_status = 1 @links.product_tracker_id = product_tracker.id @links.save elsif (Status.where(product_tracker_id: product_tracker.id).count == 2 && (((Time.parse(DateTime.now.to_s) - Time.parse(Status.where(product_tracker_id: product_tracker.id).first.created_at.to_s))/1.days).round) == 2) @links = Status.new @links.order_status = 2 @links.product_tracker_id = product_tracker.id @links.save elsif (Status.where(product_tracker_id: product_tracker.id).count == 3 && (((Time.parse(DateTime.now.to_s) - Time.parse(Status.where(product_tracker_id: product_tracker.id).first.created_at.to_s))/1.days).round) == 5) @links = Status.new @links.order_status = 3 @links.product_tracker_id = product_tracker.id @links.save elsif (Status.where(product_tracker_id: product_tracker.id).count == 4 && (((Time.parse(DateTime.now.to_s) - Time.parse(Status.where(product_tracker_id: product_tracker.id).first.created_at.to_s))/1.days).round) == 6) @links = Status.new @links.order_status = 4 @links.product_tracker_id = product_tracker.id @links.save end end endend | How to run this code faster | algorithm;ruby;ruby on rails | null |
_unix.174910 | I have a DELL server R610, on this server there is a RHEL 6.4This server has an idrac entreprise.I would like to configure the idrac from command line, avoiding reboot.I read on the man page of ipmitool that I can use a command like : #ipmitool lan set 1 mode dedicatedbut the command return man page : usage: lan set <channel> <command> <parameter>I check another command from the man page, which is not existing on my server neither : #ipmitool lan get Others commands are working without issue like : #ipmitool lan printI am running ipmitool : ipmitool-1.8.11-13.el6.1.x86_64I am wondering why I don't have all of the command available from man page ? Any idea ? | ipmitool set idrac mode | linux;command line;remote management | Up until a few years ago, ipmitool was undergoing rapid development. On some Linux distributions from around that time, the man page may not describe all the commands supported by the executable.In your case, setting Dell DRAC and iDRAC parameters is supported by ipmitool 1.8.11, and is done using the ipmitool delloem command. So you could use these commands:ipmitool delloem lan getipmitool delloem lan set dedicated |
_unix.89660 | Is there any way I could trigger a bash script when ssh times out?I have an alias to set the tmux title when starting ssh. The alias also includes a title change after the ssh session, which works if I do a clean exit, but if the session times out, the rest of the alias doesn't run. | Detecting SSH timeout | bash;ssh;error handling | null |
_scicomp.20571 | I'm trying to develop an inferential procedure for a multivariate dependent Markov process. Basically, the procedure could be considered as a non linear regression, with a known dependence structure among observation belonging to the same time-point and independent from the others. The non linear trend correspond to a the solution of a matrix differential equation. A more detailed description follows:Let define a matrix $\Theta$ of parameters $\theta_i$\begin{array}{ccc}\theta_1 & \theta_4 & \theta_7 \\\theta_2 & \theta_5 & \theta_8 \\\theta_3 & \theta_6 & \theta_9 \end{array}each entry $\theta_i$ could be unconstrained or linearly constrained (both equality and inequality).This matrix, multiply by a given, fixed matrix $V$ and a vector of previous time point $\vec{X}$ observation, governs the derivative of a stochastic process.As a consequence, in my objective function $\sum(\vec{Y}-f(\Theta,\vec{X}))^2$, I need to calculate the solutions of the matrix differential equation, $f(\Theta,\vec{X})$. To calculate the solutions, I need to calculate a matrix $A$, combining the entries of $\Theta$ according to $V$, calculate eigen decompositions of $A$ and finally the solution $\hat Y=f(\Theta,\vec{X})$ (exponential). The objective function is non-convex and has many local minima. Runnig some simulations studies, I verified that the global minimum is located at the true parameters values, and the objective is convex in the closed neighbourhood. Until now, I used a constrained Gauss-Newton method to estimate parameters, and, given good initial values, it works. Relaxing some conditions, the method to calculate initial values is not good enough to guarantee the Gauss-Newton method to converge to global minimum (it get stucks in a closed local minimum). So, I'm now looking for a global optimizer. All my code is in R and RCplex and I have some experience with C++. Is Cplex able to solve non-convex,linearly constrained problem and flexible enough to allow me for solve the matrix differential equation? Are there any alternative program? Any suggestion?Thanks. | non convex, non linear optimization involving matrix differential equation solution | eigenvalues;constrained optimization;nonlinear programming;stochastic;nonconvex | null |
_unix.57409 | In another question it was suggest that I useshopt -s extglobTo fix a problem. I get the impression that these type commands are to be used sparingly, perhaps because they can have ill effects with other scripts. Can anyone speak to this? | Dangers of shopt | bash | shopt only affects the behavior of the shell that that command is run in. If you put it in ~/.bashrc then, it will affect non-login interactive shells and commands run over rsh/ssh (login shells may also be affected if ~/.bashrc is sourced in ~/.profile or ~/.bash_profile).Setting the environment variable BASHOPTS to extglob will affect all interactive or non-interactive bash shells started while that environment variable is set (unless they're called as sh).Interactive shells are where you want to have extglob set because that's where you want to use it, so ~/.bashrc is a good place to put it to benefit from it in every interactive shell. If you want to use it in a script, just add it at the start of the script.The only place where that could cause problem is when it is set while some code that you didn't write doesn't expect it to be set. That could be for instance scripts that you source at the prompt or in ~/.bashrc after you've set the option.While that is true for some options, it is not for extglob as it was carefully designed (by David Korn as that comes from ksh) so as not to break backward compatibility with the Bourne shell (and explains why the syntax is so awkward).Basically, anything using extended globs would be a syntax error in the Bourne shell or in the POSIX shell syntax. If a Bourne or POSIX script had echo @(a), it would be broken (because of the unquoted parenthesis). It wouldn't matter if all of a sudden it started to output a instead of an error message.Why bash doesn't enable it by default is not clear to me, given that bash doesn't have any other alternative extended glob syntax of its own like zsh does.EDIT. While David Korn tried hard not to break Bourne/POSIX compatibility, it looks like bash wasn't so careful and is probably why it's not enabled by default like in ksh.In ksh (and zsh in ksh emulation), the extended globbing operators are disabled when performing globbing upon parameter or command substitution:$ touch a$ a='@(a)' ksh93 -c 'echo $a'@(a)While in bash, it's not the case:$ a='@(a)' BASHOPTS=extglob bash -c 'echo $a'a |
_webmaster.75758 | when I google my own domain name, I don't even rank for it. Instead, my terms of service page gets indexed and shows up on the second page! My blog shows up here as well (it's hosted by another service) but my main home page and any of it's pages doesn't even appear on the search results.I see the same thing on bing, and yahoo. Main page doesn't show up.the domain name is not too generic but unique enough, it uses .la domainHave I been banned from google? What the hell is going on?The domain is 4 years old and I've done a redesign 4 months ago. | 4 year old domain doesn't show up in google search results | google;serps | null |
_unix.362190 | I was trying to move a file with mv to see it works and now I cannot find it. The command I entered was:sudo mv ~/Documents/Books/UTMAnalysis.pdf /Desktop I am using OS X. Similar questions mentioned it might be in the root directory or somewhere as a hidden file. In the root directory there is a Desktop, but is that not the existing folder? | Attempted to move a file with mv command and now it is lost? | command line;files;mv | I suspect one of the following:renamedIf /Desktop did not exist when you ran that command it would have renamed the file UTMAnalysis.pdf to be Dektop. You could confirm if it was a directory or a file with this command:ls -ld /DesktopIf it's a directory the first character will be a d whereas if it's a file it will be a -. linux-okrz:~ # ls -ld file-rw-r--r-- 1 root root 0 Apr 29 19:43 filelinux-okrz:~ # ls -ld directory/drwxr-xr-x 2 root root 4096 Apr 29 19:45 directory/You can also run the stat command on it to see information on them:linux-okrz:~ # stat file File: 'file' Size: 0 Blocks: 0 IO Block: 4096 regular fileDevice: 807h/2055d Inode: 20709419 Links: 1Access: (0644/-rw-r--r--) Uid: ( 0/ root) Gid: ( 0/ root)Access: 2017-04-29 19:43:57.620769552 -0600Modify: 2017-04-29 19:43:57.620769552 -0600Change: 2017-04-29 19:43:57.620769552 -0600 Birth: -linux-okrz:~ # stat directory File: 'directory' Size: 4096 Blocks: 8 IO Block: 4096 directoryDevice: 807h/2055d Inode: 20709424 Links: 2Access: (0755/drwxr-xr-x) Uid: ( 0/ root) Gid: ( 0/ root)Access: 2017-04-29 19:45:52.036413879 -0600Modify: 2017-04-29 19:45:52.036413879 -0600Change: 2017-04-29 19:45:52.036413879 -0600 Birth: -On the right-hand side of the output you can see regular file vs directory. If it's a file then you can rename it back and check to make sure you can still access it.Inside /DesktopThe next possibility is that it is in the /Desktop directory. If it is a directory(should be confirmed from previous suggestion), you didn't indicate whether you've checked in there or not. You can run this command as root to get a full layout of the directories and files in that directory:ls -lah /Desktop/From there you can see if you find the UTMAnalysis.pdf file.Hidden ActionThe third possibility is that there is another command or action that's been taken before or after this command you've listed that's done something else to the file. You can check your history with the history command to see if you can find any other command that has acted on that file. You could also try searching for the file with a find command as root:find / -type f -name *UTMAnalysis.pdf*If the above command doesn't find it then it either doesn't have UTMAnalysis.pdf in its name anymore, or no longer exists on the system. |
_softwareengineering.128257 | Currently, I'm following a course on embedded software development. The lecturer has chosen J as an architecture language for model-driven software development. J itself is a very terse programming language and one of his main arguments for this language is its terseness. For instance, this is a Quicksoft implementation in J:quicksort=: (($:@(<#[) , (=#[) , $:@(>#[)) ({~ ?@#)) ^: (1<#)Another argument is that through such a language and the reduced number of characters, you introduce less bugs and the time to fix bugs is reduced.Since I have a strong software engineering background and through various books like Clean Code, Pragmatic Programmer and others, I feel that these arguments aren't valid. I find that there is a strong movement towards descriptive names and code that reads like natural language (alright, this might only be related to applications with lots of business logic and less math).The question therefore is, can you really argue that usage of a terse programming language will result in less errors and that time to fix a bug is reduced? Also, since the language is terse, the number of lines of code is reduced and you would get a better COCOMO rating. But can this be applied in the first place or does the COCOMO model use the number of lines of code as a way to estimate a project's overall size (project size should be the same whether you implement it in a terse language or in an imperative one, but again, maybe I didn't understand the COCOMO model correctly)?UpdateThank you all for your answers. Admittedly, I should have stated more clearly that my intention was to get more information on the COCOMO model (again, sorry S.Lott). As such, I feel that Thomas Owens's extensive answer and comments are the best fit for this question. Thanks again! :-) | Is the COCOMO model a good argument when defending a programming language choice? | functional programming;bug;clean code;cocomo | Is the COCOMO model a good argument when defending a programming language choice?No. COCOMO says nothing about language choice at all. It is a cost estimation tool to determine how much it will cost to build a given software system given a series of inputs. The latest iteration is COCOMO II, and there are web based tools to use when applying this model. Some of the inputs that go into COCOMO II include the estimated size in SLOC or function points, the team cohesion, maturity of the process, desired reliability, complexity, the capability of people filling different roles on the team, platform constraints, and schedule. The output is the estimate for effort, schedule, and cost for the project.Only a handful of the inputs are related to technology and programming language. The key adjustment factors that cover these areas are the capabilities of the programmer, experience of the programmer in the application domain, experience with the platform and language, and the ability to obtain and use supporting tools.As far as defending a language, the best that you can do with COCOMO is produce multiple estimates for different technologies and languages that the team knows to varying degrees. Perhaps there's one technology that the entire team knows and has successfully used before, so platform and language experience would be high, but that language has very few supporting tools so that would be lower. You can compare that to a language that perhaps only one person knows extremely well and a few people know a little about, calling the experience nominal, yet factoring in the rich tool set. Given two (or more) sets of effort, schedule, and cost estimates, you can compare to see which might be more effective to use.Also, since the language is terse, the number of lines of code is reduced and you would get a better COCOMO rating.There is no such thing as a COCOMO rating. COCOMO is an estimation tool that you can use to try to determine how much effort (person-months), schedule (months), and cost a project will require to complete. When estimating, this data is compared against the size of the project team and the business schedule to determine if it's realistic and to provide the project manager with information needed to control the project schedule.For example, COCOMO might produce a schedule estimate of 15 months and a cost estimate of $500,000. However, the business schedule might call for 12 months and $450,000. This schedule and isn't unreasonable, and the project manager can use this information when controlling the project and negotiating with the customer.But can this be applied in the first place or does the COCOMO model use the number of lines of code as a way to estimate a project's overall size (project size should be the same whether you implement it in a terse language or in an imperative one, but again, maybe I didn't understand the COCOMO model correctly)?Although source lines of code (SLOC) is a valid input to COCOMO, estimating size using source lines of code is not recommended because the number of SLOC varies depending on programming language (among a number of other problems). Function points are a preferred method of size estimation. There are conversion ratios that allow you to estimate a number of function points and apply the ratio to determine the size of the system in a given programming language.Now, comes the other parts to your question.Currently, I'm following a course on embedded software development. The lecturer has chosen J as an architecture language for model-driven software development. J itself is a very terse programming language and one of his main arguments for this language is its terseness. Another argument is that through such a language and the reduced number of characters, you introduce less bugs and the time to fix bugs is reduced. [...] I feel that these arguments aren't valid. I find that there is a strong movement towards descriptive names and code that reads like natural language (alright, this might only be related to applications with lots of business logic and less math).That's nice. In my experiences, the lecturer has more experience in the topic than the typical student. When they choose a given language, framework, platform, or technology to use to teach their content, they have a good reason to.Terseness is, in my opinion, a rather poor measure to discuss a language on. There are far better criteria to use when choosing a language to implement a project in - platform support, tool support, available resources, team knowledge. With never having seen J before, it seems rather difficult to read. However, it might be very good at solving the particular problems that the project is trying to solve, and the people on the team might have experience with it. It might also be easy to learn.In your specific case, of a class, you need to focus on the point - learning concepts and techniques. Not only will you learn about J (and learning new tools is always good), but you'll learn techniques that can probably be applied to other languages as well.The question therefore is, can you really argue that usage of a terse programming language will result in less errors and that time to fix a bug is reduced?My intuition says no, but that's beside the point. You need to factor in knowledge of the language, supporting tools (compilers, IDEs, static analysis), and process methodology (pair programming, code reviews, style guidelines), and more to have an adequate discussion of how to reduce errors and time-to-fix.If you're interested in more about COCOMO and what it's all about, I'd recommend reading Software Engineering Economics and Software Cost Estimation with COCOMO II, both by Barry Boehm. Software Engineering Economics is mostly general software project management, cost estimation, and effort estimation. The portion of the book that discusses COCOMO discuses the COCOMO 89 version, which Boehm has said should no longer be used due to inaccuracies that were corrected in the COCOMO II version, however the rest of the sections of the book are still relevant. |
_webmaster.5766 | How do analytics applications (like StatCounter or GoogleAnalytics) measure time spent on page? Is that possible without JavaScript? I guess they reloading 1x1 web-bug or something after certain amount of time, am I right? | How is time spent on page measured? | analytics | null |
_webmaster.81794 | While working on some optimizations for my site, I noticed some things in Networking Timings for Chrome Developer Tools differ from those in Firefox Developer Tools.Very consistently Chrome loads a number of items on the page giving a 200 (from cache) response. Those same items on Firefox just show as 304 response items.I am wondering if anyone can explain this. Below are two screen shots for the same resource. First one from Chrome, the second from Firefox. | When using resources from cache Firefox show a 304 response but Chrome says 220 (from cache) | google chrome;http headers;firefox | null |
_webmaster.27310 | I have a static mockup page, which I want to customize by switching a variable used in image-src and link-href attributes.Paths will look like this:<img src=/some/where/VARIABLE/img/1.jpg alt= /><link rel=some href=/some/where/VARIABLE/stuff/foo.bar />I'm setting a cookie with the VARIABLE value on the preceding page and now want to modfiy the paths accordingly by replacing VARIABLE with the cookie value.I'm a htaccess newbie. This is what I have (doesn't work): <IfModule mod_rewrite.c> # get cookie value cookie RewriteCond %{HTTP_COOKIE} client=([^;]*) # rewrite/redirect to correct file RewriteRule ^/VARIABLE/(.+)$ /%1/$1 [L] </IfModule>So I thought my first line gets the cookie value and stores this in %1. And on the second line I'm filtering VARIABLE, replace it with the cookie value and whatever comes after VARIABLE in $1.Thanks for sheeding some light on what I'm doing, doing wrong and if I can do this at all using htaccess.EDIT:I'm sort of halfway through, but it's still not working... Mabye someone can apply the finishing touches: <IfModule mod_rewrite.c> # check for client cookie RewriteCond %{HTTP_COOKIE} (?:^|;\s*)client=([^;]*) # check if an image was requested RewriteCond %{REQUEST_FILENAME} \.(jpe?g|gif|bmp|png)$ # exclude these folders RewriteCond %{REQUEST_URI} !some/members/logos # grab everything before the variable folder and everything afterwards # replace this with first bracket/cookie_value/second bracket RewriteRule (^.+)/VARIABLE/(.+)$ $1/%1/$2 [L] </IfModule>Still can't get it to work, but I think this is the correct way of doing it. | Rewrite img and link paths with htaccess and serve the file from rewritten path? | htaccess;mod rewrite | Solution: (after much meddling...)<IfModule mod_rewrite.c> # exclude these folders RewriteCond %{REQUEST_URI} !/some/members/logos # check for client cookie RewriteCond %{HTTP_COOKIE} client=([^;]*) [NC] # replace variable with cookie value RewriteRule ^(.+)/variabel/(.+\.(jpe?g|gif|bmp|png))$ $1/%1/$2 [L]</IfModule>The tricky part, which took forever to solve is to make sure your cookie has a trailing semi-colon... I had my cookie set like this: document.cookie = client=valuewhich did not work at all. After changing to this: document.cookie = client=+escape(value)+;it worked. Semi-colon... Maybe this save somebody half a day of searching :-) |
_codereview.7101 | I'm somewhat new to SQL (using it in the past but only being exposed to it heavily in my current role). Unfortunately nobody at my current company has really given me any advice on formatting. How can I format this better / what should I avoid doing that I may have done below? Any feedback on re-factoring would be greatly appreciated also./* Uncomment when testing this SQL */declare @period_id as int = 252 -- ### Potentially redundant ###declare @building_id as varchar(10) = '20500'declare @section_name as varchar(20) = 'ALL'declare @lease_expiry_period as int = 1;/* SQL for Section_Name parameter on report */select 'ALL', 1 as order_byunion allselect distinct upper(isnull(section_name, '')) as section_name, 2 as order_byfrom property.lease_periodwhere section_name <> ''order by 2;declare @truncateddate as date = dateadd(d,0,datediff(d,0,getdate()));/* SQL for Report (dsDetail) */select lp.period_id , lp.building_id , lp.suite_id , lp.lease_id , lp.tenant_trading_name, lp.suite_status , lp.suite_name , lp.suite_area, lp.lease_status , lp.lease_current_start_date , lp.lease_current_stop_date , lp.lease_current_term , lp.lease_occupancy_date , lp.lease_vacated_datefrom property.lease_period lpwhere lp.lease_current_stop_date < @truncateddate and (upper(lp.lease_status) = 'ACTIVE' or upper(lp.lease_status) = 'OVERHOLDING') --and lp.period_id = @period_id -- ##Potentially redundant (query now running into the future) and lp.building_id = @building_id and not exists ( select 1 from lease_deal.lease l where lp.building_id = l.building_id and lp.lease_id = l.lease_id ) and (@section_name = 'ALL' or (@section_name <> 'ALL' and upper(section_name) = upper(@section_name))) and lp.lease_current_stop_date between @truncateddate and dateadd(MONTH, @lease_expiry_period, @truncateddate)order by period_id desc | SQL - How's my formatting? | mysql;sql;sql server;t sql | What you've got is pretty readable, but there are a few points to make:Your sub-query is written with a different indentation style from the main query.I prefer to see the keywords in upper-case.Personally, I dislike spaces before commas intensely (and you aren't 100% consistent about adding them). However, I loathe even more the style where the comma is put at the start of the next line: item1 , item2 , item3I'd use explicit AS to introduce table aliases. At least on the DBMS I use mainly, using AS gives a degree of future-proofing against aliases that become keywords in a later version of the product. That is, writing FROM SomeTable st runs into a problem later if st becomes a keyword, but writing FROM SomeTable AS st avoids that problem. Whether this helps in other DBMS is open to debate.For your query, I'd probably write:SELECT lp.period_id, lp.building_id, lp.suite_id, lp.lease_id, lp.tenant_trading_name, lp.suite_status, lp.suite_name, lp.suite_area, lp.lease_status, lp.lease_current_start_date, lp.lease_current_stop_date, lp.lease_current_term, lp.lease_occupancy_date, lp.lease_vacated_date FROM property.lease_period AS lp WHERE lp.lease_current_stop_date < @truncateddate AND (UPPER(lp.lease_status) = 'ACTIVE' OR UPPER(lp.lease_status) = 'OVERHOLDING') AND lp.building_id = @building_id AND NOT EXISTS (SELECT * FROM lease_deal.lease AS l WHERE lp.building_id = l.building_id AND lp.lease_id = l.lease_id ) AND (@section_name = 'ALL' OR (@section_name <> 'ALL' AND UPPER(section_name) = UPPER(@section_name))) AND lp.lease_current_stop_date BETWEEN @truncateddate AND DATEADD(MONTH, @lease_expiry_period, @truncateddate) ORDER BY period_id DESC;Sometimes, I'd indent the sub-query more than I did here, occasionally even placing it after the EXISTS: AND NOT EXISTS (SELECT * FROM lease_deal.lease AS l WHERE lp.building_id = l.building_id AND lp.lease_id = l.lease_id )That has a tendency to run off the right-hand edge of the screen, though. |
_unix.291347 | I became my own certificate authority after running through the tutorial at: https://jamielinux.com/docs/openssl-certificate-authority/I created a root pair, created an intermediate pair, and signed a server certificate, which I installed on squid like this:http_port 3129 ssl-bump generate-host-certificates=on dynamic_cert_mem_cache_size=4MB cert=/etc/squid3/certs/gatesentry.csr.cert.pem key=/etc/squid3/key/gatesentry.key.pemin squid3.confSquid starts up just fine with this. Still not sure if it's actually working or not.When I try to generate a client-side certificate to install in a browser that will be accessing the internet through the proxy I end up with an error:I generate it based on the Sign server and client certificates section that reads Create a certificateIt states that if I'm going to create a client certificate for authentication, I'll need to use the 'usr_crt' extension and so I run:cd /root/caopenssl ca -config intermediate/openssl.conf \ -extensions usr_cert -days 375 -notext -md sha256 \ -in intermediate/csr/gatesentry.csr.pem \ -out intermediate/certs/client.cert.pemUsing configuration from intermediate/openssl.confEnter pass phrase for /root/ca/intermediate/private/intermediate.key.pem:Check that the request matches the signatureSignature okCertificate Details: Serial Number: 4097 (0x1001) Validity Not Before: Jun 22 10:36:44 2016 GMT Not After : Jul 2 10:36:44 2017 GMT Subject: countryName = US stateOrProvinceName = Pennsylvania localityName = locality organizationName = Parents organizationalUnitName = Security commonName = gatesentry.domain.lan emailAddress = [email protected] X509v3 extensions: X509v3 Basic Constraints: CA:FALSE Netscape Cert Type: SSL Client, S/MIME Netscape Comment: OpenSSL Generated Client Certificate X509v3 Subject Key Identifier: XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX X509v3 Authority Key Identifier: keyid:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX X509v3 Key Usage: critical Digital Signature, Non Repudiation, Key Encipherment X509v3 Extended Key Usage: TLS Web Client Authentication, E-mail ProtectionCertificate is to be certified until Jul 2 10:36:44 2017 GMT (375 days)Sign the certificate? [y/n]: yfailed to update databaseTXT_DB error number 2I don't understand why I am getting the TXT_DB error number 2 message when I am running the command as root (on another machine of course).According to the tutorial, I should be able to change the Common Name during this process. | Can't generate client-side certificate after becoming my own Certificate Authority | openssl;squid | null |
_codereview.2599 | I have two tables, one for jobs, and one for the names of industries (e.g. automotive, IT, etc).In SQL I would just do:SELECT industryName, count(*)FROM jobsJOIN industryON jobs.industryId = industry.idGROUP BY industryNameIn LINQ I have the following, but it's three separate statements and I'm pretty sure this would be doable in one.var allIndustries = from j in dbConnection.jobs join i in dbConnection.industries on j.industryId equals i.id select i.industryName;var industriesWithCount = from i in allIndustries group i by i into iGrouped select new { Industry = iGrouped.Key, Count = iGrouped.Count() };var industries = new Dictionary<string, int>();foreach (var ic in industriesWithCount){ industries.Add(ic.Industry, ic.Count);}Is there a way to make this simpler or shorter? | LINQ to SQL Joining Entities | c#;linq | null |
_softwareengineering.266769 | A lot of times, I have long forms that I divide into multiple tabbed sections. Each section is managed by it's own controller and there is a parent controller that manages the whole view. I use ui-router for dividing such sections into states. Should I make a service instead of a controller to manage the all the sections but generally, I don't have business logic in their. It's mostly done for collection data altogether and passing it to an API using ng-resource. I know | Is having a parent controller to manage a set of tabbed sections an anti-pattern for an angular application? | design patterns;javascript;anti patterns;angularjs | null |
_cs.76057 | For a machine learning method X (Deep Neural Nets variant), which performs classification tasks.In the output layer, for every label method, X also emits the uncertainty U associated with the respective prediction.So, in case the testing dataset is very different then the predictions made by X should have a high U. (Mean of U across all labels should be high)In the case of testing, the dataset is indeed from the same source from which training dataset was generated. For true positives, the mean of uncertainty for the correct label would be low. In the case of false positives, the mean of U would be high (ideally). What is the principled approach to measuring the effectiveness of method X in outputting the uncertainty? In other words, what would be a good metric to understand the performance of the method in computing the uncertainty for each label? Metric similar to Root mean squared error or others. | Scoring metric for machine learning method | machine learning;neural networks;classification | null |
_webmaster.91124 | I'm helping to my job's internal wiki and I find subpages useful for writing pages of a tutorial related to a topic. I understand how subpages are configured, but when I was reviewing other wikis to see how subpages can be used, I found that the Spanish version of Wikibooks renders the title of the subpages separating each ancestor's title in different lines, instead of one huge title with slashes. Here is an example.How can I achieve that kind of presentation in my wiki? It can be obtained with the default installation? Is a extension needed? Or it is necessary to edit PHP files directly? | How to render MediaWiki subpages' titles like the Spanish Wikibooks? | mediawiki | null |
_unix.358906 | I would like to mount an Apple iPad to my Linux device, to make a jpeg or ddrescue recovery on it. How I would do this with an Apple device? | How to mount an Apple device from Linux? | mount;data recovery;rescue;ddrescue;apple | You can't access the block device on Apple directly, it is forbidden by the OS, on which you don't have a root access, despite that you've purchased it and it is yours. To be able to do these, you have to jailbreak it (I intentionally don't use the word crack, because it is your property). It is hard. Although the OS of the Apple mobile devices, the iOS, is based on a Unix variant (OS X, which is based on freebsd), it doesn't mean that you would have the freedom of the unixes on it, its exact opposite is the truth.Better solution would be to use some application-level thingy (i.e. to copy the files with usb or wifi).If you have some electronical affinity, also soldering out the ssd chip from it would be a solution, although it doesn't solve the problem that their whole disk is encrypted (note: being the legal owner of the device, you are still not allowed to decrypt its content). |
_softwareengineering.237387 | What is the best way to handle errors that shouldn't ever happen?My current way to do this is to throw an exception if the 'thing that shouldn't happen' does happen, like so:/* * Restoring from a saved state. This shouldn't be * null unless someone in the future doesn't set it properly, in which * case they will realize they did something wrong because it may crash. */Object foo = bundle.getSerializable(foo);if (foo != null) { doSomethingWith(foo);} else { // This should never happen. if (BuildConfig.DEBUG) { throw new RuntimeException( Foo is null!); } foo = new Object(); doSomethingWith(foo);}This is somewhat pointless, because this should never happen. But just in case the code gets screwed up and is released into production with foo being null, should I leave these types of checks in the code? | How should I handle exception that *should* never be thrown? | java;exceptions;comments;clean code;error handling | It's amazing how often things that should never happen do.You should throw a RuntimeException with a descriptive error message and let the application crash. If that ever happens, then you know that something is deeply wrong. |
_codereview.20599 | I have a model class that contains 3 ArrayList which are in order by parallel of the same size. <Object><Calendar><Long> I want to sort it by the <Long> Is this the most clean? is there a better way? This doesn't seem memory efficient. public class ResultModel{ private ArrayList<Object> sets = new ArrayList<Object>(); private ArrayList<Calendar> dates=new ArrayList<Calendar>(); private ArrayList<Long> unixtimes=new ArrayList<Long>(); private class WinningSet implements Comparable<WinningSet>{ private long unixtime; private Object set; private Calendar date; WinningSet(Object set,Calendar date,long unixtime){ this.unixtime=unixtime; this.set=set; this.date=date; } @Override public int compareTo(WinningSet another) { return (int) (this.unixtime-another.getUnixtime()); } public long getUnixtime() { return unixtime; } public Object getSet() { return set; } public Calendar getDate() { return date; } } public void sortSelf(){ ArrayList<WinningSet> list=new ArrayList<WinningSet>(); for(int i=0;i<this.unixtimes.size();i++){ list.add(new WinningSet(this.sets.get(i),dates.get(i),unixtimes.get(i))); } Collections.sort(list,Collections.reverseOrder()); demap(list); } private void demap(ArrayList<WinningSet> list) { ArrayList<Object> tSets = new ArrayList<Object>(); ArrayList<Calendar> tDates=new ArrayList<Calendar>(); ArrayList<Long> tUnixtimes=new ArrayList<Long>(); for(WinningSet temp:list){ tDates.add(temp.getDate()); tSets.add(temp.getSet()); tUnixtimes.add(temp.getUnixtime()); } this.sets=tSets; this.dates=tDates; this.unixtimes=tUnixtimes; }} | Sorting parallel ArrayList | java;optimization;android;sorting | 1. Correctnes.compareTo() method of the WinningSet class is not correct. As of now Integer.MAX_VALUE < System.currentTimeMillis(). Consider the following example: long time1 = System.currentTimeMillis(); System.out.println(time1 > 3*Integer.MAX_VALUE); System.out.println(time1 - 3*Integer.MAX_VALUE); System.out.println((int)(time1 - 3*Integer.MAX_VALUE));It could be the case that your events are generated around the same time and it will not result in any error but in general - e.g. in future, if you restore some serialized objects, it could lead to a possible problem. You can rewrite it int the following way: @Override public int compareTo(WinningSet another) { if (this.unixtime > another.getUnixtime()) return 1; if (this.unixtime < another.getUnixTime()) return -1; return 0; }2. PerformanceCopy of the 3 lists is indeed a bad thing. You can use set() method from ListIterator to traverse through the lists and replace values in place.private void demap(ArrayList<WinningSet> list) { Iterator li = list.iterator(); Iterator si = sets.iterator(); Iterator di = dates.iterator(); Iterator ui = unixtimes.iterator(); //you can add iterators for other lists here. while (li.hasNext()) {// we assume number is the same WinningSet temp = li.next(); si.next(); //need to advance to the right element; di.next(); //need to advance to the right element; ci.next(); //need to advance to the right element; si.set(temp.getSet()); di.set(temp.getDate()); ui.set(temp.getUnixTime()); } }3. DesignAre you sure that instead of a 3 lists you can't consider TreeMap<Long, SomeClass> where SomeClass is pair or Calendar and Object ? In this case you will always have the right order of items to work with - there is no need to sort lists on demand and do an extra work. |
_unix.386249 | I am running an Arch Linux installation and I have a systemd service that runs /etc/rc.local. In rc.local, I have several commands to perform things that I couldn't find a suitable solution for, like running dmesg -D or something that would automatically create mount points in a temporary folder as in macOS with /Volumes.For each command in my rc.local script, I have the script test for a failure and then exit with a number corresponding to the line of the command. So, a snippet of the file (adjusted to keep my formatting in mind) would look like this:#!/bin/bashdmesg -D || exit 1i=2for name in usb sddo mkdir -p /mnt/${name} || exit ${i} i=$((i+1))donesysctl -w kernel.kptr_restrict=2 || exit 4exit 0This is a bit clunky and I'm under the impression that exit codes should be limited in their assignment for a script, but this is the only way I know how to check what the reason for my systemd service rc-local.service failing is since systemctl status rc-local.service will print out the exit value. Is there some other way to code rc.local such that systemd/rc-local.service will receive information on why rc.local fails, like maybe passing a string to it or something? Then I can see this string show up maybe like this when I type systemctl status rc-local.service:Error reason: Failed to set kernel.kptr_restrict | Exit codes in a startup script for different failures | shell;systemd;exit | null |
_softwareengineering.302535 | In a database I work on, most of the datetimes I store are converted to and from UTC so all of my datetime columns end in UTC such as CanceledUTC.I have a situation where I need to store a local time and want to signify that it is a local time in the column name. Is there a convention for signifying local datetime variable names?I know that storing local datetimes is a bad practice so I'm also considering storing it as a string, but that's not the question here. | How to abbreviate Local for a time variable, like UTC | naming | null |
_codereview.46759 | This is my solution for problem 26 from Project Euler:Find the value of d < 1000 for which 1/d contains the longest recurring cycle in its decimal fraction part.from timeit import default_timer as timerimport mathfrom decimal import *start = timer()def longestPeriod(n): # define function longest = [0, 0] # length, num def isPrime(k): # checks if a # is prime for x in range(2, int(math.ceil(math.sqrt(k)))): if k % x == 0: return False return True def primeFact(k): # returns prime factorization of # in list if k <= 1: return [] prime = next((x for x in range(2, int(math.ceil(math.sqrt(k))+1)) if k%x == 0), k) return [prime] + primeFact(k//prime) def periodIfPrime(k): period = 1 while (10**period - 1) % k != 0: period += 1 return period # returns period of 1/d if d is prime def lcm(numbers): # finds lcm of list of #s def __gcd(a, b): a = int(a) b = int(b) while b: a,b = b,a%b return a def __lcm(a, b): return ( a * b ) / __gcd(a, b) return reduce(__lcm, numbers) for x in range(3, n): # check all up to d for 1/d if all(p == 2 or p == 5 for p in primeFact(x)) == True: # doesn't repeat pass elif isPrime(x) is True: # run prime function if longest[0] < periodIfPrime(x): longest = [periodIfPrime(x), x] elif len(primeFact(x)) == 2 and primeFact(x)[0] == primeFact(x)[1]: if x == 3 or x == 487 or x == 56598313: # exceptions period = int(math.sqrt(x)) else: # square of prime period = periodIfPrime(primeFact(x)[0]) * x if period > longest: longest = [period, x] else: fact = primeFact(x) periods = [] for k in fact: if k != 2 and k != 5: if fact.count(k) == 1: periods.append(periodIfPrime(k)) else: periods.append((periodIfPrime(k)) * k**(fact.count(k) - 1)) if lcm(periods) > longest[0]: longest = [lcm(periods), x] return longestelapsed_time = timer() - startelapsed_time /= 100 # millisecondsprint Found %d in %r ms. % (longestPeriod(1000)[1], elapsed_time)Can it be written in a better way? | Rendition of Project Euler 26 - reciprocal cycles | python;python 2.7;programming challenge | Don't compute the same thing more than once. You call primeFact(x) up to 5 times for each x. Keep the result in a variable instead.You check if x is prime after you have already computed its prime factorization. Now think for a minute: how does the prime factorization of a prime turn out? Your program would greatly benefit from a precomputed list of primes. Look up sieve of Eratosthenes.The answer according to this program is 3, which cannot be right, as eg. 7 has a longer period already.Bug: if period > longest compares an int to a list, which is not an error in Python 2.x, but does not do what you want.To allow testing of individual functions, it is better to define them at module level. A quick test of isPrime shows it returns True for 4,9,25 etc. That's because eg. ceil(2.0) == 2.0 |
_webapps.66096 | Setup is Runkeeper for Activity logging, automatically synced to MyFitnessPal for calorie counting.If I change the activity type in a Runkeeper activity that is a few days old, is it possible to resync the activity with MyFitnessPal to update the calories burned? | Update an old activity in Runkeeper and have that update in MyFitnessPal? | runkeeper | null |
_webapps.21855 | Is there a way to get a list of all Google contacts that I have occasionally marked as never show in my Gmail Chat?That is needed to make all of them auto one by one with Gmail Chat UI. If one knows an easier way to get that result, please share. | Gmail Chat never shown Google contacts | gmail;google talk | null |
_unix.192310 | If I start an application and switch workspaces in the time the application is starting up, the application goes to the current workspace and not the one from which I called it.Where can I change this behaviour?I'm using xfce right now, but I've been having this problem for a long time with different setups, I had the same behaviour with awesome and qtile. | Start an application on initial workspace instead of current workspace | x11;xfce;window management;workspaces | null |
_cs.28642 | Suppose I give you an undirected graph with weighted edges, and tell you that each node corresponds to a point in 3d space. Whenever there's an edge between two nodes, the weight of the edge is the distance between the points.Your goal is to reconstruct the relative positions of the points, given only the available distances (represented by the edge weights). For example, if I gave you $d_{0,1} = d_{0,2} = d_{0,3} = d_{1,2} = d_{1,3} = d_{2,3} = 1$, then you know the points are the vertices of a tetrahedron. You don't know where it is relative to the origin, or its orientation, or if it's been mirrored, but you can tell it's a tetrahedron.In general, the problem is easy if I give you all of the edge lengths. Just arbitrarily pick a point $p_0$ to be at $(0,0,0)$, then pick a neighboring point $p_1$ and place it at $(d_{0,1},0,0)$, then a common neighbor $p_2$ gets triangulated onto the XY plane, then a final common neighbor $p_3$ gets triangulated into the half-space $z > 0$ and breaks the remaining symmetry (assuming you didn't pick degenerate points). You can use those four points to triangulate all the remaining ones.On the other hand, when some edge lengths are missing it may not be possible to recover the embedding. For example, if there's a vertex that disconnects the graph when cut, then the two components it would separate if removed can swing around relative to each other.Which raises the questions:How expensive is it to find a solution?How do you determine if a solution is unique, up to translation/rotation/mirroring? Is 3-connectedness sufficient? Necessary?What sorts of conditions make the problem trivial?If I don't promise the edge weights actually correspond to point distance sin 3d, how expensive is it to determine if an embedding is possible at all? | Recovering a point embedding from a graph with edges weighted by point distance | complexity theory;graph theory;computational geometry;euclidean distance | The problem is NP-Complete. The positions of the points is a good certificate, so it's in NP, and you can encode circuits into the is there a satisfying set of points? problem.Reduction from Circuit Evaluation to Distance EmbeddingWe're going to reduce circuit evaluation into a distance embedding problem by creating a coordinate system, putting logical bits in it, wiring bits to be equal, and creating widgets for NOT and AND gates.Coordinates. We need some kind of coordinate system that we can position points with. Do this by creating a base tetrahedron of points. Add four points all declared to be a distance of $1$ from each other. This forces the shape of those four points into a tetrahedron. We can position other points relative to our tetrahedron coordinate system by specifying their distance to each of the four corners of the base. The tetrahedron can be translated and rotated and reflected, but the same thing will happen to all the other points as well.Bits. To make a bit, we position a triangle of points relative to the base tetrahedron. The triangle's normal must point upward along the Z axis, so that the triangle is parallel to the XY plane (in tetrahedron coordinates). Also its edges must have length $1$. With that done, we add a value point $v$, specified to be a distance of $1$ from the other three. We don't connect $v$ to the base coordinate system. This gives it two possible positions: centered $\frac{1}{\sqrt{3}}$ above or below the triangle, as the final corner of a tetrahedron. The bit is ON if the point is above the triangle, and OFF if it's below.Wires. We can force two bits to be equal by saying the distance between their value points is equal to the distance between the centers of their triangles. There is one exception: when the top or bottom corner of one of the bits exactly lines up with the center plane of the other. In that case we first use a wire to move one of the bits vertically.NOT. We can get the negation of a bit by adding a second value point $w$ to the same triangle, but requiring that $w$ be a distance of $\frac{2}{\sqrt{3}}$ from $v$. This forces $w$ to take the position opposite of $v$, with respect to the triangle, giving us a bit with the opposite value.IMPLIES. The equidistant issue we had to work around with the wires is actually quite useful. When the bits line up in that way, which we can force with a vertical wire, the higher one implies the lower one. If the higher one is true, only the top of the lower one is the right distance away. If the higher one is false, both the top and bottom are the right distance away.AND. To make a bit $C$ be equal to $A$ AND $B$, we need two implications and a widget to force equality when $A$ and $B$ agree. The implications are just $C \implies A$ and $C \implies B$. To make the widget we move $A$ and $B$ vertically so they're on the same level and a distance $\frac{2}{\sqrt 3}$ apart, then we move $C$ to be equidistant between them. We then add a points $S_A$ and $S_B$ a distance $\frac{\sqrt 2 - 1}{2 \sqrt 3}$ from $A$ and $B$'s value points respectively, and force the distance between $S_A$ and $S_B$ to be $\frac{\sqrt 2 + 1}{\sqrt 3}$. We also add a point $S_C$ a distance $\frac{\sqrt 2 + 1}{2 \sqrt 3}$ from both $S_A$ and $S_B$. This creates a chain between $A$ and $B$'s value points, with $S_C$ at the chain's center. When $A \neq B$, the chain is stretched to the limit and $S_C$ is in the center of $C$'s triangle. When $A = B$ the chains links are forced to go in exact opposite directions, pushing it to the limit and placing $S_C$ on $C$'s value point equal to $A$. To force $C$'s value point, we insert a point $S_D$ a distance $\frac{1}{2 \sqrt 3}$ from both $S_C$ and $C$'s value point. This doesn't constrain $C$'s value point when $A \neq B$, but forces $A=B=C$ when $A=B$.With those elements, you can encode any circuit into a distance embedding. The inputs become bits, gates get decomposed into NOTs and ANDs introducing new bits as necessary, and that's it. Force the position of the output to be true, and you get your satisfiability problem. |
_webmaster.100003 | Basically I have a Heroku app on a main domain and a wordpress blog on a subdomain as blog.maindomain.com. I have google tag manager installed on the herokuapp that tracks the main domain. How am I able to also allow my wordpress to have the same functionality? I want to be able to view all the analytics in a single account. EDIT: I don't have to use GTM on the wordpress website, just as long as the data is showing on the same GA account. | How do I install Google Tag Manager on Wordpress subdomain for the same Google Analytics that is on my main domain? | google analytics;domains;subdomain;google tag manager | null |
_webmaster.38246 | I created a website for my wife, who knits scarves. The site simply displays the 18 different colours she has created, with a Lightbox-like large photo available when clicked.She would now like to give visitors the option to purchase online and pay with PayPal and possibly Google Checkout.We do not need a full ecommerce solution; I've looked at several and they all seem to be overkill for our requirements. We don't even need categories. All I want is something that will add products to a cart, take the customer details and integrate the payment provider.So far, the best solution I have found seems to be this script on Codecanyon and I wanted to find out if anyone knows of any better products before I commit to this route.Thanks for your help! | Is there a simple shopping cart I can add to my existing website? | php;ecommerce;shopping cart | You can create a product with options in PayPal which is easy to use and setup. You just copy and paste their code onto your website and visitors can select the product and colours and add it to their cart. I would go with PayPal over Google Checkout she'll get many more orders with PayPal since more people use it.http://www.mals-e.com/ is another free option that integrates with PayPal and is copy paste for setup. |
_computerscience.4606 | I've heard a lot that in shader development, you absolutely need to avoid branching and so if statements.But why? Does this have a real impact on performances on old and modern hardware or is it more a case by case choice depending on your scenario?When possible, it's better to use preprocessor macros but when it's not, what can we do?What is the purpose of using flatten or branch attributes? Are there other solutions available? | If statements in shaders - implications and consequences | opengl;shader;glsl;hlsl;directx | null |
_codereview.23548 | This code takes 8 divs and races them across the screen depending on which time value the div was assigned. How can I have coded this better so my code doesn't look so amateurish?I know I should have used something other than a hard coded 8 in my for-loop, but timeArray.length is unavailable since I am removing items from the array with splice.$(document).ready(function() {var timeArray = new Array(3,4,5,6,7,8,9,10);var shortestTime = timeArray[7];var fastestPony = {};var index;var pony = { name: pony, raceTime: -1, selected: };//change the color of the pony when the user clicks on it$('.pony').bind('click', function() { $('.pony').removeClass('selectedPony'); $(this).addClass('selectedPony'); //get the pony that the user selected pony.selected = $(this);});$('#startButton').click(function() { if (pony.selected == ) { alert(Please click the pony you think will win the race.); } else { for (i = 1; i <= 8; i++) { //get a random number from the timeArray index = Math.floor(Math.random() * timeArray.length); pony.raceTime = timeArray[index]; //pull the random race time number out of the array //so it can't be assigned to another horse timeArray.splice(index, 1); //get the fastest pony if (pony.raceTime < shortestTime) { shortestTime = pony.raceTime; fastestPony = $('#pony' + i); } //award the winner after the ponies have reached the finish line if (i == 8) { fastestPony.addClass('winner').append(' - Winner!'); } //send the horses on their way to race! $('#pony' + i).animate({left: '320px'}, pony.raceTime * 1000); } }});//reset the ponies back to the starting line by reloading the page$('#resetButton').click(function() { document.location.reload(true);});}); | Reading 8 divs across the screen depending on assignment time | javascript;jquery | null |
_unix.8241 | I am in the process of installing the required libraries for FireFox 3.6 on a Redhat Linux Nash 4.x system.I already have successfully installed the glib2.12.0 library, but When I ./configure the atk 1.9.0 library I get the following error.checking for pkg-config... /usr/bin/pkg-configchecking for GLIB - version >= 2.5.7... no*** Could not run GLIB test program, checking why...*** The test program failed to compile or link. See the file config.log for the*** exact error that occured. This usually means GLIB is incorrectly installed.configure: error:*** GLIB 2.5.7 or better is required. The latest version of*** GLIB is always available from ftp://ftp.gtk.org/. If GLIB is installed*** but not in the same location as pkg-config add the location of the file*** glib-2.0.pc to the environment variable PKG_CONFIG_PATH.How can I add the path to the Environment variable? | how to make PKG_CONFIG_PATH variable to refer an installed library? | environment variables;pkg config;autoconf | If you can install from repository. Check twice if you don't have it.If you cannot try bundled tarball from firefox page.Instead of installing all dependencies by hand try installing them from repository. For sure GLib is in debian repo. You need -dev/-devel or similar named packagesFor this particular problem - you installed the packages in the something called prefix. You can set this by ./configure --prefix=PREFIX and the default is /usr/local. Hence you need to add PREFIX/lib/pkgconfig to PKG_CONFIG_DIR. The exact method varies from shell to shell but the simplest option (for time of single session) is command export PKG_CONFIG_PATH=/usr/local/lib/pkgconfig:$PKG_CONFIG_PATHAs last piece of advice -DON'T install from source. It is much more complicated that it look like and you will run into problems. Look at the number of tools you have in Gentoo operating system (revdep-rebuild, lafilefixer etc.) to handle it. You will be on your own and firefox/xulrunner using some parts in non-standard way will give helpful errors as XPCOM cannot start in case of SONAME mismatch. You will have problems with uninstalling them as well and it may left garbage in system. Usually uninstall scripts are not well-tested and even build one are written carelessly. |
_softwareengineering.147321 | I am wondering which license the current JDK 7 (NOT the OpenJDK) is using as I know it was once under GNU GPL but with the change of the Distributor License for Java I would like to know whether they changed the allover license, too. | License of current JDK | java;licensing;gpl;oracle | Both JDK and JRE download sections link to this license. The same license seems to apply to both JDK and JRE.I'm not a lawyer but the following extract looks like they (not only JRE but also JDK) could be fairly freely redistributed as parts of your own programs:Oracle grants you a non-exclusive, non-transferable, limited license without fees to reproduce and distribute the Software, provided that (i) you distribute the Software complete and unmodified and only bundled as part of, and for the sole purpose of running, your Programs, (ii) the Programs add significant and primary functionality to the Software, (iii) you do not distribute additional software intended to replace any component(s) of the Software, (iv) you do not remove or alter any proprietary legends or notices contained in the Software, (v) you only distribute the Software subject to a license agreement that: (a) is a complete, unmodified reproduction of this Agreement; or (b) protects Oracle's interests consistent with the terms contained in this Agreement and that includes the notice set forth in Section H, and (vi) you agree to defend and indemnify Oracle and its licensors from and against any damages, costs, liabilities, settlement amounts and/or expenses (including attorneys' fees) incurred in connection with any claim, lawsuit or action by any third party that arises or results from the use or distribution of any and all Programs and/or Software. |
_webapps.98591 | Desktop:(at some point load more button disappears)Mobile App:(pull down, infinite scroll, more messages won't load)I opened Chrome Developer Tools to see what web requests are sent when I click load more button:Sidenote: reputational risk and lost trust - I am a regular user - I wasn't abusing any functionality. If I was to send 1000 messages a day to all my contact book - I would understand that loading old messages is not working.I'm actually really frustrated that such a basic functionality is not working.Maybe I should report this case to FB security as my account is being hacked? | How to load old (1 month ago) messages from Facebook? | facebook;facebook chat | null |
_webapps.101394 | I have Outlook 2016 on my local PC, it contains a lot of emails, calendar appointments and contacts. Since today I now also have a new outlook.com email address. Is there a way I export data from Outlook and import that into outlook.com?If there's another way of syncing data, I'd love to hear that. | Import Outlook local data into outlook.com | outlook.com;migrate data | null |
_unix.61144 | I'm trying to setup a Linux system that runs from an LVM-formatted image file. After some tinkering with the initramfs and boot options I managed to make it up and running by mounting the host file system to /run/initramfs/host, losetuping the image to /dev/loop0 and making sure the kernel and udev detect the LVM (and the root LV) in there. So far so good.The problem is that when shutting down (or rebooting, or ) the system neither the root file system nor the host are unmounted properly, because of a chicken-and-egg scenario: the root (or /oldroot, as it's referred to by the shutdown script) cannot be unmounted, because /oldroot/run/initramfs/host is still mounted, and the host cannot be unmounted, because doing so would make /oldroot inaccessible.Unclean shutdowns aren't the end of the world, because both file systems are journaled, so during the next boot fsck simply replays the journals, but obviously clean shutdowns would be better.So the question is: is it somehow possible to arrange the shutdown sequence (I can modify the shutdown script), or the bootup sequence (perhaps by moving the host mount point to a different place) so that both file systems can be cleanly unmounted? | Ensure that loopback root and host are unmounted on shutdown | linux;shutdown;loop device;root filesystem;unmounting | In case somebody has the same problem:All I needed was to move the mount point of the host file system to a place outside the root file system in the shutdown script (that's fine, because it runs in a tmpfs pivot root) before any unmounting takes place:mount --move /oldroot/run/initramfs/host /hostThis allows /oldroot to unmount cleanly. The host file system can be then unmounted with a simpleumount /host |
_codereview.122788 | This function works, but it's really really slow and the generated SQL is gargantuan and horrible to look at. It's also very expensive to run when it shouldn't be.public static IEnumerable<TrackingComputer> TrackingBoardPCsgroup(string groupName){ var pingresult = from p in db.GetTable<tblTBHealthPing>() group p by p.ComputerAsset into g select g.OrderByDescending(t => t.HealthPingTime).FirstOrDefault(); var healthresult = from p in db.GetTable<tblTBHealthHeartbeat>() group p by p.ComputerAsset into g select g.OrderByDescending(t => t.HealthHeartbeatTime).FirstOrDefault(); var query = (from t in TrackingBoardPCs() where t.TrackingGroup == groupName select new TrackingComputer { ComputerName = t.ComputerAsset, IPAddress = t.ComputerIP, Location = t.Location, Pingable = (from p in pingresult where p.ComputerAsset == t.ComputerAsset select p.HealthPingResult).FirstOrDefault() ?? false, PingTime = (from p in pingresult where p.ComputerAsset == t.ComputerAsset select p.HealthPingTime).FirstOrDefault() ?? DateTime.Now.AddDays(-100), Username = (from p in healthresult where p.ComputerAsset == t.ComputerAsset select p.HealthCurrentUser).FirstOrDefault(), CurrentWindow = (from p in healthresult where p.ComputerAsset == t.ComputerAsset select p.HealthCurrentWindow).FirstOrDefault(), Uptime = (from p in healthresult where p.ComputerAsset == t.ComputerAsset select p.HealthUptime).FirstOrDefault() }).OrderBy(t => t.Pingable); return query; }TrackingBoardPCs function:public static IQueryable<tblTrackingBoardPC> TrackingBoardPCs() { var query = (from tbpcs in db.GetTable<tblTrackingBoardPC>() select tbpcs); return query; } | Returning an IEnumerable using Linq-to-SQL which is then bound to a GridView | c#;database;linq to sql | First, the fact that your methods are static, and accessing what appears to be a static, disposable field, scares me: your application quite possibly has structural problems much more important than a slow query - but you haven't included nearly enough code for us to review that aspect.All I can say, is that db instances should be as short-lived as possible, and properly disposed once you're done with them; you might want to look into patterns like Repository and Unit-of-Work, to wrap up your LINQ-to-SQL dependencies.As you may or may not know, LINQ-to-SQL queries don't hit the database immediately; deferred execution makes the provider translate your expressions into proper SQL when the results are iterated... which means... your UI is actually what's triggering query execution.Let's see...var pingresult = from p in db.GetTable<tblTBHealthPing>() group p by p.ComputerAsset into g select g.OrderByDescending(t => t.HealthPingTime).FirstOrDefault();I had to read twice and think more than I should have done so, to parse exactly what's going on here and make sure I was reading it right - the FirstOrDefault applies to each grouping, right?Sometimes method notation is easier to read:var pingResult = db.GetTable<tblTBHealthPing>() .GroupBy(p => p.ComputerAsset) .Select(g => g.OrderByDescending(t => t.HealthPingTime) .FirstOrDefault());If I read this correctly (did I?), pingResult is an IGrouping<tblTBHealthPing> where each group contains the greatest HealthPingTime, and each group represents a ComputerAsset.I would materialize this query immediately, into a dictionary:var pingResults = db.GetTable<tblTBHealthPing>() .GroupBy(ping => ping.ComputerAsset) .AsEnumerable() .ToDictionary( grouping => grouping.Key, grouping => grouping.OrderByDescending(t => t.HealthPingTime) .FirstOrDefault());I'd do the same for the other one:var healthResults = db.GetTable<tblTBHealthHeartbeat>() .GroupBy(beat => beat.ComputerAsset) .AsEnumerable() .ToDictionary( grouping => grouping.Key, grouping => grouping.OrderByDescending(t => t.HealthHeartbeatTime) .FirstOrDefault());Now you have two materialized dictionaries, and you're armed for \$O(1)\$ lookups that you don't need to query anymore - I believe your code makes a bunch of \$O(n)\$ lookups for every single row.var query = db.GetTable<tblTrackingBoardPC>() .Where(t => t.TrackingGroup == groupName) .ToList() .Select(t => CreateTrackingComputerItem(t, pingResults, healthResults) .OrderBy(t => t.Pingable);Keep things clean, make a separate function for the messy projection:private TrackingComputer CreateTrackingComputerItem( tblTrackingBoardPC row, IDictionary<string,tblTBHealthPing> pingResults, IDictionary<string,tblTBHealthHeartbeat> healthResults){ tblTBHealthPing pingResult = null; pingResults.TryGetValue(row.ComputerAsset, out pingResult); tblTBHealthHeartbeat healthResult = null; healthResults.TryGetValue(row.ComputerAsset, out healthResult); return new TrackingComputer { ComputerName = row.ComputerAsset, IPAddress = row.ComputerIP, Location = row.Location, Pingable = pingResult != null ? pingResult.HealthPingResult : false, PingTime = pingResult != null ? pingResult.HealthPingTime : DateTime.Now.AddDays(-100), Username = healthResult != null ? healthResult.HealthCurrentUser : null, CurrentWindow = healthResult != null ? healthResult.HealthCurrentWindow : null, Uptime = healthResult != null ? healthResult.HealthUptime : null };}Calling ToList will materialize the query - yes, server-side sorting is generally faster, but you have complex projections going on here, and it's not because LINQ-to-SQL can do it all SQL-side that it should.With SQL doing the filtering, and LINQ-to-Objects doing the complex projection, IMO you're getting the best of both worlds, and you're returning materialized query results to your UI.That said - avoid exposing IQueryable<T> (and unmaterialized queries in general) outside your data access code. The reason is deferred execution: because the query didn't run yet, your client code is free to extend the query and potentially add things that the LINQ provider can't translate into SQL, resulting in unexpected exceptions |
_webmaster.38014 | Possible Duplicate:Do search engines penalise Home links and/or buttons? My work colleague has recently had conversations with some SEO consultants and after those conversations she has come to the conclusion that having a link to the home page on the home page will have a negative effect on the websites SEO.And because of this we are now building websites that don't have a home link show until you are on any page other than the home page.If the above argument is true then surely then if we are on the about page of a website we shouldn't show a navigation item for the page we are on, and that would the case for any other page of the website...So my question is:Does having a home navigation item on the home page have a negative effect on the websites SEO?And if not:Why has my colleague come to the above conclusion? Could she be misunderstanding something more important about home links on the home page regarding SEO? | Is having a 'home' navigation item on the home page negative to your sites SEO? | seo;links;homepage | null |
_webmaster.9360 | Does anyone know (or have running) if Chart Controls will work on GoDaddy's Windows Servers. They have ASP.NET 4.0 but is that enough?Thanks! | Does GoDaddy support Microsoft Chart Controls | web development;web hosting;godaddy;windows;microsoft | GoDaddy only has medium trust for ASP.NET apps and you will need a high level of trust. Also, I've heard you can't run MSChart.exe with GoDaddy and a lot of people have left GoDaddy just because of this.On a side note, slightly unrelated, GoDaddy's hosting is absolutely terrible, but that's just my two cents. |
_unix.204126 | I have apache folder on Debian with configuration (apache2.conf file, not httpd.conf) in /etc/apache2. On another configuration I hasn't this folder, but it was located in /usr/local/apache2/bin. Config file was httpd.conf.I need location of folders bin, and especially apxs.Thank you very much.Server version: Apache/2.2.22 (Debian)Server built: Jan 10 2015 15:51:04Server's Module Magic Number: 20051115:30Server loaded: APR 1.4.6, APR-Util 1.4.1Compiled using: APR 1.4.6, APR-Util 1.4.1Architecture: 32-bitServer MPM: Prefork threaded: no forked: yes (variable process count)Server compiled with.... -D APACHE_MPM_DIR=server/mpm/prefork -D APR_HAS_SENDFILE -D APR_HAS_MMAP -D APR_HAVE_IPV6 (IPv4-mapped addresses enabled) -D APR_USE_SYSVSEM_SERIALIZE -D APR_USE_PTHREAD_SERIALIZE -D APR_HAS_OTHER_CHILD -D AP_HAVE_RELIABLE_PIPED_LOGS -D DYNAMIC_MODULE_LIMIT=128 -D HTTPD_ROOT=/etc/apache2 -D SUEXEC_BIN=/usr/lib/apache2/suexec -D DEFAULT_PIDLOG=/var/run/apache2.pid -D DEFAULT_SCOREBOARD=logs/apache_runtime_status -D DEFAULT_LOCKFILE=/var/run/apache2/accept.lock -D DEFAULT_ERRORLOG=logs/error_log -D AP_TYPES_CONFIG_FILE=mime.types -D SERVER_CONFIG_FILE=apache2.confThe point is, that I want install PHP from source, and don't know apxs folder. | apache2 debian mod folder location | php;debian | null |
_webmaster.79546 | I have a website and looking to migrate to use Google Apps for my email. But the thing is that I'm currently using Earthlink as my mail provider for my domain name. This also goes for using Earthlink as my domain registrar too. So I basically have everything there. I just want to only migrate my mail service to google apps safely without disruption. I know I have to change my MX records in the DNS settings. I'm not sure but how do I make earthlink as a failback MX server if the Google Apps doesnt link up right away? I dont want to risk losing any mail.What I dont understand is why is there so many MX records? And what are the numbers in front of it mean? Does that mean priority on which one to goto if the other ones dont work?Below I have my dns settings: | Best and Safest Approach to Migrate Old Mail Service to Google Apps Gmail? | dns;domain registrar;mx | null |
_unix.265552 | I got this weird thing going on where,pacman -S -w awesome xorg-xinit xorg-server xorg-server-utilspacman doesn't download all the required dependencies.The reason for downloading the packages is because I'm creating a local repo with only the specific packages to my neededs. (instead of downloading the whole repo since the Arch community doesn't want you to do this because of bandwidth limitations, which is respect)Now, the packages defined above downloads nicely, it does download xorg-server and so on, and -w ensures they don't get installed. But -S should also download all the dependencies which it doesn't for whatever reason.The output when trying to install the above packages using the local repo later on results in:warning: cannot resolve xorg-xset, a dependency of xorg-server-utilswarning: cannot resolve xorg-xauth, a dependency of xorg-xinitand the list goes on... inspecting the repo surely the packages are missing and has never been downloaded anywhere.Any ideas to why this is? Have I missed something? Logically or parameter wise? | pacman doesn't download dependencies with -S and -w? | linux;arch linux;pacman | As pointed out by Earnestly and demonicmaniac3 over at #archlinux irc channel, this is because pacman won't re-download anything if it's already locally installed. But it will download whatever it is you're specifically instructing it to, which make a whole lot of sense come to think of it.This means if you're trying to download packages intended for a custom/local repo, you need to either make sure the packages you're about to download is not installed locally or do one of these options:Use a empty package database temporarly/locallypacman -y --dbpath /tmp ...This will create the illusion that nothing is installed locally and every single package needed is downloaded. This also requires you to do -y since there's no master package-list in your made up database.Perform a system upgradepacman -Syuw ...This should re-install/upgrade any package may it be installed or not already.Note: Not verified (I know to little about pacman's logic and is in a time pickle to test it)Generate a dependency-list using expacexpac -S '%E' -l '\n' xorg-xinit xorg-server-utils ...Calling expac on the <package string> (all the packages you are about to download) would give you a list of packages needed to run whatever it is you're downloading. You could use this list to fetch/add to your already existing string of packages scheduled for installation.I prefer the expac version since it holds up programmatically and would be useable in many scripts, but the quick and dirty version is to simply redirect the database which pacman checks. |
_vi.3374 | I want to select some lines in visual mode, and enter a custom command :Ex<CR> so that:'<,'>!expand -t4is run to expand all tabs in selected range. How to define the Ex command?I have tried things like:command! -range Ex !expand -t4but that command just hangs, it seems that the range was not forwarded. | How to define a custom user defined command to filter a range? | external command;user commands | null |
_codereview.84082 | I'm trying to learn more about kernels, so naturally I started to program one. I'm using tutorials from here. Right now I have modified the printf() that was supplied there. It used goto and I didn't like that.Can anyone see anything wrong with this code? It worked fine when I tested it.printf(hello %c world %c,'x','y')int printf(const char* restrict format, ...){ va_list parameters; va_start(parameters, format); int written = 0; size_t amount; while(*format != '\0') { if (*format != '%') { amount = 1; while(format[amount] && format[amount] != '%') //print every character until, % is encountered. amount++; print(format, amount); format += amount; written += amount; continue; } switch(*(++format)) //since format points now to %, move on step { case 'c': format++; //prepare next char char c = (char)va_arg(parameters, int); print(&c, sizeof(c)); written++; break; } } return written;}And print(), left completely unmodified:static void print(const char* data, size_t data_length){ for ( size_t i = 0; i < data_length; i++ ) putchar((int) ((const unsigned char*) data)[i]);} | Kernel development | c;kernel | You may need to document that this currently only works for the c option. Others may assume otherwise that this can support all or most of them. Of course, you don't have to do that since this is merely a reinvention of the wheel.Make sure to keep your indentation consistent. It seems you're mostly using four spaces for it, so it should be done everywhere. You should especially fix it in the large if statement.This looks a little unusual:switch(*(++format))I assume you're doing this to avoid duplication, but based on your current code, it looks like you can still put it in the switch body without repetition. Not having the increment in the statement itself may help with readability, too.You never check for errors, which is what the standard function does. If an error occurs, you should set the error indicator ferror and then return a negative value.Be sure you're reading the documentation on this function to help improve your own. |
_unix.367999 | This is my first post here, thanks for helping out! I have two external hard drives, HD #1 is NTFS and HD #2 is Mac OS Extended (I think this is the same as HFS+). I am copying many files from #1 to #2 (docs, pics, etc). I want to verify that all items copied correctly.On #1 (NTFS), folder A reports this size: 8,137,638,456 bytes (8.14 GB on disk) for 2,721 itemsOn #2 (HFS+), folder A' reports this size: 8,137,677,392 bytes (8.14 GB on disk) for 2,721 itemsHow can I verify that everything copied correctly? Kaleidoscope isn't helpful for this, since it just shows that the folders differ, without specifying how. Diff reports only this: that every subfolder in A' has .DS_STORE :diff -r /Volumes/WD Passport/A /Volumes/My Passport/A' Only in A': .DS_StoreOnly in A'/SUBFOLDER: .DS_StoreOnly in A'/SUBFOLDER: .DS_Store ...How can I verify that everything copied correctly? And is there something about NTFS and HFS+ file systems such that copying from one to the other results in different binary representations of files? | Size difference copying from NFTS to HFS+ | osx;file copy;ntfs | null |
_cs.43314 | Sometimes problems can be solved in $O(n^c)$ time for any $c > 1$, but not for $c=1$. Typically this is written as $O(n^{1 + \epsilon})$, since $\epsilon$ is understood to be some small positive constant. I want to know the terminology for describing this complexity class.For example, I would call a $\Theta(n)$ algorithm linear. I would call a $\Theta(n^2)$ algorithms quadratic. I would call a $\Theta(n \cdot log^c(n))$ algorithm nearly linear. (Note that nearly linear is better than $O(n^{1+\epsilon})$.)What do I call algorithms that are in $O(n^{1+\epsilon})$? | What is the name for the complexity class $O(n^{1+\epsilon})$ | terminology;asymptotics;landau notation | null |
_unix.215506 | I use a script to link some of the files I download to a different directory. When there are - in the file name, ln - s wont read the path correctly, even though the variable will be logged correctly to the log file I use. for f in ${AVIFILES}do BaseAviName=$(basename $f .avi) aviMp4name='$targetdir/$BaseAviName.mp4' linkAviFile='$targetdir/$f' downloadedFile=$('$theFile/$f') ln -s $downloadedFile $linkAviFile >>$logPath 2>&1 echo fileIs: $f ,linkAviFile is $linkAviFile ,BaseAviName: $BaseAviName '$aviMp4name: ' $aviMp4name '$downloadedFile: ' $downloadedFile >> $logPath doneThat's the error message from ln:ln: failed to create symbolic link '/home/user/Videos/TVEpisodes/Parks and Recreation/Parks.and.Recreation.S03E01.DVDRip.XviD-REWARD.avi' -> : No such file or directoryEven though the variable downloadedFile is logged with the correct path:'/home/user/Downloads/Parks And Recreation - Season 3 - DVDRip-REWARD/Parks.and.Recreation.S03E01.DVDRip.XviD-REWARD.avi'It seems, that for some reason, that when $downloadedFile is expanded for ln to work with it, ln will omit part of the filename, from the first - to the next / ( - Season 3 - DVDRip-REWARD). I can't find a good reason why this happens, and want to avoid it, any suggestions...EDIT: I rewrote the script and the problem disappeared. Thanks to anyone who helped | ln -s removes part of a file name, when filename is passed as a variable | bash;shell;quoting;ln | Even though the variable downloadedFile is logged with the correct path:'/home/user/Downloads/Parks And Recreation - Season 3 - DVDRip-REWARD/Parks.and.Recreation.S03E01.DVDRip.XviD-REWARD.avi'That's evidently not the correct path: it has extra ' characters at the beginning and at the end. You can see that in the error message from ln:ln: failed to create symbolic link '/home/user/Videos/TVEpisodes/Parks and Recreation/Parks.and.Recreation.S03E01.DVDRip.XviD-REWARD.avi' -> : No such file or directoryThe error message has the file name inside single quotes, and there are extra ' (ASCII single quotes) characters at the beginning and at the end.The problem in your script is obvious: you're adding extra ' characters when defining aviMp4name, linkAviFile and downloadedFile. Don't do that.for f in ${AVIFILES[@]}do BaseAviName=$(basename -- $f .avi) aviMp4name=$targetdir/$BaseAviName.mp4 linkAviFile=$targetdir/$f downloadedFile=$($theFile/$f) ln -s -- $downloadedFile $linkAviFile >>$logPath 2>&1 echo fileIs: $f ,linkAviFile is $linkAviFile ,BaseAviName: $BaseAviName '$aviMp4name: ' $aviMp4name '$downloadedFile: ' $downloadedFile >> $logPath doneIn the shell source syntax, single quotes delimit literal strings, for example a='hello world!' sets the variable a to the 12-character string hello world!. If you put single quotes into a variable, you get single quotes back: a='hello world!' sets a to the 14-character string 'hello world!'.The key thing to remember with quotes in shell scripts is to put double quotes around variable expansions, e.g. ln -s -- $downloadedFile $linkAviFile. Code like ln -s -- $downloadedFile $linkAviFile would split the values of the variables downloadedFile and linkAviFile at whitespace characters and would interpret each piece as a wildcard pattern. Those double quotes are part of the shell source syntax, they're interpreted by the parser. Putting quotes into a variable's value won't solve anything.Also note that if a file name begins with a -, it will be interpreted as an option by the command. To avoid this, when you have file names in variables, pass the argument -- to the command after all options and before all file names (you can omit -- if you're sure the file names don't begin with -, for example if you know they're absolute paths). -- means no more options after this point.Note that ${AVIFILES} would, like any other unquoted expansion, split the value of the variable at whitespace. To store multiple file names in a variable, make it an array instead of a string; this requires ksh, bash or zsh, it doesn't work in plain sh:AVIFILES=(foo.avi bar.avi file name with spaces.avi) |
_codereview.27531 | I've never put together a plugin before but I thought this would be useful to push technology forward. It's basically a browser sniffer, but if the user has a modern browser it will reward them for keeping it up to date.Unfortunately, the code is a little heavier than I expected (6kb minified).I just wondered if anyone could give some advice on how to make it more clean and compressed.function abiejs(d) {use strict;/* abiejs.d === defaults abiejs.b === document body abiejs.c === abie container abiejs.e === abie experience*/abiejs.d = (function() { var def = d; if(!def.position){def.position = 'tr';} if(!def.merit){def.merit = 'http://browsehappy.com/';} if(!def.demerit){def.demerit = 'http://browsehappy.com/';} if(!def.showTime){def.showTime = 5000;} if(!def.content){def.content = '';} if(!def.meritColor){def.meritColor = 'green';} if(!def.demeritColor){def.demeritColor = 'red';} if(def.cookie){def.cookie = true;} else {def.cookie = false;} if(!def.cookieShowLimit){def.cookieShowLimit = 'none';} if(!def.cookieExperiation){def.cookieExperiation = 10000;} if(def.flag){def.flag = true;} else {def.flag = false;} return def; })(d);navigator.sayswho = (function() { var N= navigator.appName, ua= navigator.userAgent, tem; var M= ua.match(/(opera|chrome|safari|firefox|msie)\/?\s*(\.?\d+(\.\d+)*)/i); if(M &&(tem= ua.match(/version\/([\.\d]+)/i)) !== null){M[2] = tem[1];} M= M? [M[1], M[2]]: [N, navigator.appVersion, '-?']; return M;})(); /* * navigator.sayswho[0] === browser name * navigator.sayswho[1] === browser version */function createAbie(p) { //Get position and set it to lowercase characters var pos = p.toLowerCase(); //Create the abie container div abiejs.c = document.createElement('div'); //Decalre id abiejs.c.id = 'abie'; //Declare position abiejs.c.style.position = 'fixed'; //Declare display abiejs.c.style.display = 'block'; //Set element in document document.getElementsByTagName('body')[0].appendChild(abiejs.c); //Create Abie Experience Element (This will animate) abiejs.e = document.createElement('div'); //Declare id abiejs.e.id = 'abieExp'; //Declare position abiejs.e.style.position = 'absolute'; abiejs.e.style.cursor = 'pointer'; //Set the merit here (this will need to be a condition) !!!!!!!!!!! abiejs.e.innerHTML = abiejs.d.content; //Append element to container abiejs.c.appendChild(abiejs.e); //Define the height and width of the merit property abiejs.e.height = abiejs.d.height || abiejs.e.offsetHeight; abiejs.e.width = abiejs.d.width || abiejs.e.offsetWidth; //Set the height and width values abiejs.c.style.height = abiejs.e.height + 'px'; abiejs.c.style.width = abiejs.e.width + 'px'; abiejs.e.style.height = abiejs.e.height + 'px'; abiejs.e.style.width = abiejs.e.width + 'px'; //Run condition to ensure where abie should be if(pos.indexOf('t') !== -1){ abiejs.c.style.top = '0'; abiejs.e.style.top = (abiejs.e.height * -1) + 'px'; } else if(pos.indexOf('b') !== -1) { abiejs.c.style.bottom = '0'; abiejs.e.style.bottom = (abiejs.e.height * -1) + 'px'; } else { abiejs.c.style.top = '0'; abiejs.e.style.top = (abiejs.e.height * -1) + 'px'; } if(pos.indexOf('r') !== -1) { abiejs.c.style.right = '0'; abiejs.e.style.right = '0'; abiejs.e.style.textAlign = 'right'; } else if(pos.indexOf('l') !== -1){ abiejs.c.style.left = '0'; abiejs.e.style.left = '0'; abiejs.e.style.textAlign = 'left'; } else { abiejs.c.style.right = '0'; abiejs.e.style.textAlign = 'right'; } abiejs.e.style.background = ((judgeAbie() === true) ? abiejs.d.meritColor : abiejs.d.demeritColor);}//Create Cookiefunction createCookie(name,value,days) { var expires = ''; if (days) { var date = new Date(); date.setTime(date.getTime()+(days*24*60*60*1000)); expires = ; expires=+date.toGMTString(); }else { expires = ; } document.cookie = name+=+value+expires+; path=/;}//Read Cookiefunction readCookie(name) { var nameEQ = name + =; var ca = document.cookie.split(';'); for(var i=0;i < ca.length;i++) { var c = ca[i]; while (c.charAt(0) == ' ') {c = c.substring(1,c.length);} if (c.indexOf(nameEQ) == 0) {return c.substring(nameEQ.length,c.length);} } return null;}//Erase Cookiefunction eraseCookie(name) { createCookie(name,,-1);}//Set property for first loop so danceInAbie.inc can be setdanceInAbie.firstStep = false;function danceInAbie(pos, h) { if(bindAbie.first === true) {return false;} //Check if it is first iteration if(danceInAbie.firstStep === false) { //Update property so danceInAbie.inc isn't updated over and over again danceInAbie.firstStep = true; //Set danceInAbie.inc to the height of element so it starts animating from current position danceInAbie.inc = (h * -1); } //If abie's height is less than -1 increment the value if(danceInAbie.inc < -1) { setTimeout(function(){ if(pos === 't') { abiejs.e.style.top = danceInAbie.inc + 'px'; } else { abiejs.e.style.bottom = danceInAbie.inc + 'px'; } danceInAbie.inc++; //danceInAbie.inc = danceInAbie.inc + 2; danceInAbie(pos, h); }, 20); return true; } else { danceOutAbie.firstStep = false; return true; }}danceOutAbie.firstStep = false;function danceOutAbie(pos, h) { if(bindAbie.first === true) {return false;} //Check if it is first iteration if(danceOutAbie.firstStep === false) { //Update property so danceInAbie.inc isn't updated over and over again danceOutAbie.firstStep = true; //Set danceInAbie.dec to the height of element so it starts animating from current position danceOutAbie.dec = 0; } //If abie's height is less than 0 increment the value if(danceOutAbie.dec < h) { setTimeout(function(){ if(pos === 't') { abiejs.e.style.top = '-' + danceOutAbie.dec + 'px'; } else { abiejs.e.style.bottom = '-' + danceOutAbie.dec + 'px'; } danceOutAbie.dec++; //danceOutAbie.dec = danceOutAbie.dec + 2; danceOutAbie(pos, h); }, 10); } else { danceInAbie.firstStep = false; return true; }}//Add Eventsfunction addEvent(elem, event, fn) { // avoid memory overhead of new anonymous functions for every event handler that's installed // by using local functions function listenHandler(e) { var ret = fn.apply(this, arguments); if (ret === false) { e.stopPropagation(); e.preventDefault(); } return(ret); } function attachHandler() { // set the this pointer same as addEventListener when fn is called // and make sure the event is passed to the fn also so that works the same too var ret = fn.call(elem, window.event); if (ret === false) { window.event.returnValue = false; window.event.cancelBubble = true; } return(ret); } if (elem.addEventListener) { elem.addEventListener(event, listenHandler, false); } else { elem.attachEvent(on + event, attachHandler); }}function judgeAbie() { var v = parseInt(navigator.sayswho[1], 10); if(navigator.sayswho[0] === 'Chrome'){ if(v < 27) { return false; } else { return true; } } else if(navigator.sayswho[0] === 'Firefox') { if(v < 21) { return false; } else { return true; } } else if(navigator.sayswho[0] === 'MSIE') { if(v < 9) { return false; } else { return true; } } else if(navigator.sayswho[0] === 'Safari') { if(v < 6) { return false; } else { return true; } } else if(navigator.sayswho[0] === 'Opera') { if(v < 12) { return false; } else { return true; } } else { //I don't know what you have return false; }}//Merit or Demeritfunction meriter() {window.location = abiejs.d.mer;}function demeriter() {window.location = abiejs.d.dmer;}function abieMeritDemerit() { //Get abies judgement abieMeritDemerit.judgement = judgeAbie(); //Decide to merit or demerit if(abieMeritDemerit.judgement === true) { //If string send user to page if(typeof abiejs.d.merit === 'string') { return meriter(); //Else try to run as function } else { return abiejs.d.merit(); } } else if(abieMeritDemerit.judgement === false) { //If string send user to page if(typeof abiejs.d.demerit === 'string') { return demeriter(); //Else try to run as function } else { return abiejs.d.demerit(); } } else { return abiejs.d.dmer(); }}function abieRun(pos) { abieRun.cookie = readCookie('abiejs'); if(abieRun.cookie < abiejs.d.cookieShowLimit || abiejs.d.cookie === false) { if(pos.indexOf('t') !== -1) { //If danceInAbie is complete and returns true then run danceOutAbie danceInAbie('t', abiejs.e.height); setTimeout(function() {danceOutAbie('t', abiejs.e.height);}, abiejs.d.showTime); } else { //If danceOutAbie is complete and returns true then run danceInAbie danceInAbie('b', abiejs.e.height); setTimeout(function() {danceOutAbie('b', abiejs.e.height);}, abiejs.d.showTime); } }}//bind mouseover and onclick events//Check if mouse is already over elementbindAbie.first = false;function bindAbie(pos) { addEvent(abiejs.c, 'mouseover', function() { bindAbie.first = true; if(pos.indexOf('t') !== -1) { abiejs.e.style.top = 0; } else { abiejs.e.style.bottom = 0; } }); addEvent(abiejs.c, 'mouseout', function() { bindAbie.first = true; if(pos.indexOf('t') !== -1) { abiejs.e.style.top = '-' + abiejs.e.height + 'px'; } else { abiejs.e.style.bottom = '-' + abiejs.e.height + 'px'; } }); addEvent(abiejs.e, 'click', function() { abieMeritDemerit(); });}function abiesFlag(pos) { if(abiejs.d.flag === true) { if(pos.indexOf('t') !== -1) { if(pos.indexOf('r') !== -1) { abiejs.e.style.WebkitBorderRadius = '0 0 0 100%'; abiejs.e.style.MozBorderRadius = '0 0 0 100%'; abiejs.e.style.borderRadius = '0 0 0 100%'; } else { abiejs.e.style.WebkitBorderRadius = '0 0 100% 0'; abiejs.e.style.MozBorderRadius = '0 0 100% 0'; abiejs.e.style.borderRadius = '0 0 100% 0'; } } else { if(pos.indexOf('r') !== -1) { abiejs.e.style.WebkitBorderRadius = '100% 0 0 0'; abiejs.e.style.MozBorderRadius = '100% 0 0 0'; abiejs.e.style.borderRadius = '100% 0 0 0'; } else { abiejs.e.style.WebkitBorderRadius = '0 100% 0 0'; abiejs.e.style.MozBorderRadius = '0 100% 0 0'; abiejs.e.style.borderRadius = '0 100% 0 0'; } } }}//Make Cookiefunction abieMakeCookies() { //Check if user wants cookie if(abiejs.d.cookie === true) { var cookieVal = readCookie('abiejs'); //Create Cookie Expiration abieMakeCookies.expry = (abiejs.d.cookieExperiation === 'none' ? 1000 : abiejs.d.cookieExperiation); //Check if no cookie exists yet if(cookieVal === null) { //If there is no cookie then create the first iteration createCookie('abiejs',0,abieMakeCookies.expry); //If there is a cookie begin incrementing iteration } else { //If the cookie has no limit then set it a huge number if(abiejs.d.cookieShowLimit === 'none') { createCookie('abiejs',0,abieMakeCookies.expry); } else { cookieVal++; createCookie('abiejs',cookieVal,abieMakeCookies.expry); } } }}createAbie(abiejs.d.position);bindAbie(abiejs.d.position);abiesFlag(abiejs.d.position);abieMakeCookies();abieRun(abiejs.d.position);}This is the initiation:abiejs({merit : function() { cornify();},demerit : 'http://browsehappy.com/'});Also, I'm curious if I'm using the proper terminology in the comments. If you look here you can see more of it's documentation. I would love it if someone could help me out and give me pointers on ways to optimize a pure javascript plugin. | Review my browser reward plugin | javascript;plugin | null |
_unix.188050 | Often, I insert my USB storage into my computer and it will not mount. I can see the USB drive recognised in KDE's panel, but it will not be mounted. I can click on the mount button in the panel, but nothing happens. If I remove the device and reconnect, always mounts the second time.I looked through sudo journalctl for the relevant log lines, and there were two differences. Firstly, the failed mounting had the additional lines:Mar 04 14:35:34 sparhawk-XPS-17 kernel: usbcore: registered new interface driver usb-storageMar 04 14:35:34 sparhawk-XPS-17 kernel: usbcore: registered new interface driver uasSecondly (perhaps unimportant), the failed mounting did mtp-probe before the kernel detected the USB mass storage device; this order was inverted when it worked.The full log is reproduced below. This represents a failed connection, a disconnection, and a working connection. How can I make my USB device be mounted on the first connection?I am using Arch Linux, but I also experienced this (I think) when I was using Kubuntu.Mar 04 14:35:34 sparhawk-XPS-17 kernel: usb 4-1.2: new high-speed USB device number 7 using ehci-pciMar 04 14:35:34 sparhawk-XPS-17 mtp-probe[5109]: checking bus 4, device 7: /sys/devices/pci0000:00/0000:00:1d.0/usb4/4-1/4-1.2Mar 04 14:35:34 sparhawk-XPS-17 mtp-probe[5109]: bus: 4, device: 7 was not an MTP deviceMar 04 14:35:34 sparhawk-XPS-17 kernel: usb-storage 4-1.2:1.0: USB Mass Storage device detectedMar 04 14:35:34 sparhawk-XPS-17 kernel: scsi host6: usb-storage 4-1.2:1.0Mar 04 14:35:34 sparhawk-XPS-17 kernel: usbcore: registered new interface driver usb-storageMar 04 14:35:34 sparhawk-XPS-17 kernel: usbcore: registered new interface driver uasMar 04 14:35:35 sparhawk-XPS-17 kernel: scsi 6:0:0:0: Direct-Access USB Flash Memory PMAP PQ: 0 ANSI: 4Mar 04 14:35:36 sparhawk-XPS-17 kernel: sd 6:0:0:0: [sdc] 15240576 512-byte logical blocks: (7.80 GB/7.26 GiB)Mar 04 14:35:36 sparhawk-XPS-17 kernel: sd 6:0:0:0: [sdc] Write Protect is offMar 04 14:35:36 sparhawk-XPS-17 kernel: sd 6:0:0:0: [sdc] Mode Sense: 23 00 00 00Mar 04 14:35:36 sparhawk-XPS-17 kernel: sd 6:0:0:0: [sdc] No Caching mode page foundMar 04 14:35:36 sparhawk-XPS-17 kernel: sd 6:0:0:0: [sdc] Assuming drive cache: write throughMar 04 14:35:36 sparhawk-XPS-17 kernel: sdc: sdc1Mar 04 14:35:36 sparhawk-XPS-17 kernel: sd 6:0:0:0: [sdc] Attached SCSI removable diskMar 04 14:35:36 sparhawk-XPS-17 baloo_file[640]: /org/freedesktop/UDisks2/drives/USB_Flash_Memory_00187D0F56A0EE214000ABF8 has new interfaces: (org.freedesktop.UDisks2.Drive)Mar 04 14:35:36 sparhawk-XPS-17 baloo_file[640]: /org/freedesktop/UDisks2/drives/USB_Flash_Memory_00187D0F56A0EE214000ABF8Mar 04 14:35:36 sparhawk-XPS-17 baloo_file[640]: QObject::connect: Cannot connect (null)::accessibilityChanged(bool,QString) to Baloo::StorageDevices::slotAccessibilityChanged(bool,QString)Mar 04 14:35:36 sparhawk-XPS-17 baloo_file[640]: /org/freedesktop/UDisks2/block_devices/sdc has new interfaces: (org.freedesktop.UDisks2.Block, org.freedesktop.UDisks2.PartitionTable)Mar 04 14:35:36 sparhawk-XPS-17 baloo_file[640]: /org/freedesktop/UDisks2/block_devices/sdcMar 04 14:35:36 sparhawk-XPS-17 baloo_file[640]: QObject::connect: Cannot connect (null)::accessibilityChanged(bool,QString) to Baloo::StorageDevices::slotAccessibilityChanged(bool,QString)Mar 04 14:35:36 sparhawk-XPS-17 baloo_file[640]: /org/freedesktop/UDisks2/block_devices/sdc1 has new interfaces: (org.freedesktop.UDisks2.Block, org.freedesktop.UDisks2.Filesystem, org.freedesktop.UDisks2.PartMar 04 14:35:36 sparhawk-XPS-17 baloo_file[640]: /org/freedesktop/UDisks2/block_devices/sdc1Mar 04 14:35:39 sparhawk-XPS-17 kernel: usb 4-1.2: USB disconnect, device number 7Mar 04 14:35:39 sparhawk-XPS-17 baloo_file[640]: /org/freedesktop/UDisks2/block_devices/sdc1 lost interfaces: (org.freedesktop.UDisks2.Partition, org.freedesktop.UDisks2.Filesystem, org.freedesktop.UDisks2.BloMar 04 14:35:39 sparhawk-XPS-17 baloo_file[640]: Found removable storage volume for Baloo undocking: /org/freedesktop/UDisks2/block_devices/sdc1Mar 04 14:35:39 sparhawk-XPS-17 baloo_file[640]: /org/freedesktop/UDisks2/block_devices/sdc lost interfaces: (org.freedesktop.UDisks2.PartitionTable, org.freedesktop.UDisks2.Block)Mar 04 14:35:39 sparhawk-XPS-17 baloo_file[640]: Found removable storage volume for Baloo undocking: /org/freedesktop/UDisks2/block_devices/sdcMar 04 14:35:39 sparhawk-XPS-17 baloo_file[640]: /org/freedesktop/UDisks2/drives/USB_Flash_Memory_00187D0F56A0EE214000ABF8 lost interfaces: (org.freedesktop.UDisks2.Drive)Mar 04 14:35:39 sparhawk-XPS-17 baloo_file[640]: Found removable storage volume for Baloo undocking: /org/freedesktop/UDisks2/drives/USB_Flash_Memory_00187D0F56A0EE214000ABF8Mar 04 14:35:39 sparhawk-XPS-17 systemd-udevd[212]: error opening USB device 'descriptors' fileMar 04 14:35:43 sparhawk-XPS-17 kernel: usb 4-1.2: new high-speed USB device number 8 using ehci-pciMar 04 14:35:43 sparhawk-XPS-17 kernel: usb-storage 4-1.2:1.0: USB Mass Storage device detectedMar 04 14:35:43 sparhawk-XPS-17 kernel: scsi host7: usb-storage 4-1.2:1.0Mar 04 14:35:43 sparhawk-XPS-17 mtp-probe[5198]: checking bus 4, device 8: /sys/devices/pci0000:00/0000:00:1d.0/usb4/4-1/4-1.2Mar 04 14:35:43 sparhawk-XPS-17 mtp-probe[5198]: bus: 4, device: 8 was not an MTP deviceMar 04 14:35:44 sparhawk-XPS-17 kernel: scsi 7:0:0:0: Direct-Access USB Flash Memory PMAP PQ: 0 ANSI: 4Mar 04 14:35:45 sparhawk-XPS-17 kernel: sd 7:0:0:0: [sdc] 15240576 512-byte logical blocks: (7.80 GB/7.26 GiB)Mar 04 14:35:45 sparhawk-XPS-17 kernel: sd 7:0:0:0: [sdc] Write Protect is offMar 04 14:35:45 sparhawk-XPS-17 kernel: sd 7:0:0:0: [sdc] Mode Sense: 23 00 00 00Mar 04 14:35:45 sparhawk-XPS-17 kernel: sd 7:0:0:0: [sdc] No Caching mode page foundMar 04 14:35:45 sparhawk-XPS-17 kernel: sd 7:0:0:0: [sdc] Assuming drive cache: write throughMar 04 14:35:45 sparhawk-XPS-17 kernel: sdc: sdc1Mar 04 14:35:45 sparhawk-XPS-17 kernel: sd 7:0:0:0: [sdc] Attached SCSI removable diskMar 04 14:35:45 sparhawk-XPS-17 baloo_file[640]: /org/freedesktop/UDisks2/drives/USB_Flash_Memory_00187D0F56A0EE214000ABF8 has new interfaces: (org.freedesktop.UDisks2.Drive)Mar 04 14:35:45 sparhawk-XPS-17 baloo_file[640]: /org/freedesktop/UDisks2/drives/USB_Flash_Memory_00187D0F56A0EE214000ABF8Mar 04 14:35:45 sparhawk-XPS-17 baloo_file[640]: QObject::connect: Cannot connect (null)::accessibilityChanged(bool,QString) to Baloo::StorageDevices::slotAccessibilityChanged(bool,QString)Mar 04 14:35:45 sparhawk-XPS-17 baloo_file[640]: /org/freedesktop/UDisks2/block_devices/sdc has new interfaces: (org.freedesktop.UDisks2.Block, org.freedesktop.UDisks2.PartitionTable)Mar 04 14:35:45 sparhawk-XPS-17 baloo_file[640]: /org/freedesktop/UDisks2/block_devices/sdcMar 04 14:35:45 sparhawk-XPS-17 baloo_file[640]: QObject::connect: Cannot connect (null)::accessibilityChanged(bool,QString) to Baloo::StorageDevices::slotAccessibilityChanged(bool,QString)Mar 04 14:35:45 sparhawk-XPS-17 baloo_file[640]: /org/freedesktop/UDisks2/block_devices/sdc1 has new interfaces: (org.freedesktop.UDisks2.Block, org.freedesktop.UDisks2.Filesystem, org.freedesktop.UDisks2.PartMar 04 14:35:45 sparhawk-XPS-17 baloo_file[640]: /org/freedesktop/UDisks2/block_devices/sdc1Mar 04 14:35:45 sparhawk-XPS-17 udisksd[554]: Mounted /dev/sdc1 at /run/media/lee/Lee-key on behalf of uid 1000Mar 04 14:35:45 sparhawk-XPS-17 org.gtk.Private.UDisks2VolumeMonitor[420]: index_parse.c:190: indx_parse(): error opening /run/media/lee/Lee-key/BDMV/index.bdmvMar 04 14:35:45 sparhawk-XPS-17 org.gtk.Private.UDisks2VolumeMonitor[420]: index_parse.c:190: indx_parse(): error opening /run/media/lee/Lee-key/BDMV/BACKUP/index.bdmvMar 04 14:35:45 sparhawk-XPS-17 baloo_file[640]: true /org/freedesktop/UDisks2/block_devices/sdc1Mar 04 14:35:45 sparhawk-XPS-17 polkitd[416]: Operator of unix-session:c2 FAILED to authenticate to gain authorization for action org.freedesktop.udisks2.filesystem-mount for system-bus-name::1.258 [kdeinit4: kded4 [Mar 04 14:35:34 sparhawk-XPS-17 kernel: usb 4-1.2: new high-speed USB device number 7 using ehci-pciMar 04 14:35:34 sparhawk-XPS-17 mtp-probe[5109]: checking bus 4, device 7: /sys/devices/pci0000:00/0000:00:1d.0/usb4/4-1/4-1.2Mar 04 14:35:34 sparhawk-XPS-17 mtp-probe[5109]: bus: 4, device: 7 was not an MTP deviceMar 04 14:35:34 sparhawk-XPS-17 kernel: usb-storage 4-1.2:1.0: USB Mass Storage device detectedMar 04 14:35:34 sparhawk-XPS-17 kernel: scsi host6: usb-storage 4-1.2:1.0Mar 04 14:35:34 sparhawk-XPS-17 kernel: usbcore: registered new interface driver usb-storageMar 04 14:35:34 sparhawk-XPS-17 kernel: usbcore: registered new interface driver uasMar 04 14:35:35 sparhawk-XPS-17 kernel: scsi 6:0:0:0: Direct-Access USB Flash Memory PMAP PQ: 0 ANSI: 4Mar 04 14:35:36 sparhawk-XPS-17 kernel: sd 6:0:0:0: [sdc] 15240576 512-byte logical blocks: (7.80 GB/7.26 GiB)Mar 04 14:35:36 sparhawk-XPS-17 kernel: sd 6:0:0:0: [sdc] Write Protect is offMar 04 14:35:36 sparhawk-XPS-17 kernel: sd 6:0:0:0: [sdc] Mode Sense: 23 00 00 00Mar 04 14:35:36 sparhawk-XPS-17 kernel: sd 6:0:0:0: [sdc] No Caching mode page foundMar 04 14:35:36 sparhawk-XPS-17 kernel: sd 6:0:0:0: [sdc] Assuming drive cache: write throughMar 04 14:35:36 sparhawk-XPS-17 kernel: sdc: sdc1Mar 04 14:35:36 sparhawk-XPS-17 kernel: sd 6:0:0:0: [sdc] Attached SCSI removable diskMar 04 14:35:36 sparhawk-XPS-17 baloo_file[640]: /org/freedesktop/UDisks2/drives/USB_Flash_Memory_00187D0F56A0EE214000ABF8 has new interfaces: (org.freedesktop.UDisks2.Drive)Mar 04 14:35:36 sparhawk-XPS-17 baloo_file[640]: /org/freedesktop/UDisks2/drives/USB_Flash_Memory_00187D0F56A0EE214000ABF8Mar 04 14:35:36 sparhawk-XPS-17 baloo_file[640]: QObject::connect: Cannot connect (null)::accessibilityChanged(bool,QString) to Baloo::StorageDevices::slotAccessibilityChanged(bool,QString)Mar 04 14:35:36 sparhawk-XPS-17 baloo_file[640]: /org/freedesktop/UDisks2/block_devices/sdc has new interfaces: (org.freedesktop.UDisks2.Block, org.freedesktop.UDisks2.PartitionTable)Mar 04 14:35:36 sparhawk-XPS-17 baloo_file[640]: /org/freedesktop/UDisks2/block_devices/sdcMar 04 14:35:36 sparhawk-XPS-17 baloo_file[640]: QObject::connect: Cannot connect (null)::accessibilityChanged(bool,QString) to Baloo::StorageDevices::slotAccessibilityChanged(bool,QString)Mar 04 14:35:36 sparhawk-XPS-17 baloo_file[640]: /org/freedesktop/UDisks2/block_devices/sdc1 has new interfaces: (org.freedesktop.UDisks2.Block, org.freedesktop.UDisks2.Filesystem, org.freedesktop.UDisks2.PartMar 04 14:35:36 sparhawk-XPS-17 baloo_file[640]: /org/freedesktop/UDisks2/block_devices/sdc1Mar 04 14:35:39 sparhawk-XPS-17 kernel: usb 4-1.2: USB disconnect, device number 7Mar 04 14:35:39 sparhawk-XPS-17 baloo_file[640]: /org/freedesktop/UDisks2/block_devices/sdc1 lost interfaces: (org.freedesktop.UDisks2.Partition, org.freedesktop.UDisks2.Filesystem, org.freedesktop.UDisks2.BloMar 04 14:35:39 sparhawk-XPS-17 baloo_file[640]: Found removable storage volume for Baloo undocking: /org/freedesktop/UDisks2/block_devices/sdc1Mar 04 14:35:39 sparhawk-XPS-17 baloo_file[640]: /org/freedesktop/UDisks2/block_devices/sdc lost interfaces: (org.freedesktop.UDisks2.PartitionTable, org.freedesktop.UDisks2.Block)Mar 04 14:35:39 sparhawk-XPS-17 baloo_file[640]: Found removable storage volume for Baloo undocking: /org/freedesktop/UDisks2/block_devices/sdcMar 04 14:35:39 sparhawk-XPS-17 baloo_file[640]: /org/freedesktop/UDisks2/drives/USB_Flash_Memory_00187D0F56A0EE214000ABF8 lost interfaces: (org.freedesktop.UDisks2.Drive)Mar 04 14:35:39 sparhawk-XPS-17 baloo_file[640]: Found removable storage volume for Baloo undocking: /org/freedesktop/UDisks2/drives/USB_Flash_Memory_00187D0F56A0EE214000ABF8Mar 04 14:35:39 sparhawk-XPS-17 systemd-udevd[212]: error opening USB device 'descriptors' fileMar 04 14:35:43 sparhawk-XPS-17 kernel: usb 4-1.2: new high-speed USB device number 8 using ehci-pciMar 04 14:35:43 sparhawk-XPS-17 kernel: usb-storage 4-1.2:1.0: USB Mass Storage device detectedMar 04 14:35:43 sparhawk-XPS-17 kernel: scsi host7: usb-storage 4-1.2:1.0Mar 04 14:35:43 sparhawk-XPS-17 mtp-probe[5198]: checking bus 4, device 8: /sys/devices/pci0000:00/0000:00:1d.0/usb4/4-1/4-1.2Mar 04 14:35:43 sparhawk-XPS-17 mtp-probe[5198]: bus: 4, device: 8 was not an MTP deviceMar 04 14:35:44 sparhawk-XPS-17 kernel: scsi 7:0:0:0: Direct-Access USB Flash Memory PMAP PQ: 0 ANSI: 4Mar 04 14:35:45 sparhawk-XPS-17 kernel: sd 7:0:0:0: [sdc] 15240576 512-byte logical blocks: (7.80 GB/7.26 GiB)Mar 04 14:35:45 sparhawk-XPS-17 kernel: sd 7:0:0:0: [sdc] Write Protect is offMar 04 14:35:45 sparhawk-XPS-17 kernel: sd 7:0:0:0: [sdc] Mode Sense: 23 00 00 00Mar 04 14:35:45 sparhawk-XPS-17 kernel: sd 7:0:0:0: [sdc] No Caching mode page foundMar 04 14:35:45 sparhawk-XPS-17 kernel: sd 7:0:0:0: [sdc] Assuming drive cache: write throughMar 04 14:35:45 sparhawk-XPS-17 kernel: sdc: sdc1Mar 04 14:35:45 sparhawk-XPS-17 kernel: sd 7:0:0:0: [sdc] Attached SCSI removable diskMar 04 14:35:45 sparhawk-XPS-17 baloo_file[640]: /org/freedesktop/UDisks2/drives/USB_Flash_Memory_00187D0F56A0EE214000ABF8 has new interfaces: (org.freedesktop.UDisks2.Drive)Mar 04 14:35:45 sparhawk-XPS-17 baloo_file[640]: /org/freedesktop/UDisks2/drives/USB_Flash_Memory_00187D0F56A0EE214000ABF8Mar 04 14:35:45 sparhawk-XPS-17 baloo_file[640]: QObject::connect: Cannot connect (null)::accessibilityChanged(bool,QString) to Baloo::StorageDevices::slotAccessibilityChanged(bool,QString)Mar 04 14:35:45 sparhawk-XPS-17 baloo_file[640]: /org/freedesktop/UDisks2/block_devices/sdc has new interfaces: (org.freedesktop.UDisks2.Block, org.freedesktop.UDisks2.PartitionTable)Mar 04 14:35:45 sparhawk-XPS-17 baloo_file[640]: /org/freedesktop/UDisks2/block_devices/sdcMar 04 14:35:45 sparhawk-XPS-17 baloo_file[640]: QObject::connect: Cannot connect (null)::accessibilityChanged(bool,QString) to Baloo::StorageDevices::slotAccessibilityChanged(bool,QString)Mar 04 14:35:45 sparhawk-XPS-17 baloo_file[640]: /org/freedesktop/UDisks2/block_devices/sdc1 has new interfaces: (org.freedesktop.UDisks2.Block, org.freedesktop.UDisks2.Filesystem, org.freedesktop.UDisks2.PartMar 04 14:35:45 sparhawk-XPS-17 baloo_file[640]: /org/freedesktop/UDisks2/block_devices/sdc1Mar 04 14:35:45 sparhawk-XPS-17 udisksd[554]: Mounted /dev/sdc1 at /run/media/lee/Lee-key on behalf of uid 1000Mar 04 14:35:45 sparhawk-XPS-17 org.gtk.Private.UDisks2VolumeMonitor[420]: index_parse.c:190: indx_parse(): error opening /run/media/lee/Lee-key/BDMV/index.bdmvMar 04 14:35:45 sparhawk-XPS-17 org.gtk.Private.UDisks2VolumeMonitor[420]: index_parse.c:190: indx_parse(): error opening /run/media/lee/Lee-key/BDMV/BACKUP/index.bdmvMar 04 14:35:45 sparhawk-XPS-17 baloo_file[640]: true /org/freedesktop/UDisks2/block_devices/sdc1Mar 04 14:35:45 sparhawk-XPS-17 polkitd[416]: Operator of unix-session:c2 FAILED to authenticate to gain authorization for action org.freedesktop.udisks2.filesystem-mount for system-bus-name::1.258 [kdeinit4: kded4 [ | Why do I have to insert USB storage twice to mount it? | arch linux;mount;usb;kde;usb drive | null |
_unix.254085 | In my ~/.i3status.confI haveorder += tztime localorder += tztime utc#...tztime local { format = %Y-%-m-%d %I:%M:%S}tztime utc { format = %H:%M:%S}but my status bar shows the same time: right now it's 7:56 and both times are 7:56.I've tried changing utc to several different things to no avail. Even tztime berlin, as shown in the documentation. At first other options would make the time disappear, but then I realized it was looking for a matching tztime <zone> { ... } declaration. None of the other zones seemed to have any effect.How do I get i3status to show UTC time? | How do I show UTC time in the i3status bar? | timestamps;timezone;i3 | As it turns out, I just needed to read the documentation a little closer:tztime berlin { format = %Y-%m-%d %H:%M:%S %Z timezone = Europe/Berlin}All I needed to do was change mine to:tztime utc { format = %I:%M:%S timezone = Etc/UTC}then restart i3, and voila! Now it's so much easier to use UTC. |
_unix.385436 | In the CentOS6, we can easily config a ip range(such as:192.168.1.10-192.168.1.254) to a NIC,but how can we config a ip range in the CentOS7?I can not use the method in the CentOS6, how to do with in CentOS7?I can use below method to configure multi ip, but if I have 200 ip, how to do with that?TYPE=EthernetBOOTPROTO=noneDEFROUTE=yesIPV4_FAILURE_FATAL=noIPV6INIT=yesIPV6_AUTOCONF=yesIPV6_DEFROUTE=yesIPV6_FAILURE_FATAL=noNAME=enp0s3UUID=933cdc9b-b383-4ddd-b219-5a72c69c9cf0ONBOOT=yesHWADDR=08:00:27:3F:AB:68IPADDR0=192.168.1.150IPADDR1=192.168.1.151IPADDR2=192.168.1.152PREFIX0=24GATEWAY0=192.168.1.1DNS1=192.168.1.1IPV6_PEERDNS=yesIPV6_PEERROUTES=yes | How can I configure a ip range in CentOS7? | centos | You can not set the ip range like CentOS6, in CentOS7 you can write script to archive that:for I in {5..250}> do nmcli con mod eth33554960 -ipv4.addresses 192.168.1.${I}/24> nmcli con mod eth33554960 +ipv4.addresses 192.168.1.${I}/24> done |
_cstheory.21155 | Recently there have been some new results on computer-based experimental study of the Erdos Discrepancy Problem (EDP) (via SAT solvers, cited below). This problem has been cited and studied by several (T)CS researchers. However the (possibly deep?) links to (T)CS are not so obvious.What are the link(s) of the EDP to (T)CS?Here are some references that show interest of the (T)CS community in EDP:SAT attack on EDP by Konev and Lisitsa, and reaction by Gowers; also, other connections to empirical/experimental TCS (e.g. SAT automated theorem proofs)Intro to EDP and techniques on Lipton's blogEDP and Differential Privacy on the Windows on Theory blog, by TalwarEDP polymath project, with some contributions by computer scientists | Connections between the Erdos Discrepancy Problem and (Theoretical) CS? | reference request;co.combinatorics;soft question;big picture | There are many links between discrepancy theory and computer science, and Bernard Chazelle has beautifully surveyed some of them in his book. A number of links have been found more recently as well, for example Kunal's blog post talks about the connection to differential privacy from [MN] and [NTZ]. Another example is Larsen's idea of using discrepancy to prove update/query time lower bounds for dynamic data structures. Many of these links can be instantiated with homogeneous arithmetic progressions (HAPs). This would give:upper bounds on the $\varepsilon$-samples for range spaces of HAPslower bounds on time required to update/query a dynamic data structure for HAP range countinglower and upper bounds on the error required to privately answer HAP queriesHowever, there two things that you must realize with respect to these links. One is that it is not clear that range spaces of HAPs are very natural. When do you expect to have input that is a multiset of integers and want to answer how many elements of a HAP are in the input? I cannot think of a situation when this comes up, but maybe I am missing something. Another thing that you must realize is that all these applications rely on the notion of hereditary discrepancy. This notion is more robust than discrepancy which makes it more tractable: there are stronger lower bounds available for it, it is approximable to within polylogarithmic factors, and it is approximately equal to the value of a convex optimization problem. The result Kunal talks about in the blog post (paper is here) and the construction by Alon and Kalai that Kalai wrote about in this blog post together essentially settle the hereditary discrepancy of HAPs. As Kunal explains, intuition for the lower bound on the hereditary discrepancy of HAPs came from the tight connection between hereditary discrepancy and differential privacy, together with prior results in differential privacy.However EDP is about the discrepancy of HAPs. Discrepancy is much more brittle than hereditary discrepancy, and that makes it harder to lower bound. This also makes it less useful in applications than hereditary discrepapncy. And this is why EDP is still wide open while the hereditary discrepancy question is fairly well understood. Let me finish with one approach to attack EDP that is inspired by computer science ideas. There is a way to relax discrepancy to a semidefinite program, see the survey by Bansal for details. The optimal value of the semidefinite program is lower bounded by the value of any feasible solution to its dual program. So one can attempt to prove EDP by exhibiting a family of dual solutions to this semidefinite relaxation of discrepancy, and showing that the value of the dual solutions goes to infinity. I see no reason why such an attack cannot work, in particular we do not know how to construct solutions to the semidefinite relaxation that have constant value for arbitrarily large instances. In fact a lot of the effort in polymath5 was centered around finding or ruling out dual solutions with particular structure. The discrepancy of arbitrary arithmetic progressions is $\Theta(n^{1/4})$ in the worse case: the lower bound is known as Roth's 1/4 Theorem. Lovasz gives a proof of the theorem using semidefinite programming (although by arguing directly about the primal rather than by constructing dual solutions). For the proof, see Section 5.2. of his SDP survey. |
_unix.75046 | when specifying ls --directory a* it should list only directories starting with a*BUT it lists files AND directories starting with aQuestions:where might I find some documentation on this, other than man and info where I think I thoroughly looked?does this work in BASH only? | why does ls -d also list files, and where is it documented? | bash;shell;ls;wildcards;options | The a* and *a* syntax is implemented by the shell, not by the ls command.When you typels a*at your shell prompt, the shell expands a* to a list of existing all files in the current directory whose names start with a. For example, it might expand a* to the sequence a1 a2 a3, and pass those as arguments to ls. The ls command itself never sees the * character; it only sees the three arguments a1, a2, and a3.For purposes of wildcard expansion, files refers to all entities in the current directory. For example, a1 might be a normal file, a2 might be a directory, and a3 might be a symlink. They all have directory entries, and the shell's wildcard expansion doesn't care what kind of entity those entries refer to.Practically all shells you're likely to run across (bash, sh, ksh, zsh, csh, tcsh, ...) implement wildcards. The details may vary, but the basic syntax of * matching zero or more characters and ? matching any single character is reasonably consistent.For bash in particular, this is documented in the Filename expansion section of the bash manual; run info bash and search for Filename expansion, or see here.The fact that this is done by the shell, and not by individual commands, has some interesting (and sometimes surprising) consequences. The best thing about it is that wildcard handling is consistent for (very nearly) all commands; if the shell didn't do this, inevitably some commands wouldn't bother, and others would do it in subtly different ways that the author thought was better. (I think the Windows command shell has this problem, but I'm not familiar enough with it to comment further.)On the other hand, it's difficult to write a command to rename multiple files. If you write:mv *.log *.log.bakit will probably fail, since*.log.bak is expanded based on the files that already exist in the current directory. There are commands that do this kind of thing, but they have to use their own syntax to specify how the files are to be renamed. Some commands (such as find) can do their own wildcard expansion; you have to quote the arguments to suppress the shell's expansion:find . -name '*.txt' -printThe shell's wildcard expansion is based entirely on the syntax of the command-line argument and the set of existing files. It can't be affected by the meaning of the command. For example, if you want to move all .log files up to the parent directory, you can type:mv *.log ..If you forget the .. :mv *.logand there happen to be exactly two .log files in the current directory, it will expand to:mv one.log two.logwhich will rename one.log and clobber two.log.EDIT: And after 52 upvotes, an accept, and a Guru badge, maybe I should actually answer the question in the title.The -d or --directory option to ls doesn't tell it to list only directories. It tells it to list directories just as themselves, not their contents. If you give a directory name as an argument to ls, by default it will list the contents of the directory, since that's usually what you're interested in. The -d option tells it to list just the directory itself. This can be particularly useful when combined with wildcards. If you type:ls -l a*ls will give you a long listing of each file whose name starts with a, and of the contents of each directory whose name starts with a. If you just want a list of the files and directories, one line for each, you can use:ls -ld a*which is equivalent to:ls -l -d a*Remember again that the ls command never sees the * character.As for where this is documented, man ls will show you the documentation for the ls command on just about any Unix-like system. On most Linux-based systems, the ls command is part of the GNU coreutils package; if you have the info command, either info ls or info coreutils ls should give you more definitive and comprehensive documentation. Other systems, such as MacOS, may use different versions of the ls command, and may not have the info command; for those systems, use man ls. And ls --help will show a relatively short usage message (117 lines on my system) if you're using the GNU coreutils implementation.And yes, even experts need to consult the documentation now and then. See also this classic joke. |
_unix.285546 | So basically from what I found out from amixer, every time I press fn and the arrows of the keyboard to change the volume, the % of volume changing is 6%. I would like to make that 1%. How can this be done? | Change volume % that changes every time I decrease it from keyboard | linux;fedora;alsa;volume | null |
_unix.109122 | Just upgraded from Debian Squeezy to Wheezy. When I logged in the menus were fancier as I expected with Gnome Display Manager 3.However the issue that occurred was the duplicate UI-elements. The UI-elements such as Applications, Places, the Clock and so forth had two instances each. What I've tried so far:Though it had something to do with me having a two monitor setup so Iran nvidia-settings and reconfigured /etc/X11/xorg.conf.However as I rebooted the UI elements had increased and now therewere three instances. I think this number increases with each reboot...Tried to manually rewrite the xorg.conf by saving in my home folderand then pushing it into `/etc/X11/xorg.confRenaming ~/.gnome2 to ~/gnome2_backupWhy do I get the duplicate menus and is there a way to remove them/make them not appear after each reboot?My xorg.conf file:# nvidia-settings: X configuration file generated by nvidia-settings# nvidia-settings: version 304.88 (pbuilder@cake) Wed Apr 3 08:58:25 UTC 2013Section ServerLayout Identifier Layout0 Screen 0 Screen0 0 0 Screen 1 Screen1 1920 0 InputDevice Keyboard0 CoreKeyboard InputDevice Mouse0 CorePointer Option Xinerama 1EndSectionSection FilesEndSectionSection InputDevice # generated from default Identifier Mouse0 Driver mouse Option Protocol auto Option Device /dev/psaux Option Emulate3Buttons no Option ZAxisMapping 4 5EndSectionSection InputDevice # generated from default Identifier Keyboard0 Driver kbdEndSectionSection Monitor # HorizSync source: edid, VertRefresh source: edid Identifier Monitor0 VendorName Unknown ModelName DELL S2740L HorizSync 30.0 - 83.0 VertRefresh 56.0 - 76.0 Option DPMSEndSectionSection Monitor # HorizSync source: edid, VertRefresh source: edid Identifier Monitor1 VendorName Unknown ModelName Samsung SMBX2440 HorizSync 30.0 - 81.0 VertRefresh 56.0 - 75.0 Option DPMSEndSectionSection Device Identifier Device0 Driver nvidia VendorName NVIDIA Corporation BoardName GeForce GT 430 BusID PCI:1:0:0 Screen 0EndSectionSection Device Identifier Device1 Driver nvidia VendorName NVIDIA Corporation BoardName GeForce GT 430 BusID PCI:1:0:0 Screen 1EndSectionSection Screen Identifier Screen0 Device Device0 Monitor Monitor0 DefaultDepth 24 Option Stereo 0 Option metamodes DFP: nvidia-auto-select +0+0 SubSection Display Depth 24 EndSubSectionEndSectionSection Screen Identifier Screen1 Device Device1 Monitor Monitor1 DefaultDepth 24 Option Stereo 0 Option nvidiaXineramaInfoOrder CRT-1 Option metamodes CRT: nvidia-auto-select +0+0 SubSection Display Depth 24 EndSubSectionEndSectionSection Extensions Option Composite DisableEndSection | Gnome 3 UI menus are duplicated | debian;xorg;gnome3;gui;display manager | It was some spooky settings or cached data from Gnome 2 that was messing with the interface. I saved the important files to an external drive and emptied the home folder, (including .*-files). |
_webmaster.66908 | I am using Galleria.io on a website to display a gallery of images. In the database, the images have a title and description to properly explain what the image is.I load the images into galleria using dataSource and a Json array. The gallery works fine and shows the title and description in the gallery however no keyword analyzer picks up the content of the title and description as the images are loaded at run time.What would be the best way of making the title and description available for a search engine to crawl while associating it to the appropriate images? | How to SEO optimise Ajax/Json loaded images? | javascript;ajax;seo | null |
_codereview.67785 | I have to refactor this method: it seems to duplicate two code blocks with some slight variation. Any suggestions? It is a bit of a mess :)public EstimatedAttitude estimate(int numStars, Double2d starsBrf, Double2d starsMeq, Long1d starsIdsForRange, double measerrRef, double probThresh) { Double2d starsBrfTry = new Double2d(9, 3); Double2d starsMeqTry = new Double2d(9, 3); Int1d idBad = new Int1d(2); int numBad = 0; //Estimate the attitude using q-method QMethodValues estimates = QMethod.compute(numStars, starsBrf, starsMeq, measerrRef); //double loss = estimates.getLoss(); //Quaternion quat = estimates.getQuat(); //Calculate probability of getting such a large value of TASTE at random double taste = estimates.getTaste(); double gammaP = new GammaP(0.5 * (2 * numStars - 3)).calc(0.5 * taste); double prob = 1.0 - gammaP; //If no error and a bad fit if ((estimates.isValid()) && (prob < probThresh)) { double bestTaste = taste; //Try each star as a candidate bad star for (int badCand = 0; badCand < numStars; badCand++) { //Exclude candidate bad star int loop = 0; for (int star = 0; star < numStars; star++) { if (star != badCand) { starsBrfTry.set(loop, starsBrf.get(star)); starsMeqTry.set(loop, starsMeq.get(star)); loop = loop + 1; } } //Estimate attitude without candidate bad star QMethodValues estimatesTry = QMethod.compute(numStars - 1, starsBrfTry, starsMeqTry, measerrRef); double tasteTry = estimatesTry.getTaste(); //Calculate probability of getting such a large value of TASTE at random double gammaPTry = new GammaP(0.5 * (2 * numStars - 5)).calc(0.5 * tasteTry); double probTry = 1.0 - gammaPTry; //If no error and we have found an acceptable value of taste that is better than //the best so far if ((estimatesTry.isValid()) && (probTry >= probThresh) && (tasteTry < bestTaste)) { //Make a note of the details numBad = 1; idBad.set(0, ((Long ) starsIdsForRange.get(badCand)).intValue()); /*quat = estimatesTry.getQuat(); loss = estimatesTry.getLoss(); taste = tasteTry;*/ estimates = estimatesTry; prob = probTry; } } } //If still no error and a bad fit if ((estimates.isValid()) && (prob < probThresh)) { //Initialize best value of taste double bestTaste = taste; //Try each pair of stars as a candidate bad star pair //bad_cand_1 \in {0, 1,..., num_stars - 2} for (int badCand_1 = 0; badCand_1 < numStars - 1; badCand_1++) { //bad_cand_2 \in {bad_cand_1 + 1, bad_cand_1 + 2,..., num_stars - 1} for (int loop_2 = 0; loop_2 < numStars - 1 - badCand_1; loop_2++) { int bad_cand_2 = loop_2 + badCand_1 + 1; //Exclude candidate bad star pair int loop = 0; for (int star = 0; star < numStars; star++) { if ((star != badCand_1) && (star != bad_cand_2)) { starsBrfTry.set(loop, starsBrf.get(star)); starsMeqTry.set(loop, starsMeq.get(star)); loop = loop + 1; } } //Estimate attitude without candidate bad star QMethodValues estimatesTry = QMethod.compute(numStars - 2, starsBrfTry, starsMeqTry, measerrRef); double tasteTry = estimatesTry.getTaste(); //Calculate probability of getting such a large value of TASTE at random double gammaPTry = new GammaP(0.5 * (2 * numStars - 7)).calc(0.5 * tasteTry); double probTry = 1.0 - gammaPTry; //If no error and we have found an acceptable value of taste that is better than //the best so far if ((estimatesTry.isValid()) && (probTry >= probThresh) && (tasteTry < bestTaste)) { //Make a note of the details numBad = 2; idBad.set(0, ((Long ) starsIdsForRange.get(badCand_1)).intValue()); idBad.set(1, ((Long ) starsIdsForRange.get(bad_cand_2)).intValue()); /*quat = estimatesTry.getQuat(); loss = estimatesTry.getLoss(); taste = tasteTry;*/ estimates = estimatesTry; prob = probTry; } } } } //create a new qmethod value with correct fields return new EstimatedAttitude(estimates, prob, numBad, idBad);} | Refactoring a method for estimation | java | null |
_codereview.86125 | The program should read equations from stdin, parse them and generate a matrix of the coefficient which represents the system.Example:$ ./eqsx + y = 4-y + 4x = 2 1 1 4 4 -1 2As you can see, the user can input as many equations they want and the program stops reading when an empty line is sent.#include <stdio.h>#include <stdlib.h>#include <string.h>#include <ctype.h>#define _M(i, j) (M->elements[(i) * M->cols + (j)])#define ROWS 10#define CHUNK 32typedef struct { size_t rows; size_t cols; double *elements;} Matrix;void print_matrix(Matrix *);Matrix *parse_input();Matrix *create_matrix(size_t, size_t);void free_matrix(Matrix *);int readline(char **, size_t *, FILE *);void memory_error(void);int main(void) { Matrix *M = parse_input(); print_matrix(M); free_matrix(M); return 0;}void print_matrix(Matrix *M) { size_t i, j; for (i = 0; i < M->rows; i++) { for (j = 0; j < M->cols; j++) { printf(%3g , _M(i, j)); } printf(\n); } printf(\n);}Matrix *parse_input() { char *row; size_t reading_size = CHUNK; if (!(row = malloc(reading_size))) memory_error(); double coeff; size_t i, j, k, numrows = ROWS; double **unknowns; if (!(unknowns = malloc(numrows * sizeof(*unknowns)))) { free(row); memory_error(); } for (i = 0 ; i < numrows; i++) { if (!(unknowns[i] = calloc(27, sizeof(**unknowns)))) { free(unknowns); memory_error(); } } i = 0; do { if (i == numrows) { numrows *= 2; for (j = i + 1; j < numrows; j++) { if (!(unknowns[j] = calloc(27, sizeof(**unknowns)))) { free(unknowns); memory_error(); } } } readline(&row, &reading_size, stdin); char *p = row; unsigned char past_equal = 0; coeff = 1; while (*p) { if (*p == '-') { coeff *= -1; p++; } else if (*p == '=') { past_equal = 1; p++; } else if (isdigit(*p)) { double val = strtod(p, &p); if (!past_equal) coeff *= val; else { unknowns[i][26] = val; break; } } else if (isalpha(*p)) { unknowns[i][tolower(*p++) - 'a'] = coeff; coeff = 1; } else p++; } i++; } while (row[0] != '\0'); free(row); i--; unsigned short int nonzero_unknowns[27] = {0}; nonzero_unknowns[26] = 1; for (j = 0; j < i; j++) { for (k = 0; k < 26; k++) { if (unknowns[j][k]) nonzero_unknowns[k] = 1; } } size_t ncols = 0; unsigned short int positions[26]; for (j = 0; j < 26; j++) { if (nonzero_unknowns[j]) { positions[ncols++] = j; } } ncols++; if (i + 1 < ncols) { for (j = 0; j < i; j++) { free(unknowns[j]); } free(unknowns); puts(The system is underdetermined.); exit(EXIT_SUCCESS); } Matrix *M = create_matrix(i, ncols); for (j = 0; j < i; j++) { for (k = 0; k + 1 < ncols; k++) { _M(j, k) = unknowns[j][positions[k]]; } _M(j, k) = unknowns[j][26]; } for (j = 0; j < i; j++) { free(unknowns[j]); } free(unknowns); return M;}Matrix *create_matrix(size_t rows, size_t cols) { Matrix *M; if (!(M = malloc(sizeof *M))) memory_error(); M->rows = rows; M->cols = cols; if (!(M->elements = calloc(rows * cols, sizeof(double)))) { free(M); memory_error(); } return M;}void free_matrix(Matrix *M) { free(M->elements); free(M);}int readline(char **input, size_t *size, FILE *file) { char *offset; char *p; size_t old_size; // Already at the end of file if (!fgets(*input, *size, file)) { return EOF; } // Check if input already contains a newline if ((p = strchr(*input, '\n'))) { *p = 0; return 0; } do { old_size = *size; *size *= 2; if (!(*input = realloc(*input, *size))) { free(*input); memory_error(); } offset = &((*input)[old_size - 1]); } while (fgets(offset, old_size + 1, file) && offset[strlen(offset) - 1] != '\n'); return 0;}void memory_error(void) { puts(Could not allocate memory.); exit(EXIT_FAILURE);}The parsing function is far too large, and it's quite complicated. Here's how the parsing is done:a line is read;the coefficients are put into the unknowns double array, which is 27 doubles wide to hold the 26 coefficients for the lowercase letters and the free term on the RHS of the equation;since an equation may not contain all the coefficients (some of them can be zero), the nonzero_unknowns holds the count;the matrix is initialized and returned.I think the parse_input() function can definitely be broken up into multiple pieces, but I'm having a hard time simplifying it. | Parsing equations from stdin | c;parsing;matrix;mathematics;math expression eval | Here are some things that may help you improve your code.Consider using parser generator toolsIf I were writing code like this, I would use flex and bison (or equivalently lex and yacc). There are many resources available for these tools. Here is one such resource.Eliminate magic numbersInstead of hard-coding the constants 26 and 27 in the code, it would be better to use a #define or const and name them.Fix memory leaksIn the case that there is, say, a single line as input, the program leaks memory. This is because the unknowns[i] or unknowns[j] allocates more than enough space, but the loop at the bottom of parse_input only frees i rows. Better would be to use a separate variable to track the actual number of allocated unknowns and then use that to drive the loop that frees them.Don't bother allocating more memory than neededThere is no benefit to allocating more unknowns than needed. You could simply add them one at a time as needed, since you're allocating them one at a time in a loop anyway. Just make sure to keep track of the number of allocations so that you can correctly free the memory later.Consider using streamlining error handlingMuch of the code does error checking for malloc and then handles the result by freeing memory and then calling memory_error() which calls exit(). This is all good practice -- you are well ahead of the pack by actually carefully checking to make sure that the memory allocation suceeeded. That's great, and I would encourage you to continue this excellent habit. However, it clutters up the code quite a bit. An alternative approach would be to create a wrapper function for malloc and calloc that would enter the address into a flexible data structure. Then you could have a corresponding free_all that would free all allocated memory that could be called either in main or in memory_error. This could be done automatically if you register the function with atexit().Break apart the parse_input functionYour description of the parse_input function points the way to how you might break apart the overly-long parse_input function. You could have one function that would create and return the unknowns structure. Then another to parse those into the matrix. Minimize redundant loopsThe nonzero_unknowns array could actually instead be the first row of the unknowns array. That way, you would reduce the number of variables (there are a lot!) and would be able to tally the unknown count as the parsing is done, making things much more efficient.Consider handling malformed input linesIf the user types the line x - 4 = y the program incorrectly parses this as 1 -4 0. Another problem occurs if the user types in x - x = 0. It would be better, I think, to issue a warning to the user or, if you can, perform the algebra to correctly interpret the equation.Eliminate return 0 at the end of mainFor a long time now, the C language says that finishing main will implicitly generate the equivalent to return 0. For that reason, you should eliminate that line from your code. |
_webapps.14637 | There were a number of sites out there that did this via Yahoo Pipes - such as noRepliesNow that it appears that Yahoo Pipes is banned from accessing Twitter data, are there any other options?I'd like to be able to link to my Twitter feed without @ replies - both as a clickable link, and ideally an RSS feed | View Twitter feed without seeing @ replies? | twitter;yahoo pipes | null |
_unix.365124 | I have a program that is parallelized using MPI. It thinks that it is able to run across multiple nodes on our (CentOS 6.6)-based HPC grid, when in actual fact it only runs successfully on multiple cores of the same compute node. e.g. If I qsub a job to the grid asking for 20 cores, and Grid Engine decides to split it over two different nodes, the program fails. However, if there is a node with 20 cores available, and Grid Engine sends it all to that one, the program runs successfully. The qsub script contains the command #$ -pe mpi 20 to select the number of cores. So at the moment, I do a qstat -f -u * to manually identify a compute node with 20 available cores, and submit to that node with qsub -q general.q@node-X-XWhat I am looking for is a way to tell Grid Engine to wait and only submit the job to a single compute node that has the required number of available cores. This will allow me to automate my job submission. I am considering writing a bash script to parse the qstat -f -u * command, but there must be a more elegant solution. I have looked through the qsub manual but am unable to find a suitable flag or command line argument. I'm not able to modify the program itself at this time. Here is some information on the different software versions I have available:MPI/gridengine info:> ompi_info | grep gridengineMCA ras: gridengine (MCA v2.0, API v2.0, Component v1.6.2)Grid engine version is: OGS/GE 2011.11p1 | Qsub to any node with more than n cores available | gridengine | null |
_codereview.126352 | I have started learning Java and was trying to solve some easy problems from different websites like HackerRank and leetcode.I am relatively new to programming so please don't mind if this is too naive. I found a problem in LeetCode to rotate array.The problem can be found here I have implemented the solution using two different methods:The first method(my initial solution) rotateArray1 is very straightforward where we divide the array into two parts and then copy the elements back into the main array.I found the logic for the second method in programcreek which says : 1. Divide the array two parts: 1,2,3,4 and 5, 6 2. Reverse first part: 4,3,2,1,5,6 3. Reverse second part: 4,3,2,1,6,5 4. Reverse the whole array: 5,6,1,2,3,4This is my solution where I implemented both the methods.I am trying to get better at writing good code for my solutions. Please give me your suggestions and also can anyone please tell me which one of these two methods is more efficiant in terms of time complexity. import java.util.Scanner;/*Problem: Rotate an array of n elements to the right by k steps. For example, with n = 7 and k = 3, the array [1,2,3,4,5,6,7] is rotated to [5,6,7,1,2,3,4]. */public class RoatateArray { public static Scanner Keyboard = new Scanner(System.in); public static void main(String[] args) { int size = Keyboard.nextInt(); int[] array = new int[size]; fillArray(array); System.out.println(Array before rotation is :); printArray(array); System.out .println(\nEnter the number of steps the array needs to be rotated); int order = Keyboard.nextInt(); if (order == array.length) { System.out .println(The order of the array will be same after rotation of + order + steps); } else { System.out .println(enter choice 1 : arrayRotate1 or choice 2 for : arrayrotate2); int choice = Keyboard.nextInt(); switch (choice) { case 1: arrayRotate1(array, order); break; case 2: arrayRotate2(array, order); break; default: break; } } } private static void arrayRotate1(int[] array, int order) { if (order > array.length) { order = order % array.length; } int[] arr1 = new int[order]; int[] arr2 = new int[array.length - order]; System.arraycopy(array, array.length - order, arr1, 0, arr1.length); System.arraycopy(array, 0, arr2, 0, arr2.length); // copy arr1 and arr2 into original array System.arraycopy(arr1, 0, array, 0, arr1.length); System.arraycopy(arr2, 0, array, arr1.length, array.length - order); printArray(array); } private static void printArray(int[] array) { for (int i = 0; i < array.length; i++) { System.out.print(array[i] + ); } } private static int[] fillArray(int[] array) { for (int i = 0; i < array.length; i++) { array[i] = Keyboard.nextInt(); } return array; } private static void arrayRotate2(int[] array, int order) { if (order > array.length) { order = order % array.length; } // get the length of the first part int a = array.length - order; reverse(array, 0, a - 1); reverse(array, a, array.length - 1); reverse(array, 0, array.length - 1); printArray(array); } private static void reverse(int[] array, int left, int right) { while (left < right) { int temp = array[left]; array[left] = array[right]; array[right] = temp; left++; right--; } }} | LeetCode Rotate Array | java;programming challenge;array | If you use ArrayList instead of int[] you can write rotate2 like this (it's less efficient): public static List<Integer> rotate2(List<Integer> numsList, int k) { k = k % numsList.size(); List<Integer> firstPart = numsList.subList(0, numsList.size() - k); List<Integer> secondPart = numsList.subList(numsList.size() - k, numsList.size()); Collections.reverse(firstPart); Collections.reverse(secondPart); ArrayList<Integer> rotated = new ArrayList<>(); rotated.addAll(firstPart); rotated.addAll(secondPart); return rotated; }The arrayRotate1 can also be written this way, I don't know whether it's more readable or not but it's definitely less efficient: public static void rotate(int[] nums, int k) { k = k % nums.length; Queue<Integer> queue = new ArrayDeque<>(k); for (int i = 0; i < Math.min(k, nums.length); i++) queue.add(nums[i]); for (int i = 0; i < nums.length; i++) { int index = (i + k) % nums.length; queue.add(nums[index]); nums[index] = queue.remove(); } } |
_cstheory.34503 | Given two lists $L,L'\subseteq\mathbb{R}^d$ of $n$ vectors each, how fast can we compute for all $p\in L$ the vector of $L'$ that maximizes the inner product with $p$, i.e., $\arg\max_{p'\in L'} \langle p, p'\rangle$.I am only interested in $d=3$ (and possibly $d=4$). | maximizing inner product | ds.data structures;time complexity;computational geometry;convex hull | For three-dimensional vectors, construct the three-dimensional convex hull of the vectors in $L'$ in time $O(n\log n)$. The maximizer for a vector $v$ in $L$ is the point of the convex hull that is most extreme in the direction of $v$, and extreme-vertex queries may be answered in logarithmic time by using a Dobkin-Kirkpatrick hierarchy for the convex hull. For this part see e.g. O'Rourke's Computational Geometry in C, pp. 272ff. So the 3d problem can be solved in total time $O(n\log n)$.For 4-dimensional vectors, the same thing would work, but you don't want to construct the convex hull because it's too expensive. Instead, it is possible to process a set of $n$ points in time and space $\tilde O(m)$ (for any $m$ between $n$ and $n^2$) so that you can answer extreme-point queries in time $\tilde O(n/\sqrt{m})$; see Corollary 8(iii) of Agarwal and Erickson's range query survey. Choosing $m=n^{4/3}$ gives total time $\tilde O(n^{4/3})$ to set up a data structure for $L'$ and query all vectors in $L$. |
_softwareengineering.95328 | When working on open source projects should one time contributor's (I mean like single or minor patchset, nothing that would be considered a major contribution ) be listed as an Author? or should they simply get listed in say an acknowledgement section somewhere? If you contribute a small patch to a project where do you want to get listed? | Should one time contributors be listed as an Author? | open source;contribution | It depends.If the single contribution ended up being half the project, then yes, of course the contributor should be listed as an author. However, that's probably not what you had in mind. It all depends on the fractional workload - how much that one person has contributed compared to everyone else. It doesn't matter if the contribution was a once-off occurrence of if they submitted multiple contributions.I wouldn't want to be treated or acknowledged any different than anyone else. If my work was seen as equal to another developer's, I would want to be where he is listed. If he isn't acknowledged at all, I wouldn't want to be either. |
_codereview.75557 | I just finished Project Euler #13 in Swift, and since there is not any version yet on Code Review, I would like to have some comments on what I did to try to improve it.Work out the first ten digits of the sum of the following one-hundred 50-digit numbers.37107287533902102798797998220837590246510135740250 46376937677490009712648124896970078050417018260538 74324986199524741059474233309513058123726617309629 91942213363574161572522430563301811072406154908250 23067588207539346171171980310421047513778063246676 89261670696623633820136378418383684178734361726757 28112879812849979408065481931592621691275889832738 44274228917432520321923589422876796487670272189318 47451445736001306439091167216856844588711603153276 70386486105843025439939619828917593665686757934951 62176457141856560629502157223196586755079324193331 64906352462741904929101432445813822663347944758178 92575867718337217661963751590579239728245598838407 58203565325359399008402633568948830189458628227828 80181199384826282014278194139940567587151170094390 35398664372827112653829987240784473053190104293586 86515506006295864861532075273371959191420517255829 71693888707715466499115593487603532921714970056938 54370070576826684624621495650076471787294438377604 53282654108756828443191190634694037855217779295145 36123272525000296071075082563815656710885258350721 45876576172410976447339110607218265236877223636045 17423706905851860660448207621209813287860733969412 81142660418086830619328460811191061556940512689692 51934325451728388641918047049293215058642563049483 62467221648435076201727918039944693004732956340691 15732444386908125794514089057706229429197107928209 55037687525678773091862540744969844508330393682126 18336384825330154686196124348767681297534375946515 80386287592878490201521685554828717201219257766954 78182833757993103614740356856449095527097864797581 16726320100436897842553539920931837441497806860984 48403098129077791799088218795327364475675590848030 87086987551392711854517078544161852424320693150332 59959406895756536782107074926966537676326235447210 69793950679652694742597709739166693763042633987085 41052684708299085211399427365734116182760315001271 65378607361501080857009149939512557028198746004375 35829035317434717326932123578154982629742552737307 94953759765105305946966067683156574377167401875275 88902802571733229619176668713819931811048770190271 25267680276078003013678680992525463401061632866526 36270218540497705585629946580636237993140746255962 24074486908231174977792365466257246923322810917141 91430288197103288597806669760892938638285025333403 34413065578016127815921815005561868836468420090470 23053081172816430487623791969842487255036638784583 11487696932154902810424020138335124462181441773470 63783299490636259666498587618221225225512486764533 67720186971698544312419572409913959008952310058822 95548255300263520781532296796249481641953868218774 76085327132285723110424803456124867697064507995236 37774242535411291684276865538926205024910326572967 23701913275725675285653248258265463092207058596522 29798860272258331913126375147341994889534765745501 18495701454879288984856827726077713721403798879715 38298203783031473527721580348144513491373226651381 34829543829199918180278916522431027392251122869539 40957953066405232632538044100059654939159879593635 29746152185502371307642255121183693803580388584903 41698116222072977186158236678424689157993532961922 62467957194401269043877107275048102390895523597457 23189706772547915061505504953922979530901129967519 86188088225875314529584099251203829009407770775672 11306739708304724483816533873502340845647058077308 82959174767140363198008187129011875491310547126581 97623331044818386269515456334926366572897563400500 42846280183517070527831839425882145521227251250327 55121603546981200581762165212827652751691296897789 32238195734329339946437501907836945765883352399886 75506164965184775180738168837861091527357929701337 62177842752192623401942399639168044983993173312731 32924185707147349566916674687634660915035914677504 99518671430235219628894890102423325116913619626622 73267460800591547471830798392868535206946944540724 76841822524674417161514036427982273348055556214818 97142617910342598647204516893989422179826088076852 87783646182799346313767754307809363333018982642090 10848802521674670883215120185883543223812876952786 71329612474782464538636993009049310363619763878039 62184073572399794223406235393808339651327408011116 66627891981488087797941876876144230030984490851411 60661826293682836764744779239180335110989069790714 85786944089552990653640447425576083659976645795096 66024396409905389607120198219976047599490197230297 64913982680032973156037120041377903785566085089252 16730939319872750275468906903707539413042652315011 94809377245048795150954100921645863754710598436791 78639167021187492431995700641917969777599028300699 15368713711936614952811305876380278410754449733078 40789923115535562561142322423255033685442488917353 44889911501440648020369068063960672322193204149535 41503128880339536053299340368006977710650566631954 81234880673210146739058568557934581403627822703280 82616570773948327592232845941706525094512325230608 22918802058777319719839450180888072429661980811197 77158542502016545090413245809786882778948721859617 72107838435069186155435662884062257473692284509516 20849603980134001723930671666823555245252804609722 53503534226472524250874054075591789781264330331690import Foundationfunc addToResult(inout results:[Int], var addResult:Int, index:Int) { if index == results.count { results.append(0) } addResult = results[index] + addResult var result = addResult % 10 results[index] = result var retain = addResult / 10 if retain > 0 { addToResult(&results, retain, index + 1) }}func add(left:String, right:String) -> String { let leftNumbers:[Int] = Array(left).reverse().map() { String($0).toInt()! } let rightNumbers:[Int] = Array(right).reverse().map() { String($0).toInt()! } var results:[Int] = [Int]() var index = max(leftNumbers.count, rightNumbers.count) var i = 0 while i < index { let leftNumber = i >= leftNumbers.count ? 0 : leftNumbers[i] let rightNumber = i >= rightNumbers.count ? 0 : rightNumbers[i] let addResult = leftNumber + rightNumber addToResult(&results, addResult, i) i++ } return .join(results.reverse().map() { String($0) } )}func largeSum(numbers:[String]) -> String { var result = for number in numbers { result = add(result, number) } return result}func euler13() { let numbers = [ 37107287533902102798797998220837590246510135740250, 46376937677490009712648124896970078050417018260538, 74324986199524741059474233309513058123726617309629, 91942213363574161572522430563301811072406154908250, 23067588207539346171171980310421047513778063246676, 89261670696623633820136378418383684178734361726757, 28112879812849979408065481931592621691275889832738, 44274228917432520321923589422876796487670272189318, 47451445736001306439091167216856844588711603153276, 70386486105843025439939619828917593665686757934951, 62176457141856560629502157223196586755079324193331, 64906352462741904929101432445813822663347944758178, 92575867718337217661963751590579239728245598838407, 58203565325359399008402633568948830189458628227828, 80181199384826282014278194139940567587151170094390, 35398664372827112653829987240784473053190104293586, 86515506006295864861532075273371959191420517255829, 71693888707715466499115593487603532921714970056938, 54370070576826684624621495650076471787294438377604, 53282654108756828443191190634694037855217779295145, 36123272525000296071075082563815656710885258350721, 45876576172410976447339110607218265236877223636045, 17423706905851860660448207621209813287860733969412, 81142660418086830619328460811191061556940512689692, 51934325451728388641918047049293215058642563049483, 62467221648435076201727918039944693004732956340691, 15732444386908125794514089057706229429197107928209, 55037687525678773091862540744969844508330393682126, 18336384825330154686196124348767681297534375946515, 80386287592878490201521685554828717201219257766954, 78182833757993103614740356856449095527097864797581, 16726320100436897842553539920931837441497806860984, 48403098129077791799088218795327364475675590848030, 87086987551392711854517078544161852424320693150332, 59959406895756536782107074926966537676326235447210, 69793950679652694742597709739166693763042633987085, 41052684708299085211399427365734116182760315001271, 65378607361501080857009149939512557028198746004375, 35829035317434717326932123578154982629742552737307, 94953759765105305946966067683156574377167401875275, 88902802571733229619176668713819931811048770190271, 25267680276078003013678680992525463401061632866526, 36270218540497705585629946580636237993140746255962, 24074486908231174977792365466257246923322810917141, 91430288197103288597806669760892938638285025333403, 34413065578016127815921815005561868836468420090470, 23053081172816430487623791969842487255036638784583, 11487696932154902810424020138335124462181441773470, 63783299490636259666498587618221225225512486764533, 67720186971698544312419572409913959008952310058822, 95548255300263520781532296796249481641953868218774, 76085327132285723110424803456124867697064507995236, 37774242535411291684276865538926205024910326572967, 23701913275725675285653248258265463092207058596522, 29798860272258331913126375147341994889534765745501, 18495701454879288984856827726077713721403798879715, 38298203783031473527721580348144513491373226651381, 34829543829199918180278916522431027392251122869539, 40957953066405232632538044100059654939159879593635, 29746152185502371307642255121183693803580388584903, 41698116222072977186158236678424689157993532961922, 62467957194401269043877107275048102390895523597457, 23189706772547915061505504953922979530901129967519, 86188088225875314529584099251203829009407770775672, 11306739708304724483816533873502340845647058077308, 82959174767140363198008187129011875491310547126581, 97623331044818386269515456334926366572897563400500, 42846280183517070527831839425882145521227251250327, 55121603546981200581762165212827652751691296897789, 32238195734329339946437501907836945765883352399886, 75506164965184775180738168837861091527357929701337, 62177842752192623401942399639168044983993173312731, 32924185707147349566916674687634660915035914677504, 99518671430235219628894890102423325116913619626622, 73267460800591547471830798392868535206946944540724, 76841822524674417161514036427982273348055556214818, 97142617910342598647204516893989422179826088076852, 87783646182799346313767754307809363333018982642090, 10848802521674670883215120185883543223812876952786, 71329612474782464538636993009049310363619763878039, 62184073572399794223406235393808339651327408011116, 66627891981488087797941876876144230030984490851411, 60661826293682836764744779239180335110989069790714, 85786944089552990653640447425576083659976645795096, 66024396409905389607120198219976047599490197230297, 64913982680032973156037120041377903785566085089252, 16730939319872750275468906903707539413042652315011, 94809377245048795150954100921645863754710598436791, 78639167021187492431995700641917969777599028300699, 15368713711936614952811305876380278410754449733078, 40789923115535562561142322423255033685442488917353, 44889911501440648020369068063960672322193204149535, 41503128880339536053299340368006977710650566631954, 81234880673210146739058568557934581403627822703280, 82616570773948327592232845941706525094512325230608, 22918802058777319719839450180888072429661980811197, 77158542502016545090413245809786882778948721859617, 72107838435069186155435662884062257473692284509516, 20849603980134001723930671666823555245252804609722, 53503534226472524250874054075591789781264330331690 ] let number = largeSum(numbers) println(number)}func printTimeElapsedWhenRunningCode(operation:() -> ()) { let startTime = CFAbsoluteTimeGetCurrent() operation() let timeElapsed = CFAbsoluteTimeGetCurrent() - startTime println(Time elapsed : \(timeElapsed) s)}printTimeElapsedWhenRunningCode(euler13)The code executes in 0.1sI'm not fan of the add function I did. Maybe storing the results in an [Int], was not the best choice, but I do not like the way String ranges/nTh character are handled.I did not find an elegant/performant way to have something like this :let str = 123str[3] // An Optional Int?str[2] // 3 as an Int | Project Euler #13 in Swift - Large sum | programming challenge;swift | The definition of the numbers array let numbers = [ 37107287533902102798797998220837590246510135740250, ... 53503534226472524250874054075591789781264330331690]takes a lot of space in the euler13() function and therefore distracts fromthe relevant code. I would store the original data from the Project Euler problem into a text file and load the data from there. That also helps to avoid copy/pasteerrors or other typos, e.g. when adding the quotation marks and commas.For an Xcode command-line project this is done by adding a Other->Empty file data.txt to the project and adding this file to the Copy Files build phase:Then you can copy/paste the given data into this file and load it at runtime,so that the main function becomesfunc euler13() { let path = NSBundle.mainBundle().pathForResource(data, ofType: txt)! let data = NSString(contentsOfFile: path, encoding: NSUTF8StringEncoding, error: nil)! let numbers = data.componentsSeparatedByString(\n) as [String] let number = largeSum(numbers) println(number)}Strictly speaking, your output is not correct, as the problem asks only for thefirst 10 digits of the sum. This would be done withfunc euler13() { // ... let number = largeSum(numbers) println(number[number.startIndex ..< advance(number.startIndex, 10)])}Storing the numbers in an integer array is a good choice, as working on a Swiftstring directly would most probably be much slower. But I would separatethe String <-> [Int] conversions into separate functions:func stringToIntArray(str : String) -> [Int] { return Array(str).reverse().map() { String($0).toInt()! }}func intArrayToString(num: [Int]) -> String { return .join(num.reverse().map() { String($0) } )}Your code computes the sum of two large numbers in an integer array andthen converts that array back to a string. In the next step the string isconverted to an integer array again for the next addition.It would be more effective to use only integer arrays for all intermediateresults, and convert only the final sum back to a string.Then largeSum() would look like this:func largeSum(numbers:[String]) -> String { var result : [Int] = [] for number in numbers { let num = stringToIntArray1(number) addToIntArray(&result, num) } return intArrayToString(result)}Your addToResult functions adds only a single digit to a large integer(represented as an [Int]) array. It is more effective to add two large integers in a single loop:func addToIntArray(inout result: [Int], num: [Int]) { var carry = 0 let commonLength = min(result.count, num.count) var index = 0 while index < commonLength { let sum = result[index] + num[index] + carry result[index] = sum % 10 carry = sum / 10 index++ } while index < num.count { let sum = num[index] + carry result.append(sum % 10) carry = sum / 10 index++ } while index < result.count && carry > 0 { let sum = result[index] + carry result[index] = sum % 10 carry = sum / 10 index++ } if carry > 0 { result.append(carry) }}On my computer, these changes reduced the time from 0.032 to 0.017 seconds.Now profiling showed that much of the time is spent in the stringToIntArray()function. The following version is significantly faster:func stringToIntArray(str : String) -> [Int] { var num : [Int] = [] let unicodeDigitZero = 48 for digit in str.unicodeScalars { num.append(Int(digit.value) - unicodeDigitZero) } return reverse(num)}The computation time is now 0.006 seconds.Ideas for further possible improvements:Store more than one decimal digit in each element of the [Int] array.This would make the addition faster, but the string to array conversion more complicated.Cheat. The problem asks only for the first 10 digits of the sum.That means that only a initial portion of the given numbers is actually needed. |
_unix.284420 | I have more schroots but there are a base part which is the same in the all schroot configs (like users, type, etc.).Can be this base file used/sourced in a schroot config file to avoid copying? | Can be any variable used in a schroot config? | schroot | null |
_codereview.93336 | I am working on uploading files through Rest API. Tried my hand using single upload and works. I have modified to accommodate parallel uploads using Futures. Will there be any chance that this code will not end during the equivalent infinite loop in checking futures's status?Another question that I have here is that the response does not return any more information about the files. I do not have control over how the server returns. How can I name a more detailed exception during response handling:'File upload failed for file xxx! Status code, error message'instead of the below?private void fileUpload(String localFolderPath, String uploadFolderPath) throws ClientProtocolException, IOException, ParserConfigurationException, SAXException { File folder = new File(localFolderPath); String url = baseUrl + /fileUpload; FutureRequestExecutionService requestExecService = null; ExecutorService execService = Executors.newFixedThreadPool(NTHREDS); try { HttpClient httpclient = HttpClientBuilder.create().setMaxConnPerRoute(NTHREDS) .setMaxConnTotal(NTHREDS).build(); requestExecService = new FutureRequestExecutionService(httpclient, execService); ResponseHandler<String> handler = new ResponseHandler<String>() { @Override public String handleResponse(HttpResponse response) throws ClientProtocolException, IOException { int statusCode = response.getStatusLine().getStatusCode(); if (statusCode == HttpStatus.SC_OK) { Document xmlDocument; try { String handleResponse = new BasicResponseHandler().handleResponse(response); System.out.println(Response: + handleResponse); xmlDocument = getXMLDocument(handleResponse); Element documentElement = xmlDocument.getDocumentElement(); int errorCode = Integer.parseInt(documentElement.getAttribute(errorCode)); if (errorCode != 200) { String errorString = documentElement.getAttribute(errorString); throw new ClientProtocolException(Error under upload! Error code: + errorCode + \nError String: + errorString); } else return ; } catch (ParserConfigurationException | SAXException e) { e.printStackTrace(); } return null; } else throw new ClientProtocolException(Failed under upload! Status code: + statusCode + \nReason: + response.getStatusLine().getReasonPhrase()); } }; List<HttpRequestFutureTask<String>> futureList = new ArrayList<HttpRequestFutureTask<String>>(); for (File fileEntry : folder.listFiles()) { String fileName = fileEntry.getName(); long fileSize = fileEntry.length(); long lastModified = fileEntry.lastModified() / 1000L; System.out.println(Uploading + fileName); HttpPost post = new HttpPost(url); post.setHeader(Cred, Token); post.setHeader(UploadFolderPath, Base64.encodeBase64String(uploadFolderPath).getBytes())); post.setHeader(FileName, Base64.encodeBase64String(fileName.getBytes())); post.setHeader(FileSize, Long.toString(fileSize)); post.setHeader(FileModifiedtime, Long.toString(lastModified)); post.setEntity(new ByteArrayEntity(IOUtils.toByteArray(new FileInputStream(fileEntry)))); HttpRequestFutureTask<String> futureTask = requestExecService.execute(post, HttpClientContext.create(), handler); futureList.add(futureTask); } System.out.println(Waiting for results); while (futureList.size() > 0) { System.out.println(FutureList size: + futureList.size()); for (Iterator<HttpRequestFutureTask<String>> iterator = futureList.iterator(); iterator.hasNext();) { try { HttpRequestFutureTask<String> futureTask = iterator.next(); if (futureTask.get() == null || futureTask.get().length() == 0) iterator.remove(); } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); } } } } finally { if (requestExecService != null) requestExecService.close(); execService.shutdown(); }} | File upload to web server using HttpRequestFutureTask | java;multithreading;http;rest | null |
_webapps.108876 | Would it be possible to limit 'sub users' (Editors and Reviewers using the same form) to only be able to view the records that match certain filters that are set up?We are using one form to collect data for the entire comoany, but certain departments only need to see some of the entries that meet a specific criteria. We have set up a filter, but they are still able to access all of the other information that is sub,titled through the form. We would be grateful if this could be implemented as an option when you first create an account for a 'sub user'. | Cognito Forms: Limit Sub-User Access to Specific Filters on Same Form | cognito forms | null |
_codereview.43747 | I've got the following Elixir code:defmodule Envvar do def exists?(env) do :os.getenv(env) != false end def get(env) do if exists?(env) do {env, :os.getenv(env)} else {env, nil} end endendTwo things:Am I using the ? correctly here? I'm assuming that any predicate function should have the ? on the end of the name by convention.Is there a way to code the get function as a pattern match rather than a if/else? I'm asking here because I'm guessing that a pattern match would be more idiomatic Elixir code. | Fetching environment variables can I use pattern matching? | functional programming;error handling;elixir | Using the ? for a boolean predicate is fine. At least it is what I would do inRuby and Elixir.You won't be able to call exists?(env) in a guard clause so pattern matching does not win you much here.You are calling :os.getenv() twice unneccessarily. I'm not sure why you just want to convert 'false' to 'nil', here is a way:defmodule Envvar do def get(env) do_get(:os.getenv(env)) end defp do_get(false) {:env, nil} end defp do_get(result) {:env,result} endend |
_unix.317771 | I am trying to enable the batman protocol on virtual machine. For this to happen there some manipulations that should be done on network device, e.g. create bridged interface and add existing interface to the bridge.I am using systemd facility to run the service on startup which will do the job. However the job fails consistently because it does not find the devices of network card.When i list interfaces from with in the script it shows that only loopback is upI have set the dependency in the best way I could - doesn't help.I have tried to work with eth1 or eth2 (according to dmesg they are beinf renamed to ensXXX somwhere in the boot proccess) - doesn't helpAny ideas???[root@batman1 ~]# systemctl status ba* ba.service - batman-adv initializer Loaded: loaded (/etc/systemd/system/ba.service; enabled; vendor preset: disab Active: inactive (dead) since Thu 2016-10-20 23:57:44 IDT; 12s ago Process: 243 ExecStart=/root/bat_conf (code=exited, status=0/SUCCESS)Main PID: 243 (code=exited, status=0/SUCCESS)Oct 20 23:57:44 batman1 systemd[1]: Started batman-adv initializer.Oct 20 23:57:44 batman1 bat_conf[243]: Cannot find device ens38Oct 20 23:57:44 batman1 bat_conf[243]: Cannot find device ens37Oct 20 23:57:44 batman1 bat_conf[243]: Error - interface does not exist: ens38Oct 20 23:57:44 batman1 bat_conf[243]: Error - interface does not exist: ens37[root@batman1 ~]# cat /etc/systemd/system/ba.service[Unit]Description=batman-adv initializerAfter=network.target dhcpcd.service sys-subsystem-net-device-ens37.device sys-subsystem-net-device-ens38.device[Service]ExecStart=/root/bat_conf[Install]WantedBy=multi-user.target[root@batman1 ~]# cat ~/bat_conf#!/bin/ship link set mtu 1532 dev ens38ip link set mtu 1532 dev ens37batctl if add ens38batctl if add ens37[root@batman1 ~]# ip link show1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN mode DEFAULT group default qlen 1 link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:002: ens33: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc fq_codel state UP mode DEFAULT group default qlen 1000 link/ether 00:0c:29:f3:4e:6b brd ff:ff:ff:ff:ff:ff3: ens37: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc fq_codel state UP mode DEFAULT group default qlen 1000 link/ether 00:0c:29:f3:4e:75 brd ff:ff:ff:ff:ff:ff4: ens38: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc fq_codel state UP mode DEFAULT group default qlen 1000 link/ether 00:0c:29:f3:4e:7f brd ff:ff:ff:ff:ff:ff | Systemd startup script fails to find network interfaces | networking;arch linux;systemd | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.