问:
Can't add time to time in PHP
So I have this code:

```<code>$laikas = htmlspecialchars($_POST['rodymolaikas']);
$laikas = date( "H:i:s", strtotime( $laikas ) );

  $videotrukme = $_POST['videotrukme'];
  $videotrukme1 = round($videotrukme);
  $videotrukme2 = sprintf('%02d:%02d:%02d', ($videotrukme1/3600),($videotrukme/60%60), $videotrukme%60);

$laikas_end = date('H:i:s', strtotime($laikas) + strtotime($videotrukme2));

echo $laikas_end;
</code>```

The variables are even to:

```<code>$laikas = 17:00:00;
$videotrukme2 = 00:01:12;
</code>```

But the answer I get is:

```<code>laikas_end = 02:00:00
</code>```

Could you please tell me why is that happening?

答:
You can accomplish time addition like thi</p>

```<code><?php
$laikas = htmlspecialchars($_POST['rodymolaikas']);
$laikas = date( "H:i:s", strtotime( $laikas ) );
$videotrukme2 = $_POST['rodymolaikas'];
$videotrukme2 = date( "H:i:s", strtotime( $videotrukme2 ) );

$h =  strtotime($laikas);
$h2 = strtotime($videotrukme2);

$minute = date("i", $h2);
$second = date("s", $h2);
$hour = date("H", $h2);

$convert = strtotime("+$minute minutes", $h);
$convert = strtotime("+$second seconds", $convert);
$convert = strtotime("+$hour hours", $convert);
$laikas_end = date('H:i:s', $convert);

echo $laikas_end;
?>
</code>```

Title: Can't add time to time in PHP

Body:
So I have this code:

$laikas = htmlspecialchars($_POST['rodymolaikas']);
$laikas = date( "H:i:s", strtotime( $laikas ) );

  $videotrukme = $_POST['videotrukme'];
  $videotrukme1 = round($videotrukme);
  $videotrukme2 = sprintf('%02d:%02d:%02d', ($videotrukme1/3600),($videotrukme/60%60), $videotrukme%60);

$laikas_end = date('H:i:s', strtotime($laikas) + strtotime($videotrukme2));

echo $laikas_end;

The variables are even to:

$laikas = 17:00:00;
$videotrukme2 = 00:01:12;

But the answer I get is:

laikas_end = 02:00:00

Could you please tell me why is that happening?

Body:
You can accomplish time addition like thi

<?php
$laikas = htmlspecialchars($_POST['rodymolaikas']);
$laikas = date( "H:i:s", strtotime( $laikas ) );
$videotrukme2 = $_POST['rodymolaikas'];
$videotrukme2 = date( "H:i:s", strtotime( $videotrukme2 ) );

$h =  strtotime($laikas);
$h2 = strtotime($videotrukme2);

$minute = date("i", $h2);
$second = date("s", $h2);
$hour = date("H", $h2);

$convert = strtotime("+$minute minutes", $h);
$convert = strtotime("+$second seconds", $convert);
$convert = strtotime("+$hour hours", $convert);
$laikas_end = date('H:i:s', $convert);

echo $laikas_end;
?>


来源: stackexchange

问:
Rails Paperclip how to use filter options of ImageMagick?
I recently implemented Paperclip with Rails and want to try out some of the filter options from ImageMagick such as blur. I've not been able to find any examples of how to do this. Does it get passed through :style as another option?

```<code>:styles => { :medium => "300x300#", :thumb => "100x100#" }
</code>```

@plang's answer was correct but I wanted to give the exact solution to the blur, just in case someone was looking and found this question:

```<code>:convert_options => { :all => "-blur 0x8" }
// -blur  {radius}x{sigma}
</code>```

Which changed this:

To this:

答:
I did not test this, but you should be able to use the "convert_options" parameter, like this:

```<code>:convert_options => { :all => ‘-colorspace Gray’ }
</code>```

Have a look at https://github.com/thoughtbot/paperclip/blob/master/lib/paperclip/thumbnail.rb

I personnaly use my own processor.

In Model:

```<code>  has_attached_file :logo,
                    :url  => PaperclipAssetsController.config_url,
                    :path => PaperclipAssetsController.config_path,
                    :styles => {
                                 :grayscale => { :processors => [:grayscale] }
                               }
</code>```

In lib:

```<code>module Paperclip
  # Handles grayscale conversion of images that are uploaded.
  class Grayscale < Processor

    def initialize file, options = {}, attachment = nil
      super
      @format = File.extname(@file.path)
      @basename = File.basename(@file.path, @format)
    end

     def make
       src = @file
       dst = Tempfile.new([@basename, @format])
       dst.binmode

       begin
         parameters = []
         parameters << ":source"
         parameters << "-colorspace Gray"
         parameters << ":dest"

         parameters = parameters.flatten.compact.join(" ").strip.squeeze(" ")

         success = Paperclip.run("convert", parameters, :source => "#{File.expand_path(src.path)}[0]", :dest => File.expand_path(dst.path))
       rescue PaperclipCommandLineError => e
         raise PaperclipError, "There was an error during the grayscale conversion for #{@basename}" if @whiny
       end

       dst
     end

  end
end
</code>```

This might not be 100% necessary for a simple grayscale conversion, but it works!

ContentLicense: CC BY-SA 2.5

Body:
I recently implemented Paperclip with Rails and want to try out some of the filter options from ImageMagick such as blur. I've not been able to find any examples of how to do this. Does it get passed through :style as another option?

:styles => { :medium => "300x300#", :thumb => "100x100#" }

@plang's answer was correct but I wanted to give the exact solution to the blur, just in case someone was looking and found this question:

:convert_options => { :all => "-blur 0x8" }
// -blur  {radius}x{sigma}

Which changed this:

To this:

Body:
I did not test this, but you should be able to use the "convert_options" parameter, like this:

:convert_options => { :all => ‘-colorspace Gray’ }

Have a look at https://github.com/thoughtbot/paperclip/blob/master/lib/paperclip/thumbnail.rb

I personnaly use my own processor.

In Model:

  has_attached_file :logo,
                    :url  => PaperclipAssetsController.config_url,
                    :path => PaperclipAssetsController.config_path,
                    :styles => {
                                 :grayscale => { :processors => [:grayscale] }
                               }

In lib:

module Paperclip
  # Handles grayscale conversion of images that are uploaded.
  class Grayscale < Processor

    def initialize file, options = {}, attachment = nil
      super
      @format = File.extname(@file.path)
      @basename = File.basename(@file.path, @format)
    end

     def make
       src = @file
       dst = Tempfile.new([@basename, @format])
       dst.binmode

       begin
         parameters = []
         parameters << ":source"
         parameters << "-colorspace Gray"
         parameters << ":dest"

         parameters = parameters.flatten.compact.join(" ").strip.squeeze(" ")

         success = Paperclip.run("convert", parameters, :source => "#{File.expand_path(src.path)}[0]", :dest => File.expand_path(dst.path))
       rescue PaperclipCommandLineError => e
         raise PaperclipError, "There was an error during the grayscale conversion for #{@basename}" if @whiny
       end

       dst
     end

  end
end

This might not be 100% necessary for a simple grayscale conversion, but it works!

ContentLicense: CC BY-SA 3.0


问:
Regarding Warning: Accessing PropTypes via the main React package is deprecated. Use the prop-types package from npm instead
I am running jest with enzyme but I am getting the above warning specifically from react-router dependency in the class I am trying to test. My question is why I am getting this warning as I have already downgraded my react version to 15.1.1.

```<code>Package.json
 "dependencies": {
    "axios": "^0.16.1",
    "babel": "^6.23.0",
    "babel-polyfill": "^6.23.0",
    "babel-preset-es2015": "^6.9.0",
    "babel-preset-react": "^6.5.0",
    "bootstrap": "^3.3.5",
    "boron": "^0.2.3",
    "browserify": "^13.0.1",
    "connect-history-api-fallback": "^1.2.0",
    "debounce": "^1.0.0",
    "envify": "^3.4.0",
    "es6-promise": "^3.2.1",
    "font-awesome": "^4.6.3",
    "jquery": "^2.2.4",
    "jwt-decode": "^2.2.0",
    "minimist": "^1.2.0",
    "node-fetch": "1.6.3",
    "node-notifier": "^4.6.0",
    "object-assign": "^4.1.0",
    "react": "^15.1.0",
    "react-autosuggest": "^3.8.0",
    "react-dnd": "^2.1.4",
    "react-dnd-html5-backend": "^2.1.2",
    "react-document-title": "^2.0.3",
    "react-dom": "^15.1.0",
    "react-dropdown": "^1.0.4",
    "react-quill": "^0.4.1",
    "react-router": "^2.4.1",
    "react-select": "^1.0.0-beta13",
    "react-select2-wrapper": "^0.6.1",
    "react-tag-input": "^3.0.3",
    "reflux": "0.4.1",
    "request": "^2.81.0",
    "request-promise": "^4.2.0",
    "toastr": "^2.1.0",
    "underscore": "^1.8.3",
    "vinyl-source-stream": "^1.1.0",
    "watchify": "^3.7.0",
    "webpack": "^2.4.1",
    "whatwg-fetch": "^1.0.0"
  },
  "devDependencies": {
    "babel-core": "^6.24.1",
    "babel-jest": "^6.0.1",
    "babel-loader": "^7.0.0",
    "babelify": "^7.3.0",
    "css-loader": "^0.28.0",
    "del": "^2.2.0",
    "enzyme": "^2.1.0",
    "eslint": "^3.19.0",
    "eslint-config-defaults": "^9.0.0",
    "eslint-loader": "^1.7.1",
    "eslint-plugin-react": "^6.10.3",
    "extract-text-webpack-plugin": "^2.1.0",
    "file-loader": "^0.11.1",
    "identity-obj-proxy": "^3.0.0",
    "jest": "^15.1.1",
    "jest-cli": "^15.1.1",
    "less": "^2.7.2",
    "less-loader": "^4.0.3",
    "node-sass": "^4.5.2",
    "react-addons-test-utils": "^15.1.1",
    "react-bootstrap": "^0.29.5",
    "regenerator-runtime": "^0.10.5",
    "sass-loader": "^6.0.3",
    "scss-loader": "0.0.1",
    "url-loader": "^0.5.8",
    "yargs": "^7.1.0"
  },
</code>```

The full stack trace of error is:

```<code>console.error node_modules\fbjs\lib\warning.js:36
    Warning: ReactTestUtils has been moved to react-dom/test-utils. Update references to remove this warning.

 FAIL  web\test\testClass.test.js
  ● Test suite failed to run

    Warning: Accessing PropTypes via the main React package is deprecated. Use the prop-types package from npm instead.

      at CustomConsole.Object.<anonymous>.console.error (web\test\jestSetup.js:12:11)
      at printWarning (node_modules\fbjs\lib\warning.js:36:17)
      at warning (node_modules\fbjs\lib\warning.js:60:22)
      at Object.get [as PropTypes] (node_modules\react\lib\React.js:95:49)
      at Object.<anonymous> (node_modules\react-router\lib\InternalPropTypes.js:9:18)
      at Object.<anonymous> (node_modules\react-router\lib\PropTypes.js:12:26)
      at Object.<anonymous> (node_modules\react-router\lib\index.js:15:19)
      at Object.<anonymous> (web\js\components\common\toolBar.jsx:2:20)
      at Object.<anonymous> (web\test\testClass.test.js:5:16)
      at process._tickCallback (internal\process\next_tick.js:103:7)
</code>```

