问:
What is the return type of resolve and reject function of a Promise?
I am trying to find the return type of resolve and reject function of a Promise I am creating with typescript, so that tslint does not complain based on the typedef rules.

Here is the code :

promises.ts

```<code>const promise: Promise<number> = new Promise((resolve, reject): void => {
    //the resolve / reject functions control the fate of the promise
    resolve(123);
});

//The promise fate can be subscribed to using .then (if resolved) or .catch (if rejected)
promise.then((res) => {
    console.log('I get called:', res === 123);      //I get called: true
});
</code>```

tslint.json

```<code>{
    "defaultSeverity": "error",
    "extends": [
        "tslint:recommended"
    ],
    "jsRules": {},
    "rules": {
        "eofline": false,
        "no-console": false,
        "no-consecutive-blank-lines": false,
        "comment-format": false,
        "no-trailing-whitespace": false,
        "quotemark": false,
        "typedef": [true, "call-signature", "arrow-call-signature", "parameter", "arrow-parameter", "property-declaration", "variable-declaration", "member-variable-declaration"],
        "typedef-whitespace": false,
        "whitespace": false
    },
    "rulesDirectory": []
}
</code>```

tsconfig.json

```<code>{
  "compilerOptions": {
    /* Basic Options */
    "target": "es5",                          /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', or 'ESNEXT'. */
    "module": "commonjs",                     /* Specify module code generation: 'commonjs', 'amd', 'system', 'umd' or 'es2015'. */
    // "lib": [],                             /* Specify library files to be included in the compilation:  */
    // "allowJs": true,                       /* Allow javascript files to be compiled. */
    // "checkJs": true,                       /* Report errors in .js files. */
    // "jsx": "preserve",                     /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
    // "declaration": true,                   /* Generates corresponding '.d.ts' file. */
    "sourceMap": true,                     /* Generates corresponding '.map' file. */
    // "outFile": "./",                       /* Concatenate and emit output to single file. */
     "outDir": "./build/",                        /* Redirect output structure to the directory. */
    // "rootDir": "./",                       /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
    // "removeComments": true,                /* Do not emit comments to output. */
    // "noEmit": true,                        /* Do not emit outputs. */
    // "importHelpers": true,                 /* Import emit helpers from 'tslib'. */
    // "downlevelIteration": true,            /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
    // "isolatedModules": true,               /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */

    /* Strict Type-Checking Options */
    "strict": true,                            /* Enable all strict type-checking options. */
    "noImplicitAny": true,                      /* Raise error on expressions and declarations with an implied 'any' type. */
    "strictNullChecks": true,              /* Enable strict null checks. */
    // "noImplicitThis": true,                /* Raise error on 'this' expressions with an implied 'any' type. */
    // "alwaysStrict": true,                  /* Parse in strict mode and emit "use strict" for each source file. */

    /* Additional Checks */
    // "noUnusedLocals": true,                /* Report errors on unused locals. */
    // "noUnusedParameters": true,            /* Report errors on unused parameters. */
    // "noImplicitReturns": true,             /* Report error when not all code paths in function return a value. */
    // "noFallthroughCasesInSwitch": true,    /* Report errors for fallthrough cases in switch statement. */

    /* Module Resolution Options */
    // "moduleResolution": "node",            /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
    // "baseUrl": "./",                       /* Base directory to resolve non-absolute module names. */
    // "paths": {},                           /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
    // "rootDirs": [],                        /* List of root folders whose combined content represents the structure of the project at runtime. */
    // "typeRoots": [],                       /* List of folders to include type definitions from. */
    // "types": [],                           /* Type declaration files to be included in compilation. */
    // "allowSyntheticDefaultImports": true,  /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */

    /* Source Map Options */
    // "sourceRoot": "./",                    /* Specify the location where debugger should locate TypeScript files instead of source locations. */
    // "mapRoot": "./",                       /* Specify the location where debugger should locate map files instead of generated locations. */
    // "inlineSourceMap": true,               /* Emit a single file with source maps instead of having a separate file. */
    // "inlineSources": true,                 /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */

    /* Experimental Options */
    // "experimentalDecorators": true,        /* Enables experimental support for ES7 decorators. */
    // "emitDecoratorMetadata": true,         /* Enables experimental support for emitting type metadata for decorators. */
    "lib": [
      "dom",
      "es5",
      "es2015.promise"
    ]
  }
}
</code>```

package.json

```<code>{
  "name": "TypescriptProject5",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "webpack-dev-server",
    "build": "webpack --watch",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "ts-loader": "^2.1.0",
    "tslint": "^5.4.2",
    "typescript": "^2.3.4",
    "webpack": "^2.6.1",
    "webpack-dev-server": "^2.4.5",
    "write-file-webpack-plugin": "^4.0.2"
  },
  "dependencies": {
    "es6-promise": "^4.1.0"
  }
}
</code>```

Right now tslint complains about resolve, reject and res (expected arrow parameter to have a typedef)

Update #2 : This code does not give me any tslint or TS errors

```<code>const promise: Promise<number> = new Promise((resolve: (value?: {} | PromiseLike<{}> | undefined) => void, reject: (reason?: any) => void): void => {
    //the resolve / reject functions control the fate of the promise
    resolve(123);
});

//The promise fate can be subscribed to using .then (if resolved) or .catch (if rejected)
promise.then((res: number) => {
    console.log('I get called:', res === 123);      //I get called: true
});
</code>```

答:
You can always check the definitions inside the lib.d.ts file, in this case the definition for the PromiseConstructorLike is:

```<code>declare type PromiseConstructorLike = new <T>(executor: (resolve: (value?: T | PromiseLike<T>) => void, reject: (reason?: any) => void) => void) => PromiseLike<T>;
</code>```

Which means that the type for resolve is:

```<code>(value?: T | PromiseLike<T>) => void
</code>```

And for reject:

```<code>(reason?: any) => void
</code>```

So both return void

Body:
I am trying to find the return type of resolve and reject function of a Promise I am creating with typescript, so that tslint does not complain based on the typedef rules.

Here is the code :

promises.ts

const promise: Promise<number> = new Promise((resolve, reject): void => {
    //the resolve / reject functions control the fate of the promise
    resolve(123);
});

//The promise fate can be subscribed to using .then (if resolved) or .catch (if rejected)
promise.then((res) => {
    console.log('I get called:', res === 123);      //I get called: true
});

tslint.json

{
    "defaultSeverity": "error",
    "extends": [
        "tslint:recommended"
    ],
    "jsRules": {},
    "rules": {
        "eofline": false,
        "no-console": false,
        "no-consecutive-blank-lines": false,
        "comment-format": false,
        "no-trailing-whitespace": false,
        "quotemark": false,
        "typedef": [true, "call-signature", "arrow-call-signature", "parameter", "arrow-parameter", "property-declaration", "variable-declaration", "member-variable-declaration"],
        "typedef-whitespace": false,
        "whitespace": false
    },
    "rulesDirectory": []
}

tsconfig.json

{
  "compilerOptions": {
    /* Basic Options */
    "target": "es5",                          /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', or 'ESNEXT'. */
    "module": "commonjs",                     /* Specify module code generation: 'commonjs', 'amd', 'system', 'umd' or 'es2015'. */
    // "lib": [],                             /* Specify library files to be included in the compilation:  */
    // "allowJs": true,                       /* Allow javascript files to be compiled. */
    // "checkJs": true,                       /* Report errors in .js files. */
    // "jsx": "preserve",                     /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
    // "declaration": true,                   /* Generates corresponding '.d.ts' file. */
    "sourceMap": true,                     /* Generates corresponding '.map' file. */
    // "outFile": "./",                       /* Concatenate and emit output to single file. */
     "outDir": "./build/",                        /* Redirect output structure to the directory. */
    // "rootDir": "./",                       /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
    // "removeComments": true,                /* Do not emit comments to output. */
    // "noEmit": true,                        /* Do not emit outputs. */
    // "importHelpers": true,                 /* Import emit helpers from 'tslib'. */
    // "downlevelIteration": true,            /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
    // "isolatedModules": true,               /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */

    /* Strict Type-Checking Options */
    "strict": true,                            /* Enable all strict type-checking options. */
    "noImplicitAny": true,                      /* Raise error on expressions and declarations with an implied 'any' type. */
    "strictNullChecks": true,              /* Enable strict null checks. */
    // "noImplicitThis": true,                /* Raise error on 'this' expressions with an implied 'any' type. */
    // "alwaysStrict": true,                  /* Parse in strict mode and emit "use strict" for each source file. */

    /* Additional Checks */
    // "noUnusedLocals": true,                /* Report errors on unused locals. */
    // "noUnusedParameters": true,            /* Report errors on unused parameters. */
    // "noImplicitReturns": true,             /* Report error when not all code paths in function return a value. */
    // "noFallthroughCasesInSwitch": true,    /* Report errors for fallthrough cases in switch statement. */

    /* Module Resolution Options */
    // "moduleResolution": "node",            /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
    // "baseUrl": "./",                       /* Base directory to resolve non-absolute module names. */
    // "paths": {},                           /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
    // "rootDirs": [],                        /* List of root folders whose combined content represents the structure of the project at runtime. */
    // "typeRoots": [],                       /* List of folders to include type definitions from. */
    // "types": [],                           /* Type declaration files to be included in compilation. */
    // "allowSyntheticDefaultImports": true,  /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */

    /* Source Map Options */
    // "sourceRoot": "./",                    /* Specify the location where debugger should locate TypeScript files instead of source locations. */
    // "mapRoot": "./",                       /* Specify the location where debugger should locate map files instead of generated locations. */
    // "inlineSourceMap": true,               /* Emit a single file with source maps instead of having a separate file. */
    // "inlineSources": true,                 /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */

    /* Experimental Options */
    // "experimentalDecorators": true,        /* Enables experimental support for ES7 decorators. */
    // "emitDecoratorMetadata": true,         /* Enables experimental support for emitting type metadata for decorators. */
    "lib": [
      "dom",
      "es5",
      "es2015.promise"
    ]
  }
}

package.json

{
  "name": "TypescriptProject5",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "webpack-dev-server",
    "build": "webpack --watch",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "ts-loader": "^2.1.0",
    "tslint": "^5.4.2",
    "typescript": "^2.3.4",
    "webpack": "^2.6.1",
    "webpack-dev-server": "^2.4.5",
    "write-file-webpack-plugin": "^4.0.2"
  },
  "dependencies": {
    "es6-promise": "^4.1.0"
  }
}

Right now tslint complains about resolve, reject and res (expected arrow parameter to have a typedef)

Update #2 : This code does not give me any tslint or TS errors

const promise: Promise<number> = new Promise((resolve: (value?: {} | PromiseLike<{}> | undefined) => void, reject: (reason?: any) => void): void => {
    //the resolve / reject functions control the fate of the promise
    resolve(123);
});

//The promise fate can be subscribed to using .then (if resolved) or .catch (if rejected)
promise.then((res: number) => {
    console.log('I get called:', res === 123);      //I get called: true
});

Body:
You can always check the definitions inside the lib.d.ts file, in this case the definition for the PromiseConstructorLike is:

