问:
Vue.js Two-Way sync Data Binding using vue-property-decorator
I'm using Vue.js with TypeScript and the vue-property-decorator. I'd like to perform some two-way data binding between a parent and child component. Here is a simple idea of what I'm trying to do:

Parent Component

```<code><template>
  <progress :is-loaded.sync="isLoaded"/>
</template>

@Component
export default class ParentComponent extends Vue {
  get isLoaded() { return Store.getters["isLoaded"]; }
  set isLoaded(value: boolean) { Store.commit("isLoaded", value); }
}
</code>```

Child Component

```<code><template>
 <progress :value="_value" min="0" max="100"></progress>
 {{_isLoaded}}
</template>

@Component
export default class ChildComponent extends Vue {
  @Prop()
  public isLoaded: boolean;

  public _isLoaded: boolean;
  public _value: number;

  public mounted() {
    this._isLoaded = this.isLoaded;
    this._value = this.value;
  }

  @Watch("isLoaded")
  public onIsLoadedChanged() {
    if (!isLoaded) {
      // Animate _value from 0 to 100.
      this._isLoaded = true;
      this.$emit("update:isLoaded", this._isLoaded);
    }
  }
}
</code>```

Do I really have to use two fields isLoaded and _isLoaded as well as use this.$emit with a magic string of update:isLoaded? All of this syntax seems very verbose, is there a simpler way? Is there some way to encapsulate some of this?

答:
At what point in your app does the value of isLoaded change? If it only changes in the parent, you don't need to emit an event back up, and you can just use the prop without the @Watch and without the _isLoaded variable.
If isLoaded changes in the child, you don't need the prop and the duplicate variable. You can just emit a loaded event and listen for that event in the parent.

This is a simplified example where the style of the child changes when the parent changes isLoaded

parent

```<code><template>
  <progress :is-loaded="isLoaded"/>
</template>

@Component
export default class ParentComponent extends Vue {
  public isLoaded: boolean = false
  created(){
    setInterval(()=>this.updateStatus(), 500)
  }
  this.updateStatus(){
    this.isLoaded = true
  }
}
</code>```

child

```<code><template>
 <div :class="{ full: isLoaded }">Loaded is {{ isLoaded }}</div>
</template>

@Component
export default class ChildComponent extends Vue {
  @Prop()
  isLoaded: boolean;
}

<css>
   .full {width:100%}
</css>
</code>```

Body:
I'm using Vue.js with TypeScript and the vue-property-decorator. I'd like to perform some two-way data binding between a parent and child component. Here is a simple idea of what I'm trying to do:

Parent Component

<template>
  <progress :is-loaded.sync="isLoaded"/>
</template>

@Component
export default class ParentComponent extends Vue {
  get isLoaded() { return Store.getters["isLoaded"]; }
  set isLoaded(value: boolean) { Store.commit("isLoaded", value); }
}

Child Component

<template>
 <progress :value="_value" min="0" max="100"></progress>
 {{_isLoaded}}
</template>

@Component
export default class ChildComponent extends Vue {
  @Prop()
  public isLoaded: boolean;

  public _isLoaded: boolean;
  public _value: number;

  public mounted() {
    this._isLoaded = this.isLoaded;
    this._value = this.value;
  }

  @Watch("isLoaded")
  public onIsLoadedChanged() {
    if (!isLoaded) {
      // Animate _value from 0 to 100.
      this._isLoaded = true;
      this.$emit("update:isLoaded", this._isLoaded);
    }
  }
}

Do I really have to use two fields isLoaded and _isLoaded as well as use this.$emit with a magic string of update:isLoaded? All of this syntax seems very verbose, is there a simpler way? Is there some way to encapsulate some of this?

Body:
At what point in your app does the value of isLoaded change? If it only changes in the parent, you don't need to emit an event back up, and you can just use the prop without the @Watch and without the _isLoaded variable.
If isLoaded changes in the child, you don't need the prop and the duplicate variable. You can just emit a loaded event and listen for that event in the parent.

This is a simplified example where the style of the child changes when the parent changes isLoaded

parent

<template>
  <progress :is-loaded="isLoaded"/>
</template>

@Component
export default class ParentComponent extends Vue {
  public isLoaded: boolean = false
  created(){
    setInterval(()=>this.updateStatus(), 500)
  }
  this.updateStatus(){
    this.isLoaded = true
  }
}

child

<template>
 <div :class="{ full: isLoaded }">Loaded is {{ isLoaded }}</div>
</template>

@Component
export default class ChildComponent extends Vue {
  @Prop()
  isLoaded: boolean;
}

<css>
   .full {width:100%}
</css>


来源: stackexchange

问:
How to open a child Window like a splash screen before MainWindow in WPF?
I have two xaml. One is MainWindow and other is NewWindow.
I want show NewWindow 5 seconds, when program is run.
And after 5 seconds, I want show MainWindow.

How to change xaml in WPF?

Here is MainWindow.

```<code><Window x:Class="WpfApplication2.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525">
<Grid>

</Grid>
</code>```

```<code>public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }
}
</code>```

Here is NewWindow.

```<code><Window x:Class="WpfApplication2.NewWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="NewWindow" Height="300" Width="300">
<Grid>

</Grid>
</code>```

```<code>public partial class NewWindow : Window
{
    public NewWindow()
    {
        InitializeComponent();
    }
}
</code>```

答:
The mainWindow should also be loaded before closing the splashScreen This way your splashscreen shows as long as it is loading.You can add additional time in the splashScreen.Close() Function.

