VMware workstation: guest OS becomes sluggish after being idle for 12+ hours?

Question: My VM becomes sluggish after a few hours (~12 hours or so) of being idle, there is no impact on the host, just the guest. The guest OS becomes sluggish.
It has lots of RAM, runs on RAID 0, quad core i5 750, everything is defragmented, but the only way I found to keep its responsiveness optimal is to shutdown (dumps the memory) and the start; a restart of the guest OS doesn't dump the memory so I need to be able to do a stop of the VM, and then a start.
Coming from Hyper-V I had to learn VMware and after a few months of fine tunning it I'm quite impressed with how configurable VMware is. This is the only small issue I haven't been able to fix, has anyone encountered this?
[EDIT]
Thanks for pointing out those features Helvik, here are my current settings.
Advanced Default/Default

Gather debugging information: None
Disable memory page trimming: Unchecked
Log virtual machine progress periodically: Unchecked
Enable template mode: Unchecked

Replay section Debugging enabled

Maximum disk: Unlimited
Save the last: Unlimited
Snapshot frequency: Never
Enable VAssert (experimental): Unchecked
Enable Visual Studio debugger (experimental): Checked

I have no snapshots. It does have Visual Studio installed. I see 3 log files were created earlier today (248 KB each). Would you recommended I change some settings?
[2nd EDIT]
Thanks, I have now disabled the Visual Studio debugging feature.
Host

OS: Windows 7 x64
Processor: Intel Core i5 750 (quad core, no hyperthreading)
Mem: 4 GB
Drives: 4x500 GB in RAID 0
1 DVD drive

Guest

OS: Windows 2008 R2
Processor: 1 CPU
Mem: 2 GB
Drives: 1 Drive 18/140 GB used, full disk space is not pre-allocated
1 DVD drive
1 floppy drive
USB controller is present, nothing is using USB on the guest, and only keyboard and mouse are using USB on the host.

So far the things I have done are:

Disable Visual Studio debugging
The DVD drive on the guest was mapped to a DVD drive letter that didn't exist anymore on the host, I now changed it to the correct drive letter.
I have changed this setting from 'some' to 'most' in VMware Workstation's: Preferences>Memory>Allow most virtual machine memory to be swapped. When it was set to 'some', I could see from the task manager on the host, that the VM was using the whole 2 GB it's allowed to use, although Task Manager on the guest showed it was using only 500 MB. Now with this setting set to 'most' Task Manager on the guest shows the VM uses about 500 MB of its 2 GB of RAM, and Task Manager on the guest also matches that.

I will let it run for a good 12 hours and then check the VM's responsiveness.
Comment: ok, I just found the answer to the no GUI question here http://serverfault.com/questions/89029/running-vms-in-a-background-on-vmware-workstation vmrun -T ws start C:\export\vmware\rh5\server.vmx nogui

 I could not find this command line option anywhere, serverfault.com is definetly a great resource.

I will edit my question to expose the idle VM performance issue incase someone else has encountered this. My host is win 7 x64 and the guest 2008 r2 x64
Comment: Do you have VM Logging enabled? Under VM Settings, Options, Advanced what settings are enabled for debugging info, memory page trimming & VM progress logging? Under The Replay section is anything enabled? Do you have any snapshots active?
Comment: Hi, thanks for answering,

Advanced Default/Default
-Gather debugging information: None
-Disable memory page trimming: Unchecked
-Log virtual machine progress periodically: Unchecked
-Enable template mode: Unchecked

Replay section Debugging enabled
-Maximum disk: Unlimited
-Save the last: Unlimited
-Snapshot frequency: Never
-Enable VAssert(experimental): Unchecked
-Enable Visual Studio debugger(experimental): Checked

I have no snapshots. It does have visual studio installed. I see 3 log files were created earlier today(248 KB each). Would you recommended I change some settings?
Comment: You could try disabling the Visual Studio Debugger to see if thats leaking something over an extended period but that's really just a guess, the other settings are OK. Can you post your Guest\Host OS details and the specific config of the VM vs the Host (amount of RAM and number of CPU's, what peripheral devices are configured like USB).
Comment: Thanks Helvick, I have updated the my question with Host vs Guest configuration, and disabled VMWare's visual studio debugging experimental feature. I'll let it run for a good 12-24 hours at idle to see if the changes had a positive effect.
Comment: after letting it run for 24hours, it's still ends up being very slow after being idle for a while, opening Windows Explorer takes 10-15 seconds when it takes only 1 second or less after a fresh boot, only solution i found so far is to schedule a restart of the VM every 4 hours or so of being idle.
Comment: You have to quantify exactly what you mean by "sluggish" and "slow." What's sluggish and slow? Are there any particular things that are slower than others? What do your host OS's performance counters say about its CPU, memory and disk activity?
Answer: If you have enough memory on the host system to comfortably fit all the virtual memory you are allocating to your VM, then you should change the memory preferences to "Fit all virtual machine memory into reserved host RAM"; this will prevent the host O.S. from swapping it out on the assumption that it's not being used.
Setting that option to "Allow most virtual machine memory to be swapped" will actually make things worse.
Comment: And you have to disable memory page trimming.
Answer: If you have VMware Tools installed, it could be this bug:
http://www.boche.net/blog/index.php/2010/03/28/windows-2008-r2-and-windows-7-on-vsphere/
http://kb.vmware.com/selfservice/microsites/search.do?language=en_US&cmd=displayKC&externalId=1011709
The symptoms are similar to what I've seen on ESX.
Comment: the driver that was installed was VMware SVGA 3D (Microsoft Corporation) from oct 17 2009, and i couldn't see the new updated driver that ESX has in common files, (I should upgrade from workstation 7.0.0 to 7.0.1) since the new driver not on my host, so I just uninstalled the current driver and logged in using remote desktop, it seems to work fine for now, i'll let it run for 12-24 hours see if it gets sluggish
Comment: thanks for the input, I will see what can be done with the VGA drivers, but I'm not convinced it would be a VGA problem, the more information the window has to gather, the more it's affected by the slowdown, it's not like graphically complex windows or snap ins are more affected, i'd bet it's I/O(CPU?) that becomes 'constipated', but I'll look into the VGA thing
Answer: If you're saying the VM becomes sluggish and not the host, then troubleshoot the VM as you would if it were physical.  My guess offhand is that it's nothing to do with the host / VMware.  With that being said, since your host is 2008 r2, try firing up the resource monitor and checking out things like disk latency, ram usage, CPU usage, etc.
Answer: in vmware ws, go to Edit > Preferences > Memory tab > Fit All virtual Machine into reserve host ram > OK
Comment: Whilst this may theoretically answer the question, it would be preferable if you described how/why this is an answer. Thank you and welcome to [SF]!
Comment: Worked for me in Workstation 16


Option for auto Masspay in ubercart marketplace

Question: Is there any auto Masspay option in ubercart marketplace module. Now working with manual payment method.
Answer: Automatic mass payment (with paypal only)
Explanation:
When a user makes an order and pays with PayPal or does ExpressCheckout with PayPal and the system redirects him to "checkout/complete" the added code starts to work and makes masspay for all the orders done before that one. (Newest order not included)
Another Method :

Go to Test Accounts, select "Create Account: Preconfigured", Choose
account type "Seller", use given data
Go to API Credentials, copy API Username, Password, and Signature to
Drupal Enable uc_paypal module
Setup PayPal Website Payment Pro settings at: "Store Administration

Configuration >> Payment Settings >> Edit >> Payment Gateways" or directly via /admin/store/settings/payment/edit/gateways

Enable this payment gateway for use API server: Sandbox
Now enter your API credentials
If IPN is setup you may now make payments at "Store administration >>
reports >> Seller reports"


Text mining "power calculations"?

Question: I have a list of 6,500 or so medical treatments, of which I have classified 700 or so as involving a physician or not.  I am interested in both the specific question of how to calculate whether 700 observations is sufficient, and the general question about how one does power calculations in text mining.
A typical treatment might have 3-10 words describing the intervention (e.g. "Coronary artery bypass graft surgery for left main artery disease").  My training dataset adds to that a binary variable indicating whether a physician is involved in the process or not.  I want to predict this binary variable on all the remaining observations.
I can classify more if necessary, but obviously the time and money cost increases to do so.  I am curious how I might know when to stop creating a training dataset.
I assume that a "power calculation" would involve:

Characteristics of the text (number of words per observation, prevalence of sparse words, overlap of the words between each of the binary categories, etc.)
Desired prediction accuracy
Algorithm used

Is there a formal method for this?  I'm using RTextTools if that helps.
Comment: I'm not sure whether you're using the term "power" in the standard statistical sense--namely, the probability of finding an effect statistically significant based on a sample, assuming that effect exists in the larger population. Unless I'm way off, power is always calculated with respect to a particular procedure--*T*-test, logistic regression, etc. Maybe that's what you meant by "algorithm." What procedure are you planning to use?
Comment: I am using power in that sense.  I realized after I wrote this that one generally thinks of power calculations as frequentist, and many ML techniques have Bayesian analogues.  So maybe power calculations don't make any sense in this world and I should just classify a few times and see whether the results are good enough.
Answer: To create a reliable trained classifier in RTextTools, you first compare its accuracy to data that has been manually classified. The create_corpus() function lets you do this by specifying the trainSize, testSize, and then setting the "virgin" flag to FALSE. This indicates that the test data has already been manually classified and is not "virgin" unclassified data, and RTextTools should compare its results against yours.
There are a variety of analytics to see how good your classifier is-- for example, the @ensemble_summary. The n-ensemble recall accuracy score shows you how accurately RTextTools classified the data in the test set. Another analytic is the @algorithm_summary which shows the precision, F-score, recall, and overall accuracy broken down by category.
Randomly sample your training and testing data over several iterations, and if these scores are consistently high you should have a reliable classifier.

Text mining "power calculations"?


About the homology of del Pezzo surfaces

Question: I would like to know what is the second homology of a del Pezzo surface (X), that is blow-ups of $\mathbb{CP}^2$ in up to 9 points, and to be more precise what are the dimensions of the positive and negative definite subspaces. I.e. for the second Betti number $b_2(X)$ what is $b_+(X)$ and $b_{-}(X)$ such that $$b_2(X) = b_+(X) + b_-(X).$$
In other words I want to know the full information of the intersection form $Q$ of these surfaces.
I have tried to find information online and I was not successful in finding it. I would assume that such information are classified or listed somewhere. Any reference would help.
Answer: When you blowup a point on a complex surface, the exceptional divisor is a curve of self-intersection $-1$. Therefore $b_-(\operatorname{Bl}_p(X)) = b_-(X) + 1$. As $\operatorname{Bl}_p(X)$ is diffeomorphic to $X\#\overline{\mathbb{CP}^2}$, we know that $b_2(\operatorname{Bl}_p(X)) = b_2(X) + b_2(\overline{\mathbb{CP}^2}) = b_2(X) + 1$, so we must have $b_+(\operatorname{Bl}_p(X)) = b_+(X)$.
Therefore, if $Y$ is the surface obtained by blowing up $\mathbb{CP}^2$ at $k$ points, then $b_+(Y) = b_+(\mathbb{CP}^2) = 1$ and $b_-(Y) = b_-(\mathbb{CP}^2) + k = k$. It follows that $Y$ has intersection form
$$\begin{bmatrix}1 & 0\\0 & -I_k\end{bmatrix}$$
where $I_k$ is the $k\times k$ identity matrix.
Comment: I know that Huybrechts's book has a proof that the blow up is diffeomorphic to a connected sum with $\overline{\mathbb{CP}^2}$. As for the other parts, I'm not sure.
Comment: thank you very much. This is what I wanted. Would you be kind enough to recommend a reference as well?


Data passing to another application in Android

