问:
why transformer don't take any arguments?
I'm begginer in SciKitLearn, and I'm making my first transformer, but when I run it I'm getting error Transformer doesn't take any arguments</p>

```<code>class DataFrameSelector(BaseEstimator, TransformerMixin):

    def init(self, attribute_names):
        self.attribute_names = attribute_names

    def fit(self, Х,y=None):
        return self

    def transform(self,Х):
        return np.array(X[self.attribute_names])
</code>```

答: You should write __init__ instead of init.

Body:
I'm begginer in SciKitLearn, and I'm making my first transformer, but when I run it I'm getting error Transformer doesn't take any arguments

class DataFrameSelector(BaseEstimator, TransformerMixin):

    def init(self, attribute_names):
        self.attribute_names = attribute_names

    def fit(self, Х,y=None):
        return self

    def transform(self,Х):
        return np.array(X[self.attribute_names])


来源: stackexchange

问:
Will firebase and googlemaps work in huawei-mate 30
What is the scenario:

I have an application that is installed on an android device

It is using GoogleMaps & Firebase

Question:

Will GoogleMaps and Firebase used in the application work on future Huawei devices? Since Play Store nor GoogleServices are available?

答: No, Your application will only work on Huawei phones having GMS. If you want to make them work on HMS (Huawei non GMS) devices You will have to integrate the relevant kits of HMS.</p>

ContentLicense: CC BY-SA 4.0


问:
Force Browser to cache images
I am generating the images and want browser to cache them forever, but instead browser never cache them at all.
This is my php code

```<code>
header('Content-type:'.$file->content_type);
header('Expires: Thu, 15 Apr '.(date('Y')+10).' 20:00:00 GMT');
header('Content-Disposition: attachment; filename="'.$file->file_name.'"');
echo(file_get_contents($model_files->files_path.$file->md5.$model_files->seprator.$file->file_name));
</code>```

and these are the response headers which i keep getting in browser.

```<code>Date:            Thu, 02 Jun 2011 12:56:56 GMT
Server:          Apache mod_fcgid/2.3.6 mod_auth_passthrough/2.1 mod_bwlimited/1.4 FrontPage/5.0.2.2635
X-Powered-By     PHP/5.2.15
Cache-Control    no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Pragma           no-cache
Expires          Thu, 15 Apr 2021 20:00:00 GMT
Content-Length   321823
Keep-Alive       timeout=5, max=100
Connection       Keep-Alive
Content-Type     image/png</code>```

I am not setting Date, Cache-Control and Pragma but keep getting them in response.

I know i can overwrite them but honestly i don't exactly know which values to set.

答:
You can use:

```<code>header( 'Cache-Control: max-age=37739520, public' );
</code>```

You could try to overwrite Pragma too but I think these day browsers just ignore Pragma if Cache-Control is isset.

```<code>header( 'Pragma: public' );
</code>```

ContentLicense: CC BY-SA 3.0

Title: Force Browser to cache images

Body:
I am generating the images and want browser to cache them forever, but instead browser never cache them at all.
This is my php code

header('Content-type:'.$file->content_type);
header('Expires: Thu, 15 Apr '.(date('Y')+10).' 20:00:00 GMT');
header('Content-Disposition: attachment; filename="'.$file->file_name.'"');
echo(file_get_contents($model_files->files_path.$file->md5.$model_files->seprator.$file->file_name));

and these are the response headers which i keep getting in browser.

Date:            Thu, 02 Jun 2011 12:56:56 GMT
Server:          Apache mod_fcgid/2.3.6 mod_auth_passthrough/2.1 mod_bwlimited/1.4 FrontPage/5.0.2.2635
X-Powered-By     PHP/5.2.15
Cache-Control    no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Pragma           no-cache
Expires          Thu, 15 Apr 2021 20:00:00 GMT
Content-Length   321823
Keep-Alive       timeout=5, max=100
Connection       Keep-Alive
Content-Type     image/png

I am not setting Date, Cache-Control and Pragma but keep getting them in response.

I know i can overwrite them but honestly i don't exactly know which values to set.

Body:
You can use:

header( 'Cache-Control: max-age=37739520, public' );

You could try to overwrite Pragma too but I think these day browsers just ignore Pragma if Cache-Control is isset.

header( 'Pragma: public' );


问:
Where does credential management api store webauthn related data
WebAuthn includes an extension of the credential management api that allows you to work with public keys. I can go to the chrome settings and check managed passwords to see which username/passwords i have chosen to store in the browser using the credential management api. Few questions related to webauthn+credential management api combination.

What info does browser store when we successfully create a
credential?

Can we access this info from chrome settings (or some other way)?

答:
None - the credentials are stored in a protected form inside the authenticator device used - e.g. a security key like a Yubikey or inside the TPM of your computer or phone.

You can create or get a credential (get in this case really meaning "sign this nonce")  at runtime via the WebAuthn API (navigator.credentials...) but you cannot enumerate them.

Even Yubico do not provide a tool that allows you to just list the FIDO2 credentials held on one of their devices.


问:
Set dynamic base url using Retrofit 2.0 and Dagger 2
I'm trying to perform a login action using Retrofit 2.0 using Dagger 2

Here's how I set up Retrofit dependency

```<code>@Provides
@Singleton
Retrofit provideRetrofit(Gson gson, OkHttpClient client) {
    Retrofit retrofit = new Retrofit.Builder()
                            .addConverterFactory(GsonConverterFactory.create(gson)
                            .client(client)
                            .baseUrl(application.getUrl())
                            .build();
    return retrofit;
}
</code>```

Here's the API interface.

```<code>interface LoginAPI {
   @GET(relative_path)
   Call<Boolean> logMe();
}
</code>```

I have three different base urls users can log into. So I can't set a static url while setting up Retrofit dependency. I created a setUrl() and getUrl() methods on Application class. Upon user login, I set the url onto Application before invoking the API call.

I use lazy injection for retrofit like this

```<code>Lazy<Retrofit> retrofit
</code>```

That way, Dagger injects dependency only when I can call

```<code>retrofit.get()
</code>```

This part works well. I got the url set to retrofit dependency. However, the problem arises when the user types in a wrong base url (say, mywifi.domain.com), understands it's the wrong one and changes it(say to mydata.domain.com). Since Dagger already created the dependency for retrofit, it won't do again.
So I have to reopen the app and type in the correct url.

I read different posts for setting up dynamic urls on Retrofit using Dagger. Nothing really worked out well in my case. Do I miss anything?

答:
This worked for me in Kotlin

```<code>class HostSelectionInterceptor: Interceptor {

    override fun intercept(chain: Interceptor.Chain): Response {

        var request = chain.request()

        val host: String = SharedPreferencesManager.getServeIpAddress()

        val newUrl = request.url().newBuilder()
            .host(host)
            .build()

        request = request.newBuilder()
            .url(newUrl)
            .build()

        return chain.proceed(request)
    }

}
</code>```

Add the interceptor to OkHttpClient builder

```<code>val okHttpClient = OkHttpClient.Builder()
                .addInterceptor(HostSelectionInterceptor())
                .cache(null)
                .build()
</code>```

Body:
I'm trying to perform a login action using Retrofit 2.0 using Dagger 2

Here's how I set up Retrofit dependency