```<code>private SplashScreen splashScreen;

private void App_Startup(object sender, StartupEventArgs e)
{
    splashScreen = new SplashScreen("SplashScreen1.png"); // Or new WPF window
    splashScreen.Show(false);
    MainWindow mainWindow = new MainWindow();
    splashScreen.Close(new TimeSpan(0, 0, 3));
    mainWindow.Show();
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have two xaml. One is MainWindow and other is NewWindow.
I want show NewWindow 5 seconds, when program is run.
And after 5 seconds, I want show MainWindow.

How to change xaml in WPF?

Here is MainWindow.

<Window x:Class="WpfApplication2.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525">
<Grid>

</Grid>

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }
}

Here is NewWindow.

<Window x:Class="WpfApplication2.NewWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="NewWindow" Height="300" Width="300">
<Grid>

</Grid>

public partial class NewWindow : Window
{
    public NewWindow()
    {
        InitializeComponent();
    }
}

Body:
The mainWindow should also be loaded before closing the splashScreen This way your splashscreen shows as long as it is loading.You can add additional time in the splashScreen.Close() Function.

private SplashScreen splashScreen;

private void App_Startup(object sender, StartupEventArgs e)
{
    splashScreen = new SplashScreen("SplashScreen1.png"); // Or new WPF window
    splashScreen.Show(false);
    MainWindow mainWindow = new MainWindow();
    splashScreen.Close(new TimeSpan(0, 0, 3));
    mainWindow.Show();
}


问:
Angular 4 + typescript fail to deploy on heroku
I am trying to deploy my angular 4 app on heroku but it fails to dpeloy properly. Locally all works fine as expected.

Here the files:

package.json

```<code>{
  "name": "webcli2",
  "version": "0.0.0",
  "license": "MIT",
  "main": "app.js",
  "scripts": {
    "ng": "ng",
    "start": "node app.js",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e",
    "postinstall": "ng build --aot  --target=production"
  },
  "engines": {
    "node": "6.11.3",
    "npm": "3.10.10"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "4.2.4",
    "@angular/cli": "1.4.3",
    "@angular/common": "4.2.4",
    "@angular/compiler": "4.2.4",
    "@angular/compiler-cli": "4.2.4",
    "@angular/core": "4.2.4",
    "@angular/forms": "4.2.4",
    "@angular/http": "4.2.4",
    "@angular/platform-browser": "4.2.4",
    "@angular/platform-browser-dynamic": "4.2.4",
    "@angular/router": "4.2.4",
    "@auth0/angular-jwt": "1.0.0-beta.9",
    "bootstrap": "3.3.7",
    "core-js": "2.4.1",
    "express": "4.16.2",
    "grunt": "1.0.1",
    "grunt-cli": "1.2.0",
    "grunt-contrib-sass": "*",
    "grunt-contrib-watch": "*",
    "ngx-bootstrap": "1.9.3",
    "rxjs": "5.4.2",
    "vue-carousel-3d": "0.1.18",
    "zone.js": "0.8.14",
    "typescript": "2.3.3"
     },
  "devDependencies": {
    ...
    }
</code>```

app.js

```<code>const express = require('express');
const app = express();
const path = require('path');

app.use(express.static(path.join(__dirname,'dist')));
app.listen(process.env.PORT || 8080);
app.get('/*', function (req,res) => {
  res.sendFile(path.join(__dirname,'/dist/index.html'));
});

console.log('console listening');
</code>```

Procfile
    web: npm start

About the error: I got this:

```<code>remote:        @angular/compiler-cli@4.4.6 requires typescript@'>=2.1.0 <2.4.0' but 2.6.1  was found instead.
remote:        Using this version can result in undefined behaviour and difficult to debug  problems.
remote:
remote:        Please run the following command to install a compatible version of TypeScript.
remote:
remote:        npm install typescript@'>=2.1.0 <2.4.0'
remote:
remote:        To disable this warning run "ng set --global warnings.typescriptMismatch=false".
remote:
remote:       11% building modules 13/13 modules 0 activeTemplate parse warnings:
remote:        The <template> element is deprecated. Use <ng-template> instead ("
remote:        [WARNING ->]<template [ngIf]="!isClosed">
remote:        <div [class]="'alert alert-' + type" role="alert" [ngClass]="classes""): ng:///tmp/build_1e53727d0184bdda3a3ece784898bf98/node_modules/ngx-bootstrap/alert/alert.component.d.ts.AlertComponent.html@1:0
remote:        Warning: Can't resolve all parameters for ApplicationError in /tmp/build_1e53727d0184bdda3a3ece784898bf98/src/app/util/applicationError.service.ts: (?). This will become an error in Angular v5.x
remote:        Warning: Can't resolve all parameters for ApplicationError in /tmp/ build_1e53727d0184bdda3a3ece784898bf98/src/app/util/applicationError.service.ts: (?).   This will become an error in Angular v5.x
Date: 2017-11-14T10:33:21.586Z
remote:        Hash: 5582f12f0052b6c3a94c
remote:        Time: 22622ms
remote:        chunk {0} styles.de3b0b246fb3804809f9.bundle.css (styles) 133 kB {3}   [initial] [rendered]
remote:        chunk {1} polyfills.3bc34265385d52184eab.bundle.js (polyfills) 86 bytes {3} [initial] [rendered]
remote:        chunk {2} main.e402deade8b026b7d50e.bundle.js (main) 84 bytes [initial] [rendered]
remote:        chunk {3} inline.ebdb3a382088c7f31aee.bundle.js (inline) 1.45 kB [entry] [rendered]
remote:
remote:        ERROR in /tmp/build_1e53727d0184bdda3a3ece784898bf98/src/app/services/auth/user/user.service.ts (73,75): Value of type '() => any' has no properties in common with type '{ headers?: HttpHeaders; observe?: "body"; params?: HttpParams; reportProgress?: boolean; respons...'. Did you mean to call it?
remote:        ERROR in /tmp/build_1e53727d0184bdda3a3ece784898bf98/src/app/services/auth/user/user.service.ts (82,39): Type 'Headers' has no properties in common with type 'RequestOptionsArgs'.
remote:        ERROR in /tmp/build_1e53727d0184bdda3a3ece784898bf98/src/app/services/auth/auth.service.ts (16,34): Cannot find module '../../util/applicationerror.service'.
remote:        ERROR in /tmp/build_1e53727d0184bdda3a3ece784898bf98/src/app/services/auth/auth.service.ts (111,5): Type 'Observable<void | {}>' is not assignable to type 'Observable<{}>'.
remote:          Type 'void | {}' is not assignable to type '{}'.
remote:            Type 'void' is not assignable to type '{}'.
remote:
remote:        npm ERR! Linux 3.13.0-133-generic
remote:        npm ERR! argv "/tmp/build_1e53727d0184bdda3a3ece784898bf98/.heroku/    node/bin/node" "/tmp/build_1e53727d0184bdda3a3ece784898bf98/.heroku/node/bin/npm"  "install" "--unsafe-perm" "--userconfig" "/tmp/  build_1e53727d0184bdda3a3ece784898bf98/.npmrc"
remote:        npm ERR! node v6.11.3
remote:        npm ERR! npm  v3.10.10
remote:        npm ERR! code ELIFECYCLE
remote:        npm ERR! webcli2@0.0.0 postinstall: `ng build --aot  --target=production`
remote:        npm ERR! Exit status 1
remote:        npm ERR!
remote:        npm ERR! Failed at the webcli2@0.0.0 postinstall script 'ng build --aot  --target=production'.
remote:        npm ERR! Make sure you have the latest version of node.js and npm installed.
remote:        npm ERR! If you do, this is most likely a problem with the webcli2 package,
remote:        npm ERR! not with npm itself.
remote:        npm ERR! Tell the author that this fails on your system:
remote:        npm ERR!     ng build --aot  --target=production
remote:        npm ERR! You can get information on how to open an issue for this project with:
remote:        npm ERR!     npm bugs webcli2
remote:        npm ERR! Or if that isn't available, you can get their info via:
remote:        npm ERR!     npm owner ls webcli2
remote:        npm ERR! There is likely additional logging output above.
remote:
remote:        npm ERR! Please include the following file with any support request:
remote:        npm ERR!     /tmp/build_1e53727d0184bdda3a3ece784898bf98/npm-debug.log
remote:
remote: -----> Build failed
</code>```

So looks like that it is not able to install a previous typescript version, in this case, heroku has already 2.6.1, but the one I have on the file is 2.3.3

This is the cause of this error's ?

Locally I got:

```<code>Brunos-MBP:webcli brunolopes$ ng build -aot
 12% building modules 18/18 modules 0 activeWarning: Can't resolve all
parameters for ApplicationError in
 /Users/brunolopes/development/workspace2016/
webroot/winpi/webcli/src/app/util/applicationerror.service.ts: (?). This will become an error in Angular v5.x
Warning: Can't resolve all parameters for ApplicationError in

/Users/brunolopes/development/workspace2016/
webroot/winpi/webcli/src/app/util/applicationerror.service.ts: (?). This will become an error in Angular
v5.x
Template parse warnings:
The <template> element is deprecated. Use <ng-template> instead ("
[WARNING ->]<template [ngIf]="!isClosed">
<div [class]="'alert alert-' + type" role="alert" [ngClass]="classes""): ng:///Users/brunolopes/development/workspace2016/webroot/winpi/webcli/node_modules/ngx-bootstrap/alert/alert.component.d.ts.AlertComponent.html@1:0
Date: 2017-11-16T07:51:16.467Z
Hash: 32f3a3b7f72daf78e799
Time: 53961ms
chunk {inline} inline.bundle.js, inline.bundle.js.map (inline) 5.83 kB
[entry] [rendered]
chunk {main} main.bundle.js, main.bundle.js.map (main) 515 kB {vendor}
[initial] [rendered]
 chunk {polyfills} polyfills.bundle.js, polyfills.bundle.js.map
(polyfills)
217 kB {inline} [initial] [rendered]
chunk {styles} styles.bundle.js, styles.bundle.js.map (styles) 153 kB
{inline} [initial] [rendered]
chunk {vendor} vendor.bundle.js, vendor.bundle.js.map (vendor) 2.43 MB
[initial] [rendered]
Brunos-MBP:webcli brunolopes$
</code>```

Thanks

B

答:
I have Changed angular version to 4.4.6 and it solved the issue.

That is the one on my local environment by mistake I had 4.2.4 on the package.json.

Thanks all!

Body:
I am trying to deploy my angular 4 app on heroku but it fails to dpeloy properly. Locally all works fine as expected.

Here the files:

package.json

{
  "name": "webcli2",
  "version": "0.0.0",
  "license": "MIT",
  "main": "app.js",
  "scripts": {
    "ng": "ng",
    "start": "node app.js",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e",
    "postinstall": "ng build --aot  --target=production"
  },
  "engines": {
    "node": "6.11.3",
    "npm": "3.10.10"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "4.2.4",
    "@angular/cli": "1.4.3",
    "@angular/common": "4.2.4",
    "@angular/compiler": "4.2.4",
    "@angular/compiler-cli": "4.2.4",
    "@angular/core": "4.2.4",
    "@angular/forms": "4.2.4",
    "@angular/http": "4.2.4",
    "@angular/platform-browser": "4.2.4",
    "@angular/platform-browser-dynamic": "4.2.4",
    "@angular/router": "4.2.4",
    "@auth0/angular-jwt": "1.0.0-beta.9",
    "bootstrap": "3.3.7",
    "core-js": "2.4.1",
    "express": "4.16.2",
    "grunt": "1.0.1",
    "grunt-cli": "1.2.0",
    "grunt-contrib-sass": "*",
    "grunt-contrib-watch": "*",
    "ngx-bootstrap": "1.9.3",
    "rxjs": "5.4.2",
    "vue-carousel-3d": "0.1.18",
    "zone.js": "0.8.14",
    "typescript": "2.3.3"
     },
  "devDependencies": {
    ...
    }

app.js

const express = require('express');
const app = express();
const path = require('path');

app.use(express.static(path.join(__dirname,'dist')));
app.listen(process.env.PORT || 8080);
app.get('/*', function (req,res) => {
  res.sendFile(path.join(__dirname,'/dist/index.html'));
});

console.log('console listening');

Procfile
    web: npm start

About the error: I got this:

remote:        @angular/compiler-cli@4.4.6 requires typescript@'>=2.1.0 <2.4.0' but 2.6.1  was found instead.
remote:        Using this version can result in undefined behaviour and difficult to debug  problems.
remote:
remote:        Please run the following command to install a compatible version of TypeScript.
remote:
remote:        npm install typescript@'>=2.1.0 <2.4.0'
remote:
remote:        To disable this warning run "ng set --global warnings.typescriptMismatch=false".
remote:
remote:       11% building modules 13/13 modules 0 activeTemplate parse warnings:
remote:        The <template> element is deprecated. Use <ng-template> instead ("
remote:        [WARNING ->]<template [ngIf]="!isClosed">
remote:        <div [class]="'alert alert-' + type" role="alert" [ngClass]="classes""): ng:///tmp/build_1e53727d0184bdda3a3ece784898bf98/node_modules/ngx-bootstrap/alert/alert.component.d.ts.AlertComponent.html@1:0
remote:        Warning: Can't resolve all parameters for ApplicationError in /tmp/build_1e53727d0184bdda3a3ece784898bf98/src/app/util/applicationError.service.ts: (?). This will become an error in Angular v5.x
remote:        Warning: Can't resolve all parameters for ApplicationError in /tmp/ build_1e53727d0184bdda3a3ece784898bf98/src/app/util/applicationError.service.ts: (?).   This will become an error in Angular v5.x
Date: 2017-11-14T10:33:21.586Z
remote:        Hash: 5582f12f0052b6c3a94c
remote:        Time: 22622ms
remote:        chunk {0} styles.de3b0b246fb3804809f9.bundle.css (styles) 133 kB {3}   [initial] [rendered]
remote:        chunk {1} polyfills.3bc34265385d52184eab.bundle.js (polyfills) 86 bytes {3} [initial] [rendered]
remote:        chunk {2} main.e402deade8b026b7d50e.bundle.js (main) 84 bytes [initial] [rendered]
remote:        chunk {3} inline.ebdb3a382088c7f31aee.bundle.js (inline) 1.45 kB [entry] [rendered]
remote:
remote:        ERROR in /tmp/build_1e53727d0184bdda3a3ece784898bf98/src/app/services/auth/user/user.service.ts (73,75): Value of type '() => any' has no properties in common with type '{ headers?: HttpHeaders; observe?: "body"; params?: HttpParams; reportProgress?: boolean; respons...'. Did you mean to call it?
remote:        ERROR in /tmp/build_1e53727d0184bdda3a3ece784898bf98/src/app/services/auth/user/user.service.ts (82,39): Type 'Headers' has no properties in common with type 'RequestOptionsArgs'.
remote:        ERROR in /tmp/build_1e53727d0184bdda3a3ece784898bf98/src/app/services/auth/auth.service.ts (16,34): Cannot find module '../../util/applicationerror.service'.
remote:        ERROR in /tmp/build_1e53727d0184bdda3a3ece784898bf98/src/app/services/auth/auth.service.ts (111,5): Type 'Observable<void | {}>' is not assignable to type 'Observable<{}>'.
remote:          Type 'void | {}' is not assignable to type '{}'.
remote:            Type 'void' is not assignable to type '{}'.
remote:
remote:        npm ERR! Linux 3.13.0-133-generic
remote:        npm ERR! argv "/tmp/build_1e53727d0184bdda3a3ece784898bf98/.heroku/    node/bin/node" "/tmp/build_1e53727d0184bdda3a3ece784898bf98/.heroku/node/bin/npm"  "install" "--unsafe-perm" "--userconfig" "/tmp/  build_1e53727d0184bdda3a3ece784898bf98/.npmrc"
remote:        npm ERR! node v6.11.3
remote:        npm ERR! npm  v3.10.10
remote:        npm ERR! code ELIFECYCLE
remote:        npm ERR! webcli2@0.0.0 postinstall: `ng build --aot  --target=production`
remote:        npm ERR! Exit status 1
remote:        npm ERR!
remote:        npm ERR! Failed at the webcli2@0.0.0 postinstall script 'ng build --aot  --target=production'.
remote:        npm ERR! Make sure you have the latest version of node.js and npm installed.
remote:        npm ERR! If you do, this is most likely a problem with the webcli2 package,
remote:        npm ERR! not with npm itself.
remote:        npm ERR! Tell the author that this fails on your system:
remote:        npm ERR!     ng build --aot  --target=production
remote:        npm ERR! You can get information on how to open an issue for this project with:
remote:        npm ERR!     npm bugs webcli2
remote:        npm ERR! Or if that isn't available, you can get their info via:
remote:        npm ERR!     npm owner ls webcli2
remote:        npm ERR! There is likely additional logging output above.
remote:
remote:        npm ERR! Please include the following file with any support request:
remote:        npm ERR!     /tmp/build_1e53727d0184bdda3a3ece784898bf98/npm-debug.log
remote:
remote: -----> Build failed

So looks like that it is not able to install a previous typescript version, in this case, heroku has already 2.6.1, but the one I have on the file is 2.3.3

This is the cause of this error's ?

Locally I got:

Brunos-MBP:webcli brunolopes$ ng build -aot
 12% building modules 18/18 modules 0 activeWarning: Can't resolve all
parameters for ApplicationError in
 /Users/brunolopes/development/workspace2016/
webroot/winpi/webcli/src/app/util/applicationerror.service.ts: (?). This will become an error in Angular v5.x
Warning: Can't resolve all parameters for ApplicationError in

/Users/brunolopes/development/workspace2016/
webroot/winpi/webcli/src/app/util/applicationerror.service.ts: (?). This will become an error in Angular
v5.x
Template parse warnings:
The <template> element is deprecated. Use <ng-template> instead ("
[WARNING ->]<template [ngIf]="!isClosed">
<div [class]="'alert alert-' + type" role="alert" [ngClass]="classes""): ng:///Users/brunolopes/development/workspace2016/webroot/winpi/webcli/node_modules/ngx-bootstrap/alert/alert.component.d.ts.AlertComponent.html@1:0
Date: 2017-11-16T07:51:16.467Z
Hash: 32f3a3b7f72daf78e799
Time: 53961ms
chunk {inline} inline.bundle.js, inline.bundle.js.map (inline) 5.83 kB
[entry] [rendered]
chunk {main} main.bundle.js, main.bundle.js.map (main) 515 kB {vendor}
[initial] [rendered]
 chunk {polyfills} polyfills.bundle.js, polyfills.bundle.js.map
(polyfills)
217 kB {inline} [initial] [rendered]
chunk {styles} styles.bundle.js, styles.bundle.js.map (styles) 153 kB
{inline} [initial] [rendered]
chunk {vendor} vendor.bundle.js, vendor.bundle.js.map (vendor) 2.43 MB
[initial] [rendered]
Brunos-MBP:webcli brunolopes$

Thanks

B


问:
Yii2: a proper way to resolve ambiguity of controller and module names
As far as I know, currently Yii 2 doesn't have an out of the box method to resolve ambiguity of controller and module names. An example of module hierarchy to describe what exactly I mean:

app\modules\v1\controllers\UserController // resolves the /v1/users and /v1/users/{id} actions
app\modules\v1\modules\user\Module.php // nested module, resolves the /v1/user/... controllers and their actions, e.g. /v1/user/something/{id}

In this case, the UserController conflicts with the user Module. The main reason of the ambiguity is the singular-plural magic of Yii 2 framework. I didn't find an appropriate solution to resolve this ambiguity. Further my ideas how to resolve it.

Rename the module.

Rename the UserController to the UsersController.

Create an additional submodule, and place there the UserController. E.g. app\modules\v1\modules\root\controllers\UserController

I'm not sure that at least one of these options is a quite elegant one and a proper solution in view of the Yii 2 philosophy.

Coming back to the main question, what is a more appropriate approach to resolve this issue by the Yii 2 philosophy? Controller and Module is two different types of objects, which is differently pluralized or not, thus should be right way to separate them in the routing for the described case.

答:
How I usually deal with this depends a bit on how I'm structuring things.

Let's say I have users, departments, orders and maybe some other stuff. All these concepts have their own module in which all interactions take place. If I want to create REST controllers for all these concepts I can choose to add a controller to every module or I can create a dedicated API module for the controllers.

When creating a dedicated module for this purpose I usually name it api, maybe with some nested versioning module(s) inside. So in this situation I would get the following structure app\modules\api\controllers\UserController which would result in the URL /api/user. No ambiguity there and pretty clear what this is meant for.

When adding such a controller to the module itself I choose a better name than just 'UserController'. When asking myself the question 'What does this controller accomplish?/What does it do?' I find that just UserController doesn't cut it; Especially when inside a User module, resulting in /user/user. This controller is probably going to exist alongside one or more different controllers in the User module, all meant for something different. So, usually, I end up naming it just ApiController, resulting in /user/api. Another controller could be the ProfileController. So when looking at the URLs it's pretty clear what /user/api and /user/profile do. Without the ambiguity.


问:
How to submit a form on page load without clicking submit button?
Is there a way to make a form submit "onload" without clicking a
submit button with PHP? i saw some ways to make it with Javascript, but i love php and id like to make it with php.

For example:

```<code><form action="https://xxxxxx.com/yyy.php" method="post" id="foo">
<input type="hidden" name="LoginEmail" value="user [at] domain.com">
<input type="hidden" name="LoginPassword" value="mycleartextpassword">
<input type="submit" name="Authenticate" value="Login">
<input type="hidden" name="Action" value="1" >
</form>
</code>```

I can make it with javascript:

```<code><form id="foo"> .... < /form>

<script type="text/javascript">
    function myfunc () {
        var frm = document.getElementById("foo");
        frm.submit();
    }
    window.onload = myfunc;
</script>
</code>```

Well, Can we make same thing with PHP? Could you please kindly share your ideas and advices?

Thank you.

答:
It isn't possible to carry out a client-side (i.e.: browser based) form submit action using a server side language (i.e.: PHP). It's a bit like trying to get a library to read a book, if that makes sense. (You get the books from the library and return them there, but the library itself can't read books.)

As such, JavaScript is your only solution if you require an automated submission. Even then, you need to ensure there's a "normal" solution for use by people who don't have JavaScript enabled. (The joy of graceful degradation, etc.)

Body:
Is there a way to make a form submit "onload" without clicking a
submit button with PHP? i saw some ways to make it with Javascript, but i love php and id like to make it with php.

For example:

<form action="https://xxxxxx.com/yyy.php" method="post" id="foo">
<input type="hidden" name="LoginEmail" value="user [at] domain.com">
<input type="hidden" name="LoginPassword" value="mycleartextpassword">
<input type="submit" name="Authenticate" value="Login">
<input type="hidden" name="Action" value="1" >
</form>

I can make it with javascript:

<form id="foo"> .... < /form>

Well, Can we make same thing with PHP? Could you please kindly share your ideas and advices?

Thank you.

ContentLicense: CC BY-SA 2.5


问:
.NET Core app unable to start in IIS due to ErrorCode = '0x80004005 : 80008083
I have a .NET Core application. It runs locally with VS2017 and Kestrel. It runs locally under IIS. However, on the server it fails to start with a 502.5 - Process Failure message.

In the event logs I get more detail:

Application '...' with physical root 'C:...\my-app-folder\' failed to start process with commandline '"dotnet" .\MyApp.dll', ErrorCode = '0x80004005 : 80008083.

Previous builds of the application work fine on the same server, the only difference being that they were published with VS2017RC (2&3) and this is the first build with the fully released VS2017.

What does ErrorCode = '0x80004005 : 80008083. mean?

How do I fix it?

答:
I faced the same issue and I only had dotnet cor 2 installed on my server, so by installing this link you are able to run your code in other versions of dot net core. dont forget to restart IIS.
https://download.microsoft.com/download/6/A/2/6A21C555-B042-46EA-BBB4-368AACCB3E25/DotNetCore.1.0.8_1.1.5-WindowsHosting.exe</p>


问:
FreeRTOS timer Tick too fast in SAM L21 Xplained Pro
When I call vTaskDelay, the delay lasts half of the supposed time. I have traced back the problem and I see that the Tick rate value is the double of what it should be as defined in configTICK_RATE_HZ. I checked this using the tick hook to toggle a led and measuring the frequency with an oscilloscope.

I am configuring the Atmel SAM L21 Xplained pro A board (ATSAML21J18A), with Atmel Studio 7 and FreeRTOS v8.0.1, based on the files of an ASF example called "FreeRTOS tickless demo using OLED1 Xplained".

My CPU clock runs at 12MHz from the SYSTEM_CLOCK_SOURCE_OSC16M. The configured tick rate is 100 Hz, from a timer clocked from GLCK_O(CPU clock). However, when I change the CPU clock rate at 4MHz instead 12 MHz, the Tick rate is correct, so I guess I'm missing some configuration somewhere for the timer which runs the OS tick.

Here are some values of OS tick rate I get with different CPU clock rates:

CPU:  4 MHz - Tick rate: 100 Hz

CPU:  8 MHz - Tick rate: 548 Hz

CPU: 12 MHz - Tick rate: 218 Hz

CPU: 16 MHz - Tick rate: 548 Hz

CPU: 48 MHz - Tick rate: 2,25 kHz

Also, when I configure the OS tick timer clock source as the internal ultra low power oscilator ULPOSC32k running at 32kHz, the tick rate is correct, independently of the CPU clock frequency (100Hz).

Moreover, when I select tickless mode (1 or 2), even with the configuration that works well in tick mode, with the CPU at 4MHz and the tick interrupt generated from the Systick timer, I have the same problem, the dalay lasts half of what it should.

In FreeRTOSConfig I have:

```<code>#define configUSE_PREEMPTION                    1
#define configUSE_TICKLESS_IDLE                 0
#define configUSE_IDLE_HOOK                     0
#define configUSE_TICK_HOOK                     1
#define configPRIO_BITS                         2
#define configCPU_CLOCK_HZ                      ( system_gclk_gen_get_hz(GCLK_GENERATOR_0) )
#define configTICK_RATE_HZ                      ( ( portTickType ) 100 )
</code>```

The tick timer  configuration is:

```<code>void vPortSetupTimerInterrupt(void)
{
    // Struct for configuring TC
    struct tc_config tcconf;
    // Set up configuration values
    tc_get_config_defaults(&tcconf);
    tcconf.clock_source    = GCLK_GENERATOR_0;
    tcconf.counter_size    = TC_COUNTER_SIZE_32BIT;
    tcconf.run_in_standby  = true;
    tcconf.clock_prescaler = TC_CLOCK_PRESCALER_DIV1;
    tcconf.wave_generation = TC_WAVE_GENERATION_MATCH_FREQ;

    // Initialize the TC
    tc_init(&tc, TICK_TC, &tcconf);

    // Register and enable callback for freeRTOS tick handler
    tc_register_callback(&tc, (tc_callback_t) xPortSysTickHandler, TC_CALLBACK_CC_CHANNEL0);
    tc_enable_callback(&tc, TC_CALLBACK_CC_CHANNEL0);

    // Set top value equal to one os tick
    tc_set_top_value(&tc, TIMER_RELOAD_VALUE_ONE_TICK);

    // Enable the timer
    tc_enable(&tc);
}
</code>```

where TIMER_RELOAD_VALUE_ONE_TICK comes from:

```<code>//! Frequency of timer
#define TIMER_HZ                            ( configCPU_CLOCK_HZ )

//! Value per os tick of timer
#define TIMER_RELOAD_VALUE_ONE_TICK         ( TIMER_HZ / configTICK_RATE_HZ )

//!  Maximum value of timer
#define TIMER_MAX_COUNT                     ( 0xffffffff )

//! Maximum possible suppressed ticks with timer
#define TIMER_MAX_POSSIBLE_SUPPRESSED_TICKS ( TIMER_MAX_COUNT / TIMER_RELOAD_VALUE_ONE_TICK )
</code>```

I would appreciate very much any insight on this timer issue, which keeps me stuck. I have already checked two similar questions related to this:

STM32 SysTick counting twice as fast as it should

freertos tick factor 2 too fast on stm32f4xx

答:
Changing the Timer instance from TC4 to TC2 solves the issue.

```<code>  // Initialize the TC
    tc_init(&tc, TICK_TC, &tcconf);

  //! Timer/Counter instance to use as tick timer
  //#define TICK_TC TC4
  #define TICK_TC TC2
</code>```

Now it generates a correct 100 Hz tick independently of the CPU clock frequency configured.

However, I still have to see the implications this will have when I activate the low power modes, as it seems the TC4 is the only timer active in Power Domain 0
 (PD0)(the lowest power domain).

Body:
When I call vTaskDelay, the delay lasts half of the supposed time. I have traced back the problem and I see that the Tick rate value is the double of what it should be as defined in configTICK_RATE_HZ. I checked this using the tick hook to toggle a led and measuring the frequency with an oscilloscope.

I am configuring the Atmel SAM L21 Xplained pro A board (ATSAML21J18A), with Atmel Studio 7 and FreeRTOS v8.0.1, based on the files of an ASF example called "FreeRTOS tickless demo using OLED1 Xplained".

My CPU clock runs at 12MHz from the SYSTEM_CLOCK_SOURCE_OSC16M. The configured tick rate is 100 Hz, from a timer clocked from GLCK_O(CPU clock). However, when I change the CPU clock rate at 4MHz instead 12 MHz, the Tick rate is correct, so I guess I'm missing some configuration somewhere for the timer which runs the OS tick.

Here are some values of OS tick rate I get with different CPU clock rates:

CPU:  4 MHz - Tick rate: 100 Hz

CPU:  8 MHz - Tick rate: 548 Hz

CPU: 12 MHz - Tick rate: 218 Hz

CPU: 16 MHz - Tick rate: 548 Hz

CPU: 48 MHz - Tick rate: 2,25 kHz

Also, when I configure the OS tick timer clock source as the internal ultra low power oscilator ULPOSC32k running at 32kHz, the tick rate is correct, independently of the CPU clock frequency (100Hz).

Moreover, when I select tickless mode (1 or 2), even with the configuration that works well in tick mode, with the CPU at 4MHz and the tick interrupt generated from the Systick timer, I have the same problem, the dalay lasts half of what it should.

In FreeRTOSConfig I have:

#define configUSE_PREEMPTION                    1
#define configUSE_TICKLESS_IDLE                 0
#define configUSE_IDLE_HOOK                     0
#define configUSE_TICK_HOOK                     1
#define configPRIO_BITS                         2
#define configCPU_CLOCK_HZ                      ( system_gclk_gen_get_hz(GCLK_GENERATOR_0) )
#define configTICK_RATE_HZ                      ( ( portTickType ) 100 )

The tick timer  configuration is:

void vPortSetupTimerInterrupt(void)
{
    // Struct for configuring TC
    struct tc_config tcconf;
    // Set up configuration values
    tc_get_config_defaults(&tcconf);
    tcconf.clock_source    = GCLK_GENERATOR_0;
    tcconf.counter_size    = TC_COUNTER_SIZE_32BIT;
    tcconf.run_in_standby  = true;
    tcconf.clock_prescaler = TC_CLOCK_PRESCALER_DIV1;
    tcconf.wave_generation = TC_WAVE_GENERATION_MATCH_FREQ;

    // Initialize the TC
    tc_init(&tc, TICK_TC, &tcconf);

    // Register and enable callback for freeRTOS tick handler
    tc_register_callback(&tc, (tc_callback_t) xPortSysTickHandler, TC_CALLBACK_CC_CHANNEL0);
    tc_enable_callback(&tc, TC_CALLBACK_CC_CHANNEL0);

    // Set top value equal to one os tick
    tc_set_top_value(&tc, TIMER_RELOAD_VALUE_ONE_TICK);

    // Enable the timer
    tc_enable(&tc);
}

where TIMER_RELOAD_VALUE_ONE_TICK comes from:

//! Frequency of timer
#define TIMER_HZ                            ( configCPU_CLOCK_HZ )

//! Value per os tick of timer
#define TIMER_RELOAD_VALUE_ONE_TICK         ( TIMER_HZ / configTICK_RATE_HZ )

//!  Maximum value of timer
#define TIMER_MAX_COUNT                     ( 0xffffffff )

//! Maximum possible suppressed ticks with timer
#define TIMER_MAX_POSSIBLE_SUPPRESSED_TICKS ( TIMER_MAX_COUNT / TIMER_RELOAD_VALUE_ONE_TICK )

I would appreciate very much any insight on this timer issue, which keeps me stuck. I have already checked two similar questions related to this:

STM32 SysTick counting twice as fast as it should

freertos tick factor 2 too fast on stm32f4xx

Body:
Changing the Timer instance from TC4 to TC2 solves the issue.

  // Initialize the TC
    tc_init(&tc, TICK_TC, &tcconf);

  //! Timer/Counter instance to use as tick timer
  //#define TICK_TC TC4
  #define TICK_TC TC2

Now it generates a correct 100 Hz tick independently of the CPU clock frequency configured.

However, I still have to see the implications this will have when I activate the low power modes, as it seems the TC4 is the only timer active in Power Domain 0
 (PD0)(the lowest power domain).


问:
Read most recent e-mail from outlook using PowerShell
I am trying to read my Outlook e-mail with the subject line "Automation" and process further with custom script. The below script reads the e-mail with the subject line but it reads the entire count of e-mail with the subject "Automation".

I want to be able to read only the most recent e-mail and process only that specific e-mail content and mark the e-mail as unread. And then read the next new e-mail with the same subject and process only the specific content.

```<code>Add-type -assembly "Microsoft.Office.Interop.Outlook" | out-null
$olFolders = "Microsoft.Office.Interop.Outlook.olDefaultFolders" -as [type]
$outlook = new-object -comobject outlook.application
$namespace = $outlook.GetNameSpace("MAPI")
$folder = $namespace.getDefaultFolder($olFolders::olFolderInBox)
$folder.items | where { $_.subject -match 'Automation' } | Select-Object -Property body
</code>```

Let's say if I have 10 new e-mail with subject "Automation" process 10th e-mail and mark as read and continue to process from 9 to 1.

How to achieve this?

答:
Just got to use a foreach-object, you can mark the mail as read/unread by modifying the unread property of a mail item ( https://msdn.microsoft.com/en-us/library/microsoft.office.interop.outlook._mailitem.unread.aspx )

```<code>$outlook = new-object -comobject outlook.application
$namespace = $outlook.GetNameSpace("MAPI")
$folder=$namespace.GetDefaultFolder(6)
$folder.Items |
    ?{$_.subject -match "automation" } |
    sort receivedtime -desc |
    %{
         echo $_.body #do stuff with body
         $_.Unread=$false #mark as read
     }
</code>```

After your comment you can verify if your outlook version expose the unread property with :
$folder.Items |select -first 1 | get-member
you should find the following property :

UnRead                            Property   bool UnRead () {get} {set}

Body:
I am trying to read my Outlook e-mail with the subject line "Automation" and process further with custom script. The below script reads the e-mail with the subject line but it reads the entire count of e-mail with the subject "Automation".

I want to be able to read only the most recent e-mail and process only that specific e-mail content and mark the e-mail as unread. And then read the next new e-mail with the same subject and process only the specific content.

Add-type -assembly "Microsoft.Office.Interop.Outlook" | out-null
$olFolders = "Microsoft.Office.Interop.Outlook.olDefaultFolders" -as [type]
$outlook = new-object -comobject outlook.application
$namespace = $outlook.GetNameSpace("MAPI")
$folder = $namespace.getDefaultFolder($olFolders::olFolderInBox)
$folder.items | where { $_.subject -match 'Automation' } | Select-Object -Property body

Let's say if I have 10 new e-mail with subject "Automation" process 10th e-mail and mark as read and continue to process from 9 to 1.

How to achieve this?

Body:
Just got to use a foreach-object, you can mark the mail as read/unread by modifying the unread property of a mail item ( https://msdn.microsoft.com/en-us/library/microsoft.office.interop.outlook._mailitem.unread.aspx )

$outlook = new-object -comobject outlook.application
$namespace = $outlook.GetNameSpace("MAPI")
$folder=$namespace.GetDefaultFolder(6)
$folder.Items |
    ?{$_.subject -match "automation" } |
    sort receivedtime -desc |
    %{
         echo $_.body #do stuff with body
         $_.Unread=$false #mark as read
     }

After your comment you can verify if your outlook version expose the unread property with :
$folder.Items |select -first 1 | get-member
you should find the following property :

UnRead                            Property   bool UnRead () {get} {set}


问:
How do I write a for loop in C
Why does the following code loop 5000 times instead of the 5 times I expect?</p>

```<code>int height = 5;

for (int height; height > 0; height -= 1){
    printf('Something')  }
}
</code>```

答:
but when I run it, it does not iterate through the loop 5 times but rather something like 5000.

That's because height declared in the for loop shadows the one declared outside. So you are
effectively using uninitialized height, which is potentially undefined behaviour.

You can leave out the declaration in order to use the previously declared value:

```<code>int height = 5;

for (; height > 0; height -= 1) {
    printf("Something");
}
</code>```

If you don't want to change height, you can use a temporary:

```<code>int height = 5;

for (int x = height; x > 0; x -= 1) {
    printf("Something");
}
</code>```

which would leave height unchanged.

Also note that values in single quotes are multi-byte chars and are not strings. So you can't pass 'Something' to printf.

Title: How do I write a for loop in C

Body:
Why does the following code loop 5000 times instead of the 5 times I expect?

int height = 5;

for (int height; height > 0; height -= 1){
    printf('Something')  }
}

Body:
but when I run it, it does not iterate through the loop 5 times but rather something like 5000.

That's because height declared in the for loop shadows the one declared outside. So you are
effectively using uninitialized height, which is potentially undefined behaviour.

You can leave out the declaration in order to use the previously declared value:

int height = 5;

for (; height > 0; height -= 1) {
    printf("Something");
}

If you don't want to change height, you can use a temporary:

int height = 5;

for (int x = height; x > 0; x -= 1) {
    printf("Something");
}

which would leave height unchanged.

Also note that values in single quotes are multi-byte chars and are not strings. So you can't pass 'Something' to printf.


问:
Manifest merger error
I am getting this error when i build my project

Here is my error image

```<code>Error:Execution failed for task ':app:processDebugManifest'.
</code>```

Manifest merger failed : uses-sdk:minSdkVersion 11 cannot be smaller than version 14 declared in library [com.google.android.gms:play-services-ads:11.0.4] /home/nicvaldy/Desktop/android/app/build/intermediates/exploded-aar/com.google.android.gms/play-services-ads/11.0.4/AndroidManifest.xml
      Suggestion: use tools:overrideLibrary="com.google.android.gms.ads.impl" to force usage

答: change minSdkVersion to 14 in your build.gradle file

Title: Manifest merger error

Body:
I am getting this error when i build my project

Here is my error image

Error:Execution failed for task ':app:processDebugManifest'.

Manifest merger failed : uses-sdk:minSdkVersion 11 cannot be smaller than version 14 declared in library [com.google.android.gms:play-services-ads:11.0.4] /home/nicvaldy/Desktop/android/app/build/intermediates/exploded-aar/com.google.android.gms/play-services-ads/11.0.4/AndroidManifest.xml
      Suggestion: use tools:overrideLibrary="com.google.android.gms.ads.impl" to force usage


问:
Convolutional Neural Network Training
I have a question regarding convolutional neural network (CNN) training.

I have managed to train a network using tensorflow that takes an input image (1600 pixels) and output one of three classes that matches it.

Testing the network with variations of the trained classes is giving good results. However; when I give it a different -fourth- image (does not contain any of the trained 3 image), it always returns a random match to one of the classes.

My question is, how can I train a network to classify that the image does not belong to either of the three trained images? A similar example, if i trained a network against the mnist database and then a gave it the character "A" or "B". Is there a way to discriminate that the input does not belong to either of the classes?

Thank you

答: Convolutional Neural Network (CNN) predicts the result from the defined classes after training. CNN always return from one of the classes regardless of accuracy. I have faced similar problem, what you can do is to check for accuracy value. If the accuracy is below some threshold value then it's belong to none category. Hope this helps.</p>

Title: Convolutional Neural Network Training


答:
Just add in your dependencies

For latest Gradle:
implementation 'com.android.support:support-v13:27.0.1'

For older one
compile 'com.android.support:support-v13:27.0.1'

Title: Manifest merger error


问:
how to use a service inside another service in symfony 2.6
I have a service setup in symfony 2.6 by name ge_lib and it looks like below

```<code>    ge_lib:
    class: GE\RestBundle\Services\GELib
    arguments: [@session, @doctrine.orm.entity_manager, @manage_ge_proc]
</code>```

inside GELib.php I have a requirement to use a function from another service manage_ge_proc

```<code>    manage_ge_proc:
    class: GE\RestBundle\Services\GEManageProcedure
    arguments: [@doctrine.orm.entity_manager, @manage_ge_native_query]
</code>```

if I try to use it this way, it is not working

```<code>$emailInv = $this->get('manage_ge_proc');
$sendStatus = $emailInv->pSendGeneralEmail(.....);
</code>```

It gives error saying that unable to find any get function by that name. generally this -> $this->get('manage_ge_proc');works in any controller.But how do i use it in service?.

I tried $this->getContainer()->get('manage_ge_proc'); but it did not work.

答:
This call is fetching service from  DI container, which you dont have in your service

```<code>$this->get('manage_ge_proc');
</code>```

It works in controller because DI container is automatically injected there.

Since you have this line in you services.yml, which tells Symfony to inject @manage_de_proc service into ge_lib constructor

```<code>arguments: [@session, @doctrine.orm.entity_manager, @manage_ge_proc]
</code>```

you should be able to pick @manage_ge_proc from constructor like this:

```<code>public function __construct(
    Session $session,
    EntityManager $entityManager,
    GEManageProcedure $manageGeProc
)
{
    //... whatever you do in your constructor
    $this->manageGeProc = $manageGeProc;
}
</code>```

Body:
I have a service setup in symfony 2.6 by name ge_lib and it looks like below

    ge_lib:
    class: GE\RestBundle\Services\GELib
    arguments: [@session, @doctrine.orm.entity_manager, @manage_ge_proc]

inside GELib.php I have a requirement to use a function from another service manage_ge_proc

    manage_ge_proc:
    class: GE\RestBundle\Services\GEManageProcedure
    arguments: [@doctrine.orm.entity_manager, @manage_ge_native_query]

if I try to use it this way, it is not working

$emailInv = $this->get('manage_ge_proc');
$sendStatus = $emailInv->pSendGeneralEmail(.....);

It gives error saying that unable to find any get function by that name. generally this -> $this->get('manage_ge_proc');works in any controller.But how do i use it in service?.

I tried $this->getContainer()->get('manage_ge_proc'); but it did not work.

Body:
This call is fetching service from  DI container, which you dont have in your service

$this->get('manage_ge_proc');

It works in controller because DI container is automatically injected there.

Since you have this line in you services.yml, which tells Symfony to inject @manage_de_proc service into ge_lib constructor

arguments: [@session, @doctrine.orm.entity_manager, @manage_ge_proc]

you should be able to pick @manage_ge_proc from constructor like this:

public function __construct(
    Session $session,
    EntityManager $entityManager,
    GEManageProcedure $manageGeProc
)
{
    //... whatever you do in your constructor
    $this->manageGeProc = $manageGeProc;
}

ContentLicense: CC BY-SA 4.0


问:
Convert the date time stamp to local epoch datatime
Assume this is my date time stamp list:

```<code>[datetime.datetime(2017, 11, 17, 9, 33, 11), datetime.datetime(2017, 11, 17, 9, 33, 36), datetime.datetime(2017, 11, 17, 9, 33, 48)]
</code>```

A lot of examples have been given for converting these values to epoch, but the values are in GMT.
How do we convert it to Epoch Local time?

To put it in simpler words. The general epoch conversion coverts the given date into epoch considering that the datetime given is in GMT. But the given date time is localtime!

Body:
Assume this is my date time stamp list:

[datetime.datetime(2017, 11, 17, 9, 33, 11), datetime.datetime(2017, 11, 17, 9, 33, 36), datetime.datetime(2017, 11, 17, 9, 33, 48)]

A lot of examples have been given for converting these values to epoch, but the values are in GMT.
How do we convert it to Epoch Local time?

To put it in simpler words. The general epoch conversion coverts the given date into epoch considering that the datetime given is in GMT. But the given date time is localtime!

Body:
>>> x = datetime.datetime(2017, 11, 17, 9, 33, 36)
>>> x.timestamp()
1510882416.0
>>> x.ctime()
'Fri Nov 17 09:33:36 2017'


问:
Running outlook interlop by an application started with process.start
I know title is a little confusing.
So my main problem is this:

I have an application which updates an another app.And after update function ends it starts the other app with process.start method

```<code>Process.Start(@"C:\Program Files (x86)\XMLMailService\XMLMailWF.exe");
</code>```

and this second updated program sends a mail with simple outlook interlop

```<code>Microsoft.Office.Interop.Outlook.Application OutlookObject = new Microsoft.Office.Interop.Outlook.Application();
                Microsoft.Office.Interop.Outlook.MailItem MailObject = (Microsoft.Office.Interop.Outlook.MailItem)(OutlookObject.CreateItem(Microsoft.Office.Interop.Outlook.OlItemType.olMailItem));
                MailObject.To = txtkime.Text;
                MailObject.Subject = psubj;
                MailObject.Importance = Microsoft.Office.Interop.Outlook.OlImportance.olImportanceNormal;
                MailObject.HTMLBody = pbody;
                MailObject.Attachments.Add(pdfyolu);
                MailObject.Send();
</code>```

Actually problem is not code related. But outlook code works like a charm when i start the app with double click. But gives me  error.

So why outlook interlop gives error when app starts with process.start.

Edit: Error translation=>

Retrieving the COM class factory for component with CLSID {0006F03A-0000-0000-C000-000000000046} failed due to the following error: 80080005 Server execution failed (Exception from HRESULT: 0x80080005 (CO_E_SERVER_EXEC_FAILURE)).

答:
For anyone has the same situation I found the solution.

First app is downloading zip files and unzipping them. After unzipping and making adjustments app starts the downloaded app with process.start("...") method.

So the problems here
1) First app needs admin priviliges for its purposes. And when it uses Process.Start it launches the second app with admin priviliges too.
2)Second app is sending mails from outlook client as a secondary function. Outlook does not like automation apps. When you try to use outlook interlop as a admin it gives you COM error. Because outlook needs to be same privilige level with the app.Regular users use outlook without admin priviliges because outlook's search function does not work in administrator mode(god knows why)

There is 2 solutions.

1) You can start the first app without admin priviliges. And try to start another instance of the app with admin priviliges which returns some kind of data to tell the first instance that it finished it job. Then first instance can use process.start without admin rights.
But this is not suitable for me because first app is installed at a lot of computers and I am a lazy person. So ı choose the hard way.
2)You can restart the second app without admin rights. (Which is tricky)

So I used this code for checking for admin rights like described in here and restart the app

```<code> static class Program
{

    public static bool IsAdministrator()
    {
        var identity = WindowsIdentity.GetCurrent();
        var principal = new WindowsPrincipal(identity);
        return principal.IsInRole(WindowsBuiltInRole.Administrator);
    }

    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
        if (IsAdministrator())
        {
            UserRights.RunAsDesktopUser(@"C:\Program Files (x86)\XMLMailService\XMLMailWF.exe");
            Form1.benciktim = true;
            Application.Exit();
        }
        else
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());
        }

    }
}
</code>```

and used this brilliant piece of code as described in here

```<code>    public static class UserRights
{

    public static void RunAsDesktopUser(string fileName)
    {
        if (string.IsNullOrWhiteSpace(fileName))
            throw new ArgumentException("Value cannot be null or whitespace.", nameof(fileName));

        // To start process as shell user you will need to carry out these steps:
        // 1. Enable the SeIncreaseQuotaPrivilege in your current token
        // 2. Get an HWND representing the desktop shell (GetShellWindow)
        // 3. Get the Process ID(PID) of the process associated with that window(GetWindowThreadProcessId)
        // 4. Open that process(OpenProcess)
        // 5. Get the access token from that process (OpenProcessToken)
        // 6. Make a primary token with that token(DuplicateTokenEx)
        // 7. Start the new process with that primary token(CreateProcessWithTokenW)

        var hProcessToken = IntPtr.Zero;
        // Enable SeIncreaseQuotaPrivilege in this process.  (This won't work if current process is not elevated.)
        try
        {
            var process = GetCurrentProcess();
            if (!OpenProcessToken(process, 0x0020, ref hProcessToken))
                return;

            var tkp = new TOKEN_PRIVILEGES
            {
                PrivilegeCount = 1,
                Privileges = new LUID_AND_ATTRIBUTES[1]
            };

            if (!LookupPrivilegeValue(null, "SeIncreaseQuotaPrivilege", ref tkp.Privileges[0].Luid))
                return;

            tkp.Privileges[0].Attributes = 0x00000002;

            if (!AdjustTokenPrivileges(hProcessToken, false, ref tkp, 0, IntPtr.Zero, IntPtr.Zero))
                return;
        }
        finally
        {
            CloseHandle(hProcessToken);
        }

        // Get an HWND representing the desktop shell.
        // CAVEATS:  This will fail if the shell is not running (crashed or terminated), or the default shell has been
        // replaced with a custom shell.  This also won't return what you probably want if Explorer has been terminated and
        // restarted elevated.
        var hwnd = GetShellWindow();
        if (hwnd == IntPtr.Zero)
            return;

        var hShellProcess = IntPtr.Zero;
        var hShellProcessToken = IntPtr.Zero;
        var hPrimaryToken = IntPtr.Zero;
        try
        {
            // Get the PID of the desktop shell process.
            uint dwPID;
            if (GetWindowThreadProcessId(hwnd, out dwPID) == 0)
                return;

            // Open the desktop shell process in order to query it (get the token)
            hShellProcess = OpenProcess(ProcessAccessFlags.QueryInformation, false, dwPID);
            if (hShellProcess == IntPtr.Zero)
                return;

            // Get the process token of the desktop shell.
            if (!OpenProcessToken(hShellProcess, 0x0002, ref hShellProcessToken))
                return;

            var dwTokenRights = 395U;

            // Duplicate the shell's process token to get a primary token.
            // Based on experimentation, this is the minimal set of rights required for CreateProcessWithTokenW (contrary to current documentation).
            if (!DuplicateTokenEx(hShellProcessToken, dwTokenRights, IntPtr.Zero, SECURITY_IMPERSONATION_LEVEL.SecurityImpersonation, TOKEN_TYPE.TokenPrimary, out hPrimaryToken))
                return;

            // Start the target process with the new token.
            var si = new STARTUPINFO();
            var pi = new PROCESS_INFORMATION();
            if (!CreateProcessWithTokenW(hPrimaryToken, 0, fileName, "", 0, IntPtr.Zero, Path.GetDirectoryName(fileName), ref si, out pi))
                return;
        }
        finally
        {
            CloseHandle(hShellProcessToken);
            CloseHandle(hPrimaryToken);
            CloseHandle(hShellProcess);
        }

    }

    #region Interop

    private struct TOKEN_PRIVILEGES
    {
        public UInt32 PrivilegeCount;
        [MarshalAs(UnmanagedType.ByValArray, SizeConst = 1)]
        public LUID_AND_ATTRIBUTES[] Privileges;
    }

    [StructLayout(LayoutKind.Sequential, Pack = 4)]
    private struct LUID_AND_ATTRIBUTES
    {
        public LUID Luid;
        public UInt32 Attributes;
    }

    [StructLayout(LayoutKind.Sequential)]
    private struct LUID
    {
        public uint LowPart;
        public int HighPart;
    }

    [Flags]
    private enum ProcessAccessFlags : uint
    {
        All = 0x001F0FFF,
        Terminate = 0x00000001,
        CreateThread = 0x00000002,
        VirtualMemoryOperation = 0x00000008,
        VirtualMemoryRead = 0x00000010,
        VirtualMemoryWrite = 0x00000020,
        DuplicateHandle = 0x00000040,
        CreateProcess = 0x000000080,
        SetQuota = 0x00000100,
        SetInformation = 0x00000200,
        QueryInformation = 0x00000400,
        QueryLimitedInformation = 0x00001000,
        Synchronize = 0x00100000
    }

    private enum SECURITY_IMPERSONATION_LEVEL
    {
        SecurityAnonymous,
        SecurityIdentification,
        SecurityImpersonation,
        SecurityDelegation
    }

    private enum TOKEN_TYPE
    {
        TokenPrimary = 1,
        TokenImpersonation
    }

    [StructLayout(LayoutKind.Sequential)]
    private struct PROCESS_INFORMATION
    {
        public IntPtr hProcess;
        public IntPtr hThread;
        public int dwProcessId;
        public int dwThreadId;
    }

    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
    private struct STARTUPINFO
    {
        public Int32 cb;
        public string lpReserved;
        public string lpDesktop;
        public string lpTitle;
        public Int32 dwX;
        public Int32 dwY;
        public Int32 dwXSize;
        public Int32 dwYSize;
        public Int32 dwXCountChars;
        public Int32 dwYCountChars;
        public Int32 dwFillAttribute;
        public Int32 dwFlags;
        public Int16 wShowWindow;
        public Int16 cbReserved2;
        public IntPtr lpReserved2;
        public IntPtr hStdInput;
        public IntPtr hStdOutput;
        public IntPtr hStdError;
    }

    [DllImport("kernel32.dll", ExactSpelling = true)]
    private static extern IntPtr GetCurrentProcess();

    [DllImport("advapi32.dll", ExactSpelling = true, SetLastError = true)]
    private static extern bool OpenProcessToken(IntPtr h, int acc, ref IntPtr phtok);

    [DllImport("advapi32.dll", SetLastError = true)]
    private static extern bool LookupPrivilegeValue(string host, string name, ref LUID pluid);

    [DllImport("advapi32.dll", ExactSpelling = true, SetLastError = true)]
    private static extern bool AdjustTokenPrivileges(IntPtr htok, bool disall, ref TOKEN_PRIVILEGES newst, int len, IntPtr prev, IntPtr relen);

    [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    [return: MarshalAs(UnmanagedType.Bool)]
    private static extern bool CloseHandle(IntPtr hObject);

    [DllImport("user32.dll")]
    private static extern IntPtr GetShellWindow();

    [DllImport("user32.dll", SetLastError = true)]
    private static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);

    [DllImport("kernel32.dll", SetLastError = true)]
    private static extern IntPtr OpenProcess(ProcessAccessFlags processAccess, bool bInheritHandle, uint processId);

    [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    private static extern bool DuplicateTokenEx(IntPtr hExistingToken, uint dwDesiredAccess, IntPtr lpTokenAttributes, SECURITY_IMPERSONATION_LEVEL impersonationLevel, TOKEN_TYPE tokenType, out IntPtr phNewToken);

    [DllImport("advapi32", SetLastError = true, CharSet = CharSet.Unicode)]
    private static extern bool CreateProcessWithTokenW(IntPtr hToken, int dwLogonFlags, string lpApplicationName, string lpCommandLine, int dwCreationFlags, IntPtr lpEnvironment, string lpCurrentDirectory, [In] ref STARTUPINFO lpStartupInfo, out PROCESS_INFORMATION lpProcessInformation);

    #endregion

}
</code>```

Body:
I know title is a little confusing.
So my main problem is this:

I have an application which updates an another app.And after update function ends it starts the other app with process.start method

Process.Start(@"C:\Program Files (x86)\XMLMailService\XMLMailWF.exe");

and this second updated program sends a mail with simple outlook interlop

Microsoft.Office.Interop.Outlook.Application OutlookObject = new Microsoft.Office.Interop.Outlook.Application();
                Microsoft.Office.Interop.Outlook.MailItem MailObject = (Microsoft.Office.Interop.Outlook.MailItem)(OutlookObject.CreateItem(Microsoft.Office.Interop.Outlook.OlItemType.olMailItem));
                MailObject.To = txtkime.Text;
                MailObject.Subject = psubj;
                MailObject.Importance = Microsoft.Office.Interop.Outlook.OlImportance.olImportanceNormal;
                MailObject.HTMLBody = pbody;
                MailObject.Attachments.Add(pdfyolu);
                MailObject.Send();

Actually problem is not code related. But outlook code works like a charm when i start the app with double click. But gives me  error.

So why outlook interlop gives error when app starts with process.start.

Edit: Error translation=>

Retrieving the COM class factory for component with CLSID {0006F03A-0000-0000-C000-000000000046} failed due to the following error: 80080005 Server execution failed (Exception from HRESULT: 0x80080005 (CO_E_SERVER_EXEC_FAILURE)).

Body:
For anyone has the same situation I found the solution.

First app is downloading zip files and unzipping them. After unzipping and making adjustments app starts the downloaded app with process.start("...") method.

So the problems here
1) First app needs admin priviliges for its purposes. And when it uses Process.Start it launches the second app with admin priviliges too.
2)Second app is sending mails from outlook client as a secondary function. Outlook does not like automation apps. When you try to use outlook interlop as a admin it gives you COM error. Because outlook needs to be same privilige level with the app.Regular users use outlook without admin priviliges because outlook's search function does not work in administrator mode(god knows why)

There is 2 solutions.

1) You can start the first app without admin priviliges. And try to start another instance of the app with admin priviliges which returns some kind of data to tell the first instance that it finished it job. Then first instance can use process.start without admin rights.
But this is not suitable for me because first app is installed at a lot of computers and I am a lazy person. So ı choose the hard way.
2)You can restart the second app without admin rights. (Which is tricky)

So I used this code for checking for admin rights like described in here and restart the app

 static class Program
{

    public static bool IsAdministrator()
    {
        var identity = WindowsIdentity.GetCurrent();
        var principal = new WindowsPrincipal(identity);
        return principal.IsInRole(WindowsBuiltInRole.Administrator);
    }

    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
        if (IsAdministrator())
        {
            UserRights.RunAsDesktopUser(@"C:\Program Files (x86)\XMLMailService\XMLMailWF.exe");
            Form1.benciktim = true;
            Application.Exit();
        }
        else
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());
        }

    }
}

and used this brilliant piece of code as described in here

    public static class UserRights
{

    public static void RunAsDesktopUser(string fileName)
    {
        if (string.IsNullOrWhiteSpace(fileName))
            throw new ArgumentException("Value cannot be null or whitespace.", nameof(fileName));

        // To start process as shell user you will need to carry out these steps:
        // 1. Enable the SeIncreaseQuotaPrivilege in your current token
        // 2. Get an HWND representing the desktop shell (GetShellWindow)
        // 3. Get the Process ID(PID) of the process associated with that window(GetWindowThreadProcessId)
        // 4. Open that process(OpenProcess)
        // 5. Get the access token from that process (OpenProcessToken)
        // 6. Make a primary token with that token(DuplicateTokenEx)
        // 7. Start the new process with that primary token(CreateProcessWithTokenW)

        var hProcessToken = IntPtr.Zero;
        // Enable SeIncreaseQuotaPrivilege in this process.  (This won't work if current process is not elevated.)
        try
        {
            var process = GetCurrentProcess();
            if (!OpenProcessToken(process, 0x0020, ref hProcessToken))
                return;

            var tkp = new TOKEN_PRIVILEGES
            {
                PrivilegeCount = 1,
                Privileges = new LUID_AND_ATTRIBUTES[1]
            };

            if (!LookupPrivilegeValue(null, "SeIncreaseQuotaPrivilege", ref tkp.Privileges[0].Luid))
                return;

            tkp.Privileges[0].Attributes = 0x00000002;

            if (!AdjustTokenPrivileges(hProcessToken, false, ref tkp, 0, IntPtr.Zero, IntPtr.Zero))
                return;
        }
        finally
        {
            CloseHandle(hProcessToken);
        }

        // Get an HWND representing the desktop shell.
        // CAVEATS:  This will fail if the shell is not running (crashed or terminated), or the default shell has been
        // replaced with a custom shell.  This also won't return what you probably want if Explorer has been terminated and
        // restarted elevated.
        var hwnd = GetShellWindow();
        if (hwnd == IntPtr.Zero)
            return;

        var hShellProcess = IntPtr.Zero;
        var hShellProcessToken = IntPtr.Zero;
        var hPrimaryToken = IntPtr.Zero;
        try
        {
            // Get the PID of the desktop shell process.
            uint dwPID;
            if (GetWindowThreadProcessId(hwnd, out dwPID) == 0)
                return;

            // Open the desktop shell process in order to query it (get the token)
            hShellProcess = OpenProcess(ProcessAccessFlags.QueryInformation, false, dwPID);
            if (hShellProcess == IntPtr.Zero)
                return;

            // Get the process token of the desktop shell.
            if (!OpenProcessToken(hShellProcess, 0x0002, ref hShellProcessToken))
                return;

            var dwTokenRights = 395U;

            // Duplicate the shell's process token to get a primary token.
            // Based on experimentation, this is the minimal set of rights required for CreateProcessWithTokenW (contrary to current documentation).
            if (!DuplicateTokenEx(hShellProcessToken, dwTokenRights, IntPtr.Zero, SECURITY_IMPERSONATION_LEVEL.SecurityImpersonation, TOKEN_TYPE.TokenPrimary, out hPrimaryToken))
                return;

            // Start the target process with the new token.
            var si = new STARTUPINFO();
            var pi = new PROCESS_INFORMATION();
            if (!CreateProcessWithTokenW(hPrimaryToken, 0, fileName, "", 0, IntPtr.Zero, Path.GetDirectoryName(fileName), ref si, out pi))
                return;
        }
        finally
        {
            CloseHandle(hShellProcessToken);
            CloseHandle(hPrimaryToken);
            CloseHandle(hShellProcess);
        }

    }

    #region Interop

    private struct TOKEN_PRIVILEGES
    {
        public UInt32 PrivilegeCount;
        [MarshalAs(UnmanagedType.ByValArray, SizeConst = 1)]
        public LUID_AND_ATTRIBUTES[] Privileges;
    }

    [StructLayout(LayoutKind.Sequential, Pack = 4)]
    private struct LUID_AND_ATTRIBUTES
    {
        public LUID Luid;
        public UInt32 Attributes;
    }

    [StructLayout(LayoutKind.Sequential)]
    private struct LUID
    {
        public uint LowPart;
        public int HighPart;
    }

    [Flags]
    private enum ProcessAccessFlags : uint
    {
        All = 0x001F0FFF,
        Terminate = 0x00000001,
        CreateThread = 0x00000002,
        VirtualMemoryOperation = 0x00000008,
        VirtualMemoryRead = 0x00000010,
        VirtualMemoryWrite = 0x00000020,
        DuplicateHandle = 0x00000040,
        CreateProcess = 0x000000080,
        SetQuota = 0x00000100,
        SetInformation = 0x00000200,
        QueryInformation = 0x00000400,
        QueryLimitedInformation = 0x00001000,
        Synchronize = 0x00100000
    }

    private enum SECURITY_IMPERSONATION_LEVEL
    {
        SecurityAnonymous,
        SecurityIdentification,
        SecurityImpersonation,
        SecurityDelegation
    }

    private enum TOKEN_TYPE
    {
        TokenPrimary = 1,
        TokenImpersonation
    }

    [StructLayout(LayoutKind.Sequential)]
    private struct PROCESS_INFORMATION
    {
        public IntPtr hProcess;
        public IntPtr hThread;
        public int dwProcessId;
        public int dwThreadId;
    }

    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
    private struct STARTUPINFO
    {
        public Int32 cb;
        public string lpReserved;
        public string lpDesktop;
        public string lpTitle;
        public Int32 dwX;
        public Int32 dwY;
        public Int32 dwXSize;
        public Int32 dwYSize;
        public Int32 dwXCountChars;
        public Int32 dwYCountChars;
        public Int32 dwFillAttribute;
        public Int32 dwFlags;
        public Int16 wShowWindow;
        public Int16 cbReserved2;
        public IntPtr lpReserved2;
        public IntPtr hStdInput;
        public IntPtr hStdOutput;
        public IntPtr hStdError;
    }

    [DllImport("kernel32.dll", ExactSpelling = true)]
    private static extern IntPtr GetCurrentProcess();

    [DllImport("advapi32.dll", ExactSpelling = true, SetLastError = true)]
    private static extern bool OpenProcessToken(IntPtr h, int acc, ref IntPtr phtok);

    [DllImport("advapi32.dll", SetLastError = true)]
    private static extern bool LookupPrivilegeValue(string host, string name, ref LUID pluid);

    [DllImport("advapi32.dll", ExactSpelling = true, SetLastError = true)]
    private static extern bool AdjustTokenPrivileges(IntPtr htok, bool disall, ref TOKEN_PRIVILEGES newst, int len, IntPtr prev, IntPtr relen);

    [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    [return: MarshalAs(UnmanagedType.Bool)]
    private static extern bool CloseHandle(IntPtr hObject);

    [DllImport("user32.dll")]
    private static extern IntPtr GetShellWindow();

    [DllImport("user32.dll", SetLastError = true)]
    private static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);

    [DllImport("kernel32.dll", SetLastError = true)]
    private static extern IntPtr OpenProcess(ProcessAccessFlags processAccess, bool bInheritHandle, uint processId);

    [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    private static extern bool DuplicateTokenEx(IntPtr hExistingToken, uint dwDesiredAccess, IntPtr lpTokenAttributes, SECURITY_IMPERSONATION_LEVEL impersonationLevel, TOKEN_TYPE tokenType, out IntPtr phNewToken);

    [DllImport("advapi32", SetLastError = true, CharSet = CharSet.Unicode)]
    private static extern bool CreateProcessWithTokenW(IntPtr hToken, int dwLogonFlags, string lpApplicationName, string lpCommandLine, int dwCreationFlags, IntPtr lpEnvironment, string lpCurrentDirectory, [In] ref STARTUPINFO lpStartupInfo, out PROCESS_INFORMATION lpProcessInformation);

    #endregion

}


答:
You have to redefine height variable with user input in your loop definition.

You can do it like this:

```<code>int user_input;
scanf("%d", &user_input);

for (int height = user_input; height > 0; height -= 1){
    printf("height = %d\n", height);
}
</code>```

If user enters "5", this code will print this:

```<code>height = 5
height = 4
height = 3
height = 2
height = 1
</code>```

Title: How do I write a for loop in C

Body:
You have to redefine height variable with user input in your loop definition.

You can do it like this:

int user_input;
scanf("%d", &user_input);

for (int height = user_input; height > 0; height -= 1){
    printf("height = %d\n", height);
}

If user enters "5", this code will print this:

height = 5
height = 4
height = 3
height = 2
height = 1


问:
What is the DSL for Jenkins downstream (post build action) job?
I would like to do this, but in the Jenkins DSL:

If found somewhere this, but it's not working:

```<code>job('ps-first') {
    steps { shell('echo "landing"') }
    postBuildSteps { ...run other job here... }
        configure {
            it <<
                    'runPostStepsIfResult' { name('SUCCESS') }
        }
}
</code>```

答:
As explained in https://jenkinsci.github.io/job-dsl-plugin/#path/freeStyleJob-publishers-downstream</p>

```<code>job('ps-first') {
...
    publishers {
        downstream('ps-archive', 'SUCCESS')
    }
}
</code>```

Body:
I would like to do this, but in the Jenkins DSL:

If found somewhere this, but it's not working:

job('ps-first') {
    steps { shell('echo "landing"') }
    postBuildSteps { ...run other job here... }
        configure {
            it <<
                    'runPostStepsIfResult' { name('SUCCESS') }
        }
}

Body:
As explained in https://jenkinsci.github.io/job-dsl-plugin/#path/freeStyleJob-publishers-downstream

job('ps-first') {
...
    publishers {
        downstream('ps-archive', 'SUCCESS')
    }
}


问:
Mysql order by column when not empty then order by other column
I would like some help that has had me stumped for two days. I need to retrieve data from a database and order it by column1 when it isn't empty and then the rest of the result by column2

```<code>column1      column2
1            11
2            12
3            13
             14
             15
             16
</code>```

Required result

```<code>1,2,3,14,15,16
</code>```

I've tried numerous approaches, my latest failed attempt being

```<code>$SQL = "SELECT * FROM table ORDER BY COALESCE(column1, column2) DESC";
</code>```

and

```<code>$SQL = "SELECT * FROM table ORDER BY COALESCE(column1, column2) ASC";
</code>```

My above SQL is returning NULL value column1 above column2

答:
Old question but this solution worked for me:

$SQL = "SELECT * FROM table ORDER BY COALESCE(NULLIF(column1, ''), column2)";

Body:
I would like some help that has had me stumped for two days. I need to retrieve data from a database and order it by column1 when it isn't empty and then the rest of the result by column2

column1      column2
1            11
2            12
3            13
             14
             15
             16

Required result

1,2,3,14,15,16

I've tried numerous approaches, my latest failed attempt being

$SQL = "SELECT * FROM table ORDER BY COALESCE(column1, column2) DESC";

and

$SQL = "SELECT * FROM table ORDER BY COALESCE(column1, column2) ASC";

My above SQL is returning NULL value column1 above column2


问:
Notification click already open application not reopen in android
more than one activity use in application click song notification already open application not reopen application how to solve this error

```<code>  Intent notificationIntent = new Intent(this, MainActivity.class);
    notificationIntent.setAction(Control.ACTION.MAIN_ACTION);

    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
            notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);

   <activity
        android:name=".Activity.MainActivity"
        android:launchMode="singleTop"
        android:configChanges="orientation|keyboardHidden|screenLayout|screenSize" />
