问:
Unable to download Library using cocoaPods
I am new in swift programming . I  am trying to download libraries for the project . I have installed  cocoa pods : sudo gem install cocoa pods, created pod file with all libraries which I need : pod 'GoogleMaps'.  After pod install I got an error:

```<code> Unable to satisfy the following requirements:

 - `GoogleMaps` required by `Podfile`
 - `GoogleMaps` required by `Podfile`
 - `GoogleMaps (= 2.3.1)` required by `Podfile.lock`

 Specs satisfying the `GoogleMaps, GoogleMaps (= 2.3.1)` dependency
 were found, but they required a higher minimum deployment target.

 [!] Automatically assigning platform ios with version 7.0 on target
  Taxi for rider because no platform was specified. Please specify a
 platform    for this target in your Podfile. See
 `https://guides.cocoapods.org/syntax/podfile.html#platform`.
</code>```

My pod file:

```<code>  # Uncomment the next line to define a global platform for your
  project
  # platform :ios, '9.0'

  target 'Taxi for rider' do
  # Comment the next line if you're not using Swift and don't want to
  use dynamic frameworks
  use_frameworks!

  # Pods for Taxi for rider
  pod 'Firebase'
  pod 'Firebase/Storage'
  pod 'Firebase/Auth'
  pod 'Firebase/Database'
  pod 'GoogleMaps'
  pod 'GoogleMaps'
  pod 'GooglePlaces'
  pod 'GooglePlacesAPI'
  pod 'GooglePlacePicker'
  pod 'SwiftyJSON'
  pod 'Firebase/Core'
  pod 'Firebase/Storage'

  end
</code>```

答:
Replace your podfile text with below text:

```<code># Uncomment the next line to define a global platform for your project
# platform :ios, '9.0'

target 'Taxi for rider' do
  # Comment the next line if you're not using Swift and don't want to use dynamic frameworks
  use_frameworks!

 # Pods for Taxi for rider

  pod 'Firebase'
  pod 'Firebase/Storage'
  pod 'Firebase/Auth'
  pod 'Firebase/Database'
  pod 'GoogleMaps'
  pod 'GoogleMaps'
  pod 'GooglePlaces'
  pod 'GooglePlacesAPI'
  pod 'GooglePlacePicker'
  pod 'SwiftyJSON'
  pod 'Firebase/Core'
  pod 'Firebase/Storage'
end
</code>```

Below is wrong line in your code:

```<code># Uncomment the next line to define a global platform for your
project
</code>```

Which should be:

```<code># Uncomment the next line to define a global platform for your project
</code>```

And you have added pod 'GoogleMaps' multiple times.

Body:
I am new in swift programming . I  am trying to download libraries for the project . I have installed  cocoa pods : sudo gem install cocoa pods, created pod file with all libraries which I need : pod 'GoogleMaps'.  After pod install I got an error:

 Unable to satisfy the following requirements:

 - `GoogleMaps` required by `Podfile`
 - `GoogleMaps` required by `Podfile`
 - `GoogleMaps (= 2.3.1)` required by `Podfile.lock`

 Specs satisfying the `GoogleMaps, GoogleMaps (= 2.3.1)` dependency
 were found, but they required a higher minimum deployment target.

 [!] Automatically assigning platform ios with version 7.0 on target
  Taxi for rider because no platform was specified. Please specify a
 platform    for this target in your Podfile. See
 `https://guides.cocoapods.org/syntax/podfile.html#platform`.

My pod file:

  # Uncomment the next line to define a global platform for your
  project
  # platform :ios, '9.0'

  target 'Taxi for rider' do
  # Comment the next line if you're not using Swift and don't want to
  use dynamic frameworks
  use_frameworks!

  # Pods for Taxi for rider
  pod 'Firebase'
  pod 'Firebase/Storage'
  pod 'Firebase/Auth'
  pod 'Firebase/Database'
  pod 'GoogleMaps'
  pod 'GoogleMaps'
  pod 'GooglePlaces'
  pod 'GooglePlacesAPI'
  pod 'GooglePlacePicker'
  pod 'SwiftyJSON'
  pod 'Firebase/Core'
  pod 'Firebase/Storage'

  end

Body:
Replace your podfile text with below text:

# Uncomment the next line to define a global platform for your project
# platform :ios, '9.0'

target 'Taxi for rider' do
  # Comment the next line if you're not using Swift and don't want to use dynamic frameworks
  use_frameworks!

 # Pods for Taxi for rider

  pod 'Firebase'
  pod 'Firebase/Storage'
  pod 'Firebase/Auth'
  pod 'Firebase/Database'
  pod 'GoogleMaps'
  pod 'GoogleMaps'
  pod 'GooglePlaces'
  pod 'GooglePlacesAPI'
  pod 'GooglePlacePicker'
  pod 'SwiftyJSON'
  pod 'Firebase/Core'
  pod 'Firebase/Storage'
end

Below is wrong line in your code:

# Uncomment the next line to define a global platform for your
project

Which should be:

# Uncomment the next line to define a global platform for your project

And you have added pod 'GoogleMaps' multiple times.


来源: stackexchange

问:
c#: Invoking Methods
i am using the following function plot() to plot data on google maps.now when i am calling the same function from another button click event it is not getting executed rather going into else() statement.my plot function is as follows:

```<code> public void plot(double temp_lat, double temp_long, string temp_date, string temp_time, string temp_bty_value)
 {
        if (this.InvokeRequired)
        {
            // do something
        }
        else { this.Close(); }
 }
</code>```

i am calling this function from button click event as follows:

```<code>private void button6_Click_1(object sender, EventArgs e) /// refresh button
{
      this.Invoke((MethodInvoker)(() =>
                   {
                        plot(28.5231445, 77.40388525, "17/06/20", "17:00:50", "82");
                   }));
}
</code>```

when is the reason for this? i am new to invoking methods.please help
Edit:https://stackoverflow.com/a/43797637/6412780 The reason why i am using  invocation because i was plotting 5 markers simultaneously on gmap from different threads.so for synchronization i am using invocation method.BUT now i  want to update my data. i made a refresh button which contains new lat /long (passing manually here) to plot on the map.being on the same UI i called the plot() function directly ,but even then  i wasn't able to execute the if statement. that is what i am doing .

答:
In WinForms all1 UI operations – anything accessing any member of any control instance – need to be performed on the single thread executing UI operations.

Invoke can be used by a non-UI thread to cause the UI thread to execute code (with BeginInvoke this can be concurrently).

But an event handler for a control will always be running on the UI thread when triggered by the UI. So no need to switch threads. To run code on a different thread (eg. it would block the UI thread) there are various options, these days using async/await, to let the runtime work it out, is preferred.

In the question's code the event handler is already using Invoke which is pointless: it is already on the UI thread.

1 Simplifying here, the actual rules have subtleties for advanced use cases.

ContentLicense: CC BY-SA 3.0

Title: c#: Invoking Methods

Body:
i am using the following function plot() to plot data on google maps.now when i am calling the same function from another button click event it is not getting executed rather going into else() statement.my plot function is as follows:

 public void plot(double temp_lat, double temp_long, string temp_date, string temp_time, string temp_bty_value)
 {
        if (this.InvokeRequired)
        {
            // do something
        }
        else { this.Close(); }
 }

i am calling this function from button click event as follows:

private void button6_Click_1(object sender, EventArgs e) /// refresh button
{
      this.Invoke((MethodInvoker)(() =>
                   {
                        plot(28.5231445, 77.40388525, "17/06/20", "17:00:50", "82");
                   }));
}

when is the reason for this? i am new to invoking methods.please help
Edit:https://stackoverflow.com/a/43797637/6412780 The reason why i am using  invocation because i was plotting 5 markers simultaneously on gmap from different threads.so for synchronization i am using invocation method.BUT now i  want to update my data. i made a refresh button which contains new lat /long (passing manually here) to plot on the map.being on the same UI i called the plot() function directly ,but even then  i wasn't able to execute the if statement. that is what i am doing .


问:
nodejs elementtree npm etree.write() pretty printing
I have ran into a problem while using the etree npm for nodejs. I am extensively using the elementtree npm in my application so I cannot afford to change the npm. I am writing the XML using the below code.

```<code>var et = require('elementtree');
tailorData = fs.readFileSync(XML_FILE).toString();
etree = et.parse(tailorData);
// Do some changes in xml
var resultXml = etree.write(); // DOES NOT DO PRETTY PRINTING
fs.writeFileSync(tailoredXML, resultXml);
</code>```

etree.write() messed up the whole XML and my later processing is halted. It does not put endline after the tags. This is how the XML looks like now.

```<code><?xml version='1.0' encoding='utf-8'?><Tailoring id="1234"><status>incomplete</status><Profile id="CIS_LEVEL_1"><title>CIS_LEVEL_1 Security Profile</title><select idref="file_group_owner_grub2_cfg" selected="true" /><select idref="file_user_owner_grub2_cfg" selected="true" /><select idref="file_permissions_grub2_cfg" selected="true" /></Profile></Tailoring>
</code>```

Below is my expectation:

```<code><?xml version='1.0' encoding='utf-8'?>
<Tailoring id="1234">
<status>incomplete</status>
<Profile id="CIS_LEVEL_1">
<title>CIS_LEVEL_1 Security Profile</title>
<select idref="file_group_owner_grub2_cfg" selected="true" />
<select idref="file_user_owner_grub2_cfg" selected="true" />
<select idref="file_permissions_grub2_cfg" selected="true" />
</Profile>
</Tailoring>
</code>```

Is their any way I can acheive the above result in nodejs.

答:
Figured out the way to do it. Using the very light weight npm "pretty-data" for achieving this.</p>

```<code>var pd = require('pretty-data').pd;

var et = require('elementtree');
tailorData = fs.readFileSync(XML_FILE).toString();
etree = et.parse(tailorData);
// Do some changes in xml
var resultXml = etree.write();
resultXml = pd.xml(resultXml); // THIS WILL DO THE PRETTY PRINTING.
fs.writeFileSync(tailoredXML, resultXml);
</code>```

Body:
I have ran into a problem while using the etree npm for nodejs. I am extensively using the elementtree npm in my application so I cannot afford to change the npm. I am writing the XML using the below code.

var et = require('elementtree');
tailorData = fs.readFileSync(XML_FILE).toString();
etree = et.parse(tailorData);
// Do some changes in xml
var resultXml = etree.write(); // DOES NOT DO PRETTY PRINTING
fs.writeFileSync(tailoredXML, resultXml);

etree.write() messed up the whole XML and my later processing is halted. It does not put endline after the tags. This is how the XML looks like now.

<?xml version='1.0' encoding='utf-8'?><Tailoring id="1234"><status>incomplete</status><Profile id="CIS_LEVEL_1"><title>CIS_LEVEL_1 Security Profile</title><select idref="file_group_owner_grub2_cfg" selected="true" /><select idref="file_user_owner_grub2_cfg" selected="true" /><select idref="file_permissions_grub2_cfg" selected="true" /></Profile></Tailoring>

Below is my expectation:

<?xml version='1.0' encoding='utf-8'?>
<Tailoring id="1234">
<status>incomplete</status>
<Profile id="CIS_LEVEL_1">
<title>CIS_LEVEL_1 Security Profile</title>
<select idref="file_group_owner_grub2_cfg" selected="true" />
<select idref="file_user_owner_grub2_cfg" selected="true" />
<select idref="file_permissions_grub2_cfg" selected="true" />
</Profile>
</Tailoring>

