问:
OnOptionsItemSelected for action 1 not showing new alert dialog
On my onOptionsItemSelected method when the user taps action settings 1, my new alert dialog does not show?

```<code>package com.karanvir.search;

import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import static com.karanvir.search.MainActivity.urlGlobal;

public class Main2Activity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        //finding webview
        WebView webView=(WebView) findViewById(R.id.web1);

//whole bunch of settings you might want to do if you .
        //do this because javascript is so wildely used that if you dont use this anywebsites you display wont be displayed properly
        webView.getSettings().setJavaScriptEnabled(true);
        //this is because on a number of phones if you dont do this it will jump to the devices default browser, and ddisplay the websview their instead.
        webView.setWebViewClient(new WebViewClient());
        webView.loadUrl("https://www.google.ca/?gws_rd=ssl#q="+urlGlobal);
        //reminder ask permission
        //you can load content using loaddata
        //then add type of data
        //then add character encoded were using

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings4) {
            Intent intentGoogle= new Intent(getApplicationContext(),Main2Activity.class);
            startActivity(intentGoogle);

            return true;
        } else if(id ==R.id.action_settings2){
            Intent intentGoogle= new Intent(getApplicationContext(),Yahoo.class);
            startActivity(intentGoogle);

            return true;

        }else if (id==R.id.action_settings3){
            Intent intentGoogle= new Intent(getApplicationContext(),MainActivity.class);
            startActivity(intentGoogle);

            return true;

        }else if(id==R.id.action_settings1){
            new AlertDialog.Builder(getApplicationContext())
                    .setIcon(android.R.drawable.ic_dialog_info)
                    .setTitle("About")
                    .setMessage("This app interchanges between different search engines, to help guess what your looking for. We dont not acess your location, also we do not save any information. Right now we are working on a way to make the app completely private in congnito.Email us if you want to help with this project also. Please email Dhillonapps93@gmail.com for help/inquries. We run this app with no ads, we also accept donations at runescapegold1291@hotmail.com. Yes I used to play runescape lol. Thanks for reading and enjoy");
            return true;

        }

        return super.onOptionsItemSelected(item);
    }

 }
</code>```

答:
you have to just write alertDialog.show(); to show the dialoge...... sample is given below</p>

```<code>AlertDialog.Builder alertDialog = new AlertDialog.Builder(
            getActivity());
    // Setting Dialog Title
    alertDialog.setTitle("Title is here");

    // Setting Dialog Message
    alertDialog.setMessage("Message is here");

    // On pressing ok button
    alertDialog.setPositiveButton("Ok",
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                     //do whatever you want

                    dialog.cancel(); //it cancel the alertdialog
                }
            });
            //on pressing cancel button
    alertDialog.setNegativeButton("Cancel",
        new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                    //do whatever you want

                    dialog.cancel(); //it cancel the alertdialog
                }
            });
            // Showing Alert Message
    alertDialog.show();
    alertDialog.setCancelable(false);
</code>```

Body:
On my onOptionsItemSelected method when the user taps action settings 1, my new alert dialog does not show?

package com.karanvir.search;

import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import static com.karanvir.search.MainActivity.urlGlobal;

public class Main2Activity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        //finding webview
        WebView webView=(WebView) findViewById(R.id.web1);

//whole bunch of settings you might want to do if you .
        //do this because javascript is so wildely used that if you dont use this anywebsites you display wont be displayed properly
        webView.getSettings().setJavaScriptEnabled(true);
        //this is because on a number of phones if you dont do this it will jump to the devices default browser, and ddisplay the websview their instead.
        webView.setWebViewClient(new WebViewClient());
        webView.loadUrl("https://www.google.ca/?gws_rd=ssl#q="+urlGlobal);
        //reminder ask permission
        //you can load content using loaddata
        //then add type of data
        //then add character encoded were using

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings4) {
            Intent intentGoogle= new Intent(getApplicationContext(),Main2Activity.class);
            startActivity(intentGoogle);

            return true;
        } else if(id ==R.id.action_settings2){
            Intent intentGoogle= new Intent(getApplicationContext(),Yahoo.class);
            startActivity(intentGoogle);

            return true;

        }else if (id==R.id.action_settings3){
            Intent intentGoogle= new Intent(getApplicationContext(),MainActivity.class);
            startActivity(intentGoogle);

            return true;

        }else if(id==R.id.action_settings1){
            new AlertDialog.Builder(getApplicationContext())
                    .setIcon(android.R.drawable.ic_dialog_info)
                    .setTitle("About")
                    .setMessage("This app interchanges between different search engines, to help guess what your looking for. We dont not acess your location, also we do not save any information. Right now we are working on a way to make the app completely private in congnito.Email us if you want to help with this project also. Please email Dhillonapps93@gmail.com for help/inquries. We run this app with no ads, we also accept donations at runescapegold1291@hotmail.com. Yes I used to play runescape lol. Thanks for reading and enjoy");
            return true;

        }

        return super.onOptionsItemSelected(item);
    }

 }

Body:
you have to just write alertDialog.show(); to show the dialoge...... sample is given below

AlertDialog.Builder alertDialog = new AlertDialog.Builder(
            getActivity());
    // Setting Dialog Title
    alertDialog.setTitle("Title is here");

    // Setting Dialog Message
    alertDialog.setMessage("Message is here");

    // On pressing ok button
    alertDialog.setPositiveButton("Ok",
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                     //do whatever you want

                    dialog.cancel(); //it cancel the alertdialog
                }
            });
            //on pressing cancel button
    alertDialog.setNegativeButton("Cancel",
        new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                    //do whatever you want

                    dialog.cancel(); //it cancel the alertdialog
                }
            });
            // Showing Alert Message
    alertDialog.show();
    alertDialog.setCancelable(false);


来源: stackexchange

问:
Gradle DSL method not found : testCompile()
I am using gradle version - 3.3-all and gradle plugin - gradle:2.3.3
I want to write test cases. So as per this page, I included the following in the the app's top build.gradle file.

```<code>        testCompile 'junit:junit:4.12'
        testCompile 'org.mockito:mockito-core:1.10.19'
</code>```

But I get the error saying

```<code>Error:(11, 0) Gradle DSL method not found: 'testCompile()'
Possible causes:<ul><li>The project 'TopLevelProject' may be using a version of the Android Gradle plug-in that does not contain the method (e.g. 'testCompile' was added in 1.1.0).
</code>```

What could be the issue?

答:
In gradle the configurations: compile runtime testCompile etc are coming from java plugin

But in android i think you need apply plugin: 'com.android.application'

Edit: Please share your root build.gradle and app build.gradle especially android closure, dependencies and plugins and describe which is where.

Sometimes is a structural problem and app related stuff lands in root build.gradle

ContentLicense: CC BY-SA 3.0

Body:
I am using gradle version - 3.3-all and gradle plugin - gradle:2.3.3
I want to write test cases. So as per this page, I included the following in the the app's top build.gradle file.

        testCompile 'junit:junit:4.12'
        testCompile 'org.mockito:mockito-core:1.10.19'

But I get the error saying

Error:(11, 0) Gradle DSL method not found: 'testCompile()'
Possible causes:

The project 'TopLevelProject' may be using a version of the Android Gradle plug-in that does not contain the method (e.g. 'testCompile' was added in 1.1.0).

What could be the issue?


问:
Counting the selected/checked boxes [EXCEL]
One of the columns (MONTHS), let's say column A in my raw data contains numbers ranging from 0-12. Now, in another sheet, I'd like to be able to count the number of observations with the selected / checked months as shown below:

How can I do that? I tried doing it with countifs but hit a snag because column A is numeric and when a user checks a box in the other sheet, it only evaluates to "TRUE". Any ideas? Thank you!

EDIT:

The column of MONTHS LOOKS LIKE THE FOLLOWING:

答:
Using SUMPRODUCT will work for sure.

A solution is using an array formula as follows:
Let Sheet1, that has TRUE or FALSE in one column (let's say Sheet1!A1:A12. Then, there's some values from 1 to 12 in Sheet1!B1:B12)
Now you want to count the amount of numbers in say Sheet2!F:F that have the Sheet1 column A set to true.

The formula to do that would be:
=SUM(COUNTIF(Sheet2!F:F,IF(Sheet1!A1:A12,Sheet1!B1:B12)))

Remember to press CTRL + SHIFT + ENTER since it's an array formula.


问:
I am having a difficulty with first time react-native run-android. The Error looks like this following

FAILURE: Build failed with an exception.

What went wrong:
     A problem occurred

configuring project ':app'.
        Failed to notify project evaluation listener.
          javax/xml/bind/annotation/XmlSchema

答:
FIX:

Make sure that java is installed on your system. Or install using linux command:

$sudo apt-get install openjdk-8-jdk

Set JAVA_HOME environment variable.
For linux

JAVA_HOME="/usr/lib/jvm/java-1.8.0-openjdk-amd64"

to /etc/environment file new line.

Make sure Android/Sdk is included in your home directory.(i.e. Assuming you have installed android-studio).

Export ANDROID_HOME in ~/.bashrc file.

export ANDROID_HOME="$HOME/Android/Sdk"
export PATH="$PATH:$ANDROID_HOME/tools"
export PATH="$PATH:$ANDROID_HOME/platform-tools"
source /etc/environment

Last tip: if you get watchman error everytime you close(ctrl+c) and open the JS server. run the following command.

echo 999999 | sudo tee -a /proc/sys/fs/inotify/max_user_watches && echo 999999 | sudo tee -a /proc/sys/fs/inotify/max_queued_events && echo 999999 | sudo tee -a /proc/sys/fs/inotify/max_user_instances && watchman shutdown-server


问:
Neo4j Session.query() - How to map query response to Custom Java Object

I have a Node Entity:

```<code>@NodeEntity(label = CollectionNames.CONSUMER)
public class Consumer extends AbstractNode{

    //Properties, removed just for simplicity

    @Relationship(type = RelationshipNames.HAS_CONTACT, direction = Relationship.OUTGOING)
    private Set<HasContact> contactList;

//Constructor & Getters, Setters
}
</code>```

For Storing custom query results:

```<code>@QueryResult
public class CustomQueryResult {

    private AbstractNode node;
    private List<? extends AbstractRelationship> relationships;

    public CustomQueryResult(AbstractNode node, List<? extends AbstractRelationship> relationships){
        this.node = node;
        this.relationships = relationships;
    }

//Default Constructor, Getters & Setters
}
</code>```

Repository Implementation

```<code>String query = String.format(
                "MATCH (startNode:Consumer {mobileNumber : {mob}})-[rel:%s *%d..%d]->(endNode:%s) RETURN startNode as node, rel as relationships",
                relationshipName, 0, depth, endNode);
        Map<String, Object> params = new HashMap<>();
        params.put("mob", mobileNo);
        CustomQueryResult consumer =  session.queryForObject(CustomQueryResult.class, query, params);
</code>```

Although given Query load required data, but unfortunately its unable to map it to given Object(CustomQueryResult). But in case if I map it to Consumer then it show given error:

