问:
Git submodule URL not including username?
I have a git repository set up with several submodules, which creates a .gitmodules file that is a tracked file in the parent repository. However, there are other developers wanting to work on this repository, and check out the submodules. But currently the URLs for the remote submodule repositories contain my username; in the .gitmodules file it's something like:

```<code>[submodule foo]
  path = sub/foo
  url = https://myuser@example.com/git/foo.git
</code>```

Obviously other developers can't fetch from example.com as myuser (they don't have my password); how can I have one main repository that multiple developers can pull/push to, and allow them to have individual access to the submodules (setting up a single username they all share on the submodule host server would work, but is not good user management)?

答:
Modify your .gitmodules and remove the username from the url:

```<code>[submodule foo]
  path = sub/foo
  url = https://example.com/git/foo.git
</code>```

And finally:

```<code>cd foo/
git submodule init
git submodule update

# Will be prompted to provide username and password
</code>```

Body:
I have a git repository set up with several submodules, which creates a .gitmodules file that is a tracked file in the parent repository. However, there are other developers wanting to work on this repository, and check out the submodules. But currently the URLs for the remote submodule repositories contain my username; in the .gitmodules file it's something like:

[submodule foo]
  path = sub/foo
  url = https://myuser@example.com/git/foo.git

Obviously other developers can't fetch from example.com as myuser (they don't have my password); how can I have one main repository that multiple developers can pull/push to, and allow them to have individual access to the submodules (setting up a single username they all share on the submodule host server would work, but is not good user management)?

Body:
Modify your .gitmodules and remove the username from the url:

[submodule foo]
  path = sub/foo
  url = https://example.com/git/foo.git

And finally:

cd foo/
git submodule init
git submodule update

# Will be prompted to provide username and password


来源: stackexchange

问:
Why does my android app only work in flight mode?
I created an app in Android studio using maps and geo location with great success.  I've recently updated my phone handset (Samsung J6 Plus) to Pie 9.0 but now the app will not load on my phone or on the virtual device within Android studio.  It will load however, when my phone and the virtual device is set to flight mode.

I've updated Android studio to 3.4.1 and updated the support repository SDK Tools, SDK Platform-Tools, Emulator and SDK build-tools 29-rc3.

```<code>import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

//Changed from Stackflow - public class AR_MapsActivity extends FragmentActivity implements OnMapReadyCallback
public class AR_MapsActivity extends AppCompatActivity implements OnMapReadyCallback {

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        MenuInflater menuInflater = getMenuInflater();
        menuInflater.inflate(R.menu.main_menu, menu);

            return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        return super.onOptionsItemSelected(item);
    }

    private GoogleMap mMap;

    LocationListener locationListener;
    LocationManager locationManager;

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 1) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) ;
            {
                if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED)
                    ;
                {
                    locationManager.requestLocationUpdates(locationManager.GPS_PROVIDER, 30, 5, locationListener);
                }
            }
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ar_maps);
        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
    }

    /**
     * Manipulates the map once available.
     * This callback is triggered when the map is ready to be used.
     * This is where we can add markers or lines, add listeners or move the camera. In this case,
     * we just add a marker near Sydney, Australia.
     * If Google Play services is not installed on the device, the user will be prompted to install
     * it inside the SupportMapFragment. This method will only be triggered once the user has
     * installed Google Play services and returned to the app.
     */
    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;
        //RM Adding the code from the location activity Lecture 97 LocationManager and listener
        locationManager = (LocationManager)this.getSystemService(Context.LOCATION_SERVICE);
        locationListener = new LocationListener() {
            @Override
            public void onLocationChanged(Location location) {

                //Added a Toast - for demo and then added the code for the location
                mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
                // Add a marker in Sydney and move the camera
                LatLng userLocation = new LatLng(location.getLatitude(), location.getLongitude());
                mMap.clear();
                mMap.addMarker(new MarkerOptions().position(userLocation).title("AR Projects HQ"));
                mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(userLocation, 16));

                //Added 06-03-2019 to add another pointer on map
                LatLng randy = new LatLng(50.877644, -2.108941);
                mMap.addMarker(new MarkerOptions().position(randy).title("Randy HQ"));

                LatLng roddy = new LatLng(50.876722, -2.101839);
                mMap.addMarker(new MarkerOptions().position(roddy).title("Roddy HQ"));
                //Hardcoded another pointer on the map

            }

            @Override
            public void onStatusChanged(String provider, int status, Bundle extras) {

            }

            @Override
            public void onProviderEnabled(String provider) {

            }

            @Override
            public void onProviderDisabled(String provider) {

            }
        };

        //RM - Adding code from location activity
        //RM - WAS - if (Build.VERSION.SDK_INT < 28)

        if (Build.VERSION.SDK_INT < 28)
        {
            locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 30, 5, locationListener);
        } else {

            //RM - Checks for permission from phone
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) !=PackageManager.PERMISSION_GRANTED)
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
                 else    {

                    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 30, 5, locationListener);

                    Location lastKnownLocation = locationManager.getLastKnownLocation(locationManager.GPS_PROVIDER);

                mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);

                LatLng userLocation = new LatLng(lastKnownLocation.getLatitude(), lastKnownLocation.getLongitude());
                mMap.clear();

                mMap.addMarker(new MarkerOptions().position(userLocation).title("AR Projects HQ"));
                mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(userLocation, 16));
                }
            }
    }
}
</code>```

The app will prompt to request location but then crash out, the message will then say that the App keeps stopping.  This is the same on my phone and virtual emulator, which is set on Pie 9.0 API 28.  However the app will load when airline mode is selected but as this is a map based app it will not display the map.

答:
this is a blind answer because you didn't provide your Log, but you may facing a common problem,
if your app is targeting API level 28 (Android 9.0) or above and your are using play-services-maps dependency version 16.0.0 or lower versions you have to implement this in your AndroidManifest file :

```<code><uses-library
  android:name="org.apache.http.legacy"
  android:required="false" />
</code>```

This is handled for you if you are using

```<code>com.google.android.gms:play-services-maps:16.1.0
</code>```

here is the full documentation :

https://developers.google.com/maps/documentation/android-sdk/config#specify_requirement_for_apache_http_legacy_library

ContentLicense: CC BY-SA 4.0

Body:
I created an app in Android studio using maps and geo location with great success.  I've recently updated my phone handset (Samsung J6 Plus) to Pie 9.0 but now the app will not load on my phone or on the virtual device within Android studio.  It will load however, when my phone and the virtual device is set to flight mode.

I've updated Android studio to 3.4.1 and updated the support repository SDK Tools, SDK Platform-Tools, Emulator and SDK build-tools 29-rc3.

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

//Changed from Stackflow - public class AR_MapsActivity extends FragmentActivity implements OnMapReadyCallback
public class AR_MapsActivity extends AppCompatActivity implements OnMapReadyCallback {

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        MenuInflater menuInflater = getMenuInflater();
        menuInflater.inflate(R.menu.main_menu, menu);

            return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        return super.onOptionsItemSelected(item);
    }

    private GoogleMap mMap;

    LocationListener locationListener;
    LocationManager locationManager;

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 1) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) ;
            {
                if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED)
                    ;
                {
                    locationManager.requestLocationUpdates(locationManager.GPS_PROVIDER, 30, 5, locationListener);
                }
            }
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ar_maps);
        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
    }

    /**
     * Manipulates the map once available.
     * This callback is triggered when the map is ready to be used.
     * This is where we can add markers or lines, add listeners or move the camera. In this case,
     * we just add a marker near Sydney, Australia.
     * If Google Play services is not installed on the device, the user will be prompted to install
     * it inside the SupportMapFragment. This method will only be triggered once the user has
     * installed Google Play services and returned to the app.
     */
    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;
        //RM Adding the code from the location activity Lecture 97 LocationManager and listener
        locationManager = (LocationManager)this.getSystemService(Context.LOCATION_SERVICE);
        locationListener = new LocationListener() {
            @Override
            public void onLocationChanged(Location location) {

                //Added a Toast - for demo and then added the code for the location
                mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
                // Add a marker in Sydney and move the camera
                LatLng userLocation = new LatLng(location.getLatitude(), location.getLongitude());
                mMap.clear();
                mMap.addMarker(new MarkerOptions().position(userLocation).title("AR Projects HQ"));
                mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(userLocation, 16));

                //Added 06-03-2019 to add another pointer on map
                LatLng randy = new LatLng(50.877644, -2.108941);
                mMap.addMarker(new MarkerOptions().position(randy).title("Randy HQ"));

                LatLng roddy = new LatLng(50.876722, -2.101839);
                mMap.addMarker(new MarkerOptions().position(roddy).title("Roddy HQ"));
                //Hardcoded another pointer on the map

            }

            @Override
            public void onStatusChanged(String provider, int status, Bundle extras) {

            }

            @Override
            public void onProviderEnabled(String provider) {

            }

            @Override
            public void onProviderDisabled(String provider) {

            }
        };

        //RM - Adding code from location activity
        //RM - WAS - if (Build.VERSION.SDK_INT < 28)

        if (Build.VERSION.SDK_INT < 28)
        {
            locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 30, 5, locationListener);
        } else {

            //RM - Checks for permission from phone
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) !=PackageManager.PERMISSION_GRANTED)
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
                 else    {

                    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 30, 5, locationListener);

                    Location lastKnownLocation = locationManager.getLastKnownLocation(locationManager.GPS_PROVIDER);

                mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);

                LatLng userLocation = new LatLng(lastKnownLocation.getLatitude(), lastKnownLocation.getLongitude());
                mMap.clear();

                mMap.addMarker(new MarkerOptions().position(userLocation).title("AR Projects HQ"));
                mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(userLocation, 16));
                }
            }
    }
}

The app will prompt to request location but then crash out, the message will then say that the App keeps stopping.  This is the same on my phone and virtual emulator, which is set on Pie 9.0 API 28.  However the app will load when airline mode is selected but as this is a map based app it will not display the map.

Body:
this is a blind answer because you didn't provide your Log, but you may facing a common problem,
if your app is targeting API level 28 (Android 9.0) or above and your are using play-services-maps dependency version 16.0.0 or lower versions you have to implement this in your AndroidManifest file :

<uses-library
  android:name="org.apache.http.legacy"
  android:required="false" />