I dont want to upgrade from Router v2 to latest version 4 as I have to do lot of upgradation in my code. Why this error is coming although I am not using latest version of React where this package was moved from 'react' to 'prop-types'.

答:
React Router has updated the packages to handle the React library changes for 'createClass' and PropTypes.

Version 2

Doesn't look like they updated this one. Makes sense because version 4 is most current.

Version 3

https://github.com/ReactTraining/react-router/releases/tag/v3.0.4

(though you could likely use 3.0.5 safely)

Body:
I am running jest with enzyme but I am getting the above warning specifically from react-router dependency in the class I am trying to test. My question is why I am getting this warning as I have already downgraded my react version to 15.1.1.

Package.json
 "dependencies": {
    "axios": "^0.16.1",
    "babel": "^6.23.0",
    "babel-polyfill": "^6.23.0",
    "babel-preset-es2015": "^6.9.0",
    "babel-preset-react": "^6.5.0",
    "bootstrap": "^3.3.5",
    "boron": "^0.2.3",
    "browserify": "^13.0.1",
    "connect-history-api-fallback": "^1.2.0",
    "debounce": "^1.0.0",
    "envify": "^3.4.0",
    "es6-promise": "^3.2.1",
    "font-awesome": "^4.6.3",
    "jquery": "^2.2.4",
    "jwt-decode": "^2.2.0",
    "minimist": "^1.2.0",
    "node-fetch": "1.6.3",
    "node-notifier": "^4.6.0",
    "object-assign": "^4.1.0",
    "react": "^15.1.0",
    "react-autosuggest": "^3.8.0",
    "react-dnd": "^2.1.4",
    "react-dnd-html5-backend": "^2.1.2",
    "react-document-title": "^2.0.3",
    "react-dom": "^15.1.0",
    "react-dropdown": "^1.0.4",
    "react-quill": "^0.4.1",
    "react-router": "^2.4.1",
    "react-select": "^1.0.0-beta13",
    "react-select2-wrapper": "^0.6.1",
    "react-tag-input": "^3.0.3",
    "reflux": "0.4.1",
    "request": "^2.81.0",
    "request-promise": "^4.2.0",
    "toastr": "^2.1.0",
    "underscore": "^1.8.3",
    "vinyl-source-stream": "^1.1.0",
    "watchify": "^3.7.0",
    "webpack": "^2.4.1",
    "whatwg-fetch": "^1.0.0"
  },
  "devDependencies": {
    "babel-core": "^6.24.1",
    "babel-jest": "^6.0.1",
    "babel-loader": "^7.0.0",
    "babelify": "^7.3.0",
    "css-loader": "^0.28.0",
    "del": "^2.2.0",
    "enzyme": "^2.1.0",
    "eslint": "^3.19.0",
    "eslint-config-defaults": "^9.0.0",
    "eslint-loader": "^1.7.1",
    "eslint-plugin-react": "^6.10.3",
    "extract-text-webpack-plugin": "^2.1.0",
    "file-loader": "^0.11.1",
    "identity-obj-proxy": "^3.0.0",
    "jest": "^15.1.1",
    "jest-cli": "^15.1.1",
    "less": "^2.7.2",
    "less-loader": "^4.0.3",
    "node-sass": "^4.5.2",
    "react-addons-test-utils": "^15.1.1",
    "react-bootstrap": "^0.29.5",
    "regenerator-runtime": "^0.10.5",
    "sass-loader": "^6.0.3",
    "scss-loader": "0.0.1",
    "url-loader": "^0.5.8",
    "yargs": "^7.1.0"
  },

The full stack trace of error is:

console.error node_modules\fbjs\lib\warning.js:36
    Warning: ReactTestUtils has been moved to react-dom/test-utils. Update references to remove this warning.

 FAIL  web\test\testClass.test.js
  ● Test suite failed to run

    Warning: Accessing PropTypes via the main React package is deprecated. Use the prop-types package from npm instead.

      at CustomConsole.Object.<anonymous>.console.error (web\test\jestSetup.js:12:11)
      at printWarning (node_modules\fbjs\lib\warning.js:36:17)
      at warning (node_modules\fbjs\lib\warning.js:60:22)
      at Object.get [as PropTypes] (node_modules\react\lib\React.js:95:49)
      at Object.<anonymous> (node_modules\react-router\lib\InternalPropTypes.js:9:18)
      at Object.<anonymous> (node_modules\react-router\lib\PropTypes.js:12:26)
      at Object.<anonymous> (node_modules\react-router\lib\index.js:15:19)
      at Object.<anonymous> (web\js\components\common\toolBar.jsx:2:20)
      at Object.<anonymous> (web\test\testClass.test.js:5:16)
      at process._tickCallback (internal\process\next_tick.js:103:7)

I dont want to upgrade from Router v2 to latest version 4 as I have to do lot of upgradation in my code. Why this error is coming although I am not using latest version of React where this package was moved from 'react' to 'prop-types'.


问:
How do I check for nulls in an '==' operator overload without infinite recursion?
The following will cause infinite recursion on the == operator overload method

```<code>    Foo foo1 = null;
    Foo foo2 = new Foo();
    Assert.IsFalse(foo1 == foo2);

    public static bool operator ==(Foo foo1, Foo foo2) {
        if (foo1 == null) return foo2 == null;
        return foo1.Equals(foo2);
    }
</code>```

How do I check for nulls?

答:
If you are using C# 7 or later you can use null constant pattern matching:

```<code>public static bool operator==(Foo foo1, Foo foo2)
{
    if (foo1 is null)
        return foo2 is null;
    return foo1.Equals(foo2);
}
</code>```

This gives you slightly neater code than the one calling object.ReferenceEquals(foo1, null)

OwnerDisplayName: Andy J

Body:
The following will cause infinite recursion on the == operator overload method

    Foo foo1 = null;
    Foo foo2 = new Foo();
    Assert.IsFalse(foo1 == foo2);

    public static bool operator ==(Foo foo1, Foo foo2) {
        if (foo1 == null) return foo2 == null;
        return foo1.Equals(foo2);
    }

How do I check for nulls?

Body:
If you are using C# 7 or later you can use null constant pattern matching:

public static bool operator==(Foo foo1, Foo foo2)
{
    if (foo1 is null)
        return foo2 is null;
    return foo1.Equals(foo2);
}

This gives you slightly neater code than the one calling object.ReferenceEquals(foo1, null)


问:
Reference sheet name via cell inside Excel formula
As you can see in the image or formula below, I am writing a series of formulas that are referencing the sheet "Lulu."  Instead of rewriting "Lulu" over and over, I would like to write Lulu once in cell B1 and reference cell B1 inside the formula.

```<code>=AVERAGE(LULU!$C$4:$C$5)/AVERAGE(LULU!$D$4:$D$5)-1
</code>```

答:
Use INDIRECT(), but this will be longer:</p>

```<code>=AVERAGE(INDIRECT("'" & B1 & "'!$C$4:$C$5"))/AVERAGE(INDIRECT("'" & B1 & "'!$D$4:$D$5"))-1
</code>```

Body:
As you can see in the image or formula below, I am writing a series of formulas that are referencing the sheet "Lulu."  Instead of rewriting "Lulu" over and over, I would like to write Lulu once in cell B1 and reference cell B1 inside the formula.

=AVERAGE(LULU!$C$4:$C$5)/AVERAGE(LULU!$D$4:$D$5)-1

Body:
Use INDIRECT(), but this will be longer:

=AVERAGE(INDIRECT("'" & B1 & "'!$C$4:$C$5"))/AVERAGE(INDIRECT("'" & B1 & "'!$D$4:$D$5"))-1


问:
How to read the JSON String
Kindly need your help as this really taking me long time to try. From JSP, I passed the stingnify JSON object as a String to the Java action, it like

String jsonDealer = [{"dealerID":"VARSSWK103","dealerName":"Dealer ABC"},
{"dealerID":"VARSSTH008","dealerName":"Dealer XYZ"}]

How I can convert this to JSON object/ or ArrayList of Dealer, so that I can retrieve the dealer ID and dealer name?

Thanks for all help...

答:
You'll need a JSON deserializer. There are quite a few for Java listed at the bottom of the JSON.org page. As of this writing:

org.json.

org.json.me.

Jackson JSON Processor.

Json-lib.

JSON Tools.

json-simple.

Stringtree.

SOJO.

Restlet.

google-gson.

...and 10 more. :-)

Title: How to read the JSON String


问:
Merging two columns with different information, python
I have a dataframe with one column of last names, and one column of first names. How do I merge these columns so that I have one column with first and last names?

Here is what I have:
First Name (Column 1)

John

Lisa

Jim

Last Name (Column 2)

Smith

Brown

Dandy

This is what I want:

Full Name

John Smith

Lisa Brown

Jim Dandy.

Thank you!

答:
Here's a sample df:

```<code>df
  first name last name
0        bob     smith
1       john     smith
2       bill     smith
</code>```

You can do the following to combine columns:

```<code>df['combined']= df['first name'] + ' ' + df['last name']

df
  first name last name    combined
0        bob     smith   bob smith
1       john     smith  john smith
2       bill     smith  bill smith
</code>```

Body:
Here's a sample df:

df
  first name last name
0        bob     smith
1       john     smith
2       bill     smith

You can do the following to combine columns:

df['combined']= df['first name'] + ' ' + df['last name']

df
  first name last name    combined
0        bob     smith   bob smith
1       john     smith  john smith
2       bill     smith  bill smith


问:
Pass event and arguments onChange in input in React
I have a component as below:

```<code>import React from 'react';

import MyComponent from '../utils/MyComponent';

export default class BasicList extends MyComponent {

    constructor(props) {
        let custom_methods = [
            'renderItemOrEditField', 'toggleEditing', 'moveCaretAtEnd',
            'editItem'
        ];
        super(props, custom_methods);
        this.state = {
            editing: null,
            current_text: ''
        };
    }

    // moveCaretAtEnd(e) {
    //     var temp_value = e.target.value
    //     e.target.value = ''
    //     e.target.value = temp_value
    // }

    editItem(event) {
        let current_value = event.target.value;
        alert(current_value + this.state.editing);
    }

    renderItemOrEditField(item) {
        console.log(item);
        if (this.state.editing === item.id) {
            return (
                <input
                  onKeyDown={ this.handleEditField }
                  type="text"
                  className="form-control"
                  ref={ `${item.type}_name_${ item.id }` }
                  name="title"
                  autofocus
                  onFocus={this.moveCaretAtEnd}
                  defaultValue={ item.name }
                  onChange={() => this.editItem(event)}
                />
            );
        } else {
            return (
                <li
                  onClick={this.toggleEditing.bind(null, item.id)}
                  key={item.id}
                  className="list-group-item">
                    {item.name}
                </li>
            );
        }
    }

    toggleEditing(item_id) {
        this.setState({editing: item_id});
    }

    render() {
        let li_elements = null;
        let items = this.props.items;

        if (items.length > 0) {
          li_elements = items.map((item) => {
              return (
                  this.renderItemOrEditField(item)
                //   {/* }<li key={item.id}>
                //       {item.name} -
                //       <button onClick={() => {this.props.deleteCallback(this.props.item_type, item.id, item.name)} }>
                //         Delete
                //       </button>
                //   </li> */}

              );
          });
        }

        return (
          <div>
            <h4>{this.props.title}:</h4>
                <ul className="list-group">
                    {li_elements}
                </ul>
          </div>
        );
    }
}
</code>```

