Logging Source IP of SMB Login Attempts

Question: We have an TrueNAS System running TrueNAS-13.0-U5.3. It is bound to Active Directory and used solely for SMB file sharing. Recently there have been periodic event where SMB service quality is degraded - performance decreases and the service stops accepting new connections. Once the SMB service is stopped and restarted, the issue is temporarily resolved.
During these events the /var/log/messages contains messages as indicated below:
Sep 15 11:03:28 FS.example.lan kernel: pid 41336 (smbd), jid 0, uid 0: exited on signal 6
Sep 15 11:03:28 FS.example.lan kernel: pid 42956 (smbd), jid 0, uid 0: exited on signal 6
Sep 15 11:03:28 FS.example.lan kernel: pid 90877 (smbd), jid 0, uid 0: exited on signal 6

Upon inspection of the var/log/samba4/log.smbd there appears to be a flood of authentication attempts by the guest user. For example, in a two hour period today there are approximately 10,000 of these attempts across the 5 shares on this server. Guest access is not permitted on any share.
[2023/09/15 11:22:38.582960,  1] ../../source3/smbd/service.c:399(create_connection_session_info)
  create_connection_session_info: guest user (from session setup) not permitted to access this share (exampleshare)
[2023/09/15 11:22:38.583037,  1] ../../source3/smbd/service.c:588(make_connection_snum)
  create_connection_session_info failed: NT_STATUS_ACCESS_DENIED
[2023/09/15 11:22:38.589570,  1] ../../source3/smbd/service.c:399(create_connection_session_info)
  create_connection_session_info: guest user (from session setup) not permitted to access this share (exampleshare)

There are approximately 300 client computers on the network, mixed macOS, Windows, Linux.
My questions are:

What if any method is there to determine the source IP or hostname of the device from which the guest authentication request is originating?
Is there any normal activity that could account for these observations?
Answer: I have not used the TrueNAS OS personally, but it-appears to have no issue with being able to SSH in, and it supports tcpdump. SO you should be able to trap SMB traffic in a packet capture and see this information with zero issues.
tcpdump -W 10 -C 50 -w smb.pcap -s 0 port 445

The above will capture the SMB traffic packets specifically in a rng buffer the values for -W and -C are (-W how many files to keep) and (-C what size in MB to keep) the files will be sequentially numbered, and operate FIFO, adjust as needed to catch the traffic you need. That sample  will get 10x50Mb so 500Mb of capture. you could easily make it 1000 x 100 and get 100Gb, depends on your normal SMB load and how long it takes to get the sample live.
Opening the subsequent files in wireshark will allow you to see the conversation to the SMB server, what is trying to authenticate, and the IP/MAC it is coming from (MAC helps you sometimes ID the device as well) and if you let it do DNS lookups may even tell you system name. But warning that can be hella resource intensive and slow if you do enable it.
Comment: Yeah, I cannot seem to strip out the specific NTLMSSP_AUTH details in tcpdump, wire shark it is fine because of the dissectors. Aside from catching all the SMB traffic in a ring buffer and parsing with wireshark, snort would be about the only other direction I could point you in, because its dissectors could likely handle it as well. I just tested it catching it all and then reading the PCAP in wireshark, I can see the data.
Comment: Do you have any suggests for narrowing the scope of the capture so it captures only the authentication portion of the conversation? The transaction volume is too high and the files are filling and splitting so quickly that I am having a hard time even locating a file that contains an authentication with filtering on the capture. I need to capture less.
Comment: You can try to filter as such 'tcp port 445 and (tcp[((tcp[12] & 0xf0) >> 2)] = 0x72)' that *should* get the SMB header from each packet, then check the message field type to see if it is a session setup., *those* packets contain the username attempted. I do not have a system handy to test though. IF that does not work, and you can get tshark on the system, tshark will let you filter based on a string and we could likely target it that way.
Comment: Hmm just tried that and it looks like it's only giving me NetBIOS Session Service packets now.
Comment: Let me build a test system later, and will get back to you, netbios should not be on 445, it should be 139 :/

Logging Source IP of SMB Login Attempts


Determine breakpoints in time series data where values change significantly

Question: Given the following chart of data:

which represents duration metrics gathered at absolute times, I am trying to determine when/if any of the values exhibit a jump in durations. In the example chart, the trend of data appears to hover around the 1.4 second mark, while later in the chart, at a particular moment, the data hovers under 4 seconds.
Given a collection of data points similar to the one that produced this chart, is there a statistical function that can find the significant breakpoints in the data? I am a statistics n00b, but doing some research has led me into piecewise regression, but I do not understand it well enough to determine if it is the appropriate route.
For what it's worth, I'll be performing the analysis in JavaScript, so external libraries that have said function probably won't be of much use. I'm more looking for the actual math to arrive at the conclusion so that I may translate that into JavaScript.
Thanks for the advice.
Comment: Eli, welcome!  Great question.  Lots of follow ups.  Will this model be given "labeled" data that identifies when spikes happened?  Is the goal to look at this data in real time and say after each tick, "Spike" or "No Spike"?  Or will it be looking back after the fact and be able to utilize information to the right of the "spike" to determine if it was a spike?
Comment: @jlimahaverford thanks! The goal is to query the data every day for the previous 7 days, then analyze that 7 days worth of data to see if a spike occurs in it, and if it does: where? Eventually I could annotate the existing data with where the spikes occurred, but I imagine that being trivial once I know where the proposed spikes are. :) (Please let me know if there are more follow-ups!)
Comment: Also, let me know if I didn't actually answer your question. :P
Comment: You kind of did.  Is the following acceptable "Yesterday might have spiked, but I need to wait a day or two to know for sure?"  Also, when I asked about labelled data, I meant would you be willing to look back at past skipes and identify them in order to help the training of the algorithm, or do you want the algorithm to identify them completely on their own.
Comment: Yes, that is acceptable. I understand that you probably need to accumulate an amount of data before you can prove a trend change rather than just some temporary out of band variance. With regards to training, it's not necessary to my use case, but wouldn't be a problem if the formula needed it. If the formula identifies regressions previously found, that's not a problem for me.
Comment: @jlimahaverford ^
Answer: Draw a graph of differences between observations. If your plot is $x_t$, then it would be $\Delta x_t=x_t-x_{t-1}$. You'll see that it'll have a big spike in the middle. If you calculate the standard deviation before and after the spike, you'd see that it's similar. You'll see that the magnitude of the spike is 2-3 times higher than of these standard deviations. This gives you an idea for modeling the series.
Start with a simple linear and symmetric model:
$$\Delta x_t = \varepsilon_t,$$
where $\varepsilon\sim\mathcal{N}(0,\sigma^2)$ the Normal Distribution with mean 0 and variance $\sigma^2$.
This is how it works. Calculate the differences $\Delta x_t$ for each observation period. Remove the outliers either manually or using something like Grubbs test. The outliers are the big jumps.
Once outliers are removed, calculate the standard deviation of differences $\sigma=\sqrt{Var[\Delta x_t]}$. You can do this in Excel, for example.
Now, going forward, keep computing $\Delta x_t$ for future periods, whenever it's large, e.g. $\Delta x_t>2\sigma$ you'll say that there's 95% probability that it's a big jump. You can go for $3\sigma$, then the probability is 99.5%.
The problem with this approach is that if you draw a histogram of $\Delta x_t$, most likely it'll be skewed. So, Gaussian distribution will not be a good fit, but what I described could be a starting point for your analysis. You need to study the distribution of differences and spikes to find a good fit.
Comment: The first paragraph kinda made sense, but I don't understand anything about the second, sorry.
Comment: Could you maybe elaborate on what the different symbols stand for and which of my terms would map to these variables?
Comment: Is this an online process?
Answer: What you are looking for is change point detection. There is an extensive literature on this topic, and there are freely available software packages for performing this type of analysis. For example, see this paper on the R package changepoint which includes a brief survey of the literature, along with examples demonstrating how to perform this kind of analysis.


Construction of free resolution of modules over a group ring.

Question: I'm reading this paper, it says(in Theoerm 2) that:

Let $A$ be a finite abelian group, $G$ a finite group, $\Delta G$ the augmentation ideal of the integral group ring $\mathbb Z G$ and a $G$-modules extension $A\hookrightarrow B \twoheadrightarrow \Delta G$, then taking a free resolution of $B$ we get a commutative diagram (4) below:

How is $\mathbb Z G^{m}$ constructed that maps correspondingly?
Answer: $\mathbb{Z}G^m$ is the direct sum of $m$ copies of the group ring $\mathbb{Z}G$.  The map $\mathbb{Z}G^m\twoheadrightarrow\Delta G$ is just mapping $1$ in each summand to corresponding generators of the ideal and extend by $\mathbb{Z}G$-linearity.
Comment: $m$ copies of $\mathbb Z G$ or $G$($= (\mathbb Z G)^{m}$ or $\mathbb Z (G^{m})$)? How does it map to $B$?
Comment: @CYC The context is that $\mathbb{Z}G^m=(\mathbb{Z}G)^m$ because we are dealing with a **free** resolution of $B$. Free modules over $\mathbb{Z}G$ are precisely $(\mathbb{Z}G)^m$. This also shows where the $\mathbb{Z}G^m\to B$ mapping comes from (the free resolution).


IntelXDK api for android notification

Question: I'm trying to archive this in intel xdk. But I couldn't find any relevant API. Would be great if someone can point me to the correct source.
P/S: What I want to achieve is the notification (showing short message), instead of push notification.
Answer: This plugin will enable you to do local notifications in your application - https://github.com/katzer/cordova-plugin-local-notifications/
See the following for adding 3rd party plugins to your app - https://software.intel.com/en-us/xdk/docs/adding-third-party-plugins-to-your-xdk-cordova-app

IntelXDK api for android notification


ggplot2, arrange multiple plots, all the same size, no gaps in between

Question: I would like to arrange multiple plots into one figure, without any gaps between the plot area, and all plots being exactly the same size (see image below for a sketch of my desired figure, which comprises 6 individual plots).