This is handled for you if you are using

com.google.android.gms:play-services-maps:16.1.0

here is the full documentation :

https://developers.google.com/maps/documentation/android-sdk/config#specify_requirement_for_apache_http_legacy_library


问:
Compress multiple blob Excel files into a zip file javascript
I am actually using this library: https://github.com/SheetJS/js-xlsx.
I used it to create and download an XLSX file that extracts a table from my website. This does work pretty well, but I am trying to do something more complicated now.

I am trying to download all my tables at the same time, which means downloading multiple XLSX files. It does works with my actual code :

```<code>function saveAll(dataAll){
    for (let i=0;i<dataAll.length;++i) {
        let ws_name = "SheetJS";
        let data = dataAll[i];

        let wb = new Workbook();
        console.log(data);
        let ws = sheet_from_array_of_arrays(data.content, null, data.mois, data.annee);

        /* add worksheet to workbook */
        wb.SheetNames.push(ws_name);
        wb.Sheets[ws_name] = ws;

        let wbout = XLSX.write(wb, {bookType: 'xlsx', bookSST: true, type: 'binary'});

        saveAs(new Blob([s2ab(wbout)],{type: "application/octet-stream"}), data.prenom_nom + " PVA " + data.mois + " " + data.annee + ".xlsx");
    }
}
</code>```

Now i'd like to download all those xlsx files into an unique ZIP or tar.gz file, but i am kinda stuck. I tryed to use the zip.js library, but without success.

My dataAll parameter is array of objects, and each object contains .content which is a matrix, and some other parameters used on the file name.

How can I manage to download all these xlsx files in only one archive, instead of downloading them one by one?

答:
You can try this

var zip = new JSZip();
for(var i=1;i<3;i++)
{
    var workbook = XLSX.utils.book_new();
    var ws1 = XLSX.utils.table_to_sheet(document.getElementById('tbl'+i));
    XLSX.utils.book_append_sheet(workbook, ws1, "Sheet1");
    let wbout = XLSX.write(workbook, {bookType: 'xlsx', bookSST: true, type: 'binary'});

    zip.file("shubham"+i+".xlsx", wbout, {binary: true});
}

