Excel crashes when loading file that contains userform

Question: Excel crashes when opening files that contain a userform
This is a known problem with a known solution workaround which is to delete a file called Excel.box from here:
C:\Users\SlowLearner\Application Data\Microsoft\Forms\Excel.box
According to this forum post the purpose of the Excel.box (& Word.box) file is:

Files such as Winword.box and Excel.box are associated with the
  Control Toolbox you see when you are designing a UserForm in the
  Visual Basic editor. The files contain information about the layout of
  the Control Toolbox (additional tab pages, controls that have been
  added or removed, custom icons, ...) If a user has never modified the
  Control Toolbox in any way, there will probably be no .box file. By
  deleting a .box file, you will restore the Control Toolbox to its
  default (factory preset) configuration - this is the only way to do
  that. Sometimes, the .box file becomes corrupted and must be deleted.
  There are no negative side effects to deleting it.

Unfortunately Excel.box returns :(
It would seem that for most users the problem is fixed by deleting the file, sadly not for me.
I'd like to understand what is causing this problem to recur. A few points to note:

this (touch wood) is not impacting MS Word on my PC
I am using Office 2010, 64 bit version on Win10
I have not made any conscious change to form settings
if I delete the file > start Excel > UN-DELETE the file: everything works :-/
some other experiences with this issue here

For the time being I'll just check for and delete the file before launching Excel, but this is hardly an acceptable solution for the long term. Appreciate thoughts for a proper fix...  TIA

Additional Information:
I have not fully explored the crash but so far it happens when:

starting the application by opening an xl?.m file with a userform

application does not get past the splash screen
crashes with the application's CRASH screen (... encounted an error...)

starting the application with a blank worksheet then adding a userform

crashes immediately with the applications CRASH screen displayed (see below)

The above crash happened after rebooting my PC, had a chance to explore it some more.

First I opened the file I had been working on (contains userforms):

annoyingly it opened without crashing
I did NOT enter the IDE
I closed the file (Excel closed normally)

Then I created a new worksheet

I opened the VBA IDE
right-click 'add UserForm' - Excel crashed immediately
(I aborted the recovery / search for a solution attempt)

Then I re-opened the file I had been working on

opened the VBA IDE (the project is PW protected)
the very instant that I entered the PW and hit enter Excel crashed
crash was same both times...

Safe Mode:
Crash still happens in safe mode - steps to reproduce:

Run: Excel /safe
Open VBA IDE
r-click add userform
crashes immediately

Creation of the EXCEL.box file
Based on visually observing the folder which had the Excel.box file I did some tests to try and see when it was created.  Basically it seems to appear when one of the following happens:
 - the UserForm tools box is closed
 - the IDE is closed (after showing the userform)
I've also now tried to modify the userform toolbox by removing everything from it. Excel is still crashing after every restart of the application (which is odd as I was not able to crash it like that earlier).

Office Repair - not tested (yet)
Reluctant to try Office Repair as based on the following quote from here (scroll down: pg 1 reply 8 by Steve IT)  I'm not expecting it to work :-/ (but will try if no other suggestions surface).

Thanks for the continued suggestions, however I have tried a repair and also removed Visual Studio 2013 and Office altogether (just in case VS was interfering) and reinstalled both, but it still throws the errors reported previously.

Other user profiles
Created a brand new user called 'test'. Test has the exact same problem.
Comment: @Mat'sMug have added extra info. Now, perversely, I am unable reproduce the crash so will reboot and see what happens :-/
Comment: @Mat'sMug - crashed after reboot, see update.
Comment: Does it crash when Excel is launched in Safe mode (`Excel.exe /safe`)?
Comment: @PatricK yup, have updated. Was expecting it to crash based on the research I had already done, but it is now confirmed. Cheers
Comment: Repair Office install is my next step, could also be some corrupted dll/ocx files.
Comment: @PatricK - not ruling it out but... see update.
Comment: Tested from logging in a new/different user on the machine?
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/157249/discussion-between-slowlearner-and-patrick).
Answer: This problem eventually resolved itself, not sure why.  I continued to use Excel normally and it continued to crash so I would delete the offending .box file and start over...
As of Nov 2017 Excel no longer crashes with respect to this issue; my best guess is there was an automatic update that resolved the issue.
Answer: Looks like this issue still occurs and it is not just limited to Excel but also Powerpoint.
The fix as mentioned above works where you move / delete any files in the below folder location resolves the issue.
    C:\Users\%username%\Application Data\Microsoft\Forms

It is highly likely that this error is caused by bad code in a macro or an Add-In that uses forms. The problem is replicating this can be difficult so you have to debug this in some way when it does crash out.
    POWERPNT.box
    EXCEL.box

are some of the files that get generated, where Excel or Powerpoint crash on the splash screen.
Comment: I don't think this is caused by bad code _in the VBA project_. None of my code was changed and the issue fixed itself. Actually, the code was working when it was last saved and something happened in the interim. Also it was confined to a single PC, other PCs ran the same code without issue. It could be caused by the project becoming corrupted... but I think I ruled that out at the time too....
Comment: I don't necessarily point to bad code in the project as such, just in some Add-Ins that may also be loaded. I have seen stuff such as debug versions of add-ins with break points in there and sort of had a (facepalm) moment.
Comment: Sure, but I can tell you that, in my case at least, there were no additional addins loaded for Excel, I basically don't use it - mostly use Word. As far as my Excel is concerned NOTHING changed. My VBA IDE Add-ins are: MZ Tools (latest ver) & Rubberduck both of which are excellent and apply to all VBA IDEs. All I can tell you is the code did not change, the IDE addins may have but I'm reasonably sure they did not cause the issue. I also ruled out buggy code because the issue happened with ONLY a NEW worksheet open. I dislike not knowing what the cause is, but... it ONLY impacted Excel so ??
Comment: @SlowLearner what antivirus do you use? I find there maybe some interactions going on with this that maybe impacting this as well.
Comment: Trend Micro - but I don't think it was involved because it would crash when adding a UF to a blank document... but... hey?
Comment: Yea...check the Heuristics level or any particular Office specific checks. I have seen some stuff that can seriously interfere without you even realising it.
Comment: Well if it happens again, at least I've got a new angle. What AV are you using?
Comment: We are using Bromium which is like a next gen AV.
Comment: Hi Add too quickly. You should have a look at how it works. Really good as an AV
Answer: Try adding the command
ThisWorkbook.VBProject.VBComponents("UserForm").Activate

just before your
"UserForm".Show line.


Pull value from hash reference

Question: I am using Perl and SOAP::Lite to pull ticket information from a system called OTRS.
At the moment we have a web service set up on OTRS called GetTicket.
We've managed to get SOAP:Lite to connect to the web service and pull the ticket information. The ticket information comes back as hash reference.
I am not creating a hash reference inside of the code, that is just what is being returned. How do I pull apart that hash reference if I haven't created it?
At this point we are trying to loop through the hash reference using foreach. I will post my progress as I go through it, but as usual, any advice is appreciated.
Perl Script
#!perl -w

use SOAP::Lite;
$ENV{PERL_LWP_SSL_VERIFY_HOSTNAME}=0;

use Data::Dumper;
print Dumper(SOAP::Lite
    -> proxy('https://ost-otrstest.ostusa.com/otrs/nph-genericinterface.pl/Webservice/Test/GetTicket')
    -> GetTicket()
    -> result);

Output
$VAR1 = {
         'ErrorCode' => 'TicketGet.AuthFail'
         'ErrorMessage' => 'TicketGet: Authorization failing!'
        };
Press any key to continue...