I have tried ggarrange (ggpubr) and plot_grid (cowplot) and a couple others but they seem to have the same problem - you can align the plots to get them the same size, but not arrange them closer to each other.
ggdraw in the cowplot package allows one to specify exactly where the plots go, but they are all slightly different sizes.
Is there a way to overcome this?
Basically, I want to make the plot area (where the data is displayed, NOT the axes and labels) the same for six graphs, then arrange them contiguously.  So far I have not found anyway to do this.
The x-axis variable is the same for all 6 graphs, but the y is different, and there are multiple series on some of the graphs but not others, so I cannot use the facet option in ggplot2.
Please help!
EDIT: Sorry, some more info - because my plots have different y variables, the plot margins and the plot panels are all slightly different sizes.  So that means when I try to add them all together, they are out of alignment.
Plots different sizes out of alignment.  plot_grid from cowplot allows you to specify position, and size, BUT, the size is the size of the whole plot, panel and margins included.  Because of the Y-axis labels, the margins are different sizes, and resizing them using the arguments to plot_grid is not so simple.
Comment: I use **library(gridExtra)** to combine plots - works perfectly. Specify **layout <- rbind(c(1, 1, 1), c(2, 2, 2))** and use  **grid.arrange(p1, p2, layout_matrix = layout)** AND for p1 and p2 (two ggplots) add **theme(plot.margin=unit(c(0,0,0,0),"cm"))**
to control space between two plots
Comment: Have you seen these questions? Unsure if they're duplicates, but they might help: [reduce space between grid.arrange plots](https://stackoverflow.com/questions/13299496/reduce-space-between-grid-arrange-plots), and [Side-by-side plots with ggplot2](https://stackoverflow.com/q/1249548/8366499)
Comment: `cowplot::draw_plot` lets you specify position, height and width.
Comment: Possible duplicate of [Side-by-side plots with ggplot2](https://stackoverflow.com/questions/1249548/side-by-side-plots-with-ggplot2)
Comment: Thank you for your responses.  None of the options were quite what I was looking for: https://stackoverflow.com/questions/1249548/side-by-side-plots-with-ggplot2 still leaves some gaps between the plots, and I need the gaps gone completely.  This one https://stackoverflow.com/questions/13299496/reduce-space-between-grid-arrange-plots I don't even understand how to use, being relatively new to R.
Comment: @Annaz that seems to only work if the plot panels are already the same size, otherwise it results in a painstaking process of a multitude of axis adjustments trying to get the panels the same size.
Answer: So I managed to find an answer, based on some code from here: https://community.rstudio.com/t/how-do-i-control-the-size-of-the-panel-in-a-ggplot-so-they-are-consistent/14377/8
The plots first need to be passed through the     align_plots()     function in
    cowplot()    , to make a list of the plots:
`multiplot <- align_plots(plotAA,plotBB,plotCC,plotDD,plotEE,plotFF, align = "hv")`

Then the panels of the graphs will be all the same size, and they can be arranged using
    ggdraw()     and     draw_plot()     as follows:
`ggdraw() + draw_grob(multiplot[[1]], 0,0.565,.6,.4) +
  draw_grob(multiplot[[2]], 0.396,0.565,0.6,0.4) +
  draw_grob(multiplot[[3]], 0, 0.285, 0.6,0.4) +
  draw_grob(multiplot[[4]], 0.396, 0.285, 0.6, 0.4) +
  draw_grob(multiplot[[5]], 0,0.004, 0.6, 0.4) +
  draw_grob(multiplot[[6]], 0.396,0.004,0.6,0.4)`

to give the final figure:
Desired plot arrangement
I hope this helps somebody else in the future,
Thanks.
Comment: EDIT: that should be the 'draw_plot()' function in place of 'draw_grob()' (though either works).
Comment: 2nd Edit: the first thing I would do is make the panel and plot backgrounds transparent using `theme(panel.background = element_rect(colour=NA, fill = "transparent"), plot.background = element_rect(colour=NA, fill = "transparent"))`.  Then it is easier to position the graphs correctly.


Can someone please explain what this regression model means?

Question: I'm studying the link between a regime's violation of its citizens' physical integrity rights and civil conflict. There are 4 independent variables (political imprisonment, torture, disappearances and killings) and one dependent variable (civil conflict). So I ran a regression formula using all of the variables and the results are below, but I don't know how to actually read them.
Comment: Can you clarify what it is about the output you don't understand?
Comment: There is an odd & large number of downvotes throughout this thread.
Comment: For the final report, fix the spelling for your `Dissap` variable. More interestingly, check for correlations between your predictors and check whether the regression should really be Poisson. How do those negative coefficients square with a response variable that sounds as if it is zero or positive? Why do your main predictors have coefficients with different signs? What happens if you leave out `PolPris` and/or `Torture`?
Comment: @NickCox my thought was that the variables may be binary. Like tortured yes/no, Killed yes/no, etc.
Comment: @RustyStatistician Could be; as you say, we need more information.
Comment: @RustyStatistician, the independent variables (torture, kill, etc.) are all categorical and measured using a scale of zero through two: if a regime frequently violates a physical integrity right, than the state will receive a zero; if a regime occasionally violates a physical integrity right, than the state will receive a one; and if a regime does not violate a physical integrity right or if there are no reported violations of a physical integrity right, than the state will receive a two. The dependent variable, civil conflict, is a yes/no binary.
Answer: The R-squared is telling you that of all the variability in the dependent variable, only 38% is explained by the independent variables in the linear model you propose. This may not be that bad giving that you are not trying to make predictions based on the linear equation that @RustyStatistician formulated for you.
The second thing to notice is that the relationship between "civil conflict" and both "killings" and "disappearances" is statistically significant at a $p$ value of $<1\%$. You can't say the same of "political imprisonment" and "torture."
The negative sign for both significant regressors is surprising in that it indicates that there is a negative relationship between disappearances and killings, and the dependent variable (civil conflict). The labels in plain English seem to point to a positive correlation, where an increase in disappearances and killings would lead to more civil conflict, not less. But it's reason to review how these variables are measured and coded.
As noted in other comments, it is also important to question whether an OLS regression is the best model. For instance, if the dependent variable is measured in counts, a Poisson model may be more appropriate.
As an aside, please be aware of the rich semiotic depth in the name of the RHS (right-hand side) variables and LHS (left-hand side) of the OLS regression equation as beautifully captured in this Wikipedia entry, and transcribed below (if it seems tangential you can safely ignore this last part):

An independent variable is also known as a "predictor variable", "regressor", "controlled variable", "manipulated variable", "explanatory variable", "exposure variable" (see reliability theory), "risk factor" (see medical statistics), "feature" (in machine learning and pattern recognition) or an "input variable.
A dependent variable is also known as a "response variable", "regressand", "predicated variable", "measured variable", "explained variable", "experimental variable", "responding variable", "outcome variable", and "output variable".
Comment: +1 As it stands now this seems like a useful contribution.
Comment: Need to fix small confusion over dependent and independent variables here. Elsewhere I have lobbied to use other terms.
Comment: There are numerous typos in your answer which renders it erroneous.  Several times you confuse dependent variable with independent variable.  Also, the structure of this regression does not have explicit interaction variables.  Thus, your whole comment about "no interactions" is either not relevant or unclear.  Your comments regarding p values and stat. significance is correct.  But, is it directionally correct?  You don't address whether the signs of the regression coefficients make sense or not.
Comment: @GaetanLion I caught one mistake in sloppily typing 'dependent' instead of 'independent'. You mention "several times". Can you kindly point out the others?
Comment: You don't know how she coded up disappearings and killings to be able to make that claim about the "common sense" of the signs.
Answer: So you basically ran a linear regression in Stata and the output that you have above is telling you that you obtained the following fitted model:
$$\text{internal}=.063-0.175\times\text{PolPris}+.0348\times\text{Torture}-0.205\times\text{Dissap}-0.134\times\text{Kill}$$
Likewise, the P>|t| column gives you the p-values associated with each explanatory variables estimated coefficient, and the next two columns give the associated 95% confidence intervals for the coefficients as well.
However, there isn't much more anyone can tell you about this problem until you give us more information about what all the variables mean. I am also curious to know are all of the variables continuous or some binary or multi-categorical?
Without knowing much more about the problem you are working on we really can't say much more about the interpretation on a meaningful level.
Comment: Hi all. I have posted a new question that clarifies some of the confusion. Here is is: https://stats.stackexchange.com/questions/184323/analyzing-two-different-regression-lines-with-independent-and-control-variables


How to tell whether function $x^a \mod{b}$ is bijective or not?

Question: What conditions must integers $a$, $b$ suffice to make $x^a \mod{b}$ a bijective function?
(I brute force tested out two findings, but not sure whether they are correct or not:

If $b$ is prime and $a$ is coprime to $b-1$ then $x^a \mod{b}$ is bijective.
If $b$ is not prime, $x^a \mod{b}$ is not bijective unless $a = 1$.

Not sure how to prove these two findings mathematically)
Any help is much appreciated!
Comment: Hi, Kandarin, and welcome to Math.StackExchange.  I think you're right about the case where $b$ is prime ($x \mapsto x^a$ is an automorphism of the multiplicative group), but the composite case is more complicated.  Take a look at $x^3\!\!\!\!\mod 15$.
Comment: The restriction of this map to the group of units is bijective iff $\gcd(a,\phi(b))=1$. I'm not sure about the whole ring.
Comment: About item 2: the map is bijective for $a=3$ and $b=6$ for instance.
Answer: If $\ b\ $ is prime and $\ a\in \mathbb Z\ $, then the function $\ f\ $ defined on $\ \{\,0,1,2, \dots, b-1\,\}$ by $\ f(x) = x^a\ \mathrm{mod}\ b\ $ is indeed bijective if and only if $\ a\ $ is coprime to $\ b-1\ $.  Here's a formal proof.
Since $\ f(0) = 0\ $, and the domain of $\ f\ $ is finite, the bijectivity of $\ f\ $ will follow once it's shown to be one-to-one on the non-zero elements of its domain.  It's well-known that these elements form a cyclic group of order $\ b-1\ $ under multiplication $\ \mathrm{mod}\ b\ $, so if $\ x\ $ and $\ y\ $ are elements of this group with $\ x^a = y^a\ $,  and $\ d\ $ is the order of the group element  $\ x\,y^{-1}\ $, then $\ d\, \vert\, b-1 $ and $\ \left(x\,y^{-1}\right)^a = 1\ $, so $\ d\,\vert\,a\ $ also, and is therefore a common divisor of $\ b-1\ $ and $\ a\ $.  Thus, if $\ a\ $ and $\ b-1\ $ are coprime, it follows that $\ d=1\ $, and $\ x\,y^{-1}=1\ $, or $\ x=y\ $. So in this case, $\ f\ $ is bijective.
On the other hand, if $\ a\ $ and $\ b-1\ $ are not coprime, then they have a common divisor $\ e > 1\ $.  If $\ b-1 = e\,h\ , a = e\,j$, and $\ g\ $ is a generator of the group of units $\ \mathrm{mod}\ b\ $, then $\ x = g^h\ $ is a non-identity element of the group with $\ x^a = g^{hej}=g^{(b-1)j}=1=1^a\ $.  Thus $\ f\left(g^h\right) = f(1)\ $ in this case, and $\ f\ $ cannot be a bijection.
If $\ b\ $ is composite, the question is more complicated, as several comments have indicated. As the next step towards the general case, I would suggest tackling the one where $\ b\ $ is a prime power.
Comment: If $b$ is a prime power, or even divisible by $p^2$ for any prime $p$, the map cannot be bijective for $a\gt 1$:  Let $x = b/p$, then $x^a$ is divisible by $x^2 = b(b/p^2)$, so $x^a \bmod b  = 0$.  Only squarefree values of $b$ are in question.
Comment: Thank you so much!
Comment: How embarrassing not to have realised that—though I did also have in mind the auxiliary question of when $\ x^a\ $ is a bijection on the group of units of the ring.


How is the human voice classified?

Question: Considering the vocal cords can be a membranophone or considering the air column can be an aerophone.
or do we need another classification?
Comment: Interesting idea, but what's wrong with vox humana?
Comment: voice. the first instrument.
Comment: @MichaelCurtis - no, I mean that it's possible for a human to imitate a trumpet, flute, drums...
Comment: "vox humana" or "voice" would be that "other classification" I'm looking for, but is this correct? Is that how it is determined in books?. I'm considering the classification in idiophones, membranophones, chordophones, aerophone, electrophones
Comment: My comment was really meant to say I think there are times to dispense with academic thinking. Just my opinion. I'll add an answer to elaborate.
Comment: @MichaelCurtis - many decades ago, at music college, a colleague was convinced that instruments were merely trying to imitate the human voice, but never got close. Still don't quite understand...  The other way round is more plausible. Make a sound like a trumpet, a flute, a drum...
Comment: @Tim. Not sure I understand you. Do you mean 10,000, 20,000 years ago human singing was trying to imitate a flute? That's sort of like a ancient cart being an imitation of an automobile. Surely the history and mimicking was the other way around. Percussion would be the other primal instrument. Of course this is just speculation with some common sense applied.
Answer: I'm not sure this is really an answer, but I thought I should elaborate on my comment which may have seemed glib or snarky.
The classification list is the Mahillon and Hornbostel–Sachs system which I really didn't know about.
I'm not really sure about the logic of that system. It lumps together bells and maracas as idiophones, because the entire bodies of the instruments vibrate. I get the idea, but don't see any musical insight from it. Then again this system is 19th century "science" ...that's the same time period of phrenology. I think it's a little outdated.
Apparently there is a Dewey Decimal-like classification in that system. An aerophone has a vibrating air column, but the instrument itself doesn't vibrate (not sure that's true, especially brass) so that would not be the human voice as the vocal chord vibrate. Seems the voice is a "242, Singing membrane, vessel kazoo," because it's a vibrating membrane inside a container.
My original comment - "voice, the first instrument" - was meant say I think we should sometimes dispense with academic systems. Surely, the human voice was the first musical "instrument", the first means to express emotion with sound. I don't really care that it's like a kazoo. I care more about the voice's intrinsic qualities - the fact that it's easy for most people to make a distinct pitch, typical range of the voice, amplitude, and the limit of what can be sung in one breath. I think many musical fundamentals stem from what we can do with our human voices. IMO, it's more important to know the musical implications of our human voice limitations rather than classification as a vibrating kazoo-like membrane in a box.