@Provides
@Singleton
Retrofit provideRetrofit(Gson gson, OkHttpClient client) {
    Retrofit retrofit = new Retrofit.Builder()
                            .addConverterFactory(GsonConverterFactory.create(gson)
                            .client(client)
                            .baseUrl(application.getUrl())
                            .build();
    return retrofit;
}

Here's the API interface.

interface LoginAPI {
   @GET(relative_path)
   Call<Boolean> logMe();
}

I have three different base urls users can log into. So I can't set a static url while setting up Retrofit dependency. I created a setUrl() and getUrl() methods on Application class. Upon user login, I set the url onto Application before invoking the API call.

I use lazy injection for retrofit like this

Lazy<Retrofit> retrofit

That way, Dagger injects dependency only when I can call

retrofit.get()

This part works well. I got the url set to retrofit dependency. However, the problem arises when the user types in a wrong base url (say, mywifi.domain.com), understands it's the wrong one and changes it(say to mydata.domain.com). Since Dagger already created the dependency for retrofit, it won't do again.
So I have to reopen the app and type in the correct url.

I read different posts for setting up dynamic urls on Retrofit using Dagger. Nothing really worked out well in my case. Do I miss anything?

Body:
This worked for me in Kotlin

class HostSelectionInterceptor: Interceptor {

    override fun intercept(chain: Interceptor.Chain): Response {

        var request = chain.request()

        val host: String = SharedPreferencesManager.getServeIpAddress()

        val newUrl = request.url().newBuilder()
            .host(host)
            .build()

        request = request.newBuilder()
            .url(newUrl)
            .build()

        return chain.proceed(request)
    }

}

Add the interceptor to OkHttpClient builder

val okHttpClient = OkHttpClient.Builder()
                .addInterceptor(HostSelectionInterceptor())
                .cache(null)
                .build()


问:
Ansible with_first_found errors
Ansible version: 2.9.6

I'm running the below include_vars task:

```<code>- name: Testing first found
  include_vars: "{{ item }}"
  with_first_found:
    - files:
        - "vars/{{ myvar.split('-')[0] }}/{{ myvar.split('-')[1] }}.yml"
        - "vars/{{ myvar.split('-')[0] }}/{{ myvar.split('-')[1] }}-{{ myvar.split('-')[2] }}.yml"
      skip: true
</code>```

Note that the value of myvar in this case is hello-world. The file vars/hello/world.yml exists, so there should be a match on the first item/file above.

When I run this I get the error: fatal: [localhost]: FAILED! => {"msg": "No file was found when using first_found. Use errors='ignore' to allow this task to be skipped if no files are found"}

However, if I comment out the above task to look like this:

```<code>- name: Testing first found
  include_vars: "{{ item }}"
  with_first_found:
    - files:
        - "vars/{{ myvar.split('-')[0] }}/{{ myvar.split('-')[1] }}.yml"
        # - "vars/{{ myvar.split('-')[0] }}/{{ myvar.split('-')[1] }}-{{ myvar.split('-')[2] }}.yml"
      skip: true
</code>```

Then the first file is found as expected and the vars are loaded.
I know that the second item in my with_first_found will give an error, since I only have 2 elements in myvar and I can't do a split [2]. But Ansible shouldn't be trying to even evaluate the second line since that's the point of with first found.

Just to test, I changed the split task a bit on the second line to use the element at 1 again:

```<code>- name: Testing first found
  include_vars: "{{ item }}"
  with_first_found:
    - files:
        - "vars/{{ myvar.split('-')[0] }}/{{ myvar.split('-')[1] }}.yml"
        - "vars/{{ myvar.split('-')[0] }}/{{ myvar.split('-')[1] }}-{{ myvar.split('-')[1] }}.yml"
      skip: true
</code>```

This also passed

答:
It seems that this works, I don't know why though:</p>

```<code>- name: Testing first found
  include_vars: "{{ item }}"
  with_first_found:
    - "vars/{{ myvar.split('-')[0] }}/{{ myvar.split('-')[1] }}.yml"
    - "vars/{{ myvar.split('-')[0] }}/{{ myvar.split('-')[1] }}-{{ myvar.split('-')[2] }}.yml"
</code>```

Title: Ansible with_first_found errors

Body:
Ansible version: 2.9.6

I'm running the below include_vars task:

- name: Testing first found
  include_vars: "{{ item }}"
  with_first_found:
    - files:
        - "vars/{{ myvar.split('-')[0] }}/{{ myvar.split('-')[1] }}.yml"
        - "vars/{{ myvar.split('-')[0] }}/{{ myvar.split('-')[1] }}-{{ myvar.split('-')[2] }}.yml"
      skip: true

Note that the value of myvar in this case is hello-world. The file vars/hello/world.yml exists, so there should be a match on the first item/file above.

When I run this I get the error: fatal: [localhost]: FAILED! => {"msg": "No file was found when using first_found. Use errors='ignore' to allow this task to be skipped if no files are found"}

However, if I comment out the above task to look like this:

- name: Testing first found
  include_vars: "{{ item }}"
  with_first_found:
    - files:
        - "vars/{{ myvar.split('-')[0] }}/{{ myvar.split('-')[1] }}.yml"
        # - "vars/{{ myvar.split('-')[0] }}/{{ myvar.split('-')[1] }}-{{ myvar.split('-')[2] }}.yml"
      skip: true

Then the first file is found as expected and the vars are loaded.
I know that the second item in my with_first_found will give an error, since I only have 2 elements in myvar and I can't do a split [2]. But Ansible shouldn't be trying to even evaluate the second line since that's the point of with first found.

Just to test, I changed the split task a bit on the second line to use the element at 1 again:

- name: Testing first found
  include_vars: "{{ item }}"
  with_first_found:
    - files:
        - "vars/{{ myvar.split('-')[0] }}/{{ myvar.split('-')[1] }}.yml"
        - "vars/{{ myvar.split('-')[0] }}/{{ myvar.split('-')[1] }}-{{ myvar.split('-')[1] }}.yml"
      skip: true

This also passed

Body:
It seems that this works, I don't know why though:

- name: Testing first found
  include_vars: "{{ item }}"
  with_first_found:
    - "vars/{{ myvar.split('-')[0] }}/{{ myvar.split('-')[1] }}.yml"
    - "vars/{{ myvar.split('-')[0] }}/{{ myvar.split('-')[1] }}-{{ myvar.split('-')[2] }}.yml"


问:
Is it possible to run a PHP function after each line of a PHP script is executed?
My question is similar to this: Is it possible to run code after each line in Ruby?
However I want to do it in PHP.

Is it possible and if so, how?

答: I don't think it is within PHP. You could, however, write a PHP script that took your original script and inserted an extra line after each line of the original.</p>


问:
problem executing a python cgi script in apache webserver
I have searched and read other posts with similar problems. I fixed the shebang line in the .py file and made sure that httpd.conf has correct config. Unfortunately, nothing has resolved my problem and I still get the dreaded errors -

```<code>[Mon Jun 01 10:37:02.994516 2020] [cgi:error] [pid 19596:tid 1196] (OS 1920)The file cannot be accessed by the system.  : [client ::1:50159] couldn't create child process: 721920: upload_file.py
[Mon Jun 01 10:37:02.994516 2020] [cgi:error] [pid 19596:tid 1196] (OS 1920)The file cannot be accessed by the system.  : [client ::1:50159] AH01223: couldn't spawn child process: C:/Users/raj_d/webroot/tsp_quick/cgi-bin/upload_file.py
</code>```

The Python script -

```<code>#!"C:\Users\raj_d\AppData\Local\Microsoft\WindowsApps\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\python.exe"
import cgi, os
import cgitb

cgitb.enable()
form = cgi.FieldStorage()
# Get filename here.
fileitem = form['filename']
# Test if the file was uploaded
if fileitem.filename:
   # strip leading path from file name to avoid
   # directory traversal attacks
   fn = os.path.basename(fileitem.filename)
   open('/tmp/' + fn, 'wb').write(fileitem.file.read())
   message = 'The file "' + fn + '" was uploaded successfully'
else:
   message = 'No file was uploaded'
print """\
Content-Type: text/html\n
<html>
<body>
   <p>%s</p>
</body>
</html>
""" % (message,)
</code>```

I have played with adding and removing quotes on the full path in the shebang and that hasn't helped.

I have these in httpd.conf -

```<code>LoadModule cgi_module modules/mod_cgi.so

<Directory "C:\Users\raj_d\webroot\tsp_quick\cgi-bin">
    AllowOverride None
    # Options None
    Options +ExecCGI
    AddHandler cgi-script .py
    Require all granted
</Directory>
</code>```

I made sure that python was excutable from the shebang path -

```<code>C:\>C:\Users\raj_d\AppData\Local\Microsoft\WindowsApps\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\python.exe
Python 3.8.3 (tags/v3.8.3:6f8c832, May 13 2020, 22:37:02) [MSC v.1924 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>
</code>```

Any help will be appreciated.

Thanks in advance.

RD

答:
Well, I figured it out.

First and foremost, one should always follow the guidelines :)

In my case, I gave up too quickly in running the script from command line. I had installed Python 3.8.3 from the Microsoft store and for some reason every time I ran the script from the command line, a new cmd window would popup and close very quickly. I was unable to change that behavior and couldn't see what was going wrong.

So I uninstalled python, downloaded the new installer from python's site, and installed in a common location where my dev tools are installed. Now, I could run my script from command line and was able to see what the actual problem was.

It turned out to be print! Here is the modified code which works just fine and the shebang became simpler as well.

```<code>#!C:\tools\python\\python.exe
import cgi, os
import cgitb
import time

cgitb.enable()
form = cgi.FieldStorage()
# Get filename here.
fileitem = form['filename']
# Test if the file was uploaded
if fileitem.filename:
   # strip leading path from file name to avoid
   # directory traversal attacks
   fn = os.path.basename(fileitem.filename)
   # open('/tmp/' + fn, 'wb').write(fileitem.file.read())
   message = 'The file "' + fn + '" was uploaded successfully'
else:
   message = 'No file was uploaded'
a = """Content-Type: text/html\n
<html>
<body>
<p>{}</p>
</body>
</html>
"""
print (a.format(message))
</code>```

Body:
I have searched and read other posts with similar problems. I fixed the shebang line in the .py file and made sure that httpd.conf has correct config. Unfortunately, nothing has resolved my problem and I still get the dreaded errors -

[Mon Jun 01 10:37:02.994516 2020] [cgi:error] [pid 19596:tid 1196] (OS 1920)The file cannot be accessed by the system.  : [client ::1:50159] couldn't create child process: 721920: upload_file.py
[Mon Jun 01 10:37:02.994516 2020] [cgi:error] [pid 19596:tid 1196] (OS 1920)The file cannot be accessed by the system.  : [client ::1:50159] AH01223: couldn't spawn child process: C:/Users/raj_d/webroot/tsp_quick/cgi-bin/upload_file.py

The Python script -

#!"C:\Users\raj_d\AppData\Local\Microsoft\WindowsApps\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\python.exe"
import cgi, os
import cgitb

cgitb.enable()
form = cgi.FieldStorage()
# Get filename here.
fileitem = form['filename']
# Test if the file was uploaded
if fileitem.filename:
   # strip leading path from file name to avoid
   # directory traversal attacks
   fn = os.path.basename(fileitem.filename)
   open('/tmp/' + fn, 'wb').write(fileitem.file.read())
   message = 'The file "' + fn + '" was uploaded successfully'
else:
   message = 'No file was uploaded'
print """\
Content-Type: text/html\n

%s

""" % (message,)

I have played with adding and removing quotes on the full path in the shebang and that hasn't helped.

I have these in httpd.conf -

LoadModule cgi_module modules/mod_cgi.so

<Directory "C:\Users\raj_d\webroot\tsp_quick\cgi-bin">
    AllowOverride None
    # Options None
    Options +ExecCGI
    AddHandler cgi-script .py
    Require all granted
</Directory>

I made sure that python was excutable from the shebang path -

C:\>C:\Users\raj_d\AppData\Local\Microsoft\WindowsApps\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\python.exe
Python 3.8.3 (tags/v3.8.3:6f8c832, May 13 2020, 22:37:02) [MSC v.1924 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>

Any help will be appreciated.

Thanks in advance.

RD

Body:
Well, I figured it out.

First and foremost, one should always follow the guidelines :)

In my case, I gave up too quickly in running the script from command line. I had installed Python 3.8.3 from the Microsoft store and for some reason every time I ran the script from the command line, a new cmd window would popup and close very quickly. I was unable to change that behavior and couldn't see what was going wrong.

So I uninstalled python, downloaded the new installer from python's site, and installed in a common location where my dev tools are installed. Now, I could run my script from command line and was able to see what the actual problem was.

It turned out to be print! Here is the modified code which works just fine and the shebang became simpler as well.

#!C:\tools\python\\python.exe
import cgi, os
import cgitb
import time

cgitb.enable()
form = cgi.FieldStorage()
# Get filename here.
fileitem = form['filename']
# Test if the file was uploaded
if fileitem.filename:
   # strip leading path from file name to avoid
   # directory traversal attacks
   fn = os.path.basename(fileitem.filename)
   # open('/tmp/' + fn, 'wb').write(fileitem.file.read())
   message = 'The file "' + fn + '" was uploaded successfully'
else:
   message = 'No file was uploaded'
a = """Content-Type: text/html\n
<html>
<body>
<p>{}</p>
</body>
</html>
"""
print (a.format(message))


问:
Prevent CTRL-V in TDBMemo
I am using a TDBMemo control in Delphi 7. I would like to prevent the user from pasting in it with CTRL+V.

This solution doesn't work:

```<code>procedure TForm1.Edit1KeyPress(Sender: TObject; var Key: Char);
begin
 if (Key=#22) or (Key=#3) then Key:=#0;   // 22 = [Ctrl+V] / 3 = [Ctrl+C]
end;
</code>```

So, I tried something else:

```<code>if (Key=#86) then Key := #0; // this is ok, doesnt allow letter v.
</code>```

But when I try:

```<code>if (Key=#17) AND (Key=#86) then Key := #0; // #17 is supposed to be CTRL value...
</code>```

