问:
Using C#, how can I read the content of dynamic created textboxes?
Hy,

I have created some dynamic textboxes with standard content.

Does anyone know how can I read the content of these textboxes (assuming that user modified the standard content) when I press one button?

Thanks a lot.

Jeff

Update

This is how I am creating the textboxes:

```<code>foreach (string name in listOfNames)
{
   TextBox tb = new TextBox();
   tb.Text = name;
   tb.BorderStyle = BorderStyle.None;
   tb.BorderWidth = 0;
   tb.Font.Name = "Arial";
   tb.Font.Size = 8;
}
</code>```

答:
The specific will vary depending on the technology you are using. However the concept would remain very similar, though for ASP.NET it will be a little more interesting.

WinForms/WPF/Silverlight

Maintain a list of the dynamically created textboxes and when the button is pressed you can run through the list of textboxes and read the Text property to get the user input.

ASP.NET - After the tag update it seems this section is most appropriate to your requirement.

For ASP.NET you will need to create the textboxes in an override of the OnInit method, this should happen on each postback. Then in the Button.Click event you can read the user input from the textboxes that you created in the OnInit function. You need to ensure that the controls are created with the same ID on each post back.

Body:
Hy,

I have created some dynamic textboxes with standard content.

Does anyone know how can I read the content of these textboxes (assuming that user modified the standard content) when I press one button?

Thanks a lot.

Jeff

Update

This is how I am creating the textboxes:

foreach (string name in listOfNames)
{
   TextBox tb = new TextBox();
   tb.Text = name;
   tb.BorderStyle = BorderStyle.None;
   tb.BorderWidth = 0;
   tb.Font.Name = "Arial";
   tb.Font.Size = 8;
}


来源: stackexchange

问:
Ghost.py webscraping list all elements in page
I'm trying to fill a form on a webpage with Ghost.py. At the moment i'm struggling with adressing the right form fields, css selectors giving me headaches. So i decided to let Ghost.py do the work and give me a list with form fields and identifiers. So far i have tried:

```<code>import ghost

g = ghost.Ghost()
with g.start(display=True) as session:
    page, extra_resources = session.open("http://www.surfbirds.com/identifier/what-british-bird.htm")
    if page.http_status == 200 and \
        'Head characters' in page.content:
        print("got it!")
        ressources =
        session.evaluate('document.getElementByName("geog");')
        print("ressources: {}".format(ressources))
</code>```

This throws an error:

```<code>Ghost<f836191b-16e6-4a0d-b2c5-96d657556b46>: undefined(0): TypeError:
'undefined' is not a function
ressources: (None, [])
</code>```

I have no idea what causes this, could someone please point me the direction where i should look?

答:
There is no tag on that page named <geog>. You probably would like to query for the form element with the name geog:

```<code>document.querySelector('form[name=geog]')
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to fill a form on a webpage with Ghost.py. At the moment i'm struggling with adressing the right form fields, css selectors giving me headaches. So i decided to let Ghost.py do the work and give me a list with form fields and identifiers. So far i have tried:

import ghost

g = ghost.Ghost()
with g.start(display=True) as session:
    page, extra_resources = session.open("http://www.surfbirds.com/identifier/what-british-bird.htm")
    if page.http_status == 200 and \
        'Head characters' in page.content:
        print("got it!")
        ressources =
        session.evaluate('document.getElementByName("geog");')
        print("ressources: {}".format(ressources))

This throws an error:

Ghost<f836191b-16e6-4a0d-b2c5-96d657556b46>: undefined(0): TypeError:
'undefined' is not a function
ressources: (None, [])

I have no idea what causes this, could someone please point me the direction where i should look?

Body:
There is no tag on that page named <geog>. You probably would like to query for the form element with the name geog:

document.querySelector('form[name=geog]')


问:
CSS bug in text input field - MSIE7
I have an input text in a form that has a problem in MSIE7.
When the text field is filled and I continue typing, the background starts scrolling left along with the text.

This is the form when the text field is filled

The background image, a white rectangle with rounded corners, scrolls left with the text, leaving the black background.

This is the CSS for this text field:

```<code>  border: none;
  background: url('/wp-content/themes/pokerbuddy/images/field.png') top left no-repeat;
  width: 100px;
  height: 20px;
  padding: 0px;
  font-size: 80%;
  color: #399;
  display:inline;
</code>```

Is there any way to solve this in MSIE7?

答:
```<code>input{overflow:hidden;}
</code>```

Don't know if this will work.

Title: CSS bug in text input field - MSIE7

Body:
I have an input text in a form that has a problem in MSIE7.
When the text field is filled and I continue typing, the background starts scrolling left along with the text.

This is the form when the text field is filled

The background image, a white rectangle with rounded corners, scrolls left with the text, leaving the black background.

This is the CSS for this text field:

  border: none;
  background: url('/wp-content/themes/pokerbuddy/images/field.png') top left no-repeat;
  width: 100px;
  height: 20px;
  padding: 0px;
  font-size: 80%;
  color: #399;
  display:inline;

Is there any way to solve this in MSIE7?

Body:
input{overflow:hidden;}

Don't know if this will work.

ContentLicense: CC BY-SA 2.5


问:
JavaFx my css file is not working
It was working earlier but now here is a screenshot

of my running program and it is clearly not. Can somebody help me with this? I am a beginner to JavaFX.

Analog_clock.java

```<code>package analog_clock;

import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.Background;
import javafx.scene.layout.BackgroundFill;
import javafx.scene.layout.Pane;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.stage.Stage;

/**
 *
 * @author ishansrivastava
 */
public class Analog_clock extends Application {

    @Override
    public void start(Stage primaryStage) {

        Circle circle = new Circle();
        circle.setCenterX(100.0f);
        circle.setCenterY(100.0f);
        circle.setRadius(50.0f);

        Group g = new Group();
        g.getChildren().add(circle);

        Pane bg = new Pane();
        //bg.setBackground(new Background(new BackgroundFill("-fx-color: #ACACE6", null,null)));
        bg.getChildren().add(g);

        Scene scene = new Scene(bg, 300, 250);
        scene.getStylesheets().add(this.getClass().getResource("style.css").toExternalForm());

        primaryStage.setTitle("Hello World!");
        primaryStage.setScene(scene);
        primaryStage.show()cl;
    }

    public static void main(String[] args) {
        launch(args);
    }

}
</code>```

style.css

```<code>.Circle
{
    -fx-stroke: #757575; /* sonic silver */
    -fx-fill: #00CC99; /* caribbean green */
}
.pane
{
    -fx-background-color: #ACACE6; /* maximum blue purple */
}
</code>```

Thank you for helping me out.

update :

after changing my css file to this :

```<code>.circle
{
    -fx-stroke: #757575; /* sonic silver */
    -fx-fill: #00CC99; /* caribbean green */
}
.root
{
    -fx-background-color: #ACACE6; /* maximum blue purple */
}
</code>```

my background appears to be purple where as I have nothing named root in my code.

Title: JavaFx my css file is not working

Body:
It was working earlier but now here is a screenshot

of my running program and it is clearly not. Can somebody help me with this? I am a beginner to JavaFX.

Analog_clock.java

package analog_clock;

import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.Background;
import javafx.scene.layout.BackgroundFill;
import javafx.scene.layout.Pane;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.stage.Stage;

/**
 *
 * @author ishansrivastava
 */
public class Analog_clock extends Application {

    @Override
    public void start(Stage primaryStage) {

        Circle circle = new Circle();
        circle.setCenterX(100.0f);
        circle.setCenterY(100.0f);
        circle.setRadius(50.0f);

        Group g = new Group();
        g.getChildren().add(circle);

        Pane bg = new Pane();
        //bg.setBackground(new Background(new BackgroundFill("-fx-color: #ACACE6", null,null)));
        bg.getChildren().add(g);

        Scene scene = new Scene(bg, 300, 250);
        scene.getStylesheets().add(this.getClass().getResource("style.css").toExternalForm());

        primaryStage.setTitle("Hello World!");
        primaryStage.setScene(scene);
        primaryStage.show()cl;
    }

    public static void main(String[] args) {
        launch(args);
    }

}

style.css

.Circle
{
    -fx-stroke: #757575; /* sonic silver */
    -fx-fill: #00CC99; /* caribbean green */
}
.pane
{
    -fx-background-color: #ACACE6; /* maximum blue purple */
}

Thank you for helping me out.

update :

after changing my css file to this :

.circle
{
    -fx-stroke: #757575; /* sonic silver */
    -fx-fill: #00CC99; /* caribbean green */
}
.root
{
    -fx-background-color: #ACACE6; /* maximum blue purple */
}

my background appears to be purple where as I have nothing named root in my code.

Body: scene.getStylesheets().add(Analog_clock.class.getResource("/style.css").toExternalForm());


问:
No prompt ubuntu virtual machine using vagrant on Git Bash
After logging into the VM using vagrant ssh using GitBash on Windows 10, I don't see any directory prompts. While it does run the python web forum (for a tutorial on Udacity on Intro to Relational Databases), it won't let me run psql so I can continue the lesson. I can change directories, list information about the files, and run python but the prompt isn't working like normal.

Screenshot here: screenshot.

Please note the forum is running, this screenshot was taken after I exited and restarted vagrant.

Vagrant version 1.9.6

Ubuntu version 16.04.2 LTS

All programs installed or running in administrator mode.

答: I wasn't able to get Git Bash to work, but the show window for the Oracle VM VirtualBox Manager does work just fine. I've been using Git Bash to start the VM, then switch to the Oracle VM UI window.</p>


问:
scons: how to specify dependency to an external build target?
I'm using protobuf to generate from .proto files to .cc/.h files. So I have my SConscript as below:

```<code>env.protoc('my.proto')
env.Program(target='pb_my',    CCFLAGS="-I.",
        source=['pb_my.cpp',    'my.pb.cc'],       LIBS='protobuf')
</code>```

I find that, the "env." commands in a SConscript is not executed in sequence(that's why targets can be build in parallel using scons -j20). But sometimes problem is, because the target of "pb_my" should be build after I generate "my.pb.cc" from "my.proto", scons will report error is second line is executed first.

So how can I specify that the second line's target should only be executed after 1st line is finished?

Thanks a lot.

答:
You cannot specify order in scons directly.

The proper way is to make sure the dependencies are specified.

Please include the code for your protobuf builder?

Likely if files output from your protobuf builder are being compiled before they are generated your protobuf builder isn't specifying them.

Also, please add output of scons --tree=prune to your question.

Body:
I'm using protobuf to generate from .proto files to .cc/.h files. So I have my SConscript as below:

env.protoc('my.proto')
env.Program(target='pb_my',    CCFLAGS="-I.",
        source=['pb_my.cpp',    'my.pb.cc'],       LIBS='protobuf')

I find that, the "env." commands in a SConscript is not executed in sequence(that's why targets can be build in parallel using scons -j20). But sometimes problem is, because the target of "pb_my" should be build after I generate "my.pb.cc" from "my.proto", scons will report error is second line is executed first.

So how can I specify that the second line's target should only be executed after 1st line is finished?

Thanks a lot.


问:
Load a javascript file when i select an option in popup.html
im making a chrome extension and i have a problem loading a file...
I want to load a file when i select an option in the popup.html file
for example, if i select option1 i want eventPage1.js, to be loaded, and if i select option2 i want eventPage2.js to be loaded, but not the two at the same time, just one.

This its my popup.html file

<!DOCTYPE html>

<form>
Paises en el menu contextual:

    <input type="radio" id="opcion1" name="opcion" value="opcion1" onclick=
    Todos los paises

    <input type="radio" id="opcion2" name="opcion" value="opcion2" onclick=
    Solo Mexico

</form>

```
</div>
</div>
</p>