declare type PromiseConstructorLike = new <T>(executor: (resolve: (value?: T | PromiseLike<T>) => void, reject: (reason?: any) => void) => void) => PromiseLike<T>;

Which means that the type for resolve is:

(value?: T | PromiseLike<T>) => void

And for reject:

(reason?: any) => void

So both return void


来源: stackexchange

问:
How to read a file to a list of lists?
I want to create a list of lists from a file that contains the following data:

```<code>101 Rahul
102 Julie
103 Helena
104 Kally
</code>```

CODE

```<code>lis = []

with open("student_details.txt" , "r+") as f:
    for i in range(1,3,1):
        for data in f.read().split():
            lis.append(data)
print(lis)
</code>```

Output I Want

```<code>[[101,Rahul] ,[102,Julie] ,[103,Helena] ,[104,Kally]]
</code>```

Output I m getting

```<code>['101', 'Rahul', '102', 'Julie', '103', 'Helena', '104', 'Kally']
</code>```

答:
You could try this alternative too. I'm using splitlines() method.</p>

```<code>data = []
f = open('student_details.txt', 'r')
for line in f.read().splitlines():
    data.append([line])
print(data)
</code>```

ContentLicense: CC BY-SA 4.0

Title: How to read a file to a list of lists?

Body:
I want to create a list of lists from a file that contains the following data:

101 Rahul
102 Julie
103 Helena
104 Kally

CODE

lis = []

with open("student_details.txt" , "r+") as f:
    for i in range(1,3,1):
        for data in f.read().split():
            lis.append(data)
print(lis)

Output I Want

[[101,Rahul] ,[102,Julie] ,[103,Helena] ,[104,Kally]]

Output I m getting

['101', 'Rahul', '102', 'Julie', '103', 'Helena', '104', 'Kally']

Body:
You could try this alternative too. I'm using splitlines() method.

data = []
f = open('student_details.txt', 'r')
for line in f.read().splitlines():
    data.append([line])
print(data)

ContentLicense: CC BY-SA 3.0


问:
How to invoke an npm script from a parent folder?
I created an express-based backend (in folder A) and a related react-based front-end project (in folder B) respectively. Now I put B inside A for the following benefits:

I don't need to copy files from font-end build to server project anymore because A/server.js can serve files from A/B/build directly.

No need to worry about the cross origin request errors.

They look like one project and are easier to manage in GitHub.
But can I run npm run buildjs from folder A, which actually runs npm run build in folder B? I guess it has much to do with the npm run-script usage.

答:
copy is not a problem, just make it be automatic. Introduce a deployment step is not bad.

there will not be any cross origin problem because you are serving front-end as static files. or at least the cross origin problem should do no matter with it

people first. split or not split projects, depends on developers


问:
Unity3D - 2D static fog of war for line of sight implementation
Unity beginner here!

So I'm trying to get some static-fog-of-war/line-of-sight  for my game.

Currently I have 2 cameras:

The first one renders the scene.

The second one has black background and a white polygon which represents the line of sight.

The 1st camera renders first, so far everything works.
(layers are set properly so that the second camera has only the line of sight polygon)

Then I wan't to do some post processing on the second camera by setting all white pixels of that camera to transparent but this is where I'm lost.

Using that code to apply the shader:

```<code>void OnRenderImage(RenderTexture src, RenderTexture dest)
{
    Graphics.Blit(src, dest, shader);
}
</code>```

The problem is that when I apply a shader on the second camera (tested with depthOnly flag on second camera), the shader also modify the renderTexture of the first camera. It looks like the cameras' render textures are combined before the shader applies.

What am I missing here?

答:
You should use a shader for this instead. OnRenderImage requires piping the data back to the CPU and processing it linearly there (slow!!!1) rather than in parallel on the GPU.

This will take a little bit of research to do properly, but the concept is pretty straight forward.  You need to use the stencil mask to get the desired effect.  The "white polygon" you have writes data (literally setting a bit to 1 instead of 0) to the stencil mask and then the rest of the scene gets rendered, but only where the stencil mask is a 1.

Basically think of the line of sight polygon as telling the camera where it's allowed to draw other things. Which is what a mask is.  The stencil mask is just a specific grouping of bits that are available during rendering that aren't data that gets drawn to the screen, but rather persist across rendering passes. So:

Pass 1: draw the LOS object to the mask buffer.
Pass 2: render the scene only where the buffer has been modified.

I wrote up an outline shader that uses the stencil mask, which you could use as an example and get started.  Mind, that shader was writen to apply only to a single object (and "creates" new geometry), but the same process should still work for doing what you're attempting (I just haven't tried to do it myself).

Looks like this thread has a (partial) shader that has the effect you're looking for.

I created two shaders of the standard affair and modified as follows: Hidden Shader: Just under the auto generated shader line "LOD 200", add:

```<code> Stencil {
 Ref 1
 Comp Equal
 }
</code>```

Portal Shader: Just under the auto generated "LOD 200", add:

```<code> ZWrite Off
 ColorMask 0

 Pass {
     Stencil {
         Ref 1
         Comp always
         Pass replace
     }
 }
</code>```

This is essentially the same concept I discussed above.

Alternatively...

Render the LOS to a separate camera as a black and white image to a render texture

Apply this render texture to a plane that sits above your scene

Apply a custom shader to this plane that converts black-white to black-transparent. A fragment shader that does this will be pretty easy to write.  You'd just have to modify the section that returns the color of the texture to return the value of the Red channel as the output Alpha value.

1I recently did an image effect that I couldn't figure out how to convert to a shader that I could pipe into the Blit function and the end result ran at 15 frames per second even at moderate resolutions (1024x768) and was crash-happy. Getting the compiled executable to run for longer than about 45 seconds was a gamble, so I wouldn't recommend following that path. It will seem OK in the editor, but then you'll get a surprise when you build it for distribution.

Body:
Unity beginner here!

So I'm trying to get some static-fog-of-war/line-of-sight  for my game.

Currently I have 2 cameras:

The first one renders the scene.

The second one has black background and a white polygon which represents the line of sight.

The 1st camera renders first, so far everything works.
(layers are set properly so that the second camera has only the line of sight polygon)

Then I wan't to do some post processing on the second camera by setting all white pixels of that camera to transparent but this is where I'm lost.

Using that code to apply the shader:

void OnRenderImage(RenderTexture src, RenderTexture dest)
{
    Graphics.Blit(src, dest, shader);
}

The problem is that when I apply a shader on the second camera (tested with depthOnly flag on second camera), the shader also modify the renderTexture of the first camera. It looks like the cameras' render textures are combined before the shader applies.

What am I missing here?

Body:
You should use a shader for this instead. OnRenderImage requires piping the data back to the CPU and processing it linearly there (slow!!!1) rather than in parallel on the GPU.

This will take a little bit of research to do properly, but the concept is pretty straight forward.  You need to use the stencil mask to get the desired effect.  The "white polygon" you have writes data (literally setting a bit to 1 instead of 0) to the stencil mask and then the rest of the scene gets rendered, but only where the stencil mask is a 1.

Basically think of the line of sight polygon as telling the camera where it's allowed to draw other things. Which is what a mask is.  The stencil mask is just a specific grouping of bits that are available during rendering that aren't data that gets drawn to the screen, but rather persist across rendering passes. So:

Pass 1: draw the LOS object to the mask buffer.
Pass 2: render the scene only where the buffer has been modified.

I wrote up an outline shader that uses the stencil mask, which you could use as an example and get started.  Mind, that shader was writen to apply only to a single object (and "creates" new geometry), but the same process should still work for doing what you're attempting (I just haven't tried to do it myself).

Looks like this thread has a (partial) shader that has the effect you're looking for.

I created two shaders of the standard affair and modified as follows: Hidden Shader: Just under the auto generated shader line "LOD 200", add:

 Stencil {
 Ref 1
 Comp Equal
 }

Portal Shader: Just under the auto generated "LOD 200", add:

 ZWrite Off
 ColorMask 0

 Pass {
     Stencil {
         Ref 1
         Comp always
         Pass replace
     }
 }

This is essentially the same concept I discussed above.

Alternatively...

Render the LOS to a separate camera as a black and white image to a render texture

Apply this render texture to a plane that sits above your scene

Apply a custom shader to this plane that converts black-white to black-transparent. A fragment shader that does this will be pretty easy to write.  You'd just have to modify the section that returns the color of the texture to return the value of the Red channel as the output Alpha value.

1I recently did an image effect that I couldn't figure out how to convert to a shader that I could pipe into the Blit function and the end result ran at 15 frames per second even at moderate resolutions (1024x768) and was crash-happy. Getting the compiled executable to run for longer than about 45 seconds was a gamble, so I wouldn't recommend following that path. It will seem OK in the editor, but then you'll get a surprise when you build it for distribution.


问:
Setting a variable equal to the data attribute of the current selected link
I need to set the variable current equal to the data attribute for the link which has been selected how can I do this. I know there are easier ways of doing what im trying to do but I need to do it this way.

I tried to create it but I can't do it.

