Connecting midi keyboard to pc

Question: Is it possible to connect a midi keyboard to a PC, WITHOUT using a midi to usb cable.. Thus instead using a midi to audio jack cable. And then be able to record midi, for example on a DAW? I tried some possibilities but couldn't figure it out. And when I try to google all I get is midi to usb cables. I also have an amplifier if that could perhaps assist with something ? anyone ?
The reason I ask is because I have this old Roland xp-80 I want to connect to my PC. I have a lot of cables hence I thought if I could solve it with what I had it'd save me a buck
Answer: There are other ways to connect a MIDI keyboard to a PC besides a MIDI to USB cable -- there are MIDI to MIDI, MIDI to ethernet, MIDI to bluetooth, MIDI to wifi adapters -- but I don't know of any MIDI to audio jack connections for good reason:
MIDI is not a system containing audio information.  It's a set of numbers just like USB data in essence (though there are many more complications); it's no more suited to coming in via an audio cable than an external HD would be.
If you just want to record audio out from your keyboard to your PC then you should be able to do audio out to audio in, but then it's the same as recording from a CD or Microphone. You won't be able to edit any MIDI data afterwards.
Answer: You won't be able to connect Midi to a PC audio with just a cable.  However, citing the first sentence of the Wikipedia entry for the Roland XP-80:

The Roland XP-80 is a music workstation that uses digital PCM subtractive synthesis
That's not a Midi keyboard, or rather, a Midi keyboard is only the smallest part of its circuitry.  The keyboard has 6.3mm sound output jacks, and an adapter for those to your sound card input is going to do the trick.
Signal-to-noise level is going to be analog quality but you can expect the general sound quality to be better than you can get with software Midi expanders as long as they come with a price tag significantly below that of your Roland.
In short: you should be happy not to connect via Midi if your goal is to work with the actual sound samples.  A (bidirectional) Midi adapter might still make sense since a DAW might be able to work more flexibly with Midi rather than audio data and you can then still use your Roland for converting the finalized Midi to sound.

Connecting midi keyboard to pc


Proof that deleting a certain node in a graph where two nodes have a path of length greater than n/2 destroys the path between the two nodes.