<p>each eventpage file, its a context menu... </p>

<p>this its how my manifest file looks like</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>{
"manifest_version": 2,
"name": "help me",
"author": "me man",
"version": "1.1.4",
"description": "test test",
"browser_action":
 {
  "default_icon": "icon-large.png",
  "default_popup": "popup.html"
 },

  "background": {
    "scripts": ["menuSelection.js"]
 },
  "permissions": [
 "storage",
 "contextMenus"
  ],
  "icons": {
          "16": "icon-bitty.png",
          "48": "icon-small.png",
          "128": "icon-large.png"
 }
}</code>```

another problem that i have, its that when i select an option... save that option in storage so everytime i use the extension its automatically loaded that option

答:
Event page is a technical term for the page declared in "background" section of manifest.json with "persistent": false. It's not just a name. It's a special context which exists only for that single hidden page. Make sure to read the extension architecture overview.

Inline code in html file doesn't work in extension pages by default for security reasons (the onclick attribute in your html). Handle all events in a separate js file

The input tags in your html aren't closed, and actually malformed. There's no opening .

To save the options use chrome.storage API or the old primitive string-based localStorage

To dynamically load js files, add a script element dynamically into head with its src property set to the name of the file to load. Or use the modern require()-based approach. However, you might want to start learning using a single script file.

Don't use form: the browser is not a web server so the page cannot be submitted. It will simply reload and you'll lose all data. Of course you can prevent the submit event in a listener but it defeats the purpose of using a form. Instead process a change immediately.

popup.html:

```<code><!DOCTYPE html>
<html>
<body>
  Paises en el menu contextual:
  <div>
    <label><input type="radio" name="opcion" value="opcion1">Todos los paises</label>
    <label><input type="radio" name="opcion" value="opcion2">Solo Mexico</label>
  </div>
  <script src="popup.js"></script>
</body>
</html>
</code>```

popup.js:

```<code>function setRadio(name, value) {
  const el = document.querySelector(`input[name="${name}"][value="${value}"]`);
  if (el && !el.checked) {
    el.checked = true;
  }
}

chrome.storage.sync.get('opcion', data => {
  setRadio('opcion', data.opcion);
});

document.onchange = event => {
  if (event.target.name == 'opcion') {
    const value = event.target.value;
    chrome.storage.sync.set({opcion: value});

    switch (value) {
      case 'opcion1':
        doSomething1();
        break;
      case 'opcion2':
        doSomething2();
        break;
    }
  }
};

chrome.storage.onChanged.addListener((changes, area) => {
  if (area == 'sync' && 'opcion' in changes) {
    setRadio('opcion', changes.opcion.newValue);
  }
});
</code>```

Body:
im making a chrome extension and i have a problem loading a file...
I want to load a file when i select an option in the popup.html file
for example, if i select option1 i want eventPage1.js, to be loaded, and if i select option2 i want eventPage2.js to be loaded, but not the two at the same time, just one.

This its my popup.html file

<!DOCTYPE html>

<form>
Paises en el menu contextual:

    <input type="radio" id="opcion1" name="opcion" value="opcion1" onclick=
    Todos los paises

    <input type="radio" id="opcion2" name="opcion" value="opcion2" onclick=
    Solo Mexico

</form>

each eventpage file, its a context menu...

this its how my manifest file looks like

{
"manifest_version": 2,
"name": "help me",
"author": "me man",
"version": "1.1.4",
"description": "test test",
"browser_action":
 {
  "default_icon": "icon-large.png",
  "default_popup": "popup.html"
 },

  "background": {
    "scripts": ["menuSelection.js"]
 },
  "permissions": [
 "storage",
 "contextMenus"
  ],
  "icons": {
          "16": "icon-bitty.png",
          "48": "icon-small.png",
          "128": "icon-large.png"
 }
}

another problem that i have, its that when i select an option... save that option in storage so everytime i use the extension its automatically loaded that option

Body:
Event page is a technical term for the page declared in "background" section of manifest.json with "persistent": false. It's not just a name. It's a special context which exists only for that single hidden page. Make sure to read the extension architecture overview.

Inline code in html file doesn't work in extension pages by default for security reasons (the onclick attribute in your html). Handle all events in a separate js file

The input tags in your html aren't closed, and actually malformed. There's no opening <body>.

To save the options use chrome.storage API or the old primitive string-based localStorage

To dynamically load js files, add a script element dynamically into head with its src property set to the name of the file to load. Or use the modern require()-based approach. However, you might want to start learning using a single script file.

Don't use form: the browser is not a web server so the page cannot be submitted. It will simply reload and you'll lose all data. Of course you can prevent the submit event in a listener but it defeats the purpose of using a form. Instead process a change immediately.

popup.html:

<!DOCTYPE html>
<html>
<body>
  Paises en el menu contextual:
  <div>
    <label><input type="radio" name="opcion" value="opcion1">Todos los paises</label>
    <label><input type="radio" name="opcion" value="opcion2">Solo Mexico</label>
  </div>
  <script src="popup.js"></script>
</body>
</html>

popup.js:

function setRadio(name, value) {
  const el = document.querySelector(`input[name="${name}"][value="${value}"]`);
  if (el && !el.checked) {
    el.checked = true;
  }
}

chrome.storage.sync.get('opcion', data => {
  setRadio('opcion', data.opcion);
});

document.onchange = event => {
  if (event.target.name == 'opcion') {
    const value = event.target.value;
    chrome.storage.sync.set({opcion: value});

    switch (value) {
      case 'opcion1':
        doSomething1();
        break;
      case 'opcion2':
        doSomething2();
        break;
    }
  }
};

chrome.storage.onChanged.addListener((changes, area) => {
  if (area == 'sync' && 'opcion' in changes) {
    setRadio('opcion', changes.opcion.newValue);
  }
});


问:
How to set target fragment
I have two fragments: the fragmentA and the dialogFragmentB in one Activity.
fragmentB has two alertDialogs, it starts from dialogA and then dialogA call dismiss() and generates dialogB.
fragmentA has method onActivityResult() and dialogB (from dialogFragmentB) has to send some intent-result there after button's click. But before i send that result i have to set target fragmentA. How to do it in onClick method of dialogB?

i think i need something like this:

```<code>public void onClick(){
     ...
     dialogB.dismiss();
     fragmentA.setTargetFragment(FragmentA, requestCode);
}
</code>```

But i have an Error: cannot find symbol variable FragmentA

Thank you!

答:
I've resolved my problem in next way:</p>

```<code>public class DialogFragmentB extends DialogFragment{
   ...
   public Dialog onCreateDialog (Bundle b){
   // here i create two dialogs, first dialogA and then it calls dialogB
   // finally dialogB has to return his datas and datas from dialogA in fragmentA
      ...
      public void onClick(View v){
         ...
         FragmentManager fm = getFragmentManager();
         // these two code's lines resolved my headache --------------
         Fragment ft = fm.findFragmentByTag(FragmentA.FRAGMENT_A_TAG);
         ft.setTargetFragment(ft, FragmentA.CODE_REQUEST);
         // ----------------------------------------------------------
         dialogB.dismiss();
         sendResult(Activity.RESULT_OK, myData);
      }
      return dialogB;
   }
   // And here myData goes in onActivityResult in fragmentA
    private void sendResult(int resultCode, MyData myData){
        if(getTargetFragment() == null){
            return;
        }
        Intent intent = new Intent();
        intent.putExtra(EXTRA_DATE_2, myData);
        getTargetFragment().onActivityResult(getTargetRequestCode(), resultCode, intent);
    }
}
</code>```

ContentLicense: CC BY-SA 4.0

Title: How to set target fragment

Body:
I have two fragments: the fragmentA and the dialogFragmentB in one Activity.
fragmentB has two alertDialogs, it starts from dialogA and then dialogA call dismiss() and generates dialogB.
fragmentA has method onActivityResult() and dialogB (from dialogFragmentB) has to send some intent-result there after button's click. But before i send that result i have to set target fragmentA. How to do it in onClick method of dialogB?

i think i need something like this:

public void onClick(){
     ...
     dialogB.dismiss();
     fragmentA.setTargetFragment(FragmentA, requestCode);
}

But i have an Error: cannot find symbol variable FragmentA

Thank you!

Body:
I've resolved my problem in next way:

public class DialogFragmentB extends DialogFragment{
   ...
   public Dialog onCreateDialog (Bundle b){
   // here i create two dialogs, first dialogA and then it calls dialogB
   // finally dialogB has to return his datas and datas from dialogA in fragmentA
      ...
      public void onClick(View v){
         ...
         FragmentManager fm = getFragmentManager();
         // these two code's lines resolved my headache --------------
         Fragment ft = fm.findFragmentByTag(FragmentA.FRAGMENT_A_TAG);
         ft.setTargetFragment(ft, FragmentA.CODE_REQUEST);
         // ----------------------------------------------------------
         dialogB.dismiss();
         sendResult(Activity.RESULT_OK, myData);
      }
      return dialogB;
   }
   // And here myData goes in onActivityResult in fragmentA
    private void sendResult(int resultCode, MyData myData){
        if(getTargetFragment() == null){
            return;
        }
        Intent intent = new Intent();
        intent.putExtra(EXTRA_DATE_2, myData);
        getTargetFragment().onActivityResult(getTargetRequestCode(), resultCode, intent);
    }
}


问:
Angular @Output not working
Trying to do child to parent communication with @Output event emitter but is no working
here is the child component

```<code>import { Component, OnInit, Output, Input, EventEmitter } from '@angular/core';

@Component({
  selector: 'app-emiter',
  templateUrl: './emiter.component.html',
  styleUrls: ['./emiter.component.css']
})
export class EmiterComponent implements OnInit {

@Output() emitor: EventEmitter<any>
  constructor() { this.emitor = new EventEmitter()}

   touchHere(){this.emitor.emit('Should Work');
   console.log('<><><><>',this.emitor) // this comes empty
  }

  ngOnInit() {
  }

}
</code>```

this is the html template

```<code><p>
<button (click)=" touchHere()" class="btn btn-success btn-block">touch</button>
</p>
</code>```

The console.log inside the touchHere it shows nothing
even if I put this inside the parent component it show nothing as well
parent component

```<code> import { Component , OnInit} from '@angular/core';
// service I use for other stuff//
    import { SenderService } from './sender.service';
// I dont know if I have to import this but did it just in case
    import { EmiterComponent } from './emiter/emiter.component'

@Component({
      selector: 'app-root',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.css']
    })
    export class AppComponent {
      title = 'app';
      user: any;
      touchThis(message: string) {
        console.log('Not working: ${message}');
      }
        constructor(private mySessionService: SenderService) { }
    }
</code>```

and here is the html template

```<code><div>
  <app-emiter>(touchHere)='touchThis($event)'</app-emiter>