Is their any way I can acheive the above result in nodejs.

Body:
Figured out the way to do it. Using the very light weight npm "pretty-data" for achieving this.

var pd = require('pretty-data').pd;

var et = require('elementtree');
tailorData = fs.readFileSync(XML_FILE).toString();
etree = et.parse(tailorData);
// Do some changes in xml
var resultXml = etree.write();
resultXml = pd.xml(resultXml); // THIS WILL DO THE PRETTY PRINTING.
fs.writeFileSync(tailoredXML, resultXml);


问:
Two-key encryption/decryption?
I'm looking to store some fairly sensitive data using PHP and MySQL and will be using some form of reversible encryption to do so since I need to get the data back out in plain text for it to be of any use.

I'll be deriving the encryption key from the users' username/password combination but I'm stumped for what to do in the (inevitable) event of a password being forgotten. I realise that the purpose of encryption is that it can only be undone using the correct key but this must have been addressed before..

I'm trying to get my head around whether or not public key cryptography would apply to the problem but all I can think of is that the private key will still need to be correct to decrypt the data..

Any ideas?

答:
The conventional solution is to have a "recovery agent": one user that holds a second password that can be used to decrypt all data. Strict usage policies would apply to using the recovery password, such as putting it physically into a safe.

Then, either encrypt all data twice: once with the user key and once with the recovery key; alternatively, generate a session key for every set of data, and encrypt the data only once, but the session key twice.

For that to work, at least the key of the recovery agent must be asymmetric, since the private part will live in the safe, and the public key in the software.

As yet another alternative using the same scheme: encrypt the user's passwords with the recovery key on password change. This is simpler to implement, but will allow to recover the passwords and not just the data, which may be undesirable.

ContentLicense: CC BY-SA 2.5

Title: Two-key encryption/decryption?


问:
Cascade remove relation without cascade remove target
I have a ManyToMany-relation between student and teacher in a Student_Teacher-table (Entityless).

```<code>Student:       Teacher(owning-side):   Student_Teacher
1= Tim         50= Mrs. Foo            1=   1   50
2= Ann         51= Mr. Bar             2=   1   51
                                       3=   2   50
                                       4=   2   51
</code>```

As you see above every Student is currently related to every Teacher.

Now I like to remove Ann and I like to use the database's cascading techique to remove entries from the Student_Teacher-table but I do neither like to remove other Students, nor Teacher, nor other relationship.

This is what I have in the Student-Entity:

```<code>@ManyToMany(mappedBy="students")
public Set<Teacher> getTeachers() {
    return teachers;
}
</code>```

This is what I have in the Teacher-Entity:

```<code>@ManyToMany
@JoinTable(name="Student_Teacher", joinColumns = {
    @JoinColumn(name="StudentID", referencedColumnName = "TeacherID", nullable = false)
}, inverseJoinColumns = {
    @JoinColumn(name="TeacherID", referencedColumnName = "StudentID", nullable = false)
})
public Set<Student> getStudents() {
    return students;
}
</code>```

Now I like to use the database's delete cascade functionality. I repeat: The database's delete cascade functionality targeting the Student_Teacher-table only!

The problem:

```<code>org.h2.jdbc.JdbcSQLException: Referentielle Integrität verletzt: "FK_43PMYXR2NU005M2VNEB99VX0X: PUBLIC.Student_Teacher FOREIGN KEY(StudentID) REFERENCES PUBLIC.Student(StudentID) (2)"
Referential integrity constraint violation: "FK_43PMYXR2NU005M2VNEB99VX0X: PUBLIC.Student_Teacher FOREIGN KEY(StudentID) REFERENCES PUBLIC.Student(StudentID) (2)"; SQL statement:
delete from "Student" where name='Ann'
    at org.h2.message.DbException.getJdbcSQLException(DbException.java:345)
    at org.h2.message.DbException.get(DbException.java:179)
    at org.h2.message.DbException.get(DbException.java:155)
    at org.h2.constraint.ConstraintReferential.checkRow(ConstraintReferential.java:425)
</code>```

What i can not use is the

```<code>@ManyToMany(cascade={CascadeType.REMOVE})
</code>```

Because of the documetation tells me:

(Optional) The operations that must be cascaded to the target of the association.

The "target" is the Teacher, so this cascade would remove the Teacher (what I do not like to remove).

Question:

How to configure the entitys to remove Ann and the relation only using the database's cascade functionality?

Proof of Concept:

I tried another feature, I have noticed the possibility to configure the foreign-key nativly like this:

```<code>@ManyToMany(cascade = { CascadeType.REMOVE })
@JoinTable(name="Student_Teacher", joinColumns = {
    @JoinColumn(name="StudentID", referencedColumnName = "TeacherID", nullable = false, foreignKey=@ForeignKey(foreignKeyDefinition="FOREIGN KEY (StudentID) REFERENCES Student ON DELETE NO ACTION"))
}, inverseJoinColumns = {
    @JoinColumn(name="TeacherID", referencedColumnName = "StudentID", nullable = false, foreignKey=@ForeignKey(foreignKeyDefinition="FOREIGN KEY (TeacherID) REFERENCES Teacher ON DELETE NO ACTION"))
})
public Set<Student> getStudents() {
    return students;
}
</code>```

The problem is: This works fine but to trigger the removal of the entries in Student_Teacher I have to specify @ManyToMany(cascade = { CascadeType.REMOVE }) on both sides. Hibernate do not parse the foreignKeyDefinition and only see the CascadeType.REMOVE and drops the target-entitys (and the referenced Student Tim) out of the cache, but they are still in the database!!! So I have to clear the hibernate-session immendentelly after drop to re-read the existence of the Teachers Mrs. Foo and Mr. Bar and the Student Tim.

答:
As you see above every Student is related to every Teacher.

The point is when in a situation where "every A is related to every B", then there is no need to have a many to many table to keep such relationship. Since logically A and B is independent to each other in this situation. Adding/Deleting/Modifying A makes no effect on B and vice versa. This behaviour is exactly what you are after, because you want the cascading operations stop at the relation table:

delete cascade functionality targeting the Student_Teacher-table only!

Relationship table is only useful when in situation where "every A is related to a subset of B".

So to solve your problem is actually a fairly one: Drop the Student_Teacher table.

Body:
I have a ManyToMany-relation between student and teacher in a Student_Teacher-table (Entityless).

Student:       Teacher(owning-side):   Student_Teacher
1= Tim         50= Mrs. Foo            1=   1   50
2= Ann         51= Mr. Bar             2=   1   51
                                       3=   2   50
                                       4=   2   51

As you see above every Student is currently related to every Teacher.

Now I like to remove Ann and I like to use the database's cascading techique to remove entries from the Student_Teacher-table but I do neither like to remove other Students, nor Teacher, nor other relationship.

This is what I have in the Student-Entity:

@ManyToMany(mappedBy="students")
public Set<Teacher> getTeachers() {
    return teachers;
}

This is what I have in the Teacher-Entity:

@ManyToMany
@JoinTable(name="Student_Teacher", joinColumns = {
    @JoinColumn(name="StudentID", referencedColumnName = "TeacherID", nullable = false)
}, inverseJoinColumns = {
    @JoinColumn(name="TeacherID", referencedColumnName = "StudentID", nullable = false)
})
public Set<Student> getStudents() {
    return students;
}

Now I like to use the database's delete cascade functionality. I repeat: The database's delete cascade functionality targeting the Student_Teacher-table only!

The problem:

org.h2.jdbc.JdbcSQLException: Referentielle Integrität verletzt: "FK_43PMYXR2NU005M2VNEB99VX0X: PUBLIC.Student_Teacher FOREIGN KEY(StudentID) REFERENCES PUBLIC.Student(StudentID) (2)"
Referential integrity constraint violation: "FK_43PMYXR2NU005M2VNEB99VX0X: PUBLIC.Student_Teacher FOREIGN KEY(StudentID) REFERENCES PUBLIC.Student(StudentID) (2)"; SQL statement:
delete from "Student" where name='Ann'
    at org.h2.message.DbException.getJdbcSQLException(DbException.java:345)
    at org.h2.message.DbException.get(DbException.java:179)
    at org.h2.message.DbException.get(DbException.java:155)
    at org.h2.constraint.ConstraintReferential.checkRow(ConstraintReferential.java:425)

What i can not use is the

@ManyToMany(cascade={CascadeType.REMOVE})

Because of the documetation tells me:

(Optional) The operations that must be cascaded to the target of the association.

The "target" is the Teacher, so this cascade would remove the Teacher (what I do not like to remove).

Question:

How to configure the entitys to remove Ann and the relation only using the database's cascade functionality?

Proof of Concept:

I tried another feature, I have noticed the possibility to configure the foreign-key nativly like this:

@ManyToMany(cascade = { CascadeType.REMOVE })
@JoinTable(name="Student_Teacher", joinColumns = {
    @JoinColumn(name="StudentID", referencedColumnName = "TeacherID", nullable = false, foreignKey=@ForeignKey(foreignKeyDefinition="FOREIGN KEY (StudentID) REFERENCES Student ON DELETE NO ACTION"))
}, inverseJoinColumns = {
    @JoinColumn(name="TeacherID", referencedColumnName = "StudentID", nullable = false, foreignKey=@ForeignKey(foreignKeyDefinition="FOREIGN KEY (TeacherID) REFERENCES Teacher ON DELETE NO ACTION"))
})
public Set<Student> getStudents() {
    return students;
}

The problem is: This works fine but to trigger the removal of the entries in Student_Teacher I have to specify @ManyToMany(cascade = { CascadeType.REMOVE }) on both sides. Hibernate do not parse the foreignKeyDefinition and only see the CascadeType.REMOVE and drops the target-entitys (and the referenced Student Tim) out of the cache, but they are still in the database!!! So I have to clear the hibernate-session immendentelly after drop to re-read the existence of the Teachers Mrs. Foo and Mr. Bar and the Student Tim.


问:
Construct Moya TargetType in iOS
I'm trying to use Moya with RxSwift in my project

I'm facing the problem with url contain "?"

This TargetType I have create

```<code>private extension String {
    var URLEscapedString: String {
        return self.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlHostAllowed)!
    }
}

enum TMDb {
    case discoverMovieList(page: Int)
    case discoverMovieDetail(moive: Movie)
}

extension TMDb: TargetType {
    var baseURL: URL { return URL(string: BASE_URL)! }

    var path: String {
        switch self {
        case .discoverMovieList(page: let page):
            return "discover/movie?api_key=\(API_KEY)&sort_by=release_date.desc&page=\(page)"
        }
    }
    var method: Moya.Method {
        return .get
    }
    var parameters: [String: Any]? {
        return nil
    }
    var sampleData: Data {
        switch self {
            case .discoverMovieList(page: _):
                return "test".data(using: .utf8)!
            case .discoverMovieDetail(moive: _):
                return "test1".data(using: .utf8)!
        }
    }
    var task: Task {
        return .request
    }
    var parameterEncoding: ParameterEncoding {
        return URLEncoding.default
    }

}
</code>```

The problem is when I make the request. The url path return is somehow not correct

This is the url i got from console

```<code>Optional("https://api.themoviedb.org/3/discover/movie%3Fapi_key=58da429caf2e25e8ff9436665e2f0e36&sort_by=release_date.desc&page=1")
</code>```

But the correct one should be

```<code>https://api.themoviedb.org/3/discover/movie?api_key=58da429caf2e25e8ff9436665e2f0e36&sort_by=release_date.desc&page=1
</code>```

