text:
Q: ASP MVC Single Application Multi-Domain Authentication I have the following strict scenario specifically required by a client: A single website using Asp.NET MVC4 which is accessible via various domains with Single-Sign On mechanism.
I have managed to make form authentication work with subdomains by specifying in the webconfig the second-level domain
 <authentication mode="Forms">
  <forms name="SingleSignOn" loginUrl="/Login/LoginRedirect" timeout="10" slidingExpiration="false" domain="domain.ml"  cookieless="UseCookies" enableCrossAppRedirects="true">
    <credentials passwordFormat="SHA1" />
  </forms>
</authentication>

Also when calling the FormsAuthentication.SetAuthCookie in the login logic, I am specifying the second level domain as well:
 System.Web.HttpCookie MyCookie = System.Web.Security.FormsAuthentication.GetAuthCookie(lName, false);
                    MyCookie.Domain = lSecondLevelDomain;
                    FormsAuthentication.SetAuthCookie(lName, false);

Across different domains, this does not work, since the actual domain will not match with the domain specified in the web.config and neither with the cookies.
The aim is:
User accesses domain1.com
User redirected to logindomain.com and authenticated cookie created
User redirected back to domain1.com
The user is always redirected to a "login domain", the cookie is created using that domain, and always authenticate using the same cookie across domains.
Is it possible to override the logic of the Authorize attribute in order to allow authorization using the cookie of the login domain instead of the domain the user originally used?

A: Before diving into programming, take a look at How does SO's new auto-login feature work? to understand how to implement such this scenarios.
Then take a look at Forms Authentication Across Applications and Single Sign On (SSO) for cross-domain ASP.NET applications. Now you can meet your purpose as you want :)
You can also use the following code if you strongly consider the validity of the resultant absolute returned URL:
public class Startup {
    public void Configuration(IAppBuilder app) {
        app.UseCookieAuthentication(new CookieAuthenticationOptions {
            AuthenticationMode = AuthenticationMode.Active,
            LoginPath = new PathString("/account/login"),
            LogoutPath = new PathString("/account/logout"),
            Provider = new CookieAuthenticationProvider { OnApplyRedirect = ApplyRedirect },
        });
    }

    private static void ApplyRedirect(CookieApplyRedirectContext context) {
        Uri absoluteUri;
        if (Uri.TryCreate(context.RedirectUri, UriKind.Absolute, out absoluteUri)) {
            var path = PathString.FromUriComponent(absoluteUri);
            if (path == context.OwinContext.Request.PathBase + context.Options.LoginPath)
                context.RedirectUri = "http://accounts.domain.com/login" +
                    new QueryString(
                        context.Options.ReturnUrlParameter,
                        context.Request.Uri.AbsoluteUri);
                        // or use context.Request.PathBase + context.Request.Path + context.Request.QueryString
        }

        context.Response.Redirect(context.RedirectUri);
    }
}


text:
Q: What's the best option for joining using multiple columns I have the below tables
TableA
ID     ID2
 1     101
 2     102
 3     103
       104
 5

TableB
ID     ID2
 1     101
 2     102
 3     103
       104
 5

I need to join on either ID or ID2. What's the right approach here, utilizing an 'OR' condition?
SELECT *
FROM TABLEA A
INNER JOIN TABLEB B ON A.ID = B.ID OR A.ID2 = B.ID2

A: Your method works.  However, or can kill performance in joins, so you might want two left joins:
SELECT *
FROM TABLEA A LEFT JOIN
     TABLEB Bid
     ON A.ID = Bid.ID LEFT JOIN
     TABLEB Bid2
     ON a.ID2 = Bid2.ID2 AND Bid.id IS NULL;

You then have to be careful about what you select -- making judicious use of COALESCE() to get the columns from the table you really wan

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to find occurences of a lettter in the string array in swift I'm beginner trying to implement this logic can anyone suggest the logic.
func findLetterOccurence(Letter: String){
    let array = ["Data", "program", "questions", "Helpful"]

    ///Logic to find the given letter occurences in string array

    print("\(Letter) occured in \(count) times")
}

Expected Output: a occured in 3 times
I've tried as below:
var count = 0
for i in array {
   var newArray.append(i)
   count = components(separatedBy: newArray).count - 1
}

But I don't understand what exactly the logic inside components(separatedBy:) ? I mean without higher function how can we implment logic here.

A: try something like this:
 func findLetterOccurence(letter: String) {
    var count = 0
    for word in array { count += word.filter{ String($0) == letter}.count }
    print("--> \(letter) occured in \(count) times")
}

You have to adjust if you want case insensitive, like this:
func findLetterOccurence(letter: String) {
    var count = 0
    for word in array { count += word.filter{ String($0).lowercased() == letter.lowercased()}.count }
    print("--> \(letter) occured in \(count) times")
}

A: A couple of ways.
    @discardableResult func findLetterOccurence(letter: String) -> Int {

    let array = ["Data", "program", "questions", "Helpful"]
    var count = 0
    // here we join the array into a single string. Then for each character we check if the lowercased version matches the string lowercased value.
    array.joined().forEach({ if $0.lowercased() == letter.lowercased() { count += 1} } )

    print("\(letter) occured in \(count) times")

    return count
}

You could also do a sensitive compare and leave the casing alone
by saying
array.joined().forEach({ if String($0) == letter { count += 1} } )

Another way would be this
//here our argument is a character because maybe we just want to search for a single letter.
    @discardableResult func findLetterOccurence2(character: Character) -> Int {

        let array = ["Data", "program", "questions", "Helpful"]

    //again join the array into a single string. and reduce takes the `into` parameter and passes it into the closure as $0 in this case, and each element of the string gets passed in the second argument of the closure.
        let count = array.joined().reduce(into: 0) {
           $0 += $1.lowercased() == letter.lowercased() ? 1 : 0
        }
        print("\(letter) occured in \(count) times")

        return count
    }

A: add this extension to find occurance of latter in string
extension String {
    func numberOfOccurrencesOf(string: String) -> Int {
        return self.components(separatedBy:string).count - 1
    }
}

use it for array
        func findLetterOccurence(Letter: String){
        let array = ["Data", "program", "questions", "Helpful"]
        var number = 0
        for str in array{
            var l = Letter
//            uncomment it to use code for upper case and lower case both
//            l = str.lowercased()

            number = number + str.numberOfOccurrencesOf(string: l)
        }
        print("\(Letter) occured in \(number) times")
    }


text: Q: Hive: Will SMB Join work if I bucket on 2 columns but use only one column in Joining condition SMB requires that both tables are bucketed on the same columns and also sorted. What if I have bucketing on 2 columns say ColA and ColB of both tables, but I use only ColA as joining column. Will SMB work in this case? How will it behave in this case?


text:
Q: How to get the name of the current layout? symfony getLayout does not seem to work when layout is set via view.yml. Is there anyway to get this within the controller's action class method

A: I recently needed this. You can do it but you just need to return the entire view.yml contents as an array:
$view_array = sfViewConfigHandler::getConfiguration(array(sfConfig::get('sf_app_config_dir').'/view.yml'));

Just adjust the relative path from sf_app_config_dir (or use another marker) to get what you need.

A: It's not a trivial task. The view.yml, is not in the "scope" of the action.
Maybe, you can use setLayout in your action rather then in view.yml.
if you can't, for some reasons... you can try this method to reach datas in view.yml:
Is it possible to get a value from view.yml in an action

A: Execute the following code in the action. It works for both cases, layout set in the action or in the view.yml.
$controller = $this->getContext()->getController();
$view = $controller->getView($this->getModuleName(), $this->getActionName(), 'Success');  // viewName == 'Success' (default)
$layout_name = $view->getDecoratorTemplate();  // e.g expected: layout.php

Let us know if it works for you.


text:
Q: React Jest Test Warning When More Than 1 Test I am getting a weird warning when I use more than 1 test.
When I use this test.
  it("should render default values", () => {
    render(
      <UserContext.Provider
        value={{
          userAuth: {
            profileId: 1,
            currentOrgId: 1,
            currentPrivileges: {}
          }
        }}
      >
        <SocialPostEdit
          id={elementId}
          socialPost={postContent}
          name={elementName}
        />
      </UserContext.Provider>
    );
  });

I get no warnings. When I duplicate it. Like this
 it("should render default values", () => {
    render(
      <UserContext.Provider
        value={{
          userAuth: {
            profileId: 1,
            currentOrgId: 1,
            currentPrivileges: {}
          }
        }}
      >
        <SocialPostEdit
          id={elementId}
          socialPost={postContent}
          name={elementName}
        />
      </UserContext.Provider>
    );
  });
 it("should render default values 1", () => {
    render(
      <UserContext.Provider
        value={{
          userAuth: {
            profileId: 1,
            currentOrgId: 1,
            currentPrivileges: {}
          }
        }}
      >
        <SocialPostEdit
          id={elementId}
          socialPost={postContent}
          name={elementName}
        />
      </UserContext.Provider>
    );
  });

I get this error
 Warning: An update to SocialPostForm inside a test was not wrapped in act(...).

      When testing, code that causes React state updates should be wrapped into act(...):

      act(() => {
        /* fire events that update state */
      });
      /* assert on the output */

The weird thing is why if I keep 1 test it works and if I add more than 1 it gives me warning?

A: The error message is correct, you need to wrap calls to render in act() as the documentation calls out:
 import { act } from 'react-dom/test-utils';

 it("should render default values 1", () => {
    act(() => {
      render(
        <UserContext.Provider
          value={{
            userAuth: {
              profileId: 1,
              currentOrgId: 1,
              currentPrivileges: {}
            }
          }}
        >
          <SocialPostEdit
            id={elementId}
            socialPost={postContent}
            name={elementName}
          />
        </UserContext.Provider>
      );
    });
  });


text:
Q: Injectivity of pullback composed with pushforward Let $\phi:X \to Y$ be a projective/proper, birational morphism between complex algebraic varieties, with connected fibers and $\phi_*\mathcal{O}_X \cong \mathcal{O}_Y$. Suppose further that $X$ is a non-singular. Let $F$ be a subsheaf of a free $\mathcal{O}_X$-module (not just locally-free) such that the quotient is torsion-free. Is the natural morphism $$\phi^*\phi_*F \to F$$ injective or surjective?