java.lang.RuntimeException: Result not of expected size. Expected 1
  row but found 6

While this same query is working fine, if I use Spring Data Neo4j Repository like

```<code>@Query("MATCH (startNode:Consumer {mobileNumber : {0}})-[rel:HAS_CONTACT *..1]->(endNode:Consumer) RETURN startNode as node, rel as relationships")
    CustomQueryResult findByMobileNumberAndRelationship(String mobileNo);
</code>```

So how can I map given query result into Consumer or CustomQueryResult object directly?

Or is that possible to do the same thing using Spring Data Neo4j Repository with dynamic Relationship names and depth like:

```<code>@Query("MATCH (startNode:Consumer {mobileNumber : {0}})-[rel:{1} *..{2}]->(endNode:Consumer) RETURN startNode as node, rel as relationships")
    CustomQueryResult findByMobileNumberAndRelationship(String mobileNo, String relationshipName, @Depth int depth);
</code>```

Although I am sure that above code is not working.

答:
Your query returns multiple rows

```<code>MATCH (startNode:Consumer {mobileNumber : {0}})-[rel:HAS_CONTACT *..1]->(endNode:Consumer)
RETURN startNode as node, rel as relationships
</code>```

where node is repeated for each rel. The repository infrastructure is able to handle that, but queryForObject is not - it expects single row.

It should work if you modify your query in following way so it returns only 1 row:

```<code>MATCH (startNode:Consumer {mobileNumber : {0}})-[rel:HAS_CONTACT *..1]->(endNode:Consumer)
RETURN startNode as node, COLLECT(rel) as relationships
</code>```

Body:
I have a Node Entity:

@NodeEntity(label = CollectionNames.CONSUMER)
public class Consumer extends AbstractNode{

    //Properties, removed just for simplicity

    @Relationship(type = RelationshipNames.HAS_CONTACT, direction = Relationship.OUTGOING)
    private Set<HasContact> contactList;

//Constructor & Getters, Setters
}

For Storing custom query results:

@QueryResult
public class CustomQueryResult {

    private AbstractNode node;
    private List<? extends AbstractRelationship> relationships;

    public CustomQueryResult(AbstractNode node, List<? extends AbstractRelationship> relationships){
        this.node = node;
        this.relationships = relationships;
    }

//Default Constructor, Getters & Setters
}

Repository Implementation

String query = String.format(
                "MATCH (startNode:Consumer {mobileNumber : {mob}})-[rel:%s *%d..%d]->(endNode:%s) RETURN startNode as node, rel as relationships",
                relationshipName, 0, depth, endNode);
        Map<String, Object> params = new HashMap<>();
        params.put("mob", mobileNo);
        CustomQueryResult consumer =  session.queryForObject(CustomQueryResult.class, query, params);

Although given Query load required data, but unfortunately its unable to map it to given Object(CustomQueryResult). But in case if I map it to Consumer then it show given error:

java.lang.RuntimeException: Result not of expected size. Expected 1
  row but found 6

While this same query is working fine, if I use Spring Data Neo4j Repository like

@Query("MATCH (startNode:Consumer {mobileNumber : {0}})-[rel:HAS_CONTACT *..1]->(endNode:Consumer) RETURN startNode as node, rel as relationships")
    CustomQueryResult findByMobileNumberAndRelationship(String mobileNo);

So how can I map given query result into Consumer or CustomQueryResult object directly?

Or is that possible to do the same thing using Spring Data Neo4j Repository with dynamic Relationship names and depth like:

@Query("MATCH (startNode:Consumer {mobileNumber : {0}})-[rel:{1} *..{2}]->(endNode:Consumer) RETURN startNode as node, rel as relationships")
    CustomQueryResult findByMobileNumberAndRelationship(String mobileNo, String relationshipName, @Depth int depth);

Although I am sure that above code is not working.

Body:
Your query returns multiple rows

MATCH (startNode:Consumer {mobileNumber : {0}})-[rel:HAS_CONTACT *..1]->(endNode:Consumer)
RETURN startNode as node, rel as relationships

where node is repeated for each rel. The repository infrastructure is able to handle that, but queryForObject is not - it expects single row.

It should work if you modify your query in following way so it returns only 1 row:

MATCH (startNode:Consumer {mobileNumber : {0}})-[rel:HAS_CONTACT *..1]->(endNode:Consumer)
RETURN startNode as node, COLLECT(rel) as relationships


问:
How do I get the d3 svg points to stay in their correct position on the leaflet map when zooming?
```<code>var map = L.map('mapid').setView([10.0, 15.0], 2);

L.tileLayer('https://api.mapbox.com/styles/v1/mapbox/light-v9/tiles/256/{z}/{x}/{y}?access_token=pk.eyJ1Ijoic2FidW1hZm9vIiwiYSI6ImNqMWE3cnlqcTA5dncyd216YjI0bnY4dGEifQ.fgmXgmkvialdBd3D405_BA', {
attribution: 'Map data © <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, <a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, Imagery © <a href="http://mapbox.com">Mapbox</a>',
maxZoom: 18,
id: 'mapbox.streets',
accessToken: 'pk.eyJ1Ijoic2FidW1hZm9vIiwiYSI6ImNqMWE3cnlqcTA5dncyd216YjI0bnY4dGEifQ.fgmXgmkvialdBd3D405_BA'
}).addTo(map);

L.svg().addTo(map);

var svg = d3.select(map.getPanes().overlayPane).select('svg');

var g = svg.append('g').attr('class', 'leaflet-zoom-hide');

const URL = 'https://earthquake.usgs.gov/fdsnws/event/1/query?format=geojson&limit=200'

function getEarthquakeData() {
  fetch(URL)
  .then((results) => {
return results.json();
  })
  .then((result) => {

function projectPoint(x,y) {
  var point = map.latLngToLayerPoint(new L.LatLng(y,x));
  this.stream.point(point.x, point.y);
}

var transform = d3.geoTransform({point: projectPoint}),
path = d3.geoPath().projection(transform);

function applyLatLngToLayer(d){
  var y = d.geometry.coordinates[1];
  var x = d.geometry.coordinates[0];
  return map.latLngToLayerPoint(new L.LatLng(y,x));
}

// console.log(result.features);
// result.features.forEach(function(d) {
//   d.LatLng = new L.LatLng(d.geometry.coordinates[1],
//     d.geometry.coordinates[0])
//   });

var circle = g.selectAll('circle')
.data(result.features)
.enter().append('circle')
.style('fill','darkred')
.attr('r', 2)
.attr('opacity',0.5);

function update() {

  circle.attr("transform",
  function(d) {
    return "translate("+
    applyLatLngToLayer(d).x+","+
    applyLatLngToLayer(d).y+")";
  });

  var bounds = path.bounds(result),
  topLeft = bounds[0],
  bottomRight = bounds[1];

  svg.attr("width", bottomRight[0] - topLeft[0])
    .attr("height", bottomRight[1] - topLeft[1])
    .style("left", topLeft[0] + "px")
    .style("top", topLeft[1] + "px");

  g.attr("transform", "translate(" + -topLeft[0] + "," + -topLeft[1] + ")");

  }

  map.on('viewreset', update);
  update();

  })

}

getEarthquakeData();
</code>```

The above code will add points to a leaflet map once it fetches the data I'm interested in mapping.  The problem is that when I zoom in on the map all of the points remain in their same position while the map background changes view.  The points are not actually "affixed" to the correct location in any view besides the opening view.  I know this has something to do with the way I'm updating the view but I haven't been able to figure it out.  Please help!  Thanks in advance.

答:
I suspect you are using version 1.*, if so then this is a known issue:

https://github.com/Leaflet/Leaflet/issues/5016

Switch from the viewreset event to the moveend event and you should be ok.

Body:
var map = L.map('mapid').setView([10.0, 15.0], 2);

L.tileLayer('https://api.mapbox.com/styles/v1/mapbox/light-v9/tiles/256/{z}/{x}/{y}?access_token=pk.eyJ1Ijoic2FidW1hZm9vIiwiYSI6ImNqMWE3cnlqcTA5dncyd216YjI0bnY4dGEifQ.fgmXgmkvialdBd3D405_BA', {
attribution: 'Map data © OpenStreetMap contributors, CC-BY-SA, Imagery © Mapbox',
maxZoom: 18,
id: 'mapbox.streets',
accessToken: 'pk.eyJ1Ijoic2FidW1hZm9vIiwiYSI6ImNqMWE3cnlqcTA5dncyd216YjI0bnY4dGEifQ.fgmXgmkvialdBd3D405_BA'
}).addTo(map);

L.svg().addTo(map);

var svg = d3.select(map.getPanes().overlayPane).select('svg');

var g = svg.append('g').attr('class', 'leaflet-zoom-hide');

const URL = 'https://earthquake.usgs.gov/fdsnws/event/1/query?format=geojson&limit=200'

function getEarthquakeData() {
  fetch(URL)
  .then((results) => {
return results.json();
  })
  .then((result) => {

function projectPoint(x,y) {
  var point = map.latLngToLayerPoint(new L.LatLng(y,x));
  this.stream.point(point.x, point.y);
}

var transform = d3.geoTransform({point: projectPoint}),
path = d3.geoPath().projection(transform);

function applyLatLngToLayer(d){
  var y = d.geometry.coordinates[1];
  var x = d.geometry.coordinates[0];
  return map.latLngToLayerPoint(new L.LatLng(y,x));
}

// console.log(result.features);
// result.features.forEach(function(d) {
//   d.LatLng = new L.LatLng(d.geometry.coordinates[1],
//     d.geometry.coordinates[0])
//   });

var circle = g.selectAll('circle')
.data(result.features)
.enter().append('circle')
.style('fill','darkred')
.attr('r', 2)
.attr('opacity',0.5);

function update() {

  circle.attr("transform",
  function(d) {
    return "translate("+
    applyLatLngToLayer(d).x+","+
    applyLatLngToLayer(d).y+")";
  });

  var bounds = path.bounds(result),
  topLeft = bounds[0],
  bottomRight = bounds[1];

  svg.attr("width", bottomRight[0] - topLeft[0])
    .attr("height", bottomRight[1] - topLeft[1])
    .style("left", topLeft[0] + "px")
    .style("top", topLeft[1] + "px");

  g.attr("transform", "translate(" + -topLeft[0] + "," + -topLeft[1] + ")");

  }

  map.on('viewreset', update);
  update();

  })

}

getEarthquakeData();

The above code will add points to a leaflet map once it fetches the data I'm interested in mapping.  The problem is that when I zoom in on the map all of the points remain in their same position while the map background changes view.  The points are not actually "affixed" to the correct location in any view besides the opening view.  I know this has something to do with the way I'm updating the view but I haven't been able to figure it out.  Please help!  Thanks in advance.


问:
How does git merge after cherry-pick work?
Let's imagine that we have a master branch.

Then we create a newbranch

```<code>git checkout -b newbranch
</code>```

and make two new commits to newbranch: commit1 and commit2

Then we switch to master and make cherry-pick

```<code>git checkout master
git cherry-pick hash_of_commit1
</code>```