</div>
</code>```

答:
Parent component template:

```<code>  <app-emitor (emitor)='touchThis($event)'></app-emiter>
</code>```

In parent template @Output should be 'called', not the child method.

Also, see: https://angular.io/guide/component-interaction#parent-listens-for-child-event

Title: Angular @Output not working

Body:
Trying to do child to parent communication with @Output event emitter but is no working
here is the child component

import { Component, OnInit, Output, Input, EventEmitter } from '@angular/core';

@Component({
  selector: 'app-emiter',
  templateUrl: './emiter.component.html',
  styleUrls: ['./emiter.component.css']
})
export class EmiterComponent implements OnInit {

@Output() emitor: EventEmitter<any>
  constructor() { this.emitor = new EventEmitter()}

   touchHere(){this.emitor.emit('Should Work');
   console.log('<><><><>',this.emitor) // this comes empty
  }

  ngOnInit() {
  }

}

this is the html template

<button (click)=" touchHere()" class="btn btn-success btn-block">touch</button>

The console.log inside the touchHere it shows nothing
even if I put this inside the parent component it show nothing as well
parent component

 import { Component , OnInit} from '@angular/core';
// service I use for other stuff//
    import { SenderService } from './sender.service';
// I dont know if I have to import this but did it just in case
    import { EmiterComponent } from './emiter/emiter.component'

@Component({
      selector: 'app-root',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.css']
    })
    export class AppComponent {
      title = 'app';
      user: any;
      touchThis(message: string) {
        console.log('Not working: ${message}');
      }
        constructor(private mySessionService: SenderService) { }
    }

and here is the html template

  <app-emiter>(touchHere)='touchThis($event)'</app-emiter>

Body:
Parent component template:

  <app-emitor (emitor)='touchThis($event)'></app-emiter>

In parent template @Output should be 'called', not the child method.

Also, see: https://angular.io/guide/component-interaction#parent-listens-for-child-event


问:
Update breaks function in Unity
I have the following code

```<code>public Rigidbody2D rb;
public float speed = 5f;

void FixedUpdate()
{
    if (Input.GetKeyDown("w"))
    {
        Fire();
    }
}

void Fire()
{
    rb.MovePosition(rb.position + Vector2.down * speed * Time.deltaTime);
}
</code>```

but every time I play the game, the ball does not move according to the fire function, it only goes down by 1 on the y-axis.

How can I edit my code, so that the Rigidbody moves according to the Fire() function?

答:
There could be a couple things going wrong here. The first thing that stands out to me is that you're using Input.GetKeyDown instead of Input.GetKey-- GetKeyDown only returns true on the first frame that the key is pressed (so it's useful for things like shooting once per keypress), whereas GetKey returns true for the entire time that the key is down (so it's useful for things like movement). Changing that should give you the behavior that you're expecting.

Another issue is that you're doing input checking in FixedUpdate. It runs on a separate game loop from Update, and you can find more details about that here: Is it really wrong to use Input.GetKey() on FixedUpdate?

I would use Input and GetKey to store the input state in a Vector2 in the Update loop, and then use that data in FixedUpdate to do the actual movement:

```<code>public Rigidbody2D rb;
public float speed = 5f;
private Vector2 velocity = Vector2.zero;

void Update()
{
    if (Input.GetKey("w"))
    {
        velocity = Vector2.down * speed;
    }
    else {
        velocity = Vector2.zero;
    }
}

void FixedUpdate()
{
    MoveBall();
}

void MoveBall()
{
    rb.MovePosition(rb.position * velocity * Time.deltaTime);
}
</code>```

This way, you also have a stronger separation between the input code and movement code, and it will be easier to handle once you start trying to implement more complexity. Good luck!

Title: Update breaks function in Unity

Body:
I have the following code

public Rigidbody2D rb;
public float speed = 5f;

void FixedUpdate()
{
    if (Input.GetKeyDown("w"))
    {
        Fire();
    }
}

void Fire()
{
    rb.MovePosition(rb.position + Vector2.down * speed * Time.deltaTime);
}

but every time I play the game, the ball does not move according to the fire function, it only goes down by 1 on the y-axis.

How can I edit my code, so that the Rigidbody moves according to the Fire() function?

Body:
There could be a couple things going wrong here. The first thing that stands out to me is that you're using Input.GetKeyDown instead of Input.GetKey-- GetKeyDown only returns true on the first frame that the key is pressed (so it's useful for things like shooting once per keypress), whereas GetKey returns true for the entire time that the key is down (so it's useful for things like movement). Changing that should give you the behavior that you're expecting.

Another issue is that you're doing input checking in FixedUpdate. It runs on a separate game loop from Update, and you can find more details about that here: Is it really wrong to use Input.GetKey() on FixedUpdate?

I would use Input and GetKey to store the input state in a Vector2 in the Update loop, and then use that data in FixedUpdate to do the actual movement:

public Rigidbody2D rb;
public float speed = 5f;
private Vector2 velocity = Vector2.zero;

void Update()
{
    if (Input.GetKey("w"))
    {
        velocity = Vector2.down * speed;
    }
    else {
        velocity = Vector2.zero;
    }
}

void FixedUpdate()
{
    MoveBall();
}

void MoveBall()
{
    rb.MovePosition(rb.position * velocity * Time.deltaTime);
}

This way, you also have a stronger separation between the input code and movement code, and it will be easier to handle once you start trying to implement more complexity. Good luck!


问:
Default, building parameters for Zabbix
I want to install zabbix (server and java-gateway) 3.2 from sources (needed to patch something). What are default parameters that i should use with  <code>./configure</code> command so it would be same as installing using packages ? </p>

答:
Something like this:

```<code>--enable-server --enable-java --enable-ipv6 --with-jabber --with-libxml2 --with-unixodbc --with-net-snmp --with-ssh2 --with-openipmi --with-ldap --with-libcurl
</code>```

For encryption, choose one of --with-mbedtls, --with-gnutls or --with-openssl.

Also add one for the database used, like --with-mysql.

Note that you will need quite a lot of development packages.

Title: Default, building parameters for Zabbix

Body: I want to install zabbix (server and java-gateway) 3.2 from sources (needed to patch something). What are default parameters that i should use with  ./configure command so it would be same as installing using packages ?

Body:
Something like this:

--enable-server --enable-java --enable-ipv6 --with-jabber --with-libxml2 --with-unixodbc --with-net-snmp --with-ssh2 --with-openipmi --with-ldap --with-libcurl

For encryption, choose one of --with-mbedtls, --with-gnutls or --with-openssl.

Also add one for the database used, like --with-mysql.

Note that you will need quite a lot of development packages.


问:
silverlight draw on bitmap
```<code>Image img = new Bitmap(Image.FromFile(file.FullName));

using (Graphics g = Graphics.FromImage(img)){
    g.DrawRectangle(Pens.Black, 0, 0, img.Width - 2, img.Height - 2);
}
</code>```

like this

how to do in sliverlight?

答:
You don't need to render a SL Rectangle into the WriteableBitmap. The WriteableBitmapEx open source library is perfect for this. See the project site for an example of the DrawRectangle method.
http://writeablebitmapex.codeplex.com

There are also live samples, including the Shape sample.

You can also find the code of the samples in the source code repository.

Title: silverlight draw on bitmap

Body:
Image img = new Bitmap(Image.FromFile(file.FullName));

using (Graphics g = Graphics.FromImage(img)){
    g.DrawRectangle(Pens.Black, 0, 0, img.Width - 2, img.Height - 2);
}

like this

how to do in sliverlight?


问:
C++ RIFF WAVE reader is painfully slow
So I've never really worked with binary files before and I'm new to C++. I wanted to read a wav file and output its data section into a txt (seperating the value of each sample with a comma). I also managed to read in the header section, but this code is not important here so I'll not include it.

My wav file stores data in the IEEE 754 standard (floating point numbers) at 32bps. I first read the entire wav file into a char vector and try to work with that afterwards. The output of the program is what I expect it to be, I can play the sound back in Python by reading in the txt without issues. The program is just horribly slow (it takes several minutes for a wav file that is a couple seconds long).

This is wavReader.cpp:

```<code>#include "stdafx.h"
#include "wavFile.h"
#include <fstream>
#include <iostream>
#include <vector>

int main()
{
    std::ifstream file("file.wav", std::ios::binary);
    std::vector<char> buffer((
        std::istreambuf_iterator<char>(file)),
        (std::istreambuf_iterator<char>()));
    std::cout << "Loading complete!\n";

    WavFile wavFile = setWavFile(buffer);

    return 0;
}
</code>```

This is wavFile.h:

```<code>#pragma once
#include <iostream>
#include <vector>

struct WavFile
{
    uint32_t dataSize;
};

WavFile setWavFile(std::vector<char> buffer);
uint32_t getUint32(std::vector<char> buffer, std::vector<char>::iterator it);
</code>```

This is wavFile.cpp:

```<code>#include "stdafx.h"
#include "WavFile.h"
#include <fstream>

WavFile setWavFile(std::vector<char> buffer) {

    WavFile wavFile;
    std::vector<char>::iterator it = buffer.begin();

    // Beginning of data chunk is marked with "data"
    it += 4;
    while (*(it - 4) != 'd' ||
        *(it - 3) != 'a' ||
        *(it - 2) != 't' ||
        *(it - 1) != 'a')
        it++;

    wavFile.dataSize = getUint32(buffer, it), it += 4;
    std::ofstream output("data.txt");

    while (it != buffer.end())
    {
        char outputChar[4];
        for (int i = 0; i < 4; (i++, it++))
            outputChar[i] = *it;
        char* outputStr = outputChar;
        char** outputStrPtr = &outputStr;
        float** outputPtr = reinterpret_cast<float**>(outputStrPtr);
        output << **outputPtr << ", ";
        std::cout << static_cast<double>(std::distance(buffer.begin(), it)) * 100 / wavFile.dataSize << "\%\n";
    }

    return wavFile;
}

uint32_t getUint32(std::vector<char> buffer, std::vector<char>::iterator it)
{
    char outputChar[4];
    for (int i = 0; i < 4; (i++, it++))
        outputChar[i] = *it;
    char* outputStr = outputChar;
    char** outputStrPtr = &outputStr;
    uint32_t** outputPtr = reinterpret_cast<uint32_t**>(outputStrPtr);
    return **outputPtr;
}
</code>```

I made the program print the progress to the console. Note that this only works with wav files that have one channel and store the samples in IEEE 754 standard. You can find the file I used here. I'm just a hobby programmer, so forgive me that I have no clue what makes my program this slow... Is it the vector iteration? Or is it the kinda messy variable declarations with reinterpret_cast?

答:
Maybe the progress printing slows it down? You print a lot. Maybe you can try to print only when the integral value of the percent changes, like:</p>

```<code>int lastPercent = -1;

