问:
Vim and Ctags tips and tricks
I have just installed Ctags (to help with C++ development) with my Vim (or rather gVim), and would like to find out your favorite commands, macros, shortcuts, tips that go along with it...

Share your best arsenal. What other Vim add-ons you would recommend for C++ on Vim development?

EDIT What other add-on you would use in conjunction with Ctags?

EDIT2 What version of gVim you use with tags? Does it make a difference?

EDIT3 How do you enhance your programming experience for both big and small projects?

答:
I use ALT-left and ALT-right to pop/push from/to the tag stack.

```<code>" Alt-right/left to navigate forward/backward in the tags stack
map <M-Left> <C-T>
map <M-Right> <C-]>
</code>```

If you use hjkl for movement you can map <M-h> and <M-l> instead.

OwnerDisplayName: Sasha

LastEditorDisplayName: Sasha

ContentLicense: CC BY-SA 2.5

Title: Vim and Ctags tips and tricks

Body:
I use ALT-left and ALT-right to pop/push from/to the tag stack.

" Alt-right/left to navigate forward/backward in the tags stack
map <M-Left> <C-T>
map <M-Right> <C-]>

If you use hjkl for movement you can map <M-h> and <M-l> instead.

OwnerDisplayName: strager

LastEditorDisplayName: strager


来源: stackexchange

问:
Have issue during curl URL for REST API used Flask url: (35) schannel: next InitializeSecurityContext failed
I have design web app using Flask for REST API server

for get id and key from frontend, backend will get info and do some action
(only using POST method)
curl command

```<code>curl -X POST -H "Content-Type:application/json" --data "{/"account_id/":/"100002/", /"access_key/":/"AKIAWDL6TY5M2INS6J7E/"}" https://192.168.172.130:443/account
</code>```

However, when I am using curl command as below:

```
X POST -H "Content-Type:application/json" --data "{/"account_id/":/"100002/", /"access_key/":/"AKIAWDL6TY5M2INS6J7E/"}" https://192.168.172.130:443/account
curl: (35) schannel: next InitializeSecurityContext failed: SEC_E_INVALID_TOKEN (0x80090308) - The token supplied to the function is invalid
```

code design in run.py

```<code>def scan_account(_account_id:str, _access_key:str):
    # building connection to db
    mySQLDB = mysqlDBConnector()
    mySQLDB.dbConnection()

    #init record log request
    _now_time = datetime.datetime.now()
    _request_info_log:str = 'Request of account id:'+str(_account_id)+' With Access Key: '+str(_access_key)+' at: '+str(_now_time)+' direction data: incoming with action type: post request'
    mySQLDB.db_log_request_insert(_request_info_log)

    # get secret key
    _AccountID: int = _account_id
    _AccessKey: str = _access_key
    _SecretKey: str =  mySQLDB.db_get_key(_AccountID,_AccessKey)

    # init boto3 session
    _aws_session = AWS_Session(_AccessKey, _SecretKey)
    _aws_session.get_credentials()

    #init running
    _worker = Worker()
    attrs = (getattr(_worker, name) for name in dir(_worker))
    methods = filter(inspect.ismethod, attrs)
    for method in methods:
        _thread_method = threading.Thread(target=method, args=(_aws_session,))
        _thread_method.start()
        _thread_method.join()

@app.route("/account/",methods=["POST"])
def account_info():
    _account_id = request.json['account_id']
    _access_key = request.json['access_key']
    #data = {'acount_id': _account_id, 'access_key': _access_key}
    scan_account(_account_id,_access_key)
    #return jsonify(data)

if __name__ == '__main__':
    app.run(debug=True,host='0.0.0.0', port='443')
</code>```

答:
Ok lets get a couple of things out the way, I DO NOT suggest you use this for anything other than a local dev. Please use proper SSL.

Make sure you have pyOpenSSL properly installed.

```<code>from flask import Flask, jsonify, request, make_response

app = Flask(__name__)

@app.route("/account/",methods=["POST"])
def account_info():
    _account_id = request.json['account_id']
    _access_key = request.json['access_key']
    data = {'acount_id': _account_id, 'access_key': _access_key}
    return make_response(jsonify(data), 200)

if __name__ == '__main__':
    app.run(debug=True,host='0.0.0.0', port='433', ssl_context='adhoc')
</code>```

I also modified your curl to make it simpler, that and it was causing issues:

```<code>curl -X POST -H "Content-Type:application/json" --data '{"account_id":"100002", "access_key":"AKIAWDL6TY5M2INS6J7E"}' https://localhost:9443/account/ --insecure
</code>```

I get the following output:

```<code>{
  "access_key": "AKIAWDL6TY5M2INS6J7E",
  "acount_id": "100002"
}
</code>```

This is how i tested it all:

```<code>docker run --rm -it -p 9443:443 python:3.7 bash -c '
pip install flask pyOpenSSL;
curl -s https://gist.githubusercontent.com/kingbuzzman/a955b49a318eef9e76b4bf9026cd2595/raw/sample.py > sample.py;
python sample.py'
</code>```

Here is the gist source: https://gist.github.com/kingbuzzman/a955b49a318eef9e76b4bf9026cd2595

ContentLicense: CC BY-SA 4.0

Body:
I have design web app using Flask for REST API server

for get id and key from frontend, backend will get info and do some action
(only using POST method)
curl command

curl -X POST -H "Content-Type:application/json" --data "{/"account_id/":/"100002/", /"access_key/":/"AKIAWDL6TY5M2INS6J7E/"}" https://192.168.172.130:443/account

However, when I am using curl command as below:

X POST -H "Content-Type:application/json" --data "{/"account_id/":/"100002/", /"access_key/":/"AKIAWDL6TY5M2INS6J7E/"}" https://192.168.172.130:443/account
curl: (35) schannel: next InitializeSecurityContext failed: SEC_E_INVALID_TOKEN (0x80090308) - The token supplied to the function is invalid

code design in run.py

def scan_account(_account_id:str, _access_key:str):
    # building connection to db
    mySQLDB = mysqlDBConnector()
    mySQLDB.dbConnection()

    #init record log request
    _now_time = datetime.datetime.now()
    _request_info_log:str = 'Request of account id:'+str(_account_id)+' With Access Key: '+str(_access_key)+' at: '+str(_now_time)+' direction data: incoming with action type: post request'
    mySQLDB.db_log_request_insert(_request_info_log)

    # get secret key
    _AccountID: int = _account_id
    _AccessKey: str = _access_key
    _SecretKey: str =  mySQLDB.db_get_key(_AccountID,_AccessKey)

    # init boto3 session
    _aws_session = AWS_Session(_AccessKey, _SecretKey)
    _aws_session.get_credentials()

    #init running
    _worker = Worker()
    attrs = (getattr(_worker, name) for name in dir(_worker))
    methods = filter(inspect.ismethod, attrs)
    for method in methods:
        _thread_method = threading.Thread(target=method, args=(_aws_session,))
        _thread_method.start()
        _thread_method.join()

@app.route("/account/",methods=["POST"])
def account_info():
    _account_id = request.json['account_id']
    _access_key = request.json['access_key']
    #data = {'acount_id': _account_id, 'access_key': _access_key}
    scan_account(_account_id,_access_key)
    #return jsonify(data)

if __name__ == '__main__':
    app.run(debug=True,host='0.0.0.0', port='443')

Body:
Ok lets get a couple of things out the way, I DO NOT suggest you use this for anything other than a local dev. Please use proper SSL.

Make sure you have pyOpenSSL properly installed.

from flask import Flask, jsonify, request, make_response

app = Flask(__name__)

@app.route("/account/",methods=["POST"])
def account_info():
    _account_id = request.json['account_id']
    _access_key = request.json['access_key']
    data = {'acount_id': _account_id, 'access_key': _access_key}
    return make_response(jsonify(data), 200)

if __name__ == '__main__':
    app.run(debug=True,host='0.0.0.0', port='433', ssl_context='adhoc')

I also modified your curl to make it simpler, that and it was causing issues:

curl -X POST -H "Content-Type:application/json" --data '{"account_id":"100002", "access_key":"AKIAWDL6TY5M2INS6J7E"}' https://localhost:9443/account/ --insecure

I get the following output:

{
  "access_key": "AKIAWDL6TY5M2INS6J7E",
  "acount_id": "100002"
}

This is how i tested it all:

docker run --rm -it -p 9443:443 python:3.7 bash -c '
pip install flask pyOpenSSL;
curl -s https://gist.githubusercontent.com/kingbuzzman/a955b49a318eef9e76b4bf9026cd2595/raw/sample.py > sample.py;
python sample.py'

Here is the gist source: https://gist.github.com/kingbuzzman/a955b49a318eef9e76b4bf9026cd2595


问:
Typescript named definition in interface Array
Let's say for example I have an interface which defines a boolean value and optional string:

Example

```<code>interface IError {
  error: [boolean, string?];
}
</code>```

Now later in the code I want to use it:

```<code>if (somethingTrue) {
  error: [false]
} else {
  error: [true, "Error occurred because of foo"]
}
</code>```

I got this working. However, I would like to add more context to the Interface. The boolean should be named errorOccured and the string should be named message.

Tried

I was thinking about the following:

```<code>interface IError {
  error: [errorOccured: boolean, message: string?];
}
</code>```

Might be something obvious that I'm missing, but I just don't get it.

答:
With the name of your interface, I would have directly put the properties into it :

```<code>interface IError {
  errorOccurred: boolean;
  message?: string;
}
</code>```

and your object error should be of type IError.

And for the implementation of this interface, you can set independantly both parameters...

Body:
Let's say for example I have an interface which defines a boolean value and optional string:

Example

interface IError {
  error: [boolean, string?];
}

Now later in the code I want to use it:

if (somethingTrue) {
  error: [false]
} else {
  error: [true, "Error occurred because of foo"]
}

I got this working. However, I would like to add more context to the Interface. The boolean should be named errorOccured and the string should be named message.

Tried

I was thinking about the following:

interface IError {
  error: [errorOccured: boolean, message: string?];
}

Might be something obvious that I'm missing, but I just don't get it.

Body:
With the name of your interface, I would have directly put the properties into it :

interface IError {
  errorOccurred: boolean;
  message?: string;
}

and your object error should be of type IError.

And for the implementation of this interface, you can set independantly both parameters...


问:
Dynamic Navbar links in the shared layout MVC/Razor
I would like links on the navigation bar to appear or disappear depending upon the data in the database. All the nav bar links are in _Layout.cshtml which is being used by all pages.

```<code><ul>
 @if (User.Identity.IsAuthenticated)
  {
   <li class="nav-item dropdown">
     <a class="nav-link dropdown-toggle" data-toggle="dropdown" href="#" role="button" aria-haspopup="true" aria-expanded="false">Bookings</a>
     <ul class="dropdown-menu">
     <li>@Html.ActionLink("All Bookings", "GetAllBookings", "Booking")</li>
     <li>@Html.ActionLink("Member's Dashboard", "GetBookingsByStatus", "Booking")</li>
     </ul>
   </li>
</ul>
</code>```

I would like member's dashboard to only appear if they are a member and have certain attributes in their profile. What is the best way to dynamically changing the nav bar links depending upon the data in database?

答:
even in your sample code, you can just leave out the list items by wrapping them in an @if conditional and checking their permissions in whatever method you see fit.

However, I hope I'm pointing out the obvious, but this method only hides the link.  It doesn't prevent the user from typing it in or using a bookmark.  You will also need to duplicate the security check in your controller.

