Identify the curve from the sample points

Question: I am writing a script which will identify the patterns drawn on the touch-pad of the laptop. I have generated all the points where user moved his finger over the touch-pad using synclient.
Now i have the points and i want to identify the pattern from these points.
For simplicity i have restricted the patterns to alphabets[A-Z], numbers and simple curves like circle, semi-circle, vertical and horizontal lines.
So, how to identify the curve from the set of points?
Comment: The first step is to normalize the inputs. For instance, you could put a rectangle around the letter or shape, then use an affine transform to map it to a 1x1 square. Then you can match the normalized input against some patterns. MMSE is a reasonable comparison method, I guess. Many machine learning methods, such as neural networks can be used as well. You need to provide your inputs as well as the patterns to get a better answer. I can't see a direct relation between your question and Mathematica, however.
Answer: This is not an easy task. Unless you have many months (or maybe even years) to work on this, I recommend that you use an existing library for handwriting recognition. There is an open source one at this CodeProject page, Windows has the "ink analysis" API, and there are probably others. I strongly recommend that you search around before attempting this yourself.


Difference between a cox model and a log transformed dependent variable linear model for regressing time to event

Question: We need a multiple regression model to infer the effects of our variables on a "time to event" dependent variable.
People usually use a Cox regression for this kind of problems. Actually I'm not very confident with this technique.
I would exclude a poisson/neg binomial model because the outcome is not strictly a count variable (am I right?)
An alternative could be a log transformed outcome model, which allows to model a zero bound positive dependent variable, giving out percentage changes as coefficients.
Which are the conceptual differences between the two and the eventual advantages of the cox model?
(Consider also that I'm going to use the bootstrap for the inference part, so a note on the efficiency of the two model with the bootstrap BCa confidence intervals would be a plus)
Comment: You're correct to think that "time" is not a count, yes.
Answer: An important reason why people use survival analysis (of which Cox regression is a special case) is that it provides a natural way of incorporating observations that have not yet experienced the event when you stopped collecting the data. For these observations we don't know how long it will take, but we do know something: it happend after we stopped observing. Ingnoring these observations (by giving them missing values) would bias your estimates. Similarly giving those observations the value for the time you stop observing will also bias your estimates. So I don't see a corresponding solution to "right censoring" in your linear regression model.
This is typically the most important reason, but there are others. A short and accesible introduction to survival analysis, including Cox regression, is: Paul D. Allison (2014) Event History and Survival Analysis, second edition. Thousand Oaks: Sage.
Comment: Would it change if the event is labeled yes/no, therefore for the "no" we don't know whether it didn't happen because we didn't observe enough or because it's not supposed to happen?
Comment: That changes the meaning of variables, and I cannot think of an application where that would correspond to something you would want to know. So I don't think you can do it that way.


Rails Polymorphic Nested Attribute with fields_for unable to save

Question: I have the following code:
class User < ActiveRecord::Base
  has_one :profile_image, :as => :owner, :class_name => 'Image'
  has_one :cover_image,   :as => :owner, :class_name => 'Image'
end

and:
class Image < ActiveRecord::Base
  belongs_to :owner, polymorphic: true
end

Now I am trying to build a form where a user can update his/her images, and his/her e-mail. I am building the form like this:
= form_for @user, :url => pages_upload_path, :html => { :multipart => true } do |form|
  = form.text_field :email
  = form.fields_for :profile_image_attributes do |profile_image|
    = profile_image.file_field :file
  = form.fields_for :cover_image_attributes do |cover_image|
    = cover_image.file_field :file
  = submit_tag("Upload")

This however compiles to the following params hash:
[2] pry(#<PagesController>)> params[:user]
=> {"email"=>"email@example.com",
 "profile_image"=>
  {"file"=>
    #<ActionDispatch::Http::UploadedFile:0x007f8a41365d30
     @content_type="image/png",
     @headers=
      "Content-Disposition: form-data; name=\"user[profile_image][file]\"; filename=\"Screenshot 2014-04-27 02.57.34.png\"\r\nContent-Type: image/png\r\n",
     @original_filename="Screenshot 2014-04-27 02.57.34.png",
     @tempfile=
      #<File:/var/folders/_2/rgn574910638hqstf85233hh0000gn/T/RackMultipart20140518-88429-15129ld>>},
 "cover_image"=>
  {"file"=>
    #<ActionDispatch::Http::UploadedFile:0x007f8a413653d0
     @content_type="image/png",
     @headers=
      "Content-Disposition: form-data; name=\"user[cover_image][file]\"; filename=\"Screenshot 2014-04-27 02.57.34.png\"\r\nContent-Type: image/png\r\n",
     @original_filename="Screenshot 2014-04-27 02.57.34.png",
     @tempfile=
      #<File:/var/folders/_2/rgn574910638hqstf85233hh0000gn/T/RackMultipart20140518-88429-1oosnc5>>}}

But when I save this, like this, I get the following error:
@user = User.last
@user.update_attributes(params.fetch(:user, {}).permit(:email, :profile_image => [:file]))
# ActiveRecord::AssociationTypeMismatch: Image(#70115863220300) expected, got
# ActionController::Parameters(#70115879244320)
# from /Users/kaspergrubbe/.rbenv/versions/2.0.0-p353/lib/ruby/gems/2.0.0/gems
# /activerecord-4.1.0/lib/active_record/associations/association.rb:216:in
# `raise_on_type_mismatch!'

How can I get it to accept my attributes for the profile_image?
Comment: Removing the `:class_name =>'Image'` could solve the problem i guess.
Comment: Post the `controller code` please.
Answer: You need to add:
accepts_nested_attributes_for :profile_image
accepts_nested_attributes_for :cover_image

The error you're getting is a result of the way rails assigns attributes. For each key it calls #{key}= method, so in your case it is trying assign hash to profile_image.
When you add accepts_nested_attributes_for many thing will change. Firstly, it will define profile_image_attributes= method which expects Hash object which will be used to build or update associated object. When fields_for noticed that this method is defined, it will update name of the field to contain _attributes at the end, so everything will work.
Note however that fields_for will not build if there is no object associated, so you will need to build those objects in your new and edit action.
Comment: LOL :D Why didn't i see it before.


Xen start hangs on waiting for root file system

Question: I'm trying to setup some Xen stuff, and made 4 images, exactly the same, based on the Ubuntu hardy 64 bit system I'm running everything on.
I literally made the images with a bash loop, and they are all exactly the same, named xen{1,2,3,4}.
1, 2, and 3 start just fine, but 4 hangs on waiting for root file system.
Comment: What does `/var/log/xen/xend.log` give you for that domain?
Answer: Just a stab in the dark, but have you ran out of loop devices? run "cat /proc/diskstats" to see how many loop devices your kernel can use.
Comment: i see loop0 through loop7, but the problem happens when i run just xen4 on its own
Answer: It was actually in the logs for the xen-create-image command. The disk image didn't get created properly since it was already mounted. I must have CTRL+C'd something and not umount'd the disk. umounting and remaking the domain fixed the problem.
Comment: Sounds reasonable. You should accept your own answer to mark the question as answered.
Comment: Yeah I will...you have to wait a little while to be able to accept your own answer.


Convert from prototype to jQuery

Question: Is there a consistent and generic way to convert prototype code to jQuery?
I'm not asking how to convert specific code like:
From:
<code>Event.observe(window, 'load', function () {
    /*code*/
});
</code>
To:
<code>$(function(e){
    /*code*/
});
</code>
But how to convert any code from prototype to jQuery.
I am not sure this is possible, but any suggestions are welcome.
Thanks
Update:
I have been here but this is 4 years old..
You know, a question like (how to load data from the server without reloading the page) in 1990 would have an obvious answer: you cannot
Comment: @ts. I seen that question, but since it's 4 years old, I was thinking maybe things have changed meanwhile...
Comment: Duplicate of http://stackoverflow.com/questions/256768/is-there-a-resource-to-help-convert-prototype-javascript-to-jquery
Comment: @ManseUK Better to be sure the answer is **no** than to keep wondering *what if it exists*..
Comment: @skafandri I really fail to see why a tool of this type to ever be created - for one .... as you have already pointed out both libraries change - and they change a lot ... I would suggest that this is going to be a manual task ..
Comment: Actually, from technical point of view, developing such a tool is possible, but who would do it?...
Comment: You're answering (a lot) your own questions, and commenting on them as well? You know there is a Q&A function right?
Answer: I realized such a tool could not exist
Comment: Yeah! I was highly expecting this kind of answers... Anyway! I tried :)

Convert from prototype to jQuery


array of parameterized types

Question: I'm having trouble figuring out what type parameter is expected at RHS of the following
ArrayList<Pair<ParseNode,ParseNode>>[] nodes = new ArrayList[indexes.length];

Why a copy of <Pair<ParseNode,ParseNode>> is not legitimate?
Answer: Arrays of concrete paramaterized types are inherently broken.  Remember arrays are covariant and the array type check is a runtime operation.  At runtime all the generics have been type erased, so the Array Store check can't tell <Pair<ParseNode, ParseNode>> from <Pair<BigInteger,IOException>>.
The fundamental contract of a generic is "I, the compiler, promise that if you write code that generates no warnings, you will never get a class cast exception at runtime."
Neither can the compiler guarantee to you that it will be able to give you a compile time error if something that is not an ArrayList<Pair<ParseNode,ParseNode>> is put into that array.  Nor can the runtime system guarantee you will get an ArrayStoreException (like the Language Specification says it will) if you add the wrong type, rather than a ClassCastException later when you take it back out.  (The second part is really why it's actually illegal rather than just a warning, it would result in an array that doesn't obey the language specification.)
So it doesn't let you declare them that way and forces you to acknowledge the 'unsafe' warning.  That way it has said "I told you I can't guarantee there will not be any class cast exceptions as a result of using this array, it's on you to make sure you only put the right things in here."
Answer: Java not supports generic arrays. Arrays are covariant, generics are not. This means that if class A extends class B then A[] is also B[]. And code
A[] a = new A[10];
B[] b = a;

is legal.
But it is not same for generics. You could not assign Foo<T> to Foo<X> even if T extends X. And so elements of Foo<T>[] can't be guaranteed type safe.
EDIT
Excuse me for just linking out, but I've found Java theory and practice: Generics gotchas article, that explains everything about arrays covariance better than I even would dream.
Comment: Indeed.  And more information about that fact is here: http://stackoverflow.com/questions/529085/java-how-to-generic-array-creation
Comment: I regret that I began answering this question. Understanding is good, but it worth nothing when you can't clearly explain that :) And now i see that is left unclear.
Answer: Don't use an array. Use another ArrayList.
ArrayList<List<Pair<ParseNode,ParseNode>>> listOfLists = new ArrayList<List<Pair<ParseNode,ParseNode>>>();

listOfLists.add(new ArrayList<<Pair<ParseNode,ParseNode>>());

array of parameterized types


Jenkins + Active Directory Authentication - Slow Login

Question: I have a Jenkins master running on Windows 2008 SP2 set up with Active Directory authentication. The authentication is working fine and normally there is no issue with Login.
Occasionally however Jenkins will take 4 to 5 minutes to log a user in. This seems to correlate with the amount of time a user has been inactive (i.e. A user who has not logged in for 2 or 3 weeks will experience extremely slow response when trying to log in).
Has anyone else experienced this behavior? I'm really not sure if I should start looking at active directory or Jenkins to troubleshoot this.
Answer: The plugin maintainers actively suggest to enable logging (using "hudson.plugins.active_directory" to ALL) and file a bug if a problem happens.
Comment: Enabling logging will allow you to obtain timed events of the auth conversation between your jenkins server and your AD server. That should give you a head start to troubleshoot further.

BTW, plugin maintainers may help you out. I added tracking of upload speed for a file distribution plugin to help troubleshoot some users.
Comment: I see, I misunderstood your answer initially. You had said "enable login" but I think you meant "enable logging"? I have edited your answer to reflect this. In that case yes, that's a good idea. I still have to manage to collect the logs on one of the rare occasions when this happens though.
Comment: I'm using the AD plugin already...Not sure what you are trying to say here. The plugin maintainers aren't going to be able to help with random performance issues that most likely have nothing to do with their plugin.
Comment: I mentioned jenkins logs because they are probably the easiest to setup and to get an idea of. In the end to solve your issue you will probably have to do more troubleshooting at the network level. The problems could range from network misconfigurations (DNS, time desynchronization, ipv6, AD address) or more AD specific issues. I've found this read to be interesting: http://blogs.technet.com/b/instan/archive/2008/04/17/troubleshooting-the-intermittent-slow-logon-or-slow-startup.aspx  Hopefully your issue is just time sync, because I believe that would be the easiest to fix ;) good luck!
Answer: Jenkins slow login with Active directory seens to be almost alway's related to DNS issue. Check your dns Service (srv), NS, DomainDnsZones, _ldap.tcp.domaine.com, _gc._tcp.domaine.com and ForestDnsZone response from your AD/DNS server. If you can't reach all ip/port listed, you will face some random slow loggin (30 or 60 seconds, depend on the query) when the jenkins AD pluggins will try to query those servers/services.
You can easly trap the dns query with tcpdump or wireshark on your jenkin's server or on the DNS server.
tcpdump -i interface port 53
specifying sites can help you to make a potable workaround as that will limit slow loging to only bad result when querying inexistant/unreachable ip/port return by ForestDnsZone.


Mann Whitney Wilcoxon test

Question: My stats background is not very strong so I was hoping I'd be able to get some help. In my MSc thesis I am using R to test for significant differences in means between populations. My data is not normally distributed (based on QQplots, Shapiro-Wilk's and histograms), therefore I cannot use parametric tests. So I am using a Mann Whitney Wilcoxon test instead (wilcox.test in R).
Now from my understanding Mann Whitney Wilcoxon test for significant differences in medians, not means. I have a table with my data reported as means, but I report significance testing results in my thesis based on medians as calculated by R. Is this an appropriate approach? Or do I need to convert the means to medians in my table?
Thanks.
Comment: It doesn't test for difference in medians. It corresponds to a test for the median pairwise difference (in the population). You can get a rejection when the sample medians are equal. Many posts on site discuss this issue.
Answer: The Wilcoxon test is acutally not a test of medians but of ranks. There is a median test, but that apparently has low power(1) ist thus rarely used (R obviously has a package - you know! (2)). You might also want to look in the wilcox.test- help pages to read about a "pseudomedian": help(wilcox.test)
There is no logical problem with presenting means whilst proving difference in ranks. You may consider it "not elegant", if you are so inclined. There is no problem in reporting the mean as well as the median, if that helps.
Chances are, that you can actually use parametric tests in the absence of normality, if you have enough data. It is hard to tell, how much data is enough for how big a deviance from normality. Some say $n>30$ or $n>50$ might bie good rules of thumb.
And finally, if you have enough observations, you might compare means of non-normal data by bootstrapping...
(1) https://www.tandfonline.com/doi/abs/10.1080/00031305.2000.10474539
(2) http://rcompanion.org/handbook/F_09.html
Comment: Yes, you should take it out, as it is wrong. The median is a common way to report the same kind of data that the Wilcoxon tests are used to examine, which makes this a common misconception. You probably do not want to know about the median, you want to know, whether values in one group are systematically higher then in the other group. That, the Wilcoxon tests do.
Comment: The test is actually about testing equality of distributions with respect to location based on ranks. It is not a test of ranks. The idea is that if the distributions are shifted significantly the low ranks would tend to come mostly from distribution and the high ranks from distribution B. If the distributions are the same the ranks would be intertwined and so the low ranks and the high ranks would tend to come "equally from both A and B.
Comment: If the distributions are shifted and the means exist the test would indicate both a difference in means and medians.
Comment: Thank you for your comment. In my methods I said " Non-parametric Mann Whitney Wilcoxon test was used to test for differences in medians..", so I guess I should take out the medians from that sentence?
Answer: Mann-Whitney only tests for a difference in medians when you assume that the only difference in the distributions of the two samples is the location, and not the scale or shape, of the distribution, which is very often too strong an assumption.
In fact, if you just want a test for a difference in means (which is often the case), t-testing will work just fine even if the data aren't normal provided that you have a reasonable sample size, as Bernhard mentioned.
Comment: (+1) But note that under the location-shift assumption, a test for a difference in medians *is* a test for a difference in means.
Comment: With large samples a t-test will (usually) work okay as far as significance level goes. Power can sometimes be a different matter.

Mann Whitney Wilcoxon test


How can I find the size of a redis topic (subset of keys)?

Question: My redis keys are ordered using all kind of topics (e.g. Topic:SubTopic:Key).
I would like to find the byte size of a section Topic:* or a Topic:SubTopic:*.
Beneath a topic I can have all kinds of entries (lists, strings, hashes, sets etc.).
Now I know the cli has the memory usage <key> command, but I'd like to somehow call this on the redis server using lua.
My approach was to run something like:
eval "local keys = redis.call('keys',KEYS[1]) ; local sum=0 ; for _,k in ipairs(keys) do sum = sum + redis.call('memory usage', k) end ; return sum" 1 Topic:SubTopic:*

I know that this command has a performance impact, and therefore I'm going to run this offline just to analyze our data structures and not on production.
My main problem is that I couldn't find a redis server command to find the memory usage of a key that is similar to the cli command.
Questions:

Is there a better approach to analyze my keys? Using bigkeys isn't enough.
If not, is there any equivalent memory usage command that I can run as part of a lua script to get the byte size of a key?
Answer: You can call MEMORY USAGE to obtain the byte size including overheads of a given key and value.
Note: even if running offline, you should use SCAN instead of KEYS in your Lua script - this will reduce the script's runtime memory consumption and prevent the sandbox's stack from overflowing.
Comment: Thanks for the answer. I was looking for an equivalent call to memory usage that I can call using my lua script on redis...
Regarding the scan issue, I'm running on version 4.0.10 that has a bug with scan not returning all keys.


Solaris 10 opencsw git package issue with bitbucket git hosting


Outlook 2013, Exchange 2013, and Windows 10 - Exchange is Unavailable Error

Question: We have an isolated network used for test and development with its own Exchange server.  We've been using Windows 7 for years and have used Outlook 2007, 2010, 2012, and 2013 (which is currently being used).  Exchange Server is 2013.  Outlook 2013 works great in Windows 7, but we want to upgrade our development machines to Windows 10 and can't get Outlook 2013 to work.  No matter what we try, we get the following error when attempting to set up an Outlook profile:
The action cannot be completed.  The connection to Microsoft Exchange is unavailable.  Outlook must be online or connected to complete this action.
Everything works great in Windows 7, the problem only exists on our Windows 10 workstations (haven't tried 8 or 8.1).  OWA works fine, as does the built-in Windows Mail app (which uses Exchange ActiveSync).  Have tried the following with no love:

Connected the Windows 10 workstation to the Internet and installed all available updates.
Installed Exchange 2013 CU 12
Installed the self-signed Exchange server certificate into the workstation's Trusted Root Certificates store
Tried specifying the domain controller's FQDN in HKCU\Software\Microsoft\Exchange\Exchange Provider "DS Server" value.
Verified proxy settings in Internet Options are set to automatically detect settings
Copied the profile stored in the Registry's HKCU\Software\Microsoft\Office\15.0\Outlook\Profiles\Outlook key from a working Windows 7 machine to a Windows 10 machine
Turned off firewalls on both the Exchange server and the client machine (Windows 7 boxes work fine with the firewall on)

Outlook Anywhere is configured on the Exchange server, the authentication method is set to Negotiate.  I'm thinking that AutoDiscover is working because the "Add Account" dialog window reports that it can establish a network connection successfully and it seems to find the correct settings for the Microsoft Exchange dialog (the Microsoft Exchange server box shows the correct GUID for my mailbox).  Again, everything works fine on our Windows 7 boxes, but we're consistently having trouble with Windows 10.
Edit: Including entries from IIS and RPC Client Access logs below.
The Windows 10 client's IP is 10.0.0.37 (IPv6 is turned off, something we do as a standard practice on our client boxes). My user name is davidsond and our domain name is MONSTERGARAGE. (I don't mind putting these details up here because this is a completely isolated test and development network with no connectivity to the Internet.)
I see entries in the Default Web Site IIS log like this:
POST /Autodiscover/Autodiscover.xml ...; 443 - 10.0.0.37 Microsoft+Office/15.0+(Windows+NT+10.0;+Microsoft+Outlook+15.0.4815;+Pro) - 401 0 0 15
POST /Autodiscover/Autodiscover.xml ...; 443 - MONSTERGARAGE\davidsond 10.0.0.37 Microsoft+Office/15.0+(Windows+NT+10.0;+Microsoft+Outlook+15.0.4815;+Pro) - 200 0 0 31
These seem to correspond to entries in the Exchange Back End IIS logs that look like this:
POST /Autodiscover/Autodiscover.xml - 444 MONSTERGARAGE\davidsond fe80::cc5b:87c5:6d04:ad7%12 Microsoft+Office/15.0+(Windows+NT+10.0;+Microsoft+Outlook+15.0.4815;+Pro) - 200 0 0 45
That IPv6 IP is our Exchange server.
The RPC Client Access log contains entries for our working Windows 7 boxes like this one:
2016-05-19T01:53:06.879Z,5,0,/o=C2LA/ou=First Administrative Group/cn=Recipients/cn=koopm,OUTLOOK.EXE,14.0.6025.1000,Cached,10.0.0.45,,fe80::cc5b:87c5:6d04:ad%12,ncacn_http...
After sifting through these and then searching for any reference to davidsond or 10.0.0.37, I realized the RPC Client Access Log had no entries whatsoever for my Windows 10 box. It seems that RPC traffic isn't reaching the Exchange server, and one of my theories is that some security setting on the Windows 10 box is preventing RPC over HTTP. I've turned off the firewall and looked in the Windows 10 Privacy settings, but didn't readily see anything I could link to RPC or Outlook.
Comment: What happens if you setup a manual connection, without Outlook Anywhere? You could also start Outlook with the /rpcdiag switch, it may show what servers the client is trying to connect to.
Comment: Thank you for the reply.  Tried this with a profile I copied from a working machine, but the diagnostics window never showed any information.  I get the following error: "Cannot start Microsoft Outlook. Cannot open the Outlook window. The set of folders cannot be opened. The information store could not be opened."  Tried again after clearing out the profile entry in the Registry.  The Add Account wizard shows, then errors with "The connection to Microsoft Exchange is unavailable. Outlook must be online or connected to complete this action." The diagnostics window never shows.
Comment: What do the IIS and rpcClientAccess logs show?
Comment: Thank you for the suggestion - I hadn't looked in these logs yet. I will edit the question with the results. Looks like autodiscover entries exist in the IIS logs, but no entries exist in the RPC Client Access logs for the Windows 10 box.
Comment: There doesn't seem to be an IIS issue, what I would suggest is you get the Autodiscover settings from a working client and then try all the URLs in the browser of a Windows 10 machine, do you see any certificate errors? It only takes something small for Outlook Anywhere to not work.
Comment: @smwk Thanks again for the suggestion.  Looks like AutoDiscover is working fine.  I go to https:/ /dev-exchange.monstergarage.local/AutoDiscover/AutoDiscover.xml and get an XML response containing an ErrorCode of 600 and a Message of Invalid Request.  I read that this is normal if AutoDiscover is working.  No certificate errors.  I get this with IE9 on my Win7 box, and with IE11 and Edge on my Win10 box.
Answer: I had this problem once when the Forward Lookup Zones on the Exchange server didn't have the correct DNS entries for the public domain, only the local domain.
The Outlook client continued to error out and change the Proxy server connection on me.
If your autoconfigure isn't correctly configured, you may also find that the authentication doesn't work properly because it defaults to the wrong format of username... eg: Email address instead of domain/username
Comment: Thank you very much for the reply. This is an isolated test and development network with no public domain. The only domain name is the local domain. Our Exchange server isn't a DNS server, but when I look up the DNS entries on our domain controller everything seems to be in order. The local domain is listed under Forward Lookup Zones, and entries exist for all clients and servers, to include our Exchange server. I even verified the AutoDiscover settings in Active Directory Sites and Services, it looks good. Also, all WIndows 7 boxes work great, so I'm thinking AutoDiscover is set up properly.
Answer: We had the same issues when moving from Windows 7 to Windows 10. I followed the given solutions in this Microsoft article: microsoft support - exchange connection.
After this everything worked fine again.
But take a look at AutoDiscovery as well. Even if you think it might work make sure it really does. A lot of problems with exchange have their root there.
Comment: Thank you for the reply. I was hesitant to try this because the only machines that work are Windows 7 machines and the broken ones are Windows 10. Copying the User Shell Folders would relocate the Cookies and Cache folders. (All other entries looked the same, and an entry for AppData was present.)  I tried it anyway, with no love. The same errors occurred when running Outlook and when attempting to set up a new profile.  I even restarted and tried again.  Thanks, anyway.


Is it alright to place equality constraints on the items loadings for assessing configural invariance using effect coding approach?

Question: I am wondering if somebody can help me out with the syntax to run a longitudinal invariance test using effects coding approach in Mplus.
I have figured out that to run a CFA with effects coding, I would label all the factor loadings and then add MODEL CONSTRAINTS. as like the code below.

AE1 by t1ae1 * (L1)
 t1ae2 t1ae3  t1ae5 (L2-L4);
 AE2 by t2ae1 * (L1)
 t2ae2 t2ae3  t2ae5 (L2-L4);
 AE3 by t3ae1 * (L1)
 t3ae2 t3ae3  t3ae5 (L2-L4);
 AE4 by t4ae1 * (L1)
 t4ae2 t4ae3  t4ae5 (L2-L4);
 AE5 by t5ae1 * (L1)
 t5ae2 t5ae3  t5ae5 (L2-L4);
 AE6 by t6ae1 * (L1)
   t6ae2 t6ae3  t6ae5 (L2-L4);
 AE9 by t9ae1 * (L1)
   t9ae2 t9ae3  t9ae5 (L2-L4);
!2)Item intercepts (tau) all freely estimated except marker indicator, not labeled
 [t1ae1-t9ae1];
 [t1ae2-t9ae2];
 [t1ae3-t9ae3];
 [t1ae5-t9ae5];

 ! 3)item variances all freely estimated, not labeled
 t1ae1-t9ae1;
 t1ae2-t9ae2;
 t1ae3-t9ae3;
 t1ae5-t9ae5;
 ! 4)All Factor variance freely estimated
 AE1-AE9;
 ! 5)All Factor mean freely estimated
 [AE1-AE9];

 ! 7)auto-correlated errors (item-specific)
 t1ae1 with t2ae1 t3ae1 t4ae1 t5ae1 t6ae1 t9ae1;
 t2ae1 with t3ae1 t4ae1 t5ae1 t6ae1 t9ae1;
 t3ae1 with t4ae1 t5ae1 t6ae1 t9ae1;
 t4ae1 with t5ae1 t6ae1 t9ae1;
 t5ae1 with t6ae1 t9ae1;
 t6ae1 with t9ae1;

 t1ae2 with t2ae2 t3ae2 t4ae2 t5ae2 t6ae2 t9ae2;
 t2ae2 with t3ae2 t4ae2 t5ae2 t6ae2 t9ae2;
 t3ae2 with t4ae2 t5ae2 t6ae2 t9ae2;
 t4ae2 with t5ae2 t6ae2 t9ae2;
 t5ae2 with t6ae2 t9ae2;
 t6ae2 with t9ae2;

 t1ae3 with t2ae3 t3ae3 t4ae3 t5ae3 t6ae3 t9ae3;
 t2ae3 with t3ae3 t4ae3 t5ae3 t6ae3 t9ae3;
 t3ae3 with t4ae3 t5ae3 t6ae3 t9ae3;
 t4ae3 with t5ae3 t6ae3 t9ae3;
 t5ae3 with t6ae3 t9ae3;
 t6ae3 with t9ae3;

 t1ae5 with t2ae5 t3ae5 t4ae5 t5ae5 t6ae5 t9ae5;
 t2ae5 with t3ae5 t4ae5 t5ae5 t6ae5 t9ae5;
 t3ae5 with t4ae5 t5ae5 t6ae5 t9ae5;
 t4ae5 with t5ae5 t6ae5 t9ae5;
 t5ae5 with t6ae5 t9ae5;
 t6ae5 with t9ae5;

 model constraint:
  L1 = 4 - L2 - L3 - L4;
  !I1 = 0 - I2 - I3 - I4 -I5 - I6 - I7;

