问:
android: Can't add current location on map
I'm having trouble putting my current/updated location on the map which has other data. please see the image below. I need it because I will do a distance between the vehicle location and my current location, anyways how to do it? this activity is extended by fragment. I really need your help.

This is my OnMapReady:

```<code>public void onMapReady(GoogleMap googleMap) {
    mMapProximity = googleMap;
    mMapProximity.setBuildingsEnabled(true);
    mMapProximity.getUiSettings().setRotateGesturesEnabled(false);

    setUpMap();
}
private void setUpMap() {
    mMapProximity.clear();
    mMapProximity.setMapType(GoogleMap.MAP_TYPE_NORMAL);
    mMapProximity.setIndoorEnabled(true);
    mMapProximity.setBuildingsEnabled(true);
    mMapProximity.getUiSettings().setZoomControlsEnabled(false);

    final Double lati = Double.parseDouble(latitudeProxListMap);
    final Double longi = Double.parseDouble(longitudeProxListMap);

    m = mMapProximity.addMarker(new MarkerOptions()
            .position(new LatLng(lati, longi))
            .anchor(0.5f, 0.5f)
            .icon(BitmapDescriptorFactory.fromResource(R.drawable.pin_logo))
            .visible(true));

    mMapProximity.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener() {
        @Override
        public void onInfoWindowClick(Marker marker) {
            marker.showInfoWindow();
        }
    });

    mMapProximity.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(lati, longi), 17.0f));

    mMapProximity.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {

        @Override
        public boolean onMarkerClick(final Marker marker) {

            if (marker.isInfoWindowShown()) {
                marker.hideInfoWindow();
            } else {
                marker.showInfoWindow();
            }

            return true;
        }
    });

    mMapProximity.setInfoWindowAdapter(new MarkerInfoWindowAdapter());

    m.showInfoWindow();
}

class MarkerInfoWindowAdapter implements GoogleMap.InfoWindowAdapter {

    @Override
    public View getInfoWindow(Marker marker) {
        return null;
    }

    @Override
    public View getInfoContents(Marker marker) {

        View v = getActivity().getLayoutInflater().inflate(R.layout.info_vehicle_list_map, null);
        TextView title =v.findViewById(R.id.title);
        TextView snippet =v.findViewById(R.id.snippet);
        snippet.setVisibility(View.GONE);
        title.setText("Location: " + location);
        return v;
    }

}
</code>```

答: Implement LocationListener in your activity and than in onLocationChange method update the marker with the current location values. That will put a marker on the current location. </p>

Body:
I'm having trouble putting my current/updated location on the map which has other data. please see the image below. I need it because I will do a distance between the vehicle location and my current location, anyways how to do it? this activity is extended by fragment. I really need your help.

This is my OnMapReady:

public void onMapReady(GoogleMap googleMap) {
    mMapProximity = googleMap;
    mMapProximity.setBuildingsEnabled(true);
    mMapProximity.getUiSettings().setRotateGesturesEnabled(false);

    setUpMap();
}
private void setUpMap() {
    mMapProximity.clear();
    mMapProximity.setMapType(GoogleMap.MAP_TYPE_NORMAL);
    mMapProximity.setIndoorEnabled(true);
    mMapProximity.setBuildingsEnabled(true);
    mMapProximity.getUiSettings().setZoomControlsEnabled(false);

    final Double lati = Double.parseDouble(latitudeProxListMap);
    final Double longi = Double.parseDouble(longitudeProxListMap);

    m = mMapProximity.addMarker(new MarkerOptions()
            .position(new LatLng(lati, longi))
            .anchor(0.5f, 0.5f)
            .icon(BitmapDescriptorFactory.fromResource(R.drawable.pin_logo))
            .visible(true));

    mMapProximity.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener() {
        @Override
        public void onInfoWindowClick(Marker marker) {
            marker.showInfoWindow();
        }
    });

    mMapProximity.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(lati, longi), 17.0f));

    mMapProximity.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {

        @Override
        public boolean onMarkerClick(final Marker marker) {

            if (marker.isInfoWindowShown()) {
                marker.hideInfoWindow();
            } else {
                marker.showInfoWindow();
            }

            return true;
        }
    });

    mMapProximity.setInfoWindowAdapter(new MarkerInfoWindowAdapter());

    m.showInfoWindow();
}

class MarkerInfoWindowAdapter implements GoogleMap.InfoWindowAdapter {

    @Override
    public View getInfoWindow(Marker marker) {
        return null;
    }

    @Override
    public View getInfoContents(Marker marker) {

        View v = getActivity().getLayoutInflater().inflate(R.layout.info_vehicle_list_map, null);
        TextView title =v.findViewById(R.id.title);
        TextView snippet =v.findViewById(R.id.snippet);
        snippet.setVisibility(View.GONE);
        title.setText("Location: " + location);
        return v;
    }

}


来源: stackexchange

问:
import statement doesn't throw any error when a exported property is not defined in the export file
while checking import/ export feature, it was surprising to see that if a named property is used in import and it is not defined in the exported file than it does not throw any error?

below is the example

_export.js

```<code>export const ALPHA = 'alpha';
export const BETA = 'beta';
</code>```

_import.js

```<code>import {ALPHA, BETA, GAMMA} from './export_'

console.log("alpha is ", ALPHA);
console.log("beta is", BETA);
console.log("gamma is", GAMMA);
</code>```

Here GAMMA is not defined in _export.js but do not throw any error regarding this in _import.js ?

I was facing this issue as I have accidentally imported a wrong file ( same file name in 2 directories) in import statement but it does not throw any error that the given exported named property is not found in the file.

Is this behavior is correct?

or

Is there any linting rule in linter ( eg. eslint)  available which identifies such mistake and throws error or warning to the developer?

答:
As far as i know, esLint doesnt provide this check out of the box.

You may want to use eslint-plugin-import.

I use it and it throws an error of import/named when a module wasn't found.

For example:

MyModule not found in '../../modules'

examples

ContentLicense: CC BY-SA 3.0

Body:
while checking import/ export feature, it was surprising to see that if a named property is used in import and it is not defined in the exported file than it does not throw any error?

below is the example

_export.js

export const ALPHA = 'alpha';
export const BETA = 'beta';

_import.js

import {ALPHA, BETA, GAMMA} from './export_'

console.log("alpha is ", ALPHA);
console.log("beta is", BETA);
console.log("gamma is", GAMMA);

Here GAMMA is not defined in _export.js but do not throw any error regarding this in _import.js ?

I was facing this issue as I have accidentally imported a wrong file ( same file name in 2 directories) in import statement but it does not throw any error that the given exported named property is not found in the file.

Is this behavior is correct?

or

Is there any linting rule in linter ( eg. eslint)  available which identifies such mistake and throws error or warning to the developer?


问:
ng-repeat - copy of objects rather than direct reference
If I want the object from ng-repeat to be a copy of the actual object in the list, how would I do so?

For example:

```<code><div ng-repeat="thing in model.things">
    <input ng-model="thing.field"/>
    <button> // clicking this button would update that thing </button>
</div>
</code>```

If I type in that input field, it will directly modify the object inside model.things. I would like it to modify a copy of the thing, and then only update the actual one when I click an update button.

I tried doing something like model.getThings() which will angular.copy() the list, but that triggers an infinite loop of $digest when a new thing is added.

How is this best done? Thanks!

答:
You can copy your original object on initialization:

```<code>function YourController() {
    $scope.copyModel = angular.copy(model);
    // ...
}
</code>```

And use copyModel in your ng-repeat

Body:
If I want the object from ng-repeat to be a copy of the actual object in the list, how would I do so?

For example:

    <input ng-model="thing.field"/>
    <button> // clicking this button would update that thing </button>

If I type in that input field, it will directly modify the object inside model.things. I would like it to modify a copy of the thing, and then only update the actual one when I click an update button.

I tried doing something like model.getThings() which will angular.copy() the list, but that triggers an infinite loop of $digest when a new thing is added.

How is this best done? Thanks!

Body:
You can copy your original object on initialization:

function YourController() {
    $scope.copyModel = angular.copy(model);
    // ...
}

And use copyModel in your ng-repeat


问:
How to remove warnings of nullable in Android?
I'm using annotations library supported by Android.
It is useful for checking NullpointerExceptions.
But, it also annoying if I checked the variable if it is null.

In this case:

```<code>@Nullable
String value;

boolean isValid(String target) {
    return (target != null && target.length() > 0);
}

void test() {
    if (isValid(value)) {
        Log.d("TEST", value);
        // Do something.
    }
}
</code>```

In above code, I already checked if 'value' is null, but still got the warning of "It maybe produce NullPointerException".

Is there some annotations that I checked null-type in this function?

答:
In android studio Go to

file-->other settings---> default settings (defaultpreference)--->inspections--->java---> @notnull and nullable Probelms

uncheck it and click ok.

Body:
I'm using annotations library supported by Android.
It is useful for checking NullpointerExceptions.
But, it also annoying if I checked the variable if it is null.

In this case:

@Nullable
String value;

boolean isValid(String target) {
    return (target != null && target.length() > 0);
}

void test() {
    if (isValid(value)) {
        Log.d("TEST", value);
        // Do something.
    }
}

In above code, I already checked if 'value' is null, but still got the warning of "It maybe produce NullPointerException".

Is there some annotations that I checked null-type in this function?


问:
Random rotation and scale on procedural created objects
I am trying to make a procedural city generate but all of the buildings in the same group are facing the same direction (rotated the same) and are the same scale. I am trying to add variation in height and rotation so it looks more random. This is what I have so far but maybe I am going about this all the wrong way. I am new to programming so I appreciate any help you guys could give. Thank you! </p>