</code>```

and i have declare android:launchMode="singleTop" all activity in android manifest file

答:
android:launchMode="singleTop"

It means if the activity is already there on the top, it won't create an another instance. Instead onNewIntent() of an activity will get called with updated intent as a parameter.

```<code>@Override
public void onNewIntent(Intent intent) {
    // Deal with new Intent over here...
}
</code>```

Body:
more than one activity use in application click song notification already open application not reopen application how to solve this error

  Intent notificationIntent = new Intent(this, MainActivity.class);
    notificationIntent.setAction(Control.ACTION.MAIN_ACTION);

    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
            notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);

   <activity
        android:name=".Activity.MainActivity"
        android:launchMode="singleTop"
        android:configChanges="orientation|keyboardHidden|screenLayout|screenSize" />

and i have declare android:launchMode="singleTop" all activity in android manifest file

Body:
android:launchMode="singleTop"

It means if the activity is already there on the top, it won't create an another instance. Instead onNewIntent() of an activity will get called with updated intent as a parameter.

@Override
public void onNewIntent(Intent intent) {
    // Deal with new Intent over here...
}


问:
Symfony 2.7: Forward to magic method login not working
1. Systemcredentials:

Using:
symfony 2.7 ,
php 5.6,
Apache 2 as Webserver

2. Problem:

Trying to implement a facebook connect. The User can login on the login page and should be login from backend. The PHPSESSION Cookie need to be set. The frontend part call a backend function fbconnect. The fbconnect action checks that the form and the facebook credentials are valid. If the handover parameters are valid and connected to facebook and my application, the action
forward to the magic login method from symfony. Now the magic login function should login the user, but the action seems to just set the cookie. I'm still an anon at this point. Maybe the event chain is broken at this point, because of the forward to the magic login action? Strange behaviour is that the fbconnect action is called twice, but in frontend part the method called once. Did I missed something special?

my parameter: facebook ID, facebook (valid) Accesstoken, facebook Email

3. Code Snippets

my security.yml file:

```<code>security:
    firewalls:
    ....
    ....
    webapi:
        provider: secureBundle
        pattern: ^/webapi
        anonymous:  ~
        form_login:
            login_path: webapi-login
            check_path: webapi-login-check
            default_target_path: webapi-login-success
            require_previous_session: false