A: The answer to both questions (injectivity ans surjectivity) is no without further hypothesis.
Surjectivity : Let $Y$ be a smooth projective variety and let $\phi : X \longrightarrow Y$ be the blow-up of $Y$ along a smooth subvariety. Denote by $L = \mathcal{O}_{X}(-E) \otimes \phi^*\mathcal{O}_{Y}(1)$, where $E$ is the exceptional divisor and $\mathcal{O}_{Y}(1)$ is an ample line bundle on $Y$. The line bundle $L$ is ample so a sufficiently high power of $L$ is globally generated. That is, we have an exact sequence:
$$0 \longrightarrow F \longrightarrow \mathcal{O}_{X}^{\oplus r} \longrightarrow L^{\otimes m} \longrightarrow 0,$$
for some $m,r \in \mathbb{N}$, when $m$ is big enough. Dualizing this sequence, we get:
$$0 \longrightarrow L^{\otimes -m} \longrightarrow \mathcal{O}_{X}^{\oplus r} \longrightarrow F^* \longrightarrow 0,$$
with $F^*$ being torsion-free as the dual of a coherent sheaf. We have:
 $$\phi_* L^{-m} = \mathcal{O}_{Y}(m) \otimes \phi_*(\mathcal{O}(mE)) = \mathcal{O}_{Y}(m),$$
by the projection formula and the fact that $\phi_* \mathcal{O}_{X}(mE) = \mathcal{O}_{Y}$ for $m \geq 0$. As a consequence, the map $\phi^* \phi_* L^{-m} \longrightarrow L^{-m}$ has cokernel equal to $\phi^*\mathcal{O}_{Y}(-m) \otimes \mathcal{O}_{mE}(mE)$, it is not surjective.
injectivity : Let $Y$ be a smooth projective variety and $Z$ be a smooth codimension $3$ subvariety of $Y$. Let $J_{Z}$ be the ideal sheaf of $Z$ and let $\mathcal{O}_{Y}(1)$ be an ample line bundle on $Y$. For $m$ big enough, the sheaf $\mathcal{J}_{Z}(m)$ is globally generated, so that we have an exact sequence:
$$0 \longrightarrow F \longrightarrow \mathcal{O}_{Y}^{\oplus r} \longrightarrow \mathcal{J}_{Z}(m) \longrightarrow 0,$$
for some $m,r \in \mathbb{N}$, when $m$ is big enough. Let $\phi : X \longrightarrow Y$ be the blow-up along $Z$. Pulling back the above exact sequence along $\phi$, we get a long exact sequence:
$$ 0 \longrightarrow Tor^1(\mathcal{J}_Z(m),\mathcal{O}_{X}) \longrightarrow \phi^*F \longrightarrow \mathcal{O}_{X}^{\oplus r} \longrightarrow \phi^*\mathcal{J}_Z(m) \longrightarrow 0.$$
There are no higher $Tor$ because $Z$ has codimension $3$ in $Y$. Denote by $G$ the cokernel of:
 $$0 \longrightarrow Tor^1(\mathcal{J}_Z(m),\mathcal{O}_{X}) \longrightarrow \phi^*F.$$
We then have an exact sequence:
$$0 \longrightarrow G \longrightarrow \mathcal{O}_{X}^{\oplus r} \longrightarrow \phi^* \mathcal{J}_{Z}(m) \longrightarrow 0.$$
Let's push forward this exact sequence by $\phi_*$, we have a long exact sequence:
$$0 \longrightarrow \phi_* G \longrightarrow \mathcal{O}_{Y}^{\oplus r} \longrightarrow \phi_* \phi^* \mathcal{J}_{Z}(m) \longrightarrow R^1 \phi_* G \longrightarrow 0.$$
Let's show that $\phi_* \phi^* \mathcal{J}_{Z}(m) = \mathcal{J}_{Z}(m)$. We have an exact sequence:
$$ 0 \longrightarrow Tor^1(\mathcal{O}_{Z}, \mathcal{O}_X) \longrightarrow \phi^* \mathcal{J}_Z \longrightarrow \mathcal{O}_{X}(-E) \longrightarrow 0.$$
Since $Tor^1(\mathcal{O}_{Z}, \mathcal{O}_X) = \Omega_{E/Z}(-E)$, (where $\Omega_{E/Z}$ is the bundle of relative differentials for the map $E \longrightarrow Z$), The relative version of Bott's vanishing Theorem implies that:
 $$\phi_* Tor^1(\mathcal{O}_{Z}, \mathcal{O}_X)  = R^1 \phi_* Tor^1(\mathcal{O}_{Z}, \mathcal{O}_X) = 0.$$ We deduce that $\phi_* \phi^* \mathcal{J}_Z(m) = \mathcal{J}_Z(m)$.
But the map $\mathcal{O}_{Y}^{\oplus r} \longrightarrow  \mathcal{J}_{Z}(m)$ is the one we started with and it is surjective. We thus get $R^1 \phi_* G = 0$ and $\phi_* G = F$. Finally, we get that the map:
$$ \phi^* \phi_* G \longrightarrow G$$
is not injective as its kernal is:
$$Tor^1(J_Z(m),O_{X}) = Tor^{2}(\mathcal{O}_{Z}(m),\mathcal{O}_{X}) = \bigwedge^2\Omega_{E/Z}(-2E) \otimes \phi^* \mathcal{O}_{Y}(m).$$


text:
Q: Separate Backbone View functions into separate files I have a Backbone View.
To organize better the code of it, I would to prefer to separate some functions of it into a separate file.
So, I would like to maintains the structure but simply I need to separate the functions into different files:
- MyView
   - functions A -> file A;
   - functions B -> file B;

I would like to use the view in the same current mode. So I need to call the functions 'A' on my view: myViewInstance.functionA_1()
What is the correct way/pattern to implement this?
I use also RequireJS.

A: You can use the Mixin pattern. Divide the prototype of MyView to the main part and to other parts, put them to separate modules, make the main module depend on them and merge the parts together.
Add prototype members from the main part to the declaration of MyView as usual:
var MyView = Backbone.View.extend({
  method: function () {
    this.otherMethod();
  }
});

Put the other parts of the prototype to separate modules and export them as object literals:
var prototypePart = {
  otherMethod: function () {}
};

Make the main module depend on them and merge the prototype from all imported parts either by Object.assign or by _.extend:
// Merging the prototype with ES6.
Object.assign(MyView.prototype, prototypePart);
// Merging the prototype with Underscore.js.
_.extend(MyView.prototype, prototypePart);

You will get MyView as if declared "in one piece":
var MyView = Backbone.View.extend({
  method: function () {
    this.otherMethod();
  },
  otherMethod: function () {}
});

For example, myview.js exports MyView. It depends on two other modules in order to import other parts of the MyView prototype from them:
define([
  'underscore', 'backbone', './myview-a', './myview-b'
], function (_, Backbone, myViewA, myViewB) {
  var MyView = Backbone.View.extend({
    // ...prototype members from this module
    initialize: function () {
      this.fromModuleA();
    }
  });
  // Add prototype members imported from other modules
  _.extend(MyView.prototype, myViewA);
  _.extend(MyView.prototype, myViewB);
  return MyView;
});

myview-a.js exports an object with a group of additional MyView prototype members:
define(function () {
  var myViewA = {
    // ...prototype members from this module
    fromModuleA: function () {
      this.fromModuleB();
    }
  };
  return myViewA;
});

myview-b.js exports an object with another group of MyView prototype members:
define(function () {
  var myViewB = {
    // ...prototype members from this module
    fromModuleB: function () {}
  };
  return myViewB;
});