Question: I think I understand the problem and why the claim is true, but I just want to make sure my proof is solid. Let me know if there's anything I can do to improve it. Thanks!
Problem: Suppose that an $n$-node undirected graph $G$ contains two nodes $s$ and $t$ such that the distance between $s$ and $t$ is strictly greater than $n/2$. Show that $G$ must contain some node $v$, not equal to $s$ or $t$, such that deleting $v$ from the graph destroys all $s$-$t$ paths. (In other words, the graph obtained from $G$ by deleting $v$ contains no path from $s$ to $t$.)
Proof: If we generate a BFS tree starting at node $s$, node $t$ will be at a level strictly greater than $n/2$ because the path between $s$ and $t$ is strictly greater than $n/2$. The remaining $n-2$ nodes of the tree must go somewhere in at least $n/2$ layers, which will lead to at least one layer containing only a single node $v$. Nodes at layers before and after $v$ cannot connect without going through $v$ because of the property of BFS trees that states that nodes in a BFS tree can only be connected in the corresponding graph if they are in the same or directly adjacent layers. Therefore, the path must go through $v$, and deleting $v$ would destroy the path from $s$ to $t$.
Answer: Another way of saying this: for some $k$, $1 \le k \le \lfloor n/2 \rfloor$, there is only one node at distance $k$ from $s$ (otherwise, counting $s$, $t$ and at least $2$ nodes at each $k$ you'd nave at least $2 + 2 \lfloor n/2 \rfloor > n$ vertices).
Every path from $s$ to $t$ must pass through a node at distance $k$ from $s$, so if you delete the only such node you no longer have such a path.


How do I reduce the number of data points in a series?

Question: I haven't studied statistics for over 10 years (and then just a basic course), so maybe my question is a bit hard to understand.
Anyway, what I want to do is reduce the number of data points in a series. The x-axis is number of milliseconds since start of measurement and the y-axis is the reading for that point.
Often there is thousands of data points, but I might only need a few hundreds. So my question is: How do I accurately reduce the number of data points?
What is the process called? (So I can google it)
Are there any prefered algorithms (I will implement it in C#)
Hope you got some clues. Sorry for my lack of proper terminology.

Edit: More details comes here:
The raw data I got is heart rate data, and in the form of number of milliseconds since last beat. Before plotting the data I calculate number of milliseconds from first sample, and the bpm (beats per minute) at each data point (60000/timesincelastbeat).
I want to visualize the data, i.e. plot it in a line graph. I want to reduce the number of points in the graph from thousands to some hundreds.
One option would be to calculate the average bpm for every second in the series, or maybe every 5 seconds or so. That would have been quite easy if I knew I would have at least one sample for each of those periods (seconds of 5-seconds-intervals).
Comment: I forgot this: The points along the x-axis come with varying spacing.
Comment: I am not sure I understand. Don't you have a y-axis?
Comment: Ah, sorry. I misstyped. I have now changed it above.
Comment: I also think you need to provide a bit more information. For example, I still cannot visualize the graph. What is your goal?
Comment: Ok, sorry. I have added some more details above.
Comment: Ok, just so I understand better- your x-axis is time with the 0 point being the time of the first sample. Your y-axis is beats per minute. Is that right? I still do not know your goal: Why do you want to reduce the number of data points? - Reduce clutter? or See patterns better? or the existing points are too close to each other for you to figure out what is happening?
Comment: Closely related: [Filtering beat-to-beat heart rate data](http://mathematica.stackexchange.com/questions/14610) (on the *Mathematica* SE site).
Answer: You have two problems: too many points and how to smooth over the remaining points.
Thinning your sample
If you have too many observations arriving in real time, you could always use simple random sampling to thin your sample. Note, for this too be true, the number of points would have to be very large.
Suppose you have N points and you only want n of them. Then generate n random numbers from a discrete uniform U(0, N-1) distribution. These would be the points you use.
If you want to do this sequentially, i.e. at each point you decide to use it or not, then just accept a point with probability p. So if you set p=0.01 you would accept (on average) 1 point in a hundred.
If your data is unevenly spread and you only want to thin dense regions of points, then just make your thinning function a bit more sophisticated. For example, instead of p, what about:
$$1-p \exp(-\lambda t)$$
where $\lambda$ is a positive number and $t$ is the time since the last observation. If the time between two points is large, i.e. large $t$, the probability of accepting a point will be one. Conversely, if two points are close together, the probability of accepting a point will be $1-p$.
You will need to experiment with values of $\lambda$ and $p$.
Smoothing
Possibly something like a simple moving average type scheme. Or you could go for something more advanced like a kernel smoother (as others suggested). You will need to be careful that you don't smooth too much, since I assume that a sudden drop should be picked up very quickly in your scenario.
There should be C# libraries available for this sort of stuff.
Conclusion
Thin if necessary, then smooth.
Comment: Ah, interesting, but I need it to be predictable, i.e. to have the same result each time I view the data.
Comment: In that case, generate the *n* indexes of the points you choose, and store those indexes.
Comment: Or store the seed to the RNG before sampling.
Comment: Dirk's solution regarding the seed is probably the better option.
Comment: Calculating averages per each second is ok, but what I do when there is no data for a specific second. I guess I could do some interpolation from the seconds before and after it, but it would be great with some specific (named) method for this, so I don't try to invent something already invented.
Comment: The interpolation you are talking about is the moving average or smoothing bit.
Comment: But moving average will not reduce the number of data points, will it? As far as I know it will _only_ smoothen. Or are there optional moving averages that does both?
Comment: I rewrote the answer. Hopefully it's clear and useful now.
Comment: Thanks, very clear! Random sampling sounds like a great tool. But what can I do if the original data points are very unevenly spread out - I still want, for example, one final data point per 5 second interval, and that might not be present (maybe not even before the random sampling). That means I need to do some kind of interpolation.
Comment: @Pete - see answer
Comment: Great method for dealing with uneaven data. I will try that. A huge thanks for all your help!
Comment: OK - More than 10 years gone by since the question was asked, and I am a *bit surprised* that no one has remarked about the apparent *incongruity* of applying **random** sampling to **heartbeat data**. If you're supporting any cardiologists - please do us all a favor & let us know their names :)
Answer: Well, I think the word you're looking for is "sampling," but I'm not sure why you want to do it. Thousands of data points isn't very many. Or are you looking just to plot a smaller number of equally-spaced points? That's usually called "binning."
Is your goal to generate a visualization? In that case, you might want to keep the raw data, plot it as a scattergraph, then overlay some sort of central tendency (regression line, spline, whatever) to communicate whatever the takehome message ought to be.
Or is your goal to numerically summarize the results in some way? In that case, you might want to explain your problem in more detail!
Comment: Yep, visualization is what I want. I have added some more info in the question.
Comment: seconding plotting raw data with a smoothing line.
Comment: thirding plotting raw data with a smoothing line --- You might want to also plot the change in BPM over time as a separate visualization.
Answer: Calculating averages leads to a different dataset than simply reducing the number of data points.
If one heartbeat per minute is much faster than the other heart beats you will lose the signal through your smoothing process.
If you summary 125-125-0-125-125 as 100 than the story that the data tells is different through your smoothing.
Sometimes the heart even skips beats and I believe that's an event that interesting for however wants to look at plotted heart rate data.
I would therefore propose that you calculate the distance between two points with a formula like d=sqrt((time1-time2)^2 + (bpm1-bpm2)).
You set a minimum distance in your program.
Then you iterate through your data and after every point you delete all following points for which d is smaller than your minimum distance.
As the unit of time and bpm isn't the same you might want to think about how you can find a way to scale the units meaningfully. To do this task right you should speak to the doctors who in the end have to interpret your graphs and ask them what information they consider to be essential.
Comment: Interesting posting. I will look into that too. You are probably right.
Answer: You're not providing enough information.  Why do you want to reduce the data points.  A few thousand is nothing these days.
Given that you want the same result each time you view the same data perhaps you want to simply bin averages.  You have variable spacing on your x-axis.  Maybe you're trying to make that consistent?  In that case you would set a bin width of perhaps 50 msec, or 100, and then average all the points in there.  Make the bin width as large as you need to reduce the data points to the size of the set you want.
binw = 50
myRTBin = ceiling(myRT / binw) * binw - binw / 2

You could then just aggregate the RTs grouped by the RT bins.
It's really a hard question to answer without a reason for why you're getting rid of data.
Comment: Ok, sorry. I have added some more details above.
Answer: If BPM is staying the same over many samples (or changing infinitesimally in a way you aren't concerned about) you can truncate your data to a significant digit that you actually care about and then do Run Length Encoding.
For example, in R this data:
0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2

has this output
rle(data)
Run Length Encoding
  lengths: int [1:3] 10 15 15
  values : num [1:3] 0 1 2

Answer: For reducing your data points, you can use the Ramer–Douglas–Peucker algorithm which is very easy to understand and implement. The sampled signal will be very similar to the original one.
Comment: Thanks for this! Best answer on this page by far, IMHO. I'd like to ask a follow-up: I have a *huge* data set of x-y (time-voltage) values generated from a transient electrical event (contact bounce in a mechanical switch), and captured on my oscilloscope. I need this data as input to my SPICE circuit analysis program, but it just won't cope with half-a-million data points. A sampled/thinned data set must preserve the *sequence* (ref `non-self-intersection` in the Wiki article), and as much as possible preserve the frequency content (a la Fourier) of the original. Any thoughts?
Comment: Here's what the data look like [on the oscilloscope](https://imgur.com/a/JcRDZ7k)


Windows Server 2008 (sp2) stops responding on network share requests from Windows Vista and 7 clients

Question: I have two Windows Server 2008 SP2 machines (TFS and TFSBUILD). Periodically, the TFSBUILD server shares (\TFSBUILD\ShareName or \TFSBUILD\C$) become unresponsive to requests from Windows Vista (Server 2008) and Windows 7 client requests. Windows XP machines are still able to connect.
No events in the server log indicate any problem. A simple restart corrects the issue temporarily, but it always returns.
It is not this http://support.microsoft.com/kb/948732 (we aren't using that software).
This does not appear to be an issue with SMB 2.0. Per @Maxwell I tried disabling it on the server and on the Windows 7 and Vista stations:
sc config lanmanworkstation depend= bowser/mrxsmb10/nsi
sc config mrxsmb20 start= disabled

All anti-virus software has been disabled, firewall is disabled by policy. No other network activity is affected.
The TFSBUILD server is a virtual, running under Hyper-V (x86 guest on an x64 host). The host has the same OS version and SP.
Any help would be greatly appreciated.
Comment: We've decided to just rebuild the server (this time as 2008 R2). Thanks to all for the input.
Answer: Maybe this has something to do with SMB 2.0, you could try disabling it  on the server and on the Windows 7 and Vista stations:
sc config lanmanworkstation depend= bowser/mrxsmb10/nsi
sc config mrxsmb20 start= disabled

You may also want to read this article at petri.co.il
This may be a workaround...
Comment: Seems I was wrong - it had an issue one time after adding the registry entries, but now is stable.
Comment: Glad it solved your problem.
Comment: Trying that now.
Comment: Excellent suggestion, but no luck.
Comment: Was Symantec Endpoint installed on the server?
Comment: No, in fact, I thought that was the KB I linked to, but I'll update it.
Comment: Per @DrZaiusApeLord I should have RTWFA - Adding reg. entry now to see if that fixes it.
Comment: Nope, that didn't help.
Comment: One more idea, maybe this has something to do with the TCP Chimney OffloadFeature http://support.microsoft.com/?scid=kb;en-us;951037&x=17&y=10
Comment: No luck there either.
Comment: If anyone reading this wonders, like I did, whether "bowser" is a typo and should be "browser", it's isn't a mistake and here's the explanation why: https://blogs.msdn.com/b/larryosterman/archive/2006/03/14/551368.aspx?
Answer: There seems to be a somewhat related question here.  One answer that sticks out is to check the "File and printer Sharing for Microsoft Networks" option on the network adapters.  However, this would likely cause it to never work, not stop working after a while.
I'd suggest you get Wireshark on the server and start a trace of the network traffic.  Check to see what it looks like when XP clients connect to a share, and when the Win7/Vista clients connect (both when it works and after it stops working).  Hopefully you'll find some obvious missing piece when it's not working that can help lead to the actual cause.
Comment: You're right - if F&P sharing wasn't installed it wouldn't work at all. Already installed Wireshark. I'll post traces of working/non-working soon.
Comment: Most av software isn't really disabled until you uninstall it! I'm pretty sure this is true for mcafee not sure of others.
Answer: hm.
can you disable/remove IPv6 and all others unnecessary filters/services on TFS/TFSBUILD servers ?
you can look at WinXP network configuration to decide what to disable ...
Answer: sc config lanmanworkstation depend= bowser/mrxsmb10/nsi
sc config mrxsmb20 start= disabled

You also need to put in the reg key on the server to disable SMB2. Then you will need to reboot the server and all your clients.


Why isn't the term "hat trick" used in American Football?

Question: Hat trick is commonly used in association football and hockey when a player scores three goals in a match or game.
Given that association football and American football have similar roots, I would think American football would also use this.  Quarterbacks throw for three scores in a game as routinely (if not more than) as footballers or hockey players, but I've never heard a reference to achieving a hat trick.
Answer: I'm not sure where you get the idea that American football has meaningful links to association football (American soccer).  It shares a name, sure, but otherwise it is much closer to Rugby (Union/League) Football - both in its rules and in its historical roots.
However, I suspect the issue at hand is primarily that it's hard to define what would be called a "hat trick".  Quarterbacks frequently throw three touchdowns in a game; so that's out due to its frequency.  Hat tricks, in most sports, are difficult to achieve; for example, only 56 hat tricks  have been achieved in Rugby World Cup history.  In comparison, 179 QBs have thrown for 5 touchdowns or more in a single game, and over three thousand have thrown three.
As for other feats - it's hard to say why a phrase didn't catch on, but I suspect because there are simply too many things going on in one game.  I've certainly heard the phrase use in its common meaning - "three of anything happening" - to refer to sacks and interceptions; it's probably been used in other circumstances as well.  This is similar to other American sports; baseball often uses it to mean three strikeouts in one game, which is pretty silly (as that's not a good stat, and it's a very common one) and to mean three home runs in one game (which at least makes more sense), but even three steals in one game might be called a hat trick.
But in American football, what else are you going to call a hat trick other than passing touchdowns?  Receiving touchdowns, rushing touchdowns, picks, sacks, made FGs... the number of things that it could be attached to is too large, likely, for it to have been attached to just one thing.  The sports that it has become commonplace in are primarily sports with one major action - goal scoring - that is fairly infrequent.  Cricket is to some extent the exception - and that's because it is the origin of the term, likely.
Comment: Your rugby example is a) for union rather than league, and b) just about the World Cup, which is played only every four years. Hat tricks are pretty common in professional rugby, either union or league.
Comment: As a historical note, American football is more derived from union rather than league; American football was certainly a recognisably separate sport from rugby (union) by 1880, while league didn't come into existence until the formation of the Northern Union in 1895, and league didn't introduce the limited tackle count until 1966.
Comment: Hmm, the link I followed to get to that link said it was League, but I don't know enough about Rugby to realize it was in error.  Thanks for the corrections.
Comment: Where do I get the idea that American football has meaningful links to association football...I don't have any links or specific sources, but my understanding was that both were derived from a rugby-type game.  Or at least soccer & rugby were the prevailing sports, while late 19th-century Americans altered the play and rules to begin what is now American football.  Apologies if I understand incorrectly.
Comment: American football derived from Rugby football in the mid-1800s.  Association football comes much much earlier, and probably has some links to Rugby (I'm not familiar enough to say) but really nothing with American football.
Comment: "Association football comes much much earlier, and probably has some links to Rugby"?!? They come from a clarification / split of rules from the mid 1850s. They are twin brothers that followed their own way, that is much more than "some links" (https://en.wikipedia.org/wiki/Association_football)


Is Selenium 3.0 supports moveHover Operations(moveToElement) using Action Class?

Question: I am trying to perform mouseHover Operation in Java but getting Below Exception
org.openqa.selenium.UnsupportedCommandException: POST /session/10089ef9-f491-4b9c-a295-d9246dd39e02/moveto did not match a known command
Build info: version: '3.0.1', revision: '1969d75', time: '2016-10-18 09:48:19 -0700'
System info: host: 'SHI58495EU1003F', ip: '192.168.0.105', os.name: 'Windows 7', os.arch: 'amd64', os.version: '6.1', java.version: '1.8.0_66'
Driver info: org.openqa.selenium.firefox.FirefoxDriver

Manual Step
Navigate to Website "http://www.fatcow.com/"
perform mouseHover on "create a Site" link
click on option "original FatCow" option.

Have I written Successfully Executable code or anything is missing?
PFB the COde
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;
import org.testng.annotations.Test;

public class mousehover {

    WebDriver driver;

    @Test
    public void start()
    {
        System.setProperty("webdriver.gecko.driver", "C:\\Users\\rkumar\\Desktop\\geckodriver.exe");
        driver  = new FirefoxDriver();
        driver.navigate().to("http://www.fatcow.com/");
        Actions action = new Actions(driver);
        WebElement createAsite = driver.findElement(By.linkText("Create a Site"));
        WebElement original = driver.findElement(By.linkText("Original FatCow"));
action.moveToElement(createAsite).moveToElement(original).click().build().perform();
    }
}

Comment: Actions is not yet implemented in Selenium 3: http://stackoverflow.com/a/41114265/1512961
Comment: Possible duplicate of [How to perform mouseover function in Selenium WebDriver using Java?](http://stackoverflow.com/questions/17293914/how-to-perform-mouseover-function-in-selenium-webdriver-using-java)
Comment: @swinkler : code is almost same but didn't work
Comment: What version of firefox browser do you have installed?  v3.0.0
======

IMPORTANT CHANGES

* Firefox is only fully supported at version 47.0.1 or earlier. Support
  for later versions of firefox is provided by geckodriver, which is
  based on the evolving W3C WebDriver spec, and uses the wire protocol
  in that spec, which is liable to change without notice.
* You may wish to choose an ESR release such as 45.4.0esr or earlier.
* Firefox 47.0.0 is not supported at all.
Comment: My general advice is to drop back to selenium v2.53.0 and firefox browser 47.0.
Comment: Note [Marionette and geckodriver are not yet feature complete. This means it does not yet offer full conformance with the WebDriver standard or complete compatibility with Selenium.](https://github.com/mozilla/geckodriver). I don't like living on the edge, even though visiting can be fun.
Comment: What exactly did not work?
Answer: Mouse hover operation can be achieved with Java script executor(without action classes):
String javaScript = "var evObj = document.createEvent('MouseEvents');"
            + "evObj.initMouseEvent(\"mouseover\",true, false, window, 0, 0,
0, 0, 0, false, false, false, false, 0, null);"
            + "arguments[0].dispatchEvent(evObj);";
    ((JavascriptExecutor) driver).executeScript(javaScript, hoverElement);
    assertion


Triangular inequality of spherical distance

Question: If $a=(a_1,a_2,a_3)$ and $b=(b_1,b_2,b_3)$ are points on a unit sphere, the distance from $a$ to $b$ along the surface of the sphere is $d(a,b)=\arccos(a\cdot{} b)=\arccos(a_1b_1+a_2b_2+a_3b_3)$. But does this distance function satisfy the triangle inequality?
Comment: @DavidK You're right, I overlooked that arccos removes ambiguity. Deleting comment.
Answer: In a word "yes." Geometrically, this function is the great circle distance. This is the infimum of arc lengths of piecewise-smooth paths, which "obviously" satisfies the triangle inequality because a concatenation of two piecewise-smooth paths is piecewise-smooth.
There are also proofs based on judicious choices of coordinates, and/or spherical trigonometry, but I don't have references offhand.


Fully Convolutional Neural Network Exploding Logits and Loss

Question: I am trying to train a fully convolutional neural network for 3D medical image segmentation, I have started from the architecture of this paper with the differences being that I have images of varying sizes so I train the network one image at a time (no batching) and I use relus instead of prelus as the non-linearities.
The problem I am having is that the outputs of the model before the softmax/sigmoid are too large (around 1e32 each logit) and when calculating the cross entropy loss the calculation blows up and returns infinity or nan.
At first I thought this might be due to exploding gradients so I tried gradient clipping and the problem remained. After this I just took the outputs and divided them by a large number (1e32) and I started to get real values for the loss function.
My question is, what it the correct (certainly more elegant way) of achieving reasonable values for the logits , perhaps some sort of local normalisation at the end of each convolution layer?
Comment: What package are you using to construct the model? Also, how are you initializing your weights?
Comment: I am using tensorflow 1.2 and initialising the weights with [truncated_normal](https://www.tensorflow.org/api_docs/python/tf/truncated_normal). I want to try the xavier initialiser but am still trying to figure out how it translates to 3D convolutions (tensorflow does have it for [2D convolutions](https://www.tensorflow.org/api_docs/python/tf/contrib/layers/xavier_initializer)). Also, all my biases start at the value of 1.0.
Comment: P.S I have made a post regarding [Xavier initialisation for 3D convolutions](https://stats.stackexchange.com/questions/291321/xavier-initialisation-of-weights-for-3d-convolutions).
Answer: Try either removing some layers or reducing the learning rate. If explosion happens before calculating the first or second loss, reducing the LR won't help.
I had the same problem and now I'm stuck with LR=0.001. Tell me if you found something better, so I can try it too.
Comment: I did find a solution afterwards, initialising the weights to smaller values. Before I sampled the initial weights from uniform distribution with zero mean and unit variance. Now I sample them from a distribution with zero mean and variance calculated with the Xavier Glorot method. I can use whatever learning rate I want, it doesn't explode.
Comment: reducing the learning rate worked for me


How to access the results of mongodb find() operation using mongodb javascript native driver

Question: I have a database in mongodb and I'm connecting to it through NodeJS and mongodb native driver. I'm trying to write a javascript code to print in the browser the information retrieved from the database through db.foo.find() operation.
I am currently able to print the value part of the json data. However, i need to print the key part as well.
Example : json data { key1:v1, key2:v2 ....}
i need a way to access the key1 and key2 values through javascript code without knowing them prehand??
Answer: You can use the for...in syntax to iterate over the keys of an object.
Answer: <code>Object.keys(json).forEach(function (key) {
    console.log(key);
});
</code>


Is it reasonable to run hundreds of sites by one Drupal core?

Question: There are more than 100 sites that are supported by our company and they can be presented as sub domain as well. from technical perspective is it reasonable to run all of these sites using only one Drupal core? is there any drawback in doing such thing? or we should have multiple cores?
Answer: Technically, there shouldn't be. But even if I had enough server resources, I'd reconsider my approach. A few problems I can think about. Note that they are really small annoyances and there are workarounds. If each site of your network has to be a very serious site, and all you are expecting is less files on the server and ease of updates, I think it's a bad idea.

Your sites.php file will get larger. You can specify which settings.php file should be used in the sites/sites.php file. That file will get larger with the number of sites in your network. However, in a age that you store 100 configurations in $GLOBALS, this shouldn't be a problem.
Your modules page will load slower if you put all modules in sites/all/modules folder, but only want to use them in a few sites.
In core or shared module updates, make one wrong move and everyone will know.
You can't use different robots.txt.
In fact, you can't use just about any "known files". favicon.ico, apple-touch-icon, Bing verification file, oh gosh.
Say hello to the complicated vhosts file and .htaccess for me. I'm a fat guy and so they should be.
Comment: Does it impose any overload to the sites? or make the sites slower ?
Comment: I'd doubt it will make sites slower all. More modules = slower modules page. That'll be all AFAIK.
Comment: @AyeshK's point 3 is a serious concern, in my opinion. Whenever I've worked with mulisites, I've had nasty surprises with updates.
Comment: Besides, it takes somewhat effort to run database updates for each site. As for drush, since it does db updates automagically, it doesn't really matter you are running multi sites or separate sites.
Comment: the forth point is not true you can use this module https://drupal.org/project/robotstxt to create `robots.txt` for every site
Comment: Yes there are workarounds. But they either add some unnecessary overhead to the site and/or make it difficult to manage as your network grows.
Comment: we have a main and very big website and lot's of other websites that are belong to our company. all of them are multi language and we are going to design different theme for each one. the only reason why we want to have one core, is to increase the main website rating, in this way when people visit the smaller websites, their statistic will be added to the main website.
Comment: Have you considered DomainAccess module for this ?
Answer: Certainly, there is a cap where it makes more sense to separate the stacks for performance reasons.
@Ayesh K made several good points.  There are ways to deal with most of these issues:

sites.php isn't required.
This is true.  Sorry :)  However, you can put modules only needed for [siteA.com] in /drupal/sites/siteA.com/modules/.  Then those modules won't show up in the other sites' module list.
So true.  Definitely use drush to do updates.  It will make backups beforehand and auto-rollback on failures.
As @Drupalist mentioned: https://drupal.org/project/robotstxt.
I think there are solutions here, at least for favicon.
Modular-style includes for your http server can help this. (look at what Aegir does for Nginx as an example).

Something that stood out in my mind in this discussion is OPcode caching.  Using opcache, APC or similar, I think you will benefit from the single stack (multi-site).
It would largely be determining:

How you want to best utilize your hardware for performance.
If you can solve the issues mentioned by Ayesh (or they aren't an issue for your use).
Comment: we have a main and very big website and lot's of other websites that are belong to our company. all of them are multi language and we are going to design different theme for each one. the only reason why we want to have one core, is to increase the main website rating, in this way when people visit the smaller websites, their statistic will be added to the main website.
Comment: Thanks for mentioning me:) Good point about OPcode caching. I think both methods have their pros and cons so it's up to the actual project to determine which way to go.
(and that's a nice T Shirt you've got!)


If $x^a \equiv x^b \bmod p$, what can we say about $a$ and $b$?

Question: If $x^a \equiv x^b \bmod p$, what can we say about $a$ and $b$, for $p$ prime?
Is there any way to show the relationship between $a$ and $b$ specifically? It doesn't seem to be the case that $ a \equiv b \bmod p$ for example.
Answer: All that you can say is that the order of $x$ divides $b-a$. Relatedly, all that you know about the order of $x$ without any additional information is that it is a divisor of $p-1$.
Comment: Then what if $x$ were a primitive root mod $p$ (for example)?
Comment: Then you'd know that the order of $x$ is $p-1$.
Comment: So p-1 divides b-a in that case, implying b-a = 0 mod p-1, implying a = b mod p-1?
Comment: Yes, that is correct.
Answer: By Little Fermat,
$$\forall x\enspace  x^a\equiv x^b\mod p\iff \forall x\enspace  x^{a-b}\equiv 1\mod p\iff a\equiv b\mod p-1.$$
For a specific $x$, if you know $x$ is a primitive root of unity $\mod p$, of course you have the same conclusion.
For a general $x$, all you can say is $a\equiv b\mod o(x)$, i.e. $a\equiv b\;$ mod$\,$ a divisor of $p-1$.


how to stop view disappearing when navigation controller left bar button pressed

Question: I am rookie to iOS .In my child view controller i made some modification in data. I inserted a done button to store a data and pop the view controller from navigation controller stack. if i press navigation controller back button it automatically goes to back without saving data. if i made any modification in data and then i pressed back button i need show alert as "modifications are made are sure want to go back". if the user press the cancel button in alert view i need to stop view disappearing and still stand on same view controller.If anybody have the answer please help me.
Comment: It looks like you should present the view modally. That way there's no navigation bar or back button. The proposed solution works fine, but I think that conceptually the view should be modal.
Answer: I think this is a way to do it
    - (void)viewDidLoad{
        [super viewDidLoad];
        [self.navigationItem setLeftBarButtonItem:nil];
        [self.navigationItem setHidesBackButton:YES];

    UIButton *myButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 100, 44)];
    [myButton setImage:[UIImage imageNamed:@"back.png"] forState:UIControlStateNormal];
    //back.png = your image name
    [myButton setTitle:@"Back" forState:UIControlStateNormal];
    [myButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [myButton addTarget:self action:@selector(backButtonTapped:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *customBackButton = [[UIBarButtonItem alloc] initWithCustomView:myButton];
    [self.navigationItem setLeftBarButtonItem:customBackButton];

    }

    - (void)backButtonTapped:(id)sender{
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Message" message:@"modifications are made are sure want to go back" delegate:self cancelButtonTitle:@"Go Back" otherButtonTitles:@"Stay Here", nil];

        [alert show];
    }

    - (void)alertView:(UIAlertView *)alertView
    clickedButtonAtIndex:(NSInteger)buttonIndex{
        if (buttonIndex == [alertView cancelButtonIndex]){
            [self.navigationController popViewControllerAnimated:YES];
        }else{
            //Stay on the page and do something
        }
    }

Don't forget to add <UIAlertViewDelegate>
Comment: just add the left bar button (override) with yours.. and make a selector and do the alert part in that selector. The above answer is fine for your requirement
Comment: This is the right answer... but if i inserted a custom navigation back button it don't shows the arrow mark... so i need to detect back button touched and then i need to show alert view...
Comment: @karthikjin you must find a back arrow icon for yourself for example like in this
[link](https://www.iconfinder.com/icons/352020/arrow_back_icon#size=32).Download the back icon from link and rename it as "back.png" and add it to your project.Then you can see a back button.Make your back button's size 32x32 for now.
Comment: Glad it helped @karthikjin


Sql Server - Conversão de Hora (HH:mm) para Decimal

Question: Olá, estou trabalhando em um sistema que requer conversão de horas em decimal e está apresentando erro de conversão de HORA (HH:mm) para decimal quando o total de horas ultrapassa 23:59.
Para melhor entendimento se eu tento converter para decimal a HORA '23:59' não ocorre erro, porém se eu tento converter '60:59' ocorre o erro 'The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.'
Qual seria a forma ideal para que um total de horas:minutos maior ou igual a 24:00 sejam convertidos corretamente para decimal?
DECLARE @HorasAtendidas VARCHAR(5) = '23:59', --Se mudar para 60:59 ocorre o erro citado.
@CargaHoraria DECIMAL(18, 2)

SET @CargaHoraria = (
SELECT
                CONVERT(NUMERIC(18,4),ROUND(DATEDIFF(ms, 0,
                    RIGHT('0' + CONVERT(VARCHAR, SUM(CONVERT(INT, LEFT(@HorasAtendidas, 2))) + (((SUM(CONVERT (INT, RIGHT (@HorasAtendidas, 2)))) - (SUM(CONVERT(INT, RIGHT(@HorasAtendidas, 2))) % 60)) / 60)), 2) + ':' +
                        RIGHT('0' + CONVERT(VARCHAR, SUM(CONVERT(INT, RIGHT(@HorasAtendidas, 2))) % 60), 2)
                ) / 3600000.000000, 4))
                )

select @CargaHoraria

Obrigado desde já.
Comment: Preciso converter um total de horas para decimal e esse total pode ultrapassar 24:00.
Comment: Imagine o cenário, faço uma consultoria de 60 horas e 30 minutos para meu cliente (60:30). No banco de dados a carga horária deverá ser armazenada em decimal.
Answer: Richard, segue uma sugestão para testes, verifique se são obtidos os resultados esperados:
DECLARE
  @HorasAtendidas VARCHAR(5) = '60:59',
  @HorasAtendidasInt int,
  @CargaHoraria DECIMAL(18, 2);

SET @HorasAtendidasInt = CONVERT(INT, REPLACE(@HorasAtendidas, ':', ''));
SET @CargaHoraria = @HorasAtendidasInt / 100 + @HorasAtendidasInt % 100 / 60.0;

select @CargaHoraria

Espero que ajude
Comment: Muito obrigado! Sua sugestão deu certo! Era isso mesmo!! Você é o cara!


Second-order nonlinear ODE $d^{2}y/dx^{2} =y^{-1/2}f(x)$

Question: Has this second-order nonlinear ODE been studied before or been given a known name that I can look up for further study or investigation?
$$ y'' \sqrt{y}+f(x)=0, $$
in single real variable $x$, with $y=y(x)$, an arbitrary function $f(x)$, and with the double primes indicating second derivative with respect to $x$?
Comment: I am not sure if it is transformable to a known ODE, or if it is integrable in general. However, if I were to investigate it I would start by looking at simpler cases. i.e. $f\equiv 0$, and $f\equiv const$. The first is very easy. The latter a first integral is easily attainable, however a general solution a lot more difficult and you will have to consider different branches, and I think at some stage you will have to invert a cubic.. egh. I would then consider the initial value problem $y(x_0)=y_0$, $y'(x_0)=v_0$. First numerically, then maybe expand the nonlinearity about $y_0$
Comment: @epiliam thanks for your comment. Apart from the simplest $f$ cases, I was thinking to investigate whether it is scale invariant or equidimensional under transformation for certain (say, polynomial) forms of $f(x)$. What do you think? I have tried transformations like $y=u^{2}$, $y=e^{u}$, $y=u^{n}$ and $y=\sin u$ to no avail.
Comment: Even if $f(x)=const$, the problem seems to be difficult.
Comment: @user135626 I think that is an interesting path to take. Indeed, if you were to find any coordinate transformation under which the ODE is invariant I think that would be a very interesting result as it leads straight in to Lie's theory of DEs
Comment: @ClaudeLeibovici indeed it is. However, I was able to write down a solution which involves the inverse of a cubic.
Comment: @epiliam. I agree with you  for the inverse.
Comment: @epiliam would you please advise or direct me to an brief introduction to this Lie theory for DEs with applied examples? I guess canonical/Hamiltonian form would be a special case for area-preserving transforms, right?
Comment: @user135626 I must admit I am not an expert on the topic (I'm a numerical guy). My knowledge of the topic is because I read Dresner's "Applications of Lie's Theory of Ordinary and Partial Differential Equations" (which happens to be sitting next to me on my desk right now). I thought it was quite a good introductory text, however, having not read any other texts on the topic I don't know how it stacks up. You'll probably need a good understanding of group theory before hand.
Comment: @epiliam thanks. Can you please advise on how you got the cubic solution analytically?
Comment: @epiliam Cannot we simply say that, a particular solution for $y'' \sqrt{y} +c_{1}=0$ by inspection is simply of the form $y=A x^{4/3}$, while the general solution for the associated homogeneous eqn $y''=0$ is of the form $y=Bx+C$, therefore the final general solution form is $y=Ax^{4/3}+Bx+C$, and then we apply initial conditions?
Comment: @user135626 You cannot do that for non-linear problems. I'll briefly write up how to solve the problem with a constant $f$ shortly.
Comment: @epiliam oh, that's right. My mistake
Answer: Let us write the equation in the form
\begin{align}
     y' ={}& v\\
     v' ={}& \frac{f}{\sqrt{y}}
\end{align}
and as mentioned in the comments we'll consider the case $f\equiv const\ne 0$. We write $$ vv' = \frac{y'}{\sqrt{y}}f $$ which, due to a constant $f$, has the first integral $$ \frac{1}{2}v^2 = 2y^\frac12 f + c $$ where $c$ is a constant of integration. Let us define $$2y^\frac12 f + c = \frac12 u^2$$ from which we infer $$y=\frac{1}{4f^2}(\frac12 u^2 - c)^2\implies y'=\frac{1}{2f^2}(\frac12 u^2 - c)uu' $$ and so $$(y')^2=v^2=u^2$$ naturally leads to the two branches $$(\frac12 u^2-c)u'=\pm 2f^2.$$ Integrating yields $$\frac16 u^3 - cu = b\pm2f^2x$$ where $b$ is another constant of integration. Taking $c=0$ there is an obvious solution (well... two obvious solutions as it has two branches... or even six if we consider the complex branches of $\cdot^\frac13$) $$u=(6(b\pm2f^2x))^\frac13\implies y=\frac{1}{16f^2}(6(b\pm2f^2x))^\frac43.$$ Setting $b=0$ yields $$y=\big(\frac{9}{4}f\big)^\frac{2}{3} x^\frac{4}{3} .$$ However let's go for something a bit harder with $c\ne 0$ (in particular with $c>0$). We'll tidy things up a bit and write $p=6c$ and $q\equiv q(x)=-6(b\pm2f^2x)$. Thus we have that
$$u^3-pu+q=0.$$ Okay, now cubics are gross but lets plow ahead anyway. I will assume from now on that $\big(\frac{q}{2}\big)^2\le\big(\frac{p}{3}\big)^3$. Note this implicitly assumes $p>0$ (which in turn implies $c>0$). I'll leave you to consider the other cases. There is a cubic formula but I don't like it and I prefer to write solutions in terms of trig or hyperbolic trig functions. Let us write $u=r\cos(\frac{\theta}{3})$, $r>0$. Applying the triple angle formula, an obvious choice is for $r$ to satisfy $\frac34 r^3 = pr$. Or equivalently, $$r = 2\big(\frac{p}{3}\big)^\frac12.$$ This leaves us with $$\frac{1}{4}r^3 \cos(\theta)+q=0\implies \cos(\theta) = -\frac{\frac{q}{2}}{\big(\frac{p}{3}\big)^\frac32}.$$ Note that my earlier assumption ensures that $|\cos (\theta)|\le 1$. Therefore we can write down all three solutions to the cubic via
$$u=2\big(\frac{p}{3}\big)^\frac12\cos\big(\frac{\theta + 2n\pi}{3}\big)$$ where $n\in\mathbb{Z}$ and $$\theta = \arccos\Big(-\frac{\frac{q}{2}}{\big(\frac{p}{3}\big)^\frac32}\Big) = \arccos\Big(\frac{3(b\pm2f^2x)}{(2c)^\frac32}\Big).$$ Recalling our formulae for $y$ and $p$, $$y = \frac{c^2}{4f^2}\Big(4\cos^2\big(\frac{\theta + 2n\pi}{3}\big) - 1\Big)^2.$$ Hopefully I haven't made any mistakes. Note that there are implicitly 6 different branches contained in this solution.
Answer: For the case where $f(x)$ is a constant $a$, first switch variable and write
$$-\frac {x''}{[x']^3 }\sqrt y=a$$ Now, reduction of order $p=x'$
$$\frac {p'}{p^3}=-\frac a{\sqrt y}\implies p=\pm \frac{1}{\sqrt{4 a \sqrt{y}+ c_1}}$$
$$x'=\pm \frac{1}{\sqrt{4 a \sqrt{y}+ c_1}}\implies x+c_2=\pm\frac{\left(2 a \sqrt{y}-c_1\right) \sqrt{4 a \sqrt{y}+c_1}}{6 a^2}$$ Squaring and using $z=\sqrt{y}$
$$16 a^3 z^3-12 a^2 c_1 z^2+c_1^3=36a^4(x+c_2)^2 \tag 1$$
Assuming $c_2=0$ and $z(0)=0$ imply $c_1=0$ which gives in the real domain
$$z=\sqrt[3]{\frac{9 a }{4}x^2} \implies y=\Bigg[\frac{9 a }{4}\Bigg]^{\frac 23} \, x^{\frac 43}$$
Otherwise, we just need to solve the cubic equation $(1)$ in $z$ .
Comment: Thanks. How did you "switch variable" in the first step? This seems to me like the key step.
Comment: @user135626. How did I ... what ? By the way, are they any boundary conditions ?
Comment: Sorry text got truncated by error. I was asking: How did you "switch variable" in the first step? This seems to me like the key step.
Comment: @user135626. It is a quite standard trick (at least for me). On the search bar, type my name plus *switch variables*. You should find 55 entries. Cheers :-)
Comment: Yes, I can see that you use it quite a lot, indeed, in your entries :-). Is this related to the hodograph transform? I am still confused; perhaps it is my ignorance! I would appreciate it if you would please explain how it is done or kindly refer me to a text or webpage that explains it. I tried looking in your other entries, and you seem to give it straight away, but it is not clear to me how it is done. Thanks.
Comment: @user135626. It it simple : use the relation between $x'(y)$ and $y'(x)$ (trivial) and the next (which I wrote). Do not go beyond since the formulae start to be a nightmare. To see the derivation : https://math.stackexchange.com/questions/566507/prove-that-d2x-dy2-equals-d2y-dx2dy-dx-3
Comment: Many thanks. I see it now. By the way, the boundary conditions are $y(0)=0, y(x_{0})=y_{0}$.
Comment: I think this approach when generalized is called the hodograph method in PDEs.
Comment: I got originally the same answer by noticing that the equation was autonomous ($x$ doesn't appear explicitly or the transform $x\rightarrow x+ const$ leaves it unchanged), which invites the substitution $u(y)=y'(x)$ and with $y$ now as independent variable. Then I realized that is basically equivalent to your method of switching the variables and leads to the same integral… Your approach, similar to hodograph transform, I think is smarter, though.. cheers
Comment: @epiliam Thanks for this, but I am not sure I fully understand why we need first $y'(0)\ge 0$ and we need it equal zero if $y(0)=0$? Are you saying that, to keep the square root argument nonnegative, we can keep $y$ non-decreasing over our domain ($x=0$ to $x=x0>0$) by making its slope always positive?
I recognized from Picard's theorem that a partial derivative in $y$ would give $1/\sqrt{y}$ term that is singular at 0. But this theorem only gives sufficient (not necessary) condition for a unique solution to exist. So your point may better help me in this, I can understand it.  Thanks
Comment: @user135626 I ended up deleting my comment as I realised it didn't apply to the two point boundary value problem. To check if that is well posed you end up with a **very** complicated set of conditions on $y_0$, $x_0$. However if you are interested in a unique real solution in a neighbourhood of the origin, then the *initial value problem* $y(0)=0$, $y'(0)=v_0$ is ill posed for all $v_0 \ne 0$. Try going through all the cases your self and figuring out why this is.
Comment: @epiliam I think you are right, and physically (from the physics related to the problem) it makes sense, but I am trying to prove it mathematically. Here is my attempt: according to Picard's theorem, if we have an equation in the form $y'(x)=F(x,y)$, then if we can show that $F, \partial F/\partial y$ are continuous at the initial point (here $x=0, y(0)=0$) then it is a well-posed problem. So, if I multiply both side of $y''=-a/\sqrt{y}$ by $y'$ and then integrate we have $y'=F(y)=\pm\sqrt{c-4a\sqrt{y}}$, where both $F$ and $\partial F/\partial y$ are indeed continuous at $(x,y)=(0,0)$ ,right?
Comment: Does that make sense? I would appreciate it if you can let me know what you think of this method, or if you have advice on other methods to use to conclude that $y'=0$ is needed for a unique solution of the initial value problem. Thank you.


Debug certain project among several

Question: I open two project in VisualStudio2013 "GoodBye" and "SayHello". I open and edit project "SayHello" but when I press button Debug in Top - startup the project "GoodBye".
How select the project "SayHello" as main and then I can sturtup it?
Answer: Right click on the project then choose the option "set as startUp project"
Comment: I have only 12 scores. Add me scores and I mark your answer =)
Comment: glad to help :) but if the answer resolved your problem you should mark it as valid

Debug certain project among several


Como alterar conteúdo de .htaccess via php?

Question: Queria saber se há algum jeito de se alterar o .htaccess via php.
Um exemplo do que desejo é que pelo htaccess posso restringir o acesso de um determinado ip com o comando:
deny from 220.127.116.11

Caso eu quisesse "desbloquear" o acesso de usuário via php(numa área administrativa por exemplo), sem ter que mexer no próprio arquivo, teria essa possibilidade via php?
Comment: `file_get_contents()` para ler o arquivo, `file_put_contents()` para escrever no arquivo
Comment: Sim, mas como poderia usar esses comandos para remover essa linha do comando deny? Com o file_put_contents() eu coloco conteúdo no arquivo, mas e para remover?
Comment: é apenas uma dica de onde poderá começar. Mãos a massa e boa sorte!
Comment: hehe, vou tentar sim, mas caso não consiga, voltarei aqui
Answer: Você pode tentar esse, só trocando o "127.0." pelo IP inteiro ou por parte.
Lembre-se que se colocar parte do ip, irá bloquear todos os ip que começam com o número definido por você
<?php
$ip=$_SERVER['REMOTE_ADDR'];
$deny_ip="127.0.";
if($ip==$deny_ip){
echo "acesso negado";
exit;
}
if(sizeof(explode($deny_ip,$ip))!=1){
echo "acesso negado";
exit;
}

echo "acesso permitido";
?>


Adding char to linked list

Question: I am trying to write an abstract data type to represent sets of integer items using linked lists.
My program works fine for this. I want to use user input sentence and store this in decimal value for input to the linked-list set.
My program crashes when I enter more than 10 chars in this sentence and I'm not sure why. Below is the long code with the fgets input highlighted with * at the bottom.
#include<stdio.h>
#include<stdlib.h>
#include <strings.h>

struct linkedListElement{
int data;
struct linkedListElement * next;
                    };

struct linkedListSet {

struct linkedListElement * header;
struct linkedListElement * current;
struct linkedListElement * temp;
int size;
                };

struct linkedListSet * createdSet (){

struct linkedListSet * newSet = malloc(sizeof(struct linkedListSet));

newSet->header = malloc(sizeof(struct linkedListElement));
    newSet->current = malloc(sizeof(struct linkedListElement));
    newSet->temp = malloc(sizeof(struct linkedListElement));
newSet->size = 0;
return newSet;
}

int addItem (struct linkedListSet * setPtr, int info){

    if(linkedList_lookup(setPtr, info)){return 0;}
        struct linkedListElement * newElementPtr = malloc(sizeof(struct      linkedListElement));

newElementPtr->data = info;

if(setPtr->header->data == 0){
    setPtr->header = newElementPtr;
    }//if first element set as header

if(setPtr->current->data != 0){ //if it is not first element last element points to       new element
    setPtr->current->next = newElementPtr;
                                }

setPtr->current = newElementPtr;
setPtr->size++;

return 1;

};

int linkedList_remove(struct linkedListSet * setPtr, int item){
if(!linkedList_lookup(setPtr, item)){return 0;};

linkedList_lookup(setPtr, item);

setPtr->temp->next = setPtr->current->next;
setPtr->size--;

return 1;

};

int linkedList_lookup(struct linkedListSet * setToBeSearched, int numToFind){

struct linkedListElement * i;
i= setToBeSearched->header;
int found = 0;
int count = 0;
setToBeSearched->temp = setToBeSearched->header;

for(count = 0, i= setToBeSearched->header; i->next !=NULL,count<setToBeSearched-    >size; i = i->next, count++){

    if(i->data == numToFind){ found = 1; setToBeSearched->current =     i;}//current points to : found matching element
    else if(found != 1){ setToBeSearched->temp = i;}// temp points to : element     before found matching element
}
if(found){return 1;}
return 0;
};

void printMyList(struct linkedListSet * setToBePrinted){

struct linkedListElement * i;
int count = 0;
for (count = 0, i = setToBePrinted->header; count<setToBePrinted->size; i = i-  >next, count++){
    printf(" %d", i->data);

};
printf("\n");

};

int main(){
//create set
struct linkedListSet * firstSet = createdSet();
struct linkedListSet * secondSet = createdSet();
struct linkedListSet * comboSet = createdSet();

addItem(firstSet, 300);
addItem(firstSet, 200);
addItem(firstSet, 100);
addItem(firstSet, 5);
addItem(firstSet, 37);
addItem(firstSet, 299);
addItem(firstSet, 201);
addItem(firstSet, 101);
addItem(firstSet, 51);
addItem(firstSet, 371);
addItem(firstSet, 301);
addItem(firstSet, 202);
addItem(firstSet, 102);
addItem(firstSet, 52);
addItem(firstSet, 377);
addItem(firstSet, 305);
addItem(firstSet, 205);
addItem(firstSet, 150);
addItem(firstSet, 55);
addItem(firstSet, 375);
addItem(firstSet, 259);
addItem(firstSet, 251);
addItem(firstSet, 151);
addItem(firstSet, 551);
addItem(firstSet, 571);
addItem(firstSet, 3501);
addItem(firstSet, 2052);
addItem(firstSet, 1052);
addItem(firstSet, 525);
addItem(firstSet, 3757);

addItem(secondSet, 340);
addItem(secondSet, 200);
addItem(secondSet, 120);
addItem(secondSet, 52);
addItem(secondSet, 3799);
addItem(secondSet, 341);
addItem(secondSet, 201);
addItem(secondSet, 121);
addItem(secondSet, 521);
addItem(secondSet, 3792);
addItem(secondSet, 342);
addItem(secondSet, 202);
addItem(secondSet, 122);
addItem(secondSet, 53);
addItem(secondSet, 3739);
addItem(secondSet, 3440);
addItem(secondSet, 2040);
addItem(secondSet, 1240);
addItem(secondSet, 524);
addItem(secondSet, 37499);
addItem(secondSet, 3441);
addItem(secondSet, 2041);
addItem(secondSet, 1241);
addItem(secondSet, 5241);
addItem(secondSet, 37492);
addItem(secondSet, 3442);
addItem(secondSet, 2042);
addItem(secondSet, 1242);
addItem(secondSet, 534);
addItem(secondSet, 37439);

printMyList(firstSet);

if(linkedList_lookup(firstSet, 100)){
    printf(" \nfound number in list");
    };

printf("\ncurrent data is now set to : %d  and temp to : %d\n",firstSet->current->data, firstSet->temp-> data);

linkedList_remove(firstSet, 100);

printMyList(firstSet);

//**********************************************************************
struct linkedListSet * charSet = createdSet();
char strBuff1[60];

printf(" Please enter sentence: ");
fgets(strBuff1, 60, stdin);

int i = 0;

for ( int i = 0 ; strBuff1[i] != 0; i++){
    printf(" %c ", strBuff1[i]);
    addItem(charSet, strBuff1[i]);
}
//***********************************************************************
return (0);

}

Comment: I am new to using fgets and feel there must be a better way to implement the code highlighted at the bottom.
Answer: i->next !=NULL,count<setToBeSearched->size

should be
i->next !=NULL && count<setToBeSearched->size

should it not?
You are not setting the newElementPtr->next pointer in addItem.
There are a few other problems too
struct linkedListSet should contain pointers to the struct linkedListElement you have created. Copying data from these structures into duplicated linkedListElement in the struct linkedListSet is unreliable and unnecessary.
Also, typedefs for your structs would make the code easier to read.
Comment: wow thank you so much for this help. The && has stopped the program from crashing and am working on the second change now. Can't thank you enough.
Comment: I have to say the program still crashed for me after I fixed that, so don't get your hopes up too much :) Have a good look at that linkListSet struct, it is definitely a weak link. You should not need that temp field, and linked lists should be terminated with a null next pointer anyway, so size isn't strictly needed.
Comment: Ok thanks again - I am working through these changes. I will add a NULL pointer to addItem new elements and also initialise first element(header) to NULL point initially. I am using the temp pointer for the _remove function so that previous element points to element that removed element pointed to.
Comment: I will try get rid of size and change for loop conditions to just != NULL

Adding char to linked list


Start tab for new thread, and close tab and end thread

Question: I followed this tutorial on http://www.dotnetspark.com/kb/1867-create-tab-control-wpf.aspx to create closable tabs for a WPF application.
I'm creating a multithreaded application and I'll be using closable tabs from the link above.  I want each thread to have its own tab and update it as it runs. Should I create the tab inside the new thread or create the tab in the main thread and update it from the new thread? What is the proper way of doing this?
How can I make the thread end when the tab is closed?
Regards!
Answer: You'll have to use the UI thread to render/display tabs. See this link(archive). As the title says "Build More Responsive Apps With The Dispatcher".
Answer: Neither. Have the main thread create the tab, update the tabs when directed to do so by the various other threads, and command the thread to terminate when the tab is closed.
Learn how to use the dispatcher to coordinate threads.
If a thread does some work that, by the program logic, should not be done at that time, that thread's code is broken. Fix it. If the thread is not supposed to continue running when the tab is closed, code it not to continue running when the tab is closed. Don't leave the thread broken, coded to do work when that work should not be done by program logic, and then try to fix it someplace else.
This is a backwards way of thinking about threads. Threads are just vehicles that do work. You control them by controlling the work. You write every line of code that the threads execute. If you don't want a thread to X in condition Y, code it not to do X in condition Y.
In sum, if program logic says work X should not be done when tab Y is closed, do this:
1) Somewhere, store a flag that indicates whether work X should be done or not.
2) In the code that does work X, check this flag. If it's set to no, don't do the work. By program logic, the work should not be done. Doing it is broken.
3) When the tab is closed, have the UI thread set the flag to stop doing work X.
Tabs should not correspond to threads. That makes no logical sense. Tabs should correspond to whatever is displayed in the tab. (They may 'happen to' correspond to threads indirectly, but this is not primary. Threads really correspond to whatever work is associated with the tab.)
In principle, if a different thread took over the same work, shouldn't it still be in the same tab? Or should the same data suddenly go in a different tab just because a different thread is producing it? That you happen to always do the work that goes in that tab in the same thread is an implementation detail that should not be reflected that way in the architecture. As you have learned, that just creates silliness where you have to figure out which thread is doing the work when you really don't care.
Comment: Here is where I'm stuck at: Lets say I create 7 threads which would open 7 tabs, when I close one of the tabs, it has to know which thread belongs to that tab so I can abort it. What is the best way to do that?
Comment: @Ayra You do not want to create one Tab per Thread because WPF does not allow threads to alter objects created on other threads. Instead you want to create a thread for the duration of some long running process, which automatically ends when the process is finished. You could also create a control that inherits from `TabItem`, which would start a thread in Constructor and ends the thread when the TabItem gets disposed. I wouldn't recommend that route though.
Comment: @Arya: It does not have to know which thread belongs to that tab, because it doesn't care which thread gets stopped. It's the thread's job to terminate when the job it is doing is done. The UI thread should simply indicate that the job associated with that tab is done, and the tab thread shouldn't continue running after its job is done. (You're coding everything, so make it work together.)
Comment: @David Schwartz The work of the thread will never end. This is a network application and I want it to run 24/7 and use the tabs to write the updates. When creating a ClosableTab is it possible to pass it the thread name and return the name through RoutedEventArgs?
Comment: @Arya: The work of the thread ends when the tab is closed. You don't want to do anything to the thread, you want to do something to the work the thread is doing, specifically, indicate that it's finished. Then any thread that tries to work on it would notice there's no more work to do and terminate itself (or do something else). You are thinking about this in a backwards way. Think about the work that no longer needs to be done. Threads are just vehicles to do work. The work dictates what the threads do. They do the work that needs to be done and stop when no more work needs to be done.
Comment: @David Schwartz I put Console.beep() in an endless loop of the method which gets started by the new thread and when I close the tab I can still hear the beeping. I have attached the full project here http://www.mediafire.com/?q0cd87rz8hg7bp7 since this is a network application, the work would never end, so I'm trying to find the correct way of aborting the thread when the tab is closed.
Comment: @Arya: You should not put 'Console.beep' in an endless loop. You don't want to beep forever. You want to beep until the tab is closed. Write the code to do what you actually want rather than making it do something else and then later having to 'force' it to do the right thing. It should not keep beeping after the tab is closed because when the tab is closed, its beeping is done. If it keeps beeping after the work is done, it's broken. **Fix it**.
Comment: The thread should not be coded to beep when it is not supposed to beep. It is not supposed to beep if the tab is closed. If it does, the thread's logic is broken. It calls 'beep' when it should not beep. Fix the thread. Do not call beep unless you want to beep. (You are thinking about this 100% backwards. Forget about what threads happen to do the work. Make the code that does the work do the work, and only the work, that is supposed to be done. When the tab is closed, you are not supposed to beep. So why are you?)


Drupal 7 - theme default node view

Question: I would like to know the recommended way to re-theme the default node view for a certain content type.
E.g. http://dev.mysite/en/node/6547, now shows a 'list' of content fields. We would like to change this to a more clean layout.
Would using a node.tpl.php in the theme folder and then create a node--[TYPE].tpl.php for the specific node type solve this problem in the correct way?
Regards,
Wouter
Answer: Using .tpl.php files would indeed give you more control over the HTML Drupal will create in the end.
Also using a module like Display Suite (DS - drupal.org/project/ds) will give you more control over the fields in a certain display so that some settings about that field on that display are stored in database instead of in code.
Answer: Yes , You are on the right track...
For more information on templates please see Drupal 7 Template (Theme Hook) Suggestions
You can override specific nodes of a type using below tpl file name
node--type.tpl.php

To print fields in node tpl you can use below code
<?php print render($content['your_field_name']); ?>

Drupal 7 - theme default node view


extending an object stored in a database

Question: Is there a way to extend objects stored in a database?
example:
say I have an object:
{
id: 1
extends: null
type: HondaAccord
doors: 4
engine: 2 liter
dealerId: null
price: 20000
}

second object extends the first
{
id: 2
extends: 1
dealerId: 2
price: 25000
key1: value1
key2: value2
}

third Object ends the second:
{
id: 3
extends: 2
dealerId: 3
price: 27000
key1: some extended value
}

I want to be able to query the second object and get back:
{
id: 2
extends: 1
type: HondaAccord
doors: 4
engine: 2 liter
dealerId: 2
price: 25000
key1: value1
key2: value2
}

I want to be able to query the third object and get back:
{
id: 3
extends: 2
type: HondaAccord
doors: 4
engine: 2 liter
dealerId: 3
price: 27000
key1: some extended value
key2: value2
}

In a relational DB, I could normalize this data and do some complicated left joins etc to get this.
Is there a simpler way to do this in a NoSQL database?  My application requires that I be able to query these objects and get back the literal representation and also the expanded (as shown in the expected results) representation.
currently, I am doing this in Java code.  ie: fetch an object, see if it is supposed to extend another one, fetch that object and recurse through it.  If I needed to be able to grab a lot of "expanded" objects, there is a significant performance issue.
Any patterns to create something like this?  either SQL or NoSQL? seems almost like a decorator pattern but for data.
Answer: $graphlookup operation recursively matches on the "extends" and "id" attributes in the collection and returns the hierarchy for each queried document.
Apply $sort as the looked up data is not guaranteed to maintain order so we can resolve the duplicate keys in a orderly way.
Using current(3.4) prod version.
Use $arrayToObject and $objectToArray in a $reduce with $concatArrays to merge documents.
$objectToArray to produce array with key value pair for current ($$this) and $$value to concat all the key value pairs to produce an array of key value pairs followed by $arrayToObject to produce the merged document and $replaceRoot to promote as top level document.
$sort by "id" desc and "extend" desc to prefer the fields from the queried document over other lookup documents.
db.collection.aggregate([
  {
    "$match": {
      "id": 3
    }
  },
  {
    "$graphLookup": {
      "from": collection,
      "startWith": "$id",
      "connectFromField": "extends",
      "connectToField": "id",
      "as": "hierarchy"
    }
  },
  {
    "$unwind": "$hierarchy"
  },
  {
    "$sort": {
      "id": -1,
      "hierarchy.extends": 1
    }
  },
  {
    "$group": {
      "_id": "$id",
      "hierarchy": {
        "$push": "$hierarchy"
      }
    }
  },
  {
    "$replaceRoot": {
      "newRoot": {
        "$arrayToObject": {
          "$reduce": {
            "input": "$hierarchy",
            "initialValue": [],
            "in": {
              "$concatArrays": [
                {
                  "$objectToArray": "$$this"
                },
                "$$value"
              ]
            }
          }
        }
      }
    }
  }
])

You can use mergeObjects aggregation operator is available in the current dev release 3.5.13  development release which will be rolled into upcoming 3.6 release.
$sort by "id" desc and "extend" asc to prefer the fields from the queried document over other lookup documents.
db.collection.aggregate([
  {
    "$match": {
      "id": 3
    }
  },
  {
    "$graphLookup": {
      "from": collection,
      "startWith": "$id",
      "connectFromField": "extends",
      "connectToField": "id",
      "as": "hierarchy"
    }
  },
  {
    "$unwind": "$hierarchy"
  },
  {
    "$sort": {
      "id": -1,
      "hierarchy.extends": -1
    }
  },
  {
    "$group": {
      "_id": "$id",
      "hierarchy": {
        "$push": "$hierarchy"
      }
    }
  },
  {
    "$replaceRoot": {
      "newRoot": {
        "$reduce": {
          "input": "$hierarchy",
          "initialValue": {},
          "in": {
            "$mergeObjects": [
              "$$this",
              "$$value"
            ]
          }
        }
      }
    }
  }
])


jQuery Flot with PHP

Question: I was dealing today with Flot and when I try to get the data from PHP (with json_encode()) I can't get it work properly.
I could display labels but no chart is created.
PHP
    $newData = array();

    $newData[0] = array();
    $newData[1] = array();
    $newData[2] = array();

    $newData[0]['label'] = 'Slice 1';
    $newData[1]['label'] = 'Slice 2';
    $newData[2]['label'] = 'Slice 3';

    $newData[0]['color'] = '#122b45';
    $newData[1]['color'] = '#064792';
    $newData[2]['color'] = '#9e253b';

    $newData[0]['data'] = array();
    $newData[0]['data'][0] = 1;
    $newData[0]['data'][1] = 1000;
    $newData[1]['data'] = array();
    $newData[1]['data'][0] = 1;
    $newData[1]['data'][1] = 500;
    $newData[2]['data'] = array();
    $newData[2]['data'][0] = 1;
    $newData[2]['data'][1] = 100;

    echo json_encode($newData);

jQuery
$.ajax({
            url: "get-stats.php",
            type: "POST",
            async: false,
            dataType : 'JSON',
            data: {section:  section, endDate: endDate, startDate: startDate},
            success: function(data){
                $.plot($("#flot"), data,{
                series: {
                    pie: {
                        show: true
                    },
                    grid: {
                        hoverable: true,
                        clickable: true
                    }
                }
            }
        });

Can anyone tell me where I'm doing wrong?
Labels and colors are ok but it seems I can't get the data.
Thank you for your time and concern in advance.
Answer: I found the problem and solution. I had to do following for the data;
$newData[0]['data'] = array(array(1,100));

This saved my day.

jQuery Flot with PHP


Using Java ScriptEngine to perform multiple evaluation synchronously

Question: how to use a single Java ScriptEngine to perform multiple evaluation synchronously?
for example

method1 includes
sce.eval(code1);
method2 includes
sce.eval(code2);

then the evaluations ran concurrently if both methods synchronized
Comment: Its difficult to understand what your question is. Please clarify. Specifically, what do you mean by this, "then the evaluations ran concurrently if both methods synchronized?"
Comment: how to use a single Java ScriptEngine to perform multiple evaluation synchronously? <---
Answer: Synchronized and concurently doesn't fit together as one is the opposite of the other. If the eval method is synchronized you need 2 instances of the scriptengine with the same context, if it is not here comes an explanation on doing parallel/concurrent execufion.
If you want to run both method concurrently, you need more than one thread running as a single thread will sequentially run through it's execution pipeline.
Synchronized means it is thread safe and will queue all the calls made to any synchronized method of a class. For example, if m1 and m2 are synchronized, thread1 calls m1 and thread2 calls m2, the first one that will reach their respctive method will run correctly ehile the second one will wait 'til the other has exit (not totally true) the method to execute the inner code of it's method..
Now, you can take a look at the class Thread, ExecutorService and Executors if you want to run multiple threada at the same time and each will run it's own pipeline/execution atack.
Finally if you want both thread to share the same script engine, you'll have to use the same reference of that object, best way by providing it to the constructor of your object.
But, this is where problems occurs. If the script engine doesn't handle concurrency well, this might lead to some obscur weird behavior so you'll have to read the spec of the scrupt engine and validate if the implementation you are using is thread safe (hence concurrently execution safe).
Simple example :
public void launchAsync(final String code) {
   new Thread() {
       public void run() {
           engine.eval(code);
       }
   }.run();
}

This will execute the code asynchronously than the main thread meaning that calling the method twice will run them in parallel (in a different thread than this one).
Comment: so u mean that the object still will be executed concurrently in case if it is multithreaded. perhaps this is why i get the runtime error probably caused by the deadlock. so how can i arrange the object so it will ran the source asynchronously? because clone it for each resource will gonna cause over-consuming on my cpu


Elemento 'configuration' não foi declarado

Question: No Web.config, o problema ocorre na linha:
<configuration>

Error list: Elemento 'configuration' não foi declarado.
Alguma solução ?
Answer: Solução:
Ir no menu XML > Esquemas...
Procurar nome do arquivo de DotNetConfig.xsd e alterar para opção de Usar este esquema.
Aqui está a reposta original em inglês aqui.


Deriving the mean values of summed poisson distributions

Question: z is a poisson distribution, in which λ = 2.887. It has been formed by summing two other independent poisson distributions, x and y.
Three further pieces of information are given about the relationship between x and y:

The probability of x being higher than y is 34.047%
The probability of y being higher than x is 37.946%
The probability of x and y being equal is 28.005%

Is it possible to derive both λx and λy from this alone?
Answer: Not exactly, because your conditions cannot be fulfilled.
Your first two bullet points imply that $\lambda_x<\lambda_y$. The initial condition implies that
$$ \lambda_x+\lambda_y = \lambda \stackrel{!}{=} 2.887. $$
The third bullet point implies that
$$ \begin{align*}
P(x=y) &= \sum_{k=0}^\infty P(x=k)P(y=k) \\
&= \sum_{k=0}^\infty\frac{\lambda_x^ke^{-\lambda_x}}{k!}\frac{\lambda_y^ke^{-\lambda_y}}{k!} \\
&= e^{-(\lambda_x+\lambda_y)}\sum_{k=0}^\infty\frac{(\lambda_x\lambda_y)^k}{k!k!} \\
&= e^{-\lambda} I_0\big(2\sqrt{\lambda_x\lambda_y}\big) \\
& \stackrel{!}{=} 0.28005,
\end{align*} $$
where we use some WolframAlpha, and $I_0$ is the modified Bessell function of the first kind.
So what we can do is take $0<\lambda_x<\frac{2.887}{2}$, plot the function
$$\lambda_x \mapsto e^{-\lambda}I_0\big(2\sqrt{\lambda_x(\lambda-\lambda_x)}\big) $$
against it and check whether it ever intercepts a horizontal line at $0.28005$. Unfortunately, it doesn't:

<code>lambda_x <- seq(0,2.887/2,by=0.01)
plot(lambda_x,exp(-2.887)*besselI(2*sqrt(lambda_x*(2.887-lambda_x)),0),
    type="l",ylim=c(0,0.28005),xlab="",ylab="",las=1)
abline(h=0.28005,col="red")
</code>
So there is no solution to your system of equations
$$ \begin{align*}
\lambda_x+\lambda_y = \lambda &= 2.887 \\
e^{-\lambda}I_0\big(2\sqrt{\lambda_x\lambda_y}\big) &= 0.28005 \\
\lambda_x &< \lambda_y.
\end{align*} $$
You could try to find an approximate solution, in which case you would need to judge how bad violations of your conditions are relative to each other. Note that "one Poisson distribution is larger than another one" is equivalent to the Skellam distribution being positive (note how the Skellam, for a difference of $k=0$, gives the formula we got from WolframAlpha above for equality of Poissons). Also note that there is no nice closed form of the Skellam. So you will likely need to do some numerical optimization, where the relative "badness" of violations of your conditions should enter the objective function as weights in some way.
Comment: Despite the solution being impossible, this is extremely useful! Thank you!
Comment: This slightly raises the question: is it always possible to find the parameters from the probabilities of $>,=,<$  and are these always unique?
Comment: @Henry: that's an interesting question. If all we have is $\lambda_x+\lambda_y$ and $P(x=y)$, then my hunch is that if a solution exists, it is unique up to switching $\lambda_x$ and $\lambda_y$ (the modified Bessel function of the first kind appears to be monotone). If we have $\lambda_x+\lambda_y$ and $P(x<y)$, then what we need is an understanding of the tail probabilities of the Skellam. I have no intuition either way in that case.
Comment: I was more thinking of having $P(XY)$, all being in $(0,1)$ adding up to $1$, and then finding $\lambda_x$ and $\lambda_y$
Comment: For example the probabilities in the question seem to suggest $\lambda_1 \approx 1.13$ and $\lambda_2 \approx 1.21$ (which do not add up to $2.887$).
Comment: @Henry: ah, I see. So it's whether there always exist Poisson parameters $\lambda_x$ and $\lambda_y$ that satisfy the given probabilities. Good question. [I kust asked it here.](https://stats.stackexchange.com/q/470055/1352) Any ideas?


Compile an exe file inside c++

Question: I want to create a c++ program in which

I can read an external file (that can be exe,dll,apk...etc...etc). That is read the file convert them into bytes and store them in an array
Next,I want to compile the bytes inside the array
Now this is the tricky part i want to compile the bytes into an array just to check that if the bytes are working well
You may say i am converting a file into bytes and then converting those bytes back to the same file....(Yes indeed i am doing so)

Is this possible?
Comment: I don't understand the "compile the bytes" part. Just makes no sense. Also please next time format your question more cleanly, use paragraphs, punctuation and such things that help us that are not yourself understand what you mean (we usually do not read your mind).
Comment: Before replying, may I ask you what is the purpose of the application you are developing?
Comment: So sehe...how can i do that??? i know i can use ifstream to read a file and ofstream to write a file using a binary reader i can read the file  into buffer .......now what???
Answer: To test whether an executable can be loaded (not quite the same as execution):

it will succeed unless

there is a lack of permissions
the file is not accessable
one of the dependencies are not accessable (dependency libraries, e.g.)

Note that on UNIX, the same can be achieved using dlopen
.
// A simple program that uses LoadLibrary

#include <windows.h>
#include <stdio.h>

int main( void )
{
    HINSTANCE hinstLib;
    BOOL fFreeResult, fRunTimeLinkSuccess = FALSE;

    // Get a handle to the DLL module.

    hinstLib = LoadLibrary(TEXT("input.exe"));  // or dll

    fFreeResult = FreeLibrary(hinstLib);

if (hinstLib != NULL)
        printf("Message printed from executable\n");

    return 0;

}

See also

LoadLibrary Function
LoadLibraryEx Function
Comment: sehe plz help me to understand this program
Answer: Use stream copy
#include <sstream>
#include <fstream>

int main()
{
    std::stringstream in_memory(
            std::ios_base::out |
            std::ios_base::in |
            std::ios::binary);

    {
        // reading whole file into memory
        std::ifstream ifs("input.exe", std::ios::in | std::ios::binary);
        in_memory << ifs.rdbuf();
    }

    {
        // optionally write it out
        std::ofstream ofs("input.exe.copy", std::ios::out | std::ios::binary);
        ofs << in_memory.rdbuf();
    }

    return 0;
}

If you don't use an in-memory stage, it'll be far more efficient (and very large files will not cause problems):
#include <sstream>
#include <fstream>

int main()
{
    std::ofstream("input.exe.copy2", std::ios::out | std::ios::binary)
        << std::ifstream("input.exe", std::ios::in | std::ios::binary).rdbuf();

    return 0;
}

Comment: can you help me understand "//no in-memory stage:" ???
Comment: Now rdbuf() contains the byte of files...How can i compile the bytes in the rdbuf??
Comment: You first answer the question: "what does it mean to compile the bytes"? I think you want to do something with them, which makes the `in_memory` idea a good option (also: `rdbuf()` _reads_ the bytes, `in_memory` _contains_ the bytes)
Comment: Here what i am trying to do is rebuild the same application.....i am breaking a file into its bytes and then constructing the file again that is going reverse...however i want to do it is by using c++..I hope you understood
Comment: I did. My code does that. I suspect you are somehow expecting some code to 'interpret' the bytes (that would be: loading and executing). However, that is not a C++ job (it's the operating system's job to load and execute binaries); also, it doesn't help to create the same binary right back. If you want to get /another/ binary that does exactly the same, you can trick it with something like [`UPX executable packer`](http://upx.sourceforge.net/)
Comment: Allright i got it the code breaks a file into the bytes and then those bytes are written to other file....No w i f u can help me in executing those bytes not in actual environment.I am trying to work here on an virtual environment or more like an x86 emulator.where the file is checked if it would compile sucessfully...does it make any sense to you??
Comment: If the executable exists, then **obviously** it compiles successfully. That's sort of required. Writing a VM is a whole 'nother mess, and you can't just "check" and "compile" the bytes for that. You should look into how virtual machines work and how to wrap and trap an executable.
Comment: @user905481: compilation is not what you think it is. You cannot test an executable without running. However look at qemu, kvm, bochs, VirtualBox, VirtualPC, VMWare, (linux:) UserMode Linux, chroot/schroot and Xen for options on running inside a virtualized container.
Comment: Also, use (windows) [DependencyWalker](http://dependencywalker.com/) or (UNIX) ldd to test whether dependencies for loading are found.
Comment: Posted another answer for a quick-and-dirty test whether you can load a binary on windows
Comment: Thanks Sehe and peachykeen...i think i got it what i wanted
Comment: @user905481: in that case, please remember to upvote or accept the answer that helped you. Thanks

Compile an exe file inside c++


transitions between pages in flutter

Question: I'm new to flutter and java script. So I have very little experience. I want to write a small application. I made 2 pages where the list of seals and the list of objects are pulled up on api. But I want to be able to navigate through these pages through the side menu. I created this menu. But I can not go to another page from this menu. Here is my application (main). I will be grateful for your help.

import 'package:flutter/material.dart';
import 'package:flutter_app_seals/model/object_list/JsonObject.dart';
import 'package:flutter_app_seals/model/seals_list/JsonSeals.dart';

void main() {
  runApp(Mains());

}

class Mains extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        debugShowCheckedModeBanner: false,
        home: Scaffold(
            appBar: AppBar(
            centerTitle: true,
              title: Text('Seals Log'),
    ),
              drawer: Drawer(
               child: ListView(
               children: <Widget>[
                    ListTile(
                      title: Text("Seals List"),
                      trailing: Icon(Icons.arrow_back),
                        onTap:() {
                          Navigator.push(
                            context,
                            MaterialPageRoute(builder: (context) => Seals()),
                          );
                        }

                    ),
                      ListTile(
                        title: Text("Object List"),
                        trailing: Icon(Icons.arrow_downward),
                          onTap:() {
                            Navigator.push(
                              context,
                              MaterialPageRoute(builder: (context) => Object()),
                            );
                          }
                      )
                ],
             ),
           ),

         )
    );
  }
}
class Seals extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        debugShowCheckedModeBanner: false,
        home:JsonParseSeals(),

    );
  }
}

class Object extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        debugShowCheckedModeBanner: false,
        home:JsonParseObject()
    );
  }
}

Error:

======== Exception caught by gesture ===============================================================
The following assertion was thrown while handling a gesture:
Navigator operation requested with a context that does not include a Navigator.

The context used to push or pop routes from the Navigator must be that of a widget that is a descendant of a Navigator widget.
When the exception was thrown, this was the stack:
dart-sdk/lib/_internal/js_dev_runtime/private/ddc_runtime/errors.dart 231:49  throw_
packages/flutter/src/widgets/navigator.dart 2690:9                            <fn>
packages/flutter/src/widgets/navigator.dart 2696:14                           of
packages/flutter/src/widgets/navigator.dart 2095:34                           push
packages/flutter_app_seals/main.dart 41:39                                    <fn>
...
Handler: "onTap"
Recognizer: TapGestureRecognizer#d2f91
  debugOwner: GestureDetector
  state: ready
  won arena
  finalPosition: Offset(63.0, 65.0)
  finalLocalPosition: Offset(63.0, 17.0)
  button: 1
  sent tap down
====================================================================================================
Answer: Add onTap action to your ListTile:
ListTile(
  title: Text("Seals list"),
  trailing: Icon(Icons.arrow_back),
  onTap() {
    Navigator.push(
      context,
      MaterialPageRoute(builder: (context) => Object_list()),
    );
  }
),

You can read more in Official Documentation.
Comment: thanks, I tried so, but I have a mistake in the word "context" and I do not understand why!
Comment: Where are you defined `ListTile`?
Comment: I gave an example of the code above, which has changed a bit, now nothing is underlined, but still does not generate to the second page.
Comment: Can you post an error to the question or to comments?
Comment: I added a message about the problem that occurs when clicking.
Comment: https://stackoverflow.com/questions/50124355/flutter-navigator-not-working
Comment: thank you I have already dealt with the problem

transitions between pages in flutter


Mechanisms for response aggregation in event sourcing based microservices

Question: When it comes to implementing event sourcing based microservices, one of the main concerns that we've come across is aggregating data for responses. For an example we may have two entities like school and student. One microservice may be responsible for handling school related business logic while another may handle students.
Now if someone makes a query through a REST endpoint and ask for a particular student and they might expect both school and student details, then the only known ways for me are the following.

Use something like service chaining. An example would be an Api-Gateway aggregating a response after making couple of requests to couple of microservices.
Having everything replicated throughout all services. Essentially, data would be duplicated.
Having services calling each other for those extra bit of information. This solution works but hard to scale and goes against basic idea of using event sourcing.

My question is that what other ways are there to do this ?
Comment: Possible duplicate of https://stackoverflow.com/a/54676222/1235935
Comment: "Essentially, data would be duplicated"  Once upon a time, that was called caching.  It wasn't regarded as a bad thing.
Comment: You may have to create materialized view based on your events to query the data.
Answer: A better approach can be to create a separate reporting/search service, that aggregates the data from both services. For example implemented using ElasticSearch or SOLR.This now allows the users to do search and queries across multiple services and aggregates.
Sure, it will be eventually consistent, but I doubt that is s a problem. This gives a better separation of concerns and you get a nice search experience for your users at the same time.


How to convert to laravel eloquent

Question: I need to convert this query to laravel, Help.
UPDATE table_name
 SET usercontact_status = CASE
     WHEN usercontact_status = 0 THEN 2
     WHEN usercontact_status = 16 THEN 64
     WHEN usercontact_status = 32 THEN 128
     WHEN usercontact_status = 4 THEN 256
 END WHERE usercontact_value = "456"

Comment: Have you created any models yet? Did you try anything?
Comment: It seems like you haven't tried anything before asking since a lot of resources can be found regarding this. try [Laracasts](https://laracasts.com/) and please read [How do I ask a good question](https://stackoverflow.com/help/how-to-ask) and [How to create a Minimal, Reproducible Example](https://stackoverflow.com/help/minimal-reproducible-example) before asking so that your answer would be more likely to be answered than downvoted.
Comment: Yes i did create model,

eibersji, Actually this is what i tried,

DB::update('
UPDATE '.UserContacts::getTableName().'
SET usercontact_status = CASE
WHEN usercontact_status = 0 THEN 2
WHEN usercontact_status = 16 THEN 64
WHEN usercontact_status = 32 THEN 128
WHEN usercontact_status = 4 THEN 256
END
WHERE usercontact_value = "'.$code->usercontact_value.'"
');

Thank you.
Answer: Here is the edited answer for you question
switch ($usercontact_status) {
    case 0:
        $value = 2;
        break;
    case 16:
        $value = 64;
        break;
    case 32:
        $value = 128;
        break;
    case 4:
        $value = 256;
        break;
}

Your query will be somewhat like this
$query = Model::where('usercontact_value','456')->where('usercontact_status',$usercontact_status)->update([
    'usercontact_status' => $value
]);

Hope this solves your problem
Comment: This is what i follow you,

UserContacts::where('usercontact_value',$code->usercontact_value)
       ->update([
        'usercontact_status' => '
        CASE
         WHEN usercontact_status = 0 THEN 2
         WHEN usercontact_status = 16 THEN 64
         WHEN usercontact_status = 32 THEN 128
         WHEN usercontact_status = 4 THEN 256
        END
        '
       ]);

Is this correct

How to convert to laravel eloquent


Menu que abre ao clicar

Question: Estou fazendo meu site responsivo, e encontrei um menu que se torna um menu hambúrguer dependendo do tamanho da tela, da maneira como eu queria. Porém, o menu abre conforme passe o mouse (e provavelmente o dedo) em cima, e eu gostaria que ele abrisse e fechasse caso clicasse no botão.
HTML:

                Home

                About

                Work

                Contact

CSS:
@import 'https://fonts.googleapis.com/css?family=Open+Sans';
header {
  background: #F62459;
  width: 100%;
  height: 76px;
  position: fixed;
  top: 0;
  left: 0;
  z-index: 100;
  border-bottom: 5px solid #F62459;
}
ul {
  list-style: none;
}
li {
  display: inline-block;
  float: left;
  padding: 10px
}
a {
  color: #fff;
  text-decoration: none;
  font-weight: bold;
}
a:hover {
  text-decoration: underline;
}
#logo {
  margin: 20px;
  float: left;
  width: 200px;
  height: 50px;
  background: url(logo.svg) no-repeat center;
  display: block;
}
nav {
  float: right;
  padding: 20px;
  font-family: 'Open Sans', sans-serif;
}
#menu-icon {
  background: url(menu-icon.png) no-repeat center;
  display: hidden;
  width: 32px;
  height: 32px;
}

