问:
Using filebeat with elasticsearch
I am not getting that how to run this filebeat in order to send output to elasticsearch.

This is from the filebeat.yml file,

```<code>- input_type: log

  # Paths that should be crawled and fetched. Glob based paths.
  paths:
    - /var/log/nginx/access.log

output.elasticsearch:
  # Array of hosts to connect to.
    hosts: ["localhost:9200"]
    index: 'filebeat_nginx'
</code>```

elasticsearch is up and running.

Now, how to run filebeat to send the log info to elasticsearch.

If I go to bin directory of filebeat, and run this command,

```<code>luvpreet@DHARI-Inspiron-3542:/usr/share/filebeat/bin$ sudo ./filebeat -configtest -e
</code>```

then it shows ,

```<code>filebeat2017/04/19 06:54:22.450440 beat.go:339: CRIT Exiting: error loading config file: stat filebeat.yml: no such file or directory
Exiting: error loading config file: stat filebeat.yml: no such file or directory
</code>```

The filebeat.yml file is in the /etc/filebeat folder. How to run it ?
Please clarify the process to run this with elasticsearch.

答:
1.If you have installed the rpm package, you will have /etc/filebeat/filebeat.yml file. Edit the file to send the output to Elasticsearch and start it using command "/etc/init.d/filebeat start"
2. If you have downloaded binary and installed it, you can use the command "Downloads/filebeat-5.4.0-darwin-x86_64/filebeat -e -c location_to_your_filebeat.yml"

Title: Using filebeat with elasticsearch

Body:
I am not getting that how to run this filebeat in order to send output to elasticsearch.

This is from the filebeat.yml file,

- input_type: log

  # Paths that should be crawled and fetched. Glob based paths.
  paths:
    - /var/log/nginx/access.log

output.elasticsearch:
  # Array of hosts to connect to.
    hosts: ["localhost:9200"]
    index: 'filebeat_nginx'

elasticsearch is up and running.

Now, how to run filebeat to send the log info to elasticsearch.

If I go to bin directory of filebeat, and run this command,

luvpreet@DHARI-Inspiron-3542:/usr/share/filebeat/bin$ sudo ./filebeat -configtest -e

then it shows ,

filebeat2017/04/19 06:54:22.450440 beat.go:339: CRIT Exiting: error loading config file: stat filebeat.yml: no such file or directory
Exiting: error loading config file: stat filebeat.yml: no such file or directory

The filebeat.yml file is in the /etc/filebeat folder. How to run it ?
Please clarify the process to run this with elasticsearch.


来源: stackexchange

问:
Signing (Debug) doesn't include the beta-reports-active entitlement
During the try to setup signing settings of Xcode 8, I've got the following error for the development provision profile:

Provisioning profile "XXX" doesn't include the beta-reports-active
  entitlement.

recreation of the provision profiles doesn't help. I'm not quite sure if this type of profile needs beta-reports-active settings at all, as I saw other issues only AppStore profiles should use these settings.

I will appreciate any help

UPDATE:

AdHoc provision profile has the same error, however AppStore provision profile works fine for Release.

答:
Regenerate your Provisional profile will solve this problem. To regenerate your Provisional Profile follow the following step.

On the Certs IDs & Profiles website > Provisioning Profiles page, click the App Store profile.

Click 'Edit'

Click 'Generate'

Rebuild your app using newly created provisional profile and Archive it.
Visit link

ContentLicense: CC BY-SA 3.0


问:
Javascript cannot get value for operation
I have the following issue. Since there're many, many business rules I've decided to enter those functions as js to update automatically.

In my view i have:
this is inside a table

```<code>(<%= javascript_include_tag 'people'%>)

      <th>Name</th>
      <th>Money</th>
      <th>Money Comment</th>
    </tr>
    <% @counter = 0 %>
    <% @people.each do |p| %>
    <% @counter += 1 %>
     <tr>
     <%= form_for(:p) do |f| %>
     <th><%= f.label(p.name) %></th>
     <th><label for="<%= "money_" + @counter.to_s %>"> <%= f.select(:money, 1..10,   :selected => p.money)%></label></th>
     <th><label for="<%= "comment_" + @counter.to_s %>"> <%= f.label(p.money_comment, :disabled => 'disabled')%></label></th>
    <% end %>
    <% end %>
</code>```

and in the javascript the function looks like this:

```<code>function change_people() {
  money1 = $('money_1').getValue();
  if (money1 == 10) {
    $('comment_2').setValue("I know what you're doing you mofo");
  }
  else {
    $('comment_2').setValue("");
  }
}

document.observe('dom:loaded', function() {
  change_people();
  $('money_1').observe('change', change_people);
});
</code>```

but for some reason it keeps telling me it doesn't know what I mean by "money_1". I check the html source and is compiling the view, am I referencing the element wrongly in js?

Thanks for the help!

答:
It looks as if you need a selector:

```<code><th id="<%= "money_" + @counter.to_s %>">
 <label for="<%= "money_" + @counter.to_s %>">
  <%= f.select(:money, 1..10,   :selected => p.money)%>
 </label>
</th>
</code>```

Now you've given Prototype the ability to search and find the correct element (the select with the value you're looking for), which you pass to the $() function to call getValue():

```<code>function change_people() {
    // Note the "#" on #money_1, which is an ID selector
    // the space " " between is a descendant element selector
    money1 = $($$('#money_1 select')).getValue();
    if (money1 == 10) {
        // do stuff
    } else {
        // do other stuff
    }
}
</code>```

If you're looking to iterate over all of the money select values in the table, you would instead want to use a class; you are only allowed to have one element per ID, but a class by rule is grouped by attribute. The difference would be:

```<code><th class="money_select">
 <label for="<%= "money_" + @counter.to_s %>">
  <%= f.select(:money, 1..10,   :selected => p.money)%>
 </label>
</th>
</code>```

And then in your javascript:

```<code>function change_people() {
    // Note the "." on .money_1, which is a class selector
    // the space " " between is a descendant element selector
    $$('.money_select select').each(function(element){
        if ($(element).getValue() == 10) {
            // do stuff
        } else {
            // do other stuff
        }
    });
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have the following issue. Since there're many, many business rules I've decided to enter those functions as js to update automatically.

In my view i have:
this is inside a table

(<%= javascript_include_tag 'people'%>)

      Name
      Money
      Money Comment

    <% @counter = 0 %>
    <% @people.each do |p| %>
    <% @counter += 1 %>

     <%= form_for(:p) do |f| %>
     <%= f.label(p.name) %>
     <label for="<%= "money_" + @counter.to_s %>"> <%= f.select(:money, 1..10,   :selected => p.money)%>
     <label for="<%= "comment_" + @counter.to_s %>"> <%= f.label(p.money_comment, :disabled => 'disabled')%>
    <% end %>
    <% end %>

and in the javascript the function looks like this:

function change_people() {
  money1 = $('money_1').getValue();
  if (money1 == 10) {
    $('comment_2').setValue("I know what you're doing you mofo");
  }
  else {
    $('comment_2').setValue("");
  }
}

document.observe('dom:loaded', function() {
  change_people();
  $('money_1').observe('change', change_people);
});

but for some reason it keeps telling me it doesn't know what I mean by "money_1". I check the html source and is compiling the view, am I referencing the element wrongly in js?

Thanks for the help!

Body:
It looks as if you need a selector:

<th id="<%= "money_" + @counter.to_s %>">
 <label for="<%= "money_" + @counter.to_s %>">
  <%= f.select(:money, 1..10,   :selected => p.money)%>
 </label>
</th>

Now you've given Prototype the ability to search and find the correct element (the select with the value you're looking for), which you pass to the $() function to call getValue():

function change_people() {
    // Note the "#" on #money_1, which is an ID selector
    // the space " " between is a descendant element selector
    money1 = $($$('#money_1 select')).getValue();
    if (money1 == 10) {
        // do stuff
    } else {
        // do other stuff
    }
}

If you're looking to iterate over all of the money select values in the table, you would instead want to use a class; you are only allowed to have one element per ID, but a class by rule is grouped by attribute. The difference would be:

<th class="money_select">
 <label for="<%= "money_" + @counter.to_s %>">
  <%= f.select(:money, 1..10,   :selected => p.money)%>
 </label>
</th>

And then in your javascript:

function change_people() {
    // Note the "." on .money_1, which is a class selector
    // the space " " between is a descendant element selector
    $$('.money_select select').each(function(element){
        if ($(element).getValue() == 10) {
            // do stuff
        } else {
            // do other stuff
        }
    });
}


问:
trying to use ngClass instead ngIf
I would rewrite this NgIf over ngClass for a shorter code. Unfortunately, the class is not accepted. Can the problem be solved?</p>

```<code>The long Version:

 <div *ngIf="sp.outboundWeeks[i].status=='GREEN'">
                                        <div class="green">
                                            {{sp.outboundWeeks[i].utilizationRate}}
                                        </div>
                                    </div>
                                    <div *ngIf="sp.outboundWeeks[i].status=='RED'">
                                        <div class="red">
                                            {{sp.outboundWeeks[i].utilizationRate}}
                                        </div>
                                    </div>
                                    <div *ngIf="sp.outboundWeeks[i].status=='YELLOW'">
                                        <div class="yellow">
                                            {{sp.outboundWeeks[i].utilizationRate}}
                                        </div>
                                    </div>

the short version should be like the code below:

[ngClass]="{'green':cw.status[i]=='GREEN','yellow':cw.status=='YELLOW','red':cw.status=='RED'}">{{cw.utilizationRate}}
     </div>
</code>```

答:
try this:</p>

```<code><div>
   <div [ngClass]="(sp.outboundWeeks[i].status=='GREEN') ? 'green' :
         (sp.outboundWeeks[i].status=='RED') ? 'red' : 'yellow'">
      {{sp.outboundWeeks[i].utilizationRate}}
   </div>
</div>
</code>```

Title: trying to use ngClass instead ngIf

Body:
I would rewrite this NgIf over ngClass for a shorter code. Unfortunately, the class is not accepted. Can the problem be solved?

The long Version:

                                            {{sp.outboundWeeks[i].utilizationRate}}

                                            {{sp.outboundWeeks[i].utilizationRate}}

                                            {{sp.outboundWeeks[i].utilizationRate}}

the short version should be like the code below:

[ngClass]="{'green':cw.status[i]=='GREEN','yellow':cw.status=='YELLOW','red':cw.status=='RED'}">{{cw.utilizationRate}}

Body:
try this:

<div>
   <div [ngClass]="(sp.outboundWeeks[i].status=='GREEN') ? 'green' :
         (sp.outboundWeeks[i].status=='RED') ? 'red' : 'yellow'">
      {{sp.outboundWeeks[i].utilizationRate}}
   </div>
</div>


问:
React select - How to filter selection based on picked option of other selection field?
I am using react-select and I want to show matching city pairs (certain origins have only certain destinations) in 2 fields. Ive been thinking a lot and can't come up with a way to filter the destination selection field based on what was picked in the origin selection field. Anyone has any ideas or any tipps?Thanks!!

My response is an array with objects. each object has (among other things) the origin city and a destination city:

```<code>...
{OriginDestinationLocations:{DestinationLocation:{CityName:'Orlando'}, OriginLocation:{CityName:'Miami'}}},
 {OriginDestinationLocations:{DestinationLocation:{CityName:'Orlando'}, OriginLocation:{CityName:'Chicago'}}},
 {OriginDestinationLocations:{DestinationLocation:{CityName:'Las Vegas'}, OriginLocation:{CityName:'Miami'}}}