```<code>public GameObject[] buildings;
public int mapWidth = 20;
public int mapHeight = 20;
int buildingFootprint = 45;
float randomY = Random.Range(-360f, 360f);

// Procedural Generation
void Start ()
{
    float seed = Random.Range(0, 500);
    for (int h = 0; h < mapHeight; h++)
    {
        for (int w = 0; w < mapWidth; w++)
        {
            int result = (int)(Mathf.PerlinNoise(w/3.0f + seed, h/3.0f + seed) * 50);
            Vector3 pos = new Vector3(w * buildingFootprint, 10, h * buildingFootprint);
            Vector3 rot = new Vector3(0, randomY, 0);

            if (result < 5)
                Instantiate(buildings[0], pos, Quaternion.Euler(rot));
            else if (result < 10)
                Instantiate(buildings[5], pos, Quaternion.Euler(rot));
            else if (result < 15)
                Instantiate(buildings[6], pos, Quaternion.Euler(rot));
            else if (result < 20)
                Instantiate(buildings[1], pos, Quaternion.Euler(rot));
            else if (result < 30)
                Instantiate(buildings[2], pos, Quaternion.Euler(rot));
            else if (result < 40)
                Instantiate(buildings[3], pos, Quaternion.Euler(rot));
            else if (result < 50)
                Instantiate(buildings[4], pos, Quaternion.Euler(rot));
        }
    }

}
</code>```

答:
It's because you set their rotation to Quaternion.identity

The identity rotation (Read Only).

This quaternion corresponds to "no rotation" - the object is perfectly
  aligned with the world or parent axes.