Question: I have two Android Application(Application A,Application B) as shown in below figure.
I want to call application B by clicking on Button from first Application A and when Application B launches then the text box will contain the text which I want to pass from Application A.
**Note-

I have access of Application A  so I can modify the code of Application A . I have no access to application B.
I have seen many post on Stackoverflow.com and other sites that explain passing data to second application but I saw it is only possible when you have access to modify the code of both class. Here in my case I have no access to Application 2, It is just a APK which is installed on my phone.
I want to just implement like we did in automating a web page through Selenium where we can access a text field and enter value in that text field and .
Application B only for example purpose. It can be any Application having text boxes.
Actually I want to automate the login process of an application(Applicaion B) with the help of Application A .Application A have a number of credential and by selecting a credential from Application A it will launch the Application B and enter the credentioal to Login screen of Application B .
**

Hope I am able to explain my problem.If some more input require I can explain.
Comment: I highly doubt this is possible, unless B _expects_ a value. A cannot modify B's views as it pleases.
Comment: why -1 cant understand. i had +1 i think this is gud question
Comment: Use content provider and Broadcast receiver.
Comment: +1 for question want to know answer.. I think @Bijay Koirala is right not possible with current scenario but want to know experts opinion:)
Answer: You have 2 options:

Application B expects an input (via intent). Then you can launch the app B and pass the value via intent:
intent.putExtra("Key", "Your data here");

You need to know which key the application B uses, otherwise you can't do this.
Application B doesn't expect an input. This is not easy and requieres root-access to the phone:
With the permission INJECT_EVENTS it is possible to type text or send clicks to any window. You can do this:
Instrumentation m_Instrumentation = new Instrumentation();
m_Instrumentation.sendKeyDownUpSync( KeyEvent.KEYCODE_B ); //send key B

you can find more to this topic here. If you need help to compile your app, these 2 links will help you: How to compile Android Application with system permissions, Android INJECT_EVENTS permission
Comment: After going through link provided by you it seems that it is possible. I am able to do it within same application but got stuck in when calling to second appication and Injecting value in that applicaion field.
Answer: Pass the data to the below intent.
And then get it from the other app.
PackageManager pm = context.getPackageManager();
Intent appStartIntent = pm.getLaunchIntentForPackage(appPackageName);
context.startActivity(appStartIntent);

Answer: I don't think this is possible as you do not have any control over the application B.As there are several ways of sending data to application B from A(intent,Content provider and Broadcast recievers etc) but you do not know will B accept those values or not and will manipulate the views according to the data you have sent from A as you have no control over the B.
Answer: i'm just gonna give you a heads up in order for you to pass data between two application which you have control over them, then you should use intent for example
intent.putExtra("MyData", "This is a data ");

and in your other application use this to get this data
    Bundle extras = getIntent().getExtras();
if (extras != null) {
    String value = extras.getString("MyData");
    myText.setText(value);
}

Comment: @SweetWisherツ as you can see he has updated his question, before that he never mentioned anything about it, and as you can see from my answer i purposely stated
i'm just gonna give you a heads up in order for you to pass data **between two application which you have control over them**, then you should use intent for example
Comment: @SweetWisherツ as you can see from his question, he forgot to edit this
**I have two Android Application(Application A,Application B)**  which make it more clearer, so do me a favor and remove your down vote.
Answer: Unless another application has set up an intent to receive another application's value, it can't be done. If you have to do it, reverse engineer B's APK, then add implicit intent to handle forms of data you need and create a newer APK
Answer: If you're trying to write tests or do something in an automated fashion (similar to WebDriver scirpts) you can use MonkeyRunner http://developer.android.com/tools/help/monkeyrunner_concepts.html but that connects remotely to a device over adb from a host computer.
Depending on how application B populates the data in those input fields you may be able to interact with application B's content provider. You'd probably want to communicate with the author of Application B in that case.
Comment: In this case I am not wrtting the test cases but exactly want to do the same through Aoolication A.Please read the point Note:-5 to get more Idea about the same.
Answer: Starting from API 18 there is UiAutomation class, which can send custom events to other applications without need of INJECT_EVENTS permission.
For more information see http://developer.android.com/reference/android/app/Instrumentation.html#getUiAutomation()


Firebase throwing "the server responded with status 400"

Question: I am implementing the CICD for an app which I've done in react native but I've a situation now that the firebase is not letting me upload the ipa and apk "the server responded with status 400". I have used my account for uploading first there it was working perfectly now I am using another account. Now it's not letting me upload it.
This is what I get in the terminal window.
[13:28:30]:  Authenticated successfully.
[13:28:33]: ⌛ Uploading the APK.
[13:28:47]: ✅ Uploaded the APK.
[13:28:48]: the server responded with status 400
+------+---------------------------+-------------+
|                fastlane summary                |
+------+---------------------------+-------------+
| Step | Action                    | Time (in s) |
+------+---------------------------+-------------+
| 1    | clean assembleRelease     | 315         |
|    | firebase_app_distribution | 18          |
+------+---------------------------+-------------+

Comment: Hey did you solve it ?
Answer: 400 means "bad request". And, to be honest, that lacks detail from Fastlane, as it just indicates (retrospectively) the provided configuration is incomplete or incorrect.
Here is an example on what happened here: The reason was a bad app ID copied from the Firebase project (I was trying the encoded app ID, instead of the app ID).
platform :ios do
  desc 'Me App'
  lane :beta do
      build_ios_app(
        export_method: 'ad-hoc',
        export_options: {
        provisioningProfiles: {
            'com.example.meapp' => 'Me App'
          }
        }
      )
      firebase_app_distribution(
          app: 'bad_id',   # The 400 was from a bad ID here.
          testers: 'email@example.com',
          release_notes: release_notes,
      )
  end
end

As of time of writing, I found clues in the error trace from Fastlane. Some Ruby code was throwing the error.
def self.run(params)
  params.values      # <= printing out the `params` showed all pieces that could lead to a 400 Bad Request
  # ...
  app = fad_api_client.get_app(app_id, app_view)

Looking at how it broke helped understand the culprit was the app ID here. Hopefully this would be enough in the OP situation too.
Answer: This could happen for two reasons: the firebase token is not valid, or the firebase distribution service account doesn't have the permission or the role for publishing builds to Firebase.
So try to generate another token, and check Google cloud if you have a service account with the role Firebase App distribution.


Hide node and file paths in view when printing page

Question: I have a views page that lists nodes that contain uploaded PDF and bibtex files (see here). Everything looks fine when you view the page, but when you go to print it in the browser, the node path (from the linked title) and the path to the uploaded files are displayed.  The client would like to be able to print the page without  those paths being shown.  Is there a way to suppress these paths when printing from the browser? I suggested having a link to another print friendly page, but he just wants to be able to print from the browser.
Answer: It sounds like a CSS issue. The most efficient way is to add a CSS to your theme whose media type is print (see below for example).
Assuming the part you want to hide is an element (div, span, etc) whose class is mycustomclass, inside that stylesheet you could add something like this.
.mycustomclass {
  display: none;
  visibility: hidden;
}

And this is the example mentioned above.
<link type="text/css" rel="stylesheet" href="http://www.example.com/sites/all/themes/mytheme/print.css" media="print" />


Where can I find a beginner's guide to using sysprep for deploying Windows 7?

Question: I am new to Windows 7, but want to deploy it in a Netware (read: no Active Directory, no domain, etc.) environment.  I have used Novell Zenworks for imaging and deploying Windows XP in the past, and have never used sysprep because it was never necessary.
Now, I find that Zenworks is unable to image Windows 7 at all.  It appears that there is a bunch of hardware-specific information that breaks the image on all machines except the specific machine it was created on.
I have recently learned what sysprep was, just a few weeks ago.  My question is simple.  Where can I find a step-by-step guide to using sysprep to image and deploy Windows 7?
Edit: I see that my question has been migrated.  Thanks.  I have read the guide that John T provided--then I read the 150+ comments.  It seems that this is becoming out of date.  Is there nothing else that sums up how to use sysprep to prepare Windows 7 for imaging and deployment?
Answer: There's only one decent guide I've come across so far for Windows 7, and that's Brian Lee Jackson's "sysprepping" guide.


Como organizar aplicação multi-nível MVC

Question: Estou desenvolvendo uma aplicação seguindo o padrão MVC, e terá 2 níveis de usuários, o normal e o admin, no que se refere as opções do que cada usuário pode fazer, é melhor fazer uma lógica no controller para mostrar determinada view ou alguma ação de outro controller ou criar alguns "blocos if" numa view padrão para "esconder" menus somente do admin ou vice/versa?

Exemplo de situação:
Um usuário normal acessa a dashboard depois do login, o ideal seria
mostrar uma view (views/user_normal) específica para ele, que só tem os menus/links do seu
nível, ou usar uma view (views/all_users) para ambos os níveis e esconder menus/links
com validações?
Answer: Um controller pode ter N views. Se acha melhor uma view para cada caso (user normal e admin), não tem problema. Mas tanto faz usar uma só view com condicionais ou múltiplas views.
Particularmente prefiro views separadas se houver muitas condicionais.
Há quem prefira um padrão estrito, ou seja, não importa se tem apenas 1 condicional, deve seguir o padrão de múltiplas views.
Quem define o padrão é o gerente do projeto.
Answer: Para fugir de (if/elses) desnecessários pelo controller, eu prefiro fazer da maneira pelo qual você citou:
view/user_normal
view/user_diferenciado
É questão de boas práticas de código, mas nesse caso, pra mim é questão pessoal de quem está desenvolvendo.


Can we recover joint distribution from a continuous range of convolutions?