There something wrong when handle the "?" (it become %3F" character in the url. How can we make it work normally?

Update

This is how I call my Moya

```<code>let provider: RxMoyaProvider<TMDb>
    let persistentContainer: PersistentContainer

    func discoverMoiveList(for page: Int) {
        self.provider.request(TMDb.discoverMovieList(page: 1)) { (result) in
            print(result.value?.request?.url?.absoluteString ?? "no url")

        }
    }
}
</code>```

答:
You should pass anything after the ? as parameter, this way Moya knows how to construct the URL correctly.</p>

```<code>  var path: String {
    switch self {
    case .discoverMovieList(page: let page):
        return "discover/movie"
    }
}
var method: Moya.Method {
    return .get
}
var parameters: [String: Any]? {
     switch self {
     case .discoverMovieList(page: let page):
       return "["api_key":"\(API_KEY)",
                "sort_by":"release_date.desc",
                "page":page]"
}
}
</code>```

ContentLicense: CC BY-SA 4.0

Title: Construct Moya TargetType in iOS

Body:
I'm trying to use Moya with RxSwift in my project

I'm facing the problem with url contain "?"

This TargetType I have create

private extension String {
    var URLEscapedString: String {
        return self.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlHostAllowed)!
    }
}

enum TMDb {
    case discoverMovieList(page: Int)
    case discoverMovieDetail(moive: Movie)
}

extension TMDb: TargetType {
    var baseURL: URL { return URL(string: BASE_URL)! }

    var path: String {
        switch self {
        case .discoverMovieList(page: let page):
            return "discover/movie?api_key=\(API_KEY)&sort_by=release_date.desc&page=\(page)"
        }
    }
    var method: Moya.Method {
        return .get
    }
    var parameters: [String: Any]? {
        return nil
    }
    var sampleData: Data {
        switch self {
            case .discoverMovieList(page: _):
                return "test".data(using: .utf8)!
            case .discoverMovieDetail(moive: _):
                return "test1".data(using: .utf8)!
        }
    }
    var task: Task {
        return .request
    }
    var parameterEncoding: ParameterEncoding {
        return URLEncoding.default
    }

}

The problem is when I make the request. The url path return is somehow not correct

This is the url i got from console

Optional("https://api.themoviedb.org/3/discover/movie%3Fapi_key=58da429caf2e25e8ff9436665e2f0e36&sort_by=release_date.desc&page=1")

But the correct one should be

https://api.themoviedb.org/3/discover/movie?api_key=58da429caf2e25e8ff9436665e2f0e36&sort_by=release_date.desc&page=1

There something wrong when handle the "?" (it become %3F" character in the url. How can we make it work normally?

Update

This is how I call my Moya

let provider: RxMoyaProvider<TMDb>
    let persistentContainer: PersistentContainer

    func discoverMoiveList(for page: Int) {
        self.provider.request(TMDb.discoverMovieList(page: 1)) { (result) in
            print(result.value?.request?.url?.absoluteString ?? "no url")

        }
    }
}

Body:
You should pass anything after the ? as parameter, this way Moya knows how to construct the URL correctly.

  var path: String {
    switch self {
    case .discoverMovieList(page: let page):
        return "discover/movie"
    }
}
var method: Moya.Method {
    return .get
}
var parameters: [String: Any]? {
     switch self {
     case .discoverMovieList(page: let page):
       return "["api_key":"\(API_KEY)",
                "sort_by":"release_date.desc",
                "page":page]"
}
}


问:
React-Native Button style not work

Import_this

import {AppRegistry, Text, View, Button, StyleSheet} from 'react-native';
```

<p>This my React Button code But style not working Hare ...</p>

<pre class="lang-jsx prettyprint-override"><code><Button
  onPress={this.onPress.bind(this)}
  title={"Go Back"}
  style={{color: 'red', marginTop: 10, padding: 10}}
/>
</code>```

Also I was try by this code

<Button
       containerStyle={{padding:10, height:45, overflow:'hidden',
       borderRadius:4, backgroundColor: 'white'}}
       style={{fontSize: 20, color: 'green'}}
       onPress={this.onPress.bind(this)} title={"Go Back"}
      > Press me!
</Button>
```

<h1>Update Question:</h1>

<p>Also I was try by This way..</p>

<pre class="lang-jsx prettyprint-override"><code><Button
    onPress={this.onPress.bind(this)}
    title={"Go Back"}
    style={styles.buttonStyle}
>ku ka</Button>
</code>```

Style

const styles = StyleSheet.create({
    buttonStyle: {
        color: 'red',
        marginTop: 20,
        padding: 20,
        backgroundColor: 'green'
    }
});
```

But No out put:
Screenshot  of my phone:-

答:
The React Native Button is very limited in what you can do, see; Button

It does not have a style prop, and you don't set text the "web-way" like <Button>txt</Button> but via the title property <Button title="txt" />

If you want to have more control over the appearance you should use one of the TouchableXXXX' components like TouchableOpacity
They are really easy to use :-)

Title: React-Native Button style not work

Body:
Import_this

import {AppRegistry, Text, View, Button, StyleSheet} from 'react-native';

This my React Button code But style not working Hare ...

<Button
  onPress={this.onPress.bind(this)}
  title={"Go Back"}
  style={{color: 'red', marginTop: 10, padding: 10}}
/>

Also I was try by this code

<Button
       containerStyle={{padding:10, height:45, overflow:'hidden',
       borderRadius:4, backgroundColor: 'white'}}
       style={{fontSize: 20, color: 'green'}}
       onPress={this.onPress.bind(this)} title={"Go Back"}
      > Press me!
</Button>

Update Question:

Also I was try by This way..

<Button
    onPress={this.onPress.bind(this)}
    title={"Go Back"}
    style={styles.buttonStyle}
>ku ka</Button>

Style

const styles = StyleSheet.create({
    buttonStyle: {
        color: 'red',
        marginTop: 20,
        padding: 20,
        backgroundColor: 'green'
    }
});

But No out put:
Screenshot  of my phone:-


问:
Element like a PageView in android
I'm creating an app for both Androids and iOS. In a view, I'm using a pageView as a subview (I mean it doesn't fill all the viewController) in the iOS app.

I need to implement the same thing in Android and I don't know what element I should use.

Here you have an example of a page view.

Thanks for the help.

答: The equivalent in Android is a ViewPager.</p>

Title: Element like a PageView in android


问:
AEM Form: Change access control of textfield
I'm using Adobe AEM Form, javascript for scripting.

In my form, I have a drop down which allow the user to pick one of the dropdown value item or to fill the textfield by typing. My script as follows:

```<code>Report.Page2.part2.body.subform.Dropdown::exit - (JavaScript, client)
if(this.selectedIndex == "0"){
    Textfield.access = "???????"
    Textfield.fillColor = "255,255,255"

}
else{
    Textfield.rawValue = this.rawValue;
    Textfield.access = "readOnly"
    Textfield.fillColor = "192,192,192"
}
</code>```

I am able to change the Textfield to read only, but not able to change it back to writtable. Can someone advice me how to? and other than "readOnly", what other access control can I assign to the textfield.

Thanks!

答:
```<code>Report.Page2.part2.body.subform.Dropdown::exit - (JavaScript, client)
if(this.selectedIndex == "0"){
    Textfield.access = ""
    Textfield.fillColor = "255,255,255"

}
else{
    Textfield.rawValue = this.rawValue;
    Textfield.access = "readOnly"
    Textfield.fillColor = "192,192,192"
}
</code>```

Body:
I'm using Adobe AEM Form, javascript for scripting.

In my form, I have a drop down which allow the user to pick one of the dropdown value item or to fill the textfield by typing. My script as follows:

Report.Page2.part2.body.subform.Dropdown::exit - (JavaScript, client)
if(this.selectedIndex == "0"){
    Textfield.access = "???????"
    Textfield.fillColor = "255,255,255"

}
else{
    Textfield.rawValue = this.rawValue;
    Textfield.access = "readOnly"
    Textfield.fillColor = "192,192,192"
}

I am able to change the Textfield to read only, but not able to change it back to writtable. Can someone advice me how to? and other than "readOnly", what other access control can I assign to the textfield.

Thanks!


问:
Write a query that gives mutual friend names of user DDD and FFF. Also, note that if A is friend of B then B is also friend A
Create 2 tables that contains list of friends and users.

This is my query:

```<code>SELECT
  U.username "Mutual Friend"
FROM users U
LEFT OUTER JOIN friends F
  ON U.userid = F.friendid
WHERE f.userid = 6
AND f.friendid IN (SELECT
  friendid
FROM friends
WHERE userid = 4);
</code>```

friends: userid, friendid

```<code>1, 2
1, 3
1, 4
2, 4
2, 5
2, 7
3, 4
3, 6
4, 7
4, 8
4, 9
5, 6
5, 9
6, 7
7, 8
8, 9
</code>```

users: userid, username

```<code>1, AAA
2, BBB
3, CCC
4, DDD
5, EEE
6, FFF
7, GGG
8, HHH
9, III
</code>```

Desired Result:

```<code>Mutual Friends
-----------------
CCC
GGG
</code>```

答:
EDITED

```<code>SELECT users.username FROM (
    SELECT
     CASE WHEN userid = 4 THEN friendid else userid END AS "MUTUAL"
    FROM friends
    WHERE (userid = 4 OR friendid = 4) AND
          (
          friendid in (SELECT friendid from friends where userid = 6) OR
          friendid in (SELECT userid from friends where friendid = 6) OR
          userid in (SELECT friendid from friends where userid = 6) OR
          userid in (SELECT userid from friends where friendid = 6)
          )
    ), users WHERE MUTUAL = users.userid
</code>```

Body:
Create 2 tables that contains list of friends and users.

This is my query:

SELECT
  U.username "Mutual Friend"
FROM users U
LEFT OUTER JOIN friends F
  ON U.userid = F.friendid
WHERE f.userid = 6
AND f.friendid IN (SELECT
  friendid
FROM friends
WHERE userid = 4);

friends: userid, friendid

1, 2
1, 3
1, 4
2, 4
2, 5
2, 7
3, 4
3, 6
4, 7
4, 8
4, 9
5, 6
5, 9
6, 7
7, 8
8, 9

users: userid, username

1, AAA
2, BBB
3, CCC
4, DDD
5, EEE
6, FFF
7, GGG
8, HHH
9, III

Desired Result:

Mutual Friends
-----------------
CCC
GGG

Body:
EDITED

SELECT users.username FROM (
    SELECT
     CASE WHEN userid = 4 THEN friendid else userid END AS "MUTUAL"
    FROM friends
    WHERE (userid = 4 OR friendid = 4) AND
          (
          friendid in (SELECT friendid from friends where userid = 6) OR
          friendid in (SELECT userid from friends where friendid = 6) OR
          userid in (SELECT friendid from friends where userid = 6) OR
          userid in (SELECT userid from friends where friendid = 6)
          )
    ), users WHERE MUTUAL = users.userid


问:
variable point to another variable by ref
I have a problem that I create a variable with value that not exist yet (other variable)

example:

```<code>var a=b;
var b=5;
console.log(a)
//I want result to be 5
</code>```

I need it to be without wrapping with function or object (unless I can still call "a" as is and not "a()" )

if 'a' can point to 'b' by ref I will do:

```<code>var b="temp"
var a=b
b=5
</code>```

so, is there any way that 'b' will point on same location as 'a' ?

答:
Well, you can do using a JS feature:

As function declarations are hoisted up by the JS interpreter, we can play around creating a "producer" for a "lazy evaluation" (very common in functional languages, but not included natively in JS).

const a = b;
b(5);
console.log(a());

//We just take advantage of the function hoisting and context to do this
function b(val) {
 return val? this.val = val : this.val;
}```