Looking into gitk we see that commit1 and its cherry-picked version have different hashes, so technically they are two different commits.

Finally we merge newbranch into master:

```<code>git merge newbranch
</code>```

and see that these two commits with different hashes were merged without problems although they imply that the same changes should be applied twice, so one of them should fail.

Does git really do a smart analysis of commit's content while merging and decide that changes shouldn't be applied twice or these commits are marked internally as linked together?

答:
After such merge you may have cherry-picked commits in history twice.

Solution to prevent this I quote from article which recommends for branches with duplicate(cherry-picked) commits use rebase before merge:

git merge after git cherry-pick: avoiding duplicate commits

Imagine we have the master branch and a branch b:

```<code>   o---X   <-- master
    \
     b1---b2---b3---b4   <-- b
</code>```

Now we urgently need the commits b1 and b3 in master, but not the
  remaining commits in b. So what we do is checkout the master branch
  and cherry-pick commits b1 and b3:

```<code>$ git checkout master
$ git cherry-pick "b1's SHA"
$ git cherry-pick "b3's SHA"
</code>```

The result would be:

```<code>   o---X---b1'---b3'   <-- master
    \
     b1---b2---b3---b4   <-- b
</code>```

Let’s say we do another commit on master and we get:

```<code>   o---X---b1'---b3'---Y   <-- master
    \
     b1---b2---b3---b4   <-- b
</code>```

If we would now merge branch b into master:

```<code>$ git merge b
</code>```

We would get the following:

```<code>   o---X---b1'---b3'---Y--- M  <-- master
     \                     /
      b1----b2----b3----b4   <-- b
</code>```

That means the changes introduced by b1 and b3 would appear twice in
  the history. To avoid that we can rebase instead of merge:

```<code>$ git rebase master b
</code>```

Which would yield:

```<code>   o---X---b1'---b3'---Y   <-- master
                        \
                         b2'---b4'   <-- b
</code>```

Finally:

```<code>$ git checkout master
$ git merge b
</code>```

gives us:

```<code>   o---X---b1'---b3'---Y---b2'---b4'   <-- master, b
</code>```

EDIT
Corrections supposed by David Lemon's comment

Body:
Let's imagine that we have a master branch.

Then we create a newbranch

git checkout -b newbranch

and make two new commits to newbranch: commit1 and commit2

Then we switch to master and make cherry-pick

git checkout master
git cherry-pick hash_of_commit1

Looking into gitk we see that commit1 and its cherry-picked version have different hashes, so technically they are two different commits.

Finally we merge newbranch into master:

git merge newbranch

and see that these two commits with different hashes were merged without problems although they imply that the same changes should be applied twice, so one of them should fail.

Does git really do a smart analysis of commit's content while merging and decide that changes shouldn't be applied twice or these commits are marked internally as linked together?

Body:
After such merge you may have cherry-picked commits in history twice.

Solution to prevent this I quote from article which recommends for branches with duplicate(cherry-picked) commits use rebase before merge:

git merge after git cherry-pick: avoiding duplicate commits

Imagine we have the master branch and a branch b:

   o---X   <-- master
    \
     b1---b2---b3---b4   <-- b

Now we urgently need the commits b1 and b3 in master, but not the
  remaining commits in b. So what we do is checkout the master branch
  and cherry-pick commits b1 and b3:

$ git checkout master
$ git cherry-pick "b1's SHA"
$ git cherry-pick "b3's SHA"

The result would be:

   o---X---b1'---b3'   <-- master
    \
     b1---b2---b3---b4   <-- b

Let’s say we do another commit on master and we get:

   o---X---b1'---b3'---Y   <-- master
    \
     b1---b2---b3---b4   <-- b

If we would now merge branch b into master:

$ git merge b

We would get the following:

   o---X---b1'---b3'---Y--- M  <-- master
     \                     /
      b1----b2----b3----b4   <-- b

That means the changes introduced by b1 and b3 would appear twice in
  the history. To avoid that we can rebase instead of merge:

$ git rebase master b

Which would yield:

   o---X---b1'---b3'---Y   <-- master
                        \
                         b2'---b4'   <-- b

Finally:

$ git checkout master
$ git merge b

gives us:

   o---X---b1'---b3'---Y---b2'---b4'   <-- master, b

EDIT
Corrections supposed by David Lemon's comment

ContentLicense: CC BY-SA 4.0


问:
Get Join table data as a result of ActiveRecord:Relation
I am using rails 5 and oracle as a database. My query look like this..

```<code>DefaultConfig.where("role_id = ?","1001").joins(:config_param)
</code>```

Now i want to get the result object as a config_param object not a default_config..
is it possible to do? Thanks for any help

```<code>class DefaultConfig < ApplicationRecord
    self.table_name = "default_config"
    belongs_to :role
    belongs_to :config_param
end

class ConfigParam < ApplicationRecord
    self.table_name = "config_param"
    has_many :default_configs, foreign_key: "param_id"
end
</code>```

答:
```<code>ConfigParam.joins(:default_configs).where(default_config: { role_id: 1001 })
</code>```

Body:
I am using rails 5 and oracle as a database. My query look like this..

DefaultConfig.where("role_id = ?","1001").joins(:config_param)

Now i want to get the result object as a config_param object not a default_config..
is it possible to do? Thanks for any help

class DefaultConfig < ApplicationRecord
    self.table_name = "default_config"
    belongs_to :role
    belongs_to :config_param
end

class ConfigParam < ApplicationRecord
    self.table_name = "config_param"
    has_many :default_configs, foreign_key: "param_id"
end


问:
Determining the object type which send as parameter
I have three classes called Person, City and District, and some other.

I'm sending one of these three classes as a function parameter. I want to do an operation depends on which one of these three has been sended. How can I do that? All these three classes extends an Entity class.

Now it's like:

```<code>public void Insert (City newCity)
</code>```

but I want it be like:

```<code>public void Insert (Entity e)
</code>```

or something like that, and whichever it is (City or Person), I want to use it's properties.

Thank you!

答:
Just use is and as operators in this way:

```<code>public void Insert(Entity e)
{
    if (e is Person)
    {
        Person tmp = e as Person;
        //do your code
    }
    else if (e is City)
    {
        City tmp = e as City;
        //do your code
    }
    else if(e is District)
    {
        District tmp = e as District;
        //do your code
    }
}
</code>```

Body:
I have three classes called Person, City and District, and some other.

I'm sending one of these three classes as a function parameter. I want to do an operation depends on which one of these three has been sended. How can I do that? All these three classes extends an Entity class.

Now it's like:

public void Insert (City newCity)

but I want it be like:

public void Insert (Entity e)

or something like that, and whichever it is (City or Person), I want to use it's properties.

Thank you!

Body:
Just use is and as operators in this way:

public void Insert(Entity e)
{
    if (e is Person)
    {
        Person tmp = e as Person;
        //do your code
    }
    else if (e is City)
    {
        City tmp = e as City;
        //do your code
    }
    else if(e is District)
    {
        District tmp = e as District;
        //do your code
    }
}


问:
Increase PHP Max Execution time
I am using this code inside my PHP File

```<code><?php
set_time_limit(0);
// More code here
?>
</code>```

But i am still getting timedout after 100 seconds, what should i do?

答:
I suggest a cron-job approach for your problem. CLI called php scripts have no time limit. A shared host however may stop process that take more than X seconds - but I think is a good option for your issue.

If that doesn't work either, please give us more details on what you're trying to do in that PHP file. Maybe we can help you reduce the execution time of that script by changing the implementation.

Title: Increase PHP Max Execution time

Body:
I am using this code inside my PHP File

<?php
set_time_limit(0);
// More code here
?>

But i am still getting timedout after 100 seconds, what should i do?


问:
Select a subset of foreign key elements in inlineformset_factory in Django
I have a model with two foreign keys:

```<code>class Model1(models.Model):
  model_a = models.ForeignKey(ModelA)
  model_b = models.ForeignKey(ModelB)
  value = models.IntegerField()
</code>```

Then, I create an inline formset class, like so:

```<code>an_inline_formset = inlineformset_factory(ModelA, Model1, fk_name="model_a")
</code>```

and then instantiate it, like so:

```<code>a_formset = an_inline_formset(request.POST, instance=model_A_object)
</code>```

Once this formset gets rendered in a template/page, there is ChoiceField associated with the model_b field. The problem I'm having is that the elements in the resulting drop down menu include all of the elements found in ModelB table. I need to select a subset of those based on some criteria from ModelB. At the same time, I need to keep the reference to the instance of model_A_object when instantiating inlineformset_factory and, therefore, I can't just use this example. Any suggestions?

答:
What you need to do is change the ModelChoiceField's queryset

The easiest way to do this may be to monkey-patch the formset's form. You should be able to do this right after constructing the formset with:

```<code>an_inline_formset.form.base_fields['model_b'].queryset = ModelB.objects.filter(whatever=True)
</code>```

Not the prettiest, but it should work.

ContentLicense: CC BY-SA 2.5

Body:
I have a model with two foreign keys:

class Model1(models.Model):
  model_a = models.ForeignKey(ModelA)
  model_b = models.ForeignKey(ModelB)
  value = models.IntegerField()

Then, I create an inline formset class, like so:

an_inline_formset = inlineformset_factory(ModelA, Model1, fk_name="model_a")

and then instantiate it, like so:

a_formset = an_inline_formset(request.POST, instance=model_A_object)

Once this formset gets rendered in a template/page, there is ChoiceField associated with the model_b field. The problem I'm having is that the elements in the resulting drop down menu include all of the elements found in ModelB table. I need to select a subset of those based on some criteria from ModelB. At the same time, I need to keep the reference to the instance of model_A_object when instantiating inlineformset_factory and, therefore, I can't just use this example. Any suggestions?

Body:
What you need to do is change the ModelChoiceField's queryset

The easiest way to do this may be to monkey-patch the formset's form. You should be able to do this right after constructing the formset with:

an_inline_formset.form.base_fields['model_b'].queryset = ModelB.objects.filter(whatever=True)

Not the prettiest, but it should work.


问:
How do I access APIs without using NetworkCredential in C#/UWP?
I got some of the APP's APIs.
When I use the browser to access these APIs, the browser popup window tell me to fill in the username/password, Then I tried to fill out my username/password and found that I passed the verification!
Then I tried to write the code

```<code>var myClientHandler = new HttpClientHandler();
myClientHandler.Credentials = new NetworkCredential("abc", "!@#");

this._client = new HttpClient(myClientHandler);
this._client.BaseAddress = new Uri("http://api.xxx.com");
var result = await this._client.GetStringAsync("some_api_foo.json");
</code>```

Run well!

(We know that if there are no NetworkCredential, there will be 401 unauthorized exception)

But I found out that the official APP could access some of the APIs without the user logging in. How does it work? Does it use a public account? Or is there another way to access the APIs?

答:
Use Fiddler >check Authorization Header is present: Basic xxxxxxxxxxxxxxxxxxxxxxxxxxxx

xxxxxxxxxxxxxxxxxxxxxxxxxxxx is Username:Password(Base64)
Decrypt it!