Set it to random rotation like this (I'm assuming you want to rotate them on Y axis):

```<code>// getting random rotation
float randomY = Random.Range(-360f, 360f);

// assigning random rotation to Y axis
Vector3 rot = new Vector3(0, randomY, 0);

// instantiating random building on position `pos` and rotation `rot`, I used `Quaternion.Euler` to convert the Vector3 to Quaternion
Instantiate(buildings[index], pos, Quaternion.Euler(rot));
</code>```

For scaling you need to decide if you want to scale them uniformly or you want to have random scale on every axis. It would look something like this:

```<code>// getting random scale
Vector3 scale = Vector3.one;
if(scaleUniform)
{
    float randomScale = Random.Range(min, max);

    scale = new Vector3(randomScale, randomScale, randomScale);
}
else
{
    scale = new Vector3(Random.Range(min, max), Random.Range(min, max), Random.Range(min, max));
}

// instantiating random building on position `pos` and rotation `rot`, I used `Quaternion.Euler` to convert the Vector3 to Quaternion
GameObject building = Instantiate(buildings[index], pos, Quaternion.Euler(rot));

// set the scale
building.localScale = scale;
</code>```

Ultimately you should end up with a code like this:

```<code>public GameObject[] buildings;
public int mapWidth = 20;
public int mapHeight = 20;
int buildingFootprint = 45;
bool scaleUniform = true;

// Procedural Generation
void Start ()
{
    float seed = Random.Range(0, 500);
    for (int h = 0; h < mapHeight; h++)
    {
        for (int w = 0; w < mapWidth; w++)
        {
            int result = (int)(Mathf.PerlinNoise(w/3.0f + seed, h/3.0f + seed) * 50);
            float randomY = Random.Range(-360f, 360f); // get random rotation for Y axis

            Vector3 pos = new Vector3(w * buildingFootprint, 10, h * buildingFootprint);
            Vector3 rot = new Vector3(0, randomY, 0); // set the random Y rotation to a new Vector3
            Vector3 scale = Vector3.one; // create a new Vector3 for scale

            if(scaleUniform) // scale the object uniformly
            {
                float randomScale = Random.Range(min, max);

                scale = new Vector3(randomScale, randomScale, randomScale);
            }
            else // or scale it randomly on every axis
            {
                scale = new Vector3(Random.Range(min, max), Random.Range(min, max), Random.Range(min, max));
            }

            int index = 0; // declare index here so you dont repeat yourself in ifs

            if (result < 5) // now you only set index value instead of copying and pasting long code in each if else
                index = 0;
            else if (result < 10)
                index = 5;
            else if (result < 15)
                index = 6;
            else if (result < 20)
                index = 1;
            else if (result < 30)
                index = 2;
            else if (result < 40)
                index = 3;
            else if (result < 50)
                index = 4;

            GameObject spawnedBuilding = Instantiate(buildings[index], pos, Quaternion.Euler(rot)); // and finally instantiate the object
            spawnedBuilding.transform.localScale = scale; // and set its rotation
        }
    }

}
</code>```

Body:
I am trying to make a procedural city generate but all of the buildings in the same group are facing the same direction (rotated the same) and are the same scale. I am trying to add variation in height and rotation so it looks more random. This is what I have so far but maybe I am going about this all the wrong way. I am new to programming so I appreciate any help you guys could give. Thank you!

public GameObject[] buildings;
public int mapWidth = 20;
public int mapHeight = 20;
int buildingFootprint = 45;
float randomY = Random.Range(-360f, 360f);

// Procedural Generation
void Start ()
{
    float seed = Random.Range(0, 500);
    for (int h = 0; h < mapHeight; h++)
    {
        for (int w = 0; w < mapWidth; w++)
        {
            int result = (int)(Mathf.PerlinNoise(w/3.0f + seed, h/3.0f + seed) * 50);
            Vector3 pos = new Vector3(w * buildingFootprint, 10, h * buildingFootprint);
            Vector3 rot = new Vector3(0, randomY, 0);

            if (result < 5)
                Instantiate(buildings[0], pos, Quaternion.Euler(rot));
            else if (result < 10)
                Instantiate(buildings[5], pos, Quaternion.Euler(rot));
            else if (result < 15)
                Instantiate(buildings[6], pos, Quaternion.Euler(rot));
            else if (result < 20)
                Instantiate(buildings[1], pos, Quaternion.Euler(rot));
            else if (result < 30)
                Instantiate(buildings[2], pos, Quaternion.Euler(rot));
            else if (result < 40)
                Instantiate(buildings[3], pos, Quaternion.Euler(rot));
            else if (result < 50)
                Instantiate(buildings[4], pos, Quaternion.Euler(rot));
        }
    }

}

Body:
It's because you set their rotation to Quaternion.identity

The identity rotation (Read Only).

This quaternion corresponds to "no rotation" - the object is perfectly
  aligned with the world or parent axes.

Set it to random rotation like this (I'm assuming you want to rotate them on Y axis):

// getting random rotation
float randomY = Random.Range(-360f, 360f);

// assigning random rotation to Y axis
Vector3 rot = new Vector3(0, randomY, 0);

// instantiating random building on position `pos` and rotation `rot`, I used `Quaternion.Euler` to convert the Vector3 to Quaternion
Instantiate(buildings[index], pos, Quaternion.Euler(rot));

For scaling you need to decide if you want to scale them uniformly or you want to have random scale on every axis. It would look something like this:

// getting random scale
Vector3 scale = Vector3.one;
if(scaleUniform)
{
    float randomScale = Random.Range(min, max);

    scale = new Vector3(randomScale, randomScale, randomScale);
}
else
{
    scale = new Vector3(Random.Range(min, max), Random.Range(min, max), Random.Range(min, max));
}

// instantiating random building on position `pos` and rotation `rot`, I used `Quaternion.Euler` to convert the Vector3 to Quaternion
GameObject building = Instantiate(buildings[index], pos, Quaternion.Euler(rot));

// set the scale
building.localScale = scale;

Ultimately you should end up with a code like this:

public GameObject[] buildings;
public int mapWidth = 20;
public int mapHeight = 20;
int buildingFootprint = 45;
bool scaleUniform = true;

// Procedural Generation
void Start ()
{
    float seed = Random.Range(0, 500);
    for (int h = 0; h < mapHeight; h++)
    {
        for (int w = 0; w < mapWidth; w++)
        {
            int result = (int)(Mathf.PerlinNoise(w/3.0f + seed, h/3.0f + seed) * 50);
            float randomY = Random.Range(-360f, 360f); // get random rotation for Y axis

            Vector3 pos = new Vector3(w * buildingFootprint, 10, h * buildingFootprint);
            Vector3 rot = new Vector3(0, randomY, 0); // set the random Y rotation to a new Vector3
            Vector3 scale = Vector3.one; // create a new Vector3 for scale

            if(scaleUniform) // scale the object uniformly
            {
                float randomScale = Random.Range(min, max);

                scale = new Vector3(randomScale, randomScale, randomScale);
            }
            else // or scale it randomly on every axis
            {
                scale = new Vector3(Random.Range(min, max), Random.Range(min, max), Random.Range(min, max));
            }

            int index = 0; // declare index here so you dont repeat yourself in ifs

            if (result < 5) // now you only set index value instead of copying and pasting long code in each if else
                index = 0;
            else if (result < 10)
                index = 5;
            else if (result < 15)
                index = 6;
            else if (result < 20)
                index = 1;
            else if (result < 30)
                index = 2;
            else if (result < 40)
                index = 3;
            else if (result < 50)
                index = 4;

            GameObject spawnedBuilding = Instantiate(buildings[index], pos, Quaternion.Euler(rot)); // and finally instantiate the object
            spawnedBuilding.transform.localScale = scale; // and set its rotation
        }
    }

}


问:
C structure assignment of same address valid?
If I have something like this in my code:

```<code>void f(struct foo *x, struct foo *y)
{
  *x = *y; // structure copy (memcpy?)
}
</code>```

If x and y point to the same address, what happens?

Is this valid code, and what if the compiler converts the assignment into a memcpy call with potentially-invalid operands (they aren't allowed to overlap)?

[Yes, I know I can use "restrict" in this case, but the actual code we found which made us consider this is automatically-generated by bison so we were wondering if it should always be valid and whether the compiler should use memmove or something else which allows overlap..]

答:
This looks perfectly valid to me. Yes, this will result in a sort of memcpy.

Two pointers to struct like that should only either be the same or not overlap at all. So you could do a check if the pointers are equal, before.

(You can certainly trick your code to have a real overlap, but there'd have to be a really special reason to do that.)

ContentLicense: CC BY-SA 2.5

Body:
If I have something like this in my code:

void f(struct foo *x, struct foo *y)
{
  *x = *y; // structure copy (memcpy?)
}

If x and y point to the same address, what happens?

Is this valid code, and what if the compiler converts the assignment into a memcpy call with potentially-invalid operands (they aren't allowed to overlap)?

[Yes, I know I can use "restrict" in this case, but the actual code we found which made us consider this is automatically-generated by bison so we were wondering if it should always be valid and whether the compiler should use memmove or something else which allows overlap..]


问:
Dynamically set the value of ui-sref Angularjs
I have searched for a similar question but the ones that came up seem slightly different.
I am trying to change the ui-sref='' of a link dynamically (this link points to the next section of a wizard form and the next section depends on the selection made on the dropdown list). I am simply trying to set the ui-sref attribute depending on some selection in a select box. I am able to change the ui-sref by binding to a scope attribute which is set when a selection is made. however the link does not work, is this possible at all? thanks

```<code>  <a ui-sref="form.{{url}}" >Next Section</a>
</code>```

and then in my controller, I set the url parameter this way

```<code>switch (option) {
  case 'A': {
    $scope.url = 'sectionA';
  } break;
  case 'B': {
    $scope.url = 'sectionB';
  } break;
}
</code>```

Alternatively, I used directives to get it to work by generating the hyperlink with the desired ui-sref attribute according to the option selected on the select box (drop down).

Hhowever this means I have to re-create the link each time a different option is selected from the selectbox which causes an undesirable flickering effect.
My question is this, is it possible to change the value of the ui-sref as I tried doing above by simpling changing the value of url in my controller or do I have to re-create the entire element using a directive each time a selection is made as I have done below? (just showing this for completeness)

Select option directive (this directive generates the link directive)

```<code>define(['app/js/modules/app', 'app/js/directives/hyperLink'], function (app) {
app.directive('selectUsage', function ($compile) {

    function createLink(scope,element) {
        var newElm = angular.element('<hyper-link></hyper-link>');
        var el = $(element).find('.navLink');
        $(el).html(newElm);
        $compile(newElm)(scope);
    }

    return {

        restrict: 'E',
        templateUrl: '/Client/app/templates/directives/select.html'

        ,link: function (scope, element, attrs) {

            createLink(scope, element);

            element.on('change', function () {
                createLink(scope,element);
            })
        }
    }
})
</code>```

Hyperlink directive

```<code>define(['app/js/modules/app'], function (app) {
app.directive('hyperLink', function () {

    return {
        restrict: 'E',
        templateUrl: '/Client/app/templates/directives/hyperLink.html',
        link: function (scope, element, attrs) { }
    }

})
</code>```

Hyperlink template

```<code><div>
    <button ui-sref="form.{url}}">Next Section</button>
</div>
</code>```

答:
```<code><ul class="dropdown-menu">
  <li ng-repeat="myPair in vm.Pairs track by $index">
     <a ui-sref="buy({myPairIndex:$index})">
          <span class="hidden-sm">{{myPair.pair}}</span>
     </a>
  </li>
</ul>
</code>```

If someone only wants to dynamically set the $stateParams of ui-sref in Angularjs.
Note: In inspect element it will still appear as "buy({myPairIndex:$index})" but $index will be fetched in that state.

Body:
I have searched for a similar question but the ones that came up seem slightly different.
I am trying to change the ui-sref='' of a link dynamically (this link points to the next section of a wizard form and the next section depends on the selection made on the dropdown list). I am simply trying to set the ui-sref attribute depending on some selection in a select box. I am able to change the ui-sref by binding to a scope attribute which is set when a selection is made. however the link does not work, is this possible at all? thanks

  Next Section

and then in my controller, I set the url parameter this way

switch (option) {
  case 'A': {
    $scope.url = 'sectionA';
  } break;
  case 'B': {
    $scope.url = 'sectionB';
  } break;
}

Alternatively, I used directives to get it to work by generating the hyperlink with the desired ui-sref attribute according to the option selected on the select box (drop down).

Hhowever this means I have to re-create the link each time a different option is selected from the selectbox which causes an undesirable flickering effect.
My question is this, is it possible to change the value of the ui-sref as I tried doing above by simpling changing the value of url in my controller or do I have to re-create the entire element using a directive each time a selection is made as I have done below? (just showing this for completeness)

Select option directive (this directive generates the link directive)

define(['app/js/modules/app', 'app/js/directives/hyperLink'], function (app) {
app.directive('selectUsage', function ($compile) {

    function createLink(scope,element) {
        var newElm = angular.element('<hyper-link></hyper-link>');
        var el = $(element).find('.navLink');
        $(el).html(newElm);
        $compile(newElm)(scope);
    }

    return {

        restrict: 'E',
        templateUrl: '/Client/app/templates/directives/select.html'

        ,link: function (scope, element, attrs) {

            createLink(scope, element);

            element.on('change', function () {
                createLink(scope,element);
            })
        }
    }
})

Hyperlink directive

define(['app/js/modules/app'], function (app) {
app.directive('hyperLink', function () {

    return {
        restrict: 'E',
        templateUrl: '/Client/app/templates/directives/hyperLink.html',
        link: function (scope, element, attrs) { }
    }

})

Hyperlink template

    <button ui-sref="form.{url}}">Next Section</button>

Body:
<ul class="dropdown-menu">
  <li ng-repeat="myPair in vm.Pairs track by $index">
     <a ui-sref="buy({myPairIndex:$index})">
          <span class="hidden-sm">{{myPair.pair}}</span>
     </a>
  </li>
</ul>

If someone only wants to dynamically set the $stateParams of ui-sref in Angularjs.
Note: In inspect element it will still appear as "buy({myPairIndex:$index})" but $index will be fetched in that state.


问:
woocommerce product addon not displaying twice on a single page?
Woocommerce Product addons not displaying more than one time on a single page.

I have added product add-ons on both the 2 products but only one (the 1st one) for which the product add on option is displaying but not for the 2nd one. Link : http://halenkocreativeagency.com/new/test/.

答:
I have shared with you screenshot for how to setup the product permalink option as per your questions. Place check the screenshot.

Setps:

```<code>1. Login on "wp-admin" backend.
2. Select the "Settings" Tab from wp-admin backend option.
3. After you can click on "Permalinks" option.
4. Select the option button on "Shop base with category".
5. After Click on "Save Changes" button.
</code>```

I hope that helpful for you.

Body:
I have shared with you screenshot for how to setup the product permalink option as per your questions. Place check the screenshot.

Setps:

1. Login on "wp-admin" backend.
2. Select the "Settings" Tab from wp-admin backend option.
3. After you can click on "Permalinks" option.
4. Select the option button on "Shop base with category".
5. After Click on "Save Changes" button.

I hope that helpful for you.


问:
Django Form ChoiceField range(): 'int' object not iterable
```<code>from django import forms

class SignUpForm(forms.Form):
    birth_day = forms.ChoiceField(choices=range(1,32))
</code>```

I'm getting "Caught TypeError while rendering: 'int' object is not iterable".
https://docs.djangoproject.com/en/dev/ref/models/fields/#field-choices says the choices argument takes iterables such as a list or tuple.

http://docs.python.org/library/functions.html#range says range() creates a list.

Why am I getting an error?

I tried converting the list to str using map() but received different errors.

答:
You need 2 tuples. Use zip built-in function for the same 2 tuples

```<code>from django import forms

class SignUpForm(forms.Form):

    birth_day = models.IntegerField(choices=list(zip(range(1, 32), range(1, 32))), unique=True)
</code>```

Remember (1,32) will create from 1 to 31 !

Body:
from django import forms

class SignUpForm(forms.Form):
    birth_day = forms.ChoiceField(choices=range(1,32))

I'm getting "Caught TypeError while rendering: 'int' object is not iterable".
https://docs.djangoproject.com/en/dev/ref/models/fields/#field-choices says the choices argument takes iterables such as a list or tuple.

http://docs.python.org/library/functions.html#range says range() creates a list.

Why am I getting an error?

I tried converting the list to str using map() but received different errors.

Body:
You need 2 tuples. Use zip built-in function for the same 2 tuples

from django import forms

class SignUpForm(forms.Form):

    birth_day = models.IntegerField(choices=list(zip(range(1, 32), range(1, 32))), unique=True)

Remember (1,32) will create from 1 to 31 !


问:
How to install FFMpeg in WampServer 2.0 (Windows XP)
I need to install the ffmpeg PHP extension on my localhost so I can test few of my scripts but I am having troubles figuring out how to do that.

I have WampServer 2.0 with PHP 5.2.9-2, my OS is Windows XP. Please somebody give me step by step instructions.

I have found some Windows builds here: http://sourceforge.net/projects/ffmpeg-php/files/

But I don't know which one to download and what to do with files.

EDITED:

What I have done so far:

Download ffmpeg_new

Copy php_ffmpeg.dll from the php5 folder to the C:\wamp\bin\php\php5.2.9-2\ext

Copy files from common to the windows/system32 folder

Add extension=php_ffmpeg.dll to php.ini file

Restarted all services (Apache, PHP...)

I am gettings an error after using this code:

```<code>            $extension = 'ffmpeg';
            $extension_soname = 'php_ffmpeg.dll';
            $extension_fullname = PHP_EXTENSION_DIR . "/" . $extension_soname;

            // load extension
            if(false === extension_loaded($extension)) {
                if (false === dl($extension_soname))
                    throw new Exception("Can't load extension $extension_fullname\n");
            }
</code>```

The error:

```<code>Warning: dl() [function.dl]: Not supported in multithreaded Web servers - use extension=ffmpeg.dll in your php.ini in C:\wamp\www\hunnyhive\application\modules\default\controllers\MyAccountController.php on line 314
</code>```

Plus I also get the exception from above.

答:
add this line to your php.ini file</p>

```<code>[PHP_ffmpeg]
extension=php_ffmpeg.dll
</code>```

Body:
I need to install the ffmpeg PHP extension on my localhost so I can test few of my scripts but I am having troubles figuring out how to do that.

I have WampServer 2.0 with PHP 5.2.9-2, my OS is Windows XP. Please somebody give me step by step instructions.

I have found some Windows builds here: http://sourceforge.net/projects/ffmpeg-php/files/

But I don't know which one to download and what to do with files.

EDITED:

What I have done so far:

Download ffmpeg_new

Copy php_ffmpeg.dll from the php5 folder to the C:\wamp\bin\php\php5.2.9-2\ext

Copy files from common to the windows/system32 folder

Add extension=php_ffmpeg.dll to php.ini file

Restarted all services (Apache, PHP...)

I am gettings an error after using this code:

            $extension = 'ffmpeg';
            $extension_soname = 'php_ffmpeg.dll';
            $extension_fullname = PHP_EXTENSION_DIR . "/" . $extension_soname;

            // load extension
            if(false === extension_loaded($extension)) {
                if (false === dl($extension_soname))
                    throw new Exception("Can't load extension $extension_fullname\n");
            }

The error:

Warning: dl() [function.dl]: Not supported in multithreaded Web servers - use extension=ffmpeg.dll in your php.ini in C:\wamp\www\hunnyhive\application\modules\default\controllers\MyAccountController.php on line 314

Plus I also get the exception from above.

Body:
add this line to your php.ini file

[PHP_ffmpeg]
extension=php_ffmpeg.dll


问:
Installed Python package is causing conflict for VirtualEnv but can't find and remove it
I was attempting to install some google modules (cloud and oauth2), was apparently successful in some and not others. Then the Virtualenv I installed them to stop working. When I try to run an iPython notebook the kernel keeps dying. Based on some research, it seems to be due to a conflict from what I installed, but now I can't even find the thing to remove it. Even a pip freeze or pip list command won't work, showing the same error, posted below. Anybody know where I can go to find the google module mentioned in the error so I can get rid of it and go back to how it was before?

```<code>  Traceback (most recent call last):
  File "/Users/my_user_name/.virtualenvs/my_virtualenv/lib/python2.7/site.py", line 703, in <module>
    main()
  File "/Users/my_user_name/.virtualenvs/my_virtualenv/lib/python2.7/site.py", line 683, in main
    paths_in_sys = addsitepackages(paths_in_sys)
  File "/Users/my_user_name/.virtualenvs/my_virtualenv/lib/python2.7/site.py", line 282, in addsitepackages
    addsitedir(sitedir, known_paths)
  File "/Users/my_user_name/.virtualenvs/my_virtualenv/lib/python2.7/site.py", line 204, in addsitedir
    addpackage(sitedir, name, known_paths)
  File "/Users/my_user_name/.virtualenvs/my_virtualenv/lib/python2.7/site.py", line 173, in addpackage
    exec(line)
  File "<string>", line 1, in <module>
KeyError: 'google'
</code>```

This is the same error that repeatedly shows when I try to run an iPython notebook with that kernel. The problems don't exist outside of this virtualenv.

答:
site.addpackage() reads and interprets *.pth files from site-packages directory. Check all files for something unusual.

Or simply destroy and recreate the failing virtual envs.

Body:
I was attempting to install some google modules (cloud and oauth2), was apparently successful in some and not others. Then the Virtualenv I installed them to stop working. When I try to run an iPython notebook the kernel keeps dying. Based on some research, it seems to be due to a conflict from what I installed, but now I can't even find the thing to remove it. Even a pip freeze or pip list command won't work, showing the same error, posted below. Anybody know where I can go to find the google module mentioned in the error so I can get rid of it and go back to how it was before?

  Traceback (most recent call last):
  File "/Users/my_user_name/.virtualenvs/my_virtualenv/lib/python2.7/site.py", line 703, in <module>
    main()
  File "/Users/my_user_name/.virtualenvs/my_virtualenv/lib/python2.7/site.py", line 683, in main
    paths_in_sys = addsitepackages(paths_in_sys)
  File "/Users/my_user_name/.virtualenvs/my_virtualenv/lib/python2.7/site.py", line 282, in addsitepackages
    addsitedir(sitedir, known_paths)
  File "/Users/my_user_name/.virtualenvs/my_virtualenv/lib/python2.7/site.py", line 204, in addsitedir
    addpackage(sitedir, name, known_paths)
  File "/Users/my_user_name/.virtualenvs/my_virtualenv/lib/python2.7/site.py", line 173, in addpackage
    exec(line)
  File "<string>", line 1, in <module>
KeyError: 'google'

This is the same error that repeatedly shows when I try to run an iPython notebook with that kernel. The problems don't exist outside of this virtualenv.


问:
How to get the id of the td based if the text value matches exactly
How to get the id of the td based if the text value matches exactly?

    George
    George2
    George3
    Georg

```

I want the id of "Georg" td4 to get returned?

Body:
How to get the id of the td based if the text value matches exactly?

    George
    George2
    George3
    Georg

I want the id of "Georg" td4 to get returned?

Body: $('td:contains("Georg")').attr(id)


问:
Kamailio Multi Registrar Solution
About me
I am very new to the use of Kamailio solution have basic background in practical application of SIP

Overview

I am tasked with building a Kamailio solution as a Active / Active Registrar

Kamailio Design

Questions

Which modules would you user and why?

Is there any good resources on the web to use?

If User 1 rings User 2 how do we remove the requirement of specifying the IP of the kamaiio server that User2 is registered to?

Is there any config examples that i could use to learn from?

答:
With Multi Registrar Solution it means Configuring Kamailio to support multiple Domains

In order to support multi-Domain you must look into 2 very important kamailio Modules  Registrar Module and  Domain

 Registrar module Details can be found here : http://www.kamailio.org/docs/modules/5.0.x/modules/registrar.html

 Domain Module Details can be found here :
http://www.kamailio.org/docs/modules/5.0.x/modules/domain.html

also you' have to do some changes to  kamailio.cfg which by default restricts the calls to other domain by myself, where myself corrsponds to the local IP/ Domain of the Kamailio instance .

Within kamailio.cfg you'll have to change all  myself to is_uri_host_local().

Title: Kamailio Multi Registrar Solution


问:
Linux command 'll' is not working
I am able to run ll command with my user but not with sudo, it giving me error as command not found!</p>

答:
Create an alias for ll.

```<code>alias ll="ls -al"
</code>```

Title: Linux command 'll' is not working

Body:
Create an alias for ll.

alias ll="ls -al"


问:
NullPointerException in TextView OnclickListener
I am trying to create a register application that lists attendees (in TextView). On Clicking an attendee, it should take to another view. Getting a NullpointerException during runtime at OnclickListener.

Mail View Layout xml :

```<code><TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:textSize="25sp"
    android:textColor="#ffffff"
    android:layout_weight="1"
    android:gravity="center_horizontal"
    android:textStyle="bold"
    android:clickable="true"
    android:text="text1" />
<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:textSize="25sp"
    android:textColor="#ffffff"
    android:layout_weight="1"
    android:gravity="center_horizontal"
    android:textStyle="bold"
    android:clickable="true"
    android:text="text2" />
<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:textSize="25sp"
    android:textColor="#ffffff"
    android:layout_weight="1"
    android:textStyle="bold"
    android:clickable="true"
    android:gravity="center_horizontal"
    android:text="text3" />
</code>```

    OnClick View xml :

```<code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FFFFFF">

<ImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/imageView"
    android:layout_gravity="center_horizontal"
    android:src="@drawable/img1"/>
</code>```

Main Activity :

```<code>public class MenuActivity extends ListActivity {

TextView text1;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_menu);
    text1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            setContentView(R.layout.onclickview);
        }
    });
}
</code>```

}

答:
```<code>public class MenuActivity extends ListActivity {

TextView text1;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_menu);

    ////add your textview id
    text1=(TextView )findViewById(R.id.yourtextviewID);
    text1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            setContentView(R.layout.onclickview);
        }
   });
}
</code>```

Body:
I am trying to create a register application that lists attendees (in TextView). On Clicking an attendee, it should take to another view. Getting a NullpointerException during runtime at OnclickListener.

Mail View Layout xml :

<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:textSize="25sp"
    android:textColor="#ffffff"
    android:layout_weight="1"
    android:gravity="center_horizontal"
    android:textStyle="bold"
    android:clickable="true"
    android:text="text1" />
<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:textSize="25sp"
    android:textColor="#ffffff"
    android:layout_weight="1"
    android:gravity="center_horizontal"
    android:textStyle="bold"
    android:clickable="true"
    android:text="text2" />
<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:textSize="25sp"
    android:textColor="#ffffff"
    android:layout_weight="1"
    android:textStyle="bold"
    android:clickable="true"
    android:gravity="center_horizontal"
    android:text="text3" />

    OnClick View xml :

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FFFFFF">

<ImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/imageView"
    android:layout_gravity="center_horizontal"
    android:src="@drawable/img1"/>

Main Activity :

public class MenuActivity extends ListActivity {

TextView text1;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_menu);
    text1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            setContentView(R.layout.onclickview);
        }
    });
}

}


问:
how to use pos tag as feature in Stanford NER training?
I am trying to use the useTags and related features in training Stanford NER CRF model. However, although I have specified in the .prop file that I will use this feature, CoreAnnotations.PartOfSpeechAnnotation.class does not seem to return anything and hence the training does not use this feature at all. Is there something I did wrong that it wasn't using this feature? Thanks!</p>

答:
You need to specify which column in your training/test data has the pos tag and add the pos tags to the CoNLL.

You specify that column in this part of the properties:

map = word=0,answer=1,tag=2

(for example if you added the tags in the 3rd column)


问:
When I filter it clears my global search on jQuery datatable
I'm using a plugin that I built for datatable for dropdown filter
and I'm using fnFilter for it.

The issue is when I search first let's say I searched for 'test' it
returns one row then when I filter, the filter doesn't do the filtering on
the one row I have on the table but instead it clears my global search
somehow.

Can someone please help me with this?

I think it just fnFilter clears search() on datatable but I don't want to
change fnFilter to search.

答:
I don't have that problem when applying the filter to a column, if you don't provide the column to set the filter to the value passed to the filter will replace the search.

```<code>$(document).ready(function() {
    const dt = $('#example').dataTable({"sPaginationType": "full_numbers"});
    $("#filterbtn").on("click",x=>{
        dt.fnFilter( 'Gecko',0 );//column will not replace search
      dt.fnFilter( 'Camino',1 );//multiple filters are possible
    });
    $("#resetfilterbtn").on("click",x=>{
        dt.fnFilter( '',0 );//reset the filter (does not reset search)
      dt.fnFilter( '',1 );
    });
});
</code>```

Here is a jsfiddle example.

In the jsfiddle example search for 3+ and get 5 rows, then press filter button and get 1 row, then press reset filter button and get 5 rows again.

If you press filter button you'll get 2 rows, no matter what you search you will not get more than 2 rows (search does not reset the filter)

Body:
I don't have that problem when applying the filter to a column, if you don't provide the column to set the filter to the value passed to the filter will replace the search.

$(document).ready(function() {
    const dt = $('#example').dataTable({"sPaginationType": "full_numbers"});
    $("#filterbtn").on("click",x=>{
        dt.fnFilter( 'Gecko',0 );//column will not replace search
      dt.fnFilter( 'Camino',1 );//multiple filters are possible
    });
    $("#resetfilterbtn").on("click",x=>{
        dt.fnFilter( '',0 );//reset the filter (does not reset search)
      dt.fnFilter( '',1 );
    });
});

Here is a jsfiddle example.

In the jsfiddle example search for 3+ and get 5 rows, then press filter button and get 1 row, then press reset filter button and get 5 rows again.

If you press filter button you'll get 2 rows, no matter what you search you will not get more than 2 rows (search does not reset the filter)


问:
Is there a quick way to remove using statements in C#?
Is there a quick way to determine whether you are using certain namespaces in your application. I want to remove all the unneccessary using statements like using System.Reflection and so on, but I need a way to determine if I am using those libraries or not. I know that the tool Resharper does this for you, but is there a quick and dirty and Free way to do this?</p>

答: Visual Studio 2008 will also do this for you, right click in your class file and select "Organize Usings" -> "Remove and Sort".</p>

OwnerDisplayName: Jason

LastEditorDisplayName: Jorge

OwnerDisplayName: CQ


问:
Passing JSON over .ajax() with jQuery
I'm having trouble understanding how to create a jQuery .ajax function to post data (multiple variables) to my php page, then return the information from the PHP page.

```<code>$('#RoomCode').change(function()
{
    //alert($(this).attr('value'));
    var RoomCode = $(this).attr('value');

    //Create JSON Object to send to Ajaxdo
    var toAjax = { "GetRoomCodeParams": [ { "GetRoomCode" : "1", "RoomCode" : RoomCode } ]};
    alert(toAjax);
    $.ajax({
        url: "ajaxdo.php",
        type: "POST",
        dataType: json,
        cache: false,
        data toAjax,
        success: function (response) {

            alert(response);
            $('#RoomInfoCode', '#RoomClassCode').fadeOut();
            $('#RoomInfoCode').empty();
            $('#RoomInfoCode').fadeIn();

        }
    });

});
</code>```

EDIT: Thanks for pointing out the missing colon : (now appended to code)

now i receive missing }  after property list success: (response) {}

i have since cleared ammended success to the following, and still receive this error:

```<code>success: function (response) { }
</code>```

答:
You have a typo:

```<code>data toAjax,
</code>```

should be

```<code>data: toAjax,
</code>```

Title: Passing JSON over .ajax() with jQuery

Body:
I'm having trouble understanding how to create a jQuery .ajax function to post data (multiple variables) to my php page, then return the information from the PHP page.

$('#RoomCode').change(function()
{
    //alert($(this).attr('value'));
    var RoomCode = $(this).attr('value');

    //Create JSON Object to send to Ajaxdo
    var toAjax = { "GetRoomCodeParams": [ { "GetRoomCode" : "1", "RoomCode" : RoomCode } ]};
    alert(toAjax);
    $.ajax({
        url: "ajaxdo.php",
        type: "POST",
        dataType: json,
        cache: false,
        data toAjax,
        success: function (response) {

            alert(response);
            $('#RoomInfoCode', '#RoomClassCode').fadeOut();
            $('#RoomInfoCode').empty();
            $('#RoomInfoCode').fadeIn();

        }
    });

});

EDIT: Thanks for pointing out the missing colon : (now appended to code)

now i receive missing }  after property list success: (response) {}

i have since cleared ammended success to the following, and still receive this error:

success: function (response) { }

Body:
You have a typo:

data toAjax,

should be

data: toAjax,


问:
intellij incorrectly saying no beans of type found for autowired repository
I have created a simple unit test but IntelliJ is incorrectly highlighting it red. marking it as an error

No beans?

As you can see below it passes the test? So it must be Autowired?

答:
All you need to do to make this work is the following code:</p>

```<code>@ComponentScan
public class PriceWatchTest{

    @Autowired
    private PriceWatchJpaRepository priceWatchJpaRepository;
...
...
}
</code>```

Body:
All you need to do to make this work is the following code:

@ComponentScan
public class PriceWatchTest{

    @Autowired
    private PriceWatchJpaRepository priceWatchJpaRepository;
...
...
}

ContentLicense: CC BY-SA 4.0


问:
Reading from a URL in java: when is a request actually sent?
I have an assignment for school that involves writing a simple web crawler that crawls Wikipedia. The assignment stipulates that I can't use any external libraries so I've been playing around with the java.net.URL class. Based on the official tutorial and some code given by my professor I have:

```<code>public static void main(String[] args) {
    System.setProperty("sun.net.client.defaultConnectTimeout", "500");
    System.setProperty("sun.net.client.defaultReadTimeout",    "1000");

    try {
        URL url = new URL(BASE_URL + "/wiki/Physics");
        InputStream is = url.openStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(is));

        String inputLine;
        int lineNum = 0;
        while ((inputLine = br.readLine()) != null && lineNum < 10) {
            System.out.println(inputLine);
            lineNum++;
        }
        is.close();
    }
    catch (MalformedURLException e) {
        System.out.println(e.getMessage());
    }
    catch (IOException e) {
        System.out.println(e.getMessage());
    }
}
</code>```

In addition, the assignment requires that:

Your program should not continuously send requests to wiki.  Your program
  must wait for at least 1 second after every 10 requests

So my question is, where exactly in the above code is the "request" being sent? And how does this connection work? Is the entire webpage being loaded in one go? or is it being downloaded line by line?

I honestly don't really understand much about networking at all so apologies if I'm misunderstanding something fundamental. Any help would be much appreciated.

答:
```<code> InputStream is = url.openStream();
</code>```

at the above line you will be sending request

```<code>BufferedReader br = new BufferedReader(new InputStreamReader(is));
</code>```

at this line getting the input stream and reading.

Calling url.openStream() initiates a new TCP connection to the server that the URL resolves to. An HTTP GET request is then sent over the connection. If all goes right (i.e., 200 OK), the server sends back the HTTP response message that carries the data payload that is served up at the specified URL. You then need to read the bytes from the InputStream that the openStream() method returns in order to retrieve the data payload into your program.

Body:
I have an assignment for school that involves writing a simple web crawler that crawls Wikipedia. The assignment stipulates that I can't use any external libraries so I've been playing around with the java.net.URL class. Based on the official tutorial and some code given by my professor I have:

public static void main(String[] args) {
    System.setProperty("sun.net.client.defaultConnectTimeout", "500");
    System.setProperty("sun.net.client.defaultReadTimeout",    "1000");

    try {
        URL url = new URL(BASE_URL + "/wiki/Physics");
        InputStream is = url.openStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(is));

        String inputLine;
        int lineNum = 0;
        while ((inputLine = br.readLine()) != null && lineNum < 10) {
            System.out.println(inputLine);
            lineNum++;
        }
        is.close();
    }
    catch (MalformedURLException e) {
        System.out.println(e.getMessage());
    }
    catch (IOException e) {
        System.out.println(e.getMessage());
    }
}

In addition, the assignment requires that:

Your program should not continuously send requests to wiki.  Your program
  must wait for at least 1 second after every 10 requests

So my question is, where exactly in the above code is the "request" being sent? And how does this connection work? Is the entire webpage being loaded in one go? or is it being downloaded line by line?

I honestly don't really understand much about networking at all so apologies if I'm misunderstanding something fundamental. Any help would be much appreciated.

Body:
 InputStream is = url.openStream();

at the above line you will be sending request

BufferedReader br = new BufferedReader(new InputStreamReader(is));

at this line getting the input stream and reading.

Calling url.openStream() initiates a new TCP connection to the server that the URL resolves to. An HTTP GET request is then sent over the connection. If all goes right (i.e., 200 OK), the server sends back the HTTP response message that carries the data payload that is served up at the specified URL. You then need to read the bytes from the InputStream that the openStream() method returns in order to retrieve the data payload into your program.


问:
Phppresentation createRichTextShape -How to create a newline
I am using PphPresentation library to create powepoint presentations.

I am trying to create a newline inside of textshape.

This is part of the code

```<code>$currentSlide=$objPHPPresentation->createSlide();