EDIT: Added dumper and received an authorization error. We do have a user name and password, at this point I'm just not sure where to put that.
Comment: Check out the [Perl references manual](http://perldoc.perl.org/perlref.html).
Comment: @daxim Do you have any idea on how to fix the AuthFail error that the OP is getting.  I can't think of anything I haven't used Perl in so long.
Comment: The code in your question is garbled.
Comment: @hobbs I just noticed I messed up a few lines, let me edit and fix it.
Answer: SOAP::Lite relies on LWP::UserAgent for a lot of its http functionality, including the behaviour when authorization is requested.
The documentation for LWP::UserAgent says this

[get_basic_credentials] should return a username and password. It
  should return an empty list to abort the authentication resolution
  attempt. Subclasses can override this method to prompt the user for
  the information.

So you need to overload LWP::UserAgent::get_basic_credentials by writing a new SOAP::Transport::HTTP::Client::get_basic_credentials.
Overloading this method is described in the SOAP::Transport documentation. You need to write this
BEGIN {
  sub SOAP::Transport::HTTP::Client::get_basic_credentials {
    return ('username', 'password');
  }
}

anywhere in your program. At the top is probably tidiest. (The BEGIN block forces the new method definition to be implemented before execution starts, regardless of its position in the program.)
I hope there is a better solution as I'm not very happy with this solution: it is an ugly piece of Perl programming. You may be better off subclassing SOAP::Lite altogether to make the interface a little tidier.
Comment: Ok, I'm experimenting with this now but still getting the authorization error. To me this looks like it is returning a username and password, is this true? If not, am I supposed to pass in the username and password I have?
Answer: my $result = SOAP::Lite
    -> proxy('https://ost-otrstest.ostusa.com/otrs/nph-genericinterface.pl/Webservice/Test/GetTicket')
    -> GetTicket()
    -> result;

To get one hash value:
my $errorcode = $result->{ErrorCode}; # TicketGet.AuthFail

To loop through them:
foreach my $key (keys %$result) {
     print "$key: " . $result->{$key};
}

Comment: That's exactly what we were doing with our code before but we are still getting that authorization error. As I said, I do have a username and password, I'm just not sure how to pass that information through SOAP::Lite. Do you have any thoughts on how to do that?
Comment: You asked how to use the hash reference that was returned. I answered the question. Maybe you should edit your question.
Comment: Actually, it had been edited prior to you posting this answer. But thank you for your input.

Pull value from hash reference


How do I filter a mongo collection on nested field value?

Question: I have a meteor collection with the below structure. This actually comes from a Meteor-files collection by ostrio.
{
 "_id" : "HsXoZ6bxkx5kMcJtm",
"name" : "trees.jpg",
"meta" : { "artist_id" : "QkmYdsZsMmRzqTg58" , "artist": "some name"},
"mime-type" : "audio/mp3",
"userId" : "QkmYdsZsMmRzqTg58",
"_collectionName" : "images"
}

I define a publication
Meteor.publish('files.artist', function publishUserImages(){
   return Images.find({meta: {artist_id: this.userId}).cursor;
});

I want to filter on the meta key, to return all items with artist_id.
My current filter will get only those Images where meta has the exact value {artist_id: "QkmYdsZsMmRzqTg58"}. The filter won't return the item shown above since it the meta value has an extra key artist
How do I construct an appropriate filter?
Answer: You can use the dot notation to query a nested field
Meteor.publish('files.artist', function publishUserImages(){
   return Images.find({ 'meta.artist_id': this.userId}).cursor;
});

The difference is that your query requires whole subdocument match while using dot notation you're just checking one subfield equality.


What type of bolt has a shoulder portion above and unthreaded region below threads?

Question: I have a couple Rex folding lounge chairs:

However, during my move one of the bolts connecting the base to the side came loose and was lost. I took out the one from the other side and I've never seen something like it and I'm not sure where to find a replacement. It has larger diameter shoulder portion above the threads and a narrow. unthreaded region below the threads. It's got a low profile slotted pan head. The narrower lower unthreaded region runs up and down in a groove in the leg when the chair folds/unfolds.
Here is a picture of the bolt:

What is this called? Anyone know where to order one?
Comment: The term is `pivot bolt`, but this is a specialized type that is custom made for this application.
Comment: If you bought it new, for what you paid for it, they should send you a replacement bolt.
Comment: @paperstreet You could probably fake one up using a drill-press, a bit of plastic tubing for the chuck to grip onto and a hand file. Cordless drill might even suffice if you clamped it down somehow.
Comment: That looks like a pretty special unit to me I doubt you'll find one at home depot. It doesn't look like anything a skilled machinist couldn't fashion out of a carriage bolt on a lathe though, might be worth the phone call?
Comment: I would of suggested drilling it out to use a standard bolt but looking up Rex chairs after DA01's comment, they had *better* send you one.
Answer: You are not going to find this on a shelf, you may get one from the manufacturer of the chair, if you talk nice and beg. Otherwise the chance is slim.
I would get a pan or philister head machine screw with the threaded portion about 1" longer than the screw pictured is over all. Chuck 3/4" of the threaded end in a drill and crank it down. Turn on the drill, keep it steady and run a file to grind off the threads exposed beyond the drill chuck to smooth the shank like the one in the picture. Since the screw is longer than needed and the drill damaged the end of the threads to hold it while it was spinning, cut it off and soften the corners like the original.
The drawing I referred to earlier
Comment: This will get the beginning of the thread between the bolt head and the smoothed part slightly damaged. To prevent that you drive a nut onto the thread and once grinding is complete you drive the nut away and it kind of restores the thread - see this http://diy.stackexchange.com/q/12465/807 for more details.
Comment: If you wish to call the burs created by the file as damage, so be it. I have used files to create the leading thread for nuts to start on. Just as you suggested, a nut can be placed on the screw first before it is chucked into the drill. That way of removing it will clear the bur/damage. IMHO, the portion of shank that has been cleared of threads will act as a guide to allow the nut to go right on. Cross-threading will not be the issue here, which is usually the concern when grinding or cutting something with threads.
Comment: You could suggest that if the bolt that the OP goes to buy has threads farther up to the head than the original it may be a good idea to fill the extra part of the threads with epoxy to smooth the upper shank of the bolt so it does not cut the wood in the bolt hinge hole. I would suggest gobbing on plenty of the epoxy, such as JB Weld brand, and then after it is fully set up you can use the drill idea to spin the bolt and file off the excess epoxy to get a nice smooth round upper shank.
Comment: Sharptooth, please reread the part about the bolt being 1" longer than needed, and chucking that into the drill only 3/4" That gives a 1/4" play to cut it off with no damage.
Comment: @Jack: I've read that carefully. I'm talking about the thread part that is closer to the head, not the part which will be cut off. Both are damaged when you grind and the former needs to be restored, otherwise how will you use the bolt?
Comment: I will make a drawing to illustrate in a while. The drill chuck will not touch any other part of the threaded section.
Comment: @Jack: The chuck will not, but the file will. No matter how carefully you grind the threading will be damaged slightly and will need restoration.


Why do I die when I run "/kill @e [type=!player]"?

Question: When I put
/kill @e [type=!player]

in a command block and power it, I die, even though players should be excluded. I need this command to be able to reset my mini-game map, but I don't know how to do it! Am I doing it wrong?
I've found other websites that say its just like that, so I don't know what I'm doing wrong.
Comment: Are there any other command blocks hooked up with a `/kill` command that could be causing trouble?
Comment: @RavenM nope. Its the only one. I literally just have a lever attached to some redstone and the command block .-.
Answer: I have found your problem.
Your command has a space between the @e and the type selector. Simply remove this space, and don't forget to capitalized the P.
Correct command: /kill @e[type=!Player]
Comment: @xXPikminXx Why do you have several kill commands? To kill different things?
Comment: If this helped, please mark it as accepted.
Comment: Also to note: The first letter, `p`, needs to be capitalized to work.
Comment: Sorry, missed that too. Edited.
Comment: Also @AngusAtkinson , is there able to be more than one /kill command block near it with the same redstone current? I'm trying that and its not working .-.
Comment: @xXPikminXx It should work. Is the redstone actually powering the block? Does the command have a Capital P and not space? If your not sure about the power, replace the command block with a redstone lamp to check.
Comment: @AngusAtkinson Its not. It worked perfectly fine with other commands and a redstone lamp, but I guess its just the way the /kill command works .-.
Comment: no so I can keep from killing certain things like zombies and players. @AngusAtkinson
Comment: Let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/23032/discussion-between-angus-atkinson-and-xxpikminxx).


is a scene graph actually a tree?

Question: All "scene graphs" I've seen in practice are actually trees, but I have some vague memories about somebody saying a while ago that sometimes they can actually be graphs (technically, trees are already graphs, but you get the point).
If they can actually be graphs, what are some practical examples?
If they're always just trees, is there some history behind why it was originally called "scene graph"?
Comment: Any time you have instancing in your scene, i.e. multiple copies of the same base geometry, you can represent that as a single leaf node with multiple transformation nodes as parents.
Comment: I completely missed that common use case, that's a very practical and clear example. Thanks.
Comment: @Rahul You should post that as an answer, even though it's short. It's exactly the example the questioner was looking for.
Answer: Yes, scene graphs can be non-tree graphs. Your question is a little vague, but assuming you're talking about something like the scene graph in rendering a frame of video, for say a feature film, then yes, there are often references between objects. For example, in a compositing application, you might have a piece of footage with an effect applied. The effect may have as one of its inputs another piece of footage which is also in the scene. (It might use the other image for blending, as a reflection map, as a diffuse or specular lighting map, a bump map etc.) So you could have a scene that looks like this:
scene contains:
    footage A contains:
        filter "Multiply Blend" which takes input:
            footage B
    footage B
    footage C

In something like a game, you might objects that refer to other objects that they can collide with:
scene contains:
    ground which can collide with:
        player
        ball
        goal
    player which can collide with:
        ground
        ball
        goal
    ball which can collide with:
        player
        ground
        goal

etc.
Comment: Sorry, my question was indeed a little vague. I had in mind scene graphs for 3D rendering. The collision examples are a bit too much into the app-specific side of things from my point view. At the app level, it's easy to imagine almost anything as a graph of relationships between different objects. However, as pointed out by @Rahul, one example is when multiple nodes with different transformations share the same geometry, in that case it's a non-tree graph.

is a scene graph actually a tree?


How does the "Art of War" resistance order in Xcom 2: War of the Chosen work?

Question: "Art of War" is a Templar resistance order that states that "ability points gained by promotion are increased by 25%"
Is this order retroactive?
If I increase a soldiers Combat Intelligence will the order give me bonus ability points?
Is there a way to force the game to re-calcualte the soldier's ability points with the resistance order?
Answer:
Is this order retroactive?

No. The "Art of War" order only has an effect on promotions that occur while the order is active. This is not retroactive.

If I increase a soldiers Combat Intelligence will the order give me bonus ability points?

Yes. The covert operation that allows you to increase the combat intelligence of a soldier will retroactively give you all the "missed" bonus ability points from earlier promotions.
I'm not sure if you can combine the two. It's possible.
If you send a soldier on a combat intelligence increase mission while the "Art of War" order is active, then he will receive the "missed" ability points (as discussed earlier).
It is possible that this recalculation (at the time of completing the covert operation) takes "Art of War" into account, and thus also gives you missed "Art of War" bonus ability points.
If this is the case, it does seem like unintentional behavior, and either a bug or an unforeseen consequence of the retroactive calculation process.


Mixing YAML and Markdown

Question: I am using YAML quite a bit, but I want to be able to include links. I tried Markdown links in a YAML file, but the entire punctuation is displayed.  I tried YAML formatting in a Markdown file, but there is no indentation in the YAML lines. I am open to a paid program, but I'd rather try an open source program first.  Thank you.
I did a number of browser searches, and I experimented with some things I found.
Answer: A link is just a data point. YAML is a data serialization format. You can of course write
<code>url: https://example.com
</code>
and YAML will parse it as mapping that contains a URL (the URL will be most likely a string unless you write a custom constructor). YAML doesn't render or display anything; applications that use YAML might allow you to process YAML input to displayed output, but that would be a question about that specific application and cannot be answered generally for YAML.
If you want to include YAML in a Markdown file and render it with indentation, use a code block, e.g.
<code>```yaml
some:
  yaml: data
```
</code>
Comment: > _If you want to include YAML in a Markdown file and render it with indentation, use a code block..._

Yes, this is exactly the answer I was looking for.  The YAML code block renders the Markdown links without the punctuation marks.  Thank you, flyx.

Mixing YAML and Markdown


How to build an Android Studio project cloned from git?

Question: I'm building a library for Android in Android Studio. In order to test and debug this library, I created a project with two modules: a library module (my code) and an app module (for testing)
Creating these was pretty easy. I just clicked File > New... > Project and followed the prompts. Afterwards I was able to write code, hit build, and observe the results in the app that was generated.
After a couple of months, everything was ready to deploy. I've been regularly committing my code and pushing it to a central repository, so another developer at my company cloned the repository and tried to open it in Android Studio. He was met with an entirely different view.
This is what I see:

This is what is seen if you clone the repo and open it:

When looking at the second view there's no way to build the project, there are no build configurations, no variants, and none of the gradle scripts seem to run.
If instead of cloning I just cp -r my entire project directory and open that in Android Studio, it opens perfectly. So the issue seems to lie with something in my .gitignore hiding an important configuration file necessary to build the project.
The .gitignore was generated for my automatically by Android Studio. It looks like this:
*.iml
.gradle
/local.properties
/.idea/caches
/.idea/libraries
/.idea/modules.xml
/.idea/workspace.xml
/.idea/navEditor.xml
/.idea/assetWizardSettings.xml
.DS_Store
/build
/captures
.externalNativeBuild

Everything there should be files generated by the build tools or local workspace configuration files, not project-level files necessary to compile. But I'm not very familiar with Android, its build steps, or the 800,000 things Android Studio is implicitly and secretly doing behind my back. Just opening the project in Android Studio causes 12 or so files to get modified on disk, so I know that it's doing a lot of things behind my back.
I can share any details about my configuration or project setup as necessary. I've spent a few hours on this already and can't figure out for the life of me how to get this project to build.
Answer: While it's probably not the proper solution (after all, Android Studio created the .gitignore for me), I found that removing /.idea/modules.xml from the .gitignore and checking in this file fixed all of my issues. Suddenly when I launched Android Studio it detected everything, some Gradle scripts ran, and I was able to build my project.


Get Apple Keychain to recognize Bouncy Castle .NET created PKCS12 (.p12) store

Question: Our organization manages a stable of iOS applications for multiple clients, which means dealing with a lot of different developer identity certificates and push notification certificates.
I have had success with the Bouncy Castle C# Crypto API in simplifying management of the certificates and private keys for push notifications, essentially eliminating the need for the Keychain for all our push notification certificates.
I would like to extend this to the developer identity certificates.  The goal would be to store all the private key and certificate information in the database for each developer identity.  Then when a new developer or build machine needs to be provisioned, server side code could wrap all of the certificates and private keys into one p12 archive with one password that could be imported into the target Mac's Keychain.
Unfortunately, the Mac Keychain doesn't like the p12 files I'm generating.  This is annoying since I can successfully import these files into the Windows certificate manager just fine.
The code I'm using (the important parts) looks like this:
private byte[] GetP12Bytes(List<DevIdentity> identities, string password)
{
    Pkcs12Store store = new Pkcs12Store();

    foreach(DevIdentity ident in identities)
    {
        // Easiest to create a Bouncy Castle cert by converting from .NET
        var dotNetCert = new X509Certificate2(ident.CertificateBytes);
        // This method (not shown) parses the CN= attribute out of the cert's distinguished name
        string friendlyName = GetFriendlyName(dotNetCert.Subject);

        // Now reconstitute the private key from saved value strings
        BigInteger modulus = new BigInteger(ident.PrivateKey.Modulus);
        BigInteger publicExponent = new BigInteger(ident.PrivateKey.PublicExponent);
        BigInteger privateExponent = new BigInteger(ident.PrivateKey.Exponent);
        BigInteger p = new BigInteger(ident.PrivateKey.P);
        BigInteger q = new BigInteger(ident.PrivateKey.Q);
        BigInteger dP = new BigInteger(ident.PrivateKey.DP);
        BigInteger dQ = new BigInteger(ident.PrivateKey.DQ);
        BigInteger qInv = new BigInteger(ident.PrivateKey.QInv);
        RsaKeyParameters kp = new RsaPrivateCrtKeyParameters(modulus, publicExponent, privateExponent, p, q, dP, dQ, qInv);
        AsymmetricKeyEntry privateKey = new AsymmetricKeyEntry(kp);

        // Now let's convert to a Bouncy Castle cert and wrap it for packaging
        Org.BouncyCastle.X509.X509Certificate cert = DotNetUtilities.FromX509Certificate(dotNetCert);
        X509CertificateEntry certEntry = new X509CertificateEntry(cert);

        // Set the private key and certificate into the store
        store.SetCertificateEntry(friendlyName, certEntry);
        store.SetKeyEntry(ident.PrivateKeyName, privateKey, new X509CertificateEntry[] { certEntry });
    }

    using (MemoryStream ms = new MemoryStream())
    {
        store.Save(ms, password.ToCharArray(), new SecureRandom());
        ms.Flush();
        byte[] p12Bytes = ms.ToArray();
        return p12Bytes;
    }
}

Like I said, this works great for import on Windows, but fails with a very generic error when importing into the Mac Keychain.
There is one major difference I can see when loading a Keychain-generated p12 and my own generated p12 file, but I do not know if this is the cause.
If I load the Mac Keychain generated p12 into a Bouncy Castle PKCS12Store, and then examine the keys, on the Keychain p12, both the certificate and the private key have an attribute with the key "1.2.840.1135188.8.131.52" with equivalent values (a DerOctetString with value #af8a1d6891efeb32756c12b7bdd96b5ec673e11e).
If I do the same to my generated p12 file, the private key contains the "1.2.840.113518.104.22.168" attribute, but the Certificate does not.
If I Google "1.2.840.1135126.96.36.199", I find out that this OID means PKCS_12_LOCAL_KEY_ID .  My only theory is that the Keychain relies on this to match up the certificate and private key, and that my generated file does not have this, so it fails.
However, I've tried adding these values to a Hashtable and then using the CertificateEntry constructor that takes the attribute hashtable.  If I do that, and then save the bytes, and then reload the bytes, that attribute is again missing.
So I'm flummoxed.  Maybe this attribute is a glitch in the Bouncy Castle API?  Maybe there's something I'm doing wrong.  Maybe the Keychain has ridiculous non-standard requirements for incoming p12 files.  In any case, any help that could be provided would be greatly appreciated.
Comment: Hi David, Did you get around fixing this issue???
Answer: BouncyCastle's Pkcs12Store takes care of setting both the Friendly Name and Local Key ID attributes for you (or at least it does so in the 1.7 release, circa April 2011). My guess is that you must have used an older version where this didn't work.
Here's how I'm saving an iPhone Developer identity to a Pkcs12Store instance (extra stuff and security omitted):
var store = new Pkcs12Store();

// pairs is IEnumerable<Tuple<X509Certificate, AsymmetricKeyParameter>>
foreach (var pair in pairs)
{
    var cn = pair.Item1.SubjectDN
         .GetValueList(X509Name.CN).OfType<string>().Single();

    var certEntry = new X509CertificateEntry(pair.Item1);
    store.SetCertificateEntry(cn, certEntry);

    var keyEntry = new AsymmetricKeyEntry(pair.Item2);
    store.SetKeyEntry("Developer Name", keyEntry, new[] { certEntry });
}

store.Save(stream, string.Empty.ToArray(), new SecureRandom());

Importing the store in Keychain Access.app on OS X 10.7 correctly places the certificate and private key in the keychain and places the certificate within the private key in the UI, as with a certificate and key generated by Keychain Access itself.
On a side note, it seems that Pkcs12Store uses the public key of the certificate to generate the value of the LocalKeyId attribute shared by the certificate and key entries.
You can see the relevant section of the Pkcs12Store source here.


How do I fix my bathtub knobs that rotate the wrong way after cartridge replacement?

Question: I replaced both hot and cold delta cartridges on my bathtub and now I have no leaks but they turn on and off backwards. What to do? Thanks.
Answer: I replaced o-rings in my tub faucets & diverters a few weeks ago. I put them all in backwards so they turned the wrong way. I opened everything back up, flipped them over (two alignment tabs, 180° opposite each other) and now they work as expected.
I'm more than willing to bet that your cartridges can, and have been, installed backwards and that flipping each one to the 180° opposite rotation will fix the problem.


Unable to execute dex:Multiple dex files define

Question: When build android project , I get the following error. I want to use jdbc driver to connect sql server.
<code>[2014-12-02 10:17:40 - Dex Loader] Unable to execute dex: Multiple dex files define Lcom/microsoft/sqlserver/jdbc/ActivityCorrelator$1;
[2014-12-02 10:17:40 - SQL_WCF] Conversion to Dalvik format failed: Unable to execute dex: Multiple dex files define Lcom/microsoft/sqlserver/jdbc/ActivityCorrelator$1;
</code>
Answer: Go to order and export tab possibly it should like this :

Make sure :

jar in order and export are checked.
dont add multiple or duplicate lib.


DIY Installation of 220v for spa

Question: I'm thinking of installing a spa at my house but the additional wiring for 220v is going to cost around $1k and I was wondering whether it's something I could attempt to do myself?
Comment: Yes, you certainly could.  Be sure you understand how it needs to be done to be safe and comply with building and electrical codes.
Comment: We all attempted to do it ourselves  at one point or another, and without this site. So, yes you could.  Do your homework and ask questions before you get into trouble. You would be smart to get some professional help when doing work inside your main electrical panel.
Comment: Buy wire last, and *after* you asked us to review your plan and work.  Run a ground.
Comment: Can you provide us with more details of your situation?
Answer: A 220/240 GFCI supply for a spa is not difficult. There are several ways to accomplish this. One of the more common is to get a "spa panel" that can be located close to the spa and serve as the disconnect and GFCI. These usually cost under $120, plus the feeder wiring. Many home DIY books cover the requirements, but it is a good idea to read up and ask questions first. Many states allow a homeowner to pull permits and do the work themselves. A few states require licensed electricians. So it is best to read up and find out what your local rules are. Call your local permitting office and ask what they require. Asking additional questions here can also help you out.
Yes this is something that is good to know, and it can save you hundreds in most cases and over a lifetime possibly many thousands.
Answer: We all attempted to do it ourselves at one point or another, and without this site. So, yes you could. Do your homework and ask questions before you get into trouble. You would be smart to get some professional help when doing work inside your main electrical panel.
Answer: Before getting started, do you know what the safety procedures are?
You need to know how to not get killed. Working on AC can very much make you dead.
This is the basic starting point: what can kill me at this phase of the DIY?
Once you are knowledgeable about the safety, do it at a pace that you're comfortable with, and without skipping any steps. Double and triple check everything, and don't skip any safety equipment.
If you are familiar with DIY projects, then this should be pretty standard, but the motivating factor should not be money. It should be your own satisfaction and comfort in doing this. $1,000 is not worth killing yourself over.

DIY Installation of 220v for spa


Compactor ram won't quit going down

Question: I've got a trash compactor with ... issues.
I came home from work to a report from my kids that it was "broken", and was making a horrible noise. All I knew was that the ram wasn't moving at all, and if you pushed the button the motor would make noise until someone manually turned it off.
I opened up the bottom, and one problem was immediately obvious: The plastic portion of the main ram gear had sheared completely into two pieces.

A week later (since the Christmas holiday was in the middle) I had a new ram gear kit, replaced the broken part, and slapped it back together.
Unfortunately, now what its doing is that when you start it, the ram gets pushed down as far as it can go, but the motor just keeps going. It makes a horrible noise once its at the bottom, until you turn the compactor off. At that point turning it back on does cause the motor to raise the ram back up until it reaches the proper stop position, like its supposed to.
From the description I was given, it sounds like this was probably how it was behaving when that gear sheared in half. So it looks like I've solved an effect, but not the cause of the problem.
I tried looking online, and found a lot of advice about what to do if the ram won't stop at the top, but nothing about what to do if it won't stop at the bottom.
I did check the plastic "ram stops" (a new pair came with my kit, so why not?), but the original ones look fine to me.
So what should a person check if the ram motor doesn't want to detect that its done going down and stop/reverse at the bottom, but it otherwise works perfectly fine going both down and up?

Update: I ordered and replaced the direction switch, and its still doing the same thing.

So the problem's not that. To reiterate, it goes down fine like it always has. Then when it gets to the bottom, it tries to keep going and I hear a much higher-pitched and louder noise from the motor, until I turn the compactor off. Turning it back on causes the compactor to come back up like normal.

Update 2:
I did a lot more research, and found the following:

A whole new compactor would be more than $1k. This is probably because almost nobody buys them anymore. Could be nobody makes them anymore either.
They aren't that complicated. About the only things that can go wrong electronically are the directional switch, the start/stop switch, and the centrifugal switch.
The centrifugal switch is part of the motor, and can't easily be serviced separately.

Realistically, of the 3 the only one that can cause the issue I'm having with it not reversing is the centrifugal switch, but the general advice is to check everything else first, since the switch in the motor can't really be checked.
So I've replaced the direction switch (kinda had to. I wasn't careful...), and the start-stop switch tests OK, so that leaves me with the motor's centrifugal switch. If that doesn't work, well I either spend a ridiculous amount of money for a simple device nobody wants anymore, or join the 21st century and embrace the compactor-free lifestyle.
Comment: ...or it just went bad (causing my clueless kids to wonder what that horrible noise was, until the plastic gear sheared in half).
Comment: Yep, this is a controls problem. Good luck with the switch.
Comment: There is a limit switch which detects when the ram has reached maximum intended pressure. Apparently when you reassembled that was set incorrectly orr otherwise blocked from operating. Can't give you any more detail than that.
Comment: @keshlam - Re-checked all the other plastic ram parts (ram stops and power nuts) and they look fine. So new ram limit switch on order. Watch this space for another week I guess.
Comment: @keshlam - Is that switch the part I pictured above, or something else? I googled "trash compactor limit switch", and all I'm getting is that "direction switch" part.
Answer: Finally got this fixed, so I thought I'd post the answer that hopefully would have helped me.
There are 4 switches in compactors, all of which being moving parts, can wear out/go bad.

The three-way directional switch.
The on/off switch
Door (aka "safety") switch
Internal motor switches

You can check the first 3 with a multimeter, but the last is/are inside the compactor motor. So the strategy is to check all the others first, and if they are all good, try replacing the motor*.
The directional switch, if it goes bad you'll likely see either the compactor refuse to start at all, or not want to stop when it gets to the top.
If either the on switch or the door switch go bad, most likely the compactor will refuse to start at all.
If an internal motor switch goes bad, then you can see what I saw: the compactor going all the way to the bottom and then just trying to keep going until turned off. According to what I read, a failure on a switch in there can also sometimes cause the compactor ram to just go up and down continually.
So I my case, I got a multimeter and tested the other 3 switches, and they were all working properly (including of course the one I replaced after I accidentally broke the old one). Since that left the motor, I ordered a replacement for that, and when installed, that fixed the problem.
So the ultimate answer was: Bad switch internal to the motor. The switch itself was not really user-serviceable, but a new motor fixed the problem.

* - This YouTube video I found very helpful for explaining the troubleshooting process.

Compactor ram won't quit going down


Binding in JIBX

Question: Hi I just started using JIBX and I am having difficulty grasping the Binding concept. I have generated the JAVA classes from an XSD File
I am using windows and here is how my folders are structures
d:\Libraries\
This folder contains the jibx folder downloaded so the rar libraries like jibx-tools.jar are in
d:\Libraries\jibx\lib.....
Now the Libraries folder also contains a folder called dwcode2
I have an XSD File called starter.xsd in
D:\Libraries\jibx\dwcode2\
I generated the JAVA files using the command in DOS
D:\Libraries\jibx\dwcode2>java -cp ..\lib\jibx-tools.jar org.jibx.schema.codegen.CodeGen -t gen\src -w starter.xsd
as a result JAVA files were generated in
D:\Libraries\jibx\dwcode2\gen\src\org\jibx\
and the binding.xml was generated in
D:\Libraries\jibx\dwcode2\gen\src
Now I want to compile and bind the file (Could anyone also tell me why do we have to compile and bind the XML )
So i did the following
D:\Libraries\jibx\dwcode2\gen\src>java -jar "D:\Java Libraries"\jibx\lib\jibx-bind.jar   binding.xml
Error: Unable to find type org.jibx.starter.Shipping; on format element at (line 3, col 66, in binding.xml)Error: Cannot find information for class org.jibx.starter.Item; on mapping element at (line 4, col 79, in binding.xml)Error: Cannot find information for class org.jibx.starter.Address; on mapping element at (line 9, col 85, in binding.xml) Error: Cannot find information for class org.jibx.starter.Customer; on mapping element at (line 17, col 87, in binding.xml)Error: Cannot find information for class org.jibx.starter.Order; on mapping element at (line 22, col 81, in binding.xml) Error: Cannot find information for class org.jibx.starter.Order; on mapping element at (line 35, col 56, in binding.xml) Error running binding compiler org.jibx.runtime.JiBXException: Binding binding.xml is unusable because of validation errors at org.jibx.binding.Utility.loadBinding(Utility.java:358)   at org.jibx.binding.Utility.loadFileBinding(Utility.java:420)
                    at org.jibx.binding.Compile.compile(Compile.java:217)
                    at org.jibx.binding.Compile.main(Compile.java:384)

Could anyone please tell me what i am doing wrong ?? How can i fix this problem ? and why do we have to bind ??
Answer: Rajesh,
When you use the JiBX code generator, you need to do three steps:
1. Use the code generator to generate java code and a binding file from XML schema
2. Compile your java code
3. Use the binding compiler to modify your java class files so they can generate XML schema.
I can't see your schema, so why don't you do a test to see if the problem is your schema or your command lines:
- Place your schema in an empty directory and run these commands.
java -cp ../lib/jibx-tools.jar org.jibx.schema.codegen.CodeGen starter.xsd
javac -cp ../lib/jibx-run.jar:. org/jibx/starter/Shipping.java
java -cp ../lib/jibx-bind.jar:. org.jibx.binding.Compile binding.xml

Of course your will replace the path to the lib directory with your path (ie., c:\Library).
If this works, now you can organize your project into folders.
You can find complete documentation on our site at www.jibx.org.
To really simplify your life, I would recommend using the maven plugin. Configuration is much easier.
I hope this helps.
Don
Comment: hmm okay. Now I have 3 java classes say A , B and C. I generated .class files for A and B individually but when I try to generate class files i get an error Pointing to the lines where class B and C were used in Class C. So the problem is since Class C uses Class A and B I am having trouble generating a class file for this class. Currently i am using the command "javac example24/example/C.java"
Answer: You have maybe an error on the build.xml. Is you're classpath location correct ? Open buid.xml, go on the field where the first line is . Look at under the line .
if it's "bin", you must have binding.xml and the package containing the .class files in "bin". If it's in bin/classes or other path you will have this error because it will not found binding.xml so change build.xml to write bin/classes.
If you use eclipse, you have to generate the classes, compile, refresh and then execute the bind option, else this error appear.

Binding in JIBX


Filter list elements by symbols

Question: Hi I want to filter elements with / without -, . into two lists. My code doesn't do the job, it seems run through everything twice and cannot replace both - and . at the same time. Where did I do wrong?
Code:
NO_SYMBOL = []
WITH_SYMBOL = []
SPACE = []
for i in DATA:
    for ch in ['-', '.']:
        if ch in i:
            WITH_SYMBOL.append(i)
            SPACE.append(i.replace(ch, ' '))
        else:
            NO_SYMBOL.append(i)

Data
['volunteer-abroad',
 'volunteer-abroad.com',
 'volunteer-abroad.ie',
 'volunteer-abroad.org',
 'volunteerabroad']

My output:
SPACE
['volunteer abroad',
 'volunteer abroad.com',
 'volunteer abroad.ie',
 'volunteer abroad.org',
 'volunteer-abroad com',
 'volunteer-abroad ie',
 'volunteer-abroad org']

NO_SYMBOL
['volunteer-abroad', 'volunteerabroad', 'volunteerabroad']

I want to get output like these:
SPACE
['volunteer abroad',
 'volunteer abroad com',
 'volunteer abroad ie',
 'volunteer abroad org']

NO_SYMBOL
['volunteerabroad']

Comment: Can you figure out why your list might be twice as long as you expected? Look at your loops. Well written question, by the way.
Comment: Well, when `i` is set to `'volunteer-abroad.com'`, you first take `'-'`, create a new string with just `-` replaced with spaces, and add that to `SPACE`. You then take `.` and do the same. Perhaps you need to first take care of all replacements?
Answer: You are treating those two characters separately, by using a for loop:

The first time through the for ch in ['-', '.']: loop, ch is set to '-'. When that character is found in i you create a new string with - removed, and append that to SPACE and i itself is appended to WITH_SYMBOL. If the character is not found you append to NO_SYMBOL.
The second time through the loop, ch is set to '.', and you do all the same work again.

As a result, you always append to either SPACE and WITH_SYMBOL, or to NO_SYMBOL twice for each i.
You need to delay appending until you have processed all the characters in ch, and only when the loop is done decide where to append. You could use a flag variable for that:
for i in data:
    altered = False
    cleaned = i
    for ch in ['-', '.']:
        if ch in clean:
            altered = True
            cleaned = cleaned.replace(ch, ' ')
    if altered:
        SPACE.append(cleaned)
        WITH_SYMBOL.append(i)
    else:
        NO_SYMBOL.append(i)

You can also just test for either character to be present, and use str.replace() for both. It's safe to do so, str.replace() doesn't care if the character you are replacing is not present at all:
if '-' in i or '.' in i:
    SPACE.append(i.replace('-', ' ').replace('.', ' '))
    WITH_SYMBOL.append(i)
else:
    NO_SYMBOL.append(i)

Rather than use two .replace() calls you can also use a translation table passed to str.translate(); this is faster, and much more flexible if you have a variable number of characters to replace. For the latter case, you can use the any() function to test for a sequence of characters:
symbols = ['-', '.']  # can be extended later
translation_map = str.maketrans(dict.fromkeys(symbols, ' '))  # map any symbol to a space
for entry in data:    # entry is a nicer name here than i
    # the following loops over symbols until one is found that matches, then
    # returns True. If no matching symbol is found, False is given instead.
    if any(ch in entry for ch in symbols):
        SPACE.append(entry.translate(translation_map))
        WITH_SYMBOL.append(entry)
    else:
        NO_SYMBOL.append(entry)

Answer: You dont need a loop to run twice on the same list instead you can modify the if condidition
NO_SYMBOL = []
WITH_SYMBOL = []
SPACE = []
for i in DATA:
    if '-' in i or '.' in i:
        WITH_SYMBOL.append(i)
        SPACE.append(i.replace('.', ' ').replace('-', ' '))
    else:
        NO_SYMBOL.append(i)

Answer: I think the error in your code was found by other answers - but by using a simple RegEx you would get more performance and could easily change it when you have to add new symbols to match:
import re
pattern = re.compile("[-.]")
NO_SYMBOL = []
WITH_SYMBOL = []
SPACE = []

for item in data:
  if pattern.search(item):
    WITH_SYMBOL.append(item)
    SPACE.append(pattern.sub(" ", item))
  else:
    NO_SYMBOL.append(item)

Online demo here

Filter list elements by symbols


Extracting information from datetime to input into a SQL query

Question: Im having a bit of a problem trying to figure out how to write a query i need.
I have a whole bunch of records in a mysql table, each record has a 'datecreated' column which is a datetime type and formatted like so: 0000-00-00 00:00:00
What i need to do is extract all records that are in the 11th month of this year, but they year needs to be taken from the servers date, so that when it ticks over into a new year, it wont still run the query from last year.
Does this make sense at all? ... Im totally stumped how to get it going.
Cheers,
Answer: select
    yt.*
from
    yourtable yt
where
    month(yt.datecreated) = 11
    and year(yt.datecreated) = year(now())
;

Comment: Will that take the values from the datecreated mysql data type?
Comment: `month()` and `year()` work on datetime, timestamp and date types. http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html
Answer: Ok so this is not hard tbh ;) you want only for month 11 (november)?
this should work man:
//connect to database
$current_year = date("Y"); //gets the current year according to server time
$query = "SELECT * FROM your_table WHERE datecreated LIKE '".$current_year."-11%'";
$result = mysql_query($query) or die(mysql_error());
while ($row = mysql_fetch_array($result)){
    echo '
';
    echo $row['column_id'];
    echo '
';
    }