Body:
I got some of the APP's APIs.
When I use the browser to access these APIs, the browser popup window tell me to fill in the username/password, Then I tried to fill out my username/password and found that I passed the verification!
Then I tried to write the code

var myClientHandler = new HttpClientHandler();
myClientHandler.Credentials = new NetworkCredential("abc", "!@#");

this._client = new HttpClient(myClientHandler);
this._client.BaseAddress = new Uri("http://api.xxx.com");
var result = await this._client.GetStringAsync("some_api_foo.json");

Run well!

(We know that if there are no NetworkCredential, there will be 401 unauthorized exception)

But I found out that the official APP could access some of the APIs without the user logging in. How does it work? Does it use a public account? Or is there another way to access the APIs?


问:
MySql get one record from two identical tables with a check
I want to get same records from two identical tables but with a check.

I have following two tables that are identical :

table_1

```<code>id  | enc   | first_name | last_name | address | city
1   | 1001  | John       | Doe       | abc     |
</code>```

table_2

```<code>id  | enc   | first_name | last_name | address | city
1   | 1001  |            | Doe       |         | xyz
</code>```

I want to get record from table_2 but since first_name and address are empty it should the from record table_1
But again city is empty in table_1 so it would get the record from table_2

I've tried the union like this :

```<code>(SELECT * from `table_1` where `id` = `1)
UNION
(SELECT * from `table_2` where `id` = `1)
</code>```

But its providing both the records from the table. I want only one record using both the table like this :

```<code>id  | enc   | first_name | last_name | address | city
1   | 1001  | John       | Doe       | abc     | xyz
</code>```

答:
```<code>SELECT IFNULL(T1.id,T2.ID) ID,IFNULL(T1.enc,T2.ENC)ENC,IFNULL(T1.first_name,T2.first_name)first_name , IFNULL(T1.last_name ,T2.last_name )last_name ,
IFNULL(T1.address ,T2.address )address ,
IFNULL(T1.city,T2.city)address
 from `table_1` T1
INNER JOIN `table_2` T2 ON T1.ID=T2.ID
</code>```

Try above query.

Body:
I want to get same records from two identical tables but with a check.

I have following two tables that are identical :

table_1

id  | enc   | first_name | last_name | address | city
1   | 1001  | John       | Doe       | abc     |

table_2

id  | enc   | first_name | last_name | address | city
1   | 1001  |            | Doe       |         | xyz

I want to get record from table_2 but since first_name and address are empty it should the from record table_1
But again city is empty in table_1 so it would get the record from table_2

I've tried the union like this :

(SELECT * from `table_1` where `id` = `1)
UNION
(SELECT * from `table_2` where `id` = `1)

But its providing both the records from the table. I want only one record using both the table like this :

id  | enc   | first_name | last_name | address | city
1   | 1001  | John       | Doe       | abc     | xyz

Body:
SELECT IFNULL(T1.id,T2.ID) ID,IFNULL(T1.enc,T2.ENC)ENC,IFNULL(T1.first_name,T2.first_name)first_name , IFNULL(T1.last_name ,T2.last_name )last_name ,
IFNULL(T1.address ,T2.address )address ,
IFNULL(T1.city,T2.city)address
 from `table_1` T1
INNER JOIN `table_2` T2 ON T1.ID=T2.ID

Try above query.


问:
How to get the name of the running application in iOS
If the application name under the icon on the home screen is "My Awesome App" how do you get that string within the application at runtime?</p>

答:
Swift 3/4</p>

```<code>let appName =  Bundle.main.object(forInfoDictionaryKey: kCFBundleNameKey as String) as? String
</code>```

Body:
Swift 3/4

let appName =  Bundle.main.object(forInfoDictionaryKey: kCFBundleNameKey as String) as? String


答:
You can make it generic:

```<code>public void Insert<T>(T entity) where T: Entity
{

}
</code>```

Now you can use all properties or methods of Entity. If you need to use properties or methods that only belong to the subtype, you have to cast it:

```<code>public void Insert<T>(T entity) where T: Entity
{
    if(entity is City)
    {
        City city = (City) entity;
        // ...
    }
    else if(entity is Person)
    {
        Person person = (Person) entity;
        // ...
    }
}
</code>```

Title: Determining the object type which send as parameter

Body:
You can make it generic:

public void Insert<T>(T entity) where T: Entity
{

}

Now you can use all properties or methods of Entity. If you need to use properties or methods that only belong to the subtype, you have to cast it:

public void Insert<T>(T entity) where T: Entity
{
    if(entity is City)
    {
        City city = (City) entity;
        // ...
    }
    else if(entity is Person)
    {
        Person person = (Person) entity;
        // ...
    }
}


问:
How to Substract time from datetime
I am using a timezone based script where there is deadline based on timezones. Say for example a deadline is on 7th July at 6PM for a person in IST timezone. The deadline should be 1:30 less than 6pm in Dubai as per their timezone.

I have already calculated the difference between the two timezone difference. I am stuck at deducting that calculated time from the deadline time.

I have saved the timezones in +5:40 +4:00 -4:00 this format instead of using php default ones.

答:
Can you explain a little more specifically what you want to do?

You want to subtract when data already on some var inside your script or you want the SQL query needed ?

If so maybe you can use this answer ---> How to subtract 3 hours from a datetime in MySQL?

The last answer of this post maybe is the one that fit the most what you need :

Assuming you have some timezone issue and know source and destination timezone, you could convert it like so

```<code>SELECT
    DATE_FORMAT(CONVERT_TZ(x.date_entered, 'UTC', 'Europe/Berlin'), '%Y-%m-%d') AS date
FROM
    x
ORDER BY
    date ASC;
</code>```

Title: How to Substract time from datetime

Body:
Can you explain a little more specifically what you want to do?

You want to subtract when data already on some var inside your script or you want the SQL query needed ?

If so maybe you can use this answer ---> How to subtract 3 hours from a datetime in MySQL?

The last answer of this post maybe is the one that fit the most what you need :

Assuming you have some timezone issue and know source and destination timezone, you could convert it like so

SELECT
    DATE_FORMAT(CONVERT_TZ(x.date_entered, 'UTC', 'Europe/Berlin'), '%Y-%m-%d') AS date
FROM
    x
ORDER BY
    date ASC;


问:
merge results in more rows than one of the data frames
I have two data frames, the first contains 9994 rows and the second contains 60431 rows. I want to merge the two data frames such that the merged data frame contains combined columns of both data frames but only contains 9994 rows.

However, I get more than 9994 rows upon merge. How can I make sure this does not happen?

```<code>df1 = readRDS('data1.RDS')
nrow(df1)
# [1] 9994

df2 = readRDS('data2.RDS')
nrow(df2)
# [1] 60431

df = merge(df1,df2,by=c("col1","col2"))
nrow(df)
# [1] 10057

df = merge(df1,df2,by=c("col1","col2"),all.x=TRUE)
nrow(df)
# [1] 10057
nrow(na.omit(df))
# [1] 10057
</code>```

EDIT : Following akrun's comment.
Yes, there were duplicates in the second data frame

```<code>nrow(unique(df2[,c("col1","col2")]))
# [1] 60263
nrow(df2)
# [1] 60431
</code>```

How can I take only one row from a data frame if there are multiple for the same {col1,col2} combination. When I merge, I would like to have only 9994 rows.

答:
This should work, be sure to sort df2 first so you select the right rows.

```<code>df = merge(
  df1,
  df2[!duplicated(df2[, c("col1","col2")]), ],
  by=c("col1","col2"),
  all.x=TRUE
)
</code>```

What happens here: I merge the two data frames by the columns we want to merge by, but I first select only the first occurrence of any combination of col1 and col2 from the second data.frame df2.

duplicated checks if lines are duplicated if called with a data.frame. I select col1 and col2 from df2, so duplicated returns TRUE for rows with the same col1 and col2 but differences in other cols. Then I select only the rows which are not duplicated.

(Read the [-expressions carefully, and check the function calls from the inside out, to get the intermediate results)

edit: added explanation as suggested in comments

Body:
I have two data frames, the first contains 9994 rows and the second contains 60431 rows. I want to merge the two data frames such that the merged data frame contains combined columns of both data frames but only contains 9994 rows.

However, I get more than 9994 rows upon merge. How can I make sure this does not happen?

df1 = readRDS('data1.RDS')
nrow(df1)
# [1] 9994

df2 = readRDS('data2.RDS')
nrow(df2)
# [1] 60431

df = merge(df1,df2,by=c("col1","col2"))
nrow(df)
# [1] 10057

df = merge(df1,df2,by=c("col1","col2"),all.x=TRUE)
nrow(df)
# [1] 10057
nrow(na.omit(df))
# [1] 10057

EDIT : Following akrun's comment.
Yes, there were duplicates in the second data frame

nrow(unique(df2[,c("col1","col2")]))
# [1] 60263
nrow(df2)
# [1] 60431

How can I take only one row from a data frame if there are multiple for the same {col1,col2} combination. When I merge, I would like to have only 9994 rows.

Body:
This should work, be sure to sort df2 first so you select the right rows.

df = merge(
  df1,
  df2[!duplicated(df2[, c("col1","col2")]), ],
  by=c("col1","col2"),
  all.x=TRUE
)

What happens here: I merge the two data frames by the columns we want to merge by, but I first select only the first occurrence of any combination of col1 and col2 from the second data.frame df2.

duplicated checks if lines are duplicated if called with a data.frame. I select col1 and col2 from df2, so duplicated returns TRUE for rows with the same col1 and col2 but differences in other cols. Then I select only the rows which are not duplicated.

(Read the [-expressions carefully, and check the function calls from the inside out, to get the intermediate results)

edit: added explanation as suggested in comments


问:
How to send a signal ( or notification ) from MPI process to another on C?
How can i make MPI process notify the others about an error for example, specially on an MPI program where all the MPI processees are independant from each others ( There no synchronisation between the different MPI processees ) ?

Thanks

答:
the disparity you point out makes me wonder: why are you using MPI?  it doesn't seem to fit your problem, and there's not much worse than trying to shove a square peg into MPI's round hole(s).  "no synchronization between MPI processes" makes it sound like you've taken a workload that is inherently serial-farming, and are trying to turn it into MPI.

that said, you can probably do what you want simply by polling periodically with MPI_Irecv and MPI_Test.


问:
fread. fseek. ftell. " warning: value computed is not used "
how to instead of

```<code>char text[10000];
</code>```

do

```<code>char text[fp_len];
</code>```

i also get this warning:

warning: value computed is not used

```<code>FILE *fp;
fp = fopen(path, "r");
int fp_len;
fseek(fp, 0, SEEK_END)+1;
fp_len = ftell(fp);
fseek(fp, 0, SEEK_SET);
printf("%d---", fp_len);

char text[10000];
fread(text, fp_len, 1, fp);

printf("%s", text);
</code>```

should i also add:

```<code>text[]= '\0'
</code>```

to the bottom. ( above printf )

答:
You get warning of unused value because when you add +1 to returned value, you are doing nothing

```<code>fseek(fp, 0, SEEK_END)+1;
</code>```

is evaluated to

```<code>fseek(fp, 0, SEEK_END);
</code>```

But compiler warns you about, maybe you forgot to assign result somewhere.

To read data, reserve memory in HEAP region using dynamic allocation otherwise you may enter to stack overflow if your fp_len is too big.

```<code>char *text = malloc(sizeof(*text) * (fp_len + 1));
</code>```

And don't forget to include stdlib.h

Body:
how to instead of

char text[10000];

do

char text[fp_len];

i also get this warning:

warning: value computed is not used

FILE *fp;
fp = fopen(path, "r");
int fp_len;
fseek(fp, 0, SEEK_END)+1;
fp_len = ftell(fp);
fseek(fp, 0, SEEK_SET);
printf("%d---", fp_len);

char text[10000];
fread(text, fp_len, 1, fp);

printf("%s", text);

should i also add:

text[]= '\0'

to the bottom. ( above printf )

Body:
You get warning of unused value because when you add +1 to returned value, you are doing nothing

fseek(fp, 0, SEEK_END)+1;

is evaluated to

fseek(fp, 0, SEEK_END);

But compiler warns you about, maybe you forgot to assign result somewhere.

To read data, reserve memory in HEAP region using dynamic allocation otherwise you may enter to stack overflow if your fp_len is too big.

char *text = malloc(sizeof(*text) * (fp_len + 1));

And don't forget to include stdlib.h


问:
Initializing a C++11 string with {}
What is the difference between initializing a string with:

```<code>std::string testString = "Test";
</code>```

and

```<code>std::string testString{"Test"};
</code>```

Is this only syntactic sugar thing or there actually are some performance related differences?

答:
There is no difference between them.

First declaration is preferred in most projects due to the syntax highlighting.

Title: Initializing a C++11 string with {}

Body:
What is the difference between initializing a string with:

std::string testString = "Test";

and

std::string testString{"Test"};

Is this only syntactic sugar thing or there actually are some performance related differences?


问:
Update values from multiple selected rows
I have 2 tables. Both have the same amount of rows.

Sample data:

```<code>Table1{
    Id, IdTable2Row
}

Table2 {
    Id, RedChicken -- LOL
}
</code>```

Each row of Table1 (column IdTable2Row) should get the id of 1 row of table 2 (irrelevant which one).
Table1.IdTable2Row is null in every row before the operation.

How can I do something like this?

```<code>UPDATE Table1 SET IdTable2Row = (SELECT Id FROM [Table2])
</code>```

答:
IN SQL SERVER if there is common column then you can join the table and update </p>

```<code>update a set a.IdTable2Row=b.Id from
Table1 a ,Table2 b
where a.column=b.column
</code>```

Body:
I have 2 tables. Both have the same amount of rows.

Sample data:

Table1{
    Id, IdTable2Row
}

Table2 {
    Id, RedChicken -- LOL
}

Each row of Table1 (column IdTable2Row) should get the id of 1 row of table 2 (irrelevant which one).
Table1.IdTable2Row is null in every row before the operation.

How can I do something like this?

UPDATE Table1 SET IdTable2Row = (SELECT Id FROM [Table2])

Body:
IN SQL SERVER if there is common column then you can join the table and update

update a set a.IdTable2Row=b.Id from
Table1 a ,Table2 b
where a.column=b.column


问:
Visual Studio 2017 HRESULT: 0x80070005 / E_ACCESSDENIED on project creation
I'm running Visual Studio 2017, version 15.0.0+26228.9

When I'm trying to create a new project via File > New > Project... in Visual Studio 2017, I'm receiving the following error message and the project is not created:

Access denied (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))

Don't mind the german message text in the screenshot:

This happens for every project template I use (e.g. C# WPF, VB WPF, C# Console App...).

If I try to create a project via the quick search box on the starting page of visual studio, VS just crashes instantly with no exception message at all:

Has anybody else ran into this issue and might know how to fix it?

答:
The below solution worked for me

Make sure all the instances of Visual studio are closed.

Go to %LocalAppData%\Microsoft\VisualStudio\15.0_****

Delete the file privateregistry.bin


问:
How to remove a header from express req object?
I'm trying to figure out how to remove header from req object in express. I believe this res.disable("Header Name") removes it from res object, but same doesn't work for req.headers

答:
That could be as simple as adding this middleware:</p>

```<code>app.use(function(req, res, next) {
  delete req.headers['header-name']; // should be lowercase
  next();
});
</code>```

Body:
That could be as simple as adding this middleware:

app.use(function(req, res, next) {
  delete req.headers['header-name']; // should be lowercase
  next();
});


问:
iPhone: different icon for homescreen and App Store
I would like to know if the app icon on the iPhone can be slightly different than the one shown in a large version in Apple's App Store.

It was discussed in short here: Tips for a successful AppStore submission?

But I wanted to make sure if anyone has more experience with that.

To give an example: The New York Times has many words incorporated in its app icon (see http://itunes.apple.com/de/app/nytimes/id284862083?mt=8). Would it be okay to have a full black colored background without the words in the small/homescreen version of the icon?

答:
You could achieve this using the new UIApplication.setAlternateIconName(_:completionHandler:) API in iOS 10.3 to change the app icon at runtime.

Note you need to ship the updated app icon as part of the app bundle however.


问:
Django. How to EXCLUDE one-to-many or many-to-many fields from query?
I have a sample model like this:

```<code>class FooBar(models.Model):
    name = models.CharField ...
    age = models.IntegerField ...
    cats = models.ManyToManyField ...
    dogs = models.ManyToManyField ...
</code>```

As u can see, there is 2 many-to-many fields (cats, dogs)

Then (somewhere else in my code) I have serializer function which converts given model into JSON. Eg.

```<code>make_json(foobar_instance) will produce smth like this:

{
    "id": "9999",
    "name": "John Romero",
    "age": "55",
    "cats": "[421, 5423, 53252]",
    "dogs": "[213, 44124, 321, 753]"
}
</code>```

BUT I don't need that "cats" and "dogs" fields in my result JSON and I don't want to charge database with additional queries for resolving that many-to-many relations.

So, how I can tell Django: Man, exclude that cats and dogs fields from result - I don't need that thing.

Eg.

```<code>FooBar.objects.filter(....).SKIP('cats', 'dogs')...
</code>```

Is that possible?

Thank you!

答: As far as I know Django's ORM will not issue sql queries to retrieve the related objects until you try to access them or unless you specifically asked for them using select_related() and/or prefetch_related(), so the simplest solution could be to inspect the model instance's fields in your make_json() function (using ._meta.get_fields()) to exclude ForeignKey and Many2ManyField fields from your serialization.

Body:
I have a sample model like this:

class FooBar(models.Model):
    name = models.CharField ...
    age = models.IntegerField ...
    cats = models.ManyToManyField ...
    dogs = models.ManyToManyField ...

As u can see, there is 2 many-to-many fields (cats, dogs)

Then (somewhere else in my code) I have serializer function which converts given model into JSON. Eg.

make_json(foobar_instance) will produce smth like this:

{
    "id": "9999",
    "name": "John Romero",
    "age": "55",
    "cats": "[421, 5423, 53252]",
    "dogs": "[213, 44124, 321, 753]"
}

BUT I don't need that "cats" and "dogs" fields in my result JSON and I don't want to charge database with additional queries for resolving that many-to-many relations.

So, how I can tell Django: Man, exclude that cats and dogs fields from result - I don't need that thing.

Eg.

FooBar.objects.filter(....).SKIP('cats', 'dogs')...

Is that possible?

Thank you!


答:
One approach would be to use inheritance and casting, something like this:

```<code>        public abstract class Entity
        {
            public int Id { get; set; }
        }

        public class City : Entity
        {
            public string CityName { get; set; }
        }

        public class Person : Entity
        {
            public string PersonName { get; set; }
        }

        public class MethodHost
        {
            public void Insert(Entity e)
            {
                if (e is Person person)
                {
                    // Do something with person
                } else if (e is City cityName)
                {
                    // Do something with city
                }
            }
        }
</code>```

P.S.: I'm using some new C# features here, if you are using an older version of C# you might need to do something like this:

```<code>var city = e as city
if(city != null)
{
    // Do something with city
}
</code>```

You also can use the is in the if and cast inside the if-tags - but this isn't the most performant way as it casts two times instead of one.

Body:
I have three classes called Person, City and District, and some other.

I'm sending one of these three classes as a function parameter. I want to do an operation depends on which one of these three has been sended. How can I do that? All these three classes extends an Entity class.

Now it's like:

public void Insert (City newCity)

but I want it be like:

public void Insert (Entity e)

or something like that, and whichever it is (City or Person), I want to use it's properties.

Thank you!

Body:
One approach would be to use inheritance and casting, something like this:

        public abstract class Entity
        {
            public int Id { get; set; }
        }

        public class City : Entity
        {
            public string CityName { get; set; }
        }

        public class Person : Entity
        {
            public string PersonName { get; set; }
        }

        public class MethodHost
        {
            public void Insert(Entity e)
            {
                if (e is Person person)
                {
                    // Do something with person
                } else if (e is City cityName)
                {
                    // Do something with city
                }
            }
        }

P.S.: I'm using some new C# features here, if you are using an older version of C# you might need to do something like this:

var city = e as city
if(city != null)
{
    // Do something with city
}

You also can use the is in the if and cast inside the if-tags - but this isn't the most performant way as it casts two times instead of one.


问:
How to synchronously animate a UIView and a CALayer
To illustrate this question, I gisted a very small Xcode project on Github (two classes, 11kb download). Have a look at the gist here or use git clone git@gist.github.com:93982af3b65d2151672e.git.

Please consider the following scenario. A custom view of mine, called 'container view', contains two little squares. Illustrated in this screenshot:

The blue square is a 22x22 pt UIView instance and the red square is a 22x22 pt CALayer instance. For purposes of this question I want the two squares to 'stick' to the bottom right corner of the outer view, while I animate the frame of that outer view.

I change the container view's frame within a UIView's class method animateWithDuration:delay:options:animations:completion:, with a non-default easing parameter of type UIViewAnimationCurveEaseOut.

```<code>[UIView animateWithDuration:1.0 delay:0
                    options:UIViewAnimationCurveEaseOut
                 animations:^{ _containerView.frame = randomFrame; }
                 completion:nil];
</code>```

Note: Both the blue UIView's and the red CALayer's frame are set in the overridden setFrame: method of the container view, but results would have been the same if I had set the blue UIView's autoresizingMask property to UIView flexible left and top margins.

In the resulting animation, the blue square 'sticks' to the corner just the way I intended it, but the red square completely disregards both timing and easing of the animation. I assume this is because of the implicit animation feature of Core Animation, a feature that has helped me in many occasions before.

Here are a few screenshots in the animation sequence that illustrate the asynchronicity of the two squares:

On to the question: Is there a way to synchronize the two frame changes so that the red CALayer and the blue UIView both move with the same animation duration and easing curve, sticking to each other as if they were one view?

P.S. Of course the required visual result of the two squares sticking together could be achieved in any number of ways, for example by having both layers become either CALayers or UIViews, but the project that the real issue is in has a very legit cause for the one to be a CALayer and the other to be a UIView.

答:
If you want David Rönnqvist's snippet in Swift 3.0, here you have it:

```<code>    CATransaction.begin()
    CATransaction.setAnimationDuration(1.0)
    CATransaction.setAnimationTimingFunction(CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut))

    // Layer animation
    let myAnimation = CABasicAnimation(keyPath: "frame");
    myAnimation.toValue = NSValue(cgRect: myNewFrame)
    myAnimation.fromValue = NSValue(cgRect: myLayer.frame)

    myLayer.frame = myNewFrame
    myLayer.add(myAnimation, forKey: "someKeyForMyAnimation")

    // Outer animation
    let outerAnimation = CABasicAnimation(keyPath: "frame")
    outerAnimation.toValue = NSValue(cgRect: myNewOuterFrame)
    outerAnimation.fromValue = NSValue(cgRect: outerView.frame)

    outerView.layer.frame = myNewOuterFrame
    outerView.layer.add(outerAnimation, forKey: "someKeyForMyOuterAnimation")

    CATransaction.commit()
</code>```

Body:
To illustrate this question, I gisted a very small Xcode project on Github (two classes, 11kb download). Have a look at the gist here or use git clone git@gist.github.com:93982af3b65d2151672e.git.

Please consider the following scenario. A custom view of mine, called 'container view', contains two little squares. Illustrated in this screenshot:

The blue square is a 22x22 pt UIView instance and the red square is a 22x22 pt CALayer instance. For purposes of this question I want the two squares to 'stick' to the bottom right corner of the outer view, while I animate the frame of that outer view.

I change the container view's frame within a UIView's class method animateWithDuration:delay:options:animations:completion:, with a non-default easing parameter of type UIViewAnimationCurveEaseOut.

[UIView animateWithDuration:1.0 delay:0
                    options:UIViewAnimationCurveEaseOut
                 animations:^{ _containerView.frame = randomFrame; }
                 completion:nil];

Note: Both the blue UIView's and the red CALayer's frame are set in the overridden setFrame: method of the container view, but results would have been the same if I had set the blue UIView's autoresizingMask property to UIView flexible left and top margins.

In the resulting animation, the blue square 'sticks' to the corner just the way I intended it, but the red square completely disregards both timing and easing of the animation. I assume this is because of the implicit animation feature of Core Animation, a feature that has helped me in many occasions before.

Here are a few screenshots in the animation sequence that illustrate the asynchronicity of the two squares:

On to the question: Is there a way to synchronize the two frame changes so that the red CALayer and the blue UIView both move with the same animation duration and easing curve, sticking to each other as if they were one view?

P.S. Of course the required visual result of the two squares sticking together could be achieved in any number of ways, for example by having both layers become either CALayers or UIViews, but the project that the real issue is in has a very legit cause for the one to be a CALayer and the other to be a UIView.

Body:
If you want David Rönnqvist's snippet in Swift 3.0, here you have it:

    CATransaction.begin()
    CATransaction.setAnimationDuration(1.0)
    CATransaction.setAnimationTimingFunction(CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut))

    // Layer animation
    let myAnimation = CABasicAnimation(keyPath: "frame");
    myAnimation.toValue = NSValue(cgRect: myNewFrame)
    myAnimation.fromValue = NSValue(cgRect: myLayer.frame)

    myLayer.frame = myNewFrame
    myLayer.add(myAnimation, forKey: "someKeyForMyAnimation")

    // Outer animation
    let outerAnimation = CABasicAnimation(keyPath: "frame")
    outerAnimation.toValue = NSValue(cgRect: myNewOuterFrame)
    outerAnimation.fromValue = NSValue(cgRect: outerView.frame)

    outerView.layer.frame = myNewOuterFrame
    outerView.layer.add(outerAnimation, forKey: "someKeyForMyOuterAnimation")

    CATransaction.commit()


问:
Dynamic two way binding to dynamic elements in wpf
I'm working on a modular application that will feature procedures that may or may not have parameters. Parameters are loaded to each procedure and on execution goal is to ask the user to input all required parameters then it does some extra work.

I've managed to load everything in and it all works fine, but I don't know how to make the dynamic binding for each of the parameters value.

I've made a demo application to test this, and even though I've fiddled with it for a bit I still can't seem to get it to work and I don't know what's missing.

Here's the code for the demo app that is a simplified version of the actual application, the concept is almost identical though:

```<code>public class TestBinding
{
    public List<Val> Values {get;set;}

    public TestBinding()
    {
        Values = new List<Val>();
        Values.Add(new Val {Caption = "First", Value = String.Empty});
        Values.Add(new Val {Caption = "Second", Value = String.Empty});
        Values.Add(new Val {Caption = "Third", Value = String.Empty});
    }
}

public class Val
{
    public string Caption {get;set;}
    public string Value {get;set;}
}

public TestBinding TB {get;set;}
public Window1()
{
    InitializeComponent();

    TB = new TestBinding();

    foreach(var x in TB.Values)
    {
        var txt = new TextBox() {Height = 25, Width = 150};

        var myBinding = new Binding("x.Value"); //???? Not sure about this
        myBinding.Source = x.Value;
        myBinding.Mode = BindingMode.TwoWay;
        myBinding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
        BindingOperations.SetBinding(txt, TextBox.TextProperty, myBinding);

        SPanel.Children.Add(txt);
    }

    var btn = new Button() {Height = 20, Width = 150, Content = "Show values"};

    btn.Click += new RoutedEventHandler(radioButton1_Click);
    SPanel.Children.Add(btn);
}

private void radioButton1_Click(object sender, RoutedEventArgs e)
{
    foreach(var x in TB.Values)
    {
        MessageBox.Show(x.Value);
    }
}
</code>```

答:
You have confused the Source object of the Binding and the Path to a source property of that object.

It should look like this:

```<code>var myBinding = new Binding("Value");
myBinding.Source = x;
myBinding.Mode = BindingMode.TwoWay;
myBinding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
</code>```

or

```<code>var myBinding = new Binding
{
    Path = new PropertyPath("Value"),
    Source = x,
    Mode = BindingMode.TwoWay,
    UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged
};

txt.SetBinding(TextBox.TextProperty, myBinding);
</code>```

Body:
I'm working on a modular application that will feature procedures that may or may not have parameters. Parameters are loaded to each procedure and on execution goal is to ask the user to input all required parameters then it does some extra work.

I've managed to load everything in and it all works fine, but I don't know how to make the dynamic binding for each of the parameters value.

I've made a demo application to test this, and even though I've fiddled with it for a bit I still can't seem to get it to work and I don't know what's missing.

Here's the code for the demo app that is a simplified version of the actual application, the concept is almost identical though:

public class TestBinding
{
    public List<Val> Values {get;set;}

    public TestBinding()
    {
        Values = new List<Val>();
        Values.Add(new Val {Caption = "First", Value = String.Empty});
        Values.Add(new Val {Caption = "Second", Value = String.Empty});
        Values.Add(new Val {Caption = "Third", Value = String.Empty});
    }
}

public class Val
{
    public string Caption {get;set;}
    public string Value {get;set;}
}

public TestBinding TB {get;set;}
public Window1()
{
    InitializeComponent();

    TB = new TestBinding();

    foreach(var x in TB.Values)
    {
        var txt = new TextBox() {Height = 25, Width = 150};

        var myBinding = new Binding("x.Value"); //???? Not sure about this
        myBinding.Source = x.Value;
        myBinding.Mode = BindingMode.TwoWay;
        myBinding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
        BindingOperations.SetBinding(txt, TextBox.TextProperty, myBinding);

        SPanel.Children.Add(txt);
    }

    var btn = new Button() {Height = 20, Width = 150, Content = "Show values"};

    btn.Click += new RoutedEventHandler(radioButton1_Click);
    SPanel.Children.Add(btn);
}

private void radioButton1_Click(object sender, RoutedEventArgs e)
{
    foreach(var x in TB.Values)
    {
        MessageBox.Show(x.Value);
    }
}

Body:
You have confused the Source object of the Binding and the Path to a source property of that object.

It should look like this:

var myBinding = new Binding("Value");
myBinding.Source = x;
myBinding.Mode = BindingMode.TwoWay;
myBinding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;

or

var myBinding = new Binding
{
    Path = new PropertyPath("Value"),
    Source = x,
    Mode = BindingMode.TwoWay,
    UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged
};

txt.SetBinding(TextBox.TextProperty, myBinding);


问:
Adding comments for "<%@" directives in asmx file
I was attempting to comment out a directive on an asmx file:

```<code><%@ WebService Language="C#" CodeBehind="test" Class="test" %>
</code>```

when i realised, i have no idea what the syntax is to do so.

Anyone know?

答:
Use
    <%--    --%>

for server-side comments, or Ctrl-K Ctrl-C in Visual Studio

Body:
I was attempting to comment out a directive on an asmx file:

<%@ WebService Language="C#" CodeBehind="test" Class="test" %>

when i realised, i have no idea what the syntax is to do so.

Anyone know?


问:
Pandas: astype error string to float (could not convert string to float: '7,50')
I am trying to convert a dataframe field from string to float in Pandas.

This is the field:

```<code>In:

print(merged['platnosc_total'].head(100))

Out:

0     0,00
1     4,50
2     0,00
3     0,00
4     0,00
5     4,50
6     6,10
7     7,99
8     4,00
9     7,69
10    7,50
</code>```

Note the 7,50, in the last row, which seems to cause the error:

```<code>In:

merged['platnosc_total'].astype(float)

Out:

ValueError: could not convert string to float: '7,50'
</code>```

Does this mean that the rest got converted, and only the row with 7,50 is the cause?

How can I actually cast this field/column to float?

答:
Need replace first:

```<code>print (merged['platnosc_total'].replace(',','.', regex=True).astype(float))
0    0.00
1    4.50
2    0.00
3    0.00
4    0.00
5    4.50
6    6.10
7    7.99
8    4.00
Name: platnosc_total, dtype: float64
</code>```

Body:
I am trying to convert a dataframe field from string to float in Pandas.

This is the field:

In:

print(merged['platnosc_total'].head(100))

Out:

0     0,00
1     4,50
2     0,00
3     0,00
4     0,00
5     4,50
6     6,10
7     7,99
8     4,00
9     7,69
10    7,50

Note the 7,50, in the last row, which seems to cause the error:

In:

merged['platnosc_total'].astype(float)

Out:

ValueError: could not convert string to float: '7,50'

Does this mean that the rest got converted, and only the row with 7,50 is the cause?

How can I actually cast this field/column to float?

Body:
Need replace first:

print (merged['platnosc_total'].replace(',','.', regex=True).astype(float))
0    0.00
1    4.50
2    0.00
3    0.00
4    0.00
5    4.50
6    6.10
7    7.99
8    4.00
Name: platnosc_total, dtype: float64


问:
How to create a facet filter that utilizes a prefix when filtering
I have an attribute that is of string data type.I am using the algoliasearchHelper object to search through my Algolia database. What I want to do is create a facet filter that takes a specified prefix and returns all objects that have a value with the specified prefix inside a specified attribute.

For example, so far I am using this:

```<code>Helper.addDisjunctiveFacetRefinement("attributeName","Can");
</code>```

This returns all objects that have the value of "Can" in the "attributeName" attribute, but it doesn't return any objects that have the value of "Canada" or "Canadians" in the "attributeName" attribute, even though those have a prefix of "Can".

How can I make it so that when it filters, it filters with a specified prefix.

答:
A disjunctive facet refinement is used for an exact match of a filter. This is mainly used to select a certain filter out of a list of possible filters. What I assume you want, is to get a subset of all possible filters.

This is possible with our searchForFacetValues function. First this needs to be set up in your indexing settings as searchable(attributeName) so we can generate the additional data structures to make the facets easily searchable. You can also read more about that setup in the documentation.

So once the attribute is searchable, you can use the helper function to refine the list of filters like this:

```<code>Helper.searchForFacetValues("attributeName","Can");
</code>```

Have a great day!

Body:
I have an attribute that is of string data type.I am using the algoliasearchHelper object to search through my Algolia database. What I want to do is create a facet filter that takes a specified prefix and returns all objects that have a value with the specified prefix inside a specified attribute.

For example, so far I am using this:

Helper.addDisjunctiveFacetRefinement("attributeName","Can");

This returns all objects that have the value of "Can" in the "attributeName" attribute, but it doesn't return any objects that have the value of "Canada" or "Canadians" in the "attributeName" attribute, even though those have a prefix of "Can".

How can I make it so that when it filters, it filters with a specified prefix.

Body:
A disjunctive facet refinement is used for an exact match of a filter. This is mainly used to select a certain filter out of a list of possible filters. What I assume you want, is to get a subset of all possible filters.

This is possible with our searchForFacetValues function. First this needs to be set up in your indexing settings as searchable(attributeName) so we can generate the additional data structures to make the facets easily searchable. You can also read more about that setup in the documentation.

So once the attribute is searchable, you can use the helper function to refine the list of filters like this:

Helper.searchForFacetValues("attributeName","Can");

Have a great day!


问:
How to support object rest spreading highlight in vscode?
```<code>{
  a: 3,
  b: 4,
  ...{c: 5}
}
</code>```

It is called object rest spreading.
How could i make vs-code to support this syntax?
At this moment it just get a syntax warning in that line

答: This has been fixed since at least VSCode 1.11 I believe. Please try using the current version of VSCode</p>

Body:
{
  a: 3,
  b: 4,
  ...{c: 5}
}

It is called object rest spreading.
How could i make vs-code to support this syntax?
At this moment it just get a syntax warning in that line


问:
Not getting local notification
I have done this in my AppDelegate

```<code>    UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge], completionHandler: {(didAllow, error) in
        if didAllow{
            print("Notification access granted")
        }
        else{
            print(error?.localizedDescription as Any)
        }
    })
</code>```

And in my ViewController class i have done this method to call on a button action

```<code>func sendNotification(inSecond: TimeInterval, completion: @escaping (_ Success: Bool) -> ()){
    let notify = UNMutableNotificationContent()
    notify.title = "Break Oil"
    notify.subtitle = "Please renew your Break Oil"
    notify.sound = UNNotificationSound(named: "carsHrn.mp3")
    let trigger = UNTimeIntervalNotificationTrigger(timeInterval: inSecond, repeats: false)
    let request = UNNotificationRequest(identifier: "myNotification", content: notify, trigger: trigger)
    UNUserNotificationCenter.current().add(request, withCompletionHandler: { error in
        if error != nil{
            print(error!)
            completion(false)
        }
        else    {
            completion(true)
        }
    })

}
</code>```

答:
Fixed by using
extension DignoSViewController : UNUserNotificationCenterDelegate {

```<code>func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
    completionHandler([.alert])
}
</code>```

}

Title: Not getting local notification

Body:
I have done this in my AppDelegate

    UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge], completionHandler: {(didAllow, error) in
        if didAllow{
            print("Notification access granted")
        }
        else{
            print(error?.localizedDescription as Any)
        }
    })

And in my ViewController class i have done this method to call on a button action

func sendNotification(inSecond: TimeInterval, completion: @escaping (_ Success: Bool) -> ()){
    let notify = UNMutableNotificationContent()
    notify.title = "Break Oil"
    notify.subtitle = "Please renew your Break Oil"
    notify.sound = UNNotificationSound(named: "carsHrn.mp3")
    let trigger = UNTimeIntervalNotificationTrigger(timeInterval: inSecond, repeats: false)
    let request = UNNotificationRequest(identifier: "myNotification", content: notify, trigger: trigger)
    UNUserNotificationCenter.current().add(request, withCompletionHandler: { error in
        if error != nil{
            print(error!)
            completion(false)
        }
        else    {
            completion(true)
        }
    })

}

Body:
Fixed by using
extension DignoSViewController : UNUserNotificationCenterDelegate {

func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
    completionHandler([.alert])
}

}