Question: Given a correct model of the joint distribution of a random vector $(X,Y)$, we can derive (though not necessarily in closed form) the correct distribution model for $pX+(1-p)Y$ for any $p\in[0,1]$.
What about the reverse? Is having correct models for $pX+(1-p)Y$ for any $p\in[0,1]$ sufficient for recovering the joint distribution of a random vector $(X,Y)$? If not, (1) what would be a counterexample and (2) what are some examples of additional conditions needed for that?
Comment: @whuber, interesting! And this transformation seems to have some relevant applications: *The Radon transform is widely applicable to tomography, the creation of an image from the projection data associated with cross-sectional scans of an object.*
Comment: This essentially asks how to invert the [Radon transform](https://en.wikipedia.org/wiki/Radon_transform).
Answer: I am not sure I understand the question, because I don't understand the relation with convolutions. If we assume that $X$ and $Y$ are independent, then $pX+(1-p)Y$ is indeed a convolution, but what if there are not assumed independent? If $X$ and $Y$ are assumed independent, then taking $p=1$ and $p=0$ allows us to recover the law of $X$ and $Y$, and therefore of $(X,Y)$.
If the law of $(X,Y)$ is uniquely determined by its moments (for example if the law of $(X,Y)$ has compact support), then from the knowledge of the law of $pX+(1-p)Y$ for each $p \in [0,1]$, we can recover all the moments $\mathbb{E}[X^nY^m]$ (since the map $p \mapsto \mathbb{E}[(pX+(1-p)Y)^{n+m}]$ is polynomial, and $\mathbb{E}[X^nY^m]$ can be recovered from the coefficients of said polynomial) and we can therefore recover the law of $(X,Y)$.
Following the remark of @whuber, we can also try to recover the characteristic function of $(X,Y)$. Indeed, we have that $\phi_{pX+(1-p)Y}(t) = \phi_{(X,Y)}(tp, t(1-p))$. If we only know the law of $pX +(1-p)Y$ for $p \in [0,1]$, we can recover half of the values (that is, on all pairs $(\lambda_1,\lambda_2)$ that have the same sign) of the characteristic function. If we know the law of $pX + (1-p)Y$ for all $p \in \mathbb{R}$, then we can recover the characteristic function of $(X,Y)$ on all the plane but one line (the line $\{(\lambda, - \lambda) \ \vert \ \lambda \in \mathbb{R}\}$), but by continuity, we can deduce the values of the characteristic function on the missing line.
Comment: Interesting. My instinct was No, since this is a bit like recovering the joint 2d distribution from a set of 1d marginal distributions. But this has persuaded me otherwise
Comment: This is a nice observation and it would be directly connected to the theory of the Radon transform if you were to reframe it in terms of the characteristic function instead of the moments, because the cf always exists.


Does Sampling Frequency matter for Time Series analysis?

Question: I am given two time series of prices between 2009 and 2013. Price series A is weekly data, series B is monthly data. I would like to compare some basic descriptive statistics of these two time series data (such as mean, standard deviation etc).
Intuitively, I just wonder if the period sampling difference should be of any concern.... What could be some potential problems, and if there are ways to reduce the impact....
I guess the other way to put it is that, should I just pick the month-end numbers of series A to match the frequency of series B. I am not sure about this approach because the quality of statistics might be compromised for series A.
Thank you so much!
Comment: How are the weekly data and monthly data computed? Also, what effect does the number of business days in the time period have on the calculation?
Comment: At the *very* least, it's important to recognize and understand the concept of [aliasing](http://en.wikipedia.org/wiki/Aliasing).
Comment: Prices of what?
Answer: The sampling difference is a problem.  To compare apples-to-apples, both series need to be based on the same frequency and timing.   In this case, if Series B is based on the last day of each month, then Series A also needs to be based on the same days.  If you can't get daily data for Series A then you may need to interpolate on the weekly data.
If seasonality is involved, then using weekly data is an even bigger problem.   The main seasonality issue with weekly data is that there aren't 52 weeks in a year.  Using 365 days per year and 7 days a week gives 52.14 weeks per year.  That's not an integer number, which means that when a year ends, the associated week may or may not end.  As result, all calculations have to be modified to reflect that.  Monthly data has exactly 12 months per year.  Each month may not have the same number of days, but that is typically understood for monthly data.
Answer: Choosing between weekly and monthly data is called time binning not sampling. Oversampling has its merits when looking for signals or time series.

In signal processing, oversampling is the process of sampling a signal
  with a sampling frequency significantly higher than the Nyquist rate.
  Theoretically a bandwidth-limited signal can be perfectly
  reconstructed if sampled above the Nyquist rate, which is twice the
  highest frequency in the signal. Oversampling improves resolution,
  reduces noise and helps avoid aliasing and phase distortion by
  relaxing anti-aliasing filter performance requirements.

The Nyqvist rate is essentially the minimum sampling frequency to reconstruct a signal of frequency $1/T$, where $T$ is the period of the signal. So, the minimum sampling frequency would be $F_s = 2/T = 2*B$
In this case, oversampling will be done on a random signal.

If multiple samples are taken of the same quantity with uncorrelated
  noise added to each sample, then averaging N samples reduces the noise
  power by a factor of 1/N.

This means that time binning your data will reduce noise. First, hypothesize how small the signal is then decided whether is better to sample weekly data or monthly.
Source
I am a hobbyist statistician so maybe someone else can give a better answer.


Pegando vários valores de inputs iguais e armazendo num array com Javascript/jQuery

Question:
Eu tenho essa div, que é
, dentro dela tenho <input type='text'> <select></select> <input type='checkbox'> A questão é que essa div inteira pode se repetir caso eu clique em adicionar nova pergunta, ou seja, eu posso tem 1 ou N divs que contenham esses mesmos campos, eu preciso fazer um script em Javascript/jQuery que pegar o valor de cada campo e armazene em um array, por exemplo, eu tenho duas
 com esses campos, preciso adicionar os valores de cada campo em um array por exemplo:
var array = [{titulo: , tipo: , requerido: }, {titulo: , tipo: , requerido: }]

Ou seja, como faço pra adicionar os valores desses campos de cada div em um array?
Answer: Cria um seletor que apanhe todas as
 e depois faz um mapeamento para ir buscar os valores do titulo e tipo.
Um exemplo seria assim:
const arr = $('.pergunta').map(function() {
  return {
    titulo: this.querySelector('input[type="text"]').value,
    tipo: this.querySelector('select').value,
    requerido: this.querySelector('input[type="checkbox"]').checked
  }
}).get();
console.log(arr);

Comment: Funcionou !! O problema é que quando tento enviar esse 'arr' via ajax, método POST, ele está me retornando o seguinte erro: "Uncaught TypeError: Illegal invocation".
Comment: @LeonardoTheodoro, usa `.get()` no final para transformar numa array nativa em vez de coleção jQuery.


Laravel Get Resource Inside Resource with ID?

Question: I am trying to get a report using laravel eloquent but have stumbled on an issue!
Report Goal: get all students the task is assigned too and the progress they have made.
I have a controller setup:
public function show($task) {
    return new TaskStudentProgressStats(Task::findOrFail($task));
}

works fine, then my resources work flow is like the following:

Task(Groups(Students(Progress())))

I get all the data but the progress is not related to the Task, How can I maybe pass the task id to the progress resource?
Or can I call some data from a parent resource?
Student Progress Relationship is the following:
public function studentProgress() {
    return $this->hasMany(ProgressStudentTaskUser::class, 'id', 'student_id');
}

Comment: something like $task->with('progress')->students()->get()
Comment: what are your `progress` model relations?
Comment: @MohamedMelouk the progress model relationship is the following:    `public function studentProgress() {
        return $this->hasMany(ProgressStudentTaskUser::class, 'mis_id', 'mis_id');
    }`
Answer: If the Task model hasMany students and students hasMany prgress
then try this code:
public function show($task) {
    return Task::find($task)->students()->with('progress')->get();
}

this should return all students of this task with there progress
note that this will return all the progress of each student if you want to customize the relation then use:
public function show($task) {
    return Task::find($task)->students()->with([ 'progress' => function($q){
        $q->where('field', 'value');
    } ])->get();
}

to call it in a view you will use:
@foreach ($students as $student)

{{ $student->name }} - {{ $student->progress->name }}

@endforeach

Comment: Thanks, my only issue might be that **Tasks get set too groups not individual students!** then in another table I store which students are assigned to which groups.


How do i calculate the confidence interval of a simple slope?

Question: I have got the following information about variable a:
simple slope of the high level of A = -0.2437579
standard error of the high level of A = 2.197419
t-value for the high level of A = -0.1109292
Mean of A   2.693911
Standard Deviation of a 0.617316
Degrees of freedom is 302
Can someone plz help me and tell me how i can or need to calculate the 95% confidence interval with the aformentioned information?
Answer: Just to be clear you don't know how many samples were used to calculate the slope, correct?
The first thing you need to do it calculate the degrees of freedom of the slope calculation (in simple linear regression this is the number of samples minus 2)
The formula for the t-value for the high level of A is
$t=\frac{A}{s_E\sqrt{df}}$
From your information $A=-0.2437579$, $s_E=2.197419$, $t=-0.1109292$
Therefore
$-0.1109292=\frac{-0.2437579}{2.197419\sqrt{df}}$
Rearranging you get $df=1$ so the slope was calculated from 3 samples.
Now to calculate the confidence interval of $A$ use the t distribution with 1 degree of freedom. I trust you know how to use tables to find a t value. For a two tailed distribution with $df=1$ the t-value for 95% coverage is $12.7$
The 95% confidence interval is $\hat{A}\pm t\times s_E= -0.2437579 \pm 12.7\times 2.197419=[-27.66,28.15]$
The confidence interval is very large because there sample size for the regression was 3.
Comment: Thank you very much!! Sorry I forgot to mention that the degrees of freedom of the slope is 302. Could you plz tell me what the confidence interval is? I want to double check if my outcome is similar to yours.


Unknown warnings in mail.warn log file

Question: still trying to setup (installation and security) my first server and today I found a few strange lines withing my mail.warn log file.
Sep  8 17:41:48 jvps postfix/smtpd[7793]: warning: hostname worker-13.sfj.censys-scanner.com does not resolve to address 220.127.116.11
Sep  8 18:44:10 jvps postfix/smtpd[9990]: warning: hostname zg-0823b-129.stretchoid.com does not resolve to address 22.214.171.124
Sep  8 23:14:54 jvps postfix/submission/smtpd[19438]: warning: hostname zg-0823a-56.stretchoid.com does not resolve to address 22.214.171.124
Sep  9 16:26:00 jvps postfix/smtpd[26250]: warning: hostname 22.214.171.124.broad.cd.sc.dynamic.163data.com.cn does not resolve to address 188.8.131.52
Sep  9 16:26:01 jvps postfix/smtpd[26250]: warning: hostname 188.8.131.52.broad.cd.sc.dynamic.163data.com.cn does not resolve to address 22.214.171.124
Sep  9 19:45:53 jvps postfix/smtpd[1008]: warning: hostname zg-0823a-256.stretchoid.com does not resolve to address 22.214.171.124
Sep  9 23:15:33 jvps postfix/submission/smtpd[8430]: warning: hostname zg-0823b-193.stretchoid.com does not resolve to address 18.104.22.168
Sep 10 10:10:33 jvps postfix/smtpd[1332]: warning: hostname hn.ly.kd.adsl does not resolve to address 220.127.116.11
Sep 10 10:10:34 jvps postfix/smtpd[1332]: warning: hostname hn.ly.kd.adsl does not resolve to address 18.104.22.168
Sep 10 15:09:48 jvps postfix/smtpd[11980]: warning: hostname worker-15.sfj.censys-scanner.com does not resolve to address 22.214.171.124
Sep 10 19:48:41 jvps postfix/smtpd[21725]: warning: hostname zg-0823b-181.stretchoid.com does not resolve to address 188.8.131.52
Sep 10 20:55:58 jvps postfix/submission/smtpd[24052]: warning: hostname zg-0823a-206.stretchoid.com does not resolve to address 188.8.131.52

Cany anyone explain what this could be? Don't know these hostnames or the IP's and I'm a bit lost
Answer: These are hosts that connected to your mail server and identified themselves by a hostname, but that hostname did not have an address record in the DNS that matched the IP address they connected from. The vast majority of these are spam sources, though one of those in your post is a data-collecting bot. On rare occasions this is someone's legitimate but misconfigured mail server; they usually fix it very quickly because virtually everyone will reject their mail or mark it as spam.
The reason they seem completely out of context is due to one of Debian's many questionable design decisions: They chose to separate mail logs by loglevel. Thus, the rest of the logs pertaining to each of these connections are in other files. Debian creates mail.info, mail.warn and mail.err, each of which contains log entries at those loglevels. Fortunately, they also create mail.log, which is complete and contains all log entries. You can search through this log for similar log entries and see the surrounding context. You should also be able to get complete logs from the systemd journal.
Comment: Ah I see,
So if there an entry like this

    Sep 10 10:10:33 jvps postfix/smtpd[1332]: warning: hostname hn.ly.kd.adsl does not resolve to address 188.8.131.52
    Sep 10 10:10:33 jvps postfix/smtpd[1332]: connect from unknown[184.108.40.206]
    Sep 10 10:10:33 jvps postfix/smtpd[1332]: lost connection after CONNECT from unknown[126.96.36.199]

within the mail.log file there is nothing to be worried about, right? They tried to connect, failed and lost connection ... or is this a "real threat"?
Comment: @Moritz They connected and gave up. That's what you should see with all of them. What you should worry about is if one of them is able to deliver an email. But if you haven't changed the default configuration and made it an open relay, then that shouldn't be happening.
Comment: awesome, thank you for your quick response, appreciate it :)

Unknown warnings in mail.warn log file


Efeito Marginal para GLM (logit) com variáveis categóricas.