change your_table to your table name  and column_id to name of a column of whatever you want to print
it will print everything which was created in 2011-11 ... however when the server time changes to 2012 it wont print out anything until there will be some input in November .. is that what you want?
hope it helps (:


Why, exactly, does performance suffer when I request more .js files rather than less?

Question: Say I have a javacsript file containing ten components. Why, exactly, is this better for performance than loading 10 files containing a component each? It seems like it's the same amount of data? So what's the difference?
Comment: By "loading" do you mean requesting? If so, there's your answer. Each request takes time traveling to and from the server.
Answer: The difference is that browsers don't load all resources at the same time.  Most browsers only have 2-4 concurrent requests open, so if you have 5 JS files, the browser will request the first four and then wait until one of them completes before requesting the 5th.  Some older browsers only request one JavaScript file at a time, and wait until it's fully parsed before fetching the next.
Often the network time is the worst part of the user experience (especially in some parts of the world or on some devices), so having a bundle where only one request is made instead of 5 means your app will feel more responsive.
There are a number of good articles online about this as well, YSlow was one of the first tools & metrics used to check these things, but there are others.
Comment: Thank you, that makes sense!
Answer: Simply put, it's not about the size of the requests it's about the amount of requests and whether or not they are synchronous or asynchronous.
Synchronous programming means that, barring conditionals and function calls, code is executed sequentially from top-to-bottom, blocking on long-running tasks such as network requests and disk I/O.
Asynchronous programming means that the engine runs in an event loop. When a blocking operation is needed, the request is started, and the code keeps running without blocking for the result. When the response is ready, an interrupt is fired, which causes an event handler to be run, where the control flow continues. In this way, a single program thread can handle many concurrent operations.
And as this answer by Cletus explains:

JavaScript is always synchronous and single-threaded. If you're executing a JavaScript block of code on a page then no other JavaScript on that page will currently be executed.

JavaScript is only asynchronous in the sense that it can make, for example, Ajax calls. The code will stop executing until the call returns (successfully or otherwise), at which point the callback will run synchronously. No other code will be running at this point. It won't interrupt any other code that's currently running.
This is why your performance suffers when you load more JavaScript files.
Comment: It seems like you're talking a lot about JS, when the question is really about a variable number of HTTP requests on page load.


request-response system

Question: I have request objects with corresponding response objects. Sender object makes a request and then listens for response. One sender/listener object may send different requests. Every request goes into a global queue and after it was processed, corresponding response is sent to every listener object.
Comment: Maybe shared or weak pointers?
Answer: There are several solutions to your problem. One would be, that the transceiver informs all Request object about its destruction. For this, you would need a method like
Transceiver::addRequest() which a Request object uses to register itself. In the
destructor of Transceiver you have to inform all registered Request's. For example:
class Transceiver
{
    virtual ~Transceiver()
    {
        for (auto request : m_requests)
            request->deleteTransceiver(this);
    }

    void addRequest(Request* r)
    {
        m_requests.push_back(r);
    }

    void removeRequest(Request* r)
    {
        m_requests.erase(std::remove(m_requests.begin(), m_requests.end(), r),
                         m_requests.end());
    }

    std::vector<Request*> m_requests;
};

class Request
{
    virtual void deleteTransceiver(Transceiver* t) = 0;
    virtual void notify() = 0;
};

class RequestImpl : public Request
{
    RequestImpl(Transceiver* t)
        : m_target(t)
    {
        if (t)
            t->addRequest(this);
    }

    ~RequestImpl()
    {
        if (m_target)
            m_target->removeRequest(this);
    }

    virtual void deleteTransceiver(Transceiver* t)
    {
        if (m_target == t)
            m_target = 0;
    }

    virtual void notify()
    {
        if (m_target)
            m_target->process(ResponseType());
    }

    Transceiver* m_target;
};

A second approach would of course be to prevent the destruction of a Transceiver as
long as it is in use. You could use a std::shared_ptr<Transceiver> m_target in the
Request class, which means the transceiver lives at least as long as the associated request.
For a bit more flexibility, there is also the possibility of an std::weak_ptr<Transceiver>. Then the transceiver could be destroyed when the request
is still alive. However, when you try a std::weak_ptr<Transceiver>::lock() and it
fails, you know that the Transceiver is dead.
Edit: Added a method to remove a Request if it is destroyed before its Transceiver.

request-response system


How to stop on first items failure FluentValidation RuleForEach

Question: I have a nested collection property in my object. i need to make it stop on first failure for collection items. I mean error message should not be repetitive for each item for failures. Cascade is not works for this scenario. Thanks :)
My Object:
public class Customer{
   public string CustomerName{get;set;}
   public List<Order> Orders {get;set;}
}