Body:
I would like links on the navigation bar to appear or disappear depending upon the data in the database. All the nav bar links are in _Layout.cshtml which is being used by all pages.

 @if (User.Identity.IsAuthenticated)
  {

     Bookings

@Html.ActionLink("All Bookings", "GetAllBookings", "Booking")

@Html.ActionLink("Member's Dashboard", "GetBookingsByStatus", "Booking")

I would like member's dashboard to only appear if they are a member and have certain attributes in their profile. What is the best way to dynamically changing the nav bar links depending upon the data in database?


问:
how format date to multiple fields in the model in the rails app?
I have a form in rails that has a date field with input mask with format mm/dd/yyyy, but at the moment to save it, I am getting an error because of the format in the model is dd/mm/yyyy. I found a solution that maybe can work.

```<code> def organization_date=(val)
   date = Date.strptime(val, “%m/%d/%Y”) if val.present?
   write_attribute(:organization_date, date)
 end
</code>```

but I need one solution more elegant because I have more field of type date, and I can't do that for each field and updating the format to input mask to dd/mm/yyyy is not an option either because the client's requirement is that it be in the format mm/dd/yyyy

I am using Rails 6.0 beta

I'm grateful for any ideas that help solve this problem

答:
I think that the best way to fix it is, create a file in config/initializers/date_format.rb</p>

```<code>module Typecasting
  module Date
    def cast_value v
      ::Date.strptime v, "%m/%d/%Y" rescue super
    end
  end

  ::ActiveRecord::Type::Date.prepend Date
end
</code>```

Body:
I have a form in rails that has a date field with input mask with format mm/dd/yyyy, but at the moment to save it, I am getting an error because of the format in the model is dd/mm/yyyy. I found a solution that maybe can work.

 def organization_date=(val)
   date = Date.strptime(val, “%m/%d/%Y”) if val.present?
   write_attribute(:organization_date, date)
 end

but I need one solution more elegant because I have more field of type date, and I can't do that for each field and updating the format to input mask to dd/mm/yyyy is not an option either because the client's requirement is that it be in the format mm/dd/yyyy

I am using Rails 6.0 beta

I'm grateful for any ideas that help solve this problem

Body:
I think that the best way to fix it is, create a file in config/initializers/date_format.rb

module Typecasting
  module Date
    def cast_value v
      ::Date.strptime v, "%m/%d/%Y" rescue super
    end
  end

  ::ActiveRecord::Type::Date.prepend Date
end


问:
Combining two columns of a table and returning it as a single column separated by a character
I'm using oracle sql developer for the first time. I want to create a view with two columns of a table combined and seperated by a slash.
I have done this in ssms but when I write the same code for sql dev it returns me problems like 'the specified number is invalid.

```<code>SELECT ID AS W_ID, CAST(data1 AS VARCHAR)+' - '+data2 AS W_CODE, +data3 AS W_TEXT
FROM table1
WHERE data3=1;
</code>```

how can I translate this query in Oracle ?

答:
Oracle uses the standard || operator for string concatenation, not +:

```<code>SELECT ID AS W_ID,
       (data1 ||  ' - ' || data2) AS W_CODE,
      data3 AS W_TEXT
FROM table1
WHERE data3 = 1;
</code>```

Casting to a string is unnecessary.  Oracle will do that automatically.  If you do, TO_CHAR() is the more colloquial method in Oracle, because it lets you control the format for numbers and dates.

I don't understand the purpose of +, so I removed it.  Perhaps you want abs()?

Body:
I'm using oracle sql developer for the first time. I want to create a view with two columns of a table combined and seperated by a slash.
I have done this in ssms but when I write the same code for sql dev it returns me problems like 'the specified number is invalid.

SELECT ID AS W_ID, CAST(data1 AS VARCHAR)+' - '+data2 AS W_CODE, +data3 AS W_TEXT
FROM table1
WHERE data3=1;

how can I translate this query in Oracle ?

Body:
Oracle uses the standard || operator for string concatenation, not +:

SELECT ID AS W_ID,
       (data1 ||  ' - ' || data2) AS W_CODE,
      data3 AS W_TEXT
FROM table1
WHERE data3 = 1;

Casting to a string is unnecessary.  Oracle will do that automatically.  If you do, TO_CHAR() is the more colloquial method in Oracle, because it lets you control the format for numbers and dates.

I don't understand the purpose of +, so I removed it.  Perhaps you want abs()?


问:
Clone A Private Repository (Github)
I have a private repository on Github for a project I'm working on.  Until now I had only worked on my home desktop, but I just bought a laptop, and am trying to set it up so that I can work on the project from either computer, and push / pull changes.

I added a new SSH key to my Github account for the laptop, and was successful in cloning and making changes to a public test repo that I set up.  However, I couldn't clone the private repo.  Is there anything special I need to do in the command line in order to clone a private repo?  Do I need to set up a new GitHub account for my laptop and set myself up as a collaborator?

The command I used was git clone git://github.com/username/reponame.git

答:
I needed a non-interactive method for cloning a private repo.

Inspired by this issue: https://github.com/github/hub/issues/1644

Step 1.

Create a personal access token in the github developer settings:
https://github.com/settings/tokens

Step 2.

```<code>git clone https://$token:x-oauth-basic@github.com/$username/$repo.git
</code>```

Title: Clone A Private Repository (Github)

Body:
I needed a non-interactive method for cloning a private repo.

Inspired by this issue: https://github.com/github/hub/issues/1644

Step 1.

Create a personal access token in the github developer settings:
https://github.com/settings/tokens

Step 2.

git clone https://$token:x-oauth-basic@github.com/$username/$repo.git


问:
how to allow autostart permission like whatapp app for ionic application
I have an application developed with ionic now I have a problem when starting the device for some phone notifications do not arrive until I open the application. I debug the application with android studio I found that the device receives the notification but the system does not allow the reception of notifcations because the application is not allowed after the boot to start; you have to go to the settings to allow the application to run to receive notifications in background.My question is how I can allow the application with ionic to have permission to do the autostart after the boot as c is the case of whatsapp. If there is also with android it's welcome</p>

答:
Manufacturers white list some apps like facebook and whatsapp rest of the app user should enable auto start permission.

There is no way to enable auto start permission.Only way to make it possible is showing auto start dialogue box take user to the auto start permission activity.

I have created one plugin you can have a look

https://github.com/saty932/cordova-plugin-autostart-permission


问:
Run java code for IBM Lotus Notes on Linux. Error no lsxbe
I am trying to run a simple java code using Notes.jar to read from NSF files on Linux.

When i run the code, I get the below error

java.lang.UnsatisfiedLinkError: no lsxbe in java.library.path

This worked in windows when I installed Notes notes.

Sample JAVA Code

NotesThread.sinitThread();
Session s = NotesFactory.createSession();

I want the below to be fixed

1.Where to get linux software for lotus notes and how to install it

How to fix the below error
java.lang.UnsatisfiedLinkError: no lsxbe in java.library.path

答:
Notes is only available on Windows and MAC. If you need to access notes data in linux, you have several options.

Notes Client on linux has been dropped around 9.0.1 FP6

a) Webservices.

b) NCSO.JAR and DIIOP see https://www-01.ibm.com/support/docview.wss?uid=swg21994330


问:
Delete global variable and release memory from a function
I need to delete a global variable and release the memory it was using from inside a function with R, but none of the options I have tried work.

I have tried rm function with envir parameter and then gc, but gc does not release the memory. I have also tried runing gc in the global environment with eval+envir.

```<code>library(data.table)
DT = data.table(col1 = 1:1e6)
cols = paste0('col', 2:100)
for (col in cols){ DT[, col := 1:1e6, with = F] }

rm_and_release <- function(dt){
  dt <- dt[sample(1e6, 9e5, FALSE)]
  print(gc())
  rm(DT, envir = globalenv())

  print(gc())
}

rm_and_release(DT)
</code>```

The result is the following

```<code>           used  (Mb) gc trigger   (Mb)  max used   (Mb)
Ncells   661556  35.4    1168576   62.5   1143443   61.1
Vcells 96303112  734.8   146725516 1119.5 146722586 1119.5
           used  (Mb) gc trigger   (Mb)  max used   (Mb)
Ncells   661569  35.4    1168576   62.5   1143443   61.1
Vcells 96303114  734.8   146725516 1119.5 146722586 1119.5
</code>```

I expected the second gc() to liberate more memory, since at that moment there is only one dataset, because the global DT has been removed.

I need to liberate RAM inside the function because the function generates more datasets and it runs out of memory.

答:
Use the list= argument of rm like this:

```<code>library(data.table)
DT = data.table(col1 = 1:1e6)
cols = paste0('col', 2:100)
for (col in cols){ DT[, col := 1:1e6, with = F] }

rm_and_release <- function(dt){
  dt <- dt[sample(1e6, 9e5, FALSE)]
  print(gc())
  rm(list = "DT", envir = globalenv())

  print(gc())
}

rm_and_release(DT)
exists("DT")
## [1] FALSE
</code>```

Note

Here is the log when I run it (on Windows):

```<code>> library(data.table)
> gc()
          used (Mb) gc trigger  (Mb) max used  (Mb)
Ncells 1075660 57.5    1899034 101.5  1899034 101.5
Vcells 2609137 20.0   91310117 696.7 99059673 755.8
> DT = data.table(col1 = 1:1e6)
> cols = paste0('col', 2:100)
> for (col in cols){ DT[, col := 1:1e6, with = F] }
There were 50 or more warnings (use warnings() to see the first 50)
>
> rm_and_release <- function(dt){
+   dt <- dt[sample(1e6, 9e5, FALSE)]
+   print(gc())
+   rm(list = "DT", envir = globalenv())
+
+   print(gc())
+ }
>
> gc()
           used  (Mb) gc trigger  (Mb) max used  (Mb)
Ncells  1076769  57.6    1899034 101.5  1899034 101.5
Vcells 53024698 404.6   91310117 696.7 99059673 755.8
> rm_and_release(DT)
           used  (Mb) gc trigger   (Mb) max used  (Mb)
Ncells  1075902  57.5    1899034  101.5  1899034 101.5
Vcells 97613454 744.8  134081733 1023.0 99059673 755.8
           used  (Mb) gc trigger   (Mb) max used  (Mb)
Ncells  1075901  57.5    1899034  101.5  1899034 101.5
Vcells 97613454 744.8  160978079 1228.2 99059673 755.8
> exists("DT")
[1] FALSE
> gc()
          used (Mb) gc trigger  (Mb) max used  (Mb)
Ncells 1075669 57.5    1899034 101.5  1899034 101.5
Vcells 2613271 20.0  128782463 982.6 99059673 755.8
> ## [1] FALSE
</code>```

Body:
I need to delete a global variable and release the memory it was using from inside a function with R, but none of the options I have tried work.

I have tried rm function with envir parameter and then gc, but gc does not release the memory. I have also tried runing gc in the global environment with eval+envir.

library(data.table)
DT = data.table(col1 = 1:1e6)
cols = paste0('col', 2:100)
for (col in cols){ DT[, col := 1:1e6, with = F] }

rm_and_release <- function(dt){
  dt <- dt[sample(1e6, 9e5, FALSE)]
  print(gc())
  rm(DT, envir = globalenv())

  print(gc())
}

rm_and_release(DT)

The result is the following

           used  (Mb) gc trigger   (Mb)  max used   (Mb)
Ncells   661556  35.4    1168576   62.5   1143443   61.1
Vcells 96303112  734.8   146725516 1119.5 146722586 1119.5
           used  (Mb) gc trigger   (Mb)  max used   (Mb)
Ncells   661569  35.4    1168576   62.5   1143443   61.1
Vcells 96303114  734.8   146725516 1119.5 146722586 1119.5

I expected the second gc() to liberate more memory, since at that moment there is only one dataset, because the global DT has been removed.

