问:
Custom titlebars/chrome in a WinForms app
I'm almost certain I know the answer to this question, but I'm hoping there's something I've overlooked.

Certain applications seem to have the Vista Aero look and feel to their caption bars and buttons even when running on Windows XP. (Google Chrome and  Windows Live Photo Gallery come to mind as examples.)  I know that one way to accomplish this from WinForms would be to create a borderless form and draw the caption bar/buttons yourself, then overriding WndProc to make sure moving, resizing, and button clicks do what they're supposed to do (I'm not clear on the specifics but could probably pull it off given a day to read documentation.)  I'm curious if there's a different, easier way that I'm overlooking.  Perhaps some API calls or window styles I've overlooked?

I believe Google has answered it for me by using the roll-your-own-window approach with Chrome.  I will leave the question open for another day in case someone has new information, but I believe I have answered the question myself.

答:
Google Chrome is not using the Vista SDK to achieve this on XP.  If you peek into src\chrome\browser\views\frame there are several files to define the browser frame depending on the capabilities of the system.  On XP, it looks like OpaqueFrame is used; line 19 has this to say:

```<code>// OpaqueFrame
//
//  OpaqueFrame is a CustomFrameWindow subclass that in conjunction with
//  OpaqueNonClientView provides the window frame on Windows XP and on Windows
//  Vista when DWM desktop compositing is disabled. The window title and
//  borders are provided with bitmaps.</code>```

It looks like it's using the resources in src\chrome\app\theme to draw the frame buttons.

So it looks like my hopes that there's some kind of cheap way to enable Vista theming on XP are dashed.  The only way to do it is to manually draw the non-client area of your window.  I believe something like this is probably the right track, since it lets Windows handle the non-client stuff like moving and resizing the window.

Unless someone can find a method to magically enable the Vista theming on XP, this is the answer to the question but I obviously cannot mark my own post as the answer.

OwnerDisplayName: OwenP

LastEditorDisplayName: OwenP

Body:
Google Chrome is not using the Vista SDK to achieve this on XP.  If you peek into src\chrome\browser\views\frame there are several files to define the browser frame depending on the capabilities of the system.  On XP, it looks like OpaqueFrame is used; line 19 has this to say:

// OpaqueFrame
//
//  OpaqueFrame is a CustomFrameWindow subclass that in conjunction with
//  OpaqueNonClientView provides the window frame on Windows XP and on Windows
//  Vista when DWM desktop compositing is disabled. The window title and
//  borders are provided with bitmaps.

It looks like it's using the resources in src\chrome\app\theme to draw the frame buttons.

So it looks like my hopes that there's some kind of cheap way to enable Vista theming on XP are dashed.  The only way to do it is to manually draw the non-client area of your window.  I believe something like this is probably the right track, since it lets Windows handle the non-client stuff like moving and resizing the window.

Unless someone can find a method to magically enable the Vista theming on XP, this is the answer to the question but I obviously cannot mark my own post as the answer.


来源: stackexchange

问:
Unable to create a versioned API in SailJS
First things first, version of various dependencies

Ubuntu - 15.04

NodeJS - 6.10.3

NPM - 3.10.10

Sails - 0.12.13

Second, here's what I did:

1. Installed Sails globally

2. In the directory /var/www, ran the command sails new app

3. Created a file UserController.js in api/controllers/v1

4. Created a file User.js in api/models

Code for UserController.js

```<code>module.exports = {

  findOne: function(req, res) {

    return res.send("Hello World!!! User -> findOne");
  },

  login: function(req, res) {

    return res.send("Hello World!!! User -> login");
  }
}
</code>```

Code for User.js

```<code>module.exports = {}
</code>```

Now, when I start my server using sails lift, here's what happens:

Browse http://localhost:1337/v1/user/1 - Page Not Found (404)

Browse http://localhost:1337/v1/user/login

Hello World!!! User -> Login

I know I'm going to sound silly, but I thought it is probably because I didn't use the Generator feature of Sails. So, here's what I did next: sails generate api v1/Product. And the file structure after this command is like this:

```<code>api
|-- controllers
    |-- v1
        |-- UserController.js
    |-- V1
        |-- ProductController.js
|-- models
    |-- User.js
    |-- V1
        |-- Product.js
</code>```

I wrote similar code in ProductController.js as I did in UserController.js and I expected that now the Product API should work but the result was same as in case of /v1/user/1.

As per the SailJS Blueprint API, this should have worked. So, can anyone explain why this is happening and how can I make /v1/user/1 and /v1/user/login both work as expected.

答:
You have a couple of ways to achieve this. The first option is to set the restPrefix to /v1 inside config/blueprints.js

An optional mount path for all REST blueprint routes on a controller and it does not include actions and shortcuts routes.
  This allows you to take advantage of REST blueprint routing even if you need to namespace your RESTful API methods

Now with same directory structure i.e., /controllers/v1/UserController.js and /models/User.js, you should be able to access both the /login and findOne methods.

The second option is to set the prefix to /v1 inside config/blueprints.js

An optional mount path for all blueprint routes on a controller, including rest, actions, and shortcuts.
  This allows you to take advantage of blueprint routing, even if you need to namespace your API methods.
  (NOTE: This only applies to blueprint autoroutes, not manual routes from sails.config.routes)

Now the directory structure would be /controllers/UserController.js and /models/User.js. You have the mapping /v1 setup for you.

On the other hand, you can completely turn off blueprint routes and set up your own routes inside /config/routes.js. This would give you more flexibility and you can also have environment specific routes inside config/env/[your_env].js

ContentLicense: CC BY-SA 3.0

Body:
First things first, version of various dependencies

Ubuntu - 15.04

NodeJS - 6.10.3

NPM - 3.10.10

Sails - 0.12.13

Second, here's what I did:

1. Installed Sails globally

2. In the directory /var/www, ran the command sails new app

3. Created a file UserController.js in api/controllers/v1

4. Created a file User.js in api/models

Code for UserController.js

module.exports = {

  findOne: function(req, res) {

    return res.send("Hello World!!! User -> findOne");
  },

  login: function(req, res) {

    return res.send("Hello World!!! User -> login");
  }
}

Code for User.js

module.exports = {}

Now, when I start my server using sails lift, here's what happens:

Browse http://localhost:1337/v1/user/1 - Page Not Found (404)

Browse http://localhost:1337/v1/user/login

Hello World!!! User -> Login

I know I'm going to sound silly, but I thought it is probably because I didn't use the Generator feature of Sails. So, here's what I did next: sails generate api v1/Product. And the file structure after this command is like this:

api
|-- controllers
    |-- v1
        |-- UserController.js
    |-- V1
        |-- ProductController.js
|-- models
    |-- User.js
    |-- V1
        |-- Product.js

I wrote similar code in ProductController.js as I did in UserController.js and I expected that now the Product API should work but the result was same as in case of /v1/user/1.

As per the SailJS Blueprint API, this should have worked. So, can anyone explain why this is happening and how can I make /v1/user/1 and /v1/user/login both work as expected.


问:
Setting default value for <select/> using ng-options with (key, value) in angularjs
I want to set a default value for the following select:

```<code><select ng-model="selected"
      ng-options="key as value.Name for (key, value) in attributes">
</select>
</code>```

I use attributes as a map with an id as key and an object as value. I want to show the name of the value in the select-box, but bind the key to the model, because when I access selected, I need the id, not the name.
This works but now I want to set a default value. The default value must also show value.Name, but bind id.

According to this, it should work something like this:

```<code>$scope.selected = { 1: {Name : "Attribute1"}};
</code>```

I haven't made it yet. I would appreciate any help.

EDIT:

My attributes variable looks like this (TypeScript):

```<code>export interface IAttributes {
    [id: number]: IAttributeProperties;
}

export interface IAttributeProperties {
    Name: string;
    DataType: string;
}
</code>```

答:
You can initialize it with ng-init :

```<code><select
      ng-init="selected = attributes[0]"
      ng-model="selected"
      ng-options="key as value.Name for (key, value) in attributes">
</select>
</code>```

Body:
I want to set a default value for the following select:

<select ng-model="selected"
      ng-options="key as value.Name for (key, value) in attributes">
</select>

I use attributes as a map with an id as key and an object as value. I want to show the name of the value in the select-box, but bind the key to the model, because when I access selected, I need the id, not the name.
This works but now I want to set a default value. The default value must also show value.Name, but bind id.

According to this, it should work something like this:

$scope.selected = { 1: {Name : "Attribute1"}};

I haven't made it yet. I would appreciate any help.

EDIT:

My attributes variable looks like this (TypeScript):

export interface IAttributes {
    [id: number]: IAttributeProperties;
}

export interface IAttributeProperties {
    Name: string;
    DataType: string;
}

Body:
You can initialize it with ng-init :

<select
      ng-init="selected = attributes[0]"
      ng-model="selected"
      ng-options="key as value.Name for (key, value) in attributes">
</select>


问:
In Swift, override func with parameters. Add Target to projects
If I've a subclass, how is possible to deny the access at one func with other one with parameters?

Is easier to explain with code:

```<code>class A {
    func printSometing() {
        print("Class A printing")
    }
}

class B: A {
    override func printSometing() {
        print("Class B printing")
    }
}

class C: A {
    func printSometing(withPar:String) {
        print("Class C printing" + withPar)
    }
}

let prA = A()
prA.printSometing()

let prB = B()
prB.printSometing()

let prC = C()
prC.printSometing() //I don't won't that C can print this
prC.printSometing(withPar: " my free par")
</code>```

the prints:

```<code>prA prints: Class A printing
prB prints: Class B printing
prC prints: Class A printing
prC prints: Class C printing my free par
</code>```

Ok, is normal, but how I can avoid that prC can print "Class A printing"?

a work around is to write:

```<code>class C: A {
    func printSometing(withPar:String) {
        print("Class C printing" + withPar)
    }
    override func printSometing() {}
}
</code>```

But I won't that who is using the func printSometing with class C, is forced to use only the fun printSometing(withPar:String) and not printSometing()

I'm sure that there is a solution.

UPDATE:

if there is no solution, I think that the only work around to force it is:

```<code>class C: A {
      var myPar:String
      init (withPar:String) {
          self.myPar = withPar
      }
      func printSometing(withPar:String) {
            print("Class C printing" + withPar)
      }
      override func printSometing() {
            printSometing(withPar: myPar)
      }
 }
</code>```

let me know thanks

UPDATE: MY REASONS

Ok I'll explain. I've a game ongoing, in the project I've duplicate the target. So some file are in common in both targets, some other no. Example GameScene.swift is different. In the new target, I want make the same game but with small difference.
Example I've added a features at the player, but I wont preserve the original file. If I change the Player.swift in target 1, the same changes are in target 2. This because the Player2 class are 90% the same of Player. If I'll change some func in Player, Player2 change too.