public class Order{
   public string OrderNumber{get;set;}
   public int Amount{get;set;}
}

Example Request:
{
    CustomerName="test",
    Orders:[
        {
            "OrderNumber":null,
            "Amount":0
        },
        {
            "OrderNumber":"",
            "Amount":null
        },
        {
            "OrderNumber":"12345",
            "Amount":0
        }
    ]
}

I use fluent validation for nested object like below. But when it runs the error messages are repetitive. It should be stop on first items failure.
Code:
this.RuleForEach(x => x.Orders).Cascade(CascadeMode = CascadeMode.Stop).SetValidator(new ShipmentListRequestItemValidator()));

Error output (actual):
"OrderNumber is null!", "OrderNumber is empty!", "Amount should be greater than 0"

Error output (should be):
"OrderNumber is null!"

Answer: you can override ValidationResult to get first error .
like this :
    public override ValidationResult Validate(ValidationContext<TestEntity> context)
            {
                 List<ValidationFailure> mainErrors = new List<ValidationFailure>();
                 mainErrors.Add(base.Validate(context).Errors.FirstOrDefault());
                 return new ValidationResult(mainErrors);
            }


set uiimage for uiimageview from other viewcontroller

Question: I have faced a problem with setting uiimageview from other viewcontroller.
DiaryDetailController.swift
let imageViewPageController = (segue.destinationViewController as! ImageViewPageController)
        if (imageCount > 0) {
            imageViewPageController.image1 = tempImage1
        }