$textRun = $shape->createTextRun('Estado de Fuerza: '.$personal['ef'].' Elementos. '.'Población: '.$personal['pb'].' hab. '.'Faltante: '.$personal['fal'].' Elementos.');
</code>```

And I get something like this:

```<code>Fuerza: 0 Elementos Población: 10987 hab. Faltante: -31 Elementos.
</code>```

But what I want to get is this:

```<code>Fuerza: 0 Elementos

Población: 10987 hab.

Faltante: -31 Elementos.
</code>```

答:
Another option of getting new line while having same font properties for all the lines is to use paragraph:</p>

```<code>$textParagraph = $shape->createParagraph();
$textParagraph->getFont()->setSize(14)->setColor($colorBlack);

$shape->getActiveParagraph()->createTextRun("Estado de Fuerza: ".$personal["ef"]." Elementos.");
$shape->getActiveParagraph()->createBreak();
$shape->getActiveParagraph()->createTextRun("Población: ".$personal["pb"]." hab. ");
$shape->getActiveParagraph()->createBreak();
$shape->getActiveParagraph()->createTextRun("Faltante: ".$personal["fal"]." Elementos.");
</code>```

Body:
I am using PphPresentation library to create powepoint presentations.

I am trying to create a newline inside of textshape.

This is part of the code

$currentSlide=$objPHPPresentation->createSlide();

$textRun = $shape->createTextRun('Estado de Fuerza: '.$personal['ef'].' Elementos. '.'Población: '.$personal['pb'].' hab. '.'Faltante: '.$personal['fal'].' Elementos.');

And I get something like this:

Fuerza: 0 Elementos Población: 10987 hab. Faltante: -31 Elementos.

But what I want to get is this:

Fuerza: 0 Elementos

Población: 10987 hab.

Faltante: -31 Elementos.

Body:
Another option of getting new line while having same font properties for all the lines is to use paragraph:

$textParagraph = $shape->createParagraph();
$textParagraph->getFont()->setSize(14)->setColor($colorBlack);

$shape->getActiveParagraph()->createTextRun("Estado de Fuerza: ".$personal["ef"]." Elementos.");
$shape->getActiveParagraph()->createBreak();
$shape->getActiveParagraph()->createTextRun("Población: ".$personal["pb"]." hab. ");
$shape->getActiveParagraph()->createBreak();
$shape->getActiveParagraph()->createTextRun("Faltante: ".$personal["fal"]." Elementos.");


问:
How to keep code-folding on save in Visual studio code
I am working on some fairly large files in Visual Studio code and to save time I fold away functions and scopes, that I do not want to see. Everytime I save, which I do fairly often just out of habit, all the folds expand again and the current position on screen changes.

Since the only settings I could find were:

```<code>"editor.folding": true,
"editor.showFoldingControls": "mouseover",
</code>```

the question is: How can I keep my folds upon saving?

答:
Thank you for bringing up the extensions Mark. It was indeed an extension: lonefy.vscode-js-css-html-formatter.

Once this was disabled, the folding kept its state after saving.

Body:
I am working on some fairly large files in Visual Studio code and to save time I fold away functions and scopes, that I do not want to see. Everytime I save, which I do fairly often just out of habit, all the folds expand again and the current position on screen changes.

Since the only settings I could find were:

"editor.folding": true,
"editor.showFoldingControls": "mouseover",

the question is: How can I keep my folds upon saving?


答:
In order to run ll with sudo, the user that is sudo'ed (superuser or another user, as specified by the security policy) needs an alias ll='ls -al' in his profile.

Note that even if defined, you may not be allowed to execute it by the security policy. To find out which commands you may execute type sudo -l

Title: Linux command 'll' is not working

Body: I am able to run ll command with my user but not with sudo, it giving me error as command not found!


问:
How to create events from google calendar API
I am working on a web application which is in PHP and javascript.In this application, we store some events in our own database.

Now, what we want is to whenever we create a new event in our app it should
create a duplicate event on the Google calendar of the current logged in User's google calendar.

We can ask our users to generate an API key from their google console.

Is there any way to create a google calendar event via using an API key only and without any other configuration.

thanks

答:
Refer to the PHP quickstart on how to setup the environment:

https://developers.google.com/google-apps/calendar/quickstart/php

Change the scope to Google_Service_Calendar::CALENDAR and delete any stored

```<code>$event = new Google_Service_Calendar_Event(array(
  'summary' => 'Google I/O 2015',
  'location' => '800 Howard St., San Francisco, CA 94103',
  'description' => 'A chance to hear more about Google\'s developer products.',
  'start' => array(
    'dateTime' => '2015-05-28T09:00:00-07:00',
    'timeZone' => 'America/Los_Angeles',
  ),
  'end' => array(
    'dateTime' => '2015-05-28T17:00:00-07:00',
    'timeZone' => 'America/Los_Angeles',
  ),
  'recurrence' => array(
    'RRULE:FREQ=DAILY;COUNT=2'
  ),
  'attendees' => array(
    array('email' => 'lpage@example.com'),
    array('email' => 'sbrin@example.com'),
  ),
  'reminders' => array(
    'useDefault' => FALSE,
    'overrides' => array(
      array('method' => 'email', 'minutes' => 24 * 60),
      array('method' => 'popup', 'minutes' => 10),
    ),
  ),
));

