binaryreader memory leak windows phone 8

Question: I'm trying to figure out what is keeping memory around for my Windows Phone 7.1 application.  The application downloads full resolution images from SkyDrive. It wires those images to Image elements in and displays them on a canvas.  I've been playing with this for a while (way too long!) and recently re-wrote my code to manually download the images as follows since I was getting tragic memory leaks using BitmapImage.SetSource(new URI(etc.)). It's much better now, but I still have leaks.  Wondering if someone can spot it in my code, much appreciated!
Here's the image from the memory profiler:
http://sdrv.ms/18aXLja (not enough reputation here to post the image directly, sorry)
Here's the code that is making the calls.  This code is triggered by the OpenReadCompleted event of a WebClient instance pointing at the image URL. This code runs for each Image Load in the diagram (so 56 times to be exact).  What I can't figure out is:
- why the memory stream remains in memory after it is closed (what's not shown in the image is there is a separate allocation on the Heap for BitmapImage.Sour).
- Why are BinaryReader allocation still on the heap
- Why are all the ExpandArray allocations still on the heap.
Thanks in advance for your insights!
 void wc_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
    {
        App.Progress.ProgressHide();

        if (null != e.Error)
        { return; }

        int index = iCenterImage;

        if (null != e.UserState)
            index = (int) e.UserState;

        MemoryStream ms = new MemoryStream(350000);
        //MemoryStream ms = new MemoryStream();
        BinaryReader br = new BinaryReader(e.Result);

        int bytesRead = 0;
        int bufferLength = 4096;
        byte[] buffer = new byte[bufferLength];

        bytesRead = br.Read(buffer, 0, bufferLength);

        while(bytesRead > 0)
        {
            ms.Write(buffer, 0, bytesRead);
            bytesRead = br.Read(buffer, 0, bufferLength);
        }

        br.Close();
        br.Dispose();
        br = null;

        BitmapImage b = new BitmapImage();
        b.SetSource(ms);
        ms.Close();
        ms.Dispose();
        ms = null;

        if (iCenterImage == index)
        {
            centerImage.Source = null;
            centerImage.Source = b;
        }
        else if (iCenterImage - 1 == index)
        {
            leftImage.Source = null;
            leftImage.Source = b;

        }
        else if (iCenterImage + 1 == index)
        {
            rightImage.Source = null;
            rightImage.Source = b;
        }
    }

Answer: Don't call manually Close()/Dispose() on streams and readers. Use using block.
For every instance in memory profiler you can see callstack to understand who allocates that object.
Basically there is a known memory leak in windows phone image stuff (internal image caching)
Try to replace this line
rightImage.Source = null;

with
(rightImage.Source as BitmapImage).UriSource = null;
(rightImage.Source as BitmapImage).SetSource(null);


Melting ice under pressure

Question: If we put a cube of metal on ice (ice with a certain thickness), under which conditions the cube will penetrate the ice? and how can we calculate the velocity of penetration?
Answer: The answer to your first question is contained in the phase diagram for $H_2O$ shown here.

Note how the line separating ice from water, line A to D, is negatively sloped.  This means that if you start in the solid phase and apply enough pressure (move upward on the Y axis), you will incur a phase change to liquid.
So to answer you question, one just needs to know the temperature and the pressure that the metal cube is exerting on the ice.  The latter, is of course, mgA, where m is the mass, g is the acceleration due to gravity and A is the area of a metal cube face.  If the calculated pressure at the known temperature puts you above the line A to D, then the cube will melt the ice and penetrate.
As far as the velocity of penetration, that of course would be related to how fast the ice is converting to water. It certainly would seem to be pressure dependent, but a complicating factor seems to me to be that the downward pressure will change as the block begins to displace water - i.e. it will begin be supported by some water and that will change the downward force.  Perhaps I am wrong about this and someone will correct me, but I don't think we can answer this part.
Edit: Further to this, I found this on the web.  Note how no equation is derived for the rate of melting under a given pressure.  I don't think, given the information provided, there is a closed form answer to this part of the question.
Answer: First part is answered by @CGS.
Answering second part in a strictly ideal sense, with following assumptions:

no heat sources around (ice doesn't melt on its own, except due to pressure).
metal is at same temperature as ice.

We can find the volume of ice molten after the metal cube crosses a distance $x$. With this, we can find the extra pressure accumulated due to water. We can then find the rate of melting of ice at that temperature, and hence the rate of the metal cube moving downwards at that point. Using the above and some calculus, you can get the expected answer, as a function of time.

Melting ice under pressure


Driving a random quote like functionality with database

Question: I want to have functionality like this:
A random quotes appears in particular section of the website (say sidebar) after a particular amount of time(say everyday).
I want to power it up using a new table in the database.
So maybe I will have these columns-

Quote_Text
Quote_Timestamp
Quote_weblink (if any)
Quoted_by

etc.
Can you help me get started on the code?
I know sql and can learn requisite php (I know other languages like java, c++ etc). But I don't have any experience with CSS (apart from some basic syntax).
Comment: Ok then I will remove that part and ask for the coding help.
Comment: Start with [custom post types](http://codex.wordpress.org/Post_Types#Custom_Post_Types) and [custom fields](http://codex.wordpress.org/Custom_Fields), no need for a new table.
Comment: Please stop using the wordpress.org tag
Comment: how will it give you extra flexibility? there's already a whole API built to work with the native content types. spend your time on parts that aren't already built for you.
Comment: To get you properly started on this site, please read [ask] and feel free to take a [tour]. Also, for any additional info, please visit [help]
Comment: Plugin recommendation is out of scope.
Comment: Thanks Pieter for applying the correct tag. I was unsure of the tag after I removed the plugin-recommendation tag.
Comment: @Milo what if I don't want to use any custom post type and custom fields? I think this will give me extra flexibility.
Answer: From your comments I don't really know why you should not make use of custom post types and custom fields.
So what is you have extra flexibility from the above. IMHO, extra flexibility is always a plus when attempting something like this. The other plus points here are that you don't have to make use of extra functions to create these functionalities, neither would you need to create extra db fields (which I will not recommend you to do, I really don't see the need for extra db tables here)
I think the problem here is a lack of implementation. Here is a basic idea:
Your first step will be to register a custom post type. This will just be a basic custom post type which you can decide to exclude from search and having a separate single view.
The important part here would be to enable custom-fields in the supports argument
Here is a modified example from the codex
function codex_custom_init() {
    $args = array(
      'supports' => array( 'custom-fields' ),
      'label'    => 'Quotes'
    );
    register_post_type( 'quotes', $args );
}
add_action( 'init', 'codex_custom_init' );

Please see the link given above for more examples and information on registering custom post types
When you create a new quote, you can now create and set your custom fields accordigly. Name your custom fields according to the fields in your question. The values will be the information that you will enter that you will need to display. Also, have a good look at the link provided to learn how to use custom fields. You might also be interested in this post
When it comes to displaying, you will need to make use of a custom query and transients. We will make use of WP_Query for the custom query which will display the quotes and the Transient API which will rotate the quote on a daily basis. Again, go and read and play with examples from the links given.
Here is a concept query (modified from the codex, untested)
// Check for transient. If none, then execute WP_Query
if ( false === ( $quotes = get_transient( 'daily_quotes' ) ) ) {

      $quotes = new WP_Query(
   array(
'post_type' => 'quotes',
'posts_per_page' => 1,
'orderby' = 'rand'
   ));

// Put the results in a transient. Expire after 24 hours.
set_transient( 'daily_quotes', $quotes, 24 * HOUR_IN_SECONDS );
}

// Run the loop as normal
if ( $quotes->have_posts() ) {

   while ( $quotes->have_posts() ) {
   $quotes->the_post();
       $data = get_post_meta( $post->ID );

       echo 'Quote Text: '. $data['Quote_Text'][0] . '
';
       echo 'Quote Timestamp: ' . $data['Quote_Timestamp'][0] . '
';
       // Continue with the rest

   }
   wp_reset_postdata();
}

Comment: A quick question though, suppose I want to have fields for say Date on which the quote was said, and a web link to store the whole story. Will your way support those 2 fields. I was planning to have 2 columns for them say QUOTE_DATE, QUOTE_WEBLINK
Comment: I think the custom_fields will help me for this.
Comment: Yes, just extend my code. I have only added two fields as an example. As suggested, just extend on that in the same way.
Comment: I found a plugin and it used a custom database table which was what I was looking for. I will customize its code as the license allows to do so.
Answer: I found a plugin and it used a custom database table which was what I was looking for. I will customize its code as the license allows to do so


How to write a wave-fuction of bose einstein condesate bosons in second quantization representation?

Question: Can we write wave function of bose einstein condensation like this $|\psi \rangle=\frac{{c^{\dagger}}^N}{ \sqrt{N!}} |0\rangle$. Or it will be different?
Answer: In second quantisation, you would write it as:
$$ |\mathrm{BEC}\rangle   = \frac{1}{\sqrt{N!}}(a^\dagger_0)^N\,|0\rangle, $$
where $a^\dagger_0$ is the (bosonic) creation operator for the $\mathbf{k} = 0$ state.


What is the difference between 에서 and 에다(가)?

Question: Are these two different in some way? Are they interchangeable? I started reading a webtoon and saw this grammar being used in a dialogue: "너 진짜 길에다 토하면 버리고 갈 거야!"
If instead it were: "길에서" would the meaning/nuance remain the same?
Answer: Depending on which verb you use, 에서 is used for either the location (where it happened) or the source (where the movement started).  For example:

산에서 점심을 먹었다. I ate lunch on the mountain.  (location)

산에서 내려오니 저녁이 되었다.  When I climbed down from the mountain, it was evening.  (source)

토하다 does not really need a source, so 에서 would mean a location.
On the other hand, 에다(가) is used for destination.  I think it's mostly used in the sense of "location where you place something (onto)."  E.g.,

가방은 의자 위에다 놓아 두세요.  Please leave your bag on the chair.

열쇠를 집에다 두고 왔다.  I left my key at home.

간장에다 식초를 탔다.  I added vinegar to the soy sauce.

So, I think "길에다 토하다" and "길에서 토하다" are very similar, but there's a subtle distinction.  In the former, 길에다 is the destination of the vomit, i.e., you threw up onto the street and the vomit ended up on the street.  On the other hand, in "길에서 토하다", the street is where the action happened.  You can even combine them:

달리는 택시에서 창밖에다 토했다.  I threw up out the window while (seating) in a running taxi.

화장실에서 변기에다 토했다.  I threw up onto the toilet in the bathroom.
Answer: In this case, 길에다 토하면 and 길에서 토하면 are very similar. But, there is a difference.
에다(가) means same as 에, so 길에다 토하다 means throwing up 'on' the street, so you throw up and then the vomit 'arrives' at the street. And 길에서 토하다 means that, the 'behavior' of throwing up is 'achieved' at the street, so it is saying that the place of the behavior is the street.
So, if you throw up in the cup at the street, it can be written 길에서 토하다, because no matter where your vomit arrives at, like in the cup or anything, you are still throwing up at the street, so 길에서 토하다 works. But we can say 길에다 토하다 doesn't work, you threw up in the cup, not on the street. So in this case, you can write 길에서 컵에다 토하다, which means 'throw up in the cup at the street'. Your behavior of throwing up is achieved at the street but the destination of vomit is your cup, not the street.
So 길에다 토하다 implies 길에서 토하다. If you throw up on the street, it means you throw up at the street, but the converse does not hold, because of many counterexamples of throwing up in a cup, tissue, etc.


How do I disassemble a VC++ application?

Question: I believe the application has some parts that target .NET, and some that don't. I'm particularly interested in looking at the resource files, if there are any.
Answer: If you want to disassemble native x86/64 app use IDA, .NET exe/dll can be disassembled using Reflector. There are tons of utilities to extract resources. Can you elaborate your question a bit?
Comment: Aku, thanks for the response. I'd be happy to elaborate, but I'm not sure what else to convey to help people give better answers.
Comment: Esteban, I mean there are a lot of different esource types, what resource you want to extract?
Answer: To add to aku's excellent answer, for English speakers, IDA Pro is available at http://www.hex-rays.com/.
Answer: Looking at the resource files isn't really "disassembling" (not really) and if that's all you want to do you can just open the .exe or .dll inside Visual Studio or a similar tool and it will give you a resources view.
Answer: I would too highly recommend IDA for reverse engineering if you want to see the assembly code and how the binaries have been compiled/linked.
To simpley see "inside" binary files (exe, dll, sys, ...) try CFF Explorer, its free and its great:
http://www.ntcore.com/exsuite.php
you can examine the binary files structure in great detail including resources.
If CFF Explorer is not enough then try PE Explorer which costs a little bit:
http://www.heaventools.com/
Answer: Do not get scared by the prices, the freeware version (available from hex-rays.com) is perfectly sufficient for reversing Win32 x86 code.
Answer: PE Explorer is definitely the best resource viewing tool, but you might want to have a look at its "resource-only" version - Resource Tuner.


If a completely open choice videogame was made, what would be the precautions?

Question: Globally, if an easily accessible videogame allowed a gamer  to do anything in a realistic setting,(from strategically and realistically solving world hunger to planning a multi-billion dollar sex trafficking system, or planning a genocide (in First person)).
would the good outweigh the bad?
Comment: Is the video game single player or a MMORPG? I.e., are all of the other "people" computer-controlled or human-controlled? If it's the latter, Second Life is a thing that exists.
Comment: What is the bad? What bad side effects do you have in mind?
Comment: Consider that existing video games already allow you to take part in any number of illegal activities. (Grand Theft Auto springs to mind)
Comment: Important question: what happens to a player who gets injured or even dies ingame? Does the game have ANY consequences in the real world (except the obvious ones that result from interaction between players or lack of interaction between player and non-player?)
Comment: Have a look at Brandon Sanderson's novella *Perfect State*, which takes this basic idea to extremes: all of humanity is now "brains in jars", with each person hooked up to a hyper-realistic VR simulation in which they are the Chosen One, the most important person (and only non-AI character) in their entire world, a world meant to maximize happiness and sense of achievement for them personally.  Of course, not everyone is benevolent about it...
Answer: Assuming that this is a realistic simulation:
What's my motivation to do anything good?
If I want to do good, I can do it in real life and actually do good. Sure, doing good likely takes resources, but I strongly suspect that saving those resources doesn't weigh up against the knowledge that you're investing effort in effectively achieving nothing.
If I have a desire to do bad however (that is, things that are not allowed), then I have all reason to do this in a game, since my senses will be tricked into thinking that I'm actually doing bad and my brain will reward me just the same without those pesky cops or my annoying conscience coming after me.
Answer: No , the bad will outweigh the good.  Reason  We, as humans do not always hate sins or crimes or illegal activities. The reason that we do not do them is law, fear and pressure of society. Imagine if you were told that you can do anything for one day and you wont be charged for it, you would do more bad than good. You would of course rob a bank, drive insanely fast, break things but you wont be that much tempted to help a beggar, teach kids or participate in any socially ethical activity.  Same is the deal with video games. We already have multiple (many many) video games that allow us to commit illegal activities like theft, killing, murder, racing, drifting and never for once do we hesitate from doing these activities. So, if we are provided with a game that allows us to do anything, I believe more people would do only immoral and bad things and even those who will try to do good things will also try the bad ones at some point.

Apart from that, your question demands the precautions while in your context your question is different. Can you re-write that
Comment: I think one of the reasons why violent games are popular is because they're completely detached from reality. I'd imagine many people, if given the opportunity you mentioned, wouldn't be nearly as violent as they are in games like GTA, simply because things like killing an NPC has far fewer moral qualms attached to it than killing another real human.
Comment: Of course, if the game is a "realistic setting," then there would be more consequences for bad actions than most video games currently have. Getting shot in a gunfight with police will not result in you walking out of the hospital moments later with half of the money you had before.
Answer: If it's a MMORPG, the problem with being able to do anything means one person's fun is quite likely another person's terrible experience.
Since its more likely that someone doing bad deeds will negatively impact more "positive" players, the positive players are more likely to leave.
If nothing is addressed, this means you end up with a community of mostly negative players.
This is why teamwork is rewarded better, and many forms of griefing prevented, in most, but not all, MMORPGs.

Alternatively, your question seems to suggest that this is a single-player game that is simulated so accurately that you could practice to pull off whatever you wanted in the simulation and then apply that strategy to the real world.

This means corporations could see how branding and certain items would do before even creating them - or see how to defeat their opponents.
This means military operations could be practiced to be pulled off near perfectly - or practiced to be defended near perfectly
This means a general civilian could practice for a job interview and go with the best result - and the interviewer can practice to determine the best candidate.

I personally think more "good" than "bad" would be achieved with this, but it would still be a never-ending battle. Similar to how virus and anti-virus creators will always be trying to defeat the opposition. Thankfully, the "good" side is (hopefully) better funded.
That scenario also suggests that whoever provides data into this game has perfect data about every place and every person in the world. Also, its able to determine what every individual choice will be as well as determine what would happen for random elements such as flipping a coin. That seems pretty impossible to me, it's pretty much like being able to tell the future.
Answer: The question is quite interesting. A few years ago i was at a convention where Peter Molineux was one of the speakers. He was asked if it was not the case that in his games (like Black&White for example) most players chose the bad side. He said (i have no quote for that, sorry) that in fact and surprisingly for him, significantly more players chose the good side.
I think that one point here is that we have (mostly) been brought up to distinguish good from bad, so you might say we have been conditionned to prefer the good side. Of course, fear of punishment would be a reason not to do bad, but doing good is also rewarding in it's own way.
Plus, in a game environment, people might like the challenge of not choosing the easy way.
@Muxammil Bashir suggests most people would do bad things if they thought they would get away with it.
I do not agree, because we all have our own conscious that will punish us. Admittedly some more so and some less, but: the original post suggests a "realistic setting", so i guess it would be acceptable to assume that this will include other people (be those NPCs or players), and those do threaten a bad character with punishment. Even more so in a game, because if you for example think of any setup like nazi germany, the good-doers were massively threatened, which slowed them down considerably. In a game environment one might much more easily accept the risk of death when confronting the bad.
@overactor suggests that if i wanted to do good i could as well do it in real life. The resources mentionned might actually hinder that. Plus, a game environment would allow for experimenting: If i think my ideas will do good but see a risk that it might turn out bad, i could always try them in such a game setup without actually harming real people.
That said: The experience of Peter Molineux plus my own wishful thinking makes me suggest that in fact the good might outweigh the bad in such a setting.
Answer: I would say that the good will outweigh the bad. It has been seen in a bunch of open-ended games (at least those which collect such data) that people tend to stick to good. There are a few simple reason for that, actually:

Being bad is way to easy (in video games, but possibly IRL too).
Conversion is one sided

If you play good and you slip and make a bad deed, your behavior is now "questionable". If you play bad and you accidentally do good, you are still (mostly) bad.
It's easy to convert from good to bad, but it's hard to get redemption if you want to go the other way around.

If a game is good you will form a bond with "yourself". Let's be honest here, people can and do get emotionally attached to their avatar. Your avatar (especially in first-person games) is you. Naturally you will be good.

All and all, gray will dominate - stealing, killing bad people and all that, but coldblooded murder and similar will be no more frequent than IRL.


What is the difference between "go on" and "go for" vacation?

Question: For example,
I will go Mexico for vacation next month.
Vs.
I will go on vacation to Mexico next month.
Is there any difference? If not, which one is more common In colloquial AmE?
Comment: If it were me, I'd say either: "I will go **on** vacation to Mexico next month," or, "I will go **to** Mexico for **a** vacation next month." (I'd include an article with the _for_ form.)
Answer: To go on vacation is to take a vacation.
But in my AmE dialect questions like these:
Where are you going for vacation?
-- I'm going to summer camp.
What are you doing for vacation?
--I'm working as an intern in a biology lab.
would be used when the vacation is not at an arbitrary time during the year (as the person taking the vacation sees fit) but at a time that occurs regularly, such as "summer vacation" (the summer months when school is not in session) or "winter break" (the time between Fall and Spring sessions).
What are you doing for winter break?
means "What are you planning to do during winter break?"
In this pattern, for is complemented by a noun-phrase which refers to a time-span.
What are you doing for the year?
What are you doing for the summer?
What are you doing for the Fourth of July?
What are you doing for the next hour?
What are you doing for the next fifteen minutes?
Comment: Can I say "What are you going to do for this weekemd?" or "What will you do for this weekend?"?  What are the differences?
Comment: @Jokaec: "What are you doing for *the* weekend?" and "What are you doing *this* weekend?" are the most likely forms, although "...for this weekend" is not an impossibility.
Answer: They mean almost the same.
I've searched the collocation on vacation. The Longman says that go on (a) vacation is more common in colloquial, so does the Excitingfinance.
Answer: In my experience, "go on" vacation is more common. However, both will be understood:
"I will go to Mexico for vacation" means the same as "I will go on vacation to Mexico."
As a side note, it is even more common to say, "I'm going on vacation to Mexico next month," replacing "I will go" with "I'm going."


Add role in ASP.NET Identity

Question: How can I add a Role in the new ASP.NET Identity system (1.0)?
There is a UserStore class but no RoleStore class.
I can't find any documentation on this issue.
Comment: There is a Simple Role providers which lets you restrict access to parts of your application by Roles. You can easily create Roles such as "Admin" and add Users to Roles.
Answer: RoleManager = new RoleManager<IdentityRole>(
                  new RoleStore<IdentityRole>(new MyDbContext()));
var roleresult = RoleManager.Create(new IdentityRole(roleName));

Comment: We could also put this in our Startup.Auth.cs file as follows. ``RoleManagerFactory = () => new RoleManager(new RoleStore());`` and then copy the usage of the UserManagerFactory.
Comment: instead of    MyDbContext() use  ApplicationDbContext()   or search for your IdentityDbContext inheritedclass
Answer: Starting with the .NET Framework 4.5, Windows Identity Foundation (WIF) has been fully integrated into the .NET Framework.
I would advice to examine the possibility, in my opinion the preferred, to implement Authorization through Claims (Expressing Roles as Claims).
When the IsInRole() method is called, there is a check made to see if the current user has that role.
In claims-aware applications, the role is expressed by a role claim type that should be available in the token.
The role claim type is expressed using the following URI:
"http://schemas.microsoft.com/ws/2008/06/identity/claims/role"
So from the UserManager you can do something like this (without the RoleManager):
var um = new UserManager();
um.AddClaimAsync(1, new Claim(ClaimTypes.Role, "administrator"));

Claims can simplify and increase the performance of authentication and authorization processes.
You can use the roles stored as claims to eliminate back-end queries every time authorization takes place.
Using Claims you will not need the RoleStore anymore (at least for the equivalent authorization purposes...)
Comment: Is there a new URI for the role claim types? Because the provided URI is not available..
Answer: I used below snippets in one sample asp.net web page page_load for starting to grasp the way ASP Identity works
   UserManager userManager = new UserManager();
    var roleStore = new RoleStore<IdentityRole>(new ApplicationDbContext());
    var roleManager = new RoleManager<IdentityRole>(roleStore);
    var applicationRoleAdministrator = new IdentityRole("superadmin");
    if (!roleManager.RoleExists(applicationRoleAdministrator.Name))
    {
        roleManager.Create(applicationRoleAdministrator);
    }
     ApplicationUser applicationUserAdministrator = userManager.FindByName(User.Identity.Name);

    if (!userManager.GetRoles(applicationUserAdministrator.Id).Contains("superadmin"))
    {
        Response.Redirect("~/account/login.aspx?ReturnUrl=" + Request.Url.AbsolutePath);
    }

Of course below ApplicationDbContext is automatically generated with ASP.NET 4.5+ templates like below
 public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
    {
        public ApplicationDbContext()
            : base("DefaultConnection")
        {
        }
    }

Also Create application Role Manager class too
public class ApplicationRoleManager : RoleManager<IdentityRole>
{
    public ApplicationRoleManager(IRoleStore<IdentityRole, string> roleStore)
        : base(roleStore)
    {
    }

    public static ApplicationRoleManager Create(IdentityFactoryOptions<ApplicationRoleManager> options, IOwinContext context)
    {
        //return new ApplicationRoleManager(new RoleStore<IdentityRole>(context.Get<ApplicationDbContext>()));
        return new ApplicationRoleManager(new RoleStore<IdentityRole>(new ApplicationDbContext()));
    }
}

also add below line in your startup.Auth.cs => ConfigureAuth(IAppBuilder app) method
  app.CreatePerOwinContext<ApplicationRoleManager>(ApplicationRoleManager.Create);

And then in your controller:
private ApplicationRoleManager _roleManager;

public ApplicationRoleManager RoleManager
{
    get
    {
        return _roleManager ?? HttpContext.GetOwinContext().Get<ApplicationRoleManager>();
    }
    private set
    {
        _roleManager = value;
    }
}

I am new to this Identity Stuff and I am not sure if it is necessary or I am doing it clean and right, but these steps worked for me
Answer: ASP.NET identity is claims aware with respect to roles. That really confused me because in the previous system you configured membership and role providers in web.config.
The issue for me is that I have code like this:
HttpContext.Current.User.IsInRole("some role")

Fortunately, this logic still works. You can see the logic in the CreateAsync function in ClaimsIdentityFactory.cs which is in Microsoft.AspNet.Identity.Core.  One of the arguments is UserManager. It asks it if it SupportsUserRole and if so then it calls GetRolesAsync and adds each role as a claim to the ClaimIdentity. There is no need to do this yourself.
IsInRole uses claims as described here:
http://msdn.microsoft.com/en-us/library/hh545448.aspx
Comment: ASP.NET Identity (at least v2.0 from what I can tell) does indeed have a `RoleManager`; it's located in the `Microsoft.AspNet.Identity` namespace and you'll find it being used in several of the sample/starter applications I believe.

Add role in ASP.NET Identity


Internal storage scheme for storing private keys inside an HSM

Question: I am trying to understand the internal storage scheme used by HSMs to store the private keys. My question is: are keys stored in plaintext inside an HSM? Are there any variations?
Answer: Every HSM will be a unique implementation.
I know that the IBM PCIe Cryptographic Coprocessor stores master keys inside the HSM, which are used to decrypt the keys that are kept encrypted in an external database.  The older version used 3DES to encrypt the keys; I don't know if V2 still uses 3DES or if they're using AES now.  Tampering with the HSM (or even violating its environmental envelope of temperature and humidity) securely destroys the internal keys and certificates, as well as rendering the HSM itself physically inoperable.
Inexpensive HSMs, such as a PIN pad you'd find at the grocery store, maintain their key state in battery-backed RAM.  Note that because PIN pads are out on countertops where they can be stolen or tampered with, they aren't trusted with a "master" key that's the same for all PIN pads.  Instead, they follow a key generation protocol called Derived Unique Key Per Transaction (DUKPT).  DUKPT specifies that each pad has a unique key injected at a secure facility before being shipped to the stores.  The PIN pad's unique key is derived from the system's base master key and the PIN pad's serial number, and DUKPT implements a "future key" generation scheme, which continually rotates forward with every use, destroying the old keys as it goes.  Attempting to violate the case will result in the CPU quickly scrambling the RAM and then cutting power to it, wiping the future key state.
I'm sure other HSMs have different variations on the theme, but they all behave in a similarly self-protective fashion.
Comment: Thanks for your reply. However, what I wanted to know was whether the key is stored in plaintext or after encryption inside an HSM. I am sorry if I was not very clear in my original message.
Comment: The key exists in cleartext inside an operating HSM, or else the device is useless.  And it doesn't really matter how the bits are kept in the storage medium.  If it's stored on a separate chip from the CPU, whatever stored bits are transmitted to the CPU are the "key to the key".  Whether it's stored on the same chip as the CPU, or baked into an FPGA, it still exists.  For a more specific answer, you would have to ask your HSM vendor, as each device is free to implement their solution however they see fit.
Comment: That was exactly what I was looking for. Thanks for your help.
Comment: How the key is "stored" on the HSM is also vendor dependent.  The device /probably/ has an internal master key that is used to encrypt anything "at rest" (keys have to survive a reboot, so they will be stored in flash or other nvram).  When at rest, they should be encrypted using the internal master key, so that if the device is compromised the only thing that needs to be destroyed to protect the keys is the internal master key.  With that gone, the data at rest is no longer useful.  The architecture will cache keys in use, in ram, and those will probably be 'in plain'.


Why did I get less magnetic strength with more windings on a coil?

Question: I wound two coils (A & B) using 27 AWG winding wire. Each coil was wound on a ¾ inch thick x 3 inch steel rod. Coil A had 7000 windings. Coil B had 4600 windings. Coil A measured 128 ohms. Coil B measured 76 ohms. I connected a 6 volt lantern battery to each coil thinking coil A would produce a much stronger magnetic core but it turned out to be the opposite. I don't have a gauss or flux meter. I simply measured the difference in strength with a piece of  flat iron. I'm guessing it has to do with volts vs. resistance. My question is…is there a "sweet spot" with volts & ohms when winding a coil for maximum magnetic core strength?
Answer: It's all about Amp-turns and how well those Amp-turns couple to the rod. If it's a fixed voltage source and fixed wire-gauge and all the turns are tightly wound on the rod, then the resistance is proportional to the number of turns, the current is inversely proportional to the number of turns, and the Amp-turns doesn't change at all.  In your case, the extra turns you added were further from the rod (less tightly coupled) and had a larger circumference (adding disproportionate resistance) so you ended up with fewer Amp-turns more poorly coupled.
To get the maximum magnetization, you need to know the internal resistance of the battery and have freedom to choose the wire gauge. You also need to make some estimate of the size of the "winding window".  For a rod that's not easily defined, but you can probably usefully stack the wire up to a thickness of about 1/3 the length of the rod at most.
The coil resistance should match the battery internal resistance to get the maximum power into the coil. Given the coil resistance and the winding window area, you can then figure out what wire gauge to use (or you can put wires in parallel to create an effectively thicker gauge).
Be careful! With this recipe it is very likely you will cause both the battery and the coil to overheat.  This high-power approach may also be unnecessary anyway because the steel core will be driven well into saturation.
Comment: I spent the evening researching what a batteries internal resistance is. I found that a 6 volt battery has an internal resistance of 0.3 ohms. To find the voltage going through the coil I used this formula from the internet.
[6V - (128.3 ohm x .046A) = 6V – 5.9V] = 0.1V
Is this correct?
Also you mentioned a rough rule of thumb for determining number of windings is that they should roughly be 1/3 the length of the rod. Could that be 1/3 the diameter? I've learned a lot tonight. Hope I got it right...Thanks
Comment: I think the 0.1 volt is the voltage drop inside the battery, but you're definitely on the right track!  The winding window is well defined for a ring magnet but not for a rod.  It's more a function of length than diameter.  In your example, I think you're ok piling turns up to a thickness of about 1 inch in the middle of the rod, but drop that down to 1/2-inch as you approach the ends of the rod.  PS. if you've only got one wire gauge available, just put several separate windings and connect them in parallel.
Answer: Here is your problem in a nutshell:
When you add a turn to the coil, you add to its inductance but you also add to its DC resistance. When you drive it with the same power supply voltage (6 volts), the incremental increase in inductance is cancelled by the incremental increase in resistance, because it reduces the current through the coil.
The fundamental strength of the electromagnet depends on the product of amps through the coil times number of turns. The optimum electromagnet design for a fixed value of the driving voltage is then the one which maximizes this product, which occurs when
(number of amps) = (number of turns).


What is the recommended maximum number of co-authoring authors?

Question: When configuring the maximum number of co-authoring authors as instructed here, what is the recommended maximum? Or is there a guideline for computing the recommended maximum number?
Answer: As per the Software boundaries and limits for SharePoint 2013 This property only applies to Microsoft PowerPoint 2010 presentations and Microsoft Word 2010 documents.
Recommended maximum number of concurrent editors is 10. The boundary is 99. If there are 99 co-authors who have a single document opened for concurrent editing, each successive user sees a "File in use" error, and can only open a read-only copy.
More than 10 co-editors will lead to a gradually degraded user experience with more conflicts, and users might have to go through more iterations to successfully upload their changes to the server.
As per the link you mentioned, There is no upper limit to the number of users who can co-author Microsoft OneNote notebooks.


Modify the display of a list webpart on default page

Question: I wish to beautify my SharePoint 2013 home page. What I want is that users should be able to add their own webparts and apply a design template to display their items so that the links may be are displayed in a different format from the default. Can I create a display template and apply it to a list view web part. I can see there is an option to link an xsl file too. Not sure what that is for?
Answer: You can use JSLink to change the UI of the OOTB List view web part. JSLink can be used to change the UI at Webpart level and also at List view level.
If you choose to associate the JSLink at webpart level, then the custom UI will be applied to only that instance of List view webpart.
If you associate the JSlink at List view level, then custom UI will be applied to all List view webparts using that view.
See this blog


Is it better to move unrelated content to another domain?

Question: I have an ecommerce site with an online community on a different subdomain. The community ranks for different keywords.
If I would move the community to a different domain would that impact the SEO of the ecommerce site in any meaningful way?
Answer: It may impact your rankings as the sub-domain is part of your main domain. It's content could be helping your rankings. Is the communities overall purpose focused around the products you are selling? If so you may want to create sub-forums if you're running a forum and moderate threads to be kept on topic.
I know of a few websites which have forums on sub-domains and i'm sure it's helping with sales. I'd try and use the forum to generate more sales. Send targeted emails to members, put up relevant ads within different forums and threads etc. But I would not remove it from my site if the initial reason was to have a forum related to my products.
Comment: Google ranks pages individually not an entire domain. So while your ecommerce site has relevance for a few topics and categories, your forum is relevant for other topics. If it's not inteferaing with your ecommerce site I would leave it and begin placing ads to test their conversions. Run searches in the forum for anything that can bring up threads which might show someone's interest in what you sell. Or add amazon affiliate products through out which are better suited to the forum. If they are telling jokes, put up a few ads for books on jokes
Comment: thanks. No, the community is mostly for sharing entertainment and jokes. The keywords that send the most organic traffic to the community site differ greatly from the ecommerce site. Couldn't that even hurt the ecommerce site?
Answer: For the keywords rating/calculations - every subdomain can be separate item as with the main domain. Most of search engines allow separate sitemap file for every subdomain you wish to submit to them (Goggle Webmaster Tools, Bing/Yahoo Webmaster Tolls, etc.).
The website traffic ranking (Alexa etc) is different - there website item/record covers the main domain and all added subdomains.
In other words the best solution is to stay on subdomain - as it will keep separate the keywords rating (in Search Engines), and will combine/increase the whole website traffic ratings.
Comment: [Subdomains are not viewed as a separate website](http://www.mattcutts.com/blog/subdomains-and-subdirectories/).
Comment: @JohnConde - I not state that the subdomain is separte site.
Comment: @JohnConde - To clear this we must define for who is that statement. For traffic rating the site is one, but for the keywords it's not. There in reality **the page** alone is rated. I have blog on one of our websites, which is posted on Blogger - hosting, management, everything is done via Blogger and on our server we have only DNS for redirecting. You can decide do the blog subdomain is separate site or not - but definitely its not physically linked with our server.


Euler-Lagrange Equation: From boundary value to initial value problem

Question: In the principle of stationary action, the initial and final points in configuration space are held fixed. This is a boundary value problem. However, this principle leads to the Euler-Lagrange equation which is a differential equation and an initial value problem. The end point of motion does not appear anywhere in the Euler-Lagrange equation. Why is this so? For example, if I want to solve for projectile motion, the Euler-Lagrange equations turn out to be Newton's second law. Now, Newton's second law is an initial value problem. Why do the Euler-Lagrange equations turn out to be an initial value problem when they are derived keeping the boundaries in configuration space fixed?
Answer: This is because of a mathematical property of variational calculus that I propose to call 'Jacob's lemma', after the mathematician who first pointed it out. Presumably this mathematical property has been rediscovered independently several times. The 'Jacob' is 'Jacob Bernoulli', brother of Johann Bernoulli.
To put Jacob's lemma in context: some history of variational calculus:
Johann Bernoulli had submitted the 'Brachistochrone problem' to his fellow mathematicians.
(Every introduction to variational calculus in physics mentions the brachistochrone problem, so I'm assuming you are familiar with it.)
Jacob Bernoulli noticed the following:
We have that the solution of the problem is a curve that has over its entire length minimizes the time to travel from initial height to final heigth. If you divide that curve in two sections then each subsection has that property too: to travel from initial height to final height the solution is a minimum. You can continue subdividing into arbitrarily short subsections, down to infinitisimally short subsections; the minimizing property remains .
Thus, Jacob Bernoulli pointed out, it should be possible to find the solution using differential calculus.
In the Feynman Lectures there is also a lecture titled "The principle of least action"
Quote from that chapter:

Now if the entire integral from $t_1$ to $t_2$ is a minimum, it is also
necessary that the integral along the little section from a to b is
also a minimum. It can't be that the part from a to b is a little bit
more. Otherwise you could just fiddle with just that piece of the path
and make the whole integral a little lower. So every subsection of the
path must also be a minimum. And this is true no matter how short the
subsection.

(In the lecture Feynman doesn't mention whether he is aware of the every-subsection-is-minimal property through learning or whether he noticed it independently.)

General discussion
The constraint that the solution is an extremum for the entire length of the curve is a very tight constraint.
It is so constraining that that it connects the problem all the way back to differential calculus.
Hamilton's  stationary action calls for a solution that is an extremum of the action. It is not so much that this leads to the Euler-Lagrange equation. More precisely, the extremum condition makes the problem accessible to differential calculus.
I recommend the derivation of the Euler-Lagrange equation by Preetum Nakkiran. Preetum Nakkiran points out that since the equation expresses a local condition it should be possible to derive it using local reasoning only.

[LATER EDIT]
Details of the history of the first development of calculus of variations are available in the book "A SOURCE BOOK IN MATHEMATICS, 1200-1800", edited by the mathematician D. J. Struik. (This book is part of a larger series 'SOURCE BOOKS IN THE HISTORY OF THE SCIENCES'.)
The various publications on the brachistochrone problem were in the journal Acta Eruditorum.
The treatment by Jacob Bernoulli:
Acta Eruditorum, May 1697, pp. 211-217
Jacob opens with a general discussion of any problem were a curve is sought that is the extremum of some property of that curve.

Lemma. Let ACEDB be the desired curve along which a heavy point falls from A to B in the shortest time, and let C and D be two points on it as close together as we like. Then the segment of arc CED is among all segments of arc with C and D as end points the segment that a heavy point falling from A traverses in the shortest time. Indeed, if another segment of arc CFD were traversed in a shorter time, then the point would move along AGFDB in a shorter time than along ACEDB, which is contrary to our supposition.

Next Jacob Bernoulli proceeds with a series of steps that leads to an expression that is satisfied by the cycloid. Hence the cycloid curve is the brachistochrone.
See also: visual demonstration of the equivalence of stationary action and F=ma. (Visual in the sense that all the mathematics is presented in diagram form)
Answer:
Unlike what OP seems to suggest (v3), Newton's 2nd law and Euler-Lagrange (EL) equations are strictly speaking just differential equations (DEs) without conditions. Rather the context provides the appropriate conditions, such as, e.g., initial conditions (ICs) or boundary  conditions (BCs). Together with the DEs, they constitute an initial value problem (IVP) or a boundary value problem (BVP), respectively.

The issues of ICs vs. BCs for the principle of stationary action are already covered in this & this related Phys.SE posts and this related Math.SE post.
Answer: The Euler-Lagrange equation establish the equivalence between the boundary value problem and the initial value problem. Here's one way to think about it: Suppose we only start only knowing about the principle of least action. That is, if you know $x(t_i)$ and $x(t_f)$, as the initial and final positions of the particle, then you can figure out $x(t)$, the position the particle at every moment in between. Now that you know the path, you can also calculate $v(t)=\frac{dx(t)}{dt}$. The Euler-Lagrange equation now tells you that if you start a particle at $x(t_i)$ with velocity $v(t_i)$ at time $t_i$, the particle will sure pass by $x(t_f)$ at time $t_f$. This is guaranteed by the fact that the Euler-Lagrange equation is second order in time, and hence, require 2 initial values (the position and the velocity) in order to fully pin down a solution.
Finally I wanna address what you said about why the Euler-Lagrange equation is an initial value problem. Not quite, a differential equation is not inherently initial value. I think this is also what Qmechanic alluded to in his answer. You can solve a differential equation with a boundary value condition. You can start with the Euler-Lagrange equations and ask what solution of this equation passes by $x(t_i)$ at $t_i$ and at $x(t_f)$ at $t_f$. Our physical intuition seems more comfortable with the idea of an initial value problem. A law that tells the particle what to do once it start moving. However from a mathematical point of view, both views are equivalent.


ios minutes to time

Question: I want to go from minutes as an int (eg 92) to a string of 1:32. Is there a fancy way to do this using objc or I'm I stuck with figuring it out the old-fashioned way?
Comment: Not to be cynical, but a great start would be to read the documentation built into Xcode. It is a very good resource.
Answer: I do not believe there is a function to do this, but it is simple enough to do on your own.
int hour = minutes / 60;
int min = minutes % 60;

NSString *timeString = [NSString stringWithFormat: %@"%d:%02d", hour, min];

The '02' will pad the results so there are always two digits in the minutes place. It may be useful to look at the NSDate Class Reference as it may save you time if you want to do calculations on the result.
Comment: While you CAN use NSDate for this (see netrace's answer) this is a much faster way of doing it.
Comment: This way lacks localization support, so it is really basic
Answer: I think you can find the answer here: NSTimeInterval to NSDate
The int you talking about should be NSTimeInterval (that is just double), convert it to a NSDate object and then format it using the NSDateFormatter with: HH:mm.
It can also could be more useful "extend" using categories NSDate object
@interface NSDate (Minutes)

and put there a method convert minutes to HH:mm (maybe could be better to move the format string as method parameter) so you never more need think about it.

ios minutes to time


Get all databases name present in Postgres Server in Drupal 7 Form API

Question: I was currently developing a module and I want to display the names of all the databases present in my Postgres server through a query. I want also to query and list the names of schemas, tables, field and field type of each databases. How can I do that? I want to do this because I was making an interface about database connections and configuration. Is that possible?
Comment: Drupal should only touch the databases that are configured in its settings.php file.  Being able to read all databases on the server would be an escalation vector for hackers.
Answer: One solution can be configurate the external database as a second database in settings.php.
$databases = array (
  'default' =>
  array (
    'default' =>
    array (
      'database' => 'standard_db',
      'username' => 'username',
      'password' => 'password',
      'host' => 'localhost',
      'port' => '',
      'driver' => 'postgres',
      'prefix' => '',
    ),
  ),
  'external' =>
  array (
    'default' =>
    array (
      'database' => 'external',
      'username' => 'username',
      'password' => 'password',
      'host' => 'db.external.com',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',
    ),
  ),
);

Then before you do your database queries you need to set the active database. In this example, to switch to external you need to execute db_set_active('external');
When you want to switch back to the default database you execute db_set_active();
Example code to switch to and query the external database:
db_set_active('external');
$result = db_query('SELECT something FROM {sometable}');
while ($row = db_fetch_array($result)) {
  drupal_set_message($row['something']);
}

db_set_active();

And here are the queries that I have used for a similar project.
Getting the Databases:
SELECT datname
FROM pg_database
WHERE datallowconn = true AND NOT datname = 'postgres' AND NOT datname = 'template1'
ORDER BY datname

Getting the Schemas:
SELECT schema_name
FROM information_schema.schemata
WHERE catalog_name = 'DATABASE_NAME' AND schema_name NOT LIKE 'pg_%' AND schema_name <> 'information_schema'
ORDER BY schema_name

Getting the Tables:
SELECT table_name
FROM information_schema.tables
WHERE table_catalog = 'DATABASE_NAME' AND table_schema NOT LIKE 'pg_%' AND table_schema <> 'information_schema' and table_type = 'BASE TABLE'

Getting Fields and Field types
SELECT ordinal_position, column_name,
CASE
WHEN character_maximum_length > 0 THEN concat(data_type, ' (',  character_maximum_length, ')')
ELSE data_type
END
AS data_type, is_nullable, column_default
FROM information_schema.columns
WHERE
table_schema = 'SCHEMA' and table_name = 'TABLE_NAME'

Reference

How to access the external database in drupal?
How to connect to multiple databases within Drupal
Comment: @AdrianCidAlmaguer --> Just one more question databases with a prefix pg_ are not physically visible in the postgres server. How will I find them?
Comment: @dsadsadsytryu you can read some about this here http://www.postgresql.org/docs/9.0/static/ddl-schemas.html


"The possibility I am going to lose is low." instead of "There is a low possibility I am going to lose"?

Question: Can I say "The possibility I am going to lose is low." or "There is a low possibility of loss for me" or "The possibility of loss is low for me" instead of "There is a low possibility I am going to lose"?
Comment: We say "gonna".  We don't usually write "gonna".  In general, write "going to" --  *unless* you are trying to mimic some dialect.
Comment: Ok, I changed it. Since I usually say "gonna", I had written as "gonna".
Comment: In casual communication you can write whatever you like, "enuf", "thru", "tho", "c u l8tr"  and so on.  But these sound *informal* and are usually inappropriate in any context where you want to sound like a mature adult.
Comment: Ok thanks. Don't you have answer for my question? :) (Is it wrong to put smileys too?)
Comment: Aside from what you are asking, you should use the word "probability", rather than "possibility". Possibility means being possible (and not impossible), it is either true or false, and can't be "low".
Comment: @laugh it's a good point, and you are correct.  However I think many native speakers use "possibility" in this way, even if it is not *technically* the right word.
Comment: Do you agree with him on the matter of saying "losing" instead of "loss" too?
Comment: We do not say "gonna" unless being informal with friends. I say "going to" all the time.
Comment: All of your examples sound the same to me; just different ways to say the same thing.
Comment: Are you a native speaker? I like saying gonna better. It feels more natural when I say "gonna". This is out of topic though.
Answer: There's a difference between "losing" and "loss".  "Loss" generally refers to misplacing or otherwise losing possession of something, more often than it refers to something like losing a game.

She is upset at the loss of her favorite ring.

You can talk about the loss of a game, but in your example you should say "a loss".

There is a low possibility of a loss for me.

Otherwise, all of your examples are fine, just awkward and artificial.  More common expressions might be:

I don't think I'm going to lose.
I'm not likely to lose.
There's only a slim possibility that I will lose.

You can also use chance instead of possibility:

There's almost no chance I will lose.
The chances of me losing are slim to none.

As well as many other expressions
Answer: Let's first distinguish between possibility and probability, and between loss and losing.
The possibility of an event is related to the answer to the question "is it possible?", which can be either yes or no. This is a binary value (can also be described as true/false or 1/0). If you ask "what's the possibility of winning" the likely answer is "it is possible".
What you are actually interested in is the probability of an event, which is the answer to the question "how probable is it?". Without going into too much math, the probability of an event is a number between 0 (impossibility) and 1 (certainty), typically expressed as a percentage. For example, winning a single "heads or tails" toss of a fair coin has a probability of 50%.
Losing and loss are related terms with similar characteristics: when you make a bet or an investment, "losing" describes the event that you lose (which is eventually a binary value - you either lose or not), and "loss" describes how much you lose (which is a number or an amount of property). The corresponding terms for the case you win are "winning" and "gain".
Having clarified the terms, let's examine the sentences you suggested.
If you change "possibility" to "probability" and "loss" to "losing", you would get syntactically correct sentences, with slightly different emphasis. The choice may depend on the context.

The probability [that] I am going to lose is low - This is the most natural one, and the one you should normally use.
There is a low probability of losing for me would make sense if followed by , but not for you.
The probability of losing is low for me  would make sense if followed by , but high for you.

Here are some other possible sentences, using "possibility" and/or "loss":

The probability of your loss exceeding $100 is low (e.g. if you invest your money, you may decide to sell your stock when the loss reaches $80).
The possibility of losing always exists (e.g. if you make a "safe investment", your return may be lower than the inflation rate).
There is no possibility that your loss exceeds $1000 (e.g. if you only invested $1000).
Comment: You don't agree with Andrew then? I searched and it seems that "high possibility" can be used. I had searched about it before as well. Also why do you think that I should use "losing" instead of "loss"? "Losing" doesn't sound wrong to me but also "loss" doesn't sound bad either to me.
Comment: "High/low possibility" is extremely uncommon compared to "high/low probability" as [Ngram results](https://books.google.com/ngrams/graph?content=high+possibility%2Chigh+probability%2Clow+possibility%2Clow+probability&year_start=1920&year_end=2008&corpus=15&smoothing=3&share=&direct_url=t1%3B%2Chigh%20possibility%3B%2Cc0%3B.t1%3B%2Chigh%20probability%3B%2Cc0%3B.t1%3B%2Clow%20possibility%3B%2Cc0%3B.t1%3B%2Clow%20probability%3B%2Cc0) show.
Comment: Regarding *loss* vs. *losing*: the argument here is related, but different. I will expand the answer.
Comment: "High possibility" is wrong. Being wrong doesn't mean it isn't used. People, including native English speakers, often use wrong words.


Aquarium is stuck on a nitrite spike

Question: I am attempting a fishless cycle on a small, nano-planted tank that is getting stuck on extremely high levels of nitrite. The tank has been set up for about two weeks now.
I am not dosing ammonia. I have two nerite snails in the tank that are creating some waste, so I get my ammonia from that and they are controlling any algae that might happen. My ammonia levels are usually always around 0.25 ppm.
After a water change, the nitrite spikes within 24 hours and then the nitrate will spike about 24-48 hours after that. However, the nitrite is still at extremely high levels even after the nitrate spikes.
Is this a patience game, waiting for the good bacteria to build and catch up to the output of nitrites? I have heard to do a water change when the nitrates get too high, but I don't want to disrupt the nitrite level in possibly letting good bacteria to colonize.
Any help on this would be awesome!
Thanks!
Comment: You may want to consider switching to cleaner shrimp. THE problem with snails is that they produce a lot of waste, so your nitrate/nitrite problem is not uncommon.

Also, sometimes the problem with persistent spikes is decaying matter rather than water quality.
Answer: Basically it is indeed a patience game.
But how often do you change the water, and how much? Since your doing a fishless cycle (which is indeed the recommened way to do it), you don't actually have to do water changes. If you replace to much water, it's indeed possible that your cycling has to start all over again every time.
Just let it rest for about 3-4 weeks and then check the nitrite levels. By then they should already start decreasing/be zero.
You can also find more information in this answer: How does one effectively "cycle" an aquarium?
Comment: I do a 40-60% water change about every 2-3 days because the nitrates start to spike.
Comment: I have live plants in the tank and I am worried the plants won't be enough to keep the nitrates down.
Comment: Don't worry about the nitrates yet (in fact you should not worry much about that at all).Stop doing these water changes, and just wait another 2-3 weeks. By then I assume your nitrites will already be a lot less/zero. And then you can check if it's needed to do anything about the nitrates.
Answer: It can take 4-6 weeks for your aquarium to cycle. So you just need to wait.
You don't need to do any water changes, this is only required when doing a cycle with fish so the ammonia/nitrite is kept low.
All you need to do is keep the ammonia up. Test your tank every day and if ammonia is below 2 ppm then top it up to 2 ppm. (you need to keep feeding the bacteria which is producing ammonia or they will die off)
Once ammonia/nitrites go to zero within 24 hours of being 2 ppm then you are cycled.
You just need to be patient.

Aquarium is stuck on a nitrite spike


Screen resolution lowers every time there is a kernel update

Question: Every time I get a kernel update, my screen resolution is lowered. I can fix this by switching the NVIDIA driver to a different version and then restarting. I think what is happening is that the NVIDIA driver module is not getting recompiled. Is there any way I can fix this? I have this workaround, but it's very annoying.
Answer: well there is a HOWTO: Automatically update manually installed NVidia drivers after kernel updates for you. I assume you have a driver with source version as NVIDIA-Linux-x86-173.14.05-pkg1.run
Then now ,open your terminal and type as
sudo mv NVIDIA-Linux-x86-173.14.05-pkg1.run /usr/src
sudo ln -s /usr/src/NVIDIA-Linux-x86-173.14.05-pkg1.run /usr/src/nvidia-driver

now type as
nano update-nvidia

then paste this code in it
#!/bin/bash
#

# Set this to the exact path of the nvidia driver you plan to use
# It is recommended to use a symlink here so that this script doesn't
# have to be modified when you change driver versions.
DRIVER=/usr/src/nvidia-driver

# Build new driver if it doesn't exist
if [ -e /lib/modules/$1/kernel/drivers/video/nvidia.ko ] ; then
    echo "NVIDIA driver already exists for this kernel." >&2
else
    echo "Building NVIDIA driver for kernel $1" >&2
    sh $DRIVER -K -k $1 -s -n 2>1 > /dev/null

    if [ -e /lib/modules/$1/kernel/drivers/video/nvidia.ko ] ; then
        echo "   SUCCESS: Driver installed for kernel $1" >&2
    else
        echo "   FAILURE: See /var/log/nvidia-installer.log" >&2
    fi
fi

exit 0

Then
sudo mkdir -p /etc/kernel/postinst.d
sudo install update-nvidia /etc/kernel/postinst.d

from now on wards at the time of new kernels your driver also get updates and compiles.
hope that helps.
For more information : Ubuntuforums-HOWTO
Comment: @VivinPaliath OMG!! just now I have seen your profile, you are master :) .
Comment: Jai, will do :) I know all about stackexchange etiquette; I'm a regular on StackOverflow. I will accept when the 5 minutes are up (it won't let me do it before that).


Security considerations when using canvas in conjunction with file uploading

Question: I'm working on a image editor/uploader based around Pixastic where I grab image data out of an <input> tag, put it into a canvas, and after manipulating it, encode the data in base 64 and post it to my app with javascript, where it will be saved as a new image file. If it were a standard file upload, I would give the file a new (safe) name, test to make sure it was really an image file and copy it to strip any potentially malicious/personal EXIF data before making it available to users.
My question is - do those security measures make sense in the canvas situation, or are they pointless? Additionally, are there any security issues with my approach that I'm overlooking?
Fyi: the serverside decoding/etc will be done with php.
Thanks.
Answer: Some of what you have asked (Not sure if all) are discussed by Shiflett Here
Check it and comment what you think of it!


Is it possible to run two separate video cards?

Question: Is it possible to run two separate video cards. Would there be any benefit to this if it is possible and I am sure it all depend on the mother board.
Thank you.
Answer: There are ATI Radeon Crossfire and nVidia SLI that allows you to setup
two Graphics cards together over two PCI slots.
The setup has an additional connection (bridge) between the two cards.
There are also multiprocessor cards that form Quad setups with two cards.
This TomsHardware article is a good starter brief.
It also gives a list for SLI and Crossfire certified motherboards.
Most configurations will also have special demands from the power supply unit.
Beyond basic SLI/Crossfire, there are now 3-way SLI and Quad-Crossfire setups
-- that is 3 video cards.
Intel Core i7 with 3-way SLI and Quad-Crossfire reviewed is a multi-page review
which has this opening picture.

These configurations need support in the hardware (motherboard, PSU, thermal conditions).
You should seriously consider your applications (typically heavy gaming, but also some modeling, animation and physics? applications).
If you will not be utilizing the hardware, it would be an awful waste of money.
You could also lookup 'Hybrid' SLI/Crossfire configurations supported by some motherboards.
Answer: It is possible, and until the advent of common cards supporting two monitors it was quite common.
If you want more a detailed answer than that then you'll need to give us more detail of your setup.
Comment: Still common since video cards typically only support 2 monitors and 3 monitors is rapidly becoming the norm.
Answer: You absolutely can.  This is how SLI and crossfire use to provide high end (read expensive) graphics.
Answer: You can indeed use multiple video cards.  An example of my multi video card setup can be found in this thread her on SU.
I found a single video card that would drive my four monitors however that video card was about $850 at the time.  Comparative performance was possible by using two Matrox Dual head video cards.  YMMV but I can tell you it was a significant savings in my case by using a distributed video solution as opposed to an integrated single card solution.  Each set of monitors had a processor of it's own, so it made it possible to run video in several windows and on different screens concurrently.   One of the cards was an AGP model and the other was a PCI card.  Your motherboard will dictate which cards are appropriate for your solution, but as always, more memory per card is better.
Just my $0.02
Answer: It does depend on the motherboard and the operating system.  Depending on the drivers installed, Vista (and presumably windows 7) may require that both video cards use the same driver.  The easiest way to ensure this is to buy two of the same card.  This means ensuring that your motherboard can support two such cards.
Comment: Just because all drivers come in the same package doesn't mean all cards are using the same driver (which I'd rather doubt).
Comment: Nice thing about the Nvidia series is that so many of them can use the same driver, makes life easy.  Not sure if any other brands are the same way.
Answer: Yes it is possible to run multiple video cards assuming you have the motherboard architecture that will allow for it. This can mean anything from having SLI-capable motherboards which allow you to run two PCI express cards in tandem, or something like I am running on an older motherboard where I have a PCI video card and an AGP video card running at the same time so that I can still have my multiple monitor set up.


Can the truth of statements cause the truth of other statements?

Question: Suppose I have a statement like "2+2=4". I believe the truth of that statement causes the truth of a statement like "2+2=4 OR 3=5". Have any philosophers or mathematicians developed the notion of a causal theory of truth? Such a theory should ideally require two statements to be relevant for there to be a causal connection between them.
Comment: I think the answer given so far is exactly what you are looking to go beyond? If so then see [SEP on Lewis's counterfactuals](https://plato.stanford.edu/entries/david-lewis/#3) for a quick-but-dense intro.
Comment: What you're likely looking for in mathematics is the notion of "forcing". Nothing causal, since mathematical entities are typically assumed to be abstract if they're countenanced, but certain statements "force" via the forcing proof method other statements to be true. For example, the axiom of constructibility (V=L) forces the continuum hypothesis (among other independent axioms) when added to ZF set theory.
Comment: Isn't "theory of truth" is simply, logic?
Answer: Causal set theory, https://sites.google.com/site/lisaglaserphysics/research/causal-set-theory or https://en.wikipedia.org/wiki/Causal_sets or just google "causal sets", imposes a poset ordering on events corresponding to "causal connection" (your words). The logical analogy is just implication, and I'd think that's all there is to it. Although maybe substructural logical connectives better fit your intuition, which you don't really elaborate in sufficient detail for a sharp answer. For example https://arxiv.org/abs/gr-qc/0109053 which involves resource-aware linear implication in this case.
Answer: Yes, Whitehead and Russell did it. What you call "a causal theory of truth" is called logic in philosophy. Whitehead and Russell showed that logic and mathematics are one and the same.
That example given in your question is called the "principle of addition" in W&R's Principia Mathematica:

If q is true, then 'p or q' is true.

But I'm curious what lead you to this idea.
Comment: Yes, they are proved in 2.02 and 2.21 in Principia Mathematica: A true proposition is implied by any proposition; a false proposition implies any proposition.
Comment: Well, in mathematics, there are vacuous implications. Such as "The angles of a triangle add up to 180 degrees" implies the four color theorem vacuously. Intuitively, the truth of the first has nothing to do with the truth of the second. Has anyone made this intuitive notion rigorous?


Saints who chose wrong vocation?

Question: Are there saints who chose the wrong vocation—i.e., entered into a certain state of life without having any attraction to it?
Comment: VOCATION

A call from God to a distinctive state of life, in which the person can reach holiness. The Second Vatican Council made it plain that there is a "Universal call [vocatio] to holiness in the Church" (Lumen Gentium, 39). (Etym. Latin vocatio, a calling, summoning; from vocare, to call.)

https://www.catholicculture.org/culture/library/dictionary/index.cfm?id=37136&randomterm=false
Answer: According to St. Alphonsus of Liguori, the "Doctor of Vocations", there is no such thing as "the wrong vocation", though resisting the inspirations of the Holy Ghost can make one's salvation more difficult:

To enter into any state of life, a divine vocation is necessary; for without such a vocation it is, if not impossible, at least most difficult to fulfill the obligation of our state, and obtain salvation. The reason of this is evident; for it is God Who in the order of His Providence assigns to each one of us his state of life, and afterwards provides us with the graces and the help suitable to the state to which He calls us. —Vocation to the Religious State

At the end of The True Spouse of Jesus Christ, St. Alphonsus gives some examples:

But how can I be content if I have not been called to religion? But
what does it matter that you have not had a vocation from the
beginning? Although you have not become a nun in obedience to a divine
call, it is certain that God has permitted your profession for your
welfare: and if he did not call you then, he certainly calls you now
to be his without reserve.
St. Paul, the first hermit, went into the desert, not to remain in it,
but to fly from the persecution that was then carried on against the
Church; but he was afterwards called by God to remain in the desert:
he remained, and became a saint.
When St. Teresa first entered a monastery she entered not without
reluctance; she said that in leaving her father's house the pain that
she felt was so great that she thought it equal to the pain that she
should suffer at death; and in her life it is related that she took
the habit, as it were, by force. But after all she became a great
saint, and the reformer of the Carmelite Order.
Blessed Hyacintha Marescotti, a religious of the convent of St. Clare,
in Viterbo, was also induced to take the sacred veil against her
inclination, and for ten years led a very imperfect life. But being
one day illumined with a divine light, she gave herself entirely to
God, and persevered till death, for the space of twenty—four years, in
a life of holiness, so that she has deserved to be venerated on the
altar.
Likewise Sister Mary Bonaventure, a nun in the convent of the Torre
Dei Specchi, entered against her will; but after a life of tepidity
and dissipation she went, during the first meditation of the spiritual
exercises, and threw herself at the feet of Father Lancicio, of the
Society of Jesus, and courageously said to him: "Father, I have
learned what God wishes from me. I wish to be a saint, and a great
saint, and I wish to be one immediately." And by the divine aid she
executed her purpose; so abundant were her tears that she could say no
more; but she went to her cell, and at the foot of the crucifix wrote
the following protestation: I, Mary Bonaventure, this day, in the
beginning of the spiritual exercises, offer myself entirely to Thee, O
my God. I promise to love nothing but Thee, O my Jesus! Accept, O most
loving Redeemer! This paper, bathed in my tears, which I consecrate to
Thee as the pledge of my love. I leave it in the wound of Thy side,
that through the merits of Thy blood Thou mayest pardon my sins, and
establish me in Thy love, so that I may be no longer mine, and may be
all Thine.

Saints who chose wrong vocation?


How do I beat the dragon in Castle Keep?

Question: In Candy Box, How do I beat the dragon at the end of the castle keep level? Even with a Level 2 sword of life, starting the fight with an invincibility buff, and 170hp I'm only getting it down to 700hp.
Answer: The way I did it seems pretty fool-proof. I just ran in and popped an invulnerability potion right before I touched the boss. Then when it runs out teleport back. When you get to the boss next time, the timer still won't be up though, so you'll have to use another teleport scroll, but then the next time you can turn invincible again, and repeat the strategy until victory. It's pretty costly, but the winnings will pay for it easily.
Comment: One alternative to using two teleport scrolls is to make some Seeds. Use one immediately after Teleporting, and that'll give you some time for your potion cooldown. You can even use an Earthquake or Acid Rain scroll while sitting around to speed things up!
Comment: When I teleport while in the boss room, it just sends me back to the door *still in the boss room*...  Is this supposed to happen?
Comment: @GnomeSlice: I'm pretty sure. It still lets the timer run down.
Comment: To get an idea of the costs: With a level 9 flame sword it took me 3 rounds, i.e. 3 invulnerability potions and 6 teleport scrolls.
Comment: You could also try planting a seed in front of yourself on the way back to save another teleport scroll (it takes a while to break the tree), but the teleport scroll is probably cheaper than concocting a seed in the cauldron.
Answer: I guess my way kind of sucked, but I kept eating candies until I got up to around 1000hp myself, then just kept drinking major health potions whenever possible.
Comment: If my math is correct getting to 1k hp would take 3.8024×10^6 candies, which seems a bit extreme for beating that level, compared to the other answer
Comment: 3,802,400 without the scientific notation
Comment: I'm all for scientific notation but @PrivatePansy might want to consider using a shorter form and rounding a bit since their version actually used more symbols than the number written out in full.
Answer: invincible, teleport, seed, repeat is the basic way to beat the dragon.
if you have to, use the cloning/seed combo in the cauldron (burn water, 869050/22750/1950 candies, stop, bottle for 650 cloning 1337 seeds/17 cloning 35 seeds/1 cloning 3 seeds)
if you have enough health, you could also clone at beginning, then invincible/fire scroll if needed.
Answer: By eating 17 000 000 candies, I had 1755 HP and when in front of the dragon, I just used an invincibility potion, having so much HP let me use another one and by the time I use the 2 potions, the dragon is left with a few HP and I still had 200HP when he died.


Querying active record objects from database based on created_at filters

Question: I know that Ruby on rails stores all times in UTC (for created_at and updated_at fields) and when you fetch an active-record object from database, and ask RoR for it's date, it will convert it your configured (in environment.rb) Timezone and show you.
But my case is different. I am building a custom query. And I am adding a where clause manually to it. Where clause is such that: select * where created_at > [user entered date].
Now the problem that's arising is that the user entered date is in UTC - 7 and created_at is in UTC. So I can't really make it work. I could hardcode it like select * where created_at > [user-entered-date] 07:00:00 - but this created problem because of daylight savings, and also doesn't seem like a good solution.
This is not the only problem, the second problem is that when I print out the record.created_at, I am getting UTC date (perhaps because I build a custom query?), which also I don't want to manually (hardcode) convert to local time.
Here's my code for the query:
cond = EZ::Where::Condition.new

if !start_date.empty?
  start_date = params[:filter][:start_date].to_date.to_s(:db)
  cond.append "(registrations.created_at) >= '#{start_date} 07:00:00'" #Here!
end

if !end_date.empty?
  end_date = params[:filter][:end_date].to_date
  end_date = end_date + 1.day;
  end_date = end_date.to_s(:db)
  cond.append "(registrations.created_at) <= '#{end_date} 07:00:00'" #Here!
end

registrations = Registration.all(
:joins => [:event],
:select => 'registrations.id, registrations.first_name, registrations.last_name, registrations.company_name,
(registrations.created_at) AS reg_date, events.name AS evt_name, sum(fees) AS fees, code, events.id AS event_id',
:group => 'registrations.id',
:order => 'evt_name, events.id',
:conditions=> cond.to_sql
)
unless registrations.empty?

  registrations.each_with_index do |registration, i|
    sheet[ i, 3 ] = (DateTime.strptime(registration.reg_date, "%Y-%m-%d %H:%M:%S") - 7.hours).to_date #Here!
  end
end

Comment: I am sure there's a canonical way of doing such stuff, which I totally didn't get a look at while educating myself, so now I am stuck with this thing.
Answer: Try to use TimeWithZone and TimeZone
tz = ActiveSupport::TimeZone.new("Mountain Time (US & Canada)")
...
start_date = tz.local_to_utc(params[:filter][:start_date].to_time).to_s(:db)
...
sheet[ i, 3 ] = registration.reg_date.in_time_zone("Mountain Time (US & Canada)").to_date


How do I know which version of EOS the mainnet is running?

Question: How do I know which version of EOS the mainnet is running?
For example, today is the mainnet running 1.0.3 or 1.0.4?
Is it possible that different Block Producers can be running different versions of EOS? Do they coordinate on updates?
Answer: You can retrieve the EOSIO version by making API call to /v1/chain/get_info endpoint and see the server_version property there, which is the first letters of the git commit id from the official repository https://github.com/EOSIO/eos/commits/master
For example, you can use http://dev.cryptolions.io/mainnet/ (or actually any BP API server from "Address" column) and go to API and enter:
API Request: /v1/chain/get_block
You will see something like:
<code>{
  "server_version": "c9b7a247",
  "chain_id": "aca376f206b8fc25a6ed44dbdc66547c36c6c33e3a119ffbeaef943642f0e906",
  "head_block_num": 1034339,
  "last_irreversible_block_num": 1034011,
  "last_irreversible_block_id": "000fc71b63fe1549e51aa84fd7619ccdbfff1eb3aca1109aed9fbd4c129bff70",
  "head_block_id": "000fc863ea9c26dfc4e3f34bb0059bcc61b107f98a472237606d5ac72f1ded8f",
  "head_block_time": "2018-06-16T15:23:49.500",
  "head_block_producer": "eosyskoreabp",
  "virtual_block_cpu_limit": 200000000,
  "virtual_block_net_limit": 1048576000,
  "block_cpu_limit": 199900,
  "block_net_limit": 1048576
}
</code>
where server_version exactly matches the https://github.com/EOSIO/eos/tree/c9b7a2472dc3c138e64d07ec388e64340577bb34 commit and if you check https://github.com/EOSIO/eos/releases page it matches v1.0.5 release.
You can query any blockproducer's api the same way, for example: https://mainnet.eoscanada.com/v1/chain/get_info
The official documentation is here: https://eosio.github.io/eos/group__eosiorpc.html#v1chaingetinfo
As I understand different block producers can run different versions, but they do great job to orchestrate and upgrade at the same time and run the same version - please someone correct me if I am wrong for this one.
Answer: Thanks to EOS Go for the following information
For the status of the mainnet please follow along here: https://t.me/eosmainnet


What time are Bloomberg Open Symbology Files updated daily?

Question: Does anyone know what time the Bloomberg Open Symbology precanned files are updated every day? I am planning on upating my view of them at 9 AM EST every morning. Furthermore, will the files for equities have any IPOs from the day listed?
Comment: I spent about an hour trying to find the answer to your question, as I am really curious about Bloomberg Open Symbology. Best I could find was that they ARE updated once daily, but no specifics.
Comment: What is the concern?  I pay for Bloomberg Back office files and usually ipos are listed well in advance
Answer: Bloomberg Open Symbology precanned files are updated twice daily.  8am and 2pm est
Comment: Do you have a source for that?


FreeIPA on Azure setup

Question: I am trying to setup FreeIPA on Azure as 1 Server ---> 2 Clients without actually utilizing a domain name i.e. I want to use a fictitious domain name such as "example.azure.local" and still have the connectivity between the server and the clients. However, I do want to expose the FreeIPA web-interface to the Server's public IP address for me to easily manage the users.
Is this possible without actually using a domain name? If so, how should I configure my DNS to achieve the same result.
Please Note: I am not that comfortable with setting up BIND or any other DNS service, extra information may be required in the DNS department of this setup.
Answer: If you don't want to run a DNS server inside your virtual network, then you have two options:

Configure all the clients to connect to the server by IP address (the internal IP of the server)
Edit the host files on the client machines to add a DNS entry of your choice mapping to the IP of the server. This can be whatever you want, but will only be resolvable on the machines where you edit the host file.
Comment: Thank you for the comment. I ended up setting a DNS using DNSMasq on one of the server in internal network.

FreeIPA on Azure setup


Can't get into Sushi High Roller despite beating the Champion

Question: How do I get into the Suhi High Roller in Lumoise City to start the post-game adventure? I thought beating the league was enough but I've done that 5 times and I still can't get in!
Comment: To my knowledge it is based off of Style, but I am not sure. Even though, I have no idea why you would want to go in there. It costs 500K and you can't make it all back (to my knowledge).
Answer: Its Lumiose City style, which is completely different than the style your clothing gives you.  You have to max it to gain access (regular clothing style must be high too i believe).  Lumiose style also gives you access to a bunch of other things, like new hairstyles and discounts to stores and cabs.  Here is a list of things that up your style:
http://www.serebii.net/xy/lumiosestyle.shtml
Answer: I believe the problem here is you aren't "stylish" enough. Style is a rating that gates various activities in Lumoise City. The easiest way to earn style is to buy Premier Balls one by one at the Pokemon mart somewhere in Lumoise. After ~150 with 0 style (less balls if you have mores style) the Mega Evolution stones in the stone emporium should be $10,000 instead of 10,000,000, and all "style" locked areas should be open.
If this is not the case, try beating the "Looker" subquests in Lumoise. I finished those and got max Style around the same time, so I'm unsure which triggered it, but for sure I can now battle in Sushi High Roller (spoiler alert: battles here are the same level as Cafe Le Wow but give lower rewards considering the price of "eating" there).
Answer: You have to play the Looker post-game... doesn't matter about your outfit, but you have to complete the Looker storyline. You'll get a holo-caster message from him sooner or later while running around Lumiose City. His bureau is right across from sushi high roller
Comment: I got it before I completed the whole Looker Quest.
Answer: Ok so it may have to do with style but it does NOT have to be maxed out. The stone at the emporium still costs me 70k but i can get in to the restaurant. As for clothes, i'm not sure that has anything to do with it. I do have nice clothes from the boutique couture but...like i said idk. Anyway i think it mostly has to do with beating the league and having at least almost maxed style considering when they let you in, it's mentioned that it's due to you being the champion. If you're getting discounted cab rides, you should be good. :p
Edit: Also you do NOT have to do the looker missions. I haven't even talked to or seen the guy.
Answer: You do not need to complete the Looker missions in order to access the post-adventure.  You need to have beaten the champion and have max Lumiose Style.  Your clothing should be mostly comprised from things you can buy at Lumiose Boutique.  You can tell when you have max style when music notes for boys and flowers for girls show up when it previews what you changed into.


How do I get both rear brake calipers to stop sticking?

Question: I changed the rear brakes on my 2004 Chevrolet Silverado and now both brake calipers are sticking.  What causes this and how do I fix it?
Comment: When you say changed the brakes, do you mean replaced the brake pads, or the calipers themselves? Can  you go into more detail about the work you did?
Answer: To add to user9181, when changing brake pads, its important to properly lubricate the moving parts.  If you are doing this yourself, the new pads/clips should come with a little diagram showing where to apply lubricant to the clips.  If you have a shop do the work, you can only hope they do all this.  If the caliper pistons are stuck, it is possible to rebuild these (basically, installing fresh rubber boots and cleaning up the sliding surfaces), but a new set of calipers is fairly cheap.
Good luck!
Answer: A brake caliper can stick because the caliper slide pins are corroded, the anti-rattle clips are corroded, or the caliper pistons are sticking (replace calipers).
Comment: Calipers can be rebuilt.  It's a little more work than just replacing, but costs less.


Where do the Shadow Guards come from?

Question: In Star Wars the Force Unleashed we see Starkiller battle Shadow Guards, a black robed version of Red Guards carrying lightsaber pikes, and they are Force sensitive. What is the origin of shadow guards? The database in the game says they are "rumored" to be brainwashed Jedi that have been trained to be the Emperors black ops guards. But what are their actual origins?
Comment: When a Mummy Shadow Guard and a Daddy Shadow Guard love each other very much...
Answer: Needless to say, none of this is canon anymore.
According to the Galaxy at War RPG sourcebook, the initial pool of Shadow Guards were originally Force-sensitive members of the Thyrsian Sun Guards, an elite military unit of the Thrysian people, an Echani offshoot. The sourcebook says of them (emphasis mine):

Near the end of the Clone Wars, Sidious tasks Asajj Ventress with eliminating the order. Of the members of the Sun Guard she spares, some join Emperor Palpatine's Royal Guard. Force-sensitive Sun Guards become candidates for the Imperial Shadow Guard.
Star Wars Roleplaying Game: Galaxy at War Chapter 4: "Military Units" Sun Guards of Thyrsus

Although RPG sourcebooks are a bit of a grey area in the canon1, this is as close to a definitive origin as we're given.
It's also not clear where new Shadow Guards come from, assuming new Shadow Guards are ever required. Since Sidious is known to have been keeping an eye on Force-sensitive children, it's possible that at some point the initial Sun Guard ranks were diluted by regular old schmucks, or by Force-sensitive applicants to the Royal Guard academy, or any number of other sources.

1 The Legends "canon", anyway; obviously they're no longer actual canon

Where do the Shadow Guards come from?


Suppose $x_n \rightarrow x$ and $y_n \rightarrow y$, then $d(x_n,y_n) \rightarrow d(x,y)$

Question: I am currently reading Erwin Kreyszig-Introductory functional analysis with applications. I don't understand the proof below in it. Why is it true that $d(x_n,y_n) \leq d(x_n,y) + d(x,y) + d(y,y_n)$ ? I also don't understand similiar inequality is given by interchanging $x_n$ and $x$ as well as $y_n$ and $y$ ? why is that true ?
Comment: It's the triangle inequality: d (xn,yn) <= d (xn,x)+d (x,yn) <= d (xn,x) + d (x,y) + d (y,yn).
Comment: You have a typo in your question -- the first term in the RHS is $d(x_n,x)$, not $d(x_n,y)$.
Answer: Recall that any metric space $M$ has a metric $d$ defined on it where:
$$d:M\times M\to \mathbb R_{\geq 0}$$
and $d$ fulfills the following axioms:

Symmetry:
$$d(x,y) = d(y,x)$$
Non-negativity
$$d(x,y)\geq 0\qquad d(x,y)=0\iff x = y$$
Triangle inequality:
$$d(x,y)\leq d(x,z)+d(z,y)$$
We can apply the triangle inequality twice to $d(x_n,y_n)$ as follows:

$$d(x_n,y_n) \leq d(x_n,y)+d(y,y_n)$$
We also have that $$d(x_n,y)\leq d(x_n,x)+d(x,y)$$
We can combine these to get that:
$$d(x_n,y_n)\leq d(x,x_n)+d(x,y)+d(y,y_n)$$
Here I implicitly used the symmetry condition to say that $d(x,x_n)=d(x_n,x)$.  It wasn't required, but it's good to recognize that these are equal.
We can interchange $x_n$ and $x$ and $y_n$ and $y$ because throughout this argument we've been treating them as points, and "forgetting" that they are sequences.  We could have used points called $a,b,c,d$ and still obtained a valid relation between them.  So, interchange the points is just saying "this argument is true for any $4$ points, and as we don't need to repeat it, we'll just take the end result and modify it to how we want it").
Comment: Sorry for late reply had problems with computer !
Answer: It's just the triangle inequality, $d (a,c) \le d (a,b) + d (b,c) $ applied twice.
$d (x_n,y_n)\le d (x_n,x)+d (x,y_n) \le d (x_n,x)+d (x,y)+d (y,y_n) $
So $d (x_n,y_n)-d (x,y)\le d (x,x_n) +d (y_n,y) $.
Likewise:
$d (x,y)\le d (x,x_n)+d (x_n,y_n)+d (y_n,y) $
So $d (x,y) -d (x_n,y_n) \le d (x,x_n)+d (y_n,y) $
So $| d (x,y) -d (x_n,y_n)|= \pm[d (x,y) -d (x_n,y_n) ]\le d (x,x_n)+d (y_n,y)$


Get last updated time for DynamoDB table

Question: Is there any way to get the timestamp for the most recent update on a DynamoDB table?
Comment: I just came across this question and I think the DynamoDB Streams might be in some cases useful. http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Streams.html
I guess this is a recent feature
Answer: No. This is not part of the DynamoDB api. Fortunately this is easy to implement yourself. Add a column to each item for each UpdateItem or PutItem request with the current time. This will insert the time according to your application servers instead of DynamoDB itself, but these ideally will be the same
Comment: Of course not, synced clocks are a fundamental problem of distributed system design.

Unfortunately, @Ajax did not speak more about his usecase so we cannot begin to guess the implications have in his system. I simply addressed his question as asked.
Comment: But there is no guarantee that the clocks of all application servers will be in sync.
Comment: Not sure why this was downvoted. The answer is 100% true. The alternative offered isn't perfect, but it's the best you can do given the constraints of ddb.
Comment: what if the item deleted from table? how do you update the time?
Answer: If you are just interested in an approximate time, you can get the timestamp of the write operations rounded to the nearest 5 minutes by looking at the SuccessfulRequestLatency metric for the PutItem operation inside Cloudwatch. You will see an entry on the x-axis only if there was a write operation in that 5-minutes time segment.
In the following screenshot, you can see that there was at least one write operation around 10:30 and 10:35, too:


Is there a way to create a load test using existing mochajs tests?

Question: We have some end-to-end tests written using WebDriverIO, and mochajs for a web application. Is there a way or tool to reuse these tests in order to create some load tests with various configuration?
Comment: You may not be really interested in all those configurations required for functional tests and apply that to performance tests. May be you can create simple tests in Jmeter.
Comment: @Rao I want my load tests to be as close as possible to real use cases and scenarios. Actually I can disable asserts in my functional tests in config, so that they become free of functional assertions. What remains in scenarios are some real use cases which can be repeated by some virtual users.
Answer: The absolute majority of the load testing tools provide record-and-replay functionality so you can go the following way:

Recording of HTTP-based applications is usually done via HTTP proxy, so you will need to start the proxy server which should be included in your load testing tool distribution
Configure your WebDriver tests to use proxy from step 1, see Using a Proxy chapter of Selenium documentation for more information
Run your Selenium test - load testing tool should be recording the associated HTTP requests
Perform correlation and parameterisation if needed
Add virtual users
Run your test

For example, Apache JMeter is a free and open source load testing tool and this is How to Convert Selenium Scripts into the JMX Converter