ImageViewPageController.swift
let page: ImageViewDetailController! = storyboard?.instantiateViewControllerWithIdentifier("imageViewDetailController") as! ImageViewDetailController
            page.setImage(image1)
            pages.append(page)

ImageViewDetailController.swift
func setImage(image: UIImage) {
    imageView.image = image
}

And I got following error on "imageView.image = image".
fatal error: unexpectedly found nil while unwrapping an Optional value
How should I solve this problem?
Comment: The code above doesn't show where imageView is declared and instantiated.  If you put a breakpoint on `imageView.image = image` and see if imageView is not nil.  Or if it was declared as an optional originally, then the line should read `imageView?.image = image`
Comment: Do your research before asking questions: http://stackoverflow.com/questions/32170456/what-does-fatal-error-unexpectedly-found-nil-while-unwrapping-an-optional-valu Your IBOutlet is probably disconnected.
Comment: Thank for your comments. I've solved the problem. It was my mistake forgot  linking the IBOutlet...
Answer: You're probably trying to set the image before the IBOutlets are set.
Create a UIImage property in ImageViewDetailController (let's call it image), and instead of saying:
page.setImage(image1)

You can do this
page.image = image1

Then let the ImageViewDetailController deal with it once it has loaded. So in the viewDidLoad, just say
imageView.image = self.image

Comment: Thank you for the answer. I have tried your answer but the problem was in linking.


How to detect if a player is wearing a custom set of gear

Question: I'm making a map in Minecraft with some custom crafting recipes that yield special items that deal with fighting. I know how to do that just fine, but I also want to add a bonus if one is wearing, say, a full set of "emerald armor." For example, if the player is wearing the full set, they would receive jump boost. So my question to you is: how do I detect if a player is wearing a specific set of gear? I know how to detect if a player is wearing a specific item with scoreboard and whatnot, but how do I combine those commands for a full set?
Answer:
I know how to detect if a player is wearing a specific item with scoreboard and whatnot, but how do I combine those commands for a full set?

You could either put all of the data tags into one scoreboard objective, like this:
<code>/scoreboard players set @a FullEmerald 0
/scoreboard players set @a FullEmerald 1 {Inventory:[{Slot:103b,<Helmet tags>},{Slot:102b,<Chestplate tags>}},{Slot:101b,<Leggings tags>}},{Slot:100b,<Boots tags>}}]}
</code>
Or, alternatively, set up an objective for each of the specific items, then combine them like:
<code>@a[score_HelmetEmerald_min=1,score_ChestplateEmerald_min=1,score_LeggingsEmerald_min=1,score_BootsEmerald_min=1]
</code>
The second method would also really be better if you've already got objectives for each of the individual armor pieces (e.g: each piece individually has powers).
Comment: Why aren't you using a tag instead?  That's the typical implementation for booleans these days.
Comment: @MBraedley I prefer to still use scoreboard objectives for item-holding/armor-wearing because you can't combine tags as easily (only one `tag=` works in a selector). Tags would also work for the first method though, just depends on what else needs to be done with it.
Comment: Never thought about it that way, thank you. I have now completed what I have decided to call the "Emerald Knight," and it's really fun :)


How to add alerts in pine script

Question: I was trying to add alerts when the label comes in the script. Tried to do it, but was not able to make it out. I am not pro in coding but tried to make some change seeing other code. I added the alert condition for an other code but this was not working. Can the alerts be added to this.?
Thank you.
//@version=4

study("BDW",overlay=true,max_lines_count=500,max_bars_back=500)
h = input(8.,'Bandwidth')
src = input(close,'Source')
//----
n = bar_index
var ln = array.new_line(0)
if barstate.isfirst
    for i = 0 to 499
        array.push(ln,line.new(na,na,na,na))