</code>```

Note: the "webapi-" part is dynamically add to the routes from the actions (Routing works properly)

fbconnect Action:

Note: the Action validate if the form is correct and that all parameters are valid, this is just the forward snippet.

```<code>$response = $this->forward(
'ApiBundle:Login:login',['/login/'], [
    '_password' => $passwordEncoder->decodePassword($user->getPassword(), null),
    '_username' => $user->getEmail(),
]
</code>```

Login Action:

Note: the references come from symfony doc Login Symfony . The Action simply let symfony handle this and jetzt return a response.

```<code> /**
 * @Route(path="/login/",name="login")
 *
 * @param Request $request
 * @return \Symfony\Component\HttpFoundation\Response
 */
public function loginAction(Request $request)
{

    $frame = $this->createFrame();

    $authenticationUtils = $this->get('security.authentication_utils');

    // get the login error if there is one
    $error = $authenticationUtils->getLastAuthenticationError();

    if ($error) {
        $frame->setError(true, Errno::GENERAL_BAD_CREDENTIALS, [$error->getMessage()]);
    }

    return $frame;
}
</code>```

4. Conclusion

Like I explained above i think that symfony can't handle a forward to the login. I don't unterstand why the the PHPSESSID Cookie is set, but im still anon. Do you have any experiences with this? I appreciate every hint.

Greeting Violence!

答:
I come up with this solution:

```<code>public function loginAction(Request $request)
{
    $frame = $this->createFrame();
    try {
        try {
            $user = $this->get('secure.user_provider')->loadUserByUsername($request->get('_username'));
        } catch (UsernameNotFoundException $exception) {
            $frame->setError($exception);

            return $frame;
        }
        $token = new UsernamePasswordToken($user, null, 'webapi', $user->getRoles());
        $this->get('security.token_storage')->setToken($token);
        $event = new InteractiveLoginEvent($request, $token);
        $this->get('event_dispatcher')->dispatch('security.interactive_login', $event);

        $authenticationUtils = $this->get('security.authentication_utils');
        // get the login error if there is one
        $error = $authenticationUtils->getLastAuthenticationError();

        if ($error) {
            $frame->setError(true, Errno::GENERAL_BAD_CREDENTIALS, [$error->getMessage()]);
        }
    } catch (\Exception $e) {
        $frame->setException($e);
    }

    return $frame;
}
</code>```

I created the login manually. Generate a UsernamePasswordToken and dispatch the event.

Hope it will help somebody with the same problem!

Body:
1. Systemcredentials:

Using:
symfony 2.7 ,
php 5.6,
Apache 2 as Webserver

2. Problem:

Trying to implement a facebook connect. The User can login on the login page and should be login from backend. The PHPSESSION Cookie need to be set. The frontend part call a backend function fbconnect. The fbconnect action checks that the form and the facebook credentials are valid. If the handover parameters are valid and connected to facebook and my application, the action
forward to the magic login method from symfony. Now the magic login function should login the user, but the action seems to just set the cookie. I'm still an anon at this point. Maybe the event chain is broken at this point, because of the forward to the magic login action? Strange behaviour is that the fbconnect action is called twice, but in frontend part the method called once. Did I missed something special?

my parameter: facebook ID, facebook (valid) Accesstoken, facebook Email

3. Code Snippets

my security.yml file:

security:
    firewalls:
    ....
    ....
    webapi:
        provider: secureBundle
        pattern: ^/webapi
        anonymous:  ~
        form_login:
            login_path: webapi-login
            check_path: webapi-login-check
            default_target_path: webapi-login-success
            require_previous_session: false

Note: the "webapi-" part is dynamically add to the routes from the actions (Routing works properly)

fbconnect Action:

Note: the Action validate if the form is correct and that all parameters are valid, this is just the forward snippet.

$response = $this->forward(
'ApiBundle:Login:login',['/login/'], [
    '_password' => $passwordEncoder->decodePassword($user->getPassword(), null),
    '_username' => $user->getEmail(),
]

Login Action:

Note: the references come from symfony doc Login Symfony . The Action simply let symfony handle this and jetzt return a response.

 /**
 * @Route(path="/login/",name="login")
 *
 * @param Request $request
 * @return \Symfony\Component\HttpFoundation\Response
 */
public function loginAction(Request $request)
{

    $frame = $this->createFrame();

    $authenticationUtils = $this->get('security.authentication_utils');

    // get the login error if there is one
    $error = $authenticationUtils->getLastAuthenticationError();

    if ($error) {
        $frame->setError(true, Errno::GENERAL_BAD_CREDENTIALS, [$error->getMessage()]);
    }

    return $frame;
}

4. Conclusion

Like I explained above i think that symfony can't handle a forward to the login. I don't unterstand why the the PHPSESSID Cookie is set, but im still anon. Do you have any experiences with this? I appreciate every hint.

Greeting Violence!

Body:
I come up with this solution:

public function loginAction(Request $request)
{
    $frame = $this->createFrame();
    try {
        try {
            $user = $this->get('secure.user_provider')->loadUserByUsername($request->get('_username'));
        } catch (UsernameNotFoundException $exception) {
            $frame->setError($exception);

            return $frame;
        }
        $token = new UsernamePasswordToken($user, null, 'webapi', $user->getRoles());
        $this->get('security.token_storage')->setToken($token);
        $event = new InteractiveLoginEvent($request, $token);
        $this->get('event_dispatcher')->dispatch('security.interactive_login', $event);

        $authenticationUtils = $this->get('security.authentication_utils');
        // get the login error if there is one
        $error = $authenticationUtils->getLastAuthenticationError();

        if ($error) {
            $frame->setError(true, Errno::GENERAL_BAD_CREDENTIALS, [$error->getMessage()]);
        }
    } catch (\Exception $e) {
        $frame->setException($e);
    }

    return $frame;
}

I created the login manually. Generate a UsernamePasswordToken and dispatch the event.

Hope it will help somebody with the same problem!


问:
NVCC refuses to link my object files
I am trying to compile a project by compiling object files and then linking them together, nothing fancy: </p>

```<code>hello.o : hello.h hello.cu
    nvcc hello.cu -c -o hello.o
#...
main.o : $(objs)
    nvcc *.o -o exec
</code>```

<p>When I get to the link phase, just about every method is shown to be missing and undeclared, despite the fact that nm shows that each is in fact sitting within my object files, and their names are unmangled. What is going on here? </p>

答:
I tried calling g++ but still got the same errors. The answer was found here:

http://forums.nvidia.com/index.php?showtopic=190973&st=0&gopid=1179661&#entry1179661

In short, function prototypes need to be correct.

Title: NVCC refuses to link my object files

Body:
I am trying to compile a project by compiling object files and then linking them together, nothing fancy:

hello.o : hello.h hello.cu
    nvcc hello.cu -c -o hello.o
#...
main.o : $(objs)
    nvcc *.o -o exec

When I get to the link phase, just about every method is shown to be missing and undeclared, despite the fact that nm shows that each is in fact sitting within my object files, and their names are unmangled. What is going on here?


问:
How can I check the 410 status of an iframe?
I'm building a page that uses the Slideshare API to pull a limited set of presentations from a specific Slideshare user and output a series of iframes with those presentations embedded.

For the most part the page is working as intended, however one of the presentations that the API is calling was recently deleted, and therefore when the page loads that iframe the browser returns a 410. Unfortunately there is no object in the XML returned by Slideshare that can be used to determine if that particular presentation has been deleted.

Therefore I would like to check for the 410 error prior to adding that particular iframe to the page. What's making this difficult for me is that the error doesn't appear when making the API call, but rather when the embedded iframe loads, so I don't know where or how to make the appropriate check.

Here's the relevant code:

```<code>$.ajax({
url: slideShareURL,
dataType: 'XML',
success: function(data) {
    var allSlides = x2js.xml2json(data);
    allSlides = allSlides.User.Slideshow;
    for (i = 0; i < allSlides.length; i++) {
        document.getElementById('slides').innerHTML += allSlides[i].Embed;
    }
}
});
</code>```

Notes:

slideShareURL is defined earlier in the code using the API

I'm using xml2json.js to convert the XML received from the API to a json object

allSlides is an array of presentations each containing a set of objects such as slide title, id, download URL, etc

Embed is the object that contains the full iframe embed code

EDIT: Answer provided by Christophe below was almost perfect, but I had to add a closure to make the second ajax call work within the for loop.

答:
Hmmm,what about this solution :</p>

```<code>$(function() {
    $.ajax({
        url: "www.domain.com/iframe",
        dataType: "jsonp",
        timeout: 5000,

        success: function () {
            $("#iframe").attr("src", "www.domain.com/iframe");
        },
        error: function (parsedjson) {
            if(parsedjson.status == "200") {
                $("#iframe").attr("src", "www.domain.com/iframe");
            } else {
                // Handle error
            }
        }
    });
});
</code>```

Body:
I'm building a page that uses the Slideshare API to pull a limited set of presentations from a specific Slideshare user and output a series of iframes with those presentations embedded.

For the most part the page is working as intended, however one of the presentations that the API is calling was recently deleted, and therefore when the page loads that iframe the browser returns a 410. Unfortunately there is no object in the XML returned by Slideshare that can be used to determine if that particular presentation has been deleted.

Therefore I would like to check for the 410 error prior to adding that particular iframe to the page. What's making this difficult for me is that the error doesn't appear when making the API call, but rather when the embedded iframe loads, so I don't know where or how to make the appropriate check.

Here's the relevant code:

$.ajax({
url: slideShareURL,
dataType: 'XML',
success: function(data) {
    var allSlides = x2js.xml2json(data);
    allSlides = allSlides.User.Slideshow;
    for (i = 0; i < allSlides.length; i++) {
        document.getElementById('slides').innerHTML += allSlides[i].Embed;
    }
}
});

Notes:

slideShareURL is defined earlier in the code using the API

I'm using xml2json.js to convert the XML received from the API to a json object

allSlides is an array of presentations each containing a set of objects such as slide title, id, download URL, etc

Embed is the object that contains the full iframe embed code

EDIT: Answer provided by Christophe below was almost perfect, but I had to add a closure to make the second ajax call work within the for loop.

Body:
Hmmm,what about this solution :

$(function() {
    $.ajax({
        url: "www.domain.com/iframe",
        dataType: "jsonp",
        timeout: 5000,

        success: function () {
            $("#iframe").attr("src", "www.domain.com/iframe");
        },
        error: function (parsedjson) {
            if(parsedjson.status == "200") {
                $("#iframe").attr("src", "www.domain.com/iframe");
            } else {
                // Handle error
            }
        }
    });
});