loop {
  ...
  float percent = ...;
  int integralPercent = (int)percent;
  if (integralPercent!=lastPercent) {
    lastPercent = integralPercent;
    // print percent here
  }
}
</code>```

Title: C++ RIFF WAVE reader is painfully slow

Body:
So I've never really worked with binary files before and I'm new to C++. I wanted to read a wav file and output its data section into a txt (seperating the value of each sample with a comma). I also managed to read in the header section, but this code is not important here so I'll not include it.

My wav file stores data in the IEEE 754 standard (floating point numbers) at 32bps. I first read the entire wav file into a char vector and try to work with that afterwards. The output of the program is what I expect it to be, I can play the sound back in Python by reading in the txt without issues. The program is just horribly slow (it takes several minutes for a wav file that is a couple seconds long).

This is wavReader.cpp:

#include "stdafx.h"
#include "wavFile.h"
#include <fstream>
#include <iostream>
#include <vector>

int main()
{
    std::ifstream file("file.wav", std::ios::binary);
    std::vector<char> buffer((
        std::istreambuf_iterator<char>(file)),
        (std::istreambuf_iterator<char>()));
    std::cout << "Loading complete!\n";

    WavFile wavFile = setWavFile(buffer);

    return 0;
}

This is wavFile.h:

#pragma once
#include <iostream>
#include <vector>

struct WavFile
{
    uint32_t dataSize;
};

WavFile setWavFile(std::vector<char> buffer);
uint32_t getUint32(std::vector<char> buffer, std::vector<char>::iterator it);

This is wavFile.cpp:

#include "stdafx.h"
#include "WavFile.h"
#include <fstream>

WavFile setWavFile(std::vector<char> buffer) {

    WavFile wavFile;
    std::vector<char>::iterator it = buffer.begin();

    // Beginning of data chunk is marked with "data"
    it += 4;
    while (*(it - 4) != 'd' ||
        *(it - 3) != 'a' ||
        *(it - 2) != 't' ||
        *(it - 1) != 'a')
        it++;

    wavFile.dataSize = getUint32(buffer, it), it += 4;
    std::ofstream output("data.txt");

    while (it != buffer.end())
    {
        char outputChar[4];
        for (int i = 0; i < 4; (i++, it++))
            outputChar[i] = *it;
        char* outputStr = outputChar;
        char** outputStrPtr = &outputStr;
        float** outputPtr = reinterpret_cast<float**>(outputStrPtr);
        output << **outputPtr << ", ";
        std::cout << static_cast<double>(std::distance(buffer.begin(), it)) * 100 / wavFile.dataSize << "\%\n";
    }

    return wavFile;
}

uint32_t getUint32(std::vector<char> buffer, std::vector<char>::iterator it)
{
    char outputChar[4];
    for (int i = 0; i < 4; (i++, it++))
        outputChar[i] = *it;
    char* outputStr = outputChar;
    char** outputStrPtr = &outputStr;
    uint32_t** outputPtr = reinterpret_cast<uint32_t**>(outputStrPtr);
    return **outputPtr;
}

I made the program print the progress to the console. Note that this only works with wav files that have one channel and store the samples in IEEE 754 standard. You can find the file I used here. I'm just a hobby programmer, so forgive me that I have no clue what makes my program this slow... Is it the vector iteration? Or is it the kinda messy variable declarations with reinterpret_cast?

Body:
Maybe the progress printing slows it down? You print a lot. Maybe you can try to print only when the integral value of the percent changes, like:

int lastPercent = -1;

loop {
  ...
  float percent = ...;
  int integralPercent = (int)percent;
  if (integralPercent!=lastPercent) {
    lastPercent = integralPercent;
    // print percent here
  }
}


问:
Connecting to Access database through HTML on PC
So I'm trying to figure out how to connect to an access database that is on my  desktop through html. Everything I've found so far involves the DB being server side and people mentioning ASP.net or just using SQL or mySQL instead. I just need to know how to get the connection up and running. Any help would be appreciated.</p>

答:
You cannot read or modify files from your (or anyone else) computer with frontend/html/javascript. Yes, you need some backend to connect to your database on your computer/server.

There are databases that work on client side/frontend, like IndexedDB, but it's not ms access and I don't think it's what you want.


问:
In Angular 4, Firebase Authentication, Login with Google causes email login to stop working until I refresh
I'm using AngularFire2 authentication. We can log in with email/pass (email has been verified) or log in with Google. If I log in with email everything is fine. I log out, I log in, back and forth no issues. Then I sign in with Google, and log out and also no issues. BUT, if I log in with Google, then log out, I CAN'T log in with email unless I refresh the page! Even tho I'm totally logged out I get "auth/invalid-email" every time I try logging in after logging in with Google and logging out. If I refresh the page I can log in again with email without having any issues. Anyone know what this behavior is?</p>

答:
I don't know why, but since refreshing the page works, I just refreshed it after logging out with:

```<code>location.reload();
</code>```

Not sure if that's the proper way to do it, but it works! ... and I would be happier if auth.signOut() did the job better.

Body:
I don't know why, but since refreshing the page works, I just refreshed it after logging out with:

location.reload();

Not sure if that's the proper way to do it, but it works! ... and I would be happier if auth.signOut() did the job better.


问:
Chained promises keep being executed despite rejection in the chain
I have the code below and i want to stop the execution when a rejection occurs in order to do a rollback. However even if there are rejects in the chain it keeps executing.

```<code>__cacheHandheldData(userResult.handhelduuid).then((oldhandheldId) => {
  olduuid = oldhandheldId;
  __cacheUserdata(userResult.userdata_id) //userResult.userdata_id
}).then((x) => {
  __reconciliateToNewUserData(userResult.userdata_id, handheldData.uuid)
}).then((x) => {
  __linkUser(userResult._id, handheldData.userdata_id, handheldData.uuid)
}).then((x) => {
  __unlinkUser(olduuid)
}).then((x) => {
  __attachMergedUserdata(userResult.handhelduuid)
}).then((x) => {
  __cleanHandheld(userResult.handhelduuid)
}).then((x) => {
  __cleanUserdata(userResult.userdata_id)
}).then((x) => {
  __cleanHandheldCache(userResult.handhelduuid)
}).then((x) => {
  __cleanUserdataCache(userResult.userdata_id)
}).then((x) => {
  __removeHandHeldFromRedis(userResult.handhelduuid)
}).then((x) => {
  console.log('reached to destination')
  var response = {};
  response.errorCode = '00';
  res.setHeader('Access-Control-Allow-Origin', '*');
  res.send(201, response);
  return next;
}).catch((err) => {
  console.log('[general]', err)
});
</code>```

each of these __functions are of form

```<code>function __cacheHandheldData(oldhandhelduuid){
return new Promise((resolve, reject)=>{});}
</code>```

答:
You have to return the promises in the .then() handlers as in:

```<code>}).then((x) => {
    return __reconciliateToNewUserData(userResult.userdata_id,handheldData.uuid)
 // ^^^^^^ add return here to return the promise
}).then((x) => {
</code>```

Only when you return a promise from within a .then() handler is it actually added into the chain.  Without that, it's just an independent promise chain that has no connection at all to the parent chain.  .then() handlers have no magic powers to know when asynchronous operations executed within them are done.  The only way they can know is if you return a promise that represents the asynchronous operation.

Once it is part of the chain (by returning the promise as shown above), if any of those returned promises reject, then they will abort the whole chain (up to the next .catch()).

Body:
I have the code below and i want to stop the execution when a rejection occurs in order to do a rollback. However even if there are rejects in the chain it keeps executing.

__cacheHandheldData(userResult.handhelduuid).then((oldhandheldId) => {
  olduuid = oldhandheldId;
  __cacheUserdata(userResult.userdata_id) //userResult.userdata_id
}).then((x) => {
  __reconciliateToNewUserData(userResult.userdata_id, handheldData.uuid)
}).then((x) => {
  __linkUser(userResult._id, handheldData.userdata_id, handheldData.uuid)
}).then((x) => {
  __unlinkUser(olduuid)
}).then((x) => {
  __attachMergedUserdata(userResult.handhelduuid)
}).then((x) => {
  __cleanHandheld(userResult.handhelduuid)
}).then((x) => {
  __cleanUserdata(userResult.userdata_id)
}).then((x) => {
  __cleanHandheldCache(userResult.handhelduuid)
}).then((x) => {
  __cleanUserdataCache(userResult.userdata_id)
}).then((x) => {
  __removeHandHeldFromRedis(userResult.handhelduuid)
}).then((x) => {
  console.log('reached to destination')
  var response = {};
  response.errorCode = '00';
  res.setHeader('Access-Control-Allow-Origin', '*');
  res.send(201, response);
  return next;
}).catch((err) => {
  console.log('[general]', err)
});

each of these __functions are of form

function __cacheHandheldData(oldhandhelduuid){
return new Promise((resolve, reject)=>{});}

Body:
You have to return the promises in the .then() handlers as in:

}).then((x) => {
    return __reconciliateToNewUserData(userResult.userdata_id,handheldData.uuid)
 // ^^^^^^ add return here to return the promise
}).then((x) => {

Only when you return a promise from within a .then() handler is it actually added into the chain.  Without that, it's just an independent promise chain that has no connection at all to the parent chain.  .then() handlers have no magic powers to know when asynchronous operations executed within them are done.  The only way they can know is if you return a promise that represents the asynchronous operation.

Once it is part of the chain (by returning the promise as shown above), if any of those returned promises reject, then they will abort the whole chain (up to the next .catch()).


问:
Can't create django app in Conda environment.
I have created a conda environment by typing the following conda create --name testenv python command from here.

Now one of my tutorials tells me to install Django which I happily did in the environment(That is the point of using environments right?, keeping dependencies straight) using pip3 install django.Post which I was told to do this django-admin startproject mysite Which didn't work. I am thinking because he was doing it in venv and I am in conda probably that's why(There is no venv folder in my test-app folder as well. Also I have already activated the environment). Every time I type the command django-admin startapp mysite I get this error.

```<code>Traceback (most recent call last):
  File "/usr/bin/django-admin", line 18, in <module>
    from django.core import management
ImportError: No module named 'django'
</code>```

How do I fix this? I have already installed Django. What more am I supposed to do?

答:
This question is old, but if anyone is wondering the exact steps to create a Django application using conda, here it is

conda create -n <nameoftheapplication> python=3.6

source activate <nameoftheapplication> Note: For Windows just put activate

pip install django

django-admin.py startproject <nameoftheapplication>

cd <nameoftheapplication>

ls

You should see manage.py and a folder called <nameoftheapplication> which contains settings files.

Body:
I have created a conda environment by typing the following conda create --name testenv python command from here.

Now one of my tutorials tells me to install Django which I happily did in the environment(That is the point of using environments right?, keeping dependencies straight) using pip3 install django.Post which I was told to do this django-admin startproject mysite Which didn't work. I am thinking because he was doing it in venv and I am in conda probably that's why(There is no venv folder in my test-app folder as well. Also I have already activated the environment). Every time I type the command django-admin startapp mysite I get this error.

Traceback (most recent call last):
  File "/usr/bin/django-admin", line 18, in <module>
    from django.core import management
ImportError: No module named 'django'

How do I fix this? I have already installed Django. What more am I supposed to do?


问:
Standard method for validating a group of XML files against schemas and each other
I'm developing a data transfer standard which is going to involve (simplistically) a client defining a project definition, in XML, to a project definition schema and a supplier supplying data which meets a data supply schema and the client defined project definition.

I know I can do this by convention/by defining a process to be followed, my question is "Is there an accepted standard way to do this type of thing?", perhaps using annotation/appinfo? (I've googled around and have come up empty)

An example of what I'm on about is below (most stuff stripped out for brevity):

Simplified Client Project Definition Schema

```<code><xs:schema ...>
    <xs:element name="ProjectConfiguration">
        <xs:complexType>
            <xs:sequence>
                <xs:element name="Enum" type="EnumType" minOccurs="0" maxOccurs="unbounded" />
            </xs:sequence>
            <xs:attribute name="id" type="xs:string" use="required" />
        </xs:complexType>
    </xs:element>

    <xs:complexType name="EnumType">
        <xs:sequence>
            <xs:element name="Value" type="xs:string" minOccurs="1" maxOccurs="unbounded" />
        </xs:sequence>
        <xs:attribute name="name" type="xs:string" use="required" />
    </xs:complexType>
</xs:schema>
</code>```

Client Project Definition XML

```<code><ProjectConfiguration id="myproj">
    <Enum name="myenum">
        <Value>AllowedValue1</Value>
        <Value>AllowedValue2</Value>
    </Enum>
</ProjectConfiguration>
</code>```

Simplified Supplier Data Supply Schema

```<code><xs:schema ...>
    <xs:element name="Data">
        <xs:complexType>
            <xs:attribute name="value" type="xs:string" use="required">
                <xs:annotation>
                    <xs:documentation>
                        Here, I want the type to be validated against the list supplied
                        in the Client Project Definition XML.  I know (think) that XSD
                        won't cut this, but am wondering if there is anything
                        that will in a standard manner.
                    </xs:documentation>
                </xs:annotation>
            </xs:attribute>
        </xs:complexType>
    </xs:element>
</xs:schema>
</code>```

For the avoidance of doubt, I've got complete control over my codebase and no externally imposed constraints.  I do not want the client to be defining a schema for every project, as the eventual solution will involve multiple tiers/stock configurations (and inheritance and amendment of these via configuration).

If there is another way which is radically different to what I'm trying to do, I'm all ears!

答:
You're correct that the enumerations cannot be specified in a separate XML file and applied as constraints to values in an XSD.

I do not want the client to be defining a schema for every project, as
  the eventual solution will involve multiple tiers/stock configurations
  (and inheritance and amendment of these via configuration).

That's a bit vague as far as requirements go, but here are some other validation options if you're finding XSD 1.0 to be too limited:

XSD 1.1 has assertions, although they're restricted to accessing the
current node and its descendants.

Schematron has assertions that are XPath based and can call user-defined
functions (XSLT syntax), which in turn could consult other XML documents
containing enumeration declarations, for example.

Raw XSLT would provide the most power and flexibility, albeit at the
expense of the standardization and predefined structure provided by
Schematron.

Body:
I'm developing a data transfer standard which is going to involve (simplistically) a client defining a project definition, in XML, to a project definition schema and a supplier supplying data which meets a data supply schema and the client defined project definition.

I know I can do this by convention/by defining a process to be followed, my question is "Is there an accepted standard way to do this type of thing?", perhaps using annotation/appinfo? (I've googled around and have come up empty)

An example of what I'm on about is below (most stuff stripped out for brevity):

Simplified Client Project Definition Schema

<xs:schema ...>
    <xs:element name="ProjectConfiguration">
        <xs:complexType>
            <xs:sequence>
                <xs:element name="Enum" type="EnumType" minOccurs="0" maxOccurs="unbounded" />
            </xs:sequence>
            <xs:attribute name="id" type="xs:string" use="required" />
        </xs:complexType>
    </xs:element>

    <xs:complexType name="EnumType">
        <xs:sequence>
            <xs:element name="Value" type="xs:string" minOccurs="1" maxOccurs="unbounded" />
        </xs:sequence>
        <xs:attribute name="name" type="xs:string" use="required" />
    </xs:complexType>
</xs:schema>

Client Project Definition XML

<ProjectConfiguration id="myproj">
    <Enum name="myenum">
        <Value>AllowedValue1</Value>
        <Value>AllowedValue2</Value>
    </Enum>
</ProjectConfiguration>

Simplified Supplier Data Supply Schema

<xs:schema ...>
    <xs:element name="Data">
        <xs:complexType>
            <xs:attribute name="value" type="xs:string" use="required">
                <xs:annotation>
                    <xs:documentation>
                        Here, I want the type to be validated against the list supplied
                        in the Client Project Definition XML.  I know (think) that XSD
                        won't cut this, but am wondering if there is anything
                        that will in a standard manner.
                    </xs:documentation>
                </xs:annotation>
            </xs:attribute>
        </xs:complexType>
    </xs:element>
</xs:schema>

For the avoidance of doubt, I've got complete control over my codebase and no externally imposed constraints.  I do not want the client to be defining a schema for every project, as the eventual solution will involve multiple tiers/stock configurations (and inheritance and amendment of these via configuration).

If there is another way which is radically different to what I'm trying to do, I'm all ears!


问:
Python Recursive Power
```<code>def main():

    base = input('Please Enter An Integer for the Base: ')
    exponent = input ('Please Enter An Exponent: ')

def power (base, exponent):
    if exponent == 0:
        return base
    else :
        return base * power(base, exponent - 1)

main()
</code>```

SAMPLE OUT:
Enter an integer for the base: 2
Enter an integer for the exponent: 5
2 to the power 5 equals 32

答:
This is sort of working for me, but I get 1000 if I use 10 as base and 2 as the exponent. Trying to figure it out now why the math is wrong.</p>

```<code>def main():

   base = float(input('Please Enter An Integer for the Base: '))
   exponent = float(input('Please Enter An Exponent: '))
   result = power(base, exponent)
   print("{} to the power of {} equals {}".format(base, exponent, result))

def power (base, exponent):

   if exponent == 0:
      return base
   else :
      return base * power(base, exponent - 1)
main()
</code>```

Title: Python Recursive Power

Body:
def main():

    base = input('Please Enter An Integer for the Base: ')
    exponent = input ('Please Enter An Exponent: ')

def power (base, exponent):
    if exponent == 0:
        return base
    else :
        return base * power(base, exponent - 1)

main()

SAMPLE OUT:
Enter an integer for the base: 2
Enter an integer for the exponent: 5
2 to the power 5 equals 32

Body:
This is sort of working for me, but I get 1000 if I use 10 as base and 2 as the exponent. Trying to figure it out now why the math is wrong.

def main():

   base = float(input('Please Enter An Integer for the Base: '))
   exponent = float(input('Please Enter An Exponent: '))
   result = power(base, exponent)
   print("{} to the power of {} equals {}".format(base, exponent, result))

def power (base, exponent):

   if exponent == 0:
      return base
   else :
      return base * power(base, exponent - 1)
main()


问:
How scons tell different OS adn build different SConscript accordingly?
I've got several directories of source code, some for linux, some for mac, etc. How can I specify inside my SConstruct, that under linux, please execute:

```<code>SConscript(dirs=['linux'],     variant_dir='linux/build',     duplicate=0);
</code>```

And under other operating system, execute other SConscript command?

Is there a convenient way to specify this?

答:
@jszakmeiter's comment it good.

Another way might be to match the directory name of the code with the value for sys.platform and then use:

```<code>SConscript(dirs=[sys.platform],     variant_dir='%s/build'%sys.platform,     duplicate=0);
</code>```

As a side note, I usually advise having the variant dirs as siblings to and not children of the source directories.

```<code>SConscript(dirs=[sys.platform],     variant_dir='build/%s'%sys.platform,     duplicate=0);
</code>```

Body:
I've got several directories of source code, some for linux, some for mac, etc. How can I specify inside my SConstruct, that under linux, please execute:

SConscript(dirs=['linux'],     variant_dir='linux/build',     duplicate=0);

And under other operating system, execute other SConscript command?

Is there a convenient way to specify this?

Body:
@jszakmeiter's comment it good.

Another way might be to match the directory name of the code with the value for sys.platform and then use:

SConscript(dirs=[sys.platform],     variant_dir='%s/build'%sys.platform,     duplicate=0);

As a side note, I usually advise having the variant dirs as siblings to and not children of the source directories.

SConscript(dirs=[sys.platform],     variant_dir='build/%s'%sys.platform,     duplicate=0);


问:
Best way to convert ShowS to String?
How to to prettify </p>

```<code>(displayS $ renderPretty 0.8 80 $ _errDoc ei <> linebreak) ""
</code>```

<p>why I cant </p>

```<code>show $ displayS $ renderPretty 0.8 80 $ _errDoc ei <> linebreak
</code>```

答:
You can't show $ displayS blah because ShowS isn't an instance of Show. Recall that

```<code>type ShowS = String -> String
</code>```

so if we wanted an instance of Show we would have to write:

```<code>instance Show (String -> String) where
    show f = ...
</code>```

And now we have a bit of a problem. After all, the only thing we can do with the function f, really, is call it with String arguments. There's a couple choices that spring to mind readily, but they each have drawbacks:

Try to describe the behavior of f on every possible input. This isn't going to work very well -- there's infinitely many inputs. Reading and understanding the infinite output would take a longish time.

Don't bother calling f at all. Pick a single String to be the output of show, as in show f = "<it's a function, lol>". This isn't terribly useful because it doesn't actually give you any information about f.

Call f with the distinguished string "". This isn't useful because there are lots of different functions that give the same output for that input, and you won't be able to distinguish between them. (Maybe it so happens that your library for cooking up ShowS values won't have that problem, but if we're going to have the instance it ought to work for values that come from anywhere, not just some tiny subset of the values!)

Because of these considerations, an instance of Show for functions is not included in the standard libraries, though approaches (1) and (2) are available for installation from Hackage.

Title: Best way to convert ShowS to String?

Body:
How to to prettify

(displayS $ renderPretty 0.8 80 $ _errDoc ei <> linebreak) ""

why I cant

show $ displayS $ renderPretty 0.8 80 $ _errDoc ei <> linebreak

Body:
You can't show $ displayS blah because ShowS isn't an instance of Show. Recall that

type ShowS = String -> String

so if we wanted an instance of Show we would have to write:

instance Show (String -> String) where
    show f = ...

And now we have a bit of a problem. After all, the only thing we can do with the function f, really, is call it with String arguments. There's a couple choices that spring to mind readily, but they each have drawbacks:

Try to describe the behavior of f on every possible input. This isn't going to work very well -- there's infinitely many inputs. Reading and understanding the infinite output would take a longish time.

Don't bother calling f at all. Pick a single String to be the output of show, as in show f = "<it's a function, lol>". This isn't terribly useful because it doesn't actually give you any information about f.

Call f with the distinguished string "". This isn't useful because there are lots of different functions that give the same output for that input, and you won't be able to distinguish between them. (Maybe it so happens that your library for cooking up ShowS values won't have that problem, but if we're going to have the instance it ought to work for values that come from anywhere, not just some tiny subset of the values!)

Because of these considerations, an instance of Show for functions is not included in the standard libraries, though approaches (1) and (2) are available for installation from Hackage.


问:
Set max width of website then center this material if browser is bigger than set width
My website is responsive up to 1800px which is the max-width I want. Say the user's screen is bigger than 1800px, I want all of my html/css to stay the same that it was for the 1800px, just be centered on the page (if the user's current with is 2200, then there would be 200px of whitespace on the left, then the 1800px in the center, and 200px of whitespace on the right).

My code is the following:

```<code><body>
    <nav class="navbar navbar-default navbar-fixed-top" role="navigation">
        <div class="container">navbar text</div>
    </nav>

    <!-- HOME -->
    <div id="home" class="content-section">
        <div class="container"></div>
    </div>

    <!-- ABOUT -->
    <div id="about" class="content-section">
        <div class="container"></div>
    </div>

    <!-- CONTACT -->
    <div id="contact" class="content-section">
        <div class="container">
            <div class="row">
                <div class="col-xs-12 col-sm-12 col-md-9 col-lg-9 "></div>
            </div>
        </div>
    </div>

    <footer> footer text</footer>
</body>
</code>```

答:
Wrap your code with

Here is css:

```<code>.wrapper{
 width:auto;
max-width:1800;
margin:0 auto;
}
</code>```

Chk if this works

Body:
My website is responsive up to 1800px which is the max-width I want. Say the user's screen is bigger than 1800px, I want all of my html/css to stay the same that it was for the 1800px, just be centered on the page (if the user's current with is 2200, then there would be 200px of whitespace on the left, then the 1800px in the center, and 200px of whitespace on the right).

My code is the following:

navbar text

     footer text

Body:
Wrap your code with <div class="wrapper"></div>

Here is css:

.wrapper{
 width:auto;
max-width:1800;
margin:0 auto;
}

Chk if this works


问:
Gradle zip: how to include and rename one file easily?
Create a zip adding file "hello/world.xml" under directory "foo/bar" as "hello/universe.xml"

```<code>task myZip(type: Zip) {
     from ("foo/bar") {
         include "hello/world.xml"
         filesMatching("hello/*") {
             it.path = "hello/universe.xml"
         }
     }
}
</code>```

filesMatching(...) will impact performance obviously.
What is a better way? like:

```<code>task myZip(type: Zip) {
     from ("foo/bar") {
         include ("hello/world.xml") {
              rename "hello/universe.xml"
         }
     }
}
</code>```

But rename is not supported with include.

答:
I don't get why you are using filesMatching at all. You are only including one single file in your child CopySpec. Simply rename it and everything is fine:

```<code>task myZip(type: Zip) {
    from ('foo/bar') {
        include 'hello/world.xml'
        rename { 'hello/universe.xml' }
    }
}
</code>```

If you want to include multiple files (or even copy all), but only want to rename one of them, specify which file(s) to rename with a regular expression as first argument:

```<code>task myZip(type: Zip) {
    from 'foo/bar'
    rename 'hello/world.xml' 'hello/universe.xml'
}
</code>```

Body:
Create a zip adding file "hello/world.xml" under directory "foo/bar" as "hello/universe.xml"

task myZip(type: Zip) {
     from ("foo/bar") {
         include "hello/world.xml"
         filesMatching("hello/*") {
             it.path = "hello/universe.xml"
         }
     }
}

filesMatching(...) will impact performance obviously.
What is a better way? like:

task myZip(type: Zip) {
     from ("foo/bar") {
         include ("hello/world.xml") {
              rename "hello/universe.xml"
         }
     }
}

But rename is not supported with include.

Body:
I don't get why you are using filesMatching at all. You are only including one single file in your child CopySpec. Simply rename it and everything is fine:

task myZip(type: Zip) {
    from ('foo/bar') {
        include 'hello/world.xml'
        rename { 'hello/universe.xml' }
    }
}

If you want to include multiple files (or even copy all), but only want to rename one of them, specify which file(s) to rename with a regular expression as first argument:

task myZip(type: Zip) {
    from 'foo/bar'
    rename 'hello/world.xml' 'hello/universe.xml'
}


问:
VB.NET FileSystemWatcher Multiple Change Events
I have the following code:

```
<code>
Imports System.IO

Public Class Blah
    Public Sub New()
        InitializeComponent()

        Dim watcher As New FileSystemWatcher("C:\")
        watcher.EnableRaisingEvents = True

        AddHandler watcher.Changed, AddressOf watcher_Changed
    End Sub

    Private Sub watcher_Changed(ByVal sender As Object, ByVal e As FileSystemEventArgs)
        MsgBox(e.FullPath)
    End Sub
End Class
</code>
```

When I run it and save changes to a file on my C drive, the code works great, except it executes the watcher_Changed() method four times.  Any idea why?  The changeType is "4" every time.

Thanks.

答:
Assuming the path is the same every time, is it possible the program you are using to save the file is actually doing the save in pieces? Or do you have more than one Blah instantiated?

Edit:
Do you have any antivirus auto-protect software running? Those might be touching the file in the process.

From the MSDN Documentation:

Common file system operations might
  raise more than one event. For
  example, when a file is moved from one
  directory to another, several
  OnChanged and some OnCreated and
  OnDeleted events might be raised.
  Moving a file is a complex operation
  that consists of multiple simple
  operations, therefore raising multiple
  events. Likewise, some applications
  (for example, antivirus software)
  might cause additional file system
  events that are detected by
  FileSystemWatcher.

Edit: Or maybe there's something to do with how windows is saving the file. You might be getting more than one event from different changes. (One for the size, one for the last write timestamp, one for the last access timestamp, and one more for...something else.) Try setting the FileSystemWatcher's NotifyFilter property to a single type of change and see if you continue to get multiple events.

OwnerDisplayName: John

Body:
I have the following code:

Imports System.IO

Public Class Blah
    Public Sub New()
        InitializeComponent()

        Dim watcher As New FileSystemWatcher("C:\")
        watcher.EnableRaisingEvents = True

        AddHandler watcher.Changed, AddressOf watcher_Changed
    End Sub

    Private Sub watcher_Changed(ByVal sender As Object, ByVal e As FileSystemEventArgs)
        MsgBox(e.FullPath)
    End Sub
End Class

When I run it and save changes to a file on my C drive, the code works great, except it executes the watcher_Changed() method four times.  Any idea why?  The changeType is "4" every time.

Thanks.

LastEditorDisplayName: Frederik Gheysels

OwnerDisplayName: lc

LastEditorDisplayName: lc


问:
Phonegap/Cordova jQuery $.get not working in iOS simulator
I have <access origin="*" allows-arbitrary-loads.../> in my config.xml, I have allowed arbitrary loads in my info.plist, and the jQuery is syntactically correct and works, but not as part of the Xcode project. Any suggestions?

答: Did you also add the required settings to the server? The server also needs to be set up with a Access-Control-Allow-Origin header.</p>


问:
Pandas using regex to return number if contains duplicated digits
I'm trying to analyze a large column of data that contains 12 digit numbers as seen below:

```<code>0    802112134267
1    300949934377
2    300999934377
3    222589009836
4    950279219923
Name: number, dtype: object
</code>```

I want to grab any number that has 3 or more repeated characters.  Row 2 contains 4 '9's and row 3 contains 3 '2's.  I would want to return:

```<code>0    None
1    None
2    300999934377
3    222589009836
4    None
Name: number, dtype: object
</code>```

Or just a truncated/filtered dataframe/series would suffice.

The regex that I think solves this is: '(\d)\1{2,}'

However, I haven't been able to successfully apply this regex to the series.

```<code>regex = re.compile('(\d)\1{2,}')
s.apply(lambda x: np.nan if regex.search(x) == None else x)
</code>```

returns all NaN.

```<code>s.str.extract('(\d)\1{2,}', expand=True)
</code>```

returns all NaN.

```<code>s.str.contains('(\d)\1{2,}')
</code>```

returns all False.

Any help would be appreciated.  I've tried searching the forum and haven't found any good examples that have worked.

Thanks

答:
@WiktorStribiżew's regex is correct. In addition to his answer, I'd like to provide you with a simpler way to filter out your column.

You can use the df.where function to filter out your rows:

```<code>In [1524]: df['Col1'] = df.where(df['Col1'].str.contains(r'(\d)\1{2,2}'), other=None)

In [1525]: df['Col1']
Out[1525]:
0            None
1            None
2    300999934377
3    222589009836
4            None
Name: Col1, dtype: object
</code>```

df['Col1'].str.contains returns a boolean mask which is then applied to the dataframe using df.where. other=None specifies that None should be put in place of elements that do not match your pattern.

You can skip the regex compilation, and you don't need a lambda anymore.

Body:
I'm trying to analyze a large column of data that contains 12 digit numbers as seen below:

0    802112134267
1    300949934377
2    300999934377
3    222589009836
4    950279219923
Name: number, dtype: object

I want to grab any number that has 3 or more repeated characters.  Row 2 contains 4 '9's and row 3 contains 3 '2's.  I would want to return:

0    None
1    None
2    300999934377
3    222589009836
4    None
Name: number, dtype: object

Or just a truncated/filtered dataframe/series would suffice.

The regex that I think solves this is: '(\d)\1{2,}'

However, I haven't been able to successfully apply this regex to the series.

regex = re.compile('(\d)\1{2,}')
s.apply(lambda x: np.nan if regex.search(x) == None else x)

returns all NaN.

s.str.extract('(\d)\1{2,}', expand=True)

returns all NaN.

s.str.contains('(\d)\1{2,}')

returns all False.

Any help would be appreciated.  I've tried searching the forum and haven't found any good examples that have worked.

Thanks

Body:
@WiktorStribiżew's regex is correct. In addition to his answer, I'd like to provide you with a simpler way to filter out your column.

You can use the df.where function to filter out your rows:

In [1524]: df['Col1'] = df.where(df['Col1'].str.contains(r'(\d)\1{2,2}'), other=None)

In [1525]: df['Col1']
Out[1525]:
0            None
1            None
2    300999934377
3    222589009836
4            None
Name: Col1, dtype: object

df['Col1'].str.contains returns a boolean mask which is then applied to the dataframe using df.where. other=None specifies that None should be put in place of elements that do not match your pattern.

You can skip the regex compilation, and you don't need a lambda anymore.


问:
Why am I not able to add the tensors together?
I am currently implementing RCL layers which is defined on this page.

```<code>import keras
from keras.models import Model
from keras.layers import Input, Dense, Dropout, Flatten
from keras.layers import merge, Conv2D, MaxPooling2D, Input
import numpy as np
from keras import backend as K

#   RCL:
#   BatchNorm(Relu(conv(L-1) + conv(L)))
#

def make_RCNN(dim_1,dim_2,dim_3,number_of_rcl,num_of_filter, filtersize):
    return True

def RCL(feed_forward_input,num_of_filter, filtersize):
    conv = Conv2D(filters=num_of_filter, kernel_size=filtersize)
    recurrent_input = conv(feed_forward_input)
    merged = merge([feed_forward_input,recurrent_input],mode='sum')
    conv_relu = Relu(merged)
    conv_relu_batchnorm = BatchNormalization()(conv_relu)
    return conv_relu_batchnorm

input = Input(shape=(30,30,3))
output = RCL(feed_forward_input=input,num_of_filter=3,filtersize=3)
</code>```

and I am getting error message:

```<code>python RCNN.py
Using TensorFlow backend.
Couldn't import dot_parser, loading of dot files will not be possible.
RCNN.py:22: UserWarning: The `merge` function is deprecated and will be removed after 08/2017. Use instead layers from `keras.layers.merge`, e.g. `add`, `concatenate`, etc.
  merged = merge([feed_forward_input,recurrent_input],mode='sum')
/usr/local/lib/python2.7/dist-packages/keras/legacy/layers.py:460: UserWarning: The `Merge` layer is deprecated and will be removed after 08/2017. Use instead layers from `keras.layers.merge`, e.g. `add`, `concatenate`, etc.
  name=name)
Traceback (most recent call last):
  File "RCNN.py", line 28, in <module>
    output = RCL(feed_forward_input=input,num_of_filter=3,filtersize=3)
  File "RCNN.py", line 22, in RCL
    merged = merge([feed_forward_input,recurrent_input],mode='sum')
  File "/usr/local/lib/python2.7/dist-packages/keras/legacy/layers.py", line 460, in merge
    name=name)
  File "/usr/local/lib/python2.7/dist-packages/keras/legacy/layers.py", line 111, in __init__
    node_indices, tensor_indices)
  File "/usr/local/lib/python2.7/dist-packages/keras/legacy/layers.py", line 155, in _arguments_validation
    'Layer shapes: %s' % input_shapes)