$(".links").click(function(){
  var current = $(this).getAttribute("data-cat");
  $(current).addClass('hide');
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>ul{
  list-style-type: none;
}

ul li{
  display: inline-block;
}

ul li a{
  font-size: 20px;
  padding: 10px;
  background-color: yellow;
}

.change{
  background-color: red;
}

.hide{
  display: none;
}

.print{
  height: 100px;
  width: 100px;
  background-color: blue;
}</code>```

link1

link2

link3

```

答:
It's better to use .data() when you deal with data-* attributes :

```<code>var current = $(this).data("cat");
</code>```

NOTE : You're missing dot . in your selector :

```<code>$('.'+current).addClass('hide');
___^
</code>```

Hope this helps.

$(".links").click(function(){
  var current = $(this).data("cat");
  $('.'+current).addClass('hide');
  console.log(current);
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>ul{
  list-style-type: none;
}

ul li{
  display: inline-block;
}

ul li a{
  font-size: 20px;
  padding: 10px;
  background-color: yellow;
}

.change{
  background-color: red;
}

.hide{
  display: none;
}

.print{
  height: 100px;
  width: 100px;
  background-color: blue;
}</code>```

link1

link2

link3

```

Body:
I need to set the variable current equal to the data attribute for the link which has been selected how can I do this. I know there are easier ways of doing what im trying to do but I need to do it this way.

I tried to create it but I can't do it.

$(".links").click(function(){
  var current = $(this).getAttribute("data-cat");
  $(current).addClass('hide');
});

ul{
  list-style-type: none;
}

ul li{
  display: inline-block;
}

ul li a{
  font-size: 20px;
  padding: 10px;
  background-color: yellow;
}

.change{
  background-color: red;
}

.hide{
  display: none;
}

.print{
  height: 100px;
  width: 100px;
  background-color: blue;
}

link1

link2

link3

Body:
It's better to use .data() when you deal with data-* attributes :

var current = $(this).data("cat");

NOTE : You're missing dot . in your selector :

$('.'+current).addClass('hide');
___^

Hope this helps.

$(".links").click(function(){
  var current = $(this).data("cat");
  $('.'+current).addClass('hide');
  console.log(current);
});

ul{
  list-style-type: none;
}

ul li{
  display: inline-block;
}

ul li a{
  font-size: 20px;
  padding: 10px;
  background-color: yellow;
}

.change{
  background-color: red;
}

.hide{
  display: none;
}

.print{
  height: 100px;
  width: 100px;
  background-color: blue;
}

<ul>
  <li><a id="hi" class="links" data-cat="print" href="#">link1</a></li>
  <li><a class="links" data-cat="porfolio" href="#">link2</a></li>
  <li><a class="links" data-cat="print" href="#">link3</a></li>
</ul>

<div class="print">

</div>

<div class="porfolio">

</div>

<div class="print">

</div>

<script
  src="https://code.jquery.com/jquery-3.2.1.js"
  integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE="
  crossorigin="anonymous"></script>


问:
Two names for a C# static class
It's extremely lazy, but I'm wondering if it's possible to have two names point to the same static class in essence.

I have a long and descriptive static class name BusinessLogicServiceUtility (as example) and it's looking rather long-winded in code.

I'd love to use BLSU as an alternative, so I tried extending the long class with my short class name:

```<code>public static class BLSU : BusinessLogicServiceUtility
{
}
</code>```

Which probably looks noob but as it turns out, it doesn't work.

It looks as though I could wrap each method in the long class with a method inside the short class, but there's a lot of methods, which makes maintaining it a pain and circumvents the whole laziness goal.

Is there a way of assigning two names to one static class, or some other method simply "extending" a static class?

答:
In addition, you can use using static that will allow you to use the methods without prefixing them with the class at all:

at the top of the file :

```<code>using static BusinessLogicServiceUtility;
</code>```

and say you have a method public static DoLogicThings() in your static class, you can access it directly now:

```<code>public void SomeMethod()
{
     DoLogicThings();
}
</code>```

this was added in C#6.

Title: Two names for a C# static class

Body:
It's extremely lazy, but I'm wondering if it's possible to have two names point to the same static class in essence.

I have a long and descriptive static class name BusinessLogicServiceUtility (as example) and it's looking rather long-winded in code.

I'd love to use BLSU as an alternative, so I tried extending the long class with my short class name:

public static class BLSU : BusinessLogicServiceUtility
{
}

Which probably looks noob but as it turns out, it doesn't work.

It looks as though I could wrap each method in the long class with a method inside the short class, but there's a lot of methods, which makes maintaining it a pain and circumvents the whole laziness goal.

Is there a way of assigning two names to one static class, or some other method simply "extending" a static class?

Body:
In addition, you can use using static that will allow you to use the methods without prefixing them with the class at all:

at the top of the file :

using static BusinessLogicServiceUtility;

and say you have a method public static DoLogicThings() in your static class, you can access it directly now:

public void SomeMethod()
{
     DoLogicThings();
}

this was added in C#6.


问:
Linq distinct not working correctly
I'm having a strange problem with a linq query. I'm using LINQPad 4 to make some a query that uses regular expression using LinqToSQL as the LinqPad driver.

Here's the query that I'm trying to make :

```<code>(from match in
from s in SystemErrors
select Regex.Match(s.Description, "...")
select new
{
  FamilyCode = match.Groups["FamilyCode"].Value,
  ProductPrefix = match.Groups["ProductPrefix"].Value,
  BillingGroup = match.Groups["BillingGroup"].Value,
  Debtor = match.Groups["Debtor"].Value
}).Distinct()
</code>```

As you can see I'm trying to extract data from a text description in a log table using groups. The query works, but the Distinct doesn't want to work, it returns a line for all Match.

I have read that distinct should work with anonymous type, matching each property. Even more strange is that distinct does actually do something, it orders the values alphabetically by the FamilyCode (and then by ProductPrefix, etc.).

Has someone an idea on why this isn't working?
Thanks

Here is what is displayed in the SQL tab of LinqPad :

```<code>DECLARE @p0 NVarChar(1000) = 'Big Regexp'
DECLARE @p1 NVarChar(1000) = 'FamilyCode'
DECLARE @p2 NVarChar(1000) = 'ProductPrefix'
DECLARE @p3 NVarChar(1000) = 'BillingGroup'
DECLARE @p4 NVarChar(1000) = 'Debtor'

SELECT DISTINCT [t2].[Description] AS [input], [t2].[value], [t2].[value2], [t2].[value3], [t2].[value4], [t2].[value5]
FROM (
    SELECT [t1].[Description], [t1].[value], @p1 AS [value2], @p2 AS [value3], @p3 AS [value4], @p4 AS [value5]
    FROM (
        SELECT [t0].[Description], @p0 AS [value]
        FROM [SystemError] AS [t0]
        ) AS [t1]
    ) AS [t2]
</code>```

答:
```<code>var result = from eachError in SystemErrors
             let match = Regex.Match(eachError.Description, "...")
             group eachError by new
             {
              FamilyCode = match.Groups["FamilyCode"].Value,
              ProductPrefix = match.Groups["ProductPrefix"].Value,
              BillingGroup = match.Groups["BillingGroup"].Value,
              Debtor = match.Groups["Debtor"].Value
             }
             into unique
             select unique.key;
</code>```

When you use Distinct(), it's distinct by pointer to each object, not value because select new {} is object type not value type. Try using group by instead.

ContentLicense: CC BY-SA 2.5

Title: Linq distinct not working correctly

Body:
I'm having a strange problem with a linq query. I'm using LINQPad 4 to make some a query that uses regular expression using LinqToSQL as the LinqPad driver.

Here's the query that I'm trying to make :

(from match in
from s in SystemErrors
select Regex.Match(s.Description, "...")
select new
{
  FamilyCode = match.Groups["FamilyCode"].Value,
  ProductPrefix = match.Groups["ProductPrefix"].Value,
  BillingGroup = match.Groups["BillingGroup"].Value,
  Debtor = match.Groups["Debtor"].Value
}).Distinct()

As you can see I'm trying to extract data from a text description in a log table using groups. The query works, but the Distinct doesn't want to work, it returns a line for all Match.

I have read that distinct should work with anonymous type, matching each property. Even more strange is that distinct does actually do something, it orders the values alphabetically by the FamilyCode (and then by ProductPrefix, etc.).

Has someone an idea on why this isn't working?
Thanks

Here is what is displayed in the SQL tab of LinqPad :

DECLARE @p0 NVarChar(1000) = 'Big Regexp'
DECLARE @p1 NVarChar(1000) = 'FamilyCode'
DECLARE @p2 NVarChar(1000) = 'ProductPrefix'
DECLARE @p3 NVarChar(1000) = 'BillingGroup'
DECLARE @p4 NVarChar(1000) = 'Debtor'

SELECT DISTINCT [t2].[Description] AS [input], [t2].[value], [t2].[value2], [t2].[value3], [t2].[value4], [t2].[value5]
FROM (
    SELECT [t1].[Description], [t1].[value], @p1 AS [value2], @p2 AS [value3], @p3 AS [value4], @p4 AS [value5]
    FROM (
        SELECT [t0].[Description], @p0 AS [value]
        FROM [SystemError] AS [t0]
        ) AS [t1]
    ) AS [t2]

Body:
var result = from eachError in SystemErrors
             let match = Regex.Match(eachError.Description, "...")
             group eachError by new
             {
              FamilyCode = match.Groups["FamilyCode"].Value,
              ProductPrefix = match.Groups["ProductPrefix"].Value,
              BillingGroup = match.Groups["BillingGroup"].Value,
              Debtor = match.Groups["Debtor"].Value
             }
             into unique
             select unique.key;

When you use Distinct(), it's distinct by pointer to each object, not value because select new {} is object type not value type. Try using group by instead.


问:
UITableView - scroll to the top
In my table view I have to scroll to the top. But I cannot guarantee that the first object is going to be section 0, row 0. May be that my table view will start from section number 5.

So I get an exception, when I call:

```<code>[mainTableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:NO];
</code>```

Is there another way to scroll to the top of table view?

答:
To have a completion when finished, add this extension</p>

```<code>// MARK: - UIScrollView

extension UIScrollView {

    /// Animate scroll to top with completion
    ///
    /// - Parameters:
    ///   - duration:   TimeInterval
    ///   - completion: Completion block
    func animateScrollToTop(withDuration duration:  TimeInterval,
                            completion:             @escaping (()->())) {

        UIView.animate(withDuration: duration, animations: { [weak self] in
                self?.setContentOffset(CGPoint.zero, animated: false)
            }, completion: { finish in
                guard finish else {
                    return
                }
                completion()
        })
    }
}

tableView.animateScrollToTop(withDuration: 0.25) {
    // Finish
}
</code>```

Title: UITableView - scroll to the top

Body:
In my table view I have to scroll to the top. But I cannot guarantee that the first object is going to be section 0, row 0. May be that my table view will start from section number 5.

So I get an exception, when I call:

[mainTableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:NO];

Is there another way to scroll to the top of table view?

Body:
To have a completion when finished, add this extension

// MARK: - UIScrollView

extension UIScrollView {

    /// Animate scroll to top with completion
    ///
    /// - Parameters:
    ///   - duration:   TimeInterval
    ///   - completion: Completion block
    func animateScrollToTop(withDuration duration:  TimeInterval,
                            completion:             @escaping (()->())) {

        UIView.animate(withDuration: duration, animations: { [weak self] in
                self?.setContentOffset(CGPoint.zero, animated: false)
            }, completion: { finish in
                guard finish else {
                    return
                }
                completion()
        })
    }
}

tableView.animateScrollToTop(withDuration: 0.25) {
    // Finish
}


问:
How do I make my player with a Rigidbody move with isKinematic checked?
My game is a topdown zombie shooter and whenever the zombies get to the player they bunch up underneath them, to the point where the player can just walk over the zombies. I noticed that when I check isKinematic on the Rigidbody the zombies cant push the player up to go underneath him, so they just run into him(which is what I want). Despite this I am then unable to move. How can i fix this?</p>

```<code>    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;

    public class PlayerMoving1 : MonoBehaviour {
    public float moveSpeed;
    private Rigidbody myRigidbody;
    private Vector3 moveInput;
    private Vector3 moveVelocity;
    private Camera mainCamera;
    public GunController theGun;
      void Start () {
         myRigidbody = GetComponent <Rigidbody>();
        mainCamera = FindObjectOfType<Camera>();
     }

// Update is called once per frame
void Update () {
    moveInput = new Vector3(Input.GetAxisRaw("Horizontal"), 0f, Input.GetAxisRaw("Vertical"));
    moveVelocity = moveInput * moveSpeed;
    Ray cameraRay = mainCamera.ScreenPointToRay(Input.mousePosition);
    Plane groundPlane = new Plane(Vector3.up, Vector3.zero);
    float rayLength;
    if(groundPlane.Raycast(cameraRay,out rayLength))
    {
        Vector3 pointToLook = cameraRay.GetPoint(rayLength);
        transform.LookAt(new Vector3(pointToLook.x,transform.position.y,pointToLook.z));
    }
    if (Input.GetMouseButtonDown(0))
        theGun.isFiring = true;
    if (Input.GetMouseButtonUp(0))
        theGun.isFiring = false;
}
void FixedUpdate(){
    myRigidbody.velocity = moveVelocity;
}
}
</code>```

答:
Another way of doing this is to lock the position of Y for the player (assuming Y is the positive "up" direction). isKinimatic is best when you want to move the player or objects around yourself.

I would say upping the mass is better in this case, and you can keep isKinematic unchecked in this case then too. Also apply the lock for Y movement (again if it is the "up" direction from the plane)

Let me know what your solution is regardless, I've had some issues in the past as well with these types of events happening

Body:
My game is a topdown zombie shooter and whenever the zombies get to the player they bunch up underneath them, to the point where the player can just walk over the zombies. I noticed that when I check isKinematic on the Rigidbody the zombies cant push the player up to go underneath him, so they just run into him(which is what I want). Despite this I am then unable to move. How can i fix this?

    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;

    public class PlayerMoving1 : MonoBehaviour {
    public float moveSpeed;
    private Rigidbody myRigidbody;
    private Vector3 moveInput;
    private Vector3 moveVelocity;
    private Camera mainCamera;
    public GunController theGun;
      void Start () {
         myRigidbody = GetComponent <Rigidbody>();
        mainCamera = FindObjectOfType<Camera>();
     }

// Update is called once per frame
void Update () {
    moveInput = new Vector3(Input.GetAxisRaw("Horizontal"), 0f, Input.GetAxisRaw("Vertical"));
    moveVelocity = moveInput * moveSpeed;
    Ray cameraRay = mainCamera.ScreenPointToRay(Input.mousePosition);
    Plane groundPlane = new Plane(Vector3.up, Vector3.zero);
    float rayLength;
    if(groundPlane.Raycast(cameraRay,out rayLength))
    {
        Vector3 pointToLook = cameraRay.GetPoint(rayLength);
        transform.LookAt(new Vector3(pointToLook.x,transform.position.y,pointToLook.z));
    }
    if (Input.GetMouseButtonDown(0))
        theGun.isFiring = true;
    if (Input.GetMouseButtonUp(0))
        theGun.isFiring = false;
}
void FixedUpdate(){
    myRigidbody.velocity = moveVelocity;
}
}


问:
pandas groupby weighted cumulative sum
```<code>A   | B    | B_new
----| ---- |---------
1   | 1    |  1
1   | 2    |  1.5
1   | 3    |  2.25
2   | 2    |  2
2   | 4    |  3
2   | 6    |  4.5
</code>```

<p>I have a dataframe, and I want to calculate weighted cumulative sum of B group by A. But I don't know how to apply the transformation. </p>

```<code>$$new = C*cur+(1-C)*old$$
</code>```

答:
You want to apply exponentially weighted moving average within a groupby

```<code>df.assign(
    B_new=df.groupby('A').B.apply(
        lambda x: x.ewm(alpha=0.5, adjust=False).mean()
    )
)

   A  B  B_new
0  1  1   1.00
1  1  2   1.50
2  1  3   2.25
3  2  2   2.00
4  2  4   3.00
5  2  6   4.50
</code>```

Title: pandas groupby weighted cumulative sum

Body:
A   | B    | B_new
----| ---- |---------
1   | 1    |  1
1   | 2    |  1.5
1   | 3    |  2.25
2   | 2    |  2
2   | 4    |  3
2   | 6    |  4.5

I have a dataframe, and I want to calculate weighted cumulative sum of B group by A. But I don't know how to apply the transformation.

$$new = C*cur+(1-C)*old$$

Body:
You want to apply exponentially weighted moving average within a groupby

df.assign(
    B_new=df.groupby('A').B.apply(
        lambda x: x.ewm(alpha=0.5, adjust=False).mean()
    )
)

   A  B  B_new
0  1  1   1.00
1  1  2   1.50
2  1  3   2.25
3  2  2   2.00
4  2  4   3.00
5  2  6   4.50


问:
RequestMapping placeholders don't work in JUnit tests
I have a simple Spring MVC controller whose RequestMapping is a property. It's a jar that include a controller. Downstream apps will take this jar and use the common endpoint, only the precise URL can vary by app)

Everything works fine when I include my jar into another app. The app has a property or yaml file and the property is set. I've verified that the endpoint works fine.

However, being the good developer that I am, I want to make an integration test that verifies that the URL determined by the property is exposed properly. I can get an @Value in the controller injected properly, but a ${} expression in the @RequestMapping will not be substituted from a properties file. I found a couple threads (Spring Boot REST Controller Test with RequestMapping of Properties Value and @RequestMapping with placeholder not working) But either they don't apply or I tried what they said and I couldn't get it to work.

The test that hits the static (iWork) endpoint works, but the one that is pulled from the property (iDontWork) doesn't work.

(This is Spring 4.2.6)

Controller

```<code>@RestController
@RequestMapping(value = {"/${appName}", "/iWork"})
public class Controller {

    @Value("${appName}")
    private String appName;

    @RequestMapping(method= RequestMethod.GET)
    public String handlerMethod (HttpServletRequest request) throws Exception {
        // Proves the placeholder is injected in the class, but
        // Not in the RequestMapping
        assert appName != null;
        assert !appName.equals("${appName}");
        return "";
    }
}
</code>```

ControllerTest

```<code>@WebAppConfiguration
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(loader = AnnotationConfigWebContextLoader.class,
    classes = { ControllerTest.Config.class })
public class ControllerTest {

    @Autowired
    private WebApplicationContext context;

    private MockMvc mvc;

    @Before
    public void setup() {
        mvc = MockMvcBuilders
            .webAppContextSetup(context)
            .build();
    }

    @Configuration
    @ComponentScan(basePackages = {"test"})
    static class Config {
        // because @PropertySource doesnt work in annotation only land
        @Bean
        PropertyPlaceholderConfigurer propConfig() {
            PropertyPlaceholderConfigurer ppc = new PropertyPlaceholderConfigurer();
            ppc.setLocation(new ClassPathResource("test.properties"));
            return ppc;
        }
    }

    @Test
    public void testStaticEndpoint() throws Exception {
        mvc.perform(get("/iWork")).andExpect(status().isOk());
    }

    @Test
    public void testDynamicEndpoint() throws Exception {
        mvc.perform(get("/iDontWork")).andExpect(status().isOk());
    }
}
</code>```

test.properties

```<code>appName = iDontWork
</code>```

答:
You need to add placeholder value while creating mockMvc as shown below.

```<code>@Before
public void setup() {
    MockitoAnnotations.initMocks(this);
    mockMvc = MockMvcBuilders.standaloneSetup(accountController)
                .addPlaceholderValue("propertyName", "propertyValue")
                .build();
}
</code>```

Body:
I have a simple Spring MVC controller whose RequestMapping is a property. It's a jar that include a controller. Downstream apps will take this jar and use the common endpoint, only the precise URL can vary by app)

Everything works fine when I include my jar into another app. The app has a property or yaml file and the property is set. I've verified that the endpoint works fine.

However, being the good developer that I am, I want to make an integration test that verifies that the URL determined by the property is exposed properly. I can get an @Value in the controller injected properly, but a ${} expression in the @RequestMapping will not be substituted from a properties file. I found a couple threads (Spring Boot REST Controller Test with RequestMapping of Properties Value and @RequestMapping with placeholder not working) But either they don't apply or I tried what they said and I couldn't get it to work.

The test that hits the static (iWork) endpoint works, but the one that is pulled from the property (iDontWork) doesn't work.

(This is Spring 4.2.6)

Controller

@RestController
@RequestMapping(value = {"/${appName}", "/iWork"})
public class Controller {

    @Value("${appName}")
    private String appName;

    @RequestMapping(method= RequestMethod.GET)
    public String handlerMethod (HttpServletRequest request) throws Exception {
        // Proves the placeholder is injected in the class, but
        // Not in the RequestMapping
        assert appName != null;
        assert !appName.equals("${appName}");
        return "";
    }
}

ControllerTest

@WebAppConfiguration
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(loader = AnnotationConfigWebContextLoader.class,
    classes = { ControllerTest.Config.class })
public class ControllerTest {

    @Autowired
    private WebApplicationContext context;

    private MockMvc mvc;

    @Before
    public void setup() {
        mvc = MockMvcBuilders
            .webAppContextSetup(context)
            .build();
    }

    @Configuration
    @ComponentScan(basePackages = {"test"})
    static class Config {
        // because @PropertySource doesnt work in annotation only land
        @Bean
        PropertyPlaceholderConfigurer propConfig() {
            PropertyPlaceholderConfigurer ppc = new PropertyPlaceholderConfigurer();
            ppc.setLocation(new ClassPathResource("test.properties"));
            return ppc;
        }
    }

    @Test
    public void testStaticEndpoint() throws Exception {
        mvc.perform(get("/iWork")).andExpect(status().isOk());
    }

    @Test
    public void testDynamicEndpoint() throws Exception {
        mvc.perform(get("/iDontWork")).andExpect(status().isOk());
    }
}

test.properties

appName = iDontWork

Body:
You need to add placeholder value while creating mockMvc as shown below.

@Before
public void setup() {
    MockitoAnnotations.initMocks(this);
    mockMvc = MockMvcBuilders.standaloneSetup(accountController)
                .addPlaceholderValue("propertyName", "propertyValue")
                .build();
}


问:
Redux form: REGISTER_FIELD / UNREGISTER_FIELD get called after change or focus events
I’m using Redux Form to render and handle form events in my React app. The following things are used:

Initial values

Field arrays

Immutable.js

Material UI

Also, the field arrays are build using the initial values.

```<code>export default connect(
  state => {
    return {
      buttonVisible,
      confirm,
      initialValues: Immutable.Map({
        configuration_items: configuration_items,
      })
    }
  }
)(AssetConfiguration)
</code>```

The problem is that all the fields in the form get deregistered and registered on every change or focus event. Without the defaultValues, it seems to work fine though.

I’m using a React component to render the form, something like this

```<code>class ConfigurationForm extends React.Component {
  renderTableBody({ fields, meta: { touched, error } }) {
    return(
      <tbody>
        {fields.map((field, index) => {
          return(
            <tr key={index}>
              <td>
                <Field fieldIndex={index} name={`${field}.value`} id={`${field}.value`} component={this.renderItemField.bind(this)} />
              </td>
            </tr>
          )
        })}
      </tbody>
    )
  }

 render() {
    return (
      <form className="defaultForm" onSubmit={handleSubmit(postAssetConfiguration)}>
        <FieldArray name="configuration_items" component={this.renderTableBody.bind(this)} />
      </form>
    )
  }
}
</code>```

What could be the problem here?

Thanks,
Rens

答:
I'm investigating a similar issue.
My guess is: you are passing in this.renderTableBody.bind(this) and this.renderItemField.bind(this) as components. Every time render is called, these will be new references, triggering an unnecessary rerender. This is considered bad practice: https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-no-bind.md

Body:
I’m using Redux Form to render and handle form events in my React app. The following things are used:

Initial values

Field arrays

Immutable.js

Material UI

Also, the field arrays are build using the initial values.

export default connect(
  state => {
    return {
      buttonVisible,
      confirm,
      initialValues: Immutable.Map({
        configuration_items: configuration_items,
      })
    }
  }
)(AssetConfiguration)

The problem is that all the fields in the form get deregistered and registered on every change or focus event. Without the defaultValues, it seems to work fine though.

I’m using a React component to render the form, something like this

class ConfigurationForm extends React.Component {
  renderTableBody({ fields, meta: { touched, error } }) {
    return(

        {fields.map((field, index) => {
          return(

                <Field fieldIndex={index} name={`${field}.value`} id={`${field}.value`} component={this.renderItemField.bind(this)} />

          )
        })}

    )
  }

 render() {
    return (
      <form className="defaultForm" onSubmit={handleSubmit(postAssetConfiguration)}>
        <FieldArray name="configuration_items" component={this.renderTableBody.bind(this)} />
      </form>
    )
  }
}

What could be the problem here?

Thanks,
Rens


问:
Is it good to duplicate the opencart module?
Well I want to make a custom page in opencart admin panel to insert and delete some data from opencart database

For example :

Set an image slider on opencart home page and fetching images from database & for insertion of images, I want to create a custom page in opencart admin panel ??

So how can it be possible ??

答:
Yes, it is pretty safe and sound to duplicate a module in opencart and it is a bit logical with any of the cms as no one is going to create a module from scratch for a very little functionality like inserting some values to database.

As depicts you just want to insert some images links, so you can proceed with replicating the catalog / information functionality in opencart admin panel.

You just need to create a new table in database to store new modules data and fetching new module data in front end.


问:
Qt: how to pass input values from on_pushButton_clicked() function to paintGL()
I am working on a mortgage calculator with QT.
When the user clicks the push button, the "on_pushButton_clicked()" function will get the inputs.

The Question is I am confused about how to pass the inputs from "on_pushButton_clicked()" to "paintGL()" function for drawing purpose.

My last resort is using global variables to solve this issue, but I really want to avoid something like that...so it will be more than welcome if someone can enlighten with better approaches.

My code are as followed:

mainwindow.h

```<code>#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include "ui_mainwindow.h"

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT
public:

    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();
    template <class T>
    T inputcheck(QLineEdit *input, T output);
    //friend class GLwidget;
    double loan;
    int maturity;
    double rate1;
    double rate2;
    double rate3;
    int period2;
    int period3;

private slots:
    void on_pushButton_Calculate_clicked();

    void on_pushButton_Quit_clicked();

private:
    Ui::MainWindow *ui;
};

#endif // MAINWINDOW_H
</code>```

mainwindow.cpp

```<code>#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QCoreApplication>
#include <QDesktopWidget>
#include "glwidget.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
}

MainWindow::~MainWindow()
{
    delete ui;
}

template <class T>
T MainWindow::inputcheck(QLineEdit *input, T output)
{
    bool ok;
    output = input->text().toDouble(&ok);
    if(TRUE && output > 0)
    {
        return output;
    }
    else
    {
        input->setText("ERR");
        return 0;
    }
}

void MainWindow::on_pushButton_Calculate_clicked()
{

    // getting inputs()
    loan = inputcheck(ui->lineEdit_loan, loan);
    maturity = inputcheck(ui->lineEdit_maturity, maturity);
    rate1 = inputcheck(ui->lineEdit_rate1, rate1);
    rate2 = inputcheck(ui->lineEdit_rate2, rate2);
    rate3 = inputcheck(ui->lineEdit_rate3, rate3);
    period2 = inputcheck(ui->lineEdit_period2, period2);
    period3 = inputcheck(ui->lineEdit_period3, period3);
    printf("loan:%f, maturity:%d,rate1:%f,rate2:%f,rate3:%f, period2:%d, period3:%d\n", loan, maturity, rate1, rate2, rate3, period2, period3);

}

void MainWindow::on_pushButton_Quit_clicked()
{
    QCoreApplication::quit();

}
</code>```

glwidget.h

```<code>#ifndef GLWIDGET_H
#define GLWIDGET_H

#include <QObject>
#include <QGLWidget>

class calculation;
class GLwidget : public QGLWidget
{
    Q_OBJECT
public:
    explicit GLwidget(QWidget *parent = 0);
    void initializeGL();
    void paintGL();
    void resizeGL(int width, int height);

private:

};

#endif // GLWIDGET_H
</code>```

glwidget.cpp

```<code>#include "glwidget.h"
#include <gl/GL.h>

GLwidget::GLwidget(QWidget *parent):QGLWidget(parent)
{
}

void GLwidget::initializeGL()
{
}

void GLwidget::paintGL()
{
**// I need the inputs to be here!!**
}

void GLwidget::resizeGL(int width, int height)
{
}
</code>```

Thanks for your help:)

答:
Move the variables in your GLwidget class. Here I assumed they are declared public, but you might want to use setters and getters. Then, call update to refresh the widget.

```<code>void MainWindow::on_pushButton_Calculate_clicked()
{
    ui->myglwidgetname->loan = inputcheck<double>(ui->lineEdit_loan);
    ui->myglwidgetname->maturity = inputcheck<int>(ui->lineEdit_maturity);
    ui->myglwidgetname->rate1 = inputcheck<double>(ui->lineEdit_rate1);
    ui->myglwidgetname->rate2 = inputcheck<double>(ui->lineEdit_rate2);
    ui->myglwidgetname->rate3 = inputcheck<double>(ui->lineEdit_rate3);
    ui->myglwidgetname->period2 = inputcheck<int>(ui->lineEdit_period2);
    ui->myglwidgetname->period3 = inputcheck<int>(ui->lineEdit_period3);
    ui->myglwidgetname->update();
}
</code>```

Additionaly, you want to correct your templated function because it is calling toDouble regardless of the type T which doesn't make sense at all...

Body:
I am working on a mortgage calculator with QT.
When the user clicks the push button, the "on_pushButton_clicked()" function will get the inputs.

The Question is I am confused about how to pass the inputs from "on_pushButton_clicked()" to "paintGL()" function for drawing purpose.

My last resort is using global variables to solve this issue, but I really want to avoid something like that...so it will be more than welcome if someone can enlighten with better approaches.

My code are as followed:

mainwindow.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include "ui_mainwindow.h"

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT
public:

    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();
    template <class T>
    T inputcheck(QLineEdit *input, T output);
    //friend class GLwidget;
    double loan;
    int maturity;
    double rate1;
    double rate2;
    double rate3;
    int period2;
    int period3;

private slots:
    void on_pushButton_Calculate_clicked();

    void on_pushButton_Quit_clicked();

private:
    Ui::MainWindow *ui;
};

#endif // MAINWINDOW_H

mainwindow.cpp

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QCoreApplication>
#include <QDesktopWidget>
#include "glwidget.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
}

MainWindow::~MainWindow()
{
    delete ui;
}

template <class T>
T MainWindow::inputcheck(QLineEdit *input, T output)
{
    bool ok;
    output = input->text().toDouble(&ok);
    if(TRUE && output > 0)
    {
        return output;
    }
    else
    {
        input->setText("ERR");
        return 0;
    }
}

void MainWindow::on_pushButton_Calculate_clicked()
{

    // getting inputs()
    loan = inputcheck(ui->lineEdit_loan, loan);
    maturity = inputcheck(ui->lineEdit_maturity, maturity);
    rate1 = inputcheck(ui->lineEdit_rate1, rate1);
    rate2 = inputcheck(ui->lineEdit_rate2, rate2);
    rate3 = inputcheck(ui->lineEdit_rate3, rate3);
    period2 = inputcheck(ui->lineEdit_period2, period2);
    period3 = inputcheck(ui->lineEdit_period3, period3);
    printf("loan:%f, maturity:%d,rate1:%f,rate2:%f,rate3:%f, period2:%d, period3:%d\n", loan, maturity, rate1, rate2, rate3, period2, period3);

}

void MainWindow::on_pushButton_Quit_clicked()
{
    QCoreApplication::quit();

}

glwidget.h

#ifndef GLWIDGET_H
#define GLWIDGET_H

#include <QObject>
#include <QGLWidget>

class calculation;
class GLwidget : public QGLWidget
{
    Q_OBJECT
public:
    explicit GLwidget(QWidget *parent = 0);
    void initializeGL();
    void paintGL();
    void resizeGL(int width, int height);

private:

};

#endif // GLWIDGET_H

glwidget.cpp

#include "glwidget.h"
#include <gl/GL.h>

GLwidget::GLwidget(QWidget *parent):QGLWidget(parent)
{
}

void GLwidget::initializeGL()
{
}

void GLwidget::paintGL()
{
**// I need the inputs to be here!!**
}

void GLwidget::resizeGL(int width, int height)
{
}

Thanks for your help:)