Question: Tenho a seguinte regressão:
Call:
glm(formula = IN_FIN_REEMB_FIES ~ CO_CATEGORIA_ADMINISTRATIVA +
CO_COR_RACA_ALUNO + IN_RESERVA_VAGAS + IN_RESERVA_ENSINO_PUBLICO +
CO_TURNO_ALUNO + IN_RESERVA_RENDA_FAMILIAR + IN_FIN_NAOREEMB_PROUNI_PARCIAL +
TP_PROCEDE_EDUC_PUBLICA + IN_SEXO_ALUNO + NU_IDADE_ALUNO,
family = binomial, data = nor1)

Deviance Residuals:
Min       1Q   Median       3Q      Max
-1.3535  -0.7779  -0.6651  -0.4668   2.8123

Coefficients:
                                 Estimate Std. Error z value Pr(>|z|)
(Intercept)                    -0.3802707  0.0112696 -33.743  < 2e-16 ***
CO_CATEGORIA_ADMINISTRATIVA5   -0.5030216  0.0063270 -79.504  < 2e-16 ***
CO_COR_RACA_ALUNO1             -0.0452001  0.0081445  -5.550 2.86e-08 ***
CO_COR_RACA_ALUNO2              0.2784830  0.0144464  19.277  < 2e-16 ***
CO_COR_RACA_ALUNO3              0.1527192  0.0067474  22.634  < 2e-16 ***
CO_COR_RACA_ALUNO4              0.2388296  0.0210065  11.369  < 2e-16 ***
CO_COR_RACA_ALUNO5              0.0357580  0.0516736   0.692  0.48894
IN_RESERVA_VAGAS                0.7116092  0.0474497  14.997  < 2e-16 ***
IN_RESERVA_ENSINO_PUBLICO      -3.1344320  0.1919678 -16.328  < 2e-16 ***
CO_TURNO_ALUNO                 -0.0157669  0.0055981  -2.816  0.00486 **
IN_RESERVA_RENDA_FAMILIAR      -9.8526964 14.0635939  -0.701  0.48356
IN_FIN_NAOREEMB_PROUNI_PARCIAL -0.3676032  0.0206161 -17.831  < 2e-16 ***
TP_PROCEDE_EDUC_PUBLICA1        0.1709269  0.0054290  31.484  < 2e-16 ***
IN_SEXO_ALUNO                   0.1497493  0.0055368  27.046  < 2e-16 ***
NU_IDADE_ALUNO                 -0.0328465  0.0003694 -88.911  < 2e-16 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

(Dispersion parameter for binomial family taken to be 1)

Null deviance: 876350  on 808601  degrees of freedom
Residual deviance: 857364  on 808587  degrees of freedom
AIC: 857394

Number of Fisher Scoring iterations: 9

Preciso criar cenários tipo:
CO_COR_RACA_ALUNO=1, TP_PROCEDE_EDUC_PUBLICA1=1, NU_IDADE_ALUNO<30
Os outros parâmetros podem ser pela média mesmo.
Que me retornem a chance (ou probabilidade) de IN_FIN_REEMB_FIES=1 ou 0
Já tentei pelo pacote mfx (que retorna os efeitos marginais) mas ele não aceita.
Alguém tem alguma sugestão?
Comment: Rafaela, você pode clarificar sua pergunta? 1. Você não forneceu os dados para reproduzir a análise. 2. Não está claro o problema de programação que você precisa resolver. 3. Não está claro o que você tentou no pacote mfx nem porque não deu certo.
Answer: Rafael, uma alternativa seria fazer o seguinte.

calcular a probabilidade predita p/ cada um dos indivíduos da sua amostra usando o seu modelo e a função predict.
filtrar na sua amostra apenas os casos do seu cenário de interesse
calcular a média da probabilidade predita no banco de dados filtrado

Como você não disponibilizou um banco de dados, vou utilizar um que aparece neste link.
# ajuste do modelo
mydata <- read.csv("http://www.ats.ucla.edu/stat/data/binary.csv")
mydata$rank <- factor(mydata$rank)
mylogit <- glm(admit ~ gre + gpa + rank, data = mydata, family = "binomial")

Aqui são usados três indices para prever se um aluno será aceito numa graduação (variável admit):

gre: Graduate Record Exam scores
gpa: grade point average
rank: 1 a 4, é o prestígio da instituição de onde provém o aluno

Agora se, por exemplo, você quiser saber a probabilidade de um aluno que vem de uma instituição com rank = 1 e gre > 500 não importando o gpa, pode fazer assim no R:
# prever a probabilidade de resposta
mydata$prediction <- predict(mylogit, type = "response")

# filtrar o banco de dados apenas com os casos do seu cenário
library(dplyr)
aux <- mydata %>% filter(rank == 1, gre > 500)
mean(aux$prediction)
[1] 0.577473

Se quisesse prever p/ quem tem rank = 1 e gre < 500:
aux <- mydata %>% filter(rank == 1, gre < 500)
mean(aux$prediction)
[1] 0.3751226


Find the Derivative of $f(x)=\frac{7}{\sqrt {x}}$ using the definition.

Question: I get that $$\frac{d}{dx}\left(7\times\dfrac{1}{\sqrt{x}}\right)=\frac{d}{dx}(7x^{.5})=\dfrac{7}{2}x^{-.5}$$ is the derivative, but I can't ever use $\lim_{h \to 0} \dfrac{f(x+h)-f(x)}{h}$.
If someone or anyone could go step by step and do the problem, I would be eternally grateful.
Comment: For your information, note that: $$\frac{d}{dx}\left(7\times \frac{1}{\sqrt{x}}\right)=\frac{d}{dx}\left(7x^{\color{red}{-0.5}}\right)$$ So that is why the answers below are giving different answers to the one you've evaluated without first principles.
Answer: $$\begin{align}f'(x)&=\lim_{h\to0}\frac{f(x+h)-f(x)}{h}\\
&=\lim_{h\to0}\frac{\frac{7}{\sqrt{x+h}}-\frac{7}{\sqrt x}}{h}\\
&=\lim_{h\to0}\frac{7\sqrt x-7\sqrt{x+h}}{h\sqrt{x(x+h)}}\\
&=7\lim_{h\to0}\frac{\sqrt x-\sqrt{x+h}}{h\sqrt{x(x+h)}}\cdot\frac{\sqrt{x}+\sqrt{x+h}}{\sqrt{x}+\sqrt{x+h}}\\
&=7\lim_{h\to0}\frac{-h}{h\sqrt{x(x+h)}(\sqrt{x}+\sqrt{x+h})}\\
&=7\lim_{h\to0}\frac{-1}{\sqrt{x(x+h)}(\sqrt{x}+\sqrt{x+h})}\\
&=-\frac{7}{2x^\frac{3}{2}}\end{align}$$
Answer: $$\begin{align*}f'(x)&=\lim_{h\to0}\frac{f(x+h)-f(x)}{h}\\
&= \lim_{h\to 0} \frac7h\cdot \left( \frac1{\sqrt{x+h}} -\frac1{\sqrt{x}} \right)\\
&= \lim_{h\to 0} \frac7h\cdot\left(\frac{\sqrt x-\sqrt{x+h}}{\sqrt{x(x+h)}} \right)\\
&= \lim_{h\to 0} \frac7h\cdot\left(\frac{\sqrt x-\sqrt{x+h}}{\sqrt{x(x+h)}} \cdot \frac{\sqrt{x}+\sqrt{x+h}}{\sqrt{x}+\sqrt{x+h}} \right)\\
&= \lim_{h\to 0} \frac7h\cdot\left(\frac{x-(x+h)}{\sqrt{x(x+h)}\cdot\left(\sqrt{x+h}+\sqrt x\right)}\right)\\
&=\lim_{h\to 0}\frac{-7}{\sqrt{x(x+h)}\cdot\left(\sqrt{x+h}+\sqrt x\right)}\\
&=\frac{-7}{x\cdot 2\sqrt x}
\end{align*}$$
Answer: \begin{align*}
\dfrac{\frac{7}{\sqrt{x+h}} - \frac{7}{\sqrt{x}}}{h} &= 7\left(\dfrac{\sqrt x - \sqrt{x+h}}{h\sqrt{x(x+h)}}\right) \\
&= 7\left(\dfrac{\sqrt x - \sqrt{x+h}}{h\sqrt{x(x+h)}}\right)\left(\dfrac{\sqrt x + \sqrt{x+h}}{\sqrt x + \sqrt{x+h}}\right) \\
&= 7\left(\dfrac{x-(x+h)}{h\sqrt{x(x+h)}}\right)\left(\dfrac{1}{\sqrt x + \sqrt{x+h}}\right) \\
&= 7\left(\dfrac{-h}{h\sqrt{x(x+h)}}\right)\left(\dfrac{1}{\sqrt x + \sqrt{x+h}}\right) \\
&= 7\left(\dfrac{-1}{\sqrt{x(x+h)}}\right)\left(\dfrac{1}{\sqrt x + \sqrt{x+h}}\right) \\
\end{align*}
Therefore,
$$\lim_{h \to 0}\dfrac{\frac{7}{\sqrt{x+h}} - \frac{7}{\sqrt{x}}}{h} = \lim_{h \to 0} 7\left(\dfrac{-1}{\sqrt{x(x+h)}}\right)\left(\dfrac{1}{\sqrt x + \sqrt{x+h}}\right) = \frac{-7}{2|x|\sqrt x} = \frac{-7}{2x^{3/2}}$$
Answer: $$f(x)=\dfrac{7}{\sqrt{x}}\\f'(x)=\lim\limits_{h \to0}\dfrac{f(x+h)-f(x)}{h}\\f'(x)=\lim\limits_{h \to0}\dfrac{\frac{7}{\sqrt{x+h}}-\frac{7}{\sqrt{x}}}{h}\\f'(x)=\lim\limits_{h \to0}\dfrac{\bigg(\frac{7}{\sqrt{x+h}}-\frac{7}{\sqrt{x}}\bigg)\bigg(\frac{7}{\sqrt{x+h}}+\frac{7}{\sqrt{x}}\bigg)}{h\bigg(\frac{7}{\sqrt{x+h}}+\frac{7}{\sqrt{x}}\bigg)}\\f'(x)=\lim\limits_{h \to0}\dfrac{\frac{49}{x+h}-\frac{7}{\sqrt{x}}}{h\bigg(\frac{7}{\sqrt{x+h}}+\frac{7}{\sqrt{x}}\bigg)}\\f'(x)=\lim\limits_{h \to0}\dfrac{49x-49x-49h}{h\bigg(\frac{7}{\sqrt{x+h}}+\frac{7}{\sqrt{x}}\bigg)(x(x+h))}\\f'(x)=\lim\limits_{h \to0}\dfrac{-49}{\bigg(\frac{7}{\sqrt{x+h}}+\frac{7}{\sqrt{x}}\bigg)(x(x+h))}\\f'(x)=\dfrac{-49}{(\frac{14}{\sqrt{x}})x^2}\\f'(x)=\dfrac{-7}{2x^{\frac{3}{2}}}\\f'(x)=-\dfrac{7}{2}x^{-\frac{3}{2}}$$
Answer:
Hint:

Use binomial series expansion of $(x+h)^{\frac{-1}{2}}$
Comment: I promise you the OP does not have series methods at their disposal yet.
Comment: @AlfredYerger Ok i got it..


Cannot Access Web Interface on HP 2510G