I want to be able to make an API call when the user edits the name of an item. To do this, I need access to the new name, the type of item it is, and the ID of the item we're editing. I am having problems getting the correct data to an onChange handler in React. In editItem, this is coming in as undefined.

Trying

onChange={() => this.editItem}

has no errors, but does nothing.

Trying

onChange={() => this.editItem()}

yields Uncaught TypeError: Cannot read property 'target' of undefined

How can I have access to this.state and also the event object in this editItem onChange?

答:
onChange={() => this.editItem()} is not working because you forgot to bind it with your component:

```<code>constructor(props){
   ...
   this.editItem = this.editItem.bind(this);
   ...
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a component as below:

import React from 'react';

import MyComponent from '../utils/MyComponent';

export default class BasicList extends MyComponent {

    constructor(props) {
        let custom_methods = [
            'renderItemOrEditField', 'toggleEditing', 'moveCaretAtEnd',
            'editItem'
        ];
        super(props, custom_methods);
        this.state = {
            editing: null,
            current_text: ''
        };
    }

    // moveCaretAtEnd(e) {
    //     var temp_value = e.target.value
    //     e.target.value = ''
    //     e.target.value = temp_value
    // }

    editItem(event) {
        let current_value = event.target.value;
        alert(current_value + this.state.editing);
    }

    renderItemOrEditField(item) {
        console.log(item);
        if (this.state.editing === item.id) {
            return (
                <input
                  onKeyDown={ this.handleEditField }
                  type="text"
                  className="form-control"
                  ref={ `${item.type}_name_${ item.id }` }
                  name="title"
                  autofocus
                  onFocus={this.moveCaretAtEnd}
                  defaultValue={ item.name }
                  onChange={() => this.editItem(event)}
                />
            );
        } else {
            return (

                    {item.name}

            );
        }
    }

    toggleEditing(item_id) {
        this.setState({editing: item_id});
    }

    render() {
        let li_elements = null;
        let items = this.props.items;

        if (items.length > 0) {
          li_elements = items.map((item) => {
              return (
                  this.renderItemOrEditField(item)
                //   {/* }

                //       {item.name} -
                //       <button onClick={() => {this.props.deleteCallback(this.props.item_type, item.id, item.name)} }>
                //         Delete
                //       </button>
                //
 */}

              );
          });
        }

        return (

{this.props.title}:

                    {li_elements}

        );
    }
}

I want to be able to make an API call when the user edits the name of an item. To do this, I need access to the new name, the type of item it is, and the ID of the item we're editing. I am having problems getting the correct data to an onChange handler in React. In editItem, this is coming in as undefined.

Trying

onChange={() => this.editItem}

has no errors, but does nothing.

Trying

onChange={() => this.editItem()}

yields Uncaught TypeError: Cannot read property 'target' of undefined

How can I have access to this.state and also the event object in this editItem onChange?

Body:
onChange={() => this.editItem()} is not working because you forgot to bind it with your component:

constructor(props){
   ...
   this.editItem = this.editItem.bind(this);
   ...
}


答:
Because you are not passing the event object, write it like this:

```<code>onChange={(event) => this.editItem(event)}
</code>```

Title: Pass event and arguments onChange in input in React

Body:
Because you are not passing the event object, write it like this:

onChange={(event) => this.editItem(event)}


问:
Getting a node in XML using fieldname in ESQL
How to get the elements of an XML if we know the nodename.I have a sample XML like below.

```<code><?xml version="1.0"?>
<!DOCTYPE PARTS SYSTEM "parts.dtd">
<?xml-stylesheet type="text/css" href="xmlpartsstyle.css"?>
<PARTS>
   <TITLE>Computer Parts</TITLE>
<PART>
  <ITEM>Motherboard</ITEM>
  <MANUFACTURER>ASUS</MANUFACTURER>
  <MODEL>P3B-F</MODEL>
  <COST> 123.00</COST>
</PART>
<PART>
  <ITEM>Video Card</ITEM>
  <MANUFACTURER>ATI</MANUFACTURER>
  <MODEL>All-in-Wonder Pro</MODEL>
  <COST> 160.00</COST>
</PART>
<PART>
  <ITEM>Sound Card</ITEM>
  <MANUFACTURER>Creative Labs</MANUFACTURER>
  <MODEL>Sound Blaster Live</MODEL>
  <COST> 80.00</COST>
</PART>
<PART>
  <ITEMᡋ inch Monitor</ITEM>
  <MANUFACTURER>LG Electronics</MANUFACTURER>
  <MODEL> 995E</MODEL>
  <COST> 290.00</COST>
</PART>
</code>```

I want to get all the  element in an array using esql. How to do it?

答:
Assuming you are parsing the xml on entry then you can simply just use the following:</p>

```<code>SET myvar[] = InputRoot.XMLNSC.PARTS.PART[]
</code>```

Body:
How to get the elements of an XML if we know the nodename.I have a sample XML like below.

<?xml version="1.0"?>
<!DOCTYPE PARTS SYSTEM "parts.dtd">
<?xml-stylesheet type="text/css" href="xmlpartsstyle.css"?>
<PARTS>
   <TITLE>Computer Parts</TITLE>
<PART>
  <ITEM>Motherboard</ITEM>
  <MANUFACTURER>ASUS</MANUFACTURER>
  <MODEL>P3B-F</MODEL>
  <COST> 123.00</COST>
</PART>
<PART>
  <ITEM>Video Card</ITEM>
  <MANUFACTURER>ATI</MANUFACTURER>
  <MODEL>All-in-Wonder Pro</MODEL>
  <COST> 160.00</COST>
</PART>
<PART>
  <ITEM>Sound Card</ITEM>
  <MANUFACTURER>Creative Labs</MANUFACTURER>
  <MODEL>Sound Blaster Live</MODEL>
  <COST> 80.00</COST>
</PART>
<PART>
  <ITEMᡋ inch Monitor</ITEM>
  <MANUFACTURER>LG Electronics</MANUFACTURER>
  <MODEL> 995E</MODEL>
  <COST> 290.00</COST>
</PART>

I want to get all the  element in an array using esql. How to do it?

Body:
Assuming you are parsing the xml on entry then you can simply just use the following:

SET myvar[] = InputRoot.XMLNSC.PARTS.PART[]


问:
How can I duplicate and delete from an array without changing the original one?
My goal is to write a method, trickysum(n) that does the following:

The method takes range of numbers 1 through n. The method then finds pairs of numbers in that range that meet a tricky qualification: The product of the pair of numbers must be equal to the sum of all numbers in the range, excluding this pair. The method then returns all number pairs that meet this qualification. Here is the expectation:

```<code>  trickysum(26)
  #=>[(15, 21), (21, 15)]
</code>```

Here is the code I have so far:

```<code>def trickysum(n)

result = []
arr = (1..n).to_a

0.upto(arr.length - 1) do |x|

  0.upto(arr.length - 1) do |y|

    prod = arr[x] * arr[y]
    #I create a new array to delete from to not affect the original
    #array. Would also love an easier way to do this :)
    new_arr = arr
    new_arr.delete(new_arr[x])
    new_arr.delete(new_arr[y])
    sum = new_arr.inject(:+)
    if sum == prod
      result << "(#{arr[x]},#{arr[y]})"
    end
  end
end

result

end
</code>```

I've looked over this code over and over and can't figure out why I'm getting the following error:

```<code>nil can't be coerced into Fixnum
(repl):7:in `*'
(repl):7:in `block (2 levels) in trickysum'
(repl):6:in `upto'
(repl):6:in `block in trickysum'
(repl):5:in `upto'
(repl):5:in `trickysum'
(repl):20:in `<main>'
</code>```

Where am I going wrong?

答:
Replace:

```<code>new_arr = arr
</code>```

With:

```<code>new_arr = arr.dup
</code>```

What's happening here is that you have created a shallow copy of the arr variable. Without explicitly duplicating the value, both new_arr and arr share the same location in memory.

Because of this, when you call new_arr.delete(new_arr[x]) and new_arr.delete(new_arr[y]), not only are you mutating the new array, but also the old one.

This means arr gets shorter in length, so your outer loop goes beyond its final value and you get a nil; hence the error.

With that said, I would have written this method totally differently, which would have avoided such subtle errors:

```<code>def trickysum(n)
  sum = (1..n).inject(:+)
  (1..n).combination(2).select do |a, b|
    (a * b) + a + b == sum
  end
end
</code>```

Ruby is a very expressive language. If you find yourself doing looping within loops, declaring temporary variables and appending to an array of results ... Then there's probably a much more elegant solution :)

Body:
My goal is to write a method, trickysum(n) that does the following:

The method takes range of numbers 1 through n. The method then finds pairs of numbers in that range that meet a tricky qualification: The product of the pair of numbers must be equal to the sum of all numbers in the range, excluding this pair. The method then returns all number pairs that meet this qualification. Here is the expectation:

  trickysum(26)
  #=>[(15, 21), (21, 15)]

Here is the code I have so far:

def trickysum(n)

result = []
arr = (1..n).to_a

0.upto(arr.length - 1) do |x|

  0.upto(arr.length - 1) do |y|

    prod = arr[x] * arr[y]
    #I create a new array to delete from to not affect the original
    #array. Would also love an easier way to do this :)
    new_arr = arr
    new_arr.delete(new_arr[x])
    new_arr.delete(new_arr[y])
    sum = new_arr.inject(:+)
    if sum == prod
      result << "(#{arr[x]},#{arr[y]})"
    end
  end
end

result

end

I've looked over this code over and over and can't figure out why I'm getting the following error:

nil can't be coerced into Fixnum
(repl):7:in `*'
(repl):7:in `block (2 levels) in trickysum'
(repl):6:in `upto'
(repl):6:in `block in trickysum'
(repl):5:in `upto'
(repl):5:in `trickysum'
(repl):20:in `'

Where am I going wrong?

Body:
Replace:

new_arr = arr

With:

new_arr = arr.dup

What's happening here is that you have created a shallow copy of the arr variable. Without explicitly duplicating the value, both new_arr and arr share the same location in memory.

Because of this, when you call new_arr.delete(new_arr[x]) and new_arr.delete(new_arr[y]), not only are you mutating the new array, but also the old one.

This means arr gets shorter in length, so your outer loop goes beyond its final value and you get a nil; hence the error.

With that said, I would have written this method totally differently, which would have avoided such subtle errors:

def trickysum(n)
  sum = (1..n).inject(:+)
  (1..n).combination(2).select do |a, b|
    (a * b) + a + b == sum
  end
end

Ruby is a very expressive language. If you find yourself doing looping within loops, declaring temporary variables and appending to an array of results ... Then there's probably a much more elegant solution :)


问:
Determine missing values based on lagged grouped values
I need to fill missing values based on previous and/or forward values, based on grouping. I would like to accomplish this using dplyr (although data.table solutions will also be welcomed).

Sample data:

```<code>testing <- tibble(key = c(10,10,10,10,10,10,20,20,20,20,20,20),
                  year = c(15,15,16,16,17,17,15,15,16,16,17,17),
                  name = c("abc","abc","","","dfg","dfg",
                          "","","nmm","nmm","",""),
                  is_name = c(1,1,0,0,1,1,0,0,0,0,0,0))

     key  year  name is_name
   <dbl> <dbl> <chr>   <dbl>