Body:
Move the variables in your GLwidget class. Here I assumed they are declared public, but you might want to use setters and getters. Then, call update to refresh the widget.

void MainWindow::on_pushButton_Calculate_clicked()
{
    ui->myglwidgetname->loan = inputcheck<double>(ui->lineEdit_loan);
    ui->myglwidgetname->maturity = inputcheck<int>(ui->lineEdit_maturity);
    ui->myglwidgetname->rate1 = inputcheck<double>(ui->lineEdit_rate1);
    ui->myglwidgetname->rate2 = inputcheck<double>(ui->lineEdit_rate2);
    ui->myglwidgetname->rate3 = inputcheck<double>(ui->lineEdit_rate3);
    ui->myglwidgetname->period2 = inputcheck<int>(ui->lineEdit_period2);
    ui->myglwidgetname->period3 = inputcheck<int>(ui->lineEdit_period3);
    ui->myglwidgetname->update();
}

Additionaly, you want to correct your templated function because it is calling toDouble regardless of the type T which doesn't make sense at all...


问:
BigQuery with limit 10 or fewer extraction value returns correct results, changing limit or adding extraction return null
The following is an issue with genomic data:
        I use the following query on the pgp data in big query: http://googlegenomics.readthedocs.io/en/latest/use_cases/discover_public_data/pgp_public_data.html
        (used one sample id for simplicity: hu089792)