it doesnt work.

答:
If I am understamding what you want correctly, put this at the top of your unit that uses TDBMemo

```<code>type

  TDBMemo = Class(DBCtrls.TDbMemo)
    procedure WMPaste(var Message: TMessage); message WM_PASTE;
  end;
</code>```

Then, in the implementation section

```<code>procedure TDBMemo.WMPaste(var Message: TMessage);
begin
  // do nothing
end;
</code>```

[tbc]If you want this behaviour in more than one unit which includes TDBMemos,  put the code above into a separate unit, then make sure that it appears in the Uses list of any other TDBMemo-containing unit after DBCtrls, that way it will take effect in all the units involved.

Title: Prevent CTRL-V in TDBMemo

Body:
I am using a TDBMemo control in Delphi 7. I would like to prevent the user from pasting in it with CTRL+V.

This solution doesn't work:

procedure TForm1.Edit1KeyPress(Sender: TObject; var Key: Char);
begin
 if (Key=#22) or (Key=#3) then Key:=#0;   // 22 = [Ctrl+V] / 3 = [Ctrl+C]
end;

So, I tried something else:

if (Key=#86) then Key := #0; // this is ok, doesnt allow letter v.

But when I try:

if (Key=#17) AND (Key=#86) then Key := #0; // #17 is supposed to be CTRL value...

it doesnt work.

Body:
If I am understamding what you want correctly, put this at the top of your unit that uses TDBMemo

type

  TDBMemo = Class(DBCtrls.TDbMemo)
    procedure WMPaste(var Message: TMessage); message WM_PASTE;
  end;

Then, in the implementation section

procedure TDBMemo.WMPaste(var Message: TMessage);
begin
  // do nothing
end;

[tbc]If you want this behaviour in more than one unit which includes TDBMemos,  put the code above into a separate unit, then make sure that it appears in the Uses list of any other TDBMemo-containing unit after DBCtrls, that way it will take effect in all the units involved.


问:
How to get the foreign key in Entity Framework?
I am developing StudentApp in .NET 3.5 SP1 MVC Application.

I have two tables

Course

    CourseID, course_Name

Students

    studentID, student_Name, courseID(fk)

Now I made StudentApp.dbml which is having both table as entities.

As Foreign key will not be present in student entity,
I can not display courseID in student model, more over i can not generate add, edit, list views.

So tell me how to display courseID(fk) in student & i also want course name instead.

And also dropdownbox showing course name & storing courseID in edit view .

答:
Can you post your DBML?  Also, DBML is used in LINQ to SQL (L2S) - EDMX is the mapping used in the ADO Entity Framework.  Are you using LINQ to SQL or the Entity Framework (EF)?

No matter which one you are using - they both support Foreign Keys and you would get a property representing either side of the relationship - you don't need to do anything special (the Foreign Key must exist in the database, of course).

In EF, the foreign  keys are called "navigtion properties" and they work a little differently to Foreign Keys in L2S.  Nothing major, but updating them and "eager loading" are somewhat different.

Just drop the tables onto the map in the designer in Visual Studio (or generate using command line equivalents if you prefer).

Regarding Foreign Keys and Drop Down Lists (and other UI goodness) - I wrote a couple of blog entries on some approaches which might suit you.  One part is located here and part two is located here.

OwnerDisplayName: Vikas

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Chad Moran

OwnerDisplayName: Rob Sanders


问:
Flutter background iOS notification don't work in XCode or TestFlight
I am trying to receive background push-notifications on an IOS device using Flutter. I have managed to get this to work on Android and it also works on iOS debug if I run code with Android Studio, but when I run code using XCode I can't get background notifications and I get this:

2020-05-19 01:45:43.617423-0700 Runner[924:720398] dnssd_clientstub read_all(22) DEFUNCT

2020-05-19 01:45:43.618224-0700 Runner[924:720398] [VERBOSE-2:FlutterObservatoryPublisher.mm(131)] Could not register as server for FlutterObservatoryPublisher. Check your network settings and relaunch the application.

2020-05-19 01:45:43.657713-0700 Runner[924:720653] [] nw_read_request_report [C1] Receive failed with error "Software caused connection abort"

2020-05-19 01:45:43.661093-0700 Runner[924:720653] [] nw_read_request_report [C1] Receive failed with error "Software caused connection abort"

Notifications also don't work in TestFlight.
Can you help me, please?

Now I am using
  firebase_messaging: ^6.0.15 but with the previous version, I got the same situation.

My flutter doctor --verbose:

[✓] Flutter (Channel stable, v1.17.0, on Mac OS X 10.15.4 19E287, locale it-IT)

• Flutter version 1.17.0 at /Users/xxxxx/development/flutter

• Framework revision e6b34c2b5c (2 settimane fa), 2020-05-02 11:39:18 -0700

• Engine revision 540786dd51

• Dart version 2.8.1

 [✓] Android toolchain - develop for Android devices (Android SDK version 29.0.3)

• Android SDK at /Users/xxxxx/Library/Android/sdk

 • Platform android-29, build-tools 29.0.3

• Java binary at: /Applications/Android   Studio.app/Contents/jre/jdk/Contents/Home/bin/java

• Java version OpenJDK Runtime Environment (build      1.8.0_212-release-1586-b4-5784211)

• All Android licenses accepted.

[✓] Xcode - develop for iOS and macOS (Xcode 11.4.1)

• Xcode at /Applications/Xcode.app/Contents/Developer

• Xcode 11.4.1, Build version 11E503a

• CocoaPods version 1.9.1

[✓] Android Studio (version 3.6)

• Android Studio at /Applications/Android Studio.app/Contents

• Flutter plugin version 45.1.1

• Dart plugin version 192.7761

• Java version OpenJDK Runtime Environment (build      1.8.0_212-release-1586-b4-5784211)

[✓] VS Code (version 1.44.2)

• VS Code at /Applications/Visual Studio Code.app/Contents

• Flutter extension version 3.10.1

[✓] Connected device (1 available)

  • iPhone • ios • iOS      13.4.1
```

答:
change your appDelegate like this :</p>

```<code>import UIKit
import Flutter

@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
  override func application(
    _ application: UIApplication,
    didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
  ) -> Bool {
    if #available(iOS 10.0, *) {
      UNUserNotificationCenter.current().delegate = self as? UNUserNotificationCenterDelegate
    }
    GeneratedPluginRegistrant.register(with: self)
    return super.application(application, didFinishLaunchingWithOptions: launchOptions)
  }

    override func applicationDidBecomeActive(_ application: UIApplication) {
        signal(SIGPIPE, SIG_IGN);
    }

    override func applicationWillEnterForeground(_ application: UIApplication) {
        signal(SIGPIPE, SIG_IGN);
    }
}
</code>```

Body:
change your appDelegate like this :

import UIKit
import Flutter

@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
  override func application(
    _ application: UIApplication,
    didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
  ) -> Bool {
    if #available(iOS 10.0, *) {
      UNUserNotificationCenter.current().delegate = self as? UNUserNotificationCenterDelegate
    }
    GeneratedPluginRegistrant.register(with: self)
    return super.application(application, didFinishLaunchingWithOptions: launchOptions)
  }

    override func applicationDidBecomeActive(_ application: UIApplication) {
        signal(SIGPIPE, SIG_IGN);
    }

    override func applicationWillEnterForeground(_ application: UIApplication) {
        signal(SIGPIPE, SIG_IGN);
    }
}


问:
Timer.scheduledTimer Swift 3 pre-iOS 10 compatibility
I need to schedule a Timer for firing a function every second but I see that in Xcode 8 beta 3 the scheduledTimer is only available for iOS 10.

Is there any alternative for using the timer in iOS 9 or previous versions?

```<code>Timer.scheduledTimer(withTimeInterval: 1, repeats: true, block: { (timer) in print("Hi!")})
</code>```

答:
You can use the following simple shim to provide the new block-based Timers to pre-iOS 10:

```<code>class TimerShim {
    private var timer: Timer?
    private let block: (Timer) -> Void

    private init(timeInterval interval: TimeInterval, repeats: Bool, block: @escaping (Timer) -> Void) {
        self.block = block
        timer = Timer.scheduledTimer(timeInterval: interval, target: self, selector: #selector(timerDidFire), userInfo: nil, repeats: repeats)
    }

    class func scheduledTimer(withTimeInterval interval: TimeInterval, repeats: Bool, block: @escaping (Timer) -> Void) -> Timer {
        return TimerShim(timeInterval: interval, repeats: repeats, block: block).timer!
    }

    @objc private func timerDidFire() {
        block(timer!)
    }
}
</code>```

Usage example:

```<code>TimerShim.scheduledTimer(withTimeInterval: 5, repeats: false) { _ in
    print("boom!")
}
</code>```

Body:
I need to schedule a Timer for firing a function every second but I see that in Xcode 8 beta 3 the scheduledTimer is only available for iOS 10.

Is there any alternative for using the timer in iOS 9 or previous versions?

Timer.scheduledTimer(withTimeInterval: 1, repeats: true, block: { (timer) in print("Hi!")})

Body:
You can use the following simple shim to provide the new block-based Timers to pre-iOS 10:

class TimerShim {
    private var timer: Timer?
    private let block: (Timer) -> Void

    private init(timeInterval interval: TimeInterval, repeats: Bool, block: @escaping (Timer) -> Void) {
        self.block = block
        timer = Timer.scheduledTimer(timeInterval: interval, target: self, selector: #selector(timerDidFire), userInfo: nil, repeats: repeats)
    }

    class func scheduledTimer(withTimeInterval interval: TimeInterval, repeats: Bool, block: @escaping (Timer) -> Void) -> Timer {
        return TimerShim(timeInterval: interval, repeats: repeats, block: block).timer!
    }

    @objc private func timerDidFire() {
        block(timer!)
    }
}

Usage example:

TimerShim.scheduledTimer(withTimeInterval: 5, repeats: false) { _ in
    print("boom!")
}


问:
Algorithm of checking if the number is prime
Hello everyone!

I came to this algorithm on how to check if number is prime and probably it's fine for me but I want to find out if it can be improved

```<code>bool isPrime(int num)
{
    bool isPrime = 1;
    if (num <= 0)
    {
        return 0;
    }
    if (num == 1)
    {
        return 0;
    }
    for (int i = 2; i <= sqrt(num); ++i)
    {
        if (num % i == 0)
        {
            isPrime = 0;
        }
    }

    return isPrime;
}
</code>```

Thanks in advance

答:
To make this more efficient, don't calculate the sqrt of the number

You don't need to check the even numbers if they are divisors.

Also, it's handy to have an early exit in case the number is negative.

Here is my code in C:

```<code>#define  boolean  int
#define   TRUE     1
#define   FALSE    0

boolean
isPrime(int number)
{
    if(number == 2)
        return TRUE;

    if(number < 2 || number % 2 == 0)
        return FALSE;

    /*
     * we only need to check until the sqrt
     * and we can omit the even numbers as well
     */
    for(int i = 3; i*i <= number; i += 2)
        if(number % i == 0)
            return FALSE;

    return TRUE;
}
</code>```

Body:
Hello everyone!

I came to this algorithm on how to check if number is prime and probably it's fine for me but I want to find out if it can be improved

bool isPrime(int num)
{
    bool isPrime = 1;
    if (num <= 0)
    {
        return 0;
    }
    if (num == 1)
    {
        return 0;
    }
    for (int i = 2; i <= sqrt(num); ++i)
    {
        if (num % i == 0)
        {
            isPrime = 0;
        }
    }

    return isPrime;
}

Thanks in advance

Body:
To make this more efficient, don't calculate the sqrt of the number

You don't need to check the even numbers if they are divisors.

Also, it's handy to have an early exit in case the number is negative.

Here is my code in C:

#define  boolean  int
#define   TRUE     1
#define   FALSE    0

boolean
isPrime(int number)
{
    if(number == 2)
        return TRUE;

    if(number < 2 || number % 2 == 0)
        return FALSE;

    /*
     * we only need to check until the sqrt
     * and we can omit the even numbers as well
     */
    for(int i = 3; i*i <= number; i += 2)
        if(number % i == 0)
            return FALSE;

    return TRUE;
}


问:
How to suppress Chrome DevTools warning: 'DevTools failed to load SourceMap: Could not load content for...'
Context

For many of my js files I have no source map. When using the devtools console it pollutes the warnings about that. I would not like to turn of all warnings, but those are not really useful for me

Question

How to suppress Chrome DevTools warning:  'DevTools failed to load SourceMap: Could not load content for...'?

答:
In DevTools (F12) -> Settings (F1) :

Disable both "enable JS source maps" and "enable CSS source maps" in "Preferences -> Sources"


问:
function is not returning data
I have the following code

```<code>    var redis = require("redis"),
    client = redis.createClient();

var getuser = function(username) {
  var userhash={};
  client.hgetall("users."+username, function(err, user) {
    userhash=user;
  });
  return userhash;
};
user_rahul = {
     username: 'rahul',
     queueno: 1,
     sessionId: '6604353811126202'

   };
user_namita = {
  username: 'namita',
  sessionId:'2'
};
client.hmset('users.rahul', user_rahul);
client.hmset('users.namita', user_namita);
var username = "rahul"; // From a POST perhaps
  var user1=getuser(username);
  console.log(user1);
client.hgetall("users." + username, function(err, user) {
  console.log(user);

});
</code>```

i have created a getuser function to return the value of particular username in userhash but it is not returning please help in finding why it is not returning .
what should i do to get the value return ?

答:
You're mixing sync and async patterns when you make an async call in your sync getUser function. You need to make your getUser function async - e.g:</p>

```<code>var redis = require("redis"),
    client = redis.createClient();

var getuser = function(username, cb) {
  client.hgetall("users."+username, cb);
};

user_rahul = {
     username: 'rahul',
     queueno: 1,
     sessionId: '6604353811126202'

   };
user_namita = {
  username: 'namita',
  sessionId:'2'
};

client.hmset('users.rahul', user_rahul);
client.hmset('users.namita', user_namita);
var username = "rahul"; // From a POST perhaps
getuser(username, function(err, res){
     console.log(res);
 });
client.hgetall("users." + username, function(err, user) {
  console.log(user);
});
</code>```

Title: function is not returning data

Body:
I have the following code

    var redis = require("redis"),
    client = redis.createClient();

var getuser = function(username) {
  var userhash={};
  client.hgetall("users."+username, function(err, user) {
    userhash=user;
  });
  return userhash;
};
user_rahul = {
     username: 'rahul',
     queueno: 1,
     sessionId: '6604353811126202'

   };
user_namita = {
  username: 'namita',
  sessionId:'2'
};
client.hmset('users.rahul', user_rahul);
client.hmset('users.namita', user_namita);
var username = "rahul"; // From a POST perhaps
  var user1=getuser(username);
  console.log(user1);
client.hgetall("users." + username, function(err, user) {
  console.log(user);

});

i have created a getuser function to return the value of particular username in userhash but it is not returning please help in finding why it is not returning .
what should i do to get the value return ?

Body:
You're mixing sync and async patterns when you make an async call in your sync getUser function. You need to make your getUser function async - e.g:

var redis = require("redis"),
    client = redis.createClient();

var getuser = function(username, cb) {
  client.hgetall("users."+username, cb);
};

user_rahul = {
     username: 'rahul',
     queueno: 1,
     sessionId: '6604353811126202'

   };
user_namita = {
  username: 'namita',
  sessionId:'2'
};

client.hmset('users.rahul', user_rahul);
client.hmset('users.namita', user_namita);
var username = "rahul"; // From a POST perhaps
getuser(username, function(err, res){
     console.log(res);
 });
client.hgetall("users." + username, function(err, user) {
  console.log(user);
});


问:
Wildcard Arguments in generics
In the program below, how does the step ob.num.doubleValue() in absEqual() method works? What is it trying to do?

```<code>class NumericFns<T extends Number>{
     T num;

     NumericFns(T n ){
         num = n ;
        }

     boolean absEqual(NumericFns<?> ob) {
         if (Math.abs(num.doubleValue())==
                 Math.abs(ob.num.doubleValue()))
             return true ;
         return false ;
     }
}
</code>```

```<code>public class demo  {

    public static void main(String[] args) {
        NumericFns<Integer> iob = new NumericFns<Integer>(6) ;
        NumericFns<Double> dob = new NumericFns<Double>(-6.0) ;
        if(iob.absEqual(dob))
            System.out.println("Absolute Values are equal") ;
        else
            System.out.println("They differ") ;
    }
}
</code>```

答:
Type parameter T has an upper bound Number, meaning that it is equal to type T or a subtype thereof.  Therefore, you can call methods of Number on variables of type T, such as in this case the method doubleValue().

See Bounded Type Parameters explanation.

Consequently, this method returns true if and only if the double value of both numbers are the same.  This might be the case for an Integer value 1 and a Double value 1.0.

Note that the method implementation can be simplified to

```<code>     boolean absEqual(NumericFns<?> ob) {
         return Math.abs(num.doubleValue()) == Math.abs(ob.num.doubleValue()));
     }
</code>```

Title: Wildcard Arguments in generics

Body:
In the program below, how does the step ob.num.doubleValue() in absEqual() method works? What is it trying to do?

class NumericFns<T extends Number>{
     T num;

     NumericFns(T n ){
         num = n ;
        }

     boolean absEqual(NumericFns<?> ob) {
         if (Math.abs(num.doubleValue())==
                 Math.abs(ob.num.doubleValue()))
             return true ;
         return false ;
     }
}

public class demo  {

    public static void main(String[] args) {
        NumericFns<Integer> iob = new NumericFns<Integer>(6) ;
        NumericFns<Double> dob = new NumericFns<Double>(-6.0) ;
        if(iob.absEqual(dob))
            System.out.println("Absolute Values are equal") ;
        else
            System.out.println("They differ") ;
    }
}

Body:
Type parameter T has an upper bound Number, meaning that it is equal to type T or a subtype thereof.  Therefore, you can call methods of Number on variables of type T, such as in this case the method doubleValue().

See Bounded Type Parameters explanation.

Consequently, this method returns true if and only if the double value of both numbers are the same.  This might be the case for an Integer value 1 and a Double value 1.0.

Note that the method implementation can be simplified to

     boolean absEqual(NumericFns<?> ob) {
         return Math.abs(num.doubleValue()) == Math.abs(ob.num.doubleValue()));
     }


问:
How to read a file from local path using C# without specifying the filename and also it should read files with .csv,.xml extensions only?
ReadAllFiles(@"../../","names.txt");
I tried this so I am able to read the file.But what I want is to read a file without giving filename and it should read only file with some particular extension like .csv, .xml only</p>

答:
You can read like this. you have to give folder path and the pattern of you want to read the file.You can use GetFiles method also.

```<code>string path = "";
foreach (string file in Directory.EnumerateFiles(path, "*.txt"))
{
    string content = File.ReadAllText(file);
}
</code>```

Body:
You can read like this. you have to give folder path and the pattern of you want to read the file.You can use GetFiles method also.

string path = "";
foreach (string file in Directory.EnumerateFiles(path, "*.txt"))
{
    string content = File.ReadAllText(file);
}


问:
formatting javascript number to years and month
I get an integer such as 20 from it, I need to calculate how many months and years are in it, in 20 for example 1 year and 8 months
how do i do this in JS?

```<code>   case (props.term === 12):
        setYears(1)
        break;
     case (props.term >12):
        ...
     break;
     default:
        break;
  }