$calendarId = 'primary';
$event = $service->events->insert($calendarId, $event);
printf('Event created: %s\n', $event->htmlLink);
</code>```

Body:
Refer to the PHP quickstart on how to setup the environment:

https://developers.google.com/google-apps/calendar/quickstart/php

Change the scope to Google_Service_Calendar::CALENDAR and delete any stored

$event = new Google_Service_Calendar_Event(array(
  'summary' => 'Google I/O 2015',
  'location' => '800 Howard St., San Francisco, CA 94103',
  'description' => 'A chance to hear more about Google\'s developer products.',
  'start' => array(
    'dateTime' => '2015-05-28T09:00:00-07:00',
    'timeZone' => 'America/Los_Angeles',
  ),
  'end' => array(
    'dateTime' => '2015-05-28T17:00:00-07:00',
    'timeZone' => 'America/Los_Angeles',
  ),
  'recurrence' => array(
    'RRULE:FREQ=DAILY;COUNT=2'
  ),
  'attendees' => array(
    array('email' => 'lpage@example.com'),
    array('email' => 'sbrin@example.com'),
  ),
  'reminders' => array(
    'useDefault' => FALSE,
    'overrides' => array(
      array('method' => 'email', 'minutes' => 24 * 60),
      array('method' => 'popup', 'minutes' => 10),
    ),
  ),
));

$calendarId = 'primary';
$event = $service->events->insert($calendarId, $event);
printf('Event created: %s\n', $event->htmlLink);


问:
SQL query on Google Sheets JSON API v4
I want to send an SQL query to Google Sheets REST API, which returns JSON for values, instead of HTML or JSONP(text)

The API i am talking about is this:
https://developers.google.com/sheets/api/reference/rest/

But i cannot see any Reference for giving SQL query as part of the API.
Is this not possible?

Google Sheets does allow to process SQL query but it is giving me only HTML or some text based JSONP data back, instead of pure json.

The endpoint i am using is this:

GET https://sheets.googleapis.com/v4/spreadsheets/{spreadsheetId}/values/{range}

答:
Check out my SO answer to another question which may contain what you're seeking — https://stackoverflow.com/a/37868852/305689 — be sure to read the actual question above, esp. the tail end of it.

I didn't mention this in the other answer, but the response defaults to JSON, however you can also select HTML or CSV with the tqx variable. See this page in the docs.

Also, I don't believe it works with the spreadsheets.readonly scope yet, so if you do this, read these authorization instructions.

Title: SQL query on Google Sheets JSON API v4


问:
Date Format not working in IOS
I have date picker to select date and display it on a label. I'm trying a format of yyyy-MM-dd. But when I select any date the label does not show the date which I have selected from date picker.

How can I show this format yyyy-MM-dd?

Here is my code:

```<code>datepicker=[[UIDatePicker alloc]init];
datepicker.datePickerMode=UIDatePickerModeDate;
datepicker.backgroundColor = [UIColor grayColor];
[datepicker setValue:[UIColor whiteColor] forKey:@"textColor"];