What puzzles me is that for configural invariance, loadings of different time points (AE1-AE9) are free to have their own loadings. However, if I put the same labels on them, I will be restricting them to be equal across time points. It would be very helpful if someone can tell me how to interpret the code, or, how it should be coded. Thank everybody for your help.
Answer:
Is it alright to place equality constraints on the items loadings for assessing configural invariance using effect coding approach?

Yes, invariance/equality of measurement parameters can be tested regardless of the identification method.
https://doi.org/10.5964/meth.10177

What puzzles me is that for configural invariance, loadings of different time points (AE1-AE9) are free to have their own loadings. However, if I put the same labels on them, I will be restricting them to be equal across time points.

Correct, so the syntax you posted is for metric invariance.  For a configural model, you need to use different labels for loadings across occasions:
AE1 by t1ae1 * (t1L1)
 t1ae2 t1ae3  t1ae5 (t1L2-t1L4);
AE2 by t2ae1 * (t2L1)
 t2ae2 t2ae3  t2ae5 (t2L2-t2L4);

And apply the effects-coding constraint to each factor's loadings.
Comment: Thank you so much! I have not been able to find examples of longitudinal invariance testing with effects coding for quite a while so I am really fascinated to get a reply so soon! Thank you again!!
Comment: I just edited my answer so "yes" was more explicit.
Comment: Thank you so much for that. I definitely think your answer is useful for lots. I got access to your article at last and will be reading it soon! However, Mplus is giving me error messages for model constraints now. Hope your article will give me good info to figure it out.