zip.generateAsync({type:"blob"})
.then(function(content) {
    // see FileSaver.js
    saveAs(content, "example.zip");
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!Doctype html>
<html lang="en">

<head>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width" , initial-scale=1, shrink>
    <meta name="theme-color" content="#000000">

    <title>ES6</title>
    <script src="https://unpkg.com/xlsx/dist/xlsx.full.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/1.3.8/FileSaver.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.2.0/jszip.min.js"></script>
</head>

<body>
<table id="tbl1">
    <tr><td>Name</td><td>Age</td></tr>
    <tr><td>Shubham</td><td>22</td></tr>
</table>
<table id="tbl2">
    <tr><td>Name</td><td>Age</td></tr>
    <tr><td>Shubham</td><td>22</td></tr>
</table>
</body>
<script>

</script>

</html></code>```

Body:
I am actually using this library: https://github.com/SheetJS/js-xlsx.
I used it to create and download an XLSX file that extracts a table from my website. This does work pretty well, but I am trying to do something more complicated now.

I am trying to download all my tables at the same time, which means downloading multiple XLSX files. It does works with my actual code :

function saveAll(dataAll){
    for (let i=0;i<dataAll.length;++i) {
        let ws_name = "SheetJS";
        let data = dataAll[i];

        let wb = new Workbook();
        console.log(data);
        let ws = sheet_from_array_of_arrays(data.content, null, data.mois, data.annee);

        /* add worksheet to workbook */
        wb.SheetNames.push(ws_name);
        wb.Sheets[ws_name] = ws;

        let wbout = XLSX.write(wb, {bookType: 'xlsx', bookSST: true, type: 'binary'});

        saveAs(new Blob([s2ab(wbout)],{type: "application/octet-stream"}), data.prenom_nom + " PVA " + data.mois + " " + data.annee + ".xlsx");
    }
}

Now i'd like to download all those xlsx files into an unique ZIP or tar.gz file, but i am kinda stuck. I tryed to use the zip.js library, but without success.

My dataAll parameter is array of objects, and each object contains .content which is a matrix, and some other parameters used on the file name.

How can I manage to download all these xlsx files in only one archive, instead of downloading them one by one?

Body:
You can try this

var zip = new JSZip();
for(var i=1;i<3;i++)
{
    var workbook = XLSX.utils.book_new();
    var ws1 = XLSX.utils.table_to_sheet(document.getElementById('tbl'+i));
    XLSX.utils.book_append_sheet(workbook, ws1, "Sheet1");
    let wbout = XLSX.write(workbook, {bookType: 'xlsx', bookSST: true, type: 'binary'});

    zip.file("shubham"+i+".xlsx", wbout, {binary: true});
}

zip.generateAsync({type:"blob"})
.then(function(content) {
    // see FileSaver.js
    saveAs(content, "example.zip");
});

<!Doctype html>
<html lang="en">

<head>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width" , initial-scale=1, shrink>
    <meta name="theme-color" content="#000000">

    <title>ES6</title>
    <script src="https://unpkg.com/xlsx/dist/xlsx.full.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/1.3.8/FileSaver.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.2.0/jszip.min.js"></script>
</head>

<body>
<table id="tbl1">
    <tr><td>Name</td><td>Age</td></tr>
    <tr><td>Shubham</td><td>22</td></tr>
</table>
<table id="tbl2">
    <tr><td>Name</td><td>Age</td></tr>
    <tr><td>Shubham</td><td>22</td></tr>
</table>
</body>
<script>

</script>

</html>


问:
Error When Deserializing a JSON String to a Java Object with Interface Data Member
I have a JSON String and I want to deserialize it to a Java object with a interface data member.  The Java object looks like this:

```<code>public class Person {
     private String id;
     private String name;
     private AddressInterface addr;
}
</code>```

Both the Person and the AddressInterface are third party classes, so I can't make any changes to them.

When I used the following to deserialize the JSON string,

```<code> objectMapper.readValue(json_file, Person.class)
</code>```

I got the following exception.  It's because the object mapper doesn't know how to deserialize the AddressInterface  field.  Can someone let me know how to deserialize the string into an Person object in this case?  Many Thanks.

```<code> abstract types either need to be mapped to
 concrete types, have custom deserializer,
 or be instantiated with additional type information
</code>```

答:
the problem is deserializing AddressInterface property because its an interface and I think objectMapper is trying to initilaize it's default constructer like bellow

```<code>addr = new AddressInterface();
</code>```

you can create an empty concrete class which inherits the AddressInterface and use it instead of AddressInterface

```<code>public class Adress implements AddressInterface {
...
}

public class Person {
 private String id;
 private String name;
 private Adress addr;
}
</code>```

Body:
I have a JSON String and I want to deserialize it to a Java object with a interface data member.  The Java object looks like this:

public class Person {
     private String id;
     private String name;
     private AddressInterface addr;
}

Both the Person and the AddressInterface are third party classes, so I can't make any changes to them.

When I used the following to deserialize the JSON string,

 objectMapper.readValue(json_file, Person.class)

I got the following exception.  It's because the object mapper doesn't know how to deserialize the AddressInterface  field.  Can someone let me know how to deserialize the string into an Person object in this case?  Many Thanks.

 abstract types either need to be mapped to
 concrete types, have custom deserializer,
 or be instantiated with additional type information

Body:
the problem is deserializing AddressInterface property because its an interface and I think objectMapper is trying to initilaize it's default constructer like bellow

addr = new AddressInterface();

you can create an empty concrete class which inherits the AddressInterface and use it instead of AddressInterface

public class Adress implements AddressInterface {
...
}

public class Person {
 private String id;
 private String name;
 private Adress addr;
}


问:
Module @google-cloud/speech not supported for Vue JS?
I'm playing with the Google Cloud API Speech-to-Text Node client library. Works quite well, and well described in their documentation.
Problems come when I wanted to use it in a VueJS : it simply seems not to be supported.

First attempt :
npm run serve returns

 ERROR  Failed to compile with 3 errors                                                                                11:35:13

This dependency was not found:

* http2 in ./node_modules/@grpc/grpc-js/build/src/channel.js, ./node_modules/@grpc/grpc-js/build/src/subchannel.js and 1 other
```

<p>But <code>http2</code> is a core module in Node now, and when I run <code>node -p http2</code> I do get results.</p>

<p>Second attempt :</p>

<ul>
<li><code>npm i http2</code></li>
<li><code>npm run serve</code> returns</li>
</ul>

<pre class="lang-sh prettyprint-override"><code> WARNING  Compiled with 1 warnings                                                                                11:41:07

 warning  in ./node_modules/http2/lib/protocol/index.js

Critical dependency: require function is used in a way in which dependencies cannot be statically extracted
</code>```

In browser, console provides error

```<code>Uncaught Error: not supported
    at Root.loadSync (root.js?ee6e:234)
    at Object.loadSync (index-light.js?071f:69)
    at Object.eval (index.js?f193:244)
    at eval (index.js:250)
    at Object../node_modules/@grpc/proto-loader/build/src/index.js (app.js:1383)
    at __webpack_require__ (app.js:724)
    at fn (app.js:101)
    at Object.eval (grpc.js?6f5f:34)
    at eval (grpc.js:288)
    at Object../node_modules/google-gax/build/src/grpc.js
</code>```

My Vue App is basic and can be retrieved using vue-cli by running vue create app. I then added in the HelloWorld Component the basic code displayed in the quickstart guide.

My theory is : VueJS can't use google-gax module due to gRPC. What do you think ?

答:
Currently the Google Cloud API client libraries such as the one you are using cannot be used from the browser. As you noted, those libraries use gRPC, which in turn uses http2. The problem is that currently no major browser allows JavaScript libraries to use the full functionality of the HTTP/2 protocol, so there is currently no complete browser shim for the Node http2 module.

The http2 module you got from npm is a different library with a different API. It most likely also does not work in the browser for the same reason.

Body:
I'm playing with the Google Cloud API Speech-to-Text Node client library. Works quite well, and well described in their documentation.
Problems come when I wanted to use it in a VueJS : it simply seems not to be supported.

First attempt :
npm run serve returns

 ERROR  Failed to compile with 3 errors                                                                                11:35:13

This dependency was not found:

* http2 in ./node_modules/@grpc/grpc-js/build/src/channel.js, ./node_modules/@grpc/grpc-js/build/src/subchannel.js and 1 other

But http2 is a core module in Node now, and when I run node -p http2 I do get results.

Second attempt :

npm i http2

npm run serve returns

 WARNING  Compiled with 1 warnings                                                                                11:41:07

 warning  in ./node_modules/http2/lib/protocol/index.js

Critical dependency: require function is used in a way in which dependencies cannot be statically extracted

In browser, console provides error

Uncaught Error: not supported
    at Root.loadSync (root.js?ee6e:234)
    at Object.loadSync (index-light.js?071f:69)
    at Object.eval (index.js?f193:244)
    at eval (index.js:250)
    at Object../node_modules/@grpc/proto-loader/build/src/index.js (app.js:1383)
    at __webpack_require__ (app.js:724)
    at fn (app.js:101)
    at Object.eval (grpc.js?6f5f:34)
    at eval (grpc.js:288)
    at Object../node_modules/google-gax/build/src/grpc.js

My Vue App is basic and can be retrieved using vue-cli by running vue create app. I then added in the HelloWorld Component the basic code displayed in the quickstart guide.

My theory is : VueJS can't use google-gax module due to gRPC. What do you think ?


问:
Prevent scrolling on mobile on page with canvas
I've tried many solutions online, but for some reason, this page still moves around vertically when moving my touch on the canvas:

```<code><html>
<head>
<style>

html, body {
  overflow-x: hidden;
}

body {
  background-color: lightgray;
  position: relative;
}

body.noScroll {
  overflow: hidden;
}

</style>
</head>
<body>
        <canvas id="myCanvas" style="touch-action: none;" width="800" height="800"></canvas><br>

        <script>

            document.body.addEventListener("touchmove", getTouchPos)

            var canvas = document.getElementById('myCanvas')
            var context = canvas.getContext('2d')

            context.fillStyle = "#000";
            context.fillRect(0, 0, canvas.width, canvas.height);

            function getTouchPos(evt) {
                evt.preventDefault();
            }

        </script>
    </body>
</html>
</code>```

Tested on iOS Safari.

答:
Have you found this post yet?
Disable scroll/swipe action for html canvas drawing on ios

It led to the following link. Looks like there are multiple events you have to account for. you have to reference your canvas as a dom element as well to evaluate the target

http://bencentra.com/code/2014/12/05/html5-canvas-touch-events.html

Body:
I've tried many solutions online, but for some reason, this page still moves around vertically when moving my touch on the canvas:

        <canvas id="myCanvas" style="touch-action: none;" width="800" height="800"></canvas>

Tested on iOS Safari.


问:
How to make an open source fork derived from closed source project?
I am forking part (but not all) of a closed source project to make an open source one. So far I have made a branch ('open') from which I have removed the features we're not going to open source.

Now I could at this point export the 'open' branch and check it in to a fresh, empty repo, which becomes the open source release.

However, I would like to maintain ability to sync changes between the open and closed source versions: i.e. if we later fix a bug in the closed source, then sync the fix to the open source version also (and vice versa if the contributor consents).

Is there a way I can achieve this, without making the history of the 'open' branch (i.e. the closed branch) public?

答:
As git stores commits as change sets, you can easily cherry-pick changes of one repo to another (if of course the same changed files are present and they don't differ too much).

One way to accomplish this is by adding both "origin"s as remote to a single repo clone.
Then fetching all commits from both remotes (so you have the commit hashes available).
You can then check out one remote's branch and cherry-pick the other remote's commit just like any other single-remote repo cherry-pick.

Something like this in a terribly construed example:

```<code>git clone git://blablabla.git mydoublerepo
cd mydoublerepo
git remote add other git://other.git
git fetch other
git checkout -b other_master -t other/master
git cherry-pick origin/master # cherry-picks the top commit off of the other remote's master branch
</code>```

Note you don't need to create a separate clone for this, you can add any repo as a remote to any other cloned repo.

Body:
As git stores commits as change sets, you can easily cherry-pick changes of one repo to another (if of course the same changed files are present and they don't differ too much).

One way to accomplish this is by adding both "origin"s as remote to a single repo clone.
Then fetching all commits from both remotes (so you have the commit hashes available).
You can then check out one remote's branch and cherry-pick the other remote's commit just like any other single-remote repo cherry-pick.

Something like this in a terribly construed example:

git clone git://blablabla.git mydoublerepo
cd mydoublerepo
git remote add other git://other.git
git fetch other
git checkout -b other_master -t other/master
git cherry-pick origin/master # cherry-picks the top commit off of the other remote's master branch

Note you don't need to create a separate clone for this, you can add any repo as a remote to any other cloned repo.


Title: how to reshape a 3d array with different dimensions?

Body:
I have a numpy array as:

y = np.array([[[14,15,16],[24,25,26],[34,35,36],[44,45,46]],
        [[11,21,31],[12,22,32],[13,23,33],[14,24,34]]])

The shape of y is (2,4,3)
and I want to reshape it to (4,3,2) like:

[[[14,11],[15,21],[16,31]],
 [[24,12],[25,22],[26,32]],
 [[34,13],[35,23],[36,33]],
 [[44,14],[45,24],[46,34]]]

I tried use y.reshape(4,3,2)) but the results are not what I want.

Body:
You can use numpy.moveaxis():

y = np.moveaxis(y,0,2)

and you get:

array([[[14, 11],
        [15, 21],
        [16, 31]],

       [[24, 12],
        [25, 22],
        [26, 32]],

       [[34, 13],
        [35, 23],
        [36, 33]],

       [[44, 14],
        [45, 24],
        [46, 34]]])


问:
Dialogflow Rest API 'Service account authorization without OAuth' failing
I am setting up a remote server and would like to invoke Dialogflow REST API's and specifically detect intent API.

I already have an agent set up with all the intents and entities and would like to access the intents remotely. I have been reading on how to integrate with the API's and I came across 'Addendum: Service account authorization without OAuth' in this article

https://developers.google.com/identity/protocols/OAuth2ServiceAccount

I believe I have pretty much followed all the instructions.What could I be doing wrongly or Am I missing ?

Here is my code:

```<code>    public class DetectIntentTest {

    private static final String PROJECTID = "myprojectid-****";
    private static final String OAUTH_TOKEN_URI = "https://oauth2.googleapis.com/token";
    private static final String CREDENTIALSFILE = "mycredentialsfile-****-****.json";
    private static final String JWT_BEARER_TOKEN_GRANT_TYPE = "urn:ietf:params:oauth:grant-type:jwt-bearer";
    private static final HttpTransport HTTPTRANSPORT = new NetHttpTransport();

public static HttpRequest buildRequest(boolean withoutOauth, String url, String message) throws Exception {
    ServiceAccountCredentials credentials = fetchCredentials();
    String jwt = createJwt(withoutOauth, credentials);
    if (jwt == null) {
        throw new Exception("Could not create a signed jwt token");
    }

    String token = withoutOauth ? jwt : fetchToken(jwt);
    if (token == null) {
        throw new Exception("Could not to retrieve token");
    }

    return HTTPTRANSPORT.createRequestFactory()
            .buildPostRequest(
                    new GenericUrl(url),
                    new JsonHttpContent(JacksonFactory.getDefaultInstance(), message))
            .setHeaders(new HttpHeaders()
                    .setAuthorization("Bearer " + token)
                    .set("Host", host));
}

public static String buildUrl(String uri, String api, String languageCode, String projectId, String sessionId) {
    return "https://dialogflow.googleapis.com/v2/projects/" + projectId + uri + sessionId + ":" + api;
}

 private static String createJwt(boolean withoutOauth, ServiceAccountCredentials credentials) throws Exception {
    long now = System.currentTimeMillis();
    String clientId = credentials.getClientId();
    String privateKeyId = credentials.getPrivateKeyId();
    String serviceAccount = credentials.getClientEmail();
    String oauthTokenURI = credentials.getTokenServerUri().toString();
    RSAPrivateKey privateKey = (RSAPrivateKey) credentials.getPrivateKey();
    Algorithm algorithm = Algorithm.RSA256(null, privateKey);
    return withoutOauth
            ? JWT.create()
                    .withKeyId(privateKeyId)
                    .withIssuer(serviceAccount)
                    .withSubject(serviceAccount)
                    .withIssuedAt(new Date(now))
                    .withExpiresAt(new Date(now + 3600 * 1000L))
                    .withAudience("https://dialogflow.googleapis.com/google.cloud.dialogflow.v2.Agents")
                    .sign(algorithm)
            : JWT.create()
                    .withKeyId(privateKeyId)
                    .withIssuer(serviceAccount)
                    .withSubject(serviceAccount)
                    .withIssuedAt(new Date(now))
                    .withExpiresAt(new Date(now + 3600 * 1000L))
                    .withAudience(oauthTokenURI)
                    .withClaim("target_audience", clientId)
                    .sign(algorithm);
}

public static ServiceAccountCredentials fetchCredentials() throws Exception {
    File credentialFile = new File(ClassLoader.getSystemResource(CREDENTIALSFILE).getFile());
    ServiceAccountCredentials credentials = ServiceAccountCredentials
            .fromStream(new FileInputStream(credentialFile));
    credentials.createScoped(
            "https://www.googleapis.com/auth/dialogflow",
            "https://www.googleapis.com/auth/cloud-platform");
    return credentials;
}

public static String fetchToken(String jwt) throws Exception {
    final GenericData tokenRequest = new GenericData().set("grant_type", JWT_BEARER_TOKEN_GRANT_TYPE).set("assertion", jwt);
    final UrlEncodedContent content = new UrlEncodedContent(tokenRequest);
    final HttpRequestFactory requestFactory = HTTPTRANSPORT.createRequestFactory();
    final HttpRequest request = requestFactory
            .buildPostRequest(new GenericUrl(OAUTH_TOKEN_URI), content)
            .setParser(new JsonObjectParser(JacksonFactory.getDefaultInstance()));
    HttpResponse response = request.execute();
    GenericData responseData = response.parseAs(GenericData.class);
    return (String) responseData.get("id_token");
}

public static void main(String[] args) {

    String api = "detectIntent";
    String uri = "/agent/sessions/";
    String languageCode = "en-US";
    String text = "Hi I would like help";
    String sessionId = UUID.randomUUID().toString();
    String host = "https://dialogflow.googleapis.com";
    String url = DetectIntentTest.buildUrl(uri, api, languageCode, PROJECTID, sessionId);
    JSONObject message = new JSONObject("{"
            + "  \"queryInput\": {"
            + "    \"text\": {"
            + "      \"languageCode\": \"" + languageCode + "\","
            + "      \"text\": \"" + text + "\""
            + "    }"
            + "  }"
            + "}");
    try {
        HttpRequest request = DetectIntentTest.buildRequest(true,host, url, message.toString());
        HttpResponse response = request.execute();
        System.out.println(response.getStatusCode());
        System.out.println(response.getStatusMessage());
        GenericData responseData = response.parseAs(GenericData.class);
        System.out.println(responseData.toString());
    } catch (Exception ex) {
        Logger.getLogger(DetectIntentTest.class.getName()).log(Level.SEVERE, null, ex);
    }
  }
}
</code>```

Variables:

```<code>    {
"bearerToken": "eyJraWQiOiIxYWEyY2MzYTQwZjUwZT********",

"host": "https://dialogflow.googleapis.com",

"text": "Hi I would like help",

"languageCode": "en-US",

"projectId": "myprojectid-****",

"url": "https://dialogflow.googleapis.com/v2/projects/myprojectid-****/agent/sessions/4a02046c-c1a2-4a35-b680-6e779c6d34b8:detectIntent"
    }
</code>```

Body:

```<code>    {"queryInput":
     {"text":
       {"text": "Hi I would like help",
        "languageCode": "en-US"
       }
      }
     }
</code>```

Request:

```<code>    Request{
    method=POST,
    url=https://dialogflow.googleapis.com/v2/projects/myprojectid-****/agent/sessions/4a02046c-c1a2-4a35-b680-6e779c6d34b8:detectIntent,
    tags={}
    }
</code>```

Headers:

```<code>    Authorization: Bearer eyJraWQiOiIxYWEyY2MzYTQwZjUwZT********
    Host: https://dialogflow.googleapis.com
    Content-Type: application/json; charset=utf-8
</code>```

Output:

```<code>    com.google.api.client.http.HttpResponseException: 401 Unauthorized
</code>```

答:
I found the problem, I was using the wrong API name for detect intent on the JWT audience in this list. The correct API Name is "google.cloud.dialogflow.v2.Sessions"

https://github.com/googleapis/googleapis/blob/master/google/cloud/dialogflow/dialogflow_v2.yaml

Body:
I am setting up a remote server and would like to invoke Dialogflow REST API's and specifically detect intent API.

I already have an agent set up with all the intents and entities and would like to access the intents remotely. I have been reading on how to integrate with the API's and I came across 'Addendum: Service account authorization without OAuth' in this article

https://developers.google.com/identity/protocols/OAuth2ServiceAccount

I believe I have pretty much followed all the instructions.What could I be doing wrongly or Am I missing ?

Here is my code:

    public class DetectIntentTest {

    private static final String PROJECTID = "myprojectid-****";
    private static final String OAUTH_TOKEN_URI = "https://oauth2.googleapis.com/token";
    private static final String CREDENTIALSFILE = "mycredentialsfile-****-****.json";
    private static final String JWT_BEARER_TOKEN_GRANT_TYPE = "urn:ietf:params:oauth:grant-type:jwt-bearer";
    private static final HttpTransport HTTPTRANSPORT = new NetHttpTransport();

public static HttpRequest buildRequest(boolean withoutOauth, String url, String message) throws Exception {
    ServiceAccountCredentials credentials = fetchCredentials();
    String jwt = createJwt(withoutOauth, credentials);
    if (jwt == null) {
        throw new Exception("Could not create a signed jwt token");
    }

    String token = withoutOauth ? jwt : fetchToken(jwt);
    if (token == null) {
        throw new Exception("Could not to retrieve token");
    }

    return HTTPTRANSPORT.createRequestFactory()
            .buildPostRequest(
                    new GenericUrl(url),
                    new JsonHttpContent(JacksonFactory.getDefaultInstance(), message))
            .setHeaders(new HttpHeaders()
                    .setAuthorization("Bearer " + token)
                    .set("Host", host));
}

public static String buildUrl(String uri, String api, String languageCode, String projectId, String sessionId) {
    return "https://dialogflow.googleapis.com/v2/projects/" + projectId + uri + sessionId + ":" + api;
}

 private static String createJwt(boolean withoutOauth, ServiceAccountCredentials credentials) throws Exception {
    long now = System.currentTimeMillis();
    String clientId = credentials.getClientId();
    String privateKeyId = credentials.getPrivateKeyId();
    String serviceAccount = credentials.getClientEmail();
    String oauthTokenURI = credentials.getTokenServerUri().toString();
    RSAPrivateKey privateKey = (RSAPrivateKey) credentials.getPrivateKey();
    Algorithm algorithm = Algorithm.RSA256(null, privateKey);
    return withoutOauth
            ? JWT.create()
                    .withKeyId(privateKeyId)
                    .withIssuer(serviceAccount)
                    .withSubject(serviceAccount)
                    .withIssuedAt(new Date(now))
                    .withExpiresAt(new Date(now + 3600 * 1000L))
                    .withAudience("https://dialogflow.googleapis.com/google.cloud.dialogflow.v2.Agents")
                    .sign(algorithm)
            : JWT.create()
                    .withKeyId(privateKeyId)
                    .withIssuer(serviceAccount)
                    .withSubject(serviceAccount)
                    .withIssuedAt(new Date(now))
                    .withExpiresAt(new Date(now + 3600 * 1000L))
                    .withAudience(oauthTokenURI)
                    .withClaim("target_audience", clientId)
                    .sign(algorithm);
}

public static ServiceAccountCredentials fetchCredentials() throws Exception {
    File credentialFile = new File(ClassLoader.getSystemResource(CREDENTIALSFILE).getFile());
    ServiceAccountCredentials credentials = ServiceAccountCredentials
            .fromStream(new FileInputStream(credentialFile));
    credentials.createScoped(
            "https://www.googleapis.com/auth/dialogflow",
            "https://www.googleapis.com/auth/cloud-platform");
    return credentials;
}

public static String fetchToken(String jwt) throws Exception {
    final GenericData tokenRequest = new GenericData().set("grant_type", JWT_BEARER_TOKEN_GRANT_TYPE).set("assertion", jwt);
    final UrlEncodedContent content = new UrlEncodedContent(tokenRequest);
    final HttpRequestFactory requestFactory = HTTPTRANSPORT.createRequestFactory();
    final HttpRequest request = requestFactory
            .buildPostRequest(new GenericUrl(OAUTH_TOKEN_URI), content)
            .setParser(new JsonObjectParser(JacksonFactory.getDefaultInstance()));
    HttpResponse response = request.execute();
    GenericData responseData = response.parseAs(GenericData.class);
    return (String) responseData.get("id_token");
}

public static void main(String[] args) {

    String api = "detectIntent";
    String uri = "/agent/sessions/";
    String languageCode = "en-US";
    String text = "Hi I would like help";
    String sessionId = UUID.randomUUID().toString();
    String host = "https://dialogflow.googleapis.com";
    String url = DetectIntentTest.buildUrl(uri, api, languageCode, PROJECTID, sessionId);
    JSONObject message = new JSONObject("{"
            + "  \"queryInput\": {"
            + "    \"text\": {"
            + "      \"languageCode\": \"" + languageCode + "\","
            + "      \"text\": \"" + text + "\""
            + "    }"
            + "  }"
            + "}");
    try {
        HttpRequest request = DetectIntentTest.buildRequest(true,host, url, message.toString());
        HttpResponse response = request.execute();
        System.out.println(response.getStatusCode());
        System.out.println(response.getStatusMessage());
        GenericData responseData = response.parseAs(GenericData.class);
        System.out.println(responseData.toString());
    } catch (Exception ex) {
        Logger.getLogger(DetectIntentTest.class.getName()).log(Level.SEVERE, null, ex);
    }
  }
}

Variables:

    {
"bearerToken": "eyJraWQiOiIxYWEyY2MzYTQwZjUwZT********",

"host": "https://dialogflow.googleapis.com",

"text": "Hi I would like help",

"languageCode": "en-US",

"projectId": "myprojectid-****",

"url": "https://dialogflow.googleapis.com/v2/projects/myprojectid-****/agent/sessions/4a02046c-c1a2-4a35-b680-6e779c6d34b8:detectIntent"
    }

Body:

    {"queryInput":
     {"text":
       {"text": "Hi I would like help",
        "languageCode": "en-US"
       }
      }
     }

Request:

    Request{
    method=POST,
    url=https://dialogflow.googleapis.com/v2/projects/myprojectid-****/agent/sessions/4a02046c-c1a2-4a35-b680-6e779c6d34b8:detectIntent,
    tags={}
    }

Headers:

    Authorization: Bearer eyJraWQiOiIxYWEyY2MzYTQwZjUwZT********
    Host: https://dialogflow.googleapis.com
    Content-Type: application/json; charset=utf-8

Output:

    com.google.api.client.http.HttpResponseException: 401 Unauthorized


问:
Julia FixedEffectsModels IV regression doesn't match R IV regression
When I run (what I think is the same regression) in R and in Julia I get very different results. I think this is because the IV regression is using an indicator variable to instrument for another indicator variable but I can't figure out if I am doing something else wrong.

I have tried several different methods, but the data starts like this:

```<code>   rc D tau     May_ret     Jun_ret      Jul_ret     Aug_ret      Sep_ret
1 -43 0   0  0.04529617  0.02106667  0.009868421 0.032573290  0.010473186
2 -19 0   0  0.01973333  0.05752213 -0.020920502 0.027521368 -0.029535865
3  74 1   1  0.33505189  0.04494382 -0.150537640 0.246835440  0.010152284
4  54 1   1  0.03602649  0.06168831  0.030581040 0.002611276 -0.027027028
5  22 1   1 -0.01584158 -0.08417509 -0.088235296 0.012903226  0.100000001
6   7 1   1  0.02484472  0.08000000  0.039548021 0.065217391  0.006122449
</code>```

D and tau are not perfectly linear, but they are close (and tau is being used to instrument for D).

My R code is

```<code>library(AER)
library(stargazer)

temp_df <- read.csv(file="output.csv")

addmay <- ivreg(May_ret ~ D*rc|tau*rc, data=temp_df)
addjun <- ivreg(Jun_ret ~ D*rc|tau*rc, data=temp_df)
addjul <- ivreg(Jul_ret ~ D*rc|tau*rc, data=temp_df)
addaug <- ivreg(Aug_ret ~ D*rc|tau*rc, data=temp_df)
addsep <- ivreg(Sep_ret ~ D*rc|tau*rc, data=temp_df)

stargazer(addmay, addjun, addjul, addaug, addsep, title="Addition Return Effect", align=TRUE, type="text", report="vc*t")
</code>```

Which produces

```<code>========================================================================================================
                                                    Dependent variable:
                    ------------------------------------------------------------------------------------
                        May_ret          Jun_ret          Jul_ret          Aug_ret          Sep_ret
                          (1)              (2)              (3)              (4)              (5)
--------------------------------------------------------------------------------------------------------
D                        0.006            0.033            -0.008           0.028           -0.044*
                       t = 0.304        t = 1.600        t = -0.353       t = 1.283        t = -1.943

rc                      -0.0001          -0.0001          -0.0003          -0.0003*          0.0002
                       t = -0.736       t = -0.730       t = -1.495       t = -1.784       t = 1.094

D:rc                     0.0002          -0.0002          0.001***          0.0002           0.0001
                       t = 0.817        t = -0.747       t = 2.660        t = 0.706        t = 0.392

Constant                 0.0002          -0.021*          -0.024*          -0.021*           0.009
                       t = 0.014        t = -1.778       t = -1.831       t = -1.673       t = 0.654

--------------------------------------------------------------------------------------------------------
Observations              827              828              824              823              818
R2                       0.003            0.007            0.007            0.026            0.012
Adjusted R2             -0.0005           0.004            0.004            0.023            0.009
Residual Std. Error 0.106 (df = 823) 0.111 (df = 824) 0.125 (df = 820) 0.116 (df = 819) 0.123 (df = 814)
========================================================================================================
Note:                                                                        *p<0.1; **p<0.05; ***p<0.01
</code>```

And my Julia code is

```<code>using FixedEffectModels, CSV, RegressionTables;

test_df = CSV.read("output.csv");

additions = Dict("May" => reg(test_df, @model(May_ret ~ (D*rc~tau*rc))),
    "Jun" => reg(test_df, @model(Jun_ret ~ (D*rc~tau*rc))),
    "Jul" => reg(test_df, @model(Jul_ret ~ (D*rc~tau*rc))),
    "Aug" => reg(test_df, @model(Aug_ret ~ (D*rc~tau*rc))),
    "Sep" => reg(test_df, @model(Sep_ret ~ (D*rc~tau*rc))));
regtable(additions["May"], additions["Jun"], additions["Jul"], additions["Aug"], additions["Sep"]; below_statistic=:tstat, regression_statistics=[:nobs, :r2, :f])
</code>```

Which produces

```<code>------------------------------------------------------------------
               May_ret    Jun_ret    Jul_ret    Aug_ret    Sep_ret
              --------   --------   --------   --------   --------
                   (1)        (2)        (3)        (4)        (5)
------------------------------------------------------------------
(Intercept)      0.008   -0.013**     -0.006     -0.021     -0.004
               (1.580)   (-2.603)   (-1.117)   (-1.673)   (-0.771)
D               -0.004      0.023     -0.032      0.028     -0.027
              (-0.268)    (1.503)   (-1.854)    (1.283)   (-1.627)
rc            0.000***   0.000***   0.000***     -0.000   0.000***
                 (NaN)      (NaN)      (NaN)   (-1.784)      (NaN)
D & rc           0.000     -0.000     0.001*      0.000      0.000
               (0.496)   (-1.372)    (2.198)    (0.706)    (1.189)
------------------------------------------------------------------
Estimator           IV         IV         IV         IV         IV
------------------------------------------------------------------
N                  827        828        824        823        818
R2               0.000      0.008      0.004      0.026      0.004
F                0.200      6.306      9.604      8.526      7.380
------------------------------------------------------------------
</code>```

As can be seen, the main difference is FixedEffectsModels seems to be dropping the rc variable from the regression. I have checked for multicollinearity but it does not seem like it is the problem. Is there a part of my code that I am using wrong?

I am trying to replicate Table 4 of Yen-Cheng Chang, Harrison Hong, Inessa Liskovich, Regression Discontinuity and the Price Effects of Stock Market Indexing, The Review of Financial Studies, Volume 28, Issue 1, January 2015, Pages 212–246, https://doi.org/10.1093/rfs/hhu041

And they provide part of the data. I uploaded the full data here: https://github.com/junder873/data.git

答:
After some work, I figured out my own answer. Julia FixedEffectModels was including the rc variable in both the endogenous and exogenous part of the regression. The correct way to fix this is to basically interact the variables beforehand. This will create the correct output. For example:

```<code>reg(test_df, @model(May_ret ~ rc + (rc_D + D~rc_tau+ tau)))
</code>```

Where rc_D is rc.*D and rc_tau is rc.*tau, basically creating two new columns and adding them manually to the regression instead of letting the model decide which columns to add. This produces the same results.

Body:
When I run (what I think is the same regression) in R and in Julia I get very different results. I think this is because the IV regression is using an indicator variable to instrument for another indicator variable but I can't figure out if I am doing something else wrong.

I have tried several different methods, but the data starts like this:

   rc D tau     May_ret     Jun_ret      Jul_ret     Aug_ret      Sep_ret
1 -43 0   0  0.04529617  0.02106667  0.009868421 0.032573290  0.010473186
2 -19 0   0  0.01973333  0.05752213 -0.020920502 0.027521368 -0.029535865
3  74 1   1  0.33505189  0.04494382 -0.150537640 0.246835440  0.010152284
4  54 1   1  0.03602649  0.06168831  0.030581040 0.002611276 -0.027027028
5  22 1   1 -0.01584158 -0.08417509 -0.088235296 0.012903226  0.100000001
6   7 1   1  0.02484472  0.08000000  0.039548021 0.065217391  0.006122449

D and tau are not perfectly linear, but they are close (and tau is being used to instrument for D).

My R code is

library(AER)
library(stargazer)

temp_df <- read.csv(file="output.csv")

addmay <- ivreg(May_ret ~ D*rc|tau*rc, data=temp_df)
addjun <- ivreg(Jun_ret ~ D*rc|tau*rc, data=temp_df)
addjul <- ivreg(Jul_ret ~ D*rc|tau*rc, data=temp_df)
addaug <- ivreg(Aug_ret ~ D*rc|tau*rc, data=temp_df)
addsep <- ivreg(Sep_ret ~ D*rc|tau*rc, data=temp_df)

stargazer(addmay, addjun, addjul, addaug, addsep, title="Addition Return Effect", align=TRUE, type="text", report="vc*t")

Which produces

========================================================================================================
                                                    Dependent variable:
                    ------------------------------------------------------------------------------------
                        May_ret          Jun_ret          Jul_ret          Aug_ret          Sep_ret
                          (1)              (2)              (3)              (4)              (5)
--------------------------------------------------------------------------------------------------------
D                        0.006            0.033            -0.008           0.028           -0.044*
                       t = 0.304        t = 1.600        t = -0.353       t = 1.283        t = -1.943

rc                      -0.0001          -0.0001          -0.0003          -0.0003*          0.0002
                       t = -0.736       t = -0.730       t = -1.495       t = -1.784       t = 1.094

D:rc                     0.0002          -0.0002          0.001***          0.0002           0.0001
                       t = 0.817        t = -0.747       t = 2.660        t = 0.706        t = 0.392

Constant                 0.0002          -0.021*          -0.024*          -0.021*           0.009
                       t = 0.014        t = -1.778       t = -1.831       t = -1.673       t = 0.654

--------------------------------------------------------------------------------------------------------
Observations              827              828              824              823              818
R2                       0.003            0.007            0.007            0.026            0.012
Adjusted R2             -0.0005           0.004            0.004            0.023            0.009
Residual Std. Error 0.106 (df = 823) 0.111 (df = 824) 0.125 (df = 820) 0.116 (df = 819) 0.123 (df = 814)
========================================================================================================
Note:                                                                        *p<0.1; **p<0.05; ***p<0.01

And my Julia code is

using FixedEffectModels, CSV, RegressionTables;

test_df = CSV.read("output.csv");

additions = Dict("May" => reg(test_df, @model(May_ret ~ (D*rc~tau*rc))),
    "Jun" => reg(test_df, @model(Jun_ret ~ (D*rc~tau*rc))),
    "Jul" => reg(test_df, @model(Jul_ret ~ (D*rc~tau*rc))),
    "Aug" => reg(test_df, @model(Aug_ret ~ (D*rc~tau*rc))),
    "Sep" => reg(test_df, @model(Sep_ret ~ (D*rc~tau*rc))));
regtable(additions["May"], additions["Jun"], additions["Jul"], additions["Aug"], additions["Sep"]; below_statistic=:tstat, regression_statistics=[:nobs, :r2, :f])

Which produces

------------------------------------------------------------------
               May_ret    Jun_ret    Jul_ret    Aug_ret    Sep_ret
              --------   --------   --------   --------   --------
                   (1)        (2)        (3)        (4)        (5)
------------------------------------------------------------------
(Intercept)      0.008   -0.013**     -0.006     -0.021     -0.004
               (1.580)   (-2.603)   (-1.117)   (-1.673)   (-0.771)
D               -0.004      0.023     -0.032      0.028     -0.027
              (-0.268)    (1.503)   (-1.854)    (1.283)   (-1.627)
rc            0.000***   0.000***   0.000***     -0.000   0.000***
                 (NaN)      (NaN)      (NaN)   (-1.784)      (NaN)
D & rc           0.000     -0.000     0.001*      0.000      0.000
               (0.496)   (-1.372)    (2.198)    (0.706)    (1.189)
------------------------------------------------------------------
Estimator           IV         IV         IV         IV         IV
------------------------------------------------------------------
N                  827        828        824        823        818
R2               0.000      0.008      0.004      0.026      0.004
F                0.200      6.306      9.604      8.526      7.380
------------------------------------------------------------------

As can be seen, the main difference is FixedEffectsModels seems to be dropping the rc variable from the regression. I have checked for multicollinearity but it does not seem like it is the problem. Is there a part of my code that I am using wrong?

I am trying to replicate Table 4 of Yen-Cheng Chang, Harrison Hong, Inessa Liskovich, Regression Discontinuity and the Price Effects of Stock Market Indexing, The Review of Financial Studies, Volume 28, Issue 1, January 2015, Pages 212–246, https://doi.org/10.1093/rfs/hhu041

And they provide part of the data. I uploaded the full data here: https://github.com/junder873/data.git

Body:
After some work, I figured out my own answer. Julia FixedEffectModels was including the rc variable in both the endogenous and exogenous part of the regression. The correct way to fix this is to basically interact the variables beforehand. This will create the correct output. For example:

reg(test_df, @model(May_ret ~ rc + (rc_D + D~rc_tau+ tau)))

Where rc_D is rc.*D and rc_tau is rc.*tau, basically creating two new columns and adding them manually to the regression instead of letting the model decide which columns to add. This produces the same results.


问:
I want to update user profile picture in all the posts as well he posted when user updated/Change his profile picture
enter image description here
I am updating user profile picture and it works perfectly in all activities i want. But problem is that it does not update user profile picture in all the posts user already posted. I want to update user's profile picture there as well.

This is database Reference

```<code>postRef= FirebaseDatabase.getInstance().getReference().child("posts");
</code>```

Here is my Recycler view setup

```<code>FirebaseRecyclerOptions<Posts> options=new FirebaseRecyclerOptions.Builder<Posts>()
            .setQuery(postRef,Posts.class)
            .build();

    FirebaseRecyclerAdapter<Posts,PostsViewHolder> firebaseRecyclerAdapter=new FirebaseRecyclerAdapter<Posts, PostsViewHolder>(options)
    {
        @Override
        protected void onBindViewHolder(@NonNull final PostsViewHolder holder, int position, @NonNull final Posts model) {

            final String postKey=getRef(position).getKey();

            holder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent clickPostIntent=new Intent(MainActivity.this, ClickPostActivity.class);
                    clickPostIntent.putExtra("postKey",postKey);
                    startActivity(clickPostIntent);
                }
            });

            holder.username.setText(model.getFullname());
            holder.date.setText(model.getDate());
            holder.time.setText(model.getTime());

            if (model.getPost_uri_link()!=null){
                holder.post_link.setText(model.getPost_uri_link());
            }
            else {
                holder.post_link.setVisibility(View.GONE);
            }
            if (model.getPost_file_name()!=null && model.getPost_file_uri()!=null) {
                holder.file_attach_name.setText(model.getPost_file_name());
                holder.file_attach_name.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        downloadFile(MainActivity.this,model.getPost_file_name(),"gs://studentcornerproject-be4c6.appspot.com/post files",model.getPost_file_uri());
                    }
                });
            }
            else{
                holder.file_attach_name.setVisibility(View.GONE);
            }

            if (model.getDescription()!=null) {
                holder.description.setText(model.getDescription());
           }
            else {
                holder.description.setVisibility(View.GONE);
            }

            if (model.getPost_img()!=null) {
                Picasso.get().load(model.post_img).networkPolicy(NetworkPolicy.OFFLINE).placeholder(android.R.drawable.progress_indeterminate_horizontal).into(holder.post_img, new Callback() {
                    @Override
                    public void onSuccess() {

                        postRef.child("post_img").keepSynced(true);
                    }

                    @Override
                    public void onError(Exception e) {

                        Picasso.get().load(model.post_img).into(holder.post_img);
                    }
                });
            }
            else {
                holder.post_img.setVisibility(View.GONE);
            }
            Picasso.get().load(model.getProfile_image()).networkPolicy(NetworkPolicy.OFFLINE).placeholder(R.drawable.profile_icon).into(holder.prof_img, new Callback() {
                @Override
                public void onSuccess() {

                }

                @Override
                public void onError(Exception e) {

                    Picasso.get().load(model.getProfile_image()).into(holder.prof_img);
                }
            });
        }

        @NonNull
        @Override
        public PostsViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {

            View view= LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.all_posts_users,viewGroup,false);
            PostsViewHolder viewHolder=new PostsViewHolder(view);
            return viewHolder;

        }
    };
    postslist.setAdapter(firebaseRecyclerAdapter);
    firebaseRecyclerAdapter.startListening();
}