//----
float y2 = na
float y1 = na
float y1_d = na
//----
line l = na
label lb = na
if barstate.islast
    for i = 0 to min(499,n-1)
        sum = 0.
        sumw = 0.
        for j = 0 to min(499,n-1)
            w = exp(-(pow(i-j,2)/(h*h*2)))
            sum += src[j]*w
            sumw += w
        y2 := sum/sumw
        d = y2 - y1

        l := array.get(ln,i)
        line.set_xy1(l,n-i+1,y1)
        line.set_xy2(l,n-i,y2)
        line.set_color(l,y2 > y1 ? #ff1100 : #39ff14)
        line.set_width(l,2)

        if d > 0 and y1_d < 0
            label.new(n-i+1,src[i],'▲',color=#00000000,style=label.style_circle,textcolor=#39ff14,textalign=text.align_center)
        if d < 0 and y1_d > 0
            label.new(n-i+1,src[i],'▼',color=#00000000,style=label.style_circle,textcolor=#ff1100,textalign=text.align_center)

        y1 := y2
        y1_d := d

crossOverAlert =if  d > 0 and y1_d < 0
alertcondition(condition=crossOverAlert,title="BUY", message="BUY")

crossUnderAlert = if d < 0 and y1_d > 0
alertcondition(condition=crossUnderAlert,title="SELL", message="SELL")

Answer: Use alert() instead of alertcondition() and put it right after when the label comes in the script.
  if d > 0 and y1_d < 0
            label.new(n-i+1,src[i],'▲',color=#00000000,style=label.style_circle,textcolor=#39ff14,textalign=text.align_center)
            alert("BUY")
        if d < 0 and y1_d > 0
            label.new(n-i+1,src[i],'▼',color=#00000000,style=label.style_circle,textcolor=#ff1100,textalign=text.align_center)
            alert("SELL")

How to add alerts in pine script


Re-run entire job sql server - not just a step

Question: I'm working on SQL Server Agent and i have some troubles. I need to re-run a job when a step fail, I mean, the entire job - not just the step. Is it possible ?
Do you know the best way to do this ?
Thanks a lot.
Comment: If you have a proper steps flow you can run the step #1 if a given step fails. But that might get you in a cycle, so I don't think that's the best way to solve your situation.
Comment: Yeah, there is to be an end... Let's say i want to retry 3 times but no more.

I need this because of async job who runs Azure job via powershell... It drive me crazy.
Comment: Are you able to create a table in the database to store details of each step that is run? If so, then you can implement a logging process where you log each step that is run, and do something like ensure that you only run Step 1 3 times in one day (thus avoiding getting stuck in a cycle). Let me know if you want further details.
Comment: The "right" way to do this would be to move it to an SSIS package, or move the operations into a single step.  SSIS gives you much better control over flow than SQL Agent does, but is more complex.  The only other alternative I can think of is to basically re-create what SQL Agent does with the flow control you want.  You can [jump through a few hoops](http://stackoverflow.com/questions/12249056/executing-sql-server-agent-job-from-a-stored-procedure-and-returning-job-result) to call jobs from other jobs, and control things that way.
Comment: @DumbRadish : That's the solution that I got in mind but I wanted to know if there was an easiest solution. Anyway, thanks :)
Comment: @bacon Bits: I dont know SSIS but it sounds interesting, and I cant do it in a single step because of asynchronous nature of the job.
Comment: SSIS is what they used to call DTS in SQL Server 2000. It's Microsoft's enterprise transform and load service meant for integration. It's very extensive; you actually create the packages using a modified version of Visual Studio. If everything you're doing is predominantly in SQL, this is probably what you want to use. If you're using SQL Agent as a scheduling tool for mostly non-SQL or non-DB tasks, SSIS is probably going the wrong way. SSIS is available on 2005+, but not Workgroup or Express.  Basic tutorial [here](https://msdn.microsoft.com/en-us/library/jj720568.aspx).
Comment: Indeed it's mostly for non-sql task. Thanks anyway :)
Answer: Under the job step properties click on "advanced", you can then restart the job on step 1.  It also gives you the option to retry a number of times before aborting and ending.


rand() function always generation same number despite seeding with time

Question: I have this code I need to write, and I created this function. Irrelevant of what it does for the code, I need it to generate a random number (a) between 0 and (i), an integer with a previously initialized value. Somehow despite seeding, I always get the same number.
I have tried entering a number instead of i and it works properly by giving me a different random number each time I execute. I also tried declaring a new int variable inside in the function and giving it the value of i, but it still doesn't work.
elementptr position_current(elementptr first, int i){
  elementptr current = first;
  int j = 1;

  printf("%d\n", i);
  srand(time(NULL));

  int a = rand() % i;
  printf("%d\n",a);
  for(j=1;jnext;
  }

  return current;
}

I expect (a) to get a different value each Time I run the code, however it's always getting the same value(2).
Can someone tell me what could be wrong?
Comment: You should call `srand()` only once, at the beginning of the program. Subsequent calls to `rand()` will change the seed and produce pseudo-trandom numbers.
Answer: I'm guessing you're calling this function many times in a single second. Since time only changes once a second, you're reseeding the same value over and over.
Don't call srand over and over. Call it exactly once in your main function, then never call it again, and rand will produce successive values based on that seed one at a time.


Django; AWS Elastic Beanstalk ERROR: Your WSGIPath refers to a file that does not exist

Question: I am using this tutorial:
http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create-deploy-python-django.html
I create the .ebextensions directory inside the root directory, and put this django.config file in it:
option_settings:
  aws:elasticbeanstalk:container:python:
    WSGIPath: mysite/wsgi.py

I've also tried setting the path to mysite/mysite/wsgi.py because I saw that work somewhere but it did not help me.
Everywhere I look shows a different .config file with different arrangements, and I don't know where to go from here. How can I properly set my WSGIPath in Elastic Beanstalk?
Comment: Do you have this file .elasticbeanstalk/optionsettings?
Answer: [Solution]
1 eb config
2 Change the WSGIPath there from application.py to mysite/wsgi.py
That's It
Comment: Three years later and this is still helping people. The really needs clearing up in the AWS tutorial!
Comment: Does the django.config not do anything then?
Comment: Does the eb config in the answer refer to the django.config file?
Comment: this comment was very helpful! -- one note, it is specific to using python 3.6 (which is now deprecated, and unfortunately still used in the tutorial linked). this issue shouldn't happen when using python 3.8 and Linux 2 ([platform history](https://docs.aws.amazon.com/elasticbeanstalk/latest/platforms/platform-history-python.html))
Answer: I ran into a similar issue, and it seemed to resolve when I put .elasticbeanstalk in the same directory as .ebextensions, rather than having it be a child directory. Then I had to run eb config to fix the wsgi file that it was de facto picking up, and now I have a running app.
Answer: Make sure that .ebextensions isn't ignored. EB looks for .ignore file (.ebignore by default and if it doesnt exists but .gitignore does, it will use it) and deploy only the files that are not ignored. Had a similar issue with my local_settings.
https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/eb-cli3-configuration.html#eb-cli3-ebignore
Answer: If you see the following error:
ERROR: Your WSGIPath refers to a file that does not exist.
Note the following:

EC2 (server) instances in EB (platform) run Apache.
Apache finds Python apps according to our WSGIPATH.
By default EB assumes the WSGI file is called application.py.

There are two ways of correcting this.
Option 1: Using environment-specific configuration settings
Run: $ eb config
Find the following config file ".elasticbeanstalk/src-test.env.yml."
This file doesn't actually exist locally; EB pulled it so that you can edit it.
If you save changes in this pseudo-file, EB will update the corresponding settings in your env.
If you search for the terms 'WSGI' in the file, you should find a config section resembling this:
aws:elasticbeanstalk:container:python:
  NumProcesses: '1'
  NumThreads: '15'
  StaticFiles: /static/=static/
  WSGIPath: application.py

Update the WSGIPath:
 aws:elasticbeanstalk:container:python:
   NumProcesses: '1'
   NumThreads: '15'
   StaticFiles: /static/=static/
   WSGIPath: src/src/wsgi.py #src/src is an example. Do not just c&p.

If you save the file, EB will update the env config automatically.
The advantage to using the $ eb config method to change settings is that you can specify different settings per env.
Option 2: Using global configuration settings
To use this option, create a new file called /.ebextensions/02_python.config:
option_settings:
  "aws:elasticbeanstalk:application:environment":
    DJANGO_SETTINGS_MODULE: "src.settings" #src is an example.
    "PYTHONPATH": "/opt/python/current/app/src:$PYTHONPATH" #src is an example.
  "aws:elasticbeanstalk:container:python":
    WSGIPath: src/src/wsgi.py #src is an example.
    NumProcesses: 3
    NumThreads: 20
  "aws:elasticbeanstalk:container:python:staticfiles":
    "/static/": "www/static/"

What's happening?

DJANGO_SETTINGS_MODULE: "src.settings" - adds the path to the settings module.

"PYTHONPATH": "/opt/python/current/app/src:$PYTHONPATH" - updates our PYTHONPATH so Python can find the modules in our application.(Note that the use of the full path is necessary.)

WSGIPath: src/src/wsgi.py sets our WSGI Path.

NumProcesses: 3 and NumThreads: 20 - updates the number of processes and threads used to run our WSGI application.

"/static/": "www/static/" sets our static files path.

Run $ git commit (if necessary) and $ eb deploy to update these settings.
Answer: I did not use console but GUI.
ERROR: Your WSGIPath refers to a file that does not exist.

where could be problem : Creating .zip file
select all : files of your project (not the project folder)
Note : weworkout is my django project (created by django-admin startproject
 weworkout)
Right way : select all files

Wrong way : selecting project folder

Also this is the only change you have to do to your django project before uploading
weworkout/.ebextensions/django.config file contains
option_settings:
  aws:elasticbeanstalk:container:python:
    WSGIPath: weworkout/wsgi.py

Note : .ebextensions is in same folder as manage.py
Answer: Check if your Django.config file was saved with the correct extension. I had the same issue and the problem was that the file was being saved as a TXT file instead of config file.


Assigning modules from a library to a server where the number of modules can change?

Question: I need to create a design for an internal tool that we will try to utilize within our own team that works with software testing. We will try to build a tool that can help us automatically setup a test system.
I have a list of servers that I want to add multiple modules to. I want to set a number on each module so it will be instantiated that many times in the server. I want to pick the modules from a library of modules displayed to the user.
Is it possible to combine drag and drop from the library to the server and at the same time apply the number of that specific module I want? Please see attached wireframe.
Comment: Hello Michael, perhaps you can add the research you've done so far or assumption that you have right now, its not in your best interest to receive an answer, without really understanding it. I often find myself, when making assumptions, thinking about how I guess the ideal world would look like, I then draw this on paper and test this out in the hallways.
Comment: Thanks for your input. I've tried to make my question more clear and how far I got!
Comment: Okay, thank your for adding this additional information. Now I'll be the critical observer and ask "why must you be able to select a server and its virtual server underneath" - what is the real problem you're trying to solve? A general remark, though, is that I wouldn't probably go suffix the XML extension, unless it has a real purpose to expose this information.
Answer: I've been wondering about the explanation, as the end-result is "i want to emulate a certain amount of certain entities", everything else (server list, ip-addresses, ...) seems clutter... my suggestion would be a list of entities and an amount, the backend should than take care that they are created in this pool of servers.
Think about "what keeps me from doing my job/the task at hand" :-)


Characteristic function of a measurable set.

Question: Let $X=L^p[0,1]$ $(1\leq p<\infty)$ be the Lebesgue space of p-integrable real functions on $[0,1]$. Let $D\subseteq [0,1]$ be measurable subset. The characteristic functions $\chi_D$ is defined as
\begin{equation}
  \chi_{D}(x)=\begin{cases}
                 1, & x\in D \\
                 \\
                 0, & x\notin D.
               \end{cases}
\end{equation}
How can we define $\chi_Du$, for $u\in M\subset L^p[0,1]$? Where $M$ is a bounded subset of $L^p[0,1]$.
Comment: That do you mean with $\chi_Du$? And what kind of set is $M$? Why do you not simply write $u\in L^p[0,1]$?
Comment: By $\chi_Du$ do you mean $\chi_D(u)$ where $\chi_D$ is defined as above?
Comment: The function, $\chi_D$ is just a representant of an $L^p$ function. You can choose $\tilde{u}$ to be a representant of $u$ and $\chi_D\times \tilde{u}$ will be a representant of the product (if you mean that).
Comment: @RuviLecamwasam I guess yes, it must be $\chi_D(u)$. actually I just found this example in an article I was going through and couldn't understand it. It was written just like I did.
Comment: @principal-ideal-domain Here $M$ is a bounded subset of $L^p[0,1]$. Thanks for pointing out I forgot to mention it.
Comment: @ShinningStar See my edit in my answer.
Answer: Your $\chi_{D}u$ can be defined in that way:
\begin{equation}
  (\chi_{D}u)(x)=\begin{cases}
                 u(x), & x\in D, \\
                 \\
                 0, & x\notin D.
               \end{cases}
\end{equation}
Edit: You don't need to mention that $u\in M\subseteq L^p[0,1]$ where $M$ is a bounded subset of $L^p[0,1]$. This is equivalent to $u\in  L^p[0,1]$ without mentioning $M$ at all because for each $u\in  L^p[0,1]$ you can choose $M$ to be $M:=\{u\}$.
Comment: Thank you Sir. Would $\chi_D u\in L^p[0,1]$? If I have to take it's norm what it should be?
Comment: @ShinningStar Since $u\in L^p[0,1]$ and $|\chi_{D}u|\le |u|$ we also have $\chi_{D}u\in L^p[0,1]$.
Comment: Thank you for your effort! :)


Is there a name for these sequences of subsets of a commutative ring resembling the definition of a graded algebra?

Question: (I am experimenting with writing arrows backwards.)
Let $R$ denote a commutative ring. Is there a term for those sequences $A : \mathcal{P}(R) \leftarrow \mathbb{N}$ satisfying the following requirements resembling the definition of a graded ring?

$A_i A_j \subseteq A_{i+j}$ and $1 \in A_0$
$A_i + A_i \subseteq A_i$ and $0 \in A_i$
$RA_i \subseteq A_i$

Example. Let $R = \mathbb{Z},$ $A_0 = \mathbb{Z}$, and $A_i = 2\mathbb{Z}$ for all $i>0$.
Motivation.
If a sequence $A$ into $\mathcal{P}(R)$ satisfies these conditions, then the following subset of the polynomial algebra $R[x]$ is in fact an $R$-subalgebra:
$$\bigcup_{n \in \mathbb{N}}\sum_{i < n}A_i x^i$$
Comment: What's the point with writing arrows backwards?
Comment: @PedroTamaroff, given morphisms $g : Z \leftarrow Y$ and $f:Y \leftarrow X,$ their composite $g \circ f$ has type $Z \leftarrow X$.
Comment: OK. ${}{}{}{}{}$
Comment: There is the notion of a filtration of a ring/module. This leads to the notions of associated graded ring, blowup algebra, Rees algebra, completion, Artin-Rees lemma...
Answer: 2 and 3 ensures that the $A_i$'s are (left) ideals of $R$, and 1 that $A_0 = R$. Such a sequence is called a filtration of the unital ring $R$ by (left) ideals. More generally, you have the notion of filtration of an (left) $R$-module by a sequence of $R$-submodules. Endowed with such a filtration, your object is called a filtered ring or filtered module. If this filtration has some monotonicity property (like being increasing or decreasing) you can define a graded object (ring or module) associated to the filtered object.
Comment: Is it really the case that $i \leq j$ implies $A_j \subseteq A_i$ for all such sequences $A$?
Comment: No, it doesn't. Adding this gives you a *non-increasing filtration*. Typically, filtering polynomial by degree gives you an increasing filtration, which is therefore not non-increasing, that is, which doesn't satisfy what you just wrote above. Tensor algebra of a module gives you an example of a filtration which is not increasing nor non-increasing.
Comment: @Robert Green: What's called a graded ring is the associated object $\bigoplus_{i\ge 0}A_i/A_{i+1}$ (for a non-increasing filtration), not the filtered ring itself. Similarly for modules.


Existence of nontrivial unit in $\mathbb{Q}[G]$, where $G$ is finite.

Question:
Suppose $G$ is a finite group of order $|G|>1$, and $\mathbb{Q}[G]$ is the group ring. I'm curious about an example of a nontrivial invertible element, i.e., one that is not of the form $ag$, with $a\in\mathbb{Q}$ and $g\in G$.

This comes from an old UCLA qual problem 2002. An example is given at the bottom of this document on page 2, but it uses some facts about circulant matrices. I'm just curious if there is an alternative example, or just a general existence argument.
Answer: Since every finite group contains a cyclic subgroup of prime order, your question reduces to that, where the answer can be gotten by simple arithmetic with roots of unity (which probably reduces to the circulant matrix thing you are alluding to). However, in a slightly more general setting, Higman (in this paper) computes structure of the group of units of a group ring of a finite abelian group. (in general, this question is extremely hard).
Answer: (This is just a more in-depth version of Igor Rivin's answer in case you are new to these types of arguments).
For the cyclic group of order $n$, your group ring is isomorphic to $\mathbb{Q}[T]/(T^n - 1)$ which is just the direct sum of the cyclotomic fields $\mathbb{Q(\zeta_d)}$ for $d | n$ (including $d = 1$, so for instance if $n = p$ is prime you get $\mathbb{Q}(\zeta_p) \oplus \mathbb{Q}$... I may need to be a little more careful if $n$ is even, so let's just assume it's not).
To write down units in this, just pick something nonzero in each summand. For a concrete example, let's let $n = 3$ and write $\omega$ for $\zeta_3$. We have
$$
(a + b\omega_3, c) \in \mathbb{Q}(\omega) \oplus \mathbb{Q}
$$
which will be a unit unless $c = 0$ and $a = b = 0$. Let's move them back to the group ring to verify that (some of them) are not "trivial" in your sense.
Write $G = \langle g \rangle$. The isomorphism goes (the first $=$ is just $g\mapsto T$, the first arrow is the chinese remainder theorem, and the last evaluates $T$ to $\omega$ resp. $1$)
$$
\mathbb{Q}[G] = \mathbb{Q}[T]/(T^3 - 1) \to \mathbb{Q}[T]/(T^2 + T  +1) \oplus \mathbb{Q}[T]/(T-1) \to \mathbb{Q}(\omega) \oplus \mathbb{Q}
$$
We want to go backwards along these identifications, so we need to unpack the Chinese remainder theorem.
We seek $\alpha, \beta \in \mathbb{Q}[T]/(T^3-1)$ such that $\alpha + \beta = 1$, $(T^2 + T + 1)|\alpha$, and $(T - 1) | \beta$. Then the preimage of $(f, g)$ under the Chinese remainder theorem map will be $\beta f + \alpha g$.
Using the Euclidean algorithm (or guessing and checking) gives $\alpha = \frac{1}{3}(T^2 + T + 1)$ and $\beta = \frac{-1}{3}(T-1)(T+2)$.
We are done! $(a + b\omega_3, c)$ lifts to
$$
\frac{1}{3}\left(-(g-1)(g-2)(a + bg) + (g^2 + g + 1)(c) \right).
$$
I'm out of time, so I'll leave it to you to tidy this expression up and see when it is non-trivial (and check to make sure I didn't make any mistakes!) Note that $g^3 = 1$ simplifies things.
Comment: I just got back and took a look at your qual question. I would answer it this way. Clearly you are reduced to considering cyclic groups of prime order (subgroups give rise to subrings). The non-units in $\mathbb{Q} \oplus \mathbb{Q}(\zeta_p)$ are a union of two $\mathbb{Q}$ vector subspaces: one of dimension $1$ and one of dimension $p-1$, and therefore this is also true in $\mathbb{Q}[G]$. If all units were of the form $\lambda g$, i.e. in a subspace of the form $\mathbb{Q}g$, then $\mathbb{Q}[G]$ would be the union of finitely many vector subspaces of proper dimension, which is absurd.


NodeJS on existing php local site

Question: I have a site build on PHP / Apache, and i would like to insert a NodeJs application inside a div area, i have already it shown in an iframe like so :

I tried ProxyPass & ProxyPassReverse with the code below but it only redirect to my nodeJs app without my PHP site in the apache configuration file /etc/apache2/sites-available/exemple.conf.
ProxyRequests off

<Proxy *>
  Order deny,allow
  Allow from all
</Proxy>

<Location />
  ProxyPass http://localhost:8080/
  ProxyPassReverse http://localhost:8080/
</Location>

How can i achieve this correctly.
Answer: Finally no need of specific server configuration, an ajax call to the server url + port from the client do the job.
=> server.js file <=
// Use of socket.IO
var io = require('socket.io')(8080);
// Establishes server connection
io.on('connection', function(socket){
//send data to client ( real time date exemple )
  setInterval(function(){
    io.emit('date', {'date': new Date()});
  }, 100);
});

=> script anywhere on the site web with css #date ID <=
jQuery(document).ready(function(){
  // Get base path
  var base_url = window.location.origin;
  // Establishes client connection to server
  jQuery.ajax({
    url : base_url + ':8080/socket.io/socket.io.js', // Socket.IO init on port (8080)
    dataType : 'script', // Turn POSTs into GETs for remote-domain requests with 'script' type
    success : function(){
      // Connection to the server
      var socket = io(base_url + ':8080');
      // Get message defined server side
      socket.on('date', function(data){
        // Print msg into html
        jQuery('#date').text(data.date);
      });
    }
  });
});

NodeJS on existing php local site


What is the problem with this code?

Question: #include<stdio.h>

class A { public: int a;};
class B: public A {
public:
    static int b;
    B(){
        b++;
        printf("B:%d\n",b);
    }
};

int main() {

    A* a1 = new B[100];
    A* a2 = new B();
    return 0;
}

Error:
In function `main':
undefined reference to `B::b'
undefined reference to `B::b'
undefined reference to `B::b'
undefined reference to `B::b'

Comment: I see this question about 10 times in a week :D
Comment: @Simon: on SO? can you post links to those questions? I'll have a look and probably learn something.
Answer: Static variables need to be allocated outside the class. Add this line outside the class B:
int B::b;

Think of static variables as being declared with the extern keyword. They still need to be allocated somewhere. This means the allocation should never be in the header file!
Comment: actually, allocation can be there in a header file, if that file is used at-most one place in a program (to avoid linking errors). Am I correct?
Comment: @Lazer: indeed, but that defeat the purpose of a header file, that is to be included in more than one file.
Comment: yeah you are correct, I just wanted to check whether I understood that right! thanks!
Answer: Because it is static, you also need to define storage for B::b (in a class definition, all you have done is declared the variable).
You need to add:
int B::b;

Comment: @Silmaril89: "Has no value"? What is it supposed to mean? Objects with static storage duration in C++ are always zero-initialized. In this case `B::b` is guaranteed to be zero at program startup.
Comment: @Silmaril89 - you are incorrect.  To quote the spec: 9.4.2/7 - `Static data members are initialized and destroyed exactly like non-local objects (3.6.2, 3.6.3).`  And in 3.6.2/1 - `Objects with static storage duration (3.7.1) shall be zero-initialized (8.5)`
Comment: I disagree, B::b has no value whether it's static or not, that will still fail.
Comment: @AndreyT: That is not true. PODs are never initialized in C++ unless explicitly specified. In this case, the declaration just allocate the memory, but doesn't initialize it.
Comment: @PierreBdR - that is only true for automatic variables.  Static and global variables are 0 initialized by default.
Comment: @PierreBdR: Absolutely incorrect. One more time: all objects with static storage duration are always guaranteed to be properly automatically *zero-initialized* before any other initialization begins. It does not matter whether you initialize them explicitly or not.
Answer: You have to initialize your static member in the according .cpp file like int B::b = 0
Comment: You don't have to initialize objects with static storage duration to `0` - they are guaranteed to be zero-initialized automatically in any case. What is missing in OP's case is the *definition* of the object. Whether it is initialized explicitly does not immediately matter.
Comment: Perhaps you can get away without initializing but it won't hurt and it makes the code clearer.

What is the problem with this code?


Celery Flower - how can i load previous catched tasks?

Question: I started to use celery flower for tasks monitoring and it is working like a charm. I have one concern though, how can i "reload" info about monitored tasks after flower restart ?
I use redis as a broker, and i need to have option to check on tasks even in case of unexpected restart of service (or server).
Thanks in advance
Answer: I found i out.
It is the matter of setting the persistant flag in command running celery flower.
Comment: could you share with me what flag did you add to the command?
Comment: Kapucko not sure after all this time, but it seems it was this: http://flower.readthedocs.io/en/latest/config.html#persistent
Comment: yeah, already tried but didn't work for me. I'm using Rabbitmq as a broker... that may be the issue. Thanks.


jQuery first object where x = true

Question: I have a number of objects passed to a function as an argument such as:
$( document ).on( "custom.event", function( evt, obj ) {
    console.log( obj );
});

The objects look like this (in console):
Object {name: "obj1", property: "", somethingElse: "some value"}
Object {name: "obj2", property: "1", somethingElse: "some value"} //I want this one!
Object {name: "obj3", property: "", somethingElse: "some value"}
Object {name: "obj4", property: "1", somethingElse: "some value"}

I would like to make use of the FIRST object where property is equal to "1" and have at my disposal the rest of the properties and their values  (from said obj).  How might I do this?  I've tried $.each but couldn't work out how to only return the first object where property == "1".
Thanks
Answer: You could use $.each to loop through the elements and use return false to break the loop when you find the first object:
var searchedObject = null;
$.each(obj, function(index, el) {
    if (el.property == "1") {
        searchedObject = el;
        return false;
    }
});

If you aren't worried about IE8 or below, you could also use Array.prototype.filter()
var searchedObject = obj.filter(function(el) {
    return el.property == "1"
})[0]; // [0] to get the 1st element.

Comment: Thanks, great answer.
Comment: @Myles It's also worth noting that @Curt's answer is the fastest since it's plain javascript. The `.filter` method will check every element and $.each has overhead.
Answer: Iterate through the array and store a reference when an item matches the property value required.
var first1Obj;

for(i=0; i<=obj.length; i++){
   if (obj[i].property == "1"){
       first1Obj = obj[i];
       break;
    }
}

See Demo: http://jsfiddle.net/7vmbs95t/
Comment: Thanks!  Perfect solution.
Answer: check if this works for you: https://jsfiddle.net/leojavier/83wt0vvg/
var obj = [
 {name: "obj1", property: "", somethingElse: "some value"},
 {name: "obj2", property: "1", somethingElse: "some value"},
 {name: "obj3", property: "", somethingElse: "some value"},
 {name: "obj4", property: "1", somethingElse: "some value"}]

 for(item in obj) {
  if(obj[item].property == 1) {
    console.log(obj[item].name)
    break;
  }

 }

jQuery first object where x = true


How to add my favorite places as a quicklist in my home's icon in Unity?

Question: So I saw all that fancy quicklists in dash, and I'm wondering if I can do it with nautilus to add places as a quicklist, like Videos, Pictures, Downloads.. etc,
So as a start, I tried to modify /usr/share/applications/nautilus-home.desktop and added this but it didn't work:
X-Ayatana-Desktop-Shortcuts=Videos;

[Videos Shortcut Group]
Name=Videos
Exec=nautilus ~/Videos
TargetEnvironment=Unity

Comment: have to logged out and back in since making the change or at least unity --reset
Comment: I tried that of-course.
Comment: The reason it did not work is most likely because of the line `OnlyShowIn=GNOME;` which should either be removed or replaced with `OnlyShowIn=GNOME;Unity;` as per the accepted answer.
Comment: It is better to read this ↠ http://askubuntu.com/questions/35488/list-of-custom-launchers-quicklists-for-unity?page=1&tab=votes#tab-top (contain a lot of quick-lists )
Answer: ubuntu 11.10
Copy 'Home Folder' launcher file to your home directory:
cp /usr/share/applications/nautilus-home.desktop ~/.local/share/applications

Open the file for editing in gedit:
gedit ~/.local/share/applications/nautilus-home.desktop

copy of mine below:
[Desktop Entry]

Name=Home Folder
Comment=Open your personal folder
TryExec=nautilus
Exec=nautilus --no-desktop
Icon=user-home
Terminal=false
StartupNotify=true
Type=Application
Categories=GNOME;GTK;Core;
OnlyShowIn=GNOME;Unity;
X-GNOME-Bugzilla-Bugzilla=GNOME
X-GNOME-Bugzilla-Product=nautilus
X-GNOME-Bugzilla-Component=general
X-Ubuntu-Gettext-Domain=nautilus

X-Ayatana-Desktop-Shortcuts=Videos;Documents;Music;Pictures;Downloads
[Videos Shortcut Group]
Name=Videos
Exec=nautilus Videos
TargetEnvironment=Unity

[Documents Shortcut Group]
Name=Documents
Exec=nautilus Documents
TargetEnvironment=Unity

[Music Shortcut Group]
Name=Music
Exec=nautilus Music
TargetEnvironment=Unity

[Pictures Shortcut Group]
Name=Pictures
Exec=nautilus Pictures
TargetEnvironment=Unity

[Downloads Shortcut Group]
Name=Downloads
Exec=nautilus Downloads
TargetEnvironment=Unity

after you have logged out and back (or just restart unity by typing unity in a terminal in you will have folders as a quicklist for the home folder icon.
Comment: As mentioned above, though that was Not  the Op's issue, starting in 11.10, when copying a .desktop to another location you must remove or comment out the line -
OnlyShowIn=GNOME;Unity;

Otherwise your launcher icon will only launch the app, not control it. A 2nd icon will show up that does that.
Comment: This is the problem I have.. I'm trying to rectify it.. I'll read on and try my luck, else return back here.
Comment: Yes.. I'm very happy.. Struggled for an Hour.. @doug Thank You.. Ur comment set me on the right track :D
Comment: This is what will happen http://youtu.be/oS52pYNFZ6I .. If that line is not removed.
Answer: Ubuntu 12.04
As of 12.04, it is no longer necessary to create a quicklist, as Nautilus automatically gets a list of your bookmarks and makes a dynamic quicklist.


Bootstrap datetimepicker :: how can i set it in 'hh:mm:ss' format?

Question: How can I set a particular format in bootstrap 3 Datetimepicker?. The format should be "hh:mm:ss" and I don't want "AM" and "PM". Actually, this is for selecting Hours, minutes and seconds. I tried with this code,but it is not working.

        <input type='text' class="form-control" id='datetimepicker4' />

I want to get it to appear like this -
Answer: You can use format option to set the date format you prefer. In your case you can have:
$('#datetimepicker4').datetimepicker({
    format: 'HH:mm:ss'
});

Comment: You're welcome! If you feel an answer solved the problem, please mark it as 'accepted' by clicking the green check mark. This helps keep the focus on older SO which still don't have answers.
Comment: But I had to include the momentjs.
Comment: As you can see from ["Installing" section](https://eonasdan.github.io/bootstrap-datetimepicker/Installing/), you need to include momentjs to make bootstrap-datetimepicker work properly.


url issues with django

Question: I can't get my urls to work for django no matter what I try
from django.contrib import admin
from django.urls import include, re_path
from django.conf.urls import url
from catalog import views

urlpatterns = [
    re_path(r'^admin/', admin.site.urls),
    re_path(r'^fruit/?$', views.fruit_catalogue, name='fruit_catalogue'),
    re_path(r'^fruit/?$', views.fruit_details),
    re_path(r'^fruit/(?P<fruit_id>[1-7]{1})/?$', views.fruit_details),
]

Comment: why do you have ? at the end of your regex, also which path are you trying to get
Comment: The patterns for `fruit_catalogue` and `fruit_details` are the same. How do you expect the view `fruit_details` to be used? Django always uses the first matching url pattern for a request so `fruit_details` will never be used, instead `fruit_catalogue` will be used.
Answer: There are 2 url.py files that you should check for the correct functioning of the URLs.
First the one, that is in your project, that should look something like this:
from django.contrib import admin
from django.urls import include, path
from django.conf import settings

urlpatterns = [
    path('admin/', admin.site.urls),
    path("", include("NAMEOFAPP.urls")),
]

and the other is inside your app. and a simple version of it should look something like this:
from django.urls import path

from . import views

urlpatterns = [
    path("home", views.index, name="index"),
    path("login", views.login_view, name="login"),
    path("register", views.register, name="register")
]

Try to use this same setup and you should be perfectly fine.

url issues with django