What is the best method to determine an account through DNS A record configuration?

Question: I apologize if my description of the problem is unclear. I am working for an online CMS that allows external domains to be used similar to Tumblr or Flavors.me. I noticed both of these services simply require you to add an A record to your domain's DNS.
When trying this, I added an A record for a blank name and "www" both leading to my webserver's IP. While this successfully routes to my server, it doesn't retain the used domain. This leaves me without any idea of what account they're attempting to reach at the application layer. I'm using nginx as my webserver.
I have changed all the nameservers for a domain before, and that works properly, however that causes complications with other issues such as mail and isn't feasible on a scaled solution.
What should I be doing here? Is the A record the correct method of accomplishing this? How are sites like Tumblr and Flavors.me determining which account is being referenced by the domain?
Answer: You most likely only want to have people create an A or CNAME record for a subdomain on their domain that directs to your server IP address (A record) or hostname (CNAME).  It isn't necessary to use subdomains, but you need to offer the option.
Your server then serves content based on the request it received, just as you might serve multiple sites from the same server.  In Apache you might use separate vhosts or, more likely in your scenario, your CMS serves different content based on the properties of the request.  You just need to figure out how the platform your CMS is on can access the different parts of a request, and then pass that to the logic that pulls the content.
If you make your question more specific to include the language/framework/platform the CMS is built in you may get more specific advice.  Or try posting to Pro Webmasters or Stack Overflow where you may find people with more specific experience doing this.
Comment: It isn't so much to authenticate their ownership, I want to be able to know the proper behavior when someone uses that specific domain to access their account. Suppose Company XYZ owns xyz.com and they want their employees to be able to see their CMS by using xyz.com. After they modify their DNS to point to my webserver, when the request comes in, how am I to know which account they're attempting to access?
Comment: Ah - I see I misread your question.  Updated answer.
Answer: To add to what dunxd said, you also do the A record because that's what directs requests for that (sub)domain to be handled by the service providers servers without the service provider having to take full control of the customers DNS. Once the request come into the service provider, there are several different ways that they can determine which customers data to display.
The first is Virtual Hosts which allow you to set different configurations for each domain you're servicing.
The second is Rewrite Rules which let you determine which data to return based on the requested URL.
The third is to use Server Variables and then use what ever language you're coding the application in to processes requests based on the the http_host value.
These aren't mutually exclusive you can use some combination of them to do what you want.
I'm not sure what you mean by:

it doesn't retain the used domain

Does the URL acctually change in address bar when you visit the domain? If so, you're probably doing an http 301 redirect somewhere. You can still do that, but you would need to have the server rewrite the URL first so that you can still pass the account information.
EDIT: I don't use nginx but I added some links that might be helpful.
Comment: This looks to be hitting close to the issue. I am currently using virtual hosts with nginx as well as rewrite rules. I have a feeling I'm redirecting the url to my root url. The URL actually changes in the address bar. I'll dig into nginx some and see if my configuration is causing some unwanted behavior. Thanks for the lead.
Comment: Maybe look for something like this: if ($host != 'your_domain.com' ) {
    rewrite  ^/(.*)$  http://your_domain.com/$1  permanent;
 }