Question: I am currently setting up a new infrastructure with HP 2510s as edge switches and an HP E5406 as the main switch.  I also have a DHCP and DNS server running on the same network.
When i first set up one of my 2510 switches, I gave it a static IP through the console and then went to the web interface to continue my configuration.  Later, I realized that I assigned it the wrong IP address, so i went through the web interface and changed the IP address to the correct one.
Now, I can't access the web interface.  I can telnet to the switch on the new IP address, but the web interface will not load.  If I switch from static IP to DHCP, it loads the web interface.  Any ideas on what could be causing the web server in the 2510 not to load with the new static IP address?
Comment: What firmware (`show ver`)? I assume you've power cycled it? Do you have an vlans defined?
Comment: I've got 25010Gs and had problems with T.11.16 that HP still hasn't resolved. I ended up [reverting to Y.11.12](https://h10145.www1.hp.com/downloads/SoftwareReleases.aspx?ProductNumber=J9280A⟨=en&cc=us&prodSeriesID=3356807).
Comment: I'm running Y.11.16.  I never actually power cycled the switch, but I have reboot it a bunch through the console.
Comment: Well, i powered cycled the switch and now everything is working.  Thanks for the suggestion.
Answer: You may need to powercycle for it to take the new settings into effect for all the management interfaces.
Answer: This is a known bug in the firmware. Just go back to the old version.

Cannot Access Web Interface on HP 2510G


Where does postfix store messages awaiting relay?

Question: If I specify a relayhost in main.cf, in what path (by default) does postfix store that message before and during the process of relaying it on to the next server? And is there a parameter that allows that path (or paths) to be customized?
Answer: Postfix will store mails waiting to be sent in the queue_directory.
See postconf for the current value.
Answer: I am guessing it is /var/spool/mail/$USER somewhere.
Comment: Not for a relay.


Python singleton design pattern - static method vs class method appraoch

Question: Foll. is a sample singleton design pattern implementation using static method. My question is - what difference would it have made if we use class method instead of static method?
<code>class Singleton:
   __instance = None
   @staticmethod
   def getInstance():
      """ Static access method. """
      if Singleton.__instance == None:
         Singleton()
      return Singleton.__instance
   def __init__(self):
      """ Virtually private constructor. """
      if Singleton.__instance != None:
         raise Exception("This class is a singleton!")
      else:
         Singleton.__instance = self
s = Singleton()
print s

s = Singleton.getInstance()
print s

s = Singleton.getInstance()
print s
</code>
Comment: you better create single instance using `__new__` method
Comment: If you use clsmethod, then you don't need to type `Singleton` on each line, just replace it with `cls`. Since classmethod accepts `cls` as first argument
Comment: https://stackoverflow.com/questions/136097/what-is-the-difference-between-staticmethod-and-classmethod
Answer: In Singleton Design Pattern we create only one instance of a class that is implemented in the above implementation.
We should use the static method here because the static method will have the following benefits:
A class method can access or modify class state while a static method can't access or modify it and we don't want to modify anything here we just want to return the singleton instance.
In general, static methods know nothing about the class state. They are utility type methods that take some parameters and work upon those parameters. On the other hand class methods must have class as a parameter.
Comment: Static method can access and modify the class state using the ClassName


Ordenando valores por ponteiros

Question: Boas, estava fazendo um exercicio que pedia para ler 3 numeros reais, ordena-los e mostrar de modo ordenado. Pensei que fazendo uma função que usa-se ponteiros seria uma boa ideia, mas o programa sempre retorna os valor sem ordem. Testei com "10.0 7.0 20.0", "10.0 20.0 7.0".
Queria saber se errei no uso dos ponteiros ou meu erro está na lógica.
Segue o código:
#include<stdio.h>

void _sort (float *x, float *y, float *z);
int main (){
    void _sort (float *x, float *y, float *z);
    float a, b, c;
    scanf("%f %f %f", &a, &b, &c);

    _sort (&a, &b, &c);

    printf("%.1f \n%.1f \n%.1f", a, b, c);
}
void _sort (float* x, float* y, float* z){
    float temp;
    if (x < y){
        temp = *x;
        *x = *y;
        *y = temp;
    }
    if (y < z){
        temp = *y;
        *y = *z;
        *z = temp;
    }
    if ((x < y) && (y < z))
        _sort (x, y, z);
}

Agradeço desde já.
Answer: O erro está nas duas coisas. O erro dos ponteiros está nos IFs, faltou usar o asterisco:
if (*x < *y)
if (*y < *z)
if(*x < *y) && (*y < *z)

O erro de lógica está na forma expressão da chamada recursiva. Dá uma olhadinha e se você não conseguir eu altero depois.
A lógica estava quase certa, mas no lugar do && vc deveria usar ||:
   if(*x < *y || *y < *z)

Comment: Opa, valeu mesmo. Não sei porque, mas pensava que podia comparar sem os asteriscos. Na parte da recursividade tinha tentado colacar '&x, &y, &z' ou colocar '*x, *y, *z' e tomava error de "incompatible type for argument", acho que faltava o "return", mas isso não retornou o que esperava, vou precisar estudar um pouco mais de recursividade.
Comment: poder pode, mas vai comparar o endereço dos ponteiros, não os valores
Comment: Quanto a recursividade, alterando o ultimo condiciona `if ((x < y) && (y < z)) {_sort (x, y, z);}` para ` if (*x < *y) {  _sort(x,y,z);}` o algoritmo funciona
Answer:
"Queria saber se errei no uso dos ponteiros ou meu erro está na lógica".

Certamente no uso dos ponteiros, ou no não-uso nas comparações. E a lógica ainda não entendi. Pode estar até certo mas é incrivelmente complicado.
E errou ao não testar o retorno de scanf(). Não há propósito em seguir se não leu os 3 valores.
Trata-se apenas de classificar 3 elementos. Isso envolve 3 comparações. Então não entendo porque usar recursão ao invés de escrever apenas isso
exemplo

void _sort (float* x, float* y, float* z)
{
    float temp;
    if( *x > *y )
    {
        temp = *x;
        *x = *y;
        *y = temp;
    };
    if( *y > *z )
    {
        temp = *y;
        *y = *z;
        *z = temp;
    };
    if( *x > *y )
    {
        temp = *x;
        *x = *y;
        *y = temp;
    };
    return;
};  // _sort()

eu acho que já serviria. O bubble sort sem loop. Duas comparações deixam o maior valor em z. Uma comparação depois leva o menor para x. E retorna.
PS C:\src\ifdef> gcc -o tsort3 -Wall -std=c17 tsort3.c
PS C:\src\ifdef> ./tsort3
PS C:\src\ifdef> ./tsort3
Entre com 3 valores [numeros reais] : 1 2 3
Em ordem crescente: 1.0 2.0 3.0
PS C:\src\ifdef> ./tsort3
Entre com 3 valores [numeros reais] : 3 2 1
Em ordem crescente: 1.0 2.0 3.0
PS C:\src\ifdef> ./tsort3
Entre com 3 valores [numeros reais] : 1 3 2
Em ordem crescente: 1.0 2.0 3.0
PS C:\src\ifdef> ./tsort3
Entre com 3 valores [numeros reais] : -3.1 -3.22 -3.333
Em ordem crescente: -3.3 -3.2 -3.1
PS C:\src\ifdef>

é a saída desse programa
#include<stdio.h>

void _sort (float*,float*,float*);

int main (void)
{
    void _sort (float *x, float *y, float *z);
    float a, b, c;
    printf("Entre com 3 valores [numeros reais] : ");
    int res = scanf("%f %f %f", &a, &b, &c);
    if (res != 3) return -1;
    _sort (&a, &b, &c);
    printf("Em ordem crescente: %.1f %.1f %.1f", a, b, c);
    return 0;
};

void _sort (float* x, float* y, float* z)
{
    float temp;
    if( *x > *y )
    {
        temp = *x;
        *x = *y;
        *y = temp;
    };
    if( *y > *z )
    {
        temp = *y;
        *y = *z;
        *z = temp;
    };
    if( *x > *y )
    {
        temp = *x;
        *x = *y;
        *y = temp;
    };
    return;
};  // _sort()

Entendi, obrigado. Nunca tinha pensado em testar o retorno do scanf, mas parece uma excelente prática. Só uma curiosidade, o return -1; serve para retornar para algum ponto?

se usar scanf() teste o retorno. Simples assim. É muito ingênuo deixar o programa seguir sem saber se leu o que pretendia. E scanf() não foi escrita para isso que está fazendo: ler do teclado. scanf() foi escrita para ler entrada formatada. Veja o nome: scanf formatted input. O teclado é free-form: 105 teclas de liberdade, ou mais.
retornar -1, ou qualquer coisa diferente serve para você saber por onde foi que seu programa saiu, quando tem um programa simples e não quer ficar tratando as possíveis 400 condições de erro com 400 mensagens bonitinhas. Você vai retornando -1, -2, -3, 4000, 5000, qualquer coisa. E quando o programa termina você vai lá e vê qual o código de retorno e sabe por onde ele saiu. Preguiça apenas.

"Por mais que tenha tentado colocar mais ou menos que 3 valores, o
sistema ou ficava em pronto esperando os valores restantes ou apenas
computava os 3 primeiro"

talvez o mais que usou não seja suficiente. :) com 3 especificadores scanf() pode retornar -1, 0, 1, 2 ou 3. -1 vai indicar um erro e vai ser difícil com o teclado. Se passar mais de 3 valores na entrada os restantes vão claro ficar no buffer de entrada à disposição do programa.  NUNCA vai retornar mais que o número de especificadores porque não faria sentido.
scanf() tem uma missão. No programa
int res = scanf("%f %f %f", &a, &b, &c);

Então há 3 %f e a função vai consumir a entrada até ler isso. Só que tem regras. Espaços, TABS e newlines serão consumidos silenciosamente. Ao ler o que foi pedido a função retorna. Não é possível retornar mais do que 3.
Considere esse código
    printf("Entre com 3 valores [numeros reais] : ");
    int res = scanf("%f %f %f", &a, &b, &c);
    if (res != 3)
    {
        switch(res)
        {
            case  1: return -1;
            case  2: return -2;
            case  0: return -3;
            default:
                return -4; // so pode ser -1
        }   // switch()
    };  // if()

Então:

se o programa não ler nadinha vai retornar -3
se ler um valor retorna -1
se ler dois valores retorna  -2
se der erro scanf() retorna -1 e o switch() vai retornar -4. quando dá erro você pode testar o valor de errorno no programa e usar perror() para mostrar a razão do erro, num programa sério. Aqui a única razão provável de erro é fim de arquivo, o que acontece se você teclar control-Z na leitura.

De todo modo no Mac/Linux você testa $? depois de rodar o programa e tem o código de erro.
No Windows é mais chato: na console você testa %ERRORLEVEL% mas no Terminal do Windows ou no PowerShell é diferente... No PS você roda como no Linux echo $?
mas vem True se o último programa terminou OK e False se deu erro. Dar erro quer dizer não retornar zero. Em C tem a constante EXIT_SUCCESS e a irmã EXIT_FAILURE justamente reservadas para isso. É uma convenção silenciosa.
E se deu erro você pode ver em $LASTEXITCODE qual foi o valor de retorno. Não me culpe. Também odiei isso.
uma _sort() recursiva
Algoritmos de sort como o MergeSort o HeapSort e o QuickSort tem mais sentido em serem implementados via recursão. De todo modo
 void _sortR (float* x, float* y, float* z)
{
    float temp;
    if( *x > *y )
    {
        temp = *x;
        *x = *y;
        *y = temp;
        _sortR( x,y,z );
    };
    if( *y > *z )
    {
        temp = *y;
        *y = *z;
        *z = temp;
        _sortR( x,y,z );
    };
    if( *x > *y )
    {
        temp = *x;
        *x = *y;
        *y = temp;
        _sortR( x,y,z );
    };
    return;
};  // _sort()

Essa versão de _sort() é recursiva, se queria ver um exemplo.
um teste de scanf() no windows
C:\src\ifdef>gcc -o tsort3 -Wall -std=c17 tsort3.c