1     10    15   abc       1
2     10    15   abc       1
3     10    16             0
4     10    16             0
5     10    17   dfg       1
6     10    17   dfg       1
7     20    15             0
8     20    15             0
9     20    16   nmm       0
10    20    16   nmm       0
11    20    17             0
12    20    17             0
</code>```

I want to fill missing names (name) in a way that if the previous year of the same key is marked as is_name==1, than fill the missing with it.
So an output can be:

```<code>     key  year  name is_name name_new
   <dbl> <dbl> <chr>   <dbl>    <chr>
1     10    15   abc       1      abc
2     10    15   abc       1      abc
3     10    16             0      abc
4     10    16             0      abc
5     10    17   dfg       1      dfg
6     10    17   dfg       1      dfg
7     20    15             0
8     20    15             0
9     20    16   nmm       0      nmm
10    20    16   nmm       0      nmm
11    20    17             0
12    20    17             0
</code>```

I tried to use lag and leap, but it didn't move beyond the group (key)properly.

Thanks!

答:
This might work for you</p>

```<code>library(dplyr)
library(zoo)

testing <- testing %>%
           arrange(key, year) %>%
           mutate(name = ifelse(name == "", NA, name),
                  is_name = ifelse(is_name == 0, NA, is_name)) %>%
           group_by(key) %>%
           mutate(newname = ifelse((is.na(name) & na.locf(is_name, na.rm = FALSE) == 1), na.locf(name, na.rm = FALSE), name),
                  is_name = ifelse(is.na(is_name),0,is_name))
</code>```

Body:
I need to fill missing values based on previous and/or forward values, based on grouping. I would like to accomplish this using dplyr (although data.table solutions will also be welcomed).

Sample data:

testing <- tibble(key = c(10,10,10,10,10,10,20,20,20,20,20,20),
                  year = c(15,15,16,16,17,17,15,15,16,16,17,17),
                  name = c("abc","abc","","","dfg","dfg",
                          "","","nmm","nmm","",""),
                  is_name = c(1,1,0,0,1,1,0,0,0,0,0,0))

     key  year  name is_name
   <dbl> <dbl> <chr>   <dbl>
1     10    15   abc       1
2     10    15   abc       1
3     10    16             0
4     10    16             0
5     10    17   dfg       1
6     10    17   dfg       1
7     20    15             0
8     20    15             0
9     20    16   nmm       0
10    20    16   nmm       0
11    20    17             0
12    20    17             0

I want to fill missing names (name) in a way that if the previous year of the same key is marked as is_name==1, than fill the missing with it.
So an output can be:

     key  year  name is_name name_new
   <dbl> <dbl> <chr>   <dbl>    <chr>
1     10    15   abc       1      abc
2     10    15   abc       1      abc
3     10    16             0      abc
4     10    16             0      abc
5     10    17   dfg       1      dfg
6     10    17   dfg       1      dfg
7     20    15             0
8     20    15             0
9     20    16   nmm       0      nmm
10    20    16   nmm       0      nmm
11    20    17             0
12    20    17             0

I tried to use lag and leap, but it didn't move beyond the group (key)properly.

Thanks!

Body:
This might work for you

library(dplyr)
library(zoo)

testing <- testing %>%
           arrange(key, year) %>%
           mutate(name = ifelse(name == "", NA, name),
                  is_name = ifelse(is_name == 0, NA, is_name)) %>%
           group_by(key) %>%
           mutate(newname = ifelse((is.na(name) & na.locf(is_name, na.rm = FALSE) == 1), na.locf(name, na.rm = FALSE), name),
                  is_name = ifelse(is.na(is_name),0,is_name))


问:
Microsoft-Cognitive: Emotion API in Python
I get the response below after making a call to the emotion api.

```<code>{
  "FaceRectangle": {
    "Top": 141,
    "Left": 331,
    "Width": 52,
    "Height": 52
  },
  "Scores": {
    "Anger": 0.002451766,
    "Contempt": 0.0005512201,
    "Disgust": 0.0063303886,
    "Fear": 0.000122375583,
    "Happiness": 0.9589189,
    "Neutral": 0.0222537462,
    "Sadness": 0.008983561,
    "Surprise": 0.000388026354
  }
}
</code>```

How can I create a variable to hold just the score of happiness? Below is the python code:

```<code>import http.client, urllib.request, urllib.parse, urllib.error, base64, sys
headers = {
  key.
  'Content-Type': 'application/octet-stream',
  'Ocp-Apim-Subscription-Key': '************************',
}

params = urllib.parse.urlencode({

    })
body = open('my_image.jpg','rb').read()
try:
    conn = http.client.HTTPSConnection('westus.api.cognitive.microsoft.com')
    conn.request("POST", "/emotion/v1.0/recognize?%s" % params, body, headers)

    response = conn.getresponse()
    data = response.read()
    print(data)

    conn.close()
except Exception as e:
    print(e.args)
</code>```

答:
I think this should work: </p>

```<code>import json
dump = json.dumps(data)
json_string = json.loads(dump)
happiness =  str(json_string[0]['Scores']['Happiness'])
</code>```

Body:
I get the response below after making a call to the emotion api.

{
  "FaceRectangle": {
    "Top": 141,
    "Left": 331,
    "Width": 52,
    "Height": 52
  },
  "Scores": {
    "Anger": 0.002451766,
    "Contempt": 0.0005512201,
    "Disgust": 0.0063303886,
    "Fear": 0.000122375583,
    "Happiness": 0.9589189,
    "Neutral": 0.0222537462,
    "Sadness": 0.008983561,
    "Surprise": 0.000388026354
  }
}

How can I create a variable to hold just the score of happiness? Below is the python code:

import http.client, urllib.request, urllib.parse, urllib.error, base64, sys
headers = {
  key.
  'Content-Type': 'application/octet-stream',
  'Ocp-Apim-Subscription-Key': '************************',
}

params = urllib.parse.urlencode({

    })
body = open('my_image.jpg','rb').read()
try:
    conn = http.client.HTTPSConnection('westus.api.cognitive.microsoft.com')
    conn.request("POST", "/emotion/v1.0/recognize?%s" % params, body, headers)

    response = conn.getresponse()
    data = response.read()
    print(data)

    conn.close()
except Exception as e:
    print(e.args)

Body:
I think this should work:

import json
dump = json.dumps(data)
json_string = json.loads(dump)
happiness =  str(json_string[0]['Scores']['Happiness'])


问:
R: Extracting string if it is an element of a list
I want to dummy-code whether some string is contained in another (which is structured). For example:

```<code>player <- c("Michael Jordan", "Steve Kerr", "Michael Jordan", "Toni Kukoc")

bulls <- c("Jordan, Michael Jeffrey", "Pippen, Scottie; Harper, Ron",
           "Rodman, Dennis", "Kerr, Steve; Longley, Luc; Kukoc, Toni")
</code>```

and create a new variable (say, included) if words Michael and Jordan are present in bulls[1], Steve Kerr in bulls[2] etc. The above should produce TRUE FALSE FALSE TRUE. For generality, names and surnames are separated by commas, whereas a semicolon indicates multiple people in a single entry. Given that the object bulls can feature longer versions of a name ("Jeffrey" in this case) but not the other way around, I suspect the solution might require some sort of an is.element check? I want to iterate this over a long list, what is the best approach?

p.s. I tried several stringr verbs, however no luck so far (_view, _extract etc.)

答:
Try this:</p>

```<code>require(stringr)
mapply(function(x,y) all(x %in% y),
    str_extract_all(player,"\\w+"),str_extract_all(bulls,"\\w+"))