Answer: Short answer: HTTP 1.1 requests must provide the Host: header field (see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.23).
I expect sites like tumblr are reading this.
Comment: This is very true, but it sounds like he'd be using a browser as his client and are they're any current browsers out there in common use that don't use http 1.1?


Grid plotting in Python with coordinates and a map image

Question: I'm fairly new to using python and I'm seeking help on a small project I'm working on.
So firstly I want to make a 10x10 grid out of coordinates and then add a loop function that can randomly pick a cell and somehow store the cell coordinates it has picked without selecting the same cell twice.
So far I have come up with this.
x = 1
y = 1

scale = 10

nn = []

for x in range(1,scale+1):
    mm = []
    for y in range(1,scale+1):
        xy = [x,y]
        mm.append(xy)
        #print(xy)
        y=+1
    nn.append(mm)
    x=+1

Out:[[[1, 1],
  [1, 2],
  [1, 3],
  [1, 4],
  [1, 5],
  [1, 6],
    etc

The next part is where I'm struggling.
import random
r = random.randint(1,10)
x = 1
y = r

xy = [x,y]
print(xy)
while x < 10:

    # direction North=1, East=2, South=3
    if y == 1:
        dir = [random.randint(0,1),random.randint(0,1)]
    elif y == 10:
        dir = [random.randint(0,1),random.randint(-1,0)]
    else:
        dir = [random.randint(0,1),random.randint(-1,1)]

    xy = [(a + b) for (a, b) in zip(xy, dir)]

    x = xy[0]
    y = xy[1]

if xy == [(a + b) for (a, b) in zip(xy, dir)]:
    pass
else:
    print(xy)

Eventually I would like to plot the coordinates onto a grid and then put a map image over the grid.
This is my first question so please excuse mistakes and code quotes.
Thanks in advance
Comment: I'm not completely following how each code block relates to each other.  What I think you're looking for is a `set`.  https://docs.python.org/3/tutorial/datastructures.html#sets . On each loop, check the set if the new value exists.  if not, add it, else try again.
Answer: From my understanding, you're trying to get non repetitive random sample from a grid of coordinates, This can be done much more easily like this:
import random
grid = [(x,y) for x in range(10) for y in range(10)] # grid points
randomset = random.sample(grid, 5) # get 5 random element from grid

Result:
>>> randomset
[(6, 6), (4, 7), (7, 7), (1, 7), (0, 3)] # each coordinate will be unique.

Comment: Many thanks for your answer it did indeed help! Can you help me plot the x,y onto a 10x10 grid like format. Thank you!
Comment: 2D grid for visualisation.  grid_array = np.array(grid)  -- grid=np.meshgrid(grid_array)


shutdown -i all computers in active directory domain

Question: I'm not sure if this is possible, but this is my goal:
At the end of the day, I want to be able to turn off all the computers in the domain from a client. My account has sufficient privileges to shutdown any single computer remotely using shutdown -I, and I can RDP into any computer in the domain.
However, is there an automated technique that does this? the computers in the domain are predictably named (computer1, computer2, etc), but than manipulating a list of 2000 computers in shutdown -I is pretty clumsy.
Is there a way to shutdown every single computer in the domain from a single client? The domain server is windows 2003, and the clients all run windows xp
thanks
Comment: Is this a production network? If so, why would you want to do this?
Comment: I believe /i is interactive. Is this what you really want?
Answer: Sure, you could create a scripted scheduled task, or create a script that executes the command via PSExec, for example, but this is an awful idea (so don't).

The most stressful time in a computer's life is during boot up.

Daily reboots will wear out your computers and drastically increase hardware failure rates.

When no one's using the computers is the ideal time for maintenance tasks.

AV scans, scheduled updates, disk defragmentation, etc.

A much better solution anyway would be to adjust the power settings via GPO.

You should use the time do do maintenance, but it's also possible to adjust the PC power settings via GPO so that they hibernate or sleep overnight, which not as hard on the equipment, and better for the users (quicker to resume than do a full boot).
Comment: How does hibernate differ from a powerdown in the context of wear and tear? If the user is concerned about power, sleep would be preferable, though you still have to deal with the drives spinning up and down.
Comment: Do you have a recent citation (made in the past couple of years, not early 2000s/late 1990s) for "Daily reboots will wear out your computers and drastically increase hardware failure rates."
Comment: @TheLQ I don't, but I also don't have a citation from the past couple years that hitting a hard drive with a hammer is bad for the hard drive.  Some things just don't change, and electronic components being put under greatest stress at power-on is one of those things.
Comment: @HopelessN00b I had assumed that the initial power on problem has been minimized or reduced since 15 years ago when this was known as a problem
Comment: @HopelessN00b Also consider home use, where a computer might be shut down and restarted multiple times with no problems
Answer: You could use script it using PsExec to run shutdown, or you could use PsShutdown:
psshutdown -u <username> -t 0 -k
psexec -d -u <username> shutdown -t 0 -s

Comment: Damnit, the other guys type faster...
Answer: Why not just use a group Policy to create a scheduled task to do this? You can even set a parameter on the task to only execute if the machine has been idle for x minutes so that you don't kick off anyone working late.
If you really want to use shutdown.exe, you should use the /m switch to target a remote computer and feed your list to it with a cmd "for" loop or a PowerShell get-content | foreach-object {} from a text list of computers.


Area of parallelogram 3D vectors

Question: I'm given the following parametrization of a parallelogram
$(x,y,z)=(1,1,1)+s\cdot(2,-1,-1)+t\cdot(-1,3,2),s\in[0,1],t\in[0,1]$
I'm now asked to determine the area of this parallelogram as well the unit normal vector in the middle of the parallelogram.
It's been a while since I've dealt with vectors, so any help would be highly appreciated!
Comment: Do you remember how the cross product relates to areas?
Comment: I think it's the length of the cross product of the two vectors spanning the parallelogram, but would that mean I have to determine the length of the cross product between (2,-1,-1) and (-1,3,2)?
Comment: That's it exactly. That will also give you a normal to the parallelogram.
Comment: Perfect, thanks! But what about the vector (1,1,1) does that not play any significant role? And how would I determine the midpoint of the parallelogram?
Comment: The specific location of the vertices doesn't affect the area, but it does determine where the middle of the parallelogram lies.
Answer: Take $P=(1,1,1)$ a vertex of the parallelogram. The two adiacent vertices are $Q=(3,0,0)$ (for $s=1$ and $t=0$) and $R=(0,4,3)$ (for $s=0$ and $t=1$). So the two vectors parallel to the two sides of the parallelogram $PQ$ and $PR$ are: $\vec v=Q-P=(2,-1,-1)^T$ and $\vec u=R-P=(-1,3,2)^T$.
Now remeber that the oriented area of a parallelogram is given by the corss product of the vectors parallel to two adiacent sides, so the area is the magnitude of the formal determinant:
$$ \mathbf{A}=
\det \begin{bmatrix}
\vec i & \vec i & \vec k\\
2&-1&-1\\
-1&3&2
\end{bmatrix}
$$
Normalizing this ''vector'' you have a unit vector orthogonal to the parallelogram.
Comment: @James It's a formal expression. Expand and compute the determinant as if the vectors in the top row were scalars.
Comment: Wouldn't Q-P = (2,-1,-1) instead of (1,-2,-2)? And how would you compute the determinant? It does not seem square to me?
Comment: We already had the sides of the parallelogram from its parameterization, so computing the two vertices seems like unnecessary work for this problem.
Comment: Okay, so it seems to me that the area is sqrt(35) when I compute it. But I'm quite lost when it comes to finding the unit normal vector that lies in the middle of the parallelogram..
Comment: @james: You are right! I have edited to correct my mistakes and to add something. The area is $\sqrt{35}$ and the unit vector orthogonal to the parallelogram is$\vec a=\frac{\vec v \times \vec u}{|\vec v \times \vec u |}=\frac{1}{\sqrt{35}}(1,-3,5)^T$.
Comment: Thanks, that's what I got as well. Now I just need to figure out how to place the unit normal vector in the center of the parallelogram
Comment: The center of the parallelogram is at $P+\frac{1}{2}(\vec v + \vec u)$

Area of parallelogram 3D vectors


When two rules attempt a page redirect, which will actually happen?

Question: I have a rule set up that redirects the user to a specific page after they edit a node.  I  have another rule that changes the value in a node, then redirects to a different page.  My problem: because the second rule makes a change to a node, the first rule is triggered and the user is sent to the first rule's URL (instead of the second rule's URL.)
When two or more URL redirects are triggered by rules, which one is performed?
Does this change if a rule is triggered within another rule?
How can I fix my problem?
Answer: try changing the order (weight) of each rule under its settings:
Weight
Order rules that react on the same event. Rules with a higher weight are evaluated after rules with less weight.
EDIT:
it's a little convoluted, but you could create a temporary variable within the node to control things - for example, a hidden boolean field or flag that is changed to true when editing - the rule checks for this as a Data Comparison in a condition. Have the change field and redirect Rule set the boolean but not redirect, then create two rules on save - one if the field is set, and one if the field is not. For the rule if the field is set, then add an action that resets the fields value.
Comment: it's a little convoluted, but you could create a temporary variable within the node to control things - for example, a hidden boolean field that is changed to true when editing - the rule checks for this as a Data Comparison in a condition. Have the change field and redirect Rule set the boolean but not redirect, then create two rules on save - one if the field is set, and one if the field is not. For the rule if the field is set, then add an action that resets the fields value.
Comment: I gave that one a try, it did not change a thing.  I'm thinking that the node saving is the last thing to happen anyway, so it is unaffected by weight.
Comment: I just noticed - you could also look into Conditional Rules (https://drupal.org/project/rules_conditional) to accomplish the same thing without needing two different rules for the save.
Comment: I eventually went with a flag that served as an extra variable.  I am currently using conditional rules.  Could you edit you answer to include the 'extra variable/flag' concept?
Answer: This is what I learned about rules and saved content:
Rules will temporarily save all changes that you make to a node, then save them all after the last action of a rule is performed.  Because of this, the node will normally be saved after a rule is 'completed.'  You can override this by calling the "Save Entity" action, which saves the entity right then.
Because the node is saved last, any rules that are triggered by the save will normally happen after the rule that triggers it has ended.
This can be changed by using the "Save Entity" action.


What is a generic solution to factor $\alpha x^6 - \beta x^4+\gamma x^2 -\delta$

Question: I'm curious if there exists a generic solution /approach to factor the polynomial
$\alpha x^6 - \beta x^4+\gamma x^2 -\delta $ with $\alpha \beta \gamma \delta$ the coefficients of the polynomial.
Comment: You may set $x^2 = u$ to get a cubic:
$\alpha u^3 - \beta u^2 + \gamma u - \delta$
Comment: And this cubic can be solved exactly
Comment: @Dietrich: edited the question
Comment: @NeverStopLearning Please remember that you can choose an answer among the given if the OP is solved, more details here https://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work
Answer: There is sometimes an alternative. The demand that roots come in $\pm$ pairs is pretty restrictive, though.
This first type is well behaved, example
$$ ( x^2 - 2)  ( x^2 - 3)  ( x^2 - 5 ) =  x^6 - 10x^4 + 31x^2 - 30 $$
There are six real roots, square roots of things. The general pattern would be
$$ (x^2 - a)(x^2 - b)(x^2 - c) = x^6 - (a+b+c)x^4 + (bc + ca + ab)x^2 - abc.$$
If $a,b,c$ are all positive, real roots.
We could also have $$  (x^2 - a)(x^4 + b x^2 + c) $$
with both factors irreducible over the rationals, say.
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
Let
$$  x^3 + a x^2 + b x + c  $$
have no rational roots, just be really unpleasant. We still get your
$$ \left(x^3 + a x^2 + b x + c \right)\left(x^3 - a x^2 + b x - c \right)= x^6 + (2b-a^2) x^4 + (b^2 - 2ac) x^2 - c^2 $$
Here is a good one
$$ \left(x^3 +  x^2 -12 x + 11 \right)\left(x^3 -  x^2 -12 x - 11 \right)= x^6 -25 x^4 +122x^2 - 121 $$
The first cubic was constructed using the cyclotomic methods of Gauss. Its roots are sums of cosines

Answer: HINT
Let $y=x^2$
$$x^6 - \alpha x^4+\beta x^2 -\gamma\iff y^3 - \alpha x^2+\beta y -\gamma$$
and solve the cubic formula.
Comment: @WillJagy nice trick, I didn't consider that possibility since I was focused on the general case. Thanks
Comment: Yes, this is clear, but how to get to the factors? Like $F(y^2) = G(y)*G(-y)$
Comment: For the cubic a general solution exists, you need to use that and then calculate $x$ such that $x^2=y$. I can't see others general approaches to that.
Comment: gimusi example $ \left(x^3 +  x^2 -12 x + 11 \right)\left(x^3 -  x^2 -12 x - 11 \right)= x^6 -25 x^4 +122x^2 - 121 $
Comment: $ ( x^2 - 2)  ( x^2 - 3)  ( x^2 - 5 ) =  x^6 - 10x^4 + 31x^2 - 30 $
Answer: Substitute $t=x^2$ to get $\alpha x^6 - \beta x^4+\gamma x^2 -\delta= \alpha t^3 - \beta t^2+\gamma t -\delta$, then solve the cubic equation using cardano's formula
Answer: Set $y=x^2$. Then $y^3-ay^2+by-c=0$ can be easily tested for a linear factor in $y$.
Also, one can solve the cubic equation in $y$.
Comment: $$ ( x^2 - 2)  ( x^2 - 3)  ( x^2 - 5 ) =  x^6 - 10x^4 + 31x^2 - 30 $$

$$ \left(x^3 +  x^2 -12 x + 11 \right)\left(x^3 -  x^2 -12 x - 11 \right)= x^6 -25 x^4 +122x^2 - 121 $$
Comment: Yes, you are right. I wanted to say a factor in $y$, not in $x$, sorry.
Comment: I thought about it overnight, and I still have not worked out a careful collection of all possible rational-reducible sextics of the type given. I did realize that my 2,3,5 example was pretty much exactly what you had in mind; so, sorry on my part. The product of two cubics does seem to be different, the actual roots in a different sort of extension field.


php - multiple connections to database

Question: I have a login page that gets the username and pwd and sanitises them before passing them to DB.
this is done through a function:
<code>function make_safe($text) {
  open_db_connection(); //this opens another connection!

  if(get_magic_quotes_gpc()) {
    $text = stripslashes($text);
  }
  $text = mysql_real_escape_string($text);
  return $text;
}
</code>
this function is called from a script that already has an open connection, but still, I found that I have to open another connection INSIDE ´make___safe()´ to make it work (otherwise I get a "Warning: mysql_real_escape_string() [function.mysql-real-escape-string]: Access denied for user blablabla@localhost ..."
I was wondering:
1) when I call make_safe, I already have an open connection - why is it not enough??
2) what are the problems in opening multiple connections?
thanks,
patrick
Comment: I'm not an expertin php but `make_safe` has nothing to do with the occurance of multiple connections to the DB, does it?
Comment: o.k.w.: mysql_real_escape_string() needs a connection to operate.  By default, it uses the most recently opened connection.  So, yes, multiple connections being open could have an effect.
Answer: I think you may need to supply the second argument to mysql_real_escape_string.
Comment: The second parameter is the ( resource $linkIdentifier ) by default it will use the last open connection, but you could specify an older connection.

php - multiple connections to database


Problem of solving a large scale Quadratic Problem with Quadratic Inquality Constraint (QCQP)

Question: I am trying to solve following large-scale quadratic fractional (QF) problem:
\begin{equation}
\begin{aligned}
\min_{x\in\Re^{n\times1}} &\frac{x^\top H x + f^\top x + C_e}{x^\top R x}\\
\text{s.t.} &~~Ax\leq b
\end{aligned}
\end{equation}
where $H$ and $R$ are both positive definite matrics. $C_e$ is a positive scalar. $n$ is around 5000.
By letting $z^2:=\frac{1}{x^\top R x}$, the original QF problem can be transferred into a non-convex QCQP problem:
\begin{equation}
\begin{aligned}
\min_{\theta\in\Re^{n+1}} &\theta^\top \tilde{H} \theta\\
\text{s.t.} &~~\theta^\top\tilde{R}\theta=1\\
 &~~\tilde{A}\theta\leq \tilde{b}\\
&~~\sigma^{-1}_{\text{vwap}} \leq z
\end{aligned}
\end{equation}
where $\theta:=[y^\top,z]^\top$, $y=xz$ and solve it using some non-convex solver i.e. IPOPT.
Alternatively, I could transform the non-convex QCQP problem into a semi-definite programming (SDP) problem, such that:
\begin{equation}
\begin{aligned}
\min_{X} &~tr(\tilde{H} X)\\
\text{s.t.} &~~tr(\tilde{R}X)=1\\
 &~~tr(\tilde{A}_iX)\leq \tilde{b}_i\\
&~~ X\succeq 0
\end{aligned}
\end{equation}
and solve it using some SDP solver, i.e. MOSEK. I firstly tried to use MOSEK to solve this $5000\times 5000$ SDP problem, but it seems very slow.
I then tried to use IPOPT (ver 3.12.9). By providing the Jacobian & Hessian informations and a feasible initial guess $x_0$, IPOPT could solve my problem very fast in most of the time. However, sometimes IPOPT iterations stucks for more than 10 mins! Because it keeps
"Reallocating memory for MA57: lfact"
I am wondering, is there any efficient and robust way to solve my optimization problem?
Comment: You are welcome to send the problem to MOSEK support. 5000x5000 is normally in the huge and hard range for any solver, unless it is very sparse or there is some other reason for it to be easy.
Answer: The IPOPT memory reallocating problem can be solved by setting
options.ipopt.ma57_automatic_scaling = 'yes';


How to access Google App Engine's dev server data from the command line

Question: I regularly download my Google App Engine production data locally (using a custom script that basically calls appcfg.py download_data) and upload it to the development server so that the data in my development environment matches production. You can find the scripts on Launchpad:

Download script (called with ./extra/manipular-datos.py --download)
Launcher script (called with ./extra/launcher.py)

This is what the launcher script does:

Start the dev server (flushing the database)
Load the previously downloaded models to the local database
Change the passwords of all normal and admin users so that we can log in with a password of "toto" for any user in the development environment. This is done with a script that accesses the freshly-loaded datastore data directly.

Everything was working fine until GAE 1.5.2. At that point the development server changed to prefix dev~, so I added --default_partition='' to launch the dev server. However now the password-changing script seems to not access the loaded data, it always returns 0 entities for normal or admin users. I'm wondering how to access the data from the command line, so explicitely not from an url to prevent this from ever happening on the production server. The scripts in ./extra are not uploaded to GAE, they can thus not be executed from there.
To give you an idea (but look at the script for more context), this is what the script used to do (and was working until GAE <= 1.5.1):
args, option_dict = ParseArguments(['', colCasaBasePath])
config, matcher = LoadAppConfig(colCasaBasePath, {})
SetupStubs(config.application, **option_dict)

The the application's models can be accessed just normally:
from src.models import WebUser, ScyllaUser
for tipo in (WebUser, ScyllaUser):
    usuarios = tipo.all()
    # Now len(usuarios) == 0

What has been changed (after GAE 1.5.1) that breaks my GAE data-accessing script? How would you perform such a workflow?
Comment: Have you tried prepending `dev~` to `config.application` when you pass it to SetupStubs?
Comment: Nick, that didn't work. In fact, since I started the dev server with --default_partition='', adding dev~ would have had the opposite effect.
Answer: The trick is to add the --default_partition= argument to the ParseArguments() call in the script that accesses the GAE data:
args, option_dict = ParseArguments(['', colCasaBasePath, "--default_partition="])

Note that there is nothing after the =, that's what put me off. I first tried adding "--default_partition=''", but that didn't have any effect (but also didn't result in errors).
After adding that call the script is again able to loop over all the users that have been loaded in the dev datastore. You can see the changes I had to make on Launchpad.


Converting DD-MM-YYYY to date format and setting value to html.Editor doesn't show value

Question: String in DD-MM-YYYY when converted to date and passed into html.editor doesn't show the correct value.
@Html.Editor("StartDate", new { htmlAttributes = new { @class = "form-control", @type = "date", @placeholder = " Start Date", @required = "", @id = "txtStrDate" } })

var myDate = document.querySelector(".update_ano #txtStrDate");

       var Displaydate = convertDateToRequiredFormat(strdate); // Converts date to DD-MM-YYYY
       var dateFormatted = new Date(Displaydate.replace(/(\d{2})-(\d{2})-(\d{4})/, "$2/$1/$3"));

       console.log(dateFormatted)//Shows the correct date format
       myDate.value = dateFormatted;
       console.log(myDate.value);// Shows empty Console

Razor HTML.Editor shows DD/MM/YYYY
Answer: document.querySelector(); returns an html object which doesn't have a value property.
Try change myDate.value = dateFormatted to myDate.innerText = dateFormatted
PS. You could look into the .toLocaleDateString function to format the date as well.
Comment: The value appears when I used the innerText property. However the Razor html.editor style shows the vale as dd/mm/yyy and not the date passed into the element.
Comment: @ANB tried using `myDate.innerText = dateFormatted.toString()` ?


How do you change the namespace of the serialized message in NServiceBus

Question: I've tried adding the appSetting "NameSpace" to my publisher and subscriber but the messages still contain the namespace http://tempuri.org/...
[Edit]
In the publisher EndpointConfig I have added:
<code>public class ServerInit : IWantCustomInitialization
{
    public void Init()
    {
        Configure.With().XmlSerializer("http://foo.com");
    }
}
</code>
This works but I would rather see this in the config file. Please let me know if anyone can suggest a way to do this.
Answer: Thanks Udi, I noticed that the distributor reads this from the appSettings already, just wondered why the others don't.
Comment: Because it's not something that should be possible for an administrator to accidentally change in your app. The distributor has it exposed so that you won't need to recompile it.
Answer: Just put that in your app settings and pull it using the .net configuration manager.


how do i substitute text for a variable in a terraform?

Question: I'm new to terraform and wanted to substitute the value devcert below for a variable value called env, how do i format the below to include the variable value instead of devcert?
pfx_blob = data.azurerm_key_vault_secret.devcert.value
// Get Certificate from External KeyVault
resource "azurerm_app_service_certificate" "cert" {
  name                = "sslCertificate"
  resource_group_name = "rg1"
  location            = "uk west"
  pfx_blob            = data.azurerm_key_vault_secret.devcert.value

Comment: im going through that now, it requires Basic Permissions In Azure Devops and once i get those permissions i can test
Answer: You can't do that. Such operation is not supported in terraform. Instead you should use for_each to create multiple instances of azurerm_key_vault_secret, rather then fully separate data sources. Then you can reference it using:
pfx_blob = data.azurerm_key_vault_secret.devcert["myinstance"].value

Comment: how would you do the For Each part?
Comment: @itye1970 It depends on your actual code, which you haven't shown.
Comment: // Get Certificate from External KeyVault
resource "azurerm_app_service_certificate" "cert" {
  name                = "sslCertificate"
  resource_group_name = "rg1"
  location            = "uk west"
  pfx_blob            = data.azurerm_key_vault_secret.devcert.value
Comment: @itye1970 Please update the question with correctly formatted new code.


Depending on what the user choose with determine the out put

Question: If the user enters A it works then they enter B it works and it works if they enter E it also works but if they then enter A to start over the program closes.
const double COMMRATE = 0.10;
const double COMMRATE = 0.10;

string inputstring;

char response;
Console.Write("Do you want to Calculate Sales A or B or E...");
inputstring = Console.ReadLine();
response = Convert.ToChar(inputstring);

    while (response == 'A')
     {
    Console.WriteLine("Enter amount of sales");
    string salesStr = Console.ReadLine();
    Console.WriteLine(Double.Parse(salesStr) * COMMRATE);
    Console.WriteLine("Enter sales member to continue or Z to exit");
    response = Convert.ToChar(Console.ReadLine());
     }
    while (response == 'B')
    {
        Console.WriteLine("Enter amount of sales");
        string salesStr = Console.ReadLine();
        Console.WriteLine(Double.Parse(salesStr) * COMMRATE);
        Console.WriteLine("Enter sales member to continue or Z to exit");
        response = Convert.ToChar(Console.ReadLine());
    }
    while (response == 'E')
     {
         Console.WriteLine("Enter amount of sales");
    string salesStr = Console.ReadLine();
    Console.WriteLine(Double.Parse(salesStr) * COMMRATE);
    Console.WriteLine("Enter sales member to continue or Z to exit");
    response = Convert.ToChar(Console.ReadLine());
       }

Answer: Because your code only loops per response type.
It iterates while the response is A, then while B, then while E. Meaning that it can only operate in that sequence
Maybe you should look at something like:
do
{
    Console.WriteLine("EnterNextCommand");
    inputstring = Console.ReadLine();
    response = Convert.ToChar(inputstring);
    switch (response)
    {
        case 'A':
        case 'a':
        //case A logic
        break;
        case 'B':
        case 'b':
        //case B logic
        break;
        //etc.
        default:
        //they enter something you're not handling
        break;
    }

}
while (inputstring != "Z")

Answer: This is the same situation as your other question: Do loops and while loops
You'll want to use an if statement or a switch statement to parse the user's input:
if (response == 'A')
{
    Console.WriteLine("Enter amount of sales");
    string salesStr = Console.ReadLine();
    Console.WriteLine(Double.Parse(salesStr) * COMMRATE);
    Console.WriteLine("Enter sales member to continue or Z to exit");
    response = Convert.ToChar(Console.ReadLine());
}

if (response == 'B')
{
    Console.WriteLine("Enter amount of sales");
    string salesStr = Console.ReadLine();
    Console.WriteLine(Double.Parse(salesStr) * COMMRATE);
    Console.WriteLine("Enter sales member to continue or Z to exit");
    response = Convert.ToChar(Console.ReadLine());
}

if (response == 'E')
{
    Console.WriteLine("Enter amount of sales");
    string salesStr = Console.ReadLine();
    Console.WriteLine(Double.Parse(salesStr) * COMMRATE);
    Console.WriteLine("Enter sales member to continue or Z to exit");
    response = Convert.ToChar(Console.ReadLine());
}

Also, you're declaring the string salesStr inside the scope of your while (or in my example, the if).  You won't be able to access it anywhere else.  Since you're repeating the same logic in each block, but with a different value, I would be inclined to move the repeating code outside it, and only put it in there once.  This way you only need to change one place in the future if the requirements change:
string salesStr;

if (response == 'A')
{
    Console.WriteLine("Enter amount of sales");
    salesStr = Console.ReadLine();
}

if (response == 'B')
{
    Console.WriteLine("Enter amount of sales");
    salesStr = Console.ReadLine();
}

if (response == 'E')
{
    Console.WriteLine("Enter amount of sales");
    salesStr = Console.ReadLine();
}

Console.WriteLine(Double.Parse(salesStr) * COMMRATE);
Console.WriteLine("Enter sales member to continue or Z to exit");
response = Convert.ToChar(Console.ReadLine());

Since each of these if statements is doing the same thing, you can combine them too:
string salesStr;

if (response == 'A' || response == 'B' || response == 'E')
{
    Console.WriteLine("Enter amount of sales");
    salesStr = Console.ReadLine();
}

Console.WriteLine(Double.Parse(salesStr) * COMMRATE);
Console.WriteLine("Enter sales member to continue or Z to exit");
response = Convert.ToChar(Console.ReadLine());

Comment: I have the same problem. I can start at A and goto B then E, but when I try to hit A again the program closes.
Comment: @randywhite30 - check out Val's answer above, it incorporates the loop to keep the program running until you hit Z.
Comment: +1 for the included lesson plan. @randy You're not looping your program, you're using the loops like if statements.
Answer: Look at the order your program flows in: first, it checks for As, and then it checks for Bs, and then Es, and then it exits.
It looks like you're not doing anything important with the ID of the salesperson yet, although I assume you will later.
Instead of three separate loops, you need one big loop that continues as long as the response isn't Z, and then uses a set of if(...) statements internally, or perhaps even a switch statement, to decide what to do with the ID of the salesperson.


What methods are there to determine when a violin string should be replaced?

Question: I am very new to the violin. I have broken a string just once - and it was while attempting to tune it.
The string breaking was rather surprising and powerful - I'm glad my face was not too close.
So, to avoid a similar incident while playing the violin, I'd like to know when would it be ideal to replace a violin string before it gets too weak.
A little search got me this site: http://www.howtodothings.com/sports-recreation/how-to-know-when-to-replace-violin-strings which lists some options:

I should listen carefully - if the string sounds wrong, it is probably because it is already weakening.

My problem with this is that I don't have a very well trained ear - I probably would never be able to notice this.

Watch for wear on the strings.

Is there a good reference image out there? I'm not entirely sure how a weary violin string should look like.

It becomes hard for your finger to move it across a string due to the wear.

I don't have much faith on my fingers.

Are there other clues? Particularly some that don't involve my ears? Is there, perhaps, some kind of timeframe?
Answer: I remember breaking my first string :) Almost hit my eye.. And I was super afraid to tell my parents.. (I thought I broke the whole instrument because I believed that the string was as much a part of the instrument as the neck or fingerboard)
I'd like to address your question by answering a few you didn't explicitly ask..
1. Why do strings break?
Obvious answer: when the string can no longer stretch to accommodate the level of tension placed on it. There are two primary factors that go into a string breaking:

The string's tension threshold: whenever tension is applied to something, its threshold is deteriorating. The more the tension, the faster this threshold lessens (think of pulling on a laffy taffy, and how it takes less force to rip it as you stretch it out). As stringed instruments place constant tension on the strings, the strings will naturally break at a lower threshold over time. As strings initially have a higher threshold than desired (as it affects tone), the time it takes to lower it to the desired threshold is called "breaking in" the strings, which you will often see described in string catalogs.
Tension: the string will break when it has reached the threshold described above. It theoretically can't break without some sort of tension, no matter how low the threshold (gravity is technically a source of tension, although it's quite insignificant when it comes to really small masses). In addition to physical items (pegs, bridge, etc) that provide tension, temperature plays a very important role in tension. A higher temperature causes the string to expand and the tension to lessen (as the string is technically longer), while a lower temperature causes the string to shrink and creates more tension.

2. What can I do to not break a string? The most common way to break a string is to simply turn the peg too far. To avoid this, there are two things you can do:

Tune down first when using the pegs: Tension often builds up based on various factors including changes in temperature. It's very possible that you're right at the threshold, and the string snaps as soon as you turn the peg even slightly higher. By tuning down first, you 'reset' the tension a bit and get a better feel for both the amount of tension on the string and how close you are to the threshold.
Use fine tuners: if you don't already have fine tuners, I'd highly recommend you get them. Whenever you're not too far away from the correct pitch, fine tuners make it easy to get a more precise pitch and reduces the risk of overshooting and breaking the string.

3. How do I know when to change strings? Using an objective method, the only two ways I can think of for knowing when to change a string is either when you can see the string wearing translated as sharp/rough spots on the string, or after you've already broken the string. But when we get into the more subjective area, there are a few ways, all which come with time and experience.
There are essentially two ways to tell that you need/want to change strings: the tension feels weird, and the strings don't provide the sound you want (anymore, or they never did in which case you'll want different strings anyways).
For both of these, you'll need to be in a place where enough of your playing has become second nature, and you're exploring more advanced stuff.
In order to be able to tell when the tension is wrong, you need to have been playing for long enough where it's just something you notice. It'll be most notable (in your left hand) when shifting and crossing strings.
Responsiveness and tonal quality are things that require you to know the sound of a violin and specifically your instrument very intimately. The responsiveness is essentially how easily the string responds to your bow. This is a quality that varies by strings and deteriorates over time. When the strings are not responding the way you want them to (and you are in a place where you know what responsiveness you want/how to achieve it), then it is time to change strings.
Tonal quality/timbre is generally measured for violins in  spectrum that ranges from warm/rich (produced more when strings are wound with gold) to bright/clear (produced more when strings are wound with silver). The tonal quality varies from instrument to instrument, and also from string to string. This is why it requires you to both know your instrument very well, and then also to know/have experimented with different strings. In retrospect, I don't think I could was even in a place to consider these until I had been playing for 7 years, with four on the same instrument. A few things to take into consideration when looking at tone are the instrument (wood/varnish/shape), bow(wood/shape/hair), and string (core/wound/gauge/tension). Essentially, when you stop getting the tone/response you want from your strings (and it's not your fault), then it's time to change strings.
Further Reading:

String Care: Pirastro Website (Click on the green icon at the bottom, select violin, and scroll down and read the manual)
How strings work: D'Addario Website (You'll find String Tension Explained on the left if you scroll down)
Nerd out about strings: Wikipedia article about strings