@media only screen and (max-width: 640px) {
header {
    position: absolute;
}
#menu-icon {
    display: inline-block;
}
nav ul {
    display: none;
    position: absolute;
    padding: 20px;
    background: #c5c5c5;
    right: 10px;
    top: 65px;
    width: 35%;
}
nav:hover ul {
    display: block;
}
nav li {
    text-align: center;
    width: 100%;
    padding: 15px 0;
    margin: 0;
}
}

JAVASCRIPT:

Comment: Seu menu já enta funcionando no `.on('click')` repare no script dele... Repare tb que para ele funcionar precisa de jQuery indexado no documento.
Comment: Você removeu a pergunta `Exibir se dado já existe no banco dentro do formulário`. Acabei de desenvolver uma resposta para ela, veja funcionando em http://kithomepage.com/sos/lua.html
Comment: Leo, eu restaurei a postagem, será que você poderia responder lá?
Answer: Seu menu já está funcionando no click repare que ele é .on('click')
No entanto seu menu tem uns problemas de CSS que vc ainda precisa corrigir, pois ele está quebrando a linha antes de entrar o css que recolhe o menu. Além disso display:hidden não existe, acredito que deveria ser display:none...

Resumindo fiz alguns ajustes de css e no script... pois o toggle estava escondendo o menu inteiro inclusive o próprio btn o correto seri '#menu ul'
Veja como fica no código:

$('#menu-icon').on('click', function () {
    $('#menu ul' ).slideToggle('slow');
});
@import 'https://fonts.googleapis.com/css?family=Open+Sans';

header {
    background: #F62459;
    width: 100%;
    height: 76px;
    position: fixed;
    top: 0;
    left: 0;
    z-index: 100;
    border-bottom: 5px solid #F62459;
}

ul {
    list-style: none;
}

li {
    display: inline-block;
    float: left;
    padding: 10px
}

a {
    color: #000;
    text-decoration: none;
    font-weight: bold;
}

a:hover {
    text-decoration: underline;
}

#logo {
    margin: 20px;
    float: left;
    width: 200px;
    height: 50px;
    background: url(https://unsplash.it/100/50) no-repeat center;
        display: block;
}

nav {
    float: right;
    padding: 20px;
    font-family: 'Open Sans', sans-serif;
}

#menu-icon {
    background: url(https://unsplash.it/32/32) no-repeat center;
        display: none;
    width: 32px;
    height: 32px;
}

@media only screen and (max-width: 640px) {
    header {
        position: absolute;
    }

    #menu-icon {
        display: inline-block;
    }

    nav ul {
        display: none;
        position: absolute;
        padding: 20px;
        background: #c5c5c5;
        right: 10px;
        top: 65px;
        width: 35%;
    }

   /* nao precisa desse css
nav:hover ul {
    display: block;
} */

    nav li {
        text-align: center;
        width: 100%;
        padding: 15px 0;
        margin: 0;
    }
}

                Home

                About

                Work

                Contact