....
// so here (pretending that would be the full list) when I pick Orlando as origin in the 1st selection field, I should only see Miami and Chicago in the second field.

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      from:[],
      to:[]
    }
  }
componentDidMount() {
   cityPairs().then(response => {
        let from = [];
        let to = [];
    // here its wrong to separate destination and origin as origin needs to stay 'connected' to the matching destinations but I just don't know what else to do. if I push objects with always matching origins/destinations into 1 array, I was thinking it would create so many pair, that can't be right in terms of performance etc. or would that be the only way?
        for (var i = 0; i < response.length; i++) {
            from.push(response[i].DestinationLocation.CityName);
            to.push(response[i].OriginLocation.CityName);
        }
        this.setState({
            to: to,
            from: from
        })
    })
}

 handleChange(event) {
    this.setState({value: event.target.value});
 }
render(){
  return (
  <div>
      <Select
          name="form-field-name"
          value={this.state.value}
          onChange={this.handleChange}
          clearable={this.state.clearable}
          searchable={this.state.searchable}
          labelKey='name'
          valueKey='cityCode'
          options={this.state.to}
       />
  </div>
  )
}
}
</code>```

-added parts:

```<code> cityPairs().then(response => {
        this.setState({
            routes: response
                .reduce((dest, x) => Object.assign({}, dest, {
                  ...
                }), {})
        });
    }).then(res => {
        var result = [];
        var r = this.state.routes;
        for (var key in r) {
            result.push(key)
        }
        this.setState({
            originRoutes: result.map(x => ({
                name: x,
                value: x
            } ))
        })
    })

//as I believe  const routes  = this.state.routes[this.state.selected]; should be changed to

const originRoutes  = this.state.originRoutes[this.state.selected];
    const options = !originRoutes ? [] : originRoutes.map(x => ({
        name:  x,
        value: x
} ));

            <Select
                onChange={this.onChange}
                options={this.state.originRoutes}
            />
            <Select
               onChange={this.onChange}
               options={options}
            />
</code>```

答:
What this solution is not containing right now is sending requests again and again. It just loads data from the API initially. But I think this is how the API itself is working right now. Should be changed if the data is too big.</p>

```<code>class App extends React.Component {
    componentWillMount() {
        this.setState({
            routes: []
        });

        cityPairs().then(response => {
            // result is an object with a key of the origin name and a list of destination names
            this.setState({
                routes: response
                    .reduce((dest, x) => Object.assign({}, dest, {
                        // multiple lines at best :-D
                        [x.OriginLocation.CityName]: dest[x.OriginLocation.CityName] ? dest[x.OriginLocation.CityName].concat([x.DestinationLocation.CityName]) : [x.DestinationLocation.CityName]
                    }), {})
            });
        });
    }

    onChange(event) {
        this.setState({
            selected: event.value
        })
    }

    render() {
        const routes  = this.state.routes[this.state.selected];
        const options = !routes ? [] : routes.map(x => ({
            name:  x,
            value: x
        }));

        return(
            <div>
                <Select
                    ...
                    onChange={::this.onChange}
                    options={options}
                />
            </div>
        );
    }
}
</code>```

Body:
I am using react-select and I want to show matching city pairs (certain origins have only certain destinations) in 2 fields. Ive been thinking a lot and can't come up with a way to filter the destination selection field based on what was picked in the origin selection field. Anyone has any ideas or any tipps?Thanks!!

My response is an array with objects. each object has (among other things) the origin city and a destination city:

...
{OriginDestinationLocations:{DestinationLocation:{CityName:'Orlando'}, OriginLocation:{CityName:'Miami'}}},
 {OriginDestinationLocations:{DestinationLocation:{CityName:'Orlando'}, OriginLocation:{CityName:'Chicago'}}},
 {OriginDestinationLocations:{DestinationLocation:{CityName:'Las Vegas'}, OriginLocation:{CityName:'Miami'}}}
....
// so here (pretending that would be the full list) when I pick Orlando as origin in the 1st selection field, I should only see Miami and Chicago in the second field.

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      from:[],
      to:[]
    }
  }
componentDidMount() {
   cityPairs().then(response => {
        let from = [];
        let to = [];
    // here its wrong to separate destination and origin as origin needs to stay 'connected' to the matching destinations but I just don't know what else to do. if I push objects with always matching origins/destinations into 1 array, I was thinking it would create so many pair, that can't be right in terms of performance etc. or would that be the only way?
        for (var i = 0; i < response.length; i++) {
            from.push(response[i].DestinationLocation.CityName);
            to.push(response[i].OriginLocation.CityName);
        }
        this.setState({
            to: to,
            from: from
        })
    })
}

 handleChange(event) {
    this.setState({value: event.target.value});
 }
render(){
  return (

      <Select
          name="form-field-name"
          value={this.state.value}
          onChange={this.handleChange}
          clearable={this.state.clearable}
          searchable={this.state.searchable}
          labelKey='name'
          valueKey='cityCode'
          options={this.state.to}
       />

  )
}
}

-added parts:

 cityPairs().then(response => {
        this.setState({
            routes: response
                .reduce((dest, x) => Object.assign({}, dest, {
                  ...
                }), {})
        });
    }).then(res => {
        var result = [];
        var r = this.state.routes;
        for (var key in r) {
            result.push(key)
        }
        this.setState({
            originRoutes: result.map(x => ({
                name: x,
                value: x
            } ))
        })
    })

//as I believe  const routes  = this.state.routes[this.state.selected]; should be changed to

const originRoutes  = this.state.originRoutes[this.state.selected];
    const options = !originRoutes ? [] : originRoutes.map(x => ({
        name:  x,
        value: x
} ));

            <Select
                onChange={this.onChange}
                options={this.state.originRoutes}
            />
            <Select
               onChange={this.onChange}
               options={options}
            />

Body:
What this solution is not containing right now is sending requests again and again. It just loads data from the API initially. But I think this is how the API itself is working right now. Should be changed if the data is too big.

class App extends React.Component {
    componentWillMount() {
        this.setState({
            routes: []
        });

        cityPairs().then(response => {
            // result is an object with a key of the origin name and a list of destination names
            this.setState({
                routes: response
                    .reduce((dest, x) => Object.assign({}, dest, {
                        // multiple lines at best :-D
                        [x.OriginLocation.CityName]: dest[x.OriginLocation.CityName] ? dest[x.OriginLocation.CityName].concat([x.DestinationLocation.CityName]) : [x.DestinationLocation.CityName]
                    }), {})
            });
        });
    }

    onChange(event) {
        this.setState({
            selected: event.value
        })
    }

    render() {
        const routes  = this.state.routes[this.state.selected];
        const options = !routes ? [] : routes.map(x => ({
            name:  x,
            value: x
        }));

        return(
            <div>
                <Select
                    ...
                    onChange={::this.onChange}
                    options={options}
                />
            </div>
        );
    }
}


问:
How can I convert JSON object to readable swift object?
This is the JSON data I receive from the server:

```<code>[{
    "_id": someRandomID;
    comment = {
        identifier = someRandomIdentifier;
        text = someRandomText;
    };
}]
</code>```

I am using socket.io and I get the data from socket.on() as below:

```<code>socket?.on("add-comment") {data, ack in
   print(data)
}
</code>```

I have tried to create a class for it as below:

```<code>class addComment: Codable {
let _id: String
let comment: comments
}

class comments: Codable {
    let identifier: String
    let text: String

    init(identifier: String, text: String) {
        self.identifier = identifier
        self.text = text
    }
}
</code>```

and inside socket.on I added the following codes:

```<code>socket?.on("add-comment") {data, ack in
    let decoder = JSONDecoder()
    let comment = decoder.decode(addComment.self, from: data)
}
</code>```

It shows me the following:

cannot convert value of type '[Any]' to expected argument type 'Data'

Can anyone please guide through how can I convert the data object I receive from the server to a readable object in swift to be able to access its values?

答:
You are getting this array in the completion handler, data is not of type Data

```<code>let data : [Any]  = [["_id": "someRandomID",
                      "comment" : ["identifier" : "someRandomIdentifier",
                                   "text" : "someRandomText"]
                                  ]
                    ]
</code>```

To use Codable you need to serialize the array to JSON

These are your classes conforming to the Swift naming convention

```<code>class AddComment: Codable {

    private enum CodingKeys : String, CodingKey {
        case id = "_id", comment
    }

    let id: String
    let comment: Comment
}