target 1: GameScene.swift

target 1 and target 2: Player.swift

target 2: Player2.swift

```<code>class Player: SKNode {
    //All my stuff
    func shot() {
        //bla bla bla
    }
}
class Player2: Player {
    override init() {
        //Different physics etc
    }
    func shot(withColor: SKColor) {
        //bla bla bla
    }
    //All other func of Player.swift are available, ok I whant this.
}
</code>```

Now what is the problem?
In may GameScene.swift of target 2, I can call shot(). But for the new game, is necessary to call only func shot(withColor: SKColor).
Ok I know this and is sufficent don't call shot(). But I'm thinking that tomorrow I forget this.

Another work around is to copy all Player.swift in target2. But if I'll add a func in Player.swift in target1, the func doesn't appear in target2.

Is the first time that I'm working with 2 targets in the project, I would be sure to do it correctly.
Thanks

答:
From Wikipedia:

Substitutability is a principle in object-oriented programming stating that, in a computer program, if S is a subtype of T, then objects of type T may be replaced with objects of type S (i.e. an object of type T may be substituted with any object of a subtype S) without altering any of the desirable properties of T.

This is called the Liskov substitution principle (as @dan pointed out in the comments) and the only way to not break it with what you want to achieve is through brute force, either with the code you provided in your question's edit, either with the following code (they are equivalent, without creating an unneeded variable):

```<code>class C: A {
    override func printSometing() {
        print("Class C printing")
    }
    func printSometing(withPar:String) {
        print("Class C printing" + withPar)
    }
}
</code>```

Body:
If I've a subclass, how is possible to deny the access at one func with other one with parameters?

Is easier to explain with code:

class A {
    func printSometing() {
        print("Class A printing")
    }
}

class B: A {
    override func printSometing() {
        print("Class B printing")
    }
}

class C: A {
    func printSometing(withPar:String) {
        print("Class C printing" + withPar)
    }
}

let prA = A()
prA.printSometing()

let prB = B()
prB.printSometing()

let prC = C()
prC.printSometing() //I don't won't that C can print this
prC.printSometing(withPar: " my free par")

the prints:

prA prints: Class A printing
prB prints: Class B printing
prC prints: Class A printing
prC prints: Class C printing my free par

Ok, is normal, but how I can avoid that prC can print "Class A printing"?

a work around is to write:

class C: A {
    func printSometing(withPar:String) {
        print("Class C printing" + withPar)
    }
    override func printSometing() {}
}

But I won't that who is using the func printSometing with class C, is forced to use only the fun printSometing(withPar:String) and not printSometing()

I'm sure that there is a solution.

UPDATE:

if there is no solution, I think that the only work around to force it is:

class C: A {
      var myPar:String
      init (withPar:String) {
          self.myPar = withPar
      }
      func printSometing(withPar:String) {
            print("Class C printing" + withPar)
      }
      override func printSometing() {
            printSometing(withPar: myPar)
      }
 }

let me know thanks

UPDATE: MY REASONS

Ok I'll explain. I've a game ongoing, in the project I've duplicate the target. So some file are in common in both targets, some other no. Example GameScene.swift is different. In the new target, I want make the same game but with small difference.
Example I've added a features at the player, but I wont preserve the original file. If I change the Player.swift in target 1, the same changes are in target 2. This because the Player2 class are 90% the same of Player. If I'll change some func in Player, Player2 change too.

target 1: GameScene.swift

target 1 and target 2: Player.swift

target 2: Player2.swift

class Player: SKNode {
    //All my stuff
    func shot() {
        //bla bla bla
    }
}
class Player2: Player {
    override init() {
        //Different physics etc
    }
    func shot(withColor: SKColor) {
        //bla bla bla
    }
    //All other func of Player.swift are available, ok I whant this.
}

Now what is the problem?
In may GameScene.swift of target 2, I can call shot(). But for the new game, is necessary to call only func shot(withColor: SKColor).
Ok I know this and is sufficent don't call shot(). But I'm thinking that tomorrow I forget this.

Another work around is to copy all Player.swift in target2. But if I'll add a func in Player.swift in target1, the func doesn't appear in target2.

Is the first time that I'm working with 2 targets in the project, I would be sure to do it correctly.
Thanks

Body:
From Wikipedia:

Substitutability is a principle in object-oriented programming stating that, in a computer program, if S is a subtype of T, then objects of type T may be replaced with objects of type S (i.e. an object of type T may be substituted with any object of a subtype S) without altering any of the desirable properties of T.

This is called the Liskov substitution principle (as @dan pointed out in the comments) and the only way to not break it with what you want to achieve is through brute force, either with the code you provided in your question's edit, either with the following code (they are equivalent, without creating an unneeded variable):

class C: A {
    override func printSometing() {
        print("Class C printing")
    }
    func printSometing(withPar:String) {
        print("Class C printing" + withPar)
    }
}


问:
AfterTestRun hook not working Is there any work around without upgrading the version
I am using Nunit 2.6.4  with specflow.Nunit 1.1.1 version.Please suggest if there is any work around without upgrading. If not please let me know the first version where this fix is available, as i have limitation in upgrading it to latest version.</p>

答:
The AfterTestRun hook is normally called when the step assembly is unloaded. This does not work on all test runners and NUnit 2.6 is one of them.

You need this extension for NUnit: https://github.com/techtalk/SpecFlow/blob/master/Installer/NuGetPackages/SpecFlow.NUnit.Runners/SpecFlowNUnitExtension.cs

Download and add this file to your test project and the hook should be called.


问:
IntelliJ is hiding folder in project window mentioned in .gitignore file, how to show that folder in project window?

ignoring build folder does not show it in project window.

commenting .gradle in .gitignore does show it in project windows.

I want to show both .gradle and build folders in project windows but I also want to include them in .gitignore file.

答:
Right click on a directory in the project view and make sure Hide ignored files option is not enabled.

This feature is provided by a third-party .ignore plug-in. IntelliJ IDEA doesn't hide ignored files out of the box.

Note: If you don't see the .gitignore-d files, then try clicking this option regardless of its label in this menu. Sometimes because of a bug the entry says "hide" but clicking it actually shows the hidden files.

ContentLicense: CC BY-SA 4.0


问:
SOAP interceptor for .NET?
I'm working with an API and my results (CRUD) are getting mangled somehow in the return and .NET is throwing invalid XML errors.  Is there a setup trick to getting tcpmon to work with a debugger in Visual Studio?  Or is there another lightweight interceptor/analyzer that I can use to capture the XML?

Thanks.

答:
You can use System.Net.Tracing to view the data. Just add this to the configuration on client or server.

You need to set maxdatasize to a high value.

ContentLicense: CC BY-SA 2.5

Title: SOAP interceptor for .NET?


问:
Convert nested loop to recursion
I have used 3 nested loop. Now i want to convert these loops to recursive.
Also is there a general way to convert a loop into recursive?</p>

```<code>#include <stdio.h>

#define f(x, y, z) ((x + y) * (y + z))

int main()
{
    int test_case, p, q, r, i, j, k, a[100001], b[100001], c[100001], sum;
    scanf("%d", &test_case);
    while (test_case--) {
        scanf("%d%d%d", &p, &q, &r);
        sum = 0;
        for (i = 0; i < p; i++) {
            scanf("%d", &a[i]);
        }
        for (i = 0; i < q; i++) {
            scanf("%d", &b[i]);
        }
        for (i = 0; i < p; i++) {
            scanf("%d", &c[i]);
        }
        for (i = 0; i < q; i++) { // I have convert this to recursion.
            for (j = 0; j < p; j++) {
                for (k = 0; k < r; k++) {
                    if (b[i] >= a[j] && b[i] >= c[k]) {
                        sum += f(a[j], b[i], c[k]);
                    }
                }
            }
        }
        printf("%d\n", sum % 1000000007);
    }
    return 0;
}
</code>```

答:
A loop like:

```<code>for (int i=0; i<n; i++) {
    func(i);
}
</code>```

can be translated to recursion as:

```<code>void rec_fun(int i,int n) {
    if (!(i<n)) return;
    func(i);
    rec_fun(i+1,n);
}
...
rec_fun(0,n);
</code>```

So:

```<code>for (i = 0; i < q; i++) { // I have convert this to recursion.
    for (j = 0; j < p; j++) {
        for (k = 0; k < r; k++) {
            if (b[i] >= a[j] && b[i] >= c[k]) {
                sum += f(a[j], b[i], c[k]);
            }
        }
    }
}
</code>```

can be translated as:

```<code>void rec_k(int k,int r,int i,int j) { // k-loop
    if (!(k<r)) return;
    if (b[i] >= a[j] && b[i] >= c[k]) {
        sum += f(a[j], b[i], c[k]);
    }
    rec_k(k+1,r,i,j); // recurse
}

void rec_j(int j,int p,int i,int r) { // j-loop
    if (!(j<p)) return;
    rec_k(0,r,i,j); // inner loop
    rec_j(j+1,p,i,r); // recurse
}

void rec_i(int i,int q,int p,int r) { // i-loop
    if (!(i<q)) return;
    rec_j(0,p,i,r); // inner loop
    rec_i(i+1,q,p,r); // recurse
}
...
rec_i(0,q,p,r);
</code>```

I'm not sure this is either more readable or useful, but it meets your initial needs.

Title: Convert nested loop to recursion

Body:
I have used 3 nested loop. Now i want to convert these loops to recursive.
Also is there a general way to convert a loop into recursive?

#include <stdio.h>

#define f(x, y, z) ((x + y) * (y + z))

int main()
{
    int test_case, p, q, r, i, j, k, a[100001], b[100001], c[100001], sum;
    scanf("%d", &test_case);
    while (test_case--) {
        scanf("%d%d%d", &p, &q, &r);
        sum = 0;
        for (i = 0; i < p; i++) {
            scanf("%d", &a[i]);
        }
        for (i = 0; i < q; i++) {
            scanf("%d", &b[i]);
        }
        for (i = 0; i < p; i++) {
            scanf("%d", &c[i]);
        }
        for (i = 0; i < q; i++) { // I have convert this to recursion.
            for (j = 0; j < p; j++) {
                for (k = 0; k < r; k++) {
                    if (b[i] >= a[j] && b[i] >= c[k]) {
                        sum += f(a[j], b[i], c[k]);
                    }
                }
            }
        }
        printf("%d\n", sum % 1000000007);
    }
    return 0;
}

Body:
A loop like:

for (int i=0; i<n; i++) {
    func(i);
}

can be translated to recursion as:

void rec_fun(int i,int n) {
    if (!(i<n)) return;
    func(i);
    rec_fun(i+1,n);
}
...
rec_fun(0,n);