Comment: Obrigada Hugo, como não tenho tanta prática com o java acabo me confundindo. Tá tudo funcionando como eu queria!
Comment: @lua Legal que bom que resolveu ai, na verdade seu js estava praticamente certo só que vcs estava referenciando o elemento errado. No mais boa sorte ai

Menu que abre ao clicar


Atributo CSS no innerHTML, como utilizar?

Question: Tenho uma span que dependendo do valor queria que a mesma ficasse vermelho para divergencia e azul caso o dado seja aceitavel, tentei desta forma:
getElementById('span').css('color', 'blue').innerHTML = <valor>

Mas desta forma não funcionou, vi na documentação algo como style
getElementById('span').style.color = "blue" //nesse caso como recupero o valor?

Também não consegui utilizar, não queria utilizar css. tem alguma forma de se aplicar esse efeito?
Answer: Tens de escolher se usas a API jQuery ou JavaScript nativo. Com jQuery podes passar uma função no segundo argumento do método .css() e dar o valor dependendo do html do elemento. Seria algo assim:

$('span').css('color', function() {
  return this.innerHTML == 'A' ? 'blue' : 'red';
});

A
B

Com JavaScript nativo tens de separar em mais passos:

var spans = [].slice.call(document.querySelectorAll('span'));
spans.forEach(function(span) {
  span.style.color = span.innerHTML == 'A' ? 'blue' : 'red';
});
A
B
Comment: obrigado me salvou mais uma vez.