public static class PostsViewHolder extends RecyclerView.ViewHolder
{

   TextView username,date,time,description,file_attach_name,post_link;
    CircleImageView prof_img;
    ImageView post_img;

    public PostsViewHolder(@NonNull View itemView) {
        super(itemView);
        post_link=itemView.findViewById(R.id.post_link);
        username=itemView.findViewById(R.id.post_user_name);
        date=itemView.findViewById(R.id.post_date);
        time=itemView.findViewById(R.id.post_time);
        description=itemView.findViewById(R.id.post_description);
        file_attach_name=itemView.findViewById(R.id.post_filename);
        prof_img=itemView.findViewById(R.id.post_profile_img);
        post_img=itemView.findViewById(R.id.post_image);

    }
</code>```

I want to update profile picture in all the posts he already posted as well.

答:
My problem has been solved. here is the correct code.</p>

```<code> Query postQuery=postRef.orderByChild("uid").equalTo(currentUserId);
        postQuery.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                for (DataSnapshot snapshot:dataSnapshot.getChildren()){
                    Log.i("Post",snapshot.getKey());
                    postRef.child(snapshot.getKey()).child("profile_image").setValue(profile_img);
                    postRef.child(snapshot.getKey()).child("fullname").setValue(fullname);

                }
            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {

            }
        });