问:
Uppercase characters in UItextfield
I have a question about iOS UIKeyboard.

I have a UITextField and I would to have the keyboard with only uppercase characters.

I use a storyboard and I tried to set the Cpitalization as "All characters" to UITextField properties.

But this not solve my problem...any suggestion?

答:
Maybe it's a bit late for an answer here, but as I have a working solution someone might find it useful.

Well, in the following textfield delegate method, check if the new string contains any lowercase characters. If so, then:

Append the character that was just typed to the textfield's text.

Make all the textfield's text uppercased.

Make sure that false is returned by the method.

Otherwise just return true and let the method work as expected.

Here's its implementation:

```<code>func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    var returnValue = true
    let lowercaseRange = string.rangeOfCharacter(from: CharacterSet.lowercaseLetters)
    if let _ = lowercaseRange?.isEmpty {
        returnValue = false
    }

    if !returnValue {
        textField.text = (textField.text! + string).uppercased()
    }

    return returnValue
}
</code>```

The above has worked perfectly for me, and a similar implementation works for textviews too, after making the proper adjustments first of course.

Hope it helps!

Title: Uppercase characters in UItextfield

Body:
Maybe it's a bit late for an answer here, but as I have a working solution someone might find it useful.

Well, in the following textfield delegate method, check if the new string contains any lowercase characters. If so, then:

Append the character that was just typed to the textfield's text.

Make all the textfield's text uppercased.

Make sure that false is returned by the method.

Otherwise just return true and let the method work as expected.

Here's its implementation:

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    var returnValue = true
    let lowercaseRange = string.rangeOfCharacter(from: CharacterSet.lowercaseLetters)
    if let _ = lowercaseRange?.isEmpty {
        returnValue = false
    }

    if !returnValue {
        textField.text = (textField.text! + string).uppercased()
    }

    return returnValue
}

The above has worked perfectly for me, and a similar implementation works for textviews too, after making the proper adjustments first of course.

Hope it helps!


问:
Docker - docker compose two branches - Updated
I'm new to using Docker.

I'm using Dockerhub to link up with my GitHub repo. I have two branches on my GitHub repo: master and test. I want to know how to use docker-compose to specifically build either the master project (live) or the test project (development). Do I specify the tag name? when using:

docker-compose up -d

Because right now it only builds master project.

Updated docker-compose.yml

docker-compose.yml

```<code>version: '3.1'
services:
  web:
    image: melkawakibi/blogandportfolio:latest
  links:
     - db

  web:
    image: melkawakibi/blogandportfolio:test
  links:
     - db

  db:
    image: mysql:5.6
    environment:
      MYSQL_ROOT_PASSWORD: ""
      MYSQL_DATABASE: ""
      MYSQL_USER: ""
</code>```