ValueError: Only layers of same output shape can be merged using sum mode. Layer shapes: [(None, 30, 30, 3), (None, 28, 28, 3)]
</code>```

It says that the shape is not the same... Which indeed is a problem, which only can be caused be a misunderstanding of the RCL..

But from what i understand, also defined here

What i've implemented is a RCL that takes in a tensor that from a previous layer (feed forward tensor),  and apply a convolution on that tensor (reccurent tensor), These two tensor make the first and the second part of the z_ijk(t) equation. After this is the sum of both tensor computed, like according to the equation, which is where the function have some problems making sense as the the convoluted feed forward input = the recurrent input don't have the same size.. so how shall sum two tensor, when their size isn't the same?

答:
I think the solution may just be as simple as adding a padding='same' argument to the Conv2D call, so the RCL method looks like this:

```<code>def RCL(feed_forward_input,num_of_filter, filtersize):
    conv = Conv2D(filters=num_of_filter, kernel_size=filtersize, padding='same')
    recurrent_input = conv(feed_forward_input)
    merged = merge([feed_forward_input,recurrent_input], mode='sum')
    conv_relu = relu(merged)
    conv_relu_batchnorm = BatchNormalization()(conv_relu)
    return conv_relu_batchnorm
</code>```

Without it, the Conv2D layer resizes the input to a (28, 28, 3) image, which can't be merged with the original image. The padding parameter pads the image with zeros so the output has the same shape (or a simple fraction of the same shape) as the input.

Body:
I am currently implementing RCL layers which is defined on this page.

import keras
from keras.models import Model
from keras.layers import Input, Dense, Dropout, Flatten
from keras.layers import merge, Conv2D, MaxPooling2D, Input
import numpy as np
from keras import backend as K

#   RCL:
#   BatchNorm(Relu(conv(L-1) + conv(L)))
#

def make_RCNN(dim_1,dim_2,dim_3,number_of_rcl,num_of_filter, filtersize):
    return True

def RCL(feed_forward_input,num_of_filter, filtersize):
    conv = Conv2D(filters=num_of_filter, kernel_size=filtersize)
    recurrent_input = conv(feed_forward_input)
    merged = merge([feed_forward_input,recurrent_input],mode='sum')
    conv_relu = Relu(merged)
    conv_relu_batchnorm = BatchNormalization()(conv_relu)
    return conv_relu_batchnorm

input = Input(shape=(30,30,3))
output = RCL(feed_forward_input=input,num_of_filter=3,filtersize=3)

and I am getting error message:

python RCNN.py
Using TensorFlow backend.
Couldn't import dot_parser, loading of dot files will not be possible.
RCNN.py:22: UserWarning: The `merge` function is deprecated and will be removed after 08/2017. Use instead layers from `keras.layers.merge`, e.g. `add`, `concatenate`, etc.
  merged = merge([feed_forward_input,recurrent_input],mode='sum')
/usr/local/lib/python2.7/dist-packages/keras/legacy/layers.py:460: UserWarning: The `Merge` layer is deprecated and will be removed after 08/2017. Use instead layers from `keras.layers.merge`, e.g. `add`, `concatenate`, etc.
  name=name)
Traceback (most recent call last):
  File "RCNN.py", line 28, in <module>
    output = RCL(feed_forward_input=input,num_of_filter=3,filtersize=3)
  File "RCNN.py", line 22, in RCL
    merged = merge([feed_forward_input,recurrent_input],mode='sum')
  File "/usr/local/lib/python2.7/dist-packages/keras/legacy/layers.py", line 460, in merge
    name=name)
  File "/usr/local/lib/python2.7/dist-packages/keras/legacy/layers.py", line 111, in __init__
    node_indices, tensor_indices)
  File "/usr/local/lib/python2.7/dist-packages/keras/legacy/layers.py", line 155, in _arguments_validation
    'Layer shapes: %s' % input_shapes)
ValueError: Only layers of same output shape can be merged using sum mode. Layer shapes: [(None, 30, 30, 3), (None, 28, 28, 3)]

It says that the shape is not the same... Which indeed is a problem, which only can be caused be a misunderstanding of the RCL..

But from what i understand, also defined here

What i've implemented is a RCL that takes in a tensor that from a previous layer (feed forward tensor),  and apply a convolution on that tensor (reccurent tensor), These two tensor make the first and the second part of the z_ijk(t) equation. After this is the sum of both tensor computed, like according to the equation, which is where the function have some problems making sense as the the convoluted feed forward input = the recurrent input don't have the same size.. so how shall sum two tensor, when their size isn't the same?

Body:
I think the solution may just be as simple as adding a padding='same' argument to the Conv2D call, so the RCL method looks like this:

def RCL(feed_forward_input,num_of_filter, filtersize):
    conv = Conv2D(filters=num_of_filter, kernel_size=filtersize, padding='same')
    recurrent_input = conv(feed_forward_input)
    merged = merge([feed_forward_input,recurrent_input], mode='sum')
    conv_relu = relu(merged)
    conv_relu_batchnorm = BatchNormalization()(conv_relu)
    return conv_relu_batchnorm

Without it, the Conv2D layer resizes the input to a (28, 28, 3) image, which can't be merged with the original image. The padding parameter pads the image with zeros so the output has the same shape (or a simple fraction of the same shape) as the input.


问:
How to extract double from a stringstream
While working on my C++ project I've noticed something odd while playing with stringstream objects: I'm not able to extract a double from a stringstream using >>.

Consider this example:

```<code>#include <string>
#include <sstream>