UIToolbar *toolBar=[[UIToolbar alloc]initWithFrame:CGRectMake(0, self.view.frame.size.height - 216 - 44, self.view.frame.size.width, 44)];
[toolBar setTintColor:[UIColor blackColor]];
UIBarButtonItem *doneBtn=[[UIBarButtonItem alloc]initWithTitle:@"Done" style:UIBarButtonItemStylePlain target:self action:@selector(ShowSelectedDate)];
UIBarButtonItem *space=[[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];
[toolBar setItems:[NSArray arrayWithObjects:doneBtn,space,nil]];

[_DOB setInputView: datepicker];

_DOB.inputAccessoryView =toolBar;

-(void)ShowSelectedDate {
    NSDateFormatter *fromatter=[[NSDateFormatter alloc]init];
    [fromatter setDateFormat:@"yyyy-MM-dd"];
    self.DOB.text=[NSString stringWithFormat:@"%@",[fromatter stringFromDate:datepicker.date]];
    [_DOB resignFirstResponder];
}
</code>```

My date picker looks like this:

答:
You can implement an action method for intercepting the UIControlEventValueChanged of the date picker. Usually this is placed in the view controller class which manages the date picker:

```<code>-(IBAction)dateChanged:(UIDatePicker * )inPicker {
     // applying inPicker.date to your label
}
</code>```

Add the action method to your picker as follows:

```<code>datepicker=[[UIDatePicker alloc]init];
datepicker.datePickerMode=UIDatePickerModeDate;
[datepicker addTarget:self action:@selector(dateChanged:) forControlEvents:UIControlEventValueChanged];
</code>```

Where self is the view controller, which implements dateChanged:. You can also use your ShowSelectedDatemethod for that:

```<code>[datepicker addTarget:self action:@selector(ShowSelectedDate) forControlEvents:UIControlEventValueChanged];
</code>```

Note: Since ShowSelectedDate takes no parameters there is no colon at the end in @selector.

You can also pass the date picker as parameter to ShowSelectedDate:

```<code>-(void)ShowSelectedDate:(UIDatePicker * )datepicker {
    NSDateFormatter *fromatter=[[NSDateFormatter alloc]init];
    [fromatter setDateFormat:@"yyyy-MM-dd"];
    self.DOB.text=[NSString stringWithFormat:@"%@",[fromatter stringFromDate:datepicker.date]];
    [_DOB resignFirstResponder];
}
</code>```

Then you should apply the action with:

```<code>[datepicker addTarget:self action:@selector(ShowSelectedDate:) forControlEvents:UIControlEventValueChanged];
</code>```

Note the additional colon, because the method has now a parameter.

Title: Date Format not working in IOS

Body:
I have date picker to select date and display it on a label. I'm trying a format of yyyy-MM-dd. But when I select any date the label does not show the date which I have selected from date picker.

How can I show this format yyyy-MM-dd?

Here is my code:

datepicker=[[UIDatePicker alloc]init];
datepicker.datePickerMode=UIDatePickerModeDate;
datepicker.backgroundColor = [UIColor grayColor];
[datepicker setValue:[UIColor whiteColor] forKey:@"textColor"];

UIToolbar *toolBar=[[UIToolbar alloc]initWithFrame:CGRectMake(0, self.view.frame.size.height - 216 - 44, self.view.frame.size.width, 44)];
[toolBar setTintColor:[UIColor blackColor]];
UIBarButtonItem *doneBtn=[[UIBarButtonItem alloc]initWithTitle:@"Done" style:UIBarButtonItemStylePlain target:self action:@selector(ShowSelectedDate)];
UIBarButtonItem *space=[[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];
[toolBar setItems:[NSArray arrayWithObjects:doneBtn,space,nil]];

[_DOB setInputView: datepicker];

_DOB.inputAccessoryView =toolBar;

-(void)ShowSelectedDate {
    NSDateFormatter *fromatter=[[NSDateFormatter alloc]init];
    [fromatter setDateFormat:@"yyyy-MM-dd"];
    self.DOB.text=[NSString stringWithFormat:@"%@",[fromatter stringFromDate:datepicker.date]];
    [_DOB resignFirstResponder];
}

My date picker looks like this:

Body:
You can implement an action method for intercepting the UIControlEventValueChanged of the date picker. Usually this is placed in the view controller class which manages the date picker:

-(IBAction)dateChanged:(UIDatePicker * )inPicker {
     // applying inPicker.date to your label
}

Add the action method to your picker as follows:

datepicker=[[UIDatePicker alloc]init];
datepicker.datePickerMode=UIDatePickerModeDate;
[datepicker addTarget:self action:@selector(dateChanged:) forControlEvents:UIControlEventValueChanged];

Where self is the view controller, which implements dateChanged:. You can also use your ShowSelectedDatemethod for that:

[datepicker addTarget:self action:@selector(ShowSelectedDate) forControlEvents:UIControlEventValueChanged];

Note: Since ShowSelectedDate takes no parameters there is no colon at the end in @selector.

You can also pass the date picker as parameter to ShowSelectedDate:

-(void)ShowSelectedDate:(UIDatePicker * )datepicker {
    NSDateFormatter *fromatter=[[NSDateFormatter alloc]init];
    [fromatter setDateFormat:@"yyyy-MM-dd"];
    self.DOB.text=[NSString stringWithFormat:@"%@",[fromatter stringFromDate:datepicker.date]];
    [_DOB resignFirstResponder];
}

Then you should apply the action with:

[datepicker addTarget:self action:@selector(ShowSelectedDate:) forControlEvents:UIControlEventValueChanged];

Note the additional colon, because the method has now a parameter.


问:
Textarea auto height, the same height maintained while refreshing on the page
I defined Textarea auto height.
If data keyed on textarea auto height will be working fine. and I stored localstorage in browser. when refreshing the page height will changed to the normal height and text will be hidden.
I need to the same height when refreshing the page. Please guide me. Thanks in advance. sorry for poor english.

  function saveEdits1() {
    var editElem = document.getElementById("post_title");
    var userVersion1 = editElem.value;
    sessionStorage.userEdits1 = userVersion1;
  }

  function checkEdits() {
    if( sessionStorage.userEdits1!=null){
    document.getElementById("post_title").value = sessionStorage.userEdits1;
    }
}
     function textAreaAdjust(txt) {
            txt.style.height = "10px";
            txt.style.height = (25+txt.scrollHeight)+"px";
        }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body onload="checkEdits()">
           <div class="container">
                <div class="cont_group1">
                  <div class="form-group">
                       <textarea cols="33" onkeydown="textAreaAdjust(this)" style="overflow:hidden"  name="post_title" id="post_title" onblur="saveEdits1()" class="form-control"></textarea>
                  </div>
                </div>
             </div>
             </body></code>```

答:
make a fake event to trigger key event in your textarea.

        function saveEdits1() {
          var editElem = document.getElementById("post_title");
          var userVersion1 = editElem.value;
          sessionStorage.userEdits1 = userVersion1;
        }

        function checkEdits() {
          if (sessionStorage.userEdits1 != null) {
      document.getElementById("post_title").value = sessionStorage.userEdits1;

            var ev = new Event("keypress", {"bubbles":true, "cancelable":false});
            var el = document.getElementById("post_title");
                el.addEventListener("keypress",textAreaAdjust(el));
                el.dispatchEvent(ev)
          }
        }
        function textAreaAdjust(txt) {
          txt.style.height = "10px";
          txt.style.height = (25 + txt.scrollHeight) + "px";
        }
  ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">

<head>
    <title>Starfleet</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">

</head>
<body onload="checkEdits()">
  <div class="container">
    <div class="cont_group1">
      <div class="form-group">
        <textarea cols="33" onkeydown="textAreaAdjust(this)" style="overflow:hidden"  name="post_title" id="post_title" onblur="saveEdits1()" class="form-control"></textarea>
      </div>
    </div>
  </div>
</body>

</html></code>```

Body:
I defined Textarea auto height.
If data keyed on textarea auto height will be working fine. and I stored localstorage in browser. when refreshing the page height will changed to the normal height and text will be hidden.
I need to the same height when refreshing the page. Please guide me. Thanks in advance. sorry for poor english.

  function saveEdits1() {
    var editElem = document.getElementById("post_title");
    var userVersion1 = editElem.value;
    sessionStorage.userEdits1 = userVersion1;
  }

  function checkEdits() {
    if( sessionStorage.userEdits1!=null){
    document.getElementById("post_title").value = sessionStorage.userEdits1;
    }
}
     function textAreaAdjust(txt) {
            txt.style.height = "10px";
            txt.style.height = (25+txt.scrollHeight)+"px";
        }

                       <textarea cols="33" onkeydown="textAreaAdjust(this)" style="overflow:hidden"  name="post_title" id="post_title" onblur="saveEdits1()" class="form-control"></textarea>

Body:
make a fake event to trigger key event in your textarea.

        function saveEdits1() {
          var editElem = document.getElementById("post_title");
          var userVersion1 = editElem.value;
          sessionStorage.userEdits1 = userVersion1;
        }

        function checkEdits() {
          if (sessionStorage.userEdits1 != null) {
      document.getElementById("post_title").value = sessionStorage.userEdits1;

            var ev = new Event("keypress", {"bubbles":true, "cancelable":false});
            var el = document.getElementById("post_title");
                el.addEventListener("keypress",textAreaAdjust(el));
                el.dispatchEvent(ev)
          }
        }
        function textAreaAdjust(txt) {
          txt.style.height = "10px";
          txt.style.height = (25 + txt.scrollHeight) + "px";
        }

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

<head>
    <title>Starfleet</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">

</head>
<body onload="checkEdits()">
  <div class="container">
    <div class="cont_group1">
      <div class="form-group">
        <textarea cols="33" onkeydown="textAreaAdjust(this)" style="overflow:hidden"  name="post_title" id="post_title" onblur="saveEdits1()" class="form-control"></textarea>
      </div>
    </div>
  </div>
</body>

</html>


问:
Why won't my function return largest even if numbers are negative
I need to create a function that returns the largest even number in a list. I created this but it doesn't work for negative numbers and I'm not sure why.</p>

```<code>def largest_even(list_int):
large = False
print(list_int)
for i in list_int:
    if i % 2 == 0:
        i = large
for i in list_int:
    if i % 2 == 0:
        if i > large:
            large = i
return large
</code>```

答:
Why are you initializing large with False? I think you don't need to do that.
and the second error is at sixth line (i = large). it should be (large = i), as you want to store the first occurring even number to a variable and not the variable at that position in list.</p>

Body:
I need to create a function that returns the largest even number in a list. I created this but it doesn't work for negative numbers and I'm not sure why.

def largest_even(list_int):
large = False
print(list_int)
for i in list_int:
    if i % 2 == 0:
        i = large
for i in list_int:
    if i % 2 == 0:
        if i > large:
            large = i
return large


问:
Is there an actual way to launch developer settings directly?
I checked the official settings page on the developer website, I checked google, there seems to be no way to programmatically launch android the developer settings. How do apps like this do that?</p>

答:
You can use this code:

```<code>startActivityForResult(new Intent(android.provider.Settings.ACTION_APPLICATION_DEVELOPMENT_SETTINGS), 0);
</code>```

For more settings ACTIONS you can pass through documentation here or in particular here.

Body:
You can use this code:

startActivityForResult(new Intent(android.provider.Settings.ACTION_APPLICATION_DEVELOPMENT_SETTINGS), 0);

For more settings ACTIONS you can pass through documentation here or in particular here.


问:
How to disable dates in jDatePicker Java
This is probably very easy but I could not find a solution.

I have two jDatePickers generated using the code below (using jdatepicker 1.3.4 jar).

```<code>    UtilDateModel model = new UtilDateModel();
    Properties p = new Properties();
    p.put( "text.today", "Today" );
    p.put( "text.month", "Month" );
    p.put( "text.year", "Year" );
    JDatePanelImpl datePanel = new JDatePanelImpl( model, p );
    JDatePickerImpl datePicker1 = new JDatePickerImpl( datePanel, new DateComponentFormatter() );

    UtilDateModel model2 = new UtilDateModel();
    Properties p2 = new Properties();
    p2.put( "text.today", "Today" );
    p2.put( "text.month", "Month" );
    p2.put( "text.year", "Year" );
    JDatePanelImpl datePanelTo = new JDatePanelImpl( model2, p2 );
    JDatePickerImpl datePicker2 = new JDatePickerImpl( datePanelTo, new DateComponentFormatter() );

    datePicker1.addPropertyChangeListener( new PropertyChangeListener()
    {

        @Override
        public void propertyChange( PropertyChangeEvent arg0 )
        {
            //code to disable
        }
    } );
</code>```

I want to disable the dates in datepicker2 so that it cannot select dates before the selected date in datepicker1. What should go into the event listener?

答:
you can check out this..</p>

```<code>   datePicker2.getComponent(1).setEnabled(false);
</code>```

Body:
This is probably very easy but I could not find a solution.

I have two jDatePickers generated using the code below (using jdatepicker 1.3.4 jar).

    UtilDateModel model = new UtilDateModel();
    Properties p = new Properties();
    p.put( "text.today", "Today" );
    p.put( "text.month", "Month" );
    p.put( "text.year", "Year" );
    JDatePanelImpl datePanel = new JDatePanelImpl( model, p );
    JDatePickerImpl datePicker1 = new JDatePickerImpl( datePanel, new DateComponentFormatter() );

    UtilDateModel model2 = new UtilDateModel();
    Properties p2 = new Properties();
    p2.put( "text.today", "Today" );
    p2.put( "text.month", "Month" );
    p2.put( "text.year", "Year" );
    JDatePanelImpl datePanelTo = new JDatePanelImpl( model2, p2 );
    JDatePickerImpl datePicker2 = new JDatePickerImpl( datePanelTo, new DateComponentFormatter() );

    datePicker1.addPropertyChangeListener( new PropertyChangeListener()
    {

        @Override
        public void propertyChange( PropertyChangeEvent arg0 )
        {
            //code to disable
        }
    } );

I want to disable the dates in datepicker2 so that it cannot select dates before the selected date in datepicker1. What should go into the event listener?

Body:
you can check out this..

   datePicker2.getComponent(1).setEnabled(false);


问:
Linux command 'll' is not working
I am able to run ll command with my user but not with sudo, it giving me error as command not found!</p>

答:
That's expected because ll is defined in your profile (.bashrc in Ubuntu, for instance).

```<code>grep "alias ll" ~/.bashrc
alias ll='ls -alF'
</code>```

Your .bashrc will not run when you sudo.

Title: Linux command 'll' is not working

Body:
That's expected because ll is defined in your profile (.bashrc in Ubuntu, for instance).

grep "alias ll" ~/.bashrc
alias ll='ls -alF'

Your .bashrc will not run when you sudo.


问:
creating a dictionary with two lists when a key should have two values in python
hi I have two lists,

```<code>list1
['PO', 'NA', 'PO']

list2
['Post Office', 'Not Available', 'Post area']
</code>```

Iam trying to get a dictionary using this two lists
I tried, my_dict=dict(zip(list1,list2))
it gives,

```<code> {'NA': 'Not Available', 'PO': 'Post area'}
</code>```

but my expected output is,

```<code> {'NA': 'Not Available', 'PO': ['Post area','Post Office']}
</code>```

pls help

答:
I think it can be usefull for you also.

```<code>list1 = ['PO', 'NA', 'PO', 'TCS', 'TCS']
list2 = ['Post Office', 'Not Available', 'Post area', 'Track Complaint Status', 'Tata Consultancy Service', 'Tata Consultancy Service']

output_dict = {}

for index, value in enumerate(list1):
     if not value in output_dict:
          output_dict.update({value:list2[index]})
     else:
          temp_list = [list2[index]]
          temp_list.append(output_dict[value])
          output_dict.update({value:temp_list})
 print(output_dict)
</code>```

output :- {'NA': 'Not Available', 'PO': ['Post area', 'Post Office'], 'TCS': ['Tata Consultancy Service', 'Tata Consultancy Service']}

In this program no matter duplicate values in list2 and length too. You can modify this code according your exact problem.

Body:
hi I have two lists,

list1
['PO', 'NA', 'PO']

list2
['Post Office', 'Not Available', 'Post area']

Iam trying to get a dictionary using this two lists
I tried, my_dict=dict(zip(list1,list2))
it gives,

 {'NA': 'Not Available', 'PO': 'Post area'}

but my expected output is,

 {'NA': 'Not Available', 'PO': ['Post area','Post Office']}

pls help

Body:
I think it can be usefull for you also.

list1 = ['PO', 'NA', 'PO', 'TCS', 'TCS']
list2 = ['Post Office', 'Not Available', 'Post area', 'Track Complaint Status', 'Tata Consultancy Service', 'Tata Consultancy Service']

output_dict = {}

for index, value in enumerate(list1):
     if not value in output_dict:
          output_dict.update({value:list2[index]})
     else:
          temp_list = [list2[index]]
          temp_list.append(output_dict[value])
          output_dict.update({value:temp_list})
 print(output_dict)

output :- {'NA': 'Not Available', 'PO': ['Post area', 'Post Office'], 'TCS': ['Tata Consultancy Service', 'Tata Consultancy Service']}

In this program no matter duplicate values in list2 and length too. You can modify this code according your exact problem.


问:
Print statement in class getting executed even though there is no class instance/object
content of my python file

```<code>class myclass(object):
    def __init__(self):
        pass
    def myfun(self):
        pass
    print ("hello world")
</code>```

Output on executing file

```<code>hello world
</code>```

Query

```<code>since I did not create object of class . How's it still able to print "hello world"
</code>```

答:
The class body executes at class definition time, and that's how the language is designed.

From section 9.3.1 Class Definition syntax:

In practice, the statements inside a class definition will usually be function definitions, but other statements are allowed, and sometimes useful.

That is simply how the execution model works in Python, so there's not much more to say about it.

as per my understanding...anything class can not run until we call it by creating a object

Simply a misunderstanding.  This applies for def, i.e. function blocks, but not for class blocks.

Body:
content of my python file

class myclass(object):
    def __init__(self):
        pass
    def myfun(self):
        pass
    print ("hello world")

Output on executing file

hello world

Query

since I did not create object of class . How's it still able to print "hello world"


问:
FATAL EXCEPTION: main KotlinNullPointerException
This is my first time building an android application. However when i run the app on my Virtual Device, it stopped working and keeps crashing. The error says something about null pointer exception. This is my first time using Kotlin and I coded in Java and changed to Kotlin.

```<code> override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_add_sales)

    val date: EditText? = null
    val changeDate: CheckBox? = null
    val yes: RadioButton? = null
    val no: RadioButton? = null

    date!!.setText("15-11-2017")
    date.isEnabled = false

    val button2 = findViewById<View>(R.id.btnSubmit) as Button
    button2.setOnClickListener {
        var name = findViewById<View>(R.id.name) as EditText
        var cost = findViewById<View>(R.id.cost) as EditText
        val itemcost = Integer.parseInt(cost!!.text.toString())
        var price = findViewById<View>(R.id.price) as EditText
        val itemprice = Integer.parseInt(price!!.text.toString())
        var qty = findViewById<View>(R.id.quantity) as EditText
        var chgDate = false
        var discount = false
        val toast = Toast(applicationContext)
        if (itemprice < itemcost) {
            price!!.error = "Selling price cannot be lower than item price!"
        } else {
            if (changeDate!!.isChecked) {
                chgDate = true
                date.isEnabled = true
            }
            if (yes!!.isChecked) {
                discount = true
            }
        }
        Toast.makeText(this@AddSales, "Item Name: " + name!!.text + "\n" + "Cost: " + cost!!.text + "\n" + "Item Price: " + price!!.text + "\n" + "Quantity: " + qty!!.text + "Date: " + date + "Staff Discount: " + discount, Toast.LENGTH_SHORT).show()
    }

}
</code>```

and the error is:

11-17 06:23:34.603 3540-3540/com.example.ruiru.salestracker
  E/AndroidRuntime: FATAL EXCEPTION: main
                                                                                Process: com.example.ruiru.salestracker, PID: 3540
                                                                                java.lang.RuntimeException: Unable to start activity
  ComponentInfo{com.example.ruiru.salestracker/com.example.ruiru.salestracker.AddSales}:
  kotlin.KotlinNullPointerException
                                                                                at
  android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2817)
                                                                                at
  android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892)
                                                                                at android.app.ActivityThread.-wrap11(Unknown Source:0)
                                                                                at
  android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:105)
                                                                                at android.os.Looper.loop(Looper.java:164)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:6541)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at
  com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
                                                                                Caused by: kotlin.KotlinNullPointerException
                                                                                at com.example.ruiru.salestracker.AddSales.onCreate(AddSales.kt:25)
                                                                                at android.app.Activity.performCreate(Activity.java:6975)
                                                                                at
  android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1213)
                                                                                at
  android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2770)
                                                                                at
  android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892)
                                                                                at android.app.ActivityThread.-wrap11(Unknown Source:0)
                                                                                at
  android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:105)
                                                                                at android.os.Looper.loop(Looper.java:164)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:6541)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at
  com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)

答:
Because your date EditText is null.Before use editText initialise editText like this

```<code>var date = findViewById<View>(R.id.date) as? EditText
</code>```

then set the value of date

```<code>date?.setText("15-11-2017")
date?.isEnabled = false
</code>```

Body:
This is my first time building an android application. However when i run the app on my Virtual Device, it stopped working and keeps crashing. The error says something about null pointer exception. This is my first time using Kotlin and I coded in Java and changed to Kotlin.

 override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_add_sales)

    val date: EditText? = null
    val changeDate: CheckBox? = null
    val yes: RadioButton? = null
    val no: RadioButton? = null

    date!!.setText("15-11-2017")
    date.isEnabled = false

    val button2 = findViewById<View>(R.id.btnSubmit) as Button
    button2.setOnClickListener {
        var name = findViewById<View>(R.id.name) as EditText
        var cost = findViewById<View>(R.id.cost) as EditText
        val itemcost = Integer.parseInt(cost!!.text.toString())
        var price = findViewById<View>(R.id.price) as EditText
        val itemprice = Integer.parseInt(price!!.text.toString())
        var qty = findViewById<View>(R.id.quantity) as EditText
        var chgDate = false
        var discount = false
        val toast = Toast(applicationContext)
        if (itemprice < itemcost) {
            price!!.error = "Selling price cannot be lower than item price!"
        } else {
            if (changeDate!!.isChecked) {
                chgDate = true
                date.isEnabled = true
            }
            if (yes!!.isChecked) {
                discount = true
            }
        }
        Toast.makeText(this@AddSales, "Item Name: " + name!!.text + "\n" + "Cost: " + cost!!.text + "\n" + "Item Price: " + price!!.text + "\n" + "Quantity: " + qty!!.text + "Date: " + date + "Staff Discount: " + discount, Toast.LENGTH_SHORT).show()
    }

}

and the error is:

11-17 06:23:34.603 3540-3540/com.example.ruiru.salestracker
  E/AndroidRuntime: FATAL EXCEPTION: main
                                                                                Process: com.example.ruiru.salestracker, PID: 3540
                                                                                java.lang.RuntimeException: Unable to start activity
  ComponentInfo{com.example.ruiru.salestracker/com.example.ruiru.salestracker.AddSales}:
  kotlin.KotlinNullPointerException
                                                                                at
  android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2817)
                                                                                at
  android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892)
                                                                                at android.app.ActivityThread.-wrap11(Unknown Source:0)
                                                                                at
  android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:105)
                                                                                at android.os.Looper.loop(Looper.java:164)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:6541)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at
  com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
                                                                                Caused by: kotlin.KotlinNullPointerException
                                                                                at com.example.ruiru.salestracker.AddSales.onCreate(AddSales.kt:25)
                                                                                at android.app.Activity.performCreate(Activity.java:6975)
                                                                                at
  android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1213)
                                                                                at
  android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2770)
                                                                                at
  android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892)
                                                                                at android.app.ActivityThread.-wrap11(Unknown Source:0)
                                                                                at
  android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:105)
                                                                                at android.os.Looper.loop(Looper.java:164)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:6541)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at
  com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)

Body:
Because your date EditText is null.Before use editText initialise editText like this

var date = findViewById<View>(R.id.date) as? EditText

then set the value of date

date?.setText("15-11-2017")
date?.isEnabled = false