问:
Trying a quick cluster deployment with Docker:Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?
I found that DolphinDB now supports a quick cluster deployment with docker containers and I followed the guide on github: https://github.com/dolphindb/Tutorials_CN/blob/master/docker_deployment.md to deploy a cluster with DolphinDB Docker package. But I encountered a problem. I looked at any other questions but can't find my own solution.

Here is the problem:

```<code>xllu@xllu-OptiPlex-7060:~/DolphinDB-Docker-Compose/Dockerbuild$ docker -v
Docker version 18.09.3, build 774a1f4
xllu@xllu-OptiPlex-7060:~/DolphinDB-Docker-Compose/Dockerbuild$ docker-compose --version
docker-compose version 1.24.0, build 0aa59064
xllu@xllu-OptiPlex-7060:~/DolphinDB-Docker-Compose/Dockerbuild$ docker build -t ddb:latest ./
Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?

</code>```

I tried restarting docker:

```<code>xllu@xllu-OptiPlex-7060:~/DolphinDB-Docker-Compose/Dockerbuild$ sudo service docker restart
Job for docker.service failed because the control process exited with error code.
See "systemctl status docker.service" and "journalctl -xe" for details.
</code>```

Then I checked this :

```<code>xllu@xllu-OptiPlex-7060:~/DolphinDB-Docker-Compose/Dockerbuild$ systemctl status docker.service
● docker.service - LSB: Create lightweight, portable, self-sufficient containers.
   Loaded: loaded (/etc/init.d/docker; generated)
   Active: failed (Result: exit-code) since Fri 2019-05-31 15:16:01 CST; 16s ago
     Docs: man:systemd-sysv-generator(8)
  Process: 29234 ExecStart=/etc/init.d/docker start (code=exited, status=1/FAILURE)
 Main PID: 2596 (code=exited, status=0/SUCCESS)

5月 31 15:16:01 xllu-OptiPlex-7060 systemd[1]: Starting LSB: Create lightweight, portable, self-sufficient containers....
5月 31 15:16:01 xllu-OptiPlex-7060 docker[29234]:  * /usr/bin/dockerd not present or not executable
5月 31 15:16:01 xllu-OptiPlex-7060 systemd[1]: docker.service: Control process exited, code=exited status=1
5月 31 15:16:01 xllu-OptiPlex-7060 systemd[1]: docker.service: Failed with result 'exit-code'.
5月 31 15:16:01 xllu-OptiPlex-7060 systemd[1]: Failed to start LSB: Create lightweight, portable, self-sufficient containers..

</code>```

答:
Can you try removing /var/lib/docker with sudo rm -rf /var/lib/docker and try restarting the docker?

You will lose the images stored.

Body:
I found that DolphinDB now supports a quick cluster deployment with docker containers and I followed the guide on github: https://github.com/dolphindb/Tutorials_CN/blob/master/docker_deployment.md to deploy a cluster with DolphinDB Docker package. But I encountered a problem. I looked at any other questions but can't find my own solution.

Here is the problem:

xllu@xllu-OptiPlex-7060:~/DolphinDB-Docker-Compose/Dockerbuild$ docker -v
Docker version 18.09.3, build 774a1f4
xllu@xllu-OptiPlex-7060:~/DolphinDB-Docker-Compose/Dockerbuild$ docker-compose --version
docker-compose version 1.24.0, build 0aa59064
xllu@xllu-OptiPlex-7060:~/DolphinDB-Docker-Compose/Dockerbuild$ docker build -t ddb:latest ./
Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?

I tried restarting docker:

xllu@xllu-OptiPlex-7060:~/DolphinDB-Docker-Compose/Dockerbuild$ sudo service docker restart
Job for docker.service failed because the control process exited with error code.
See "systemctl status docker.service" and "journalctl -xe" for details.

Then I checked this :

xllu@xllu-OptiPlex-7060:~/DolphinDB-Docker-Compose/Dockerbuild$ systemctl status docker.service
● docker.service - LSB: Create lightweight, portable, self-sufficient containers.
   Loaded: loaded (/etc/init.d/docker; generated)
   Active: failed (Result: exit-code) since Fri 2019-05-31 15:16:01 CST; 16s ago
     Docs: man:systemd-sysv-generator(8)
  Process: 29234 ExecStart=/etc/init.d/docker start (code=exited, status=1/FAILURE)
 Main PID: 2596 (code=exited, status=0/SUCCESS)

5月 31 15:16:01 xllu-OptiPlex-7060 systemd[1]: Starting LSB: Create lightweight, portable, self-sufficient containers....
5月 31 15:16:01 xllu-OptiPlex-7060 docker[29234]:  * /usr/bin/dockerd not present or not executable
5月 31 15:16:01 xllu-OptiPlex-7060 systemd[1]: docker.service: Control process exited, code=exited status=1
5月 31 15:16:01 xllu-OptiPlex-7060 systemd[1]: docker.service: Failed with result 'exit-code'.
5月 31 15:16:01 xllu-OptiPlex-7060 systemd[1]: Failed to start LSB: Create lightweight, portable, self-sufficient containers..


来源: stackexchange

问:
How to get the revision of latest deployment in openshift?
We trying to run openshift command via jenkins, as automation pipeline.
If we run

```<code>oc rollout latest dc/myapp
</code>```

it triggers the deployment and jenkins job is completed as success.
We are not able to identify, whether triggered openshift deployment is successful or failed.

As one of the solution, we thought to get status of the latest deployment,
run while loop until status is complete.

we thought of using below command :

```<code>oc rollout history dc/<name> --revision=1
</code>```

But, problem with it is , we are not able to get revision number of latest deployment.

Is this right approach, if not what can be the way to find out whether open-shift deployment is failed or successful ?

Thank you.

答:
you can watch the status of latest roleout with the following command

```<code>oc rollout status dc/<name>
</code>```

you can get more information with oc rollout --help command

if you want a specific condition to be true on specific resource, you can also use the oc waitcommand

oc wait --help

ContentLicense: CC BY-SA 4.0

Body:
We trying to run openshift command via jenkins, as automation pipeline.
If we run

oc rollout latest dc/myapp

it triggers the deployment and jenkins job is completed as success.
We are not able to identify, whether triggered openshift deployment is successful or failed.

As one of the solution, we thought to get status of the latest deployment,
run while loop until status is complete.

we thought of using below command :

oc rollout history dc/<name> --revision=1

But, problem with it is , we are not able to get revision number of latest deployment.

Is this right approach, if not what can be the way to find out whether open-shift deployment is failed or successful ?

Thank you.

Body:
you can watch the status of latest roleout with the following command

oc rollout status dc/<name>

you can get more information with oc rollout --help command

if you want a specific condition to be true on specific resource, you can also use the oc waitcommand

oc wait --help


问:
set debounce in ionic searchbox with angular not working
I'm trying to let users make a search to the database to pull results by searching in a textbox and I don't want the API to be called whenever a variable is inserted in the textbox but wait for 3 seconds before the call is made to the API.
I'm using debounce but it's not working

```<code><ion-searchbar
[(ngModel)]="userSearch"
          [debounce]="4000"
           (ionInput)="liveSearch($event)"
           placeholder="Search for Politics, Entertainment, Sports..."
></ion-searchbar>
</code>```

JS

```<code>import { Component } from '@angular/core';
import { NewsService } from '../services/news-service.service';

@Component({
  selector: 'app-tab3',
  templateUrl: 'tab3.page.html',
  styleUrls: ['tab3.page.scss']
})
export class Tab3Page {

  userSearch: any;
  searchResults: any= [];

  constructor(private newsService: NewsService) {}

  liveSearch() {
    this.newsService.searchNews(this.userSearch).subscribe(data => {
      this.searchResults = data;
      console.log(data);
    });
  }

}
</code>```

答: You should change (ionInput)="liveSearch($event)" to (ionChange)="liveSearch($event)", since the debounce property only changes the ionChange behaviour.

Body:
I'm trying to let users make a search to the database to pull results by searching in a textbox and I don't want the API to be called whenever a variable is inserted in the textbox but wait for 3 seconds before the call is made to the API.
I'm using debounce but it's not working

<ion-searchbar
[(ngModel)]="userSearch"
          [debounce]="4000"
           (ionInput)="liveSearch($event)"
           placeholder="Search for Politics, Entertainment, Sports..."
></ion-searchbar>

JS

import { Component } from '@angular/core';
import { NewsService } from '../services/news-service.service';

@Component({
  selector: 'app-tab3',
  templateUrl: 'tab3.page.html',
  styleUrls: ['tab3.page.scss']
})
export class Tab3Page {

  userSearch: any;
  searchResults: any= [];

  constructor(private newsService: NewsService) {}

  liveSearch() {
    this.newsService.searchNews(this.userSearch).subscribe(data => {
      this.searchResults = data;
      console.log(data);
    });
  }

}


问:
How can I remove rows starting with ' in a variant?
Following the answer to this question, I execute different queries stored in a .txt file using the following code:

```<code>   Dim vSql       As Variant
   Dim vSqls      As Variant
   Dim strSql     As String
   Dim intF       As Integer

   intF = FreeFile()
   Open "MyFile.txt" For Input As #intF
   strSql = Input(LOF(intF), #intF)
   Close intF
   vSql = Split(strSql, ";")

   On Error Resume Next
   For Each vSqls In vSql
      DoCmd.RunSQL vSqls
   Next
</code>```

The queries are separated by ;, and each query is preceded by a comment line, starting with ' and ending with ;(so that it gets split by vSql = Split(strSql, ";") ).

The resulting vSql variant is composed of valid SQL statements, interspersed with comment lines starting with '. The current code works, but I would like to remove the On Error Resume Next so that a faulty SQL statement returns an error instead of being ignored.

How can I remove the rows starting with ' in the variant before executing the For Each loop? Or is there another way to accomplish my goal? The comment character can be changed if necessary.

答:
It depends on exactly how the file is stored, but the simplest way is to find the first return character and take the rest of the text.

```<code>vSqls=mid(vSqls = Mid(vSqls, InStr(vSqls, vbCrLf) + 2)
</code>```

or

```<code>vSqls=mid(vSqls = Mid(vSqls, InStr(vSqls, vbCr) + 1)
</code>```

Bear in mind that this will only remove the first line so if there are blanks you will need to check whether the next line starts with a '.

And you might find that your queries don't work if they are spread across more than one line that you might need to deal with that by replacing any remaining carriage returns with a space.