C:\src\ifdef>tsort3
Entre com 3 valores [numeros reais] : 1 2 3
Em ordem crescente: 1.0 2.0 3.0
C:\src\ifdef>tsort3
Entre com 3 valores [numeros reais] : 3 2 1
Em ordem crescente: 1.0 2.0 3.0
C:\src\ifdef>tsort3
Entre com 3 valores [numeros reais] : ^Z

C:\src\ifdef>echo %ERRORLEVEL%
-4

C:\src\ifdef>tsort3
Entre com 3 valores [numeros reais] : 1x

C:\src\ifdef>echo %ERRORLEVEL%
-1

C:\src\ifdef>tsort3
Entre com 3 valores [numeros reais] : 1 2asda

C:\src\ifdef>echo %ERRORLEVEL%
-2

C:\src\ifdef>tsort3
Entre com 3 valores [numeros reais] : fim

C:\src\ifdef>echo %ERRORLEVEL%
-3

C:\src\ifdef>

Comment: Vlw, não sei o que dizer quanto a lógica estar complicada, rascunhei primeiro no papel e me pareceu aceitavel. Quanto ao uso de ponteiro e recursão, usei para praticar, já que recursão é uma pedra no meu sapato. Entendi que o uso das três condicionais no '_sort', parece bem mais compreensível mesmo.
Comment: Teste o retorno de `scanf()`. Se quer usar recursão aqui entenda que recursão é apenas um loop mais lento e sem contexto. Então eis o que pode fazer: em _sort() continue chamando _sort até não fazer nenhuma troca. Se quiser um exemplo escreva e te mostro um. Mas recomendo você tentar... Pode usar a mesma função que te mostrei
Comment: Entendi, obrigado. Nunca tinha pensado em testar o retorno do scanf, mas parece uma excelente prática. Só uma curiosidade, o return -1; serve para retornar para algum ponto? Por mais que tenha tentado colocar mais ou menos que 3 valores, o sistema ou ficava em pronto esperando os valores restantes ou apenas computava os 3 primeiro.
Comment: retornar -1 é usado para você poder saber de onde o programa retornou quando dá erro. Em geral em programas assim de estudo simples não se trata todos os erros e dá mensagens explicando 300 condições que tem deveriam acontecer. Então você vai retornando -1, -2, -n. E na linha de comando você pode usar echo %ERRORLEVEL% no Windows ou echo $? no Mac/Linux e vai mostrar -1. -2, n. Assim você sabe onde o programa parou...
Comment: ok ok vou editar a resposta e explicar como funciona...

Ordenando valores por ponteiros


What is wrong with this argument: Range Space?

Question: Suppose we are in 2D and $\lambda$ is an eigenvalue associated with eigenvector $e_v$ for some transformation surjective $T$
Define: $U=\operatorname{range}(T-\lambda I) $
I want understand what the range space here. $U$ must have dimension less than 2, particularly dimension 1, as the null space is the eigenvector space which is given above.
Suppose the eigenvector space related to this $\lambda$ is $\operatorname{span}\{(1,1)\}$.
So everything except $\operatorname{span}\{(1,1)\}$ must be in $U$.
Therefore $\operatorname{span}\{(1,2)\}$ and $\operatorname{span}\{(1,3)\}$ must be in $U$.
But notice that $\operatorname{span}\{(1,2)\}$ and $\operatorname{span}\{(1,3)\}$ are linearly independent.
Thus $U$ has two linearly independant vectors.
Thus $U$ has at least dimension 2. This contradicts the statement that $U$ has dimension less than 2.
What is wrong with this argument? Or is it right?
Answer: There is no reason why "everything except $\operatorname{span}\{(1,1)\}$ is in $U$".  In fact it is false.
Simple example:
$$T=\begin{pmatrix}0&1\\1&0\end{pmatrix}$$
Then for $\lambda=1$,
$$
T-I=\begin{pmatrix}-1&1\\1&-1\end{pmatrix}
$$
and so $U=\operatorname{span}\{(1,-1)\}$ does not contain $(1,2)$ or $(1,3)$, for example.
Another example, $T$ is not self-adjoint:
$$
T=\begin{pmatrix}1&1\\0&2\end{pmatrix}
$$
and you can check eigenvector $(1,1)$ with eigenvalue $\lambda=2$.  We have
$$
T-2I=\begin{pmatrix}-1&1\\0&0\end{pmatrix}
$$
so $U=\operatorname{span}\{(1,0)\}$, again does not contain $(1,2)$ or $(1,3)$.
Comment: In your second example, if (1,1) is in the null space of T-2I, then shouldnt everything else be in its range space? or is that not how range spaces work?
Comment: No, that is not how range spaces work.  Range space looks at where everything get sent to, not sent from.
Answer: Just taking your argument, we can show that both $a=(1,2)$ and $b=(1,3)$ cannot be in $U$. Say they were in $U$, then $U$ being a subspace must be closed under vector operations. This means $a-b=(0,-1) \in U$. But then $(1,2)+(0,-1)=(1,1) \in U$ as well. This is a contradiction by your own reasoning that $(1,1) \not\in U$.

Further addition to answer your query in the comment:
Let $S=T-\lambda I$, we want to know the range of $S$ provided we know that the null space of $S$ is spanned by $u=\begin{bmatrix}1\\1\end{bmatrix}$. Let the matrix representation of $S$ be $\begin{bmatrix}a&b\\c&d\end{bmatrix}$. Then with $Su=0$, we get
$$S=\begin{bmatrix}a&-a\\c&-c\end{bmatrix}.$$
Recall range of $S$ is just the span of the columns of $S$. So without any more information the best we can say is that

If $a=c=0$, then the range is just $\left\{\begin{bmatrix}0\\0\end{bmatrix}\right\}$.
If either of them is non-zero, say $a \neq 0$, then the
range is $1$ dimensional and is spanned by the vector $\begin{bmatrix}a\\c\end{bmatrix}$.
Comment: Thanks. So then what is in U exactly? How can we determine its contents only knowing span{(1,1)} is the null space? I thought the range space automatically consists of all vectors not in the null space.
Comment: @RahulDeora are you familiar with rank-nullity theorem? based on that one can say $\text{dim (range)} T +\text{dim (nullspace)} T=\text{dim (domain space)}$. With this, one can easily see if we are in $\Bbb{R}^2$ and null space is of dimension one then the range space can only be $1-$dimensional. Hence it cannot contain everything that is NOT in the null space.
Comment: @RahulDeora I have added a bit more to my answer to help you with the problem.


Suppose $\lim \sup_{n \to \infty}a_n \le \rho$. Show $\lim \sup_{n \to \infty} a_n^{{(n-m)}/{n}} \le \rho$.

Question: Suppose that $\{a_n\}$ is a sequence of positive numbers with $\lim \sup_{n \to \infty} a_n\le \rho$. Show $\lim \sup_{n \to \infty} a_n^{{(n-m)}/{n}} \le \rho$, where $m \in \Bbb N$.
I was thinking about doing something along the lines of
$\lim \sup_{n \to \infty} a_n^{{(n-m)}/{n}}=\lim \sup_{n \to \infty}a_n (a_n^{-m})^{\frac {1}n}$
Then proving that $(a_n^{-m})^{\frac {1}n}$ goes to $1$ as you take the limit supremum. Please let me know if I am completely off base with this logic.
EDIT:
$$(a_n^{-m})^{\frac {1}n} = \frac 1 {\underbrace{a_n^{1/n} \cdots a_n^{1/n}}_{m \text{ times}}}$$
Because $a_n^{1/n}$ converges to 1, $\lim_{n \to \infty} a_n^{1/n} =  \lim \sup_{n \to \infty} a_n^{1/n}=1$.
Thus, $\lim \sup_{n \to \infty} a_n^{{(n-m)}/{n}}=\lim \sup_{n \to \infty} a_n\le \rho $.
Is this correct? If not, where did I mess up? If so, this is not the most elegant solution, is there a better one?
Comment: Do you mean $\limsup_{n\to\infty} a_n\leq \rho$? And say what $m$ is.
Comment: Fixed. Sorry about that.
Comment: Please see edit.
Comment: It's fine except you have to consider the possible n for which $a_n \leq 0$
Comment: $a_n$ is a sequence of positive numbers. See question statement.
Answer: The problem is that $(a^{-m}_n)^{\frac 1n}$ might not be even bounded. An example is that $a_n = \frac{1}{n^{\frac{n}{m}}}$. In this case we have $(a^{-m}_n)^{\frac 1n} = n$. This observation suggests that one should not break the term into two.
Indeed, the claim can be proved directly. Let $\epsilon >0$. Then there is $N_1 \in \mathbb N$ so that
$$ a_n < \rho +\epsilon$$
whenever $n\ge N_1$. Then
$$ a_n^{\frac{n-m}{n}} <\left(\rho +\epsilon \right)^{\frac{n-m}{n}}. $$
when $n\ge N_1$. This implies
$$\limsup_{n\to \infty} a_n^{\frac{n-m}{n}}  \le \limsup_{n\to \infty}\left(\rho +\epsilon \right)^{\frac{n-m}{n}} = \rho +\epsilon$$
(of course we used that $x\mapsto (\rho+\epsilon)^x$ is continuous when $\rho+ \epsilon >0$). As $\epsilon >0$ is arbitrary, we have
$$\limsup_{n\to \infty} a_n^{\frac{n-m}{n}}  \le  \rho. $$


Simple way to extend server disk capacities

Question: What's the least cumbersome way to extend existing server's storage capabilities?
I have a SuperMicro custom server and a Dell PowerEdge 2950 and I would like to extend their storage with budget hard drives, not the server ones.
I'm looking for something like a JBOD chassis (12+ 3.5") that can be connected directly to the server via some kind of controller/extension card - and then be just in /dev ready for LVM/Raid.
Comment: Is this for a long-term or short-term solution?
Comment: Long-term, but not mission critical, academic experiments on big data.
Answer: The simplest way is probably to buy a cheap NAS and to then stick the harddisks in there. Mid-range NAS devices will typically allow you to export their hard disks as iSCSI nodes, so you could then use them directly on your server. This might put quite a bit of strain on your network load, however.
Alternatively, stick in a PCI-E storage controller with external connectors in there and just hook up SATA hard disks externally.
Answer: Server systems should not use disk storage in any non-redundant fashion - not for the OS, not for anything.
JBOD itself is a huge no-no in server environments, as it offers no redundancy whatsoever.
Instead, you could invest in a proper HBA such as a card with an LSI SAS2008 or better - this offers 2 mini-SAS 6Gbs connectors (4 lanes each), and allows you to connect 8 SAS or SATA drives directly, or one or two SAS expanders in an external chassis.
These can then be RAIDed using md or lvm2 into RAID-10 and/or RAID-6 arrays.
A basic HP SAS expander allows a further 24 or 28 drives to be connected; presumably, this will suffice for the near future.
It all depends on your requirements - OS, storage space, transfer and access speed.
Comment: Thanks, seems good. Don't worry - my terminology might be inaccurate. As I wrote in OP, I have LVM and md. JBOD was meant literally to host bunch of disks, not as logical layer.
Answer: While there's lots of smaller enclosures about (1-5 drives) I've not seen anything big enough for 12 drives. And since you probably want the disks in caddies, I'd go with a large PC case (or 2) and several esata connectors.
A quick google turned up this, this and this, if you hunt around there are probably cheaper cases about. Or you could use a more convenitonal case and disk bay doublers like this. The problem with this approach is that you're going to need a cable for each HD (I believe that there are esata multiplexers availalbe - but they're very commonplace outside of dedicated enclosures).
It might be a better idea to stick in a motherboard, OS, 10Gb ethernet and hook up the drives as an iSCSI target (don't route this through your existing network - use a direct connection / dedicated NIC or 2 in the server).
(NB I'm not recommending these specific products just giving you an idea of what's involved).
Comment: Thanks for idea with iSCSI, for case I'm considering something like [this](http://www.supermicro.nl/products/chassis/3U/?chs=936)
with some kind of SATA backplane conencted via some robus interface to SATA expander in the main server. Wanted to avoid buying MB/CPU/MEMORY
Comment: what is 'some robust interface'? While there are SATA cards supporting 24+ drives, they get very expensive very quickly - and they don't come with lots of external ports meaning that you start using up expansion slots for adapter plates - sata still requires one cable per disk. Find your hardware, do the sums, multiplexing across iSCSI looks a lot cheaper and less complicated to me. But if you disagree (or even if you don't) I'd be interested to see what you chose.
Comment: These links might be useful: http://www.openfiler.com http://blog.backblaze.com/2009/09/01/petabytes-on-a-budget-how-to-build-cheap-cloud-storage/