I need to liberate RAM inside the function because the function generates more datasets and it runs out of memory.

Body:
Use the list= argument of rm like this:

library(data.table)
DT = data.table(col1 = 1:1e6)
cols = paste0('col', 2:100)
for (col in cols){ DT[, col := 1:1e6, with = F] }

rm_and_release <- function(dt){
  dt <- dt[sample(1e6, 9e5, FALSE)]
  print(gc())
  rm(list = "DT", envir = globalenv())

  print(gc())
}

rm_and_release(DT)
exists("DT")
## [1] FALSE

Note

Here is the log when I run it (on Windows):

> library(data.table)
> gc()
          used (Mb) gc trigger  (Mb) max used  (Mb)
Ncells 1075660 57.5    1899034 101.5  1899034 101.5
Vcells 2609137 20.0   91310117 696.7 99059673 755.8
> DT = data.table(col1 = 1:1e6)
> cols = paste0('col', 2:100)
> for (col in cols){ DT[, col := 1:1e6, with = F] }
There were 50 or more warnings (use warnings() to see the first 50)
>
> rm_and_release <- function(dt){
+   dt <- dt[sample(1e6, 9e5, FALSE)]
+   print(gc())
+   rm(list = "DT", envir = globalenv())
+
+   print(gc())
+ }
>
> gc()
           used  (Mb) gc trigger  (Mb) max used  (Mb)
Ncells  1076769  57.6    1899034 101.5  1899034 101.5
Vcells 53024698 404.6   91310117 696.7 99059673 755.8
> rm_and_release(DT)
           used  (Mb) gc trigger   (Mb) max used  (Mb)
Ncells  1075902  57.5    1899034  101.5  1899034 101.5
Vcells 97613454 744.8  134081733 1023.0 99059673 755.8
           used  (Mb) gc trigger   (Mb) max used  (Mb)
Ncells  1075901  57.5    1899034  101.5  1899034 101.5
Vcells 97613454 744.8  160978079 1228.2 99059673 755.8
> exists("DT")
[1] FALSE
> gc()
          used (Mb) gc trigger  (Mb) max used  (Mb)
Ncells 1075669 57.5    1899034 101.5  1899034 101.5
Vcells 2613271 20.0  128782463 982.6 99059673 755.8
> ## [1] FALSE


问:
How to apply multiple conditional filters with group by operation in R?
I have following dataframe named 'data'

I want to take only those rows where Actual Discount value compares with Discount value and takes higher sealing value. and if Actual Discount is higher that Discount as that of Model RTD9 it should take highest sealing of Discount.

My final output dataframe should be as followed(coloured yellow in above dataframe),

答:
We can use findInterval to get the closest interval

```<code>library(dplyr)

df %>%
  group_by(Model) %>%
  slice(if(any(Discount > ActualDiscount))
          which.max(findInterval(Discount, first(ActualDiscount))) else
          which.max(Discount - ActualDiscount))

#  Model Level Discount ActualDiscount
#  <fct> <int>    <dbl>          <dbl>
#1 BD56      1     21             20
#2 HT67      2     25             24
#3 KJ90      3     33             32
#4 RTD9      3     33.7           35.5
#5 YT61      5     33             32.5
</code>```

Body:
We can use findInterval to get the closest interval

library(dplyr)

df %>%
  group_by(Model) %>%
  slice(if(any(Discount > ActualDiscount))
          which.max(findInterval(Discount, first(ActualDiscount))) else
          which.max(Discount - ActualDiscount))

#  Model Level Discount ActualDiscount
#  <fct> <int>    <dbl>          <dbl>
#1 BD56      1     21             20
#2 HT67      2     25             24
#3 KJ90      3     33             32
#4 RTD9      3     33.7           35.5
#5 YT61      5     33             32.5


问:
Detect when Android emulator is fully booted
I want to create a script where I start an emulator and after the system is fully booted, I want to install an .apk.

How can I know when the emulator is fully booted so I can run the install command? Here http://developer.android.com/guide/developing/tools/adb.html it is said that adb wait-for-device install <app>.apk is not correct.

So how can I achieve this? Is it possible? Is my only option to sleep for a few minutes until I can be sure that the emulator is started?

答: Just run emulator with -delay-adb flag and then run adb wait-for-device. adb will exit when the emulator booted.


问:
Connecting to codefresh image registry via kubectl, problem with secrets
I am trying to deploy an application via kubectl using an image stored on Codefresh. I have it running perfectly when i place the image on a public registry.

The problem is when I apply the deployment.yaml I get a "ImagePullBackOff" error on the pods. I'm assuming, i think correctly, that this is because I need a secret to be able to access my Codefresh image.

This is the container part of my current deployment.yaml:

```<code>spec:
      containers:
        - name: dockapp
        #States the image that will be put inside the pod. Secret to get access is declared below
        #registry.hub.docker.com/jamiedovu/dockapp:latest
          image:  r.cfcr.io/jamiew87/my-app-image:master
          ports:
          - containerPort: 8080
            name: http
      imagePullSecrets:
      - name: regcred
</code>```

My question is, what is it i need to put into the secret "regcred" to be able to connect to this private registry. The Kubernetes documentation only demonstrates how to do one for docker.

答:
I think it's explained in the docs.</p>

```<code>export DOCKER_REGISTRY_SERVER=r.cfcr.io
export DOCKER_USER=YOUR_USERNAME
export DOCKER_PASSWORD=YOUR_REGISTRY_PASSWORD
export DOCKER_EMAIL=YOUR_EMAIL

kubectl create secret docker-registry cfcr\
 --docker-server=$DOCKER_REGISTRY_SERVER\
 --docker-username=$DOCKER_USER\
 --docker-password=$DOCKER_PASSWORD\
 --docker-email=$DOCKER_EMAIL
</code>```

Body:
I am trying to deploy an application via kubectl using an image stored on Codefresh. I have it running perfectly when i place the image on a public registry.

The problem is when I apply the deployment.yaml I get a "ImagePullBackOff" error on the pods. I'm assuming, i think correctly, that this is because I need a secret to be able to access my Codefresh image.

This is the container part of my current deployment.yaml:

spec:
      containers:
        - name: dockapp
        #States the image that will be put inside the pod. Secret to get access is declared below
        #registry.hub.docker.com/jamiedovu/dockapp:latest
          image:  r.cfcr.io/jamiew87/my-app-image:master
          ports:
          - containerPort: 8080
            name: http
      imagePullSecrets:
      - name: regcred

My question is, what is it i need to put into the secret "regcred" to be able to connect to this private registry. The Kubernetes documentation only demonstrates how to do one for docker.

Body:
I think it's explained in the docs.

export DOCKER_REGISTRY_SERVER=r.cfcr.io
export DOCKER_USER=YOUR_USERNAME
export DOCKER_PASSWORD=YOUR_REGISTRY_PASSWORD
export DOCKER_EMAIL=YOUR_EMAIL

kubectl create secret docker-registry cfcr\
 --docker-server=$DOCKER_REGISTRY_SERVER\
 --docker-username=$DOCKER_USER\
 --docker-password=$DOCKER_PASSWORD\
 --docker-email=$DOCKER_EMAIL


问:
Implementing DFT, inverse function not working properly
I've implemented DFT and the inverse DFT Function according to the following formulas:

The DFT function works, but when testing the inverse on the output I don't get the original series.

import numpy as np
import random

exp = np.exp
pi = np.pi

def mydft(X):
    n = len(X)
    out = []
    for k in range(n):
        temp = 0
        for i in range(n):
            temp += X[i] * exp(-2j*pi*k*i/n)
        out.append(temp)
    return np.array(out)

def myidft(X):
    n = len(X)
    out = []
    for k in range(n):
        temp = 0
        for i in range(n):
            temp += X[i] * exp(2j*pi*k*i/n)
        out.append(temp)
    return (1/n) * np.array(out)
```
<h2>Testing</h2>
<pre class="lang-py prettyprint-override"><code>orig = np.random.random(100)
trans = mydft(orig)

inv = myidft(trans)
print(np.allclose(inv, trans))
>>> False

print(np.allclose(trans, np.fft.fft(orig)))
>>> True
</code>```

Since the original Function works and the modifications for the inverse are quite simple, I have no clue what went wrong!?

答:
Shouldn't your test be

```<code>print(np.allclose(inv, orig))
</code>```

since

```<code>orig = myidft(mydft(orig))
</code>```

because when I plot your DFT

and invDFT (of DFT of original signal)

compared to the numpy FFT algorithm the results are exactly the same. Your implementation seems right. Your test is wrong.

Body:
I've implemented DFT and the inverse DFT Function according to the following formulas:

The DFT function works, but when testing the inverse on the output I don't get the original series.

import numpy as np
import random

exp = np.exp
pi = np.pi

def mydft(X):
    n = len(X)
    out = []
    for k in range(n):
        temp = 0
        for i in range(n):
            temp += X[i] * exp(-2j*pi*k*i/n)
        out.append(temp)
    return np.array(out)

def myidft(X):
    n = len(X)
    out = []
    for k in range(n):
        temp = 0
        for i in range(n):
            temp += X[i] * exp(2j*pi*k*i/n)
        out.append(temp)
    return (1/n) * np.array(out)

Testing

orig = np.random.random(100)
trans = mydft(orig)

inv = myidft(trans)
print(np.allclose(inv, trans))
>>> False

print(np.allclose(trans, np.fft.fft(orig)))
>>> True

Since the original Function works and the modifications for the inverse are quite simple, I have no clue what went wrong!?

Body:
Shouldn't your test be

print(np.allclose(inv, orig))

since

orig = myidft(mydft(orig))

because when I plot your DFT

and invDFT (of DFT of original signal)

compared to the numpy FFT algorithm the results are exactly the same. Your implementation seems right. Your test is wrong.


问:
Tkinter Listobox Selection calls a Function repeatedly/autorefresh
I am running a GUI in Python 3 with Tkinter implementation.

I am populating a Listbox with some values that I query from a database and on select of a result from the Listbox, I "bind" a function.

```<code>tagsList.bind('<<ListboxSelect>>', get_anchors)
</code>```

This function/event widget, queries again another database that has saved the location of some PNG images and imports them to the GUI using: ImageTk.PhotoImage(Image.open(path)), as PhotoImage. It populates a grid with all these images loaded, as you may see in the code below:

```<code>def get_anchors(event):
    lb = event.widget
    index = lb.curselection()[0]
    tag_name = lb.get(index)

    # Get the anchor list from the database row
    alist = []
    for row in conn.execute("SELECT anchor FROM \"" + tag_name + "\" ORDER BY anchor"):
        alist.append(row[0])

    # ===== Import PNG Images =====
    i = 1
    for anchor in alist:
        j = 1
        for key in measurements:
            path = conn.execute("SELECT \"" + key + "\" FROM \"" + tag_name + "\" WHERE anchor = \"" + anchor +"\"").fetchone()[0]
            photo = ImageTk.PhotoImage(Image.open(path))
            label = tkinter.Label(mainWindow, relief="sunken", image=photo)
            label.image = photo
            label.grid(row=i, column=j, sticky='nsew')
            j += 1
        i += 1
</code>```

The Problem: The PNG images are changing over the time, they are basically replaced with new generated ones from another program. So, I was wondering if the is a way to autorefresh/load again the newly PNG files, without having to click/select again the same result from the Listbox, that I already have it selected.

The PNG images are generated every 5 seconds, if that helps and they are basically replacing the existing ones(same file name, location etc.). I was hoping that there might be something like a constant autorefresh feature/method or at least a way to call this get_anchors function repeatedly once a specific result is selected from the Listbox.