</code>```

Body:
enter image description here
I am updating user profile picture and it works perfectly in all activities i want. But problem is that it does not update user profile picture in all the posts user already posted. I want to update user's profile picture there as well.

This is database Reference

postRef= FirebaseDatabase.getInstance().getReference().child("posts");

Here is my Recycler view setup

FirebaseRecyclerOptions<Posts> options=new FirebaseRecyclerOptions.Builder<Posts>()
            .setQuery(postRef,Posts.class)
            .build();

    FirebaseRecyclerAdapter<Posts,PostsViewHolder> firebaseRecyclerAdapter=new FirebaseRecyclerAdapter<Posts, PostsViewHolder>(options)
    {
        @Override
        protected void onBindViewHolder(@NonNull final PostsViewHolder holder, int position, @NonNull final Posts model) {

            final String postKey=getRef(position).getKey();

            holder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent clickPostIntent=new Intent(MainActivity.this, ClickPostActivity.class);
                    clickPostIntent.putExtra("postKey",postKey);
                    startActivity(clickPostIntent);
                }
            });

            holder.username.setText(model.getFullname());
            holder.date.setText(model.getDate());
            holder.time.setText(model.getTime());

            if (model.getPost_uri_link()!=null){
                holder.post_link.setText(model.getPost_uri_link());
            }
            else {
                holder.post_link.setVisibility(View.GONE);
            }
            if (model.getPost_file_name()!=null && model.getPost_file_uri()!=null) {
                holder.file_attach_name.setText(model.getPost_file_name());
                holder.file_attach_name.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        downloadFile(MainActivity.this,model.getPost_file_name(),"gs://studentcornerproject-be4c6.appspot.com/post files",model.getPost_file_uri());
                    }
                });
            }
            else{
                holder.file_attach_name.setVisibility(View.GONE);
            }

            if (model.getDescription()!=null) {
                holder.description.setText(model.getDescription());
           }
            else {
                holder.description.setVisibility(View.GONE);
            }

            if (model.getPost_img()!=null) {
                Picasso.get().load(model.post_img).networkPolicy(NetworkPolicy.OFFLINE).placeholder(android.R.drawable.progress_indeterminate_horizontal).into(holder.post_img, new Callback() {
                    @Override
                    public void onSuccess() {

                        postRef.child("post_img").keepSynced(true);
                    }

                    @Override
                    public void onError(Exception e) {

                        Picasso.get().load(model.post_img).into(holder.post_img);
                    }
                });
            }
            else {
                holder.post_img.setVisibility(View.GONE);
            }
            Picasso.get().load(model.getProfile_image()).networkPolicy(NetworkPolicy.OFFLINE).placeholder(R.drawable.profile_icon).into(holder.prof_img, new Callback() {
                @Override
                public void onSuccess() {

                }

                @Override
                public void onError(Exception e) {

                    Picasso.get().load(model.getProfile_image()).into(holder.prof_img);
                }
            });
        }

        @NonNull
        @Override
        public PostsViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {

            View view= LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.all_posts_users,viewGroup,false);
            PostsViewHolder viewHolder=new PostsViewHolder(view);
            return viewHolder;

        }
    };
    postslist.setAdapter(firebaseRecyclerAdapter);
    firebaseRecyclerAdapter.startListening();
}

public static class PostsViewHolder extends RecyclerView.ViewHolder
{

   TextView username,date,time,description,file_attach_name,post_link;
    CircleImageView prof_img;
    ImageView post_img;

    public PostsViewHolder(@NonNull View itemView) {
        super(itemView);
        post_link=itemView.findViewById(R.id.post_link);
        username=itemView.findViewById(R.id.post_user_name);
        date=itemView.findViewById(R.id.post_date);
        time=itemView.findViewById(R.id.post_time);
        description=itemView.findViewById(R.id.post_description);
        file_attach_name=itemView.findViewById(R.id.post_filename);
        prof_img=itemView.findViewById(R.id.post_profile_img);
        post_img=itemView.findViewById(R.id.post_image);

    }

I want to update profile picture in all the posts he already posted as well.

Body:
My problem has been solved. here is the correct code.

 Query postQuery=postRef.orderByChild("uid").equalTo(currentUserId);
        postQuery.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                for (DataSnapshot snapshot:dataSnapshot.getChildren()){
                    Log.i("Post",snapshot.getKey());
                    postRef.child(snapshot.getKey()).child("profile_image").setValue(profile_img);
                    postRef.child(snapshot.getKey()).child("fullname").setValue(fullname);

                }
            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {

            }
        });


问:
How to extract hour part of timestamp to a new column in DataFrame Spark
I want to extract the hour from current timestamp column  and store the hour value in a new column in the data frame. Please do help</p>

Body:
Hope this will help

val df = Seq((" Virat ",18,"RCB"),("Rohit ",45,"MI "),(" DK",67,"KKR ")).toDF("captains","jersey_number","teams")

scala> df.show

+--------+-------------+-----+
|captains|jersey_number|teams|
+--------+-------------+-----+
|  Virat |           18|  RCB|
|  Rohit |           45|  MI |
|      DK|           67| KKR |
+--------+-------------+-----+

scala>val trimmedDF = df.withColumn("captains",trim(df("captains"))).withColumn("teams",trim(df("teams")))

scala> trimmedDF.show

+--------+-------------+-----+
|captains|jersey_number|teams|
+--------+-------------+-----+
|   Virat|           18|  RCB|
|   Rohit|           45|   MI|
|      DK|           67|  KKR|
+--------+-------------+-----+


问:
How to access to a file in docker container already exit?
I create a file hello.txt:

```<code>docker run centos6-ssh echo "hello world" > /root/hello.txt
</code>```

docker will create a container,excecute the command,and the container exit.
probblem is that how do i access the file?

in case of container exit,the right way to use container is run a container with ssh service background(-d args)?

答:
```<code>docker container ls -a
</code>```

to list starting and exited containers, and select a $containerId,

then

```<code>docker container export -o myContainerFileSystem.tar $containerId
</code>```

to extract the filesystem as tar file

ContentLicense: CC BY-SA 3.0

Body:
I create a file hello.txt:

docker run centos6-ssh echo "hello world" > /root/hello.txt

docker will create a container,excecute the command,and the container exit.
probblem is that how do i access the file?

in case of container exit,the right way to use container is run a container with ssh service background(-d args)?

Body:
docker container ls -a

to list starting and exited containers, and select a $containerId,

then

docker container export -o myContainerFileSystem.tar $containerId

to extract the filesystem as tar file


问:
d3 transition for transform translate not working for DIV
Why is the transform property not working for DIV in D3?
It works for any svg elements, but not for "div". Any alternate solution?

NOT WORKING

```<code>d3.select("div")
  .transition()
  .style("transform","translate(0px,-500px)");