Body:
Following the answer to this question, I execute different queries stored in a .txt file using the following code:

   Dim vSql       As Variant
   Dim vSqls      As Variant
   Dim strSql     As String
   Dim intF       As Integer

   intF = FreeFile()
   Open "MyFile.txt" For Input As #intF
   strSql = Input(LOF(intF), #intF)
   Close intF
   vSql = Split(strSql, ";")

   On Error Resume Next
   For Each vSqls In vSql
      DoCmd.RunSQL vSqls
   Next

The queries are separated by ;, and each query is preceded by a comment line, starting with ' and ending with ;(so that it gets split by vSql = Split(strSql, ";") ).

The resulting vSql variant is composed of valid SQL statements, interspersed with comment lines starting with '. The current code works, but I would like to remove the On Error Resume Next so that a faulty SQL statement returns an error instead of being ignored.

How can I remove the rows starting with ' in the variant before executing the For Each loop? Or is there another way to accomplish my goal? The comment character can be changed if necessary.

Body:
It depends on exactly how the file is stored, but the simplest way is to find the first return character and take the rest of the text.

vSqls=mid(vSqls = Mid(vSqls, InStr(vSqls, vbCrLf) + 2)

or

vSqls=mid(vSqls = Mid(vSqls, InStr(vSqls, vbCr) + 1)

Bear in mind that this will only remove the first line so if there are blanks you will need to check whether the next line starts with a '.

And you might find that your queries don't work if they are spread across more than one line that you might need to deal with that by replacing any remaining carriage returns with a space.


问:
How do I get the "results" object nested in the array "news" and map over it?
I'm trying to map over an array which is fetched using componentDidMount. However, I keep receiving this same error "Uncaught TypeError: this.state.news.map is not a function".

This is on componentDidMount

```<code>componentDidMount() {
        fetch(
            "https://content.guardianapis.com/search?api-key=test"
        )
            .then(response => response.json())
            .then(data => {
                this.setState({
                    news: data
                })
                console.log(data)
            })
    }
</code>```

This is my function to map over the data

```<code>renderNews() {
        return this.state.news.map((a, i) => (
            <div key={i}>
                {a.response.map((b, i) => (
                    <div key={i}>
                        <div key={i} className="newsEach">
                            <h3>{b.webTitle}</h3>
                            <ul className="newsInfoUl">
                                <li className="newsInfoEach">{b.type}</li>
                                <li className="newsInfoEach">
                                    {b.sectionName}
                                </li>
                                <li className="newsInfoEach">{b.pillarName}</li>
                                <li className="newsInfoEach">{b.webUrl}</li>
                            </ul>
                        </div>
                    </div>
                ))}
            </div>
        ))
    }
</code>```

Then I render out the data over here

```<code>render() {
        return (
            <div className="newsWrapper">
                {/* <h3>{this.renderNews()}</h3> */}
                <h3>Hello</h3>
            </div>
        )
    }
</code>```

Update #1
Here is the data that I got from console.log(data)

```<code>{response: {…}}
response:
currentPage: 1
orderBy: "newest"
pageSize: 10
pages: 211707
results: Array(10)
0: {id: "business/live/2019/may/31/markets-trump-shock-mexi…ffs-trade-war-china-brexit-ftse-100-business-live", type: "liveblog", sectionId: "business", sectionName: "Business", webPublicationDate: "2019-05-31T08:25:12Z", …}
1: {id: "football/2019/may/31/atletico-madrid-stadium-wanda…litano-champions-league-final-liverpool-tottenham", type: "article", sectionId: "football", sectionName: "Football", webPublicationDate: "2019-05-31T08:23:15Z", …}
2: {id: "tv-and-radio/2019/may/31/a-sinister-tale-from-the-minds-behind-dirty-john-podcasts-of-the-week", type: "article", sectionId: "tv-and-radio", sectionName: "Television & radio", webPublicationDate: "2019-05-31T08:12:02Z", …}
3: {id: "politics/2019/may/31/alastair-campbell-labour-expulsion-discrimination-appeal", type: "article", sectionId: "politics", sectionName: "Politics", webPublicationDate: "2019-05-31T08:11:22Z", …}
4: {id: "football/from-the-archive-blog/2019/may/31/womens-football-match-crouch-end-1895", type: "article", sectionId: "football", sectionName: "Football", webPublicationDate: "2019-05-31T08:00:27Z", …}
5: {id: "culture/2019/may/31/what-to-see-this-week-in-the-uk", type: "article", sectionId: "culture", sectionName: "Culture", webPublicationDate: "2019-05-31T08:00:27Z", …}
6: {id: "tv-and-radio/2019/may/31/when-they-see-us-review-netflix-ava-duvernay-central-park-five", type: "article", sectionId: "tv-and-radio", sectionName: "Television & radio", webPublicationDate: "2019-05-31T08:00:27Z", …}
7: {id: "music/2019/may/31/lee-scratch-perry-rainford-review-on-u-sound-records", type: "article", sectionId: "music", sectionName: "Music", webPublicationDate: "2019-05-31T08:00:27Z", …}
8: {id: "books/2019/may/31/mother-ship-francesca-segal-review", type: "article", sectionId: "books", sectionName: "Books", webPublicationDate: "2019-05-31T07:58:27Z", …}
9: {id: "football/2019/may/31/football-transfer-rumours-spurs-to-bid-for-wilfried-zaha", type: "article", sectionId: "football", sectionName: "Football", webPublicationDate: "2019-05-31T07:47:36Z", …}
length: 10
__proto__: Array(0)
startIndex: 1
status: "ok"
total: 2117063
userTier: "developer"
__proto__: Object
__proto__: Object
</code>```

Sorry I forgot to include this portion of my code which is what I initialize this.state.news with. Here it is

```<code>constructor() {
        super()

        this.state = {
            news: []
        }

        this.renderNews = this.renderNews.bind(this)
    }
</code>```

答:
Because this.state.news is an object. In your setState, I think you are expecting data.results (which is an array) instead of just data.

```<code>this.setState({
  news: data.results,
  loading: false
});
</code>```

Body:
I'm trying to map over an array which is fetched using componentDidMount. However, I keep receiving this same error "Uncaught TypeError: this.state.news.map is not a function".

This is on componentDidMount

componentDidMount() {
        fetch(
            "https://content.guardianapis.com/search?api-key=test"
        )
            .then(response => response.json())
            .then(data => {
                this.setState({
                    news: data
                })
                console.log(data)
            })
    }

This is my function to map over the data

renderNews() {
        return this.state.news.map((a, i) => (

                {a.response.map((b, i) => (

{b.webTitle}

{b.type}

                                    {b.sectionName}

{b.pillarName}

{b.webUrl}

                ))}

        ))
    }

Then I render out the data over here

render() {
        return (

                {/*
{this.renderNews()}
 */}

Hello

        )
    }

Update #1
Here is the data that I got from console.log(data)

{response: {…}}
response:
currentPage: 1
orderBy: "newest"
pageSize: 10
pages: 211707
results: Array(10)
0: {id: "business/live/2019/may/31/markets-trump-shock-mexi…ffs-trade-war-china-brexit-ftse-100-business-live", type: "liveblog", sectionId: "business", sectionName: "Business", webPublicationDate: "2019-05-31T08:25:12Z", …}
1: {id: "football/2019/may/31/atletico-madrid-stadium-wanda…litano-champions-league-final-liverpool-tottenham", type: "article", sectionId: "football", sectionName: "Football", webPublicationDate: "2019-05-31T08:23:15Z", …}
2: {id: "tv-and-radio/2019/may/31/a-sinister-tale-from-the-minds-behind-dirty-john-podcasts-of-the-week", type: "article", sectionId: "tv-and-radio", sectionName: "Television & radio", webPublicationDate: "2019-05-31T08:12:02Z", …}
3: {id: "politics/2019/may/31/alastair-campbell-labour-expulsion-discrimination-appeal", type: "article", sectionId: "politics", sectionName: "Politics", webPublicationDate: "2019-05-31T08:11:22Z", …}
4: {id: "football/from-the-archive-blog/2019/may/31/womens-football-match-crouch-end-1895", type: "article", sectionId: "football", sectionName: "Football", webPublicationDate: "2019-05-31T08:00:27Z", …}
5: {id: "culture/2019/may/31/what-to-see-this-week-in-the-uk", type: "article", sectionId: "culture", sectionName: "Culture", webPublicationDate: "2019-05-31T08:00:27Z", …}
6: {id: "tv-and-radio/2019/may/31/when-they-see-us-review-netflix-ava-duvernay-central-park-five", type: "article", sectionId: "tv-and-radio", sectionName: "Television & radio", webPublicationDate: "2019-05-31T08:00:27Z", …}
7: {id: "music/2019/may/31/lee-scratch-perry-rainford-review-on-u-sound-records", type: "article", sectionId: "music", sectionName: "Music", webPublicationDate: "2019-05-31T08:00:27Z", …}
8: {id: "books/2019/may/31/mother-ship-francesca-segal-review", type: "article", sectionId: "books", sectionName: "Books", webPublicationDate: "2019-05-31T07:58:27Z", …}
9: {id: "football/2019/may/31/football-transfer-rumours-spurs-to-bid-for-wilfried-zaha", type: "article", sectionId: "football", sectionName: "Football", webPublicationDate: "2019-05-31T07:47:36Z", …}
length: 10
__proto__: Array(0)
startIndex: 1
status: "ok"
total: 2117063
userTier: "developer"
__proto__: Object
__proto__: Object

Sorry I forgot to include this portion of my code which is what I initialize this.state.news with. Here it is

constructor() {
        super()

        this.state = {
            news: []
        }

        this.renderNews = this.renderNews.bind(this)
    }

Body:
Because this.state.news is an object. In your setState, I think you are expecting data.results (which is an array) instead of just data.

this.setState({
  news: data.results,
  loading: false
});


问:
GoogleSignIn Works But Google_DEFAULT_GAMES Doesn't
When I call GoogleSignInOptions from the default sign-in option, I get a signIn UI displayed

```<code>GoogleSignInOptions ClientInfo = GoogleSignInOptions.Builder.(GoogleSignInOptions.DEFAULT_SIGN_IN).requestEmail().build();
GoogleSignInClient mGoogleSignInClient = GoogleSignInClient.getClient(this, ClientInfo);
Intent SignInintent = mGoogleSignInClient.getSignInIntent();
startActivityForResult(SignInintent,3000);
</code>```

However if I call GoogleSignInOptions with the default games sign in. I get no UI displayed at all infact I get a dim light as if it wants to display but then it dissappears.

```<code>GoogleSignInOptions ClientInfo = GoogleSignInOptions.Builder. GoogleSignInOptions.DEFAULT_GAMES_SIGN_IN).requestEmail().build();
GoogleSignInClient mGoogleSignInClient = GoogleSignInClient.getClient(this, ClientInfo);
Intent SignInintent = mGoogleSignInClient.getSignInIntent();
startActivityForResult(SignInintent,3000);
</code>```

答:
I had the same problem. The checks for SHA-1, packageName, and other possible problems listed in https://developers.google.com/games/services/android/troubleshooting did not produce any effective results. My problem was solved by moving app_id written directly to the metadata in string resources. Really, i don't know why but it works.

Before:

AndroidManifest.xml:

```<code><meta-data
        android:name="com.google.android.gms.games.APP_ID"
        android:value="XXXXXXXXXXXX" />
</code>```

After:

AndroidManifest.xml:

```<code><meta-data
        android:name="com.google.android.gms.games.APP_ID"
        android:value="@string/app_id" />
</code>```

res/values/games_ids:

```<code><?xml version="1.0" encoding="utf-8"?>
<resources>
    <!-- app_id -->
    <string name="app_id" translatable="false">XXXXXXXXXXXX</string>
</resources>
</code>```

Body:
When I call GoogleSignInOptions from the default sign-in option, I get a signIn UI displayed

GoogleSignInOptions ClientInfo = GoogleSignInOptions.Builder.(GoogleSignInOptions.DEFAULT_SIGN_IN).requestEmail().build();
GoogleSignInClient mGoogleSignInClient = GoogleSignInClient.getClient(this, ClientInfo);
Intent SignInintent = mGoogleSignInClient.getSignInIntent();
startActivityForResult(SignInintent,3000);

However if I call GoogleSignInOptions with the default games sign in. I get no UI displayed at all infact I get a dim light as if it wants to display but then it dissappears.

GoogleSignInOptions ClientInfo = GoogleSignInOptions.Builder. GoogleSignInOptions.DEFAULT_GAMES_SIGN_IN).requestEmail().build();
GoogleSignInClient mGoogleSignInClient = GoogleSignInClient.getClient(this, ClientInfo);
Intent SignInintent = mGoogleSignInClient.getSignInIntent();
startActivityForResult(SignInintent,3000);

Body:
I had the same problem. The checks for SHA-1, packageName, and other possible problems listed in https://developers.google.com/games/services/android/troubleshooting did not produce any effective results. My problem was solved by moving app_id written directly to the metadata in string resources. Really, i don't know why but it works.

Before:

AndroidManifest.xml:

<meta-data
        android:name="com.google.android.gms.games.APP_ID"
        android:value="XXXXXXXXXXXX" />

After:

AndroidManifest.xml:

<meta-data
        android:name="com.google.android.gms.games.APP_ID"
        android:value="@string/app_id" />

res/values/games_ids:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <!-- app_id -->
    <string name="app_id" translatable="false">XXXXXXXXXXXX</string>
</resources>


问:
Swift: conformance to the Protocol with Generic method with "where" clause
Summary:

I'd like to create a Class<T> which would have a corresponding ClassDelegate protocol with func<T> in it.

Goal:

To reuse a single object and behavior with multiple object classes. Receive a delegate callback with already a specialized class, without the need to cast the object to a specific class to work with it.

Sample Code:

A protocol with a generic method:

```<code>protocol GenericTableControllerDelegate: AnyObject {
    func controller<T>(controller: GenericTableController<T>, didSelect value: T)
}
</code>```

A generic base UITableViewController subclass:

```<code>open class GenericTableController<DataType>: UITableViewController {
    weak var delegate: GenericTableControllerDelegate?
    var data = [DataType]()

    open override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let item = data[indexPath.row]
        delegate?.controller(controller: self, didSelect: item)
    }
}
</code>```

A specialized version of the GenericTableController:

```<code>final class SpecializedTableController: GenericTableController<NSObject> {}
</code>```

Client of the SpecializedTableController - achieves the result, but requires type-casting to be able to access the specialized data type:

```<code>final class ClientOfTableController: UIViewController, GenericTableControllerDelegate {
    // Works OK
    func controller<T>(controller: GenericTableController<T>, didSelect value: T) {
        if let value = value as? NSObject {
            // Requires unwrapping and casting
        }
    }
}
</code>```

Client of the SpecializedTableController, with "where" requirement - the only problem that it doesn't compile

```<code>final class AnotherClientOfTableController: UIViewController, GenericTableControllerDelegate {
    // Works OK
    func controller<T>(controller: GenericTableController<T>, didSelect value: T) where T: NSObject {
        // `value` is String
    }
}
</code>```

Type 'AnotherClientOfTableController' does not conform to protocol
  'GenericTableControllerDelegate' Do you want to add protocol stubs?

Is there a way to have a protocol with a generic method and being able to have a concrete (specialized) type in that method implementation?

Are there close alternatives achieving satisfying similar requirement (having a generic class but being able to handle a concrete type in the delegate callback)?

答:
I don't think this is doable in a sense you want it. The closest would be combining with subclass. Consider the following:

```<code>protocol MagicProtocol {
    func dooMagic<T>(_ trick: T)
}

class Magician<TrickType> {
    private let listener: MagicProtocol
    private let tricks: [TrickType]
    init(listener: MagicProtocol, tricks: [TrickType]) { self.listener = listener; self.tricks = tricks }
    func abracadabra() { listener.dooMagic(tricks.randomElement()) }
}

class Audience<DataType>: MagicProtocol {

    var magician: Magician<DataType>?

    init() {
        magician?.abracadabra()
    }

    func doExplicitMagic(_ trick: DataType) {

    }

    func dooMagic<T>(_ trick: T) {
        doExplicitMagic(trick as! DataType)
    }

}
</code>```

Now I can create a subclass and restrict it to some type:

```<code>class IntegerAudience: Audience<Int> {

    override func doExplicitMagic(_ trick: Int) {
        print("This works")
    }

}
</code>```

The problem is that there is no correlation between the 2 generics. So at some point a cast must be done. Here we do it in protocol method:

```<code>doExplicitMagic(trick as! DataType)
</code>```

it seems like this is pretty safe and it could never crash but if you look a bit closer we could do this:

```<code>func makeThingsGoWrong() {
    let myAudience = IntegerAudience()
    let evilMagician = Magician(listener: myAudience, tricks: ["Time to burn"])
    evilMagician.abracadabra() // This should crash the app
}
</code>```

Here myAudience corresponds to protocol MagicProtocol which may not be restricted to generic. But myAudience is restricted to Int. Nothing is stopping the compiler but if it did, what would the error be?

Anyway, it works as long as you use it correctly. If you don't then it will crash. You could do an optional unwrap but I am not sure it is appropriate.

Body:
Summary:

I'd like to create a Class<T> which would have a corresponding ClassDelegate protocol with func<T> in it.

Goal:

To reuse a single object and behavior with multiple object classes. Receive a delegate callback with already a specialized class, without the need to cast the object to a specific class to work with it.

Sample Code:

A protocol with a generic method:

protocol GenericTableControllerDelegate: AnyObject {
    func controller<T>(controller: GenericTableController<T>, didSelect value: T)
}

A generic base UITableViewController subclass:

open class GenericTableController<DataType>: UITableViewController {
    weak var delegate: GenericTableControllerDelegate?
    var data = [DataType]()

    open override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let item = data[indexPath.row]
        delegate?.controller(controller: self, didSelect: item)
    }
}

A specialized version of the GenericTableController:

final class SpecializedTableController: GenericTableController<NSObject> {}

Client of the SpecializedTableController - achieves the result, but requires type-casting to be able to access the specialized data type:

final class ClientOfTableController: UIViewController, GenericTableControllerDelegate {
    // Works OK
    func controller<T>(controller: GenericTableController<T>, didSelect value: T) {
        if let value = value as? NSObject {
            // Requires unwrapping and casting
        }
    }
}

Client of the SpecializedTableController, with "where" requirement - the only problem that it doesn't compile

final class AnotherClientOfTableController: UIViewController, GenericTableControllerDelegate {
    // Works OK
    func controller<T>(controller: GenericTableController<T>, didSelect value: T) where T: NSObject {
        // `value` is String
    }
}

Type 'AnotherClientOfTableController' does not conform to protocol
  'GenericTableControllerDelegate' Do you want to add protocol stubs?

Is there a way to have a protocol with a generic method and being able to have a concrete (specialized) type in that method implementation?

Are there close alternatives achieving satisfying similar requirement (having a generic class but being able to handle a concrete type in the delegate callback)?

Body:
I don't think this is doable in a sense you want it. The closest would be combining with subclass. Consider the following:

protocol MagicProtocol {
    func dooMagic<T>(_ trick: T)
}

class Magician<TrickType> {
    private let listener: MagicProtocol
    private let tricks: [TrickType]
    init(listener: MagicProtocol, tricks: [TrickType]) { self.listener = listener; self.tricks = tricks }
    func abracadabra() { listener.dooMagic(tricks.randomElement()) }
}

class Audience<DataType>: MagicProtocol {

    var magician: Magician<DataType>?

    init() {
        magician?.abracadabra()
    }

    func doExplicitMagic(_ trick: DataType) {

    }

    func dooMagic<T>(_ trick: T) {
        doExplicitMagic(trick as! DataType)
    }

}

Now I can create a subclass and restrict it to some type:

class IntegerAudience: Audience<Int> {

    override func doExplicitMagic(_ trick: Int) {
        print("This works")
    }

}

The problem is that there is no correlation between the 2 generics. So at some point a cast must be done. Here we do it in protocol method:

doExplicitMagic(trick as! DataType)

it seems like this is pretty safe and it could never crash but if you look a bit closer we could do this:

func makeThingsGoWrong() {
    let myAudience = IntegerAudience()
    let evilMagician = Magician(listener: myAudience, tricks: ["Time to burn"])
    evilMagician.abracadabra() // This should crash the app
}

Here myAudience corresponds to protocol MagicProtocol which may not be restricted to generic. But myAudience is restricted to Int. Nothing is stopping the compiler but if it did, what would the error be?

Anyway, it works as long as you use it correctly. If you don't then it will crash. You could do an optional unwrap but I am not sure it is appropriate.


问:
Legend in ggplotly doesnt display all the values
I have created the following dataframe

```<code>  ##### TOY SET
  DF1<-data.frame("Sl_NO"= c(1:70))

 DF1$ID<-paste0("A_1234_2345_3456_4567_7777", as.character(DF1$Sl_NO))

  DF1$Value<-DF1$Sl_NO
</code>```

Next I Create 2 more dataframes with the following changes

```<code>  DF2<-DF1
  DF2$Value<-DF1$Sl_NO*1.5
  DF3<-DF1
  DF3$Value<-DF3$Sl_NO*1.25
</code>```

Next we rbind the dataframes

```<code>    DFmain<-rbind(DF1, DF2, DF3)
    library(ggplot2)
</code>```

Create a plot with ggplot

```<code>     p<-ggplot(data = DFmain)+geom_line(aes(x = Sl_NO, y = Value, color=ID))
     p
     library(plotly)
     ggplotly(p, dynamicTicks = T)
</code>```

When I run the plot, p runs and all the legend entries are visible. When I run the part with ggplotly, the legend appears as a scroll down but the number of legend items is less than the number of plotted lines.
Is there a way to ensure all the legend entries are visible. Request someone to help

答: I get length(unique(DFmain$ID)) = 70 and I can see 70 items in the legend. I visualize the plot in Chrome. Probably you get an issue because you visualize in RStudio. It's better to use a browser like Chrome.

Body:
I have created the following dataframe

  ##### TOY SET
  DF1<-data.frame("Sl_NO"= c(1:70))

 DF1$ID<-paste0("A_1234_2345_3456_4567_7777", as.character(DF1$Sl_NO))

  DF1$Value<-DF1$Sl_NO

Next I Create 2 more dataframes with the following changes

  DF2<-DF1
  DF2$Value<-DF1$Sl_NO*1.5
  DF3<-DF1
  DF3$Value<-DF3$Sl_NO*1.25

Next we rbind the dataframes

    DFmain<-rbind(DF1, DF2, DF3)
    library(ggplot2)

Create a plot with ggplot

     p<-ggplot(data = DFmain)+geom_line(aes(x = Sl_NO, y = Value, color=ID))
     p
     library(plotly)
     ggplotly(p, dynamicTicks = T)

When I run the plot, p runs and all the legend entries are visible. When I run the part with ggplotly, the legend appears as a scroll down but the number of legend items is less than the number of plotted lines.
Is there a way to ensure all the legend entries are visible. Request someone to help


问:
What those F# functions are supposed to do?
Learning F# these days, I've noticed that in some libraries like this one or that one
there are some similar functions which seem to be common in F# but can't really decipher them, what are they doing, what are they for?

let ap x f =
    match f, x with
    | Ok f        , Ok x    -> Ok (f x)
    | Error e     , _       -> Error e
    | _           , Error e -> Error e
let inline (<*>) f x = ap x f
let inline (<!>) f x = Result.map f x
let inline lift2 f a b = f <!> a <*> b
```

<p>Even aggregating comments with them does not really help in my understanding:</p>

<pre class="lang-ml prettyprint-override"><code>/// Sequential application
/// If the wrapped function is a success and the given result is a success the function is applied on the value.
/// Otherwise the exisiting error messages are propagated.
let ap x f =
match f,x with
    | Ok f        , Ok x    -> Ok (f x)
    | Error e     , _       -> Error e
    | _           , Error e -> Error e

/// Sequential application
/// If the wrapped function is a success and the given result is a success the function is applied on the value.
/// Otherwise the exisiting error messages are propagated.
let inline (<*>) f x = ap x f

/// Infix map, lifts a function into a Result and applies it on the given result.
let inline (<!>) f x = Result.map f x

/// Promote a function to a monad/applicative, scanning the monadic/applicative arguments from left to right.
let inline lift2 f a b = f <!> a <*> b
</code>```

I don't even see an example of how they could be used, not sure also why inline has been used.

If there is somebody who could hint about how useful those functions are, I would greatly appreciate.

答:
Scott Wlaschin's F# for fun and profit (https://fsharpforfunandprofit.com) has a series Map and Bind and Apply, Oh my! (https://fsharpforfunandprofit.com/posts/elevated-world-7) which should be able to shed more light on this. Regarding your particular question:

<!> is the map operator which applies a function f and a parameter x to elements of the data structure you are mapping over, or in other words, lifts the function into the realm of the data structure, in this case the Result type.

<*> is the ap (apply) operator which unpacks a function wrapped inside a elevated value into a lifted function.

lift2 is basically the map operator for a two-parameter function.

Please have a look at the blog, it really helps!

Body:
Learning F# these days, I've noticed that in some libraries like this one or that one
there are some similar functions which seem to be common in F# but can't really decipher them, what are they doing, what are they for?

let ap x f =
    match f, x with
    | Ok f        , Ok x    -> Ok (f x)
    | Error e     , _       -> Error e
    | _           , Error e -> Error e
let inline (<*>) f x = ap x f
let inline (<!>) f x = Result.map f x
let inline lift2 f a b = f <!> a <*> b

Even aggregating comments with them does not really help in my understanding:

/// Sequential application
/// If the wrapped function is a success and the given result is a success the function is applied on the value.
/// Otherwise the exisiting error messages are propagated.
let ap x f =
match f,x with
    | Ok f        , Ok x    -> Ok (f x)
    | Error e     , _       -> Error e
    | _           , Error e -> Error e

/// Sequential application
/// If the wrapped function is a success and the given result is a success the function is applied on the value.
/// Otherwise the exisiting error messages are propagated.
let inline (<*>) f x = ap x f

/// Infix map, lifts a function into a Result and applies it on the given result.
let inline (<!>) f x = Result.map f x

/// Promote a function to a monad/applicative, scanning the monadic/applicative arguments from left to right.
let inline lift2 f a b = f <!> a <*> b

I don't even see an example of how they could be used, not sure also why inline has been used.

If there is somebody who could hint about how useful those functions are, I would greatly appreciate.


问:
Default size for database fields
What the size that you use for common database fields, like firstName, lastName, Email, password, etc? I see these common fields in a lot of databases of blogs, forums, e-commerces, etc. But I don't know if there is some reference or default for the size for that common fields. So, I want to know what the method/reference/basis that you to use for selecting size for common fields.</p>

OwnerDisplayName: Click Ok

ContentLicense: CC BY-SA 2.5

Title: Default size for database fields

Body: i like 16, 32, 64, 128, or 256

OwnerDisplayName: Steven A. Lowe


问:
How can I fix a "NoMethodError" exception?
I'm getting this error:

```<code>NoMethodError in Videos#index

Showing /rubyprograms/dreamstill/app/views/videos/index.html.erb where line #12 raised:

undefined method `upvoted_videos' for nil:NilClass
Extracted source (around line #12):

9: <div class="home_options">
10:     <ul class="home_options_list">
11:         <li> <%= link_to "Top Songs", videos_path, :class => "top_songs  chosen_home_option" %> </li>
12:         <li> <%= link_to "#{pluralize(current_user.upvoted_videos.count, 'Upvoted Song')}", upvoted_videos_path, :action => "upvoted_songs", :class => "upvoted_songs" %> </li>
</code>```

This is in my user model:

```<code>def upvoted_videos
  self.voted_videos.where("value = 1")
end
</code>```

答:
Whenever you get a NoMethodError always just go to check why, and it says that you are trying to call something on a nil object.
This means you must not have a current_user before doing this operation, so make sure someone is signed in.

Also it is good practice to have a fallback on functions like this, like a
<% unless current_user.nil? %> ...(Do function here)... <% end %>
or something in the view

ContentLicense: CC BY-SA 3.0

Body:
I'm getting this error:

NoMethodError in Videos#index

Showing /rubyprograms/dreamstill/app/views/videos/index.html.erb where line #12 raised:

undefined method `upvoted_videos' for nil:NilClass
Extracted source (around line #12):

9:

10:

11:
 <%= link_to "Top Songs", videos_path, :class => "top_songs  chosen_home_option" %>

12:
 <%= link_to "#{pluralize(current_user.upvoted_videos.count, 'Upvoted Song')}", upvoted_videos_path, :action => "upvoted_songs", :class => "upvoted_songs" %>

This is in my user model:

def upvoted_videos
  self.voted_videos.where("value = 1")
end


问:
odp.net Add-Type error in Powershell
I'm trying to connect to a remote Oracle database on a RHEL node using Oracle.ManagedDataAccess.dll. But when I try to reference the dll using Add-Type I get the following:

Add-Type : Could not load file or assembly Oracle.ManagedDataAccessDTC.dll' or one of its dependencies. This assembly is built by a runtime newer than the currently loaded runtime and cannot be loaded.

The server is running on Windows Server 2008R2, my Powershell version is 2.0, and my odp.net dll is ODP.NET_Managed12.1.0.2.160719

Additional info: I am referencing the .dll from a NAS, the dll does not reside on the server.

What version of odp.net should I be using? Or what dependency am I missing? Any insight on this would be greatly appreciated.

Thanks!

答:
"This assembly is built by a runtime newer..."

Try installing a new version of PowerShell.

With PowerShell 5.1 I have installed .Net version 4.5.2

But now I have another error "Could not load file or assembly"... I'm working on it ;-)

Title: odp.net Add-Type error in Powershell


问:
how to filter all string sequence in array using javascript
I have a large array, and I want to filter it based on a string I pass it. This string could be one or two characters, up to an entire string.

Here's an example array:

```<code>var data = ["bourbon", "beer", "electric"]
</code>```

If I pass e, I want the result ["electric", "beer"].

How can I achieve this functionality?

答:
```<code>products_name = ['ebay','eaby','ebb','ebbe','eaab','eeb']
search_options = []
const searched_word = "eb";
for (const key in products_name)
{
    const search_count = products_name[key].search(new RegExp(searched_word, "i"));
    if (search_count != -1)
    {
        search_options.push(products_name[key])
    }
}
console.log(search_options)
</code>```

Body:
I have a large array, and I want to filter it based on a string I pass it. This string could be one or two characters, up to an entire string.

Here's an example array:

var data = ["bourbon", "beer", "electric"]

If I pass e, I want the result ["electric", "beer"].

How can I achieve this functionality?


问:
How to Color Code Gridview based on date values
I would like to allow my Gridview control to display various colours based on conditions. A person has a date for a medical. I want the gridview to show a green color when the day has arrived. I want the date to show red when one day has passed on from the due date and orange like 7 days before the medical date. I have only managed to fix it for the green color which shows the medical on the day but I am having difficulties for the other conditions.

This is what i currently have. The first part of the If Statement works when i change the row to green based on the due date and the current date that is equal but I do not know how to set the if statement for the other conditions mentioned above. Please assist

```<code> If e.Row.RowType = DataControlRowType.DataRow Then

            Dim row As DataRow = (CType(e.Row.DataItem, DataRowView)).Row
            Dim DueDate As DateTime = row.Field(Of DateTime)(7)

            If DueDate.Date = DateTime.Today Then

                e.Row.Cells(0).BackColor = System.Drawing.Color.Green
                e.Row.Cells(0).ForeColor = System.Drawing.Color.White

                e.Row.Cells(1).BackColor = System.Drawing.Color.Green
                e.Row.Cells(1).ForeColor = System.Drawing.Color.White

                e.Row.Cells(2).BackColor = System.Drawing.Color.Green
                e.Row.Cells(2).ForeColor = System.Drawing.Color.White

                e.Row.Cells(3).BackColor = System.Drawing.Color.Green
                e.Row.Cells(3).ForeColor = System.Drawing.Color.White

                e.Row.Cells(4).BackColor = System.Drawing.Color.Green
                e.Row.Cells(4).ForeColor = System.Drawing.Color.White

                e.Row.Cells(5).BackColor = System.Drawing.Color.Green
                e.Row.Cells(5).ForeColor = System.Drawing.Color.White

                e.Row.Cells(6).BackColor = System.Drawing.Color.Green
                e.Row.Cells(6).ForeColor = System.Drawing.Color.White

                e.Row.Cells(7).BackColor = System.Drawing.Color.Green
                e.Row.Cells(7).ForeColor = System.Drawing.Color.White

                e.Row.Cells(8).BackColor = System.Drawing.Color.Green
                e.Row.Cells(8).ForeColor = System.Drawing.Color.White

                e.Row.Cells(9).BackColor = System.Drawing.Color.Green
                e.Row.Cells(9).ForeColor = System.Drawing.Color.White

                e.Row.Cells(10).BackColor = System.Drawing.Color.Green
                e.Row.Cells(10).ForeColor = System.Drawing.Color.White

                e.Row.Cells(11).BackColor = System.Drawing.Color.Green
                e.Row.Cells(11).ForeColor = System.Drawing.Color.White

                e.Row.Cells(12).BackColor = System.Drawing.Color.Green
                e.Row.Cells(12).ForeColor = System.Drawing.Color.White

                e.Row.Cells(13).BackColor = System.Drawing.Color.Green
                e.Row.Cells(13).ForeColor = System.Drawing.Color.White

            ElseIf Day(DateTime.Now) > 1 Then

                e.Row.Cells(0).BackColor = System.Drawing.Color.Orange
                e.Row.Cells(0).ForeColor = System.Drawing.Color.White

                e.Row.Cells(1).BackColor = System.Drawing.Color.Orange
                e.Row.Cells(1).ForeColor = System.Drawing.Color.White

                e.Row.Cells(2).BackColor = System.Drawing.Color.Orange
                e.Row.Cells(2).ForeColor = System.Drawing.Color.White

                e.Row.Cells(3).BackColor = System.Drawing.Color.Orange
                e.Row.Cells(3).ForeColor = System.Drawing.Color.White

                e.Row.Cells(4).BackColor = System.Drawing.Color.Orange
                e.Row.Cells(4).ForeColor = System.Drawing.Color.White

                e.Row.Cells(5).BackColor = System.Drawing.Color.Orange
                e.Row.Cells(5).ForeColor = System.Drawing.Color.White

                e.Row.Cells(6).BackColor = System.Drawing.Color.Orange
                e.Row.Cells(6).ForeColor = System.Drawing.Color.White

                e.Row.Cells(7).BackColor = System.Drawing.Color.Orange
                e.Row.Cells(7).ForeColor = System.Drawing.Color.White

                e.Row.Cells(8).BackColor = System.Drawing.Color.Orange
                e.Row.Cells(8).ForeColor = System.Drawing.Color.White

                e.Row.Cells(9).BackColor = System.Drawing.Color.Orange
                e.Row.Cells(9).ForeColor = System.Drawing.Color.White

                e.Row.Cells(10).BackColor = System.Drawing.Color.Orange
                e.Row.Cells(10).ForeColor = System.Drawing.Color.White

                e.Row.Cells(11).BackColor = System.Drawing.Color.Orange
                e.Row.Cells(11).ForeColor = System.Drawing.Color.White

                e.Row.Cells(12).BackColor = System.Drawing.Color.Orange
                e.Row.Cells(12).ForeColor = System.Drawing.Color.White

                e.Row.Cells(13).BackColor = System.Drawing.Color.Orange
                e.Row.Cells(13).ForeColor = System.Drawing.Color.White

            End If

        End If

</code>```

答:
Use a for loop 0 to 13 and remove your repetitions or color the whole row

to get a date which is 7 days later and check if sooner, compare to  date.Now.addDays(7)

to check if day passed, use date.Now.addDays(-1)

Body:
I would like to allow my Gridview control to display various colours based on conditions. A person has a date for a medical. I want the gridview to show a green color when the day has arrived. I want the date to show red when one day has passed on from the due date and orange like 7 days before the medical date. I have only managed to fix it for the green color which shows the medical on the day but I am having difficulties for the other conditions.

This is what i currently have. The first part of the If Statement works when i change the row to green based on the due date and the current date that is equal but I do not know how to set the if statement for the other conditions mentioned above. Please assist

 If e.Row.RowType = DataControlRowType.DataRow Then

            Dim row As DataRow = (CType(e.Row.DataItem, DataRowView)).Row
            Dim DueDate As DateTime = row.Field(Of DateTime)(7)

            If DueDate.Date = DateTime.Today Then

                e.Row.Cells(0).BackColor = System.Drawing.Color.Green
                e.Row.Cells(0).ForeColor = System.Drawing.Color.White

                e.Row.Cells(1).BackColor = System.Drawing.Color.Green
                e.Row.Cells(1).ForeColor = System.Drawing.Color.White

                e.Row.Cells(2).BackColor = System.Drawing.Color.Green
                e.Row.Cells(2).ForeColor = System.Drawing.Color.White

                e.Row.Cells(3).BackColor = System.Drawing.Color.Green
                e.Row.Cells(3).ForeColor = System.Drawing.Color.White

                e.Row.Cells(4).BackColor = System.Drawing.Color.Green
                e.Row.Cells(4).ForeColor = System.Drawing.Color.White

                e.Row.Cells(5).BackColor = System.Drawing.Color.Green
                e.Row.Cells(5).ForeColor = System.Drawing.Color.White

                e.Row.Cells(6).BackColor = System.Drawing.Color.Green
                e.Row.Cells(6).ForeColor = System.Drawing.Color.White

                e.Row.Cells(7).BackColor = System.Drawing.Color.Green
                e.Row.Cells(7).ForeColor = System.Drawing.Color.White

                e.Row.Cells(8).BackColor = System.Drawing.Color.Green
                e.Row.Cells(8).ForeColor = System.Drawing.Color.White

                e.Row.Cells(9).BackColor = System.Drawing.Color.Green
                e.Row.Cells(9).ForeColor = System.Drawing.Color.White

                e.Row.Cells(10).BackColor = System.Drawing.Color.Green
                e.Row.Cells(10).ForeColor = System.Drawing.Color.White

                e.Row.Cells(11).BackColor = System.Drawing.Color.Green
                e.Row.Cells(11).ForeColor = System.Drawing.Color.White

                e.Row.Cells(12).BackColor = System.Drawing.Color.Green
                e.Row.Cells(12).ForeColor = System.Drawing.Color.White

                e.Row.Cells(13).BackColor = System.Drawing.Color.Green
                e.Row.Cells(13).ForeColor = System.Drawing.Color.White

            ElseIf Day(DateTime.Now) > 1 Then

                e.Row.Cells(0).BackColor = System.Drawing.Color.Orange
                e.Row.Cells(0).ForeColor = System.Drawing.Color.White

                e.Row.Cells(1).BackColor = System.Drawing.Color.Orange
                e.Row.Cells(1).ForeColor = System.Drawing.Color.White

                e.Row.Cells(2).BackColor = System.Drawing.Color.Orange
                e.Row.Cells(2).ForeColor = System.Drawing.Color.White

                e.Row.Cells(3).BackColor = System.Drawing.Color.Orange
                e.Row.Cells(3).ForeColor = System.Drawing.Color.White

                e.Row.Cells(4).BackColor = System.Drawing.Color.Orange
                e.Row.Cells(4).ForeColor = System.Drawing.Color.White

                e.Row.Cells(5).BackColor = System.Drawing.Color.Orange
                e.Row.Cells(5).ForeColor = System.Drawing.Color.White

                e.Row.Cells(6).BackColor = System.Drawing.Color.Orange
                e.Row.Cells(6).ForeColor = System.Drawing.Color.White

                e.Row.Cells(7).BackColor = System.Drawing.Color.Orange
                e.Row.Cells(7).ForeColor = System.Drawing.Color.White

                e.Row.Cells(8).BackColor = System.Drawing.Color.Orange
                e.Row.Cells(8).ForeColor = System.Drawing.Color.White

                e.Row.Cells(9).BackColor = System.Drawing.Color.Orange
                e.Row.Cells(9).ForeColor = System.Drawing.Color.White

                e.Row.Cells(10).BackColor = System.Drawing.Color.Orange
                e.Row.Cells(10).ForeColor = System.Drawing.Color.White

                e.Row.Cells(11).BackColor = System.Drawing.Color.Orange
                e.Row.Cells(11).ForeColor = System.Drawing.Color.White

                e.Row.Cells(12).BackColor = System.Drawing.Color.Orange
                e.Row.Cells(12).ForeColor = System.Drawing.Color.White

                e.Row.Cells(13).BackColor = System.Drawing.Color.Orange
                e.Row.Cells(13).ForeColor = System.Drawing.Color.White

            End If

        End If


问:
Is it possible to display latest comment I made in issues globally in github using web ui?
I've added a few comments on issues that bothers me in a few repositories. I'd like to search for them. Is it possible to find them using github web ui ?</p>

答: Click on the top right bell icon (notifications), then go to the tab Subscriptions. You should be able to find your stuff there.


问:
Sqlite .all() function returns a promise, but I need the database items...?
I'm new to NodeJS, and I'm trying to learn it by building a Shopping cart web app. I'm storing the data in an SQLite database but I can't seem to access it. The .all() method returns a Promise object and I can't figure out how to obtain the items in the database instead.

I followed this tutorial: https://stackabuse.com/a-sqlite-tutorial-with-node-js/ to build a data access object and two models: ItemRepository and CartRepository.

This is the get method in my data access object script:

```<code>get(sql, params = []) {
    return new Promise((resolve, reject) => {
      this.db.get(sql, params, (err, result) => {
        if (err) {
          console.log('Error running sql: ' + sql)
          console.log(err)
          reject(err)
        } else {
          resolve(result)
        }
      })
  }
</code>```

And this is my index.js

```<code>router.get('/', function(req, res, next) {
    var dao = new AppDAO('./database.sqlite3');
  var itemRepo = new ItemRepository(dao);
  var cartRepo = new CartRepository(dao);
  items = itemRepo.getAll();
  console.log(items);
  var itemRows = [];
  var rowSize = 3;
  for (var i = 0; i < items.length; i += rowSize){
    itemRows.push(items.slice(i, i+rowSize));
  }
  res.render('shop/index', { title: 'sHOP', items: itemRows })

});
</code>```

I'm a little lost as for how to get the table's content and not the Promise object.

答:
I will recommend you to read promises and async/await or bluebird promises. you will need to use then method on promise to get the actual result as below.

```<code>router.get('/', function(req, res, next) {
var dao = new AppDAO('./database.sqlite3');
var itemRepo = new ItemRepository(dao);
var cartRepo = new CartRepository(dao);
itemRepo.getAll().then(( items) =>{
   console.log(items);
   var itemRows = [];
   var rowSize = 3;
   for (var i = 0; i < items.length; i += rowSize){
    itemRows.push(items.slice(i, i+rowSize));
     }
    res.render('shop/index', { title: 'sHOP', items: itemRows })
   })
});
</code>```

Body:
I'm new to NodeJS, and I'm trying to learn it by building a Shopping cart web app. I'm storing the data in an SQLite database but I can't seem to access it. The .all() method returns a Promise object and I can't figure out how to obtain the items in the database instead.

I followed this tutorial: https://stackabuse.com/a-sqlite-tutorial-with-node-js/ to build a data access object and two models: ItemRepository and CartRepository.

This is the get method in my data access object script:

get(sql, params = []) {
    return new Promise((resolve, reject) => {
      this.db.get(sql, params, (err, result) => {
        if (err) {
          console.log('Error running sql: ' + sql)
          console.log(err)
          reject(err)
        } else {
          resolve(result)
        }
      })
  }

And this is my index.js

router.get('/', function(req, res, next) {
    var dao = new AppDAO('./database.sqlite3');
  var itemRepo = new ItemRepository(dao);
  var cartRepo = new CartRepository(dao);
  items = itemRepo.getAll();
  console.log(items);
  var itemRows = [];
  var rowSize = 3;
  for (var i = 0; i < items.length; i += rowSize){
    itemRows.push(items.slice(i, i+rowSize));
  }
  res.render('shop/index', { title: 'sHOP', items: itemRows })

});

I'm a little lost as for how to get the table's content and not the Promise object.

Body:
I will recommend you to read promises and async/await or bluebird promises. you will need to use then method on promise to get the actual result as below.

router.get('/', function(req, res, next) {
var dao = new AppDAO('./database.sqlite3');
var itemRepo = new ItemRepository(dao);
var cartRepo = new CartRepository(dao);
itemRepo.getAll().then(( items) =>{
   console.log(items);
   var itemRows = [];
   var rowSize = 3;
   for (var i = 0; i < items.length; i += rowSize){
    itemRows.push(items.slice(i, i+rowSize));
     }
    res.render('shop/index', { title: 'sHOP', items: itemRows })
   })
});


问:
Experiences deploying ASP.NET 3.5 web site with charting control
Has anyone deployed a web site using the 3.5 framework and the Microsoft charting control?

I know this is built into .NET 4.0, but our client isn't ready to move up to the .NET 4.0 yet.

Specifically, do you need to run the chart install on the server to deploy the control, or is there a way to do this in the deployment (such as dropping the System.Web.DataVisualization [sp?] dll into the BIN directory and updating Web.config?

Thanks,
Tim

EDIT:
I want to add we're using VS 2010 as our IDE...has anyone used the chart control while targeting the 3.5 .NET framework?

答:
I have not used the controls myself so I don't now what major differences there are between versions, if any, but you can try using the .NET 3.5 version of the charting controls.

Edit: You should be able to add the .NET 3.5 control to the VS 2010 Toolbox manually, if it isn't added automatically using the instructions on MSDN.


问:
MySQL correct statement for "update all rows where column > number"?
I have a table called 'images' with a few rows of image names and a value for their position (order which they will appear on site).

```<code>id      name       position
1       dog.png    3
2       cat.png    1
3       snake.png  2
</code>```

What im trying to do is decrement all position column values if they are above a specific value.

For example, if 'cat' is to be deleted, i want to find all rows with a position higher (would be snake and dog) and decrement their position values by 1. I need an SQL statement for

"update all 'position' columns where 'position' > 'value'"

I know i need to get the 'position' of the image to be deleted, and set this to 'value' before updating the rest of the rows with higher position columns. But, I'm not sure how to create the SQL statement for the rest of:

"update all 'position' columns where 'position' > 'value'"

I'm not sure whether i would need one or two queries for it.

答:
I would use a trigger : </p>

```<code>DELIMITER //

CREATE TRIGGER position_after_delete
AFTER DELETE
   ON images FOR EACH ROW

BEGIN

   -- Update position
   UPDATE images SET position = position - 1 WHERE position > OLD.position

END; //

DELIMITER ;
</code>```

Body:
I have a table called 'images' with a few rows of image names and a value for their position (order which they will appear on site).

id      name       position
1       dog.png    3
2       cat.png    1
3       snake.png  2

What im trying to do is decrement all position column values if they are above a specific value.

For example, if 'cat' is to be deleted, i want to find all rows with a position higher (would be snake and dog) and decrement their position values by 1. I need an SQL statement for

"update all 'position' columns where 'position' > 'value'"

I know i need to get the 'position' of the image to be deleted, and set this to 'value' before updating the rest of the rows with higher position columns. But, I'm not sure how to create the SQL statement for the rest of:

"update all 'position' columns where 'position' > 'value'"

I'm not sure whether i would need one or two queries for it.

Body:
I would use a trigger :

DELIMITER //

CREATE TRIGGER position_after_delete
AFTER DELETE
   ON images FOR EACH ROW

BEGIN

   -- Update position
   UPDATE images SET position = position - 1 WHERE position > OLD.position

END; //

DELIMITER ;


问:
Why does not save the chart in PNG format with html2canvas and canvas2image?
Why does not save the chart in PNG format with html2canvas and canvas2image? This is link for my code

```<code><div class="canvas__container" style="width:100%; height:100%">
<button id="btnSave" title="Save as PNG" style="position: absolute; left: 4px; top: 4px;">Save</button>
<div id="myChart1"></div>
</div>

<script src="//cdnjs.cloudflare.com/ajax/libs/d3/4.7.2/d3.min.js"></script>
<script src="//cdn.jsdelivr.net/npm/d3pie@0.2.1/d3pie/d3pie.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script src="//github.com/niklasvh/html2canvas/releases/download/0.4.1/html2canvas.js"></script>
<script src="//superal.github.io/canvas2image/canvas2image.js"></script>
<script>
$(function() {
    $("#btnSave").click(function() {
        html2canvas($("#myChart1"), {
            onrendered: function (canvas) {
                Canvas2Image.saveAsPNG(canvas, canvas.width, canvas.height, "Image_" + Date.now());
            }
        });
    });
});
</script>
</code>```

答:
I've found the solution. Because d3pie uses the svg tag, you must use saveSvgAsPng.js to save the diagram. solution</p>

```<code><div class="canvas__container" style="width:100%; height:100%">
<button id="btnSave" title="Save as PNG" style="position: absolute; left: 4px; top: 4px;">Save</button>
<div id="myChart1"></div>
</div>

<script src="//cdnjs.cloudflare.com/ajax/libs/d3/4.7.2/d3.min.js"></script>
<script src="//cdn.jsdelivr.net/npm/d3pie@0.2.1/d3pie/d3pie.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="//exupero.org/saveSvgAsPng/src/saveSvgAsPng.js"></script>
<script>
$(function() {
    $("#btnSave").click(function() {
        saveSvgAsPng(document.getElementById("myChart1").getElementsByTagName("svg")[0], "plot_" + Date.now(), {scale: 2, backgroundColor: "#FFFFFF"});
    });
});
</script>
</code>```

Body:
Why does not save the chart in PNG format with html2canvas and canvas2image? This is link for my code

<button id="btnSave" title="Save as PNG" style="position: absolute; left: 4px; top: 4px;">Save</button>

Body:
I've found the solution. Because d3pie uses the svg tag, you must use saveSvgAsPng.js to save the diagram. solution

<div class="canvas__container" style="width:100%; height:100%">
<button id="btnSave" title="Save as PNG" style="position: absolute; left: 4px; top: 4px;">Save</button>
<div id="myChart1"></div>
</div>

<script src="//cdnjs.cloudflare.com/ajax/libs/d3/4.7.2/d3.min.js"></script>
<script src="//cdn.jsdelivr.net/npm/d3pie@0.2.1/d3pie/d3pie.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="//exupero.org/saveSvgAsPng/src/saveSvgAsPng.js"></script>
<script>
$(function() {
    $("#btnSave").click(function() {
        saveSvgAsPng(document.getElementById("myChart1").getElementsByTagName("svg")[0], "plot_" + Date.now(), {scale: 2, backgroundColor: "#FFFFFF"});
    });
});
</script>


问:
Unity exceptions on load texture with WWW
I need to download an image from a server and show in sprite. All example I can find recommended next code:

```<code>WWW www = new WWW(requestUrl);
yield return www;
onTextureLoaded(www.texture,id);
</code>```

But I can't find the way how to handle exceptions in this case. Should I add Try catch? Or is there any way to check if the request was successful?

答:
```<code>System.Collections.IEnumerator GetRemoteTexture ( string url )
{
    using( var www = UnityEngine.Networking.UnityWebRequestTexture.GetTexture( url ) )
    {
        //begin request:
        var asyncOp = www.SendWebRequest();

        //await until it's done:
        var hz30 = new WaitForSecondsRealtime( 1f/30f );
        while( asyncOp.isDone==false )
        {
            yield return hz30;
        }

        //read results:
        if( www.isNetworkError || www.isHttpError )
        {
            //log error:
            #if DEBUG
            Debug.Log( $"{ www.error }, URL:{ www.url }" );
            #endif
        }
        else
        {
            //success:
            Texture2D texture = UnityEngine.Networking.DownloadHandlerTexture.GetContent( www );

            //> DO SOMETHING WITH THIS TEXTURE HERE <

        }
    }
}
</code>```

PRO version: https://stackoverflow.com/a/53770838/2528943

Body:
I need to download an image from a server and show in sprite. All example I can find recommended next code:

WWW www = new WWW(requestUrl);
yield return www;
onTextureLoaded(www.texture,id);

But I can't find the way how to handle exceptions in this case. Should I add Try catch? Or is there any way to check if the request was successful?

Body:
System.Collections.IEnumerator GetRemoteTexture ( string url )
{
    using( var www = UnityEngine.Networking.UnityWebRequestTexture.GetTexture( url ) )
    {
        //begin request:
        var asyncOp = www.SendWebRequest();

        //await until it's done:
        var hz30 = new WaitForSecondsRealtime( 1f/30f );
        while( asyncOp.isDone==false )
        {
            yield return hz30;
        }

        //read results:
        if( www.isNetworkError || www.isHttpError )
        {
            //log error:
            #if DEBUG
            Debug.Log( $"{ www.error }, URL:{ www.url }" );
            #endif
        }
        else
        {
            //success:
            Texture2D texture = UnityEngine.Networking.DownloadHandlerTexture.GetContent( www );

            //> DO SOMETHING WITH THIS TEXTURE HERE <

        }
    }
}

PRO version: https://stackoverflow.com/a/53770838/2528943


问:
Print multiple row outputs in csv file
Suppose

```<code>A='First'
B='Random'
C='Degree'
D='Largest'

A='Second'
B='Odd'
C='Inclined'
D='Maximum'

A='Third'
B='Even'
C='Steep'
D='Smallest'

A='Fourth'
B='Prime'
C='Gradient'
D='Minimum'

c = ['Group', 'Number', 'Angle', 'Max value']

df = pd.DataFrame([[A, B, C, D]], columns=c)
print (df)

#to csv
df.to_csv('Output.csv', encoding='utf-8', index=False)

</code>```

Actual Output:

It is showing only the last output, instead of each and every value. Like this if there are N values, the csv  must store all the N values one below each other

```<code>Group  Number Angle    Max Value
Fourth Prime  Gradient Minimum
</code>```

Expected Output:

答:
you can go with the following code,

```<code>import pandas as pd

data = [
    ['First', 'Random', 'Degree', 'Largest'],
    ['Second', 'Odd', 'Inclined', 'Maximum'],
    ['Third', 'Even', 'Steep', 'Smallest'],
    ['Fourth', 'Prime', 'Gradient', 'Minimum']
]

c = ['Group', 'Number', 'Angle', 'Max value']

df = pd.DataFrame(data, columns=c)
print (df)

df.to_csv('Output.csv', encoding='utf-8', index=False)
</code>```

and the output is

Also the CSV file you get

Title: Print multiple row outputs in csv file

Body:
Suppose

A='First'
B='Random'
C='Degree'
D='Largest'

A='Second'
B='Odd'
C='Inclined'
D='Maximum'

A='Third'
B='Even'
C='Steep'
D='Smallest'

A='Fourth'
B='Prime'
C='Gradient'
D='Minimum'

c = ['Group', 'Number', 'Angle', 'Max value']

df = pd.DataFrame([[A, B, C, D]], columns=c)
print (df)

#to csv
df.to_csv('Output.csv', encoding='utf-8', index=False)

Actual Output:

It is showing only the last output, instead of each and every value. Like this if there are N values, the csv  must store all the N values one below each other

Group  Number Angle    Max Value
Fourth Prime  Gradient Minimum

Expected Output:

Body:
you can go with the following code,

import pandas as pd

data = [
    ['First', 'Random', 'Degree', 'Largest'],
    ['Second', 'Odd', 'Inclined', 'Maximum'],
    ['Third', 'Even', 'Steep', 'Smallest'],
    ['Fourth', 'Prime', 'Gradient', 'Minimum']
]

c = ['Group', 'Number', 'Angle', 'Max value']

df = pd.DataFrame(data, columns=c)
print (df)

df.to_csv('Output.csv', encoding='utf-8', index=False)

and the output is

Also the CSV file you get


问:
Can floating point numbers ending with `.0` be considered as mathematical integers
We all know that using floating point numbers can lead to strange results:

```<code>>>> 0.1*3
0.30000000000000004
</code>```

My question: can all floating point numbers ending with .0 be considered as mathematical integers?

My use case:

```<code>>>> x = 3.4296875
>>> 2*x*(128*x-695)+1856
100.0
</code>```

Is it possible to assert that there is no quirk and that the result is a true and precise 100? I mean without doing the calculation by hand!

Thanks!

答:
Floating point arithmetic is not a quirk magical mess. It is a precise arithmetic (after all, it is a machine which deals with it, not an intoxicated leprechaun). It is just much more complicated or rather much more unknown, than natural numbers or real numbers arithmetic. So short or long, the answer is no.
Even Python, which looks sometimes (too) cool concerning types, is aware of this:

```<code>>>> x = 1+1e-100
>>> x == 1
True
>>> isinstance(x,int)
False
>>> isinstance(x,float)
True
</code>```

The work of William Kahan has been pedagogical enough to make us being aware of all the dangers of tempting short paths.

Body:
We all know that using floating point numbers can lead to strange results:

>>> 0.1*3
0.30000000000000004

My question: can all floating point numbers ending with .0 be considered as mathematical integers?

My use case:

>>> x = 3.4296875
>>> 2*x*(128*x-695)+1856
100.0

Is it possible to assert that there is no quirk and that the result is a true and precise 100? I mean without doing the calculation by hand!

Thanks!

Body:
Floating point arithmetic is not a quirk magical mess. It is a precise arithmetic (after all, it is a machine which deals with it, not an intoxicated leprechaun). It is just much more complicated or rather much more unknown, than natural numbers or real numbers arithmetic. So short or long, the answer is no.
Even Python, which looks sometimes (too) cool concerning types, is aware of this:

>>> x = 1+1e-100
>>> x == 1
True
>>> isinstance(x,int)
False
>>> isinstance(x,float)
True

The work of William Kahan has been pedagogical enough to make us being aware of all the dangers of tempting short paths.


问:
Convert doc to txt
I'm on a Linux server and I need to convert MS Word 97-2003 .doc format to plain text .txt files using PHP

I already tried this solutions:

How to extract text from word file .doc,docx,.xlsx,.pptx php

Extract text from doc and docx

But both are just working fine for .docx format.

The issue is when I convert files, I got scrap characters at the end of the text.
The length of the chars I don't need vary depending on the length of the file.
Also, it may happen that if the file is a bit long, it get truncated.

Is there any simple way to get this converted?

答:
I've lastly come to use the following solution, launching Antiword:</p>

```<code>private function doc() {
    $file = escapeshellarg($this->filename);
    $text = `/usr/sbin/antiword -w 0 $file`;
    return html_entity_decode(utf8_encode(trim($text)));
}
</code>```

Title: Convert doc to txt

Body:
I've lastly come to use the following solution, launching Antiword:

private function doc() {
    $file = escapeshellarg($this->filename);
    $text = `/usr/sbin/antiword -w 0 $file`;
    return html_entity_decode(utf8_encode(trim($text)));
}


问:
Oracle SQL query question
I'm trying to complete this Oracle SQL query with no luck.

"List the department that has the least average cost. (Hint: SELECT  MIN(AVG(cost)) is valid as long as no other column is combined in the SELECT statement. You can combine the above as a subquery with another query)"

I'm able to get it to display the Depts with their average cost, but when I try to work in MIN it breaks. This is what I have so far.

```<code>SELECT DeptNo, AVG(projcost) FROM projects, clinicians WHERE clinicians.Clinicianno = projects.Clinicianno GROUP BY DeptNo;
</code>```

That will give me the depts and their AVG, but when I change AVG(projcost) to be MIN(AVG(projcost) it breaks. The hint is to make it a subquery but I can't figure out how to do that yet. Any help would be much appreciated.

答:
SELECT TOP 1
        DeptNo
       ,AVG(projcost)
    FROM
        projects
       ,clinicians
    WHERE
        clinicians.Clinicianno = projects.Clinicianno
    GROUP BY
        DeptNo
    ORDER BY
        AVG(projcost) ; </p>

Title: Oracle SQL query question

Body:
I'm trying to complete this Oracle SQL query with no luck.

"List the department that has the least average cost. (Hint: SELECT  MIN(AVG(cost)) is valid as long as no other column is combined in the SELECT statement. You can combine the above as a subquery with another query)"

I'm able to get it to display the Depts with their average cost, but when I try to work in MIN it breaks. This is what I have so far.

SELECT DeptNo, AVG(projcost) FROM projects, clinicians WHERE clinicians.Clinicianno = projects.Clinicianno GROUP BY DeptNo;

That will give me the depts and their AVG, but when I change AVG(projcost) to be MIN(AVG(projcost) it breaks. The hint is to make it a subquery but I can't figure out how to do that yet. Any help would be much appreciated.


问:
ApachePoi fails with Font error on OpenJdk 1.8.0_121 Okay on Oracle Jre
The error occurs during initilizing of a org.apache.poi.ss.usermodel.Sheet
Can I fix this to prevent failure on OpenJdk on Linux.

```<code>java.lang.NullPointerException
        at sun.awt.FontConfiguration.getVersion(FontConfiguration.java:1264)
        at sun.awt.FontConfiguration.readFontConfigFile(FontConfiguration.java:219)
        at sun.awt.FontConfiguration.init(FontConfiguration.java:107)
        at sun.awt.X11FontManager.createFontConfiguration(X11FontManager.java:774)
        at sun.font.SunFontManager$2.run(SunFontManager.java:431)
        at java.security.AccessController.doPrivileged(Native Method)
        at sun.font.SunFontManager.<init>(SunFontManager.java:376)
        at sun.awt.FcFontManager.<init>(FcFontManager.java:35)
        at sun.awt.X11FontManager.<init>(X11FontManager.java:57)
        at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
        at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
        at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
        at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
        at java.lang.Class.newInstance(Class.java:442)
        at sun.font.FontManagerFactory$1.run(FontManagerFactory.java:83)
        at java.security.AccessController.doPrivileged(Native Method)
        at sun.font.FontManagerFactory.getInstance(FontManagerFactory.java:74)
        at java.awt.Font.getFont2D(Font.java:491)
        at java.awt.Font.canDisplayUpTo(Font.java:2060)
        at java.awt.font.TextLayout.singleFont(TextLayout.java:470)
        at java.awt.font.TextLayout.<init>(TextLayout.java:531)
        at org.apache.poi.ss.util.SheetUtil.getDefaultCharWidth(SheetUtil.java:275)
        at org.apache.poi.xssf.streaming.AutoSizeColumnTracker.<init>(AutoSizeColumnTracker.java:117)
        at org.apache.poi.xssf.streaming.SXSSFSheet.<init>(SXSSFSheet.java:79)
        at org.apache.poi.xssf.streaming.SXSSFWorkbook.createAndRegisterSXSSFSheet(SXSSFWorkbook.java:656)
        at org.apache.poi.xssf.streaming.SXSSFWorkbook.createSheet(SXSSFWorkbook.java:677)
        at org.apache.poi.xssf.streaming.SXSSFWorkbook.createSheet(SXSSFWorkbook.java:83)
        at com.jthink.songkong.reports.spreadsheet.Worksheet.<init>(Worksheet.java:24)
</code>```

Update

Based on comment no font files found in lib

[root@N1-ZS10 lib]# ls -l

```<code>total 70948
drwxrwxr-x 4 root root     4096 Mar 29 15:09 aarch32
drwxrwxr-x 2 root root     4096 Mar 29 11:28 applet
-rw-rw-r-- 1 root root     2375 Mar 29 11:28 calendars.properties
-rw-rw-r-- 1 root root  3135391 Mar 29 11:28 charsets.jar
-rw-rw-r-- 1 root root    84311 Mar 29 11:28 classlist
drwxrwxr-x 2 root root     4096 Mar 29 15:09 cmm
-rw-rw-r-- 1 root root     5916 Mar 29 11:28 content-types.properties
-r--r--r-- 1 root root     4122 Mar 29 11:28 currency.data
drwxrwxr-x 2 root root     4096 Mar 29 15:09 ext
-rw-rw-r-- 1 root root     3901 Mar 29 11:28 flavormap.properties
-rw-rw-r-- 1 root root    14959 Mar 29 11:28 hijrah-config-umalqura.properties
drwxrwxr-x 3 root root     4096 Mar 29 15:08 images
-rw-rw-r-- 1 root root    95642 Mar 29 11:28 jce.jar
-rwxrwxr-x 1 root root    15917 Mar 29 11:28 jexec
-rw-rw-r-- 1 root root   647046 Mar 29 11:28 jsse.jar
-rw-rw-r-- 1 root root     4226 Mar 29 11:28 jvm.hprof.txt
-rw-rw-r-- 1 root root     2455 Mar 29 11:28 logging.properties
drwxrwxr-x 2 root root     4096 Mar 29 15:09 management
-rw-rw-r-- 1 root root      381 Mar 29 11:28 management-agent.jar
-rw-rw-r-- 1 root root     1922 Mar 29 11:28 meta-index
-rw-rw-r-- 1 root root     4464 Mar 29 11:28 net.properties
-rw-rw-r-- 1 root root     3793 Mar 29 11:28 psfont.properties.ja
-rw-rw-r-- 1 root root    11390 Mar 29 11:28 psfontj2d.properties
-rw-rw-r-- 1 root root  3509545 Mar 29 11:28 resources.jar
-rw-rw-r-- 1 root root 64833198 Mar 29 11:28 rt.jar
drwxrwxr-x 2 root root     4096 Mar 29 15:08 security
-rw-rw-r-- 1 root root     1210 Mar 29 11:28 sound.properties
-rw-rw-r-- 1 root root   104311 Mar 29 11:28 tzdb.dat
</code>```

答:
Just for completeness I add here the answer of Paul Taylor:

Openjdk depends on system fonts of which i had none installed, but I
  found that creating a fonts folder in the jre's lib folder and just
  copyig some fonts into it fixed the problem

see here: stackoverflow.com/questions/43144517/…

Body:
The error occurs during initilizing of a org.apache.poi.ss.usermodel.Sheet
Can I fix this to prevent failure on OpenJdk on Linux.

java.lang.NullPointerException
        at sun.awt.FontConfiguration.getVersion(FontConfiguration.java:1264)
        at sun.awt.FontConfiguration.readFontConfigFile(FontConfiguration.java:219)
        at sun.awt.FontConfiguration.init(FontConfiguration.java:107)
        at sun.awt.X11FontManager.createFontConfiguration(X11FontManager.java:774)
        at sun.font.SunFontManager$2.run(SunFontManager.java:431)
        at java.security.AccessController.doPrivileged(Native Method)
        at sun.font.SunFontManager.<init>(SunFontManager.java:376)
        at sun.awt.FcFontManager.<init>(FcFontManager.java:35)
        at sun.awt.X11FontManager.<init>(X11FontManager.java:57)
        at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
        at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
        at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
        at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
        at java.lang.Class.newInstance(Class.java:442)
        at sun.font.FontManagerFactory$1.run(FontManagerFactory.java:83)
        at java.security.AccessController.doPrivileged(Native Method)
        at sun.font.FontManagerFactory.getInstance(FontManagerFactory.java:74)
        at java.awt.Font.getFont2D(Font.java:491)
        at java.awt.Font.canDisplayUpTo(Font.java:2060)
        at java.awt.font.TextLayout.singleFont(TextLayout.java:470)
        at java.awt.font.TextLayout.<init>(TextLayout.java:531)
        at org.apache.poi.ss.util.SheetUtil.getDefaultCharWidth(SheetUtil.java:275)
        at org.apache.poi.xssf.streaming.AutoSizeColumnTracker.<init>(AutoSizeColumnTracker.java:117)
        at org.apache.poi.xssf.streaming.SXSSFSheet.<init>(SXSSFSheet.java:79)
        at org.apache.poi.xssf.streaming.SXSSFWorkbook.createAndRegisterSXSSFSheet(SXSSFWorkbook.java:656)
        at org.apache.poi.xssf.streaming.SXSSFWorkbook.createSheet(SXSSFWorkbook.java:677)
        at org.apache.poi.xssf.streaming.SXSSFWorkbook.createSheet(SXSSFWorkbook.java:83)
        at com.jthink.songkong.reports.spreadsheet.Worksheet.<init>(Worksheet.java:24)

Update

Based on comment no font files found in lib

[root@N1-ZS10 lib]# ls -l

total 70948
drwxrwxr-x 4 root root     4096 Mar 29 15:09 aarch32
drwxrwxr-x 2 root root     4096 Mar 29 11:28 applet
-rw-rw-r-- 1 root root     2375 Mar 29 11:28 calendars.properties
-rw-rw-r-- 1 root root  3135391 Mar 29 11:28 charsets.jar
-rw-rw-r-- 1 root root    84311 Mar 29 11:28 classlist
drwxrwxr-x 2 root root     4096 Mar 29 15:09 cmm
-rw-rw-r-- 1 root root     5916 Mar 29 11:28 content-types.properties
-r--r--r-- 1 root root     4122 Mar 29 11:28 currency.data
drwxrwxr-x 2 root root     4096 Mar 29 15:09 ext
-rw-rw-r-- 1 root root     3901 Mar 29 11:28 flavormap.properties
-rw-rw-r-- 1 root root    14959 Mar 29 11:28 hijrah-config-umalqura.properties
drwxrwxr-x 3 root root     4096 Mar 29 15:08 images
-rw-rw-r-- 1 root root    95642 Mar 29 11:28 jce.jar
-rwxrwxr-x 1 root root    15917 Mar 29 11:28 jexec
-rw-rw-r-- 1 root root   647046 Mar 29 11:28 jsse.jar
-rw-rw-r-- 1 root root     4226 Mar 29 11:28 jvm.hprof.txt
-rw-rw-r-- 1 root root     2455 Mar 29 11:28 logging.properties
drwxrwxr-x 2 root root     4096 Mar 29 15:09 management
-rw-rw-r-- 1 root root      381 Mar 29 11:28 management-agent.jar
-rw-rw-r-- 1 root root     1922 Mar 29 11:28 meta-index
-rw-rw-r-- 1 root root     4464 Mar 29 11:28 net.properties
-rw-rw-r-- 1 root root     3793 Mar 29 11:28 psfont.properties.ja
-rw-rw-r-- 1 root root    11390 Mar 29 11:28 psfontj2d.properties
-rw-rw-r-- 1 root root  3509545 Mar 29 11:28 resources.jar
-rw-rw-r-- 1 root root 64833198 Mar 29 11:28 rt.jar
drwxrwxr-x 2 root root     4096 Mar 29 15:08 security
-rw-rw-r-- 1 root root     1210 Mar 29 11:28 sound.properties
-rw-rw-r-- 1 root root   104311 Mar 29 11:28 tzdb.dat


问:
msrest.exceptions.ValidationError: Parameter 'resource_group_name' must conform to the following pattern: '^[-\\w\\._\\(\\)]+$'
sathish@Azure:~/quickstart/python-docs-hello-world$ az webapp up -n appname
The command failed with an unexpected error. Here is the traceback:</p>

```<code>Parameter 'resource_group_name' must conform to the following pattern: '^[-\\w\\._\\(\\)]+$'.
Traceback (most recent call last):
  File "/opt/az/lib/python3.6/site-packages/knack/cli.py", line 206, in invoke
    cmd_result = self.invocation.execute(args)
  File "/opt/az/lib/python3.6/site-packages/azure/cli/core/commands/__init__.py", line 326, in execute
    raise ex
  File "/opt/az/lib/python3.6/site-packages/azure/cli/core/commands/__init__.py", line 384, in _run_jobs_serially
    results.append(self._run_job(expanded_arg, cmd_copy))
  File "/opt/az/lib/python3.6/site-packages/azure/cli/core/commands/__init__.py", line 375, in _run_job
    cmd_copy.exception_handler(ex)
  File "/opt/az/lib/python3.6/site-packages/azure/cli/command_modules/appservice/commands.py", line 54, in _polish_bad_errors
    raise ex
  File "/opt/az/lib/python3.6/site-packages/azure/cli/core/commands/__init__.py", line 354, in _run_job
    result = cmd_copy(params)
  File "/opt/az/lib/python3.6/site-packages/azure/cli/core/commands/__init__.py", line 145, in __call__
    return self.handler(*args, **kwargs)
  File "/opt/az/lib/python3.6/site-packages/azure/cli/core/__init__.py", line 451, in default_command_handler
    return op(**command_args)
  File "/opt/az/lib/python3.6/site-packages/azure/cli/command_modules/appservice/custom.py", line 2313, in webapp_up
    _create_new_rg = should_create_new_rg(cmd, default_rg, rg_name, is_linux)
  File "/opt/az/lib/python3.6/site-packages/azure/cli/command_modules/appservice/_create_util.py", line 282, in should_create_new_rg
    elif (_check_resource_group_exists(cmd, rg_name) and
  File "/opt/az/lib/python3.6/site-packages/azure/cli/command_modules/appservice/_create_util.py", line 86, in _check_resource_group_exists
    return rcf.resource_groups.check_existence(rg_name)
  File "/opt/az/lib/python3.6/site-packages/azure/mgmt/resource/resources/v2018_05_01/operations/resource_groups_operations.py", line 61, in check_existence
    'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'),
  File "/opt/az/lib/python3.6/site-packages/msrest/serialization.py", line 592, in url
    data = self.validate(data, name, required=True, **kwargs)
  File "/opt/az/lib/python3.6/site-packages/msrest/serialization.py", line 672, in validate
    raise ValidationError(key, name, value)
msrest.exceptions.ValidationError: Parameter 'resource_group_name' must conform to the following pattern: '^[-\\w\\._\\(\\)]+$'.

To open an issue, please run: 'az feedback'
</code>```

答:
I had this problem, but resolved it by removing the quotes around the resource group name. Silly mistake on my behalf, but may be the issue here.

e.g. use az group create -n my-groupname-rg -l northeurope
rather than: e.g. use az group create -n 'my-groupname-rg' -l 'northeurope'

Body:
sathish@Azure:~/quickstart/python-docs-hello-world$ az webapp up -n appname
The command failed with an unexpected error. Here is the traceback:

Parameter 'resource_group_name' must conform to the following pattern: '^[-\\w\\._\\(\\)]+$'.
Traceback (most recent call last):
  File "/opt/az/lib/python3.6/site-packages/knack/cli.py", line 206, in invoke
    cmd_result = self.invocation.execute(args)
  File "/opt/az/lib/python3.6/site-packages/azure/cli/core/commands/__init__.py", line 326, in execute
    raise ex
  File "/opt/az/lib/python3.6/site-packages/azure/cli/core/commands/__init__.py", line 384, in _run_jobs_serially
    results.append(self._run_job(expanded_arg, cmd_copy))
  File "/opt/az/lib/python3.6/site-packages/azure/cli/core/commands/__init__.py", line 375, in _run_job
    cmd_copy.exception_handler(ex)
  File "/opt/az/lib/python3.6/site-packages/azure/cli/command_modules/appservice/commands.py", line 54, in _polish_bad_errors
    raise ex
  File "/opt/az/lib/python3.6/site-packages/azure/cli/core/commands/__init__.py", line 354, in _run_job
    result = cmd_copy(params)
  File "/opt/az/lib/python3.6/site-packages/azure/cli/core/commands/__init__.py", line 145, in __call__
    return self.handler(*args, **kwargs)
  File "/opt/az/lib/python3.6/site-packages/azure/cli/core/__init__.py", line 451, in default_command_handler
    return op(**command_args)
  File "/opt/az/lib/python3.6/site-packages/azure/cli/command_modules/appservice/custom.py", line 2313, in webapp_up
    _create_new_rg = should_create_new_rg(cmd, default_rg, rg_name, is_linux)
  File "/opt/az/lib/python3.6/site-packages/azure/cli/command_modules/appservice/_create_util.py", line 282, in should_create_new_rg
    elif (_check_resource_group_exists(cmd, rg_name) and
  File "/opt/az/lib/python3.6/site-packages/azure/cli/command_modules/appservice/_create_util.py", line 86, in _check_resource_group_exists
    return rcf.resource_groups.check_existence(rg_name)
  File "/opt/az/lib/python3.6/site-packages/azure/mgmt/resource/resources/v2018_05_01/operations/resource_groups_operations.py", line 61, in check_existence
    'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'),
  File "/opt/az/lib/python3.6/site-packages/msrest/serialization.py", line 592, in url
    data = self.validate(data, name, required=True, **kwargs)
  File "/opt/az/lib/python3.6/site-packages/msrest/serialization.py", line 672, in validate
    raise ValidationError(key, name, value)
msrest.exceptions.ValidationError: Parameter 'resource_group_name' must conform to the following pattern: '^[-\\w\\._\\(\\)]+$'.

To open an issue, please run: 'az feedback'


问:
Change the background color of item when it is newly added/removed from one multi-select list to another
I have two multi-select lists that have objects that can move between the two. I would like to show visually the movement/flow of items when they are moving from two multi-select lists.

The two lists are side by side. (One on the right and one on left)

If I move x number of objects from the right to the left, I want the background color to be red (showing removal) for those objects. If objects move from left to right, they are added so should be green. The ones that do not move should stay white background.

How can I go about this?

    Current Keywords:

        <select multiple size="8" ng-model="selectedCurr" ng-options="keyword in selectedKeywords"></select>

    <input id="moveRight" type="button" value=">" ng-click="moveItem(selectedCurr, selectedKeywords, availableKeywords)"/>
    <input id="moveLeft" type="button" value="<" ng-click="moveItem(selectedAvailable, availableKeywords, selectedKeywords)"/>

    Available Keywords:

        <select multiple size="8" ng-model="selectedAvailable" ng-options="keyword in availableKeywords"></select>

```

```$scope.moveItem = function(items, from, to) {
    angular.forEach(items, function(item) {
        var idx = from.indexOf(item);
        from.splice(idx, 1);
        to.push(item);
    });
    $scope.selectedCurrent = [];
    $scope.selectedAvailable = [];
};
```

答:
You can use ngStyle or ngClass, depending on your needs

https://docs.angularjs.org/api/ng/directive/ngStyle

https://docs.angularjs.org/api/ng/directive/ngClass

In my case I had to set a different background depending on an attribute, so I made it generate the color in the back-end and it worked pretty well

```<code><tr ng-style="{'background-color': x.color }" ng-repeat="x in reparaciones | filter: filter4">
</code>```

Body:
I have two multi-select lists that have objects that can move between the two. I would like to show visually the movement/flow of items when they are moving from two multi-select lists.

The two lists are side by side. (One on the right and one on left)

If I move x number of objects from the right to the left, I want the background color to be red (showing removal) for those objects. If objects move from left to right, they are added so should be green. The ones that do not move should stay white background.

How can I go about this?

    Current Keywords:

        <select multiple size="8" ng-model="selectedCurr" ng-options="keyword in selectedKeywords"></select>

    <input id="moveRight" type="button" value=">" ng-click="moveItem(selectedCurr, selectedKeywords, availableKeywords)"/>
    <input id="moveLeft" type="button" value="<" ng-click="moveItem(selectedAvailable, availableKeywords, selectedKeywords)"/>

    Available Keywords:

        <select multiple size="8" ng-model="selectedAvailable" ng-options="keyword in availableKeywords"></select>

$scope.moveItem = function(items, from, to) {
    angular.forEach(items, function(item) {
        var idx = from.indexOf(item);
        from.splice(idx, 1);
        to.push(item);
    });
    $scope.selectedCurrent = [];
    $scope.selectedAvailable = [];
};

Body:
You can use ngStyle or ngClass, depending on your needs

https://docs.angularjs.org/api/ng/directive/ngStyle

https://docs.angularjs.org/api/ng/directive/ngClass

In my case I had to set a different background depending on an attribute, so I made it generate the color in the back-end and it worked pretty well

<tr ng-style="{'background-color': x.color }" ng-repeat="x in reparaciones | filter: filter4">


问:
Eclipse's Ctrl+1 in IntelliJ and Android Studio
I really like the Ctrl+1 shortcut (hints for errors and mini refactorings) in Eclipse. Is there an equivalent for it in IntelliJ and Android Studio?

答:
Try pressing CTRL + ALT + v.

It will give the return type exactly of that method.


问:
Could the STAN number be repeteable and random?
I'm developing a Connector with some bank, and we're using the ISO8583 protocol, right now, i'm setting the STAN(field 11) with some random number generated with a random generator but sometimes I have some number collisions, the question is, could I safely use this generator or do I need to make the STAN a sequential number?

Thanks in advance.

答:
Usually STAN is the number increased for each request.
Random STAN generation is not the best case for network messages sequences.

The duplication of STANs can be due to different sources, i.e. Host clients or Terminals.

STAN itself cannot be the only field to detect unique transaction requests. It must be mixed together with other fields like RRN, Terminal ID, Merchant ID.

See also "In ISO message, what's the use of stan and rrn ?"


问:
Moving a predifined class into a thread using Qthread
I am not too great a programmer and quite new to QT sorry for my wording.

I have an already created a sensor class in Qt in a different .cpp file from main, whenever i ran my program it ran slow and lagged so my prof suggested making another thread for the class that retrieves values from sensors. I was wondering to move this class into a seperate new thread do i just simply copy and paste everything (functions calls, signals etc..) under the run() function of the new Qthread.

If this is not the procedure some help in basic terms would be quite beneficial, I dont really understand the QT index information.

Thanks

答:
If you are novice in Qt and especially multi threading, I recommend you to try Qt Concurrent Framework. That will at least protect you form crashes and deadlocks that hard to find out without having enough experience. Use QFuture and QFutureWatcher to execute your function in a thread and read the data.

Overall, your description is very general so I'm not sure its possible to provide a definitive answer how to use your class with QThread.