class Comment: Codable {
    let identifier: String
    let text: String
}
</code>```

And this is the way to make the array Codable compliant

```<code>do {
    let jsonData = try JSONSerialization.data(withJSONObject: data)
    let decoder = JSONDecoder()
    let addComments = try decoder.decode([AddComment].self, from: jsonData)
    print(addComments[0])

} catch {
    print(error)
}
</code>```

Body:
This is the JSON data I receive from the server:

[{
    "_id": someRandomID;
    comment = {
        identifier = someRandomIdentifier;
        text = someRandomText;
    };
}]

I am using socket.io and I get the data from socket.on() as below:

socket?.on("add-comment") {data, ack in
   print(data)
}

I have tried to create a class for it as below:

class addComment: Codable {
let _id: String
let comment: comments
}

class comments: Codable {
    let identifier: String
    let text: String

    init(identifier: String, text: String) {
        self.identifier = identifier
        self.text = text
    }
}

and inside socket.on I added the following codes:

socket?.on("add-comment") {data, ack in
    let decoder = JSONDecoder()
    let comment = decoder.decode(addComment.self, from: data)
}

It shows me the following:

cannot convert value of type '[Any]' to expected argument type 'Data'

Can anyone please guide through how can I convert the data object I receive from the server to a readable object in swift to be able to access its values?

Body:
You are getting this array in the completion handler, data is not of type Data

let data : [Any]  = [["_id": "someRandomID",
                      "comment" : ["identifier" : "someRandomIdentifier",
                                   "text" : "someRandomText"]
                                  ]
                    ]

To use Codable you need to serialize the array to JSON

These are your classes conforming to the Swift naming convention

class AddComment: Codable {

    private enum CodingKeys : String, CodingKey {
        case id = "_id", comment
    }

    let id: String
    let comment: Comment
}

class Comment: Codable {
    let identifier: String
    let text: String
}

And this is the way to make the array Codable compliant

do {
    let jsonData = try JSONSerialization.data(withJSONObject: data)
    let decoder = JSONDecoder()
    let addComments = try decoder.decode([AddComment].self, from: jsonData)
    print(addComments[0])

} catch {
    print(error)
}


问:
Android Dex: Unable to execute DX (IntelliJ)
I follow the steps from https://stackoverflow.com/a/5271194/1973953 this link.

But when i run an application i am getting these errors

i have only one line in my project.properties file "target=android-11"

And this is my AndroidManifest.xml

So my question is why i am getting these errors and how to solve them...

答:
I had same problem, I had added a jar to my project lib. I deleted it and
problem solved.
You can check your project, undo your last changes to find the problem.  </p>


问:
Root path of site in CodeIgniter
I am using Uploading Class to upload images. But the location where my uploaded images will be stored is: http://www.mysite.com/uploads/

Absolute path to this folder is: c:\wamp\www\mysite\uploads\

Application folder is in : c:\wamp\www\mysite\application\

So when I upload to server, absolute path will not be same. So, how to get absolute root path to use with the upload_path config of Uploading Class?

答:
Please use APPPATH you will get the directory path of your site root directory.

like this APPPATH.'uploads/images/';

Title: Root path of site in CodeIgniter


问:
Subsonic race condition detected each new DB connection
I'm having a hard time debugging a service.

I will start by explaining the cenario that I'm running.
I got 9 databases using their services importations, generations of reports and exporting data.
They all run fine for a day or two but after that subsonic starts to give exceptions when there is a new connection to database, all exceptions are simillar, just change the database operation, there is an exemple:

```<code>Probable I/O race condition detected while copying memory. The I/O package is not thread safe by default. In multithreaded applications, a stream must be accessed in a thread-safe way, such as a thread-safe wrapper returned by TextReader's or TextWriter's Synchronized methods. This also applies to classes like StreamWriter and StreamReader.
   at System.Buffer.InternalBlockCopy(Array src, Int32 srcOffsetBytes, Array dst, Int32 dstOffsetBytes, Int32 byteCount)
   at System.IO.StreamWriter.Write(Char[] buffer, Int32 index, Int32 count)
   at System.IO.TextWriter.WriteLine(String value)
   at System.IO.TextWriter.WriteLine(String format, Object arg0)
   at System.IO.TextWriter.SyncTextWriter.WriteLine(String format, Object arg0)
   at SubSonic.DataProviders.DbDataProvider.ExecuteReader(QueryCommand qry) in C:\[path]\SubSonic.Core\DataProviders\DbDataProvider.cs:line 112
   at SubSonic.Linq.Structure.DbQueryProvider.Execute[T](QueryCommand`1 query, Object[] paramValues) in C:\[path]\SubSonic.Core\Linq\Structure\DbQueryProvider.cs:line 280
   at lambda_method(Closure )
   at SubSonic.Linq.Structure.DbQueryProvider.Execute(Expression expression) in C:\[path]\SubSonic.Core\Linq\Structure\DbQueryProvider.cs:line 131
   at SubSonic.Linq.Structure.QueryProvider.System.Linq.IQueryProvider.Execute(Expression expression) in C:\[path]\SubSonic.Core\Linq\Structure\QueryProvider.cs:line 50
   at SubSonic.Linq.Structure.Query`1.GetEnumerator() in C:\[path]\SubSonic.Core\Linq\Structure\Query.cs:line 85
   at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
   at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
   at [namespace].ReportManager.GetAllPending() in [path]\ReportManager.cs:line 193
   at [namespace].ReportsServiceHandler.Run() in C:\[path]\ReportsServiceHandler.cs:line 137
</code>```

The only solution so far that I have is to reset the service but I wasn't able yet to discovery what may cause this. I tried to debug it in my local environment but I wasn't able to do it.

Anyone know if there is a bug in subsonic or how can I find the problem in the services?

Thank you in advance for the help.

答:
subsonics3 returns you reader , and you can dispose it following way

```<code>Query qry = Product.CreateQuery().WHERE("ListPrice > 50.00")
            .AND("Class = L").AND("Color = Yellow");
using(IDataReader rdr = qry.ExecuteReader())
{
 while (rdr.Read()) {
   Console.WriteLine(rdr[Product.Columns.Name].ToString());
 }
}
</code>```

using(SqlDataReader reader = command.ExecuteReader())
        {
            ... do your stuff ...
        }

i think you need to dispose you connection properly by making use of using, because there might be cause connection you used previously still open i.e. not closed.

```<code>using(var connection = new Connection())
{
}
</code>```

above code dispose you connection. or if it is not there i suggest make use of Dispose Pattern and dispose conneciton object after use of it.

Body:
I'm having a hard time debugging a service.

I will start by explaining the cenario that I'm running.
I got 9 databases using their services importations, generations of reports and exporting data.
They all run fine for a day or two but after that subsonic starts to give exceptions when there is a new connection to database, all exceptions are simillar, just change the database operation, there is an exemple:

Probable I/O race condition detected while copying memory. The I/O package is not thread safe by default. In multithreaded applications, a stream must be accessed in a thread-safe way, such as a thread-safe wrapper returned by TextReader's or TextWriter's Synchronized methods. This also applies to classes like StreamWriter and StreamReader.
   at System.Buffer.InternalBlockCopy(Array src, Int32 srcOffsetBytes, Array dst, Int32 dstOffsetBytes, Int32 byteCount)
   at System.IO.StreamWriter.Write(Char[] buffer, Int32 index, Int32 count)
   at System.IO.TextWriter.WriteLine(String value)
   at System.IO.TextWriter.WriteLine(String format, Object arg0)
   at System.IO.TextWriter.SyncTextWriter.WriteLine(String format, Object arg0)
   at SubSonic.DataProviders.DbDataProvider.ExecuteReader(QueryCommand qry) in C:\[path]\SubSonic.Core\DataProviders\DbDataProvider.cs:line 112
   at SubSonic.Linq.Structure.DbQueryProvider.Execute[T](QueryCommand`1 query, Object[] paramValues) in C:\[path]\SubSonic.Core\Linq\Structure\DbQueryProvider.cs:line 280
   at lambda_method(Closure )
   at SubSonic.Linq.Structure.DbQueryProvider.Execute(Expression expression) in C:\[path]\SubSonic.Core\Linq\Structure\DbQueryProvider.cs:line 131
   at SubSonic.Linq.Structure.QueryProvider.System.Linq.IQueryProvider.Execute(Expression expression) in C:\[path]\SubSonic.Core\Linq\Structure\QueryProvider.cs:line 50
   at SubSonic.Linq.Structure.Query`1.GetEnumerator() in C:\[path]\SubSonic.Core\Linq\Structure\Query.cs:line 85
   at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
   at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
   at [namespace].ReportManager.GetAllPending() in [path]\ReportManager.cs:line 193
   at [namespace].ReportsServiceHandler.Run() in C:\[path]\ReportsServiceHandler.cs:line 137

The only solution so far that I have is to reset the service but I wasn't able yet to discovery what may cause this. I tried to debug it in my local environment but I wasn't able to do it.

Anyone know if there is a bug in subsonic or how can I find the problem in the services?

Thank you in advance for the help.

Body:
subsonics3 returns you reader , and you can dispose it following way

Query qry = Product.CreateQuery().WHERE("ListPrice > 50.00")
            .AND("Class = L").AND("Color = Yellow");
using(IDataReader rdr = qry.ExecuteReader())
{
 while (rdr.Read()) {
   Console.WriteLine(rdr[Product.Columns.Name].ToString());
 }
}

using(SqlDataReader reader = command.ExecuteReader())
        {
            ... do your stuff ...
        }

i think you need to dispose you connection properly by making use of using, because there might be cause connection you used previously still open i.e. not closed.

using(var connection = new Connection())
{
}

above code dispose you connection. or if it is not there i suggest make use of Dispose Pattern and dispose conneciton object after use of it.


问:
Setting a C++ Class char* in constructor
I am writing a simple client / server program to mess around with socket programming. I made two classes, one for the client and one for the server. I can run my server with no problems and also my client can connect. But now I am attempting to modify my client so it accepts the hostname and port number in the constructor.

Here is what I have so far (client.h class only the constructor and attributes):

```<code>#ifndef CLIENT_H
#define CLIENT_H

class Client
{
    public:

    Client(char *in_hostname, int in_port)
        : hostname(&in_hostname), port(in_port)
    {

    }

    ~Client() {}

    private:

    char *hostname;
    int port;

};

#endif
</code>```

I am having a hard time setting the char * hostname from the constructor. I am obviously having a little trouble with pointers and references. Can someone help me out here, coding mostly in PHP for the past 5 years has made my C++ rusty...

Here is the C++ file I use the client.h class.

```<code>#include <iostream>

#include "client.h"

using namespace std;

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

    if(argc == 3)
    {
        hostname = argv[1];
        port = argv[2];

        Client *client = new Client(hostname, port);

        delete(client);
    }
    else
    {
        cout << "Usage: ./client hostname port" << endl;
    }

    return 0;
}
</code>```

Thanks!

答:
I am having a hard time setting the char * hostname from the constructer.

Change &in_hostname to in_hostname

```<code>Client(char *in_hostname, int in_port)
        : hostname(in_hostname), port(in_port)
    {

    }
</code>```

However if you want your code to be clean you should use std::string (C++ style string) instead of (char *) i.e C style string

Body:
I am writing a simple client / server program to mess around with socket programming. I made two classes, one for the client and one for the server. I can run my server with no problems and also my client can connect. But now I am attempting to modify my client so it accepts the hostname and port number in the constructor.

Here is what I have so far (client.h class only the constructor and attributes):

#ifndef CLIENT_H
#define CLIENT_H

class Client
{
    public:

    Client(char *in_hostname, int in_port)
        : hostname(&in_hostname), port(in_port)
    {

    }

    ~Client() {}

    private:

    char *hostname;
    int port;

};

#endif

I am having a hard time setting the char * hostname from the constructor. I am obviously having a little trouble with pointers and references. Can someone help me out here, coding mostly in PHP for the past 5 years has made my C++ rusty...

Here is the C++ file I use the client.h class.

#include <iostream>

#include "client.h"

using namespace std;

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

    if(argc == 3)
    {
        hostname = argv[1];
        port = argv[2];

        Client *client = new Client(hostname, port);

        delete(client);
    }
    else
    {
        cout << "Usage: ./client hostname port" << endl;
    }

    return 0;
}

Thanks!

Body:
I am having a hard time setting the char * hostname from the constructer.

Change &in_hostname to in_hostname

Client(char *in_hostname, int in_port)
        : hostname(in_hostname), port(in_port)
    {

    }

However if you want your code to be clean you should use std::string (C++ style string) instead of (char *) i.e C style string


问:
How to check if Spark RDD is in memory?
I have an instance of org.apache.spark.rdd.RDD[MyClass].
How can I programmatically check if the instance is persist\inmemory?</p>

答:
You can call rdd.getStorageLevel.useMemory to check if it is in memory or not as follows:</p>

```<code>scala> myrdd.getStorageLevel.useMemory
res3: Boolean = false

scala> myrdd.cache()
res4: myrdd.type = MapPartitionsRDD[2] at filter at <console>:29