text:
Q: Print double quotations with WshShell.Sendkeys and windows batch I have a script that changes the users directory and prefills the input with a command, so he only has to look it over and change values before pressing enter. The command that's going to be written requires double quotations and I cannot get it to print this in the input. I've tried various of escape characters like ^", \", "", """ and {"} but I get none of them to work. I use the WshShell for this but if it's not possible using it and there's a better way that will solve this then I'm all ears.
The goal is that the user will see this in command window:
command.exe parameter="hello" parameter2="world"

The .bat file:
@if (@CodeSection == @Batch) @then
@echo off
rem Use %SendKeys% to send keys to the keyboard buffer
set SendKeys=CScript //nologo //E:JScript "%~F0"
rem Start cmd.exe program
start "" cmd
rem Send whatever you want to previous cmd.exe
%SendKeys% "echo Hello World!{ENTER}"
%SendKeys% "cd C:\temp{ENTER}"
%SendKeys% "command.exe parameter="hello" parameter2="world""
set /P "="
ECHO TERMINATE ORIGINAL BATCH
goto :EOF
@end
var WshShell = WScript.CreateObject("WScript.Shell");
WshShell.SendKeys(WScript.Arguments(0));

Source for batscript: https://stackoverflow.com/a/22772040/1350598

A: Use %SendKeys% "'command.exe parameter=\u0022hello\u0022 parameter2=\u0022world\u0022'" and change the last line by WshShell.SendKeys(eval(WScript.Arguments(0)));. Note that you need to add the apostrophe ' at begin-end of all strings; that is:
@if (@CodeSection == @Batch) @then
@echo off
rem Use %SendKeys% to send keys to the keyboard buffer
set SendKeys=CScript //nologo //E:JScript "%~F0"
rem Start cmd.exe program
start "" cmd
rem Send whatever you want to previous cmd.exe
%SendKeys% "'echo Hello World!{ENTER}'"
%SendKeys% "'cd C:\temp{ENTER}'"
%SendKeys% "'command.exe parameter=\u0022hello\u0022 parameter2=\u0022world\u0022'"
set /P "="
ECHO TERMINATE ORIGINAL BATCH
goto :EOF
@end
var WshShell = WScript.CreateObject("WScript.Shell");
WshShell.SendKeys(eval(WScript.Arguments(0)));


text:
Q: Concatenate and inserting in table I have one table in my database, in my table I have 4 column
NAME_1 NAME_2  LASTNAME_1 LASTNAME_2
Well now I'm adding one column more "FULL NAME" and I want concatenate NAME_1 NAME_ 2 LASTNAME_1 AND LASTNAME_2 and insert in FULL_NAME.
How do I do it?
NAME_1      NAME_2     LASTNAME_1    LASTNAME_2
-------------------------------------------------
ALISON     NULL      LAWRENCE      NULL
CARLOS     NULL      LOPEZ         RECINOS
MEL        ANDREA    CHEW          PHELPS

NAME1      NAME2     LASTNAME1    LASTNAME2     FULL_NAME
----------------------------------------------------------------------
ALISON     NULL      LAWRENCE      NULL        ALISON LAWRENCE
CARLOS     NULL      LOPEZ         RECINOS    CARLOS LOPEZ RECINOS
MEL        ANDREA    CHEW          PHELPS     MEL ANDREA CHEW PHELPS

A: you can use ISNULL and concatenation operator + and set the value
UPDATE Table1
SET  FULL_NAME = ISNULL(NAME_1,'') +
                 ISNULL(NAME_2,'') +
                 ISNULL(LASTNAME_1,'') +
                 ISNULL(LASTNAME_2,'')


text:
Q: How to avoid using too many && and || package CurrencyConverter;

import java.util.Scanner;

public class CurrencyConverter {

    public static void main(String[] args) {

        System.out.println("Welcome to the Currency Converter"
               + " \"MONEY MONEY KACHINGG\"\n ");

        Scanner s = new Scanner(System.in);
        System.out.print("Enter desired amount: ");
        double amount = s.nextDouble();
    //----------------Supported Amount------------------------------------------
        if(amount < 0 || amount > 1000) {
            System.out.println("Amount must be between 0 and 1000");
            return; }
    //--------------------------------------------------------------------------
        System.out.print("Type currency to START FROM: ");
        String from = s.next();
        System.out.print("Type currency to CONVERT TO: ");
        String to = s.next();

        double currency;
    //-----------------------UNSUPPORTED------------- ---------------------------
        if((!from.equals("BGN") && !to.equals("USD")) &&
           (!from.equals("USD") && !to.equals("BGN"))) {

            System.out.println("Unsupported Currency!\n"
                   + "Please choose from BGN or USD"); }
    //------------------------BGN to USD----------------------------------------
        else if(from.equals("BGN") && to.equals("USD")) {
           for(currency = 0; currency <= amount; currency++) {
               System.out.printf("%.2f leva = %.2f $\n",currency,(currency/1.52)); }
            }
    //------------------------USD to BGN----------------------------------------
        else if(from.equals("USD") && to.equals("BGN")) {
            for(currency = 0; currency <= amount; currency++) {
                System.out.printf("%.2f $ = %.2f leva\n",currency,(currency/1.52)); }
            }
    //------------------------Incorrect-----------------------------------------
        else {
            System.out.println("Unsupported Currency!\n"
                    + "Please choose from BGN or USD"); }

Is there an easier way to tell which currency is allowed and which is not? (See UNSUPPORTED).
I was told that so many && or || are not good for the code. Is that correct?

A: In general, it's not true that many || or && is bad coding. Having excess is not good though. In your case since you only support two types of conversion you can simplify things:
    if(from.equals("BGN") && to.equals("USD")) {
       for(currency = 0; currency <= amount; currency++) {
           System.out.printf("%.2f leva = %.2f $\n",currency,(currency/1.52)); }
    }
    else if(from.equals("USD") && to.equals("BGN")) {
        for(currency = 0; currency <= amount; currency++) {
            System.out.printf("%.2f $ = %.2f leva\n",currency,(currency/1.52)); }
    }
    else {
    //unsupported
    }

Previously you were checking for unsupported conversions twice: in the first if, and also implicitly in the last else. Also I should point out that you are doing the same conversion in both cases, so something is likely wrong there.


text:
Q: Rotating a sphere in threejs not working if using a loop I'm trying to have a sphere rotated a certain number of times when a button is clicked (the number of times is selected by the user). Since the number of rotations is open ended, I figured it would be easiest to have it done in a for loop:
$('#clickme').on('click', function () {
    var multiple = 4; //Change this value to rotate at different angles
    var rotationVector = new THREE.Vector3(0,1,0);
    var angle = ((360 / multiple) * Math.PI) / 180;
    for (var i = 0; i < multiple; i++) {
        sphere.rotateOnAxis(rotationVector, angle);
        alert(i);
    }
});

The alert is just a placeholder for now, but I do want other things done after each rotation. The problem here is that the rotation is never done. There's no errors and it hits that line of code, but the object never rotates. If I take the sphere.rotateOnAxis out of the for loop, then it works fine (at least it rotates once per click). I've tried various methods of re-rendering the scene, but that never does anything.
Working example here: http://jsfiddle.net/weatL3nc/2/

A: Notice what you're doing here:
var angle = ((360 / multiple) * Math.PI) / 180;

You're getting an angle by dividing 360 degrees (or 2 π radians) into n slices. Then here:
for (var i = 0; i < multiple; i++) {
    sphere.rotateOnAxis(rotationVector, angle);
}

You're rotating n times by that angle. That means that no matter what multiple was, at the end of the for loop, you'll have rotated precisely 360 degrees. In other words, it is working, you just won't ever notice it because the next time it draws the screen, the sphere will be right back where it was before.
As an alternative you can try to using setInterval to allow the screen to redraw between frames, like this:
$('#clickme').on('click', function () {
    var multiple = 2; //Change this value to rotate at different angles
    var rotationVector = new THREE.Vector3(0,1,0);
    var angle = ((360 / multiple) * Math.PI) / 180;
    var frame = 0;
    var ival = setInterval(function() {
        sphere.rotateOnAxis(rotationVector, angle);
        frame++;
        alert('Frame ' + frame + ' of ' + multiple);
        if (multiple == frame)
            clearInterval(ival);
    }, 1);
});

Demonstration

A: To wait for the render to complete you can implement a setTimeout() insted of a for loop with an interval high enough to wait for the render:
var iteration = 0;
var multiple = 4;
var interval = 100; // ms
var angle = ((360 / multiple) * Math.PI) / 180;

function rotateAndSave() {
    iteration++;
    sphere.rotateOnAxis(rotationVector, angle);
    //alert(iteration);
    if (iteration < maxIterations) setTimeout(rotateAndSave, interval);
}

Then call this function on your click:
rotateAndSave();

http://jsfiddle.net/weatL3nc/6/


text:
Q: Organizing data in NSArray (may be using NSSortDescriptor) I am trying to organize in order this json data...
{"message":["Untitled1b","Untitled2b","Untitled3b"],"name":["Untitled1a","Untitled2a","Untitled3a"]}

...red in this way...
NSString *fileContent = [[NSString alloc] initWithContentsOfFile:getImagePath2];

SBJsonParser *parser = [[SBJsonParser alloc] init];

NSDictionary *data = (NSDictionary *) [parser objectWithString:fileContent error:nil];

// getting the data from inside of "menu"

//NSString *message = (NSString *) [data objectForKey:@"message"];
 //NSString *name = (NSString *) [data objectForKey:@"name"];

NSArray *messagearray = [data objectForKey:@"message"];
NSArray *namearray    = [data objectForKey:@"name"];

NSDictionary* Dictionary = [NSDictionary dictionaryWithObjects:messagearray forKeys:namearray];

f = namearray.count;
NSLog(@"happt = %i", f);

//namegroup.text = [NSString stringWithFormat:@"%@  %@",name, message];

g= 0;

do{

    NSArray *allKeys = [Dictionary allKeys];
    for (int i = 0; i < [allKeys count]; i++) {
        NSString *key = [allKeys objectAtIndex:i];
        NSObject *obj = [Dictionary objectForKey:key];
        // do something

As you can see, in the json file message and name (the pair of data) are in the correct order (1a, 1b...). for each pair of data I create 2 text views and display the data. the pairs display correctly, but are mixed up. I mean, I would like them to display in the JSON file order (first 1a, 1b, then 2a, 2b, then 3a, 3b..., not 2a, 2b, then 1a, 1b, then 3a, 3b...)
I tried to use this:
NSSortDescriptor *dateSortDescriptor = [[[NSSortDescriptor alloc] initWithKey:@"date"     ascending:NO selector:@selector(compare:)] autorelease];
[list sortUsingDescriptors:[NSArray arrayWithObjects:dateSortDescriptor, nil]];

...but it did not work!! Please help!!

A: NSDictionary objects are unordered. The order of the keys is usually determined by the most efficient way to search through them, which is unlikely to be the same order in which they were added to the dictionary. In any case, the order of keys in an NSDictionary is typically not the order you want them to be in. If you want to sort your keys, you can use:
NSDictionary *dict = /* fill your dictionary */;

NSArray *allKeys = [dict allKeys];

NSArray *sortedKeys = [allKeys sortedArrayUsingSelector:@selector(compare:)];

for (NSString *key in sortedKeys)
{
    id value = [dict objectForKey:key];

    // do something with "key" and "value" in sorted order of "key"
}


text:
Q: HTTP Error 500.19 - Internal Server Error 0x8007052e I copied an MVC project from another development pc to my laptop and tried to deploy it on the laptop which gave this error. The user account password was changed recently prior to this error. I tried tinkering around with the app pool permissions for the root folders with no effect. Any ideas? I am stuck.
HTTP Error 500.19 - Internal Server Error
The requested page cannot be accessed because the related configuration data for the page is invalid.
Detailed Error Information
Module         IIS Web Core
Notification   Unknown
Handler Not yet determined
Error Code  0x8007052e
Config Error    Can not log on locally to C:\inetpub\wwwroot as user {MY ACCOUNT} with virtual directory password
Config File \?\C:\inetpub\temp\apppools\ASP.NET v4.0\ASP.NET v4.0.config
Requested URL http://localhost:80/hts
Physical Path
Logon Method    Not yet determined
Logon User  Not yet determined
Config Source
145: <application path="/" applicationPool="ASP.NET v4.0">
146:  <virtualDirectory path="/" physicalPath="%SystemDrive%\inetpub\wwwroot" userName="{MY ACCOUNT}" password="[enc:AesProvider:{etc etc etc}:enc]" />
147: </application>

A: *

*Open the Internet Information Services (IIS) Manager (Start > Run > type "inetmgr").

*Using the navigation pane on the left, browse to Sites > Default Web Site.

*Right-click on Default Web Site and select Manage Web Site > Advanced Settings.

*Set the Physical Path Credentials field to Application user (you must enter user and password).

*Click OK and then OK again.

*Right-click on Default Web Site and select Manage Web Site > Restart to refresh the changes that were just made.

*At this point you should be able to reload the page in your browser.

A: *

*Open IIS Manager

*Select the site. Default Web site in my case and click "Basic Settings..."

*This opens the Edit Site dialog.Click "Connect as".

*In the Connect As dialog, click Set and provide the new password in the Set Credentials dialog.

*Come back to Edit Site dialog and click "Test Settings..."

*Once the connections succeeds, you should be able to successfully open the site in your browser.

A: I ended up reinstalling visual studio and eventually got everything working.


text:
Q: Efficient indexing / joining in data.table across multiple dependent conditions for stop detection algorithm Edit: Real data set available here
With thanks to

Wang, Rui, Fanglin Chen, Zhenyu Chen, Tianxing Li, Gabriella Harari, Stefanie Tignor, Xia Zhou, Dror Ben-Zeev, and Andrew T. Campbell. "StudentLife: Assessing Mental Health, Academic Performance and Behavioral Trends of College Students using Smartphones." In Proceedings of the ACM Conference on Ubiquitous Computing. 2014.

Explanation
I'm running a simulation study in which I am performing stop detection on location data (lat/lon coordinates) based on relatively simple criteria.
A location (A) is a stop if there exists another location (B) with a timestamp of at least 180 seconds after A, and if all locations between A and B inclusive have a distance from A less than or equal to 80 meters.
I've tried to reduce the data such that it still works but doesn't require actual coordinates.
data <- data.table(id = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10),
                   latlon = c(0, 50, 80, 90, 90, 100, 190, 110, 110, 110),
                   time = c(0, 60, 120, 180, 240, 300, 360, 420, 480, 520))

id 1 isn't a stop, because the first location with a difference in time > 180 (id 5) has a distance in latlon of 90.
id 2 is a stop, because all locations between itself and the first location with a difference in time > 180 (id 6) have a distance less than 80 (0, 30, 40, 40, 50).
id 6 is not a stop because even though id 10 is > 180 difference in time, id 7 which falls between has a distance greater than 80.
id 8 is not a stop because there is no location afterwards at least 180 seconds following.
Ultimately, I need to be able to assign "stop id" greedily such if I find for example that id 2 has points that satisfy the distance requirement through until id 7, locations with ids 2:7 have a stop id of 2.
Matrix and for loop
If I run this:
nrows <- nrow(data)

latlon_dist <- outer(data$latlon, data$latlon, `-`)
latlon_dist[upper.tri(latlon_dist)] <- NA
time_window <- outer(data$time, data$time, `-`)
time_window[upper.tri(time_window)] <- NA

foo <- function(x){
  mindist <- min(which(x[, 1] > 80), nrows)
  if (mindist >= min(which(x[, 2] > 180), nrows + 1)) mindist else NA
}

bar <- array(c(latlon_dist, time_window),
  dim = c(nrows, nrows, 2))

apply(bar, 2, foo)

It gives me back the threshholds > NA  7  7 NA NA NA NA NA NA NA which I can use in a for loop to set the stop id as appropriate.
threshholds <- apply(bar, 2, foo) - 1

previous_threshhold <- 0
for (i in seq_along(threshholds)) {
  current_threshhold <- threshholds[i]

  if (!is.na(current_threshhold) && current_threshhold > previous_threshhold) {
    data[i:current_threshhold, stop_id := i]
    previous_threshhold <- current_threshhold
  }
}

At this point, this is the only way I've been able to guarantee accuracy. Everything else I've tried I've thought was correct, only to find that it wasn't behaving identically to this situation. But this is, as you might imagine, horribly inefficient, and it's being run 116,000 times in my simulation study.
My assumption is that the best way to handle this is with a non-equi join in data.table.
The other implementation I'm currently running functions better when the number of rows in the data set make the array too memory-heavy. I won't translate this to work on the data, but it's here in case it gives anyone ideas. I've stuck it in a while loop so it can skip over some iterations when it's already assigned a stop_id to a number of points. If points 1:7 all belong to stop_id 1, they aren't considered candidate stops themselves, we just move on to testing again at point 8. It technically returns a different solution, but stops that are "close enough" are merged later in this process, so the final result is unlikely to differ much.
For loop, no matrix
stopFinder <- function(dt){

  nrows <- nrow(dt)

  if (nrows < 20000){
    return(quickStopFinder(dt))
  }
  i <- 1
  remove_indices <- 0
  while (i < nrows) {
    this_ends  <- dt[!remove_indices,
                     Position(
                       geodist_vec(rep(longitude[1], .N),
                                   rep(latitude[1], .N),
                                   longitude,
                                   latitude,
                                   paired = TRUE),
                       f = function(x) x > 80,
                       nomatch = .N + 1) ] + i - 1
    # A) Do some number of points occur within the distance?
    # B) If so, is it at least three minutes out?
    if (this_ends > (i + 1) && dt[c(i, (this_ends - 1)), timestamp[.N] > time_window[1]]) {
      # Last index is the one before the distance is broken
      last_index_of_stop <- this_ends - 1

      # Next run, we will remove all prior considerations
      remove_indices <- c(1:last_index_of_stop)

      # Set the point itself
      dt[i,
         `:=`(candidate_stop = TRUE,
              stop_id = id,
              within_stop = TRUE)]
      # Set the attached points
      dt[(i + 1):last_index_of_stop,
         `:=`(within_stop = TRUE,
              stop_id = i)]

      # Start iterating again on the point that broke the distance
      i <- this_ends
    } else {
      # If no stop, move on and leave out this point
      remove_indices <- c(1:i)
      i <- i + 1
    }
  }
  dt[]
}

quickStopFinder is more or less the implementation I share at the beginning, which is memory intensive and slow, but slightly less slow than stopFinder.
Previously, I had something like this as the basis, but it required a lot of subsequent steps and didn't always give me the results I was looking for, but I'll add it for posterity.
  res <- dt[dt,
            on = .(timestamp >= timestamp_dup,
                   timestamp <= time_window)]
  res[, dist := geodist_vec(x1 = longitude,
                            y1 = latitude,
                            x2 = i.longitude,
                            y2 = i.latitude,
                            paired = TRUE,
                            measure = "haversine")]
  res[, candidate_stop := all(dist <= 80), i.id]

New with real data
Edit with example from real data:
This handles the situation with joins, but grows too big too quickly. It is fast when the data are small.
sm2 <- read.csv(file = "http://daniellemc.cool/sm.csv", row.names = NULL)
sm <- copy(sm2)
setDT(sm)
sm <- sm[, .(timestamp, longitude, latitude, id)]
sm[, timestamp := as.POSIXct(timestamp)]
sm[, id2 := id]

# This is problematic on my data because of how quickly it grows.
test <- sm[sm, on = .(id >= id)]
test[, i.id2 := NULL]
setnames(test, c("time.2", "longitude.2", "latitude.2", "id.1",
                 "id.2", "time.1", "longitude.1", "latitude.1"))

# Time and distance differences calculated between each pair
test[, distdiff := geodist_vec(longitude.1, latitude.1,
                               longitude.2, latitude.2,
                               paired = TRUE)]
test[, timediff := time.2 - time.1]

# Include the next distance to make sure there's at least one within distance and
# over 180 timediff.
test[, nextdistdiff := shift(distdiff, -1), id.1]

# Are all distances within 180 sec within 80, and is the next following also < 80
test[, dist_met := FALSE]
test[timediff < 180, dist_met := all(distdiff < 80 & nextdistdiff < 80), id.1]
test[, dist_met := any(dist_met), id.1]

# Test how many occur consecutively
# This keeps us from having > 80 dist but then coming back within 80
test[, consecutive := FALSE]
test[distdiff < 80, consecutive :=  c(TRUE, cummin(diff(id.2) == 1) == 1), id.1]
test[consecutive == TRUE & dist_met == TRUE, stop_id := min(id.1), id.2]
test[test[consecutive == TRUE & dist_met == TRUE], stop_id := i.stop_id, on = .(id.1 = id.2)]
test <- unique(test[, .(stop_id, id.1)])

# Join it back to the data.
sm[test, stop_id := stop_id, on = .(id = id.1)]

A: Using non-equi joins capabilities of data.table, you could join the data to itself while avoiding a cartesian product which would be too expensive.
As data.table only allows >, < or =, joins are first done on rectangular areas, before filtering out the appropriate distances. On the real data you provided, this makes 7 times less calculations.
library(data.table)
library(geosphere)

data <- copy(sm)

minduration <- 180
maxdistance <- 80

data[,latmin := destPoint(cbind(longitude,latitude),b = 180, d=maxdistance)[,2]]
data[,latmax := destPoint(cbind(longitude,latitude),b = 0 , d=maxdistance)[,2]]

data[,lonmin := destPoint(cbind(longitude,latitude),b = 270, d=maxdistance)[,1]]
data[,lonmax := destPoint(cbind(longitude,latitude),b = 90, d=maxdistance)[,1]]

data[,timestampmin := timestamp+minduration]

# Cross product with space and time windows
cross <- data[data,.(i.id,x.id,i.latitude,i.longitude,x.latitude,x.longitude,dist = distGeo(cbind(x.longitude,x.latitude),cbind(i.longitude,i.latitude)) ,i.timestamp,x.timestamp)
              ,on=.(timestamp>timestampmin,
                    longitude >= lonmin,
                    longitude<=lonmax,
                    latitude >= latmin,
                    latitude <= latmax)][
                    dist<maxdistance]

# Summarizing the results
cross[,.(keep=cumsum(fifelse(diff(x.id-i.id)==1,1,NA_integer_))),by=i.id][
      !is.na(keep),.(startid = i.id,nextid = i.id+keep)][
      !(startid %in% nextid)][
      ,.(maxid=max(nextid)),by=startid][
      ,.(stopid = min(startid)),by=maxid]

     maxid stopid
  1:     6      1
  2:    18     10
  3:    26     22
  4:    33     28
  5:    48     40
 ---
162:  4273   4269
163:  4276   4274
164:  4295   4294
165:  4303   4301
166:  4306   4305


text:
Q: How to get the coordinates of a click event inside Panel?  How can one get the coordinates of a mouse click inside a panel?
For instance I want to be able to put pixels wherever I click with my mouse. I can handle the drawing part, but I don't know how to make my program to listen for that click event, and how to get x/y coordinates of it so it can draw in right place.
I never saw a similar piece of code, and I was unable to find relevant information with google so I can't show any code "how I tried to achieve that" because I simply didn't :/ I have no clue how to start. I am probably searching the wrong keywords, but I am sure that it can be done.
EDIT: Thank you all

A: The Click event is not the right choice.  It can be generated both by the mouse and the keyboard so it doesn't pass the mouse position.  A button for example can be clicked by pressing the space bar.  This of course won't happen for a panel.  Simply use the MouseUp event instead.  Check the passed e->Button property.
A panel is not the good choice either btw.  It is not double-buffered so it is likely to start flickering when the drawing gets intricate.  It doesn't redraw properly when the size changes.  A PictureBox doesn't have these problems.  Just treat it like the panel, implement its Paint event and don't set the Image property.

A: Here is a complete hint for your question, with code. For the panel you can use the mouseDown event. And from the event arguments you can get the coords.

A: private: System::Void panel1_MouseDown(System::Object^  sender, System::Windows::Forms::MouseEventArgs^  e)
{
     int x= e->X;
     int y= e->y;
}


text:
Q: No Such Attribute: Entry cn=schema cannot be modified because the attempt to update attribute objectclasses I am facing this issue while trying to upgrade Forgerock OpenAM from 13.5.2 to 14.6.4. Can anyone help as to what is the cause for this error. Does it require any changes to be done from OpenDJ side?
 Thread[http-bio-8080-exec-2,5,main]: TransactionId[cb42ba57-6658-42db-a5c5-d2b8ac630453-30]
ERROR: An error occurred while processing /WEB-INF/template/ldif/sfha/cts-add-multivalue.ldif
org.forgerock.opendj.ldap.ConstraintViolationException: No Such Attribute: Entry cn=schema cannot be modified because the attempt to update attribute objectclasses would have removed one or more values from the attribute that were not present:  ( 1.3.6.1.4.1.36733.2.2.2.27 )

I see that the /WEB-INF/template/ldif/sfha/cts-add-multivalue.ldif below content
dn: cn=schema
changetype: modify
add: attributeTypes
attributeTypes: ( 1.3.6.1.4.1.36733.2.2.1.136 NAME ( 'coreTokenMultiString01' ) DESC 'General mapped multi value string field' SYNTAX 1.3.6.1.4.1.1466.115.121.1.15  X-ORIGIN 'ForgeRock OpenAM CTSv2' )
attributeTypes: ( 1.3.6.1.4.1.36733.2.2.1.137 NAME ( 'coreTokenMultiString02' ) DESC 'General mapped multi value string field' SYNTAX 1.3.6.1.4.1.1466.115.121.1.15  X-ORIGIN 'ForgeRock OpenAM CTSv2' )
attributeTypes: ( 1.3.6.1.4.1.36733.2.2.1.138 NAME ( 'coreTokenMultiString03' ) DESC 'General mapped multi value string field' SYNTAX 1.3.6.1.4.1.1466.115.121.1.15  X-ORIGIN 'ForgeRock OpenAM CTSv2' )

It would help if anyone can explain the error so that I can debug more on this.


text:
Q: How do make a node server application that receives email? There are dedicated modules for sending email, such as nodemailer. Or for building an email client using IMAP.
I need a lightweight email server node application on a dedicated domain with an MX record so that the app can receive emails on it's own; not just logging in to a pre-existing email server.
Does a library exist for this purpose? Preferably one that supports Opportunistic TLS over port 465, as an addition to default port 25 for MX.
The only relevant mention I have come across is mailin.io. However, this domain has been offline since I'm trying to check it out, and the repository seems very outdated, so I am calling this "Plan C" and haven't researched if this is a viable solution. I'm looking for a "Plan A" and a "Plan B" first.


text:
Q: Hdfs find files below certain size Is there a way to list files with size less than certain size in Hdfs . Using the command line or even a spark script ?
Scala / spark would be great as it may run faster as compared to command line .
I have looked at the Apache FileSystem documentation but could not find much information

A: You can use the below command to show files which are more than 1KB
hdfs dfs -ls -R / | awk '$5 > 1000'

Similarly, you can use the below script to show files of less than 1KB
hdfs dfs -ls -R / | awk '$5 < 1000'

Hope that helps.


text:
Q: Any way to use a different SSL certificate for DevFabric? We're running an HTTPS WebRole in Windows Azure DevFabric. DevFabric comes with its own SSL certificate, issued to 127.0.0.1. Is there any way to make it use a different certificate?
Background: we actually want to access the web services from another machine. I know, I know, it wasn't designed for that, but that's what we'd like to do if at all possible. For HTTP this works fine - we have a port redirector running that redirects ports on the machine's external IP to the same ports on 127.0.0.1. However, for SSL, the connection fails, because the hostname in the URL doesn't match the hostname in the certificate (which is "127.0.0.1").

A: In this scenario, what you want to do, is ignore the certificate errors if you're running in Dev:
ServicePointManager.ServerCertificateValidationCallback += new RemoteCertificateValidationCallback(ValidateCertificate);

private static bool ValidateCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
     #if DEBUG
     return true;
     #endif
     return (sslPolicyErrors == SslPolicyErrors.None);
}


text:
Q: Javascript: How to find a specific shape on a canvas based on click coordinates I have a grid of squares, in a canvas, and I am able to get the click coordinates within the canvas perfectly. I want to know how you can find the shape at those coordinate. Here is the code:
ngOnInit(): void {

    const canvas = document.getElementById('myCanvas');
    const ctxGrid = canvas.getContext('2d');
    ctxGrid.lineWidth = 0.1;

    canvas.addEventListener('mousedown', onDown, false);

    //grid with rectangles
    for (let i = 0; i < 50; i++) {
      for (let j = 0; j < 25; j++) {
        //variables
        let x = i * 20;
        let y = j * 20;
        let l = 20, w = 20;
        //push the square info
        this.shapes.push({ x, y, l, w }) //array of objects storing the information of the rectangle
        //draw it
        ctxGrid.strokeRect(x, y, l, w);
      }
    }

    function onDown(event) {

      const rect = canvas.getBoundingClientRect()
      let cx = event.clientX - rect.left;
      let cy = event.clientY - rect.top;
      console.log(cx + ", " + cy);
    }

  }

Here is the HTML:
<canvas id="myCanvas" width="1000" height="500">
</canvas>

A: I figured it out. Since I create an array of objects containing information of each rectangle, I just use the coordinates and compare the coordinates all the square info objects using a loop, and use the index of the correct square!


text:
Q: Trouble reading bash script output in Python I'm pulling my hair out trying to parse the output of the following Bash script in Python
#!/bin/bash
for pid in `ps aux | grep '[i]nclude' | grep -v '[i]gnore' | awk '{ print $2 }'`; do ps -p $pid -o pid= -o etime=; done

using os.popen like this, but it returns an empty list.
>>>import os
>>>p = os.popen('bin/findpid', 'r')
>>>p.readlines()
[]

Similarly, using subprocess.Popen also returns nothing
>>>import subprocess
>>>subprocess.Popen('bin/findpid', shell=True)

Running the script in bash outputs something like this
 8849    02:58:26
 9696    01:58:27

What am I doing wrong?

A: Can you try this one (I've used python 2.6.6, but may be you want it in the latest python 2.6):
#!/usr/bin/python

import subprocess
import os

CMD = "bin/findpid"
p = subprocess.Popen(CMD, shell=True, stdout=subprocess.PIPE)
print p.communicate()[0]

UPDATE: probably, first grep of findpid script needs -v too?


text:
Q: Insert into table from select distinct query in postgresql I have a table with 33 columns that has several duplicates so i am trying to remove all the duplicates this way because this select distinct query has the correct number of data.
    CREATE TABLE students (
school char(2),sex char(1),age int,address char(1),famsize char(3),
Pstatus char(1),Medu int,Fedu int,Mjob varchar,Fjob varchar,reason varchar,
guardian varchar,traveltime int,studytime int,failures char(1),
schoolsup varchar,famsup varchar,paid varchar,activities varchar,
nursery varchar,higher varchar,internet varchar,romantic varchar,
famrel int,freetime int,goout int,Dalc int,Walc int,
health int,absences int,id serial primary key)

I want to insert all values from this select distinct query
with 8 columns into a different empty table.
SELECT DISTINCT ("school","sex","age","address","famsize","Pstatus","Medu","Fedu","Mjob","Fjob","reason","nursery","internet")
FROM students;

A:
I want to insert all values from this select distinct query with 8 columns into a different empty table.

Use create table .. as select ... if you want to create the table
create table new_table
as
SELECT DISTINCT school, sex, age, address, famsize, "Pstatus", "Medu", "Fedu", "Mjob", "Fjob", reason, nursery, internet
FROM students;

Other wise just use an insert based on a select:
insert into empty_table (school, sex, age, address, famsize, "Pstatus", "Medu", "Fedu", "Mjob", "Fjob", reason, nursery, internet)
SELECT DISTINCT school, sex, age, address, famsize, "Pstatus", "Medu", "Fedu", "Mjob", "Fjob", reason, nursery, internet
FROM students;

Very important: do not put parentheses around the columns in the select list - that creates a single column with an anonymous record type.

A: insert into destinationTable(dC1, dC2, dC3, dC4, dC5, dC6, dC7, dC8)
select sC1, sC2, sC3, sC4, sC5, sC6, sC7, sC8
from sourceTable

You can join the tables to get the 33 columns.


text:
Q: Clever ways to get a forEach and event listener to run in sequence? My app allows a user to establish multiple oauths with their different Google accounts - let's say User Alex has Oauths with Google accounts A, B and C.
In my database, I store the tokens from their oauth connection and the expiry date of the access_token.
The oauth is done with the nodejs Google auth library, and declares a client object (note: this is all on my server) like so:
export const oauth2Client = new google.auth.OAuth2(
    process.env.GOOGLE_CLIENT_ID,
    process.env.GOOGLE_CLIENT_SECRET,
    'postmessage'
);

When the user loads my app, I have logic that runs through all their saved oauths, checks if the current time is past any of the tokens' expiry dates, and if so, set the refresh_token on the client and make a random Google API call - the client will automatically detect that the access_token needs to be refreshed and does so.
existingGoogleauths.forEach(async (eGa) => {
            if (eGa.expiry_date < new Date()) {
                console.log("Past expiry date - attempting to refresh");
                oauth2Client.setCredentials({
                    refresh_token: eGa.refresh_token
                });
                await google.calendar("v3").calendarList.list({
                        auth: oauth2Client
                    }, (e, profile) => {
                        // An unneeded call just to force oauth2Client to do a refresh
                        console.log('Refreshing call - Profile: ' + profile.toString());
                });
            }
        })

Note the forEach above.
Per the Google documentation, when the oauth2Client refreshes the access_token (which I cannot proactively call myself), it emits an event and I have this listener to react accordingly:
oauth2Client.on('tokens', async (tokens) => {
    // `tokens` will have the new token info

    // this will get more info about the user this token is related to
    const tokenInfo = await oauth2Client.getTokenInfo(tokens.access_token);

    [logic to save the new access_token and expiry_date to my db]
});

The trouble here is that when a user has multiple Google oauth connections and visits my page, it kicks off all this logic, but logging in the middle of it suggests that the refresh calls are happen all in parallel. The main symptom is that while I expect refreshed tokens for accounts A, B and C, I end up getting tokens back for B, B and B, for example. I think this has to do with how forEach and event listeners act in terms of running async in parallel, but there's a chance it has to do with the fact that I'm using the same oauth2Client across the accounts being refreshed.
If my hunch is correct, is there a way to force the forEach and event listener to happen strictly in sequence?


text:
Q: convert IST time zone to GMT using momentjs I want to convert IST time zone to GMT format using momentjs. The date value which is coming from database is in the following way,
2018-07-17T10:52:39.785

A: Just do this:
moment("2018-07-17T10:52:39.785").utc().format()

See utc() docs.


text:
Q: NTFS partition problem I used Gnome Disks to shrink an NTFS partition, something went wrong and now I can't mount nor boot Windows.
Every time I try to mount it I get this message:
Run lists overlap. Cannot merge: Numerical result out of range
ntfs_mapping_pairs_decompress() failed: Numerical result out of range
Failed to load $MFT: Numerical result out of range
Failed to mount '/dev/sdc4': Numerical result out of range

What does this mean? What could have happened?

A: You've seemingly destroyed your partition. Boot into Windows, try running chkdsk. Before running chkdsk I'd recommend making a full byte to byte copy of the disk because chkdsk may make data restoration impossible.
You should probably avoid resizing NTFS partitions using Linux utilities in the future: either use Windows Disk Manager or tools like Acronis Disk Director.


text:
Q: How fix bug with composer install --disable-phar I'm have php version 5.6, and I need to install composer for my project. I'm installing using these commands:
 curl -sS https://getcomposer.org/installer | php
 php -r "readfile('https://getcomposer.org/installer');" | php

I'm getting this error message:
Some settings on your machine make Composer unable to work properly.
Make sure that you fix the issues listed below and run this script again:

The phar extension is missing.
Install it or recompile php without --disable-phar

A: The error tells you that you have to enable or install the extension for .phar files.
Because you didn't give any information about your system, OS and so on, there is nothing more I can do to help point you into the correct direction. In general it's unlikely that you have to recompile PHP, you have to search the source of your current PHP version how to obtain or enable said extension.


text:
Q: Why don't textbooks foreground marginally generalized theorems?
*

*'Marginally generalized theorems' refers to theorems that were generalized so marginally that they can still be taught, and understood by the students, in the same course.

Examples of theorems NOT marginally generalized:

*A skilled high-schooler can understand Puiseux series, Dirichlet's theorem on arithmetic progressions, and Lagrange's four-square theorem. But their generalizations are too cavernous.

Examples of theorems that can be marginally generalized:

*Spivak proves $\sqrt{2}$'s irrationality fully, but banishes $a^{\frac 1b}$'s to the exercises. Isn't proving (only) the latter more efficient?

*Most multivariate calculus textbooks devote 1 chapter to Green's Theorem. Why not introduce Stokes's first, and then state Green's as a corollary?

*Why not prove first Gauss's generalization of Wilson's Theorem:
$\forall \; p \; \text{odd prime}, \alpha \in \mathbb{N} : \quad \prod_{k = 1 \atop \gcd(k,m)=1}^{m} \!\!k \ \equiv
\begin{cases}
-1      \pmod{m}  & \text{if } m=4,\;p^\alpha,\;2p^\alpha \\
\;\;\,1 \pmod{m}  & \text{otherwise}
\end{cases}?$
I refer not the further generalization requiring group theory.

A: I don't have enough reputation to post this as a comment but a very standard proof of Stokes theorem in 3 dimensions is to reduce the problem and apply Green's theorem.


text:
Q: Linear Differential Equation So I asked this question a while back but the answer I recorded really did not help me solve it.
Find the general solution to:
$a_0 + a_1x + a_2y + a_3dy/dx = 0$
If $a_0 = 0$ this becomes quite easy to solve (just set y = vx and factor it) but separation of variables doesn't work otherwise.
I think it is important to note that this is non homogenous.
Can someone give the general solution with an explanation of how it was solved (and if it isn't too much) as well as an explanation of intuitions/motivations behind the methods used?

A: Hints:

*

*Rewrite it as $\displaystyle y' + \frac{a_2}{a_3} y = -\frac{a_0}{a_3} - \frac{a_1}{a_3} x$

*Find an integrating factor

After those steps, you'll end up with:
$$\displaystyle \large y(x) = -\frac{a_0}{a_2}+\frac{a_1 a_3}{a_2^2}-\frac{a_1 x}{a_2}+c_1 e^{-\frac{a_2 x}{a_3}}$$
As an alternate approach, you could solve the homogeneous equation and then guess at a particular solution and find the constants.


text:
Q: VBA using Loop with .find and .copy values I want to use a loop in my SearchFunction in a way it will search for a customer till the right customer is found. I'm using a custom msgbox to define if the found customer is the customer i was looking for.
So basicly i want this:
MsgBox "Is this the customer you were looking for?"

Yes: it will copy cells(sheet2) and paste them into the invoice (sheet1)
No:  it will find next customer (and ask same question)**

** And keep doing/asking this till last found customer is shown.

This is how the msgbox looks like when a customer has been found:
Custom msgbox
At the moment it searches for a customer and shows it in a custom msgbox. When i say 'Yes this is the customer', it will copie the values like it should and paste them in the invoice. But when i say 'no this not my customer' it won't go to the next found customer but it will exit the SearchFunction.
I have tried using a Loop but i couldn't get it to work. Also i tried .findnext but i couldn't embed it to the code i'm using..
This is the code that i am using:
Sub SearchCustomer()
 '
 ' Search for customer
 '
 '*****************************************************************************************************

Dim Finalrow As Integer
Dim I As Integer
Dim cC As Object
Dim iR As Integer
Dim foundrange As Range

 '*****************************************************************************************************
 '                                      This Searches for the customer
 '*****************************************************************************************************

' Set up searchrange
    Set foundrange = Sheets("sheet2").Cells.Find(What:=Sheets("sheet1").Range("B12").Value, LookIn:=xlFormulas, LookAt:=xlPart)

' Checks if fields are filled
If Sheets("sheet1").Range("B12").Value = "" Then
    MsgBox "Please fill in a search key", vbOKOnly, "Search customer"

Else

    'When nothing is found
    If foundrange Is Nothing Then
        MsgBox "Customer not found," & vbNewLine & vbNewLine & "Refine your search key", vbOKOnly, "Search customer"

    Else

        Finalrow = Sheets("sheet1").Range("A1000").End(xlUp).Row

        For I = 2 To Finalrow

            'When range is found
            If Worksheets("sheet2").Cells(I, 1) = foundrange Then
                Set cC = New clsMsgbox
                cC.Title = "Search contact"
                cC.Prompt = "Is this the customer you searched for?" & vbNewLine & "" & vbNewLine & Worksheets("sheet2").Cells(I, 1) & vbNewLine & Worksheets("sheet2").Cells(I, 2) _
                & vbNewLine & Worksheets("sheet2").Cells(I, 3) & vbNewLine & Worksheets("sheet2").Cells(I, 4) & vbNewLine & Worksheets("sheet2").Cells(I, 5)
                cC.Icon = Question + DefaultButton2
                cC.ButtonText1 = "Yes"
                cC.ButtonText2 = "No"
                 iR = cC.MessageBox()

                If iR = Button1 Then
                    'Name
                    Worksheets("sheet2").Cells(I, 1).Copy
                    Worksheets("sheet1").Range("B12").PasteSpecial xlPasteFormulasAndNumberFormats
                    'Adress
                    Worksheets("sheet2").Cells(I, 2).Copy
                    Worksheets("sheet1").Range("B13").PasteSpecial xlPasteFormulasAndNumberFormats
                    'Zipcode & City
                    Worksheets("sheet2").Cells(I, 3).Copy
                    Worksheets("sheet1").Range("B14").PasteSpecial xlPasteFormulasAndNumberFormats
                    'Phonenumber
                    Worksheets("sheet2").Cells(I, 4).Copy
                    Worksheets("sheet1").Range("B15").PasteSpecial xlPasteFormulasAndNumberFormats
                    'E-mail
                    Worksheets("sheet2").Cells(I, 5).Copy
                    Worksheets("sheet1").Range("B16").PasteSpecial xlPasteFormulasAndNumberFormats

                ElseIf iR = Button2 Then
                    MsgBox "Customer not found", vbOKOnly, "Contact zoeken"

                End If

                Range("B12").Select

            End If 'gevonden item
        Next I

    Application.CutCopyMode = False

    End If
End If

End Sub

Some help would be great! Been searching for a long time now.
Thanks in advanced!
Greets Mikos

A: You need to restructure your code, the For loop doesn't make sense for looping over search results. You need a Do While Loop, see examples in Range.FindNext Method
Pseudo code:
Set foundrange = Sheets("sheet2").Cells.Find(What:=...)
Do While Not foundrange Is Nothing
    If Msgbox(<Customer data from foundrange.Row>) = vbYes Then
        ' copy stuff
        Exit Do  ' we're done
    Else
        Set foundrange = Sheets("sheet2").Cells.FindNext(After:=foundrange)
    End If
Loop

P.S. These are not the droids you're looking for!

A: Many thanks to Andre451 because he solved my problem!
Final code:
Sub SearchCustomer()
 '
 ' Search customer
 '
 '*****************************************************************************************************

    Dim Finalrow As Integer
    Dim foundrange As Range
    Dim answer As Integer

 '*****************************************************************************************************
 '                                      Search for customername
 '*****************************************************************************************************
' Search Range
Set foundrange = Sheets("sheet2").Cells.Find(What:=Sheets("sheet1").Range("B12").Value, LookIn:=xlFormulas, LookAt:=xlPart)
Finalrow = Sheets("sheet1").Range("A:A").End(xlDown).Row

' Checks if search range is filled
If Sheets("sheet1").Range("B12").Value = "" Then
    MsgBox "Please fill in a searchkey", vbOKOnly, "Search customer"
Else
    Do While Not foundrange Is Nothing
        If MsgBox("Is this the customer you were looking for? " & foundrange, vbYesNo + vbQuestion, "Zoek klant") = vbYes Then
            'Name
            foundrange.Copy
            Worksheets("sheet1").Range("B12").PasteSpecial xlPasteFormulasAndNumberFormats
            'Address
            foundrange.Offset(0, 1).Copy
            Worksheets("sheet1").Range("B13").PasteSpecial xlPasteFormulasAndNumberFormats
            'Zipcode and City
            foundrange.Offset(0, 2).Copy
            Worksheets("sheet1").Range("B14").PasteSpecial xlPasteFormulasAndNumberFormats
            'Phonenumber
            foundrange.Offset(0, 3).Copy
            Worksheets("sheet1").Range("B15").PasteSpecial xlPasteFormulasAndNumberFormats
            'Email
            foundrange.Offset(0, 4).Copy
            Worksheets("sheet1").Range("B16").PasteSpecial xlPasteFormulasAndNumberFormats
            Exit Do
        Else
            Set foundrange = Sheets("sheet2").Cells.FindNext(After:=foundrange)
            End If
Loop

Range("B12").Select
Application.CutCopyMode = False

End If
End Sub

Thanks again!


text:
Q: Messages with expired event time causing java heap space OutOfMemory error I am running a job with a normal tumbling event time window (window size of 1 hour). After running long enough, it will throw an error about the java heap running out of space. Now the thing about the data that is being processed is that there will be one message that occurs today at noon and the next 15k or so will be from a week prior (this isn't how the data is expected to always be, but it should be handled either way). So the watermark is well past the time of the event times of the next 15k messages, even with allowable lateness, so the late messages should be discarded. Or at least that is what I thought since they are no longer in that window.
So my question is this. Does Flink maintain messages that are expired even though they aren't used by the window? Or is it just for their tumbling window and there is something else or some property I should be setting to make sure that expired data doesn't eat up memory?
Thanks for the help!
EDIT
DataStream<OutputObject> outputStream = sourceData
    .assignTimestampsAndWatermarks(new BoundedOutOfOrdernessTimestampExtractor<Record>(Time.minutes(1)) {
        @Override
        public long extractTimestamp(Record record) {
            long eventTimeFromRecord = record.eventTimestamp;

            return eventTimeFromRecord;
        }
    })
    .keyBy("fieldToKeyBy")
    .window(TumblingEventTimeWindows.of(Time.hours(1)))
    .apply(new ApplyFunction());

A: When a source has parallelism of n, then there are n watermarks -- one for each of the parallel sub-tasks. In a case where a Flink job receives one message timestamped today at noon, followed by many events from a week ago, that one message will only advance the watermark for one of the parallel tasks, and the other n-1 tasks will still have Long.min_value as their watermark. So those "late" events will only be recognized as late in one of the parallel window operators, and the other n-1 windows will go ahead and process those "late" events.
Note this could also happen if you had just restored from a checkpoint or savepoint, because watermarks aren't saved in checkpoints or savepoints. This means you can't count on message traffic from a previous job to have brought the watermarks up to date.


text:
Q: Calculate 3D Euler angle between two 3D vectors? Say I have 2 3D vectors, each describing a direction in 3D space (or a rotation, but I'm not sure if that terminology is correct). How would I calculate the difference between the two vectors as an Euler angle? That is, if I applied the angle to the first vector, it would rotate to equal the other? I understand how Euler angles have issues and are implementation-dependant, but I don't know what the implications of this are on a question such as mine.
To clarify a little, when I say "3D vectors", I'm picturing the "translation" gizmo you get in most 3D modelling packages or in Unity (which is what I'm using).
EDIT: Actually I just reviewed the "vectors" that I'm using, and what I said is not quite correct. I actually have 6 vectors, 3 for each rotation. Each vector is a position in 3D space offset from the centre of rotation. This probably makes an already-difficult question near-impossible, right?
ADDITIONAL INFORMATION: Ok, so I've worked out what I actually want to ask (because this question is really badly done), and it applies more to Unity, so I've asked a more Unity-specific question over on Unity Answers.
I'm don't normally understand mathematical formulae that are posted online, so C++-styled pseudo-code would be by far the most helpful for me.
Any help would be much appreciated, and if my question lacks certain information, please just ask for more :)

A: If you are going to do 3d you need to understand linear algebra and matrix notation.[1] Affine 4x4 matrices are the basis of space transformations in all 3d applications I've ever seen, (Euler angles just give alternate means to describe that matrix). Even unity uses matrices, although to be able to efficiently do the Euler-Lagrange particle motion equation they prefer to have the decomposed form. A matrix encodes a entire space with 4 vectors. This is conceptually easy in this case (not the only use for matrices), the matrix encodes the directions x  y z  and offset vector w.
The reason matrix notation is useful is: It becomes possible to manipulate the things like normal math symbols. If you remember from school solving x from:
a * x = b

Divide both sides by a and you get
a/a * x = b /a ->
x = b / a

Now if you have 2 spaces with 3 vectors each you essentially have 2 fully formed spaces at origin. Assuming the vectors span a 3D space (in other words dont point all in one plane, its even better if they are orthogonal to each other in which case you can just use transformation functions directly). That means you have 3 spaces. So your problem is given you know 2 spaces. You need to know the space transform form space A -> space B (its customary to give matrices big letters to denote they are more complex). This is mathematically:
A * X = B

Where * is a matrix multiplications and A, X and B are transformation matrices. So then divide by A, but alas there's no matrix division, fortunately there is inverse and division is multiplication by inverse so that's what we do instead. Also one other note rotations are not commutative so we need to specify on which side we multiply so because A is before X we multiply on the left hand side with inverse of A. So we get:
A^-1 * A * X = A^-1 * B

Where ^-1 denotes matrix inverse. This simplifies to :
I * X = A^-1 * B ->
X = A^-1 * B

X is the rotation space. In unity code this looks like:
X = A.inverse * B

Where X, A and B are Matrix4x4 elements The language you use may have other conventions I'm using the java script reference here. You can covert this matrix to a quaternion and from there to Euler angles an example of this can be found here.
How to form A and B from the vectors? Just put the vector for starting space to A's columns 0-2 and destination spaces correspondingly to B columns[2].
[1] Yes its compulsory, its much simpler than it may seem at first. While you can live quite far without them they aren't any harder to use than saying rotate about x axis fro so and so. Also learn quats.
[2] I should check this, but unity seems to use column matrices so it should be right
PS: By the way if you have noisy data and more then 3 vectors per instance then you can use least squares to average the matrix t a 3 by 3 sub matrix.


text:
Q: python importing class from python package I am using python in a cgi enviroment and I use the mvc design pattern.
So i currently have the following hierarchy:
  main.py
  mvc/
  __init__.py
  model/
          __init__.py
          session_initiator.py
  view/
          __init__.py
  controller/
          __init__.py
          interface.py

In session_initiator.py I have defined the class session_initiator
I am trying to import session_initiator class inside interface.py
The following code in interface.py is successful:
 from .. import model

but when I try adding anything like:
from model import session_initiator

I get an error that model is not a module.
Please don't refer to solutions regarding sys.path
because I am using an enviroment where I am unable to edit it.
Thanks.
Edit: all the init files are empty.
Edit: I changed the line to:
from  mvc.model import session_initator

and this line works!
But now when trying to do:
self.session_init = session_initiator()

I get the following error:
 TypeError: 'module' object is not callable

A: Imports don't build on existing names like that.
from ..model import session_initiator

Also, session_initiator is now a module, not a class. If you meant to import something from inside that module then you must do so.
from ..model.session_initiator import session_initiator


text:
Q: Fatal error: Class 'PagesController' not found in i m using cake for some time, and now i have a slightly modified pages controller, i want to use it in my default.ctp, i import it with
App::uses('PagesController', 'Controller');

or
App::import('Controller', 'Pages');

both work on my localhost xampp, neither on openshift web server.
whatever i do, i get the fatal error, class not found. been googling this problem for 2 hours, and feel like i m hitting the wall here. please help :)

A: I would try to avoid these calls and use the CakePHP conventions. The difference between your local XAMPP copy and the OpenShift copy is probably due to running different versions of CakePHP, but this won't matter if you follow conventions.
It's best practice to put everything using the PagesController in the foler app/View/Pages. That way CakePHP handles all the imports, requires, routing, etc. Other than that, remember that the application path in OpenShift is /php/app/ (as opposed to the XAMPP /app/). I guess that could cause problems if you have custom controllers. Hope this helps!
Edit: I just realized that by default.ctp, you mean the layout file. I personally don't like calling controllers in the layout. I prefer to use the elements or helpers for this. Also, the PagesController isn't actually meant for being included in a site-wide layout. It's just meant for the files in your /app/View/Pages folder.

A: ok, i used requestAction instead, and this works. :)
to solve similar issue, use lets say $pages = $this->requestAction('pages/');
then 'foreach' the $pages array whenever u need.
IMPORTANT! in your controller's function that creates the page(in this case controller pagesController and function 'index' ) dont forget to RETURN the $pages object u compose, and not just 'set' it as usually done.
:)


text:
Q: Does javascript Array.slice(0) return a shallow copy? IIUC Array.slice(0) returns a copy of the array.  Is it a shallow copy?  In other words the array items still have the same memory location, but the array container gets assigned a new one?
Effectively:
let oldArray = ['old', 'array'];
let newArray = oldarray.slice(0);
let same = oldArray[0] === newArray[0]; //true
let same = oldArray === newArray; //false

A: Yes,see demo:

var o = [{
  x: 1
}]
var o2 = o.slice(0)
o2[0].x = 2
console.log(o[0].x)

A: You are correct - it does create a shallow copy.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice

The slice() method returns a shallow copy of a portion of an array into a new array object selected from begin to end (end not included). The original array will not be modified.

If you are wanting a deep copy you can do the ye ole dirty dirt:

var arr = [1];
var arr2 = JSON.parse(JSON.stringify(arr));

arr[0] = 99;
arr2[0] = 1000;

console.log({arr, arr2});


text:
Q: Uncompressed .lzo files in parallel and then delete the original .lzo files So I have .lzo files in /test01/primary folder which I need to uncompress and then delete all the .lzo files. Same thing I need to do in /test02/secondary folder as well. I will have around 150.lzo files in both folders so total around 300 files.
From a command line I was running like this to uncomressed one file lzop -d file_name.lzo
What is the fastest way to uncompressed all .lzo files and then delete all .lzo files from both folders. I came up with below code.
#!/bin/bash

set -e

export PRIMARY=/test01/primary
export SECONDARY=/test02/secondary

lzop -d $PRIMARY/* & lzop -d $SECONDARY/*
find $PRIMARY $SECONDARY -name '*.lzo' -delete

May be we can decompress the .lzo files in parallel and then delete all .lzo file in both the folders simultaneously to speed up the process.
Is there a better way?

A: Per the man page:
   -U, --unlink, --delete
              Delete input files after succesful compression or decompression.

so you could simply run
lzop -dU -- {"$PRIMARY","$SECONDARY"}/*.lzo

to delete each lzo file as soon as it's successfully decompressed.
lzop is single-threaded so if you want parallel processing you could use gnu parallel:
parallel lzop -dU -- ::: {"$PRIMARY","$SECONDARY"}/*.lzo

A: GNU Parallel spawns the jobs in the order they are given to GNU Parallel. So if you first list the $PRIMARY files and then the $SECONDARY files, then the $PRIMARY files will be processed first.
Unless --shuf is given. --shuf shuffles the arguments before running them. You will still not get one $PRIMARY file, then a $SECONDARY file every time, but at least the order will be random.


text:
Q: How to dump a Python dictionary to JSON when keys are non-trivial objects? import datetime, json
x = {'alpha': {datetime.date.today(): 'abcde'}}
print json.dumps(x)

The above code fails with a TypeError since keys of JSON objects need to be strings. The json.dumps function has a parameter called default that is called when the value of a JSON object raises a TypeError, but there seems to be no way to do this for the key. What is the most elegant way to work around this?

A: You can extend json.JSONEncoder to create your own encoder which will be able to deal with datetime.datetime objects (or objects of any type you desire) in such a way that a string is created which can be reproduced as a new datetime.datetime instance. I believe it should be as simple as having json.JSONEncoder call repr() on your datetime.datetime instances.
The procedure on how to do so is described in the json module docs.
The json module checks the type of each value it needs to encode and by default it only knows how to handle dicts, lists, tuples, strs, unicode objects, int, long, float, boolean and none :-)
Also of importance for you might be the skipkeys argument to the JSONEncoder.

After reading your comments I have concluded that there is no easy solution to have JSONEncoder encode the keys of dictionaries with a custom function. If you are interested you can look at the source and the methods iterencode() which calls _iterencode() which calls _iterencode_dict() which is where the type error gets raised.
Easiest for you would be to create a new dict with isoformatted keys like this:
import datetime, json

D = {datetime.datetime.now(): 'foo',
     datetime.datetime.now(): 'bar'}

new_D = {}

for k,v in D.iteritems():
  new_D[k.isoformat()] = v

json.dumps(new_D)

Which returns '{"2010-09-15T23:24:36.169710": "foo", "2010-09-15T23:24:36.169723": "bar"}'. For niceties, wrap it in a function :-)

A: http://jsonpickle.github.io/ might be what you want. When facing a similar issue, I ended up doing:
to_save = jsonpickle.encode(THE_THING, unpicklable=False, max_depth=4, make_refs=False)

A: you can do
x = {'alpha': {datetime.date.today().strftime('%d-%m-%Y'): 'abcde'}}

A: If you really need to do it, you can monkeypatch json.encoder:
from _json import encode_basestring_ascii  # used when ensure_ascii=True (which is the default where you want everything to be ascii)
from _json import encode_basestring  # used in any other case

def _patched_encode_basestring(o):
    """
    Monkey-patching Python's json serializer so it can serialize keys that are not string!
    You can monkey patch the ascii one the same way.
    """
    if isinstance(o, MyClass):
        return my_serialize(o)
    return encode_basestring(o)

json.encoder.encode_basestring = _patched_encode_basestring

A: JSON only accepts the here mentioned data types for encoding. As @supakeen mentioned, you can extend the JSONEncoder class in order to encode any values inside a dictionary but no keys! If you want to encode keys, you have to do it on your own.
I used a recursive function in order to encode tuple-keys as strings and recover them later.
Here an example:
def _tuple_to_string(obj: Any) -> Any:
"""Serialize tuple-keys to string representation. A tuple wil be obtain a leading '__tuple__' string and decomposed in list representation.

Args:
    obj (Any): Typically a dict, tuple, list, int, or string.

Returns:
    Any: Input object with serialized tuples.
"""
# deep copy object to avoid manipulation during iteration
obj_copy = copy.deepcopy(obj)
# if the object is a dictionary
if isinstance(obj, dict):
    # iterate over every key
    for key in obj:
        # set for later to avoid modification in later iterations when this var does not get overwritten
        serialized_key = None
        # if key is tuple
        if isinstance(key, tuple):
            # stringify the key
            serialized_key = f"__tuple__{list(key)}"
            # replace old key with encoded key
            obj_copy[serialized_key] = obj_copy.pop(key)
        # if the key was modified
        if serialized_key is not None:
            # do it again for the next nested dictionary
            obj_copy[serialized_key] = _tuple_to_string(obj[key])
        # else, just do it for the next dictionary
        else:
            obj_copy[key] = _tuple_to_string(obj[key])
return obj_copy

This will turn a tuple of the form ("blah", "blub") to "__tuple__["blah", "blub"]" so that you can dump it using json.dumps() or json.dump(). You can use the leading "__tuple"__ to detect them during decoding. Therefore, I used this function:
def _string_to_tuple(obj: Any) -> Any:
"""Convert serialized tuples back to original representation. Tuples need to have a leading "__tuple__" string.

Args:
    obj (Any): Typically a dict, tuple, list, int, or string.

Returns:
    Any: Input object with recovered tuples.
"""
# deep copy object to avoid manipulation during iteration
obj_copy = copy.deepcopy(obj)
# if the object is a dictionary
if isinstance(obj, dict):
    # iterate over every key
    for key in obj:
        # set for later to avoid modification in later iterations when this var does not get overwritten
        serialized_key = None
        # if key is a serialized tuple starting with the "__tuple__" affix
        if isinstance(key, str) and key.startswith("__tuple__"):
            # decode it so tuple
            serialized_key = tuple(key.split("__tuple__")[1].strip("[]").replace("'", "").split(", "))
            # if key is number in string representation
            if all(entry.isdigit() for entry in serialized_key):
                # convert to integer
                serialized_key = tuple(map(int, serialized_key))
            # replace old key with encoded key
            obj_copy[serialized_key] = obj_copy.pop(key)
        # if the key was modified
        if serialized_key is not None:
            # do it again for the next nested dictionary
            obj_copy[serialized_key] = _string_to_tuple(obj[key])
        # else, just do it for the next dictionary
        else:
            obj_copy[key] = _string_to_tuple(obj[key])
# if another instance was found
elif isinstance(obj, list):
    for item in obj:
        _string_to_tuple(item)
return obj_copy

Insert you custom logic for en-/decoding your instance by changing the
if isinstance(key, tuple):
    # stringify the key
    serialized_key = f"__tuple__{list(key)}"

in the _tuple_to_string function or the corresponding code block from the _string_to_tuple function, respectively:
if isinstance(key, str) and key.startswith("__tuple__"):
    # decode it so tuple
    serialized_key = tuple(key.split("__tuple__")[1].strip("[]").replace("'", "").split(", "))
    # if key is number in string representation
    if all(entry.isdigit() for entry in serialized_key):
        # convert to integer
        serialized_key = tuple(map(int, serialized_key))

Then, you can use it as usual:
>>> dct = {("L1", "L1"): {("L2", "L2"): "foo"}}
>>> json.dumps(_tuple_to_string(dct))
... {"__tuple__['L1', 'L2']": {"__tuple__['L2', 'L2']": "foo"}}

Hope, I could help you!


text:
Q: Android shadowed bottom border
I want to know can I draw this type of line (Shadowed line) for my bottom border any help???

A: Create a 9 patch of the same image, mark the expandable area as everything above this border, and set this 9 patch as the background of the view to which you want to have this border.
You could also, create a LinearLayout with required height (2-3 dp?) and use this as the background image. Put this layout below the view for which you want this border.


text:
Q: How do weak instruments violate full rank condition? So I know that if the instruments $(Z_i)$ in 2SLS regression are weak i.e. $X_i$ and $Z_i$ are uncorrelated, then full rank condition for matrix $\Sigma_{ZX}=E[Z_iX_i]$ will fail to hold, but how can one prove this formally?

A: If they are indeed uncorrelated, then we do not talk about weak instrument asymptotics. Then, the rank condition for identification that $\Sigma_{ZX}$ have full column rank will fail.
There is lots of literature about weak instruments, but one way to formalize weak instruments is to postulate the following relationship between regressors and instruments (based on an exercise in Hayashi, Econometrics):
$$
x_i=\frac{1}{\sqrt{n}}z_i+v_i
$$
This formalizes the notion that we do wish to have asymptotics in which a (possibly small) correlation between endogenous regressor and IV accumulates without bound, so that we ultimately get consistency. Instead, we formalize the relationship between the two so that the knowledge about the relationship between regressor and IV remains bounded even as $n\to\infty$, as the coefficient relating the two shrinks to zero as $n\to\infty$.
It is of course a bit unusual to think of a parameter as sample-size dependent, but then again, all asymptotics are fiction, and ultimately the test as to whether they are useful is the extent to which they are capable of reflecting actual finite-sample situations. And such weak-IV asymptotics have been widely found to be useful in the literature.
Indeed, one can show that IV is not consistent under such asymptotics:
Consider
$$
y_i=x_i\delta+\epsilon_i\;\;(i=1,\ldots,n),
$$
where $y_i, x_i, \epsilon_i$ are scalar. We further have a scalar instrument
$z_i$ related to $x_i$ via
$$x_i=z_i\beta+v_i$$
Let $g_i:=(z_i\epsilon_i,\; z_iv_i)'$. Make the following assumptions, which are standard except for condition 4:

*

*$(z_i,\epsilon_i,v_i)$ is an i.i.d. sequence.

*Likewise, $g_i$ is i.i.d. with mean zero and $E(g_ig_i')=S$ positive definite.

*$E(z_i^2)=\sigma_z^2>0$ (this is a variance as the notation suggests if $E(z_i)=0$, but the latter is not necessary).

*$\beta= 1/\sqrt{n}$.
Let $\hat{\delta}:=s_{zx}^{-1}s_{zy}$, where
$$
s_{zx}=\frac{1}{n}\sum_iz_ix_i, \;\;s_{zy}=\frac{1}{n}\sum_iz_iy_i.
$$
We first show that $\sqrt{n}s_{zx}\xrightarrow{d}\sigma_z^2+a$, where $a\sim N(0,S_{22})$ ($S_{ij}$ is the $(i,j)$-element of $S$).
\begin{eqnarray*}
\sqrt{n}s_{zx}&=&\sqrt{n}\frac{1}{n}\sum_iz_ix_i\\
&=&\sqrt{n}\frac{1}{n}\sum_iz_i\left(\frac{z_i}{\sqrt{n}}+v_i\right)\\
&=&\underbrace{\frac{1}{n}\sum_iz_i^2}_{\xrightarrow{p}\sigma^2_z \text{ by LLN}}+\underbrace{\frac{1}{\sqrt{n}}\sum_iz_iv_i}_{\xrightarrow{d} a\text{ by CLT}}\\
\end{eqnarray*}
(A sum of expressions converging in probability and distribution converges in distribution together.)
Next, we show that $\hat{\delta}-\delta\xrightarrow{d} (\sigma_z^2+a)^{-1}b$, where $b\sim N(0,S_{11})$ and $(a,b)\sim N(0,S)$ are jointly normal.
Using the standard sampling error representation we can write
\begin{eqnarray*}
\hat{\delta}-\delta&=&\frac{\frac{1}{n}\sum_iz_i\epsilon_i}{\frac{1}{n}\sum_iz_ix_i}\\
&=&\frac{\frac{1}{\sqrt{n}}\sum_iz_i\epsilon_i}{\frac{1}{\sqrt{n}}\sum_iz_ix_i}\\
&\xrightarrow{d}&\frac{b}{\sigma_z^2+a},
\end{eqnarray*}
where we are allowed to look at the distribution of the ratio due to joint normality.
As $\hat{\delta}-\delta$ converges in distribution to some r.v., and hence not in probability to the number zero. The estimator is therefore inconsistent.


text:
Q: Failed to execute 'setSelectionRange' on 'HTMLInputElement' I have the following error an simle "number" input field in Chrome (ver. 33 =>) and other webkit browsers
<input type="number" name="number">

Failed to execute 'setSelectionRange' on 'HTMLInputElement': The input
  element's type ('number') does not support selection.

I tested in FF & IE (10=>) and working well
I found the following issue in chromium project:
https://code.google.com/p/chromium/issues/detail?id=346270
any idea?
thank you!

A: Yes, this is an webkit bug, try this solution:
Jsfiddle demo
Code:

        <form role="form">

            tel
              <input type="tel" class="form-control" id="tel" placeholder="tel"/>

        </form>