id
stringlengths
5
27
question
stringlengths
19
69.9k
title
stringlengths
1
150
tags
stringlengths
1
118
accepted_answer
stringlengths
4
29.9k
_softwareengineering.219482
Not sure how to go about this method to reduce Cyclomatic Complexity. Sonar reports 13 whereas 10 is expected. I am sure nothing harm in leaving this method as it is, however, just challenging me how to go about obeying Sonar's rule. Any thoughts would be greatly appreciated. public static long parseTimeValue(String sValue) { if (sValue == null) { return 0; } try { long millis; if (sValue.endsWith(S)) { millis = new ExtractSecond(sValue).invoke(); } else if (sValue.endsWith(ms)) { millis = new ExtractMillisecond(sValue).invoke(); } else if (sValue.endsWith(s)) { millis = new ExtractInSecond(sValue).invoke(); } else if (sValue.endsWith(m)) { millis = new ExtractInMinute(sValue).invoke(); } else if (sValue.endsWith(H) || sValue.endsWith(h)) { millis = new ExtractHour(sValue).invoke(); } else if (sValue.endsWith(d)) { millis = new ExtractDay(sValue).invoke(); } else if (sValue.endsWith(w)) { millis = new ExtractWeek(sValue).invoke(); } else { millis = Long.parseLong(sValue); } return millis; } catch (NumberFormatException e) { LOGGER.warn(Number format exception, e); } return 0;}All ExtractXXX methods are defined as static inner classes. For example, like one below - private static class ExtractHour { private String sValue; public ExtractHour(String sValue) { this.sValue = sValue; } public long invoke() { long millis; millis = (long) (Double.parseDouble(sValue.substring(0, sValue.length() - 1)) * 60 * 60 * 1000); return millis; } }UPDATE 1I am going to settle down with a mix of suggestions here to satisfy Sonar guy. Definitely room for improvements and simplification. Guava Function is just a unwanted ceremony here. Wanted to update the question about current status. Nothing is final here. Pour your thoughts please..public class DurationParse {private static final Logger LOGGER = LoggerFactory.getLogger(DurationParse.class);private static final Map<String, Function<String, Long>> MULTIPLIERS;private static final Pattern STRING_REGEX = Pattern.compile(^(\\d+)\\s*(\\w+));static { MULTIPLIERS = new HashMap<>(7); MULTIPLIERS.put(S, new Function<String, Long>() { @Nullable @Override public Long apply(@Nullable String input) { return new ExtractSecond(input).invoke(); } }); MULTIPLIERS.put(s, new Function<String, Long>() { @Nullable @Override public Long apply(@Nullable String input) { return new ExtractInSecond(input).invoke(); } }); MULTIPLIERS.put(ms, new Function<String, Long>() { @Nullable @Override public Long apply(@Nullable String input) { return new ExtractMillisecond(input).invoke(); } }); MULTIPLIERS.put(m, new Function<String, Long>() { @Nullable @Override public Long apply(@Nullable String input) { return new ExtractInMinute(input).invoke(); } }); MULTIPLIERS.put(H, new Function<String, Long>() { @Nullable @Override public Long apply(@Nullable String input) { return new ExtractHour(input).invoke(); } }); MULTIPLIERS.put(d, new Function<String, Long>() { @Nullable @Override public Long apply(@Nullable String input) { return new ExtractDay(input).invoke(); } }); MULTIPLIERS.put(w, new Function<String, Long>() { @Nullable @Override public Long apply(@Nullable String input) { return new ExtractWeek(input).invoke(); } });}public static long parseTimeValue(String sValue) { if (isNullOrEmpty(sValue)) { return 0; } Matcher matcher = STRING_REGEX.matcher(sValue.trim()); if (!matcher.matches()) { LOGGER.warn(String.format(%s is invalid duration, assuming 0ms, sValue)); return 0; } if (MULTIPLIERS.get(matcher.group(2)) == null) { LOGGER.warn(String.format(%s is invalid configuration, assuming 0ms, sValue)); return 0; } return MULTIPLIERS.get(matcher.group(2)).apply(matcher.group(1));}private static class ExtractSecond { private String sValue; public ExtractSecond(String sValue) { this.sValue = sValue; } public long invoke() { long millis; millis = Long.parseLong(sValue); return millis; }}private static class ExtractMillisecond { private String sValue; public ExtractMillisecond(String sValue) { this.sValue = sValue; } public long invoke() { long millis; millis = (long) (Double.parseDouble(sValue)); return millis; }}private static class ExtractInSecond { private String sValue; public ExtractInSecond(String sValue) { this.sValue = sValue; } public long invoke() { long millis; millis = (long) (Double.parseDouble(sValue) * 1000); return millis; }}private static class ExtractInMinute { private String sValue; public ExtractInMinute(String sValue) { this.sValue = sValue; } public long invoke() { long millis; millis = (long) (Double.parseDouble(sValue) * 60 * 1000); return millis; }}private static class ExtractHour { private String sValue; public ExtractHour(String sValue) { this.sValue = sValue; } public long invoke() { long millis; millis = (long) (Double.parseDouble(sValue) * 60 * 60 * 1000); return millis; }}private static class ExtractDay { private String sValue; public ExtractDay(String sValue) { this.sValue = sValue; } public long invoke() { long millis; millis = (long) (Double.parseDouble(sValue) * 24 * 60 * 60 * 1000); return millis; }}private static class ExtractWeek { private String sValue; public ExtractWeek(String sValue) { this.sValue = sValue; } public long invoke() { long millis; millis = (long) (Double.parseDouble(sValue) * 7 * 24 * 60 * 60 * 1000); return millis; }}}UPDATE 2Though I added my update, it is only that much worth the time. I am going to move on since Sonar now does not complains. Don't worry much and I am accepting the mattnz answer as it is the way to go and don't want to set a bad example for those who bumps on to this question. Bottom line -- Don't over engineer for the sake of Sonar (or Half Baked Project Manager) complains about CC. Just do what's worth a penny for the project. Thanks to all.
Avoid too complex method - Cyclomatic Complexity
java;code quality;refactoring;coding standards;cyclomatic complexity
Software Engineering Answer: This is just one of the many cases where simply counting beans that are simple to count will make you do the wrong thing. Its not a complex function, don't change it. Cyclomatic Complexity is merely a guide to complexity, and you are using it poorly if you change this function based on it. Its simple, its readable, its maintainable (for now), if it gets bigger in the future the CC will skyrocket exponentially and it will get the attention it needs when it needs needs it, not before. Minion working for a Large Multinational Corporation Answer: Organizations are full of overpaid, unproductive teams of bean counters. Keeping the bean counters happy is easier, and certainly wiser, than doing the right thing. You need to change the routine to get he CC down to 10, but be honest about why you are doing it - to keep the bean counters off your back. As suggested in comments - monadic parsers might help
_unix.277511
I'm creating an OCR-ed PDF through tesseract:tesseract input.tif out pdfBut I also need the hocr and txt files.Recent versions of tesseract already solved this but because it requires compiling both leptonica and tesseract, I'm not entirely comfortable with it.I can use pdftotext to extract the text file but I can't seem to find a way to extract hocr from the PDF.
How to extract hocr file from PDF?
pdf
null
_unix.300164
So I have a small script that I run as source (for those interested, I do this so that I can attain the correct $SECONDS value of the person running the script), as well as place the program in the background. Inside of this script there is an infinite loop that runs to update a temp file every second.So my question, how do I attain the PID of the loop inside the script that needs to be terminated to kill the updating of the temp file/the script?
Getting the PID of a backgrounded process that is run through source
shell script;background process
null
_unix.382072
I have a pkcs#8 encrypted key. I would like to sign a file using this key without having to decrypt it beforehand. What I want to achieve is to do all the process with a single openssl command.Something like this :openssl dgst -sha256 -sign pkcs8 -inform DER -in private.key -out sign_this.txt.signed sign.txtThis command would prompt for the password and then generate the signature.Is it possible to nest commands with openssl? Please explain the right way to proceed.Thanks.
How to sign something with dgst combined with pkcs8
openssl
null
_codereview.25813
I'm working on my Scala chops and implemented a small graph API to track vertices and edges added to graph. I have basic GraphLike Trait, and have an Undirected Graph class ( UnDiGraph) and a Directed graph class (DiGraph ) that extend the GraphLike trait.Here is some of the listing:trait GraphLike[T] { val vertices: Map[T, VertexLike[T]] def addEdge( a:T, b:T ): GraphLike[T] def addVertex( t:T ): GraphLike[T] def addVertex( vert: VertexLike[T] ): GraphLike[T] def adjacency( t:T ): Option[ List[T] ] = { if ( vertices contains t ) Some( vertices(t).adjList ) else None } def vertNum: Integer = vertices size def edgeNum: Integer = { def summer( sum: Integer, ms: Map[T, VertexLike[T] ] ): Integer = { if ( ms.isEmpty ) sum else summer( sum + ms.head._2.adjList.size, ms.tail ) } summer( 0, vertices ) } def getVertex( t: T ): VertexLike[T] = { vertices( t ) } def edgeExists( a:T, b:T ): Boolean = { try { if( vertices( a ).adjList contains b ) true else false }catch { case ex: NoSuchElementException => false } }}Here's what the DiGraph looks like:class DiGraph[T](val vertices: Map[ T, VertexLike[ T ] ] = Map.empty ) extends GraphLike[T] { def makeVertex( t:T ): VertexLike[T] = new Vertex( t ) def addEdge( a:T, b:T ): GraphLike[T] = { //Make sure vertices exist if( edgeExists(a, b) ) this else { try { vertices(b) vertices(a) } catch { case ex: NoSuchElementException => println(Vertices not Found); this } addVertex( vertices( a ) + b ) } } def addVertex( t:T ): DiGraph[T] = { if( vertices contains t ) this else new DiGraph[T]( vertices + ( t -> makeVertex(t) ) ) } def addVertex( vert: VertexLike[T] ): DiGraph[T] = { new DiGraph[T]( vertices + ( vert.apply -> vert ) ) }}Vertices are stored in a Map going from type T to VertexLike[T]. VertexLike basically holds an adjacency list for the specific Vertex.Here's what VertexLike looks like:trait VertexLike[T] { def addEdgeTo( dest: T ): VertexLike[T] def adjList: List[T] def +( dest: T) = addEdgeTo(dest) def apply: T} class Vertex[T](t: T, adj: List[T] = List() ) extends VertexLike[T]{ def apply() = t def adjList = adj def addEdgeTo( dest: T ) = if( adjList contains dest ) this else new Vertex[T]( t, dest :: adjList )}(Yes, I realize the apply method in the class is useless and it only works on objects. I realized that a little later). Anyways, I have a sample graph where I have about 80,000 vertices. Adding the vertices to the Graph is taking just way too long. I tried to do things functionally and in an immutable way. Whenever you add a vertex or an edge to a graph, you get a new graph (I tried to make sure the constructors of the graph types weren't doing much). This is the client code that I use to create my graph from my data.def GraphInstantiater: GraphLike[Int] ={ println( Total number of Vertices: + synMap.keys.size ) def vertexAdder( ls: Iterable[Int], graph:GraphLike[Int] ): GraphLike[Int] = if( ls.isEmpty) graph else vertexAdder( ls.tail, graph.addVertex( ls.head ) ) val gr = vertexAdder( synMap.keys, new DiGraph[Int]( Map() ) ) println( Vertices added. Total: %d.format( gr.vertices.size ) ) gr}I know constructing new graphs will take cycles but is it really all that great given that I'm not doing much in the constructors. Would repeatedly creating the Map of vertices keep causing problems (it's one of the parameters of the graph class). Any ideas on what the bottlenecks are in this method would be much appreciated.
Small graph API to track vertices and edges added to graph
performance;scala;graph
null
_unix.28961
Say I have local access to two machines A and B and remote access to machine C.If I generate a public-private pair of keys for accessing machine C from A, can I share the private key with machine B to access machine C from it? Or do I need to generate a new public-private pair?At the moment I have a pair of keys working to access C from A, but when I use this private key from B it doesn't work.In case it matters, I use a config file for this as follows:Host XXXUser XXXHostName XXXIdentityFile ZZZWhere ZZZ points to the key in B (different paths in the machines A and B)I am using the same username in both.
Sharing private keys across machines
ssh
You always can. I think C will have your public key (outside) and, if A and B are both inside a local network (ie: your home network), you are not doing something risky by sharing, unless you use internet to send it unencrypted xD. If A and B are machines you own and you can be sure that nobody can read your private key, then you can share a private key with no risk.The thing is that your private key must never be compromissed. Ensure you have a revoke certificate generated and printed, and the public key in a keyserver, so anyone can just refresh it to see new signatures and revoke certificates.I will give you an example. I have a GitHub account, and I access it from SSH from my machines at home. I have more than one machine, and more than one OS inside each machine, but I use only one key for GitHub. Why? Well... I have my key in personal, encrpted drives. Nobody can see my private key, no matter how much copies I own.Hope it'ill be helpfulCheers
_webapps.28672
I am currently creating a survey using Google Forms. It's quite a long survey, so I would like to make it as quick as possible for everybody doing it. A lot of the survey questions are repeated and depend on whether or not a person has had training in a particular area. For example, the first question for each page will be:Have you had training in X?Followed by questions according to the first answer, e.g.If you have not had training in X, how interested would you be in having training in X?If you have had training in X, how confident are you in delivering the service?Do you feel you have enough time to deliver the service?etc.Is it possible to create the survey so that if somebody indicates that they have or have not had training in X, it only shows them the follow-up question relevant to their experience?Another advantage would be that I would increase the likelihood that the people are responding to every answer, and not just skipping over it. At the moment, I have to make the follow-up questions optional due to it applying/not applying to them, so it means they can skip over questions that are relevant to them.
Set up specific questions to appear only after particular answers on Google Forms
google forms
null
_unix.160487
When I had to repair my Debian system, I tried to use schroot due the convenience of not having to mount bind several partitions. But, contrary to my expectations, schroot decided to override my passwd file and other configuration files (in /etc and my home directory) which I didn't like (and sometimes causes weird messages). Is there a way to prevent that behavior? I used the type directory for schroot, since it seemed the one I needed. I checked the man page and only found a --preserve-environment option, but from its description I'm not sure if it preserves the chrooted system environment or just copies my user environment to the chroot session instead of a clean slate (which is the default).
How to prevent schroot from overridding passwd file and others files already present on the chrooted system?
chroot;accounts;schroot
null
_webapps.55029
I have read all the current responses, and still do not see an answer, but I too have a desire to remove ALL E mails in the category of all mail. How do I do this???
Removing all E mails from a gmail (all mail) account
gmail
null
_unix.284913
I have a ultrabook and its touchpad doesn't work.Linux mike 3.16.0-4-amd64 #1 SMP Debian 3.16.7-ckt25-1 (2016-03-06) x86_64 GNU/Linuxtouchpad doesn't work and it is also not listed in output of following command.cat /proc/bus/input/devicesit's outputtouchpad model : Sentelic Finger Sensing Pad Driverso I typed following commandmodinfo psmouseit's outputaccording to these information when I type following commandls /lib/modules/3.16.0-4-amd64/kernel/drivers/input/mouse/I see following output :appletouch.ko bcm5974.ko cyapa.ko psmouse.ko sermouse.ko synaptics_i2c.ko synaptics_usb.ko vsxxxaa.koso as a result I thought I should recompile psmouse module which supports sentelic touchpad. I look around the internet, I get the linux repository.I checked the tag v3.16I went into drivers/input/mouse and I see following filesalps.c appletouch.c cyapa.c elantech.c hgpk.c Kconfig logibm.c Makefile pc110pad.c pxa930_trkball.c sentelic.h synaptics.h touchkit_ps2.c trackpoint.halps.h atarimouse.c cypress_ps2.c elantech.h hgpk.h lifebook.c logips2pp.c maplemouse.c psmouse-base.c rpcmouse.c sermouse.c synaptics_i2c.c touchkit_ps2.h vsxxxaa.camimouse.c bcm5974.c cypress_ps2.h gpio_mouse.c inport.c lifebook.h logips2pp.h navpoint.c psmouse.h sentelic.c synaptics.c synaptics_usb.c trackpoint.cwhich includes sentelic.h and sentelic.c files also there is a Makefile but when I hit enter the command make it says make: *** No targets. Stop.my question is how could I compile psmouse module with the sentelic touchpad support.I really hate my jessie I'm stuck with this touchpad issue.any help would be appreciated.UPDATED :I get following information from windows driver's fspad.inf filedriver; Localizable StringsProvider = SentelicDiskId1 = Finger Sensing Pad Driver Installation DiskAVC.DeviceDesc = Finger Sensing PadAVC.DriverDisplayName = Finger Sensing Pad DriverAVC.DriverDisplayVersion = 9.2.9.7AVC.DriverReleaseDate = 05/09/2012AVC.DriverCfg = fspad.SvcDesc = Finger Sensing Pad Driver for Windows 2000/XP/Vista/Win7fspadsvr.SvcDesc = Finger Sensing Control ServiceUPDATED 2 :I tried following Live USBs and the result is same :I checked lsmod, and proc/bus/input/devices not much different than details that I gave above. There is no touchpad thing. Point Linux Mate Full 2.3-32 i386 Kernel 3.2.0-4Ubuntu 12.04.4-Desktop amd64 Kernel 3.11Xubuntu 16.04-Desktop amd64 Kernel 4.4.0I really need help how could I make this work ? Is this a absolute kernel bug ? How could I be sure whether is this a bug or there is another solution, so according to that result I'm going to file a bug.
psmouse kernel module recompiling
kernel;linux kernel;kernel modules
null
_webmaster.43564
In order to determine whether to serve the mobile or full version of my site by default, I use a service that examines requests to determine the type of device they originated from. However, calls to that service are somewhat expensive, so I'd like to filter out a number of desktop clients before having to call my service.My current traffic stats show the following breakdown for my site:35% - Chrome25% - IE20% - Firefox16% - SafariI don't know what percentage of these are desktop browsers vs. mobile browsers. However, last month (before the mobile version of my site existed), mobile users accounted for about 10% of my traffic.Here's my question: Are there some regular expressions I can apply to the user agent to identify much of my non-mobile traffic so I can avoid unnecessary service calls? It isn't critical that I catch all desktop browsers at this stage. Even identifying 50% of them would be a huge help. It is important, however, not to incorrectly identify a mobile browser as a desktop one. Thus, conservatism would be a benefit here.ClarificationI want to unambiguously identify some of the common desktop browsers as desktop, but the info I've been able to find so far has been outdated (the bane of browser detection) or otherwise unhelpful.Here's an example: Chrome is available both on the desktop and on cell phones. Can I write a regular expression to look at a Chrome user agent string and say definitively that it isn't a cell phone? If it makes things simpler, I'm currently treating tablets as desktop browsers, though if it's too complicated, I don't need to handle them here.
Filtering desktop users by user agent string
mobile;user agent;browser detecting
null
_unix.162133
I want to run a bash script in a detached screen. The script calls a program a few times, each of which takes too long to wait. My first thought was to simply open a screen and then call the script, but it appears that I can't detach (by ctrl-a d) while the script is running. So I did some research and found this instruction to replace the shebang with following:#!/usr/bin/screen -d -m -S screenName /bin/bashBut that doesn't work, either (the options are not recognized). Any suggestions? PS It occurs to me just now that screen -dmS name ./script.sh would probably work for my purposes, but I'm still curious about how to incorporate this into the script. Thank you.
Run script in a screen
shell script;scripting;gnu screen;shebang
The shebang line you've seen may work on some unix variants, but not on Linux. Linux's shebang lines are limited: you can only have one option. The whole string -d -m -S screenName /bin/bash is passed as a single option to screen, instead of being passed as different words.If you want to run a script inside screen and not mess around with multiple files or quoting, you can make the script a shell script which invokes screen if not already inside screen.#!/bin/shif [ -z $STY ]; then exec screen -dm -S screenName /bin/bash $0; fido_stuffmore_stuff
_codereview.104280
This is (the significant) part of an implementation of a logging mechanism for recording events in a real-time control system. The basic requirements are:No dynamic memory on either side (producers or consumer),Lock-freevariable length event entriesstrictly sequential timestampsmulti-processor safetolerant of overruns/data dropsusable from both kernel and user space codeAs I've never written a lock free algorithm before, I'm hoping for some comment on any concurrency problems.I have this running, but I am very occasionally seeing a corrupted log message, which seems to have been published (tail moved forwards) before the body is completed. I'm hoping I'm missing something simple.The system holds log data in a shared memory area (or several, depending on the use case). Typically each process in the system will create one log buffer of the form:typedef atomic_uint_least32_t LogIndex_t;typedef uint32_t LogVar_t;struct LogInfo_struct{ LogIndex_t m_need; //declaration of space needed LogIndex_t m_head; //current head of buffered log data LogIndex_t m_alloc; //allocated out beyond working area LogIndex_t m_filled; //committed complete data LogIndex_t m_tail; //safe location at tail of buffered log data uint8_t m_logBuffer[LOG_SIZE]; //head of log buffer char m_strings[1<<12][64]; //copied and validated table of strings} *g_log = 0;Where LOG_SIZE is a power of 2, and the string table is used to encode longer, reused items. I won't be discussing the shared memory setup or the actual content of the message body, since this is unimportant here. The structure of each log entry is:1 byte length of body2-16 byte timestamp (depending on requirements)X bytes of arbitrary data (0-255 bytes)Logging involves computing the body length and content, calling openEntry, writing the body content into the provided frame, and calling closeEntry.static inline void bh_log_getTimeStamp( struct timespec *time ){ #if defined(__KERNEL__) getrawmonotonic(time); #else clock_gettime(CLOCK_MONOTONIC_RAW, time); #endif}static LogVar_t bh_log_openEntry( uint8_t bodySize ){ uint16_t size = bodySize + 1 + sizeof(struct timespec); LogVar_t need, target, head, newHead, zero, alloc; struct timespec timeStamp; int i; memset(openLoopCount,0,3*sizeof(int)); //first, push the needed position out by the size required need = atomic_fetch_add(&g_log->m_need,size) + size; //then verify that the head is beyond the need position (using tail as reference) zero = atomic_load(&g_log->m_tail) + 1; //tail can't move until we commit target = (need - zero) & LOG_SIZE_MASK; //ensure the head is moved far enough to free up space for allocation do { head = newHead = atomic_load(&g_log->m_head); if (((newHead - zero) & LOG_SIZE_MASK) >= target) break; do { newHead += g_log->m_logBuffer[newHead & LOG_SIZE_MASK] + 1 + sizeof(struct timespec); } while( ((newHead - zero) & LOG_SIZE_MASK) < target ); } while(!atomic_compare_exchange_strong(&g_log->m_head, &head, newHead)); //either I moved the head down beyond all allocated areas, or someone else did do { alloc = atomic_load(&g_log->m_alloc); target = alloc + size; bh_log_getTimeStamp(&timeStamp); } while( !atomic_compare_exchange_strong(&g_log->m_alloc, &alloc, target) ); //alloc == index of allocated location, timestamp = captured timestamp to use g_log->m_logBuffer[alloc & LOG_SIZE_MASK] = bodySize; for(i=0; i < sizeof(struct timespec); ++i) { g_log->m_logBuffer[(alloc + 1 + i) & LOG_SIZE_MASK] = ((uint8_t*)(&timeStamp))[i]; } return alloc + 1 + sizeof(struct timespec);}static void bh_log_closeEntry( uint8_t bodySize ){ uint16_t size = bodySize + 1 + sizeof(struct timespec); LogVar_t need, newFilled, tail; newFilled = atomic_fetch_add(&g_log->m_filled,size) + size; do //I'm not sure this loop is needed. If tail moved, then someone else passed //this logic in the interim. We can possibly just try once and give up { tail = atomic_load(&g_log->m_tail); need = atomic_load(&g_log->m_need); if (newFilled != need) break; } while( !atomic_compare_exchange_strong(&g_log->m_tail,&tail,newFilled) );}On the backend I have a (non-realtime) task which pulls out chunks of entries (anything [m_head..m_tail)) and moves m_head forward (ideally, faster than the m_tail is moving on average). This backend service collates multiple log buffers, converts the log entries into human readable format, and does UI and file system interactions.The relevant consumer portion of that code looks like this: uint8_t work[1000]; bool didWork = true; int len = 0, addLen = 0; LogVar_t head, tail; struct timespec captureTime; do { clock_gettime(CLOCK_MONOTONIC_RAW, &captureTime); head = atomic_load(&m_log->m_head); tail = atomic_load(&m_log->m_tail); uint8_t *tmps; //pull out a chunk of pending entries if ( head == tail ) { didWork = false; break; } else if ( head > tail ) { int len = (LOG_SIZE - head) & LOG_SIZE_MASK; if (len > 1000) len = 1000; memcpy(work,&m_log->m_logBuffer[head & LOG_SIZE_MASK],len); tmps = &m_log->m_logBuffer[0]; addLen = tail & LOG_SIZE_MASK; } else { len = 0; tmps = &m_log->m_logBuffer[head & LOG_SIZE_MASK]; addLen = (tail - head) & LOG_SIZE_MASK; } if (addLen > 1000 - len) addLen = 1000 - len; if (addLen) memcpy(&work[len], tmps, addLen); len += addLen; if ( len >= 1000 ) { //might have truncated, find proper new head addLen = 0; while( (int)(addLen) < len ) { int fsize = work[addLen] + 1 + sizeof(struct timespec); if (addLen + fsize <= len) addLen += fsize; else break; } tail = head + addLen; //new } } while(!atomic_compare_exchange_strong(&m_log->m_head,&head,tail));
Real-Time MP/SC Lock Free Ring
c;lock free
Consumer bugUnless I am misunderstanding something, there seems to be a big problem in the consumer. Your variables m_head and m_tail appear to start at 0 and move forward indefinitely, without wrapping around at LOG_SIZE (which is fine). But the way the consumer interprets head and tail looks like it expected them to wrap around. For example, I don't see how this if could ever be true: else if ( head > tail )And when the code inevitably falls into the next case: else { len = 0; tmps = &m_log->m_logBuffer[head & LOG_SIZE_MASK]; addLen = (tail - head) & LOG_SIZE_MASK; } if (addLen > 1000 - len) addLen = 1000 - len; if (addLen) memcpy(&work[len], tmps, addLen); len += addLen;You will be copying past the end of m_logBuffer whenever head gets close to the end of the buffer. For example, suppose LOG_SIZE is 32768, head is 32700, and tail is 32800. The above code will copy 33 bytes past the end of the buffer.I'm surprised that you haven't noticed this problem. I wonder if your producer also copies past the end of the buffer? You never showed us the part where the producer copies the body. If that code had a similar problem, it could explain why the code might appear to be working.Memory barriersNormally, you would need to use memory barriers on both the producer and consumer sides to ensure that the content and tail updates are seen in the correct order. However, I'm assuming this program is running on an x86 target, where these barriers are not needed due to the strong memory ordering guarantees on that architecture.
_unix.299147
I am setting certain environment variables for the command pyspark to work. When I set the variables in /etc/environment and source it, it doesn't work. However, when I set them in command line they do work but ofcourse only for this session. My intent is to set them globally so that even if I re-open the session I can just type pysparkSetting in /etc/environment[root@localhost ~]# more /etc/environment[root@localhost ~]# echo export SPARK_HOME=/srv/spark >> /etc/environment[root@localhost ~]# echo export PATH=$SPARK_HOME/bin:$PATH >> /etc/environment[root@localhost ~]# echo export JAVA_HOME=/usr/lib/jvm/jre-1.7.0-openjdk >> /etc/environment[root@localhost ~]# source /etc/environment[root@localhost ~]# pyspark --version-bash: pyspark: command not foundSetting on command line[root@localhost ~]# export SPARK_HOME=/srv/spark[root@localhost ~]# export PATH=$SPARK_HOME/bin:$PATH[root@localhost ~]# export JAVA_HOME=/usr/lib/jvm/jre-1.7.0-openjdk[root@localhost ~]# pyspark --versionWelcome to ____ __ / __/__ ___ _____/ /__ _\ \/ _ \/ _ `/ __/ '_/ /___/ .__/\_,_/_/ /_/\_\ version 1.6.1 /_/Type --help for more information.
Setting variables in /etc/environment not having an affect but setting them in command line is
centos;environment variables
Put the export SPARK_HOME=... etc. commands in the startup files of your shell. With bash, that would be either ~/.profile or ~/.bash_profile. On Linux, /etc/environment is usually read by pam_env.so during login, and it doesn't support expanding existing variables, so setting PATH=$PATH:/something will result in the literal string $PATH to appear in your PATH. This isn't what you want. (See e.g. this and this, also for fun this.)Also, setting PATH in /etc/environment might not work, since the global startup scripts for the shell might rewrite them. (They do on Debian by default, on the old CentOS I have handy, the startup scripts only seem to prepend to PATH). If your system doesn't use pam_env.so, but you only source the script by hand, then these considerations don't matter, of course. But it looks like it's widely used by at least a couple of Linux distributions, so it might be a good idea to use another filename.(Because this is completely opposite to what the other answers said, I tested it on an old CentOS.)I put the following in /etc/environment:export FOO1=barexport FOO2=foo:$FOOAfter logging in again, set | grep FOO shows:FOO1=barFOO2='foo:$FOO'
_codereview.91944
I need to intercept a URL and go outside the WebView if the URL contains MAPS or DOCUMENTS constants. I must also go outside if url does not contain the value of DOMAIN and LOGIN_SALES_FORCE.This is working nice, but seems ugly for me. Any ideas?if ([request.URL.absoluteString rangeOfString:MAPS ].location != NSNotFound || [request.URL.absoluteString rangeOfString:DOCUMENTS ].location != NSNotFound){ NSURL *url = [NSURL URLWithString:request.URL.absoluteString]; return [[UIApplication sharedApplication] openURL:url];} else if ([request.URL.absoluteString rangeOfString:DOMINIO ].location == NSNotFound && [request.URL.absoluteString rangeOfString:LOGIN_SALES_FORCE ].location == NSNotFound) { NSURL *url = [NSURL URLWithString:request.URL.absoluteString]; return [[UIApplication sharedApplication] openURL:url];}
Intercept URL containing values or not
objective c;url
Disclaimer: I don't know Objective-C. The proposed changes are quite basic, though, and should give the same result as your original code.Intermediate variablesTo shorten your expressions, you may want to use an intermediate variable:NSString *absUrl = request.URL.absoluteString;Then, you can group your conditions using boolean operators.Boolean logicif ( [absUrl rangeOfString:MAPS].location != NSNotFound || [absUrl rangeOfString:DOCUMENTS].location != NSNotFound || ( [absUrl rangeOfString:DOMINIO].location == NSNotFound && [absUrl rangeOfString:LOGIN_SALES_FORCE].location == NSNotFound)){ NSURL *url = [NSURL URLWithString:request.URL.absoluteString]; return [[UIApplication sharedApplication] openURL:url];}RemarksReading this documentation, I find it strange that you are converting request.URL to url using URLWithString. I may be wrong, but you could use absoluteUrl to achieve the same effect.
_reverseengineering.9555
I'm working on converting a game originally developed to run on Windows for the web. I have a bunch of artwork for the game received from the artist in .tga image files which open fine in Photoshop. However I don't have the complete set of artwork and it cannot be found. I also have a distribution of the Windows game which consists of .dlls, .lua files and a lot of .tga files. The .tga (Targa) files in the game distribution are named the same as the .tga files in the artwork I have received so I think it's safe to assume they are the same images. Even the images that I'm missing from the supplied artwork are present in the game distribution. Bingo! Well actually noThe .tga files from the game won't open in Photoshop or Preview (mac) or Pixelmator (mac). So I think something has been done to the game .tga files to protect them and I want to reverse engineer them back to normal .tga files.First I need to discover what the new files are and how they've been modified. Here's what I've tried so far:Using linux file command:rockExplosion.tga (from artwork). Output: rockExplosion.tga: Targa image data - RGB 100 x 43rockExplosion.tga (from game). Output: rockExplosion.tga: dataInspecting using hex viewer and diffThe two files are exactly the same byte length. The last ~15% of bytes are identical in each file and the first ~85% are completely different.Binwalk didn't tell me anything for either file.What other techniques exist for reverse engineering unknown file formats?Is there a standard way of protecting images in .NET applications that could have been used?What other tools could I use to probe further?
Techniques for reverse engineering an unknown or protected file format
windows;file format;.net;encodings
null
_webapps.8669
I want to be able to do visualization of some raw data, be able to draw different kinds of graphs etc, and be able to post an interactive drawing on my map. I know that Tableau Public does just this. But I don't have permission to install anything on my windows machine (Don't have admin rights). Is there an online version of tableau public where I can make diagrams online or any alternatives one would like to suggest?
How to visualize data online?
blog;drawing;visualization;data visualization
null
_unix.113925
When searching for string (no regex etc.) in large file less filename and less -b 1 filename quits or prints it cannot allocate memory. top shows less using roughly about 5% of memory before it dies (1 sec interval).What other tool can I use that supports large files? The file has only 100 mb of logs.$ less -Vless 458 (GNU regular expressions)Copyright (C) 1984-2012 Mark NudelmanOS details:$ ulimit -a-t: cpu time (seconds) unlimited-f: file size (blocks) unlimited-d: data seg size (kbytes) unlimited-s: stack size (kbytes) 8192-c: core file size (blocks) 0-m: resident set size (kbytes) unlimited-u: processes 15988-n: file descriptors 1024-l: locked-in-memory size (kbytes) 64-v: address space (kbytes) 2048000-x: file locks unlimited-i: pending signals 15988-q: bytes in POSIX msg queues 819200-e: max nice 0-r: max rt priority 0-N 15: unlimited$ cat /etc/*rele*DISTRIB_ID=UbuntuDISTRIB_RELEASE=13.10
less command runs out of memory
less;gnu
This probably has nothing to do with your memory and everything to do with the way less is written and how much space it allocates for it's internal variables.Anyway, less is really not designed for this, you should use a tool like grep instead:grep yourQuery fileIf you want to see the lines around your query (5 for example), run this:grep -C 5 yourQuery fileIf you have too many matches for that, you can pass the output to less and now you should be able to search through it:grep -C 5 yourQuery file | lessOf course, if you want to do this manually, you can open the file in a text editor. Any serious editor like vim or emacs will be able to open and search through a 100MB file.
_codereview.132729
A valid Sudoku board has the following propertiesThe board must be square (n-by-n). Let m = sqrt(n)All rows must contain the numbers 1-n All columns must contain the numbers 1-n All nine m-by-m blocks must contain all numbers 1-n The following MATLAB code verifies a Sudoku board of arbitrary sizes (where n is a square number):function correct_board = sudoku_checker(board)correct_board = true;[rows, cols] = size(board);correct_size = (rows == cols) && mod(sqrt(rows),1) == 0;if correct_size == false disp('The board is not square') correct_board = falseelse disp('The board is square') for ii = 1:rows if ~(isequal(unique(board(:,ii)), (1:rows)') && isequal(unique(board(ii,:)), (1:rows))) disp(['Numbers ' num2str(1) '-' num2str(rows) ' are not present in all rows or columns']) correct_board = false; return end end disp(['Numbers ' num2str(1), '-' num2str(rows) ' are present in all rows and columns']) cell_blocks = mat2cell(board, repmat(sqrt(rows),sqrt(rows),1),repmat(sqrt(rows),sqrt(rows),1)); blocks_ok = all(arrayfun(@(x) isequal(unique(cell_blocks{x}),(1:rows)'), 1:rows)); if blocks_ok == true disp(['All blocks are OK']) else disp(['All blocks are not OK']) correct_board = false; return; end disp('Board is OK')endendA valid board will give the following output:sudoku_checker(board)The board is squareNumbers 1-9 are present in all rows and columnsAll blocks are OKBoard is OKAn incorrect board will give an output like this (dependent on which condition that fails):sudoku_checker(board)The board is squareNumbers 1-4 are present in all rows and columnsAll blocks are not OKI'm wondering if there are ways to improve this code. I'm looking for improvements in performance and algorithm, as well as improvement in coding style etc.Can I simplify any expressions? Remove some boolean operators?
Verification of Sudoku boards
matlab;sudoku
A few general things first:' is the conjugate transpose, not the transpose. These are the same for real values, but will behave differently when you have complex values. To avoid confusion, it is recommended that you always use .' when transposing a matrix, even if it's real.You're using both disp('text') and disp('[text]'). The first one works for plain strings, while the other must be used when concatenating strings and numbers. I suggest you either use brackets on all calls to disp, or skip the brackets for all calls to disp where the string is plain text. Consistency is always nice.Variable names:The variable names are well chosen and descriptive. One minor comment is that you're using correct_size and correct_board, but blocks_ok. correct_blocks is probably a better word here, to keep consistency.Frequently used variables:There are a few variables that are used over and over again. You should declare the following variables outside the loop:sq_rows = sqrt(rows); values= 1:rows;Avoid the loop and calls to unique by sorting the board by rows and columns:You can avoid the loops by sorting all columns of the regular board, and the board when it's transposed, instead of checking for unique values.isequal(sort(board), sort(board.'), repmat(values.',1, rows))repmat(values.',1,rows) produces a matrix looking like this:1 1 1 12 2 2 23 3 3 34 4 4 4Alternatives to repmat(sqrt(rows),sqrt(rows),1):Using mat2cell to create cell_blocks is good, but the expression can be simplifed using the new pre-defined variables. There are some alternatives to repmat(sqrt(rows),sqrt(rows),1) that are more readable, such as:ones(sq_rows,1) * sq_rows;zeros(sq_rows,1) + sq_rows;repelem is an option if you're using MATLAB version R2015a or newer. Use cellfun when you're working with cells, and arrayfun when you are working with other stuff.Since cell_blocks is a cell array, you can use cellfun:all(cellfun(@(x) isequal(unique(x),values.'), cell_blocks))Simplifying the disp-calls:You know that the first number in the sequence is 1, so you can simplify the two disp-calls in the middle:disp(['Numbers 1-' num2str(rows) ' are present in all rows and columns'])I believe you're missing a break after checking the size of the board (first if).Comments!I suggest you use a lot more comments! Explain what the different parts of your code do.
_softwareengineering.78379
I'm coding a Linux/PHP site for an organization. The site has two views, activated by a login $_SESSION variable indicating whether one is logged in as a member or not. I need to provide search functionality for both the public and for members. The members area is private. Note that Google Custom Search can't be used here in that case.Does anyone have any recommendations on F/OSS scripts (or perhaps cheap scripts I can purchase) that would provide this functionality with two separate indices, one public and one private, and which would provide paginated results and a keyword search form?Otherwise, I guess I'll have to code one myself. I'm trying to save time, and therefore keep more money in my pocket.P.S.Note I can't ask this on StackOverflow because they want programmer questions there. This isn't a how do I code this? question, but what F/OSS scripts or cheap sitescripts would solve this problem? type of question.Note also that this won't help me either. I mean, look at the answers of that question.
Need Advice on PHP Search Functionality
php;linux;search;search engine
null
_unix.368611
By using iostat I see a constant 200+MB/s read on a certain device. How can I understand on CentOS which process is causing this, without using iotop (I cannot install it in this environment)?
How to find process doing very high io read (without iotop)
io;iostat
null
_unix.312089
I am using the latest Ubuntu Linux with a custom kernel (4.2.0-36-generic), in which I have disabled the CONFIG_STRICT_DEVNEM, because I need to dump and search some terms in memory during a project.However, when using:dd if=/dev/mem to print it on screen,dd if=/dev/mem of=/home/user/Documents/file.dump to save it as a file, ordd if=/dev/mem | hexdump -C | grep 'term' to directly find what I'm looking for,the system freezes and reboots while in the process.I have checked with df -h and my disc has plenty of free space. Also, the process always stops after writing a 2.1Gb to 2.5Gb, out of a 8Gb RAM and before reaching addresses that start with 4 (if these make any difference). In addition, checking /var/log/syslog and /var/log/kern.log shows nothing relevant before the freezing.Also, using parameters bs=1G count=2 successfully copies the first 2GB of the memory but then trying bs=1G count=2 skip=2 to get then next 2GB again freezes the system.Would you suggest any solution so it is possible to dump the full memory or some other way to directly search terms in memory?
Accessing /dev/mem freezes Ubuntu
linux;memory;freeze;forensics
I think you may run into some memory area used by PCI/ACPI or some such hardware. There might be a memory mapped device that doesn't like being accessed. I can't tell what address exactly causes the problem, but it's usual for some special areas to be located just under the 4 GB limit.On one machine with 4 GB memory, the kernel prints the following on boot:BIOS-e820: 0000000000000000 - 000000000009e400 (usable)BIOS-e820: 000000000009e400 - 00000000000a0000 (reserved)BIOS-e820: 00000000000f0000 - 0000000000100000 (reserved)BIOS-e820: 0000000000100000 - 00000000cf690000 (usable)BIOS-e820: 00000000cf690000 - 00000000cf6e0000 (reserved)BIOS-e820: 00000000cf6e0000 - 00000000cf6e3000 (ACPI NVS)BIOS-e820: 00000000cf6e3000 - 00000000cf6f0000 (ACPI data)BIOS-e820: 00000000cf6f0000 - 00000000cf700000 (reserved)BIOS-e820: 00000000e0000000 - 00000000f0000000 (reserved)BIOS-e820: 00000000fec00000 - 0000000100000000 (reserved)BIOS-e820: 0000000100000000 - 0000000130000000 (usable)Part of the usable memory is above the 4 GB limit at 0x100000000 and there seems to be holes between 0xcf700000 and 0xfec00000.The areas corresponding to usable memory are also shown in /proc/iomem, marked as System RAM. (the file also contains information about the other memory areas.) You might be safer just reading from those areas. $ grep System RAM /proc/iomem 00001000-0009e3ff : System RAM00100000-cf68ffff : System RAM100000000-12fffffff : System RAM
_codereview.120173
Here is my approach. Do DFS and check in stack whether the new node is already in the Stack or not.public static boolean isCyclicDFS(int[][] adjMat) { int len = adjMat.length; boolean[] isVisited = new boolean[len]; for(int i =0; i<len; i++) { isVisited[i] = false; } Stack s = new Stack<>(); s.add(0); while(!s.isEmpty()) { int current = (int) s.pop(); System.out.println(current); isVisited[current] = true; for(int i =0; i<len; i++) { if(adjMat[current][i] ==1 && isVisited[i] == false) { if(s.contains(i)) { return false; } s.push(i); break; } } } return true; }Kindly suggest if any improvement/correction.
Check if the undirected graph is cyclic
java;interview questions;graph
null
_datascience.13055
I have written my custom scorer object which is necessary for my problem and which I've called p_value_scoring_object.For the function sklearn.cross_validation.cross_val_score one of the parameters is scoring, which allows to use this scorer object.However, this option is not available for the score method of a classifier. Is sklearn just lacking that feature, or is there a way around it?from sklearn.datasets import load_irisfrom sklearn.cross_validation import cross_val_scorefrom sklearn.tree import DecisionTreeClassifierclf = DecisionTreeClassifier(random_state=0)iris = load_iris()cross_val_score(clf, iris.data, iris.target, cv=10,scoring=p_value_scoring_object)This works. However, this doesn't:clf.fit(iris.data,iris.target)clf.score(iris.data,iris.target,scoring=p_value_scoring_object)
Using Scorer Object for Classifier Score Method for scikit-learn
machine learning;python;scikit learn
null
_codereview.28902
This is my Clojure code for finding prime numbers.Note: this is an advanced version which starts eliminating from i*i with step i, instead of filtering all list against mod i == 0 (Sieve of Eratosthenes).It has better asymptotic runtime: O(n log log n) instead of O(n log n) in typical examples of finding primes in Clojure.What can be done better? Do I use some slow constructions? Can I make it more concise? Gain more performance? Format it better?(defn primes [n] (let [mark (fn [i di v] (if (<= i (count v)) (recur (+ i di) di (assoc v (dec i) di)) v)) step (fn [i ps v] (if (<= i (count v)) (if (= (v (dec i)) 1) (recur (inc i) (conj ps i) (mark (* i i) i v)) (recur (inc i) ps v)) ps))](->> (repeat 1) (take n) vec (step 2 []))))(defn -main [& args] (println (primes 50)))
Clojure code for finding prime numbers
primes;clojure
null
_codereview.93301
We have a main application made of a few separate parts - Unity and Clc.I'm writing a new tool which will be used to manage them: deploy Unity, or run some checks and a lot of other stuff. As there will be a lot of options, I want split them in to separate namespaces.Here is my implementation, it works, but I'm not sure if it's the best way.import argparseparser = argparse.ArgumentParser()subparsers = parser.add_subparsers()parser_unity = subparsers.add_parser('unity', help='Unity help')parser_unity.add_argument('-t', '--tagcheck', dest='unity_tagcheck', action='store_true', help='Check tags in .csproj files')parser_unity.add_argument('-d', '--deploy', dest='unity_deploy', action='store_true', help='Deploy Unity project to appropriate URL')parser_clc = subparsers.add_parser('clc', help='Clc help')parser_clc.add_argument('-d', '--deploy', dest='clc_deploy', action='store_true', help='Deploy Cloudlibrary project to appropriate environment')res = parser.parse_args()print('All %s' % res)try: if res.unity_deploy: print('Unity deploy') if res.unity_tagcheck: print('Unity tagcheck')except AttributeError: passtry: if res.clc_deploy: print('Clc deploy')except AttributeError: passAnd here is how is works:d:\RDS\rdsmanager>tmp\test.py clc -dAll Namespace(clc_deploy=True)Clc deployd:\RDS\rdsmanager>tmp\test.py unity -d -tAll Namespace(unity_deploy=True, unity_tagcheck=True)Unity deployUnity tagcheckd:\RDS\rdsmanager>tmp\test.py unity -dAll Namespace(unity_deploy=True, unity_tagcheck=False)Unity deploy
Argparse with subparsers
python;python 2.7
If you take a look at the argparse documentation, they suggest to useset_defaults on each of the parsers to associate a processing functiondepending on which parser is selected. So if you do that then you canget rid of the try/except blocks, which would improve things quite alot.E.g.:def handler_unity(res): if res.unity_deploy: print('Unity deploy') if res.unity_tagcheck: print('Unity tagcheck')def handler_clc(res): if res.clc_deploy: print('Clc deploy')...parser_unity.set_defaults(func=handler_unity)...parser_clc.set_defaults(func=handler_clc)...res.func(res)
_unix.213861
When I am running this code from my local wamp, it works fine and prints the result. //connection to a ftp server across proxyputenv('TMPDIR=/tmp/');$ftp_server = SERVER IP; $ftp_user_name = XXXXXX; $ftp_user_pass = XXXXXX;$destination_path = /sanketik/;$remote_file = $destination_path.$file;// set up basic connection$conn_id = ftp_connect($ftp_server);// login with username and password$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);// enabling passive modeftp_pasv( $conn_id, true );// get contents of the current directory$contents = ftp_nlist($conn_id, /sanketik);// output $contentsvar_dump($contents);Output:array (size=5) 0 => string '/sanketik/bittu' (length=15) 1 => string '/sanketik/mysql.png' (length=19) 2 => string '/sanketik/shakun' (length=16) 3 => string '/sanketik/shakun.txt' (length=20) 4 => string '/sanketik/TTTTT.txt' (length=19)But when I am running same code from my CentOS-based server it gives NULL.Thanks
Enable CentOS server to make FTP connections to other windows based server via php
centos;php;ftp
null
_unix.157419
I wrote this script #!/bin/bashif [ $# -ne 2 ] ; thenecho \n Usage : sh $0 BSSID interface \nexit 0;fiwhile true; doreaver -b $1 -i $2 -vv -N -g 10 -S -asleep 3603;donebut i got this messages :bash T.shT.sh :line 2: $'\r':command not foundT.sh :line 10: $'\r':command not foundT.sh :line 27: syntax error near unexpected token 'done'T.sh: line 27: 'done'
Bash : syntax error near unexpected token ' done '
shell script
Script looks okay. If you had edited/created this on a windows machine and copied to *nix, a 'dos2unix' will fix this. dos2nix T.shInstall the 'dos2unix' rpm if 'dos2unix' returns a 'command not found' message.
_unix.70408
I can not load my saved iptables rules when the server reboots on Arch Linux. Any ideas? The latest Arch updates are in place.I have followed Arch Linux's tutorial... neither either works. The following do work via the prompt as root user: 1. iptables-save & restore /usr/sbin/iptables-restore < /etc/iptables/iptables.rules2. rc.drc.d start iptables I have even attempted to run below as a cron on root with no joy:@reboot /usr/bin/bash /usr/sbin/iptables-restore < /etc/iptables/iptables.rules > /home/me/boot-iptables.logSurely I am missing something... everyone must be doing this*?*By 'this' I mean wanting privileged port 80 going to 8080. I am going the wrong route for the simplest, cleanest way to do so? Everything was so good till now PacMan.
Can't save / load iptables rules on Arch Linux via rc.d
iptables;arch linux
The problem is that the tutorial you followed is written with systemd in mind.As you are still using the old init system you have to add iptables to the DAEMONS array in your rc.conf.Please be aware that the next update to the iptables package my drop the /etc/rc.d/iptables script.The old init has been deprecated for some time and is being purged from the wiki and the packages. Do yourself a favor and take the time for a clean migration.
_codereview.46959
I'm still new in Java so I always try to find new ways and improve my skills.I found enum in Java to be very powerful (maybe excessively?) and while I was reading Effective Java book I've had some great ideas and I thought about using it to improve the flexibility of a standard console application which asks to the user to select 1...x options and does actions with it (to avoid the problems to update indexes options every time you need to add/remove an option).Ok, to test it I've just created a small application which doesn't do anything special (add and remove elements from a Set in logic code)The application allows the user to add a contact, remove it and show all contacts.Main.javaThe main class of the application, show the menu and ask to the user to select an option and execute the selected option.Code:public class Main{ public static void main(String[] args) { Agenda agenda = new Agenda(); boolean result = true; while (result) { for (MENU_SCELTE scelte : MENU_SCELTE.values()) { System.out.println(scelte); } MENU_SCELTE scelta = chooseOption(); if (scelta == null) { System.out.println(Scelta non valida.); } else { result = scelta.perform(agenda); } } } /** * This method will create the menu * * @return True if the program should continue to create the menu; false otherwise. */ private static MENU_SCELTE chooseOption() { int userScelta; while (true) { try { userScelta = Integer.parseInt(Actions.bufferedReader.readLine()); break; } catch (IOException ignored) { } catch (NumberFormatException e) { System.out.println(Inserisci un numero valido.); } } return MENU_SCELTE.from(userScelta); }}MENU_SCELTE.javaMenuAction is an interface which declares only one method (perform) which executes the method.While it would be better to define it inside the MENU_SCELTE as abstract method I chose to use an interface for no reason... Maybe an interface would be better in a more serious scenario.A description of the action is passed to the constructor; the value (the number to write to execute the action) is calculated using ordinal() + 1 it could be read as a bad practice but I may be wrong, am I?public enum MENU_SCELTE implements MenuAction{ AGGIUNGI_CONTATTO (Permette di aggiungere un contatto) { @Override public boolean perform(Agenda agenda) { Actions.aggiungiContatto(agenda); return true; } }, RIMUOVI_CONTATTO (Permette di rimuovere un contatto) { @Override public boolean perform(Agenda agenda) { Actions.rimuoviContatto(agenda); return true; } }, ELENCO_CONTATTI (Elenca tutti i contatti) { @Override public boolean perform(Agenda agenda) { Actions.elencoContatti(agenda); return true; } }, ESCI (Chiude il programma) { @Override public boolean perform(Agenda agenda) { return false; } }; private static final EnumMap<MENU_SCELTE, Integer> map; private final int value; static { map = new EnumMap<MENU_SCELTE, Integer>(MENU_SCELTE.class); for (MENU_SCELTE scelte : values()) { map.put(scelte, scelte.value); } } private final String description; MENU_SCELTE(String description) { this.description = description; value = ordinal() + 1; } @Override public String toString() { return value + : + description; } public static MENU_SCELTE from(int code) { for (EnumMap.Entry<MENU_SCELTE, Integer> entry : map.entrySet()) { if (entry.getValue() == code) { return entry.getKey(); } } return null; }}MenuAction.javaI know the Javadoc is wrong.public interface MenuAction{ /** * Will be the action which should be executed when selected * * @return Returns true if the application can show again the menu; false if not. */ boolean perform(Agenda agenda);}Actions.javaHere is my main problem, the code inside the enum will start to be very big if I implement the code of the various actions inside the perform method so I created some static methods which contain the logic. Well, I don't like it really, it sounds like a strange solution. How could it be replaced?To avoid creating a new BufferedReader every time I used a static one.public class Actions{ public static final BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in)); public static void aggiungiContatto(Agenda agenda) { try { Contatto.Builder builder = new Contatto.Builder(); System.out.println(Inserisci il nome del contatto); // i don't care if he uses a bad name builder.setNome(bufferedReader.readLine()); System.out.println(Inserisci il cognome del contatto.); builder.setCognome(bufferedReader.readLine()); String phoneNumber; while (true) { try { System.out.println(Inserisci il numero di telefono); phoneNumber = bufferedReader.readLine(); // 20 - but could be 15? if (phoneNumber.length() < 20 && tryIsNumeric(phoneNumber)) { break; } else { System.out.println(Inserisci un numero valido.); } } catch (IOException ignored) { } } builder.setPhoneNumber(phoneNumber); if (agenda.add(builder.build())) { System.out.println(Contatto aggiunto!); } else { System.out.println(Contatto non aggiunto, gi presente.); } } catch (IOException e) {// e.printStackTrace(); } } public static void rimuoviContatto(Agenda agenda) { try { System.out.println(Nome contatto:); String nome = bufferedReader.readLine(); System.out.println(Cognome contatto:); String cognome = bufferedReader.readLine(); System.out.println(Numero di telefono:); String phoneNumber = bufferedReader.readLine(); if (agenda.remove(nome, cognome, phoneNumber)) { System.out.println(Contatto rimosso.); } else { System.out.println(Impossibile rimuovere il contatto.); } } catch (IOException e) { e.printStackTrace(); } } public static void elencoContatti(Agenda agenda) { Set<Contatto> contatti = agenda.getContatti(); if (contatti.size() == 0) { System.out.println(Nessun contatto.); } else { for (Contatto contatto : contatti) { System.out.println(contatto); } } } /** * Check if a String is a Number but doesn't convert it. * * It works checking if Long.parseLong thrown an NumberFormatException * @param string The string to check * @return True if the string contains only numbers; otherwise false. */ public static boolean tryIsNumeric(String string) { try { Long.parseLong(string); return true; } catch (NumberFormatException e) { return false; } }}Agenda.javaThis class is nothing special, it just keeps a List of Contatto.What about HashSet as collection? And the remove(String, String, String) method? Maybe I could use a foreach, since I will stop the loop after I've deleted it, so no ConcurrentModificationException should be thrown?public class Agenda{ private Set<Contatto> contatti; public Agenda() { contatti = new HashSet<Contatto>(); } public boolean add(Contatto contatto) { return contatti.add(contatto); } public void remove(Contatto contatto) { contatti.remove(contatto); } public boolean remove(String nome, String cognome, String phoneNumber) { Iterator<Contatto> iterator = contatti.iterator(); while (iterator.hasNext()) { Contatto contatto = iterator.next(); if (contatto.getNome().equals(nome) && contatto.getCognome().equals(cognome) && contatto.getPhoneNumber().equals(phoneNumber)) { iterator.remove(); return true; } } return false; } public Set<Contatto> getContatti() { return Collections.unmodifiableSet(contatti); }}Contatto.javaWhile i know hashCode method do useless checks (nome, cognome and phoneNumber will never be null so why check it?) It's a basic class.public final class Contatto{ public static class Builder { private String nome; private String cognome; private String phoneNumber; public Builder setNome(String nome) { if (nome == null) throw new IllegalArgumentException(nome == null); this.nome = nome; return this; } public Builder setCognome(String cognome) { if (cognome == null) throw new IllegalArgumentException(cognome == null); this.cognome = cognome; return this; } public Builder setPhoneNumber(String phoneNumber) { if (phoneNumber == null) throw new IllegalArgumentException(phoneNumber == null); this.phoneNumber = phoneNumber; return this; } public Contatto build() { return new Contatto(this); } } private final String nome; private final String cognome; private final String phoneNumber; private Contatto(Builder builder) { nome = builder.nome; cognome = builder.cognome; phoneNumber = builder.phoneNumber; } public String getNome() { return nome; } public String getCognome() { return cognome; } public String getPhoneNumber() { return phoneNumber; } @Override public boolean equals(Object obj) { if (obj instanceof Contatto) { Contatto contatto = (Contatto) obj; return contatto.phoneNumber.equals(phoneNumber) && contatto.nome.equals(nome) && contatto.cognome.equals(cognome); } return false; } @Override public int hashCode() { int result = nome != null ? nome.hashCode() : 0; result = 31 * result + (cognome != null ? cognome.hashCode() : 0); result = 31 * result + (phoneNumber != null ? phoneNumber.hashCode() : 0); return result; } @Override public String toString() { return nome + + cognome + ( + phoneNumber + ); }}The application works very well, but its design is terrible for me... how could it be improved?
Agenda test application for Enum
java;console;enum
Just a few random comments:For this:A description of the action is passed to the constructor; the value (the number to write to execute the action) is calculated using ordinal() + 1 it could be read as a bad practice but I may be wrong, am I?You might not want this to be calculated automatically. A maintainer might insert a new enum value in the middle of the other values which would break the existing hotkeys: code for the listing items menu was 3 but in a new release it's changed to 4. It could be frustrating to users.Mixing two languages in the code makes it harder to read and maintain. Maintainers have to remember which method/variable is in English and which one is in Italian. Using only one language requires less work.For this:Well, I don't like it really, it sounds like a strange solution. How could it be replaced?Another idea is creating a separate class for every Action and storing the available instances in a list/map.public interface Action { String getKeyCode(); void doAction() throws MenuExitException;}Usage:List<Action> actions = new Action<>();actions.add(new OpenAction());actions.add(new ExitAction());for (Action action: actions) { if (!action.getKeyCode().eqauls(pressedKey)) { continue; } action.doAction(); return;}// invalid actionNote the MenuExitException too (instead of the boolean return value). It's another way of exitting the application.The following pattern is in the code multiple times:if (nome == null) throw new IllegalArgumentException(nome == null);I'd use Guava's checkArgument method here (or create a similar one). With checkNotNull you can save another line (although it throws NullPointerException instad of IllegalArgumentException):this.nome = checkNotNull(nome, nome == null);You could use Objects.hash in the hashCode method.This assignment could be in the same line as the declaration:private Set<Contatto> contatti;public Agenda(){ contatti = new HashSet<Contatto>();}And it could be final:private final Set<Contatto> contatti = new HashSet<Contatto>();final would improve code readability since readers don't have to check whether it's is changed somewhere in the class or not.I would not restrict the phone number to have only numbers.If the user wants to give you his phone number, then trust him to get it right. If he does not want to give it to you then forcing him to enter a valid number will either send him to a competitor's site or make him enter a random string that fits your regex. I might even be tempted to look up the number of a premium rate sex line and enter that instead.Source: https://stackoverflow.com/a/1245990/843804Anyway, a named method (readPhoneNumber()) for the phone number reading logic would be easier to follow here.Instead of ignoring IOException log them. It could help debugging a lot. (Having does not work bug reports without any possible/available clue about what went wrong could harm you. Saying that you have no idea is not too professional.)Instead of if (contatti.size() == 0)the following would be more convenient:if (contatti.isEmpty())Furthermore, instead of this:if (contatti.isEmpty()){ System.out.println(Nessun contatto.);}else{ for (Contatto contatto : contatti) { System.out.println(contatto); }}you could use a guard clause to make the code flatten:if (contatti.isEmpty()) { System.out.println(Nessun contatto.); return;}for (final Contatto contatto: contatti) { System.out.println(contatto);}MENU_SCELTE.from refers to the value as code. It would be easier to read if both were called menuCode or something more descriptive.chooseOption() also could use a guard clause:private static MENU_SCELTE chooseOption() { while (true) { try { int userScelta = Integer.parseInt(Actions.bufferedReader.readLine()); return MENU_SCELTE.from(userScelta); } catch (IOException ignored) { } catch (NumberFormatException e) { System.out.println(Inserisci un numero valido.); } }}Referring to Actions.bufferedReader from Main seems too tightly coupled:userScelta = Integer.parseInt(Actions.bufferedReader.readLine());I would create it only once and pass it to the object instances which require it. It would also make testing easier (you can give them a mocked/fake reader) and make dependencies visible which is easier to work with (no surprises, you won't find a static method call/field access in the middle of another method, it will be clear which class requires which one at the beginning).I would also rename bufferedReader to something which reflects that it's reading from the stdin.
_unix.341532
I've got a home server with music files stored locally on said server.I've got MPD & ncmpcpp installed on this home server.I'm trying to prototype this so I can go the extra trivial step of forwarding ports so this can be accessed anywhere, but I'm having quite a bit of trouble even getting this to work locally. I'm working on a remote machine, but all the work I've done this morning has been in a remote shell inside the home server...I've killed and disabled the daemon for mpd, and started it like so:mpd --stdout --no-daemon --verbose ~/.config/mpd/mpd.conf and gotten this output:config_file: loading file .config/mpd/mpd.confpath: SetFSCharset: fs charset is:libsamplerate: libsamplerate converter 'Fastest Sinc Interpolator'vorbis: Xiph.Org libVorbis 1.3.5opus: libopus 1.1.4sndfile: libsndfile-1.0.27simple_db: reading DBcurl: version 7.52.1curl: with OpenSSL/1.0.2kavahi: Initializing interfaceavahi: Client changed to state 101avahi: Client is CONNECTINGstate_file: Loading state file /home/dale/.config/mpd/stateThe port appears to be doing something, or at least ready to do something for MPD:~ sudo netstat -lnp | sudo grep 8002tcp 0 0 127.0.0.1:8002 0.0.0.0:* LISTEN 21596/mpd However, when I run ncmpcpp (from within the same machine that is running MPD, the home server....remember, I'm ssh'ed in), I get the following complaint:ncmpcpp: Failed to resolve host nameI've got the following ~/.config/mpd/mpd.conf file:music_directory /mnt/media/Musicplaylist_directory ~/.config/mpd/playlistsdb_file ~/.config/mpd/databaselog_file ~/.config/mpd/logpid_file ~/.config/mpd/pidstate_file ~/.config/mpd/statesticker_file ~/.config/mpd/sticker.sql#mixer_type software# optsbind_to_address 127.0.0.1port 6601log_level defaultgapless_mp3_playback yesfilesystem_charset UTF-8# ioinput { plugin curl}audio_output { type alsa name My ALSA Device device hw:0,0 # optional mixer_type hardware # optional mixer_device default # optional mixer_control PCM # optional mixer_index 0 # optional}#audio_output {# type alsa# name audio#}audio_output { type fifo name visualizer path /tmp/mpd.fifo format 44100:16:2}audio_output { type httpd name My HTTP Stream encoder vorbis # optional bind_to_address 127.0.0.1 port 8002# quality 5.0 # do not define if bitrate is defined bitrate 128 # do not define if quality is defined format 44100:16:1 always_on yes # prevent MPD from disconnecting all listeners when playback is stopped. tags yes # httpd supports sending tags to listening streams.}`I've got this in my ~/.ncmpcpp/config file:ncmpcpp_directory = ~/.ncmpcpp#lyrics_directory = ~/.lyricsexternal_editor = /usr/bin/vim# MPD Settingsmpd_crossfade_time = 3mpd_music_dir = /mnt/media/Musicmpd_host = 127.0.0.1:8002mpd_port = 8002Any ideas which property(ies) I've misconfigured?Thanks
mpd httpd not responding to tcp port
networking;port forwarding;http;mpd
null
_cs.54217
I am trying to convert the follow language$$L = \{0^m1^n \ | \ 0 \le m \le n \le 2m\}$$We have an exam in 2 days and the professor didn't teach us much about PDA's. They will be on the test though and I am freaking out because I have no idea how to do them. Could anyone give me a hint or get me started on this example?
Converting a language to a PDA?
formal languages;regular languages;context free;pushdown automata
null
_softwareengineering.17100
The Single Responsibility Principle states that a class should do one and only one thing. Some cases are pretty clear cut. Others, though, are difficult because what looks like one thing when viewed at a given level of abstraction may be multiple things when viewed at a lower level. I also fear that if the Single Responsibility Principle is honored at the lower levels, excessively decoupled, verbose ravioli code, where more lines are spent creating tiny classes for everything and plumbing information around than actually solving the problem at hand, can result.How would you describe what one thing means? What are some concrete signs that a class really does more than one thing?
Clarify the Single Responsibility Principle
design;object oriented
I really like the way Robert C. Martin (Uncle Bob) restates the Single Responsibility Principle (linked to PDF):There should never be more than one reason for a class to changeIt's subtly different from the traditional should do only one thing definition, and I like this because it forces you to change the way you think about your class. Instead of thinking about is this doing one thing?, you instead think about what can change and how those changes affect your class. So for example, if the database changes does your class need to change? What about if the output device changes (for example a screen, or a mobile device, or a printer)? If your class needs to change because of changes from many other directions, then that's a sign that your class has too many responsibilities.In the linked article, Uncle Bob concludes:The SRP is one of the simplest of the principles, and one of the hardest to get right. Conjoining responsibilities is something that we do naturally. Finding and separating those responsibilities from one another is much of what software design is really about.
_codereview.104232
I have finished my first project using ASP.NET MVC. I did not have to wait long to realise I have essentially violated all possible codes of good programming. Well, experience comes with practice.One of the styles I completely missed was Dependency Injection Principle. It was far too late I could re-write the project and apply it.DI took me some time to understand. Based on this very simple project, I would like experience programmers to give me some reviews, whether I have sorted the DI correctly.This is a very simple task. I want to generate hashed texts based on password provided by users. I know I could sort this in couple of lines but I wanted to do something I could apply DI.I split the whole solution into two projects. The first project contains hashing algorithms, the second the main function to generate hashed text. I tried to lose all possible couplings based everything on interfaces.So, GeneratePassword.computetHashedPassword() uses injected object of HashingAlgorithm to make GeneratePassword independent to it. On the other hand, HashingAlgorithm using one of the System interfaces, System.Security.Cryptography.HashAlgorithm. This way I tried to make hashing algorithm also independent.class Program{ static void Main(string[] args) { IGeneratePassword gp; string password = propiotr; Console.WriteLine(By bew class:); gp = new GeneratePassword(new XAlgorithm(new SHA256Cng())); Console.WriteLine(string.Format({0,19}: {1}, HashedPassword, gp.GetHashedPassword(password))); Console.WriteLine(string.Format({0,19}: {1}, Password, gp.Password)); Console.WriteLine(string.Format({0,19}: {1}, Password Salt, gp.PasswordSalt)); Console.WriteLine(); }}Hashing Algorithmspublic interface IHashAlgorithm{ string GetHashedText(string text);}public class XAlgorithm : IHashAlgorithm{ private System.Security.Cryptography.HashAlgorithm sysHashAlgorithm; public XAlgorithm(System.Security.Cryptography.HashAlgorithm hashAlgorithm) { this.sysHashAlgorithm = hashAlgorithm; } public string GetHashedText(string text) { string hashedtext = getHashX(text); for (int i = 0; i < 255; i++) hashedtext = getHashX(hashedtext); return hashedtext; } private string getHashX(string text) { byte[] bytes = Encoding.Unicode.GetBytes(text); byte[] hash = sysHashAlgorithm.ComputeHash(bytes); string hashString = string.Empty; foreach (byte x in hash) { hashString += String.Format({0:x2}, x); } return hashString; }}public class MD5Algorithm : IHashAlgorithm{ public string GetHashedText(string text) { XAlgorithm ha = new XAlgorithm(new MD5Cng()); return ha.GetHashedText(text); }}public class Sha256Algorithm : IHashAlgorithm{ public string GetHashedText(string text) { XAlgorithm ha = new XAlgorithm(new SHA256Cng()); return ha.GetHashedText(text); }} PasswordEncryptionpublic interface IGeneratePassword{ string Password { get; set; } string HashedPassword { get; } string PasswordSalt { get; } string GetHashedPassword(string password);}public class GeneratePassword : IGeneratePassword{ private IHashAlgorithm hashAlgorithm; private string password; private string passwordSalt; private string hashedPassword; public string Password { get { return password; } set { this.password = value; } } public string HashedPassword { get { computetHashedPassword(); return hashedPassword; } } public string PasswordSalt { get { return passwordSalt; } } public GeneratePassword(IHashAlgorithm hashAlgorithm) { this.hashAlgorithm = hashAlgorithm; this.passwordSalt = getRandomString(25); } public string GetHashedPassword(string password) { this.password = password; return HashedPassword; } private void computetHashedPassword() { if (string.IsNullOrEmpty(this.password)) throw new ArgumentNullException(Cannot compute a hashed password for the empty property 'Password'); this.hashedPassword = hashAlgorithm.GetHashedText(this.password + this.passwordSalt); } private static string getRandomString(int number) { string chars = ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789; Random random = new Random(); return new string(Enumerable.Repeat(chars, number) .Select(s => s[random.Next(s.Length)]) .ToArray()); }}
Hashed texts based on user's passwords
c#;dependency injection
null
_webapps.31489
When I use the FB search bar it always finds groups or pages, etc. I want to search stuff my friends have posted... for instance I remember last week someone posted or commented on a post about a flood. But searching for flood finds all kinds of global FB stuff, not results relevant to my friends.Is this possible somehow, it kinda seems an obvious thing?
Search friends' posts on Facebook
facebook
According to Facebook, to search for relevant content posted by your friends, follow these steps:Enter a keyword into the Search Typeahead at the top of the page. Click on either the Search icon or the See more results for option from the drop-down menu. You will land in the All Results filter by default. Note: pressing enter after typing your query into Search Typeahead will take you to the first Search Typeahead result and not to the All Results Filter. To refine your search to show content only from your friends, select the Posts by Friends filter from the menu on the left side of the search results page. This will display search results exclusively from your friends.
_codereview.154487
Here is a design to achieve a simple model in Java which uses a Thread and has these features:Starting the thread with an initial valuePausing the threadResuming the thread with new valueStopping the threadRestrictions: Do not use already implemented java libraries (from the concurrent package).A similar question was asked on SO where I have answered with this code, but I want to get some review comments for the same.I defined an interface for the model:/** * * @author krishna.k * * This defines the methods for the model. * */public interface IResumable { /** * starts the model */ public void requestStart(); /** * requests the model to pause */ public void requestPause(); /** * requests the model to resume with new parameter * @param newParam */ public void resumeWithNewParam(int newParam); /** * terminate the model */ public void requestStop();}The concrete Model:public class ResumableModel implements IResumable { private Thread worker; private WorkerRunnable work; public ResumableModel(int initialValue) { work = new WorkerRunnable(initialValue); worker = new Thread(work); } @Override public void requestStart() { worker.start(); } @Override public void requestPause() { work.setPauseRequested(true); } @Override public void resumeWithNewParam(int newParam) { work.setNewParam(newParam); } @Override public void requestStop() { worker.interrupt(); } private static class WorkerRunnable implements Runnable { private int param; // we can have the variable of the type depending // upon // the requirement. private final Object lock = new Object(); private volatile boolean isPauseRequested = false; public void run() { synchronized (lock) { try { while (!Thread.currentThread().isInterrupted()) { while (isPauseRequested) { lock.wait(); } System.out.println(value of param is + param); } } catch (InterruptedException e) { e.printStackTrace(); } } } public WorkerRunnable(int param) { this.param = param; } private void setPauseRequested(boolean isPauseRequested) { this.isPauseRequested = isPauseRequested; } private void setNewParam(int param) { // double locking to prevent the calling thread from being locked // (if in running state without pause requested then calling thread // will be in indefinite wait state for acquiring the lock. if (isPauseRequested) { synchronized (lock) { if (isPauseRequested) { this.param = param; this.isPauseRequested = false; lock.notifyAll(); } else { // logger will be used in real application System.out.println(Need to pause first before setting a new param); } } } else { // logger will be used in real application System.out.println(Need to pause first before setting a new param); } } }}The testing driver code:public class Test { public static void main(String[] args) throws InterruptedException { IResumable resumable = new ResumableModel(10); resumable.requestStart(); //Current thread is Main thread Thread.currentThread().sleep(3000); // making the main thread sleep for 3 seconds. resumable.requestPause(); Thread.currentThread().sleep(3000); // again making the main thread sleep for 3 seconds. resumable.resumeWithNewParam(20); Thread.currentThread().sleep(3000); // again making the main thread sleep for 3 seconds. resumable.requestStop(); }}Please provide review comments and feedback. It will help me and the people to whom I tell this approach.
Model for starting a thread with an initial value, pausing, resuming with a new value and stopping a thread
java;multithreading
null
_unix.340752
I'm trying to build ecl on termux for my android phone. With termux /bin/sh does not exist. Sh is located at /data/data/com.termux/files/usr/bin/sh. When I run./configure ...make installI get errors saying make: /bin/sh: Command not foundhow do I make configure use the correct shell?
configure with nonstandard shell
shell;make;configure
null
_webmaster.56786
I have a blog on a subdomain technotes.tostaky.biz and I want to move it to a new URL: www.mytechnotes.biz. Of course, I want to redirect technotes.tostaky.biz to www.mytechnotes.biz.www.mytechnotes.biz has been set-up properly, but I am trying to figure what I should do for the redirect.Right now, I have two A records (www.technotes and technotes) pointing to the IP address of the root tostaky.biz URL server.I also have a permanent redirect (both www and non-www) from technotes.tostaky.biz to http://www.mytechnotes.biz/. When I open technotes.tostaky.biz in Chrome, I get a 404 The requested URL / was not found on this server. Thats all we know.I don't know what is causing this issue. Should I wait for propagation or do I need to modify my configuration? Should I use CNAMEs instead of A records?P.S: I forgot to mention that www.technotes.tostaky.biz redirects properly.
Changing subdomain url to new root url issue (404)
redirects;url;subdomain;cname
Apparently, my (blue) host was not modifying my .htaccess properly. I found the solution here.I used the following:RewriteEngine OnRewriteCond %{HTTP_HOST}%{REQUEST_URI} ^technotes.tostaky.biz/$ [NC,OR]RewriteCond %{HTTP_HOST}%{REQUEST_URI} ^www.technotes.tostaky.biz/$ [NC]RewriteRule ^(.*)$ http://www.mytechnotes.biz/$1 [r=301,nc]instead of:RewriteEngine onRewriteCond %{HTTP_HOST} ^technotes\.tostaky\.biz$ [OR]RewriteCond %{HTTP_HOST} ^www\.technotes\.tostaky\.biz$RewriteRule ^/?$ http\:\/\/www\.mytechnotes\.biz\/ [R=301,L]
_unix.340361
I need to group rows based on the first column then to calculate the summation of the values of all second row and the summation of the values of all third row.The second column should be calculated as following: 10:56 = 10*60 + 56 = 656 seconds.Input file: testing 00:34 123487 archive 00:45 3973 testing 09:16 800500 archive 10:10 100000Output: archive 655 103973 testing 590 923987
Group all rows based on the first column then calculate the total of the second and third columns
text processing;awk;sed
Golfed it down to a one-liner. Works fine on GNU awk 3.1.7. Other awk implementations might need the $2*60 replaced with substr($2,0,2)*60. (Expecting the likes of '09:16' to get interpreted as an integer value of 9 is stretching the rules a little.)awk '{a[$1]+=$2*60+substr($2,4);b[$1]+=$3}END{for(c in a){print c,a[c],b[c]}}'Giving output:archive 655 103973testing 590 923987Alternatively, a perl approach:perl -e 'while(<>){/(\S+) +(\d+):(\d+) (\d+)/;$a{$1}+=$2*60+$3;$b{$1}+=$4;}for(keys %a){print $_ $a{$_} $b{$_}\n}'
_unix.171847
When I change the shell appearance opacity it works fine but when I reboot Ubuntu again, the opacity is back to 0 and I have to configure it again.How can I save the Yakuake settings?I am using Ubuntu 14.04 Unity. I have Cinnamon too but in both of them the settings don't save.
Yakuake doesn't save shell setting
ubuntu;configuration
null
_softwareengineering.271248
I'm considering using parts of a GNU Affero General Public License v3 (GNU AGPL v3) licensed library in a commercial context, but we obviously can't afford to release our whole code-base. We would only need the library for a crawler-like step in the backend. If we use the library in the crawler to generate data and push it into a database, and have our web-app hosted by another program/process entirely that reads from the database, are we legally required to release any of our source code? The web-facing (distributed) code would not call the AGPL-v3 licensed code, only use it's generated output.Any insight is greatly appreciated!
Is using data generated using AGPL-v3 licensed code considered distribution?
licensing;commercial;agpl
null
_unix.107574
Firstly, before I explain my problem, I have referred to the question previously asked on Ask.Fedora about the libGL error, which can be seen here.I have been trying to play the game FTL - Faster Than Light, and I have been running into problems where the graphics perform extraordinarily poorly, and the sound keeps turning into a strange buzzing sound. Upon looking further, I noticed that my Terminal outputted the following message during the game's launch.libGL error: failed to load driver: swrastlibGL error: Try again with LIBGL_DEBUG=verbose for more details.After doing some further research, it would appear that this issue has affected multiple people on numerous distributions of Linux, all with different solutions. Below, I have provided as much information as I can to help diagnose my specific issue.This also seems to be similar to Bug 971437 on the Red Hat bug trackerWhen getting libGL debug info on glxinfo:$ LIBGL_DEBUG=verbose glxinfo | grep directlibGL: screen 0 does not appear to be DRI2 capablelibGL: OpenDriver: trying /usr/lib64/dri/tls/swrast_dri.solibGL: OpenDriver: trying /usr/lib64/dri/swrast_dri.solibGL: Can't open configuration file /home/jflory/.drirc: No such file or directory.libGL: Can't open configuration file /home/jflory/.drirc: No such file or directory.direct rendering: YesI have a feeling there is some sort of issue with my graphics card, because I am VERY new to Linux and I'm unsure about what I may need to properly be able to run games. Below, I have some of the numerous packages I have tried to install during this process.$ cat /etc/ld.so.conf.d/nvidia-lib64.confcat: /etc/ld.so.conf.d/nvidia-lib64.conf: No such file or directory$ cat /etc/ld.so.conf.d/nvidia-lib.confcat: /etc/ld.so.conf.d/nvidia-lib.conf: No such file or directory$ sudo yum install mesa-libglapiLoaded plugins: langpacks, refresh-packagekitPackage mesa-libglapi-9.2.5-1.20131220.fc20.x86_64 already installed and latest versionNothing to do$ sudo yum install xorg-x11-drv-nvidia-libs.i686Loaded plugins: langpacks, refresh-packagekitNo package xorg-x11-drv-nvidia-libs.i686 available.Error: Nothing to doI have installed a few more things across the course of the night, but none of them seemed to have done any good, so I don't think they are relevant.If any more information is needed, please let me know and I will provide. As a reminder, I am very new to Linux in general and I am still learning, so I am not the most familiar with all the different UNIX operations I am able to do.Here's a quick rundown of my system specs:$ uname -aLinux localhost.localdomain 3.12.5-302.fc20.x86_64 #1 SMP Tue Dec 17 20:42:32 UTC 2013 x86_64 x86_64 x86_64 GNU/Linux$ grep model name /proc/cpuinfomodel name : Intel(R) Core(TM) i3-3120M CPU @ 2.50GHzEdit #1I ran sudo yum install mesa-dri-drivers and it appeared it is already installed on my system. $ sudo yum install mesa-dri-driversLoaded plugins: langpacks, refresh-packagekitDropbox | 951 B 00:00 google-chrome | 951 B 00:00 updates/20/x86_64/metalink | 18 kB 00:00 updates | 4.6 kB 00:00 updates/20/x86_64/primary_db | 3.0 MB 00:06 updates/20/x86_64/updateinfo FAILED ftp://mirror.nexicom.net/pub/fedora/linux/updates/20/x86_64/repodata/updateinfo.xml.gz: [Errno 14] curl#56 - response reading failedTrying other mirror.(1/2): updates/20/x86_64/updateinfo | 309 kB 00:01 (2/2): updates/20/x86_64/pkgtags | 755 kB 00:23 Package mesa-dri-drivers-9.2.5-1.20131220.fc20.x86_64 already installed and latest versionNothing to doEdit #2After executing lspci -vvv -s 00:02.0, my output was the following:# lspci -vvv -s 00:02.000:02.0 VGA compatible controller: Intel Corporation 3rd Gen Core processor Graphics Controller (rev 09) (prog-if 00 [VGA controller]) Subsystem: Toshiba America Info Systems Device fa20 Control: I/O+ Mem+ BusMaster- SpecCycle- MemWINV- VGASnoop- ParErr- Stepping- SERR- FastB2B- DisINTx- Status: Cap+ 66MHz- UDF- FastB2B+ ParErr- DEVSEL=fast >TAbort- <TAbort- <MAbort- >SERR- <PERR- INTx- Interrupt: pin A routed to IRQ 16 Region 0: Memory at c8000000 (64-bit, non-prefetchable) [size=4M] Region 2: Memory at c0000000 (64-bit, prefetchable) [size=128M] Region 4: I/O ports at 4000 [size=64] Expansion ROM at <unassigned> [disabled] Capabilities: [90] MSI: Enable- Count=1/1 Maskable- 64bit- Address: 00000000 Data: 0000 Capabilities: [d0] Power Management version 2 Flags: PMEClk- DSI+ D1- D2- AuxCurrent=0mA PME(D0-,D1-,D2-,D3hot-,D3cold-) Status: D0 NoSoftRst- PME-Enable- DSel=0 DScale=0 PME- Capabilities: [a4] PCI Advanced Features AFCap: TP+ FLR+ AFCtrl: FLR- AFStatus: TP-
Issues with libGL on Fedora 20 - unable to load driver swrast?
linux;fedora;drivers;graphics
Original answer provided on Ask Fedora (source)Original commentAlso, please try adding i915.modeset=1 to kernel command line when booting (you should edit Fedora line in grub and add it to the end of linux/linux16/linuxefi line in the boot config, and then press F10), and then run glxinfo when booted.Also, I'd like to know what do you see when you boot Fedora? The Fedora logo which is being filled with white color, or 3 simple bars at the bottom of screen?UpdateAs can be seen in your last glxinfo output after adding i915.modeset=1 to kernel boot command line, your graphics driver has been loaded and is working successfully. Previously, it did not load at all and you were using a generic driver.However, this is actually a bug. Kernel should have been loading i915 driver automatically. Please report a bug about this issue with sufficient data at: https://bugzilla.redhat.com/enter_bug.cgi?product=Fedora If you don't, I can do it myself but they might need some data that I cannot provide. Thanks!Update 2To change kernel command line permanently, you can:If you don't want to run grun2-mkconfig to generate new configuration file, you should edit /boot/grub2/grub.cfg and add the command line option (the format is exactly like what you see when you edit boot entry on boot) to the Fedora menu entry items.Even if you go with the above solution, you might some day run grub2-mkconfig -o /boot/grub2/grub.cfg to create a new configuration file (which will completely overwrite /boot/grub2/grub.cfg so your changes to it will be lost). Therefore, I'd suggest to also edit /etc/default/grub and add i915.modeset=1 at the end of GRUB_CMDLINE_LINUX= line (but before the closing ); so that it'll become something like this:GRUB_CMDLINE_LINUX=vconsole.font=latarcyrheb-sun16 $([ -x /usr/sbin/rhcrashkernel-param ] && /usr/sbin/rhcrashkernel-param || :) rhgb quiet i915.modeset=1
_webapps.65484
I've got a google form with a checkboxes question: https://docs.google.com/forms/d/1ngHnWZlyZQ3RirL7X4rHj8_x9gLa_CvVyPiyLkUmQls/viewformI edited an option (to clarify it), and now the number of respondents who ticked that option has been reset to zero. I've tried a search and replace on the responses spreadsheet, but the summary still shows zero.Can I do something so that the old responses are counted in the summary?
Google Forms - Checkboxes - Edit Option
google drive;google forms
null
_softwareengineering.193643
I have a project where the customer requirement specifies a report and contains mathematical equations for the contents of some of the columns on that report. One of the columns on this report is a running total which starts at a opening value, and which 'should' remain at that opening value all the way down the report because the other stuff balances out. I.e. if something had gone missing, the value would change and the customer would see that there is a problem.The reason I quoted the 'should' in that last paragraph is because the spec defines an equation for this column, and I can mathematically prove that it cancels out to 'the value from the previous row'. In other words, the value will never ever change from the opening value.So my options are:Implement the equation as spec'd, I suspect the interpreter will not resolve the equation so there will be a performance hitDo some cancelling out, and implement the column value as 'value from the previous row'Send the question back up the chain to the customer and risk missing the deadline because of several days lost to bureaucracy and impromptu math 101 lessons to explain the difference between yeah, it'll never change, it's there just in case and it. will. never. change. I've pretty much decided what I'm going to do, but I thought it was an interesting question. What do you think is the professional thing to do?
Customer Requirements Contains Equations that Cancel to Nothing
math;specifications;customer relations;reporting
null
_hardwarecs.520
I'd like to use an Asus H81T motherboard for my next desktop, and wanted a fanless case for it. I found the Akasa Euler and Streacom FC8 and the FC8 is the clear winner since it gives me enough room to put 2 disks in the box as well as letting me include an optical drive.Problem is that looking at Streacom's system-build guide about where the CPU should be placed for FC8's heat-pipes to be usable, I get the impression that the Thin-ITX form used by the H81T puts the CPU too far from the backplate.Can someone confirm (or deny) that the FC8's heat pipes can be used with a Thin-ITX motherboard such as the H81T?Alternatively, what other cases would you recommend for a fanless system that can host a Thin-ITX motherboard and with room for an optical drive?
Can the Streacom FC8's heat pipes accomodate a Thin-ITX motherboard
case;mini pc
I ended up asking Streacom (what an idea, eh?) and they confirmed that the FC8 should work fine with Thin-ITX, such as the Asus H81T.I received my FC8 Alpha and can confirm that it happily accomodates Thin-ITX boards (I'm using an H81T, but Thin-ITX is sufficiently precisely defined that it should work for all Thin-ITX boards).
_unix.303751
So I been doing some research and I looks like my xrandr some issues. The problem is that I connect a hdmi monitor and it shows that is disconnected some how the port its not working properly.(I'm using manjaro)xrandr out put:Screen 0: minimum 8 x 8, current 1920 x 1080, maximum 32767 x 32767eDP1 connected primary 1920x1080+0+0 (normal left inverted right x axis y axis) 380mm x 210mm 1920x1080 60.03*+ 48.01 1400x1050 59.98 1600x900 60.00 1280x1024 60.02 1280x960 60.00 1368x768 60.00 1280x720 60.00 1024x768 60.00 1024x576 60.00 960x540 60.00 800x600 60.32 56.25 864x486 60.00 640x480 59.94 720x405 60.00 640x360 60.00 DP1 disconnected (normal left inverted right x axis y axis)HDMI1 disconnected (normal left inverted right x axis y axis)VGA1 disconnected (normal left inverted right x axis y axis)VIRTUAL1 disconnected (normal left inverted right x axis y axis)If you see it show as disconnected but the hdmi is connected.any way to solve this?
hdmi port not working manjaro
xrandr;dual monitor;manjaro
null
_webapps.1016
I'm looking for a website that when given a URL will show you a trace of all the information that is sent when communication with this domain (e.g. HTTP headers). Specifically, I want to see how URL redirects are handled: what type of redirect is used (e.g. 301 or 302) and to what URL it is redirected to.
Website that will let me run an HTTP Trace?
webapp rec
The Domain Dossier on CentralOps.net has a Service Scan option which does exactly that, among many other features.This is the result from stackexchange.com HTTP/1.1 200 OKConnection: closeDate: Thu, 01 Jul 2010 21:56:15 GMTServer: Microsoft-IIS/6.0X-Powered-By: ASP.NETX-UA-Compatible: IE=8X-AspNet-Version: 2.0.50727X-AspNetMvc-Version: 1.0Cache-Control: privateContent-Type: text/html; charset=utf-8Content-Length: 2121and from google.comHTTP/1.0 301 Moved PermanentlyLocation: http://www.google.com/Content-Type: text/html; charset=UTF-8Date: Thu, 01 Jul 2010 21:57:43 GMTExpires: Sat, 31 Jul 2010 21:57:43 GMTCache-Control: public, max-age=2592000Server: gwsContent-Length: 219X-XSS-Protection: 1; mode=block
_webmaster.24565
It seems like when you 301 a page A to page B, sometime google indexes page A, showing the url in the results, with the contents of page B?Google site:http://tinyurl.com/ to see some examplesIs this by design or a bug?How do I avoid it?
Google indexes 301 source, with the destination content
google search
null
_cs.70174
Background: This is to be seen in the context of formal languages, very beginner-level.My professor claims that concatenation is not distributive over intersection, meaning that $L \circ (L_1 \cap L_2) \neq (L \circ L_1) \cap (L \circ L_2)$ and $(L_1 \cap L_2) \circ L \neq (L_1 \circ L) \cap (L_2 \circ L)$.While it seems silly of me to doubt what he says, I personally have trouble explaining this to myself and am looking for a counter example.If I concatenate only with the intersection of $L_1, L_2$ it ought to be the same as concatenating first and then finding the duplicates, so to speak.
Why is string concatenation not distributive over intersection?
formal languages
When we say that concatenation doesn't distribute over intersection, we don't mean that $L(L_1\cap L_2) \neq LL_1 \cap LL_2$ for all languages $L,L_1,L_2$, but rather that this inequality holds for some $L,L_1,L_2$. Here is one example:$$L = \{a,aa\}, L_1 = \{a\}, L_2 = \{aa\}.$$In this case $L(L_1 \cap L_2) = \emptyset$ but $LL_1 \cap LL_2 = \{aaa\}$.
_webmaster.27880
I've got a super secure javascript downloader* that I wrote, and it usually works alright. But I noticed, while trying to download a 90 meg file with it on a client's machine that on IE7, it's getting hung up about 1/3rd of the way through. I've never tried to send a file that large through the iFrame and it works fine in other browsers. Is there a size restriction on files that IE7 can read in an iFrame? * It's really just a PHP line that sets header(location: http://someplace/downloadbigthing.exe); after it does some logging and verification.
Maximum file size for iFrame in IE7
php;iframe;download;headers;internet explorer 7
null
_unix.154891
I have a problem with find. It doesn't find *.sh files if I am in certain directory level. It does, however, find *.sql files./path$ cd do_not_upload/updates/1.1.1//path/do_not_upload/updates/1.1.1$ find . -path *.sh./run_pre_update/002.sh./run_pre_update/001.sh./run_post_update/001.sh/path/do_not_upload/updates/1.1.1$ find . -path *.sh./run_pre_update/002.sh./run_pre_update/001.sh./run_post_update/001.sh/path/do_not_upload/updates/1.1.1$ cd ../path/do_not_upload/updates$ find . -path *.sh./1.1.3/run_pre_update/002.sh./1.1.3/run_pre_update/001.sh./1.1.3/run_post_update/001.sh./1.1.1/run_pre_update/002.sh./1.1.1/run_pre_update/001.sh./1.1.1/run_post_update/001.sh/path/do_not_upload/updates$ cd ../path/do_not_upload$ find . -path *.sh./updates/1.1.3/run_pre_update/002.sh./updates/1.1.3/run_pre_update/001.sh./updates/1.1.3/run_post_update/001.sh./updates/1.1.1/run_pre_update/002.sh./updates/1.1.1/run_pre_update/001.sh./updates/1.1.1/run_post_update/001.sh/path/do_not_upload$ cd ../path$ find . -path *.sh/path$ find . -path *.sql./do_not_upload/updates/1.1.3/sql_migrations/002.sql./do_not_upload/updates/1.1.3/sql_migrations/001.sql./do_not_upload/updates/1.1.1/sql_migrations/002.sql./do_not_upload/updates/1.1.1/sql_migrations/001.sql$ find --versionfind (GNU findutils) 4.4.2/path$ stat do_not_upload/ File: do_not_upload/ Size: 60 Blocks: 0 IO Block: 4096 directoryDevice: 14h/20d Inode: 159862 Links: 3Access: (0775/drwxrwxr-x) Uid: ( 1000/ jorgee) Gid: ( 1000/ jorgee)Access: 2014-09-10 14:02:34.449376973 -0300Modify: 2014-09-10 13:54:13.805363567 -0300Change: 2014-09-10 13:54:13.805363567 -0300 Birth: -
Find doesn't want to find *.sh in certain level
shell;find;wildcards
On Unix-like systems, *.sh is a glob expression that is expanded by the shell and the results are passed as arguments to the program being invoked. If and only if there are no matching files will the glob expression be passed as-is. You should get in the habit of quoting wildcards if you want them to be passed to the program you're running.As an example, if you were to run find . -path *.sh from /path/do_not_upload/updates/1.1.1/run_pre_update/, the actual command being executed would be find . -path 001.sh 002.sh, which is almost certainly not what you want.Note that this differs from MS-DOS and related systems, where glob expansion is done (or not done) by the program being invoked.To prevent shell expansions, enclose the argument in double or even single quotes - that will pass it to the invoked program verbatim and thus let find do its own expansions:$ find . -path '*.sh'
_unix.193636
I'm very new to Linux, BTW. The ultimate goal for me is to run applications and their GUIs on a (Mac) computer from another computer. The first step is to just use SSH to access and control the computer using another computer and the terminal. This was working fine.The next step was to install XQuartz on the server and terminal to be able to see and use GUI on the other computer. Regular SSH control worked but not the GUI. Apparently, the DISPLAY variable was not set correctly and this was probably due to the fact that X11Forwarding was set to no in the sshd.config file. I changed it to yes; regular SSH still worked but the DISPLAY was still wrong and GUI did not appear. So, I read that I had to restart the SSH service and I found a way to do it:sudo launchctl unload -w /System/Library/LaunchDaemons/ssh.plistThis screwed something up, because now I can't even do regualr ssh control. I tried to both unload and load, this gives different error messages in the terminal:When I run (on the other computer):sudo launchctl load -w /System/Library/LaunchDaemons/ssh.plistI instantly get:ssh_exchange_identification: Connection closed by remote hostThen I tried to undo the damage:sudo launchctl unload -w /System/Library/LaunchDaemons/ssh.plistThen I, after some time (about 3 seconds), get:ssh: connect to host macpro-c10c8b.imt.liu.se port 22: Connection refusedWhat have I done, and how can I fix it?
My ssh server stopped working after I did something
ssh;x11;gui
null
_cs.48848
Since, I don't have strong algorithmic background my question may sound a litlle odd. Please correct me, if so.I have quite a large bitmap (~100 Million bits) (e.g. 100100101001010001001...010010). The bitmap is just an example, it doesn't have to start with 1 or end with 0. Now, I need to choose randomly any 0-bit from the bitmap and retrieve it's position. Memory is not an issue in my case, I can maintain a few copies of the bitmap, if necessary. But the acceptable complexity of the algorithm would be linear or O(n lnn) in the worst case. Couldn't you advice a direction to move to? I'll appreciate any advices or refernces to some related resources.
Choosing a random bit from a bitmap
algorithms;randomized algorithms;sampling
There is a simple $O(n)$ algorithm using the technique of reservoir sampling. Keep a currently selected element $x$ (initially, none). Go over all bits in the file in order. When seeing the $m$th zero, put it in $x$ with probability $1/m$. You can show (exercise) that the final contents of $x$ is a uniformly random zero from the file.If you are allowed preprocessing, you can store the locations of all zeroes in a new file, and then choose a uniformly random zero in $O(1)$ by choosing a uniformly random position in the list.Practically speaking, we expect bitmaps to contain a decent fraction of zeroes say at least 1%. This suggests querying uniformly random locations in the file until you reach a zero. The expected runtime of this algorithm is at most 100 random queries.
_cs.65494
Big data era, people say the big data systems must use the scalable data structures and store.I didn't get the point here. I need some examples.What are the good examples of (1) scalable and (2) non-scalable data structure respectively?Can any one give me an idea on it?
What are the examples of scalable and non-scalable data structures?
data structures
null
_cs.40964
Given a set $P$ of $k$ points in a plane. The Distance Variant problem: partition set $P$ into two subsets $P_{1}, P_{2}$ so you can maximize, $d(P_{1}, P_{2})$ = min $p \in P_{1}$ min $ q \in P_{2}$ $d(p,q)$, where$d(p,q)$ is the Euclidean distance between $p$ and $q$. So basically, $d(P_{1}, P_{2})$ is the smallest distance between $P_{1}$ and $P_{2}$.Let's say $G$ is a complete graph with vertex set $P$, and the edge $pq$ has weight $w(pq) = d(p,q)$.$T$ be the MST of $G$, $e$ be the edge in $T$ with the largest weight. Removing $e$ from $T$ would create two components $P_{1}, P_{2}$. Assume edge weights are distinct. $1.$ What I want to prove is that $d(P_{1}, P_{2}) = w(e)$. I think there must exist some type of lemma which is used to aid this proof. My intuition/attempt: well in $T$ I know by removing $e$ would create two components which separate both $P_{1}, P_{2}$, and what is truly separating these sets, are $e$. Because of this the only path from $P_{1}$ to $P_{2}$ and vice versa is through $e$. Because $e$ is the only path, then it must be smallest distance from $P_{1}$ to $P_{2}$.$2.$ Curveball, let's say $P^*_{1},P^*_{2}$ are optimal solutions, I also think it would possible to show that is $d(P^*_{1},P^*_{2}) \leq w(e)$, but I am unsure if it is actually possible. $3.$ Algorithm application: I can somewhat see how this problem can be solved in ${O}(n^2)$, but still debating on which algorithm truly fits.
Distance Largest Weight Edge in MST
algorithms;graphs
null
_softwareengineering.52151
I have a blog where users can post comments. When creating a comment, various things happen:creating the comment object, associations, persistingsending notification emails to post's author given his preferencessending notification to moderators given their preferencesupdating a fulltext database for search...I could put all this in the controller, but what if I want to reuse this code ? e.g. I would like to provide an API for posting comments.I could also put this in the model, but I wonder if I won't lose flexibility by doing so. And would it be acceptable to do all of this from the model layer ?What would you do ?
Models, controllers, and code reuse
design;object oriented;mvc
null
_softwareengineering.264067
Could anyone explain why short(100000) is -31072 as said in p.48 of java-notes.The article says that the value -31072 is obtained by taking the the 4 byte int 100000 and throwing away two of these bytes to obtain a short.The code in the article related to the question is:int A;short B;A = 17;B = (short)A;
Type Casting in Java
java
In Java, ints are stored using a 32-bit 2's complement representation and shorts with a 16-bit 2's complement representation.This means that an int with the value 17 will contain the bitpattern 00000000 00000000 000000000 00010001 and with the value 100000 it will contain the bitpattern 00000000 00000001 10000110 10100000.When converting these numbers to short, you need to stuff them in 16 bits. This is done by keeping the lower (right-most) 16 bits and throwing the rest away, as that preserves any value that can be represented in a short.The pattern for 17 becomes 00000000 00010001, which still is the number 17.The pattern for 100000 becomes 10000110 10100000. Here we have lost one bit that was actually needed for the representation of the number, so the value represented by the remaining bits is different. According to 16-bit 2'complement representation,the bitpattern 10000110 10100000 represents the number -31072.
_webapps.40477
I created a Group for a reunion and did not choose a administrator to run the group. Left it open for individuals in the group to add people. I accidentally removed myself from my group (duh) and requested to join again. Who will get this? and let me back in? The group was also removed from my page and I can not edit anything. I am waited to be added but not
Facebook Group re-join
facebook;facebook groups
null
_cs.77102
I have an equation $x = 3a+4b+2c+4d$, where $a$, $b$, $c$ and $d$ are nonnegative integers such that $a+b+c+d=5$.What algorithm can I use to calculate maximum value of $x$?
Partitioning a Number on the basis of an equation
algorithms
null
_webapps.1158
I get a lot of invitations via Facebook, but I keep track of my schedule with Google calendar. Is there any way to automatically import or sync my Facebook events to my Google calendar?
How can I import Facebook events into my Google calendar?
facebook;google calendar;sync;import
You can get an iCal link for your Upcoming Events (or Birthdays) that you can import into Google Calendar which will automatically stay up to date.In Facebook:Go to your Events.On the left sidebar, click CalendarGo to the lower right portion of the page, where you'll see a message with two links:Save the URL for the Upcoming Events link. (This will vary by browser/OS, but is generally something like right-click and Copy link address)The URL should be similar to:webcal://www.facebook.com/ical/u.php?uid=999999999&key=AbCDEf12345AAcd-f(Your actual uid and key values will be different, of course.)In Google Calendar:Scroll down and open the Other calendars menu (on the left)Choose Add by URLPaste the webcal URL in the URL space then Add CalendarYou should now have a calendar {Your Name}'s Facebook Events listed under Other Calendars and can change the color, details, etc. as needed.See also: Facebook Help - How do I export my events or friends' birthdays?
_codereview.93302
I am using the following method to validate if user has given any input or left an EditText empty. I am concerned about the return statement in particular, because my IDE keeps complaining about it.Environment: Android Studio 1.0 public void clientsideauth() { if (TextUtils.isEmpty(edt_name.getText().toString().trim())) { onShake(edt_name, Please enter a valid name); return; } else { name = edt_name.getText().toString().trim(); } if (isValidEmail(edt_email.getText().toString().trim())) { email = edt_email.getText().toString().trim(); } else { onShake(edt_email, Please enter a valid email ID); return; } if (((edt_password.getText().length() < 6) || (TextUtils.isEmpty(edt_password.getText().toString().trim())))) { onShake(edt_password, Password must be at least six characters long); return; } else { pwd = edt_password.getText().toString().trim(); } if (TextUtils.isEmpty(edt_password1.getText().toString().trim())) { onShake(edt_password1, Not valid); return; } else { pwd1 = edt_password1.getText().toString().trim(); } if (pwd.equals(pwd1)) { startbackgroundtask(formBased); } else { onShake(edt_password, Passwords do not match); onShake(edt_password1, Passwords do not match); return; } }The return type of the method is void, because I don't want any return from this, I only want to stop execution if validation fails. However my IDE complains about the last return statement in the last if-else construct. I am wondering if I should in fact change the return type from void to boolean and maintain an array value for each form field. Later on I can check if all the array values are true or not. The above function gets called on the Submit button and is further processed to the server.
Validating multiple EditText fields
java;android;client
The warning is trying to tell you that the return is pointless,because it's the last statement anyway.Here's a better way to rewrite that,which will make the warning naturally go away:if (!pwd.equals(pwd1)) { onShake(edt_password, Passwords do not match); onShake(edt_password1, Passwords do not match); return;} startbackgroundtask(formBased);I simply inverted the condition, and removed the else branch.If you think about it, all the else branches are unnecessary when the if branch returns. You can apply this to all the conditions in the posted code.Many of your conditions handle the invalid case in the if and the normal case in the else, but not all.It would be better to consistently handle the invalid case first everywhere,and use early returns so you can get rid of the else. Like this: if (TextUtils.isEmpty(edt_name.getText().toString().trim())) { onShake(edt_name, Please enter a valid name); return; } name = edt_name.getText().toString().trim(); if (!isValidEmail(edt_email.getText().toString().trim())) { onShake(edt_email, Please enter a valid email ID); return; } email = edt_email.getText().toString().trim(); if (((edt_password.getText().length() < 6) || (TextUtils.isEmpty(edt_password.getText().toString().trim())))) { onShake(edt_password, Password must be at least six characters long); return; } pwd = edt_password.getText().toString().trim(); if (TextUtils.isEmpty(edt_password1.getText().toString().trim())) { onShake(edt_password1, Not valid); return; } pwd1 = edt_password1.getText().toString().trim(); if (!pwd.equals(pwd1)) { onShake(edt_password, Passwords do not match); onShake(edt_password1, Passwords do not match); return; } startbackgroundtask(formBased);Notice that the code contains many duplicated logic, for example here,the code to extract and clean edt_name is written twice: if (TextUtils.isEmpty(edt_name.getText().toString().trim())) { onShake(edt_name, Please enter a valid name); return; } name = edt_name.getText().toString().trim();It would be better to rewrite without duplication, like this: String cleanedName = edt_name.getText().toString().trim(); if (cleanedName.isEmpty()) { onShake(edt_name, Please enter a valid name); return; } name = cleanedName;I also removed TextUtils.isEmpty, which was either a bug or pointless:It's a bug if edt_name can be null, or if edt_name.getText() might return null: in both of these cases you will get a NullPointerExceptionIf there won't be nulls, then you don't need TextUtils, you can use isEmpty method of StringThere are several elements of poor coding style:Variable names and method names should be camelCase, not like edt_name or clientsideauthpwd and pwd1 are also poorly named, since pwd is the first password and pwd1 is the second. pwd1 and pwd2, or even pwd and pwdConfirmation would have been even better.The clientsideauth method is doing too much:Validate inputIf successful, start background taskIt mutates variables defined outside the methodInstead of mutating variables defined outside,it would be better to validate,collect the cleaned values in local variables,and then pass these variables to the authentication task.Since you do .getText().toString().trim() so often,a helper method to do this for you would be a good idea,to reduce your typing and the noise for readers.
_unix.206632
I have a bash script which downloads images from Google Images.This is the command I use:bash getimages.sh 3 rocky%20mountainsThat command will download the 3rd picture in Google Images. To download the first 10 pictures of the Rocky Mountains in Google Image Search I use the following amateurish command:bash getimages.sh 1 rocky%20mountains && \ bash getimages.sh 2 rocky%20mountains && \ bash getimages.sh 3 rocky%20mountains && \ bash getimages.sh 4 rocky%20mountains && \ bash getimages.sh 5 rocky%20mountains && \ bash getimages.sh 6 rocky%20mountains && \ bash getimages.sh 7 rocky%20mountains && \ bash getimages.sh 8 rocky%20mountains && \ bash getimages.sh 9 rocky%20mountains && \ bash getimages.sh 10 rocky%20mountainsI want a For Loop incorporated into the bash script so that it will download 20 images of a designated search term.Bash Script:#! /bin/bash# function to create all dirs til file can be madefunction mkdirs { file=$1 dir=/ # convert to full path if [ ${file##/*} ]; then file=${PWD}/${file} fi # dir name of following dir next=${file#/} # while not filename while [ ${next//[^\/]/} ]; do # create dir if doesn't exist [ -d ${dir} ] || mkdir ${dir} dir=${dir}/${next%%/*} next=${next#*/} done # last directory to make [ -d ${dir} ] || mkdir ${dir}}# get optional 'o' flag, this will open the image after downloadgetopts 'o' option[[ $option = 'o' ]] && shift# parse argumentscount=${1}shiftquery=$@[ -z $query ] && exit 1 # insufficient arguments# set user agent, customize this by visiting http://whatsmyuseragent.com/useragent='Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:38.0) Gecko/20100101 Firefox/38.0'# construct google linklink=www.google.com/search?q=${query}\&tbm=isch# fetch link for downloadimagelink=$(wget -e robots=off --user-agent $useragent -qO - $link | sed 's/</\n</g' | grep '<a href.*\(png\|jpg\|jpeg\)' | sed 's/.*imgurl=\([^&]*\)\&.*/\1/' | head -n $count | tail -n1)imagelink=${imagelink%\%*}# get file extention (.png, .jpg, .jpeg)ext=$(echo $imagelink | sed s/.*\(\.[^\.]*\)$/\1/)# set default save location and file name change this!!dir=$PWDfile=google image# get optional second argument, which defines the file name or dirif [[ $# -eq 2 ]]; then if [ -d $2 ]; then dir=$2 else file=${2} mkdirs ${dir} dir= fifi # construct image link: add 'echo ${google_image}'# after this line for debug outputgoogle_image=${dir}/${file}# construct name, append number if file existsif [[ -e ${google_image}${ext} ]] ; then i=0 while [[ -e ${google_image}(${i})${ext} ]] ; do ((i++)) done google_image=${google_image}(${i})${ext}else google_image=${google_image}${ext}fi# get actual picture and store in google_image.$extwget --max-redirect 0 -qO ${google_image} ${imagelink}# if 'o' flag supplied: open image[[ $option = o ]] && gnome-open ${google_image}# successful execution, exit code 0exit 0
For Loop for Google Image Downloading Bash Script
shell script;images;download;for
Why do you want to incorporate it in the script when you can run the command in loop itself: for i in `seq 1 20`; do ./getimages.sh $i rocky%20mountains ; done;However, if you really do want to incorporate, a quick way is to move the main script code inside another function and write a for loop to invoke that function. Your bass script would then become: #! /bin/bash# function to create all dirs til file can be madefunction mkdirs { file=$1 dir=/ # convert to full path if [ ${file##/*} ]; then file=${PWD}/${file} fi # dir name of following dir next=${file#/} # while not filename while [ ${next//[^\/]/} ]; do # create dir if doesn't exist [ -d ${dir} ] || mkdir ${dir} dir=${dir}/${next%%/*} next=${next#*/} done # last directory to make [ -d ${dir} ] || mkdir ${dir}}function getMyImages { # get optional 'o' flag, this will open the image after download getopts 'o' option [[ $option = 'o' ]] && shift # parse arguments count=${1} shift query=$@ [ -z $query ] && exit 1 # insufficient arguments # set user agent, customize this by visiting http://whatsmyuseragent.com/ useragent='Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:38.0) Gecko/20100101 Firefox/38.0' # construct google link link=www.google.com/search?q=${query}\&tbm=isch # fetch link for download imagelink=$(wget -e robots=off --user-agent $useragent -qO - $link | sed 's/</\n</g' | grep '<a href.*\(png\|jpg\|jpeg\)' | sed 's/.*imgurl=\([^&]*\)\&.*/\1/' | head -n $count | tail -n1) imagelink=${imagelink%\%*} # get file extention (.png, .jpg, .jpeg) ext=$(echo $imagelink | sed s/.*\(\.[^\.]*\)$/\1/) # set default save location and file name change this!! dir=$PWD file=$1_$count # get optional second argument, which defines the file name or dir if [[ $# -eq 2 ]]; then if [ -d $2 ]; then dir=$2 else file=${2} mkdirs ${dir} dir= fi fi # construct image link: add 'echo ${google_image}' # after this line for debug output google_image=${dir}/${file} # construct name, append number if file exists if [[ -e ${google_image}${ext} ]] ; then i=0 while [[ -e ${google_image}(${i})${ext} ]] ; do ((i++)) done google_image=${google_image}(${i})${ext} else google_image=${google_image}${ext} fi # get actual picture and store in google_image.$ext wget --max-redirect 0 -qO ${google_image} ${imagelink} # if 'o' flag supplied: open image [[ $option = o ]] && gnome-open ${google_image} # successful execution, exit code 0 #exit 0}for i in `seq 1 $1`; do echo Downloading image $i getMyImages $i $2; done;To download the first 10 images, simply invoke is as previously: ./getimages 10 rocky%20mountains
_softwareengineering.231771
Below is a pseudo declaration for a multilevel inheritance.Base class ( protected int data)derived1 : virtual public base ( protected int data1 )derived2 : virtual public base ( protected int data2)derived3 : derived1,derived2 ( private int data3 )Main(){ base b; derived1 d1; derived2 d2; derived3 d3; } sizeof(b) // 4 which is correct as only int (4bytes) sizeof(d1) // 12 why not 8 -> 4(base) + 4(derived) sizeof(d2) // ??? whatever applies above should apply here sizeof(d3) // 24 why not 12 -> 4(base) + 4(derived1/derived2) + 4(d3).Does size also include virtual tables also. Again here there cannot be virtual table as no virtual function defined. Please help in clarifying my doubt.PS: What I have understood till now:Unless the function is declared virtual in base class, base *bptr; derived d; bptr = &d; bptr->fun(); // will call the base class function.But if the fun() is declared virtual then the above code will call derived class fun().
Size of objects during Multilevel inheritance
c++;object;multiple inheritance
null
_unix.105718
I am looking a simple way to lock my session in Xfce (Debian Unstable). I don't want to have to write my password at every wake-up but I want to be able to press to a shortcut (which launches a commandline) which asks for identification. The usage is to lock my laptop when I leave office for lunch. I want to press this shortcut before closing the screen (and so putting the laptop to suspend). If someone tries to wake it up, he will have to enter the password.
How to lock my session in Xfce?
xfce;suspend;lock
I found these methods on Ubuntu Forums in a thread titled: Thread: How do I lock the screen in XFCE?.excerpted from 2 of the answers in that threadMethod #1 - Keyboard shortcutOpen the settings manager > keyboard > shortcuts and you can see that the default shortcut to lock the screen is ctrl-alt-del. If you want to change it, click add on the left, type in a name for your list of shortcuts, (widen the window so you can see the whole thing) select xflock4 shortcut on the right and enter the new key combo.Method #2 - via command line $ xflock4Method #3 - xscreenlockMost of the time I use xscreenlock on a multitude of Linux distros. It's fairly ubiquitous.excerpt from developers websiteXScreenSaver is the standard screen saver collection shipped on most Linux and Unix systems running the X11 Window System. I released the first version in 1992. I ported it to MacOS X in 2006, and to iOS in 2012.On X11 systems, XScreenSaver is two things: it is both a large collection of screen savers; and it is also the framework for blanking and locking the screen.On MacOS systems, these screen savers work with the usual MacOS screen saving framework (X11 is not required).On iOS devices, it is an application that lets you run each of the demo modes manually.screenshot of main dialog    .There is a ton of screenshots of the various screensavers and Xscreensaver also provides screen locking as well.http://www.jwz.org/xscreensaver/screenshots/
_unix.157038
Due to the nature of Fedora licensing, it does not come with many propeitary software like adobe, flash, and codecs. So many Fedora users resort to using RPMFusion. My question is how safe is RPMFusion from a security prespective and has it had any history of ever being 0wn3d? How much trust can I put on the rpm builders in RPMFusion?I am aware every RPM package from RPMFusion is signed with their GPG keys and yum will verify (by default) the integrity of every package installed from RPMFusion.
Security of Fedora third party repo RPMFusion
fedora;security
null
_unix.89186
I want you help me how to organize my data by cutting in the following way. I have the input data as below.input.file:1 2 1 0.6007 0.1 0.3 0.2 0.7 0.7 0 2 0.3073 0.1 0.1 0.2 0.4 0.7 0.52 2 1 0.4022 0.1 0.3 0.2 0.7 0.7 0 2 0.5085 0.1 0.1 0.2 0.4 0.7 0.53 2 1 0.0029 0.1 0.3 0.2 0.7 0.7 0 2 0.9078 0.1 0.1 0.2 0.4 0.7 0.54 2 1 0.0692 0.1 0.3 0.2 0.7 0.7 0 2 0.8805 0.1 0.1 0.2 0.4 0.7 0.5My desired output file would look like this:out.file:1 2 0.6007 1 0.1 0.3 0.2 0.7 0.7 0 0.3073 2 0.1 0.1 0.2 0.4 0.7 0.52 2 0.4022 1 0.1 0.3 0.2 0.7 0.7 0 0.5085 2 0.1 0.1 0.2 0.4 0.7 0.53 2 0.0029 1 0.1 0.3 0.2 0.7 0.7 0 0.9078 2 0.1 0.1 0.2 0.4 0.7 0.54 2 0.0692 1 0.1 0.3 0.2 0.7 0.7 0 0.8805 2 0.1 0.1 0.2 0.4 0.7 0.5
how to select part of the row and pasting to form other file?
awk;copy paste
null
_unix.279451
I wonder, whether the whole traffic is redirected through port 22, if I create a SSH tunnel?For example if I create a tunnel to a remote pc joes-pc, will it be enough to open port 22 on joes-pc?ssh -R 5900:localhost:5900 guest@joes-pc
Port tunneling via ssh. Is the traffic redirected via port 22?
ssh tunneling
In summary, yes, ssh tunnels send all data across the port ssh is using (which is usually port 22).However, it only sends traffic specifically sent over the port you specify (5900 in your example above).The classic example of this is tunnelling web traffic, so that a local web browser uses the tunnel to reach destination web sites. In this instance, the local machine will do DNS lookups which do not go over the tunnel, before sending web traffic over the tunnel.In your example, yes, only port 22 is required, but just keep in mind that it relies on the application only using the specific port (5900) for all traffic, and if it does other stuff (like DNS lookups) they may go out from the localhost network, not the tunnel.
_unix.7769
Symlinking to a directory gives to different results with ls -l depending on whether I ln -s dir or ln -s dir/. But what's the actual difference, and which one should I prefer why?
Should I include a trailing slash / in a symlink to a directory?
directory;symlink
There's no difference. (There would be a difference if the target was not an existing directory.)The final slash might have ended up there because of shell completion: with some configuration, ln -s tarTabSpacelink completes to ln -s target/ link.
_softwareengineering.213423
I've read the flame wars over the use of spaces and tabs. When working with any markup language (when scope isn't very important and when pressing space 4 times is a PITA), I tend to minimize the tab width to just a space or two but I fluidly change to four full tabs for my other programming work.It is a matter of convenience most of the time and it only translates into real errors when sharing or mixing code. So why they don't just declare a format for optional overrides such as #tab = 2 at the beginning of a file? There would be no scoping issues and it could be handled with 2 lines of code.UpdateWhoa, I didn't explain myself very clearly: I only use editors that handle the tab/space conversion automatically. The only cogent point I can understand in the criticisms I have read regarding Pythons use of white space is how borked the space/tab convention becomes when sharing code.Perhaps my confusion about using 4 spaces is because of my prior life in the publishing industry and our use of tabs not as a unit of white space but an abstract element used to describe a document's structure, not the display. Substituting it with 4 spaces has more to do with Unix's shitty 8-space convention than it does with elegance. If Python standardized on using tabs by default we would eliminate the layer of abstraction (literal visual spaces -> abstract tab) that is getting lost when we leave IDE land and go to Usenet/chat/email land. I thought that #tab=2 would be a nice way to ensure that any differences originating due to convenience formatting wouldn't muck things up elsewhere.
Why doesn't Python just establish a format for declaring tab widths?
python;code formatting
null
_webmaster.49288
I have successfully masked the URL in Mediawiki. By using the following scripts in .htaccess and localsettings.php files in Mediawiki, i.e.:.htaccess:Options +FollowSymLinksRewriteEngine onRewriteCond %{REQUEST_FILENAME} !-fRewriteCond %{REQUEST_FILENAME} !-dRewriteRule ^(.*)/(.*)$ /mediawiki/index.php?title=$1&actions=$2 [L]Localsettings.php:$wgScriptPath = /lib/mediawiki;$wgArticlePath = /lib/mediawiki/$1/$2;It is working fine with required URL. But my problem is I want to consider the second parameter as a querystring for my pages. But I could not get the second parameter in my file. I tried with $wgrequest function but it is only giving the first parameter as title. I tried with $_REQUEST also, it is sometimes give the value of $_REQUEST['actions']. But many times not. I cant understand what is the problem.
Getting the masked URL values in Mediawiki
php;apache;htaccess;mod rewrite;mediawiki
null
_webmaster.65398
I have encountered a problem or atleast that's what I think, I have recently started an ec2 instance and I changed my A records at Godaddy to point to my new elastic ip and it worked fine and then I signed up to Route 53 and changed the name servers at Godaddy and imported the DNS zone file to Route 53 and it all worked fine, but for some reason when I do whois search for my domain I get Godaddy's ip address, but my site loads fine.Here is the link for whois records: http://goo.gl/a3z0MIThe reason this question aries in my mind is because I have seen other site's whois with ec2 and route 53 and they seem to be normal here is the example: http://goo.gl/lPE8OYThanks in advanceAnkit Yadav
DNS and Whois problem
dns;whois;amazon ec2;route53
null
_webmaster.65808
I have to transfer ~6GB of data from my server to another which I don't own.On my server I have ssh access, and I have SFTP console client. The thing is, other server only supports plain old FTP and I can't connect to it using SFTP (at least I don't know how to do it, maybe it's possible).So does SFTP also support plain FTP connection or is there another utility on cPanel server I could use?I have tried to use php script to copy file by url but target server ran out of memory (only damn 64MB)
cPanel ssh ftp application to transfer files to another server
cpanel;ftp;transfer;files
null
_unix.166341
I have a file called file1 I want in a script, whenever there is a change in it, do something, a beep sound actually. How do I do that ? Thank you in advance
Constantly check if file is modified bash
linux;bash;shell script;files;monitoring
null
_softwareengineering.310942
Situation: I've recently joined a new project, and I've quickly noticed that the team is very keen on keeping the code flexible. It seems that for each class or function, they don't want to prevent the users of this framework from using things however they want. As such, the team wants to provide multiple ways of doing the same thing.Example: One class requires that the user provide a render callback function. The class has a function each for accepting an interface or free function, and third template function that takes an object and pointer-to-member function. Another class repeats this pattern and has ~13 render-type functions and other suspicious looking use functions and so on.This philosophy is duplicated through the rest of the code. Many classes have multiple ways of doing the same thing for your convenience. The rationale is we don't want to make extra work for the user to force them to conform.My response: This is a very bad philosophy with tangible negative effects.Code/responsibility duplication galoreBugs. I can see them coming. I've already found some due to the duplication.Confusing to new users. Why are there 13 slightly different render functions? Do they so the same thing? What's the purpose of using this one vs that one?Confusing to future devs - same reasons as above.Difficult to maintain - changing the render function means actually changing multiple render-type functions.Design takes far too long. We've spent weeks on a single UML chart of ~15 squares because keeping everything flexible makes things muddled and unclear. It's often But what if it needs to do this? or I see, but when would we actually use this?My general spidey senses tell me to be horrified.Question: Am I right in arguing that this flexible philosophy is very bad design? If so, how should I convince them that making n different ways to do every potential task is not doing the user any favors and is only making the code, in so many words, bad?
Flexibility - Multiple ways for users to do the same thing
design
null
_cs.13675
While reading the paper Holistic twig joins: optimal XML pattern matching I came across the pseudo code for liststack algorithm. (available through google scholar)A function in the algorithm confused me, since I can understand what it is supposed to do, but can't deconstruct the notation:$\qquad \mathtt{Function}\ \mathtt{end}(q\mathtt) \\ \qquad\qquad \mathtt{return}\ \forall q_i \in \mathtt{subtreeNodes}(q) : \mathtt{isLeaf}(q_i) \implies \mathtt{eof}(T_{q_i})$This function is supposed to return a single boolean result. It is supposed to be true when all lists associated to leaf nodes of a query pattern node are at their end. So true means there are no more nodes in the query pattern to process.But what is the meaning of the set builder(ish?) notation here? Is it $\qquad$ for all subtree nodes of $q$ for which $\mathtt{isLeaf}(q_i)$ is true $\mathtt{eof}(T_{q_i})$ is also true(which means that the list is at the end position)? Or is it $\qquad$ for all subtree nodes of $q$, $\mathtt{isLeaf}(q_i)$ implies $\mathtt{eof}(T_{q_i})$ is true? Is double arrow representing implies with its truth table? As you can see, I'm having a bit difficulty in associating the colon and its precedence.
What is the meaning of this pseudo-code function?
algorithms;terminology
Let us abstract what you have there to$ \renewcommand{\models}{\mathop{|\!\!\!=}}\newcommand{\rmodels}{\mathop{=\!\!\!|}} \newcommand{\semeq}{\models\!\rmodels}$$\qquad \mathtt{return}\ \forall x \in X.\, P(x) \implies Q(x)$.For evaluation, remember that$\qquad A \implies B \quad \models\!\rmodels \quad \lnot A \lor B$.What this means is that you return true if and only if for all $x$ it is true that$\qquad$whenever $P(x)$ holds, then $Q(x)$ holds.In your example, that translates to$\qquad$ return true if all subtree nodes that are leaves have also reached the end of their respective files.This is exactly what you expected, up to semantics of the eof function.It is supposed to be true when all lists associated to leaf nodes of a query pattern node are at their end.Note that the only other way to apply operator precendences, i.e.$\qquad \mathtt{return}\ \bigl(\forall x \in X.\, P(x)\bigr) \implies Q(x)$,does not make sense: in the term $Q(x)$, variable $x$ is not bound and there is no global interpretation shadowed by the $\forall$, so it's free. Hence, the term does not have a (fixed) truth value.
_softwareengineering.327908
Given an array of numbers, count the total number of subarrays (consecutive elements) where all elements are equal.Example: For below array [1,1,3]Ans: 4Below are desired subarrays:[1], [1], [3], [1,1]So I first wrote a Java program whose efficiency is bad:import java.util.*;public class EqualSubarrays { public static void main(String[] args) { int count = 0; Integer[] arr = {1,1,3}; List<Integer> list = new ArrayList<Integer>(Arrays.asList(arr)); for(int i=1; i<=arr.length; i++) { for(int j=0; j<=arr.length-i; j++) { if(areAllElementsEqual(list.subList(j, j+i))) count++; } } System.out.println(count); } static boolean areAllElementsEqual(List<Integer> list) { if (list.size()==1) return true; if (Collections.frequency(list, list.get(0))==list.size()) return true; else return false; }}And then, I thought of it with more simplicity and wrote a program in Python (can be written in any language though). Here it is:def count_equal_subarrays(nums): n = len(nums) total = 0 i = 0 while i < n: count = 1 while i+1 < n and nums[i] == nums[i+1]: i += 1 count += 1 i += 1 total += count * (count + 1) / 2 return int(total)num_arr = [1, 1, 1, 1]print(count_equal_subarrays(num_arr))I wanted to know if there is a more efficient method or interesting approach. If you know, please explain as well if its complicated.
Finding total number of subarrays from given array of numbers with equal elements. Better approach
java;algorithms;python
null
_cs.10044
What data structure should I store my graph in to get the best performance from the Dijkstra algorithm?Object-pointer? Adjacency list? Something else?I want the lowest O(). Any other tips are appreciated too!
What graph data structure works fastest with Dijkstra's algorithm?
algorithms;data structures
Implementing Dijkstra's algorithm with a Fibonacci-heap gives $O(|E|+|V|\log |V|)$ time, and is the fastest implementation known. As for the representation of the graph - theoretically, Dijkstra may scan the entire graph, so an adjacency list should work best, since from every vertex the algorithm scans all its neighbors.
_softwareengineering.84886
I was wondering what the general best practice is for when you have multiple unit test fixtures testing different things that use the same file paths.My test files are in a directory tree with certain rules so currently I am reusing directory macros in each file, i.e.#define TYPE1FILE Type1Files/#define TYPE2FILE Type2Files/#define GENERIC_FILE generic/#define SPECIAL_FILE special/#define BAR1 TYPE1FILE GENERIC_FILE /foo.txt#define BAR2 TYPE1FILE SPECIAL_FILE /foo2.txt#define BAR3 TYPE2FILE GENERIC_FILE /foo.txt#define BAR4 TYPE2FILE SPECIAL_FILE /foo2.txtHowever, this is starting to cause duplication in multiple files because multiple test fixtures will use the same:#define BAR1 TYPE1FILE GENERIC_FILE /foo.txtif they both use the same file.Also, it seems like it may be better to give them some scope by using variables inside the fixture or at least within the file.I like being able to see a list of what files are being used for each test, but I am also considering moving the BAR defines all into a shared header file. I am not crazy about that idea because it will end up being a giant list of files without any indication of what is used where. Also it couples the test cases together more.Does anyone have any suggestions?
Best practice for shared files within multiple unit test fixtures
c++;c;unit testing
null
_unix.294180
If I disable memory overcommit by setting vm.overcommit_memory to 2, by default the system will allow to allocate the memory up to the dimension of swap + 50% of physical memory, as explained here.I can change the ratio by modifying vm.overcommit_ratio parameter.Let's say I set it to 80%, so 80% of physical memory may be used.My question are: what the system will do with the remaining 20%?why is this parameter required in first place?why I should not always set it to 100%?
Where the remaining memory of vm.overcommit_ratio goes?
linux;kernel;memory;out of memory
What the system will do with the remaining 20%?The kernel will use the remaining physical memory for its own purposes (internal structures, tables, buffers, caches, whatever). The memory overcommitment setting handle userland application virtual memory reservations, the kernel doesn't use virtual memory but physical one.Why is this parameter required in first place?The overcommit_ratio parameter is an implementation choice designed to prevent applications to reserve more virtual memory than what will reasonably be available for them in the future, i.e. when they actually access the memory (or at least try to). Setting overcommit_ratio to 50% has been considered a reasonable default value by the Linux kernel developers. It assumes the kernel won't ever need to use more than 50% of the physical RAM. Your mileage may vary, the reason why it is a tunable.Why I should not always set it to 100%?Setting it to 100% (or any too high value) doesn't reliably disable overcommitment because you cannot assume the kernel will use 0% (or too little) of RAM.It won't prevent applications to crash as the kernel might preempt anyway all the physical memory it demands.
_softwareengineering.138614
I am developing a software system (Patient Administration System) and I have noticed it already had 451 lines of code(in one namespace). Is this bad? Or does the number of lines of code not matter as long as the methods and comments are useful and they doing what they are intended to do? Or there is a number of lines of code to maintain like a namespace should only have 500 lines of code something like that
Is there a certain number of lines of code to be followed /maintain?
c#;.net;programming practices
null
_softwareengineering.275957
When thinking of agile software development and all the principles (SRP, OCP, ...) I ask myself how to treat logging.Is logging next to an implementation a SRP violation?I would say yes because the implementation should be also able to run without logging. So how can I implement logging in a better way? I've checked some patterns and came to a conclusion that the best way not to violate the principles in a user-defined way, but to use any pattern which is known to violate a principle is to use a decorator pattern.Let's say we have a bunch of components completely without SRP violation and then we want to add logging.component Acomponent B uses AWe want logging for A, so we create another component D decorated with A both implementing an interface I.interface Icomponent L (logging component of the system)component A implements Icomponent D implements I, decorates/uses A, uses L for loggingcomponent B uses an IAdvantages:- I can use A without logging- testing A means I don't need any logging mocks- tests are simplerDisadvantage:- more components and more testsI know this seem to be another open discussion question, but I actually want to know if someone uses better logging strategies than a decorator or SRP violation. What about static singleton logger which are as default NullLogger and if syslog-logging is wanted, one change the implementation object at runtime?
Is logging next to an implementation a SRP violation?
design patterns;logging;single responsibility;decorator
Yes it is a violation of SRP as logging is a cross cutting concern.The correct way is to delegate logging to a logger class (Interception) which sole purpose is to log - abiding by the SRP.See this link for a good example:https://msdn.microsoft.com/en-us/library/dn178467%28v=pandp.30%29.aspxHere is a short example:public interface ITenantStore{ Tenant GetTenant(string tenant); void SaveTenant(Tenant tenant);}public class TenantStore : ITenantStore{ public Tenant GetTenant(string tenant) {....} public void SaveTenant(Tenant tenant) {....}} public class TenantStoreLogger : ITenantStore{ private readonly ILogger _logger; //dep inj private readonly ITenantStore _tenantStore; public TenantStoreLogger(ITenantStore tenantStore) { _tenantStore = tenantStore; } public Tenant GetTenant(string tenant) { _logger.Log(reading tenant + tenant.id); return _tenantStore.GetTenant(tenant); } public void SaveTenant(Tenant tenant) { _tenantStore.SaveTenant(tenant); _logger.Log(saving tenant + tenant.id); }}Benefits include You can test this without logging - true unit testingyou can easily toggle logging on / off - even at runtimeyou can substitute logging for other forms of logging, without ever having to change the TenantStore file.
_cogsci.11036
I am currently doing a research about computer games and in my experiment set up I need to asses each players gaming experience via Gaming Experience Questionnaire (GEQ). Is there any place I can obtain a sample GEQ and the scoring criteria ?
Where can I find Gaming Experience Questionnaire (GEQ) ?
experimental psychology;video games
null
_softwareengineering.189498
I have one one software system which allows developers to specify an ID or name to create NodeReferences. Both work fine, but ID's are not guaranteed to be the same across different environments. I've tried in documentation and in conversations to stress that ID's should not be hard coded (since they will break when deployed to a different environments), but some developers are still using them. This works only in dev environment:var level = LevelReference.ById(20);var node = NodeReference.ByName(level, _patientGuid.ToString());This works in all environments:var app = ApplicationReference.ByName(Reporting);var area = AreaReference.ByName(app, Default);var level = LevelReference.ByName(area, Patient);var node = NodeReference.ByName(level, _patientGuid.ToString());I think the appeal is just that it produces fewer lines of code. The use of ID's is not by itself bad (since there are valid use cases like caching the ID returned from the server and using it later for faster look-up), but hard-coded ID's are bad. Most of the time the first code will throw an exception, but it's possible that it could be a valid ID for a different object than the developer intended, and this could result in very bad problems.What's the best way to discourage the use of such constants in code? Ideally I'd like throw some kind of compiler error when I see code like the first example, or at least throw an exception before the call gets down to the database.
Prevent developers from using constants
c#;coding style;coding standards;teamwork
Hide the int ids in opaque objects/structs; var id = level.id;Here id is such a struct.This way you can remove the ById(int) method and replace it with ById(Id) and it still lets you keep the cashed Ids for future use.You can also create unique ID types for each reference type to ensure type safety (so you can't do NodeReference.ById(level.id)).
_webmaster.104454
I have a website and I don't want this website to be visible on Google. So I deployed a robots.txt file. But the homepage of the website is still visible on Google. Here is the full code of my robots.txt copy-pasted below-User-agent: *Disallow: /cgi-bin/Disallow: /private/Disallow: /tmp/Disallow: /_/Disallow: /cgi-bin/Disallow: /index.htmlDisallow: /imagesDisallow: /about.html
What's wrong with my robots.txt file to block Google?
robots.txt
If you don't want to allowed to crawl your website on Google search result, then use this robots.txtUser-agent: *Disallow: /These will block all directories.But if many website links to your website, then Google will start displaying this snippet in future.Now if you don't want to index that website competely, then use noindex meta-tags/HTTP headers. That meta tags simply no index your all pages, but it is allowed to crawl. So if your main concern is about to, not visible in search result, then I highly recommended to use noindex tags.But don't use it both, because when the site is blocked by robots.txt then Google will not going to see your meta-tags/http headers.
_codereview.15927
I have written a PDO wrapper and a class file like a model. It's looking good so far, but I'm just confuseed on where I should put the try/catch block. Would it be better to place it in the PDO wrapper (pdoDatabase.php), mobile.php (model) or test.php?pdoDatabase.phpclass pdoDatabase {public $db;private $sth;private static $instance;private $error;private function __construct() { $dsn = mysql:dbname= . config::read(db.database) . ;host=localhost; $username = config::read(db.username); $password = config::read(db.password); $this->db = new PDO($dsn, $username, $password); $this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);}public static function getInstance() { if (!isset(self::$instance)) { self::$instance = new static(); } return self::$instance;}public function fetchData($sql, $params = array(), $fetchMode = 'all') { // Should try...catch block be here? try { $this->sth = $this->db->prepare($sql); if (count($params) > 0) $this->setBind($params); $this->sth->execute(); $fetch = ($fetchMode == 'single') ? fetch : fetchAll; return $this->sth->$fetch(); } catch (PDOException $e) { $this->error = array( 'status' => 'error', 'message' => $e->getMessage() ); return false; }}public function setBind($params) { if (is_object($this->sth)) { foreach ($params as $key => $value) { $this->sth->bindValue(:$key, $value); } }}public function error() { return $this->error;}public function beginTransaction() { }public function commit() { }public function rollBack() { }mobile.phpclass Mobile { public $db; public function __construct() { $this->db = pdoDatabase::getInstance(); } public function findPhoneAffiliate($phoneId = null, $affiliateId = null, $affiliatePhoneId = null) { // or should try...catch block be here? $bindAr = array(); if ($phoneId !== null) $whereAr[] = phone_id = . $phoneId; if ($affiliateId !== null) $whereAr[] = 'affiliate_id = ' . $affiliateId; if ($affiliatePhoneId !== null) { $whereAr[] = 'affiliate_phone_id = :affiliate_phone_id'; $bindAr['affiliate_phone_id'] = $affiliatePhoneId; } $where = count($whereAr) > 0 ? 'WHERE ' . implode(' AND ', $whereAr) : ''; $sql = SELECT * FROM phone_affiliate $where; return $this->db->fetchData($sql, $bindAr, 'single'); }}test.php$mobileResult = $mobile->findPhoneAffiliate(null, 'f', ASEF33);if ($mobileResult) { // Data Found! print_r($mobileResult);} else { if ($mobile->db->error()) { print_r($mobile->db->error()); exit(); } if ($mobile->db->rowCount() == 0) echo Data Not Found;}As you can see, it will need to check if there any error or no data found in the else statement. Is this how it should be done? If now, what can be improved to reduce the code from the test.php sample?
Try/catch block in PDO wrapper
php;php5;exception handling;pdo
I'll probably revisit this later, but for now:The exception catching should be done at either the model or model-using layer. I would probably let the exceptions bubble up through the model unless you want the model to be fairly high level.For the sake of abstracting the DB layer away from the model layer, I might consider wrapping the PDOException in some kind of model exception(s). Exception wrapping is typically an anti-pattern, but it would keep your consuming code from needing to know that the models are all dependent on PDO. (Thus allowing you to change PDO to something else if you ever wanted to -- basically it's a weird instance of separation of concerns and hiding implementation details.)I'm starting to ramble, but what I'm trying to convey is that your consuming code needs to know something went wrong. If you handle the exception in your DB class, you model has no (pleasant) way to know that something went wrong. If you handle the exception in your model, the level above the model has no (pleasant) way to know something went wrong. Basically your consuming code needs to know something happened, and for that to be the case, you need exceptions to come out of the model. (An alternative would of course be returning a Boolean or something along those lines. That tends to not fit the OO paradigm very well though, and PDO sometimes uses Boolean false when something isn't an error.)Your pdoDatabase class shouldn't be a singleton.$this->db = pdoDatabase::getInstance(); you pass the pdoDatabase instance as a parameter instead of coupling your code to this static method.Dependency InjectionThere's a few other things that stuck out to me, but I'm out of time now ;(. Will come back later.Exception CatchingIt should be extremely rare for an exception to actually happen with your Mobile.Consider the sources of exceptions: connection drops, invalid syntax, unknown column/table/etc, so on. Basically there's different layers of exceptions. There's the connection oriented ones, and the SQL oriented ones. The SQL oriented ones should never happen. By the time your code goes into production, you should be certain that none of your queries have invalid syntax, reference non-existing entities, so on.This leaves connection problems as the only source of exceptions (or perhaps MySQL related hiccups, though those should be pretty rare).Because of this rarity, I would be tempted to basically ignore any exceptions.Even if you did handle the exceptions, what are you going to do with them?try { $affs = $mobile->findPhoneAffiliate(5);} catch (SomeExceptionClass $ex) { //There's not really a good way to recover from this, so you might as well //show some kind of Oops, something broke. page. //You could then log the exception behind the scenes and make sure the end-user //sees nothing sensitive.}What I would do in this situation is just let the exception bubble up to the very top. I would have a giant try/catch at the top layer though that intercepts any uncaught exceptions and renders some kind of error page.How you do this will highly depend on the structure of your website, but assuming you're doing something MVC-ish, it should be fairly simple. In the catch block, just kill the current dispatch, and instead dispatch a request for the exception page.
_unix.277276
On X window system (TWM) of my Ubuntu 12.04, xterm has width of 484 pixel and height of 316 pixel, and its geometry is 80x24, based on xwininfo.On X window system (TWM) of my LFS 7.9, xterm has with of 644 pixel and height of 388 pixel, and its geometry is 80x24, based on xwininfo.How can I configure xterm of LFS 7.9 so that its width by height size can be like Ubuntu 12.04? I like how Ubuntu xterm looks.
xterm width and height with regard to number of pixels NOT number of characters
x11;fonts;xterm
An XTerm's size is determined by the number of characters its displaying, the font it is using, and the size of the window manager decorations (title bar, outlines, etc.). You're probably using a different (larger) font on LFS. Ubuntu's xterm settings are probably in /etc/X11/app-defaults/{XTerm,XTerm-color} (at least that's where they are in Debian). You could copy them over, or at least the settings you want. [BTW: If you're not aware, XTerm has multiple fonts you can switch to via ControlRightClick and ControlShiftKeypad +/- (all bindings configurable).You can also do that on a per-user basis in your ~/.Xresources file and with xrdb.If you want to know what all the settings in the XTerm app-defaults mean, the xterm manpage actually documents them thoroughly.
_softwareengineering.148811
We have a repository of tables. Around 200 tables, each table can be thousands of rows, all tables are originally in Excel sheets.Each table has a different scheme. All data is text or numbers.We would like to create an application that allows free text search on all tables (we define which columns will be searched in each table) efficiently - speed is important. The main dilemma is which DB technology we should choose.We created a mock up by importing all tables to MS SQL Server, and creating a full text index over them. The search is done using the CONTAINS keyword. This solution works well for a small number of tables, but it doesn't scale.We thought about a NoSQL solution, but we don't yet have any experience in it.Our limitations (which unfortunately I can not effect): Windows servers only. But we can install on them whatever we want.
DB technology for efficient search in tabular data?
database;search
If you were to go the NoSQL route, or even if you weren't, I'd suggest looking at Lucene (also has a .NET implementation) for your indexing needs. It is a very high performance component and would actually yawn at the numbers you're quoting.If it's a little low level for you, look at RavenDb. It's a NoSQL solution that uses Lucene for its indexing. It's a .NET solution though (you never mentioned which language/platform you're using), if you are using .NET it really shines with its support for LINQ. I would consider another alternative (like MongoDB) if you're not using .NET because there aren't currently any RavenDB clients implemented for other platforms.I would say try them both if you have the time (it sounds like you're still in the prototyping stage of your application). There are advantages to each. As I mentioned, RavenDB really shines for a .NET application because of how deeply ingrained LINQ is in it's API. You define indexes using LINQ, you query with LINQ...it's really powerful stuff. MongoDB is older and can be used easily with other platforms if you have that need.Hope this helps.
_unix.287382
I have two ubuntu virtual machines running on my computer. I want to design an application that provides me with a window via which I can communicate with both machines without having to use the individual terminals. That is, as opposed to going back and forth between two terminal programs, I have one window that I can use to communicate to both (e.g., by toggling a button, the window will let me communicate with VM1, and by toggling it again, the same window will let me communicate with VM2). Is there a way I could do this? Or better still, is there a framework which already does this kind of thing?
Create an inetrface to two virtual machines
virtualbox;virtual machine
null
_unix.61880
I have a laptop, with installations of Ubuntu 12.10, and Windows 8.Windows 8 was first installed on the system, and Ubuntu was installed afterwards.During the Ubuntu installation, the installer recognized that there are existing partitions, but failed to see any OS on them. I created another ext4 partition in the free space, and installed Ubuntu. Initially grub only added the entry for Ubuntu, and Ubuntu works ok.Now I wanted to enter w8 settings to Grub manually, and modified /etc/grub.d/40_custom:#!/bin/bashexec tail -n +3 $0# This file provides an easy way to add custom menu entries. Simply type the# menu entries you want to add after this comment. Be careful not to change# the 'exec tail' line above.menuentry Windows 8 { insmod part_gpt insmod fat insmod search_fs_uuid insmod chain #set root='(hd0,gpt1)' search --fs_uuid --no-floppy --set=root --hint-bios=hd0,gpt2 --hint efi=hd0,gpt2 --hint-baremetal=ahci0,gpt2 chainloader /boot/efi/EFI/Microsoft/Boot/bootmgfw.efi}The search string (second to last) I found with this command: sudo grub-probe --target=hints_string /boot/efi/EFI/Microsoft/Boot/bootmgfw.efiNow after updating grub config, rebooting and selecting windows 8 entry, it complains: error: unspecified search typeerror: file '/boot/efi/EFI/Microsoft/Boot/bootmgfw.efi' not foundPress any key to continueIn Ubuntu however, if I do ls /boot/efi/EFI/Microsoft/Boot/b*/boot/efi/EFI/Microsoft/Boot/bootmgfw.efi/boot/efi/EFI/Microsoft/Boot/bootmgr.efi/boot/efi/EFI/Microsoft/Boot/boot.stl/boot/efi/EFI/Microsoft/Boot/bg-BG:bootmgfw.efi.muibootmgr.efi.muiNow, if I press e to edit the Windows 8 entry, and then select F2 to enter grub shell, indeed if I try to run ls /boot/efi, no files are shown.Funnily enough, if at this point I just type exit, windows 8 will boot up.fdisk -l gives me that it recognizes /dev/sda1 as GPT partitionAny ideas what I should do to get grub working right out of the menu?
Dual booting Ubuntu and Windows 8. w8 boots through grub shell, but not from menu
windows;dual boot;grub2;gpt;uefi
null
_cs.62413
I understand how neural networks that are implemented in software learn. You simply change the synaptic weights in the program. But how would you get a hardware implementation of neural networks to learn? The synaptic weights in the case of a physical system are INSIDE the machine, so how do you adjust the synapses? Do these neuromorphic systems require extra wires connected to every synapse (memristor etc.) in order to interface with traditional computers?
How would physical neural nets learn?
computer architecture;artificial intelligence;neural networks
null
_codereview.132326
I have the following script that reads JSONified data from within a DIV, generates HTML with values using JavaScript, then sends them to another DIV. What I'd like to improve is to remove HTML from JavaScript. Namely, not have HTML inside the JavaScript. I am not 100% on how to do this. I want minimal work but most separation of HTML and JS.var selection = eval(( + document.getElementById(result).innerHTML + ));/* * Relevant Example only: * selection[index].couplings = [{price:13.00,description:Couplings}]; *//** * Show Couplings */if (selection[index].couplings != null){ for (i = 0; i < selection[index].couplings.length; i++) { result += '<TR>'; result += '<TD>' + selection[index].couplings[i].description + '</TD>'; result += '<TD style=text-align: right;>' + moneyFormat(selection[index].couplings[i].price) + '</TD>'; result += '</TR>'; }}document.getElementById('couplings').innerHTML = result;/*****************//* Number Format *//*****************/function moneyFormat(num) { return '$' + parseFloat(num).toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, $1,).toString();}
Displaying user selection in the browser
javascript;html
null
_unix.127823
I recently lost my dual-booted HDD (with both Linux and Windows). It did some weird stuff and started changing all files to read-only on every start-up. So, I bought a new HDD and put Fedora 20 on it. Now, the only thing I'm looking to replace is Finale (I have found acceptable substitutes or Linux versions of everything else). I have found MusScore, NoteEdit, etc, but all of these programs need to be compiled (I can't find a suitable .rpm), and typing 'make' gives me errors. First I need cmake, then qmake, then a whole ton of things I don't recognize, and some of which I don't understand. Honestly, I've gotten to the point of saying it isn't worth it unless I can find an RPM of something, because compiling things is ridiculously difficult (I don't NEED a music writing program, just want one). Does anyone know of a suitable replacement already compiled and ready for distribution for Fedora 20?EDIT #1For those who are unfamiliar with Finale, it is a music-composition software, similar to linux's NoteEdit or MusScore. It allows exportation of audio files, note annotations, and printing pages of musical scores. It also supports transposition and human playback features. Some of these things are not that important to me, and I can do some by hand (like transposition), but I would really like the audio file export and printing features. Here is the about page for Finale:http://www.finalemusic.com/products/finale/
Pre-compiled Finale substitute for Fedora 20?
compiling;rpm;music
Method #1 - Using Wine + FinaleIf you have Fedora 20 setup and a copy of Finale already you can apparently run it under Wine, at least according to this thread titled: Finale 2014 without Windows or Mac.excerptHey allHeads up: Finale 2014 is working perfectly on Linux. You can use PlayOnLinux (or basic WINE) and performance is incredible. Of course, if you insist on using VST third-party playback and whatnot, you'll be sad but it's not surprising.For strictly notation and basic playback, Finale 2014 is golden on Linux. If all you want to do is input and edit scores, then you will be very happy. Finale 2014 on Linux does everything as the other OS can do, minus comprehensive VST support.Even though Finale is only supported on Mac and PC, I figured I would share my findings with the forum in case any other users like myself prefer to use Linux whenever possible.What's Wine?Wine is an emulation layer that allows Window executables to run under Linux natively. It's not virtualization and it isn't emulation, it's somewhere in between both of these approaches. But it really doesn't matter how it works, just that it does. You can read more of the technology underpinnings on the project's website.The software application Finale is listed in Wine's AppDB. It's listed as being Gold or Bronze level for versions 2011 & 2012. This is a pretty good indication that the application should run reasonably well through this approach.Method #2 - MusScoreI did find the package already pre-built for Fedora 20. It's called mscore and looks to be in the standard repositories.http://pkgs.org/fedora-20/fedora-i386/mscore-1.3-2.fc20.i686.rpm.htmlTo install it:$ sudo yum install mscore*On Fedora 19 (which I'm currently using) the packages are definitely already available:$ yum search mscoreLoaded plugins: auto-update-debuginfo, changelog, langpacks, refresh-packagekit============================================================================================================ N/S matched: mscore ============================================================================================================mscore-debuginfo.x86_64 : Debug information for package mscoremscore.i686 : Music Composition & Notation Softwaremscore.x86_64 : Music Composition & Notation Softwaremscore-doc.noarch : MuseScore documentationmscore-fonts.noarch : MuseScore fontsMethod #3 - NoteEditThere is a distro that builds on top of Fedora called CCRMA (pronounced Karma) which is geared towards doing music pre/post production along with video editing.Planet CCRMA at Home (CCRMA is pronounced ``karma'') is a collection of free, open source rpm packages (RPM stands for RPM Package Manager) that you can add to a computer running Fedora, 18, 19 or 20, or CentOS 5 (not all applications are built on the 64 bit version) to transform it into an audio workstation with a low-latency kernel, current audio drivers and a nice set of music, midi and audio applicationsThis distro offers NoteEdit as a pre-built RPM:$ sudo yum install noteeditYou should be able to add the packages from the CCRMA website directly to any stock Fedora 20 system, I'd probably add the CCRMA YUM repositories to the system so that any dependencies can also be automatically downloaded and installed as well.Details for doing this are covered here:http://ccrma.stanford.edu/planetccrma/software/installplanettwenty.html
_scicomp.12924
I am working on a Universe Simulator. I'm stuck on creating the dark matters webs of the universe that look like this: http://www.mpa-garching.mpg.de/galform/data_vis/sim3dnew-highres.png I am generating the particles as solid spheres with the radius of 1. How can I make the particles slowly move toward each other as demonstrated in the picture above to form webs of these particles? If anyone has any ideas or might have some examples of how this can be done that would be great. Code in either c/c++/python would be great. (I have the first step of the picture done) Here is a picture of what I have done: http://i.imgur.com/uiTEa3j.png
PyOpenGL/OpenGL Generating Cosmic NBodys
python;simulation;c
null
_codereview.30945
I'm not sure if this implementation is good enough. The function takes a vector of 1 million chars and creates a table of the sequences that pass before the next occurrence of itself.Some questions I have, though feel free to point other things out as well:Is the initialization of the hash-map done well?Am I using the correct / optimal data structures and algorithm?I think my code is more procedural than needs to be, having trouble thinking of folding this correctly.(define (get-reocc v);'(#\J #\S #\T #\I #\J #\I #\O #\Z #\T #\S ....) ->; '#hash((#\T . #(1 357 1661 1939 1759 1425 1240 985 890 716 556 483 392 335 268 1258)); (#\J . #(1 449 1613 1914 1725 1480 1266 1021 850 748 581 527 377 317 255 1223)); (#\S . #(1 379 1678 1995 1708 1397 1230 1006 860 714 605 489 378 318 323 1211)); (#\L . #(1 449 1671 1916 1663 1492 1256 1000 862 735 572 449 400 330 276 1259)); (#\O . #(1 396 1596 1854 1727 1491 1270 1109 873 743 584 473 371 315 273 1209)); (#\I . #(1 396 1625 1901 1758 1414 1229 1057 852 733 605 483 359 328 260 1249)); (#\Z . #(1 394 1529 1973 1657 1473 1309 1018 863 746 569 481 362 355 245 1256))) (define reocc-table2 (make-hash)) (for ([i pieces]) (hash-set! reocc-table2 i (make-vector 16 0))) (define (update-reocc key pos t); #\T 3 '#hash((#\T . #(1 357 1661 1939 1759 -> '#hash((#\T . #(1 357 1661 1940 1759 (define v2 (hash-ref t key)) (vector-set! v2 pos (+ 1 (vector-ref v2 pos)))); (hash-set y key (vector-set! v2 pos (+ 1 (vector-ref v2 pos))))) same as above?(define (find-prev v piece pos i2) ; (#\J #\S #\T #\I #\J #\I #\O #\Z #\T #\S) #\T, #\T, 10, 0 -> 8 ; (define x (vector-ref v (- pos i2))) (cond [(char=? piece x) i2] [(= 0 (- pos i2)) 0] [#t (find-prev v piece pos (+ i2 1))]))(define (f v t i) (define p (vector-ref v i)) (define stop (- 1 (vector-length v))) (if(>= i stop) t (f v (lambda () (update-reocc p (find-prev v p i 0) t)) (+ i 1)))) (f v reocc-table2 0))
Creating an updating hash table
lisp;scheme;vectors;hash table;racket
null
_codereview.52193
I have this table (inradar_ad) with almost 300k entries. I want to know why my query takes 160 secs to run. I tried limiting with LIMIT 10 to see if I get a speed boost, I but didn't. Does LIMIT speed anything up? I don't think so in this case, since it has to calculate everything and then limit it.-- ---------------------------------------------------------------------------------- Routine DDL-- Note: comments before and after the routine body will not be stored by the server-- --------------------------------------------------------------------------------DELIMITER $$CREATE DEFINER=`root`@`localhost` PROCEDURE `SearchAdsOrderedByGroupThenLocation`(IN basic_user_id INT, IN mylat DOUBLE, IN mylon DOUBLE, IN max_dist INT, IN q VARCHAR(255))BEGIN DECLARE lon1 FLOAT; DECLARE lon2 FLOAT; DECLARE lat1 FLOAT; DECLARE lat2 FLOAT; SET @group_id = (SELECT group_id from basicuser where id = basic_user_id); SET @subgroup_id = (SELECT subgroup_id from basicuser where id = basic_user_id); SET @tertiarygroup_id = (SELECT tertiarygroup_id from basicuser where id = basic_user_id); -- get the original lon and lat for the userid SET lon1 = mylon - max_dist / abs(cos(radians(mylat)) * 69); SET lon2 = mylon + max_dist / abs(cos(radians(mylat)) * 69); SET lat1 = mylat - (max_dist / 69); SET lat2 = mylat + (max_dist / 69); SELECT DISTINCT `inradar_ad`.*, 3956 * 2 * ASIN(SQRT(POWER(SIN((orig.latitude - dest.latitude) * pi()/180 / 2), 2) + COS(orig.latitude * pi()/180) * COS(dest.latitude * pi()/180) * POWER(SIN((orig.longitude - dest.longitude) * pi()/180 / 2), 2))) as distance FROM location AS dest LEFT OUTER JOIN `inradar_ad` ON (`inradar_ad`.location_id = dest.id) LEFT OUTER JOIN `inradar_ad_company` ON (`inradar_ad`.`id` = `inradar_ad_company`.`inradarad_ptr_id`) LEFT OUTER JOIN `inradar_ad_person` ON (`inradar_ad`.`id` = `inradar_ad_person`.`inradarad_ptr_id`) LEFT OUTER JOIN `inradar_category` ON (`inradar_ad`.`category_id` = `inradar_category`.`id`) LEFT OUTER JOIN `inradar_subcategory` ON (`inradar_ad`.`subcategory_id` = `inradar_subcategory`.`id`) LEFT OUTER JOIN `basicuser` ON (`inradar_ad`.`owner_id` = `basicuser`.`id`) LEFT OUTER JOIN `auth_user` ON (`basicuser`.`user_id` = `auth_user`.`id`) LEFT OUTER JOIN `inradar_ad_multiple` ON (`inradar_ad`.`multiple_advertiser_id` = `inradar_ad_multiple`.`id`), location AS orig WHERE `inradar_ad`.`available` != 0 AND ( ( `inradar_ad_multiple`.`id` IS NULL AND ( `inradar_ad_company`.`corporate_name` LIKE REPLACE('%$$**$$%', '$$**$$', q) OR `inradar_ad_person`.`name` LIKE REPLACE('%$$**$$%', '$$**$$', q) OR `inradar_category`.`name` LIKE REPLACE('%$$**$$%', '$$**$$', q) OR `inradar_subcategory`.`name` LIKE REPLACE('%$$**$$%', '$$**$$', q) OR `inradar_ad`.`description` LIKE REPLACE('%$$**$$%', '$$**$$', q) OR `inradar_ad`.`tags` LIKE REPLACE('%$$**$$%', '$$**$$', q) OR `auth_user`.`first_name` LIKE REPLACE('%$$**$$%', '$$**$$', q) OR `auth_user`.`last_name` LIKE REPLACE('%$$**$$%', '$$**$$', q) ) ) ) AND `inradar_ad`.`available` = 1 AND dest.longitude BETWEEN lon1 AND lon2 AND dest.latitude BETWEEN lat1 AND lat2 HAVING distance < max_dist ORDER BY CASE WHEN `basicuser`.`tertiarygroup_id` = @tertiarygroup_id THEN `basicuser`.`tertiarygroup_id` END DESC, CASE WHEN `basicuser`.`subgroup_id` = @subgroup_id THEN `basicuser`.`subgroup_id` END DESC, CASE WHEN `basicuser`.`group_id` = @group_id THEN `basicuser`.`group_id` END DESC, distance ASC;ENDHere's the table structure:DROP TABLE IF EXISTS `location`;CREATE TABLE `location` ( `id` int(11) NOT NULL AUTO_INCREMENT, `address` varchar(200) COLLATE utf8_unicode_ci DEFAULT NULL, `address_number` int(11) DEFAULT NULL, `address_complement` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL, `neighborhood` varchar(200) COLLATE utf8_unicode_ci DEFAULT NULL, `zip_code` varchar(25) COLLATE utf8_unicode_ci DEFAULT NULL, `city_id` int(11) DEFAULT NULL, `state_id` int(11) DEFAULT NULL, `country_id` int(11) DEFAULT NULL, `latitude` double DEFAULT NULL, `longitude` double DEFAULT NULL, PRIMARY KEY (`id`), KEY `location_b376980e` (`city_id`), KEY `location_5654bf12` (`state_id`), KEY `location_d860be3c` (`country_id`), CONSTRAINT `city_id_refs_id_ab743da9` FOREIGN KEY (`city_id`) REFERENCES `location_city` (`id`), CONSTRAINT `country_id_refs_id_8d58a0d2` FOREIGN KEY (`country_id`) REFERENCES `location_country` (`id`), CONSTRAINT `state_id_refs_id_9f4f2609` FOREIGN KEY (`state_id`) REFERENCES `location_state` (`id`)) ENGINE=InnoDB AUTO_INCREMENT=102346 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;DROP TABLE IF EXISTS `basicuser`;CREATE TABLE `basicuser` ( `id` int(11) NOT NULL AUTO_INCREMENT, `added_by_id` int(11) DEFAULT NULL, `photo` varchar(100) COLLATE utf8_unicode_ci NOT NULL, `user_id` int(11) NOT NULL, `mobile_phone` varchar(24) COLLATE utf8_unicode_ci NOT NULL, `phone` varchar(24) COLLATE utf8_unicode_ci NOT NULL, `group_id` int(11) DEFAULT NULL, `subgroup_id` int(11) DEFAULT NULL, `tertiarygroup_id` int(11) DEFAULT NULL, `location_id` int(11) DEFAULT NULL, `user_type` varchar(50) COLLATE utf8_unicode_ci NOT NULL, `personal_data_filled` int(11) NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `basicuser_user_id_70deebc304043f15_uniq` (`user_id`), KEY `basicuser_f6b8c251` (`added_by_id`), KEY `basicuser_6340c63c` (`user_id`), KEY `basicuser_5f412f9a` (`group_id`), KEY `basicuser_d6ee8a04` (`subgroup_id`), KEY `basicuser_9394537f` (`tertiarygroup_id`), KEY `basicuser_afbb987d` (`location_id`), CONSTRAINT `added_by_id_refs_id_1a91b691` FOREIGN KEY (`added_by_id`) REFERENCES `basicuser` (`id`), CONSTRAINT `group_id_refs_id_cd2e32a4` FOREIGN KEY (`group_id`) REFERENCES `inradar_group` (`id`), CONSTRAINT `location_id_refs_id_a7ee2d0b` FOREIGN KEY (`location_id`) REFERENCES `location` (`id`), CONSTRAINT `subgroup_id_refs_id_3c81d859` FOREIGN KEY (`subgroup_id`) REFERENCES `inradar_subgroup` (`id`), CONSTRAINT `tertiarygroup_id_refs_id_4f311f89` FOREIGN KEY (`tertiarygroup_id`) REFERENCES `inradar_tertirarygroup` (`id`), CONSTRAINT `user_id_refs_id_cb17b658` FOREIGN KEY (`user_id`) REFERENCES `auth_user` (`id`)) ENGINE=InnoDB AUTO_INCREMENT=144 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;/*!40101 SET character_set_client = @saved_cs_client */;---- Table structure for table `inradar_subgroup`--DROP TABLE IF EXISTS `inradar_subgroup`;/*!40101 SET @saved_cs_client = @@character_set_client */;/*!40101 SET character_set_client = utf8 */;CREATE TABLE `inradar_subgroup` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(200) COLLATE utf8_unicode_ci NOT NULL, `group_id` int(11) NOT NULL, PRIMARY KEY (`id`), KEY `inradar_subgroup_5f412f9a` (`group_id`), CONSTRAINT `group_id_refs_id_02dc2b6d` FOREIGN KEY (`group_id`) REFERENCES `inradar_group` (`id`)) ENGINE=InnoDB AUTO_INCREMENT=32 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;/*!40101 SET character_set_client = @saved_cs_client */;---- Table structure for table `inradar_ad`--DROP TABLE IF EXISTS `inradar_ad`;/*!40101 SET @saved_cs_client = @@character_set_client */;/*!40101 SET character_set_client = utf8 */;CREATE TABLE `inradar_ad` ( `id` int(11) NOT NULL AUTO_INCREMENT, `owner_id` int(11) DEFAULT NULL, `description` varchar(5000) COLLATE utf8_unicode_ci NOT NULL, `category_id` int(11) DEFAULT NULL, `subcategory_id` int(11) DEFAULT NULL, `video_url` varchar(200) COLLATE utf8_unicode_ci NOT NULL, `logo` varchar(100) COLLATE utf8_unicode_ci NOT NULL, `location_id` int(11) NOT NULL, `business_hours` varchar(500) COLLATE utf8_unicode_ci NOT NULL, `subscription_plan_id` int(11) DEFAULT NULL, `tags` varchar(500) COLLATE utf8_unicode_ci NOT NULL, `advertiser_occupation` varchar(150) COLLATE utf8_unicode_ci NOT NULL, `advertiser_group_message` varchar(1000) COLLATE utf8_unicode_ci NOT NULL, `email` varchar(75) COLLATE utf8_unicode_ci NOT NULL, `email_contact_form` varchar(75) COLLATE utf8_unicode_ci NOT NULL, `website` varchar(200) COLLATE utf8_unicode_ci NOT NULL, `e_commerce` varchar(200) COLLATE utf8_unicode_ci NOT NULL, `phone` varchar(20) COLLATE utf8_unicode_ci NOT NULL, `phone2` varchar(20) COLLATE utf8_unicode_ci NOT NULL, `blap_phone` varchar(30) COLLATE utf8_unicode_ci NOT NULL, `delivery` tinyint(1) DEFAULT NULL, `comment_votes` int(11) NOT NULL, `comment_quantity` int(11) NOT NULL, `multiple_advertiser_id` int(11) DEFAULT NULL, `user_type` varchar(20) COLLATE utf8_unicode_ci NOT NULL, `additional_info` varchar(500) COLLATE utf8_unicode_ci NOT NULL, `advertiser_available` tinyint(1) NOT NULL, `used_free_coupom` tinyint(1) NOT NULL, `modified_datetime` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, `available` tinyint(1) NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `inradar_ad_location_id_c75ed6fdef730d0_uniq` (`location_id`), UNIQUE KEY `multiple_advertiser_id` (`multiple_advertiser_id`), KEY `inradar_ad_cb902d83` (`owner_id`), KEY `inradar_ad_6f33f001` (`category_id`), KEY `inradar_ad_790ef9fb` (`subcategory_id`), KEY `inradar_ad_afbb987d` (`location_id`), KEY `inradar_ad_edafc3c2` (`subscription_plan_id`), CONSTRAINT `category_id_refs_id_d9b04586` FOREIGN KEY (`category_id`) REFERENCES `inradar_category` (`id`), CONSTRAINT `location_id_refs_id_a1d009d1` FOREIGN KEY (`location_id`) REFERENCES `location` (`id`), CONSTRAINT `multiple_advertiser_id_refs_id_8f1f14fc` FOREIGN KEY (`multiple_advertiser_id`) REFERENCES `inradar_ad_multiple` (`id`), CONSTRAINT `owner_id_refs_id_caece728` FOREIGN KEY (`owner_id`) REFERENCES `basicuser` (`id`), CONSTRAINT `subcategory_id_refs_id_b5f2fdc5` FOREIGN KEY (`subcategory_id`) REFERENCES `inradar_subcategory` (`id`), CONSTRAINT `subscription_plan_id_refs_id_76dc847a` FOREIGN KEY (`subscription_plan_id`) REFERENCES `inradar_subscription` (`id`)) ENGINE=InnoDB AUTO_INCREMENT=101552 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;/*!40101 SET character_set_client = @saved_cs_client */;---- Table structure for table `inradar_tertirarygroup`--DROP TABLE IF EXISTS `inradar_tertirarygroup`;/*!40101 SET @saved_cs_client = @@character_set_client */;/*!40101 SET character_set_client = utf8 */;CREATE TABLE `inradar_tertirarygroup` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(200) COLLATE utf8_unicode_ci NOT NULL, `subgroup_id` int(11) NOT NULL, `location_id` int(11) DEFAULT NULL, `phone` varchar(30) COLLATE utf8_unicode_ci NOT NULL, `email` varchar(75) COLLATE utf8_unicode_ci NOT NULL, PRIMARY KEY (`id`), KEY `inradar_tertirarygroup_d6ee8a04` (`subgroup_id`), KEY `inradar_tertirarygroup_afbb987d` (`location_id`), CONSTRAINT `location_id_refs_id_6d3145dd` FOREIGN KEY (`location_id`) REFERENCES `location` (`id`), CONSTRAINT `subgroup_id_refs_id_c0dcd513` FOREIGN KEY (`subgroup_id`) REFERENCES `inradar_subgroup` (`id`)) ENGINE=InnoDB AUTO_INCREMENT=61 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;/*!40101 SET character_set_client = @saved_cs_client */;---- Table structure for table `inradar_ad_multiple`--Just in case you need to know, I call it like this:call SearchAdsOrderedByGroupThenLocation(40, -22.4169605, -42.9756016, 100, 'a');Since creating an INDEX to latitude and longitude on Location table did not do me so much good, here's the output of the EXPLAIN SELECT command:'1','SIMPLE','dest','range','PRIMARY,location_latlng','location_latlng','18',NULL,'3445','Using where; Using index; Using temporary; Using filesort''1','SIMPLE','inradar_ad','eq_ref','inradar_ad_location_id_c75ed6fdef730d0_uniq,inradar_ad_afbb987d','inradar_ad_location_id_c75ed6fdef730d0_uniq','4','inradar_db.dest.id','1','Using where''1','SIMPLE','inradar_ad_company','eq_ref','PRIMARY','PRIMARY','4','inradar_db.inradar_ad.id','1',NULL'1','SIMPLE','inradar_ad_person','eq_ref','PRIMARY','PRIMARY','4','inradar_db.inradar_ad.id','1',NULL'1','SIMPLE','inradar_category','eq_ref','PRIMARY','PRIMARY','4','inradar_db.inradar_ad.category_id','1',NULL'1','SIMPLE','inradar_subcategory','eq_ref','PRIMARY','PRIMARY','4','inradar_db.inradar_ad.subcategory_id','1',NULL'1','SIMPLE','basicuser','eq_ref','PRIMARY','PRIMARY','4','inradar_db.inradar_ad.owner_id','1',NULL'1','SIMPLE','auth_user','eq_ref','PRIMARY','PRIMARY','4','inradar_db.basicuser.user_id','1','Using where''1','SIMPLE','inradar_ad_multiple','eq_ref','PRIMARY','PRIMARY','4','inradar_db.inradar_ad.multiple_advertiser_id','1','Using where; Not exists; Using index''1','SIMPLE','orig','index',NULL,'location_latlng','18',NULL,'100816','Using index; Using join buffer (Block Nested Loop)'
Geographic search
performance;sql;mysql;geospatial;join
null
_unix.352736
ubuntu 16.04I have 2 node applications, app-1 and app-2, with usernames matching their application names, listening locally (on ports 8001 and 8002, respectively) on the same instance. When app-1 makes a request to app-2 I can find the remoteHost of the socket handling the request from app-2. Then when I try to look up this remoteHost via netstat and retrieve some user/process information, I find that the user associated with the socket is uid: 0 or root. My expectation is that the user associated with this connection would be app-1, since that is the application where the request is being generated. So part 1 of my question is: why is the user root and not app-1?Part 2: My goal is to get the user id of the remote process based solely on the information in remoteHost (e.g. 127.0.0.1:53900). Seems to me like the operating system should know exactly what process/user-id is using that host/port combination. So, assuming netstat will not work, for the reasons mentioned in the previous paragraph, what other system calls or utilities could I look at to get this information?
netstat (/proc/net): why is user associated with socket root? how to get user-id of 'remote' process?
networking;users;proc;socket;netstat
null
_unix.290302
I'm setting up a file share for a small group (CIFS/samba on FreeNAS, so the base system is FreeBSD/ZFS using ACLs). I want to allow users to put stuff into a folder on the share - but not to be able to read the share's contents once written. Since they can't read the shares contents or get directory listings, the share will be flat (no subdirectories) and they mustn't be able to overwrite or alter files that already exist unseen there, since they couldn't see them to avoid the overwrite and because it allows probing of filenames that exist or don't.Is there a way to do this?
Permissions to allow files to be written, but not read, overwritten or modified
permissions;acl;freebsd;samba;cifs
null
_unix.320582
Is it possible to have a server running in screen and back out to resume working on other things in the console, without shutting down screen.EDIT: Answered. CTRL+A +D will detach the screen and leave the process running.
How to keep a process running in screen but back out of the screen session
debian;gnu screen
screen -dmS Name /path/to/some/process arg1 arg2Then, later, to interact with process:screen -x Name
_unix.196215
I run a virtual vmware archlinux installation, and constantly have problems with mouse grab/ungrab. At some point it was fixed by commenting out pointer lines in 10-evdev config, but on every update there's different sort of problem, and the only way I know to address them is to try all sorts of tweaks, and see if one of them works. The log file is sometimes helpful, but sometimes confusing. This gets annoying. I am searching for generic way to debug the mouse problem. With that, can someone tell me:How do I tell: which mouse driver(s) the X server is currently using?How do I tell: which OTHER mouse driver the X server loaded but not using?Whether vmware driver is even loaded?
General way of debugging vmware mouse issues in X11
x11;xorg;vmware
null
_softwareengineering.310043
If there's a bug that triggers undefined behavior in a piece of code, is the undefined behavior consistent each time running it? and changes each time compiling it?For example if you had some C code that does some string manipulation. You compile it, run it 3 times and the output is consistent of weird characters like ABCE*D-*+. You compile it again and the next time it run it 3 times it just crashes.I'm sorry if the description is a little ambiguous, as I'm trying to figure this out myself.
Consistency of Undefined behavior
c;bug;undefined behavior
No. The consistency of undefined behaviour is undefined.Speaking practically, when you've caused undefined behaviour by dereferencing a null pointer, you can probably expect fairly deterministic results (segmentation fault) at least on the same computer, because that computer has been constructed to behave that way for null pointer dereferences.But when you've caused it by dereferencing uninitialised pointers, whether the ensuing dereference is even physically possible will depend on what that unspecified, uninitialised value is, which may depend on what code has run before, and with what user inputs, and in what order. Like a dice roll, it's not actually random, but it's also neither fully deterministic nor usefully predictable. Add optimisations into the mix and it's no longer practical to attempt rationalising about any of it.That's why we tend not to go into any further detail about the causes of specific symptoms of undefined behaviour; there's rarely any point.