scala> myrdd.getStorageLevel.useMemory
res5: Boolean = true
</code>```

Title: How to check if Spark RDD is in memory?

Body:
You can call rdd.getStorageLevel.useMemory to check if it is in memory or not as follows:

scala> myrdd.getStorageLevel.useMemory
res3: Boolean = false

scala> myrdd.cache()
res4: myrdd.type = MapPartitionsRDD[2] at filter at <console>:29

scala> myrdd.getStorageLevel.useMemory
res5: Boolean = true


问:
Auto generate pkpass file and send to wallet Iphone
I would like to generate pkpass files on my server automatically and send them to users in an email.

According to Apple's Wallet Developer Guide, I should use signpass tool to generate pkpass file. Can I install this on server (Debian) and auto generate pkpass for our Guests after they submit a new order? If it isn't possible - how can I auto generate pkpass files and attach to E-mail confirmation with php Laravel?

I don't want to use external tools like passsource.com.

答:
You can use this, it's very simple to implement and works properly:

https://github.com/tschoffelen/PHP-PKPass

You might need to change the code a bit, that is, generate the .pkpass file, save on local, send via email and delete. Repeat the number of times that you want.


问:
get data to viewPager fragment from its fragments
I am using viewPager for my custom Tablayout.  I have two fragments, when viewPager activity was created , it should get the data from one of the fragment and have to display it on the tabs as unread count.
but I am getting data at scrolling. how can I over come this issue ?. please help me.

```<code>viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                PendingPlusPendingForUploadFiles frage = new PendingPlusPendingForUploadFiles();
                System.out.println("====c value===" + frage.count);
            }

            @Override
            public void onPageSelected(int position) {
                //  previousTabPosition = position;
                viewPager.setCurrentItem(position);

            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
</code>```

答: you can  onResume(); method in the Fragment get it!</p>

Body:
I am using viewPager for my custom Tablayout.  I have two fragments, when viewPager activity was created , it should get the data from one of the fragment and have to display it on the tabs as unread count.
but I am getting data at scrolling. how can I over come this issue ?. please help me.

viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                PendingPlusPendingForUploadFiles frage = new PendingPlusPendingForUploadFiles();
                System.out.println("====c value===" + frage.count);
            }

            @Override
            public void onPageSelected(int position) {
                //  previousTabPosition = position;
                viewPager.setCurrentItem(position);

            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });


问:
PaginationAndSortingRepository returning empty
I am working on a application where I need to display some screens with pagination. I started with PaginationAndSortingRepository of Spring Data JPA .All seemed to work fine but when I executed the code I could not get the Data ,it returned empty without any error on eclipse console .

Below is my code for controller :-

```<code>@RequestMapping(value="/monatsultimodata" , method=RequestMethod.Get)
public List<Monatsultimo> getData(Pageable pageable){
List<Monatsultimo> dataList = null ;
try{
dataList= monatsultimoservice.getData(pageable)
}catch(Exception e){
e.printStackTrace();
}
return dataList;
}
</code>```

Below is my service code :-

```<code>public List<Monatsultimo> getData(Pageable pageable){
List<Monatsultimo> tableData = new AarrayList();
monatsultimorepo.findAll(pageable)
return tableData;
}
</code>```

Below is my repository code :-

```<code>@Repository
public interface MonatsultimoRepo extends
PagingAndSortingRepository<MonatSultimo, Integer>{
}
</code>```

Below is my application.yaml file

```<code>    jpa:
        properties:
            hibernate:
                format_sql: true
                show_sql: true
                type: 'debug'
                use_sql_comments: true
                ddl-auto:update
server:
        port: 9000

security:
    basic:
        enabled: false
</code>```

URL I am using to hit the Rest Service - localhhost:9000/Add to dictionary?page=0&size=25

everything goes right ,,till the time it return with no data .Please help me with this ,I have been struggling with it since days .

Thanks in advance ..

答:
Before return tableData assign result of monatsultimorepo.findAll(pageable)to tableData

Service:

```<code> public List<Monatsultimo> getData(){
   List<Monatsultimo> tableData = new AarrayList();
   tableData =monatsultimorepo.findAll()
   return tableData;
 }
</code>```

Controller:

```<code>@RequestMapping(value="/monatsultimodata" , method=RequestMethod.Get)
   public List<Monatsultimo> getData(){
     List<Monatsultimo> dataList = null ;
     try{
       dataList= monatsultimoservice.getData()
     }catch(Exception e){
     e.printStackTrace();
   }
   return dataList;
 }
</code>```

Repository:

```<code>@Repository
public interface MonatsultimoRepo extends JpaRepository<MonatSultimo,Integer>{
}
</code>```

Body:
I am working on a application where I need to display some screens with pagination. I started with PaginationAndSortingRepository of Spring Data JPA .All seemed to work fine but when I executed the code I could not get the Data ,it returned empty without any error on eclipse console .

Below is my code for controller :-

@RequestMapping(value="/monatsultimodata" , method=RequestMethod.Get)
public List<Monatsultimo> getData(Pageable pageable){
List<Monatsultimo> dataList = null ;
try{
dataList= monatsultimoservice.getData(pageable)
}catch(Exception e){
e.printStackTrace();
}
return dataList;
}

Below is my service code :-

public List<Monatsultimo> getData(Pageable pageable){
List<Monatsultimo> tableData = new AarrayList();
monatsultimorepo.findAll(pageable)
return tableData;
}

Below is my repository code :-

@Repository
public interface MonatsultimoRepo extends
PagingAndSortingRepository<MonatSultimo, Integer>{
}

Below is my application.yaml file

    jpa:
        properties:
            hibernate:
                format_sql: true
                show_sql: true
                type: 'debug'
                use_sql_comments: true
                ddl-auto:update
server:
        port: 9000

security:
    basic:
        enabled: false

URL I am using to hit the Rest Service - localhhost:9000/Add to dictionary?page=0&size=25

everything goes right ,,till the time it return with no data .Please help me with this ,I have been struggling with it since days .

Thanks in advance ..

Body:
Before return tableData assign result of monatsultimorepo.findAll(pageable)to tableData

Service:

 public List<Monatsultimo> getData(){
   List<Monatsultimo> tableData = new AarrayList();
   tableData =monatsultimorepo.findAll()
   return tableData;
 }

Controller:

@RequestMapping(value="/monatsultimodata" , method=RequestMethod.Get)
   public List<Monatsultimo> getData(){
     List<Monatsultimo> dataList = null ;
     try{
       dataList= monatsultimoservice.getData()
     }catch(Exception e){
     e.printStackTrace();
   }
   return dataList;
 }

Repository:

@Repository
public interface MonatsultimoRepo extends JpaRepository<MonatSultimo,Integer>{
}


答:
Add square brackets around the object you want to create, your json is an array of (1) objects, not an object.

try this:

```<code>let comments = decoder.decode([addComment].self, from: data)
</code>```

(also your class name as a plural without a starting capital is quite confusing)

Title: How can I convert JSON object to readable swift object?

Body:
Add square brackets around the object you want to create, your json is an array of (1) objects, not an object.

try this:

let comments = decoder.decode([addComment].self, from: data)

(also your class name as a plural without a starting capital is quite confusing)


答:
If you're going to be coding in C++ may I suggest using std::string instead of char pointers?

```<code>class Client
{
    public:

    Client(const string& in_hostname, int in_port)
        : hostname(in_hostname), port(in_port)
    {

    }

    ~Client() {}

    private:

    std::string hostname;
    int port;
};
</code>```

Edit:

In response to your comment.  If you have to pass the pointer around to another function you can get it from  std::string::c_str

```<code>std::string stuff;
stuff.c_str();
</code>```

Title: Setting a C++ Class char* in constructor

Body:
If you're going to be coding in C++ may I suggest using std::string instead of char pointers?

class Client
{
    public:

    Client(const string& in_hostname, int in_port)
        : hostname(in_hostname), port(in_port)
    {

    }

    ~Client() {}

    private:

    std::string hostname;
    int port;
};

Edit:

In response to your comment.  If you have to pass the pointer around to another function you can get it from  std::string::c_str

std::string stuff;
stuff.c_str();


问:
Pass an array or list of different objects to a function for modification
Currently I am receiving an array of objects from a database.

```<code>object [] sqlResultData = DatabaseCall.Result();
</code>```

This array of objects needs to be matched to class variables like this

```<code>CClassOfVars classVar = new CClassOfVars();
classVar.myProperty = sqlResultData[0];
classVar.myProperty1 = sqlResultData[1];
</code>```

What i wish to do is pass the list of propertys on the class in order to a function and have the mapping from the object array occur automatically based on the order.

For example:

Method defined like this

```<code>FillData(object [] databaseValues, IList<object>())
</code>```

Called like this

```<code>CClassOfVars classVar = new CClassOfVars();
object [] sqlResultData = DatabaseCall.Result();
FillData(sqlResultData, new List<object>(){classVar.myProperty,classVar.myProperty1});
</code>```

The FillData function would hopefully type cast and set the values of myProperty and myProperty1 to the values in array locations of 0,1 etc...

Something like this

```<code>FillData(object [] databaseValues, IList<object> mapMe)
{
   for (int i = 0; i < mapMe.Count; i++)
     {
        mapMe[i] = CastToTheCorrectType(mapMe[i], databaseValues[i]);
     }
}
</code>```

Cast to the correct type could look like this?? I took from here: cast object with a Type variable

```<code> public T CastToTheCorrectType<T>(T hackToInferNeededType, object givenObject) where T : class
  {
     return givenObject as T;
  }
</code>```

How can i pass a list of different object types to all have there values modified and assigned within a different function?

答:
The matter you asking about is dark and difficult to be implemented through just a function. There are frameworks out there dealing with object relational mapping. If it is an option, install and learn some OR/M. If not ... well,  there might be some dirty way.

You can use the JSON.NET library to do the heavy lifting for you. It's super easy to use and install through Nuget. My point is as follows.

Construct an anonymous object. Use the property names of the original object.

Fill it with the data from the object array. Spin a loop over the object array...

Serialize the anonymous object.

Deserialize the JSON string into the target type.
At this point, JSON.NET will handle property mapping for you.

List item

E.g. if your target type is Person you might do this:

```<code>var x = new
{
    FirstName = String.Empty,
    LastName = String.Empty
};

var persons = new List<Person>(sqlResultData.Length);

foreach (var record in sqlResultData)
{
    x.FirstName = record[0];
    x.LastName = record[1];

    var s = JsonConvert.SerializeObject(x)`
    var personX = JsonConvert.Deserialize<Person>(s);
    persons.Add(person);
}
</code>```

Body:
Currently I am receiving an array of objects from a database.

object [] sqlResultData = DatabaseCall.Result();

This array of objects needs to be matched to class variables like this

CClassOfVars classVar = new CClassOfVars();
classVar.myProperty = sqlResultData[0];
classVar.myProperty1 = sqlResultData[1];

What i wish to do is pass the list of propertys on the class in order to a function and have the mapping from the object array occur automatically based on the order.

For example:

Method defined like this

FillData(object [] databaseValues, IList<object>())

Called like this

CClassOfVars classVar = new CClassOfVars();
object [] sqlResultData = DatabaseCall.Result();
FillData(sqlResultData, new List<object>(){classVar.myProperty,classVar.myProperty1});

The FillData function would hopefully type cast and set the values of myProperty and myProperty1 to the values in array locations of 0,1 etc...

Something like this

FillData(object [] databaseValues, IList<object> mapMe)
{
   for (int i = 0; i < mapMe.Count; i++)
     {
        mapMe[i] = CastToTheCorrectType(mapMe[i], databaseValues[i]);
     }
}

Cast to the correct type could look like this?? I took from here: cast object with a Type variable

 public T CastToTheCorrectType<T>(T hackToInferNeededType, object givenObject) where T : class
  {
     return givenObject as T;
  }

How can i pass a list of different object types to all have there values modified and assigned within a different function?

Body:
The matter you asking about is dark and difficult to be implemented through just a function. There are frameworks out there dealing with object relational mapping. If it is an option, install and learn some OR/M. If not ... well,  there might be some dirty way.

You can use the JSON.NET library to do the heavy lifting for you. It's super easy to use and install through Nuget. My point is as follows.

Construct an anonymous object. Use the property names of the original object.

Fill it with the data from the object array. Spin a loop over the object array...

Serialize the anonymous object.

Deserialize the JSON string into the target type.
At this point, JSON.NET will handle property mapping for you.

List item

E.g. if your target type is Person you might do this:

var x = new
{
    FirstName = String.Empty,
    LastName = String.Empty
};

var persons = new List<Person>(sqlResultData.Length);

foreach (var record in sqlResultData)
{
    x.FirstName = record[0];
    x.LastName = record[1];

    var s = JsonConvert.SerializeObject(x)`
    var personX = JsonConvert.Deserialize<Person>(s);
    persons.Add(person);
}


问:
How to call on destroy() method without being called onPause & onStop
I want to call onDestroy() method without calling other method of lifecycle apart from onCreate() method.

答: You have to invoke finish() in onCreate()


问:
Linux - moving files from source to destination with overwrite
Firstly I'd like to apologize if I duplicated a questions which already exists but it's too important to screw this.

I have two directories on my linux server:
 - /tmp/tmp as source
 - /var as destination

There are already like 500 txt files in /var directory and I'd like to move all my files from /tmp directory (about 200 files) to /var directory with replacing those ones which already exist with the same name but as well as not touching those ones which are not in /tmp.

Practical example:
/var files: a.txt , b.txt , c.txt , d.txt
/tmp files: a.txt , b.txt
Result: /var files: a.txt(from /tmp) , b.txt(from /tmp) , c.txt , d.txt

Not sure if mv is a proper method to do that, so thank you in advance guys! :)

答:
You cannot merge two directories using mv command simply. You can use either of the following ways:

1) You can use cp and rm commands to achieve your purpose.

```<code>$ cp -r /var /tmp
$ rm -rf /var
</code>```

2) Using rsync, you can achieve that but rsync doesn't actyally "move" as per your question. It rather copies from one location to other(usually remote).

```<code>$ rsync -a -v /var /tmp
$ rm -r /var
</code>```

I think this should serve the purpose. Cheers!

Body:
You cannot merge two directories using mv command simply. You can use either of the following ways:

1) You can use cp and rm commands to achieve your purpose.

$ cp -r /var /tmp
$ rm -rf /var

2) Using rsync, you can achieve that but rsync doesn't actyally "move" as per your question. It rather copies from one location to other(usually remote).

$ rsync -a -v /var /tmp
$ rm -r /var

I think this should serve the purpose. Cheers!


问:
Make button tapped only once - Swift
I am making timer. I cannot figure out how to make start button tapped only once as it is starting to count. And at stop button timer.invalidate() does not work </p>

```<code>@IBAction func start(_ sender: Any) {
    timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(W1ViewController.counter), userInfo: nil, repeats: true)
}

@IBOutlet weak var stopOutlet: UIButton!

@IBAction func stop(_ sender: Any) {
    seconds = 30
    label.text = "\(seconds)"
    timer.invalidate()
    audioPlayer.stop()
}
</code>```

答:
Just disable the button

```<code>@IBAction func start(_ sender: Any) {
    stopOutlet.isEnabled = false
    timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(W1ViewController.counter), userInfo: nil, repeats: true)
}
</code>```

Then re-enable when needed:

```<code>stopOutlet.isEnabled = true
</code>```

UIButton extends UIControl. UIControl provides this and alot more functionality to all controls.

Title: Make button tapped only once - Swift

Body:
I am making timer. I cannot figure out how to make start button tapped only once as it is starting to count. And at stop button timer.invalidate() does not work

@IBAction func start(_ sender: Any) {
    timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(W1ViewController.counter), userInfo: nil, repeats: true)
}

@IBOutlet weak var stopOutlet: UIButton!

@IBAction func stop(_ sender: Any) {
    seconds = 30
    label.text = "\(seconds)"
    timer.invalidate()
    audioPlayer.stop()
}

Body:
Just disable the button

@IBAction func start(_ sender: Any) {
    stopOutlet.isEnabled = false
    timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(W1ViewController.counter), userInfo: nil, repeats: true)
}

Then re-enable when needed:

stopOutlet.isEnabled = true

UIButton extends UIControl. UIControl provides this and alot more functionality to all controls.


问:
integrating onesignal in multimodule project android
i m getting android failed to choose configuration of the library when i m adding one-signal code in the gradle

this is my app gradle

```<code>apply plugin: 'com.android.application'

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile project(':letsinternlib')
    compile project(':commonslib')
    implementation 'com.android.support:appcompat-v7:26.1.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.1'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'

}
</code>```

my library gradle is look like i added one signal code in this library
but it does not sync the comman library in the projects so please take a look

```<code>plugins {
    id 'com.onesignal.androidsdk.onesignal-gradle-plugin' version '0.7.0'
}
apply plugin: 'com.onesignal.androidsdk.onesignal-gradle-plugin'
apply plugin: 'com.android.library'
apply plugin: 'com.google.gms.google-services'