int main(int argc, const char * argv[]) {

    std::string string("1000 ; 523277527397538 ; 0.183 ; 0.453 ; 0.5 ; 0.5 ; 0.033 ; 0 ; 0 ;");
    std::stringstream stringstream(string);
    int integer;
    char character;
    double doubleprec;
    stringstream >> integer >> character;
    stringstream >> integer >> character;
    stringstream >> doubleprec >> character;
    stringstream >> doubleprec >> character;

    return 0;
}
</code>```

Using my debugger I've noticed that the variable integer takes first the value 1000 and then the value 523277527397538 (as I expected), but doubleprec takes always the value 0.

Why is that? Am I missing something about how streams work?

答:
Only the first stream output statement of:

```<code>stringstream >> integer >> character;
</code>```

is successful. The remaining three are not due to the fact that your int variable can not hold the value of 523277527397538. Change it to long long:

```<code>long long integer;
</code>```

When stream extraction fails to put the 523277527397538 number literal to your variable then the stringstream's failbit is set and subsequent calls to stringstream extraction also fail. A good approach is to use the if statement when working with stream IO:

```<code>if (stringstream >> integer >> character){
    // success
}
</code>```

Body:
While working on my C++ project I've noticed something odd while playing with stringstream objects: I'm not able to extract a double from a stringstream using >>.

Consider this example:

#include <string>
#include <sstream>

int main(int argc, const char * argv[]) {

    std::string string("1000 ; 523277527397538 ; 0.183 ; 0.453 ; 0.5 ; 0.5 ; 0.033 ; 0 ; 0 ;");
    std::stringstream stringstream(string);
    int integer;
    char character;
    double doubleprec;
    stringstream >> integer >> character;
    stringstream >> integer >> character;
    stringstream >> doubleprec >> character;
    stringstream >> doubleprec >> character;

    return 0;
}

Using my debugger I've noticed that the variable integer takes first the value 1000 and then the value 523277527397538 (as I expected), but doubleprec takes always the value 0.

Why is that? Am I missing something about how streams work?

Body:
Only the first stream output statement of:

stringstream >> integer >> character;

is successful. The remaining three are not due to the fact that your int variable can not hold the value of 523277527397538. Change it to long long:

long long integer;

When stream extraction fails to put the 523277527397538 number literal to your variable then the stringstream's failbit is set and subsequent calls to stringstream extraction also fail. A good approach is to use the if statement when working with stream IO:

if (stringstream >> integer >> character){
    // success
}


问:
AWS EC2 + Nginx + SSL fro subdomain
Can anyone explain to me a little bit how I can install SSL on my AWS EC2. I read lots of article that those steps are simple but I tried couple of them and none of them works.

I have one AWS EC2

EC2 staic ip, 54.X.X.X

subdoamin, xxxx.ab.abc.com

security group: port from

custom 80, 443, 9000-9100

nginx redirect

aaa1.ab.abc.com:80 to aaa1.ab.abc.com:9001

aaa2.ab.abc.com:80 to aaa1.ab.abc.com:9002

aaa3.ab.abc.com:80 to aaa1.ab.abc.com:9003

...

aaa(n).ab.abc.com:80 to aaa1.ab.abc.com:900(n)

```<code>ngnix.conf
server {
    listen       80;
    server_name ~^(aaa(?<site>[0-9]+)).ab.abc.com;
    location / {
        set $custom_port 90$site;
        if ($custom_port ~ "^.{3}$") {
            set $custom_port 900$site;
        }
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_set_header Host $host;
        proxy_pass http://127.0.0.1:$custom_port;
    }
}
</code>```

How can I install SSL into EC2 so no matter which subdomain I hit. it will have certificated?

```<code>Steps I have done.