</code>```

Is there another way?

答:
```<code>var years = Math.floor(term/12);
var months = term % 12;
</code>```

Body:
I get an integer such as 20 from it, I need to calculate how many months and years are in it, in 20 for example 1 year and 8 months
how do i do this in JS?

   case (props.term === 12):
        setYears(1)
        break;
     case (props.term >12):
        ...
     break;
     default:
        break;
  }

Is there another way?


问:
nested collapsible container in drawio?
I'm wondering if it's possible to nest collapsible containers? In the picture below I have a container containing various lists of text organised in "sections"; it'd be great to be able to collapse the sections individually as well.

Related query, since I'm creating those boxes programmatically – is it possible to create the text content programmatically and not need to position them with absolute y positions? With the user interface I can just add a new text box and it automatically stacks below the current one, and the container expands. If I create those with a script it seems I need to provide the y positions and sizes myself.

答:
you could try adding a new container for every section (as shown in the attachment) and check if it suits your needs. I created a simple test diagram, it could be improved visually.

nested containers

Title: nested collapsible container in drawio?


问:
python fixed digits rounding
Is there an function in python 2 that can do this?

```<code>1234 -> round(1234, 2) = 1200
1234 -> round(1234, 3) = 1230
12.34 -> round(12.34, 3) = 12.3
</code>```

Basically the second number says the precision of the number and the everything behind should be rounded.

Based on the comment i came up with this:

```<code>def round_to_precision(x, precision):
    return int(round(x / float(10 ** precision))) * 10 ** precision
</code>```

But this is still wrong, because i don't know the size of the numbers.

答:
Here's a solution (written step by step for clarity). </p>

```<code>import math

num_digits = lambda x: int((math.log(x, 10)) + 1)

def round(x, precision):
    digits = num_digits(x)
    gap = precision - digits
    x = x * (10 ** gap)
    x = int(x)
    x = x / (10 ** gap)
    return x