</code>```

WORKING

```<code>d3.select("circle")
  .transition()
  .style("transform","translate(0px,-500px)");
</code>```

答:
just

```<code>d3.select('div')
 .style('transition-duration', '.5s')
 .style('transform', 'translate(0px, -500px)');
</code>```

not

```<code>d3.select('div')
  .transition()
  .duration(500)
  .style('transform', 'translate(0px, -500px)');
</code>```

use transition-duration when you are dealing not-svg element

It doing very well !

Body:
Why is the transform property not working for DIV in D3?
It works for any svg elements, but not for "div". Any alternate solution?

NOT WORKING

d3.select("div")
  .transition()
  .style("transform","translate(0px,-500px)");

WORKING

d3.select("circle")
  .transition()
  .style("transform","translate(0px,-500px)");

Body:
just

d3.select('div')
 .style('transition-duration', '.5s')
 .style('transform', 'translate(0px, -500px)');

not

d3.select('div')
  .transition()
  .duration(500)
  .style('transform', 'translate(0px, -500px)');

use transition-duration when you are dealing not-svg element

It doing very well !


问:
Wrong value returned when converting from raw character to hex equivalent
I have an application where the input is a raw set of bytes and I want to see the two-digit hex code of each of those bytes. For now I'm trying to get the proper hex code for one byte. This is my code:

```<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(){
char hexvc; //= ascii code for hex value
char aval[2]={0xFF,0x00}; //Our raw 1 byte data. can't print actual code here
char hexv[20]; //value for output
memset(hexv,0,19); //clear output
hexvc=strtol(aval,NULL,16) & 0xFF;
if (hexvc != '\0'){
    sprintf(hexv,"%02hx",hexvc);
}else{
    //hexvc always equals 0. why not FFh?
    strcpy(hexv,"00");
}
printf("%s\n",hexv);
return 0;
}
</code>```

I expected to see ff appear on the screen, but instead I see 00.
How do I fix this?

And if I change 0xFF after aval[2]= to 0x31 or '1' (since 1 is the actual value for ascii code 0x31) then I want to see 31 appear on the screen.

答:
aval[2]={0xFF,0x00};

This is not ascii.

aval[]={'f', 'f',0x00};

Or

aval[]="ff";

And try again

Body:
I have an application where the input is a raw set of bytes and I want to see the two-digit hex code of each of those bytes. For now I'm trying to get the proper hex code for one byte. This is my code:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(){
char hexvc; //= ascii code for hex value
char aval[2]={0xFF,0x00}; //Our raw 1 byte data. can't print actual code here
char hexv[20]; //value for output
memset(hexv,0,19); //clear output
hexvc=strtol(aval,NULL,16) & 0xFF;
if (hexvc != '\0'){
    sprintf(hexv,"%02hx",hexvc);
}else{
    //hexvc always equals 0. why not FFh?
    strcpy(hexv,"00");
}
printf("%s\n",hexv);
return 0;
}

I expected to see ff appear on the screen, but instead I see 00.
How do I fix this?

And if I change 0xFF after aval[2]= to 0x31 or '1' (since 1 is the actual value for ascii code 0x31) then I want to see 31 appear on the screen.


问:
Using Python to read .CSV files and then compare the columns/rows
I am currently trying to develop a program that reads data from a text file, and returns the pair of employees that has worked the most time together. I decided to it in a .CSV format, as that is still a plain text format, but seperated with comas.

Example:

```<code>EmpID,ProjectID,DateFrom,DateTo
1,A,2014-11-01,2015-05-01
2,B,2013-12-06,2014-10-06
2,C,2014-01-07,2016-03-07
3,B,2015-06-04,2017-09-04
5,C,2014-10-01,2015-12-01
1,A,2013-03-07,2015-11-07
2,C,2015-07-09,2019-01-19
3,B,2013-11-13,2014-03-13
4,C,2016-02-14,NULL
5,D,2014-03-15,2015-11-09
</code>```

Now, I learned how to read .CSV files, but I am not sure on what is the best way for the thing after (the comparing of values, etc). For now, I decided that this is the cleanest option:

```<code>import csv