```<code>    *SELECT
      sample_id,
      allele1Gene,
      NTH(2,SPLIT(s.allele1XRef,':')) AS rsID,
      NTH(1,SPLIT(allele1Gene,';')) AS input,
      NTH(3,SPLIT((NTH(1,SPLIT(allele1Gene,';'))),':')) AS gene1,
      NTH(2,SPLIT(allele1Gene,';')) AS input2,
      NTH(3,SPLIT((NTH(2,SPLIT(allele1Gene,';'))),':')) AS gene2
    FROM
      [speedy-emissary-167213:pgp_orielresearch.pgp_variants_gene_dbsnp_hu089792] AS s
    LIMIT
      10*

    **the result is as expected:**
    *Row|   sample_id|  allele1Gene|    rsID|   input|  gene1|  input2| gene2
    --------------------
    1   hu089792    10645:NM_006549.3:CAMKK2:INTRON:UNKNOWN-INC;10645:NM_153499.2:CAMKK2:INTRON:UNKNOWN-INC;10645:NM_153500.1:CAMKK2:INTRON:UNKNOWN-INC;10645:NM_172214.2:CAMKK2:INTRON:UNKNOWN-INC;10645:NM_172215.2:CAMKK2:INTRON:UNKNOWN-INC;10645:NM_172216.1:CAMKK2:INTRON:UNKNOWN-INC;10645:NM_172226.2:CAMKK2:INTRON:UNKNOWN-INC rs3794207   10645:NM_006549.3:CAMKK2:INTRON:UNKNOWN-INC CAMKK2  10645:NM_153499.2:CAMKK2:INTRON:UNKNOWN-INC CAMKK2
    2   hu089792    387357:NM_001010923.2:THEMIS:INTRON:UNKNOWN-INC;387357:NM_001164685.1:THEMIS:INTRON:UNKNOWN-INC;387357:NM_001164687.1:THEMIS:INTRON:UNKNOWN-INC rs683202    387357:NM_001010923.2:THEMIS:INTRON:UNKNOWN-INC THEMIS  387357:NM_001164685.1:THEMIS:INTRON:UNKNOWN-INC THEMIS
    3   hu089792    10207:NM_176877.2:INADL:INTRON:UNKNOWN-INC  rs2666491   10207:NM_176877.2:INADL:INTRON:UNKNOWN-INC  INADL   null    null*

    **when i change the limit to 100 / or add another gene extraction, i get null results:**
    **the limit change query is:**

    SELECT

      sample_id,

      allele1Gene,

      NTH(2,SPLIT(s.allele1XRef,':')) AS rsID,

      NTH(1,SPLIT(allele1Gene,';')) AS input,

      NTH(3,SPLIT((NTH(1,SPLIT(allele1Gene,';'))),':')) AS gene1,

      NTH(2,SPLIT(allele1Gene,';')) AS input2,

      NTH(3,SPLIT((NTH(2,SPLIT(allele1Gene,';'))),':')) AS gene2

    FROM

          [speedy-emissary-167213:pgp_orielresearch.pgp_variants_gene_dbsnp_hu089792] AS s
        LIMIT
          1000

    **The result is:**
    *Row|   sample_id|  allele1Gene|    rsID|   input|  gene1|  input2| gene2
    ------------------
    1   hu089792    null    rs6078843   null    null    null    null
    2   hu089792    null    rs79092469  null    null    null    null
    3   hu089792    null    rs56216546  null    null    null    null
    4   hu089792    null    rs9576011   null    null    null    null*

    **The other query (adding extraction query):**

SELECT
  sample_id,
  allele1Gene,
  NTH(2,SPLIT(s.allele1XRef,':')) AS rsID,
  NTH(1,SPLIT(allele1Gene,';')) AS input,
  NTH(3,SPLIT((NTH(1,SPLIT(allele1Gene,';'))),':')) AS gene1,
  NTH(2,SPLIT(allele1Gene,';')) AS input2,
  NTH(3,SPLIT((NTH(2,SPLIT(allele1Gene,';'))),':')) AS gene2,
  NTH(3,SPLIT(allele1Gene,';')) AS input3,
  NTH(3,SPLIT((NTH(3,SPLIT(allele1Gene,';'))),':')) AS gene3

   FROM
      [speedy-emissa167213:pgp_orielresearch.pgp_variants_gene_dbsnp_hu089792] AS s
        LIMIT 10

        **returns:**
        *Row|   sample_id|  allele1Gene|    rsID|   input|  gene1|  input2| gene2|  input3| gene3
        -----------------------
        1   hu089792    null    rs6551009   null    null    null    null    null    null
        2   hu089792    null    rs2050586   null    null    null    null    null    null
        3   hu089792    null    rs7151797   null    null    null    null    null    null*

        **any idea why?**

        Any help is greatly appreciated

        Best,
        eilalan

        **the original table includes 3 columns that are extracted from [google.com:biggene:pgp.cgi_variants]
        see below:**
        Row|    sample_id|  allele1XRef|    allele1Gene|
        -------------
        1   hu089792    dbsnp.107:rs3794207 10645:NM_006549.3:CAMKK2:INTRON:UNKNOWN-INC;10645:NM_153499.2:CAMKK2:INTRON:UNKNOWN-INC;10645:NM_153500.1:CAMKK2:INTRON:UNKNOWN-INC;10645:NM_172214.2:CAMKK2:INTRON:UNKNOWN-INC;10645:NM_172215.2:CAMKK2:INTRON:UNKNOWN-INC;10645:NM_172216.1:CAMKK2:INTRON:UNKNOWN-INC;10645:NM_172226.2:CAMKK2:INTRON:UNKNOWN-INC

    2   hu089792    dbsnp.83:rs683202   387357:NM_001010923.2:THEMIS:INTRON:UNKNOWN-INC;387357:NM_001164685.1:THEMIS:INTRON:UNKNOWN-INC;387357:NM_001164687.1:THEMIS:INTRON:UNKNOWN-INC

    3   hu089792    dbsnp.100:rs2666491 10207:NM_176877.2:INADL:INTRON:UNKNOWN-INC
</code>```