dependencies {
    implementation 'com.android.support.constraint:constraintlayout:1.0.2'
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation project(path:':commonslib',configuration: 'default')
    implementation 'com.android.volley:volley:1.0.0'
    implementation 'com.android.support:appcompat-v7:26.1.0'
    implementation 'com.android.support:support-core-utils:26.1.0'
    implementation 'com.android.support:design:26.1.0'
    implementation 'com.android.support:support-v4:26.1.0'
    implementation 'com.aurelhubert:ahbottomnavigation:2.1.0'
    implementation 'com.android.support:customtabs:26.1.0'
    implementation 'com.facebook.android:facebook-android-sdk:[4,5)'
    implementation 'com.nostra13.universalimageloader:universal-image-loader:1.9.5'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
    androidTestImplementation 'com.android.support.test:runner:1.0.1'
    implementation 'com.google.android.gms:play-services-gcm:11.6.0'
   // implementation 'com.onesignal:OneSignal:[3.6.5, 3.99.99]'
    testCompile 'junit:junit:4.12'
}
</code>```

答:
I believe you are running into the same issue as below.
https://github.com/OneSignal/OneSignal-Gradle-Plugin/issues/9

Until we can resolve the issue you can try removing it by removing the following from your build.gradle

```<code>plugins {
    id 'com.onesignal.androidsdk.onesignal-gradle-plugin' version '0.7.0'
}
apply plugin: 'com.onesignal.androidsdk.onesignal-gradle-plugin'
</code>```

However without this you may see some errors related to version not matching with gms, firebase, the android support library. To resolve these you can follow this guide:

OneSignal Documentation: Troubleshooting Android

Body:
i m getting android failed to choose configuration of the library when i m adding one-signal code in the gradle

this is my app gradle

apply plugin: 'com.android.application'

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile project(':letsinternlib')
    compile project(':commonslib')
    implementation 'com.android.support:appcompat-v7:26.1.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.1'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'

}

my library gradle is look like i added one signal code in this library
but it does not sync the comman library in the projects so please take a look

plugins {
    id 'com.onesignal.androidsdk.onesignal-gradle-plugin' version '0.7.0'
}
apply plugin: 'com.onesignal.androidsdk.onesignal-gradle-plugin'
apply plugin: 'com.android.library'
apply plugin: 'com.google.gms.google-services'

dependencies {
    implementation 'com.android.support.constraint:constraintlayout:1.0.2'
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation project(path:':commonslib',configuration: 'default')
    implementation 'com.android.volley:volley:1.0.0'
    implementation 'com.android.support:appcompat-v7:26.1.0'
    implementation 'com.android.support:support-core-utils:26.1.0'
    implementation 'com.android.support:design:26.1.0'
    implementation 'com.android.support:support-v4:26.1.0'
    implementation 'com.aurelhubert:ahbottomnavigation:2.1.0'
    implementation 'com.android.support:customtabs:26.1.0'
    implementation 'com.facebook.android:facebook-android-sdk:[4,5)'
    implementation 'com.nostra13.universalimageloader:universal-image-loader:1.9.5'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
    androidTestImplementation 'com.android.support.test:runner:1.0.1'
    implementation 'com.google.android.gms:play-services-gcm:11.6.0'
   // implementation 'com.onesignal:OneSignal:[3.6.5, 3.99.99]'
    testCompile 'junit:junit:4.12'
}

Body:
I believe you are running into the same issue as below.
https://github.com/OneSignal/OneSignal-Gradle-Plugin/issues/9

Until we can resolve the issue you can try removing it by removing the following from your build.gradle

plugins {
    id 'com.onesignal.androidsdk.onesignal-gradle-plugin' version '0.7.0'
}
apply plugin: 'com.onesignal.androidsdk.onesignal-gradle-plugin'

However without this you may see some errors related to version not matching with gms, firebase, the android support library. To resolve these you can follow this guide:

OneSignal Documentation: Troubleshooting Android


问:
app:transformDexArchiveWithExternalLibsDexMergerForDebug
hi guys i get this error when i try to run my app

Error:Execution failed for task
':app:transformDexArchiveWithExternalLibsDexMergerForDebug'.
com.android.builder.dexing.DexArchiveMergerException: Unable to merge dex

i don't know why!

I tried also to clean and rebuild project but i get always the same error!

Now i post my gradle:

```<code>android {
    compileSdkVersion 23
    buildToolsVersion '26.0.2'

    defaultConfig {
        applicationId "com.compscitutorials.basigarcia.navigationdrawervideotutorial"
        minSdkVersion 19
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
        multiDexEnabled true

    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    packagingOptions {
        exclude 'META-INF/DEPENDENCIES'
        exclude 'META-INF/LICENSE'
        exclude 'META-INF/LICENSE.txt'
        exclude 'META-INF/license.txt'
        exclude 'META-INF/NOTICE'
        exclude 'META-INF/NOTICE.txt'
        exclude 'META-INF/notice.txt'
        exclude 'META-INF/ASL2.0'    }
}

dependencies {
    implementation 'com.android.support.constraint:constraint-layout:1.0.2'
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    //noinspection GradleCompatible
    compile 'com.android.support:appcompat-v7:23.1.0'
    compile 'com.android.support:design:23.1.1'
    compile 'de.hdodenhof:circleimageview:1.3.0'
    //noinspection GradleCompatible
    compile 'com.android.support:recyclerview-v7:26.1.0'
    //noinspection GradleCompatible
    compile 'com.android.support:cardview-v7:26.1.0'
    compile 'com.squareup.picasso:picasso:2.5.2'
    compile 'com.github.bumptech.glide:glide:3.8.0'
    //compile 'com.android.volley:volley:1.0.0'
    compile 'com.google.android.exoplayer:exoplayer:r2.4.0'
    compile 'com.google.android.exoplayer:exoplayer-core:r2.4.0'
    compile 'com.google.android.exoplayer:exoplayer-dash:r2.4.0'
    compile 'com.google.android.exoplayer:exoplayer-hls:r2.4.0'
    compile 'com.google.android.exoplayer:exoplayer-smoothstreaming:r2.4.0'
    compile 'com.google.android.exoplayer:exoplayer-ui:r2.4.0'
    compile 'com.facebook.android:facebook-android-sdk:3.21.1'
    //noinspection DuplicatePlatformClasses
    implementation 'org.apache.httpcomponents:httpclient:4.5.3'
}
</code>```

答:
I could compile your gradle after this changes:

```<code>compile 'com.android.support:appcompat-v7:26.1.0'
compile 'com.android.support:design:26.1.0'
compile 'com.android.support:support-core-utils:26.1.0'
</code>```

instead of

```<code>compile 'com.android.support:appcompat-v7:23.1.0'
compile 'com.android.support:design:23.1.1'
</code>```

and also

```<code>android {
    compileSdkVersion 26
</code>```

instead of

```<code>android {
    compileSdkVersion 23
</code>```

ContentLicense: CC BY-SA 4.0

Body:
hi guys i get this error when i try to run my app

Error:Execution failed for task
':app:transformDexArchiveWithExternalLibsDexMergerForDebug'.
com.android.builder.dexing.DexArchiveMergerException: Unable to merge dex

i don't know why!

I tried also to clean and rebuild project but i get always the same error!

Now i post my gradle:

android {
    compileSdkVersion 23
    buildToolsVersion '26.0.2'

    defaultConfig {
        applicationId "com.compscitutorials.basigarcia.navigationdrawervideotutorial"
        minSdkVersion 19
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
        multiDexEnabled true

    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    packagingOptions {
        exclude 'META-INF/DEPENDENCIES'
        exclude 'META-INF/LICENSE'
        exclude 'META-INF/LICENSE.txt'
        exclude 'META-INF/license.txt'
        exclude 'META-INF/NOTICE'
        exclude 'META-INF/NOTICE.txt'
        exclude 'META-INF/notice.txt'
        exclude 'META-INF/ASL2.0'    }
}

dependencies {
    implementation 'com.android.support.constraint:constraint-layout:1.0.2'
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    //noinspection GradleCompatible
    compile 'com.android.support:appcompat-v7:23.1.0'
    compile 'com.android.support:design:23.1.1'
    compile 'de.hdodenhof:circleimageview:1.3.0'
    //noinspection GradleCompatible
    compile 'com.android.support:recyclerview-v7:26.1.0'
    //noinspection GradleCompatible
    compile 'com.android.support:cardview-v7:26.1.0'
    compile 'com.squareup.picasso:picasso:2.5.2'
    compile 'com.github.bumptech.glide:glide:3.8.0'
    //compile 'com.android.volley:volley:1.0.0'
    compile 'com.google.android.exoplayer:exoplayer:r2.4.0'
    compile 'com.google.android.exoplayer:exoplayer-core:r2.4.0'
    compile 'com.google.android.exoplayer:exoplayer-dash:r2.4.0'
    compile 'com.google.android.exoplayer:exoplayer-hls:r2.4.0'
    compile 'com.google.android.exoplayer:exoplayer-smoothstreaming:r2.4.0'
    compile 'com.google.android.exoplayer:exoplayer-ui:r2.4.0'
    compile 'com.facebook.android:facebook-android-sdk:3.21.1'
    //noinspection DuplicatePlatformClasses
    implementation 'org.apache.httpcomponents:httpclient:4.5.3'
}

Body:
I could compile your gradle after this changes:

compile 'com.android.support:appcompat-v7:26.1.0'
compile 'com.android.support:design:26.1.0'
compile 'com.android.support:support-core-utils:26.1.0'

instead of

compile 'com.android.support:appcompat-v7:23.1.0'
compile 'com.android.support:design:23.1.1'

and also

android {
    compileSdkVersion 26

instead of

android {
    compileSdkVersion 23


问:
How to resolve this "required a bean" error
I am new to Springboot and I learning by Sping's tutorials and guides on "https://spring.io/guides".

Right now I try to understand and redo the tutorial: "Accessing data with MySQL"

Unfortunatelly I got the Error during Mavenbuild:

Error starting ApplicationContext. To display the auto-configuration report re-run your application with 'debug' enabled.
  2017-12-07 10:26:42.708 ERROR 8100 --- [           main] o.s.b.d.LoggingFailureAnalysisReporter   :

APPLICATION FAILED TO START

Description:

Field goodRepository in xxx.controller.GoodController required a bean of type 'xxx.repositories.GoodRepository' that could not be found.

Action:

Consider defining a bean of type 'xxx.repositories.GoodRepository' in your configuration.

Process finished with exit code 1

Here is my Code:

Good.java:

```<code>import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

import lombok.Data;

@Entity
@Data
public class Good {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private Integer id;

    private String name;

    public Good() {
    }

    public void setName(String name) {
        this.name = name;
    }
}
</code>```

GoodRepository:

```<code>import org.springframework.data.repository.CrudRepository;

import xxx.model.Good;

public interface GoodRepository extends CrudRepository<Good, Long>
{

}
</code>```

GoodController:

```<code>import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import xxx.model.Good;
import xxx.repositories.GoodRepository;

@Controller
@RequestMapping(path="/goods")
public class GoodController {

    @Autowired
    private GoodRepository goodRepository;

    @GetMapping(path="/add")
    public @ResponseBody String addNewGod( @RequestParam String name)
    {
        Good god= new Good();
        god.setName(name);
        goodRepository.save(god);
        return "Saved";
    }

    @GetMapping(path="/all")
    public @ResponseBody Iterable<Good> getAllGods()
    {
        return goodRepository.findAll();
    }

}
</code>```

My application.properties:

```<code>spring.jpa.hibernate.ddl-auto=update
spring.datasource.url=jdbc:mysql://localhost:3306/gccontest
spring.datasource.username=xxx
spring.datasource.password=xxx
</code>```

the mysql-db exists on this port...

What did I where wrong?

答:
I HAVE FOUND IT!!! ;-)

I have had to edit my Application.java:

```<code>package xxx;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;

@SpringBootApplication
@EnableAutoConfiguration(exclude = { DataSourceAutoConfiguration.class,WebMvcAutoConfiguration.class })
@ComponentScan({ "xxx.repositories"})
public class Application
{
    public static void main(String[] args)
    {
        SpringApplication.run(Application.class, args);
    }
}
</code>```

I did not checked my functionality yet, but it compiles and is runnig! Thank you very much for your tips!!!

Body:
I am new to Springboot and I learning by Sping's tutorials and guides on "https://spring.io/guides".

Right now I try to understand and redo the tutorial: "Accessing data with MySQL"

Unfortunatelly I got the Error during Mavenbuild:

Error starting ApplicationContext. To display the auto-configuration report re-run your application with 'debug' enabled.
  2017-12-07 10:26:42.708 ERROR 8100 --- [           main] o.s.b.d.LoggingFailureAnalysisReporter   :

APPLICATION FAILED TO START

Description:

Field goodRepository in xxx.controller.GoodController required a bean of type 'xxx.repositories.GoodRepository' that could not be found.

Action:

Consider defining a bean of type 'xxx.repositories.GoodRepository' in your configuration.

Process finished with exit code 1

Here is my Code:

Good.java:

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

import lombok.Data;

@Entity
@Data
public class Good {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private Integer id;

    private String name;

    public Good() {
    }

    public void setName(String name) {
        this.name = name;
    }
}

GoodRepository:

import org.springframework.data.repository.CrudRepository;

import xxx.model.Good;

public interface GoodRepository extends CrudRepository<Good, Long>
{

}

GoodController:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import xxx.model.Good;
import xxx.repositories.GoodRepository;

@Controller
@RequestMapping(path="/goods")
public class GoodController {

    @Autowired
    private GoodRepository goodRepository;

    @GetMapping(path="/add")
    public @ResponseBody String addNewGod( @RequestParam String name)
    {
        Good god= new Good();
        god.setName(name);
        goodRepository.save(god);
        return "Saved";
    }

    @GetMapping(path="/all")
    public @ResponseBody Iterable<Good> getAllGods()
    {
        return goodRepository.findAll();
    }

}

My application.properties:

spring.jpa.hibernate.ddl-auto=update
spring.datasource.url=jdbc:mysql://localhost:3306/gccontest
spring.datasource.username=xxx
spring.datasource.password=xxx

the mysql-db exists on this port...

What did I where wrong?

Body:
I HAVE FOUND IT!!! ;-)

I have had to edit my Application.java:

package xxx;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;

@SpringBootApplication
@EnableAutoConfiguration(exclude = { DataSourceAutoConfiguration.class,WebMvcAutoConfiguration.class })
@ComponentScan({ "xxx.repositories"})
public class Application
{
    public static void main(String[] args)
    {
        SpringApplication.run(Application.class, args);
    }
}

I did not checked my functionality yet, but it compiles and is runnig! Thank you very much for your tips!!!


问:
Python3 + selenium + PhantomJS UnicodeDecodeError

ENV

PhantomJS2.1.1;Windows10;selenium-3.8.0;python3

CODE

```<code>browser = webdriver.PhantomJS() //throw a UnicodeDecodeError
</code>```

Problem

UnicodeDecodeError: 'utf-8' codec can't decode byte 0xbd in position
  2: invalid start byte

Details

Traceback (most recent call last):
        File "d:/devtools/phantomjs-2.1.1-windows/bin/IndustryLeaderSpider.py",
  line 20, in
          browser = webdriver.PhantomJS('D:/phantomjs.exe')
        File "D:\Continuum\Anaconda3\lib\site-packages\selenium\webdriver\phantomjs\webdriver.py",
  line 58, in init
          desired_capabilities=desired_capabilities)
        File "D:\Continuum\Anaconda3\lib\site-packages\selenium\webdriver\remote\webdriver.py",
  line 154, in init
          self.start_session(desired_capabilities, browser_profile)
        File "D:\Continuum\Anaconda3\lib\site-packages\selenium\webdriver\remote\webdriver.py",
  line 243, in start_session
          response = self.execute(Command.NEW_SESSION, parameters)
        File "D:\Continuum\Anaconda3\lib\site-packages\selenium\webdriver\remote\webdriver.py",
  line 309, in execute
          response = self.command_executor.execute(driver_command, params)
        File "D:\Continuum\Anaconda3\lib\site-packages\selenium\webdriver\remote\remote_connection.py",
  line 460, in execute
          return self._request(command_info[0], url, body=data)
        File "D:\Continuum\Anaconda3\lib\site-packages\selenium\webdriver\remote\remote_connection.py",
  line 522, in _request
          resp = opener.open(request, timeout=self._timeout)
        File "D:\Continuum\Anaconda3\lib\urllib\request.py", line 526, in open
          response = self._open(req, data)
        File "D:\Continuum\Anaconda3\lib\urllib\request.py", line 544, in _open
          '_open', req)
        File "D:\Continuum\Anaconda3\lib\urllib\request.py", line 504, in _call_chain
          result = func(*args)
        File "D:\Continuum\Anaconda3\lib\urllib\request.py", line 806, in
          meth(r, proxy, type))
        File "D:\Continuum\Anaconda3\lib\urllib\request.py", line 814, in proxy_open
          if req.host and proxy_bypass(req.host):
        File "D:\Continuum\Anaconda3\lib\urllib\request.py", line 2739, in proxy_bypass
          return proxy_bypass_registry(host)
        File "D:\Continuum\Anaconda3\lib\urllib\request.py", line 2706, in proxy_bypass_registry
          fqdn = socket.getfqdn(rawHost)
        File "D:\Continuum\Anaconda3\lib\socket.py", line 673, in getfqdn
          hostname, aliases, ipaddrs = gethostbyaddr(name)
      UnicodeDecodeError: 'utf-8' codec can't decode byte 0xbd in position 2: invalid start byte

Do someone have this problem? How to fix it?

答:
Your main error seems to be :

```<code>File "D:\Continuum\Anaconda3\lib\site-packages\selenium\webdriver\remote\remote_connection.py", line 460, in execute return self._request(command_info[0], url, body=data) File "D:\Continuum\Anaconda3\lib\site-packages\selenium\webdriver\remote\remote_connection.py", line 522, in _request resp = opener.open(request, timeout=self._timeout) File "D:\Continuum\Anaconda3\lib\urllib\request.py", line 526, in open response = self._open(req, data)
</code>```

Try the following steps :

Run CCleaner tool to wipe off all the OS chores.

Take a System Reboot.

While you initiate PhantomJS() provide the absolute path of the phantomjs binary as follows :

```<code>driver = webdriver.PhantomJS(executable_path=r'C:\path\to\phantomjs.exe')
</code>```

Ensure that there is no unnecessary imports in your script. Example : urllib.request

Execute your Test.

Body:
ENV

PhantomJS2.1.1;Windows10;selenium-3.8.0;python3

CODE

browser = webdriver.PhantomJS() //throw a UnicodeDecodeError

Problem

UnicodeDecodeError: 'utf-8' codec can't decode byte 0xbd in position
  2: invalid start byte

Details

Traceback (most recent call last):
        File "d:/devtools/phantomjs-2.1.1-windows/bin/IndustryLeaderSpider.py",
  line 20, in
          browser = webdriver.PhantomJS('D:/phantomjs.exe')
        File "D:\Continuum\Anaconda3\lib\site-packages\selenium\webdriver\phantomjs\webdriver.py",
  line 58, in init
          desired_capabilities=desired_capabilities)
        File "D:\Continuum\Anaconda3\lib\site-packages\selenium\webdriver\remote\webdriver.py",
  line 154, in init
          self.start_session(desired_capabilities, browser_profile)
        File "D:\Continuum\Anaconda3\lib\site-packages\selenium\webdriver\remote\webdriver.py",
  line 243, in start_session
          response = self.execute(Command.NEW_SESSION, parameters)
        File "D:\Continuum\Anaconda3\lib\site-packages\selenium\webdriver\remote\webdriver.py",
  line 309, in execute
          response = self.command_executor.execute(driver_command, params)
        File "D:\Continuum\Anaconda3\lib\site-packages\selenium\webdriver\remote\remote_connection.py",
  line 460, in execute
          return self._request(command_info[0], url, body=data)
        File "D:\Continuum\Anaconda3\lib\site-packages\selenium\webdriver\remote\remote_connection.py",
  line 522, in _request
          resp = opener.open(request, timeout=self._timeout)
        File "D:\Continuum\Anaconda3\lib\urllib\request.py", line 526, in open
          response = self._open(req, data)
        File "D:\Continuum\Anaconda3\lib\urllib\request.py", line 544, in _open
          '_open', req)
        File "D:\Continuum\Anaconda3\lib\urllib\request.py", line 504, in _call_chain
          result = func(*args)
        File "D:\Continuum\Anaconda3\lib\urllib\request.py", line 806, in
          meth(r, proxy, type))
        File "D:\Continuum\Anaconda3\lib\urllib\request.py", line 814, in proxy_open
          if req.host and proxy_bypass(req.host):
        File "D:\Continuum\Anaconda3\lib\urllib\request.py", line 2739, in proxy_bypass
          return proxy_bypass_registry(host)
        File "D:\Continuum\Anaconda3\lib\urllib\request.py", line 2706, in proxy_bypass_registry
          fqdn = socket.getfqdn(rawHost)
        File "D:\Continuum\Anaconda3\lib\socket.py", line 673, in getfqdn
          hostname, aliases, ipaddrs = gethostbyaddr(name)
      UnicodeDecodeError: 'utf-8' codec can't decode byte 0xbd in position 2: invalid start byte

Do someone have this problem? How to fix it?

Body:
Your main error seems to be :

File "D:\Continuum\Anaconda3\lib\site-packages\selenium\webdriver\remote\remote_connection.py", line 460, in execute return self._request(command_info[0], url, body=data) File "D:\Continuum\Anaconda3\lib\site-packages\selenium\webdriver\remote\remote_connection.py", line 522, in _request resp = opener.open(request, timeout=self._timeout) File "D:\Continuum\Anaconda3\lib\urllib\request.py", line 526, in open response = self._open(req, data)

Try the following steps :

Run CCleaner tool to wipe off all the OS chores.

Take a System Reboot.

While you initiate PhantomJS() provide the absolute path of the phantomjs binary as follows :

driver = webdriver.PhantomJS(executable_path=r'C:\path\to\phantomjs.exe')

Ensure that there is no unnecessary imports in your script. Example : urllib.request

Execute your Test.


问:
How to add a constraint to my optimization?
I am working on formulating an optimization problem where I have a 2-D matrix A.

```<code>           A= [0 f1 0 f2]
              [f3 f3 0 0]
              .........
</code>```

And I have another 2-D matrix B that I should fill. B has the same size of A. I need b_ij (element of B) to be zero if a_ij=0 (element of A) and I need b_ij to be greater than zero and less than or equal to a_ij if a_ij is not zero.

How can I represent this in my formulation? I have added this constraint/condition:

```<code>            b_ij<=a_ij
</code>```

But this does not satisfy the condition that states that b_ij is not equal zero when a_ij is not equal zero. Any help?

答:
You want to implement the implication

```<code>a = 0 => b = 0
a <> 0 =>  0 < b <= a
</code>```

If a is (constant) data this is trivial. If a is a variable then things are not so easy.

You implemented part of the implications as

```<code>b <= a
</code>```

This implies a is non-negative: a>=0. It also implies b is non-negative. The remaining implication a>0 => b>0 can now be implemented as

```<code>a <= δ * 1000
b >= δ / 1000
δ in {0,1}
</code>```

Many MIP solvers support indicator constraints. That would allow you to say:

```<code>δ = 0 -> a = 0
δ = 1 -> b >= 0.001
δ in {0,1}
</code>```

Body:
I am working on formulating an optimization problem where I have a 2-D matrix A.

           A= [0 f1 0 f2]
              [f3 f3 0 0]
              .........

And I have another 2-D matrix B that I should fill. B has the same size of A. I need b_ij (element of B) to be zero if a_ij=0 (element of A) and I need b_ij to be greater than zero and less than or equal to a_ij if a_ij is not zero.

How can I represent this in my formulation? I have added this constraint/condition:

            b_ij<=a_ij

But this does not satisfy the condition that states that b_ij is not equal zero when a_ij is not equal zero. Any help?

Body:
You want to implement the implication

a = 0 => b = 0
a <> 0 =>  0 < b <= a

If a is (constant) data this is trivial. If a is a variable then things are not so easy.

You implemented part of the implications as

b <= a

This implies a is non-negative: a>=0. It also implies b is non-negative. The remaining implication a>0 => b>0 can now be implemented as

a <= δ * 1000
b >= δ / 1000
δ in {0,1}

Many MIP solvers support indicator constraints. That would allow you to say:

δ = 0 -> a = 0
δ = 1 -> b >= 0.001
δ in {0,1}


问:
MongoDB get records for specific day
so I am trying to get all records that are 3 days old, but I keep on getting empty results...

```<code> public function getUnansweredDiscussionsForPeriod() {

        $where = [

            'related.theme_id' => 3455537,

            'date_added' => [
                '$gte' => new MongoDate(strtotime('-3 days')),
                '$lt' => new MongoDate(strtotime('-4 days'))
            ],

            'subscribers.1' => [
                '$exists' => false
            ],

            'satisfaction_checked' => [
                '$exists' => false
            ]
        ];
        return $this->get_all($where, ['uri','user_id']);

    }
</code>```

Basically I am saving the date as ISO date.

Also just to note 1 thing, I tried removing everything else from the function to see if for example something else was the problem but nothing happened, the results were exactly the same. ALTHO when I removed the date and left everything as it is, it worked fine

This is how I save the date inside the mongo itself

```<code>"date_added" : ISODate("2017-12-04T12:40:31Z")
</code>```

答:
You have mixed up the fields:

```<code>'date_added' => [
   '$gte' => new MongoDate(strtotime('-4 days')),
   '$lt' => new MongoDate(strtotime('-3 days'))
],
</code>```

What you wrote is basically that you're looking for a document where date_added is newer than 3 days ago, but also older than 4 days ago

Title: MongoDB get records for specific day

Body:
so I am trying to get all records that are 3 days old, but I keep on getting empty results...

 public function getUnansweredDiscussionsForPeriod() {

        $where = [

            'related.theme_id' => 3455537,

            'date_added' => [
                '$gte' => new MongoDate(strtotime('-3 days')),
                '$lt' => new MongoDate(strtotime('-4 days'))
            ],

            'subscribers.1' => [
                '$exists' => false
            ],

            'satisfaction_checked' => [
                '$exists' => false
            ]
        ];
        return $this->get_all($where, ['uri','user_id']);

    }

Basically I am saving the date as ISO date.

Also just to note 1 thing, I tried removing everything else from the function to see if for example something else was the problem but nothing happened, the results were exactly the same. ALTHO when I removed the date and left everything as it is, it worked fine

This is how I save the date inside the mongo itself

"date_added" : ISODate("2017-12-04T12:40:31Z")

Body:
You have mixed up the fields:

'date_added' => [
   '$gte' => new MongoDate(strtotime('-4 days')),
   '$lt' => new MongoDate(strtotime('-3 days'))
],

What you wrote is basically that you're looking for a document where date_added is newer than 3 days ago, but also older than 4 days ago


问:
Basic exercise on "expect" - beginner
I am a beginner learning the tool "expect", I am trying out several exercises at this stage.

Below is a simple exercise illustrating the use of two consecutive "spawn" commands -- to change the password of unix system and then restore the old. Basically, automating what one does manually:

```<code>$passwd
Changing password for <username>.
(current) UNIX password:
Enter new UNIX password:
Retype new UNIX password:
passwd: password updated successfully
</code>```

The problem is that "expect" mysteriously stops at the entry of the second spawn waiting for the prompt.. keeping me in an endless mystery.

```<code>#!/usr/bin/expect -f

#PREAMBLE
set timeout -1
set force_conservative 1
set send_slow {1 .1}
if {$force_conservative} {
    set send_slow {1 .1}
    proc send {ignore arg} {
        sleep .1
        exp_send -s -- $arg
    }
}

#ACTUAL CODE
spawn passwd

expect "(current)"
send -- "PW-OLD\r"

expect "Enter"
send -- "PW-NEW\r"

expect "Retype"
send -- "PW-NEW\r"

sleep 1

spawn passwd

expect "(current)"
send -- "PW-NEW"

expect "Enter"
send -- "PW-OLD\r"

expect "Retype"
send -- "PW-OLD\r"
interact
</code>```

I would also love to hear any bad practices that you notice, and any good practices that you may want to tell.

Below is the output of expect -d (replacing expect -f in the first shebang line), after the suggestion of user @pynexj. This looks like the actual coder's debug utility, that I was not aware of.

```<code>$./exercise1.sh
expect version 5.45
argv[0] = /usr/bin/expect  argv[1] = -d  argv[2] = ./exercise1.sh
set argc 0
set argv0 "./exercise1.sh"
set argv ""
executing commands from command file ./exercise1.sh
spawn passwd
parent: waiting for sync byte
parent: telling child to go ahead
parent: now unsynchronized from child
spawn: returns {7848}

expect: does "" (spawn_id exp4) match glob pattern "(current)"? no
Changing password for <username>.
(current) UNIX password:
expect: does "Changing password for <username>.\r\n(current) UNIX password: " (spawn_id exp4) match glob pattern "(current)"? yes
expect: set expect_out(0,string) "(current)"
expect: set expect_out(spawn_id) "exp4"
expect: set expect_out(buffer) "Changing password for <username>.\r\n(current)"
send: sending "PW-OLD\r" to { exp4 }

expect: does " UNIX password: " (spawn_id exp4) match glob pattern "Enter"? no

expect: does " UNIX password: \r\n" (spawn_id exp4) match glob pattern "Enter"? no
Enter new UNIX password:
expect: does " UNIX password: \r\nEnter new UNIX password: " (spawn_id exp4) match glob pattern "Enter"? yes
expect: set expect_out(0,string) "Enter"
expect: set expect_out(spawn_id) "exp4"
expect: set expect_out(buffer) " UNIX password: \r\nEnter"
send: sending "PW-NEW\r" to { exp4 }

expect: does " new UNIX password: " (spawn_id exp4) match glob pattern "Retype"? no

expect: does " new UNIX password: \r\n" (spawn_id exp4) match glob pattern "Retype"? no
Retype new UNIX password:
expect: does " new UNIX password: \r\nRetype new UNIX password: " (spawn_id exp4) match glob pattern "Retype"? yes
expect: set expect_out(0,string) "Retype"
expect: set expect_out(spawn_id) "exp4"
expect: set expect_out(buffer) " new UNIX password: \r\nRetype"
send: sending "PW-NEW\r" to { exp4 }
spawn passwd
parent: waiting for sync byte
parent: telling child to go ahead
parent: now unsynchronized from child
spawn: returns {7861}

expect: does "" (spawn_id exp7) match glob pattern "(current)"? no
Changing password for <username>.
(current) UNIX password:
expect: does "Changing password for <username>.\r\n(current) UNIX password: " (spawn_id exp7) match glob pattern "(current)"? yes
expect: set expect_out(0,string) "(current)"
expect: set expect_out(spawn_id) "exp7"
expect: set expect_out(buffer) "Changing password for <username>.\r\n(current)"
send: sending "PW-NEW" to { exp7 }

expect: does " UNIX password: " (spawn_id exp7) match glob pattern "Enter"? no
^Csighandler: handling signal(2)
async event handler: Tcl_Eval(exit 130)
</code>```

答:
I would use a regex pattern that applies to all the password prompts:

```<code>expect -re "password: $"
</code>```

Change both sleep 1 and interact to expect eof

# create new password
spawn passwd
expect -re "password: $"; send -- "PW-OLD\r"
expect -re "password: $"; send -- "PW-NEW\r"
expect -re "password: $"; send -- "PW-NEW\r"
expect eof

# restore old password
spawn passwd
expect -re "password: $"; send -- "PW-NEW\r"
expect -re "password: $"; send -- "PW-OLD\r"
expect -re "password: $"; send -- "PW-OLD\r"
expect eof
```

<hr>

<p>With glob patterns, if you don't specify any wildcards, you're basically doing string equality checking. You could do:</p>

```expect "*(current) UNIX password: "
expect "*Enter new UNIX password: "
expect "*Retype new UNIX password: "
```

Note the trailing spaces, which are present in the passwd prompts.

Title: Basic exercise on "expect" - beginner

Body:
I am a beginner learning the tool "expect", I am trying out several exercises at this stage.

Below is a simple exercise illustrating the use of two consecutive "spawn" commands -- to change the password of unix system and then restore the old. Basically, automating what one does manually:

$passwd
Changing password for <username>.
(current) UNIX password:
Enter new UNIX password:
Retype new UNIX password:
passwd: password updated successfully

The problem is that "expect" mysteriously stops at the entry of the second spawn waiting for the prompt.. keeping me in an endless mystery.

#!/usr/bin/expect -f

#PREAMBLE
set timeout -1
set force_conservative 1
set send_slow {1 .1}
if {$force_conservative} {
    set send_slow {1 .1}
    proc send {ignore arg} {
        sleep .1
        exp_send -s -- $arg
    }
}

#ACTUAL CODE
spawn passwd

expect "(current)"
send -- "PW-OLD\r"

expect "Enter"
send -- "PW-NEW\r"

expect "Retype"
send -- "PW-NEW\r"

sleep 1

spawn passwd

expect "(current)"
send -- "PW-NEW"

expect "Enter"
send -- "PW-OLD\r"

expect "Retype"
send -- "PW-OLD\r"
interact

I would also love to hear any bad practices that you notice, and any good practices that you may want to tell.

Below is the output of expect -d (replacing expect -f in the first shebang line), after the suggestion of user @pynexj. This looks like the actual coder's debug utility, that I was not aware of.

$./exercise1.sh
expect version 5.45
argv[0] = /usr/bin/expect  argv[1] = -d  argv[2] = ./exercise1.sh
set argc 0
set argv0 "./exercise1.sh"
set argv ""
executing commands from command file ./exercise1.sh
spawn passwd
parent: waiting for sync byte
parent: telling child to go ahead
parent: now unsynchronized from child
spawn: returns {7848}

expect: does "" (spawn_id exp4) match glob pattern "(current)"? no
Changing password for <username>.
(current) UNIX password:
expect: does "Changing password for <username>.\r\n(current) UNIX password: " (spawn_id exp4) match glob pattern "(current)"? yes
expect: set expect_out(0,string) "(current)"
expect: set expect_out(spawn_id) "exp4"
expect: set expect_out(buffer) "Changing password for <username>.\r\n(current)"
send: sending "PW-OLD\r" to { exp4 }

expect: does " UNIX password: " (spawn_id exp4) match glob pattern "Enter"? no

expect: does " UNIX password: \r\n" (spawn_id exp4) match glob pattern "Enter"? no
Enter new UNIX password:
expect: does " UNIX password: \r\nEnter new UNIX password: " (spawn_id exp4) match glob pattern "Enter"? yes
expect: set expect_out(0,string) "Enter"
expect: set expect_out(spawn_id) "exp4"
expect: set expect_out(buffer) " UNIX password: \r\nEnter"
send: sending "PW-NEW\r" to { exp4 }

expect: does " new UNIX password: " (spawn_id exp4) match glob pattern "Retype"? no

expect: does " new UNIX password: \r\n" (spawn_id exp4) match glob pattern "Retype"? no
Retype new UNIX password:
expect: does " new UNIX password: \r\nRetype new UNIX password: " (spawn_id exp4) match glob pattern "Retype"? yes
expect: set expect_out(0,string) "Retype"
expect: set expect_out(spawn_id) "exp4"
expect: set expect_out(buffer) " new UNIX password: \r\nRetype"
send: sending "PW-NEW\r" to { exp4 }
spawn passwd
parent: waiting for sync byte
parent: telling child to go ahead
parent: now unsynchronized from child
spawn: returns {7861}

expect: does "" (spawn_id exp7) match glob pattern "(current)"? no
Changing password for <username>.
(current) UNIX password:
expect: does "Changing password for <username>.\r\n(current) UNIX password: " (spawn_id exp7) match glob pattern "(current)"? yes
expect: set expect_out(0,string) "(current)"
expect: set expect_out(spawn_id) "exp7"
expect: set expect_out(buffer) "Changing password for <username>.\r\n(current)"
send: sending "PW-NEW" to { exp7 }

expect: does " UNIX password: " (spawn_id exp7) match glob pattern "Enter"? no
^Csighandler: handling signal(2)
async event handler: Tcl_Eval(exit 130)

Body:
I would use a regex pattern that applies to all the password prompts:

expect -re "password: $"

Change both sleep 1 and interact to expect eof

# create new password
spawn passwd
expect -re "password: $"; send -- "PW-OLD\r"
expect -re "password: $"; send -- "PW-NEW\r"
expect -re "password: $"; send -- "PW-NEW\r"
expect eof

# restore old password
spawn passwd
expect -re "password: $"; send -- "PW-NEW\r"
expect -re "password: $"; send -- "PW-OLD\r"
expect -re "password: $"; send -- "PW-OLD\r"
expect eof

With glob patterns, if you don't specify any wildcards, you're basically doing string equality checking. You could do:

expect "*(current) UNIX password: "
expect "*Enter new UNIX password: "
expect "*Retype new UNIX password: "

Note the trailing spaces, which are present in the passwd prompts.


问:
Copy to clipboard with jQuery/js in Chrome
I know this kind of question has been asked here for many times, including:  How do I copy to the clipboard in JavaScript? or How to copy text to the client's clipboard using jQuery?, I'm narrowing the scope:

Condition:

works fine in Google Chrome (would be nice if cross-browser, but not necessary)

with no flash

Is there such a solution or workaround?

答:
If you're using knockout, like me (for some reason I still am), you'll want to take a look at this question/answer:

How to make KnokoutJS and ClipboardJS work together?


问:
How to get data passed from PUT method
I am creating an API for Laravel. I use the PUT method for updating data.

I send data with Postman using the PUT method. In my controller, I got an empty array. How to access the passed data?

In my route, I have:

```<code>Route::put('vehicletypes/{id}','API\VehicletypeController@update');
</code>```

In my controller:

```<code>public function update(Request $request, $id){

print_r($request->all()); exit;

}
</code>```

How to get the data passed in PUT method?

答:
```<code>public function putUpdate(Request $request, $id){

print_r($request->all()); exit;

}
</code>```

<p>And change route too, </p>

```<code>Route::put('vehicletypes/{id}','API\VehicletypeController@putUpdate');
</code>```

Title: How to get data passed from PUT method

Body:
I am creating an API for Laravel. I use the PUT method for updating data.

I send data with Postman using the PUT method. In my controller, I got an empty array. How to access the passed data?

In my route, I have:

Route::put('vehicletypes/{id}','API\VehicletypeController@update');

In my controller:

public function update(Request $request, $id){

print_r($request->all()); exit;

}

How to get the data passed in PUT method?

Body:
public function putUpdate(Request $request, $id){

print_r($request->all()); exit;

}

And change route too,

Route::put('vehicletypes/{id}','API\VehicletypeController@putUpdate');