Let me know if you have questions about anything I said :)
Comment: Usable for players of other string instruments
Comment: It is an art to change strings at the right time. If the string loses its sound quality it can happen very gradually, which means you can get used to the sound without noticing that the sound quality changes. Then you suddenly "wake up" realizing that the string needs to be changed.
Answer: Here are three things that will clue you in when you need to change your strings.
1. How long has it been since you last changed strings?
If you play your violin for about 30 min to an hour every day, you will probably need to change your strings about once a year. Of course this will vary based upon the quality of the strings, climate, how you care for the instrument, how well you can tune it, etc. However, as a rule of thumb, a set of strings should last a beginning student about a year.
2. Do the strings look/feel strange?
As the strings age, you will notice dark spots forming on the strings. They will eventually start turning your fingers black when you play, and eventually they will even begin to unravel. If they becoming noticeably worn, you should think about replacing them. If the outer metal wrapping looks/feels loose, you definitely need to replace.
3. How do they sound?
I know you weren't looking for tips on hearing, but that's what will actually give you your first clue that your strings are getting old. The easiest thing for you to hear is the "ringing" that should accompany you playing your third finger on the D, A, or E strings. When properly tuned, you will make the G, D, or A string vibrate and cause a pleasant ring. As your strings age, they will begin to go false and that ringing will gradually go away.
Hope this helps.
Answer: In eight years playing violin I never learned a good way to tell when it was ready to replace. So when they snapped, I would replace them.
If they start to lose a bit of brightness in tone, then they are on the way out, but could still be good for months.
Answer: First off, often there's no real way to tell, because the weak point in the string could be anywhere - not necessarily between the bridge and neck. I'll change strings whenever I see a point that appears to be "going", but I'll still get some that snap at random times. Get used to it, it's hardly pleasant but I haven't lost an eye yet and I've been playing for almost 20 years ;)
However, when I have seen strings that have needed to be replaced, there's generally two main physical signs that manifest:

The string develops a kink, perhaps just a minor one, but one that's definitely noticeable when you run your finger across it. This is often due to the string's core buckling while the outer one (for now) stays relatively in tact. When you see this, replace it.
The outer thread of the string begins to unravel, exposing the core - an easy one to spot, but watch out for it because if you leave it then shift positions quickly across it, it can cause a nasty cut. Experience talking here, not pleasant!

Of course, sometimes you can hear audible symptoms too - despite what I read, I've yet to see a common pattern in how this happens, aside from saying that the audio quality changes, and not for the better. I've heard the same type of strings from the same manufacturer get duller, brighter, develop a buzz, a rasping sound, pretty much everything. (In one particular case, the rasp on my D string got so bad I could barely play a proper note, but visually the string looked fine.)
If you're a beginner, these audible signs will be harder to spot, so preferably get someone more experienced to check before you change over the strings for no reason. However, physical signs are easy to spot yourself - just give the strings a quick regular check.


Testing the significance of multiple variables in a data set

Question: My data set relates to goods sold. I have a unit price, qty sold at that price and a number of other variable, such as sales person, geography, marketing support. the qty sold varies throughout any sampled period of time irrespective of price. It also 'appears' to vary more when the price is changed-as common sense would sugggest.
What I would like to measure is the impact/significance of each of the other variables on the qty sold. I'm not a stats expert or coder butr have some experience/knowledge of using linear regression and correlation coefficients in my work
Comment: Are you trying to choose the best subset of predictors? If so, this falls under the general category called "variable-selection", which has been discussed on this site a lot - http://stats.stackexchange.com/questions/tagged/feature-selection. But, the sentence *What I would like to measure is the impact/significance of each of the other variables on the qty sold.* makes me think it may suffice to simply look at the marginal relationships between each variable and the response, as not mention of the "joint effects" is made.
Answer: Yes, substantially you should use a linear model, where 'qty sold' is the dependent variable and (initially) all the other variables are the predictors. You can also choose to not insert all the variables in the model, for example because you have theoretical resasons for which some variables are not important in this specific case. Bytheway, starting from your full model, then you should (step by step) reduce it, since surely not all variables will significally influence the dependent variable. Each time, you observe the changes in your model after the reduction, and decide whether continuing to reduce it or accept it. At the end of the process, you should have the more economic linear model that explains the behavior of your dependent variable.
If you want to use R, as suggested by Arielf (and also I suggest you to use it...), this is a guide that explains the basic commands.
Answer: this.is.not.a.nick's answer is good as a general and solid set of guidelines.
If you need a more exact howto recipe, here's a start:

Use R. It can be downloaded from www.r-project.org
write your data set into a CSV file where the 1st column is the target variable (say qty_sold) and the rest of the columns are the independent input variables
Once inside R you may load your data into a data-frame using the read.csv() function and run the lm() function to generate the model.
run a summary() on the model to get all the linear coefficients

And the actual minimalistic code example:
<code>    R> dat <- read.csv('my_sales_file.csv', header=T)  # read the data
    R> model <- lm(qty_sold ~ . , data=dat)            # learn the model
    R> summary(model)                                  # show the model
</code>
The above assumes that your CSV file 1st line is a header (column names), and that the target variable column is called qty_sold.
HTH


How to connect to internal server via WWW

Question: Was wondering if its possible to connect to an internal server on the domain via WWW?
Lets say the internal machine i want is at 192.168.10.200.
Its running IIS / Sharepoint or whatever, something that a webbrowser understands.
The external user has, lets say, 184.108.40.206 and this goes to the SBS server. When you get there it has several choices like outlook, a list of computers to connect to and finally an internal website. This internal website link should go not to the default but to the machine at 192.168.10.200. Surely this cant be done?
Comment: Huh? You really need to reword the question into something meaningful.
Comment: totally! sorry rushed ...
Comment: Im thinking at the moment perhaps something to do with proxy server or dns settings?
Answer: Found out how to do this after all. just set port forwarding to any of the attached ip's in the router.


creating random variable with certain auto-correlation in R

Question: I want to create a random variable with a given autocorrelation in R.
The target autocorrelation is defined by:
$$acf_{target}=(lag+1)^{(-b)}$$
with $b=1.41519$ which I derived from a natural dataset. You can see the function in the next plot generated with this code:
lag <- seq(0,52)
b <- 1.41519
acf.target <- (lag+1)^(-b)
plot(lag, acf.target, col="green", type="l", xaxs="i", yaxs="i", las=1, lwd=2)

Using the R approach shown in the answer to this question I created a random variable and then filtered the variable with my target autocorrelation function:
n <- 100000
var <- rnorm(n)
var_autocor <- filter(var, filter=acf.target, circular = T)

But if I calculate the autocorrelation of var_autocor I get a difference to the target autocorrelation function:
acf(var_autocor)
lines(lag, acf.target, col="green")

I calculate that the acf of the generated variable (var_autocor) has an $b_{result}=1.215306$ which slightly deviates from $b_{target}=1.41519$.
This deviation is more than I want and I don't understand why it appears. Do I use the filter function wrong? Do I have to give additional arguments? Or does someone have a totally different approach to create a random variable with the target autocorrelation?
Answer: In this case, each value returned by filter is a weighted sum of $m$ out of $n$ normal random variates $\{x_1,...,x_n\}$ with the $m$ weights, $w$, set equal to acf.target in the example provided by the OP. The $i^\text{th}$ term is:
$$y_i=\sum_{j=1}^m{w_j{}x_{\text{mod}(i-j+\lfloor(m-1)/2\rfloor,n)+1}}$$
The $i^{th}$ term returned by the acf function is:
$$a_i=\text{cor}(\{y_1,...,y_{n-i+1}\},\{y_i,...,y_{n}\})$$
$$=\frac{\text{cov}(\{y_1,...,y_{n-i+1}\},\{y_i,...,y_{n}\})}{\sum_{j=1}^mw_j^2}$$
$$\lim_{n\to\infty}a_i=\frac{\sum_{j=1}^{m-i+1}w_jw_{j+i-1}}{\sum_{j=1}^mw_j^2}\neq{w_i}$$
x <- rnorm(1e5)
b <- 1.41519
acf.target <- (1:53)^(-b)
w <- acf.target
n <- 1:(length(w) - 1)

y <- filter(x, w, circular = TRUE)
acf(y)
a <- c(1, sapply(n, function(i) sum(head(w, -i)*tail(w, -i)))/sum(w^2))
lines(seq_along(a) - 1, a, col = "green")

If $\{\alpha_i,...\alpha_m\}$ are the desired autocorrelation values, a naive approach would be to iteratively update $w_i$:
$$w_i'=w_i\frac{\alpha_i}{a_i}$$
This works for the OP's example:
tol <- sqrt(.Machine$double.eps)

while (max(abs(acf.target - a)) > tol) {
  a <- c(1, sapply(n, function(i) sum(head(w, -i)*tail(w, -i)))/sum(w^2))
  w <- w*acf.target/a
}

y <- filter(x, w, circular = TRUE)
acf(y)
lines(seq_along(acf.target) - 1, acf.target, col = "green")