#[1]  TRUE FALSE FALSE  TRUE
</code>```

Body:
I want to dummy-code whether some string is contained in another (which is structured). For example:

player <- c("Michael Jordan", "Steve Kerr", "Michael Jordan", "Toni Kukoc")

bulls <- c("Jordan, Michael Jeffrey", "Pippen, Scottie; Harper, Ron",
           "Rodman, Dennis", "Kerr, Steve; Longley, Luc; Kukoc, Toni")

and create a new variable (say, included) if words Michael and Jordan are present in bulls[1], Steve Kerr in bulls[2] etc. The above should produce TRUE FALSE FALSE TRUE. For generality, names and surnames are separated by commas, whereas a semicolon indicates multiple people in a single entry. Given that the object bulls can feature longer versions of a name ("Jeffrey" in this case) but not the other way around, I suspect the solution might require some sort of an is.element check? I want to iterate this over a long list, what is the best approach?

p.s. I tried several stringr verbs, however no luck so far (_view, _extract etc.)

Body:
Try this:

require(stringr)
mapply(function(x,y) all(x %in% y),
    str_extract_all(player,"\\w+"),str_extract_all(bulls,"\\w+"))
#[1]  TRUE FALSE FALSE  TRUE


问:
Use Picasso to load images in RecyclerView with DataObject
I want to use picasso lib in a "RecyclerViewAdapter". I want to display different images for each entry. It worked for my when I only use text...
I parse a JSON file with the data I use in getDataSet().

At the moment I have no idea how I can use the picasso function to add the images to the dataSet.

WRONG => int imageUrl = Picasso.

CardViewActivity.java

```<code>public class CardViewActivity extends AppCompatActivity {

    private RecyclerView mRecyclerView;
    private RecyclerView.Adapter mAdapter;
    private RecyclerView.LayoutManager mLayoutManager;
    private static String LOG_TAG = "CardViewActivity";

    // url to make request - Hole fixe Coupons (max. 100)
    private static String url = "http://json.file";

    // JSON Node names
    private static final String TAG_FIXES = "result";
    private static final String TAG_TITEL = "titel";
    private static final String TAG_BESCHREIBUNG = "beschreibung";

    // contacts JSONArray
    JSONArray fixes = null;

    ImageView image;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_card_view);
        /*
        image = (ImageView) findViewById(R.id.image_view);

        Picasso.with(getApplicationContext())
                .load("http://1UVZ8A9DRLH/bild.jpg")
                .placeholder(R.drawable.logo)
                .fit().centerCrop().into(image);
        */
        mRecyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);
        mRecyclerView.setHasFixedSize(true);
        mLayoutManager = new LinearLayoutManager(this);
        mRecyclerView.setLayoutManager(mLayoutManager);
        mAdapter = new MyRecyclerViewAdapter(getDataSet());
        mRecyclerView.setAdapter(mAdapter);

        // Code to Add an item with default animation
        //((MyRecyclerViewAdapter) mAdapter).addItem(obj, index);

        // Code to remove an item with default animation
        //((MyRecyclerViewAdapter) mAdapter).deleteItem(index);
    }

    @Override
    protected void onResume() {
        super.onResume();
        ((MyRecyclerViewAdapter) mAdapter).setOnItemClickListener(new MyRecyclerViewAdapter
                .MyClickListener() {
            @Override
            public void onItemClick(int position, View v) {
                Log.i(LOG_TAG, " Clicked on Item " + position);
            }
        });
    }

    private ArrayList<DataObject> getDataSet() {
        ArrayList results = new ArrayList<DataObject>();

        // Creating JSON Parser instance
        JSONParser jParser = new JSONParser();

        // getting JSON string from URL
        JSONObject json = jParser.getJSONFromUrl(url);

        try {
            // Getting Array of fixes
            fixes = json.getJSONArray(TAG_FIXES);

            // looping through All Contacts
            for(int i = 0; i < fixes.length(); i++){
                JSONObject f = fixes.getJSONObject(i);

                // Storing each json item in variable
                String titel = f.getString(TAG_TITEL);
                String description = f.getString(TAG_BESCHREIBUNG);
                int imageUrl = Picasso.with(getApplicationContext())
                        .load("http://1UVZ8A9DRLH/bild.jpg")
                        .placeholder(R.drawable.logo)
                        .fit().centerCrop().into(image);

                DataObject obj = new DataObject(
                        titel,
                        description,
                        imageUrl
                );
                results.add(i, obj);

            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return results;
    }
}
</code>```

DataObject.java

```<code>public class DataObject {
    private String mText1;
    private String mText2;
    private int imageUrl;

    DataObject(String text1, String text2, int imageUrl){
        mText1 = text1;
        mText2 = text2;
        imageUrl = imageUrl;
    }

    public String getmText1() { return mText1;  }

    public void setmText1(String mText1) {
        this.mText1 = mText1;
    }

    public String getmText2() {
        return mText2;
    }

    public void setmText2(String mText2) { this.mText2 = mText2; }

    public int getImageUrl() { return imageUrl; }

    public void getImageUrl(int imageUrl) {
        this.imageUrl = imageUrl;
    }
}
</code>```

MyRecyclerViewAdapter

```<code>public class MyRecyclerViewAdapter extends RecyclerView
        .Adapter<MyRecyclerViewAdapter
        .DataObjectHolder> {
    private static String LOG_TAG = "MyRecyclerViewAdapter";
    private ArrayList<DataObject> mDataset;
    private static MyClickListener myClickListener;

    public static class DataObjectHolder extends RecyclerView.ViewHolder
            implements View
            .OnClickListener {
        TextView label;
        ImageView imgViewIcon;
        TextView description;

        public DataObjectHolder(View itemView) {
            super(itemView);
            label = (TextView) itemView.findViewById(R.id.textView);
            imgViewIcon = (ImageView) itemView.findViewById(R.id.image_view);
            description = (TextView) itemView.findViewById(R.id.textView2);
            Log.i(LOG_TAG, "Adding Listener");
            itemView.setOnClickListener(this);
        }

        @Override
        public void onClick(View v) {
            myClickListener.onItemClick(getAdapterPosition(), v);
        }
    }

    public void setOnItemClickListener(MyClickListener myClickListener) {
        this.myClickListener = myClickListener;
    }

    public MyRecyclerViewAdapter(ArrayList<DataObject> myDataset) {
        mDataset = myDataset;
    }

    @Override
    public DataObjectHolder onCreateViewHolder(ViewGroup parent,
                                               int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.card_view_row, parent, false);

        DataObjectHolder dataObjectHolder = new DataObjectHolder(view);
        return dataObjectHolder;
    }

    @Override
    public void onBindViewHolder(DataObjectHolder holder, int position) {
        holder.label.setText(mDataset.get(position).getmText1());
        holder.imgViewIcon.setImageResource(mDataset.get(position).getImageUrl());
        holder.description.setText(mDataset.get(position).getmText2());
    }

    public void addItem(DataObject dataObj, int index) {
        mDataset.add(index, dataObj);
        notifyItemInserted(index);
    }

    public void deleteItem(int index) {
        mDataset.remove(index);
        notifyItemRemoved(index);
    }

    @Override
    public int getItemCount() {
        return mDataset.size();
    }

    public interface MyClickListener {
        public void onItemClick(int position, View v);
    }
}
</code>```

答:
Firts set the imageUrl as a DataObject attribute:

```<code>...
String titel = f.getString(TAG_TITEL);
String description = f.getString(TAG_BESCHREIBUNG);
int imageUrl = f.getString(TAG_IMAGE); //Assuming TAG_IMAGE is the name of the Json attribute with the image url

 DataObject obj = new DataObject(
                titel,
                description,
                imageUrl);
...
</code>```

Then on your adapter do the following:

```<code>@Override
public void onBindViewHolder(DataObjectHolder holder, int position) {
    holder.label.setText(mDataset.get(position).getmText1());
    Picasso.with(context).load(mDataset.get(position).getImageUrl()).into(holder.imgViewIcon);
    holder.description.setText(mDataset.get(position).getmText2());
}
</code>```

Body:
I want to use picasso lib in a "RecyclerViewAdapter". I want to display different images for each entry. It worked for my when I only use text...
I parse a JSON file with the data I use in getDataSet().

At the moment I have no idea how I can use the picasso function to add the images to the dataSet.

WRONG => int imageUrl = Picasso.

CardViewActivity.java

public class CardViewActivity extends AppCompatActivity {

    private RecyclerView mRecyclerView;
    private RecyclerView.Adapter mAdapter;
    private RecyclerView.LayoutManager mLayoutManager;
    private static String LOG_TAG = "CardViewActivity";

    // url to make request - Hole fixe Coupons (max. 100)
    private static String url = "http://json.file";

    // JSON Node names
    private static final String TAG_FIXES = "result";
    private static final String TAG_TITEL = "titel";
    private static final String TAG_BESCHREIBUNG = "beschreibung";

    // contacts JSONArray
    JSONArray fixes = null;

    ImageView image;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_card_view);
        /*
        image = (ImageView) findViewById(R.id.image_view);

        Picasso.with(getApplicationContext())
                .load("http://1UVZ8A9DRLH/bild.jpg")
                .placeholder(R.drawable.logo)
                .fit().centerCrop().into(image);
        */
        mRecyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);
        mRecyclerView.setHasFixedSize(true);
        mLayoutManager = new LinearLayoutManager(this);
        mRecyclerView.setLayoutManager(mLayoutManager);
        mAdapter = new MyRecyclerViewAdapter(getDataSet());
        mRecyclerView.setAdapter(mAdapter);

        // Code to Add an item with default animation
        //((MyRecyclerViewAdapter) mAdapter).addItem(obj, index);

        // Code to remove an item with default animation
        //((MyRecyclerViewAdapter) mAdapter).deleteItem(index);
    }

    @Override
    protected void onResume() {
        super.onResume();
        ((MyRecyclerViewAdapter) mAdapter).setOnItemClickListener(new MyRecyclerViewAdapter
                .MyClickListener() {
            @Override
            public void onItemClick(int position, View v) {
                Log.i(LOG_TAG, " Clicked on Item " + position);
            }
        });
    }

    private ArrayList<DataObject> getDataSet() {
        ArrayList results = new ArrayList<DataObject>();

        // Creating JSON Parser instance
        JSONParser jParser = new JSONParser();

        // getting JSON string from URL
        JSONObject json = jParser.getJSONFromUrl(url);

        try {
            // Getting Array of fixes
            fixes = json.getJSONArray(TAG_FIXES);

            // looping through All Contacts
            for(int i = 0; i < fixes.length(); i++){
                JSONObject f = fixes.getJSONObject(i);

                // Storing each json item in variable
                String titel = f.getString(TAG_TITEL);
                String description = f.getString(TAG_BESCHREIBUNG);
                int imageUrl = Picasso.with(getApplicationContext())
                        .load("http://1UVZ8A9DRLH/bild.jpg")
                        .placeholder(R.drawable.logo)
                        .fit().centerCrop().into(image);

                DataObject obj = new DataObject(
                        titel,
                        description,
                        imageUrl
                );
                results.add(i, obj);

            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return results;
    }
}

DataObject.java

public class DataObject {
    private String mText1;
    private String mText2;
    private int imageUrl;

    DataObject(String text1, String text2, int imageUrl){
        mText1 = text1;
        mText2 = text2;
        imageUrl = imageUrl;
    }

    public String getmText1() { return mText1;  }

    public void setmText1(String mText1) {
        this.mText1 = mText1;
    }

    public String getmText2() {
        return mText2;
    }

    public void setmText2(String mText2) { this.mText2 = mText2; }

    public int getImageUrl() { return imageUrl; }

    public void getImageUrl(int imageUrl) {
        this.imageUrl = imageUrl;
    }
}

MyRecyclerViewAdapter

public class MyRecyclerViewAdapter extends RecyclerView
        .Adapter<MyRecyclerViewAdapter
        .DataObjectHolder> {
    private static String LOG_TAG = "MyRecyclerViewAdapter";
    private ArrayList<DataObject> mDataset;
    private static MyClickListener myClickListener;

    public static class DataObjectHolder extends RecyclerView.ViewHolder
            implements View
            .OnClickListener {
        TextView label;
        ImageView imgViewIcon;
        TextView description;

        public DataObjectHolder(View itemView) {
            super(itemView);
            label = (TextView) itemView.findViewById(R.id.textView);
            imgViewIcon = (ImageView) itemView.findViewById(R.id.image_view);
            description = (TextView) itemView.findViewById(R.id.textView2);
            Log.i(LOG_TAG, "Adding Listener");
            itemView.setOnClickListener(this);
        }

        @Override
        public void onClick(View v) {
            myClickListener.onItemClick(getAdapterPosition(), v);
        }
    }

    public void setOnItemClickListener(MyClickListener myClickListener) {
        this.myClickListener = myClickListener;
    }

    public MyRecyclerViewAdapter(ArrayList<DataObject> myDataset) {
        mDataset = myDataset;
    }

    @Override
    public DataObjectHolder onCreateViewHolder(ViewGroup parent,
                                               int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.card_view_row, parent, false);

        DataObjectHolder dataObjectHolder = new DataObjectHolder(view);
        return dataObjectHolder;
    }

    @Override
    public void onBindViewHolder(DataObjectHolder holder, int position) {
        holder.label.setText(mDataset.get(position).getmText1());
        holder.imgViewIcon.setImageResource(mDataset.get(position).getImageUrl());
        holder.description.setText(mDataset.get(position).getmText2());
    }

    public void addItem(DataObject dataObj, int index) {
        mDataset.add(index, dataObj);
        notifyItemInserted(index);
    }

    public void deleteItem(int index) {
        mDataset.remove(index);
        notifyItemRemoved(index);
    }

    @Override
    public int getItemCount() {
        return mDataset.size();
    }

    public interface MyClickListener {
        public void onItemClick(int position, View v);
    }
}

Body:
Firts set the imageUrl as a DataObject attribute:

...
String titel = f.getString(TAG_TITEL);
String description = f.getString(TAG_BESCHREIBUNG);
int imageUrl = f.getString(TAG_IMAGE); //Assuming TAG_IMAGE is the name of the Json attribute with the image url

 DataObject obj = new DataObject(
                titel,
                description,
                imageUrl);
...

Then on your adapter do the following:

@Override
public void onBindViewHolder(DataObjectHolder holder, int position) {
    holder.label.setText(mDataset.get(position).getmText1());
    Picasso.with(context).load(mDataset.get(position).getImageUrl()).into(holder.imgViewIcon);
    holder.description.setText(mDataset.get(position).getmText2());
}


问:
Pause a script till a certain time and start again at another certain time
I made a RGB LED color changing script on my raspberry pi 3 for my setup but i want it to make it so at 11PM the lights stop and start again at 9AM. How can i make this possible ?
Thank you,
PhantomX</p>

答:
This is a more idempotent solution that guarantees the lights are in the correct state regardless of what time you start the script or if it gets interrupted.</p>

```<code>from datetime import time, datetime
from time import sleep