Body:
I have a problem that I create a variable with value that not exist yet (other variable)

example:

var a=b;
var b=5;
console.log(a)
//I want result to be 5

I need it to be without wrapping with function or object (unless I can still call "a" as is and not "a()" )

if 'a' can point to 'b' by ref I will do:

var b="temp"
var a=b
b=5

so, is there any way that 'b' will point on same location as 'a' ?


问:
How to check MPMusicPlayerController permission?
I have a viewController in my objective c application to show song list of my iPhone. The first time when I open this viewController, show the permission to use the music, but when I accept the permission, the tableView of all songs not refresh.
Like this:

How can I check when the user click on allow to refresh the view?

答:
```<code>MPMediaLibraryAuthorizationStatus authorizationStatus = MPMediaLibrary.authorizationStatus;

switch (authorizationStatus)
{
    case MPMediaLibraryAuthorizationStatusAuthorized:
    {
        break;
    }
    case MPMediaLibraryAuthorizationStatusNotDetermined:
    {

        break;
    }

    case MPMediaLibraryAuthorizationStatusRestricted:
    case MPMediaLibraryAuthorizationStatusDenied:
    {
        break;
    }
}
</code>```


问:
jQuery toggle on Internet Explorer 7. Position and height Problem
i made a simple script that hide/show a hidden div. The page automatically adjusts its height on Firefox, Safari and Chrome.

However on Internet Explorer 7, the div overlaps the contents at the bottom
I'm currently using Joomla as CMS. Where have i gone wrong ? I have tried including "position:relative" for the bottom contents but it isn't helping.

```<code>$j(idName).css({"opacity": "0"});
$j(idName).slideToggle('fast', function() {
    $j(idName).animate({opacity:"1"}, function() {
        if(jQuery.browser.msie) {
            this.style.removeAttribute('filter');
            $j("#main-body").css("height","auto");
        }
    });

});
</code>```

Visit http://educationtechnologysummit.com/sponsors-a-partners.html to get a clearer view

答:
I'm a bit unclear about your question, but from the looks of it, I think the problem you are presenting is that when you mouseover a menu item in IE7 the menu div is hidden behind other elements. (the menu div that is hidden is shown through the jQuery slideToggle function)

It looks like you've included a z-index for the hidden divs, but you didn't specify the z-index for the other elements that it is supposed to overlap. IE7 may incorrectly be allowing elements with an undefined z-index to be layered over the menu items.

EDIT:
Add to your CSS this:

```<code>#menu-spacer{z-index:489;}
#main-body{z-index:489;}
</code>```

Body:
i made a simple script that hide/show a hidden div. The page automatically adjusts its height on Firefox, Safari and Chrome.

However on Internet Explorer 7, the div overlaps the contents at the bottom
I'm currently using Joomla as CMS. Where have i gone wrong ? I have tried including "position:relative" for the bottom contents but it isn't helping.

$j(idName).css({"opacity": "0"});
$j(idName).slideToggle('fast', function() {
    $j(idName).animate({opacity:"1"}, function() {
        if(jQuery.browser.msie) {
            this.style.removeAttribute('filter');
            $j("#main-body").css("height","auto");
        }
    });

});

Visit http://educationtechnologysummit.com/sponsors-a-partners.html to get a clearer view

Body:
I'm a bit unclear about your question, but from the looks of it, I think the problem you are presenting is that when you mouseover a menu item in IE7 the menu div is hidden behind other elements. (the menu div that is hidden is shown through the jQuery slideToggle function)

It looks like you've included a z-index for the hidden divs, but you didn't specify the z-index for the other elements that it is supposed to overlap. IE7 may incorrectly be allowing elements with an undefined z-index to be layered over the menu items.

EDIT:
Add to your CSS this:

#menu-spacer{z-index:489;}
#main-body{z-index:489;}


问:
Filling of a structure using memcpy
This is my code. I thought I will be getting a SegFault on b2->x.pointer1->data because I didn't malloc the b2->x.pointer1. Can anybody please give me some explanation to it? What values were copied to b2->x.pointer1 while doing memcpy? And also regarding the book-keeping of struct *b2 particularly which was filled by memcpy, that how it kept a record of its members? All my motive is to know that how b2->x.pointer1 got its memory on heap.

```<code>struct A
{
    int data;
};

struct B
{
    int data;
    union X
    {
        struct A *pointer1;
        //another
    }x;
};

int main(int argc, char **argv)
{

    struct B *b1 = (struct B*) malloc(sizeof(struct B));
    b1->data = 100;
    b1->x.pointer1 = (struct A*) malloc(sizeof(struct A));
    b1->x.pointer1->data = 1;

    struct B *b2 = (struct B*) malloc(sizeof(struct B));
    //b2->x.pointer1 = (struct A*) malloc(sizeof(struct A));

    memcpy(b2, b1, sizeof(struct B));

    printf("%d", b2->x.pointer1->data);

    return 0;
}
</code>```

And what if I'll free(b1)? Will it free the b1->x.pointer1 too or will there be some memory leak here?

答:
The free function doesn't know anything about the content of the memory being freed.

In other words free(b1) will simply free the memory b1 points to, resulting in a memory leak because b1->x.pointer1 has not been freed and cannot be accessed anymore.

You need to free b1->x.pointer1 explicitly before freeing b1.

Correct sequence for freeing:

```<code>free(b1->x.pointer1);
free(b1);
free(b2);
</code>```

The rule of thumb is: everything that has been allocated by malloc needs explicitely to be freed with free.

Concerning b2: after the memcpy, the content of *b2 is exactly the same as the content of *b1, so b2->x.pointer1 points to the exact same location as b1->x.pointer1, therefore free(b2->x.pointer1); must not be done once free(b1->x.pointer1); has been done. Freeing twice the same memory results in undefined behaviour (most likely a crash).

Title: Filling of a structure using memcpy

Body:
This is my code. I thought I will be getting a SegFault on b2->x.pointer1->data because I didn't malloc the b2->x.pointer1. Can anybody please give me some explanation to it? What values were copied to b2->x.pointer1 while doing memcpy? And also regarding the book-keeping of struct *b2 particularly which was filled by memcpy, that how it kept a record of its members? All my motive is to know that how b2->x.pointer1 got its memory on heap.

struct A
{
    int data;
};

struct B
{
    int data;
    union X
    {
        struct A *pointer1;
        //another
    }x;
};

int main(int argc, char **argv)
{

    struct B *b1 = (struct B*) malloc(sizeof(struct B));
    b1->data = 100;
    b1->x.pointer1 = (struct A*) malloc(sizeof(struct A));
    b1->x.pointer1->data = 1;

    struct B *b2 = (struct B*) malloc(sizeof(struct B));
    //b2->x.pointer1 = (struct A*) malloc(sizeof(struct A));

    memcpy(b2, b1, sizeof(struct B));

    printf("%d", b2->x.pointer1->data);

    return 0;
}

And what if I'll free(b1)? Will it free the b1->x.pointer1 too or will there be some memory leak here?

Body:
The free function doesn't know anything about the content of the memory being freed.

In other words free(b1) will simply free the memory b1 points to, resulting in a memory leak because b1->x.pointer1 has not been freed and cannot be accessed anymore.

You need to free b1->x.pointer1 explicitly before freeing b1.

Correct sequence for freeing:

free(b1->x.pointer1);
free(b1);
free(b2);

The rule of thumb is: everything that has been allocated by malloc needs explicitely to be freed with free.

Concerning b2: after the memcpy, the content of *b2 is exactly the same as the content of *b1, so b2->x.pointer1 points to the exact same location as b1->x.pointer1, therefore free(b2->x.pointer1); must not be done once free(b1->x.pointer1); has been done. Freeing twice the same memory results in undefined behaviour (most likely a crash).


问:
How do you slice an image in corona sdk?
How do you slice up an image like in the photo provided?

答:
Corona alone does not provide anything to achieve this.

But you can use other libraries or plugins to process the image which you then display in Corona as external bitmap textures.

Please refer to https://coronalabs.com/blog/2016/09/22/introducing-external-bitmap-textures/


问:
How can I horizontally and vertically center an  in a
?
I don't want to center a div, I want the contents of a div to be centered.  I would like horizontal and vertical alignment.

Sorry, if this is too easy or whatever, but this is kind of a hassle to get it right.

Grae

I am using IE7

答:
I know you've said that dont want to center a div but to achieve your requirement in a cross browser way would be easier using a jquery plugin and a fake div that contains your element to be centered.

I have successfully centered almost anything using this very small plugin that can center any block element.

The only other way I know are the answer that you already received from @simshaun & @Prhogz

EDIT: As per comment request

Include the script in your head tag

```<code><script type="text/javascript" src="<%: Url.Content( "~/_assets/js/jquery.center.min.js" )%>"></script>
</code>```

Now if you have a DIV that you want to center inside your markup simply use it as

```<code>$(document).ready(function() {
    $("#myDIV").center({ vertical: false });
});
</code>```

Title: How can I horizontally and vertically center an <img> in a <div>?

Body:
I know you've said that dont want to center a div but to achieve your requirement in a cross browser way would be easier using a jquery plugin and a fake div that contains your element to be centered.

I have successfully centered almost anything using this very small plugin that can center any block element.

The only other way I know are the answer that you already received from @simshaun & @Prhogz

EDIT: As per comment request

Include the script in your head tag

<script type="text/javascript" src="<%: Url.Content( "~/_assets/js/jquery.center.min.js" )%>"></script>

Now if you have a DIV that you want to center inside your markup simply use it as

$(document).ready(function() {
    $("#myDIV").center({ vertical: false });
});


问:
HTML Structure how do i wrap whole content inside div or section
i am little confused with html structure, should i wrap whole content inside inside div or section, because am making body 90% width apart from footer</p>

```<code><body>
    <div class="homepage">
        <nav id="mainNav" class="navbar navbar-default navbar-fixed-top">
            navigation
        </nav> <!-- Nav End -->
        <header>
            Header content
        </header> <!-- Header End -->
        <section class="product">
            Main content
        </section>
        <!-- <hr class="Hhr"> -->
    </div> <!-- Homepage End -->
    <footer>
        Footer copyrights annd social icons
    </footer>
    </div>
</body>
</code>```

答:
It may be the solution that you want, but it is not mandatory to wrap whole content inside the div to make it's width 90%.

* {
  text-align: center;
}

.navbar-fixed-top {
  width: 90%;
  left: 0px;
  right: 0px;
  margin: auto;
  background-color: gray;
}

.homepage {
  width: 90%;
  margin: auto;
}

header {
  margin-top: 50px;
  background-color: blue;
}

section {
  background-color: red;
}