How is the human voice classified?


Need a recommendation for a C++ GUI library

Question: I want to make remote administration tool. I want to take the first step by implementing the GUI or part of it (since it will be fun while being my first real experience with C++).
I need the following features in the GUI library:-
1) Modern easy-to-work-with paradigm
2) Modern kool features.
3) OS-independent. i.e. works on Mac OSx, Linux Ubuntu, and Win 7. And if could be, Android also.
Comment: This will start a flame, I guess. Isn't the internet full of comparisons?
Comment: What are you looking for, a networking library or a GUI library? They are completely different things.
Comment: If you find it please let us know
Comment: Dam... I changed the title in 5 seconds but got downrated before that! Anyway I want a GUI library, (I was thinking of both in my mind.)
Answer: Sounds to me you're looking for Qt.
Answer: Use Qt ... it offers pretty much everything you need.
Answer: Although there are already similar answers, it cannot be said often enough: Qt definitely offers everything you're looking for. I highly recommend it!
Answer: Have you looked at http://www.wxwidgets.org/ ? I've never used it in C++, but I have used the python bindings for it and found it pretty easy and very powerful. Believe they have a nice demo/sample code application for most of the features in the library too.


Display images of a specific content type in a lightbox when vocabulary is clicked

Question: Background
I am using Drupal 7 and I have a taxonomy "Kitchen Type" and content type "Kitchen Picture" having default field_image for images. There are three Kitchen Types Traditional, Contemporary and Transitional. I have more than 10 Kitchen Pictures assigned to each Kitchen Type.
Problem
I have a view at /kitchens (Page 1) that lists three kitchen types and when clicked, lists the Kitchen pictures (another dynamic view) (Page 2). When a picture is clicked a lightbox open up. But,  I would like to have a lightbox open up with kitchen Pictures (including next-back navigation) when any of the kitchen type (traditional etc) is clicked. So, I want to skip Page 2 actually. I have no idea how to go about it. Any help would be appreciated.
Edited
I am afraid I also have a link in the header "Kitchen Portfolio" that supposed to open a lightbox and allows visitor to navigate through all the kitchen pictures. I want to avoid loading all the images on all pages. I need a way out such as when link is clicked it loads the html and start lightbox navigation. I do not know how I can achieve it in Drupal.
I already have lightbox2 installed.
Thanks
Answer: If I were you I would create a "Kitchen Type" content type and then edit the image field to allow unlimited amount of images. Then add a taxonomy field to "Kitchen Type" assigning a taxonomy term to each.
Create a new view which pulls all "Kitchen Type" content types and add the Taxonomy Field and Image field to the display. Views allows you to style individual fields by its tpl naming convention. If you go to the "theme" option in that view you will see a set of file names to place in your theme to style individual fields. You will need to style the image field by looping through the image array and output html which conforms to the lightbox2 convention like this:

This should display each set of images for each kitchen type right under it. Once one image is clicked it should open up a lightbox with arrows to go to next image.
Hope this helps or at least points you in the right direction!
Comment: That sounds like a good plan. But avoided unlimited images because every image would have a caption. Secondly, I believe, putting more than 40 images in one page increase page load time. I am afraid I also have a link in the header "Kitchen Portfolio" that supposed to open a lightbox and allows visitor to navigate through all the kitchen pictures. There in this case, we have to load all the images on all the pages.
Comment: Please read out the Edited part of the question.
Comment: In order for lightbox to display a gallery the images have to be in the markup already (hidden or not). Otherwise, if you are trying to avoid putting all of them on the page, you have to set up some sort of AJAX service to your backend to load the images on click. I don't believe lightbox does this.
Comment: Yeah, I think the same, I believe, I have to fetch the markup first when link is clicked an start the slideshow. It would all be custom coded.
Answer: Here is how I implemented it

Created a block view to display empty links of all "Kitchen Pictures" images

Added Content:Body, Content: Kitchen Type and Field:Image
Field Image Settings

Uncheck create a label, Set Formatter as "Image URL"
Set "Link image url" to "Nothing"
"Rewrite Result" => Check "Rewrite the output of this field" and paste following code.

Content:Body and Content:Kitchen Type Settings

Uncheck Create a label
Check Exclude from Display
Set Formatter to "Plain text"

Place the above created block in footer and use CSS to make it hidden (i.e. display:none)
To start lightbox of all images, I then used following JS function and applied to "onclick" of the "Portfolio" link.
function start_portfolio_slidshow()
{
   jQuery('a.portfolio_kpic').each(function(){
      title = jQuery(this).attr('title');

      rel = 'lightshow[portfolio]['+title+']';
      jQuery(this).attr('rel',rel);

      Lightbox.initList();
      Lightbox.triggerLightbox('lightshow', 'portfolio');

   });
   return false;
}

To start lightbox of each kitchen-type (category). I implemented following functions
function start_kitchen_slidshow(event)
{
    type = event.data.type.toUpperCase();

    jQuery('a.portfolio_kpic.'+type).each(function(){
        title = jQuery(this).attr('title');

        rel = 'lightshow['+type+']['+title+']';
        jQuery(this).attr('rel',rel);

        Lightbox.initList();
        Lightbox.triggerLightbox('lightshow', type);

    });
    return false;
}

Which is implemented to links like following (in jQuery(document).ready)
    $('a.lightbox_portfolio_kitchen').each(function(){
       $(this).bind('click', {type: $(this).attr('rel')}, start_kitchen_slidshow);
    });

Note: Links should have "lightbox_portfolio_kitchen" with category name in its "rel" attribute.
There may be some other solutions but this one worked for me.


Why won't this NAT rule work?

Question: I need to make a NAT rule to allow a user to access their workstation from networks outside of our own. I have added the following line to my router's configuration file (it's a Cisco 2911), which specifies the internal IP and port as well as the external IP and port that I'd like the system to be accessible at;
ip nat inside source static tcp 172.xxx.xxx.33 3389 204.xxx.xxx.26 55512 extendable

and have also specified to allow the external port through the ACL applied to the WAN interface;
permit tcp any any eq 55512

So why isn't this working? I can connect fine to the system inside the network, but not from the outside using the settings configured in the NAT rule shown above. Allowing all inbound connections through all firewall profiles on the host I am attempting to connect to makes no difference, neither allowing edge traversal for RDP protocols on the firewall. thanks for any possible assistance.
Comment: What is your Cisco IOS version? The rules have changed over the years.
Comment: @CoryKnutson 15.4 or 15.3, not sure which, but either of those two. Shouldn't be any difference there.
Comment: The ACL applied to the WAN is input or output?
Comment: @mikhailkhirgiy it's applied to the input.
Comment: Well. Try to connect from Internet and watch `router#sh ip nat trans | i 55512` on Cisco. Also see ACL rules on Cisco LAN interface and firewall rules on the server.
Comment: Can you post a full configuration?
Answer: For your firewall rule, the destination port is not 55512. You should also always avoid permit any any rules. I believe you should have something similar to
permit tcp any 172.xxx.xxx.33 eq 3389

Why won't this NAT rule work?


Invertible elements of a quotient ring of $ℝ[x]$.

Question: I was given the following problem as part of an algebra assignment:  Let: $$f(x)=15x^3+8x^2+5x+9 \in ℝ[x]$$ and $$I=\langle f(x)\rangle$$
the ideal generated by $f(x)$.  If $ℝ[x]/I$ is the quotient ring modulo I, then find all the invertible elements of $ℝ[x]/I$ and similarly all the invertible elements of the quotient ring $ℚ[x]/I$.
My approach so far:
I imagine that we are not expected to come up with a certain set of specific elements, but rather describe them in their general form.
So, let $p(x)$ be an element of $ℝ[x]/I$. Then, $p(x)$ is of the form: $$ax^2+bx+c$$ Since $$deg(p(x))<deg(f(x))$$ and $a,b,c \in ℝ$, not all zero