with open('data.csv', 'r') as f:
  reader = csv.reader(f)
  your_list = list(reader)

print(your_list)
</code>```

I just want a piece of advice, if the best way to go would be with comparing indexes of the list. I was also thinking about dictionaries, but I am not sure, hence the reason I am asking here :) And SQL is not an option, even though it would be so easy with it. Sorry if this is a bad question, but I am currently learning Python and this is quite an important task for me. Thanks!

答:
You can use datetime package to check total time elapsed. Create a list of people in the csv file, then sort the list based on the elapsed time. for the first 8 rows of csv file (because NULL is undefined!):

```<code>1,A,2014-11-01,2015-05-01
2,B,2013-12-06,2014-10-06
2,C,2014-01-07,2016-03-07
3,B,2015-06-04,2017-09-04
5,C,2014-10-01,2015-12-01
1,A,2013-03-07,2015-11-07
</code>```

You can use this:

```<code>from datetime import datetime
with open('file.txt', 'r') as file:
    my_list = list()
    for line in file:
        list_ = line.split(',')
        dt1 = datetime.strptime(list_[2], '%Y-%M-%d')
        dt2 = datetime.strptime(list_[3][:10], '%Y-%M-%d')
        my_list.append(list_[:2] + [dt2-dt1])
        my_list.sort(key=lambda x: x[2])
print(my_list)
</code>```

output:

```<code>[['3', 'B', datetime.timedelta(days=364, seconds=85920)], ['1', 'A', datetime.timedelta(days=364, seconds=86040)], ['2', 'B', datetime.timedelta(days=364, seconds=86280)], ['5', 'C', datetime.timedelta(days=365, seconds=120)], ['2', 'C', datetime.timedelta(days=730, seconds=120)], ['1', 'A', datetime.timedelta(days=730, seconds=480)], ['3', 'B', datetime.timedelta(days=731, seconds=180)], ['2', 'C', datetime.timedelta(days=1470, seconds=86040)]]
</code>```

Body:
I am currently trying to develop a program that reads data from a text file, and returns the pair of employees that has worked the most time together. I decided to it in a .CSV format, as that is still a plain text format, but seperated with comas.

Example:

EmpID,ProjectID,DateFrom,DateTo
1,A,2014-11-01,2015-05-01
2,B,2013-12-06,2014-10-06
2,C,2014-01-07,2016-03-07
3,B,2015-06-04,2017-09-04
5,C,2014-10-01,2015-12-01
1,A,2013-03-07,2015-11-07
2,C,2015-07-09,2019-01-19
3,B,2013-11-13,2014-03-13
4,C,2016-02-14,NULL
5,D,2014-03-15,2015-11-09

Now, I learned how to read .CSV files, but I am not sure on what is the best way for the thing after (the comparing of values, etc). For now, I decided that this is the cleanest option:

import csv

with open('data.csv', 'r') as f:
  reader = csv.reader(f)
  your_list = list(reader)

print(your_list)

I just want a piece of advice, if the best way to go would be with comparing indexes of the list. I was also thinking about dictionaries, but I am not sure, hence the reason I am asking here :) And SQL is not an option, even though it would be so easy with it. Sorry if this is a bad question, but I am currently learning Python and this is quite an important task for me. Thanks!

Body:
You can use datetime package to check total time elapsed. Create a list of people in the csv file, then sort the list based on the elapsed time. for the first 8 rows of csv file (because NULL is undefined!):

1,A,2014-11-01,2015-05-01
2,B,2013-12-06,2014-10-06
2,C,2014-01-07,2016-03-07
3,B,2015-06-04,2017-09-04
5,C,2014-10-01,2015-12-01
1,A,2013-03-07,2015-11-07

You can use this:

from datetime import datetime
with open('file.txt', 'r') as file:
    my_list = list()
    for line in file:
        list_ = line.split(',')
        dt1 = datetime.strptime(list_[2], '%Y-%M-%d')
        dt2 = datetime.strptime(list_[3][:10], '%Y-%M-%d')
        my_list.append(list_[:2] + [dt2-dt1])
        my_list.sort(key=lambda x: x[2])
print(my_list)

output:

[['3', 'B', datetime.timedelta(days=364, seconds=85920)], ['1', 'A', datetime.timedelta(days=364, seconds=86040)], ['2', 'B', datetime.timedelta(days=364, seconds=86280)], ['5', 'C', datetime.timedelta(days=365, seconds=120)], ['2', 'C', datetime.timedelta(days=730, seconds=120)], ['1', 'A', datetime.timedelta(days=730, seconds=480)], ['3', 'B', datetime.timedelta(days=731, seconds=180)], ['2', 'C', datetime.timedelta(days=1470, seconds=86040)]]


问:
tableView.reloadData() adds a UIView that it should not do
I a have a modal with optional properties. And as you may have guessed, I only add a UIView for non-optional properties. In the following code, dueDate is optional. The first one has due-date and the second does not.

```<code>let london = Task( name: "Hello from London",
                     createdDate: Date(),
                     isCompleted: false,
                     dueDate: Date())