Eager loading not working in EF 6

Question: I am having a method that returns me a list of employees.
public Employee GetAdminTypeAndPermission(int userID)
{
    using (var unitOfWork = new EFUnitOfWork())
    {
        var employeeRepo =
            new EmployeeRepository(new EFRepository<Employee>(), unitOfWork);

        DbSet<Employee> employeeObjSet =
            ((EmployeeEntities)employeeRepo.Repository.UnitOfWork.Context).Employees;

        return employeeObjSet.Where(emp => emp.FK_UserID == userID).
            Include("AdminType.Permissions").FirstOrDefault();
    }
}

In another method I am trying to use like,
var employee= GetAdminTypeAndPermission(loginInfo.UserID);
var permission = employee.AdminType.Permissions.FirstOrDefault();

I am getting an error at the following line:
var permission = employee.AdminType.Permissions.FirstOrDefault();

The ObjectContext instance has been disposed and can no longer be used
  for operations that require a connection.
   I understand the Context object disposes after the end of using block but I am using Eager loading to access the Navigation properties and I should get the result set.

Please help me in understanding what mistake I am doing here and how should I correct.
Any help is highly appreciated.
Thanks in advance.
Comment: Can you post the internals of `employee.AdminType.Permissions`. How is `Permissions` retrieved behind the scenes?
Answer: You have your DbContext in a using statement:
using (var unitOfWork = new EFUnitOfWork())

Once you get out of this using statement, your connection to the database is effectively closed. Either:

Query the information you need while inside your function (and inside your using statement) or
Pass in the DbContext to the method so you can continue to use it:
using (var unitOfWork = new EFUnitOfWork())
{
    var employee= GetAdminTypeAndPermission(loginInfo.UserID, unitOfWork); //DbContext passed in
    var permission = employee.AdminType.Permissions.FirstOrDefault();
}

Comment: It may actually be employeeRepo in this case (the use looks a little odd to me) but the reason should still be the same.
Comment: He is trying to eager load it. It does not matter if the ctx is disposed. If the related navigation collection/entity is eager loaded it does not get a lazy load reference and does not need a "live" DbContext. But what you've done here should solve the problem because you're explicitly saving the value into a local var. It's OK if it's suitable for him as the proper solution. Agreed on passing the DbContext reference for later use.
Comment: Its the FirstOrDefault that causes the Eager loading, which still needs to be done in the context. Alternative could involve an include to pull it all in a single query but it'd just be more complicated.
Answer: Well, maybe you got the related table name wrong? What I mean, stringly typed stuff is hard to control in your code, i.e. is it maybe (Permission without the last 's'?):
return employeeObjSet.Where(emp => emp.FK_UserID == userID).
            Include("AdminType.Permission").FirstOrDefault();

For this kind of error I would advise you to use the lambda extension property name resolver, i.e. the overload/extension of the Include method which will be included if you enter the following using directive:
using System.Data.Entity;

This is the extension I tend to use:
public static IQueryable<T> Include<T, TProperty>(this IQueryable<T> source, Expression<Func<T, TProperty>> path);

It's used like this:
return employeeObjSet.Where(emp => emp.FK_UserID == userID).
        Include(x => x.Permissions).FirstOrDefault();

Here its x.Permissions because of the ICollection pluralization of the ef generator or your cf coding standard you use.
Hope it helps.

Eager loading not working in EF 6


How are constant expressions dealt with in c++ enum?

Question: What is the range of a c++ enum with a constant expression? This is my code
#include <iostream>

int main(){
    enum e3{min = -10, max = 100000};
    e3 x = e3(-1000);
    e3 y= e3(-100000912241);
    std::cout<<x<<" "<<y<<std::endl;
}

It outputs -1000 -1216664433
How is this happening?
Also, The C++ programming language by Bjarne Stroustrup specifies that the result of conversion of integral type to enumeration is undefined unless the value is the within the range of the enumeration. What is this range and how to calculate it?
Comment: I recommend not using enums values as integers. It is a bad design as this is not the purpose of usage of them. Maybe `struct` is a good replacement. That is why c++ prefers [enum class](https://stackoverflow.com/questions/18335861/why-is-enum-class-preferred-over-plain-enum)es over typical enums.
Answer: The range of an enum is the range of the underlying type. The compiler has probably selected an int as the underlying type of your enum.
It's allowed to do that since an int (assuming it's 32 bit on your platform) can contain all the explicit values you've given it.
You'll probably find that the type of -100000912241 is a long or a long long on your platform (note there is no such thing as a negative literal in C++: -100000912241 is the unary negation of the literal 100000912241.). But -100000912241 can't fit into that int, so the behaviour of your code is undefined.
If you want to inspect the underlying type of an enum, then use std::underlying_type.
Reference: http://en.cppreference.com/w/cpp/types/underlying_type
Comment: It makes sense but what is the range of an enum? Is an enum supposed to accept all integral values or only values within a particular range based on its initialisation
Comment: @Krash: Added that to the answer.


Show that points on an elliptic curve have order 4

Question: I am studying elliptic curves using this book and have a problem with task 4.11 which goes as follows:
Let $F_q$ be a finite field of odd characteristic and let $ a,b \in F_q $ with $a \ne2b$ and $b \ne 0. $ Define the elliptic curve E by $ y^2 = x^3+ax^2+b^2x $
a) Show that the points $ (b,b\sqrt{a+2b})$  and $(-b,-b\sqrt{a-2b}) $ have order 4.
So, if the curve was on normal weierstrass form I guess I could use the formula and eventually reach infinity, but if the curve can have characteristic 3, then how can I transform it to weierstrass? Or is there any other way to show that the points have order 4 using schoof's or baby-step giant-step etc?
Comment: the characteristic of the field doesn't really play a role, just take the formula for adding points and compute $2P,3P$ and $4P$, where $P$ is your point.
Comment: @Ferra If I understand OP correctly, they want to use a form of the group law that applies just to curves in Weierstrass form (which, to be clear, does not always exist for an elliptic curve over $\Bbb F_3$). Also, one can just compute $2P$ and then $4P = 2P + 2P$.
Comment: to me, that form is called Weierstrass... probably he meant short Weierstrass form. In that case, when the characteristic is $3$ you can compute manually $2P$ and check that this is $2$-torsion.
Answer: First, the form $y^2=x^3+ax^2+bx$ is close enough to the classical form to do all the necessary computations in, as long as the characteristic is not $2$.
Second, when an elliptic curve is in this form, I hope it's obvious that the points of order two are exactly those on the $x$-axis.
Third, on this particular curve, the origin is thus a point of order two, and to find $2$-division of this point, you only need to find points on the curve at which the tangent passes through the origin.
It's no fancier than that.


How to create a simple list of links to Drupal panel pages?

Question: I would like to create a simple HTML menu made of links to pages A, B, C created in Drupal (but not all pages, only a subset). Unfortunately, menu's in Drupal are displayed as li lists, not just a list of urls, which adds bullets to the display.
A view displayed as unformatted list would be great, but you cannot create a view of miscellaneous page links.
I could create a mini-panel and hardcode the links, but hardcoding is always a bad idea. Ideally, there should be a way to set relative links to pages and let Drupal generate absolute links.
What would be the best way to create a simple a list of links to pages created in Drupal? A block or a mini-panels are acceptable solutions.
Answer: You could create a View of miscellaneous page links, if the list of links was actually a list of a series of nodes with a particular taxonomy term applied to them.
For example:
Create a taxonomy vocabulary called "Page Links", and create a new taxonomy term for it called "Custom Menu One". Then, tag each of the pages which you want included in your list of links, with this Custom Menu term.
Now, you can go into the Views UI, and create a block View which outputs all nodes which have the taxonomy term "Custom Menu" applied to them. You can set up the view to use fields, and output the title of each node as a link back to the original content.
You'll also be able to configure the display settings for the View so that the links are output as a List, or Table, or unformatted, etc.
Comment: Side note, this is an example of how many interesting things can be made possible with Taxonomy, once you wrap your head around it's many possible applications.
Comment: This could work if I created a node type and recreated my pages as such, which is a bit of over-engineering according to me. It is a pity that one cannot add tags to panel pages...
Answer: Using an HTML list is semantically correct in this situation. If you literally want to create a list of links to pages in your site, why would you object to using semantically correct HTML via an intuitive element of site architecture (menus)?
Bullets are a superficial styling default for HTML lists and can easily be removed with CSS.
.block-menu-menu-name ul.menu li {
  list-style: none;
  list-style-image: none;
}

Using the Drupal menu system is still the easiest and most efficient way to create a list of links to pages within your site, even if you do not want to use an HTML list to display them.
You can easily override the theme functions that create any menu's HTML. In your theme's template.php file you can override theme_menu_link() and theme_menu_tree() for the menu you want to manipulate. Let's say the menu is called "Links List".
function THEMENAME_menu_link__links_list($variables) {
  $element = $variables['element'];
  $sub_menu = '';

  if ($element['#below']) {
    $sub_menu = drupal_render($element['#below']);
  }
  $output = l($element['#title'], $element['#href'], $element['#localized_options']);
  return '
' . $output . $sub_menu . "
\n";
}

function THEMENAME_menu_tree__links_list($variables) {
  return '
' . $variables['tree'] . '
';
}

Note that there are two underscores before the machine name of the menu in the function name.
This would result in a list of divs with links inside them. Also, you could omit the div wrappers and add a
 after each link instead.
It seems like a lot of unnecessary work for what is essentially a superficial styling issue, but perhaps there some other aspect to your overall goal that would make this approach seem more appropriate?
Comment: Thanks for the detailed answer. I could remove the bullets with you CSS advise. So thanks for that. the underlying li prevents me from aligning the items horizontally. I think, I'll need to create a list manually...
Comment: You can align the items horizontally using a little bit of CSS as well.
Comment: Thanks for the suggestion. I am no expert at CSS. I found display: inline; With this suggestion, I have a complete solution to my issue. I did not know it was possible to achieve this only with CSS. Thanks again.


Eigenvalues of A(adj A). Are they necessarily real?

Question:
I do not understand how if det(A) comes out to be a complex number then the eigenvalues will still be real?
Answer: I think you are confusing adjugate from adjoint of a matrix. In this context, it refers to the conjugate transpose.
Guide:
A possible way to solve the problem is to consider the SVD of $A$, compute $A^*$ and then compute $AA^*$ and $A^*A$.


JQuery ajax error

Question: Ok, so my Ajax call looks like this:
var poststring = "id_Client=" + id_client + "&id_File=" + id_file;
        alert(poststring);
        $.ajax({
            type: "POST",
            url: "addclpermission.php",
            data: poststring,
            error: function(xhr, textStatus, errorThrown){
                alert("Error: " +textStatus)
            }
        });

Everything works fine until the $.ajax(). If I use alert(poststring) the output looks like this:
id_Client=7&id_File=32