$sudo service nginx stop
$git clone https://github.com/certbot/certbot.git to use certbot to generate SSL key
$./certbot-auto certonly --manual --email test@gmail.com -d ab.abc.com
$mkdir -p /tmp/certbot/public_html/.well-known/acme-challenge
$cd /tmp/certbot/public_html
$printf "%s" <key> > .well-known/acme-challenge/<key>
$sudo $(command -v python2 || command -v python2.7 || command -v python2.6) -c "import BaseHTTPServer, SimpleHTTPServer; s=BaseHTTPServer.HTTPServer(('', 80), SimpleHTTPServer.SimpleHTTPRequestHandler);s.serve_forever()"

then I have

108.14.0.213 - - [09/Jul/2017 03:32:26] "GET /path? HTTP/1.1" 404 -
^CTraceback (most recent call last):
  File "<string>", line 1, in <module>
  File "/usr/lib/python2.7/SocketServer.py", line 236, in serve_forever
    poll_interval)
  File "/usr/lib/python2.7/SocketServer.py", line 155, in _eintr_retry
    return func(*args)
KeyboardInterrupt
</code>```

答:
if all you want to do is install an SSl certificate on your instance then the best would be to generate a CSR and sign one with a third party provider like trustsign. Note that your choice SSL Certificate in this case would have to be a wildcard ssl cert type given your name format above. Should be *ab.abc.com

If this is just a test server and you don't care about the security warning, then you can sign it your self as follow but you will have to accept the security warning when accessing the url from your browser

```<code># openssl genrsa -out keyfile.key 2048
# openssl req -new -key keyfile.key -out certrequest.csr
# openssl x509 -req -days 3650 -in certrequest.csr -signkey keyfile.key -out certificate.pem
</code>```

You can then update your nginx config to look as follow:

```<code>server {
    listen       80;
    listen       443;
    ssl on;
    ssl_certificate /path_to_your_public_Cert/certificate.pem;
    ssl_certificate_key /path_to_yourPrivate_key/keyfile.key;
    server_name ~^(aaa(?<site>[0-9]+)).ab.abc.com;
    location / {
        set $custom_port 90$site;
        if ($custom_port ~ "^.{3}$") {
            set $custom_port 900$site;
        }
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_set_header Host $host;
        proxy_pass http://127.0.0.1:$custom_port;
    }
}
</code>```

Title: AWS EC2 + Nginx + SSL fro subdomain

Body:
Can anyone explain to me a little bit how I can install SSL on my AWS EC2. I read lots of article that those steps are simple but I tried couple of them and none of them works.

I have one AWS EC2

EC2 staic ip, 54.X.X.X

subdoamin, xxxx.ab.abc.com

security group: port from

custom 80, 443, 9000-9100

nginx redirect

aaa1.ab.abc.com:80 to aaa1.ab.abc.com:9001

aaa2.ab.abc.com:80 to aaa1.ab.abc.com:9002

aaa3.ab.abc.com:80 to aaa1.ab.abc.com:9003

...

aaa(n).ab.abc.com:80 to aaa1.ab.abc.com:900(n)

ngnix.conf
server {
    listen       80;
    server_name ~^(aaa(?<site>[0-9]+)).ab.abc.com;
    location / {
        set $custom_port 90$site;
        if ($custom_port ~ "^.{3}$") {
            set $custom_port 900$site;
        }
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_set_header Host $host;
        proxy_pass http://127.0.0.1:$custom_port;
    }
}

How can I install SSL into EC2 so no matter which subdomain I hit. it will have certificated?

Steps I have done.

$sudo service nginx stop
$git clone https://github.com/certbot/certbot.git to use certbot to generate SSL key
$./certbot-auto certonly --manual --email test@gmail.com -d ab.abc.com
$mkdir -p /tmp/certbot/public_html/.well-known/acme-challenge
$cd /tmp/certbot/public_html
$printf "%s" <key> > .well-known/acme-challenge/<key>
$sudo $(command -v python2 || command -v python2.7 || command -v python2.6) -c "import BaseHTTPServer, SimpleHTTPServer; s=BaseHTTPServer.HTTPServer(('', 80), SimpleHTTPServer.SimpleHTTPRequestHandler);s.serve_forever()"

then I have

108.14.0.213 - - [09/Jul/2017 03:32:26] "GET /path? HTTP/1.1" 404 -
^CTraceback (most recent call last):
  File "<string>", line 1, in <module>
  File "/usr/lib/python2.7/SocketServer.py", line 236, in serve_forever
    poll_interval)
  File "/usr/lib/python2.7/SocketServer.py", line 155, in _eintr_retry
    return func(*args)
KeyboardInterrupt

Body:
if all you want to do is install an SSl certificate on your instance then the best would be to generate a CSR and sign one with a third party provider like trustsign. Note that your choice SSL Certificate in this case would have to be a wildcard ssl cert type given your name format above. Should be *ab.abc.com

If this is just a test server and you don't care about the security warning, then you can sign it your self as follow but you will have to accept the security warning when accessing the url from your browser

# openssl genrsa -out keyfile.key 2048
# openssl req -new -key keyfile.key -out certrequest.csr
# openssl x509 -req -days 3650 -in certrequest.csr -signkey keyfile.key -out certificate.pem

You can then update your nginx config to look as follow:

server {
    listen       80;
    listen       443;
    ssl on;
    ssl_certificate /path_to_your_public_Cert/certificate.pem;
    ssl_certificate_key /path_to_yourPrivate_key/keyfile.key;
    server_name ~^(aaa(?<site>[0-9]+)).ab.abc.com;
    location / {
        set $custom_port 90$site;
        if ($custom_port ~ "^.{3}$") {
            set $custom_port 900$site;
        }
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_set_header Host $host;
        proxy_pass http://127.0.0.1:$custom_port;
    }
}


答:
this is what i usually do (i develop websites up to 4k resoultion, but they are locked to 1920px and then they are centered (just like you want)

I set html & body width and height to 100%, then i set the body max width to 1940px and i apply a padding left and right of 10 px so that it is bordered nicely.

This is the code i usually use:

```<code>html, body{
 display:block;
 width: 100%;
 height: 100%;
 position:relative;
}