I can't really find something that will enable this functionality and the only way to go right now, is by clicking again the option that refreshes the grid with the new PNGs by calling again the get_anchors.

答:
Not entirely sure why it was not working before with the lb.after(5000, get_anchors, args=(event,)), but it is working now in the format lb.after(5000, get_anchors, event).

I am basically calling a function from the main Tkinter code like this:

```<code>tagsList.bind('<<ListboxSelect>>', get_anchors)
</code>```

which is a listbox and once I select my choice, it calls the get_anchors function, which I bind to it. Then, all I wanted was to re-call the function every 6 seconds from within the same function get_anchors. The code looks like:

```<code>def get_anchors(event):
    # ===== Clear canvas and re-assign it on GUI =====
    canvas.delete("all")
    canvas.grid(row=1, column=1, sticky='nsew', rowspan=17, columnspan=5, padx=(10, 0))
    image_plots = tkinter.Frame(canvas, background='white')
    canvas.create_window((0,0), window=image_plots, anchor='nw')

    lb = event.widget
    index = lb.curselection()[0]
    tag_name = lb.get(index)

    # Get the anchor list from the database row
    alist = []
    for row in conn.execute("SELECT anchor FROM \"" + tag_name + "\" ORDER BY anchor"):
        alist.append(row[0])

    # ===== Import PNG Images =====
    i = 1
    for anchor in alist:
        j = 1
        for key in measurements:
            path = conn.execute("SELECT \"" + key + "\" FROM \"" + tag_name + "\" WHERE anchor = \"" + anchor +"\"").fetchone()[0]
            photo = ImageTk.PhotoImage(Image.open(path))
            label = tkinter.Label(image_plots, relief="sunken", image=photo)
            label.image = photo  # Keeping reference is needed
            label.grid(row=i, column=j, sticky='nsew')
            j += 1
        i += 1

    # Refresh PNGs every 6s; they are generated roughly every 5s
    mainWindow.after(6000, get_anchors, event)
</code>```

This solution at the last line works for refreshing the Canvas and populating it with the new PNGs. With the args=(event,) solution, it did not work.

ContentLicense: CC BY-SA 3.0

Body:
I am running a GUI in Python 3 with Tkinter implementation.

I am populating a Listbox with some values that I query from a database and on select of a result from the Listbox, I "bind" a function.

tagsList.bind('<<ListboxSelect>>', get_anchors)

This function/event widget, queries again another database that has saved the location of some PNG images and imports them to the GUI using: ImageTk.PhotoImage(Image.open(path)), as PhotoImage. It populates a grid with all these images loaded, as you may see in the code below:

def get_anchors(event):
    lb = event.widget
    index = lb.curselection()[0]
    tag_name = lb.get(index)

    # Get the anchor list from the database row
    alist = []
    for row in conn.execute("SELECT anchor FROM \"" + tag_name + "\" ORDER BY anchor"):
        alist.append(row[0])

    # ===== Import PNG Images =====
    i = 1
    for anchor in alist:
        j = 1
        for key in measurements:
            path = conn.execute("SELECT \"" + key + "\" FROM \"" + tag_name + "\" WHERE anchor = \"" + anchor +"\"").fetchone()[0]
            photo = ImageTk.PhotoImage(Image.open(path))
            label = tkinter.Label(mainWindow, relief="sunken", image=photo)
            label.image = photo
            label.grid(row=i, column=j, sticky='nsew')
            j += 1
        i += 1

The Problem: The PNG images are changing over the time, they are basically replaced with new generated ones from another program. So, I was wondering if the is a way to autorefresh/load again the newly PNG files, without having to click/select again the same result from the Listbox, that I already have it selected.

The PNG images are generated every 5 seconds, if that helps and they are basically replacing the existing ones(same file name, location etc.). I was hoping that there might be something like a constant autorefresh feature/method or at least a way to call this get_anchors function repeatedly once a specific result is selected from the Listbox.

I can't really find something that will enable this functionality and the only way to go right now, is by clicking again the option that refreshes the grid with the new PNGs by calling again the get_anchors.

Body:
Not entirely sure why it was not working before with the lb.after(5000, get_anchors, args=(event,)), but it is working now in the format lb.after(5000, get_anchors, event).

I am basically calling a function from the main Tkinter code like this:

tagsList.bind('<<ListboxSelect>>', get_anchors)

which is a listbox and once I select my choice, it calls the get_anchors function, which I bind to it. Then, all I wanted was to re-call the function every 6 seconds from within the same function get_anchors. The code looks like:

def get_anchors(event):
    # ===== Clear canvas and re-assign it on GUI =====
    canvas.delete("all")
    canvas.grid(row=1, column=1, sticky='nsew', rowspan=17, columnspan=5, padx=(10, 0))
    image_plots = tkinter.Frame(canvas, background='white')
    canvas.create_window((0,0), window=image_plots, anchor='nw')

    lb = event.widget
    index = lb.curselection()[0]
    tag_name = lb.get(index)

    # Get the anchor list from the database row
    alist = []
    for row in conn.execute("SELECT anchor FROM \"" + tag_name + "\" ORDER BY anchor"):
        alist.append(row[0])

    # ===== Import PNG Images =====
    i = 1
    for anchor in alist:
        j = 1
        for key in measurements:
            path = conn.execute("SELECT \"" + key + "\" FROM \"" + tag_name + "\" WHERE anchor = \"" + anchor +"\"").fetchone()[0]
            photo = ImageTk.PhotoImage(Image.open(path))
            label = tkinter.Label(image_plots, relief="sunken", image=photo)
            label.image = photo  # Keeping reference is needed
            label.grid(row=i, column=j, sticky='nsew')
            j += 1
        i += 1

    # Refresh PNGs every 6s; they are generated roughly every 5s
    mainWindow.after(6000, get_anchors, event)

This solution at the last line works for refreshing the Canvas and populating it with the new PNGs. With the args=(event,) solution, it did not work.


问:
Java beginner question: Method for finding next available ID in an ArrayList
ive been given this Exercise: Make a method for finding the next available member ID in an ArrayList of member objects. I create the member ID's manually when creating a new member, and i can always assume that the members have been arranged in order by ID.
For example: If i have 4 members with ID's from 0-3, and i remove the 2nd member, the method should return 1. </p>

<p>Here is the messy part i have for now: </p>

```<code>public int getNextID (){
    int i;
    for(i = 0; i < members.size(); i++){
        if(i == members.get(i).getID()){
            i++;

        }
        else if(i != members.get(i).getID()){
            System.out.println("Next available ID:  " + i);

        } else {
            System.out.println("Next available ID: " + members.size());
            break;
        }
    }
    return i;
}
</code>```