morning = time(9,0,0)
evening = time(23,0,0)

while True:

    while morning < datetime.now().time() < evening:
        print 'lights on...'
        sleep(1)

    print 'lights off...'
    sleep(1)
</code>```

Body:
This is a more idempotent solution that guarantees the lights are in the correct state regardless of what time you start the script or if it gets interrupted.

from datetime import time, datetime
from time import sleep

morning = time(9,0,0)
evening = time(23,0,0)

while True:

    while morning < datetime.now().time() < evening:
        print 'lights on...'
        sleep(1)

    print 'lights off...'
    sleep(1)


问:
Undefined trying to parse through this xml file
so I am definately a beginner when it comes to javascript and jquery, and I am currently trying to parse through this xml (which is a response from an API call).  The problem I am having is I am not sure how to parse through the xml file in order to get some values.

```<code><group_user>
<id type="integer">2671029</id>
<created_at type="datetime">2013-01-20T21:42:01+00:00</created_at>
<comments_count type="integer">0</comments_count>
<moderator_at type="datetime" nil="true"/>
<user>
<id type="integer">5586131</id>
<first_name>Melora</first_name>
</user>
</group_user>
<group_user>
<id type="integer">2026289</id>
<created_at type="datetime">2012-06-08T04:22:38+00:00</created_at>
<comments_count type="integer">38</comments_count>
<moderator_at type="datetime" nil="true"/>
<user>
<id type="integer">6082517</id>
<first_name>Cindy</first_name>
</user>
</code>```

for all the users (not group_users) I want to store/ consolelog all of the id's and all of the first names.

Right now I am doing:

```<code>   var name = $(xml).find("first_name").text();
   console.log(name);

  var id = $(xml).find("id").text();
  console.log(id);
</code>```

but that just gives me a giant list of all id's and names concatenated together. I want to be able to see them as separate elements.

答:
var data = `
<data>
  <group_user>
    <id type="integer">2671029</id>
    <created_at type="datetime">2013-01-20T21:42:01+00:00</created_at>
    <comments_count type="integer">0</comments_count>
    <moderator_at type="datetime" nil="true"/>
    <user>
      <id type="integer">5586131</id>
      <first_name>Melora</first_name>
    </user>
  </group_user>

  <group_user>
    <id type="integer">2026289</id>
    <created_at type="datetime">2012-06-08T04:22:38+00:00</created_at>
    <comments_count type="integer">38</comments_count>
    <moderator_at type="datetime" nil="true"/>
    <user>
      <id type="integer">6082517</id>
      <first_name>Cindy</first_name>
    </user>
  </group_user>
</data>
`;

var xmlDoc = $.parseXML(data);
// var xmlDoc = new DOMParser().parseFromString(data, 'text/xml');

// find all and iterate over each <user>
$(xmlDoc).find('user').each(function(index, tag) {
  // tag -> <user>...</user>

  // find first occurrence of <first_name> within <user>
  var first_name = $(tag).find('first_name')[0];
  // first_name = tag.querySelector('first_name');
  // first_name = tag.getElementsByTagName('first_name')[0];

  // find first occurrence of <id> within <user>
  var id = $(tag).find('id')[0];
  // id = tag.querySelector('id');
  // id = tag.getElementsByTagName('id')[0]

  // user object creation
  var user = {
    id: $(id).text(),
    // or
    // id: id.textContent
    // id: $(id)[0].textContent,
    name: $(first_name).text()
    // or
    // name: first_name.textContent
    // name: $(first_name)[0].textContent
  };

  console.log('id: ' + user.id);
  console.log('name: ' + user.name);
});

/*
xmlDoc.querySelectorAll('user').forEach(function(tag, index) {
 // ...
});
*/

/*
var users = xmlDoc.findElementsByTagName('user');
for (var index=0; index<users.length; index++) {
  var tag = users[index];
  // ...
}
*/```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script></code>```

Body:
so I am definately a beginner when it comes to javascript and jquery, and I am currently trying to parse through this xml (which is a response from an API call).  The problem I am having is I am not sure how to parse through the xml file in order to get some values.

<group_user>
<id type="integer">2671029</id>
<created_at type="datetime">2013-01-20T21:42:01+00:00</created_at>
<comments_count type="integer">0</comments_count>
<moderator_at type="datetime" nil="true"/>
<user>
<id type="integer">5586131</id>
<first_name>Melora</first_name>
</user>
</group_user>
<group_user>
<id type="integer">2026289</id>
<created_at type="datetime">2012-06-08T04:22:38+00:00</created_at>
<comments_count type="integer">38</comments_count>
<moderator_at type="datetime" nil="true"/>
<user>
<id type="integer">6082517</id>
<first_name>Cindy</first_name>
</user>

for all the users (not group_users) I want to store/ consolelog all of the id's and all of the first names.

Right now I am doing:

   var name = $(xml).find("first_name").text();
   console.log(name);

  var id = $(xml).find("id").text();
  console.log(id);

but that just gives me a giant list of all id's and names concatenated together. I want to be able to see them as separate elements.

Body:
var data = `
<data>
  <group_user>
    <id type="integer">2671029</id>
    <created_at type="datetime">2013-01-20T21:42:01+00:00</created_at>
    <comments_count type="integer">0</comments_count>
    <moderator_at type="datetime" nil="true"/>
    <user>
      <id type="integer">5586131</id>
      <first_name>Melora</first_name>
    </user>
  </group_user>

  <group_user>
    <id type="integer">2026289</id>
    <created_at type="datetime">2012-06-08T04:22:38+00:00</created_at>
    <comments_count type="integer">38</comments_count>
    <moderator_at type="datetime" nil="true"/>
    <user>
      <id type="integer">6082517</id>
      <first_name>Cindy</first_name>
    </user>
  </group_user>
</data>
`;

var xmlDoc = $.parseXML(data);
// var xmlDoc = new DOMParser().parseFromString(data, 'text/xml');

// find all and iterate over each <user>
$(xmlDoc).find('user').each(function(index, tag) {
  // tag -> <user>...</user>

  // find first occurrence of <first_name> within <user>
  var first_name = $(tag).find('first_name')[0];
  // first_name = tag.querySelector('first_name');
  // first_name = tag.getElementsByTagName('first_name')[0];

  // find first occurrence of <id> within <user>
  var id = $(tag).find('id')[0];
  // id = tag.querySelector('id');
  // id = tag.getElementsByTagName('id')[0]

  // user object creation
  var user = {
    id: $(id).text(),
    // or
    // id: id.textContent
    // id: $(id)[0].textContent,
    name: $(first_name).text()
    // or
    // name: first_name.textContent
    // name: $(first_name)[0].textContent
  };

  console.log('id: ' + user.id);
  console.log('name: ' + user.name);
});

/*
xmlDoc.querySelectorAll('user').forEach(function(tag, index) {
 // ...
});
*/

/*
var users = xmlDoc.findElementsByTagName('user');
for (var index=0; index<users.length; index++) {
  var tag = users[index];
  // ...
}
*/

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


问:
Async method await keyword doesn't suspend to calling method
I have following line of code, to understand async-await and suspension till awaited task complete.

```<code>public async Task<string> WaitAsynchronouslyAsync()
    {
        var results = await WaitAsync();
        Console.WriteLine($@"I am not waiting");
        return results;
    }

    public async Task<string> WaitAsync()
    {
        await Task.Delay(10000).ConfigureAwait(false);
        return "Async programming suspension point demo.";
    }