答:
BigQuery does not guarantee order of output rows (unless you add explicit ORDER BY)

So, when you change LIMIT - you most likely getting different rows in owtput and for those rows respective extractions produce NULL

To test  - I would recommend adding specific ORDER BY so you will have consistent rows output thus you will compare oranges with oranges  - not with apples

Body:
The following is an issue with genomic data:
        I use the following query on the pgp data in big query: http://googlegenomics.readthedocs.io/en/latest/use_cases/discover_public_data/pgp_public_data.html
        (used one sample id for simplicity: hu089792)

    *SELECT
      sample_id,
      allele1Gene,
      NTH(2,SPLIT(s.allele1XRef,':')) AS rsID,
      NTH(1,SPLIT(allele1Gene,';')) AS input,
      NTH(3,SPLIT((NTH(1,SPLIT(allele1Gene,';'))),':')) AS gene1,
      NTH(2,SPLIT(allele1Gene,';')) AS input2,
      NTH(3,SPLIT((NTH(2,SPLIT(allele1Gene,';'))),':')) AS gene2
    FROM
      [speedy-emissary-167213:pgp_orielresearch.pgp_variants_gene_dbsnp_hu089792] AS s
    LIMIT
      10*

    **the result is as expected:**
    *Row|   sample_id|  allele1Gene|    rsID|   input|  gene1|  input2| gene2
    --------------------
    1   hu089792    10645:NM_006549.3:CAMKK2:INTRON:UNKNOWN-INC;10645:NM_153499.2:CAMKK2:INTRON:UNKNOWN-INC;10645:NM_153500.1:CAMKK2:INTRON:UNKNOWN-INC;10645:NM_172214.2:CAMKK2:INTRON:UNKNOWN-INC;10645:NM_172215.2:CAMKK2:INTRON:UNKNOWN-INC;10645:NM_172216.1:CAMKK2:INTRON:UNKNOWN-INC;10645:NM_172226.2:CAMKK2:INTRON:UNKNOWN-INC rs3794207   10645:NM_006549.3:CAMKK2:INTRON:UNKNOWN-INC CAMKK2  10645:NM_153499.2:CAMKK2:INTRON:UNKNOWN-INC CAMKK2
    2   hu089792    387357:NM_001010923.2:THEMIS:INTRON:UNKNOWN-INC;387357:NM_001164685.1:THEMIS:INTRON:UNKNOWN-INC;387357:NM_001164687.1:THEMIS:INTRON:UNKNOWN-INC rs683202    387357:NM_001010923.2:THEMIS:INTRON:UNKNOWN-INC THEMIS  387357:NM_001164685.1:THEMIS:INTRON:UNKNOWN-INC THEMIS
    3   hu089792    10207:NM_176877.2:INADL:INTRON:UNKNOWN-INC  rs2666491   10207:NM_176877.2:INADL:INTRON:UNKNOWN-INC  INADL   null    null*

    **when i change the limit to 100 / or add another gene extraction, i get null results:**
    **the limit change query is:**

    SELECT

      sample_id,

      allele1Gene,

      NTH(2,SPLIT(s.allele1XRef,':')) AS rsID,

      NTH(1,SPLIT(allele1Gene,';')) AS input,

      NTH(3,SPLIT((NTH(1,SPLIT(allele1Gene,';'))),':')) AS gene1,

      NTH(2,SPLIT(allele1Gene,';')) AS input2,

      NTH(3,SPLIT((NTH(2,SPLIT(allele1Gene,';'))),':')) AS gene2

    FROM

          [speedy-emissary-167213:pgp_orielresearch.pgp_variants_gene_dbsnp_hu089792] AS s
        LIMIT
          1000

    **The result is:**
    *Row|   sample_id|  allele1Gene|    rsID|   input|  gene1|  input2| gene2
    ------------------
    1   hu089792    null    rs6078843   null    null    null    null
    2   hu089792    null    rs79092469  null    null    null    null
    3   hu089792    null    rs56216546  null    null    null    null
    4   hu089792    null    rs9576011   null    null    null    null*

    **The other query (adding extraction query):**

SELECT
  sample_id,
  allele1Gene,
  NTH(2,SPLIT(s.allele1XRef,':')) AS rsID,
  NTH(1,SPLIT(allele1Gene,';')) AS input,
  NTH(3,SPLIT((NTH(1,SPLIT(allele1Gene,';'))),':')) AS gene1,
  NTH(2,SPLIT(allele1Gene,';')) AS input2,
  NTH(3,SPLIT((NTH(2,SPLIT(allele1Gene,';'))),':')) AS gene2,
  NTH(3,SPLIT(allele1Gene,';')) AS input3,
  NTH(3,SPLIT((NTH(3,SPLIT(allele1Gene,';'))),':')) AS gene3

   FROM
      [speedy-emissa167213:pgp_orielresearch.pgp_variants_gene_dbsnp_hu089792] AS s
        LIMIT 10

        **returns:**
        *Row|   sample_id|  allele1Gene|    rsID|   input|  gene1|  input2| gene2|  input3| gene3
        -----------------------
        1   hu089792    null    rs6551009   null    null    null    null    null    null
        2   hu089792    null    rs2050586   null    null    null    null    null    null
        3   hu089792    null    rs7151797   null    null    null    null    null    null*

        **any idea why?**

        Any help is greatly appreciated

        Best,
        eilalan

        **the original table includes 3 columns that are extracted from [google.com:biggene:pgp.cgi_variants]
        see below:**
        Row|    sample_id|  allele1XRef|    allele1Gene|
        -------------
        1   hu089792    dbsnp.107:rs3794207 10645:NM_006549.3:CAMKK2:INTRON:UNKNOWN-INC;10645:NM_153499.2:CAMKK2:INTRON:UNKNOWN-INC;10645:NM_153500.1:CAMKK2:INTRON:UNKNOWN-INC;10645:NM_172214.2:CAMKK2:INTRON:UNKNOWN-INC;10645:NM_172215.2:CAMKK2:INTRON:UNKNOWN-INC;10645:NM_172216.1:CAMKK2:INTRON:UNKNOWN-INC;10645:NM_172226.2:CAMKK2:INTRON:UNKNOWN-INC

    2   hu089792    dbsnp.83:rs683202   387357:NM_001010923.2:THEMIS:INTRON:UNKNOWN-INC;387357:NM_001164685.1:THEMIS:INTRON:UNKNOWN-INC;387357:NM_001164687.1:THEMIS:INTRON:UNKNOWN-INC

    3   hu089792    dbsnp.100:rs2666491 10207:NM_176877.2:INADL:INTRON:UNKNOWN-INC