答:
For List, use size() to get the number of elements.(also it's give you the last but 1 index used).
Index is starting from 0 and is automatically adjusted when adding or removing elements.
So you do not need to keep tracking manually for indexes.

Note, when you add on list with method add(index, element) index should always be less then or equal to size()_methods return.

```<code>    List<String> l = new ArrayList<String>();
    l.add("a"); //auto index 0
    l.add("b"); //auto index 1
    l.add("c"); //auto index 2
    System.out.println(l.size()); //3 and it's also next_available for add at bottom
    l.remove(1);
    l.forEach(System.out::println); //a c
    System.out.println(l.size()); // 2
    System.out.println(l.get(0)); //a
    System.out.println(l.get(1)); //c adjusted index from 2 to 1 after remove
    l.add(2,"d");
    System.out.println(l.size()); //3
    l.add(4,"e"); //error  java.lang.IndexOutOfBoundsException: Index: 4, Size: 3
</code>```

Kindly see @Sunchezz and @Evan answers for a full solution.

Body:
ive been given this Exercise: Make a method for finding the next available member ID in an ArrayList of member objects. I create the member ID's manually when creating a new member, and i can always assume that the members have been arranged in order by ID.
For example: If i have 4 members with ID's from 0-3, and i remove the 2nd member, the method should return 1.

Here is the messy part i have for now:

public int getNextID (){
    int i;
    for(i = 0; i < members.size(); i++){
        if(i == members.get(i).getID()){
            i++;

        }
        else if(i != members.get(i).getID()){
            System.out.println("Next available ID:  " + i);

        } else {
            System.out.println("Next available ID: " + members.size());
            break;
        }
    }
    return i;
}

Body:
For List, use size() to get the number of elements.(also it's give you the last but 1 index used).
Index is starting from 0 and is automatically adjusted when adding or removing elements.
So you do not need to keep tracking manually for indexes.

Note, when you add on list with method add(index, element) index should always be less then or equal to size()_methods return.

    List<String> l = new ArrayList<String>();
    l.add("a"); //auto index 0
    l.add("b"); //auto index 1
    l.add("c"); //auto index 2
    System.out.println(l.size()); //3 and it's also next_available for add at bottom
    l.remove(1);
    l.forEach(System.out::println); //a c
    System.out.println(l.size()); // 2
    System.out.println(l.get(0)); //a
    System.out.println(l.get(1)); //c adjusted index from 2 to 1 after remove
    l.add(2,"d");
    System.out.println(l.size()); //3
    l.add(4,"e"); //error  java.lang.IndexOutOfBoundsException: Index: 4, Size: 3

Kindly see @Sunchezz and @Evan answers for a full solution.


答:
There is an existing feature request for named tuples in TypeScript, but they are not currently supported.

In the mean time, you can either use the unnamed tuple like you have, or use an object:

```<code>interface IError {
  errorOccurred: boolean;
  message?: string;
}
</code>```

Another option depending on your use case may be for errorOccurred to be implicit based on whether there is an error object at all or whether it has a message.

Title: Typescript named definition in interface Array

Body:
Let's say for example I have an interface which defines a boolean value and optional string:

Example

interface IError {
  error: [boolean, string?];
}

Now later in the code I want to use it:

if (somethingTrue) {
  error: [false]
} else {
  error: [true, "Error occurred because of foo"]
}

I got this working. However, I would like to add more context to the Interface. The boolean should be named errorOccured and the string should be named message.

Tried

I was thinking about the following:

interface IError {
  error: [errorOccured: boolean, message: string?];
}

Might be something obvious that I'm missing, but I just don't get it.

Body:
There is an existing feature request for named tuples in TypeScript, but they are not currently supported.

In the mean time, you can either use the unnamed tuple like you have, or use an object:

interface IError {
  errorOccurred: boolean;
  message?: string;
}

Another option depending on your use case may be for errorOccurred to be implicit based on whether there is an error object at all or whether it has a message.


问:
NoSuchMethodError: The method 'ancestorStateOfType' was called on null with await and async method
i would like to create a loader data, at the end the load of the data the screen will automaticly change the screen (with Navigator).

BUT i have some problem.

```<code>Unhandled Exception: NoSuchMethodError: The method 'ancestorStateOfType' was called on null.
</code>```

At the end of the method "getDataOfUser()" the "print(a)" executed fine but when it try to change the screen it crash and i have this error :

```<code>E/flutter (32148): [ERROR:flutter/lib/ui/ui_dart_state.cc(148)] Unhandled Exception: NoSuchMethodError: The method 'ancestorStateOfType' was called on null.
E/flutter (32148): Receiver: null
E/flutter (32148): Tried calling: ancestorStateOfType(Instance of 'TypeMatcher<NavigatorState>')
E/flutter (32148): #0      Object.noSuchMethod (dart:core-patch/object_patch.dart:50:5)
E/flutter (32148): #1      Navigator.of (package:flutter/src/widgets/navigator.dart:1446:19)
E/flutter (32148): #2      LoginScreenPresenter.initState.<anonymous closure> (package:test_app/login_presenter.dart:35:17)
</code>```

class loginPresenter extends StatefulWidget {
  Vendeur v;
  loginPresenter({Key key, this.v}) : super(key: key);

  @override
  LoginScreenPresenter createState() => new LoginScreenPresenter();
}

class LoginScreenPresenter extends State<loginPresenter> {
  RestDatasource api = new RestDatasource();

  BuildContext context;

  bool finish = false;

  @override
  void initState() {
    getDataOfUser(widget.v).then((a) {
      print(a)
      Navigator.of(context).pushReplacement(new MaterialPageRoute(
          builder: (BuildContext context) => HomePage(
                v: widget.v,
              )));
    });

    super.initState();
  }

  Future<bool> getDataOfUser(Vendeur user) async {

    await api.getRegionsFromUser(user.idV).then((list) async {
      if (list != null) {
        for (var i = 0; i < list.length; ++i) {
          await DBProvider.db.newRegion(list[i], 1);
        }
      }
    });

    await api.getClientsFromUser(user.idV).then((list) async {
      if (list != null) {
        for (var i = 0; i < list.length; ++i) {
          await DBProvider.db.newClient(list[i], 1);
        }
      }
    });

    await api.getInterlocuteursFromUser(user.idV).then((list) async {
      if (list != null) {
        for (var i = 0; i < list.length; ++i) {
          await DBProvider.db.newInterlocuteurs(list[i], 1);
        }
      }
    });

    await api.getVisitesFromUser(user.idV).then((list) async {
      if (list != null) {
        for (var i = 0; i < list.length; ++i) {
          await DBProvider.db.newVisite(list[i], 1);
        }
      }
    });

    await api.getAvoirsFromUser(user.idV).then((list) async {
      if (list != null) {
        for (var i = 0; i < list.length; ++i) {
          if (list[i].deleted == 0) {
            await DBProvider.db.newAvoir(list[i], 1);
          }
        }
      }
    });

    await api.getRapportsFromUser(user.idV).then((list) async {
      if (list != null) {
        for (var i = 0; i < list.length; ++i) {
          await DBProvider.db.newRapport(list[i], user);
        }
      }
    });

    return true;
  }

  @override
  Widget build(context) {
    return RaisedButton(
      onPressed: () {
        Navigator.push(
            context,
            SlideRightRoute(
                widget: HomePage(
              v: widget.v,
            )));
      },
      child: Text('go'),
    );

  }

}
```

答:
Your context was never assigned. You are calling Navigator using that context while it is still null. Try to assign it with the context from the page when it is built.

```<code>@override
Widget build(context) {
  setState(() => this.context = context);
  ...
}
</code>```

Body:
i would like to create a loader data, at the end the load of the data the screen will automaticly change the screen (with Navigator).

BUT i have some problem.

Unhandled Exception: NoSuchMethodError: The method 'ancestorStateOfType' was called on null.

At the end of the method "getDataOfUser()" the "print(a)" executed fine but when it try to change the screen it crash and i have this error :

E/flutter (32148): [ERROR:flutter/lib/ui/ui_dart_state.cc(148)] Unhandled Exception: NoSuchMethodError: The method 'ancestorStateOfType' was called on null.
E/flutter (32148): Receiver: null
E/flutter (32148): Tried calling: ancestorStateOfType(Instance of 'TypeMatcher<NavigatorState>')
E/flutter (32148): #0      Object.noSuchMethod (dart:core-patch/object_patch.dart:50:5)
E/flutter (32148): #1      Navigator.of (package:flutter/src/widgets/navigator.dart:1446:19)
E/flutter (32148): #2      LoginScreenPresenter.initState.<anonymous closure> (package:test_app/login_presenter.dart:35:17)

class loginPresenter extends StatefulWidget {
  Vendeur v;
  loginPresenter({Key key, this.v}) : super(key: key);

  @override
  LoginScreenPresenter createState() => new LoginScreenPresenter();
}

class LoginScreenPresenter extends State<loginPresenter> {
  RestDatasource api = new RestDatasource();

  BuildContext context;

  bool finish = false;

  @override
  void initState() {
    getDataOfUser(widget.v).then((a) {
      print(a)
      Navigator.of(context).pushReplacement(new MaterialPageRoute(
          builder: (BuildContext context) => HomePage(
                v: widget.v,
              )));
    });

    super.initState();
  }

  Future<bool> getDataOfUser(Vendeur user) async {

    await api.getRegionsFromUser(user.idV).then((list) async {
      if (list != null) {
        for (var i = 0; i < list.length; ++i) {
          await DBProvider.db.newRegion(list[i], 1);
        }
      }
    });

    await api.getClientsFromUser(user.idV).then((list) async {
      if (list != null) {
        for (var i = 0; i < list.length; ++i) {
          await DBProvider.db.newClient(list[i], 1);
        }
      }
    });

    await api.getInterlocuteursFromUser(user.idV).then((list) async {
      if (list != null) {
        for (var i = 0; i < list.length; ++i) {
          await DBProvider.db.newInterlocuteurs(list[i], 1);
        }
      }
    });

    await api.getVisitesFromUser(user.idV).then((list) async {
      if (list != null) {
        for (var i = 0; i < list.length; ++i) {
          await DBProvider.db.newVisite(list[i], 1);
        }
      }
    });

    await api.getAvoirsFromUser(user.idV).then((list) async {
      if (list != null) {
        for (var i = 0; i < list.length; ++i) {
          if (list[i].deleted == 0) {
            await DBProvider.db.newAvoir(list[i], 1);
          }
        }
      }
    });

    await api.getRapportsFromUser(user.idV).then((list) async {
      if (list != null) {
        for (var i = 0; i < list.length; ++i) {
          await DBProvider.db.newRapport(list[i], user);
        }
      }
    });

    return true;
  }

  @override
  Widget build(context) {
    return RaisedButton(
      onPressed: () {
        Navigator.push(
            context,
            SlideRightRoute(
                widget: HomePage(
              v: widget.v,
            )));
      },
      child: Text('go'),
    );

  }

}

Body:
Your context was never assigned. You are calling Navigator using that context while it is still null. Try to assign it with the context from the page when it is built.

@override
Widget build(context) {
  setState(() => this.context = context);
  ...
}


问:
How to disable creating/copying obj outside a Factory-Method?
I have a class, that has very heavy payload, so that it is very expensive to create/copy/move an instance of this class.
Since they will not change after the app has finished initialization, there is no need to create temporary objects of this class anywere. I only need to cache objects in a container(std::map), and offer a "const reference" when needed.

The thing that must be emphasized is that I'm seeking a solution which can avoid double-create or unnecessary copy a object before add it into the container(I don't think a solution likes one @getsoubl proposed can resolve the problem, because it does not eliminate doulbe-creating or unnecessary copying).

So I want to arrange the constructor method into "private/protected" section of the class body, so as to forbid any of creating/copying/moving outside of the "Factory-Method". Following is my original solution:

```<code>class MyClass {
public:
   // methods of the class
   static const MyClass & findObject( int iKey ) {
      auto pair = mapObjects.try_emplace( iKey, iKey );
      if ( pair.second )
         cout << "New object has been created" << endl;

      return pair.first->second;
   };

   // deleted
   MyClass() = delete;
   MyClass( MyClass & ) = delete;
   MyClass( MyClass && ) = delete;
   MyClass( const MyClass & ) = delete;
   MyClass( const MyClass && ) = delete;
   MyClass & operator=( MyClass & ) = delete;
   MyClass & operator=( MyClass && ) = delete;
   MyClass & operator=( const MyClass & ) = delete;
   MyClass & operator=( const MyClass && ) = delete;

private:
   // vars of the class
   static map<int, MyClass> mapObjects;

   // vars of instance
   string some_heavy_payload;

   // methods of instance
   MyClass( int iKey ) :
     some_heavy_payload( std::to_string( iKey ) ) {};
};

map<int, MyClass> MyClass::mapObjects;

int main() {
   const MyClass & obj = MyClass::findObject( 1 );
   return EXIT_SUCCESS;
};
</code>```

But I'm put into a contradiction that the "std::try-emplace" can NOT also call the constructor of MyClass.
The compiler reports: "error: ‘MyClass::MyClass(int)’ is private within this context".

So I tried the solution 2:

```<code>class MyClass {
public:
   // methods of the class
   static const MyClass & findObject( int iKey ) {
      if ( mapObjects.find( iKey ) == mapObjects.cend() )
         mapObjects[iKey] = MyClass( iKey );

      return mapObjects[iKey];
   };

   // deleted
   MyClass() = delete;
   MyClass( MyClass & ) = delete;
   MyClass( MyClass && ) = delete;
   MyClass( const MyClass & ) = delete;
   MyClass( const MyClass && ) = delete;
   MyClass & operator=( MyClass & ) = delete;
   MyClass & operator=( const MyClass & ) = delete;
   MyClass & operator=( const MyClass && ) = delete;

private:
   // vars of the class
   static map<int, MyClass> mapObjects;

   // vars of instance
   string some_heavy_payload;

   // methods of instance
   MyClass( int iKey ) {
      some_heavy_payload = std::to_string( iKey );
   };
   MyClass & operator=( MyClass && src ) {
      some_heavy_payload = std::move( src.some_heavy_payload );
      return *this;
   };
};

map<int, MyClass> MyClass::mapObjects;

int main() {
   const MyClass & obj = MyClass::findObject( 1 );

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

This time I got a error: "use of deleted function ‘MyClass::MyClass()’".
I guess that is resulted by "[]" operator of std::map, because it tries to call the default constructor of MyClass.

How can I get it done?

答:
You can achieve this by using a map of pointers (which are cheap to copy or move into the map), rather than a map of objects, and if you use a map of smart pointers then you can still have the map manage the lifetime of the objects within it.

Here is some proof-of-concept code which should let you take the idea forward.  In practise, createA and the map would be hidden away inside some factory function to to populate the map.

Note that As constructor is private and that we cannot copy a unique_ptr, only move it.  Also, make_unique is off-limits because A has a private constructor, but that's no big deal, cost-wise.  Copying pointers is cheap.

```<code>#include <iostream>
#include <map>
#include <memory>

class A
{
    A () { std::cout << "Create A" << '\n'; }
    A (const A &) = delete;
    A &operator= (const A&) = delete;
    A (A &&) = delete;
    A &operator= (const A&&) = delete;
public:
    ~A () { std::cout << "Destroy A" << '\n'; }
    friend void createA (int key);
};

static std::map <int, std::unique_ptr <A>> objects;

void createA (int key)
{
    std::unique_ptr <A> a (new A);
    objects.insert (std::pair <int, std::unique_ptr <A>> (key, std::move (a)));
}

int main ()
{
    createA (1);
    createA (2);
}
</code>```

Output (showing object lifetime management by the map):

```<code>Create A
Create A
Destroy A
Destroy A
</code>```

Live demo

Alternatively, write an efficient move constructor (which is not usually difficult) and move your objects into your map rather than copying them, like so:

```<code>#include <iostream>
#include <map>
#include <memory>

class A
{
    A () { std::cout << "Create A" << '\n'; }
    A (const A &) = delete;
    A &operator= (const A&) = delete;
    A &operator= (const A&&) = delete;
public:
    A (const A &&) { std::cout << "Move A" << '\n'; }
    ~A () { std::cout << "Destroy A" << '\n'; }
    friend void createA (int key);
};

static std::map <int, A> objects;

void createA (int key)
{
    A a;
    objects.insert (std::pair <int, A> (key, std::move (a)));
}

int main ()
{
    createA (1);
    createA (2);
}
</code>```

Output:

```<code>Create A
Move A
Move A
Destroy A
Destroy A
Create A
Move A
Move A
Destroy A
Destroy A
Destroy A
Destroy A
</code>```

Live demo

Body:
I have a class, that has very heavy payload, so that it is very expensive to create/copy/move an instance of this class.
Since they will not change after the app has finished initialization, there is no need to create temporary objects of this class anywere. I only need to cache objects in a container(std::map), and offer a "const reference" when needed.

The thing that must be emphasized is that I'm seeking a solution which can avoid double-create or unnecessary copy a object before add it into the container(I don't think a solution likes one @getsoubl proposed can resolve the problem, because it does not eliminate doulbe-creating or unnecessary copying).

So I want to arrange the constructor method into "private/protected" section of the class body, so as to forbid any of creating/copying/moving outside of the "Factory-Method". Following is my original solution:

class MyClass {
public:
   // methods of the class
   static const MyClass & findObject( int iKey ) {
      auto pair = mapObjects.try_emplace( iKey, iKey );
      if ( pair.second )
         cout << "New object has been created" << endl;

      return pair.first->second;
   };

   // deleted
   MyClass() = delete;
   MyClass( MyClass & ) = delete;
   MyClass( MyClass && ) = delete;
   MyClass( const MyClass & ) = delete;
   MyClass( const MyClass && ) = delete;
   MyClass & operator=( MyClass & ) = delete;
   MyClass & operator=( MyClass && ) = delete;
   MyClass & operator=( const MyClass & ) = delete;
   MyClass & operator=( const MyClass && ) = delete;

private:
   // vars of the class
   static map<int, MyClass> mapObjects;

   // vars of instance
   string some_heavy_payload;

   // methods of instance
   MyClass( int iKey ) :
     some_heavy_payload( std::to_string( iKey ) ) {};
};

map<int, MyClass> MyClass::mapObjects;

int main() {
   const MyClass & obj = MyClass::findObject( 1 );
   return EXIT_SUCCESS;
};

But I'm put into a contradiction that the "std::try-emplace" can NOT also call the constructor of MyClass.
The compiler reports: "error: ‘MyClass::MyClass(int)’ is private within this context".

So I tried the solution 2:

class MyClass {
public:
   // methods of the class
   static const MyClass & findObject( int iKey ) {
      if ( mapObjects.find( iKey ) == mapObjects.cend() )
         mapObjects[iKey] = MyClass( iKey );

      return mapObjects[iKey];
   };

   // deleted
   MyClass() = delete;
   MyClass( MyClass & ) = delete;
   MyClass( MyClass && ) = delete;
   MyClass( const MyClass & ) = delete;
   MyClass( const MyClass && ) = delete;
   MyClass & operator=( MyClass & ) = delete;
   MyClass & operator=( const MyClass & ) = delete;
   MyClass & operator=( const MyClass && ) = delete;

private:
   // vars of the class
   static map<int, MyClass> mapObjects;

   // vars of instance
   string some_heavy_payload;

   // methods of instance
   MyClass( int iKey ) {
      some_heavy_payload = std::to_string( iKey );
   };
   MyClass & operator=( MyClass && src ) {
      some_heavy_payload = std::move( src.some_heavy_payload );
      return *this;
   };
};

map<int, MyClass> MyClass::mapObjects;

int main() {
   const MyClass & obj = MyClass::findObject( 1 );

   return EXIT_SUCCESS;
};

This time I got a error: "use of deleted function ‘MyClass::MyClass()’".
I guess that is resulted by "[]" operator of std::map, because it tries to call the default constructor of MyClass.

How can I get it done?

Body:
You can achieve this by using a map of pointers (which are cheap to copy or move into the map), rather than a map of objects, and if you use a map of smart pointers then you can still have the map manage the lifetime of the objects within it.

Here is some proof-of-concept code which should let you take the idea forward.  In practise, createA and the map would be hidden away inside some factory function to to populate the map.

Note that As constructor is private and that we cannot copy a unique_ptr, only move it.  Also, make_unique is off-limits because A has a private constructor, but that's no big deal, cost-wise.  Copying pointers is cheap.

#include <iostream>
#include <map>
#include <memory>

class A
{
    A () { std::cout << "Create A" << '\n'; }
    A (const A &) = delete;
    A &operator= (const A&) = delete;
    A (A &&) = delete;
    A &operator= (const A&&) = delete;
public:
    ~A () { std::cout << "Destroy A" << '\n'; }
    friend void createA (int key);
};

static std::map <int, std::unique_ptr <A>> objects;

void createA (int key)
{
    std::unique_ptr <A> a (new A);
    objects.insert (std::pair <int, std::unique_ptr <A>> (key, std::move (a)));
}

int main ()
{
    createA (1);
    createA (2);
}

Output (showing object lifetime management by the map):

Create A
Create A
Destroy A
Destroy A

Live demo

Alternatively, write an efficient move constructor (which is not usually difficult) and move your objects into your map rather than copying them, like so:

#include <iostream>
#include <map>
#include <memory>

class A
{
    A () { std::cout << "Create A" << '\n'; }
    A (const A &) = delete;
    A &operator= (const A&) = delete;
    A &operator= (const A&&) = delete;
public:
    A (const A &&) { std::cout << "Move A" << '\n'; }
    ~A () { std::cout << "Destroy A" << '\n'; }
    friend void createA (int key);
};

static std::map <int, A> objects;

void createA (int key)
{
    A a;
    objects.insert (std::pair <int, A> (key, std::move (a)));
}

int main ()
{
    createA (1);
    createA (2);
}

Output:

Create A
Move A
Move A
Destroy A
Destroy A
Create A
Move A
Move A
Destroy A
Destroy A
Destroy A
Destroy A

Live demo


问:
AWS CodeBuild Docker image with ASP.NET Core 2.2
I want to build my project in AWS with ASP.NET Core 2.2, and since AWS unfortunately does not have their own build image available for that, I'm trying to use the Docker image mcr.microsoft.com/dotnet/core/sdk:2.2.

It was getting stuck on pip install --upgrade awscli... I think because pip is not installed on the image. So I've tried to fix that by installing pip and I am getting this error:

Phase context status code: COMMAND_EXECUTION_ERROR Message: Error while executing command: apt-get install python3-dev. Reason: exit status 1

My troubleshooting attempts have included:

toggling the Privileged flag for the CodeBuild Environment

including and not including sudo in my buildspec.yml commands

trying both pip and pip3

Here is my current buildspec.yml:

```<code>version: 0.2
phases:
  pre_build:
    commands:
      - apt-get update --fix-missing
      - apt-get install -y apt-transport-https
      - apt-get update
      - apt-get install python3-dev
      - apt-get install python3-pip
      - pip3 install --upgrade awscli
      - dotnet restore AspNetCoreWebApplication/AspNetCoreWebApplication.csproj
      - dotnet restore AspNetCoreWebApplicationTest/AspNetCoreWebApplicationTest.csproj
  build:
    commands:
      .....the rest omitted for brevity......
</code>```

My question is why is this not working?

答:
Found the problem. These commands:

```<code>apt-get install python3-dev
apt-get install python3-pip
</code>```

need to include the -y flag to automatically say yes to any prompts from the commands.

Adding the flags like this works:

```<code>apt-get install -y python3-dev
apt-get install -y python3-pip
</code>```

Body:
I want to build my project in AWS with ASP.NET Core 2.2, and since AWS unfortunately does not have their own build image available for that, I'm trying to use the Docker image mcr.microsoft.com/dotnet/core/sdk:2.2.

It was getting stuck on pip install --upgrade awscli... I think because pip is not installed on the image. So I've tried to fix that by installing pip and I am getting this error:

Phase context status code: COMMAND_EXECUTION_ERROR Message: Error while executing command: apt-get install python3-dev. Reason: exit status 1

My troubleshooting attempts have included:

toggling the Privileged flag for the CodeBuild Environment

including and not including sudo in my buildspec.yml commands

trying both pip and pip3

Here is my current buildspec.yml:

version: 0.2
phases:
  pre_build:
    commands:
      - apt-get update --fix-missing
      - apt-get install -y apt-transport-https
      - apt-get update
      - apt-get install python3-dev
      - apt-get install python3-pip
      - pip3 install --upgrade awscli
      - dotnet restore AspNetCoreWebApplication/AspNetCoreWebApplication.csproj
      - dotnet restore AspNetCoreWebApplicationTest/AspNetCoreWebApplicationTest.csproj
  build:
    commands:
      .....the rest omitted for brevity......

My question is why is this not working?

Body:
Found the problem. These commands:

apt-get install python3-dev
apt-get install python3-pip

need to include the -y flag to automatically say yes to any prompts from the commands.

Adding the flags like this works:

apt-get install -y python3-dev
apt-get install -y python3-pip


问:
How to fix "SSL error: certificate verify failed"
I started a bash code that tries to download a file via axel, but when the script is about to download the file, it crashes and the error SSL error: certificate verify failed.

Can someone please help me with that, like adding an exception via command-line?

Part of the code:

```<code>axel ${EXTRAARGS} --alternate "https://build.nethunter.com/kalifs/kalifs-20171013/kalifs-armhf-minimal.tar.xz "
</code>```

Other variables were already declared.
The result is:

```<code>Initializing download: https://build.nethunter.com/kalifs/kalifs-20171013/kalifs-armhf-minimal.tar.xz<br>
SSL error: certificate verify failed
</code>```

Thanks anyway.

答:
Did you try man axel? From the man page:

```<code>   --insecure, -k
          Do not verify the SSL certificate. Only use this if
          you are getting certificate errors and you are sure
          of the sites authenticity.
</code>```

Body:
I started a bash code that tries to download a file via axel, but when the script is about to download the file, it crashes and the error SSL error: certificate verify failed.

Can someone please help me with that, like adding an exception via command-line?

Part of the code:

axel ${EXTRAARGS} --alternate "https://build.nethunter.com/kalifs/kalifs-20171013/kalifs-armhf-minimal.tar.xz "

Other variables were already declared.
The result is:

Initializing download: https://build.nethunter.com/kalifs/kalifs-20171013/kalifs-armhf-minimal.tar.xz

SSL error: certificate verify failed

Thanks anyway.

Body:
Did you try man axel? From the man page:

   --insecure, -k
          Do not verify the SSL certificate. Only use this if
          you are getting certificate errors and you are sure
          of the sites authenticity.


问:
Make a background image transparent using CSS
I have a scenario where I need a transparent background image but I have no control over the dynamically generated images I use. For that reason Transparent PNG is out of the question. All child elements within the same div should NOT be effected and should be fully visible.

I know how to apply transparency to background colours and block level elements but can you do this for a background image?

答:
Setting the opacity of the element with the background is a good start, but you'll see that any elements within the one whose opacity is changed will also be transparent.

The way around that is to have an element that contains the background and is transparent (opacity:0.6; filter:alpha(opacity=60)), and then float or position the container with the actual content over it.

Here's a sample of how this approach would work:

#container {
    width: 200px;
    postiion: relative;
  }

  #semitrans {
    width: 100%; height: 100px;
    background: #f00;
    opacity: 0.6;
    filter:alpha(opacity=60);
  }

  #hello {
    width: 100%; height: 100px;
    position: absolute;
    top: 20px; left: 20px;
  }
  ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="container">
    <div id="semitrans"></div>
    <p id="hello">Hello World</p>