</code>```

<p>results: </p>

```<code>round(1234, 2) # 1200
round(1234, 3) # 1230
round(12.34, 3) # 12.3
</code>```

Title: python fixed digits rounding

Body:
Is there an function in python 2 that can do this?

1234 -> round(1234, 2) = 1200
1234 -> round(1234, 3) = 1230
12.34 -> round(12.34, 3) = 12.3

Basically the second number says the precision of the number and the everything behind should be rounded.

Based on the comment i came up with this:

def round_to_precision(x, precision):
    return int(round(x / float(10 ** precision))) * 10 ** precision

But this is still wrong, because i don't know the size of the numbers.

Body:
Here's a solution (written step by step for clarity).

import math

num_digits = lambda x: int((math.log(x, 10)) + 1)

def round(x, precision):
    digits = num_digits(x)
    gap = precision - digits
    x = x * (10 ** gap)
    x = int(x)
    x = x / (10 ** gap)
    return x

results:

round(1234, 2) # 1200
round(1234, 3) # 1230
round(12.34, 3) # 12.3


问:
RxSwift: How to respond to a series of notifications?
Suppose I have two notifications coming one after another. I need to wait for work to complete from 1st notification and only then fire the work from 2nd notification. For now, I tried to schedule sequences to a serial scheduler, but it doesn't work as expected, it seems that I'm missing something.

```<code>NotificationCenter.default.rx.notification(.notification1)
  .observeOn(MainScheduler.instance)
  .subscribe(onNext: { [weak self] in
     self?.doSomeAsynchWork() //Fires another subscription, kind of ugly
  })
  .disposed(by: disposeBag)

NotificationCenter.default.rx.notification(.notification2)
  .observeOn(MainScheduler.instance)
  .subscribe(onNext: { [weak self] in
     self?.doSomeWork() //This should only be executed after doSomeAsynchWork() is done
  })
  .disposed(by: disposeBag)
</code>```

I was expecting work to be done in a serial manner, but that's not the case, my guess is that doSomeAsynchWork() is, well, asynchronous and doSomeWork() fires right after. But can I somehow wait for asynchronous work to complete? Any help is appreciated

UPD: notification2 may or may not arrive, so they are kind of independent of each other. Also, notification1 may or may not arrive, it's just different use cases in the app. But when both notification1 and notification2 are present, I need to wait for doSomeAsynchWork() to finish

The flow is as follows:

User taps to block some element in the list, which is only allowed for a signed-in user

User gets redirected to a sign-in screen

User sings in and then, notification1 fires

We continue to block that element now that we're signed in

Notification2 fires

The problem is when notification1 fired, we need to reload the screen, so that logic comes to doSomeAsynchWork(). On top of that, we're getting the "delete element" notification and we're trying to locate the element which is not there yet, so we're kind of stuck with an inconsistent state, where the element's blocked, but still present on a screen

The difficulty is that we can sign-in without blocking element and we can block element without the need of signing-in in (because we are already signed-in for example)

答:
Based on the flow you described in your update, I would expect to see something like this:

```<code>func example(tapElement: Observable<ID>, isLoggedIn: Observable<Bool>, presentLogin: Observable<Void>) {
    tapElement
        .withLatestFrom(isLoggedIn) { (id: $0, isLoggedIn: $1) }
        .flatMapFirst { id, isLoggedIn in
            isLoggedIn ? Observable.just(id) : presentLogin.map { id }
        }
        .subscribe(onNext: { id in
            blockElement(id: id)
        })
}
</code>```

I don't see any reason to have all the notifications in the first place.

Old Answer

I would have doSomeAsynchWork() return an Observable<Void> which emits an event with the async work is complete. Then I could:

```<code>NotificationCenter.default.rx.notification(.notification1)
    .flatMap { doSomeAsynchWork() }
    .subscribe(onNext: { doSomeWork() }
</code>```

Another option would be to have doSomeAsynchWork() return a Completable, then you would do something like:

```<code>NotificationCenter.default.rx.notification(.notification1)
    .flatMap { doSomeAsynchWork() }
    .subscribe(onCompleted: { doSomeWork() }
</code>```

Body:
Suppose I have two notifications coming one after another. I need to wait for work to complete from 1st notification and only then fire the work from 2nd notification. For now, I tried to schedule sequences to a serial scheduler, but it doesn't work as expected, it seems that I'm missing something.

NotificationCenter.default.rx.notification(.notification1)
  .observeOn(MainScheduler.instance)
  .subscribe(onNext: { [weak self] in
     self?.doSomeAsynchWork() //Fires another subscription, kind of ugly
  })
  .disposed(by: disposeBag)

NotificationCenter.default.rx.notification(.notification2)
  .observeOn(MainScheduler.instance)
  .subscribe(onNext: { [weak self] in
     self?.doSomeWork() //This should only be executed after doSomeAsynchWork() is done
  })
  .disposed(by: disposeBag)

I was expecting work to be done in a serial manner, but that's not the case, my guess is that doSomeAsynchWork() is, well, asynchronous and doSomeWork() fires right after. But can I somehow wait for asynchronous work to complete? Any help is appreciated

UPD: notification2 may or may not arrive, so they are kind of independent of each other. Also, notification1 may or may not arrive, it's just different use cases in the app. But when both notification1 and notification2 are present, I need to wait for doSomeAsynchWork() to finish

The flow is as follows:

User taps to block some element in the list, which is only allowed for a signed-in user

User gets redirected to a sign-in screen

User sings in and then, notification1 fires

We continue to block that element now that we're signed in

Notification2 fires

The problem is when notification1 fired, we need to reload the screen, so that logic comes to doSomeAsynchWork(). On top of that, we're getting the "delete element" notification and we're trying to locate the element which is not there yet, so we're kind of stuck with an inconsistent state, where the element's blocked, but still present on a screen

The difficulty is that we can sign-in without blocking element and we can block element without the need of signing-in in (because we are already signed-in for example)

Body:
Based on the flow you described in your update, I would expect to see something like this:

func example(tapElement: Observable<ID>, isLoggedIn: Observable<Bool>, presentLogin: Observable<Void>) {
    tapElement
        .withLatestFrom(isLoggedIn) { (id: $0, isLoggedIn: $1) }
        .flatMapFirst { id, isLoggedIn in
            isLoggedIn ? Observable.just(id) : presentLogin.map { id }
        }
        .subscribe(onNext: { id in
            blockElement(id: id)
        })
}

I don't see any reason to have all the notifications in the first place.

Old Answer

I would have doSomeAsynchWork() return an Observable<Void> which emits an event with the async work is complete. Then I could:

NotificationCenter.default.rx.notification(.notification1)
    .flatMap { doSomeAsynchWork() }
    .subscribe(onNext: { doSomeWork() }

Another option would be to have doSomeAsynchWork() return a Completable, then you would do something like:

NotificationCenter.default.rx.notification(.notification1)
    .flatMap { doSomeAsynchWork() }
    .subscribe(onCompleted: { doSomeWork() }


问:
How to Expand a List with Selenium Webdriver for Python
I am trying to expand a list with Selenium WebDriver for Python, which is controlled by a button that looks like this:

List When Closed

To give you an idea of how it looks when open:

List When Open

The HTML looks like this:

```<code><div>  ##just for more information on the tree
<div>  ##
<ul>   ##

<li>
role = "presentation"
ng-if = "session.hasOccurrences" ## this is the name of a span
class = "expand-children ng-scope"

<button
role = "button"
class = "icon-button has tooltip"
bb-translate-attrs = "{aria-label ': 'session.session-list.toggle-occurrences-aria'}"
aria-pressed = "false"
ng-click = "expand()"
aria-label = "Toggle session occurrences">
</button>

</li>

</ul>  ##
</div> ##
</div> ##
</code>```

Since it had a tag name "button", I tried to use the following but it did not work:

```<code>url = 'Example.com'
driver = webdriver.Chrome()
driver.get(url)

driver.find_element_by_tag_name("button").click()
</code>```

I tried to use xpath and CSS selectors, which I have very minimal experience with. Is there something I could do to expand the list?

Thank you for your help in advance.

UPDATE 6/6/2020

My life became difficult because there was JS on the web page I am trying to access. One of the changes this JS makes is that it hides some of the elements' paths. It is strange; on the web page they are accessible and clickable, but no XPATH can locate them.

I tried to outsmart this by locating an accessible element on the page using ActionChains, then tabbing into the element I want to access and click it. But when I reach the element by tabbing, I can't click it. I printed the element to see what Python sees, and it sees "None". Is there any workaround to this?

答:
Use 'contains method' in the XPath as mentioned below.</p>

```<code>WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH, "//ul/li/button[contains(@class,'icon-button has tooltip')]"))).click()
</code>```

Body:
I am trying to expand a list with Selenium WebDriver for Python, which is controlled by a button that looks like this:

List When Closed

To give you an idea of how it looks when open:

List When Open

The HTML looks like this:

  ##just for more information on the tree

  ##

   ##

role = "presentation"
ng-if = "session.hasOccurrences" ## this is the name of a span
class = "expand-children ng-scope"

<button
role = "button"
class = "icon-button has tooltip"
bb-translate-attrs = "{aria-label ': 'session.session-list.toggle-occurrences-aria'}"
aria-pressed = "false"
ng-click = "expand()"
aria-label = "Toggle session occurrences">
</button>

  ##

 ##

 ##

Since it had a tag name "button", I tried to use the following but it did not work:

url = 'Example.com'
driver = webdriver.Chrome()
driver.get(url)

driver.find_element_by_tag_name("button").click()

I tried to use xpath and CSS selectors, which I have very minimal experience with. Is there something I could do to expand the list?

Thank you for your help in advance.

UPDATE 6/6/2020

My life became difficult because there was JS on the web page I am trying to access. One of the changes this JS makes is that it hides some of the elements' paths. It is strange; on the web page they are accessible and clickable, but no XPATH can locate them.

I tried to outsmart this by locating an accessible element on the page using ActionChains, then tabbing into the element I want to access and click it. But when I reach the element by tabbing, I can't click it. I printed the element to see what Python sees, and it sees "None". Is there any workaround to this?

Body:
Use 'contains method' in the XPath as mentioned below.

WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH, "//ul/li/button[contains(@class,'icon-button has tooltip')]"))).click()


问:
Safely serializing complex values to HTML element attributes
When I have to transfer complex values (e.g. a list of dicts) through a Django template to the front end, I typically use json_script to try and prevent XSS vectors.

Recently, I started using lit-element, which has a neat way of pulling attribute values from your custom elements and providing them as properties to your component. You can say:

<my-element items="{{ serialized array of items }}"></my-element>
```