So:

for (i = 0; i < q; i++) { // I have convert this to recursion.
    for (j = 0; j < p; j++) {
        for (k = 0; k < r; k++) {
            if (b[i] >= a[j] && b[i] >= c[k]) {
                sum += f(a[j], b[i], c[k]);
            }
        }
    }
}

can be translated as:

void rec_k(int k,int r,int i,int j) { // k-loop
    if (!(k<r)) return;
    if (b[i] >= a[j] && b[i] >= c[k]) {
        sum += f(a[j], b[i], c[k]);
    }
    rec_k(k+1,r,i,j); // recurse
}

void rec_j(int j,int p,int i,int r) { // j-loop
    if (!(j<p)) return;
    rec_k(0,r,i,j); // inner loop
    rec_j(j+1,p,i,r); // recurse
}

void rec_i(int i,int q,int p,int r) { // i-loop
    if (!(i<q)) return;
    rec_j(0,p,i,r); // inner loop
    rec_i(i+1,q,p,r); // recurse
}
...
rec_i(0,q,p,r);

I'm not sure this is either more readable or useful, but it meets your initial needs.


问:
What is an example of statically typed javascript in context to better unit testing?
I'm new to testing but recently, I've been trying using angularJS and Jasmine.

With ES6 on the horizon, in comes new frameworks/languages like: atScript and google angular-dart.  Both which now support optional type javascript and they claim that it becomes easier for testing?

Question:
1.  Being a novice to testing could someone give me a practical example/usecase that would illustrate how statically typed javascript would be better for unit testing.  moreover an example where vanilla javascript unit test would fall short??

Lastly, if this isnt a stackoverflow question could we move it to the appropriate stack subdomain?

答:
Type based assertions are possible. For example:

```<code>is(value : Dynamic, type : Dynamic, ?msg : String , ?pos : PosInfos)
</code>```

Asserts successfully when the 'value' parameter is of the of the passed type 'type'.

```<code>raises(method:Void -> Void, ?type:Class<Dynamic>, ?msgNotThrown : String , ?msgWrongType : String, ?pos : PosInfos)
</code>```

It is used to test an application that under certain circumstances must react throwing an error. This assert guarantees that the error is of the correct type (or Dynamic if none is specified).

This code:

```<code>enum Color { R, G, B }

function f1(x: Color | string) {
    if (typeof x === "number") {
        var y = x;
        var y: Color;
    }
    else {
        var z = x;
        var z: string;
    }
}

function f2(x: Color | string | string[]) {
    if (typeof x === "object") {
        var y = x;
        var y: string[];
    }
    if (typeof x === "number") {
        var z = x;
        var z: Color;
    }
    else {
        var w = x;
        var w: string | string[];
    }
    if (typeof x === "string") {
        var a = x;
        var a: string;
    }
    else {
        var b = x;
        var b: Color | string[];
    }
}
</code>```

would need shims for the following:

enum

type hinting (x: Color)

union types (|)

and this code:

```<code>class A {
    propA: number;
}

class B {
    propB: number;
}

class C extends A {
    propC: number;
}

declare function isB(p1): p1 is B;
declare function isC(p1): p1 is C;
declare function retC(x): C;

declare function funA<T>(p1: (p1) => T): T;
declare function funB<T>(p1: (p1) => T, p2: any): p2 is T;
declare function funC<T>(p1: (p1) => p1 is T): T;
declare function funD<T>(p1: (p1) => p1 is T, p2: any): p2 is T;
declare function funE<T, U>(p1: (p1) => p1 is T, p2: U): T;

let a: A;
let test1: boolean = funA(isB);

if (funB(retC, a)) {
    a.propC;
}
let test2: B = funC(isB);
if (funD(isC, a)) {
    a.propC;
}
let test3: B = funE(isB, 1);
</code>```

would need shims for the following:

user-defined type guards (p1 is B)

type casting of return values (funA<T>(p1: (p1) => T): T)

References

fponticelli/utest: cross-platform unit testing system for Haxe

Typescript infer return type from passed functions return type

What is the difference between ' : ' and ' => 'on functions in typescript?

Cappuccino - Testing with OJTest

ECMAScript 6: New Features: Overview and Comparison

TypeScript Github repo | typeGuardFunctionGenerics.ts

TypeScript Github repo | TypeGuardWithEnumUnion.ts

List of reserved keywords · Issue #2536 · Microsoft/TypeScript

Features That Will Matter in the Upcoming TypeScript 1.8 -- Visual Studio Magazine

Learn with Me - Typescript: A Study in Types - CodeProject

TypeScript 2.0: Even Better Data Typing and Class Discriminants -- Visual Studio Magazine

Kicking TypeScript's Tires

TypeScript for ActionScript Developers

Hello World: How to set up Apache FlexJS to transpile ActionScript to JavaScript - NextGen ActionScript

Microsoft/TypeScript-React-Conversion-Guide: A guide for converting a simple JavaScript/React project to TypeScript. Contains both before an after code with the step-by-step process in the README below.

Body:
Type based assertions are possible. For example:

is(value : Dynamic, type : Dynamic, ?msg : String , ?pos : PosInfos)

Asserts successfully when the 'value' parameter is of the of the passed type 'type'.

raises(method:Void -> Void, ?type:Class<Dynamic>, ?msgNotThrown : String , ?msgWrongType : String, ?pos : PosInfos)

It is used to test an application that under certain circumstances must react throwing an error. This assert guarantees that the error is of the correct type (or Dynamic if none is specified).

This code:

enum Color { R, G, B }

function f1(x: Color | string) {
    if (typeof x === "number") {
        var y = x;
        var y: Color;
    }
    else {
        var z = x;
        var z: string;
    }
}

function f2(x: Color | string | string[]) {
    if (typeof x === "object") {
        var y = x;
        var y: string[];
    }
    if (typeof x === "number") {
        var z = x;
        var z: Color;
    }
    else {
        var w = x;
        var w: string | string[];
    }
    if (typeof x === "string") {
        var a = x;
        var a: string;
    }
    else {
        var b = x;
        var b: Color | string[];
    }
}

would need shims for the following:

enum

type hinting (x: Color)

union types (|)

and this code:

class A {
    propA: number;
}

class B {
    propB: number;
}

class C extends A {
    propC: number;
}

declare function isB(p1): p1 is B;
declare function isC(p1): p1 is C;
declare function retC(x): C;

declare function funA<T>(p1: (p1) => T): T;
declare function funB<T>(p1: (p1) => T, p2: any): p2 is T;
declare function funC<T>(p1: (p1) => p1 is T): T;
declare function funD<T>(p1: (p1) => p1 is T, p2: any): p2 is T;
declare function funE<T, U>(p1: (p1) => p1 is T, p2: U): T;

let a: A;
let test1: boolean = funA(isB);

if (funB(retC, a)) {
    a.propC;
}
let test2: B = funC(isB);
if (funD(isC, a)) {
    a.propC;
}
let test3: B = funE(isB, 1);

would need shims for the following:

user-defined type guards (p1 is B)

type casting of return values (funA<T>(p1: (p1) => T): T)

References

fponticelli/utest: cross-platform unit testing system for Haxe

Typescript infer return type from passed functions return type

What is the difference between ' : ' and ' => 'on functions in typescript?

Cappuccino - Testing with OJTest

ECMAScript 6: New Features: Overview and Comparison

TypeScript Github repo | typeGuardFunctionGenerics.ts

TypeScript Github repo | TypeGuardWithEnumUnion.ts

List of reserved keywords · Issue #2536 · Microsoft/TypeScript

Features That Will Matter in the Upcoming TypeScript 1.8 -- Visual Studio Magazine

Learn with Me - Typescript: A Study in Types - CodeProject

TypeScript 2.0: Even Better Data Typing and Class Discriminants -- Visual Studio Magazine

Kicking TypeScript's Tires

TypeScript for ActionScript Developers

Hello World: How to set up Apache FlexJS to transpile ActionScript to JavaScript - NextGen ActionScript

Microsoft/TypeScript-React-Conversion-Guide: A guide for converting a simple JavaScript/React project to TypeScript. Contains both before an after code with the step-by-step process in the README below.


问:
How to run browsers(chrome, IE and firefox) in headless mode?
I want to integrate JSTestDriver with jenkins-CI.
problem is that the build server does not have display.
is there a way to run browsers headlessly?

Thanks

答:
Google Chrome now (Chrome 59 for Mac and Linux, Chrome 60 for Windows) has a headless mode built-in. It works cross-platform, and doesn't require any messing around with display devices, virtual machines, or anything like that. You can find a great Getting Started article by Eric Bidelman here, but here are the most key points:

You must launch the Chrome binary (on macOS it is located inside the Google Chrome.app bundle in the the Contents/MacOS directory) using --headless flag. It is currently also necessary to add the --disable-gpu flag, because GPU acceleration does not work properly in headless mode.

```<code>chrome --headless --disable-gpu [url/path/flags...]
</code>```

As with standard non-headless Chrome, your test runner can communicate with Chrome using the dev tools interface if it's enabled by the --remote-debugging-port=[SOME_PORT] flag. However, if you'd just like to test it quickly by yourself you can use the --screenshot or --dump-dom flags to check out the contents of the page after loading.

```<code>chrome --headless --disable-gpu --dump-dom https://stackoverflow.com/
</code>```

Body:
Google Chrome now (Chrome 59 for Mac and Linux, Chrome 60 for Windows) has a headless mode built-in. It works cross-platform, and doesn't require any messing around with display devices, virtual machines, or anything like that. You can find a great Getting Started article by Eric Bidelman here, but here are the most key points:

You must launch the Chrome binary (on macOS it is located inside the Google Chrome.app bundle in the the Contents/MacOS directory) using --headless flag. It is currently also necessary to add the --disable-gpu flag, because GPU acceleration does not work properly in headless mode.

chrome --headless --disable-gpu [url/path/flags...]

As with standard non-headless Chrome, your test runner can communicate with Chrome using the dev tools interface if it's enabled by the --remote-debugging-port=[SOME_PORT] flag. However, if you'd just like to test it quickly by yourself you can use the --screenshot or --dump-dom flags to check out the contents of the page after loading.

chrome --headless --disable-gpu --dump-dom https://stackoverflow.com/


问:
Extended methods on Boolean value class wrapper
In my codebase I used tags to encode some information into types. As tags works using t.asInstanceOf[T @@ U] I could get away with many troubles with writing mapping between wrapped and unwrapped values.

Recently I hit the wall with tagged types as they break some functionality in shapeless that I would like to use, so I am trying to use value classes.

So far I could cheat away some e.g. boolean checks with tagged types using something like:

```<code>implicit class TaggedBooleanAsFirstOperand[P1, U](val c: Rep[P1 @@ U]) {
    private val em = new BooleanColumnExtensionMethods[P1](c.asInstanceOf[Rep[P1]])
    type o = OptionMapperDSL.arg[Boolean, P1]

    def @&&[P2, R](b: Rep[P2])(implicit om: o#arg[Boolean, P2]#to[Boolean, R]): Rep[R] = em.&&[P2, R](b)
    def @||[P2, R](b: Rep[P2])(implicit om: o#arg[Boolean, P2]#to[Boolean, R]): Rep[R] = em.||[P2, R](b)
    def unary_! : Rep[P1] = em.unary_!
  }

  implicit class TaggedBooleanAsSecondOperand[P1](val c: Rep[P1]) {
    private val em = new BooleanColumnExtensionMethods[P1](c)
    type o = OptionMapperDSL.arg[Boolean, P1]

    def &&@[P2, U, R](b: Rep[P2 @@ U])(implicit om: o#arg[Boolean, P2]#to[Boolean, R]): Rep[R] = em.&&[P2, R](b.asInstanceOf[Rep[P2]])
    def ||@[P2, U, R](b: Rep[P2 @@ U])(implicit om: o#arg[Boolean, P2]#to[Boolean, R]): Rep[R] = em.||[P2, R](b.asInstanceOf[Rep[P2]])
  }

  implicit class TaggedBooleanAsBothOperands[P1, U](val c: Rep[P1 @@ U]) {
    private val em = new BooleanColumnExtensionMethods[P1](c.asInstanceOf[Rep[P1]])
    type o = OptionMapperDSL.arg[Boolean, P1]

    def @&&@[P2, V, R](b: Rep[P2 @@ V])(implicit om: o#arg[Boolean, P2]#to[Boolean, R]): Rep[R] = em.&&[P2, R](b.asInstanceOf[Rep[P2]])
    def @||@[P2, V, R](b: Rep[P2 @@ V])(implicit om: o#arg[Boolean, P2]#to[Boolean, R]): Rep[R] = em.||[P2, R](b.asInstanceOf[Rep[P2]])
  }
</code>```

With AnyVal however, I cannot simply cast one type into the other where I want to, and I would have to provide some honest code allowing to achieve what I want.

I tried to read Slick source code, but the whole idea where should I start is a little blurry to me - relevant information are spread across many places, so I cannot simply pinpoint a few places to e.g. figure how to map one Rep into the other or extract data from wrapped and unwrapped Boolean and combine them.

Can some Slick experts recommend some good starting point for those?

答:
Tags actually give you not only type safety. It gives you abstraction level as well. Once you wrapped your boolean into a tag you abstract away from runtime representation of your boolean. BTW you should use Tag.unwrap or Tag.unsubst instead of asInstanceOf.
Slick works on a lower level of abstraction. It works with simple types which SQL is aware of.
Of course you need to unwrap tags somewhere in between before working with DB.
I would encapsulate it in table schema. See Mapped Tables section: http://slick.lightbend.com/doc/3.0.0/schemas.html

Body:
In my codebase I used tags to encode some information into types. As tags works using t.asInstanceOf[T @@ U] I could get away with many troubles with writing mapping between wrapped and unwrapped values.

Recently I hit the wall with tagged types as they break some functionality in shapeless that I would like to use, so I am trying to use value classes.

So far I could cheat away some e.g. boolean checks with tagged types using something like:

implicit class TaggedBooleanAsFirstOperand[P1, U](val c: Rep[P1 @@ U]) {
    private val em = new BooleanColumnExtensionMethods[P1](c.asInstanceOf[Rep[P1]])
    type o = OptionMapperDSL.arg[Boolean, P1]

    def @&&[P2, R](b: Rep[P2])(implicit om: o#arg[Boolean, P2]#to[Boolean, R]): Rep[R] = em.&&[P2, R](b)
    def @||[P2, R](b: Rep[P2])(implicit om: o#arg[Boolean, P2]#to[Boolean, R]): Rep[R] = em.||[P2, R](b)
    def unary_! : Rep[P1] = em.unary_!
  }

  implicit class TaggedBooleanAsSecondOperand[P1](val c: Rep[P1]) {
    private val em = new BooleanColumnExtensionMethods[P1](c)
    type o = OptionMapperDSL.arg[Boolean, P1]

    def &&@[P2, U, R](b: Rep[P2 @@ U])(implicit om: o#arg[Boolean, P2]#to[Boolean, R]): Rep[R] = em.&&[P2, R](b.asInstanceOf[Rep[P2]])
    def ||@[P2, U, R](b: Rep[P2 @@ U])(implicit om: o#arg[Boolean, P2]#to[Boolean, R]): Rep[R] = em.||[P2, R](b.asInstanceOf[Rep[P2]])
  }

  implicit class TaggedBooleanAsBothOperands[P1, U](val c: Rep[P1 @@ U]) {
    private val em = new BooleanColumnExtensionMethods[P1](c.asInstanceOf[Rep[P1]])
    type o = OptionMapperDSL.arg[Boolean, P1]

    def @&&@[P2, V, R](b: Rep[P2 @@ V])(implicit om: o#arg[Boolean, P2]#to[Boolean, R]): Rep[R] = em.&&[P2, R](b.asInstanceOf[Rep[P2]])
    def @||@[P2, V, R](b: Rep[P2 @@ V])(implicit om: o#arg[Boolean, P2]#to[Boolean, R]): Rep[R] = em.||[P2, R](b.asInstanceOf[Rep[P2]])
  }

With AnyVal however, I cannot simply cast one type into the other where I want to, and I would have to provide some honest code allowing to achieve what I want.

I tried to read Slick source code, but the whole idea where should I start is a little blurry to me - relevant information are spread across many places, so I cannot simply pinpoint a few places to e.g. figure how to map one Rep into the other or extract data from wrapped and unwrapped Boolean and combine them.

Can some Slick experts recommend some good starting point for those?


问:
Haml breaking. Illegal nesting: content can't be both given on the same line
I am still unclear about why this breaks:

```<code>.form-box
      %h3 Restrictions
      %legend Restricted Locations
        = form_for [:blueadmin, :wine, @wine], html: {class: 'form-horizontal col-lg-2'} do |f|
          %fieldset.inputs
            .control-group
              = f.label :us_states, "US States", class: 'control-label'
              .controls
                = f.collection_select :product, Restriction.all, :us_state, :us_state, {}, :multiple => 'true'
          %fieldset
            %ol
              %li.button
                = f.submit "Submit", class: 'btn btn-primary'
      %table.table.table-hover.table-condensed.story-list
        %th State
        %th Remove
</code>```

The error I get is:
Illegal nesting: content can't be both given on the same line as %legend and nested within it.

the = form_for seems to be the culprit

I understand Restricted Location is on the same line as %legend... but that's how I see the docs.

This works though, but it screws up my legend border:

```<code>  .form-box
      %h3 Restrictions
      %legend
        Restricted Locations
        = form_for [:blueadmin, :wine, @wine], html: {class: 'form-horizontal col-lg-2'} do |f|
          %fieldset.inputs
            .control-group
              = f.label :us_states, "US States", class: 'control-label'
              .controls
                = f.collection_select :product, Restriction.all, :us_state, :us_state, {}, :multiple => 'true'
          %fieldset
            %ol
              %li.button
                = f.submit "Submit", class: 'btn btn-primary'
    %table.table.table-hover.table-condensed.story-list
      %th State
      %th Remove
</code>```

It looks like this:

instead of this:

(notice how the thin line is in a different spot)

Lastly, how do I get the table on the bottom to appear to the right of the form and not underneath? How can I use columns to do this?

答:
you have your form for nested inside the legend element.</p>

```<code> .form-box
  %h3 Restrictions
  %legend
    Restricted Locations
  = form_for [:blueadmin, :wine, @wine], html: {class: 'form-horizontal col-lg-2'} do |f|
    %fieldset.inputs
      .control-group
        = f.label :us_states, "US States", class: 'control-label'
        .controls
          = f.collection_select :product, Restriction.all, :us_state, :us_state, {}, :multiple => 'true'
    %fieldset
      %ol
        %li.button
          = f.submit "Submit", class: 'btn btn-primary'
%table.table.table-hover.table-condensed.story-list
  %th State
  %th Remove
</code>```

Body:
I am still unclear about why this breaks:

.form-box
      %h3 Restrictions
      %legend Restricted Locations
        = form_for [:blueadmin, :wine, @wine], html: {class: 'form-horizontal col-lg-2'} do |f|
          %fieldset.inputs
            .control-group
              = f.label :us_states, "US States", class: 'control-label'
              .controls
                = f.collection_select :product, Restriction.all, :us_state, :us_state, {}, :multiple => 'true'
          %fieldset
            %ol
              %li.button
                = f.submit "Submit", class: 'btn btn-primary'
      %table.table.table-hover.table-condensed.story-list
        %th State
        %th Remove

The error I get is:
Illegal nesting: content can't be both given on the same line as %legend and nested within it.

the = form_for seems to be the culprit

I understand Restricted Location is on the same line as %legend... but that's how I see the docs.

This works though, but it screws up my legend border:

  .form-box
      %h3 Restrictions
      %legend
        Restricted Locations
        = form_for [:blueadmin, :wine, @wine], html: {class: 'form-horizontal col-lg-2'} do |f|
          %fieldset.inputs
            .control-group
              = f.label :us_states, "US States", class: 'control-label'
              .controls
                = f.collection_select :product, Restriction.all, :us_state, :us_state, {}, :multiple => 'true'
          %fieldset
            %ol
              %li.button
                = f.submit "Submit", class: 'btn btn-primary'
    %table.table.table-hover.table-condensed.story-list
      %th State
      %th Remove

It looks like this:

instead of this:

(notice how the thin line is in a different spot)

Lastly, how do I get the table on the bottom to appear to the right of the form and not underneath? How can I use columns to do this?

Body:
you have your form for nested inside the legend element.

 .form-box
  %h3 Restrictions
  %legend
    Restricted Locations
  = form_for [:blueadmin, :wine, @wine], html: {class: 'form-horizontal col-lg-2'} do |f|
    %fieldset.inputs
      .control-group
        = f.label :us_states, "US States", class: 'control-label'
        .controls
          = f.collection_select :product, Restriction.all, :us_state, :us_state, {}, :multiple => 'true'
    %fieldset
      %ol
        %li.button
          = f.submit "Submit", class: 'btn btn-primary'
%table.table.table-hover.table-condensed.story-list
  %th State
  %th Remove


问:
How to load different html files for jit and aot in Angular?
I would like to have both just-in-time and the ahead-of-time compiler options in the same package (directory). I have different versions of: app.module.ts, main.ts, tsconfig.json and main.html files in the same directory. Can anyone tell me how to tell the lite-server to use different a different html file depending on which compiler I am using?

I think the solution is to use a configure file from browser-sync, but I have no idea how to configure it.

答:
try to follow below link it will good understand about mainting two html file for JIT and AOT
https://angular.io/docs/ts/latest/cookbook/aot-compiler.html#!#run-jit</p>


问:
How to split single column comma separated values into multiple column and left joint to each cell from another table in MySQL?
I need a solution to create view in MySQL.
I have two table of data. One have list of customer names.

```
Table: name_list
Id          Name
------------------
12345       Steve
23456       Mick
34567       Robert
45678       John
56789       Taylor
67890       Steven
23234       Ken
56746       Harry
```

another have customer groups.

```
Table: customer_group
Group       Customers
----------------------
A5213       12345,34567,56789
B5314       23234
D5486       23456,45678,67890,56746
```

Now I need to show these data by splitting comma separated customer id from customer_group table and join name of those customers from name_list table.

```
View: customer_name_result
Group   Cust1   Name1   Cust2   Name2   Cust3   Name3   Cust4   Name4
----------------------------------------------------------------------
A5213   12345   Steve   34567   Robert  56789   Taylor  NULL    NULL
B5314   23234   Ken     NULL    NULL    NULL    NULL    NULL    NULL
D5486   23456   Mick    45678   John    67890   Steven  56746   Harry
```

Body:
I need a solution to create view in MySQL.
I have two table of data. One have list of customer names.

Table: name_list
Id          Name
------------------
12345       Steve
23456       Mick
34567       Robert
45678       John
56789       Taylor
67890       Steven
23234       Ken
56746       Harry

another have customer groups.

Table: customer_group
Group       Customers
----------------------
A5213       12345,34567,56789
B5314       23234
D5486       23456,45678,67890,56746

Now I need to show these data by splitting comma separated customer id from customer_group table and join name of those customers from name_list table.

View: customer_name_result
Group   Cust1   Name1   Cust2   Name2   Cust3   Name3   Cust4   Name4
----------------------------------------------------------------------
A5213   12345   Steve   34567   Robert  56789   Taylor  NULL    NULL
B5314   23234   Ken     NULL    NULL    NULL    NULL    NULL    NULL
D5486   23456   Mick    45678   John    67890   Steven  56746   Harry

Body:
You can use pivot as below:

;with cte as (
    select [Group], [Value], nl.[name], RowN = Row_Number() over(partition by [Group] order by [Value])
        ,RowN1 = Row_Number() over(partition by [Group] order by [Value]) +1000
        from customer_group cg
    cross apply
    (
        Select * from string_split(customers,',')
    ) a
    inner join name_list nl
    on a.value = nl.id
)
select [Group],   max([1001]) as [Name1], max([1]) as [Val1]
                , max([1002]) as [Name2], max([2]) as [Val1]
                , max([1003]) as [Name3], max([3]) as [Val1]
                , max([1004]) as [Name4], max([4]) as [Val1]
from
(select * from cte ) b
pivot (max([value]) for RowN in([1],[2],[3],[4])) p
pivot (max([name]) for RowN1 in ([1001],[1002],[1003],[1004])) p1
group by [Group]

Answer as below:

+-------+--------+-------+--------+-------+--------+-------+--------+-------+
| Group | Name1  | Val1  | Name2  | Val1  | Name3  | Val1  | Name4  | Val1  |
+-------+--------+-------+--------+-------+--------+-------+--------+-------+
| A5213 | Steve  | 12345 | Robert | 34567 | Taylor | 56789 | NULL   | NULL  |
| B5314 | Ken    | 23234 | NULL   | NULL  | NULL   | NULL  | NULL   | NULL  |
| D5486 | Mick   | 23456 | John   | 45678 | Harry  | 56746 | Steven | 67890 |
+-------+--------+-------+--------+-------+--------+-------+--------+-------+


问:
Woocommerce shipping calculation timing out
I've created a function discount_foil_seal_items() that applies a price change in the cart using the hook woocommerce_before_calculate_totals.  It will update the cart totals fine but when I get to checkout the shipping calculation times out (ie spinning icon perpetually). I haven't been able to find any posts relating to this specific issue.

I tried commenting out sections of the function to see what was causing it and it seems that if I run either of the foreach in this function it times out.  Is it something to do with nesting an if statement or switch statement inside the foreach?

```<code>//apply discounts to foil and seal product categories
add_action( 'woocommerce_before_calculate_totals', 'discount_foil_seal_items', 10, 1 );
function discount_foil_seal_items( $cart_object ) {

// Iterating through each item in cart
foreach ( $cart_object->get_cart() as $item_values ) {

    // Get cart item data
    $item_id = $item_values['data']->id; // Product ID
    $item_qty = $item_values['quantity']; // Item quantity

    // Get the object
    $product = new WC_Product( $item_id );
    $prod_cat = wp_get_post_terms($product->id,'product_cat',array('fields'=>'slugs'));

    //tally totals
    if (in_array('seal-stickers', $prod_cat)){
        $seal_prod_tally += $item_qty;
    }else if(in_array('foil-badges', $prod_cat)){
        $foil_prod_tally += $item_qty;
    }
}

 foreach ( $cart_object->get_cart() as $item_values ) {

    //Get cart item data
    $item_id = $item_values['data']->id; // Product ID
    $item_qty = $item_values['quantity']; // Item quantity

    // Get the object
    $product = new WC_Product( $item_id );
    $prod_cat2 = wp_get_post_terms($product->id,'product_cat',array('fields'=>'slugs'));

    //apply discount to each item within category
    if (in_array('seal-stickers',$prod_cat2)){
        switch ($seal_prod_tally){
            case 25000:
                $item_values['data']->set_price(1327.01/20000);
                echo 'case 25000 seal has run <br>';
                break;
            case 30000:
                $item_values['data']->set_price(1578.65/30000);
                break;
            case 50000:
                $item_values['data']->set_price(2126.76/50000);
                break;
            case 60000:
                $item_values['data']->set_price(2405.98/60000);
                break;
        }
    }else if (in_array( 'foil-badges',$prod_cat2)){
        switch ($foil_prod_tally){
            case 25000:
                $item_values['data']->set_price(5872.63/25000);
                break;
            case 50000:
                $item_values['data']->set_price(10815.47/50000);
                break;
        }
    }

 }
</code>```

}

Also I've commented out both foreach and inserted a simplified foreach like below which runs fine:

```<code>//this foreach doesn't timeout
    foreach ( $cart_object->get_cart() as $item_values ){
        $item_values['data']->set_price(1327.01/20000);
    }
</code>```

Other products on this site checkout fine without timeout errors.

Any help on what is causing the timeout would be much appreciated!

Here's a screenshot of the timeout:

https://i.gyazo.com/f5869d0b7b01e4e73ff27885e5b18208.png

Update

I tried rewriting the code replacing the switch statements with if else if blocks to no avail. I then tried splitting the functions into two separate ones just to see if that did anything which also didn't fix the timeout.  Here's the code split in two different functions:

```<code>//apply discounts to foil and seal product categories
add_action( 'woocommerce_before_calculate_totals', 'cart_count_foil_seal_items',10,1);

function cart_count_foil_seal_items( $cart_object ) {
    echo 'discount_foil_seal_items() has run <br>';
    $seal_prod_tally = 0;
    $foil_prod_tally = 0;
// Iterating through each item in cart
foreach ( $cart_object->get_cart() as $item_values ) {
    //  Get cart item data
    $item_id = $item_values['data']->get_id(); // Product ID
    $item_qty = $item_values['quantity']; // Item quantity

    // Getting the object
    $product = new WC_Product( $item_id );
    $prod_cat = wp_get_post_terms($product->get_id(),'product_cat',array('fields'=>'slugs'));

    //tally total
    if (in_array('seal-stickers', $prod_cat)){
        $seal_prod_tally += $item_qty;
    }else if(in_array('foil-badges', $prod_cat)){
        $foil_prod_tally += $item_qty;
    }
}

 return array($seal_prod_tally,$foil_prod_tally);
}

//apply discounts to foil and seal product categories
add_action( 'woocommerce_before_calculate_totals', 'discount_foil_seal_items',12);

function discount_foil_seal_items( $cart_object ) {
echo 'discount_foil_seal_items() has run <br>';

list($seal_prod_tally, $foil_prod_tally) = cart_count_foil_seal_items($cart_object);

 foreach ( $cart_object->get_cart() as $item_values ) {

    //Get cart item data
    $item_id = $item_values['data']->get_id(); // Product ID
    $item_qty = $item_values['quantity']; // Item quantity

    // Getting the object
    $product = new WC_Product( $item_id );
    $prod_cat2 = wp_get_post_terms($product->get_id(),'product_cat',array('fields'=>'slugs'));

    //apply discount to each item within category

      if (in_array('seal-stickers',$prod_cat2)){

        switch ($seal_prod_tally){
            case 25000:
                $item_values['data']->set_price(1327.01/20000);
                break;
            case 30000:
                $item_values['data']->set_price(1578.65/30000);
                break;
            case 50000:
                $item_values['data']->set_price(2126.76/50000);
                break;
            case 60000:
                $item_values['data']->set_price(2405.98/60000);
                break;
            default:
                break;
        }
    }else if (in_array( 'foil-badges',$prod_cat2)){
        switch ($foil_prod_tally){
            case 25000:
                $item_values['data']->set_price(5872.63/25000);
                break;
            case 50000:
                $item_values['data']->set_price(10815.47/50000);
                break;
            default:
                break;
        }
    }
 }

}
</code>```

答:
I found the issue it was an echo statement that I had for debugging purposes. I removed that and it worked.  I didn't realize an echo statement would cause timeouts like that but it's good to know:

I removed this line:
echo 'discount_foil_seal_items() has run
';

In both functions and it works.

Body:
I've created a function discount_foil_seal_items() that applies a price change in the cart using the hook woocommerce_before_calculate_totals.  It will update the cart totals fine but when I get to checkout the shipping calculation times out (ie spinning icon perpetually). I haven't been able to find any posts relating to this specific issue.

I tried commenting out sections of the function to see what was causing it and it seems that if I run either of the foreach in this function it times out.  Is it something to do with nesting an if statement or switch statement inside the foreach?

//apply discounts to foil and seal product categories
add_action( 'woocommerce_before_calculate_totals', 'discount_foil_seal_items', 10, 1 );
function discount_foil_seal_items( $cart_object ) {

// Iterating through each item in cart
foreach ( $cart_object->get_cart() as $item_values ) {

    // Get cart item data
    $item_id = $item_values['data']->id; // Product ID
    $item_qty = $item_values['quantity']; // Item quantity

    // Get the object
    $product = new WC_Product( $item_id );
    $prod_cat = wp_get_post_terms($product->id,'product_cat',array('fields'=>'slugs'));

    //tally totals
    if (in_array('seal-stickers', $prod_cat)){
        $seal_prod_tally += $item_qty;
    }else if(in_array('foil-badges', $prod_cat)){
        $foil_prod_tally += $item_qty;
    }
}

 foreach ( $cart_object->get_cart() as $item_values ) {

    //Get cart item data
    $item_id = $item_values['data']->id; // Product ID
    $item_qty = $item_values['quantity']; // Item quantity

    // Get the object
    $product = new WC_Product( $item_id );
    $prod_cat2 = wp_get_post_terms($product->id,'product_cat',array('fields'=>'slugs'));

    //apply discount to each item within category
    if (in_array('seal-stickers',$prod_cat2)){
        switch ($seal_prod_tally){
            case 25000:
                $item_values['data']->set_price(1327.01/20000);
                echo 'case 25000 seal has run
';
                break;
            case 30000:
                $item_values['data']->set_price(1578.65/30000);
                break;
            case 50000:
                $item_values['data']->set_price(2126.76/50000);
                break;
            case 60000:
                $item_values['data']->set_price(2405.98/60000);
                break;
        }
    }else if (in_array( 'foil-badges',$prod_cat2)){
        switch ($foil_prod_tally){
            case 25000:
                $item_values['data']->set_price(5872.63/25000);
                break;
            case 50000:
                $item_values['data']->set_price(10815.47/50000);
                break;
        }
    }

 }

}

Also I've commented out both foreach and inserted a simplified foreach like below which runs fine:

//this foreach doesn't timeout
    foreach ( $cart_object->get_cart() as $item_values ){
        $item_values['data']->set_price(1327.01/20000);
    }

Other products on this site checkout fine without timeout errors.

Any help on what is causing the timeout would be much appreciated!

Here's a screenshot of the timeout:

https://i.gyazo.com/f5869d0b7b01e4e73ff27885e5b18208.png

Update

I tried rewriting the code replacing the switch statements with if else if blocks to no avail. I then tried splitting the functions into two separate ones just to see if that did anything which also didn't fix the timeout.  Here's the code split in two different functions:

//apply discounts to foil and seal product categories
add_action( 'woocommerce_before_calculate_totals', 'cart_count_foil_seal_items',10,1);

function cart_count_foil_seal_items( $cart_object ) {
    echo 'discount_foil_seal_items() has run
';
    $seal_prod_tally = 0;
    $foil_prod_tally = 0;
// Iterating through each item in cart
foreach ( $cart_object->get_cart() as $item_values ) {
    //  Get cart item data
    $item_id = $item_values['data']->get_id(); // Product ID
    $item_qty = $item_values['quantity']; // Item quantity

    // Getting the object
    $product = new WC_Product( $item_id );
    $prod_cat = wp_get_post_terms($product->get_id(),'product_cat',array('fields'=>'slugs'));

    //tally total
    if (in_array('seal-stickers', $prod_cat)){
        $seal_prod_tally += $item_qty;
    }else if(in_array('foil-badges', $prod_cat)){
        $foil_prod_tally += $item_qty;
    }
}

 return array($seal_prod_tally,$foil_prod_tally);
}

//apply discounts to foil and seal product categories
add_action( 'woocommerce_before_calculate_totals', 'discount_foil_seal_items',12);

function discount_foil_seal_items( $cart_object ) {
echo 'discount_foil_seal_items() has run
';

list($seal_prod_tally, $foil_prod_tally) = cart_count_foil_seal_items($cart_object);

 foreach ( $cart_object->get_cart() as $item_values ) {

    //Get cart item data
    $item_id = $item_values['data']->get_id(); // Product ID
    $item_qty = $item_values['quantity']; // Item quantity

    // Getting the object
    $product = new WC_Product( $item_id );
    $prod_cat2 = wp_get_post_terms($product->get_id(),'product_cat',array('fields'=>'slugs'));

    //apply discount to each item within category

      if (in_array('seal-stickers',$prod_cat2)){

        switch ($seal_prod_tally){
            case 25000:
                $item_values['data']->set_price(1327.01/20000);
                break;
            case 30000:
                $item_values['data']->set_price(1578.65/30000);
                break;
            case 50000:
                $item_values['data']->set_price(2126.76/50000);
                break;
            case 60000:
                $item_values['data']->set_price(2405.98/60000);
                break;
            default:
                break;
        }
    }else if (in_array( 'foil-badges',$prod_cat2)){
        switch ($foil_prod_tally){
            case 25000:
                $item_values['data']->set_price(5872.63/25000);
                break;
            case 50000:
                $item_values['data']->set_price(10815.47/50000);
                break;
            default:
                break;
        }
    }
 }

}

Body:
I found the issue it was an echo statement that I had for debugging purposes. I removed that and it worked.  I didn't realize an echo statement would cause timeouts like that but it's good to know:

I removed this line:
echo 'discount_foil_seal_items() has run <br>';

In both functions and it works.


问:
I'm trying to translate my app in Qt but something goes wrong and there is no result
So I have made a *.qm file with translation done via QLinguist. Now I'm trying to translate program by clicking the button, but nothing happens.

it's files hierarchy

```<code>QTranslator translator;
void ChatWindow::on_actionRussian_triggered()
{
     translator.load(":/chApp_ru.qm");
     qApp->installTranslator(&translator);
     ui->retranslateUi(this);
}
</code>```

答:
The problem is that you must place the path of the generated file, in your case Translations/chApp_ru.qm since this is a conversion of chApp_ru.ts, and the latter file takes as reference a relative path:

```<code><?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE TS>
<TS version="2.1" language="ru_RU">
<context>
    <name>ChatWindow</name>
    <message>
        <location filename="../chatwindow.ui" line="14"/>
        <location filename="../chatwindow.ui" line="266"/>
        <source>chApp</source>
        <extracomment>by tia</extracomment>
        <translation></translation>
    </message>
[...]
</code>```

I recommend adding to your qresource the .qm file that is in the translations folder.

Add it as shown in the figure:

And you have to modify your code to:

```<code>void ChatWindow::on_actionRussian_triggered()
{
     translator.load(":/Translations/chApp_ru.qm");
     qApp->installTranslator(&translator);
     ui->retranslateUi(this);
}
</code>```

Output:

Body:
So I have made a *.qm file with translation done via QLinguist. Now I'm trying to translate program by clicking the button, but nothing happens.

it's files hierarchy

QTranslator translator;
void ChatWindow::on_actionRussian_triggered()
{
     translator.load(":/chApp_ru.qm");
     qApp->installTranslator(&translator);
     ui->retranslateUi(this);
}

Body:
The problem is that you must place the path of the generated file, in your case Translations/chApp_ru.qm since this is a conversion of chApp_ru.ts, and the latter file takes as reference a relative path:

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE TS>
<TS version="2.1" language="ru_RU">
<context>
    <name>ChatWindow</name>
    <message>
        <location filename="../chatwindow.ui" line="14"/>
        <location filename="../chatwindow.ui" line="266"/>
        <source>chApp</source>
        <extracomment>by tia</extracomment>
        <translation></translation>
    </message>
[...]

I recommend adding to your qresource the .qm file that is in the translations folder.

Add it as shown in the figure:

And you have to modify your code to:

void ChatWindow::on_actionRussian_triggered()
{
     translator.load(":/Translations/chApp_ru.qm");
     qApp->installTranslator(&translator);
     ui->retranslateUi(this);
}

Output:


问:
window in pygame freeze while waiting
I'm using pygame for my game and its online but the problem is that whenever the main loop of the game waits for the socket from the server its freezes.
so unless you are doing your turn, the client wait for a socket from the server and its doing nothing while waiting and freeze until its get the socket and do its turn.

So I read few answers and solutions on this site and on some others and from what I understood after 5 seconds of doing nothing the OS thinks the window (locked itself)? so I created the thread keep_run but it does not make any change and the window still freeze while its not his turn.

Also to mention the server works with select library if its help in anyway because keep_run() is the only thread I used.

I did not include many lines in my code because there are too much but its a basic conclusion of the important stuff that maybe cause it?

```<code>import sockets
import pygame
from threading import Thread
def keep_run():
    clock = pygame.time.Clock()
    fps = 60
    while True:
        pygame.event.pump()
        clock.tick(fps)

pygame.init()
keep_running = Thread(target=keep_run)
keep_running.setDaemon(True)
keep_running.start()

while Game_run:

   #the main loop
   server_command = client_socket.recv(1024)
   if server_command == "move":
       # make your turn
       do_turn()
   elif server_command == "over":
       # finish the game
       finish_game()
</code>```

image of the example: https://i.stack.imgur.com/b4Qx8.png

答:
You must call pygame.event.pump() (which is implicitly called by pygame.event.get(), pygame.event.clear(), pygame.event.poll(), pygame.event.wait() or pygame.event.peek()) regularly in the thread that initialized the video subsystem (Pygame is built on SDL, hence the link to SDL documentation).

I would also suggest that you don't use pygame.event.pump() and instead handle all events properly with pygame.event.get() or pygame.event.poll(). More about this here.

Title: window in pygame freeze while waiting

Body:
I'm using pygame for my game and its online but the problem is that whenever the main loop of the game waits for the socket from the server its freezes.
so unless you are doing your turn, the client wait for a socket from the server and its doing nothing while waiting and freeze until its get the socket and do its turn.

So I read few answers and solutions on this site and on some others and from what I understood after 5 seconds of doing nothing the OS thinks the window (locked itself)? so I created the thread keep_run but it does not make any change and the window still freeze while its not his turn.

Also to mention the server works with select library if its help in anyway because keep_run() is the only thread I used.

I did not include many lines in my code because there are too much but its a basic conclusion of the important stuff that maybe cause it?

import sockets
import pygame
from threading import Thread
def keep_run():
    clock = pygame.time.Clock()
    fps = 60
    while True:
        pygame.event.pump()
        clock.tick(fps)

pygame.init()
keep_running = Thread(target=keep_run)
keep_running.setDaemon(True)
keep_running.start()

while Game_run:

   #the main loop
   server_command = client_socket.recv(1024)
   if server_command == "move":
       # make your turn
       do_turn()
   elif server_command == "over":
       # finish the game
       finish_game()

image of the example: https://i.stack.imgur.com/b4Qx8.png


问:
mysql remove duplicate month
I want to remove duplicate month

this is my data

i want remove duplicate and show like this

this is my code

```<code><?php
    include "connect.php";
    $query = "select * from mydata";
    $result = mysqli_query($con,$query);
    while($data  = mysqli_fetch_array($result)){
        $dbasearray[] = $data['month_data'].",".$data['week_data'].",".$data['total_data'];
    }
    $s1 = array();
    $s2 = array();
    $a  = array();
    $b  = array();

    echo "<table border='1'>

            <tr>
                <th>Month</th>
                <th>Week</th>
                <th>Total</th>
                <th>s1</th>
                <th>s2</th>
                <th>a</th>
                <th>b</th>
            </tr>
            ";
        foreach ($dbasearray as $index => $datah){

            $data = explode(",", $datah);

            echo "<tr>";
            echo "<td align='center'>".$data[0]."</td>";
            echo "<td align='center'>".$data[1]."</td>";
            echo "<td align='center'>".$data[2]."</td>";
                if($index==0){
                    echo "<td>".$s1[$index] = $data[2]."</td>";
                    echo "<td>".$s2[$index] = $data[2]."</td>";
                }
                else {
                    echo "<td>".$s1[$index] = 0.1*$data[2]+0.9*$s1[$index-1]."</td>";
                    echo "<td>".$s2[$index] = 0.1*$s1[$index]+0.9*$s2[$index-1]."</td>";
                }
                echo "<td>".$a[$index] = 2*$s1[$index]-$s2[$index]."</td>";
                echo "<td>".$b[$index] = (0.1/0.9)*($s1[$index]-$s2[$index])."</td>";
            echo "</tr>";
        }
    echo "</table>";
    ?>
</code>```

i don't know to remove/hidden my code, i'm cannot using group by
help me. Thank's

答:
```<code><?php
include "koneksi.php";
$chkArry=array();
$query = "select * from mydata";
$result = mysql_query($query);
while($data  = mysql_fetch_array($result)){
    $dbasearray[] = $data['month_data'].",".$data['week_data'].",".$data['total_data'];
}
$s1 = array();
$s2 = array();
$a  = array();
$b  = array();

echo "<table border='1'>

        <tr>
            <th>Month</th>
            <th>Week</th>
            <th>Total</th>
            <th>s1</th>
            <th>s2</th>
            <th>a</th>
            <th>b</th>
        </tr>
        ";
    foreach ($dbasearray as $index => $datah){

        $data = explode(",", $datah);
        if(in_array($data[0], $chkArry)){
            $data[0]='';
        }
        else
         {
            array_push($chkArry, $data[0]);
         }
        echo "<tr>";
        echo "<td align='center'>".$data[0]."</td>";
        echo "<td align='center'>".$data[1]."</td>";
        echo "<td align='center'>".$data[2]."</td>";
            if($index==0){
                echo "<td>".$s1[$index] = $data[2]."</td>";
                echo "<td>".$s2[$index] = $data[2]."</td>";
            }
            else {
                echo "<td>".$s1[$index] = 0.1*$data[2]+0.9*$s1[$index-1]."</td>";
                echo "<td>".$s2[$index] = 0.1*$s1[$index]+0.9*$s2[$index-1]."</td>";
            }
            echo "<td>".$a[$index] = 2*$s1[$index]-$s2[$index]."</td>";
            echo "<td>".$b[$index] = (0.1/0.9)*($s1[$index]-$s2[$index])."</td>";
        echo "</tr>";
    }
echo "</table>";
?>
</code>```

try above code and let me know if problem still persists.

Title: mysql remove duplicate month

Body:
I want to remove duplicate month

this is my data

i want remove duplicate and show like this

this is my code

<?php
    include "connect.php";
    $query = "select * from mydata";
    $result = mysqli_query($con,$query);
    while($data  = mysqli_fetch_array($result)){
        $dbasearray[] = $data['month_data'].",".$data['week_data'].",".$data['total_data'];
    }
    $s1 = array();
    $s2 = array();
    $a  = array();
    $b  = array();

    echo "

                Month
                Week
                Total
                s1
                s2
                a
                b

            ";
        foreach ($dbasearray as $index => $datah){

            $data = explode(",", $datah);

            echo "
";
            echo "".$data[0]."	";
            echo "".$data[1]."	";
            echo "".$data[2]."	";
                if($index==0){
                    echo "".$s1[$index] = $data[2]."	";
                    echo "".$s2[$index] = $data[2]."	";
                }
                else {
                    echo "".$s1[$index] = 0.1*$data[2]+0.9*$s1[$index-1]."	";
                    echo "".$s2[$index] = 0.1*$s1[$index]+0.9*$s2[$index-1]."	";
                }
                echo "".$a[$index] = 2*$s1[$index]-$s2[$index]."	";
                echo "".$b[$index] = (0.1/0.9)*($s1[$index]-$s2[$index])."	";
            echo "
";
        }
    echo "
";
    ?>

i don't know to remove/hidden my code, i'm cannot using group by
help me. Thank's

Body:
<?php
include "koneksi.php";
$chkArry=array();
$query = "select * from mydata";
$result = mysql_query($query);
while($data  = mysql_fetch_array($result)){
    $dbasearray[] = $data['month_data'].",".$data['week_data'].",".$data['total_data'];
}
$s1 = array();
$s2 = array();
$a  = array();
$b  = array();

echo "<table border='1'>

        <tr>
            <th>Month</th>
            <th>Week</th>
            <th>Total</th>
            <th>s1</th>
            <th>s2</th>
            <th>a</th>
            <th>b</th>
        </tr>
        ";
    foreach ($dbasearray as $index => $datah){

        $data = explode(",", $datah);
        if(in_array($data[0], $chkArry)){
            $data[0]='';
        }
        else
         {
            array_push($chkArry, $data[0]);
         }
        echo "<tr>";
        echo "<td align='center'>".$data[0]."</td>";
        echo "<td align='center'>".$data[1]."</td>";
        echo "<td align='center'>".$data[2]."</td>";
            if($index==0){
                echo "<td>".$s1[$index] = $data[2]."</td>";
                echo "<td>".$s2[$index] = $data[2]."</td>";
            }
            else {
                echo "<td>".$s1[$index] = 0.1*$data[2]+0.9*$s1[$index-1]."</td>";
                echo "<td>".$s2[$index] = 0.1*$s1[$index]+0.9*$s2[$index-1]."</td>";
            }
            echo "<td>".$a[$index] = 2*$s1[$index]-$s2[$index]."</td>";
            echo "<td>".$b[$index] = (0.1/0.9)*($s1[$index]-$s2[$index])."</td>";
        echo "</tr>";
    }
echo "</table>";
?>

try above code and let me know if problem still persists.


问:
C# disable listbox from parent form
I have an mdi child form as a dockable content in my application and I want to disable/enable a listbox in it from the parent form depending on a certain event. I thought this would be simple as:

```<code>_child.listBox1.Enabled = false;
</code>```

But it doesn't seem to disable it. _child is an object reference of the mdi child form btw. Why does it not work and how can I fix this?

答:
_child probably refers to a different instance of the child form.

Make sure that _child refers to the same instance that you called Show() on.

Title: C# disable listbox from parent form

Body:
I have an mdi child form as a dockable content in my application and I want to disable/enable a listbox in it from the parent form depending on a certain event. I thought this would be simple as:

_child.listBox1.Enabled = false;

But it doesn't seem to disable it. _child is an object reference of the mdi child form btw. Why does it not work and how can I fix this?


问:
How do I stop the position of JLabels changing inside a JPanel whenever I change the text of other JLabels in the same JPanel?
I have multiple JLabels in a JPanel. Whenever I change the text in one, it causes the other JLabels inside the JPanel to move. How to I lock them in place?</p>

答:
The approach really depends how you labels are positioned and what LayoutManager you are using.

JLabel by default will calculate its size mostly based on the label text and font size. If you are changing the text, then the JLabel size will change as well and thus make the layout manager to reposition the other labels.

Here is an example that uses FlowLayout and hard sets JLabel preferred size so that it wont change when its text changes. Other layout managers might choose to ignore the preferred size:

```<code>    JFrame frame = new JFrame();
    frame.getContentPane().setLayout( new FlowLayout() );

    JLabel l = new JLabel("text1");
    l.setPreferredSize( new Dimension( 50, (int)l.getPreferredSize().getHeight() ) );
    frame.getContentPane().add(l);

    frame.getContentPane().add( new JLabel("text2") );
    frame.getContentPane().add( new JLabel("text3") );
</code>```

Here if you change text for l it wont shift the other 2 labels.

Body:
The approach really depends how you labels are positioned and what LayoutManager you are using.

JLabel by default will calculate its size mostly based on the label text and font size. If you are changing the text, then the JLabel size will change as well and thus make the layout manager to reposition the other labels.

Here is an example that uses FlowLayout and hard sets JLabel preferred size so that it wont change when its text changes. Other layout managers might choose to ignore the preferred size:

    JFrame frame = new JFrame();
    frame.getContentPane().setLayout( new FlowLayout() );

    JLabel l = new JLabel("text1");
    l.setPreferredSize( new Dimension( 50, (int)l.getPreferredSize().getHeight() ) );
    frame.getContentPane().add(l);

    frame.getContentPane().add( new JLabel("text2") );
    frame.getContentPane().add( new JLabel("text3") );

Here if you change text for l it wont shift the other 2 labels.


问:
Div floating left in another div onclick to fill screen
I have looked for a solution to this for ages, but have not been able to find an answer. I have some divs inside another div which all float left. I want it so when one is clicked it expands to fill the entire screen and then when a close button that appears in the top right is clicked it goes back to normal, without pushing any of the other divs around. I HAVE been able to achieve this but when i click the div again after the close button is pressed it wont re-expand. Help!

/* We need to create dynamic keyframes to show the animation from full-screen to normal. So we create a stylesheet in which we can insert CSS keyframe rules */

/* Click on the container */
$("#box1").on('click', function() {
  $("body").append('');
 /* The position of the container will be set to fixed, so set the top & left properties of the container */
 var bounding_box = $("#box1").get(0).getBoundingClientRect();
 $(this).css({ top: bounding_box.top + 'px', left: bounding_box.left + 'px' });
  $('#twitter').hide();
   $('#googlebadge').hide();

 /* Set container to fixed position. Add animation */
 $(this).addClass('in-animation');

 /* An empty container has to be added in place of the lightbox container so that the elements below don't come up
 Dimensions of this empty container is the same as the original container */
 $('

').insertAfter("#box1");

 /* To animate the container from full-screen to normal, we need dynamic keyframes */
 var styles = '';
 styles = '@keyframes outlightbox {';
  styles += '0% {';
  styles += 'height: 100%;';
  styles += 'width: 100%;';
  styles += 'top: 0px;';
  styles += 'left: 0px;';
  styles += '}';
  styles += '50% {';
  styles += 'height: 200px;';
  styles += 'top: ' + bounding_box.y + 'px;';
  styles += '}';
  styles += '100% {';
  styles += 'height: 200px;';
  styles += 'width: 500px;';
  styles += 'top: ' + bounding_box.y + 'px;';
  styles += 'left: ' + bounding_box.x + 'px;';
  styles += '}';
 styles += '}';

 /* Add keyframe to CSS */
 $("#lightbox-animations").get(0).sheet.insertRule(styles, 0);

 /* Hide the window scrollbar */
 $("body").css('overflow', 'hidden');
});

/* Click on close button when full-screen */
$("#close").on('click', function(e) {
 $("#close").hide();
    $('#twitter').show();
   $('#googlebadge').show();
     $('#empty-container').remove();

 /* Window scrollbar normal */
 $("body").css('overflow', 'auto');

 /* Show animation */
$("#box1").replaceWith(divClone.clone());
  $("#box2").replaceWith(divClone1.clone());
  $("#box3").replaceWith(divClone2.clone());
  $("#box4").replaceWith(divClone3.clone());

 e.stopPropagation();
});

/* On animationend : from normal to full screen & full screen to normal */
$("#box1").on('animationend', function(e) {
 /* On animation end from normal to full-screen */
 if(e.originalEvent.animationName == 'inlightbox') {
  $("#close").show();
 }
 /* On animation end from full-screen to normal */
 else if(e.originalEvent.animationName == 'outlightbox') {
  /* Remove fixed positioning, remove animation rules */
  $("#box1").removeClass('in-animation').removeClass('out-animation');

  /* Remove the empty container that was earlier added */
  $("#empty-container").remove();

  /* Delete the dynamic keyframe rule that was earlier created */
  $("#lightbox-animations").get(0).sheet.deleteRule(0);
 }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#wrapper {
  position: absolute;
  top: 15%;
  left: 25%;
  width: 50%;
  height: 100%;
  z-index: 888;
}

.box {
  position: relative;
  background: #5C97FF;
  overflow: hidden;
  float: left;
  border: 0.1px solid white;
  box-shadow: 0px 0px 10px 1px white;
  margin: 2%;
  z-index: 777;
  opacity: 1;
}

.box:first-child {
  margin-left: 0;
}

.box:before {
  content: ' ';
  display: block;
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  z-index: 777;
  opacity: 0.6;
  background-image: url('http://wiki.dpconline.org/images/f/f3/Template_clipboard.png');
  background-repeat: no-repeat;
  background-position: 50% 50%;
  -ms-background-size: cover;
  -o-background-size: cover;
  -moz-background-size: cover;
  -webkit-background-size: cover;
  background-size: cover;
}

.box h2 {
  padding: 25px;
  text-align: center;
  z-index: 2;
  position: relative;
  color: #fff;
  top: 0;
  left: 0;
}

article {
  background: #fff;
  padding: 15px;
  top: 0;
  left: 0;
}</code>```

I am Template minus One!

This is a template, works pretty well, right?

              <button id="close">Close</button>

I am Template 0!

This is a template, works pretty well, right?

I am Template One!

This is a template, works pretty well, right?

I am Template Two!

This is a template, works pretty well, right?

```

EDIT:

It appears my javascript does not work in snippets. here is the link to my project : https://codepen.io/TechTime/pen/ZKdxQK

答:
What I had to do was use

```<code>$(document).on('click',"#box1" function() {
</code>```

instead of

```<code>$("#box1").on('click', function() {
</code>```

Body:
I have looked for a solution to this for ages, but have not been able to find an answer. I have some divs inside another div which all float left. I want it so when one is clicked it expands to fill the entire screen and then when a close button that appears in the top right is clicked it goes back to normal, without pushing any of the other divs around. I HAVE been able to achieve this but when i click the div again after the close button is pressed it wont re-expand. Help!

/* We need to create dynamic keyframes to show the animation from full-screen to normal. So we create a stylesheet in which we can insert CSS keyframe rules */

/* Click on the container */
$("#box1").on('click', function() {
  $("body").append('');
 /* The position of the container will be set to fixed, so set the top & left properties of the container */
 var bounding_box = $("#box1").get(0).getBoundingClientRect();
 $(this).css({ top: bounding_box.top + 'px', left: bounding_box.left + 'px' });
  $('#twitter').hide();
   $('#googlebadge').hide();

 /* Set container to fixed position. Add animation */
 $(this).addClass('in-animation');

 /* An empty container has to be added in place of the lightbox container so that the elements below don't come up
 Dimensions of this empty container is the same as the original container */
 $('

').insertAfter("#box1");

 /* To animate the container from full-screen to normal, we need dynamic keyframes */
 var styles = '';
 styles = '@keyframes outlightbox {';
  styles += '0% {';
  styles += 'height: 100%;';
  styles += 'width: 100%;';
  styles += 'top: 0px;';
  styles += 'left: 0px;';
  styles += '}';
  styles += '50% {';
  styles += 'height: 200px;';
  styles += 'top: ' + bounding_box.y + 'px;';
  styles += '}';
  styles += '100% {';
  styles += 'height: 200px;';
  styles += 'width: 500px;';
  styles += 'top: ' + bounding_box.y + 'px;';
  styles += 'left: ' + bounding_box.x + 'px;';
  styles += '}';
 styles += '}';

 /* Add keyframe to CSS */
 $("#lightbox-animations").get(0).sheet.insertRule(styles, 0);

 /* Hide the window scrollbar */
 $("body").css('overflow', 'hidden');
});

/* Click on close button when full-screen */
$("#close").on('click', function(e) {
 $("#close").hide();
    $('#twitter').show();
   $('#googlebadge').show();
     $('#empty-container').remove();

 /* Window scrollbar normal */
 $("body").css('overflow', 'auto');

 /* Show animation */
$("#box1").replaceWith(divClone.clone());
  $("#box2").replaceWith(divClone1.clone());
  $("#box3").replaceWith(divClone2.clone());
  $("#box4").replaceWith(divClone3.clone());

 e.stopPropagation();
});

/* On animationend : from normal to full screen & full screen to normal */
$("#box1").on('animationend', function(e) {
 /* On animation end from normal to full-screen */
 if(e.originalEvent.animationName == 'inlightbox') {
  $("#close").show();
 }
 /* On animation end from full-screen to normal */
 else if(e.originalEvent.animationName == 'outlightbox') {
  /* Remove fixed positioning, remove animation rules */
  $("#box1").removeClass('in-animation').removeClass('out-animation');

  /* Remove the empty container that was earlier added */
  $("#empty-container").remove();

  /* Delete the dynamic keyframe rule that was earlier created */
  $("#lightbox-animations").get(0).sheet.deleteRule(0);
 }
});

#wrapper {
  position: absolute;
  top: 15%;
  left: 25%;
  width: 50%;
  height: 100%;
  z-index: 888;
}

.box {
  position: relative;
  background: #5C97FF;
  overflow: hidden;
  float: left;
  border: 0.1px solid white;
  box-shadow: 0px 0px 10px 1px white;
  margin: 2%;
  z-index: 777;
  opacity: 1;
}

.box:first-child {
  margin-left: 0;
}

.box:before {
  content: ' ';
  display: block;
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  z-index: 777;
  opacity: 0.6;
  background-image: url('http://wiki.dpconline.org/images/f/f3/Template_clipboard.png');
  background-repeat: no-repeat;
  background-position: 50% 50%;
  -ms-background-size: cover;
  -o-background-size: cover;
  -moz-background-size: cover;
  -webkit-background-size: cover;
  background-size: cover;
}

.box h2 {
  padding: 25px;
  text-align: center;
  z-index: 2;
  position: relative;
  color: #fff;
  top: 0;
  left: 0;
}

article {
  background: #fff;
  padding: 15px;
  top: 0;
  left: 0;
}

I am Template minus One!

This is a template, works pretty well, right?

              <button id="close">Close</button>

I am Template 0!

This is a template, works pretty well, right?

I am Template One!

This is a template, works pretty well, right?

I am Template Two!

This is a template, works pretty well, right?

EDIT:

It appears my javascript does not work in snippets. here is the link to my project : https://codepen.io/TechTime/pen/ZKdxQK

Body:
What I had to do was use

$(document).on('click',"#box1" function() {

instead of

$("#box1").on('click', function() {


问:
Javascript variable not changing inside setInterval() function?
The variable counter does not change for some reason, it stays its initial value, of 50. It's a global variable, that is tried to be changed inside a function called by setInterval().

```<code>var mode = false;
var counter = 50;
var interval = null;
var increment = false;
var MAX = 50;
var MIN = 0;
var INTERVAL_MS = 3000;

setInterval(doInterval, INTERVAL_MS);

function doInterval() {
    if(increment)
    {
        counter += 1;
    }
    else
    {
        console.log("Decrement, " + counter);
        counter -= 1;
    }

    // Set direction
    if(counter = MIN)
    {
        increment = true;
    }
    else if(counter = MAX)
    {
        increment = false;
    }

    console.log("set to " + counter + " (D) Increment next time? " + increment);

    // dosomething with the values
}
</code>```

The output from this code

decrement, 50

set to 50 (D) Increment next time? false

decrement, 50

set to 50 (D) Increment next time? false

decrement, 50

set to 50 (D) Increment next time? false

And so on

Since it's 50 and increment is false, it should become 49, 48, however it seems that I can't change the variable's value. What could be a reason? The code is run inside a NodeJS app.

答:
these lines

```<code>if(counter = MIN)
</code>```

and

```<code>else if( counter = MAX )
</code>```

are setting counter to MIN or MAX. You want to === triple equals (== is fine in this case) to check for equality.

Body:
The variable counter does not change for some reason, it stays its initial value, of 50. It's a global variable, that is tried to be changed inside a function called by setInterval().

var mode = false;
var counter = 50;
var interval = null;
var increment = false;
var MAX = 50;
var MIN = 0;
var INTERVAL_MS = 3000;

setInterval(doInterval, INTERVAL_MS);

function doInterval() {
    if(increment)
    {
        counter += 1;
    }
    else
    {
        console.log("Decrement, " + counter);
        counter -= 1;
    }

    // Set direction
    if(counter = MIN)
    {
        increment = true;
    }
    else if(counter = MAX)
    {
        increment = false;
    }

    console.log("set to " + counter + " (D) Increment next time? " + increment);

    // dosomething with the values
}

The output from this code

decrement, 50

set to 50 (D) Increment next time? false

decrement, 50

set to 50 (D) Increment next time? false

decrement, 50

set to 50 (D) Increment next time? false

And so on

Since it's 50 and increment is false, it should become 49, 48, however it seems that I can't change the variable's value. What could be a reason? The code is run inside a NodeJS app.

Body:
these lines

if(counter = MIN)

and

else if( counter = MAX )

are setting counter to MIN or MAX. You want to === triple equals (== is fine in this case) to check for equality.