</div></code>```

Body:
Setting the opacity of the element with the background is a good start, but you'll see that any elements within the one whose opacity is changed will also be transparent.

The way around that is to have an element that contains the background and is transparent (opacity:0.6; filter:alpha(opacity=60)), and then float or position the container with the actual content over it.

Here's a sample of how this approach would work:

#container {
    width: 200px;
    postiion: relative;
  }

  #semitrans {
    width: 100%; height: 100px;
    background: #f00;
    opacity: 0.6;
    filter:alpha(opacity=60);
  }

  #hello {
    width: 100%; height: 100px;
    position: absolute;
    top: 20px; left: 20px;
  }

<div id="container">
    <div id="semitrans"></div>
    <p id="hello">Hello World</p>
</div>


问:
Design a turing machine that accepts the language L= {a^n+1 b^2n c^3n: n>=0}
I need some help with designing Turing machine that accepts language
L= {a^n+1 b^2n c^3n: n>=0}</p>

答:
There are a lot of correct ways to do this. I will just walk through one of them I hope illustrates a useful way to attack these problems.

First, we notice the commonality n between the three segments. We will cross off symbols from each section, one at a time, to make sure they have the right relationships. First, we can verify that the relationship between a and b is right. Then, we can check the relationship between a and c. If those are both right, we are done.

First, let's get rid of the pesky "+1" from the a. This means we have at least one a regardless of what n is. So, we can begin by changing a to X. Now, the remaining input should have n instances of a, 2n instances of b and 3n instances of c. If we don't have the one a, we can halt-reject immediately; we can't have n+1 instances of a if we don't have at least one.

Now, if there are more instances of a, cross it off by writing A in its place, and go cross off two instances of b by writing B in their places. Then, go back and look for more instances of a, bouncing back and forth until there are no more instances of a. Then, verify there are no more instances of b; if so, there were twice as many instances of b as there were of a, and the first two sections have the right relationship. If at any point you didn't have enough b to cross off, or if after you ran out of a you still had b, then you can safely halt-reject at this point.

Next, you can do the same thing for instances of A and c, just cross off three instances of c instead of two. If we find the A get exhausted at the same time as the c do, we are done and halt-accept.

The transitions might look like this:

```<code>Q    T    Q'    T'    d        comment
q0   a    q1    X     right    account for +1