Then lit-element will take whatever string value is passed to the items attribute and call JSON.parse() on it, so I need a way of serializing my value to JSON.

Since that is relatively trivial in itself, my initial idea was to write a custom template filter and try to match how json_script escapes values. But then I read the source for that function and it explicitly states:

Escape all the HTML/XML special characters with their unicode escapes,
  so value is safe to be output anywhere except for inside a tag attribute.

This sounds like attribute values are potentially a more serious XSS vector. So I guess my question is - how to serialize data (in Django/Python) to JSON so it's safe for use in tag attribute values?

答:
I think the reason it says can be used anywhere apart from attributes is that this function doesn't escape speechmarks, this means you would be able to close an attribute and start a new one easily. Django provides the escapejs template tag that escapes speech marks as well.

This function is in the same source that you linked in your question. Following the approach used there should be safe.

Body:
When I have to transfer complex values (e.g. a list of dicts) through a Django template to the front end, I typically use json_script to try and prevent XSS vectors.

Recently, I started using lit-element, which has a neat way of pulling attribute values from your custom elements and providing them as properties to your component. You can say:

<my-element items="{{ serialized array of items }}"></my-element>

Then lit-element will take whatever string value is passed to the items attribute and call JSON.parse() on it, so I need a way of serializing my value to JSON.

Since that is relatively trivial in itself, my initial idea was to write a custom template filter and try to match how json_script escapes values. But then I read the source for that function and it explicitly states:

Escape all the HTML/XML special characters with their unicode escapes,
  so value is safe to be output anywhere except for inside a tag attribute.

This sounds like attribute values are potentially a more serious XSS vector. So I guess my question is - how to serialize data (in Django/Python) to JSON so it's safe for use in tag attribute values?


问:
Why Stream.of(1, 2, 3).max(Comparator::comparingInt) can not be compiled?
```<code>1: Stream.of(1, 2, 3).max(Comparator::comparingInt)
2: Stream.of(1, 2, 3).max(Integer::compare)
</code>```

why the second line can be used, but the first way can not ?

答:
Stream.max() requires a Comparator instance. A method reference that fits this interface must have two arguments and return an int.

Integer's compare method fits these requirements.

Comparator's comparingInt does not.

comparingInt returns a Comparator, so if you want to use it with Stream.max(), you have to execute it instead of passing a method reference referring to it.

For example, the following will work:

```<code>Stream.of(1, 2, 3).max(Comparator.comparingInt(i -> i));
</code>```

or

```<code>Stream.of(1, 2, 3).max(Comparator.comparingInt(Integer::intValue));
</code>```

In both cases, you have to pass a ToIntFunction to comparingInt (i.e. a function that accepts an object and returns an int).

Body:
1: Stream.of(1, 2, 3).max(Comparator::comparingInt)
2: Stream.of(1, 2, 3).max(Integer::compare)

why the second line can be used, but the first way can not ?

Body:
Stream.max() requires a Comparator instance. A method reference that fits this interface must have two arguments and return an int.

Integer's compare method fits these requirements.

Comparator's comparingInt does not.

comparingInt returns a Comparator, so if you want to use it with Stream.max(), you have to execute it instead of passing a method reference referring to it.

For example, the following will work:

Stream.of(1, 2, 3).max(Comparator.comparingInt(i -> i));

or

Stream.of(1, 2, 3).max(Comparator.comparingInt(Integer::intValue));

In both cases, you have to pass a ToIntFunction to comparingInt (i.e. a function that accepts an object and returns an int).


问:
How to add Leverage browser caching for CDN in .htaccess?
I have below code in my .htaccess

```<code>ExpiresActive On
ExpiresByType image/jpg "access 1 year"
ExpiresByType image/jpeg "access 1 year"
ExpiresByType image/gif "access 1 year"
ExpiresByType image/png "access 1 year"
ExpiresByType text/css "access 1 month"
ExpiresByType application/pdf "access 1 month"
ExpiresByType application/x-javascript "access 1 month"
ExpiresByType application/x-shockwave-flash "access 1 month"
ExpiresByType image/x-icon "access 1 year"
ExpiresDefault "access 2 days"
</code>```

on

```<code>cdn.domain.com/abc.jpg (expiration not specified)
cdn.domain.com/abc.png (expiration not specified)
</code>```

Same issue for JS, CSS & Other as well.

What i need to put in .htaccess so mostly achieve A Grade in that.

答:
I solved the problem with the following steps:
First checked my apache site configuration and make sure "AllowOverride all" present like below.

```<code><Directory /var/www/mysite>
    AllowOverride all
</Directory>
</code>```

Then tried the following commands:

```<code>sudo a2enmod rewrite
sudo a2enmod headers
sudo a2enmod expires
sudo service apache2 restart
</code>```

Body:
I have below code in my .htaccess

ExpiresActive On
ExpiresByType image/jpg "access 1 year"
ExpiresByType image/jpeg "access 1 year"
ExpiresByType image/gif "access 1 year"
ExpiresByType image/png "access 1 year"
ExpiresByType text/css "access 1 month"
ExpiresByType application/pdf "access 1 month"
ExpiresByType application/x-javascript "access 1 month"
ExpiresByType application/x-shockwave-flash "access 1 month"
ExpiresByType image/x-icon "access 1 year"
ExpiresDefault "access 2 days"

on

cdn.domain.com/abc.jpg (expiration not specified)
cdn.domain.com/abc.png (expiration not specified)

Same issue for JS, CSS & Other as well.

What i need to put in .htaccess so mostly achieve A Grade in that.

Body:
I solved the problem with the following steps:
First checked my apache site configuration and make sure "AllowOverride all" present like below.

<Directory /var/www/mysite>
    AllowOverride all
</Directory>

Then tried the following commands:

sudo a2enmod rewrite
sudo a2enmod headers
sudo a2enmod expires
sudo service apache2 restart


问:
Objective-C, Adwhirl banner in Interface Builder
Does anyone have any suggestions on how to make a AdWhirl banner in interface builder? Right now I use this code to make a banner:

```<code> AdWhirlView *awView = [AdWhirlView requestAdWhirlViewWithDelegate:self];

[self.view addSubview:awView];

awView.frame = CGRectMake(0, 361, kAdWhirlViewWidth, kAdWhirlViewHeight);
</code>```

I've tried to make a UIView and making an IBOutlet to it and making it's class a AdWhirlView but I can't seem to get it right...

Thanks

答:
I remember i used ADWhirl in one of my projects something like this. I am just copying the code here

```<code>- (void)viewDidLoad {
    // Add the ADView.
    AdWhirlView *adWhirlView = [AdWhirlView requestAdWhirlViewWithDelegate:self];
    // I use this tag to remove the ADWhirl view, as per my application settings (lite or paid)
    adWhirlView.tag = ADVIEW_TAG;
    adWhirlView.frame = CGRectMake(0, 412, kAdWhirlViewWidth, kAdWhirlViewHeight);
    [self.view addSubview:adWhirlView];
}
</code>```

Then don't forget to implement these delegate methods.

```<code>- (NSString *)adWhirlApplicationKey {
    return @"yourADWhirlAppKey";
}

- (UIViewController *)viewControllerForPresentingModalView {
    return self;
}
</code>```

Finally, also implement these delegate methods for better debugging.

```<code>- (void)adWhirlDidReceiveAd:(AdWhirlView *)adWhirlView;
- (void)adWhirlDidFailToReceiveAd:(AdWhirlView *)adWhirlView usingBackup:(BOOL)yesOrNo;
</code>```

UPDATE:

I am receiving ads after using the view from IB.

But it takes the adView's rect only programatically. I mean, i put the adView in the IB in the middle, but it used to display at the top. But yeah, i get ad's.

Body:
Does anyone have any suggestions on how to make a AdWhirl banner in interface builder? Right now I use this code to make a banner:

 AdWhirlView *awView = [AdWhirlView requestAdWhirlViewWithDelegate:self];

[self.view addSubview:awView];

awView.frame = CGRectMake(0, 361, kAdWhirlViewWidth, kAdWhirlViewHeight);

I've tried to make a UIView and making an IBOutlet to it and making it's class a AdWhirlView but I can't seem to get it right...

Thanks

Body:
I remember i used ADWhirl in one of my projects something like this. I am just copying the code here

- (void)viewDidLoad {
    // Add the ADView.
    AdWhirlView *adWhirlView = [AdWhirlView requestAdWhirlViewWithDelegate:self];
    // I use this tag to remove the ADWhirl view, as per my application settings (lite or paid)
    adWhirlView.tag = ADVIEW_TAG;
    adWhirlView.frame = CGRectMake(0, 412, kAdWhirlViewWidth, kAdWhirlViewHeight);
    [self.view addSubview:adWhirlView];
}

Then don't forget to implement these delegate methods.

- (NSString *)adWhirlApplicationKey {
    return @"yourADWhirlAppKey";
}

- (UIViewController *)viewControllerForPresentingModalView {
    return self;
}

Finally, also implement these delegate methods for better debugging.

- (void)adWhirlDidReceiveAd:(AdWhirlView *)adWhirlView;
- (void)adWhirlDidFailToReceiveAd:(AdWhirlView *)adWhirlView usingBackup:(BOOL)yesOrNo;

UPDATE:

I am receiving ads after using the view from IB.

But it takes the adView's rect only programatically. I mean, i put the adView in the IB in the middle, but it used to display at the top. But yeah, i get ad's.


问:
How to fill the custom columns with joined values
I have a query like:

```<code>    SELECT `main_table`.*,
       IF(sosh.status = 'pending_payment', sosh.created_at, null)      AS `pending_payment_status_datetime`,
       IF(sosh.status = 'processing_payd', sosh.created_at, null)      AS `processing_payd_status_datetime`,
       IF(sosh.status = 'processing', sosh.created_at, null)           AS `processing_status_datetime`,
       IF(sosh.status = 'complete', sosh.created_at, null)             AS `complete_status_datetime`,
       IF(sosh.status = 'shipping_ready', sosh.created_at, null)       AS `shipping_ready_status_datetime`,
       IF(sosh.status = 'shipping_ready_cod', sosh.created_at, null)   AS `shipping_ready_cod_status_datetime`,
       IF(sosh.status = 'shipping_in_progress', sosh.created_at, null) AS `shipping_in_progress_status_datetime`,
       IF(sosh.status = 'closed', sosh.created_at, null)               AS `closed_status_datetime`,
       IF(sosh.status = 'archived', sosh.created_at, null)             AS `archived_status_datetime`,
       IF(sosh.status = 'withdraw', sosh.created_at, null)             AS `withdraw_status_datetime`,
       IF(sosh.status = 'canceled', sosh.created_at, null)             AS `canceled_status_datetime`
FROM `sales_order_grid` AS `main_table`
         LEFT JOIN `sales_order_status_history` AS `sosh` ON sosh.parent_id = main_table.entity_id
GROUP BY `main_table`.`entity_id`;
</code>```