body{
 max-width:1940px;
 padding-left:10px;
 padding-right:10px;
}
</code>```

and you obtain something like this:

You don't have to border it (the white gap before the light gray color is the border i'm talking about) but that's my preference.

Title: Set max width of website then center this material if browser is bigger than set width

Body:
this is what i usually do (i develop websites up to 4k resoultion, but they are locked to 1920px and then they are centered (just like you want)

I set html & body width and height to 100%, then i set the body max width to 1940px and i apply a padding left and right of 10 px so that it is bordered nicely.

This is the code i usually use:

html, body{
 display:block;
 width: 100%;
 height: 100%;
 position:relative;
}

body{
 max-width:1940px;
 padding-left:10px;
 padding-right:10px;
}

and you obtain something like this:

You don't have to border it (the white gap before the light gray color is the border i'm talking about) but that's my preference.


问:
How to Represent collection of alternatives in JSON-LD
I have properties in my model which have value as alternate array (which indicates a collection of alternates from which only one value is to be chosen).
Earlier I was using RDF/XML to do this using rdf:Alt.  See the following example

```<code><rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:ex="http://ns.example.com/example/">
<rdf:Description>
    <ex:prop1>
        <rdf:Alt>
            <rdf:li>100</rdf:li>
            <rdf:li>120</rdf:li>
            <rdf:li>130</rdf:li>
        </rdf:Alt>
    </ex:prop1>
</rdf:Description>
</rdf:RDF>
</code>```

But now I want to do same thing in JSON-LD. I tried converting the above snippet to JSON-LD by online converter and got the following result

```<code>{
  "@context": {
    "ex": "http://ns.example.com/example/",
    "rdf": "http://www.w3.org/1999/02/22-rdf-syntax-ns#"
  },
  "@graph": [
    {
      "@id": "_:g70327238021300",
      "ex:prop1": {
        "@id": "_:g70327280101680"
      }
    },
    {
      "@id": "_:g70327280101680",
      "@type": "rdf:Alt",
      "rdf:_1": "100",
      "rdf:_2": "120",
      "rdf:_3": "130"
    }
  ]
}
</code>```

Actually I found out that rdf:Alt/Seq/Bag are marked as archaic by w3c. There is @list and @set for ordered and unordered arrays respectively in JSON-LD. So is there any other way to do this in JSON-LD without using "rdf:Alt" as @type?

答:
The rdf:li expansion in to rdf:_n is a feature of RDF/XML, which is really the only format to provide native support for rdf:Alt/Bag/Seq. As you note, these are considered archaic, so don't look for any native support in other serializations, including JSON-LD.

For other ways of collecting information, other than RDF Collections, which have semantic support in RDF Concepts, and are directly supported by most RDF serializations, look to ontologies such as the Ordered List Ontology, which shows how you might do something similar to rdf:Alt semantics using semantics, rather than syntax.

For example, schema.org has a Choose Action, which seems like it is similar to what you want to do. The related Vote Action is also similar.

Body:
I have properties in my model which have value as alternate array (which indicates a collection of alternates from which only one value is to be chosen).
Earlier I was using RDF/XML to do this using rdf:Alt.  See the following example

<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:ex="http://ns.example.com/example/">
<rdf:Description>
    <ex:prop1>
        <rdf:Alt>
            <rdf:li>100</rdf:li>
            <rdf:li>120</rdf:li>
            <rdf:li>130</rdf:li>
        </rdf:Alt>
    </ex:prop1>
</rdf:Description>
</rdf:RDF>

But now I want to do same thing in JSON-LD. I tried converting the above snippet to JSON-LD by online converter and got the following result

{
  "@context": {
    "ex": "http://ns.example.com/example/",
    "rdf": "http://www.w3.org/1999/02/22-rdf-syntax-ns#"
  },
  "@graph": [
    {
      "@id": "_:g70327238021300",
      "ex:prop1": {
        "@id": "_:g70327280101680"
      }
    },
    {
      "@id": "_:g70327280101680",
      "@type": "rdf:Alt",
      "rdf:_1": "100",
      "rdf:_2": "120",
      "rdf:_3": "130"
    }
  ]
}

Actually I found out that rdf:Alt/Seq/Bag are marked as archaic by w3c. There is @list and @set for ordered and unordered arrays respectively in JSON-LD. So is there any other way to do this in JSON-LD without using "rdf:Alt" as @type?


问:
Objective-C: Pass Variable to block
I am very inexperienced with blocks. I have not mastered the syntax.

What I would like to do is to pass a date obtained in the first part of a method into a completion block so that the date is not set until the completion block runs (ie everything else is done).   Can anyone suggest how to do this?  Following gives error use of undeclared Identifier secondItem.

Edited:

```<code>- (void)myMethod: (NSInteger *) state {
    switch (state) {
        case 1: {
//do some stuff
} completion:^(BOOL finished) {
                   //finish up
                }];
            }
            break;
        }
 default: {
Items* firstItem = [self.fetchedResultsController objectAtIndexPath:indexPath];
           __ block NSDate* myDate = firstitem.date;
Items* secondItem = [self.fetchedResultsController objectAtIndexPath:sourceIndexPath];

            } completion:^(BOOL finished) {

                secondItem.date = __block myDate;//ERROR THROWN HERE
            }];
            break;
        }
    }
</code>```

答: Try using the __block keyword. The docs can be found here</p>

Title: Objective-C: Pass Variable to block

Body:
I am very inexperienced with blocks. I have not mastered the syntax.

What I would like to do is to pass a date obtained in the first part of a method into a completion block so that the date is not set until the completion block runs (ie everything else is done).   Can anyone suggest how to do this?  Following gives error use of undeclared Identifier secondItem.

Edited:

- (void)myMethod: (NSInteger *) state {
    switch (state) {
        case 1: {
//do some stuff
} completion:^(BOOL finished) {
                   //finish up
                }];
            }
            break;
        }
 default: {
Items* firstItem = [self.fetchedResultsController objectAtIndexPath:indexPath];
           __ block NSDate* myDate = firstitem.date;
Items* secondItem = [self.fetchedResultsController objectAtIndexPath:sourceIndexPath];

            } completion:^(BOOL finished) {

                secondItem.date = __block myDate;//ERROR THROWN HERE
            }];
            break;
        }
    }