问:
PHP Error - 'Can't use function return value in write context'
So, I just got this error on a page that is meant to show some product categories:

Fatal error: Can't use function return value in write context in /home/name/public_html/wp-content/themes/name/taxonomy-prodcat.php on line 37

On line 37 is this code:

```<code><?php if(!empty(get_field('product_size', get_the_ID()))): ?>
                                            <p class="producttext"><span class="boldproduct">Size -</span> <?php echo get_field('product_size', get_the_ID()); ?></p>
                                        <?php endif; ?>
</code>```

PHP Version 5.6.30
MySQL Version   5.6.35

I really cant find the problem. Any help ?

答:
You must write:

$v = get_field(...);
if(!empty($v))...

Body:
So, I just got this error on a page that is meant to show some product categories:

Fatal error: Can't use function return value in write context in /home/name/public_html/wp-content/themes/name/taxonomy-prodcat.php on line 37

On line 37 is this code:

<?php if(!empty(get_field('product_size', get_the_ID()))): ?>

Size - <?php echo get_field('product_size', get_the_ID()); ?>

                                        <?php endif; ?>

PHP Version 5.6.30
MySQL Version   5.6.35

I really cant find the problem. Any help ?


问:
Is there something wrong with my form?
I have my form working and all of the errors and everything works.
But if you have an error, it refreshes the page and removes any text that was inserted before the submit button was clicked and you have to re-enter all of the information.
Anyway to fix this?

I think it has something to do with not using $_SERVER["PHP_SELF"] in the action of the form.
Instead I have action=""

I am doing this because the page that needs to be refreshed with the same info has a variable in its url (monthly_specials_info.php?date=Dec10) that was put there from the last page.

I tried using

```<code><form method="post" action="'.$_SERVER["PHP_SELF"].'?date='.$date.'">
</code>```

and it produced the right url. but the text was all removed anyway when form was submitted (with errors).. any ideas?

Form code:

```<code>echo '    <div id="specialsForm"><h3>Interested in this coupon? Email us! </h3>
                                            <form method="post" action="'.$_SERVER["PHP_SELF"].'?date='.$date.'">
                                              Name: <input name="name" type="text" /><br />
                                              Email: <input name="email" type="text" /><br />
                                              Phone Number: <input name="phone" type="text" /><br /><br />
                                              Comment: <br/>
                                              <textarea name="comment" rows="5" cols="30"></textarea><br /><br />
                                              <input type="submit" name="submit" value="Submit Email"/>
                                            </form></div>
                                            <div style="clear:both;"></div><br /><br />';
</code>```

and the vaildator:

```<code>if(isset($_POST['submit'])) {

                                                $errors = array();
                                                if (empty($name)) {
                                                    $errors[] = '<span class="error">ERROR: Missing Name </span><br/>';
                                                }
                                                if (empty($phone) || empty($email)) {
                                                    $errors[] = '<span class="error">ERROR: You must insert a phone number or email</span><br/>';
                                                }
                                                if (!is_numeric($phone)) {
                                                    $errors[] = '<span class="error">ERROR: You must insert a phone number or email</span><br/>';
                                                }
                                                if (!preg_match('/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}/', strtoupper($email))) {
                                                    $errors[] = '<span class="error">ERROR: Please Insert a valid Email</span><br/>';
                                                }
                                                if ($errors) {
                                                    echo '<p style="font-weight:bold;text-align:center;">There were some errors:</p> ';
                                                    echo '<ul><li>', implode('</li><li>', $errors), '</li></ul><br/>';
                                                } else {
                                                    mail( "email@hotmail.com", "Monthly Specials Email",
                                                        "Name: $name\n".
                                                        "Email: $email\n".
                                                        "Phone Number: $phone\n".
                                                        "Comment: $comment", "From: $email");
                                                    echo'<span id="valid">Message has been sent</span><br/>';
                                                }
}
</code>```

答:
If you want the form to submit to the same page, you don't need to set an action, it works without it as well. Also I'd suggest you to send the date in this way:</p>

```<code><input type="hidden" name="date" value="'.$date.'"/>
</code>```

Title: Is there something wrong with my form?

Body:
I have my form working and all of the errors and everything works.
But if you have an error, it refreshes the page and removes any text that was inserted before the submit button was clicked and you have to re-enter all of the information.
Anyway to fix this?

I think it has something to do with not using $_SERVER["PHP_SELF"] in the action of the form.
Instead I have action=""

I am doing this because the page that needs to be refreshed with the same info has a variable in its url (monthly_specials_info.php?date=Dec10) that was put there from the last page.

I tried using

<form method="post" action="'.$_SERVER["PHP_SELF"].'?date='.$date.'">

and it produced the right url. but the text was all removed anyway when form was submitted (with errors).. any ideas?

Form code:

echo '

Interested in this coupon? Email us!

                                            <form method="post" action="'.$_SERVER["PHP_SELF"].'?date='.$date.'">
                                              Name: <input name="name" type="text" />

                                              Email: <input name="email" type="text" />

                                              Phone Number: <input name="phone" type="text" />

                                              Comment:

                                              <textarea name="comment" rows="5" cols="30"></textarea>

                                              <input type="submit" name="submit" value="Submit Email"/>
                                            </form>

';

and the vaildator:

if(isset($_POST['submit'])) {

                                                $errors = array();
                                                if (empty($name)) {
                                                    $errors[] = 'ERROR: Missing Name
';
                                                }
                                                if (empty($phone) || empty($email)) {
                                                    $errors[] = 'ERROR: You must insert a phone number or email
';
                                                }
                                                if (!is_numeric($phone)) {
                                                    $errors[] = 'ERROR: You must insert a phone number or email
';
                                                }
                                                if (!preg_match('/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}/', strtoupper($email))) {
                                                    $errors[] = 'ERROR: Please Insert a valid Email
';
                                                }
                                                if ($errors) {
                                                    echo '
There were some errors:
 ';
                                                    echo '

', implode('

', $errors), '

';
                                                } else {
                                                    mail( "email@hotmail.com", "Monthly Specials Email",
                                                        "Name: $name\n".
                                                        "Email: $email\n".
                                                        "Phone Number: $phone\n".
                                                        "Comment: $comment", "From: $email");
                                                    echo'Message has been sent
';
                                                }
}

Body:
If you want the form to submit to the same page, you don't need to set an action, it works without it as well. Also I'd suggest you to send the date in this way:

<input type="hidden" name="date" value="'.$date.'"/>


问:
getting value from void function with printf
I am trying to understand following C program.

```<code>#include <stdio.h>
int main()
{
   int k = m();
    printf("%d", k);
}
void m()
{
    printf("hello");
}
</code>```

Above code produces output of hello5. I understand why it is printing hello, but I do not understand why there is 5 behind it. How the 5 is getting returned and stored into variable k? How does the flow of this program work?

答: You are assigning return value of m() to k. Since m() has no return value undefined behaviour will be visible, so there will be "garbage" in k (in this case: 5).

Body:
I am trying to understand following C program.

#include <stdio.h>
int main()
{
   int k = m();
    printf("%d", k);
}
void m()
{
    printf("hello");
}

Above code produces output of hello5. I understand why it is printing hello, but I do not understand why there is 5 behind it. How the 5 is getting returned and stored into variable k? How does the flow of this program work?


问:
DotNetZip Cancel extraction in Task
I have a method that executes a zip-extraction in a Task. Now I want the ability to Cancel the operation. But when I call the Cancel() method everything seems to stop immediately and the while runs forever:

```<code>public class OsiSourceZip
{
    private const string ZipPassword = "******";

    private bool _extractionDone;
    private bool _cancelExtraction;

    public async Task Extract(string sourceFile, string extractionDir)
    {
        Task extraction = Task.Run(() =>
        {
            using (ZipFile zipf = ZipFile.Read(sourceFile))
            {
                zipf.ExtractProgress += delegate(object sender, ExtractProgressEventArgs args)
                {
                    args.Cancel = _cancelExtraction;
                    RaiseExtractionProgressUpdate(args);
                };
                zipf.Password = ZipPassword;
                zipf.Encryption = EncryptionAlgorithm.WinZipAes256;
                zipf.ExtractExistingFile = ExtractExistingFileAction.OverwriteSilently;
                zipf.ExtractAll(extractionDir);
            }
        });

        await extraction;
        _extractionDone = true;
        RaiseSourceInstallationCompleted();
    }

    public void Cancel()
    {
        _cancelExtraction = true;
        while (!_extractionDone)
        {
            Thread.Sleep(500);
        }
    }
}
</code>```

I've set a break point on args.Cancel = _cancelExtraction; but the event is not fired anymore as soon as the Cancel() method is called.

答:
I've found a solution to this. I basically got rid of my own Cancel Method and do it as the dotnetzip Framework wants it. In the progress event.

Let's say you want to cancel the operation when the Form gets closed. I capture the FormClosing Event, cancel the close procedure and remember the close request. The next time the progress event fires, I set the the cancel property in the event args and close the Form myself in the completed Event:

```<code>public partial class MainForm : Form
{
    private bool _closeRequested;

    private void OnSourceInstallationCompleted(object sender, EventArgs e)
    {
        if (_closeRequested) { this.Close(); }
    }

    private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
    {
        if (!_closeRequested)
        {
            _closeRequested = true;
            e.Cancel = true;
        }
    }

    private void OnExtractionProgressUpdate(object sender, ExtractProgressEventArgs e)
    {
        e.Cancel = _closeRequested;
    }
}
</code>```

I think it's rather ugly but it works....

Title: DotNetZip Cancel extraction in Task

Body:
I have a method that executes a zip-extraction in a Task. Now I want the ability to Cancel the operation. But when I call the Cancel() method everything seems to stop immediately and the while runs forever:

public class OsiSourceZip
{
    private const string ZipPassword = "******";

    private bool _extractionDone;
    private bool _cancelExtraction;

    public async Task Extract(string sourceFile, string extractionDir)
    {
        Task extraction = Task.Run(() =>
        {
            using (ZipFile zipf = ZipFile.Read(sourceFile))
            {
                zipf.ExtractProgress += delegate(object sender, ExtractProgressEventArgs args)
                {
                    args.Cancel = _cancelExtraction;
                    RaiseExtractionProgressUpdate(args);
                };
                zipf.Password = ZipPassword;
                zipf.Encryption = EncryptionAlgorithm.WinZipAes256;
                zipf.ExtractExistingFile = ExtractExistingFileAction.OverwriteSilently;
                zipf.ExtractAll(extractionDir);
            }
        });

        await extraction;
        _extractionDone = true;
        RaiseSourceInstallationCompleted();
    }