I have 2 tables:

sales_order_grid (where the main data is)

sales_order_status_history (where I want to attach the status data)

I need to fetch custom columns values of the latest statuses (I mean there could be more than one status for the order, but the date differs).

Could you please help me with that?

答:
I assume you want an aggregation query:

```<code>SELECT `main_table`.*,
       SUM(sosh.status = 'pending_payment')  AS `pending_payment_status_datetime`,
       SUM(sosh.status = 'processing_payd') AS `processing_payd_status_datetime`,
       SUM(sosh.status = 'processing')           AS `processing_status_datetime`,
       SUM(sosh.status = 'complete')             AS `complete_status_datetime`,
       SUM(sosh.status = 'shipping_ready')       AS `shipping_ready_status_datetime`,
       SUM(sosh.status = 'shipping_ready_cod')   AS `shipping_ready_cod_status_datetime`,
       SUM(sosh.status = 'shipping_in_progress') AS `shipping_in_progress_status_datetime`,
       SUM(sosh.status = 'closed',)               AS `closed_status_datetime`,
       SUM(sosh.status = 'archived')             AS `archived_status_datetime`,
       SUM(sosh.status = 'withdraw' )             AS `withdraw_status_datetime`,
       SUM(sosh.status = 'canceled')             AS `canceled_status_datetime`
FROM `sales_order_grid``main_table` LEFT JOIN
     `sales_order_status_history` `sosh`
     ON sosh.parent_id = main_table.entity_id
GROUP BY `main_table`.`entity_id`;
</code>```

This may fix the problems you are having.

EDIT:

You are asking for the latest statuses.  Then the logic is:

```<code>SELECT so.*,
       MAX(CASE WHEN sosh.status = 'pending_payment' THEN sosh.created_at END) AS pending_payment_status_datetime,
       MAX(CASE WHEN sosh.status = 'processing_payd' THEN sosh.created_at END) AS processing_payd_status_datetime,
       . . .
FROM sales_order_grid so LEFT JOIN
     sales_order_status_history `sosh`
     ON sosh.parent_id = so.entity_id
GROUP BY so.entity_id;
</code>```

Body:
I have a query like:

    SELECT `main_table`.*,
       IF(sosh.status = 'pending_payment', sosh.created_at, null)      AS `pending_payment_status_datetime`,
       IF(sosh.status = 'processing_payd', sosh.created_at, null)      AS `processing_payd_status_datetime`,
       IF(sosh.status = 'processing', sosh.created_at, null)           AS `processing_status_datetime`,
       IF(sosh.status = 'complete', sosh.created_at, null)             AS `complete_status_datetime`,
       IF(sosh.status = 'shipping_ready', sosh.created_at, null)       AS `shipping_ready_status_datetime`,
       IF(sosh.status = 'shipping_ready_cod', sosh.created_at, null)   AS `shipping_ready_cod_status_datetime`,
       IF(sosh.status = 'shipping_in_progress', sosh.created_at, null) AS `shipping_in_progress_status_datetime`,
       IF(sosh.status = 'closed', sosh.created_at, null)               AS `closed_status_datetime`,
       IF(sosh.status = 'archived', sosh.created_at, null)             AS `archived_status_datetime`,
       IF(sosh.status = 'withdraw', sosh.created_at, null)             AS `withdraw_status_datetime`,
       IF(sosh.status = 'canceled', sosh.created_at, null)             AS `canceled_status_datetime`
FROM `sales_order_grid` AS `main_table`
         LEFT JOIN `sales_order_status_history` AS `sosh` ON sosh.parent_id = main_table.entity_id
GROUP BY `main_table`.`entity_id`;

I have 2 tables:

sales_order_grid (where the main data is)

sales_order_status_history (where I want to attach the status data)

I need to fetch custom columns values of the latest statuses (I mean there could be more than one status for the order, but the date differs).

Could you please help me with that?

Body:
I assume you want an aggregation query:

SELECT `main_table`.*,
       SUM(sosh.status = 'pending_payment')  AS `pending_payment_status_datetime`,
       SUM(sosh.status = 'processing_payd') AS `processing_payd_status_datetime`,
       SUM(sosh.status = 'processing')           AS `processing_status_datetime`,
       SUM(sosh.status = 'complete')             AS `complete_status_datetime`,
       SUM(sosh.status = 'shipping_ready')       AS `shipping_ready_status_datetime`,
       SUM(sosh.status = 'shipping_ready_cod')   AS `shipping_ready_cod_status_datetime`,
       SUM(sosh.status = 'shipping_in_progress') AS `shipping_in_progress_status_datetime`,
       SUM(sosh.status = 'closed',)               AS `closed_status_datetime`,
       SUM(sosh.status = 'archived')             AS `archived_status_datetime`,
       SUM(sosh.status = 'withdraw' )             AS `withdraw_status_datetime`,
       SUM(sosh.status = 'canceled')             AS `canceled_status_datetime`
FROM `sales_order_grid``main_table` LEFT JOIN
     `sales_order_status_history` `sosh`
     ON sosh.parent_id = main_table.entity_id
GROUP BY `main_table`.`entity_id`;

This may fix the problems you are having.

EDIT:

You are asking for the latest statuses.  Then the logic is:

SELECT so.*,
       MAX(CASE WHEN sosh.status = 'pending_payment' THEN sosh.created_at END) AS pending_payment_status_datetime,
       MAX(CASE WHEN sosh.status = 'processing_payd' THEN sosh.created_at END) AS processing_payd_status_datetime,
       . . .
FROM sales_order_grid so LEFT JOIN
     sales_order_status_history `sosh`
     ON sosh.parent_id = so.entity_id
GROUP BY so.entity_id;


问:
How can one use an USB OTG serial interface on Android, in Qt?
I intend to port a Qt desktop application to Android. It uses QSerialPort to communicate with an external device (which has a built-in CP210x)

The application, although written purely in Qt and C++, runs fine on Android, but it doesn't see the device. The CP210x official driver download page recommends to compile the kernel on Android from source, which is not feasible to expect from the average customer. Other recommendations I found online recommend jailbraking the phone, which also isn't something we could expect end users to do.

There are scant few questions in this topic on the Qt forums, most saying that QSerialPort's Android support is quite limited. However, these topics are often at least 6-7 years old.

An Android developer forum/wiki/tutorial? recommends to use "Android Things", whatever it is. I couldn't find any apps fitting that description.

I know that it's physically possible to use serial-usb on an non-jailbroken Android, as I tried out a serial console app and it worked, I could successfully exchange data with my device.

Does this mean that the only was is to develop my own wrapper in Java, and use JNIEXPORT? That would break the easy multi-platform compilation I used before (just selecting a different kit from Qt Creator) Are there any simpler ways to accomplish this? Is USB OTG usage so low that no one else thought to implement anything in this regard?