Let $p(x)\in U(ℝ[x]/I)$, where $U(ℝ[x]/I)$ denotes the set of all invertible elements in $ℝ[x]/I$.
Then, let $$q(x)=a'x^2+b'x+c'$$ be its inverse. It follows that: $$(q(x)+I)(p(x)+I)=1_{ℝ[x]}+I=1+I$$ So, $$(q(x)p(x)-1)\in I$$ and if we use the expressions of $q,p$:
 $$(a'x^2+b'x+c')(ax^2+bx+c)-1 \in I$$
$$aa'x^4+9ab'+a'bx^3+(ac'+bb')x^2+(bc'+cb')x+cc'-1\in I$$
If I understand correctly, this means that the expression above must be generated somehow by $f(x)$, and its degree must equal the degree of $f(x)$. But where does that lead? How can I continue-if this approach can indeed work-and find a general form for the inverses?
To be more specific, am I to find expressions of $a',b',c'$ in relation to $a,b,c$? Under which conditions will they apply?Any help is appreciated.
Comment: Since the quadratic term can appear as a multiple of $f$, I would not suggest assuming that $aa'=0$.
Comment: One way to find an inverse in the quotient of a polynomial ring is to use the (extended) Euclidean algorithm.  If you try this here, there will be a few cases where some expression will need to be nonzero and you can consider those on a case-by-case basis.
Comment: @MichaelBurr My guess is that the term $aa'$ will have to be zero, so $a'=0$ and that is a start, leading to $b',c'$.
Comment: @MichaelBurr Ahh,thank you. I see my mistake there. Will try applying the extended Euclidean Algorithm as you suggested though I am not very familiar with its workings
Answer:
If ℝ[x]/I is the division ring modulo $I$...

I guess you mean "quotient ring."  "Division ring" means something else altogether: a division ring is a noncommutative field. This is important because this quotient is not a field (or division ring either.)

then find all the inverse elements of ℝ[x]/I

Do you mean find all invertible elements? It must be impossible to specify a general form of invertible elements, but you can say that the invertible polynomials are the ones coprime to $f(x)$.

similarly all the inverse elements of the [quotient] ring ℚ[x]/I.

Here you can work to show that $f(x)$ is irreducible over $\Bbb Q$, so the quotient is a field extension of $\Bbb Q$ of degree $3$. All nonzero elements are invertible.
Comment: Done! Thanks a lot!
Comment: @OttavioConsone Yes, well, you still have to convince yourself $f(x)$ is irreducible over $\Bbb Q$, and then you'll have your answer :) Do you know the rational root test?
Comment: I fear english is not my native language so there is a chance I mixed that up. Should I edit it by changing division for quotient?
Comment: Yes, quotient is the correct term.
Comment: @OttavioConsone In this case I think it is OK if you do that.
Comment: @rschwieb If I understand correrctly, as suggested by both you and Michael, I am to say that all invertible polynomials are the ones coprime to $f(x)$ and then go about using the extended Euclidean Algorithm to "refine" my answer. While in the case of $ℚ[x]/I$ you pretty much answered it yourself :-)
Comment: @rschwieb Yes, I am familiar with the method-that is I have seen it before. Not sure how it apllies here though :-( I suppose also a very "direct" approach would be to find it's roots or simply say that since two of them must be complex it is irreducible over $ℚ$?
Comment: If a degree 3 polynomial is to be irreducible over a field, it must have a root in the field
Comment: @rschwieb *reducible*! :)
Comment: @SpamIAm yes, that's what I meant.  Reducible
Answer: In a way, the interesting case is where the base is $\Bbb R$ instead of $\Bbb Q$. You see that the derivative of your cubic polynomial is a quadratic with negative discriminant, so that there is no local maximum nor minimum. That is, your cubic polynomial represents a strictly monotone real-valued function, and so has only one real root, which I'll call $\rho$. We can write $f/15=x^3+8x^2/15+x/3 +3/5=(x-\rho)(x^2+bx+c)$, where the quadratic factor has two (nonreal) complex roots $z$ and $\bar z$. Now, we expect $\Bbb R[x]/(f)$ to have the shape $\Bbb R\oplus\Bbb C$, with coordinatewise addition and multiplication, and indeed we get our isomorphism $\psi:\Bbb R[x]/(f)\to\Bbb R\oplus\Bbb C$ by defining $\psi(g)=\bigl(g(\rho),g(z)\bigr)$. Since $g$ has real coefficients, $g(\rho)\in\Bbb R$ and $g(z)\in\Bbb C$. The answer to your question of which $g$ are invertible is easy now: you need both $g(\rho)\ne0$ and $g(z)\ne0$.
For the less interesting case of $\Bbb Q[x]/(f)$, you know that every element is uniquely representable as a polynomial $a+bx+cx^2$, and this is invertible if and only if at least one of $a$, $b$, $c$ is nonzero.
Comment: Thank you for your answer sir! It makes it much clearer for me now, though obviously I need much more practice to familiarize myself with the concepts involved.


2 separate Profile2 Views (one faculty, one staff)