</code>```

The await operator suspends execution until the work of the WaitAsync() (Delay 10 seconds) method is complete.

In the meantime, I was expecting that Console.WriteLine($@"I am not waiting"); should write text to output window until awaited task completes, as control is returned to the caller of WaitAsync(). When the task finishes execution, the await expression evaluates string ("Async programming suspension point demo.").

Am I confused here with suspension pointer vs debug pointer?

答:
await means "wait until this finishes executing asynchronously" your function will not continue until the supplied Task finishes executing.

If you instead said the following it wouldn't wait:

```<code>var results = WaitAsync();
Console.WriteLine($@"I am not waiting");
return await results;
</code>```

Or even more succinctly, remove the async from the signature and then you can just return results;.

Body:
I have following line of code, to understand async-await and suspension till awaited task complete.

public async Task<string> WaitAsynchronouslyAsync()
    {
        var results = await WaitAsync();
        Console.WriteLine($@"I am not waiting");
        return results;
    }

    public async Task<string> WaitAsync()
    {
        await Task.Delay(10000).ConfigureAwait(false);
        return "Async programming suspension point demo.";
    }

The await operator suspends execution until the work of the WaitAsync() (Delay 10 seconds) method is complete.

In the meantime, I was expecting that Console.WriteLine($@"I am not waiting"); should write text to output window until awaited task completes, as control is returned to the caller of WaitAsync(). When the task finishes execution, the await expression evaluates string ("Async programming suspension point demo.").

Am I confused here with suspension pointer vs debug pointer?

Body:
await means "wait until this finishes executing asynchronously" your function will not continue until the supplied Task finishes executing.

If you instead said the following it wouldn't wait:

var results = WaitAsync();
Console.WriteLine($@"I am not waiting");
return await results;

Or even more succinctly, remove the async from the signature and then you can just return results;.


问:
how to add a c++ file in Qt Creator whose name starts with capital letters ? It automatically makes it small letter
I am trying to add a c++ file to a existing Qt project but I can't make the name  of the c++ file start with a capital letter.
E.g. DownloadOsm.cpp becomes downloadosm.cpp automatically using the wizard. </p>

答:
To solve this issue do the following:

[Tools] -> [Options] -> [C++] -> [File Naming] -> uncheck "Lower case file names"


问:
Navigate from UIView to UIViewController without storyboard and navigation controller
Is there a way to navigate from a UIView, which is part of a UIViewController, to another UIViewController neither using storyboards nor navigation controllers?

I have a UITapGestureRecognizer which I want to navigate to another UIViewController (BuyController()) whenever it is tapped once.  Accordingly, my code looks like this:

```<code>//handle singleTap
func singleTapOnLikesDetected(_ sender: UITapGestureRecognizer) {

    print("check") //works
    let toController = BuyController()
    BarController().pushViewController(toController, animated: true) //error occurs since BarController is no navigationcontroller

}
</code>```

BarController (UITabBarController, UITabBarControllerDelegate) is my rootViewController in the AppDelegate.swift. The UIView however belongs to another UIViewController called HomeController (UIViewController, UIScrollViewDelegate). I do not use storyboards at all and I would like to keep it that way, as I am going to work on a project in a team (thus, a programmatic solution would be very welcome)...

答:
Only UIViewControllers can present other UIViewControllers not UIViews so your won't find the present method on the UIView.  You also can't replace self with HomeController() because that creates a new HomeController with it's own UIView which hasn't been added to any other view (as the error suggests).

You have a couple of options really:

1) Create a protocol/delegate on your UIView and make the HomeController conform to it.  Then the UIView can call the method in the protocol and the HomeController do the actual switching.

2) You could get the root view controller to present the new UIViewController like this: UIApplication.shared.keyWindow?.rootViewController?.present(viewController, animated: true, completion: nil)

Body:
Is there a way to navigate from a UIView, which is part of a UIViewController, to another UIViewController neither using storyboards nor navigation controllers?

I have a UITapGestureRecognizer which I want to navigate to another UIViewController (BuyController()) whenever it is tapped once.  Accordingly, my code looks like this:

//handle singleTap
func singleTapOnLikesDetected(_ sender: UITapGestureRecognizer) {

    print("check") //works
    let toController = BuyController()
    BarController().pushViewController(toController, animated: true) //error occurs since BarController is no navigationcontroller

}

BarController (UITabBarController, UITabBarControllerDelegate) is my rootViewController in the AppDelegate.swift. The UIView however belongs to another UIViewController called HomeController (UIViewController, UIScrollViewDelegate). I do not use storyboards at all and I would like to keep it that way, as I am going to work on a project in a team (thus, a programmatic solution would be very welcome)...


问:
How to check if multiple checkboxes are selected
I am working on some kind of calculator, and lets say i have a global variable called IQ. Now, I have a checkbox with 5 options (in this case 5 different persons). I want each person to either reduce or increase the global variable IQ when they are selected.

I thought about doing this with if statements, but what if the first if is true(i.e one person is checked and value === person). Then the code would stop right and not check the other if-statements to see if more persons/checkboxes are selected. Hope this is clear what i ment.

This is my HTML-code:

```<code><input type="checkbox" name="person" value="frank"> Frank Aarebrot<br>
<input type="checkbox" name="person" value="gaben"> Gabe Newell<br>
<input type="checkbox" name="person" value="lance"> Lance Armstrong<br>
<input type="checkbox" name="person" value="trond"> Trond Kirkvaag<br>
<input type="checkbox" name="person" value="davy"> Davy Wathne<br>
</code>```

答:
You can listen to change event on each checkbox and calculate your number accordingly. Here I create a new map-like object with person name as a key and +-1 as a value to indicate weither to add or subtract 1:

var cbs = document.querySelectorAll('input[type=checkbox][name=person]');

var plusMinus = {
  frank: 1,
  gaben: -1,
  lance: 1,
  trond: -1,
  davy: 1
}

var p = document.getElementById('iq');
p.textContent = '0';

for (const cb of cbs) {
  cb.addEventListener('change', (e) => {
    var {checked, value} = e.target;
    p.textContent = parseInt(p.textContent) + plusMinus[value]
      * ((checked) ? 1 : -1) // +- math
  })
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="checkbox" name="person" value="frank"> Frank Aarebrot<br>
<input type="checkbox" name="person" value="gaben"> Gabe Newell<br>
<input type="checkbox" name="person" value="lance"> Lance Armstrong<br>
<input type="checkbox" name="person" value="trond"> Trond Kirkvaag<br>
<input type="checkbox" name="person" value="davy"> Davy Wathne<br>
<hr>
<p id="iq"></p></code>```

Body:
I am working on some kind of calculator, and lets say i have a global variable called IQ. Now, I have a checkbox with 5 options (in this case 5 different persons). I want each person to either reduce or increase the global variable IQ when they are selected.

I thought about doing this with if statements, but what if the first if is true(i.e one person is checked and value === person). Then the code would stop right and not check the other if-statements to see if more persons/checkboxes are selected. Hope this is clear what i ment.

This is my HTML-code:

<input type="checkbox" name="person" value="frank"> Frank Aarebrot

<input type="checkbox" name="person" value="gaben"> Gabe Newell

<input type="checkbox" name="person" value="lance"> Lance Armstrong

<input type="checkbox" name="person" value="trond"> Trond Kirkvaag

<input type="checkbox" name="person" value="davy"> Davy Wathne

Body:
You can listen to change event on each checkbox and calculate your number accordingly. Here I create a new map-like object with person name as a key and +-1 as a value to indicate weither to add or subtract 1:

var cbs = document.querySelectorAll('input[type=checkbox][name=person]');

var plusMinus = {
  frank: 1,
  gaben: -1,
  lance: 1,
  trond: -1,
  davy: 1
}

var p = document.getElementById('iq');
p.textContent = '0';

for (const cb of cbs) {
  cb.addEventListener('change', (e) => {
    var {checked, value} = e.target;
    p.textContent = parseInt(p.textContent) + plusMinus[value]
      * ((checked) ? 1 : -1) // +- math
  })
}

<input type="checkbox" name="person" value="frank"> Frank Aarebrot<br>
<input type="checkbox" name="person" value="gaben"> Gabe Newell<br>
<input type="checkbox" name="person" value="lance"> Lance Armstrong<br>
<input type="checkbox" name="person" value="trond"> Trond Kirkvaag<br>
<input type="checkbox" name="person" value="davy"> Davy Wathne<br>
<hr>
<p id="iq"></p>


问:
Using Timer to repaint in the fixed time then continuing calculation
Currently, I am making a Java program for graph visualization Prim's algorithm in finding minimum spanning tree.

Here is the image of my program's output

```<code>while(condition){
    //Find the min vertex and min edges
    Vertex vertex = findMinVertex();
    Edge[] edges = findMinEdges();

    //Then, for each vertex and edges I found, I will change the color of
    //them and pause the program for 3 seconds, so user can see how
    //algorithm works.

    repaintAndPause(3000);
}
.
.
private void repaintAndPause(int time){
    long start = System.currentTimeMillis();
    long end = start + speed;

    //Here is the timer for repainting.
    Timer timer = new Timer(speed, new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e){
            GraphPanel.this.repaint();
        }
    });
    timer.setRepeats(false);
    timer.setDelay(0);
    timer.start();

    //And here is for pausing the program, a while loop without any commands.
    while(System.currentTimeMillis() < end){}
}
</code>```

However, I don't know why but the program doesn't work. Yes, there are the pauses of program but, all the edges and vertices are just changed the color at the end of program. They aren't changed every 3 seconds.

Could someone please tell me where I did wrong?

Thank you and hope you have a nice day!

答:
Could someone please tell me where I did wrong?

Yes.  You are putting a busy-loop in the Event Dispatching Thread.

```<code>    while(System.currentTimeMillis() < end){}
</code>```

You code reads:

do some calculation (busy)

when done, post a "repaint" message, to redraw the panel when not busy

continue being very busy doing nothing for 3 seconds

continue being busy by repeating steps 1 through 4.

The Event Dispatching Thread never finishes processing the first "event" until the end of the algorithm, after the while (condition) loop finally finishes.

You want:

```<code>Timer timer = new Timer(speed, new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
       /* Code to perform one step of Prim's algorithm here */
       /* Change edge/vertex colour for step */
       /* Call timer.stop(), once done */

       GraphPanel.this.repaint();
    }
});
timer.setRepeats(true);
timer.setDelay(3000);
timer.start();
</code>```

On every tick of the timer (once every 3 seconds), one step of the algorithm is performed.

Note this means that each step of the algorithm must run with any partial results stored into class members, so the the next step will be able to retrieve all the information it needs to continue.  Stack variables can only be used inside one step; they cannot be used to hold inter-step values.

You could rework the algorithm to use a SwingWorker to run the calculation in its own background thread, and publish intermediate results when computed.  The EDT could then repaint as intermediate results are produced.  With a Thread#sleep() call, this background thread could delay production of intermediate results to once per 3 seconds.

Alternately, you could run the algorithm, and store multiple copies of the output, once for each 'step'.  Then your Panel timer could simply show the output of the next step.

Body:
Currently, I am making a Java program for graph visualization Prim's algorithm in finding minimum spanning tree.

Here is the image of my program's output

while(condition){
    //Find the min vertex and min edges
    Vertex vertex = findMinVertex();
    Edge[] edges = findMinEdges();

    //Then, for each vertex and edges I found, I will change the color of
    //them and pause the program for 3 seconds, so user can see how
    //algorithm works.

    repaintAndPause(3000);
}
.
.
private void repaintAndPause(int time){
    long start = System.currentTimeMillis();
    long end = start + speed;

    //Here is the timer for repainting.
    Timer timer = new Timer(speed, new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e){
            GraphPanel.this.repaint();
        }
    });
    timer.setRepeats(false);
    timer.setDelay(0);
    timer.start();

    //And here is for pausing the program, a while loop without any commands.
    while(System.currentTimeMillis() < end){}
}

However, I don't know why but the program doesn't work. Yes, there are the pauses of program but, all the edges and vertices are just changed the color at the end of program. They aren't changed every 3 seconds.

Could someone please tell me where I did wrong?

Thank you and hope you have a nice day!

Body:
Could someone please tell me where I did wrong?

Yes.  You are putting a busy-loop in the Event Dispatching Thread.

    while(System.currentTimeMillis() < end){}

You code reads:

do some calculation (busy)

when done, post a "repaint" message, to redraw the panel when not busy

continue being very busy doing nothing for 3 seconds

continue being busy by repeating steps 1 through 4.

The Event Dispatching Thread never finishes processing the first "event" until the end of the algorithm, after the while (condition) loop finally finishes.

You want:

Timer timer = new Timer(speed, new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
       /* Code to perform one step of Prim's algorithm here */
       /* Change edge/vertex colour for step */
       /* Call timer.stop(), once done */

       GraphPanel.this.repaint();
    }
});
timer.setRepeats(true);
timer.setDelay(3000);
timer.start();

On every tick of the timer (once every 3 seconds), one step of the algorithm is performed.

Note this means that each step of the algorithm must run with any partial results stored into class members, so the the next step will be able to retrieve all the information it needs to continue.  Stack variables can only be used inside one step; they cannot be used to hold inter-step values.

You could rework the algorithm to use a SwingWorker to run the calculation in its own background thread, and publish intermediate results when computed.  The EDT could then repaint as intermediate results are produced.  With a Thread#sleep() call, this background thread could delay production of intermediate results to once per 3 seconds.

Alternately, you could run the algorithm, and store multiple copies of the output, once for each 'step'.  Then your Panel timer could simply show the output of the next step.


答:
The sequence of operations will go something like this:

You call WaitAsynchronouslyAsync

WaitAsynchronouslyAsync calls WaitAsync

WaitAsync calls Task.Delay(10000).ConfigureAwait(false), which produces a Task.

WaitAsync returns a new Task to its caller, WaitAsynchronouslyAsync, which will be completed later

WaitAsynchronouslyAsync awaits the task from WaitAsync, and then returns to it's caller, providing a Task representing when it will be finished.

Other stuff happens further up the call stack.

Task.Delay finishes, so the continuation of WaitAsync fires, picking up where it left off.

WaitAsync returns the string, completing the Task.

WaitAsynchronouslyAsync can now continue, since the Task returned from WaitAsync has finished.  It will go on to print out text to the console.