Using firebug, I found out that the url "addclpermission.php" is actually requested, but then 'aborted'. The path is correct though, if I copy the url out of firebug and call it directly, no error is displayed.
The alert in the 'error' option returns "Error: error"
The file addclpermission.php:
<?php
require_once("../allgemein/includes/dbconnect.php");
$id_File = $_POST['id_File'];
$id_Client = $_POST['id_Client'];
$sql = "INSERT INTO permission (id_File,id_Client) VALUES (".$id_File.",".$id_Client.")";
mysql_query($sql);
?>

I'm pretty sure this code once worked and that I haven't changed that much.
Any ideas?
Thanks!
Edit: I don't think that the error is in the php script, I have multiple ajax calls to several php scripts, but all of them fail the same way.
Edit 2: Now it works! Well, at least half of it. The request is still aborted, but the data gets inserted in the database. But as I said, this isn't the only ajax call and the others still aren't working, and this one is aborted. So I'd really like to know what caused this error and how I can fix it for good. Thanks!
Comment: Your code is vulnerable to sql injections - use http://php.net/manual/de/function.mysql-real-escape-string.php
Comment: What is the error you get? Also, `alert("Error: " +textStatus)` is missing a semi-colon (*;*) at the end.
Comment: @Ghommey: I know, I trimmed the code to the relevant part.
Comment: @stealthyninja: Thanks for the tip with the semi-colon. However, it didn't change anything. I don't get any other error than the one that I display using alert().
Comment: You have to use the `xhr.responseText` instead of textStatus http://stackoverflow.com/questions/1637019/how-to-get-the-jquery-ajax-error-response-text
Comment: Do you mean `xhr.responseText`? If so, it's emtpy.
Comment: Not sure if you've tried this, but in Firebug's Net tab, right-click on the relevant link and try both `Open in new tab` and `Open response in new tab`. The former will make a new request, exactly as the AJAX did (same post data and all), the latter will simply copy the response to a new tab. One of these might give a bit of insight.
Answer: Does the data get inserted to mysql despite the error? If so, can you put echo on your addclpermission.php file to return 'success' and/or 'fail' for mysql_query()? How about stripping this php file to just echo "hello"???
Comment: Thanks for your input! The data doesn't get inserted. And I tried just echoing "hello", but firebug still shows Status: aborted, and the error function gets called.
Comment: are you under linux box ? or IIS? are you sending and requesting data on the same servers?
Comment: I don't know what kind of server I'm working on, but the data is on the same server.
Comment: you might want to check the directory permissions from your server particularly with the directory where the post file is called including where the include files are located and ensure there were no changes made to these permissions...
Comment: Thanks for your comment! I believe the problem is elsewhere, please look at the second edit above for more information.
Comment: why don't you try including a complete event to know which error, if this is a timeout error or what.. can you try error:function(){..},complete(XMLHttpRequest, textStatus){ alert(textStatus);} and remove the other alert notice on error?
Comment: have you also tried running a stripped file just to test jquery functionality for your server? maybe something else in your code is aborting the ajax process? and check firebug on what line of code gets performed just before this ajax call?
Answer: First, I would try just requesting addclpermission.php in the browser and see what happens.
Then, if that works, what if you just make addclpermission.php contain some text, no PHP content at all. Then for each stage that works, gradually add content (so first the include, for example).
Comment: Thanks for your answer. Requesting the script works perfectly. I tried echoing "hello", which works on its own, but not via ajax. Same applies for no content at all or just html content.
Comment: So does the ajax request work if you don't put any PHP content in the php file? Its a process of elimination to work out what's causing the problem.
Answer: I think the error could be in dbonnect.php or addclpermission.php. Save this in addclpermission.php (make a backup of your current file) and browse to it directly:
<?php
require_once("../allgemein/includes/dbconnect.php");
$id_File = 1;
$id_Client = 1;
$sql = "INSERT INTO permission (id_File,id_Client) VALUES (".$id_File.",".$id_Client.")";
mysql_query($sql);
?>

Please let us know if it works or if you get an error.
Comment: Thanks, it the request is still aborted. The query however wouldn't work because of foreign keys, but I will try it using values that won't cause a mysql error.
Answer: When I do jQuery Ajax, I set the data as a Javascript object that jQuery then serializes. Do you have better luck if you provide data: property as an object like this:
data: {
    id_Client: id_client,
    id_File: id_file
}

Comment: Nothing changed, but then I'm never lucky when it's about anything code related :)
Answer: I am pretty sure your problem is that you are not returning an expected dataType to the .ajax call, if you explicity set the datatype (json or text for example):
$.ajax({
        type: "POST",
        url: "addclpermission.php",
        data: poststring,
        dataType: "json",
        error: function(xhr, textStatus, errorThrown){
            alert("Error: " +textStatus)
        }
    });

Then just echo out the expected datatype, just so the server responds, then ajax will know the request was successful.
<?php
// if your dataType is json
echo json_encode(true);

// if your dataType is text
echo ' ';

// exit so the server can return the request
exit;

Answer: problem is a  --> require_once
require_once("../allgemein/includes/dbconnect.php");

remove this line in a php and write all code here
but I don't know why ?

JQuery ajax error


Purpose of class balancing

Question: I see people doing class balancing (via oversampling, etc.) before learning classifiers all the time. I wanted to know why does class balancing improve classification accuracy. Is it true all the time. If so, is it true for all classification tasks. I was trying to find some theory paper to justify this but couldn't find any.
Comment: This is probably a duplicate, maybe of http://stats.stackexchange.com/questions/20948/best-way-to-handle-unbalanced-multiclass-dataset-with-svm  or  http://stats.stackexchange.com/questions/107874/how-to-deal-with-a-skewed-class-in-binary-classification-having-many-features/121089#121089    or  http://stats.stackexchange.com/questions/105797/training-and-testing-on-unbalanced-data-set   or  ... .  Search this site for the tag [unbalanced-classes]
Comment: Also this question of mine: http://stats.stackexchange.com/questions/247871/what-is-the-root-cause-of-the-class-imbalance-problem.  My current thinking is that class balancing is intended to fix issues with non-probabilistic models.
Comment: @MatthewDrury I am trying to find cases in which the class balancing (over sampling) has been shown in theory to perform better than uniform sampling. As in, if there has been theoretical works in showing that for certain class of models, class balancing would work better.
Answer: What I am going to write is partly described in some of the posts mentioned in the comments.  I thought How to deal with a skewed class in binary classification having many features? is close to what I want to say.
I think that in general, class balancing and oversampling will not improve overall accuracy,  but that is not the goal. As described in the cited post, with strong class imbalance you can get very high accuracy by simply saying everything is majority class. What I would like to emphasize is that getting the highest accuracy is not always the goal.  It is often better to make more false positive errors in return for eliminating some of the false negatives. Many diseases have a fairly low incidence rate.  But simply saying that no one has the disease is not an acceptable solution. If you identify most of the true positives (and include some false positives) additional testing can be applied to a small group to sort out which cases were real and which were not. The overall accuracy is lower, but you identify more of the cases that it is critical to identify.
Comment: Would'nt it be better to achieve this using a loss function giving higher weight to the low-frequency class?

Purpose of class balancing


SMO ManagedComputer.ServiceInstances is empty

Question: I am trying to use SMO (VS 2010, SQL Server 2008) to connect to SQL Server and view the server protocol configuration. I can connect and list the Services and ClientProtocols as well as the account MSSQLSERVER service is running under. However, the ServerInstances collection is empty. The only instance on the target server is the default (MSSQLSERVER), shouldn't that be in the collection? How can I get an instance of it so I can inspect the ServerProtocols collection? Here's the code I'm using:
    class Program
{
    static void Main(string[] args)
    {
        //machine hosting installed sql server instance
        ManagedComputer host = new ManagedComputer("fully-qualified.host.name");

        if (host.ServerInstances.Count != 0)
        {
            //why is this 0? Is it because only the DEFAULT instance exists?
            Console.WriteLine("/////////////// INSTANCES ////////////////");
            foreach (ServerInstance inst in host.ServerInstances)
            {
                Console.WriteLine(inst.Name);
            }
        }

        Console.WriteLine("/////////////// SERVICES ////////////////");
        // enumerate sql services (looking for MSSSQLSERVER)
        foreach (Service svc in host.Services)
        {
            Console.WriteLine(svc.Name);
        }

        Console.WriteLine("/////////////// DETAILS ////////////////");

        // get name of MSSQLSERVER instance from user (pick from list above)
        Service mssqlserver = host.Services["MSSQLSERVER"];

        // print service account: .\{account} == "local account", "LocalSystem", "NetworkService", {domain}\{account} == "domain account"
        Console.WriteLine("Service Account: {0}", mssqlserver.ServiceAccount);

        // get client protocols
        foreach (ClientProtocol cp in host.ClientProtocols)
        {
            Console.WriteLine("{0} {1} ({2})", cp.Order, cp.DisplayName, cp.IsEnabled ? "Enabled" : "Disabled");
        }

    }
}

I've also tried:
            Urn u = new Urn("ManagedComputer[@Name='fully-qualified.host.name']/ServerInstance[@Name='MSSQLSERVER']/ServerProtocol[@Name='Tcp']");
        ServerProtocol tcp = host.GetSmoObject(u) as ServerProtocol;
        if (tcp != null)
        {
            Console.WriteLine("{0}", tcp.DisplayName);
        }

But I get an error message stating: "child expressions are not supported." Any ideas what's wrong?
Answer: To get results in the ServerInstances list, you need to explicit set:
host.ConnectionSettings.ProviderArchitecture = ProviderArchitecture.Use64bit;
or
host.ConnectionSettings.ProviderArchitecture = ProviderArchitecture.Use32bit;
Answer: So I never found the answer to this, but I came up with a workaround.
            ManagedComputer host = new ManagedComputer(hostName);

        Server server = new Server();
        Console.WriteLine("TcpEnabled: {0}", server.TcpEnabled);

This gets me what I need, I would prefer to be able to enumerate the ServerProtocols, but this will allow me to verify the very minimum.


Over-fitting SARIMA model

Question: I am currently running an iterative process(for loop) to determine best ARIMA model for monthly sales data according to smallest AIC and MAPE.
Box-Jenkins methodology clearly states to choose the order of the ARIMA components according to smallest AIC and validate according to out of sample accuracy measures, such as MAPE.
My question is:
Is over-fitting a risk if I choose my models according to smallest MAPE instead of AIC?Are there any risks/disadvantages?
Comment: *Box-Jenkins methodology clearly states to choose the order of the ARIMA components according to smallest AIC* does not seem to be a common interpretation of the Box-Jenkins methodology. Determining lag orders by ACF and PACF is a more common interpretation.
Comment: You're right, thank you for the notice.The school subject were I learned about the methodology had mentioned the terms multiple times together. I guess the AIC came later in the method.
Answer: Following @Richard Hardy's excellent comment ...and a paraphrase of @Adamo's advice here Interrupted Time Series Analysis - ARIMAX for High Frequency Biological Data?
"The correlograms i.e. the acf and the pacf should be calculated from residuals using a model that controls for intervention administration, otherwise the intervention effects are taken to be Gaussian noise, underestimating the actual autoregressive effect."
In other words if there is latent deterministic structure the acf and pacf can be quite misleading thus one needs to examine data that is conditioned upon possible pulses, level/step shifts, seasonal pulses and deterministic time trends.
Mindless fitting of all possible models can and often will produce redundancies and/or unnecessary differences and power transformations and over-populated structure. KISS (parsimony) should be the objective . Care should be taken to ensure that parameter constancy is validated over time and that model error variance is not flagrantly heterogeneous over time.
https://autobox.com/pdfs/ARIMA%20FLOW%20CHART.pdf suggests a script/paradigm that can often be useful.
Comment: Einstein: "Everything should be as simple as it can be, but not simpler"
Comment: Thank you, I remember my professor laying emphasis on the principle of parsimony.

Over-fitting SARIMA model