let madrid = Task( name: "hola desde madrid",
                     createdDate: Date(),
                     isCompleted: false)
</code>```

Data source method that inserts cells.

```<code>func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: TableViewCell.identifier, for: indexPath) as! TableViewCell

    if  let _ = tasks[indexPath.row].dueDate {
        cell.textLabel?.text = "Due Date"
    }

    return cell
}
</code>```

When I open the app, it works as I expect.  Only the first cell has Due Date. I expect it so since it is only the first task that has due-date.  However, when I remove the first cell(see code below) and reload date, Due Date is added in the second cell too. I do not understand it. I expect that it should not be added since the second task does not have due-date

Delegate method that removes cells

```<code>func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
    let remove = UITableViewRowAction(style: .normal, title: "Remove") { action, index in
        let task =  self.tasks.remove(at: indexPath.row)
        print(task.name) //
        tableView.reloadData()
    }
    remove.backgroundColor = .red

    return [remove]
}
</code>```

What I do wrong? How can I fix this issue?

If you need more info, please just ask.

答:
Look at your cellForRow:

```<code>func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: TableViewCell.identifier, for: indexPath) as! TableViewCell

    if let _ = tasks[indexPath.row].dueDate {
        cell.textLabel?.text = "London"
    }

    return cell
}
</code>```

Now, when you remove a cell, you call reloadData on a cell that previously had a due date, but now does not. Since the if doesn't get executed, you're not doing anything with the cell. Add an else case.

```<code>func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: TableViewCell.identifier, for: indexPath) as! TableViewCell

    if let _ = tasks[indexPath.row].dueDate {
        cell.textLabel?.text = "London"
    }
    else {
        cell.textLabel?.text = nil
    }

    return cell
}
</code>```

Body:
I a have a modal with optional properties. And as you may have guessed, I only add a UIView for non-optional properties. In the following code, dueDate is optional. The first one has due-date and the second does not.

let london = Task( name: "Hello from London",
                     createdDate: Date(),
                     isCompleted: false,
                     dueDate: Date())

let madrid = Task( name: "hola desde madrid",
                     createdDate: Date(),
                     isCompleted: false)

Data source method that inserts cells.

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: TableViewCell.identifier, for: indexPath) as! TableViewCell

    if  let _ = tasks[indexPath.row].dueDate {
        cell.textLabel?.text = "Due Date"
    }

    return cell
}

When I open the app, it works as I expect.  Only the first cell has Due Date. I expect it so since it is only the first task that has due-date.  However, when I remove the first cell(see code below) and reload date, Due Date is added in the second cell too. I do not understand it. I expect that it should not be added since the second task does not have due-date

Delegate method that removes cells

func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
    let remove = UITableViewRowAction(style: .normal, title: "Remove") { action, index in
        let task =  self.tasks.remove(at: indexPath.row)
        print(task.name) //
        tableView.reloadData()
    }
    remove.backgroundColor = .red

    return [remove]
}

What I do wrong? How can I fix this issue?

If you need more info, please just ask.

Body:
Look at your cellForRow:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: TableViewCell.identifier, for: indexPath) as! TableViewCell

    if let _ = tasks[indexPath.row].dueDate {
        cell.textLabel?.text = "London"
    }

    return cell
}

Now, when you remove a cell, you call reloadData on a cell that previously had a due date, but now does not. Since the if doesn't get executed, you're not doing anything with the cell. Add an else case.

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: TableViewCell.identifier, for: indexPath) as! TableViewCell

    if let _ = tasks[indexPath.row].dueDate {
        cell.textLabel?.text = "London"
    }
    else {
        cell.textLabel?.text = nil
    }

    return cell
}


问:
I need a simple java example of processing a JSON response via HTTP for Android App?
I am writing a simple Android app and have a database that will send back information into the app. I am new to Android and am looking for a simple example that demonstrates how the Android App can process a JSON response received from a HTTP request.

I need to see what classes are used for Android apps to process a HTTP response. A reference to a good tutorial, or if you're keen, write a very basic method to do the job. Thanks

答: I once wrote a tutorial for the exact opposite case (to send a JSON request). However from that you will be able to derive for what you need.</p>

ContentLicense: CC BY-SA 2.5


问:
Cloud Run Memory Restriction
How do I get a Cloud Run container that uses more than 2 GB run on custom GKE cluster?

Since Cloud Run uses knative, I wonder if it is possible to tweak deployment describtor with more allocated/allowed memory limit to run it on GKE.

```<code>apiVersion: serving.knative.dev/v1alpha1
kind: Revision
metadata:
 ...
</code>```

答:
As you said, when you are using Cloud Run on GKE, you're using Knative serving stack, which allows you to configure custom CPU and memory requests/limits just like Kubernetes: https://kubernetes.io/docs/concepts/configuration/manage-compute-resources-container/

For example, to get 4 GiB memory, you must add a field like:

```<code>resources:
  limits:
    memory: "4GiB"
</code>```

to your container: field in Knative Service spec.

In Knative 0.6 (serving v1beta1) this field's path would be Service.spec.template.spec.containers[*].resources field, in earlier versions (serving v1alpha1) something like Service.spec.runLatest.revisionTemplate.spec.container.resources.

Title: Cloud Run Memory Restriction

Body:
How do I get a Cloud Run container that uses more than 2 GB run on custom GKE cluster?

Since Cloud Run uses knative, I wonder if it is possible to tweak deployment describtor with more allocated/allowed memory limit to run it on GKE.

apiVersion: serving.knative.dev/v1alpha1
kind: Revision
metadata:
 ...

Body:
As you said, when you are using Cloud Run on GKE, you're using Knative serving stack, which allows you to configure custom CPU and memory requests/limits just like Kubernetes: https://kubernetes.io/docs/concepts/configuration/manage-compute-resources-container/

For example, to get 4 GiB memory, you must add a field like:

resources:
  limits:
    memory: "4GiB"

to your container: field in Knative Service spec.

In Knative 0.6 (serving v1beta1) this field's path would be Service.spec.template.spec.containers[*].resources field, in earlier versions (serving v1alpha1) something like Service.spec.runLatest.revisionTemplate.spec.container.resources.


问:
XCTest UI Testing - How to close and open an app without relaunch?
I want to make my app to go to background, and then comeback to the foreground.

To make an app to go background: XCUIDevice.shared().press(XCUIDeviceButton.home)

To terminate an app(force tap): XCUIApplication().terminate()

To launch the app: XCUIApplication().launch()

Problem: when I try to close and open the app, the launch() method clears the app from background and it opens the app freshly.

I saw this comment regarding this. But cant able to figure out it in UI test. I'm using Swift. Help needed!!

答:
A similar question was asked and answered here
Possible to bring the app from background to foreground?

This is what I have in my XCUITest and it works like a charm (xcode 10.1 and test device is iPhone X 11.0)

```<code>func testWhatever() {

// You test steps go here until you need the background foreground to run
// To background the app
XCUIDevice.shared.press(XCUIDevice.Button.home)
// To bring the app back
XCUIApplication().activate()

// You test continues after background foreground has been done. }
</code>```

Body:
A similar question was asked and answered here
Possible to bring the app from background to foreground?

This is what I have in my XCUITest and it works like a charm (xcode 10.1 and test device is iPhone X 11.0)

func testWhatever() {

// You test steps go here until you need the background foreground to run
// To background the app
XCUIDevice.shared.press(XCUIDevice.Button.home)
// To bring the app back
XCUIApplication().activate()

// You test continues after background foreground has been done. }


问:
Cleaning dupes and keeping max data
I have a table that contains duplicates and I need to keep the max data and blow away the rest. Due to requirements I cannot change the date field format and I am getting a conversion error. Any ideas?

```<code>DELETE from MAIN_TBL
WHERE ID NOT IN
(
select * from
(SELECT MAX(updated_on)
FROM MAIN_TBL
GROUP BY widget_tag, ID) as TEMP
)
</code>```

ERROR = Conversion failed when converting date and/or time from character string.

答:
If you want to delete everything except newest rows per widget_tag you could use:</p>

```<code>WITH cte AS (
  SELECT *, ROW_NUMBER() OVER(PARITITION BY widget_tag ORDER BY updated_on DESC) rn
  FROM MAIN_TBL
)
DELETE FROM cte WHERE rn <> 1;
</code>```

Title: Cleaning dupes and keeping max data

Body:
I have a table that contains duplicates and I need to keep the max data and blow away the rest. Due to requirements I cannot change the date field format and I am getting a conversion error. Any ideas?

DELETE from MAIN_TBL
WHERE ID NOT IN
(
select * from
(SELECT MAX(updated_on)
FROM MAIN_TBL
GROUP BY widget_tag, ID) as TEMP
)

ERROR = Conversion failed when converting date and/or time from character string.

Body:
If you want to delete everything except newest rows per widget_tag you could use:

WITH cte AS (
  SELECT *, ROW_NUMBER() OVER(PARITITION BY widget_tag ORDER BY updated_on DESC) rn
  FROM MAIN_TBL
)
DELETE FROM cte WHERE rn <> 1;