WaitAsynchronouslyAsync finishes it's task, letting anyone who has anything set up to run when it's finished to be able to run.

Title: Async method await keyword doesn't suspend to calling method


问:
Benefits of Stagemonitor over JMX monitoring
How does Stagemonitor compare over simple JMX metrics?

Unlike java-native JMX MBeans, Stagemonitor includes an agent that sits in your Java application, sending metrics and request traces at the central database, which can be Elasticsearch.

Since both ways can serve as input for an ELK Monitoring Stack (JMX see this blog post) what are the benefits of Stagemonitor?

答:
Most of the metrics stagemonitor collects are not available via JMX. For example, response time statistics grouped by the endpoint of your application.

Also, stagemonitor is much more than just metrics. It is also a profiler, you can use to see which methods caused a request to be slow. Further more, it can (soon) do distributed tracing which helps you to analyze and debug latency problems in a microservice environment by correlating related requests. It also offers you a Kibana dashboard you can use to drill into the requests your application serves to find out about causes of errors or latency. Another use case is lightweight web analytics to identify which devices and operating systems your customers use to access your site.


问:
concat 3 columns in csv,How to do this?
I am trying to create a unique id for the data in the csv file.
I have 3 columns in a csv and want to concat 3 columns in to  1 column and output in 4th column,
How to do this?
example:
col1  col2 col3     col4
ab     cd    ef    ab_cd_ef

this should be done to all the other rows as well,I have like around 90k rows.

答:
You can use logstash csv input to import the date to elasticsearch. Following configuration will parse the csv files and sent to elasticsearch with a spesific pipeline.

```<code>input {
  beats {
    port => 5044
    type => "myindex"
  }
}

filter {
  csv {
    separator => ","
    columns => ["Ref","ID","Case_Number","Date","Block","IUCR","Primary_Type","Description","Location_Description","Arrest","Domestic","Beat","District","Ward","Community_Area","FBI_Code","X_Coordinate","Y_Coordinate","Year","Updated_On","Latitude","Longitude","Location"]
    remove_field => ["Location"]
  }
}

output {
  stdout
  {

  }

  elasticsearch
  {
    hosts => ["elasticsearch:9200"]
    index => "myindex"
    template_name => "myindex"
    template => "/etc/logstash/conf.d/template.json"
    template_overwrite => true
    document_type => "mytype"
    pipeline => "my_pipeline"
  }
}
</code>```

In this example, we can parse the csv files with logstash after that We can create a pipeline to concat the fields. For example, following example will concat the coordiante fields to location field.

```<code>PUT _ingest/pipeline/my_pipeline
{
  "description" : "Crimes in Chicago Pipeline",
  "processors" : [
    {
      "script": {
        "lang": "painless",
        "inline": "ctx.Location = ctx.Location.X_Coordinate + ctx.Location.Y_Coordinate"
      }
    }
  ]
}
</code>```

For complete example, you can check this repo. (https://github.com/hkulekci/es5-devnot).

On the other hand, logstash also handle your concat transformation. To do this, you can use mutate filter of logstash.
You should update your logstash filter configuration like below:

```<code>filter {
  csv {
    separator => ","
    columns => ["Ref","ID","Case_Number","Date","Block","IUCR","Primary_Type","Description","Location_Description","Arrest","Domestic","Beat","District","Ward","Community_Area","FBI_Code","X_Coordinate","Y_Coordinate","Year","Updated_On","Latitude","Longitude","Location"]
    remove_field => ["Location"]
  }
  mutate {
    "add_field" => { "your_new_field" => "%{col_1} %{col_2} ..." }
  }
}
</code>```

Title: concat 3 columns in csv,How to do this?

Body:
You can use logstash csv input to import the date to elasticsearch. Following configuration will parse the csv files and sent to elasticsearch with a spesific pipeline.

input {
  beats {
    port => 5044
    type => "myindex"
  }
}

filter {
  csv {
    separator => ","
    columns => ["Ref","ID","Case_Number","Date","Block","IUCR","Primary_Type","Description","Location_Description","Arrest","Domestic","Beat","District","Ward","Community_Area","FBI_Code","X_Coordinate","Y_Coordinate","Year","Updated_On","Latitude","Longitude","Location"]
    remove_field => ["Location"]
  }
}

output {
  stdout
  {

  }

  elasticsearch
  {
    hosts => ["elasticsearch:9200"]
    index => "myindex"
    template_name => "myindex"
    template => "/etc/logstash/conf.d/template.json"
    template_overwrite => true
    document_type => "mytype"
    pipeline => "my_pipeline"
  }
}

In this example, we can parse the csv files with logstash after that We can create a pipeline to concat the fields. For example, following example will concat the coordiante fields to location field.

PUT _ingest/pipeline/my_pipeline
{
  "description" : "Crimes in Chicago Pipeline",
  "processors" : [
    {
      "script": {
        "lang": "painless",
        "inline": "ctx.Location = ctx.Location.X_Coordinate + ctx.Location.Y_Coordinate"
      }
    }
  ]
}

For complete example, you can check this repo. (https://github.com/hkulekci/es5-devnot).

On the other hand, logstash also handle your concat transformation. To do this, you can use mutate filter of logstash.
You should update your logstash filter configuration like below:

filter {
  csv {
    separator => ","
    columns => ["Ref","ID","Case_Number","Date","Block","IUCR","Primary_Type","Description","Location_Description","Arrest","Domestic","Beat","District","Ward","Community_Area","FBI_Code","X_Coordinate","Y_Coordinate","Year","Updated_On","Latitude","Longitude","Location"]
    remove_field => ["Location"]
  }
  mutate {
    "add_field" => { "your_new_field" => "%{col_1} %{col_2} ..." }
  }
}


问:
How do I mount a remote Linux folder in Windows through SSH?
I'm a blind student currently in a system admin/shell programming class. Although ssh works fine for executing commands like ls, pwd, etc editors do not work well with my screen reader and an ssh session. I was wondering if it is possible to mount a Linux folder over ssh so it appears as a windows drive? This way I could edit any files I needed to with accessible software and not have to constantly use SCP to send files back and fourth.</p>

答:
I don't think you can mount a Linux folder as a network drive under windows having only access to ssh. I can suggest you to use WinSCP that allows you to transfer file through ssh and it's free.

EDIT: well, sorry. Vinko posted before me and now i've learned a new thing :)

OwnerDisplayName: Jared

LastEditorDisplayName: Michael Haren


问:
Multi Join on two tables not working in Access 2016
I have an Issue with alias joins in access 2016.I have a table 'projects' that includes fields for Employer, End User, Purchaser. Each of these fields references the same table 'Client'.
I want to list Project name, Employer and Purchaser with this SQL:

```<code>SELECT Projects.[Project Name],A.Company as employer,B.company as Purchaser
FROM Projects INNER JOIN Clients as A ON Projects.Employer = A.ID
 INNER JOIN Clients B  ON Projects.Purchaser = B.ID;
</code>```

I get an error:

Syntax error(missing operator) in query expression Projects.Employer = A.ID
   INNER JOIN Clients B  ON Projects.Purchaser = Clients.ID;

Can't work out what is going on as each individual join works fine but I get the error when I put them together!

答:
Access is a little strange on the kind of SQL it will accept, you definitely have to alter your syntax just a little bit for most things. I believe for multiple inner joins you need to add some parentheses

This should work:

```<code>SELECT Projects.[Project Name],A.Company as employer,B.company as Purchaser
FROM (Projects INNER JOIN Clients as A ON Projects.Employer = A.ID)
 INNER JOIN Clients B  ON Projects.Purchaser = B.ID;
</code>```

Body:
I have an Issue with alias joins in access 2016.I have a table 'projects' that includes fields for Employer, End User, Purchaser. Each of these fields references the same table 'Client'.
I want to list Project name, Employer and Purchaser with this SQL:

SELECT Projects.[Project Name],A.Company as employer,B.company as Purchaser
FROM Projects INNER JOIN Clients as A ON Projects.Employer = A.ID
 INNER JOIN Clients B  ON Projects.Purchaser = B.ID;

I get an error:

Syntax error(missing operator) in query expression Projects.Employer = A.ID
   INNER JOIN Clients B  ON Projects.Purchaser = Clients.ID;

Can't work out what is going on as each individual join works fine but I get the error when I put them together!

Body:
Access is a little strange on the kind of SQL it will accept, you definitely have to alter your syntax just a little bit for most things. I believe for multiple inner joins you need to add some parentheses

This should work:

SELECT Projects.[Project Name],A.Company as employer,B.company as Purchaser
FROM (Projects INNER JOIN Clients as A ON Projects.Employer = A.ID)
 INNER JOIN Clients B  ON Projects.Purchaser = B.ID;


问:
Selenium Webdriver C# wait for existence when using PageFactory
I need to click an okay button which might appear after completing a field - it might take 5 seconds to appear. So i need (if) Wait for existence 5 seconds. I'm using PageFactory in a pages framework, I've seen some solutions but cant figure out how to implement them in this context.

```<code>[FindsBy(How = How.Name, Using = "OK")]
private IWebElement alertOKBtn;

public void PopulateFields //method to populate the form
{
   // Populate fields
   dateFromField.SendKeys(DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss"));
   // Click on this field
   descriptionField.Click();

   //OK button might appear, might take 5secs - pseudcode
   if ( ***alertOKBtn exists, wait for it for 5 secs..*** )
   {
     alertOkBtn.Click();
   }

   //continue populating form

   }
</code>```

The PopulateFields method is called from the [Test] as:-

Pages.PTW.PopulateFields();

where Pages.PTW is a get method to PageFactory.InitElements(browser.Driver, page); return page;

答:
Need to add conditional wait. That means, your code should wait till the control appears and then perform the action.

WebDriverWait class which inherits DefaultWait class serves the purpose. The below is the code snippet.

```<code> var wait = new WebDriverWait(this.driver, waitTime);
 wait.Until(ExpectedConditions.ElementToBeClickable(alertOkBtn));
 alertOkBtn.Click();
</code>```

Body:
I need to click an okay button which might appear after completing a field - it might take 5 seconds to appear. So i need (if) Wait for existence 5 seconds. I'm using PageFactory in a pages framework, I've seen some solutions but cant figure out how to implement them in this context.

[FindsBy(How = How.Name, Using = "OK")]
private IWebElement alertOKBtn;

public void PopulateFields //method to populate the form
{
   // Populate fields
   dateFromField.SendKeys(DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss"));
   // Click on this field
   descriptionField.Click();

   //OK button might appear, might take 5secs - pseudcode
   if ( ***alertOKBtn exists, wait for it for 5 secs..*** )
   {
     alertOkBtn.Click();
   }

   //continue populating form

   }

The PopulateFields method is called from the [Test] as:-

Pages.PTW.PopulateFields();

where Pages.PTW is a get method to PageFactory.InitElements(browser.Driver, page); return page;

Body:
Need to add conditional wait. That means, your code should wait till the control appears and then perform the action.

WebDriverWait class which inherits DefaultWait class serves the purpose. The below is the code snippet.

 var wait = new WebDriverWait(this.driver, waitTime);
 wait.Until(ExpectedConditions.ElementToBeClickable(alertOkBtn));
 alertOkBtn.Click();