dockerfile

```<code>FROM hitalos/laravel

RUN git config --system http.sslverify false

RUN git clone @github.com/melkawakibi/blogandportfolio.git /var/www

RUN cp .env.production .env

# Run Compser Install
RUN composer install -d /var/www
RUN php /var/www/artisan key:generate

WORKDIR /var/www

CMD php /var/www/artisan serve --port=80 --host=0.0.0.0
EXPOSE 80
</code>```

答: Use image: melkawakibi/blogandportfolio:master for master branch, and image: melkawakibi/blogandportfolio:test for test branch. The absence of a tag implies latest, that you don't have.

Body:
I'm new to using Docker.

I'm using Dockerhub to link up with my GitHub repo. I have two branches on my GitHub repo: master and test. I want to know how to use docker-compose to specifically build either the master project (live) or the test project (development). Do I specify the tag name? when using:

docker-compose up -d

Because right now it only builds master project.

Updated docker-compose.yml

docker-compose.yml

version: '3.1'
services:
  web:
    image: melkawakibi/blogandportfolio:latest
  links:
     - db

  web:
    image: melkawakibi/blogandportfolio:test
  links:
     - db

  db:
    image: mysql:5.6
    environment:
      MYSQL_ROOT_PASSWORD: ""
      MYSQL_DATABASE: ""
      MYSQL_USER: ""

dockerfile

FROM hitalos/laravel

RUN git config --system http.sslverify false

RUN git clone @github.com/melkawakibi/blogandportfolio.git /var/www

RUN cp .env.production .env

# Run Compser Install
RUN composer install -d /var/www
RUN php /var/www/artisan key:generate

WORKDIR /var/www

CMD php /var/www/artisan serve --port=80 --host=0.0.0.0
EXPOSE 80


问:
Edit and preview the video in real time on iOS
Can I use GPUImage or what real-time editing and preview video on iOS?

I have read the GPUImage's instructions about "Filtering and re-encoding a movie", but it does not seem to preview the video in real time?

Thank you very much for your help :)

答:
You can have a preview of filtered video with following chain (GPUImage): </p>

```<code>GPUImageMovie -> Any GPUImage Filter -> GPUImageView
</code>```

Body:
You can have a preview of filtered video with following chain (GPUImage):

GPUImageMovie -> Any GPUImage Filter -> GPUImageView


问:
Wordpress Post Transition - JS Alert
We have a few processes that team member must follow when changing a Wordpress status. Because of this I am trying to display a message on status change as a reminder.

I found the post transition function on the WP Codex and think this is the right function for the job, I tried setting up simple JS Alert as a test but does not seem to work. I tested my function was being called using a die() test.

Any suggestions would be appreciated, does not need to be JS as long as I can display a message on status change..

My current function:

```<code>function status_change_dtp( $post  ) {
    echo "<script>alert('Display a message on change')</script>";
}
add_action( 'draft_to_publish', 'status_change_dtp', 10, 3 );
</code>```

答:
Came up with a solution, rather than using the post transition hook I simply updated the status messages themselves...</p>

```<code>add_filter( 'post_updated_messages', 'rw_post_updated_messages' );

function rw_post_updated_messages( $messages ) {

    $post             = get_post();
    $post_type        = get_post_type( $post );
    $post_type_object = get_post_type_object( $post_type );

    $messages['cpt_operator'] = array(
        6  => __( "Operator Published - <script>alert('Please Set to Live in Protostar')</script>." ),
        10 => __( 'Draft Saved.' )
    );

    return $messages;
}
</code>```