footer {
  background-color: yellow;
  height: 100px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

<body>

  <div style="width: 100%">
    <div class="homepage">
      <nav id="mainNav" class="navbar navbar-default navbar-fixed-top">
        navigation
      </nav>
      <!-- Nav End -->
      <header>
        Header content
        <br /><br /><br /><br /><br />
      </header>
      <!-- Header End -->
      <section class="product">
        Main content
        <br /><br /><br /><br /><br />
        <br /><br /><br /><br /><br />
        <br /><br /><br /><br /><br />
        <br /><br /><br /><br /><br />
        <br /><br /><br /><br /><br />
      </section>
      <!-- <hr class="Hhr"> -->
    </div>
    <!-- Homepage End -->
    <footer>
      Footer copyrights annd social icons
    </footer>
  </div>

</body></code>```

Body:
i am little confused with html structure, should i wrap whole content inside inside div or section, because am making body 90% width apart from footer

            navigation

            Header content

            Main content

        Footer copyrights annd social icons

Body:
It may be the solution that you want, but it is not mandatory to wrap whole content inside the div to make it's width 90%.

* {
  text-align: center;
}

.navbar-fixed-top {
  width: 90%;
  left: 0px;
  right: 0px;
  margin: auto;
  background-color: gray;
}

.homepage {
  width: 90%;
  margin: auto;
}

header {
  margin-top: 50px;
  background-color: blue;
}

section {
  background-color: red;
}

footer {
  background-color: yellow;
  height: 100px;
}

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

<body>

  <div style="width: 100%">
    <div class="homepage">
      <nav id="mainNav" class="navbar navbar-default navbar-fixed-top">
        navigation
      </nav>
      <!-- Nav End -->
      <header>
        Header content
        <br /><br /><br /><br /><br />
      </header>
      <!-- Header End -->
      <section class="product">
        Main content
        <br /><br /><br /><br /><br />
        <br /><br /><br /><br /><br />
        <br /><br /><br /><br /><br />
        <br /><br /><br /><br /><br />
        <br /><br /><br /><br /><br />
      </section>
      <!-- <hr class="Hhr"> -->
    </div>
    <!-- Homepage End -->
    <footer>
      Footer copyrights annd social icons
    </footer>
  </div>

</body>


问:
onclick function does not get registered in created DOM element's outerHTML
I wonder why the onclick function for my button created by createElement("button") does not get registered and fired when I take use of the buttons outerHTML. I mean, a normal attribute like Title does get attached, but the function does not.</p>

```<code>function createBtn(answer){
    var btn = document.createElement("button");
    var btnTxt = document.createTextNode("Are we twins?");
    btn.appendChild(btnTxt);

    btn.onclick = function(){
        alert(answer);
    }
    btn.title = "This is the title";

    document.write(btn.outerHTML); // onclick is not registered
    document.body.appendChild(btn); // onclick is registered

}

createBtn("Not quite");
</code>```

答:
The outerHTML property of a HTML Node returns String. The events will be attached to the HTML Node, but when you convert them to Stings all the events linked to them are lost. So, when you use document.write with btn.outerHTML, it copies the button as a text and all events attached are lost.

But when you use appendChild with btn object, it appends the HTMLButtonElement object with the events attached to it.

So, if you have to use outerHTML, attach the events once you write it to the document.

Body:
I wonder why the onclick function for my button created by createElement("button") does not get registered and fired when I take use of the buttons outerHTML. I mean, a normal attribute like Title does get attached, but the function does not.

function createBtn(answer){
    var btn = document.createElement("button");
    var btnTxt = document.createTextNode("Are we twins?");
    btn.appendChild(btnTxt);

    btn.onclick = function(){
        alert(answer);
    }
    btn.title = "This is the title";

    document.write(btn.outerHTML); // onclick is not registered
    document.body.appendChild(btn); // onclick is registered

}

createBtn("Not quite");


问:
How to boost individual documents
I have a pretty complex query and now I want to boost some documents that fulfill some criteria. I have the following simplified document structure and I try to give some documents a boost based on the id, genre, tag.

```<code>{
  "id": 123,
  "genres": ["ACTION", "DRAMA"],
  "tags": ["For kids", "Romantic", "Nature"]
}
</code>```

What I want to do is for example

```<code>id: 123 boost: 5
genres: ACTION boost: 3
tags: Romantic boost: 0.2
</code>```

and boost all documents that are contained in my query and fit the criteria but I don't want to filter them out. So query clause boosting is not of any help I guess.

Edit: To make if easier to understand what I want to achieve (not sure if it is possible with elasticsearch, no is also a valid answer).

I want to search with a query and get a result set. In this set I want to boost some documents. But I don't want to enlarge the result set or filter it. The boost should be independent from the query.

For example I search for a specific tag and want to boost all documents with category 'ACTION' in the result set. But I don't want all documents with category 'ACTION' in the result set and also I don't want only documents with the specific tag AND category 'ACTION'.

答:
I found a solution and it was pretty simple. I use a boosting query. I now just nest the different boosting criteria with and my original query is now the base query.

https://www.elastic.co/guide/en/elasticsearch/reference/2.3/query-dsl-boosting-query.html

For example:

```<code>{
  "query": {
    "boosting": {
      "positive": {
        "boosting": {
          "positive": {
            "match": {
              "director": "Spielberg"
            }
          },
          "negative": {
            "term": {
              "genres": "DRAMA"
            }
          },
          "negative_boost": 1.3
        }
      },
      "negative": {
        "term": {
          "tags": "Romantic"
        }
      },
      "negative_boost": 1.2
    }
  }
}
</code>```

Title: How to boost individual documents

Body:
I have a pretty complex query and now I want to boost some documents that fulfill some criteria. I have the following simplified document structure and I try to give some documents a boost based on the id, genre, tag.

{
  "id": 123,
  "genres": ["ACTION", "DRAMA"],
  "tags": ["For kids", "Romantic", "Nature"]
}

What I want to do is for example

id: 123 boost: 5
genres: ACTION boost: 3
tags: Romantic boost: 0.2

and boost all documents that are contained in my query and fit the criteria but I don't want to filter them out. So query clause boosting is not of any help I guess.

Edit: To make if easier to understand what I want to achieve (not sure if it is possible with elasticsearch, no is also a valid answer).

I want to search with a query and get a result set. In this set I want to boost some documents. But I don't want to enlarge the result set or filter it. The boost should be independent from the query.

For example I search for a specific tag and want to boost all documents with category 'ACTION' in the result set. But I don't want all documents with category 'ACTION' in the result set and also I don't want only documents with the specific tag AND category 'ACTION'.

Body:
I found a solution and it was pretty simple. I use a boosting query. I now just nest the different boosting criteria with and my original query is now the base query.

https://www.elastic.co/guide/en/elasticsearch/reference/2.3/query-dsl-boosting-query.html

For example:

{
  "query": {
    "boosting": {
      "positive": {
        "boosting": {
          "positive": {
            "match": {
              "director": "Spielberg"
            }
          },
          "negative": {
            "term": {
              "genres": "DRAMA"
            }
          },
          "negative_boost": 1.3
        }
      },
      "negative": {
        "term": {
          "tags": "Romantic"
        }
      },
      "negative_boost": 1.2
    }
  }
}


问:
Getting unique values in Excel by using formulas only
Do you know a way in Excel to "calculate" by formula a list of unique values ?

E.g: a vertical range contains values "red", "blue", "red", "green", "blue", "black"

and I want to have as result "red, "blue", "green", "black" + eventually 2 other blank cells.

I already found a way to get a calculated sorted list using SMALL or LARGE combined with INDEX, but I'd like to have this calculated sort as well, WITHOUT USING VBA.

答:
Try this formula in B2 cell

```<code>=IFERROR(INDEX($A$2:$A$7,MATCH(0,COUNTIF(B$1:$B1,$A$2:$A$7),0),1),"")
</code>```

After click F2 and press Ctrl + Shift + Enter

Body:
Try this formula in B2 cell

=IFERROR(INDEX($A$2:$A$7,MATCH(0,COUNTIF(B$1:$B1,$A$2:$A$7),0),1),"")

After click F2 and press Ctrl + Shift + Enter


问:
What do single quotes do in C++ when used on multiple characters?
I'm curious about this code:

```<code>cout << 'test'; // Note the single quotes.
</code>```

gives me an output of 1952805748.

My question: Is the output an address in memory or something?

答:
This kind of feature is really good when you are building parsers.
Consider this:

```<code>byte* buffer = ...;
if(*(int*)buffer == 'GET ')
  invoke_get_method(buffer+4);
</code>```

This code will likely only work on specific endianess and might break across different compilers

Body:
I'm curious about this code:

cout << 'test'; // Note the single quotes.

gives me an output of 1952805748.

My question: Is the output an address in memory or something?

Body:
This kind of feature is really good when you are building parsers.
Consider this:

byte* buffer = ...;
if(*(int*)buffer == 'GET ')
  invoke_get_method(buffer+4);

This code will likely only work on specific endianess and might break across different compilers


问:
Select image from specific folder Android
Hi i want to get image from a specific folder. Now im using this code:

```<code>                    Intent intent = new Intent();
                    Uri uri = Uri.parse(Environment.DIRECTORY_PICTURES);
                    intent.setDataAndType(uri, "image/*");
                    intent.setAction(Intent.ACTION_GET_CONTENT);
                    startActivityForResult(Intent.createChooser(intent,"Scegli foto"),PICK_IMAGE_REQUEST);
</code>```

Now,with that uri i see the recent and i have to open manually folder.I've tryed setting uri.parse input with the path of my folder,but i got anyway my recent.How can i open automatically my folder?

答:
try this my friend

```<code>    private void getImages() {
    String[] filenames = new String[0];
    File path = new File(Environment.getExternalStorageDirectory() + "/FolderName");
    if (path.exists()) {
        filenames = path.list();
    }
    ArrayList<String> imagesPathArrayList;

    for (int i = 0; i < filenames.length; i++) {
        imagesPathArrayList.add(path.getPath() + "/" + filenames[i]);
        Log.e("FAV_Images", imagesPathArrayList.get(i));
        ///Now set this bitmap on imageview
    }
}
</code>```

set image like this

```<code>Bitmap bitmap =  BitmapFactory.decodeFile(imagesPathArrayList.get(position));
ImageView.setImageBitmap(bitmap);
</code>```

Body:
Hi i want to get image from a specific folder. Now im using this code:

                    Intent intent = new Intent();
                    Uri uri = Uri.parse(Environment.DIRECTORY_PICTURES);
                    intent.setDataAndType(uri, "image/*");
                    intent.setAction(Intent.ACTION_GET_CONTENT);
                    startActivityForResult(Intent.createChooser(intent,"Scegli foto"),PICK_IMAGE_REQUEST);

Now,with that uri i see the recent and i have to open manually folder.I've tryed setting uri.parse input with the path of my folder,but i got anyway my recent.How can i open automatically my folder?

Body:
try this my friend

    private void getImages() {
    String[] filenames = new String[0];
    File path = new File(Environment.getExternalStorageDirectory() + "/FolderName");
    if (path.exists()) {
        filenames = path.list();
    }
    ArrayList<String> imagesPathArrayList;

    for (int i = 0; i < filenames.length; i++) {
        imagesPathArrayList.add(path.getPath() + "/" + filenames[i]);
        Log.e("FAV_Images", imagesPathArrayList.get(i));
        ///Now set this bitmap on imageview
    }
}

set image like this

Bitmap bitmap =  BitmapFactory.decodeFile(imagesPathArrayList.get(position));
ImageView.setImageBitmap(bitmap);


问:
bash sort unusual order. Problem with spaces?
Lots of time gone in to a bug, which tracks back to sort...

Can someone explain why I get this unsorted result, when the bash docs tell me the delimiter is a transition from white to non-white characters? Shouldn't the first field be sorted?

```<code>>sort myfile.txt
10_10000000 19
10_10000001 20
10_10000002 19
10_10000003 17
10_10000004 16
10_1000000 44
10_10000005 16
10_10000006 16
10_10000007 17
10_10000008 16
</code>```

of course using +0 -1 gives me my expected result:

```<code>>sort +0 -1 myfile.txt
10_1000000 44
10_10000000 19
10_10000001 20
10_10000002 19
10_10000003 17
10_10000004 16
10_10000005 16
10_10000006 16
10_10000007 17
10_10000008 16
</code>```

Some metainfo:

```<code>>type sort
sort is hashed (/bin/sort)
</code>```

I am using

```<code>sort (GNU coreutils) 5.97

>locale
LANG=en_US.UTF-8
LC_CTYPE="en_US.UTF-8"
LC_NUMERIC="en_US.UTF-8"
LC_TIME="en_US.UTF-8"
LC_COLLATE="en_US.UTF-8"
LC_MONETARY="en_US.UTF-8"
LC_MESSAGES="en_US.UTF-8"
LC_PAPER="en_US.UTF-8"
LC_NAME="en_US.UTF-8"
LC_ADDRESS="en_US.UTF-8"
LC_TELEPHONE="en_US.UTF-8"
LC_MEASUREMENT="en_US.UTF-8"
LC_IDENTIFICATION="en_US.UTF-8"
LC_ALL=
</code>```

答:
I think you are seeing locale-based issues. Some (many?) locales affect the way sort works, in that certain chars will be ignored. In this case, it looks like the space between the fields are being ignored when you don't specify the fields to sort. Remove the space and you can see that the row that looks like it's in the wrong place is correct.

If you run sort with a different locale you'll probably get a different result:

```<code>$ LANG=C sort myfile.txt
</code>```

My default locale is en_AU.UTF-8 and I see your original sort results. When I set LANG=C, I see the results you are expecting.

Body:
Lots of time gone in to a bug, which tracks back to sort...

Can someone explain why I get this unsorted result, when the bash docs tell me the delimiter is a transition from white to non-white characters? Shouldn't the first field be sorted?

>sort myfile.txt
10_10000000 19
10_10000001 20
10_10000002 19
10_10000003 17
10_10000004 16
10_1000000 44
10_10000005 16
10_10000006 16
10_10000007 17
10_10000008 16

of course using +0 -1 gives me my expected result:

>sort +0 -1 myfile.txt
10_1000000 44
10_10000000 19
10_10000001 20
10_10000002 19
10_10000003 17
10_10000004 16
10_10000005 16
10_10000006 16
10_10000007 17
10_10000008 16

Some metainfo:

>type sort
sort is hashed (/bin/sort)

I am using

sort (GNU coreutils) 5.97

>locale
LANG=en_US.UTF-8
LC_CTYPE="en_US.UTF-8"
LC_NUMERIC="en_US.UTF-8"
LC_TIME="en_US.UTF-8"
LC_COLLATE="en_US.UTF-8"
LC_MONETARY="en_US.UTF-8"
LC_MESSAGES="en_US.UTF-8"
LC_PAPER="en_US.UTF-8"
LC_NAME="en_US.UTF-8"
LC_ADDRESS="en_US.UTF-8"
LC_TELEPHONE="en_US.UTF-8"
LC_MEASUREMENT="en_US.UTF-8"
LC_IDENTIFICATION="en_US.UTF-8"
LC_ALL=

Body:
I think you are seeing locale-based issues. Some (many?) locales affect the way sort works, in that certain chars will be ignored. In this case, it looks like the space between the fields are being ignored when you don't specify the fields to sort. Remove the space and you can see that the row that looks like it's in the wrong place is correct.

If you run sort with a different locale you'll probably get a different result:

$ LANG=C sort myfile.txt

My default locale is en_AU.UTF-8 and I see your original sort results. When I set LANG=C, I see the results you are expecting.


问:
MYSQL - Subquery on same table in WHERE clause of UPDATE statement
I got an "error '#1093 - You can't specify target table 't1' for update in FROM clause" with this code:

```<code>UPDATE `table1` t1 SET t1.name = 'abc'
WHERE t1.id = 165 AND NOT EXISTS (
    SELECT t2.id FROM `table1` t2 WHERE t2.id != 165 AND t2.name = 'abc'
)
</code>```

But there is no problem with the code:

```<code>UPDATE `table1` t1 SET t1.name = 'abc'
WHERE t1.id = 165 AND NOT EXISTS (
    SELECT t2.id FROM `table2` t2 WHERE t2.id != 165 AND t2.name = 'abc'
)
</code>```

What did I go wrong?

答:
You can rephrase this query as a self join to the same table:

```<code>UPDATE table1 t1
LEFT JOIN table1 t2
    ON t2.id != 165 AND t2.name = 'abc'
SET t1.name = 'abc'
WHERE t1.id = 165 AND t2.name IS NULL
</code>```

The update logic here is that your NOT EXISTS clause has been replaced with a LEFT JOIN where any record from the left side of the join did not match (t2.name IS NULL) to any record where the id is not 165 and the name is abc.

Body:
I got an "error '#1093 - You can't specify target table 't1' for update in FROM clause" with this code:

UPDATE `table1` t1 SET t1.name = 'abc'
WHERE t1.id = 165 AND NOT EXISTS (
    SELECT t2.id FROM `table1` t2 WHERE t2.id != 165 AND t2.name = 'abc'
)

But there is no problem with the code:

UPDATE `table1` t1 SET t1.name = 'abc'
WHERE t1.id = 165 AND NOT EXISTS (
    SELECT t2.id FROM `table2` t2 WHERE t2.id != 165 AND t2.name = 'abc'
)

What did I go wrong?

Body:
You can rephrase this query as a self join to the same table:

UPDATE table1 t1
LEFT JOIN table1 t2
    ON t2.id != 165 AND t2.name = 'abc'
SET t1.name = 'abc'
WHERE t1.id = 165 AND t2.name IS NULL

The update logic here is that your NOT EXISTS clause has been replaced with a LEFT JOIN where any record from the left side of the join did not match (t2.name IS NULL) to any record where the id is not 165 and the name is abc.


问:
Replace double quotes to string empty
I want to remove "Portugal" remove double quotes and replace it with string empty what to do i am using Replace("""," ") but this not working

答:
Use backslash n instead:

```<code>Replace("\"", string.Empty);
</code>```

The backslash ("\") character is a special escape character used to indicate other special characters such as quotation marks (\"). For other special escape characters, you can refer to this link:

https://msdn.microsoft.com/en-us/library/aa691087(v=vs.71).aspx

Title: Replace double quotes to string empty

Body:
Use backslash n instead:

Replace("\"", string.Empty);

The backslash ("\") character is a special escape character used to indicate other special characters such as quotation marks (\"). For other special escape characters, you can refer to this link:

https://msdn.microsoft.com/en-us/library/aa691087(v=vs.71).aspx


问:
How do I use HTML as the view engine in Express?
I tried this simple change from the seed and created the corresponding .html files (e.g. index.html).

```<code>//app.set('view engine', 'jade');
app.set('view engine', 'html');
</code>```

and this file remained the same:

```<code>exports.index = function(req, res){
  res.render('index');
};
</code>```

but while running I get

500 Error: Cannot find module 'html'

Is my only option to use 'ejs'? My intent was to use plain HTML in conjuction with AngularJS.

答:
Answer is very Simple.
You Must use app.engine('html') to render *.html Pages.
try this.It must Solve the Problem.

```<code>app.set('views', path.join(__dirname, 'views'));
**// Set EJS View Engine**
app.set('view engine','ejs');
**// Set HTML engine**
app.engine('html', require('ejs').renderFile);
</code>```

the .html file Will work

Body:
I tried this simple change from the seed and created the corresponding .html files (e.g. index.html).

//app.set('view engine', 'jade');
app.set('view engine', 'html');

and this file remained the same:

exports.index = function(req, res){
  res.render('index');
};

but while running I get

500 Error: Cannot find module 'html'

Is my only option to use 'ejs'? My intent was to use plain HTML in conjuction with AngularJS.

Body:
Answer is very Simple.
You Must use app.engine('html') to render *.html Pages.
try this.It must Solve the Problem.

app.set('views', path.join(__dirname, 'views'));
**// Set EJS View Engine**
app.set('view engine','ejs');
**// Set HTML engine**
app.engine('html', require('ejs').renderFile);

the .html file Will work


问:
Redim array after it is filled
Before filling my array I don't know how big it's going to get, but at a certain point (after all data has been inserted) I want to redim the array so there are no empty values in the end of the array. If I dim it as

```<code>valuesForSix() As Double
</code>```

I cannot add values with

```<code>valuesForSix(0) = 9.654
</code>```

Can somebody help me?

答:
You can use ReDim Preserve to redefine the array's dimensions. The Preserve keyword means the array retains all existing data. See this MSDN language reference for details.

This example initialises an empty array, then loops from 1 to 10 adding an extra element each time:

```<code>Dim v() As Double, i As Long
For i = 1 To 10
    ReDim Preserve v(1 To i) As Double
    v(i) = i
Next i
' v = [1 2 3 4 5 6 7 8 9 10]
</code>```

You can extend the array by n elements using LBound and UBound:

```<code>Dim v(0 To 10) As Double, n As Long
n = 7
ReDim Preserve v(LBound(v) To UBound(v) + n)
' Now v is Double(0 to 17)
</code>```

Title: Redim array after it is filled

Body:
Before filling my array I don't know how big it's going to get, but at a certain point (after all data has been inserted) I want to redim the array so there are no empty values in the end of the array. If I dim it as

valuesForSix() As Double

I cannot add values with

valuesForSix(0) = 9.654

Can somebody help me?

Body:
You can use ReDim Preserve to redefine the array's dimensions. The Preserve keyword means the array retains all existing data. See this MSDN language reference for details.

This example initialises an empty array, then loops from 1 to 10 adding an extra element each time:

Dim v() As Double, i As Long
For i = 1 To 10
    ReDim Preserve v(1 To i) As Double
    v(i) = i
Next i
' v = [1 2 3 4 5 6 7 8 9 10]

You can extend the array by n elements using LBound and UBound:

Dim v(0 To 10) As Double, n As Long
n = 7
ReDim Preserve v(LBound(v) To UBound(v) + n)
' Now v is Double(0 to 17)


问:
How can I make this generic method more flexible?
I'm working with a library (TreeView in Gtk to be specific) that allows you to sort by passing a function that compares two rows. A simplified version of the function signature might look like this:

```<code>int SomeSortFunc (Foo foo1, Foo foo2)
{
    // Return -1 if foo1 < foo2, 0 if foo1 == foo2, 1 if foo1 > foo2
}
</code>```

I can't simply implement Foo.CompareTo (Foo), because I want to sort differently depending on the context. There are several fields in Foo that I sort by. The sort priority of each field is what depends on the context. I would like to write something like this:

```<code>int SortFunc<T> (Foo foo1, Foo foo2, params Func<Foo, T> [] selectors)
    where T : IComparable<T>
{
    return selectors
        .Select (s => s (foo1).CompareTo (s (foo2)))
        .FirstOrDefault (i => i != 0);
}

// Compare by SomeString, then by SomeInt, then by SomeBar
int SomeSortFunc (Foo foo1, Foo foo2)
{
    // Won't compile, because String, Int, and Bar are all different types.
    return SortFunc (foo1, foo2, f => f.SomeString, f => f.SomeInt, f => f.SomeBar);
}
</code>```

This won't compile, because the T in Func<Foo, T> is different for String, Int, and Bar : IComparable<Bar> (in other words, there is no way to resolve the T in SortFunc<T>).

Is there any way to write this function such that each selector can return a different type, as long as each type SomeType implements IComparable<SomeType>?

答:
I would simplify it and just accept a function returning a non-generic IComparable. Now you can pass in functions returning primitives without needing to figure out the number of generic type parameters your function would actually need, as it would truthfully need type parameters for each of the functions provided.

```<code>int SortFunc(Foo foo1, Foo foo2, params Func<Foo, IComparable>[] selectors)
</code>```

Body:
I'm working with a library (TreeView in Gtk to be specific) that allows you to sort by passing a function that compares two rows. A simplified version of the function signature might look like this:

int SomeSortFunc (Foo foo1, Foo foo2)
{
    // Return -1 if foo1 < foo2, 0 if foo1 == foo2, 1 if foo1 > foo2
}

I can't simply implement Foo.CompareTo (Foo), because I want to sort differently depending on the context. There are several fields in Foo that I sort by. The sort priority of each field is what depends on the context. I would like to write something like this:

int SortFunc<T> (Foo foo1, Foo foo2, params Func<Foo, T> [] selectors)
    where T : IComparable<T>
{
    return selectors
        .Select (s => s (foo1).CompareTo (s (foo2)))
        .FirstOrDefault (i => i != 0);
}

// Compare by SomeString, then by SomeInt, then by SomeBar
int SomeSortFunc (Foo foo1, Foo foo2)
{
    // Won't compile, because String, Int, and Bar are all different types.
    return SortFunc (foo1, foo2, f => f.SomeString, f => f.SomeInt, f => f.SomeBar);
}

This won't compile, because the T in Func<Foo, T> is different for String, Int, and Bar : IComparable<Bar> (in other words, there is no way to resolve the T in SortFunc<T>).

Is there any way to write this function such that each selector can return a different type, as long as each type SomeType implements IComparable<SomeType>?

Body:
I would simplify it and just accept a function returning a non-generic IComparable. Now you can pass in functions returning primitives without needing to figure out the number of generic type parameters your function would actually need, as it would truthfully need type parameters for each of the functions provided.

int SortFunc(Foo foo1, Foo foo2, params Func<Foo, IComparable>[] selectors)


问:
ConstraintLayout layout_constraintDimensionRatio not working
I used constraintLayout and layout_constraintDimensionRatio="1:1"
(width is wrap_content, height is 0dp (match_constraint))

As a result, I expected width and height to be 1:1, but it's not working.

What is wrong?

I attached code and screenshot.

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/t1"
        android:layout_width="wrap_content"
        android:layout_height="0dp"
        android:background="@android:color/holo_blue_bright"
        android:gravity="center"
        android:text="Hello World!11"
        app:layout_constraintDimensionRatio="1:1" />

</android.support.constraint.ConstraintLayout>
</code>```

screenshot

I quote android developer site about Constraintlayout.
https://developer.android.com/reference/android/support/constraint/ConstraintLayout.html#DimensionConstraints

Ratio :: You can also define one dimension of a widget as a ratio of
the other one. In order to do that, you need to have at least one
constrained dimension be set to 0dp (i.e., MATCH_CONSTRAINT), and set
the attribute layout_constraintDimentionRatio to a given ratio. For
example:

```<code>     <Button android:layout_width="wrap_content"
               android:layout_height="0dp"
               app:layout_constraintDimensionRatio="1:1" />

  will set the height of the button to be the same as its width.
</code>```

but it was not working.

答:
Please notice the last line, adding constraints around the edges makes the constraint work.

You can also use the design view in Studio, and drag and drop the constraints between objects.

```<code><TextView
    android:id="@+id/textView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Available chats" />

<ListView
    android:id="@+id/listChats"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    app:layout_constraintTop_toBottomOf="@+id/textView"/>
</code>```

Body:
I used constraintLayout and layout_constraintDimensionRatio="1:1"
(width is wrap_content, height is 0dp (match_constraint))

As a result, I expected width and height to be 1:1, but it's not working.

What is wrong?

I attached code and screenshot.

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/t1"
        android:layout_width="wrap_content"
        android:layout_height="0dp"
        android:background="@android:color/holo_blue_bright"
        android:gravity="center"
        android:text="Hello World!11"
        app:layout_constraintDimensionRatio="1:1" />

</android.support.constraint.ConstraintLayout>

screenshot

I quote android developer site about Constraintlayout.
https://developer.android.com/reference/android/support/constraint/ConstraintLayout.html#DimensionConstraints

Ratio :: You can also define one dimension of a widget as a ratio of
the other one. In order to do that, you need to have at least one
constrained dimension be set to 0dp (i.e., MATCH_CONSTRAINT), and set
the attribute layout_constraintDimentionRatio to a given ratio. For
example:

     <Button android:layout_width="wrap_content"
               android:layout_height="0dp"
               app:layout_constraintDimensionRatio="1:1" />

  will set the height of the button to be the same as its width.

but it was not working.

Body:
Please notice the last line, adding constraints around the edges makes the constraint work.

You can also use the design view in Studio, and drag and drop the constraints between objects.

<TextView
    android:id="@+id/textView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Available chats" />

<ListView
    android:id="@+id/listChats"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    app:layout_constraintTop_toBottomOf="@+id/textView"/>


问:
How to test an auto complete textbox using selenium c#
I have tried many solutions present in this site. But none of it worked. I wanted a simple code using " keys.enter " . Can someone help me out with the solution.</p>

答:
Hope this will help you.Here you are opening facebook, and trying to login.</p>

```<code>import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import java.util.List;

public class TestCase {
    private static WebElement element;
    static WebDriver driver;
    public static void main(String[] args) throws InterruptedException {
        String URL = "https://www.facebook.com/";
        driver = new FirefoxDriver();
        driver.get(URL);
        driver.findElement(By.id("email")).sendKeys("username");
        driver.findElement(By.id("pass")).sendKeys("password");
        driver.findElement(By.id("pass")).sendKeys(Keys.ENTER);
    }
}
</code>```

Body:
Hope this will help you.Here you are opening facebook, and trying to login.

import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import java.util.List;

public class TestCase {
    private static WebElement element;
    static WebDriver driver;
    public static void main(String[] args) throws InterruptedException {
        String URL = "https://www.facebook.com/";
        driver = new FirefoxDriver();
        driver.get(URL);
        driver.findElement(By.id("email")).sendKeys("username");
        driver.findElement(By.id("pass")).sendKeys("password");
        driver.findElement(By.id("pass")).sendKeys(Keys.ENTER);
    }
}


问:
why does python treat all the lists declared in the same line as a same object when modifying?
In python3 lets say i need to have 3 empty lists.I can assign empty lists separately in 3 separate lines. But the when i declared them in the same line as shown below

s1 , s2 , s3 = [[]]*3

After doing this whenever i append an element to any one of these lists the same element gets appended to all the lists. Its the same with all operations and whenever i pop an item in one list , all the three lists s1 , s2 , s3 pop an item . I can't seam to understand this behaviour

答:
Ok assuming that you meant:

```<code>s1 = s2 = s3 = [[]]
</code>```

The reason that appending to one of them appends to all of the others is because all of them are pointing at the same object. s2 and s3 are really just aliases for s1. If you want to make deep copies of things then consider looking into the copy module: https://docs.python.org/3/library/copy.html

Body:
Ok assuming that you meant:

s1 = s2 = s3 = [[]]

The reason that appending to one of them appends to all of the others is because all of them are pointing at the same object. s2 and s3 are really just aliases for s1. If you want to make deep copies of things then consider looking into the copy module: https://docs.python.org/3/library/copy.html


问:
What are the best use cases for Akka framework
I have heard lots of raving about Akka framework (Java/Scala service platform), but so far have not seen many actual examples of use cases it would be good for. So I would be interested in hearing about things developers have used it succesfully.

Only one limitation: please do not include case of writing a chat server.
(why? since this has been overused as an example for lots of similar things)

答:
An example of how we use it would be on a priority queue of debit/credit card transactions. We have millions of these and the effort of the work depends on the input string type. If the transaction is of type CHECK we have very little processing but if it is a point of sale then there is lots to do such as merge with meta data (category, label, tags, etc) and provide services (email/sms alerts, fraud detection, low funds balance, etc).
Based on the input type we compose classes of various traits (called mixins) necessary to handle the job and then perform the work. All of these jobs come into the same queue in realtime mode from different financial institutions. Once the data is cleansed it is sent to different data stores for persistence, analytics, or pushed to a socket connection, or to Lift comet actor. Working actors are constantly self load balancing the work so that we can process the data as fast as possible. We can also snap in additional services, persistence models, and stm for critical decision points.

The Erlang OTP style message passing on the JVM makes a great system for developing realtime systems on the shoulders of existing libraries and application servers.

Akka allows you to do message passing like you would in a traditional esb but with speed! It also gives you tools in the framework to manage the vast amount of actor pools, remote nodes, and fault tolerance that you need for your solution.


问:
Django sqlite content in easy-pdf
Django version: 1.11.3

I have stored data in a sqlite database as I want to have displayed in a pdf. I use easy-pdf. I don't know how to parse the data without using render(). How do I do it with get_context_data(). Any suggestions?

This works:

```<code>def test(request):
all_organizations = Organization.objects.all()
all_tickets = Ticket.objects.all()
context = {'all_organizations': all_organizations, 'all_tickets': all_tickets}
return render(request, 'test/docs/examples/theme/test.html', context)
</code>```

Don't know how to parse all_organizations and all_tickets for use in the easy-pdf:

```<code>class HelloPDFView(PDFTemplateView):
all_organizations = Organization.objects.all()
all_tickets = Ticket.objects.all()
context = {'all_organizations': all_organizations, 'all_tickets': all_tickets}
template_name = "test/docs/examples/theme/hello.html"
def get_context_data(self, **kwargs):
    return super(HelloPDFView, self).get_context_data(
        pagesize="A4",
        title="Test",
        **kwargs
    )
</code>```

答:
```<code>def get_context_data(self, **kwargs):
    context = super(HelloPDFView, self).get_context_data(**kwargs)
    context['all_organizations'] = Organization.objects.all()
    context['all_tickets'] = Ticket.objects.all()
    context['pagesize']="A4"
    context['title']= 'Test'
    return context
</code>```

try this, and in the template you can access the data using the key names like pagesize, title and all

Title: Django sqlite content in easy-pdf

Body:
Django version: 1.11.3

I have stored data in a sqlite database as I want to have displayed in a pdf. I use easy-pdf. I don't know how to parse the data without using render(). How do I do it with get_context_data(). Any suggestions?

This works:

def test(request):
all_organizations = Organization.objects.all()
all_tickets = Ticket.objects.all()
context = {'all_organizations': all_organizations, 'all_tickets': all_tickets}
return render(request, 'test/docs/examples/theme/test.html', context)

Don't know how to parse all_organizations and all_tickets for use in the easy-pdf:

class HelloPDFView(PDFTemplateView):
all_organizations = Organization.objects.all()
all_tickets = Ticket.objects.all()
context = {'all_organizations': all_organizations, 'all_tickets': all_tickets}
template_name = "test/docs/examples/theme/hello.html"
def get_context_data(self, **kwargs):
    return super(HelloPDFView, self).get_context_data(
        pagesize="A4",
        title="Test",
        **kwargs
    )

Body:
def get_context_data(self, **kwargs):
    context = super(HelloPDFView, self).get_context_data(**kwargs)
    context['all_organizations'] = Organization.objects.all()
    context['all_tickets'] = Ticket.objects.all()
    context['pagesize']="A4"
    context['title']= 'Test'
    return context

try this, and in the template you can access the data using the key names like pagesize, title and all


问:
How do you serve content other than files using Flask?
This questing might seem a bit dumb since I'm only beginning to get a grasp of HTTP. As far as I understand, HTTP is a communication protocol, which means that 2 computers can communicate using it. On the internet, however, it seems like all HTTP servers are serving files. Can I make a flask server which doesn't serve files but just communicates with clients over HTTP?</p>

答:
Can I make a flask server which doesn't serve files but just communicates with clients over HTTP?

My understanding is that when you receive a "file" in a "normal" web request, what's really happening is that you are receiving an HTTP response (which is like a text file), and that HTTP response contains a status code (which is what you seem to be thinking of as the real HTTP), a "content" section which contains the text of the "file", and there is another line in the HTTP response that specifies how the recipient computer should interpret the contents of that "content" section (e.g. as JSON, or plaintext, or HTML, or XML, etc.). That line usually looks something like Content-Type: text/html.

In your case, you would only be specifying the status code while leaving the content section blank.

Since you aren't sending any content, you might be thinking that you'd like to specify a 'null' content type in your HTTP responses, but there doesn't seem to be a 'null' content type.  Nevertheless, it wouldn't really matter what you set the content-type to since you wouldn't be filling out any content. One thing I've seen is to set it to text/plain or application/json.

If you want to send structured data to the user, the usual way to do that is to send it as JSON. So you would specify that Content-Type as application/json, and then you would format the body ("content") of your response as JSON.

Here's an example of Flask code that would do this:

```<code>@app.route('/get_current_user')
def get_current_user():
    return jsonify(
        username=g.user.username,
        email=g.user.email,
        id=g.user.id
    )
</code>```

Source: Return JSON response from Flask view

Body:
Can I make a flask server which doesn't serve files but just communicates with clients over HTTP?

My understanding is that when you receive a "file" in a "normal" web request, what's really happening is that you are receiving an HTTP response (which is like a text file), and that HTTP response contains a status code (which is what you seem to be thinking of as the real HTTP), a "content" section which contains the text of the "file", and there is another line in the HTTP response that specifies how the recipient computer should interpret the contents of that "content" section (e.g. as JSON, or plaintext, or HTML, or XML, etc.). That line usually looks something like Content-Type: text/html.

In your case, you would only be specifying the status code while leaving the content section blank.

Since you aren't sending any content, you might be thinking that you'd like to specify a 'null' content type in your HTTP responses, but there doesn't seem to be a 'null' content type.  Nevertheless, it wouldn't really matter what you set the content-type to since you wouldn't be filling out any content. One thing I've seen is to set it to text/plain or application/json.

If you want to send structured data to the user, the usual way to do that is to send it as JSON. So you would specify that Content-Type as application/json, and then you would format the body ("content") of your response as JSON.

Here's an example of Flask code that would do this:

@app.route('/get_current_user')
def get_current_user():
    return jsonify(
        username=g.user.username,
        email=g.user.email,
        id=g.user.id
    )

Source: Return JSON response from Flask view


问:
React Native custom toggle button component
I have been working on a custom component that acts similar to a radio button, but now have a few questions on how I can extend it.

I want to be able set TouchableOpacity style via a stylesheet which is currently done inline due to the dynamic nature of it.

I also want to be able to pass a second variable/string in price through.

Further to the above if I can send through 2 variables these will be coming via firebase/props so how would I expose them.

Component

```<code>import React, { Component } from 'react'
import { View, Text, TouchableOpacity } from 'react-native'
import styles from './Styles/OptionStyle'

export default class Option extends Component {
  constructor(props) {
    super(props);
    this.state = {
      activeOption: this.props.options[0],
    };
  }
  updateActiveOption = (activeOption) => {
    this.setState({
      activeOption,
    });
  };
  render() {
    return (
      <View style={styles.container}>
        {this.props.options.map((option, index) => (
          <TouchableOpacity key={index} style={styles.button}
            onPress={() => {
              this.props.onChange(option);
              this.updateActiveOption(option);
            }}
          >
            <Text
              style={{
                width: 100,
                borderWidth: 1,
                borderColor: this.state.activeOption === option ? '#4caf50' : 'rgb(117, 117, 118)',
                borderRadius: 6,
                height: 100,
                padding: 10,
                color: this.state.activeOption === option ? '#4caf50' : 'rgb(117, 117, 118)'
              }}
            >
              {option}
            </Text>
          </TouchableOpacity>
        ))}
      </View>
    );
  }
}
</code>```

Calling the component

```<code><Option
            options={['Small','Medium','Large']}
            onChange={(option) => {
              console.log(option);
            }}
          />
</code>```

This is where I would like to be able to pass 2 variables per option ie Small and $3.95 or Medium and $4.95

答:
You can pass array of objects via props and then use them in your component. Something like this:

```<code><Option
        options={[{label: 'Small', price: '$3.95'},{label: 'Medium', price: '$4.95'}]}
        onChange={(option) => {
          console.log(option);
        }}
      />
</code>```

And then in your Component simply iterate over it for example with map:

```<code>{this.props.options.map((option, index) => (
 <TouchableOpacity><Text>{option.label} - {option.value}</Text></TouchableOpacity>
))}
</code>```

Body:
I have been working on a custom component that acts similar to a radio button, but now have a few questions on how I can extend it.

I want to be able set TouchableOpacity style via a stylesheet which is currently done inline due to the dynamic nature of it.

I also want to be able to pass a second variable/string in price through.

Further to the above if I can send through 2 variables these will be coming via firebase/props so how would I expose them.

Component

import React, { Component } from 'react'
import { View, Text, TouchableOpacity } from 'react-native'
import styles from './Styles/OptionStyle'

export default class Option extends Component {
  constructor(props) {
    super(props);
    this.state = {
      activeOption: this.props.options[0],
    };
  }
  updateActiveOption = (activeOption) => {
    this.setState({
      activeOption,
    });
  };
  render() {
    return (
      <View style={styles.container}>
        {this.props.options.map((option, index) => (
          <TouchableOpacity key={index} style={styles.button}
            onPress={() => {
              this.props.onChange(option);
              this.updateActiveOption(option);
            }}
          >
            <Text
              style={{
                width: 100,
                borderWidth: 1,
                borderColor: this.state.activeOption === option ? '#4caf50' : 'rgb(117, 117, 118)',
                borderRadius: 6,
                height: 100,
                padding: 10,
                color: this.state.activeOption === option ? '#4caf50' : 'rgb(117, 117, 118)'
              }}
            >
              {option}
            </Text>
          </TouchableOpacity>
        ))}
      </View>
    );
  }
}

Calling the component

<Option
            options={['Small','Medium','Large']}
            onChange={(option) => {
              console.log(option);
            }}
          />

This is where I would like to be able to pass 2 variables per option ie Small and $3.95 or Medium and $4.95

Body:
You can pass array of objects via props and then use them in your component. Something like this:

<Option
        options={[{label: 'Small', price: '$3.95'},{label: 'Medium', price: '$4.95'}]}
        onChange={(option) => {
          console.log(option);
        }}
      />

And then in your Component simply iterate over it for example with map:

{this.props.options.map((option, index) => (
 <TouchableOpacity><Text>{option.label} - {option.value}</Text></TouchableOpacity>
))}


问:
the Classification of threads in browser
Is there an official classification of threads in browser? I want to write an article related with browser thread concepts. Is the following classification correct?
Javascript interpreter thread, GUI rendering thread, event handler thread, timing thread, http request thread...

If you have more official detail about it, please tell me with a list or give me the related links, thank you.

答:
Behind the scenes of modern web browsers

The JavaScript Event Loop: Explained


问:
How to fetch last row of a webtable in selenium
I have a webtable for which I have to fetch the last row . The problem is that the webtable is dynamic so I don't know the row number.I have tried below code but the row number is static there which will fail.</p>

```<code>List<WebElement> rows=driver.findElements(By.xpath("//table[1]/tbody/tr[5]"));
</code>```

答:
to get last element use (locator)[last()] method, like:

```<code>WebElement lastRow =  driver.findElement(By.xpath("(//table[1]/tbody/tr)[last()]"));
</code>```

which is shorted variant of:

```<code>(locator)[position() = last()]
</code>```

Body:
I have a webtable for which I have to fetch the last row . The problem is that the webtable is dynamic so I don't know the row number.I have tried below code but the row number is static there which will fail.

List<WebElement> rows=driver.findElements(By.xpath("//table[1]/tbody/tr[5]"));

Body:
to get last element use (locator)[last()] method, like:

WebElement lastRow =  driver.findElement(By.xpath("(//table[1]/tbody/tr)[last()]"));

which is shorted variant of:

(locator)[position() = last()]


问:
Ignoring locked row in a MySQL query
I have one table that is read at the same time by different threads.

Each thread must select 100 rows, execute some tasks on each row (unrelated to the database) then they must delete the selected row from the table.

rows are selected using this query:

```<code>SELECT id FROM table_name FOR UPDATE;
</code>```

My question is: How can I ignore (or skip) rows that were previously locked using a select statement in MySQL ?

答:
Even though it is not the best solution, as there is no way that I know to ignore locked rows, I select a random one and try to obtain a lock.

```<code>START TRANSACTION;
SET @v1 =(SELECT myId FROM tests.table WHERE status is NULL LIMIT 1);
SELECT * FROM tests.table WHERE myId=@v1 FOR UPDATE; #<- lock
</code>```

Setting a small timeout for the transaction, if that row is locked the transaction is aborted and I try another one. If I obtain the lock, I process it. If (bad luck) that row was locked, it is processed and the lock is released before my timeout, I then select a row that has already been 'processed'! However, I check a field that my processes set (e.g. status): if the other process transaction ended OK, that field tells me that work has already been done and I do not process that row again.

Every other possible solution without transactions (e.g. setting another field if the row has no status and ... etc.) can easily provide race conditions and missed processes (e.g. one thread abruptly dies, the allocated data is still tagged, while a transaction expires; ref. comment here

Hope it helps

Title: Ignoring locked row in a MySQL query

Body:
I have one table that is read at the same time by different threads.

Each thread must select 100 rows, execute some tasks on each row (unrelated to the database) then they must delete the selected row from the table.

rows are selected using this query:

SELECT id FROM table_name FOR UPDATE;

My question is: How can I ignore (or skip) rows that were previously locked using a select statement in MySQL ?

Body:
Even though it is not the best solution, as there is no way that I know to ignore locked rows, I select a random one and try to obtain a lock.

START TRANSACTION;
SET @v1 =(SELECT myId FROM tests.table WHERE status is NULL LIMIT 1);
SELECT * FROM tests.table WHERE myId=@v1 FOR UPDATE; #<- lock

Setting a small timeout for the transaction, if that row is locked the transaction is aborted and I try another one. If I obtain the lock, I process it. If (bad luck) that row was locked, it is processed and the lock is released before my timeout, I then select a row that has already been 'processed'! However, I check a field that my processes set (e.g. status): if the other process transaction ended OK, that field tells me that work has already been done and I do not process that row again.

Every other possible solution without transactions (e.g. setting another field if the row has no status and ... etc.) can easily provide race conditions and missed processes (e.g. one thread abruptly dies, the allocated data is still tagged, while a transaction expires; ref. comment here

Hope it helps