答:
QSerialPort has only a non-official partial Android Support (see https://wiki.qt.io/Qt_Serial_Port).

(... Use on own risk, only for rooted devices, in which is it possible to get/set a permissions to the /dev/ttyXYZ nodes)

You can use JNI to get a FileDescriptor with permission and then use the libusb library in C++ to communicate with device.
But yes, it would break the easy multi-platform compilation.


问:
Can I add [FromBody] parameter with backward compatibility?
I have endpoint which doesn't have [FromBody] parameter:

```<code>    [HttpPost("{id:int}/publish")]
    public async Task<IActionResult> Publish()
    {
        <do some stuff>
        return Ok();
    }
</code>```

But now I need to add [FromBody] parameter in the way that old code is still able to use this endpoint without parameter:

```<code>    [HttpPost("{id:int}/publish")]
    public async Task<IActionResult> Publish([FromBody] PublishRequest request)
    {
        <do some stuff>
        return Ok();
    }
</code>```

But if I add it in this way and try to call this endpoint with empty body, i got 415 (Unsupported Media Type) response back.

I want to make this change backward compatible. So it should be possible to use this endpoint without request body and content-type header. Is is possible?

答:
You can make the PublishRequest optional.</p>

```<code>[HttpPost("{id:int}/publish")]
public async Task<IActionResult> Publish([FromBody] PublishRequest? request)
{
    // <do some stuff>
    return Ok();
}
</code>```

Body:
I have endpoint which doesn't have [FromBody] parameter:

    [HttpPost("{id:int}/publish")]
    public async Task<IActionResult> Publish()
    {
        <do some stuff>
        return Ok();
    }

But now I need to add [FromBody] parameter in the way that old code is still able to use this endpoint without parameter:

    [HttpPost("{id:int}/publish")]
    public async Task<IActionResult> Publish([FromBody] PublishRequest request)
    {
        <do some stuff>
        return Ok();
    }

But if I add it in this way and try to call this endpoint with empty body, i got 415 (Unsupported Media Type) response back.

I want to make this change backward compatible. So it should be possible to use this endpoint without request body and content-type header. Is is possible?

Body:
You can make the PublishRequest optional.

[HttpPost("{id:int}/publish")]
public async Task<IActionResult> Publish([FromBody] PublishRequest? request)
{
    // <do some stuff>
    return Ok();
}


问:
illegal 0000-00-00 00:00:00 timestamp being sent by php to mysql using codeigniter
here is a Database_update_entry function in my CodeIgniter model which gets executed upon successful form submission.

```<code><?php
    function update_entry(){
        $data = array(
            'sl' => $this->input->post('item_sl'),
            'item_name' => $this->input->post('item_name'),
            'img_url' => $this->input->post('img_url'),
            'sound_url' => $this->input->post('sound_url'),
            'price' => $this->input->post('price'),
            'unit' => $this->input->post('unit'),
            'timestamp' => time(),
        );
        echo "current time: ".  time();
        $this->db->update(MY_TABLE_NAME, $data);
    }
?>
</code>```

the database query gets executed fine.... but the time that gets set into the mysql table is
0000-00-00 00:00:00 whereas the <?php echo time() ?> statement shows 1307018223 in the browser.... which is a valid UNIX timestamp... you can check the timestamp validity here.

here is a screenshot of the table that takes data from mySQL table after successful update_queryhttp://s3.amazonaws.com/awesome_screenshot/658523?AWSAccessKeyId=0R7FMW7AXRVCYMAPTPR2&Expires=1307020816&Signature=AncPjnzG9p9QTX7zebZp7c9teB0%3D

what am i doing wrong??? how can i pass a legal timestamp from my php to mySQL?
[p.s. i have checked that the timestamp field in my mysql table is a timestamp field]

答:
You need to provide a time stamp string, not an integer. Try:</p>

```<code>'timestamp' => date('Y-m-d H:i:s', time()),
</code>```

Body:
here is a Database_update_entry function in my CodeIgniter model which gets executed upon successful form submission.

<?php
    function update_entry(){
        $data = array(
            'sl' => $this->input->post('item_sl'),
            'item_name' => $this->input->post('item_name'),
            'img_url' => $this->input->post('img_url'),
            'sound_url' => $this->input->post('sound_url'),
            'price' => $this->input->post('price'),
            'unit' => $this->input->post('unit'),
            'timestamp' => time(),
        );
        echo "current time: ".  time();
        $this->db->update(MY_TABLE_NAME, $data);
    }
?>

the database query gets executed fine.... but the time that gets set into the mysql table is
0000-00-00 00:00:00 whereas the <?php echo time() ?> statement shows 1307018223 in the browser.... which is a valid UNIX timestamp... you can check the timestamp validity here.

here is a screenshot of the table that takes data from mySQL table after successful update_queryhttp://s3.amazonaws.com/awesome_screenshot/658523?AWSAccessKeyId=0R7FMW7AXRVCYMAPTPR2&Expires=1307020816&Signature=AncPjnzG9p9QTX7zebZp7c9teB0%3D

what am i doing wrong??? how can i pass a legal timestamp from my php to mySQL?
[p.s. i have checked that the timestamp field in my mysql table is a timestamp field]

Body:
You need to provide a time stamp string, not an integer. Try:

'timestamp' => date('Y-m-d H:i:s', time()),


问:
VSTS docker task failed on '&&' token in docker RUN command
I configuring CI for my ASP.NET Core application in VSTS (visual studio online).
I've added "docker-compose build" task to build definition but it fails with errors:

```

    Step 4/9 : RUN dotnet restore QuizService.sln && dotnet publish QuizService.sln -c Release -o obj/Docker/publish
    ---> Running in 7ea0cf1881d1
    ... rence = 'SilentlyContinue'; dotnet restore QuizService.sln && dotnet  ...
    The token '&&' is not a valid statement separator in this version.
    + CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : InvalidEndOfLine
    Service 'quizservice' failed to build: The command 'powershell -Command $ErrorActionPreference = 'Stop'; $ProgressPreference = 'SilentlyContinue'; dotnet restore QuizService.sln && dotnet publish QuizService.sln -c Release -o obj/Docker/publish' returned a non-zero code: 1
    ##[error]Building quizservice
    ##[error]Service 'quizservice' failed to build: The command 'powershell -Command $ErrorActionPreference = 'Stop'; $ProgressPreference = 'SilentlyContinue'; dotnet restore QuizService.sln && dotnet publish QuizService.sln -c Release -o obj/Docker/publish' returned a non-zero code: 1
    ##[error]C:\ProgramData\Chocolatey\bin\docker-compose.exe failed with return code: 1

```

The problem is with my dockerfile on line:

```
RUN dotnet restore QuizService.sln && dotnet publish QuizService.sln -c Release -o obj/Docker/publish
```

Somehow docker does not understand '&&' operator:
The token '&&' is not a valid statement separator. The exception itself seems to be related to powershell rather than to docker. Poweshell has no '&&' syntax but why it starts using powershell for RUN command here instead of cmd.exe?

It works like a charm when I build locally on my dev machine.

Do somebody faced the same problem?

答:
If you have docker desktop installed, by default it starts with Windows Container.

From the Docker Desktop menu, select Switch to Linux containers, in order for && symbol to work.

Body:
I configuring CI for my ASP.NET Core application in VSTS (visual studio online).
I've added "docker-compose build" task to build definition but it fails with errors:

    Step 4/9 : RUN dotnet restore QuizService.sln && dotnet publish QuizService.sln -c Release -o obj/Docker/publish
    ---> Running in 7ea0cf1881d1
    ... rence = 'SilentlyContinue'; dotnet restore QuizService.sln && dotnet  ...
    The token '&&' is not a valid statement separator in this version.
    + CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : InvalidEndOfLine
    Service 'quizservice' failed to build: The command 'powershell -Command $ErrorActionPreference = 'Stop'; $ProgressPreference = 'SilentlyContinue'; dotnet restore QuizService.sln && dotnet publish QuizService.sln -c Release -o obj/Docker/publish' returned a non-zero code: 1
    ##[error]Building quizservice
    ##[error]Service 'quizservice' failed to build: The command 'powershell -Command $ErrorActionPreference = 'Stop'; $ProgressPreference = 'SilentlyContinue'; dotnet restore QuizService.sln && dotnet publish QuizService.sln -c Release -o obj/Docker/publish' returned a non-zero code: 1
    ##[error]C:\ProgramData\Chocolatey\bin\docker-compose.exe failed with return code: 1

The problem is with my dockerfile on line:

RUN dotnet restore QuizService.sln && dotnet publish QuizService.sln -c Release -o obj/Docker/publish

Somehow docker does not understand '&&' operator:
The token '&&' is not a valid statement separator. The exception itself seems to be related to powershell rather than to docker. Poweshell has no '&&' syntax but why it starts using powershell for RUN command here instead of cmd.exe?

It works like a charm when I build locally on my dev machine.

Do somebody faced the same problem?


问:
Algorithm of checking if the number is prime
Hello everyone!

I came to this algorithm on how to check if number is prime and probably it's fine for me but I want to find out if it can be improved

```<code>bool isPrime(int num)
{
    bool isPrime = 1;
    if (num <= 0)
    {
        return 0;
    }
    if (num == 1)
    {
        return 0;
    }
    for (int i = 2; i <= sqrt(num); ++i)
    {
        if (num % i == 0)
        {
            isPrime = 0;
        }
    }

    return isPrime;
}
</code>```

Thanks in advance

答:
The algorithm can be improved further by observing that all primes are of the form 6k ± 1, with the exception of 2 and 3. This is because all integers can be expressed as (6k + i) for some integer k and for i = -1, 0, 1, 2, 3, or 4; 2 divides (6k + 0), (6k + 2), (6k + 4); and 3 divides (6k + 3). So a more efficient method is to test if n is divisible by 2 or 3, then to check through all the numbers of form 6k ± 1

Implementation of the above:

```<code>#include <iostream>

bool isPrime(int n) {
    // Corner cases
    if(n <= 1) return false;
    if(n <= 3) return true;

    // This is checked so that we can skip
    // middle five numbers in below loop
    if(n % 2 == 0 || n % 3 == 0) return false;

    for(int i = 5; i * i <= n; i = i + 6)
        if(n % i == 0 || n % (i + 2) == 0) return false;

    return true;
}

// Driver Program to test above function
int main() {
    std::cout << std::boolalpha
        << isPrime(11) << '\n'
        << isPrime(15) << '\n';
}

</code>```

Body:
Hello everyone!

I came to this algorithm on how to check if number is prime and probably it's fine for me but I want to find out if it can be improved

bool isPrime(int num)
{
    bool isPrime = 1;
    if (num <= 0)
    {
        return 0;
    }
    if (num == 1)
    {
        return 0;
    }
    for (int i = 2; i <= sqrt(num); ++i)
    {
        if (num % i == 0)
        {
            isPrime = 0;
        }
    }

    return isPrime;
}

Thanks in advance

Body:
The algorithm can be improved further by observing that all primes are of the form 6k ± 1, with the exception of 2 and 3. This is because all integers can be expressed as (6k + i) for some integer k and for i = -1, 0, 1, 2, 3, or 4; 2 divides (6k + 0), (6k + 2), (6k + 4); and 3 divides (6k + 3). So a more efficient method is to test if n is divisible by 2 or 3, then to check through all the numbers of form 6k ± 1

Implementation of the above:

#include <iostream>

bool isPrime(int n) {
    // Corner cases
    if(n <= 1) return false;
    if(n <= 3) return true;

    // This is checked so that we can skip
    // middle five numbers in below loop
    if(n % 2 == 0 || n % 3 == 0) return false;

    for(int i = 5; i * i <= n; i = i + 6)
        if(n % i == 0 || n % (i + 2) == 0) return false;

    return true;
}

// Driver Program to test above function
int main() {
    std::cout << std::boolalpha
        << isPrime(11) << '\n'
        << isPrime(15) << '\n';
}


问:
Git history messed up by TFS PR
I've been doing a PR from our main branch dev into a sub branch dev_group1 that we use for parallel development and that we usually merge to dev and where me merge dev back from.

Dev has a No-Fast Forward merge policy in TFS (enforced), while dev_group1 has a Squash merge policy (enforced).

Every few weeks we do:

```<code>dev -> dev-group1
dev_group1 -> dev
</code>```

This has been working fine for several months, but during the last merge we first did a

```<code>dev -> dev-group1
</code>```

merge, which had about 20 file conflicts. We solved them and merged the PR.

When we tried to do the merge

```<code>dev_group1 -> dev
</code>```

We saw pretty much the same files conflicting again (there were about 18 conflicts). This was already very strange, and we resolved to redo the merge

```<code>dev -> dev-group1
</code>```

, which gave the same conflicts. We took the dev_group1 version, as it had the conflicts resolved.

When we went to TFS we saw that the PR was affecting about 180 tfs items, but without any file change.

We closed the PR.

Then we tried to redo the merge

```<code>dev_group1 -> dev
</code>```

But we still have the same conflicts!

This is very puzzling, and I cannot provide an explanation for this. What can have gone wrong?

答:
The issue was related to having a branch dev_group1 and another dev_GROUP1.

So, the second branch was created by mistake on a dev machine, and git treated them as separated branches, and in the TFS web interface they were shown as two separate ones.

But probably the TFS api was not discerning between the two. We deleted the dev_GROUP1 branch and everything was fine then.

Title: Git history messed up by TFS PR

Body:
I've been doing a PR from our main branch dev into a sub branch dev_group1 that we use for parallel development and that we usually merge to dev and where me merge dev back from.

Dev has a No-Fast Forward merge policy in TFS (enforced), while dev_group1 has a Squash merge policy (enforced).

Every few weeks we do:

dev -> dev-group1
dev_group1 -> dev

This has been working fine for several months, but during the last merge we first did a

dev -> dev-group1

merge, which had about 20 file conflicts. We solved them and merged the PR.

When we tried to do the merge

dev_group1 -> dev

We saw pretty much the same files conflicting again (there were about 18 conflicts). This was already very strange, and we resolved to redo the merge

dev -> dev-group1

, which gave the same conflicts. We took the dev_group1 version, as it had the conflicts resolved.

When we went to TFS we saw that the PR was affecting about 180 tfs items, but without any file change.

We closed the PR.

Then we tried to redo the merge

dev_group1 -> dev

But we still have the same conflicts!

This is very puzzling, and I cannot provide an explanation for this. What can have gone wrong?