Title: Wordpress Post Transition - JS Alert

Body:
We have a few processes that team member must follow when changing a Wordpress status. Because of this I am trying to display a message on status change as a reminder.

I found the post transition function on the WP Codex and think this is the right function for the job, I tried setting up simple JS Alert as a test but does not seem to work. I tested my function was being called using a die() test.

Any suggestions would be appreciated, does not need to be JS as long as I can display a message on status change..

My current function:

function status_change_dtp( $post  ) {
    echo "";
}
add_action( 'draft_to_publish', 'status_change_dtp', 10, 3 );

Body:
Came up with a solution, rather than using the post transition hook I simply updated the status messages themselves...

add_filter( 'post_updated_messages', 'rw_post_updated_messages' );

function rw_post_updated_messages( $messages ) {

    $post             = get_post();
    $post_type        = get_post_type( $post );
    $post_type_object = get_post_type_object( $post_type );

    $messages['cpt_operator'] = array(
        6  => __( "Operator Published - <script>alert('Please Set to Live in Protostar')</script>." ),
        10 => __( 'Draft Saved.' )
    );

    return $messages;
}


问:
Sqoop ORACLE SSL JDBC network adapter could not establish the connection using TCPS protocol
Am trying to import(SQOOP) table data from ORACLE DB to HDFS using SSL connection.

Sqoop command i use is as below,

sqoop import -Djavax.net.ssl.trustStore=/app/Wallets/client_wallet/ewallet.p12 -Djavax.net.ssl.trustStoreType=PKCS12 -Djavax.net.ssl.trustStorePassword=WalletPasswd123 --connect jdbc:oracle:thin:@testssl --username test --password test --table APP_INSTANCE

ERROR:

```<code>17/06/30 18:43:12 INFO sqoop.Sqoop: Running Sqoop version: 1.4.6
17/06/30 18:43:12 WARN util.NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable
17/06/30 18:43:13 DEBUG tool.BaseSqoopTool: Enabled debug logging.
17/06/30 18:43:13 WARN tool.BaseSqoopTool: Setting your password on the command-line is insecure. Consider using -P instead.
17/06/30 18:43:13 DEBUG sqoop.ConnFactory: Loaded manager factory: org.apache.sqoop.manager.oracle.OraOopManagerFactory
17/06/30 18:43:13 DEBUG sqoop.ConnFactory: Loaded manager factory: com.cloudera.sqoop.manager.DefaultManagerFactory
17/06/30 18:43:13 WARN sqoop.ConnFactory: Parameter --driver is set to an explicit driver however appropriate connection manager is not being set (via --connection-manager). Sqoop is going to fall back to org.apache.sqoop.manager.GenericJdbcManager. Please specify explicitly which connection manager should be used next time.
17/06/30 18:43:13 INFO manager.SqlManager: Using default fetchSize of 1000
17/06/30 18:43:13 INFO tool.CodeGenTool: Beginning code generation
17/06/30 18:43:13 DEBUG manager.SqlManager: Execute getColumnInfoRawQuery : SELECT t.* FROM APP_INSTANCE AS t WHERE 1=0
17/06/30 18:43:13 DEBUG manager.SqlManager: No connection paramenters specified. Using regular API for making connection.
17/06/30 18:43:14 ERROR manager.SqlManager: Error executing statement: java.sql.SQLRecoverableException: IO Error: The Network Adapter could not establish the connection java.sql.SQLRecoverableException: IO Error: The Network Adapter could not establish the connection
        at oracle.jdbc.driver.T4CConnection.logon(T4CConnection.java:458)
</code>```

tnsnames.ora:

```<code>testssl =   (DESCRIPTION =
    (ADDRESS = (PROTOCOL = TCPS)(HOST = IP )(PORT = 2484))
    (CONNECT_DATA = (SERVER = dedicated)(SERVICE_NAME = ORACL)))
</code>```

sqlnet.ora:

```<code>WALLET_LOCATION=(SOURCE=(METHOD=FILE)
      (METHOD_DATA=(DIRECTORY=/app/Wallets/client_wallet)))
SQLNET.AUTHENTICATION_SERVICES = (tcps)
SSL_CIPHER_SUITES = (SSL_RSA_WITH_AES_128_CBC_SHA,SSL_DH_anon_WITH_3DES_EDE_CBC_SHA)
SSL_CLIENT_AUTHENTICATION = FALSE
</code>```

Try with SQLPLUS:

```<code>$ sqlplus64 neon_main/bullet@testssl

SQL*Plus: Release 11.2.0.3.0 Production on Fri Jun 30 19:23:58 2017

Copyright (c) 1982, 2011, Oracle.  All rights reserved.

Connected to:
Oracle Database 11g Enterprise Edition Release 11.2.0.4.0 - 64bit Production
With the Partitioning, OLAP, Data Mining and Real Application Testing options

SQL>
</code>```

This is working fine. But not working with JDBC.

Please point me out where am wrong.?

答:
Since, you are using the TNS Name alias, you should pass the -Doracle.net.tns_admin= explicitly.  Also, JDBC thin will not read the file sqlnet.ora.  So, these properties need to be explicitly passed as connection level properties. </p>

<p>Check out SSL with JDBC whitepaper for more details. </p>

Body:
Am trying to import(SQOOP) table data from ORACLE DB to HDFS using SSL connection.

Sqoop command i use is as below,

sqoop import -Djavax.net.ssl.trustStore=/app/Wallets/client_wallet/ewallet.p12 -Djavax.net.ssl.trustStoreType=PKCS12 -Djavax.net.ssl.trustStorePassword=WalletPasswd123 --connect jdbc:oracle:thin:@testssl --username test --password test --table APP_INSTANCE

ERROR:

17/06/30 18:43:12 INFO sqoop.Sqoop: Running Sqoop version: 1.4.6
17/06/30 18:43:12 WARN util.NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable
17/06/30 18:43:13 DEBUG tool.BaseSqoopTool: Enabled debug logging.
17/06/30 18:43:13 WARN tool.BaseSqoopTool: Setting your password on the command-line is insecure. Consider using -P instead.
17/06/30 18:43:13 DEBUG sqoop.ConnFactory: Loaded manager factory: org.apache.sqoop.manager.oracle.OraOopManagerFactory
17/06/30 18:43:13 DEBUG sqoop.ConnFactory: Loaded manager factory: com.cloudera.sqoop.manager.DefaultManagerFactory
17/06/30 18:43:13 WARN sqoop.ConnFactory: Parameter --driver is set to an explicit driver however appropriate connection manager is not being set (via --connection-manager). Sqoop is going to fall back to org.apache.sqoop.manager.GenericJdbcManager. Please specify explicitly which connection manager should be used next time.
17/06/30 18:43:13 INFO manager.SqlManager: Using default fetchSize of 1000
17/06/30 18:43:13 INFO tool.CodeGenTool: Beginning code generation
17/06/30 18:43:13 DEBUG manager.SqlManager: Execute getColumnInfoRawQuery : SELECT t.* FROM APP_INSTANCE AS t WHERE 1=0
17/06/30 18:43:13 DEBUG manager.SqlManager: No connection paramenters specified. Using regular API for making connection.
17/06/30 18:43:14 ERROR manager.SqlManager: Error executing statement: java.sql.SQLRecoverableException: IO Error: The Network Adapter could not establish the connection java.sql.SQLRecoverableException: IO Error: The Network Adapter could not establish the connection
        at oracle.jdbc.driver.T4CConnection.logon(T4CConnection.java:458)

tnsnames.ora:

testssl =   (DESCRIPTION =
    (ADDRESS = (PROTOCOL = TCPS)(HOST = IP )(PORT = 2484))
    (CONNECT_DATA = (SERVER = dedicated)(SERVICE_NAME = ORACL)))

sqlnet.ora:

WALLET_LOCATION=(SOURCE=(METHOD=FILE)
      (METHOD_DATA=(DIRECTORY=/app/Wallets/client_wallet)))
SQLNET.AUTHENTICATION_SERVICES = (tcps)
SSL_CIPHER_SUITES = (SSL_RSA_WITH_AES_128_CBC_SHA,SSL_DH_anon_WITH_3DES_EDE_CBC_SHA)
SSL_CLIENT_AUTHENTICATION = FALSE

Try with SQLPLUS:

$ sqlplus64 neon_main/bullet@testssl

SQL*Plus: Release 11.2.0.3.0 Production on Fri Jun 30 19:23:58 2017

Copyright (c) 1982, 2011, Oracle.  All rights reserved.

Connected to:
Oracle Database 11g Enterprise Edition Release 11.2.0.4.0 - 64bit Production
With the Partitioning, OLAP, Data Mining and Real Application Testing options

SQL>

This is working fine. But not working with JDBC.

Please point me out where am wrong.?

Body:
Since, you are using the TNS Name alias, you should pass the -Doracle.net.tns_admin= explicitly.  Also, JDBC thin will not read the file sqlnet.ora.  So, these properties need to be explicitly passed as connection level properties.

Check out SSL with JDBC whitepaper for more details.


问:
using jquery.noConflict()
I have two files. HTML and .js files. in code.js, I have written jquery code and in HTML file, I am including code.js as following:

```<code><script src="jquery-1.4.2.js"></script>
<script src="jquery.interval.js"></script>
<script src="code.js">
jQuery.noConflict();
var $jcode = jQuery;
</script>
</code>```

in code.js, I have written following:

```<code>jcode(document).ready(function() {
     jcode.interval(checkForms, 2000);
});
</code>```

When I run it, it gives me error as can not read property of interval undefined.
I think there is something wrong with my usage of noConflict. Can you please help?

Thanks

答:
The problem that you are encountering is in the use of the src attribute for the script tag that contains inline code. Either move the call to noConflict to code.js or create a new script tag that calls noConflict prior to referencing code.js.

```<code><script>
jQuery.noConflict();
var $jcode = jQuery;
</script>
<script src="code.js"></script>
</code>```

Also, as noted by others, be sure to use $jcode instead of jcode when referencing your jQuery alias.

John Resig discussed this in his Degrading Script Tags post.

Title: using jquery.noConflict()

Body:
I have two files. HTML and .js files. in code.js, I have written jquery code and in HTML file, I am including code.js as following:

in code.js, I have written following:

jcode(document).ready(function() {
     jcode.interval(checkForms, 2000);
});

When I run it, it gives me error as can not read property of interval undefined.
I think there is something wrong with my usage of noConflict. Can you please help?

Thanks

Body:
The problem that you are encountering is in the use of the src attribute for the script tag that contains inline code. Either move the call to noConflict to code.js or create a new script tag that calls noConflict prior to referencing code.js.

<script>
jQuery.noConflict();
var $jcode = jQuery;
</script>
<script src="code.js"></script>

Also, as noted by others, be sure to use $jcode instead of jcode when referencing your jQuery alias.

John Resig discussed this in his Degrading Script Tags post.