q1   a    q2    A     right    n>0 case, continue
q1   #    hA    #     same     n=0 case, accept

q2   a    q2    a     right    skip uncrossed a
q2   B    q2    B     right    skip crossed b
q2   b    q3    B     right    find first uncrossed b, cross it

q3   b    q4    B     left     find next b, cross it

q4   B    q4    B     left     find last uncrossed a
q4   a    q2    A     right    cross it
q4   A    q4    A     left     skip crossed a, if any
q4   X    q5    X     right    ran out of a to cross

q5   A    q5    A     right    skip crossed a
q5   B    q5    B     right    skip crossed b
q5   c    q6    c     left     verify existence of some c

q6   C    q6    C     left     skip crossed c
q6   B    q6    B     left     skip crossed b
q6   A    q7    a     right    find last crossed a, uncross
q6   X    q10   X     right    ran out of crossed a

q7   a    q7    a     right    skip uncrossed a
q7   B    q7    B     right    skip crossed b
q7   C    q7    C     right    skip crossed c
q7   c    q8    C     right    find first uncrossed c, cross
q8   c    q9    C     right    cross 2nd uncrossed c
q9   c    q6    C     left     cross 3rd uncrossed c

q10  a    q10   a     right    skip uncrossed a
q10  B    q10   B     right    skip crossed b
q10  C    q10   C     right    skip crossed c
q10  #    hA    #     same     accept if no leftover symbols until end
</code>```

Body:
There are a lot of correct ways to do this. I will just walk through one of them I hope illustrates a useful way to attack these problems.

First, we notice the commonality n between the three segments. We will cross off symbols from each section, one at a time, to make sure they have the right relationships. First, we can verify that the relationship between a and b is right. Then, we can check the relationship between a and c. If those are both right, we are done.

First, let's get rid of the pesky "+1" from the a. This means we have at least one a regardless of what n is. So, we can begin by changing a to X. Now, the remaining input should have n instances of a, 2n instances of b and 3n instances of c. If we don't have the one a, we can halt-reject immediately; we can't have n+1 instances of a if we don't have at least one.

Now, if there are more instances of a, cross it off by writing A in its place, and go cross off two instances of b by writing B in their places. Then, go back and look for more instances of a, bouncing back and forth until there are no more instances of a. Then, verify there are no more instances of b; if so, there were twice as many instances of b as there were of a, and the first two sections have the right relationship. If at any point you didn't have enough b to cross off, or if after you ran out of a you still had b, then you can safely halt-reject at this point.

Next, you can do the same thing for instances of A and c, just cross off three instances of c instead of two. If we find the A get exhausted at the same time as the c do, we are done and halt-accept.

The transitions might look like this:

Q    T    Q'    T'    d        comment
q0   a    q1    X     right    account for +1

q1   a    q2    A     right    n>0 case, continue
q1   #    hA    #     same     n=0 case, accept

q2   a    q2    a     right    skip uncrossed a
q2   B    q2    B     right    skip crossed b
q2   b    q3    B     right    find first uncrossed b, cross it

q3   b    q4    B     left     find next b, cross it

q4   B    q4    B     left     find last uncrossed a
q4   a    q2    A     right    cross it
q4   A    q4    A     left     skip crossed a, if any
q4   X    q5    X     right    ran out of a to cross

q5   A    q5    A     right    skip crossed a
q5   B    q5    B     right    skip crossed b
q5   c    q6    c     left     verify existence of some c

q6   C    q6    C     left     skip crossed c
q6   B    q6    B     left     skip crossed b
q6   A    q7    a     right    find last crossed a, uncross
q6   X    q10   X     right    ran out of crossed a

q7   a    q7    a     right    skip uncrossed a
q7   B    q7    B     right    skip crossed b
q7   C    q7    C     right    skip crossed c
q7   c    q8    C     right    find first uncrossed c, cross
q8   c    q9    C     right    cross 2nd uncrossed c
q9   c    q6    C     left     cross 3rd uncrossed c

q10  a    q10   a     right    skip uncrossed a
q10  B    q10   B     right    skip crossed b
q10  C    q10   C     right    skip crossed c
q10  #    hA    #     same     accept if no leftover symbols until end


问:
Load CSV file from S3 to postgressql
Am new to AWS ,I have CSV file in amazon S3, now I want to read and import the CSV file in to aws postgres table using java.

I know we can use the below commands in CLI,

```<code>aws s3 cp s3://bucket/file.csv /mydirectory/file.csv
psql -h your_rds.amazonaws.com -U username -d dbname -c '\COPY table FROM ''file.csv'' CSV HEADER'
</code>```

But I need to run it in java.

Can anyone please suggest me any solution.

答:
If can use other options, can explore:

Load S3 Data into Amazon RDS MySQL Table

But if has to be Java, then you may AWS Lambda, as this looks to be administrative activity

Read file from S3

How to read S3 file from AWS Lambda Function written in Java?

Load into RDS ( code sample ):

Import CSV file into mysql using Java

Title: Load CSV file from S3 to postgressql

Body:
Am new to AWS ,I have CSV file in amazon S3, now I want to read and import the CSV file in to aws postgres table using java.

I know we can use the below commands in CLI,

aws s3 cp s3://bucket/file.csv /mydirectory/file.csv
psql -h your_rds.amazonaws.com -U username -d dbname -c '\COPY table FROM ''file.csv'' CSV HEADER'

But I need to run it in java.

Can anyone please suggest me any solution.


问:
Best UML designing tool in Linux?
Urgently want to know best UML designing tool in Linux?
Which Also Support ERD
Is it Possible to use in NetBEANs IDE 6.9.1</p>

答: I never had any problems with dia. It's part of gnome, almost all distributions package it. Also has a Windows version but I didn't use that one for a long time. Of course, "best" is relative to what you are expecting from it.</p>

Title: Best UML designing tool in Linux?


问:
MAMP can't load php_memcache.dll
I am using PHP 7.2.1 with MAMP PRO 4 on Windows 10.

When an exec() function in php handles large files (>100M), my code stops and I keep getting an internal server error (500). (Even though the exec() still continues and finishes in the background)

MAMP has logged them as

PHP Warning:  PHP Startup: Unable to load dynamic library 'php_memcache.dll' (tried: C:\MAMP\bin\php\php7.2.1\ext\php_memcache.dll (The specified procedure could not be found.
  ), C:\MAMP\bin\php\php7.2.1\ext\php_php_memcache.dll.dll (The specified module could not be found.
  )) in Unknown on line 0

(translated from Dutch).

Memcached is activated in MAMP

C:\MAMP\bin\php\php7.2.1\ext\php_memcache.dll exists

and my php.ini contains extension=php_memcache.dll

FYI the exec is

```<code>exec('"C:\Program Files\LibreOffice 5\program\soffice.exe" --headless --convert-to pdf --outdir "path/to/output" "path/to/input/presentation.pptx"');
</code>```

and will continue its job even after the server error is displayed on screen. (the PDF is created without problems)

For smaller files there is no problem at all, and the rest of my PHP will execute as expected.

答:
I had this same issue, I resolved it by doing the following

go to C:\MAMP\bin\php

select any folder having name php7.2.6 and above

copy the path name and set it in the enviroment variables

for me I chose 7.2.8
set this path C:\MAMP\bin\php\php7.2.8 in enviroment variables

Title: MAMP can't load php_memcache.dll

Body:
I am using PHP 7.2.1 with MAMP PRO 4 on Windows 10.

When an exec() function in php handles large files (>100M), my code stops and I keep getting an internal server error (500). (Even though the exec() still continues and finishes in the background)

MAMP has logged them as

PHP Warning:  PHP Startup: Unable to load dynamic library 'php_memcache.dll' (tried: C:\MAMP\bin\php\php7.2.1\ext\php_memcache.dll (The specified procedure could not be found.
  ), C:\MAMP\bin\php\php7.2.1\ext\php_php_memcache.dll.dll (The specified module could not be found.
  )) in Unknown on line 0

(translated from Dutch).

Memcached is activated in MAMP

C:\MAMP\bin\php\php7.2.1\ext\php_memcache.dll exists

and my php.ini contains extension=php_memcache.dll

FYI the exec is

exec('"C:\Program Files\LibreOffice 5\program\soffice.exe" --headless --convert-to pdf --outdir "path/to/output" "path/to/input/presentation.pptx"');

and will continue its job even after the server error is displayed on screen. (the PDF is created without problems)

For smaller files there is no problem at all, and the rest of my PHP will execute as expected.


问:
Automatic MD5 column in Entity Framework
We are starting a new project here and as a premise, every row in every table must have a md5 column calculated with the other columns contents, to check if it was modified outside the application (using manual updates or inserts).

There are already any solution for that?

答: You can use Triggers package by Nick Strupat. This gives you a possibility to react on every row's inserting/updating. In triggers implementation you can calculate MD5 for the actual data.</p>


问:
How do I run a Java program from the command line on Windows?
I'm trying to execute a Java program from the command line in Windows.

Here is my code:

```<code>import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class CopyFile {
    public static void main(String[] args) {
        InputStream inStream = null;
        OutputStream outStream = null;

        try {
            File afile = new File("input.txt");
            File bfile = new File("inputCopy.txt");

            inStream = new FileInputStream(afile);
            outStream = new FileOutputStream(bfile);

            byte[] buffer = new byte[1024];

            int length;

            // copy the file content in bytes
            while ((length = inStream.read(buffer)) > 0) {
                outStream.write(buffer, 0, length);
            }

            inStream.close();
            outStream.close();

            System.out.println("File is copied successful!");

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
</code>```

I'm not sure how to execute the program - any help?

Is this possible on Windows?

Why is it different than another environment (I thought JVM was write once, run anywhere)?

答:
Since Java 11, java command line tool has been able to run a single-file source-code directly. e.g.

```<code>java HelloWorld.java
</code>```

This was an enhancement with JEP 330: https://openjdk.java.net/jeps/330

For the details of the usage and the limitations, see the manual of your Java implementation such as one provided by Oracle: https://docs.oracle.com/en/java/javase/11/tools/java.html

Body:
I'm trying to execute a Java program from the command line in Windows.

Here is my code:

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class CopyFile {
    public static void main(String[] args) {
        InputStream inStream = null;
        OutputStream outStream = null;

        try {
            File afile = new File("input.txt");
            File bfile = new File("inputCopy.txt");

            inStream = new FileInputStream(afile);
            outStream = new FileOutputStream(bfile);

            byte[] buffer = new byte[1024];

            int length;

            // copy the file content in bytes
            while ((length = inStream.read(buffer)) > 0) {
                outStream.write(buffer, 0, length);
            }

            inStream.close();
            outStream.close();

            System.out.println("File is copied successful!");

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

I'm not sure how to execute the program - any help?

Is this possible on Windows?

Why is it different than another environment (I thought JVM was write once, run anywhere)?

Body:
Since Java 11, java command line tool has been able to run a single-file source-code directly. e.g.

java HelloWorld.java

This was an enhancement with JEP 330: https://openjdk.java.net/jeps/330

For the details of the usage and the limitations, see the manual of your Java implementation such as one provided by Oracle: https://docs.oracle.com/en/java/javase/11/tools/java.html


问:
Efficiently add multiple lines to file by index
Given an input file data.dat like this one:

```<code># Some comment
# more comments
#
45.78
# aaa
0.056
0.67
# aaa
345.
0.78
99.
2.34
# aaa
65.7
0.9
</code>```

I need to add different comments above each line that starts with an "# aaa" so it looks like this:

```<code># Some comment
# more comments
#
45.78
# cmmt1
# aaa
0.056
0.67
# another cmmt
# aaa
345.
0.78
99.
2.34
# last one
# aaa
65.7
0.9
</code>```

I know a priori the number of "# aaa" comments present in the data.dat file,  but not their positions.

I have a way to do it (see code below) but it is quite complicated and not at all efficient. I need to apply this code to hundreds of large files, so I'm looking for an efficient way to do this.

```<code># Read file
with open("data.dat", mode="r") as f:
    data = f.readlines()

# Indexes of "# aaa" comments
idx = []
for i, line in enumerate(data):
    if line.startswith("# aaa"):
        idx.append(i)

# Insert new comments in their proper positions
add_data = ["# cmmt1\n", "# another cmmt\n", "# last one\n"]
for i, j in enumerate(idx):
    data.insert(j + i, add_data[i])

# Write final data to file
with open("data_final.dat", mode="w") as f:
    for item in data:
        f.write("{}".format(item))
</code>```

答:
When I need to change data in a text file, I try to read with one handle and immediately write with a second one.

```<code>def add_comments(input_file_name, output_file_name, list_of_comments):
    comments = iter(list_of_comments)  # or itertools.cycle(list_of_comments)
    with open(input_file_name) as fin, open(output_file_name, 'w') as fout:
        for line in fin:
            if line.startswith("# aaa"):
                fout.write(next(comments))
            fout.write(line)
</code>```

For your example code, if would be called as:

```<code>add_comments("data.dat", "final_data.dat", ["# cmmt1\n", "# another cmmt\n", "# last one\n"])
</code>```

Body:
Given an input file data.dat like this one:

# Some comment
# more comments
#
45.78
# aaa
0.056
0.67
# aaa
345.
0.78
99.
2.34
# aaa
65.7
0.9

I need to add different comments above each line that starts with an "# aaa" so it looks like this:

# Some comment
# more comments
#
45.78
# cmmt1
# aaa
0.056
0.67
# another cmmt
# aaa
345.
0.78
99.
2.34
# last one
# aaa
65.7
0.9

I know a priori the number of "# aaa" comments present in the data.dat file,  but not their positions.

I have a way to do it (see code below) but it is quite complicated and not at all efficient. I need to apply this code to hundreds of large files, so I'm looking for an efficient way to do this.

# Read file
with open("data.dat", mode="r") as f:
    data = f.readlines()

# Indexes of "# aaa" comments
idx = []
for i, line in enumerate(data):
    if line.startswith("# aaa"):
        idx.append(i)

# Insert new comments in their proper positions
add_data = ["# cmmt1\n", "# another cmmt\n", "# last one\n"]
for i, j in enumerate(idx):
    data.insert(j + i, add_data[i])

# Write final data to file
with open("data_final.dat", mode="w") as f:
    for item in data:
        f.write("{}".format(item))

Body:
When I need to change data in a text file, I try to read with one handle and immediately write with a second one.

def add_comments(input_file_name, output_file_name, list_of_comments):
    comments = iter(list_of_comments)  # or itertools.cycle(list_of_comments)
    with open(input_file_name) as fin, open(output_file_name, 'w') as fout:
        for line in fin:
            if line.startswith("# aaa"):
                fout.write(next(comments))
            fout.write(line)

For your example code, if would be called as:

add_comments("data.dat", "final_data.dat", ["# cmmt1\n", "# another cmmt\n", "# last one\n"])


问:
Spark Unable to find JDBC Driver
So I've been using sbt with assembly to package all my dependencies into a single jar for my spark jobs.  I've got several jobs where I was using c3p0 to setup connection pool information, broadcast that out, and then use foreachPartition on the RDD to then grab a connection, and insert the data into the database.  In my sbt build script, I include

```<code>"mysql" % "mysql-connector-java" % "5.1.33"
</code>```

This makes sure the JDBC connector is packaged up with the job.  Everything works great.

So recently I started playing around with SparkSQL and realized it's much easier to simply take a dataframe and save it to a jdbc source with the new features in 1.3.0

I'm getting the following exception :

java.sql.SQLException: No suitable driver found for
  jdbc:mysql://some.domain.com/myschema?user=user&password=password     at
  java.sql.DriverManager.getConnection(DriverManager.java:596)  at
  java.sql.DriverManager.getConnection(DriverManager.java:233)

When I was running this locally I got around it by setting

```<code>SPARK_CLASSPATH=/path/where/mysql-connector-is.jar
</code>```

Ultimately what I'm wanting to know is, why is the job not capable of finding the driver when it should be packaged up with it?  My other jobs never had this problem.  From what I can tell both c3p0 and the dataframe code both make use of the java.sql.DriverManager (which handles importing everything for you from what I can tell) so it should work just fine??  If there is something that prevents the assembly method from working, what do I need to do to make this work?

答: Simple easy way is to copy "mysql-connector-java-5.1.47.jar" into "spark-2.4.3\jars\" directory

Title: Spark Unable to find JDBC Driver

Body:
So I've been using sbt with assembly to package all my dependencies into a single jar for my spark jobs.  I've got several jobs where I was using c3p0 to setup connection pool information, broadcast that out, and then use foreachPartition on the RDD to then grab a connection, and insert the data into the database.  In my sbt build script, I include

"mysql" % "mysql-connector-java" % "5.1.33"

This makes sure the JDBC connector is packaged up with the job.  Everything works great.

So recently I started playing around with SparkSQL and realized it's much easier to simply take a dataframe and save it to a jdbc source with the new features in 1.3.0

I'm getting the following exception :

java.sql.SQLException: No suitable driver found for
  jdbc:mysql://some.domain.com/myschema?user=user&password=password     at
  java.sql.DriverManager.getConnection(DriverManager.java:596)  at
  java.sql.DriverManager.getConnection(DriverManager.java:233)

When I was running this locally I got around it by setting

SPARK_CLASSPATH=/path/where/mysql-connector-is.jar

Ultimately what I'm wanting to know is, why is the job not capable of finding the driver when it should be packaged up with it?  My other jobs never had this problem.  From what I can tell both c3p0 and the dataframe code both make use of the java.sql.DriverManager (which handles importing everything for you from what I can tell) so it should work just fine??  If there is something that prevents the assembly method from working, what do I need to do to make this work?


问:
Power shell script SelectSingleNode not working
```<code>   $xmlFile = "D:\ServiceConfiguration.cscfg"
   [xml]$doc = Get-Content $xmlFile
   $node = $doc.SelectSingleNode("/ServiceConfiguration/Role/ConfigurationSettings[@name='DiagnosticsConnectionString']")
   $node.value = "New-Value"
   $doc.Save($xmlFile)
</code>```

SelectSingleNode is always returning null. Please help

答:
The elements are namespace qualified so you need to specify the namespace in your query:</p>

```<code>$xmlFile = "D:\ServiceConfiguration.cscfg"
[xml]$doc = Get-Content $xmlFile
$ns = new-object Xml.XmlNamespaceManager $xml.NameTable
$ns.AddNamespace('dns', 'http://schemas.microsoft.com/ServiceHosting/2008/10/ServiceConfiguration')
$node = $doc.SelectSingleNode("/dns:ServiceConfiguration/dns:Role/dns:ConfigurationSettings[@name='DiagnosticsConnectionString']", $ns)
$node.value = "New-Value"
$doc.Save($xmlFile)
</code>```

Body:
   $xmlFile = "D:\ServiceConfiguration.cscfg"
   [xml]$doc = Get-Content $xmlFile
   $node = $doc.SelectSingleNode("/ServiceConfiguration/Role/ConfigurationSettings[@name='DiagnosticsConnectionString']")
   $node.value = "New-Value"
   $doc.Save($xmlFile)

SelectSingleNode is always returning null. Please help

Body:
The elements are namespace qualified so you need to specify the namespace in your query:

$xmlFile = "D:\ServiceConfiguration.cscfg"
[xml]$doc = Get-Content $xmlFile
$ns = new-object Xml.XmlNamespaceManager $xml.NameTable
$ns.AddNamespace('dns', 'http://schemas.microsoft.com/ServiceHosting/2008/10/ServiceConfiguration')
$node = $doc.SelectSingleNode("/dns:ServiceConfiguration/dns:Role/dns:ConfigurationSettings[@name='DiagnosticsConnectionString']", $ns)
$node.value = "New-Value"
$doc.Save($xmlFile)


问:
Automatically formatting a line with semicolon in netbeans
Yet another silly question.  I am using netbeans, and need to know how to autoformat a line when I type semicolon.

Example

```<code>type var=new type();
type var = new type();
</code>```

答:
To accomplish this do the following

Type in the statement without hitting the semicolon

Click on the red circle on editor toolbar(Start Macro Recording)

Type a semicolon followed by alt shift F followed by a backspace(needed to remove extra semicolon)

Click on the icon Stop Macro Recording (next to the Start)

NetBeans will prompt you for a macro name, I called mine formatline

Completing a statement with a semicolon will now reformat the the line.

Body:
Yet another silly question.  I am using netbeans, and need to know how to autoformat a line when I type semicolon.

Example

type var=new type();
type var = new type();


问:
How to stop service account credential printing on Jenkins console?
I have Jenkins server which builds project, build docker image and push it to Google Container Registry.

I am using service account to login to GCR using command docker login -u _json_key -p "$(cat ${service-account.json})" https://gcr.io as stated here

When this line is executed, content of service-account.json file is printed on console in Jenkins pipeline.

How would I stop credential being printed on console?

答:
The trick is to use the --password-stdin flag.

cat ${service-account.json} | docker login -u _json_key --password-stdin https://gcr.io

Provide a password using STDIN. To run the docker login command non-interactively, you can set the --password-stdin flag to provide a password through STDIN. Using STDIN prevents the password from ending up in the shell’s history, or log-files.

See https://docs.docker.com/engine/reference/commandline/login/

Note: The password file should only include the password,  and should not be json encoded.