Question: I've been able to create a view with the profile2 module (with custom forms)that renders all users on a view. How can I create a separate category of users, say 'faculty' and 'students' and have a view for each? So the faculty view would only show users labeled as faculty.
Thanks!
Answer: You could add a field "user type" to the current profile and then add a views filter or views "contextual filter" to only show one type at a time. You may need to add a "relationship" on the profile2.
Alternatively, profile2 lets you specify different types of profiles. So you could make a 'faculty' profile and a 'students' profile.
It really depends on what would work best in your setup.
Comment: If I do this via profile2, how do I configure the view to only show faculty then? Is there a tutorial you can point me to? Much appreciated!
Comment: [This tutorial](http://codekarate.com/daily-dose-of-drupal/drupal-7-creating-membership-directory-views-and-profile-2) looks pretty good


something like google suggest example

Question: i have a qlineEdit and a QListWidget i want to have something like google suggestion, when user type a text, i want to display only items with text starting with that text, but i don't know how should i do that? i think i should write a searchbox but i should call it every time user insert or delete character, i don't know if there is a better idea?
SearchBox(QWidget *parent = 0);

or is there any sample in examples like this?
thank you in advance
Answer: You can use QCompleter to provide auto completions in any Qt widget, such as QLineEdit and QComboBox. When the user starts typing a word, QCompleter suggests possible ways of completing the word, based on a word list.
An example is :
 QStringList wordList;
 wordList << "alpha" << "omega" << "omicron" << "zeta";

 QLineEdit *lineEdit = new QLineEdit(this);

 QCompleter *completer = new QCompleter(wordList, this);
 completer->setCaseSensitivity(Qt::CaseInsensitive);
 lineEdit->setCompleter(completer);

Comment: This will list possible items when you type. Try it.
Comment: thanks a lot for your help, but i need when they type my list possible item shows, not helping complete the text

something like google suggest example


Probability that two random permutations of an $n$-set commute?

Question: From this MathOverflow question:

It is well known that two randomly chosen permutations of $n$ symbols commute with probability $p_n/n!$ where $p_n$ is the number of partitions of $n$. -- Benjamin Steinberg

Unfortunately, it's not well known to me.  Can I get a reference or link to this result?  Or a proof, if it's simple enough.
(Google doesn't work where I am; I tried Binging two random permutations commute but it only gives the MathOverflow link.)
I need this result for a secret sharing scheme I'm currently analyzing.
Answer: It's a simple matter of combining two other well-known facts:

In any finite group $G$, the probability that $a,b$ commute, with $(a,b)\in G\times G$ chosen uniformly at random, is $k/G$, where $k$ is the number of conjugacy classes of $G$.
Conjugacy classes in $S_n$ correspond to cycle types, which correspond to integer partitions.

For fact one, see the very end of my answer here. One easily finds proofs and discussions of the second fact googling "conjugacy classes symmetric group," for instance this one.
Comment: Understood!  Thanks for that.
Answer: Just to add a bit more detail to blue's answer, for a finite group $G$, the probability that two randomly chosen elements commute is
$$\frac{1}{|G|^2}\sum_{g \in G} |C_G(g)| = \frac{1}{|G|}\sum_{g \in G} \frac{1}{|{\rm Cl}(g)|} = \frac{k}{|G|}$$
where $k$ is the number of conjugacy classes of $G$.
Comment: And thanks here too!


How to pass []*type to function?

Question: I have a method in Golang that requires a []*type as a parameter.
I have a slice:
s := make([]myType, 3)

How do I do that?
Comment: [Please take the Go Tour](https://tour.golang.org/welcome/1). And if your question is: How to pass a **type** to a function as opposed to a **value**, just like `make` and `new` do it; then the answer is: You cannot do that. `make` and `new` are special builtin functions that allow that, but you cannot pass a type identifier to a function you declared.
Comment: If the problem is that the function takes a slice of pointers to a type and you have a slice of that type, you can't pass it because the types don't match. You have to create a slice of pointers to the type and pass that.
Answer: In short (and as somewhat alluded to by other commenters), it sounds like you're asking how to use a feature that Go doesn't support. Namely, generics: a function with signature []*type, where type isn't actually a specific concrete type that you've already defined. While this might be supported in the future, it isn't for right now - you're stuck with defining the function with []*specific-concrete-type for now.

How to pass []*type to function?


Views expose filter with ajax showing validation message after reloading page?

Question: I added a date filter that showing select list for year and month. I created the block type view. When I select the month and submit the form it makes the red border outside the year. But when I reload the page or go to another page it gives me the error :
Please choose a year.

How to show error message at the time of form submit?
Any Solution???
Answer: Disable the Ajax for exposed filter, It will show only the message on form submit.
Comment: Where is this option? Do I need to install bef?
Comment: @SumitMadan I updated the answer with screenshot
Comment: I can't disable it. I displayed the view using https://drupal.org/project/viewreference. If I disabled the ajax it takes me to origional url of view and my other configuration of page will not work.
Answer: Solved this using custom javascript code.
    jQuery(".views-exposed-form #edit-date-filter-value-year").live('change',function(){
    jQuery('#edit-date-filter-value-year').removeClass("error");
    var month=jQuery('#edit-date-filter-value-month').val();
    if(jQuery('#edit-date-filter-value-year').val()==""){
        jQuery('#edit-date-filter-value-year').addClass("error");
        jQuery('input[type="submit"]').attr('disabled','disabled');
        jQuery('input[type="submit"]').css('background', '#dedede');
    }
    else if(month=="") {
        jQuery('#edit-date-filter-value-month').focus();
        jQuery('#edit-date-filter-value-month').addClass("error");
        jQuery('input[type="submit"]').attr('disabled','disabled');
        jQuery('input[type="submit"]').css('background', '#dedede');
    }
    else {
        jQuery('input[type="submit"]').removeAttr('disabled');
        jQuery('input[type="submit"]').css('background', '');
    }
});

jQuery('.views-exposed-form #edit-date-filter-value-month').live('change',function(){
    jQuery('#edit-date-filter-value-month').removeClass("error");
    var year=jQuery('#edit-date-filter-value-year').val();
    if(jQuery('#edit-date-filter-value-month').val()==""){
        jQuery('#edit-date-filter-value-month').addClass("error");
        jQuery('input[type="submit"]').attr('disabled','disabled');
        jQuery('input[type="submit"]').css('background', '#dedede');
    }
    else if(year=="") {
        jQuery('#edit-date-filter-value-year').focus();
        jQuery('#edit-date-filter-value-year').addClass("error");
        jQuery('input[type="submit"]').attr('disabled','disabled');
        jQuery('input[type="submit"]').css('background', '#dedede');
    }
    else{
        jQuery('input[type="submit"]').removeAttr('disabled');
        jQuery('input[type="submit"]').css('background', '');
    }
});

Answer: I ran into this issue too recently. I didn't try the javascript solution posted above, because I found this thread on d.o that seemed to solve the issue for me, so thought I would add it here as another option: https://www.drupal.org/node/1833322#comment-9184301
Specifically, the comment provides this code:
function MODULE_views_ajax_data_alter(&$commands, $view) {
  $commands[] = ajax_command_prepend($commands[0]['selector'], theme('status_messages'));
}

Comment: Yeah, that was an old issue. I just applied whatever solution clicked to my mind. Thanks for posting your answer. :)


cumulative sum by group and under some condition in r

Question: Within the group with the same m1 and n1, I need to calculate cumulative sum of x1  if x1 is not 0 and cumulative sum of y1 if y1 is not 0. Any help would be appreciated.
 d <- data.frame ()
    for ( m1 in 2: 3) {
         for (n1 in 2: 3){
              for (x1 in 0: m1) {
                   for (y1 in 0: n1) {

                  d<-rbind(d, c(m1, n1, x1,y1))
    }}}}

so for m1=2, n1=2, the cumlative sum of x1 should be 9 and sum of y1 is 9,
for  m1=2, n1=3, the cumlative sum of x1 should be 12 and sum of y1 is 18.
Comment: What should happen in the cases, which include different values in `m1` and `m2`?
Comment: For those of us who are not Svens, what do input and output look like?
Answer: Is this what you are looking for? (using data.table). And I think you want to sum all the elements, and not cumulatively sum and return all elements.
# after running your code, I had to rename it
names(d) <- c("m1", "n1", "x1", "y1")
require(data.table)
dt <- data.table(d)
setkey(dt, m1, n1)
out <- dt[, list(s.x1=sum(x1), x.y1=sum(y1)),by="m1,n1"]
> out
#    m1 n1 s.x1 x.y1
# 1:  2  2    9    9
# 2:  2  3   12   18
# 3:  3  2   18   12
# 4:  3  3   24   24


How to show $\bigcap_{m \textrm{: maximal ideal}} A_m=A$?

Question: $A$ is an integral domain. For every maximal ideal $m$ in $A$, consider $A_m$ as a subring of the quotient field $K$ of $A$. Show $\bigcap A_m=A$, where the intersection is taken over all maximal ideals $m$ of $A$.
This is a homework problem. I thought I figured it out but soon I realized that my argument only works in the case that there are finitely many maximal ideals, which is much weaker.
Answer: Hint: Let $\frac{a}{b} \in \bigcap_m A_m$. Consider the ideal $I = \{r \in A: r\frac{a}{b} \in A\}$. What can you say about $I$? You need to use the fact that any proper ideal is always contained in a maximal ideal.
Answer: Since $1\in S$, we clearly have $$A\subseteq \bigcap_{\mathbf{m}\in\mathcal{M}}A_\mathbf{m}.$$
    On the other hand, let $a\in\bigcap_{\mathbf{m}\in\mathcal{M}}A_\mathbf{m}$ and define $I$ to be the ideal such that $a\frac{x}{1}=\frac{x'}{1}$, where $x$ and $x'$ are elements of $A$. Thus, $I$ consists of those elements which are denominators of $a$. We claim that $I=A$. Suppose not, then $I$ is a proper ideal, hence it is contained in a maximal ideal, say $\mathbf{m}^*$. Then, since $a\in\bigcap_{\mathbf{m}\in\mathcal{M}}A_\mathbf{m}$, we know $a\in A_{\mathbf{m}^*}$. This implies $a$ can be written in the form $\frac{p}{q}$ with $q\notin \mathbf{m}^*$, but clearly $\frac{p}{q}\cdot\frac{q}{1}=\frac{p}{1}$, hence $q\in I$. This is a contradiction to the fact that $I$ is contained in the maximal ideal, hence $I$ must not be proper, i.e., $I=A$.
Comment: I'd make that definition of $I$ a bit clearer. It's not obvious that you mean all $x$ such that there exists $x'$ such that... Also, the "denominator" explanation seems to exclude $x=0$.
Comment: What is S in this proof?
Comment: Nice argument. Thanks.


Expected exit code 0, not 1?

Question: I submitted this problem set, but I'm unable to get a full mark grade because the exit code "is expected to be 0 and not a 1". However, if you take a look at the code (the recover.c file), the exit code is 0. What is wrong? The program accomplishes everything it was made for, which is to read through bits in a corrupted file and find the bits that make up a JPG file and write them in a separate file. The only problem I'm having is this aforementioned exit code issue. Please help!
recover.c file
#include <stdio.h>
#include <cs50.h>
#include <stdlib.h>
#include "bmp.h"

int main (void){

    FILE* card_ptr = fopen("card.raw","r");

    if (card_ptr == NULL){

        fprintf(stderr,"File Not Found!");
        return 1;
    }

    BYTE buffer[512];

    bool found_jpg = false;

    FILE* new_jpg_ptr;

    int file_counter = 0;

    while(fread(buffer,1,512,card_ptr)!=0x00){

        if(buffer[0]== 0xff && buffer[1]== 0xd8 && buffer[2]==0xff && (buffer[3] & 0xf0)== 0xe0){

            if(!found_jpg){

                char filename[8];

                sprintf(filename, "%03i.jpg", file_counter++);

                found_jpg = true;

                new_jpg_ptr = fopen(filename,"w");

                if(new_jpg_ptr == NULL){
                    return 2;
                }

                fwrite(buffer,1,512,new_jpg_ptr);

            }

            else {

                fclose(new_jpg_ptr);

                char filename[8];

                sprintf(filename, "%03i.jpg", file_counter++);

                found_jpg = true;

                new_jpg_ptr = fopen(filename,"w");

                if(new_jpg_ptr == NULL){
                    return 3;
                }

                fwrite(buffer,1,512, new_jpg_ptr);

            }

        }

        else {

            if(found_jpg){

                 fwrite(buffer,1,512, new_jpg_ptr);

            }

        }

    }

    fclose(new_jpg_ptr);

    fclose(card_ptr);

    return 0;
}

bmp.h file
/**
 * BMP-related data types based on Microsoft's own.
 */

#include <stdint.h>

/**
 * Common Data Types
 *
 * The data types in this section are essentially aliases for C/C++
 * primitive data types.
 *
 * Adapted from https://msdn.microsoft.com/en-us/library/cc230309.aspx.
 * See http://en.wikipedia.org/wiki/Stdint.h for more on stdint.h.
 */
typedef uint8_t  BYTE;
typedef uint32_t DWORD;
typedef int32_t  LONG;
typedef uint16_t WORD;

/**
 * BITMAPFILEHEADER
 *
 * The BITMAPFILEHEADER structure contains information about the type, size,
 * and layout of a file that contains a DIB [device-independent bitmap].
 *
 * Adapted from https://msdn.microsoft.com/en-us/library/dd183374(v=vs.85).aspx.
 */
typedef struct
{
    WORD bfType;
    DWORD bfSize;
    WORD bfReserved1;
    WORD bfReserved2;
    DWORD bfOffBits;
} __attribute__((__packed__))
BITMAPFILEHEADER;

/**
 * BITMAPINFOHEADER
 *
 * The BITMAPINFOHEADER structure contains information about the
 * dimensions and color format of a DIB [device-independent bitmap].
 *
 * Adapted from https://msdn.microsoft.com/en-us/library/dd183376(v=vs.85).aspx.
 */
typedef struct
{
    DWORD biSize;
    LONG biWidth;
    LONG biHeight;
    WORD biPlanes;
    WORD biBitCount;
    DWORD biCompression;
    DWORD biSizeImage;
    LONG biXPelsPerMeter;
    LONG biYPelsPerMeter;
    DWORD biClrUsed;
    DWORD biClrImportant;
} __attribute__((__packed__))
BITMAPINFOHEADER;

/**
 * RGBTRIPLE
 *
 * This structure describes a color consisting of relative intensities of
 * red, green, and blue.
 *
 * Adapted from https://msdn.microsoft.com/en-us/library/dd162939(v=vs.85).aspx.
 */
typedef struct
{
    BYTE rgbtBlue;
    BYTE rgbtGreen;
    BYTE rgbtRed;
} __attribute__((__packed__))
RGBTRIPLE;

Comment: Perhaps fopen failed, leading to the exit code 1 ?
Comment: There's an awful lot of blank lines in the tail of that code.  It makes it hard to read -- too much white space is as bad as too little white space.
Comment: Also this program overflows a buffer if there are more than 1000 input files
Comment: `fclose(new_jpg_ptr);` is called always, but sometimes `new_jpg_ptr` is uninitialized
Comment: @M.M When I run the code it actually works. Only when I submit it for grading, does the grading bot find a problem.
Comment: @user8468882 perhaps the grading bot fails to open a file called "card.raw"
Comment: It would help if you posted the exact problem stipulation and conditions
Answer: I experienced the same problem. My program worked as expected with no obvious reasons for a return code of 1. As you have, I had also included a header file with some definitions in it. Placing those definitions in the core file solved my problem. Perhaps if you move the needed definitions from your bmp.h file into recover.c, check50 will be able to compile.
My solution if you're interested.
// Recover any forgotten JPEGS from a given forensic image

# include <stdio.h>
# include <stdbool.h>
# include <stdint.h>

typedef uint8_t BYTE;

typedef struct
{
    BYTE byte_1;
    BYTE byte_2;
    BYTE byte_3;
    BYTE byte_4_min;
    BYTE byte_4_max;
} __attribute__((__packed__))
SIG;

// declare helper function prototypes
int check_args(int argc, char *argv[]);
bool signature_is_present(BYTE potential_sig[4], SIG jpeg_sig);

SIG set_jpeg_signature(void);

// main program
int main (int argc, char *argv[])
{
    // check input for validity
    int check_args_value = check_args(argc, argv);
    if (check_args_value != 0)
    {
        return check_args_value;
    }

    // call function to set default jpeg signature
    SIG jpeg_sig = set_jpeg_signature();

    // open buffers and declare other necessary variables for later use
    BYTE FAT_block[512];
    BYTE first_byte[1];
    int signature_offset = -4;
    int counter = 0;

    // open forensic image
    FILE * inptr = fopen(argv[1], "r");
    FILE * outptr = NULL;

    // loop through file searching for first '255'
    while (fread(first_byte, sizeof(BYTE), 1, inptr) == 1)
    {
        // check if byte is 255, the first byte of a jpeg signature
        if (*first_byte == jpeg_sig.byte_1)
        {
            // check for signature
            BYTE possible_sig[4];

            // back pointer up one byte to compensate for already discovered 255
            fseek(inptr, -1, SEEK_CUR);

            // read four bytes from file that could potentially be a signature.
            fread(possible_sig, sizeof(possible_sig), 1, inptr);

            if (signature_is_present(possible_sig, jpeg_sig))
            {
                // close previously open write file, if any.
                if (outptr != NULL)
                {
                    fclose(outptr);

                    //Increment counter for image signatures found.
                    counter++;
                }

                // setup name for image file
                char file_name[8] = {};
                snprintf(file_name, 8, "%.3i.jpg\n", counter);

                // move pointer back 4 bytes after checking what they contain
                fseek(inptr, signature_offset, SEEK_CUR);

                //read FAT block from forensic image into buffer
                fread(FAT_block, sizeof(FAT_block), 1, inptr);

                // open new output file based on current signature
                outptr = fopen(file_name, "w");

                // write FAT block buffer to file
                fwrite(FAT_block, sizeof(FAT_block), 1, outptr);
            }
            else // byte is 255 but not part of a signature
            {
                if (outptr != NULL)
                {
                    // move pointer back 4 bytes after checking what they contain
                    fseek(inptr, signature_offset, SEEK_CUR);

                    //read FAT block from forensic image into buffer
                    fread(FAT_block, sizeof(FAT_block), 1, inptr);

                    // write FAT block buffer to file
                    fwrite(FAT_block, sizeof(FAT_block), 1, outptr);
                }
            }
        }
        else // if byte is not 255
        {
            if (outptr != NULL)
            {
                //back up one byte
                fseek(inptr, -1, SEEK_CUR);

                //read FAT block from forensic image into buffer
                fread(FAT_block, sizeof(FAT_block), 1, inptr);

                // write FAT block buffer to file
                fwrite(FAT_block, sizeof(FAT_block), 1, outptr);
            }
        }
    }

    // close files
    fclose(inptr);

    if (outptr != NULL)
    {
        fclose(outptr);
    }

    return 0;
}

// helper functions
int check_args(int argc, char *argv[])
{
    if (argc != 2)
    {
        fprintf(stderr, "Invalid Input.\nForensic image file must be provided.\n");
        return 1;
    }

    FILE *inptr = fopen(argv[1], "r");

    if (inptr == NULL)
    {
        fprintf(stderr, "File does not exist.\n");
        return 2;
    }

    fclose(inptr);

    return 0;
}

bool signature_is_present(BYTE potential_sig[4], SIG jpeg_sig)
{
    if( potential_sig[0] == jpeg_sig.byte_1 &&
        potential_sig[1] == jpeg_sig.byte_2 &&
        potential_sig[2] == jpeg_sig.byte_3 &&
        potential_sig[3] >= jpeg_sig.byte_4_min &&
        potential_sig[3] <= jpeg_sig.byte_4_max )
    {
        return true;
    }

    return false;
}

SIG set_jpeg_signature(void)
{
    SIG jpeg_sig;

    jpeg_sig.byte_1 = 255;
    jpeg_sig.byte_2 = 216;
    jpeg_sig.byte_3 = 255;
    jpeg_sig.byte_4_min = 224;
    jpeg_sig.byte_4_max = 239;

    return jpeg_sig;
}

Expected exit code 0, not 1?


Run a specific unit test in Laravel before al other unit tests (phpunit)

Question: I'm busy learning to unit test in Laravel and I have a question.
I want one test that has to do with authentication to run first before running other all other tests. Can this be achieved?
I have 4 test classes with a few methods so far.
Comment: In PHPUnit, every single test is run with a fresh environment, all the setting up and tearing down is done for every test, so the order does not matter. If you're trying to authenticate as part of your other tests, say for example you're testing your API and you need your tests to authenticate as a user, Laravel's testing facility has methods and helpers to let you do just that. Can you give more context to your problem? I might be able to help you better if I know what you're trying to achieve
Comment: What you'll need to do is do all of your setup in the `setUp` method of your test cases, that method is executed before each and every test is run. Similarly, the `tearDown` method is run after every one of your tests have completed. Alternatively, you could create a method that does all of your setup and call it at the beginning of each of your tests.
Comment: There you go :)
Comment: I have some methods that will only work when the DB / authentication is set up properly, And sometimes due to my working environment the test data is gone, So I want to check in a test (before all other tests) that the test data is there. Else all my tests fail
Comment: Your comment is an answer, If you post it as an answer i will accept it :-)
Comment: @Jonathon Is there a way to only do a setUp() on the first test in a class? Like a constructor
Answer: In PHPUnit, every single test is run with a fresh environment, all the setting up and tearing down is done for every test, so the order does not matter. If you're trying to authenticate as part of your other tests, say for example you're testing your API and you need your tests to authenticate as a user, Laravel's testing facility has methods and helpers to let you do just that.
You'll need to do all of your setup in the setUp method of your test cases. That method is executed before each and every test is run. Similarly, the tearDown method is run after every one of your tests have completed:
public class YourTest extends TestCase
{
    protected function setUp()
    {
        // Do your setup here
    }

    protected function tearDown()
    {
        // Your cleanup here, if you're using Mockery, this
        // is a good place to call Mockery::close();
    }

    public function testSomething()
    {
        // Your test code, you can assume that setUp has
        // already run and you're ready to go.
    }
}

Alternatively, you could create a method that does all of your setup and call it at the beginning of each of your tests.


Count array items and add div after certain number

Question: $specs = array ('Name' => 'Cleopatra', 'Year' => '2008', 'Length' => '20ft', 'Make' => 'manufacturer', 'Model' => 'model', 'Engines Count' => '2', 'Fuel' => 'Diesel', 'Rudder' => 'rudder', 'Keel' => 'keel', 'Price' => '$1');

foreach ($specs as $label => $detail) {
  echo "
";
  echo "{$label}	";
  echo "{$detail}	";
  echo "
";
}

The foreach loop returns 1 column in each row. How can I render 4 columns per row like so

      Label
      Detail
      Label
      Detail
      Label
      Detail
      Label
      Detail

      Label
      Detail
      Label
      Detail
      Label
      Detail
      Label
      Detail

Comment: 4 rows per column? or columns per row? Your example is columns per row.
Answer: Just add counter, something like this:
echo "
";
foreach ($specs as $label => $detail) {
  if($i%4 == 0 && $i != 0) {
    echo "
";
    echo "
";
  }
  echo "{$label}	";
  echo "{$detail}	";
  $i++;
}
echo "
";

Update: Fixed edge case $i=0 and
's in right order
Comment: Not quite, this doesn't put the ``s and ``s in the right spot.
Comment: Thanks, fixed, hope now it's okay
Answer: Set a counter, and every 4th iteration, print a new
.
$i = 0;
echo '
';
foreach ($specs as $label => $detail) {
  if($i !== 0 && $i%4 === 0){
     echo '

';
  }
  echo "{$label}	";
  echo "{$detail}	";
  $i++;
}
echo '
';

Answer: If you remember your maths from school, you can use the mod operator to get the remainder of a division operation.  This is what you need to get what you want.
 echo "
";
foreach ($specs as $label => $detail)
{
  $counter++;
  //get remainder of division by 4, when 1 create new row
 if ($counter % 4 == 1)
 {
  echo "
";
  echo "
";
 }
 echo "{$label}	";
 echo "{$detail}	";

}
echo "
";

Answer: This carries the assumption that your index is zero based.
First we define the number of columns we want in each row. Then, we define two rules sets: when to start a new row and when to end a row.
We want to start a new row on the first iteration and anytime the current iteration count is divisible by the number of columns we want in each row.
We want to end a row when we are on the last iteration. Also we will end a row anytime that we are not on the first iteration and the total count of the collection minus the current iteration count is divisible by the number of columns we want in each row minus one.
$cols_in_row = 5;
foreach ($array as $i => $item)
{
    if ($i == 0 || $i % $cols_in_row == 0)
    {
        echo '
';
    }

    echo ''.$item.'	';

    if ($i + 1 == count($array) || ($i != 0 && count($array) - $i % ($cols_in_row - 1)))
    {
        echo '
';
    }
}

This method allows you to only write the opening and closing tags once so that editors don't think that you are forgetting to open or close something.


What actions are taken by FIFA/UEFA against what's known as filming or diving

Question: It seems to me that modern football is suffering from the kind of unsportsmanly behavior of diving which became all the more common, perhaps with the recent success of southern European teams/nations.
For those who might not be familiar with the concept, diving is the act of fooling the referee into a wrong call, either by pretending as if the tackle is much harder than it really was (in which case the opponent might be punished with a card) or to get a free kick/penalty kick where there is no apparent foul. Not only does it result in unfair calls, but also in many cases it slows the game down due to all the unnecessary free kick calls. In many cases it is normal to see players rolling on the grass seemingly screaming in agony for a second, and up on their feet arguing with an opponent in the next...
With more and more efforts going into campaigns against factors that spoil the game (such as racism) I would like to know if any steps are taken against this type of behavior aimed to interfere with the objective call of the referee? As far as I know, the referee can punish a player with a yellow card if the player is attempting to cheat the referee into giving a penalty but more often than not unnecessary cards and fouls are given as seen by instant replays from different angles. Are there any active measures to decrease this type of behavior or the pitch?
Answer:
Referees and FIFA are now trying to prevent diving with more frequent
  punishments as part of their ongoing target to stop all kinds of
  simulation in football. The game's rules now state that: "Any
  simulating action anywhere on the field, which is intended to deceive
  the referee, must be sanctioned as unsporting behaviour" which is
  misconduct punishable by a yellow card. The rule changes are in
  response to an increasing trend of diving and simulation.
FIFA , in order to improve detection, Increased the number of
  officials on the field – near the goals, where most dives occur – what
  make it easier to detect diving.
Second, in order to increase the costs associated with diving.
  Progressive football leagues like the Australian A-League and the
  American MLS are using post-match video analysis to assign
  retrospective punishment to cheating players.
In these countries, there's strong competition from more physical
  footballing codes (such as rugby, or American football) for the
  sporting public's attention, and there's little patience for
  play-acting.
MLS in the United States, for the 2011 season, began implementing
  fines and suspensions for simulation in football through its
  Disciplinary Committee, which has the right to review plays after the
  match.   On June 24, 2011, MLS penalized D.C. United forward Charlie
  Davies with a US$1,000 fine as the Disciplinary Committee ruled he:
  "intentionally deceived the officials and gained an unfair advantage
  which directly impacted the match" in a simulation that occurred in
  the 83rd minute of the match against Real Salt Lake on June 18, 2011.
On July 29, 2011, the Disciplinary Committee suspended Real Salt Lake
  forward Álvaro Saborío one game and fined him US$1,000 for a
  simulation in a game against the San Jose Earthquakes on July 23,
  2011. Officials noted the simulation resulted in Earthquakes defender Bobby Burling being sent off on the simulation, and the warning from
  MLS that fines and suspensions will increase for simulation being
  detected by the Disciplinary Committee.

Another unique scenario was with Juventus winger Milos Krasic who has been banned for two games by the Italian football league for diving.
Krasic won a controversial penalty in goalless draw at Bologna after falling inside the area.
Video replays, however, showed Bologna defender Daniele Portanova did not touch the player.
A statement from the league read:

"The TV replay showed that there was no contact between the two
  players and that the player's dive was the cause for the referee to
  make a mistake."

But until these methods are adopted universally, you'll just have to keep shouting at the television.
Sources:
Wikipedia on Diving
Why footballers dive; how it could be stopped.
Milos Krasic incident related to diving.
Comment: It's very interesting to see that there are some aspects in football where European leagues can learn something from MLS. Actually it's stated by many football experts that the diving factor of football is one of the main reasons why it's only 4-5th most popular sport in NA.


ZXing Could not load Type in Xamarin Forms for iOS

Question: im getting an Error in my Xamarin Forms Application. This error only occurs on Android. iOS Works fine.
This is the line where the Exception is thrown.
ZXing.Net.Mobile.Forms.Android.Platform.Init();

This is the Exception
Could not load typeZXing.Net.Mobile.Forms.Android.ZXingScannerViewRenderer'
from assembly 'ZXing.Net.Mobile.Forms.Android, Version=184.108.40.206,
Culture=neutral, PublicKeyToken=null'.

StackTrance:
at ZXing.Net.Mobile.Forms.Android.Platform.Init () [0x00000] in <30849edafd8e4fbb9f24af588a9bebb0>:0
at AllergyDetector.Droid.MainActivity.OnCreate (Android.OS.Bundle bundle) [0x0002d] in /Users/alexanderrummel/Development/Projects/dotNet/AllergyDetector/Droid/MainActivity.cs:28
at Android.Support.V4.App.FragmentActivity.n_OnCreate_Landroid_os_Bundle_ (System.IntPtr jnienv, System.IntPtr native__this, System.IntPtr native_savedInstanceState) [0x00011] in <27c17fe440cf491ba8255bcefade6e02>:0
at (wrapper dynamic-method) System.Object:ceddf78a-cf9a-4fee-97a9-ea86e17b2375 (intptr,intptr,intptr)

I use the following Versions
XamarinForms: 220.127.116.11-pre2
ZXing.Net.Mobile 2.1.47
ZXing.Net.Mobile.Forms 2.1.47

TargetFramework Android 5.0
MinimalAndroid Version Android 5.0

Answer: After a quick Google action it seems that this is a known issue with the Xamarin.Forms 220.127.116.11-pre2 release. Have a look at the GitHub page here although it also seems to happen with other version of Xamarin.Forms.
There also is a fix suggested by richardpike:

I was able to fix this for myself by downloading the source code and
  updating the xamarin forms package to the pre-release (220.127.116.11-pre2)
This required 2 new override functions in ZXingScannerViewRenderer.cs,
  and ZXingBarcodeImageViewRenderer.cs (from the
  ZXing.Net.Mobile.Forms.Android project). All I did was make them
  return null.
This builds successfully and I was able to use the resulting dll in my
  project without it crashing.
I would make a pull request, but I've never done one before using
  github...

If that is not something you're comfortable with I'm afraid you are stuck with waiting until they have fixed this.
Comment: totaly agree. i mark it as solved. thats not a solutions which should be used for production...


Como pesquisar por número digitado?

Question: Tenho uma barra de pesquisa através de um teclado numérico, como faço para fazer pesquisa de página por número digitado
Código html:

<DOCTYPE HTML PUBLIC>

        <form name="calculator">
            <input name="display" value="" size="6" style="text: Arial; font-size: 20pt; background-color:#58D3F7" >
            <input type="button" value="ver" onclick="ver()" />

                          <input value=" 7 " onclick="number(7)" type="button" style='width:50px; height:50px;font-size:30px;color:blue'>
                          <input value=" 8 " onclick="number(8)" type="button" style='width:50px; height:50px;font-size:30px;color:blue'>
                          <input value=" 9 " onclick="number(9)" type="button" style='width:50px; height:50px;font-size:30px;color:blue'>

                          <input value=" 4 " onclick="number(4)" type="button" style='width:50px; height:50px;font-size:30px;color:blue'>
                          <input value=" 5 " onclick="number(5)" type="button" style='width:50px; height:50px;font-size:30px;color:blue'>
                          <input value=" 6 " onclick="number(6)" type="button" style='width:50px; height:50px;font-size:30px;color:blue'>

                          <input value=" 1 " onclick="number(1)" type="button" style='width:50px; height:50px;font-size:30px;color:blue'>
                          <input value=" 2 " onclick="number(2)" type="button" style='width:50px; height:50px;font-size:30px;color:blue'>
                          <input value=" 3 " onclick="number(3)" type="button" style='width:50px; height:50px;font-size:30px;color:blue'>

                        <input value=" 0 " onclick="number(0)" type="button" style='width:50px; height:50px;font-size:30px;color:blue'>

                          <input value="C" onclick="clear1()" type="button" style='width:50px; height:50px;font-size:30px;color:blue'>

        </form>

Comment: Olá César,

sou iniciante na área de desenvolvimento e criei um teclado numérico virtual, para utilizá-lo como uma barra de pesquisa dentro de um site, onde ao digitar um número e clicar no botão ver o usuário consiga ser direcionado para uma página dentro do site referente ao número que digitou, porém não estou conseguindo concluir esse processo, se poder ajudar
Comment: Não consegui entender nem o que você tem, nem o que quer fazer, nem o erro que acontece. Pode explicar melhor? O que é "barra de pesquisa através de um teclado numérico", e o que seria "fazer pesquisa de página por número digitado"?
Answer: Isso porque voce está pegando o valor do input de forma errada na sua função ver().
function ver(){
   location.href="/"+document.calculator.display.value;
}

De uma estudada na sintaxe básica do getElementByID do javascript que vai entender como selecionar elementos para manipulá-los ou recuperar seu valor.
Primeiro de um id ao input que voce quer recuperar o valor (no seu caso o input display):
<input name="display" id="valor_atual_display" value="" .../>

Depois é só pegar seu valor por meio do getElementByID como voce estava fazendo, porém usando a sintaxe correta:
function ver(){
   location.href="/"+document.getElementById("valor_atual_display").value;
}

O mesmo vale para o seletor forms do javascript nessa linha:
document.forms["calculator"].display.value += ch;

Compare a sintaxe com o da documentação oficial e veja onde está o erro. Não vou passar de mão a sintaxe de tudo pra não te atrapalhar nos estudos mas vou deixar os link de referencia (dica: está no titulo "Named form access"):
https://developer.mozilla.org/en-US/docs/Web/API/Document/forms
https://developer.mozilla.org/pt-BR/docs/Web/API/Document/getElementById

Como pesquisar por número digitado?


Como posso obter o BluetoothManager do dispositivo no Kotlin?

Question: Estou aprendendo sobre Bluetooth em Kotlin e estava lendo este documento do Google sobre BluetoothAdapter https://developer.android.com/reference/android/bluetooth/BluetoothAdapter. Comecei a implementar o código para dispositivos Android com a API 6.0 (superior a JELLY_BEAN_MR1) e tenho alguns problemas para obter o BluetoothManager. Aqui está o código em que estou trabalhando:
lateinit var mBluetoothManager:BluetoothManager
fun foo(context:Context){
      this.mBluetoothManager = context.getSystemService(Context.BLUETOOTH_SERVICE)
}

O Android Studio mostra que é uma incompatibilidade de tipos (obrigatório: BluetoothManager, Founded: Any!). Então, como posso obter a instância do BluetoothManager, eu fiz algo de errado? Por que preciso ligar dessa forma usando o SystemService e não dessa forma:
var mBluetoothManager = BluetoothManager()

?
Answer: Porque o método getSystemService é um método feito para funcionar de forma genérica e retornar qualquer tipo de serviço do sistema, não apenas um gerenciador de bluetooth. Desta forma, o retorno do método é Any! (Kotlin) / Object (Java).
Portanto, falta fazer uma conversão para o tipo de destino
this.mBluetoothManager =
    context.getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager

Por que preciso ligar dessa forma usando o SystemService e não dessa forma var mBluetoothManager = BluetoothManager()?

Porque, da segunda forma, você estaria criando uma instância de BluetoothManager, mas não é isso que você precisa. Você precisa obter uma instância a partir de Context.
Comment: Entáo quando eu mudar de contexto eu preciso chamar o getSystemService novamente?


OpenVZ container as gateway performance issue?

Question: I am running a lot of openvz container in server. Now I have a lot of performance issue, and I think they come from I/O since munin graph show a lot of I/O activiy.
Server is proxmox, and it was recently upgraded (this could be the problem also)
But near upgrade to last version of proxmox I added a gateway in a container running shorewall.
But now is almost impossible to log in the server, rebooting makes the system usuable but after two or tree hours I/O problems come again.
There isnt too much network activiy (10kb/s) it's  a home "test" server.
Any other idea in order to detect the problem? openvz container asgateway is not a good idea?
Answer: You may look at the "failctl" column by typing this command :
vzctl exec 101 cat /proc/user_beancounters

You now need to adapt (101 here) this number to all of your VMs. If some beancounters are not equal to 0, you need to increase those value.
Now for example, if you want to grow a value on the fly, you could do like this :
vzctl set 101 --privvmpages 786432:1048576 --save --setmod restart

Now, for your I/O poblems, on the main machine (hosting VMs), is a "top" commands is giving you some iowaits ? If it's the case, it means you should add more disks.
Comment: yes, at hardware node there was a problem with a process using %100 cpu. I now change the kernel, but not sure if this would fix the problem since is like random
Comment: Did you try to upgrade to the last version of proxmox ?
Comment: the problem started after upgrade to last version (1.5)
Comment: Did you look at beancounters like I told you ?
Answer: I switch back to kernel 2.6.18 and the I/O problem went away. It seems a problem with kernel 2.6.24


Find curve pattern of simple time series

Question: I have time series data of credit card transaction volumes for different companies. For example:
week1: \$5000
week2: \$6000
week3: \$6200
week4: \$7000
week5: \$9000
...

Is there a simple method in R to determine if the number series has a linear trend upwards, downwards or like a normal distribution (rising first then dropping)?
Comment: Plotting the data is one answer. Presumably you know that, so please be more precise about the kind of method you seek.
Comment: A method that takes a vector of time series data and gives me as output: "linear trend up", "linear trend down", "rise-then-fall".
Comment: That's clearer. Good luck on finding it! I don't think people write programs like that, but being wrong is very possible.
Answer: You should first try and remove any seasonal effects from your data, otherwise the trend might be misleading, especially if your data include transcations from several years. For processing and plotting, the R package stl should be a good point to start: http://stat.ethz.ch/R-manual/R-devel/library/stats/html/stl.html
For general time series analysis issues, you should also see what CRAN has to suggest: http://cran.r-project.org/web/views/TimeSeries.html
Answer: You should studiously avoid any attempt to deseasonalize or to detrend as eventually that structure potentially has to be re-inserted at the end in order to make forecasts in the observational space. It is a good idea to form a useful equation that incorporates 1) weekly factors 2) holiday effects 3) trends 4) level shifts 5) changes in parameters over time and/or 6) changs in error variance over time without any unwarranted transformations.
Comment: Is all this really necessary when the O.P. merely requests a set of *descriptive* statistics?
Comment: The op sked for a method to determine if the series was upwards trending or downwards trending. To me this a request for an inferential analysis not a descriptive analysis.
Comment: I agree that the question could be interpreted in different ways, but a [comment to the question](http://stats.stackexchange.com/questions/77826/r-find-curve-pattern-of-simple-time-series/77856?noredirect=1#comment152303_77826) indicates that forecasting is not intended.
Answer: Sure, This is possible with some programming effort. I work with transaction data a lot. There are two approaches that i have used. Unfortunately there is no standard procedures that is available.
Approach 1 (Pattern known a priori):
If you interested in finding a priori pattern like trend up trend down, then you could use a similarity analysis or a classification problem, click here for an example implementation in SAS with Proc Similarity. There are 6 types of pattern that you can notice in the transnational data sets and I have used in the past:

Increasing trend
Decreasing trend
Level Shift up
Level shift down
Spike Up or Down
no pattern

You could also use neural network to train the 6 patterns and then apply the trained network to your transnational data. See below for these patterns.
Approach 2 (Pattern not known a priori)
If you do not have a priori pattern, then you would want to use AI techniques based on clustering such as neural networks, kohonen networks etc. to let the method automatically find and cluster similar patterns such as trend increase/down etc.
Based on my experience, approach 1 is better than approach 2. If you are intrested in a worked out example, I can post a link to a paper.
Hope this is helpful.
Comment: Hi, thanks, I think I get the idea of this approach. Do you have some R code or a package that has this implemented? My skills are not sufficient to write my own package from the paper you provided.
Comment: I used sas for my project
Comment: is there any chance you could post a link to a paper to work approach 1?


How to make my spider's leg move in XNA

Question: I've done a 3D spider model in Blender, and currently I can export it as a .x(direct X) file and import this .x file into XNA gamestudio and make it shown there as a static model.
Now this project is coming to the final stage, that is, we need to make one of its legs move back and forth in the XNA, however,it only needs to move back and forth, so no keyboard response is required.
We already successfully made one leg of the spider in the Blender has bones and armature and ik constraint, so in Blender, I can drag the leg to move. But now we are really stuck on how to get this move automatically in XNA, we tried exporting it as .x file the same way as before, but this time it won't even show in XNA.
It would be really great if you could give us a little help here, or maybe refer us to some tutorials on how to animate Blender model in XNA, thanks in advance!
Answer: here is a pretty good thread in the XNA forums that talks about animating models
http://forums.create.msdn.com/forums/p/53155/322140.aspx

How to make my spider's leg move in XNA


Como preencher um DropDownList a partir de outro DropDownList

Question: Preciso saber como faço para popular um DropDownList a partir de outro DropDownList. Exemplo: Tenho um DropDownList chamado Equipe que pega as informações do meu DB. Quando seleciono por exemplo "Equipe1" preciso que no meu segundo DropDownList carregue todos os integrantes daquela equipe. Todas essas informações estão no DB. Tenho 3 tabelas Equipe, Integrante e EquipedeIntegrantes.
Buscar Integrante
    [HttpGet]
    public ActionResult ListarIntegrantes(int id)
    {
        GerenciadorContexto ctx = new GerenciadorContexto();
        var lista = new List<EquipedeIntegrante>();

        try
        {
            lista = ctx.EquipedeIntegrantes.Where(m => m.EquipeId == id).ToList();
        }
        catch (Exception ex)
        {

            throw;
        }

        return Json(new { Resultado = lista }, JsonRequestBehavior.AllowGet);
    }

View
    @using (Html.BeginForm())
    {

TarefaViewModel

            @Html.LabelFor(model => model.EquipeId, htmlAttributes: new { @class = "control-label col-md-2" })

                @Html.DropDownListFor(model => model.EquipeId, Model.Equipes, "--Selecione", new { @class = "form-control" })

            @Html.LabelFor(model => model.IntegranteId, htmlAttributes: new { @class = "control-label col-md-2" })

                <select id="IntegranteId" class="form-control"></select>

            @Html.LabelFor(model => model.Descricao, htmlAttributes: new { @class = "control-label col-md-2" })

                @Html.EditorFor(model => model.Descricao, new { htmlAttributes = new { @class = "form-control" } })

            @Html.LabelFor(model => model.Conclusao, htmlAttributes: new { @class = "control-label col-md-2" })

                @Html.EditorFor(model => model.Conclusao, new { htmlAttributes = new { @class = "form-control" } })

                <input type="submit" value="Create" class="btn btn-default" />

}

Script
$(document).ready(function () {

    $("#EquipeId").change(function () {

        var value = $("#EquipeId option:selected").val();

        if (value !== 0 || value !== undefined)
        {
            ListarIntegrantes(value);
        }

    })

})

function ListarIntegrantes(value)
{

    var url = "/Tarefas/ListarIntegrantes";
    var data = { equipe: value };
    $("#EquipeId").empty();
    $.ajax({

        url: url,
        type: "GET",
        datatype: "json",
        data: data
    }).done(function (data) {

        if (data.Resultado.length > 0) {
            var dadosGrid = data.Resultado;
            $("#EquipeId").append('<option value="">--Selecione</option>');

            $.each(dadosGrid, function (indice, item) {

                var opt = "";

                opt = '<option value="' + item["Id"] + '">' + item["Nome"] + '</option>';
            })
        }
    })

}

Tabelas
Answer: Ao colocar var opt = ""; dentro do laço .each, a variável será esvaziada (e redeclarada) a cada iteração do objeto dadosGrid.
Coloque-a fora, e dentro do laço concatene a variável com a string que monta as option; e após isso, envie via .append o resultado:
if (data.Resultado.length > 0) {
   var dadosGrid = data.Resultado;
   $("#EquipeId").append('<option value="">--Selecione</option>');

   var opt = "";
   $.each(dadosGrid, function (indice, item) {
      opt += '<option value="' + item["Id"] + '">' + item["Nome"] + '</option>';
   })
   $("#EquipeId").append(opt);
}

Ou você pode fazer um .append só no final, concatenando tudo:
if (data.Resultado.length > 0) {
   var dadosGrid = data.Resultado;
   var opt = "";
   $.each(dadosGrid, function (indice, item) {
      opt += '<option value="' + item["Id"] + '">' + item["Nome"] + '</option>';
   })
   $("#EquipeId").append('<option value="">--Selecione</option>'+opt);
}

Comment: Continua retornando o mesmo erro amigo no console do navegador
GET http://localhost:54446/Tarefas/ListarIntegrantes?equipe=1 500 (Internal Server Error)
Comment: Mas na pergunta não cita nenhum erro :D  ... os únicos erros que vi foram os que coloquei na resposta. Se está dando erro de servidor, não é problema no JavaScript. Tem que saber que erro é esse do servidor. Provavelmente no arquivo `"/Tarefas/ListarIntegrantes"`.
Comment: Olhe acima o método ListarIntegrantes se possui algum erro por gentileza


Javascript crash sometimes and sometimes not?

Question: I building website using following script. Sometime this javascript crash sometimes not. Weird thing is when I add alert box at third line after sliderLeft define, script never crash. Someone please help with this.
I am using same function twice for different output.
Even I remove Second similar function I am still getting error. Please help me with this.
$(window).load(function() {
    var sliderLeft=$('#thumbScroller .container').position();
    //alert(sliderLeft);
 //   padding=$('#outer_container').css('paddingRight').replace("px", "");
    var sliderWidth=$(window).width()
    $('#thumbScroller').css('width',sliderWidth);
    var totalContent=0;
    $('#thumbScroller .content').each(function () {
        totalContent+=$(this).innerWidth();
        $('#thumbScroller .container').css('width',totalContent);
    });
    //alert(sliderLeft);
    $('#thumbScroller').mousemove(function(e){
        if($('#thumbScroller  .container').width()>sliderWidth){
            var mouseCoords=(e.pageX - this.offsetLeft);
            var mousePercentX=mouseCoords/sliderWidth;
            var destX=-(((totalContent-(sliderWidth))-sliderWidth)*(mousePercentX));
            var thePosA=mouseCoords-destX;
            var thePosB=destX-mouseCoords;
            var animSpeed=600; //ease amount
            var easeType='easeOutCirc';
            if(mouseCoords==destX){
                $('#thumbScroller .container').stop();
            }
            else if(mouseCoords>destX){
                //$('#thumbScroller .container').css('left',-thePosA); //without easing
                $('#thumbScroller .container').stop().animate({left: -thePosA}, animSpeed,easeType); //with easing
            }
            else if(mouseCoords<destX){
                //$('#thumbScroller .container').css('left',thePosB); //without easing
                $('#thumbScroller .container').stop().animate({left: thePosB}, animSpeed,easeType); //with easing
            }
        }
    });
    $('#thumbScroller  .thumb').each(function () {
        $(this).fadeTo(fadeSpeed, 0.6);
    });
    var fadeSpeed=200;
    $('#thumbScroller .thumb').hover(
    function(){ //mouse over
        $(this).fadeTo(fadeSpeed, 1);
    },
    function(){ //mouse out
        $(this).fadeTo(fadeSpeed, 0.6);
    }
);
});
$(window).resize(function() {
    //$('#thumbScroller .container').css('left',sliderLeft); //without easing
    $('#thumbScroller .container').stop().animate({left: sliderLeft}, 400,'easeOutCirc'); //with easing
    $('#thumbScroller').css('width',$(window).width());
    sliderWidth=$(window).width();
});

I just remove second function as per suggestion, but still not work
removed few lines and script crash and doesn't display any error
Comment: Crash how? It causes the browser to crash, or it doesn't run at all?
Comment: are all browsers crashing, or any one in particular?
Comment: You can remove `sliderLeft`, it's not being used anywhere in your code.
Comment: thanks badzoke it nothing wrong with script, problem is different thankx for your suggestion
Answer: You have 2 $(window).load(function() {...}); function definitions.
Try combing them into 1 $(window).load(function() {...}); call.
Comment: I just remove second function to find bug and still getting error and getting error on this line  padding=$('#outer_container').css('paddingRight').replace("px", ""); I define outer_container id in css as well as padding-right but still not under stand where am i wrong
Comment: Here is error

TypeError: $(...).css(...) is undefined
[Break On This Error]

    padding=$('#outer_container').css('paddingRight').replace("px", "");

I define outer_container id in css as well as padding-right but still not under stand where am i wrong
Comment: I dont think i getting error in this line , look at the updated script in question and getting unknown error
Comment: Can you put your html, css and javascript into http://jsfiddle.net/? Recreate the problem and share it with us.
Comment: sorry I can't upload html, css and javascript in jsfiddle.net because I am using 6 different javascript for my project.
Comment: Do you have this code running live on the internet somewhere that you can share?
Comment: I found the problem, Actual problem is I am not loading page properly. check this live example I just add simple script in home about page. www.simpleclick.com.au Please note:- I am using third party source code....
Answer: Just an idea...
Hard to say without seeing the problem (as said by 3dgoo try put your code into jsfiddle.net) but Are you sure your code executes when dom is ready ?
It'd explained that the 'alert' you put in your code 'solve' the problem by giving it time to finish loading.
Comment: thankx for replay, you may be right because I am using $(window).load function for above script. Originally I am loading page through ajax so i get www.example.com./#/test url. My friend point me this mistake. so I am going to use trigger() function to call window function. And sorry I can't upload html, css and javascript in jsfiddle.net because I am using 6 different javascript for my project. If you know any good example for trigger() function share with me. thanks
Comment: No example for using trigger() but you can also :
 - test your elements (ex :$('#thumbScroller')) before using them
 - use $(document).ready(function () {...});