Comment: Hi jblood94. I created a new [thread](https://stats.stackexchange.com/questions/610341/how-to-generate-a-standard-normal-distributed-time-series-with-a-given-acf) regarding this problem. Unfortunately your approach does only work for very specific ACFs.


How to create an array from a Obj in another array? JS React

Question: I want to build a self updating filter with checkboxes.
My Data:

const Shooting= [
    {
      name: "John & Johna ",
      tag: ["wedding", "couple"],
      img: [ src1 , src2, ...] //irrelevant
    },
    {
      name: "Mario & Marie",
      tag: ["couple", "NSFW"],
      img: [ src1 , src2, ...] //irrelevant
    },
  ];
  export default Shooting;

how my output should look like that:
Filter:
[]wedding
[]couple
[]NSFW
// [] are checkboxes, "couple" is a duplicate in the array

My code idea:

Get all tags into a new array
Build function to remove duplicates from new array
list the filtered array with map-function -> Obj.map((tag))=>{...}

My question:
How can I get all tags in a new list?
Answer: Create reduce function  with set

const Shooting= [
    {
      name: "John & Johna ",
      tag: ["wedding", "couple"],
    },
    {
      name: "Mario & Marie",
      tag: ["couple", "NSFW"],
    },
  ];

 const result = Shooting.reduce((acc, item) => {
   return [ ...new Set([...acc, ...item.tag]) ]
 }, [])

 console.log(result)
Answer: You can use a reducer to get all unique tags
const array = [
  {
    name: "name1",
    tag: ["tag1", "tag2"],
  },
  {
    name: "name2",
    tag: ["tag2", "tag3"],
  },
];

const tags = array.reduce((acc, item) => {
  item.tag.forEach((tag) => {
    if (!acc.includes(tag)) {
      acc.push(tag);
    }
  });
  return acc;
}, []);

Then with your tags you can do whatever you want. Good luck!
Answer: You can try with [...new Set(Shooting.map(({ tag }) => tag).flat(1))],
-> Shooting.map(({tag}) => tag) will give back the tags in array.
-> Then we can use array.flat() to concatenate the tags.
-> Then to remove duplicate, we use ...new Set(...) .

const App = () => {
  const Shooting = [
    {
      name: "John & Johna ",
      tag: ["wedding", "couple"],
      img: ["src1", "src2"]
    },
    {
      name: "Mario & Marie",
      tag: ["couple", "NSFW"],
      img: ["src1", "src2"]
    }
  ];

  const result = [...new Set(Shooting.map(({ tag }) => tag).flat(1))];

  return

 Filter:

      {
        result.map((list, i) =>
<input type="checkbox" /> {list}
 )
      }

}

// Render it
ReactDOM.createRoot(
    document.getElementById("root")
).render(
    <App  />
);


Não Remover Data Frame Específico

Question: Estou trabalhando com diversos DF (mais de 30), porém quero excluir todos, exceto um específico. Exemplo dos meus DF:
DF1

VCBGF2

FGFR3

BBTYI4

QQASX5

RRTPS6

DF7

TTIPMBBT8

DF9

DF10

Assim, quero excluir 9 DF's, exceto o DF 7. Como faço para manter somente o DF7?
Answer: A seguinte função não remove objetos de classe obj.class que correspondam a pattern.
keepObject <- function(pattern, obj.class, envir = .GlobalEnv){
  obj <- ls(envir = envir)
  obj <- obj[!grepl(pattern = pattern, obj)]
  i <- unlist(lapply(obj, function(o) inherits(get(o), obj.class)))
  rm(list = obj[i], envir = envir)
}

ls(pattern = "^DF")
# [1] "DF1"  "DF10" "DF2"  "DF3"  "DF4"  "DF5"  "DF6"  "DF7"  "DF8"
#[10] "DF9"

O padrão "DF7" corresponde a strings que contenham "DF7". Se quiser pode usar outras expressões regulares, como por exemplo "^DF7$".
keepObject("DF7", "data.frame")
ls(pattern = "^DF")
#[1] "DF7"

Dados.
DF1 <- data.frame(a = 1:10)
DF2 <- data.frame(a = 1:10)
DF3 <- data.frame(a = 1:10)
DF4 <- data.frame(a = 1:10)
DF5 <- data.frame(a = 1:10)
DF6 <- data.frame(a = 1:10)
DF7 <- data.frame(a = 1:10)
DF8 <- data.frame(a = 1:10)
DF9 <- data.frame(a = 1:10)
DF10 <- data.frame(a = 1:10)

Comment: Obrigado. Vou editar e especificar melhor minha dúvida. Desculpe.

Não Remover Data Frame Específico


$\lim_{x\to\infty} \sqrt{x^2 + 2x + 1} $

Question: I get $\lim_{x\to\infty} {x+1} = \infty $
But I am wrong. Why?
With L'Hospital, I get $$ \lim_{x\to\infty}\frac{1}{2}\sqrt{x^2 + 2x + 1} \cdot (2x+2) = \frac{1}{2} \sqrt{1} 2 = 1$$
Comment: You applied L'Hôpital's rule incorrectly.
Comment: I'd like to say how much the notation $\frac{1}{2}\sqrt{1}2$ *bothers* me! :-P
Comment: I am afraid you confused $\infty$ and $0$ (not counting that you *did not* apply L'Hospital at all).
Comment: The question is not in a form where L'Hopital's rule can be used.
Answer: If $x\geqslant-1$, then $\sqrt{x^2+2x+1}=x+1$ and therefore, yes,$$\lim_{x\to\infty}\sqrt{x^2+2x+1}=\lim_{x\to\infty}x+1=\infty.$$
And you cannot apply L'Hopital's rule, since you do not have an indeterminate form here.
Answer: The correct answer is
$$
\begin{gathered}
  \mathop {\lim }\limits_{x \to \infty } \sqrt {x^2  + 2x + 1}  =  \hfill \\
   \hfill \\
   = \mathop {\lim }\limits_{x \to \infty } \sqrt {\left( {x + 1} \right)^2 }  = \mathop {\lim }\limits_{x \to \infty } \left| {x + 1} \right| =  + \infty  \hfill \\
\end{gathered}
$$
De L'Hospital's Rule is for limits of the type
$$
\mathop {\lim }\limits_{x \to \infty } \frac{{f(x)}}
{{g(x)}}
$$
with
$
\mathop {\lim }\limits_{x \to \infty } f(x) = \infty
$ and $
\mathop {\lim }\limits_{x \to \infty } g(x) = \infty
$
under suitable hypothesis. This is not your case
Answer: Without L'Hopital's rule you can rewrite:
$$\lim_{x \to \infty} \sqrt{x^2 + 2x + 1} = \lim_{x \to \infty} \sqrt{(x + 1)^2} = \lim_{x \to \infty} |x+1|$$
Since $x$ is a large value, you can omit absolute value: $\lim_{x \to \infty} (x+1)=\infty$.
Answer: L'Hopital applies to the indeterminate forms $\infty/\infty$ or $0/0$.
In this case we have simply
$$\sqrt{x^2 + 2x + 1}\ge x\to \infty$$


How to dynamically load data into a sliding menu with SlideOverKit?

Question: I am creating a cross-platform app using Xamarin Forms 4.0 in VS 2019.
I need a slide up menu who's menu options change depending on the tapped cell date in a calendar selection. I've installed SlideOverKit to attempt to accomplish this. Getting the menu itself works, but changing the options dynamically isn't working.
How should I proceed?
As I said, I've tried passing in the dates, but I also tried saving the date to SecureStorage and requesting the string in the SlideUpMenu's loading method... I believe I may be hitting a 'life cycle of a view' issue.
Here, I pass the selected date from the content page to the slide menu view and a model containing data.
   public partial class PublicCalendarPage : MenuContainerPage
    {
        private CalendarModel _calendarModel;
        private bool _showDetails = true;

        public PublicCalendarPage(CalendarModel calendarModel)
        {
            InitializeComponent();
            Content.BackgroundColor = Color.White;
            BindingContext = new PublicCalendarViewModel(this, new ApiService())
            {
                CalendarModel = GetCalendarModel(calendarModel)
            };
            _calendarModel = calendarModel;

            SlideMenu = new ShowMealsView(new DateTime(), calendarModel.CalendarDays);
        }

        private CalendarModel GetCalendarModel(CalendarModel calendarModel)
        {

            //gets the model data via api call
        }

         private void Schedule_OnCellTapped(object sender, CellTappedEventArgs e)
        {
            SlideMenu = new ShowMealsView(e.Datetime, _calendarModel.CalendarDays);
            ShowMenu();
        }
    }

Below is the code behind for loading the menu
    public partial class ShowMealsView : SlideMenuView
    {
        private readonly List<CalendarDayModel> _calendarDays;

        public ShowMealsView(DateTime eDatetime, List<CalendarDayModel> calendarDaysList)
        {
            InitializeComponent();
            HeightRequest = 80;
            IsFullScreen = true;
            MenuOrientations = MenuOrientation.BottomToTop;
            BackgroundColor = Color.LightGray;
            BackgroundViewColor = Color.Transparent;
            _calendarDays = calendarDaysList;
            if (Device.RuntimePlatform == Device.Android)
                this.HeightRequest += 50;

            var layout = GetLayout(eDatetime);

            Content = layout;

        }

        private Grid GetLayout(DateTime date)
        {
            var layout = new Grid();

            // formats grid layout before the relevant code

            var dinnerGrid = new Grid();
            dinnerGrid.RowDefinitions.Add(new RowDefinition { Height = new GridLength(1, GridUnitType.Star) });
            dinnerGrid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(10, GridUnitType.Absolute) });
            dinnerGrid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) });

            var dinnerBox = new BoxView
            {
                VerticalOptions = LayoutOptions.Fill,
                BackgroundColor = Color.FromHex("#f3d176")
            };
            dinnerGrid.Children.Add(dinnerBox, 0, 0);

            //var selectedDate = SecureStorage.GetAsync("SelectedDate").Result;
            var selectedDateTime = date;
            var dinnerLabel = new Label
            {
                Text = "Provide Dinner",
                TextColor = Color.Black,
                HorizontalOptions = LayoutOptions.Center,
                HorizontalTextAlignment = TextAlignment.Center,
                VerticalTextAlignment = TextAlignment.Center,
                VerticalOptions = LayoutOptions.Center
            };

            if (_calendarDays.Any(x => x.ForDay == selectedDateTime.Date && x.Email != null))
            {
                dinnerLabel = new Label
                {
                    Text = $"A DINNER EXISTS!",
                    TextColor = Color.Black,
                    HorizontalOptions = LayoutOptions.Center,
                    HorizontalTextAlignment = TextAlignment.Center,
                    VerticalTextAlignment = TextAlignment.Center,
                    VerticalOptions = LayoutOptions.Center
                };

            }

            dinnerGrid.Children.Add(dinnerLabel, 1, 0);

            var table = new TableView
            {
                Root = new TableRoot { new TableSection { new ViewCell() { View = lunchGrid }, new ViewCell() { View = dinnerGrid } } },
                Intent = TableIntent.Data
            };

            layout.Children.Add(table, 0, 0);

            return layout;
        }
    }

Initial loading returns "Provide Dinner"
Once a selected date is made on the content page, the menu selection should include "A DINNER EXISTS!"
However, even though a debug shows that dinnerLabel.Text might equal "A Dinner EXISTS", what is actually showing on screen is always "Provide Dinner"
UPDATE:
I've switched to using ObservableCollection, using that collection as a ListView itemsource because I keep reading that ListView automatically updates its views depending on what data is in the list. (if anything is added or removed)
This does not work, but I'm willing admit I may be doing it wrong as I've never used ListViews...
Essentially I'm still getting ONLY original state of the view which only shows "Provide Dinner"; and again when debugging the property assigned in the model does have the value "A Dinner Exists!" ... so getting the same result with this different method
Answer: I think it's a limitation of SlideOverKit and you can't change SlideMenu dynamically.
I download the sample and use your code to test. I meet the same problem with you.
Then I find a similar issue here on Github, the Author recommend you to use binding IsVisible to show different view in a single slide menu.
Later, I find another issue here about change SlideMenu dynamically and the author said:

Well, it cannot be add, cause of OnAppearing will be called after
  OnElementChanged. How about change the content in MenuView in runtime?
  Like set IsVisible for ViewA and un visible for ViewB
Comment: That is actually the route I've gone, with the IsVisible boolean. It just seems so... gross.
Comment: @CSharpMinor Did you see the source code?  You can modify it to meet your requirement.


Extend boot partition in lvm on Centos 7

Question: I have a CentOS 7 with a Boot Partition  of 400M as number 1. And after that I have a root Partition of 50G as number 2. What would be the steps to extend the Boot volume with parted or so ?
Kind regards.
Answer: Using any backup utility you'd like, You would need to backup your root partition to another drive. Then you can reinstall CentOS with a larger boot partition.
Before you do all that, You should attempt to clean up your boot partition and remove the extra files.
CentOS 7 package-cleanup -y --oldkernels --count=1 && package-cleanup -y --cleandupes
CentOS 8+ dnf remove --duplicates