    public void Cancel()
    {
        _cancelExtraction = true;
        while (!_extractionDone)
        {
            Thread.Sleep(500);
        }
    }
}

I've set a break point on args.Cancel = _cancelExtraction; but the event is not fired anymore as soon as the Cancel() method is called.

Body:
I've found a solution to this. I basically got rid of my own Cancel Method and do it as the dotnetzip Framework wants it. In the progress event.

Let's say you want to cancel the operation when the Form gets closed. I capture the FormClosing Event, cancel the close procedure and remember the close request. The next time the progress event fires, I set the the cancel property in the event args and close the Form myself in the completed Event:

public partial class MainForm : Form
{
    private bool _closeRequested;

    private void OnSourceInstallationCompleted(object sender, EventArgs e)
    {
        if (_closeRequested) { this.Close(); }
    }

    private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
    {
        if (!_closeRequested)
        {
            _closeRequested = true;
            e.Cancel = true;
        }
    }

    private void OnExtractionProgressUpdate(object sender, ExtractProgressEventArgs e)
    {
        e.Cancel = _closeRequested;
    }
}

I think it's rather ugly but it works....


答:
first, a few general changes:

change

<form method="post" action="'.$_SERVER["PHP_SELF"].'?date='.$date.'">

to

```<code><form method="post" action="'.$_SERVER["PHP_SELF"].'">
    <input type="hidden" name="data" value="'.$date.'" />
</code>```

the answer to your original question:

set each input elements value attribute with $_POST['whatever'] if array_key_exists('whatever', $_POST);

For example: the name field

```<code><input type="text" name="name" value="<?php echo array_key_exists('name', $_POST) ? $_POST['name'] : ''; ?>" />
</code>```

Title: Is there something wrong with my form?

Body:
first, a few general changes:

change

<form method="post" action="'.$_SERVER["PHP_SELF"].'?date='.$date.'">

to

<form method="post" action="'.$_SERVER["PHP_SELF"].'">
    <input type="hidden" name="data" value="'.$date.'" />

the answer to your original question:

set each input elements value attribute with $_POST['whatever'] if array_key_exists('whatever', $_POST);

For example: the name field

<input type="text" name="name" value="<?php echo array_key_exists('name', $_POST) ? $_POST['name'] : ''; ?>" />


问:
splitting tweets based on time
I have a collection of tweets in json format in a file. The "created_at" key in each tweets looks like:

```<code>Sun May 28 23:59:59 +0000 2017
Sun May 28 23:59:58 +0000 2017
Sun May 28 23:59:58 +0000 2017
Sun May 28 23:59:58 +0000 2017
Sun May 28 23:59:58 +0000 2017
Sun May 28 23:59:57 +0000 2017
Sun May 28 23:59:57 +0000 2017
Sun May 28 23:59:57 +0000 2017
Sun May 28 23:59:57 +0000 2017
Sun May 28 23:59:56 +0000 2017
Sun May 28 23:59:56 +0000 2017
</code>```

I would like to collect tweets for every 10 second interval and do some calculations on the tweets (e.g. consider from Sun May 28 23:59:59 +0000 2017 to Sun May 28 23:59:49 +0000 2017) and next step from Sun May 28 23:59:49 +0000 2017 to Sun May 28 23:59:39 +0000 2017 and so on). How can I do this?

答:
You can use pandas module to create a dataframe from the json with df = pd.read_json(filename) and use TimeGrouper to group time intervals grouped = df.groupby(pd.TimeGrouper("10s")). Then you can iterate through the groups with for name, group in grouped:

```<code>df = pd.read_json(filename)
grouped = df.groupby(pd.TimeGrouper("10s"))

for name, group in grouped:
    ...
</code>```

Title: splitting tweets based on time

Body:
I have a collection of tweets in json format in a file. The "created_at" key in each tweets looks like:

Sun May 28 23:59:59 +0000 2017
Sun May 28 23:59:58 +0000 2017
Sun May 28 23:59:58 +0000 2017
Sun May 28 23:59:58 +0000 2017
Sun May 28 23:59:58 +0000 2017
Sun May 28 23:59:57 +0000 2017
Sun May 28 23:59:57 +0000 2017
Sun May 28 23:59:57 +0000 2017
Sun May 28 23:59:57 +0000 2017
Sun May 28 23:59:56 +0000 2017
Sun May 28 23:59:56 +0000 2017

I would like to collect tweets for every 10 second interval and do some calculations on the tweets (e.g. consider from Sun May 28 23:59:59 +0000 2017 to Sun May 28 23:59:49 +0000 2017) and next step from Sun May 28 23:59:49 +0000 2017 to Sun May 28 23:59:39 +0000 2017 and so on). How can I do this?

Body:
You can use pandas module to create a dataframe from the json with df = pd.read_json(filename) and use TimeGrouper to group time intervals grouped = df.groupby(pd.TimeGrouper("10s")). Then you can iterate through the groups with for name, group in grouped:

df = pd.read_json(filename)
grouped = df.groupby(pd.TimeGrouper("10s"))

for name, group in grouped:
    ...


问:
Password-checker JavaScript and HTML <form>
I am trying to have a website display different messages depending on whether the password entered is correct or not (correct password is thePassword). So far, no luck.

According to Chrome, the error is in this line (first line of the function):

if (document.getElementById("psw") = "thePassword") {

JSFiddle: https://jsfiddle.net/5grtmxd4/

Thanks in advance!

```<code><!DOCTYPE html>
<html>
<head>
</head>
<body>
  <form>
    Password<br>
    <input id="psw" type="password" name="password" size="45" autofocus></input><br><br>
    <input type="submit" value="Submit" onclick="message();"></input>
  </form>
<script>
function message () {
  if (document.getElementById("psw") = "thePassword") {
    document.getElementById("display").innerHTML = "Logged in";
  } else {
    document.getElementById("display").innerHTML = "Try again!";
  }}
</script>
<p id="display"></p>
</body>
</html>
</code>```

EDIT: I would appreciate that instead of trying to rewrite the entire code, only neccessary changes are made. Thanks!

答:
Change </p>

```<code>if(document.getElementById("psw") = "thePassword")

if(document.getElementById("psw").value == "thePassword")
</code>```

Body:
I am trying to have a website display different messages depending on whether the password entered is correct or not (correct password is thePassword). So far, no luck.

According to Chrome, the error is in this line (first line of the function):

if (document.getElementById("psw") = "thePassword") {

JSFiddle: https://jsfiddle.net/5grtmxd4/

Thanks in advance!

<!DOCTYPE html>

  <form>
    Password

    <input id="psw" type="password" name="password" size="45" autofocus></input>

    <input type="submit" value="Submit" onclick="message();"></input>
  </form>

EDIT: I would appreciate that instead of trying to rewrite the entire code, only neccessary changes are made. Thanks!

Body:
Change

if(document.getElementById("psw") = "thePassword")

if(document.getElementById("psw").value == "thePassword")


问:
iOS: A specific function can be called from multiple threads/places, but I want each call to execute in a queue
I have a function readData reading data from HealthKit that takes a few seconds to execute.
This function can be called from multiple threads/places, but I want each call to execute in a queue, one at a time, rather than in parallel.

Is there a simple way to use GCD or OperationQueues to achieve this in Swift for iOS?

答:
Yes, a serial DispatchQueue should solve your problem. Make sure that you create it in a scope that each of your functions that need to can access it.</p>

```<code>let serialQueue = DispatchQueue(label: "serialQueue")
serialQueue.async{  //call this whenever you need to add a new work item to your queue
    //call function here
}
</code>```

Body:
Yes, a serial DispatchQueue should solve your problem. Make sure that you create it in a scope that each of your functions that need to can access it.

let serialQueue = DispatchQueue(label: "serialQueue")
serialQueue.async{  //call this whenever you need to add a new work item to your queue
    //call function here
}


问:
How can I clear firebase cloud message notifications?
I use firebase cloud message to send messages to my phone, and I can successfully receive notifications. But in some cases, I do not click  notifications to open my app, but manually open the app to go into foregroud. And what I want is when I open the app, notifications in notification bar should be automatically cleared.</p>

答:
The following code will clear all notifications for your app, including those created by FCM. You could add this to the onResume method of your main activity:

```<code>NotificationManager manager = (NotificationManager) getApplicationContext()
                        .getSystemService(Context.NOTIFICATION_SERVICE);
manager.cancelAll();
</code>```

Usually you would cancel a notification by specifying the ID you gave it when it was created, however as FCM is creating the notification for you, you can't know its ID, and so must cancel it by cancelling all notifications as above.

Body:
The following code will clear all notifications for your app, including those created by FCM. You could add this to the onResume method of your main activity:

NotificationManager manager = (NotificationManager) getApplicationContext()
                        .getSystemService(Context.NOTIFICATION_SERVICE);
manager.cancelAll();

Usually you would cancel a notification by specifying the ID you gave it when it was created, however as FCM is creating the notification for you, you can't know its ID, and so must cancel it by cancelling all notifications as above.


问:
How to make a dynamic HTML table repopulate after form is reopened based on saved value
I have created a form which uses a dropdown, based on the selection in this dropdown a few tables dynamically populate with dynamically created inputs. This all works properly.

The problem is that I have to place this form inside of another HTML/JS/JQuery based 3rd party system and the form will need to be closed and reopened multiple times on different computers of an intranet. From what I can tell, this system has a background script (probably using serialization?) that saves the user inputs for any fields that is an input/select/check which allows it to store forms with entered user input.

Given that this system is storing the data for my dropdown selection, I should be able to call my function again to "reset" the table I would think.

I have tried checking if the dropdown is not at the "default" and running the function for setting dropdowns and it did not work.

How can I have my table populate when the form is reloaded?

```<code>if (document.getElementById('cmblstPartNumber') != "Select Product"){
    setDropdowns(document.getElementById('cmblstPartNumber'),document.getElementById('cmblstLine'));
}
</code>```

This is the function declaration for my functional code to set the dropdowns.

```<code>function setDropdowns(cmblstPartNumber,cmblstLine) {
//Massive Switch statement
}
</code>```

答:
You can store the selected values in local storage and repopulate it when the form element is reloaded.
Clear the local storage when you are done

Body:
I have created a form which uses a dropdown, based on the selection in this dropdown a few tables dynamically populate with dynamically created inputs. This all works properly.

The problem is that I have to place this form inside of another HTML/JS/JQuery based 3rd party system and the form will need to be closed and reopened multiple times on different computers of an intranet. From what I can tell, this system has a background script (probably using serialization?) that saves the user inputs for any fields that is an input/select/check which allows it to store forms with entered user input.

Given that this system is storing the data for my dropdown selection, I should be able to call my function again to "reset" the table I would think.

I have tried checking if the dropdown is not at the "default" and running the function for setting dropdowns and it did not work.

How can I have my table populate when the form is reloaded?

if (document.getElementById('cmblstPartNumber') != "Select Product"){
    setDropdowns(document.getElementById('cmblstPartNumber'),document.getElementById('cmblstLine'));
}

This is the function declaration for my functional code to set the dropdowns.

function setDropdowns(cmblstPartNumber,cmblstLine) {
//Massive Switch statement
}