问:
Android Studio - passing an ArrayList through an intent and populate a ListView
i'm tying to populate a ListView with an Array that i get from another activity.
The ListView Activity crashes with the following error:

Caused by: java.lang.NullPointerException: Attempt to invoke interface
  method 'int java.util.List.size()' on a null object reference

this is my ListView class:

```<code>public class CarrinhoActivity extends Activity {

    private ListView lv;

    @Override
    public void onCreate(Bundle saveInstanceState) {
        super.onCreate(saveInstanceState);
        setContentView(R.layout.activity_carrinho);

       lv = (ListView) findViewById(R.id.ListViewCarrinho);

        ArrayList<String> lista_carrinho = getIntent().getStringArrayListExtra("lista_carrinho");

        ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(
                this,
                android.R.layout.simple_list_item_1,
                lista_carrinho );

        lv.setAdapter(arrayAdapter);

    }
}
</code>```

the error points to line 37 : where  lv.setAdapter(arrayAdapter); is

答:
before you go to this activity convert list to json and then pass this json

```<code>intent.putExtra("myList",new Gson().toJson(lista_carrinho));
</code>```

and then at your second activity
pull the string and convert it to ArrayList then apply it to adapter

Body:
i'm tying to populate a ListView with an Array that i get from another activity.
The ListView Activity crashes with the following error:

Caused by: java.lang.NullPointerException: Attempt to invoke interface
  method 'int java.util.List.size()' on a null object reference

this is my ListView class:

public class CarrinhoActivity extends Activity {

    private ListView lv;

    @Override
    public void onCreate(Bundle saveInstanceState) {
        super.onCreate(saveInstanceState);
        setContentView(R.layout.activity_carrinho);

       lv = (ListView) findViewById(R.id.ListViewCarrinho);

        ArrayList<String> lista_carrinho = getIntent().getStringArrayListExtra("lista_carrinho");

        ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(
                this,
                android.R.layout.simple_list_item_1,
                lista_carrinho );

        lv.setAdapter(arrayAdapter);

    }
}

the error points to line 37 : where  lv.setAdapter(arrayAdapter); is

Body:
before you go to this activity convert list to json and then pass this json

intent.putExtra("myList",new Gson().toJson(lista_carrinho));

and then at your second activity
pull the string and convert it to ArrayList then apply it to adapter


来源: stackexchange

问:
How to pass parameter from ActionResult to JsonResult?
How can I pass the Id parameter(I already pass in the Id parameter) from ActionResult to JsonResult? Because now I cannot pass in the Id data to JsonResult parameter, so it cannot hit the following JsonResult code.

I using angularjs to display the List of table.

```<code>[HttpGet]
public ActionResult ManageCustomerStocks(Int64 Id)
{
    return View();
}

public JsonResult GetStocksByCustomerId(Int64 Id)
{
   List<CustomerStocksVM> model = new List<CustomerStocksVM>();
   var stocks = _repositories.GetStocksByClientProfileId(Id);

   var result = from stock in stocks
               select new StocksVM()
               {
                   Code = stock.Code,
                    Name = stock.Name
               };

    model = result.ToList();

    return Json(new
    {
        customerstocks = model
    },JsonRequestBehavior.AllowGet);
}
</code>```

Javascript:

```<code>var myApp = angular.module('myApp', []);
myApp.controller('MyCtrl', ['$scope', '$http', function ($scope, $http) {

    $scope.reverse = true;
    $scope.sortBy = function (propertyName) {
        $scope.reverse = ($scope.propertyName === propertyName) ? !$scope.reverse : false;
        $scope.propertyName = propertyName;
    };

    $http({
        method: 'POST',
        url: 'GetStocksByCustomer'
    })
    .then(function (response) {
        console.log(response);
        $scope.customerstocks = response.data.customerstocks ;

    }, function (error) {
        console.log(error);
    });
}]);
</code>```

答:
```<code> $http({
        url: 'request-url',
        method: "POST",
        data: { 'id' : urId }
    })
    .then(function(response) {
            // success
    },
    function(response) { // optional
            // failed
    });
</code>```

ContentLicense: CC BY-SA 3.0

Body:
How can I pass the Id parameter(I already pass in the Id parameter) from ActionResult to JsonResult? Because now I cannot pass in the Id data to JsonResult parameter, so it cannot hit the following JsonResult code.

I using angularjs to display the List of table.

[HttpGet]
public ActionResult ManageCustomerStocks(Int64 Id)
{
    return View();
}

public JsonResult GetStocksByCustomerId(Int64 Id)
{
   List<CustomerStocksVM> model = new List<CustomerStocksVM>();
   var stocks = _repositories.GetStocksByClientProfileId(Id);

   var result = from stock in stocks
               select new StocksVM()
               {
                   Code = stock.Code,
                    Name = stock.Name
               };

    model = result.ToList();

    return Json(new
    {
        customerstocks = model
    },JsonRequestBehavior.AllowGet);
}

Javascript:

var myApp = angular.module('myApp', []);
myApp.controller('MyCtrl', ['$scope', '$http', function ($scope, $http) {

    $scope.reverse = true;
    $scope.sortBy = function (propertyName) {
        $scope.reverse = ($scope.propertyName === propertyName) ? !$scope.reverse : false;
        $scope.propertyName = propertyName;
    };

    $http({
        method: 'POST',
        url: 'GetStocksByCustomer'
    })
    .then(function (response) {
        console.log(response);
        $scope.customerstocks = response.data.customerstocks ;

    }, function (error) {
        console.log(error);
    });
}]);


问:
How to explain the reverse of a sequence by slice notation a[::-1]
From the python.org tutorial

Slice indices have useful defaults; an omitted first index defaults to zero, an omitted second index defaults to the size of the string being sliced.

```<code>>>> a = "hello"
>>> print(a[::-1])
olleh
</code>```

As the tutorial says a[::-1] should equals to a[0:5:-1]

but a[0:5:-1] is empty as follows:

```<code>>>> print(len(a[0:5:-1]))
0
</code>```

The question is not a duplicate of explain-slice-notation. That question is about the general use of slicing in python.

答: a[0:5:-1] does not make much sense, since when you use this notation the indices mean: a[start:end:step]. When you use a negative step your end value needs to be at an "earlier" position than your start value.

Body:
From the python.org tutorial

Slice indices have useful defaults; an omitted first index defaults to zero, an omitted second index defaults to the size of the string being sliced.

>>> a = "hello"
>>> print(a[::-1])
olleh

As the tutorial says a[::-1] should equals to a[0:5:-1]

but a[0:5:-1] is empty as follows:

>>> print(len(a[0:5:-1]))
0

The question is not a duplicate of explain-slice-notation. That question is about the general use of slicing in python.


问:
Error Handling in AngularJs and servlets
I am currently working on some project where I am writing UI code in angularjs.
I am stuck at framing the error handling.

The scenario is: I am writing some forms in angularJS. inside the controller I am making several $http calls which eventually call the servlets defined.

I need to notify the user about the success/failure of the servlets.

How can I achieve this?

Also, how can I handle the errors in this scenario?

For ex. when I submit the form below function gets executed:

```<code>`$scope.submitForm = function(form) {
            console.log("--> Submitting form");
            if(confirm("Are you sure to finish?")){
                $http({
                    method  : 'POST',
                    url     : '/XMLParser',
                    dataType: 'JSON',
                    data    : JSON.stringify($scope.form), //forms user object
                    headers : {'Content-Type': 'application/x-www-form-urlencoded'}
                }).success(function(data) {
                    console.log(data);
                    if (data.errors) {
                        // Showing errors.
                        $scope.errorName = data.errors.name;
                        $scope.errorUserName = data.errors.username;
                        $scope.errorEmail = data.errors.email;
                    } else {
                        $scope.message = data.message;
                    }
                    alert("successful");
                });
                $scope.redirectToHome();
            }
        };`
</code>```

The servlet /XMLParser will either successfully executed or may produce some errors. How can I handle those?

答:
```<code>//Hope this could make sense
$http.get('your api url').then(success, failure);

function success(){
//your code when request respond success
};

function failure(){
//your code when request respond failure
};
</code>```

Body:
I am currently working on some project where I am writing UI code in angularjs.
I am stuck at framing the error handling.

The scenario is: I am writing some forms in angularJS. inside the controller I am making several $http calls which eventually call the servlets defined.

I need to notify the user about the success/failure of the servlets.

How can I achieve this?

Also, how can I handle the errors in this scenario?

For ex. when I submit the form below function gets executed:

`$scope.submitForm = function(form) {
            console.log("--> Submitting form");
            if(confirm("Are you sure to finish?")){
                $http({
                    method  : 'POST',
                    url     : '/XMLParser',
                    dataType: 'JSON',
                    data    : JSON.stringify($scope.form), //forms user object
                    headers : {'Content-Type': 'application/x-www-form-urlencoded'}
                }).success(function(data) {
                    console.log(data);
                    if (data.errors) {
                        // Showing errors.
                        $scope.errorName = data.errors.name;
                        $scope.errorUserName = data.errors.username;
                        $scope.errorEmail = data.errors.email;
                    } else {
                        $scope.message = data.message;
                    }
                    alert("successful");
                });
                $scope.redirectToHome();
            }
        };`

The servlet /XMLParser will either successfully executed or may produce some errors. How can I handle those?


问:
Unable to open Visual Studio Command Prompt pragmatically using VS 2015
I want to run visual studios command programmatically.I have tried the above code but no help.All I am getting is a command prompt with my project`s directory open.

I have used Execute("VS140COMNTOOLS") as input.

```<code> private void Execute(string vsEnvVar) {

        var vsInstallPath = Environment.GetEnvironmentVariable(vsEnvVar);

        if (Directory.Exists(vsInstallPath)) {
            var filePath = vsInstallPath + "vsvars32.bat";
            if (File.Exists(filePath)) {
                //start vs command process
                Process proc = new Process();

                var command = Environment.GetEnvironmentVariable("ComSpec");
                command = @"" + command + @"";

                //var batfile = @"E:\Test\vstest.bat";
                var args = string.Format("/S/K \" \"{0}\" \"", filePath);

                proc.StartInfo.FileName = command;
                proc.StartInfo.Arguments = args;

                //proc.StartInfo.RedirectStandardInput = true;
                //proc.StartInfo.RedirectStandardOutput = true;
                proc.StartInfo.CreateNoWindow = false;
                proc.StartInfo.UseShellExecute = false;

                proc.Start();
            } else {
                Console.WriteLine("File Does not exists " + filePath);
            }
        }
    }
</code>```

答:
Try this:

```<code>private Process Execute(string vsEnvVar)
    {
        Process process = new Process();
        ProcessStartInfo psi = new ProcessStartInfo("cmd.exe");//assume location is in path. Otherwise use ComSpec env variable
        psi.CreateNoWindow = true;
        psi.UseShellExecute = false;
        psi.RedirectStandardError = true;
        psi.RedirectStandardInput = true;
        psi.RedirectStandardOutput = true;
        psi.WindowStyle = ProcessWindowStyle.Hidden;
        process.StartInfo = psi;
        // attach output events
        process.ErrorDataReceived += new DataReceivedEventHandler(process_ErrorDataReceived);
        process.OutputDataReceived += new DataReceivedEventHandler(process_OutputDataReceived);
        process.StartInfo = psi;
        process.Start();
        process.BeginErrorReadLine();
        process.BeginOutputReadLine();
        process.StandardInput.WriteLine(string.Format("call \"%{0}%vsvars32.bat\""), vsEnvVar);
        process.StandardInput.Flush();
        return process;
    }
</code>```

Now you can execute any commands by writing to process.StandardInput

```<code>process.StandardInput.WriteLine(@"msbuild c:\MySolution.sln /t:Clean");
</code>```

Body:
I want to run visual studios command programmatically.I have tried the above code but no help.All I am getting is a command prompt with my project`s directory open.

I have used Execute("VS140COMNTOOLS") as input.

 private void Execute(string vsEnvVar) {

        var vsInstallPath = Environment.GetEnvironmentVariable(vsEnvVar);

        if (Directory.Exists(vsInstallPath)) {
            var filePath = vsInstallPath + "vsvars32.bat";
            if (File.Exists(filePath)) {
                //start vs command process
                Process proc = new Process();

                var command = Environment.GetEnvironmentVariable("ComSpec");
                command = @"" + command + @"";

                //var batfile = @"E:\Test\vstest.bat";
                var args = string.Format("/S/K \" \"{0}\" \"", filePath);

                proc.StartInfo.FileName = command;
                proc.StartInfo.Arguments = args;

                //proc.StartInfo.RedirectStandardInput = true;
                //proc.StartInfo.RedirectStandardOutput = true;
                proc.StartInfo.CreateNoWindow = false;
                proc.StartInfo.UseShellExecute = false;

                proc.Start();
            } else {
                Console.WriteLine("File Does not exists " + filePath);
            }
        }
    }

Body:
Try this:

private Process Execute(string vsEnvVar)
    {
        Process process = new Process();
        ProcessStartInfo psi = new ProcessStartInfo("cmd.exe");//assume location is in path. Otherwise use ComSpec env variable
        psi.CreateNoWindow = true;
        psi.UseShellExecute = false;
        psi.RedirectStandardError = true;
        psi.RedirectStandardInput = true;
        psi.RedirectStandardOutput = true;
        psi.WindowStyle = ProcessWindowStyle.Hidden;
        process.StartInfo = psi;
        // attach output events
        process.ErrorDataReceived += new DataReceivedEventHandler(process_ErrorDataReceived);
        process.OutputDataReceived += new DataReceivedEventHandler(process_OutputDataReceived);
        process.StartInfo = psi;
        process.Start();
        process.BeginErrorReadLine();
        process.BeginOutputReadLine();
        process.StandardInput.WriteLine(string.Format("call \"%{0}%vsvars32.bat\""), vsEnvVar);
        process.StandardInput.Flush();
        return process;
    }

Now you can execute any commands by writing to process.StandardInput

process.StandardInput.WriteLine(@"msbuild c:\MySolution.sln /t:Clean");


问:
How to keep animation working on UICollectionView
Basically I just add a simple rotate animation on an imageView which is a subview of UICollectionViewCell, the animation works fine, but when I scroll the collection view and scroll back, the animation just stoped. How to solve this problem?
This is what I added to the imageView.</p>

```<code>let rotationAnimation = CABasicAnimation(keyPath: "transform.rotation")
rotationAnimation.fromValue = 0.0
rotationAnimation.toValue = Double.pi
rotationAnimation.duration = 2.0
rotationAnimation.repeatCount = .infinity
view.layer.add(rotationAnimation, forKey: nil)
</code>```

答:
To avoid scrolling's influence, need to use Runloop and its commonModes, making animation with CADisplayLink can do it:

```<code>private var _displayLinkForRotation:CADisplayLink?
var displayLinkForRotation:CADisplayLink {
    get{
        if _displayLinkForRotation == nil {
            _displayLinkForRotation = CADisplayLink(target: self, selector: #selector(excuteAnimations))
            _displayLinkForRotation?.add(to: RunLoop.current, forMode: RunLoopMode.commonModes)
        }
        return _displayLinkForRotation!
    }
}

func excuteAnimations() {
    //This function will be called 60 times per second.
    //According to your question, you have 2 seconds to rotate the view to 180 angle. So we rotate 90 angle per second here.
    //self.view could be replaced by another view you want to rotate.
    self.view.transform = self.view.transform.rotated(by: 90.0 / 60.0 / 180.0 * CGFloat.pi)

    let angle = atan2(self.view.transform.b, self.view.transform.a) * (45.0/atan(1.0))
    if (round(angle) >= 180.0) { //Stop when rotated 180 angle
        self.displayLinkForRotation.isPaused = true
    }
}
</code>```

To start animation:

```<code>self.displayLinkForRotation.isPaused = false
</code>```

To destroy it:

```<code>self.displayLinkForRotation.invalidate()
_displayLinkForRotation = nil
</code>```

Body:
Basically I just add a simple rotate animation on an imageView which is a subview of UICollectionViewCell, the animation works fine, but when I scroll the collection view and scroll back, the animation just stoped. How to solve this problem?
This is what I added to the imageView.

let rotationAnimation = CABasicAnimation(keyPath: "transform.rotation")
rotationAnimation.fromValue = 0.0
rotationAnimation.toValue = Double.pi
rotationAnimation.duration = 2.0
rotationAnimation.repeatCount = .infinity
view.layer.add(rotationAnimation, forKey: nil)

Body:
To avoid scrolling's influence, need to use Runloop and its commonModes, making animation with CADisplayLink can do it:

private var _displayLinkForRotation:CADisplayLink?
var displayLinkForRotation:CADisplayLink {
    get{
        if _displayLinkForRotation == nil {
            _displayLinkForRotation = CADisplayLink(target: self, selector: #selector(excuteAnimations))
            _displayLinkForRotation?.add(to: RunLoop.current, forMode: RunLoopMode.commonModes)
        }
        return _displayLinkForRotation!
    }
}

func excuteAnimations() {
    //This function will be called 60 times per second.
    //According to your question, you have 2 seconds to rotate the view to 180 angle. So we rotate 90 angle per second here.
    //self.view could be replaced by another view you want to rotate.
    self.view.transform = self.view.transform.rotated(by: 90.0 / 60.0 / 180.0 * CGFloat.pi)

    let angle = atan2(self.view.transform.b, self.view.transform.a) * (45.0/atan(1.0))
    if (round(angle) >= 180.0) { //Stop when rotated 180 angle
        self.displayLinkForRotation.isPaused = true
    }
}

To start animation:

self.displayLinkForRotation.isPaused = false

To destroy it:

self.displayLinkForRotation.invalidate()
_displayLinkForRotation = nil


问:
How do I replace a product image in Magento?
I need to replace a product image with a new one.

I need to replace image in position 2 with the new image.

This is my code.

```<code>$position = 2;//this is the image to delete
$file_location = "../WS-Access-000036-Black-2.jpg";
$sku = "WS-Access-000036-Black";

//delete image
$mediaApi = Mage::getModel("catalog/product_attribute_media_api");
$product = Mage::getModel('catalog/product')->loadByAttribute('sku', $sku);
$product_id = $product->getId();
$items = $mediaApi->items($product_id);
foreach($items as $item){
    if($item['position']=="$position" or ($position==1 and $item['position']=="0")){

        $mediaApi->remove($product_id, $item['file']);//this doesnt remove file from directory

        $image_location = Mage::getBaseDir('media') . DS . 'catalog' . DS . 'product' . $item['file'];
        unlink ($image_location);//have to use this to delete image from disk because $mediaApi->remove doesn't delete it from disk
        break;
    }
}
//end delete image
//EVERYTHING UP TO HERE WORKS, THE IMAGE IS DELETED FROM THE DISK AND
//IN THE BACKEND OF THE PRODUCT

//save new image
$pathInfo = pathinfo($file_location);
switch($pathInfo['extension']){
    case 'png':
        $mimeType = 'image/png';
        break;
    case 'jpg':
        $mimeType = 'image/jpeg';
        break;
    case 'gif':
        $mimeType = 'image/gif';
        break;
}

$types = ($position == 1) ? array('image', 'small_image', 'thumbnail') : array();

$newImage = array(
    'file' => array(
        'content' => base64_encode($file_location),
        'mime' => $mimeType,
        'name' => pathinfo($sku."-".$position, PATHINFO_FILENAME),
    ),
    'label' => '',
    'position' => $position,
    'types' => $types,
    'exclude' => 0,
);

$media = Mage::getModel('catalog/product_attribute_media_api');
$media->create($sku, $newImage);
//end save new image
</code>```

My issue is that when I delete image WS-Access-000036-Black-2.jpg from disk and the products gallery then I add the new WS-Access-000036-Black-2.jpg to the products gallery it loads the old WS-Access-000036-Black-2.jpg.
 I'm thinking its a caching issue but i've cleared my cache and the old image keeps loading.
It's only when I change the name under this line

```<code>'name' => pathinfo($sku."-".$position, PATHINFO_FILENAME),
</code>```

that everything works correctly.

I need to keep the original file name.

Why is this happening?

答:
Do This One
If the new image inserted then probably you need to go to admin, System -> Cache Management & refresh all cache + please flush catalog images cache

After Cache Clear it will work

Body:
I need to replace a product image with a new one.

I need to replace image in position 2 with the new image.

This is my code.

$position = 2;//this is the image to delete
$file_location = "../WS-Access-000036-Black-2.jpg";
$sku = "WS-Access-000036-Black";

//delete image
$mediaApi = Mage::getModel("catalog/product_attribute_media_api");
$product = Mage::getModel('catalog/product')->loadByAttribute('sku', $sku);
$product_id = $product->getId();
$items = $mediaApi->items($product_id);
foreach($items as $item){
    if($item['position']=="$position" or ($position==1 and $item['position']=="0")){

        $mediaApi->remove($product_id, $item['file']);//this doesnt remove file from directory

        $image_location = Mage::getBaseDir('media') . DS . 'catalog' . DS . 'product' . $item['file'];
        unlink ($image_location);//have to use this to delete image from disk because $mediaApi->remove doesn't delete it from disk
        break;
    }
}
//end delete image
//EVERYTHING UP TO HERE WORKS, THE IMAGE IS DELETED FROM THE DISK AND
//IN THE BACKEND OF THE PRODUCT

//save new image
$pathInfo = pathinfo($file_location);
switch($pathInfo['extension']){
    case 'png':
        $mimeType = 'image/png';
        break;
    case 'jpg':
        $mimeType = 'image/jpeg';
        break;
    case 'gif':
        $mimeType = 'image/gif';
        break;
}

$types = ($position == 1) ? array('image', 'small_image', 'thumbnail') : array();

$newImage = array(
    'file' => array(
        'content' => base64_encode($file_location),
        'mime' => $mimeType,
        'name' => pathinfo($sku."-".$position, PATHINFO_FILENAME),
    ),
    'label' => '',
    'position' => $position,
    'types' => $types,
    'exclude' => 0,
);

$media = Mage::getModel('catalog/product_attribute_media_api');
$media->create($sku, $newImage);
//end save new image

My issue is that when I delete image WS-Access-000036-Black-2.jpg from disk and the products gallery then I add the new WS-Access-000036-Black-2.jpg to the products gallery it loads the old WS-Access-000036-Black-2.jpg.
 I'm thinking its a caching issue but i've cleared my cache and the old image keeps loading.
It's only when I change the name under this line

'name' => pathinfo($sku."-".$position, PATHINFO_FILENAME),

that everything works correctly.

I need to keep the original file name.

Why is this happening?


问:
ng-repeat get length of array and bind last value of array
```<code>$scope.GetDetails={
  Student:[
      {"id":1,"Name":"Apple","Price":3500}
    ],
  Student:[
      {"id":2,"Name":"Samsung","Price":4000}
     ],
  Student:[
    {"id":3,"Name":"Nokia","Price":1500},
    {"id":3,"Name":"Nokia","Price";7000}
   ]
 }
</code>```

Am binding data using ng-repeat

```<code> <div ng-repeat="As in GetDetails">
         <div ng-repeat="A in As.Student">
        <span>{{A.Name}}</span> - <span>{{A.Price}}</span>
    </div>
     </div>
</code>```

Result is
    Apple - 3500
Samsung - 4000
Nokia - 1500
Nokia - 7000

Here every thing Ok.But what i want mean , Nokia have two array ,so i have to get name from first array and price from 2nd array Like,

Nokia - 7000,

And Also i need the length of student array.

答:
If you want this only for Name: Nokia, then do it like;

```<code><div ng-repeat="A in As.Student">
 <span ng-if="A.Name!=='Nokia'">{{A.Name}}-{{A.Price}}</span>
 <span ng-if="A.Name==='Nokia' && $last">{{A.Name}}-{{A.Price}}</span>
</div>
</code>```

and it you want  only last element from every array :

then:

```<code> <div ng-repeat="A in As.Student" ng-if="$last">
        <span>{{A.Name}}</span> - <span>{{A.Price}}</span>
 </div>
</code>```

Body:
$scope.GetDetails={
  Student:[
      {"id":1,"Name":"Apple","Price":3500}
    ],
  Student:[
      {"id":2,"Name":"Samsung","Price":4000}
     ],
  Student:[
    {"id":3,"Name":"Nokia","Price":1500},
    {"id":3,"Name":"Nokia","Price";7000}
   ]
 }

Am binding data using ng-repeat

        {{A.Name}} - {{A.Price}}

Result is
    Apple - 3500
Samsung - 4000
Nokia - 1500
Nokia - 7000

Here every thing Ok.But what i want mean , Nokia have two array ,so i have to get name from first array and price from 2nd array Like,

Nokia - 7000,

And Also i need the length of student array.

Body:
If you want this only for Name: Nokia, then do it like;

<div ng-repeat="A in As.Student">
 <span ng-if="A.Name!=='Nokia'">{{A.Name}}-{{A.Price}}</span>
 <span ng-if="A.Name==='Nokia' && $last">{{A.Name}}-{{A.Price}}</span>
</div>

and it you want  only last element from every array :

then:

 <div ng-repeat="A in As.Student" ng-if="$last">
        <span>{{A.Name}}</span> - <span>{{A.Price}}</span>
 </div>


问:
How to schedule PHP script on Job Finish (from CLI)
I am processing a big .gz file using PHP (transfering data from gz to mysql)
it takes about 10 minutes per .gz file.
I have a lot of .gz file to be processed.

After PHP is finished with one file I have to manually change the PHP script to select another .gz file and then run the script again manually.

I want it to be automatically run the next job to process the next file.
the gz file is named as 1, 2 ,3, 4, 5 ...
I can simply make a loop to be something like this ( process file 1 - 5):

```<code>for ($i = 1 ; $i >= 5; $i++)
{
    $file = gzfile($i.'.gz')
    ...gz content processing...
}
</code>```

However, since the gz file is really big, I cannot do that, because if I use this loop, PHP will run multiple big gz files as single script job. (takes a lot of memory)

What I want to do is after PHP is finished with one job I want a new job to process the next file.

maybe its going to be something like this:

```<code>    $file = gzfile($_GET['filename'].'.gz')
    ...gz content processing...
</code>```

Thank You

答:
If you clean up after processing and free all memory using unset(), you could simply wrap the whole script in a foreach (glob(...) as $filename) loop. Like this:

```<code><?php
foreach (glob(...) as $filename) {
    // your script code here
    unset($thisVar, $thatVar, ...);
}
?>
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I am processing a big .gz file using PHP (transfering data from gz to mysql)
it takes about 10 minutes per .gz file.
I have a lot of .gz file to be processed.

After PHP is finished with one file I have to manually change the PHP script to select another .gz file and then run the script again manually.

I want it to be automatically run the next job to process the next file.
the gz file is named as 1, 2 ,3, 4, 5 ...
I can simply make a loop to be something like this ( process file 1 - 5):

for ($i = 1 ; $i >= 5; $i++)
{
    $file = gzfile($i.'.gz')
    ...gz content processing...
}

However, since the gz file is really big, I cannot do that, because if I use this loop, PHP will run multiple big gz files as single script job. (takes a lot of memory)

What I want to do is after PHP is finished with one job I want a new job to process the next file.

maybe its going to be something like this:

    $file = gzfile($_GET['filename'].'.gz')
    ...gz content processing...

Thank You

Body:
If you clean up after processing and free all memory using unset(), you could simply wrap the whole script in a foreach (glob(...) as $filename) loop. Like this:

<?php
foreach (glob(...) as $filename) {
    // your script code here
    unset($thisVar, $thatVar, ...);
}
?>


问:
findViewById in Fragment
I am trying to create an ImageView in a Fragment which will refer to the ImageView element which I have created in the XML for the Fragment. However, the findViewById method only works if I extend an Activity class. Is there anyway of which I can use it in Fragment as well?

```<code>public class TestClass extends Fragment {
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        ImageView imageView = (ImageView)findViewById(R.id.my_image);
        return inflater.inflate(R.layout.testclassfragment, container, false);
    }
}
</code>```

The findViewById method has an error on it which states that the method is undefined.

答:
In fragments we need a view of that window so that we make a onCreateView of this Fragment.

Then get the view and use it to access each and every view id of that view elements..

```<code>  class Demo extends Fragment
    {
        @Override
        public View onCreateView(final LayoutInflater inflater,ViewGroup container, Bundle savedInstanceState)
        {
            View view =inflater.inflate(R.layout.demo_fragment, container,false);
            ImageView imageview=(ImageView)view.findViewById(R.id.imageview1);

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

Title: findViewById in Fragment

Body:
I am trying to create an ImageView in a Fragment which will refer to the ImageView element which I have created in the XML for the Fragment. However, the findViewById method only works if I extend an Activity class. Is there anyway of which I can use it in Fragment as well?

public class TestClass extends Fragment {
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        ImageView imageView = (ImageView)findViewById(R.id.my_image);
        return inflater.inflate(R.layout.testclassfragment, container, false);
    }
}

The findViewById method has an error on it which states that the method is undefined.

Body:
In fragments we need a view of that window so that we make a onCreateView of this Fragment.

Then get the view and use it to access each and every view id of that view elements..

  class Demo extends Fragment
    {
        @Override
        public View onCreateView(final LayoutInflater inflater,ViewGroup container, Bundle savedInstanceState)
        {
            View view =inflater.inflate(R.layout.demo_fragment, container,false);
            ImageView imageview=(ImageView)view.findViewById(R.id.imageview1);

            return view;
        }
    }


问:
Tensorflow always predict the same output
So, I'm trying to learn tensorflow and, for that, I try to create a classifier for something that, I think, is not so hard.
I'd like to predict if a number is odd or even.
The problem is that Tensorflow always predict the same output, I searched answers the last days but nothing helped me...
I saw the following answers : -Tensorflow predicts always the same result

-TensorFlow always converging to same output for all items after training

-TensorFlow always return same result

Here's my code:

in:

```<code>df
    nb  y1
0   1   0
1   2   1
2   3   0
3   4   1
4   5   0
...
19  20  1

inputX = df.loc[:, ['nb']].as_matrix()
inputY = df.loc[:, ['y1']].as_matrix()
print(inputX.shape)
print(inputY.shape)
</code>```

out:

(20, 1)
(20, 1)

in:

```<code># Parameters
learning_rate = 0.00000001
training_epochs = 2000
display_step = 50
n_samples = inputY.size

x = tf.placeholder(tf.float32, [None, 1])
W = tf.Variable(tf.zeros([1, 1]))
b = tf.Variable(tf.zeros([1]))
y_values = tf.add(tf.matmul(x, W), b)
y = tf.nn.relu(y_values)
y_ = tf.placeholder(tf.float32, [None,1])

# Cost function: Mean squared error
cost = tf.reduce_sum(tf.pow(y_ - y, 2))/(2*n_samples)
# Gradient descent
optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost)

# Initialize variabls and tensorflow session
init = tf.global_variables_initializer()
sess = tf.Session()
sess.run(init)

for i in range(training_epochs):
    sess.run(optimizer, feed_dict={x: inputX, y_: inputY}) # Take a gradient descent step using our inputs and labels

    # Display logs per epoch step
    if (i) % display_step == 0:
        cc = sess.run(cost, feed_dict={x: inputX, y_:inputY})
        print("Training step:", '%04d' % (i), "cost=", "{:.9f}".format(cc)) #, \"W=", sess.run(W), "b=", sess.run(b)

print ("Optimization Finished!")
training_cost = sess.run(cost, feed_dict={x: inputX, y_: inputY})
print ("Training cost=", training_cost, "W=", sess.run(W), "b=", sess.run(b), '\n')
</code>```

out:

```<code>Training step: 0000 cost= 0.250000000
Training step: 0050 cost= 0.250000000
Training step: 0100 cost= 0.250000000
...
Training step: 1800 cost= 0.250000000
Training step: 1850 cost= 0.250000000
Training step: 1900 cost= 0.250000000
Training step: 1950 cost= 0.250000000
Optimization Finished!
Training cost= 0.25 W= [[ 0.]] b= [ 0.]
</code>```

in:

```<code>sess.run(y, feed_dict={x: inputX })
</code>```

out:

```<code>array([[ 0.],
       [ 0.],
       [ 0.],
       [ 0.],
       [ 0.],
       [ 0.],
       [ 0.],
       [ 0.],
       [ 0.],
       [ 0.],
       [ 0.],
       [ 0.],
       [ 0.],
       [ 0.],
       [ 0.],
       [ 0.],
       [ 0.],
       [ 0.],
       [ 0.],
       [ 0.]], dtype=float32)
</code>```

I tried to play with my Hyper parameters like, the learning rate or the number of training epochs.
I changed the activation function from softmax to relu.
I changed my dataframe to have more examples but nothing happened.
I also tried to add random for my Weights, but nothing changed, the cost was just starting to a higher value.

答:
From giving a quick look at the code, it looks ok to me (maybe a part initializing the weights to zero, usually you want a small number different from zero to avoid a trivial solution), while I don't think that you can fit the problem of the parity of integers with a linear regression.

The point is that you are trying to fit

```<code>x % 2
</code>```

with predictions of the form

```<code>activation(x * w + b)
</code>```

and there is no way to find good w and b to solve this problem.

Another way to understand this is to plot your data: the scatter plot of the parity of x are two lines of points, and the only way to fit them with a line is with a flat line (that will have a high cost anyway).

I think it would be better to change data to start with, but if you want to address this problem, you should obtain some result using a sine or a cosine as activation function.

Body:
So, I'm trying to learn tensorflow and, for that, I try to create a classifier for something that, I think, is not so hard.
I'd like to predict if a number is odd or even.
The problem is that Tensorflow always predict the same output, I searched answers the last days but nothing helped me...
I saw the following answers : -Tensorflow predicts always the same result

-TensorFlow always converging to same output for all items after training

-TensorFlow always return same result

Here's my code:

in:

df
    nb  y1
0   1   0
1   2   1
2   3   0
3   4   1
4   5   0
...
19  20  1

inputX = df.loc[:, ['nb']].as_matrix()
inputY = df.loc[:, ['y1']].as_matrix()
print(inputX.shape)
print(inputY.shape)

out:

(20, 1)
(20, 1)

in:

# Parameters
learning_rate = 0.00000001
training_epochs = 2000
display_step = 50
n_samples = inputY.size

x = tf.placeholder(tf.float32, [None, 1])
W = tf.Variable(tf.zeros([1, 1]))
b = tf.Variable(tf.zeros([1]))
y_values = tf.add(tf.matmul(x, W), b)
y = tf.nn.relu(y_values)
y_ = tf.placeholder(tf.float32, [None,1])

# Cost function: Mean squared error
cost = tf.reduce_sum(tf.pow(y_ - y, 2))/(2*n_samples)
# Gradient descent
optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost)

# Initialize variabls and tensorflow session
init = tf.global_variables_initializer()
sess = tf.Session()
sess.run(init)

for i in range(training_epochs):
    sess.run(optimizer, feed_dict={x: inputX, y_: inputY}) # Take a gradient descent step using our inputs and labels

    # Display logs per epoch step
    if (i) % display_step == 0:
        cc = sess.run(cost, feed_dict={x: inputX, y_:inputY})
        print("Training step:", '%04d' % (i), "cost=", "{:.9f}".format(cc)) #, \"W=", sess.run(W), "b=", sess.run(b)

print ("Optimization Finished!")
training_cost = sess.run(cost, feed_dict={x: inputX, y_: inputY})
print ("Training cost=", training_cost, "W=", sess.run(W), "b=", sess.run(b), '\n')

out:

Training step: 0000 cost= 0.250000000
Training step: 0050 cost= 0.250000000
Training step: 0100 cost= 0.250000000
...
Training step: 1800 cost= 0.250000000
Training step: 1850 cost= 0.250000000
Training step: 1900 cost= 0.250000000
Training step: 1950 cost= 0.250000000
Optimization Finished!
Training cost= 0.25 W= [[ 0.]] b= [ 0.]

in:

sess.run(y, feed_dict={x: inputX })

out:

array([[ 0.],
       [ 0.],
       [ 0.],
       [ 0.],
       [ 0.],
       [ 0.],
       [ 0.],
       [ 0.],
       [ 0.],
       [ 0.],
       [ 0.],
       [ 0.],
       [ 0.],
       [ 0.],
       [ 0.],
       [ 0.],
       [ 0.],
       [ 0.],
       [ 0.],
       [ 0.]], dtype=float32)

I tried to play with my Hyper parameters like, the learning rate or the number of training epochs.
I changed the activation function from softmax to relu.
I changed my dataframe to have more examples but nothing happened.
I also tried to add random for my Weights, but nothing changed, the cost was just starting to a higher value.

Body:
From giving a quick look at the code, it looks ok to me (maybe a part initializing the weights to zero, usually you want a small number different from zero to avoid a trivial solution), while I don't think that you can fit the problem of the parity of integers with a linear regression.

The point is that you are trying to fit

x % 2

with predictions of the form

activation(x * w + b)

and there is no way to find good w and b to solve this problem.

Another way to understand this is to plot your data: the scatter plot of the parity of x are two lines of points, and the only way to fit them with a line is with a flat line (that will have a high cost anyway).

I think it would be better to change data to start with, but if you want to address this problem, you should obtain some result using a sine or a cosine as activation function.


问:
Update lower and upper bounds in PostgreSQL
I have a table (12 rows) in my PostgreSQL 9.5 database with two columns ID and geometry. Table structure from PgAdmin3 is:

```<code>CREATE TABLE public.my_table
(
id integer,
geom geometry
)
</code>```

The geometry represents triangles starting from true north having ID as 1 and so on. The ID for each row is unique i.e., 1 - 12. Based on this ID, I am trying to update angles and their lower and upper bounds. My approach has been:

```<code>Select
id,
Case    when id = 1 then 30
        when id = 2 then 60
        when id = 3 then 90
        when id = 4 then 120
        when id = 5 then 150
        when id = 6 then 180
        when id = 7 then 210
        when id = 8 then 240
        when id = 9 then 270
        when id = 10 then 300
        when id = 11 then 330
        when id = 12 then 360
end as angle,
case    when id = 1 then lower(numrange(0, 30))
        when id = 2 then lower(numrange(30, 60))
        when id = 3 then lower(numrange(60, 90))
        when id = 4 then lower(numrange(90, 120))
        when id = 5 then lower(numrange(120, 150))
        when id = 6 then lower(numrange(150, 180))
        when id = 7 then lower(numrange(180, 210))
        when id = 8 then lower(numrange(210, 240))
        when id = 9 then lower(numrange(240, 270))
        when id = 10 then lower(numrange(270, 300))
        when id = 11 then lower(numrange(300, 330))
        when id = 12 then lower(numrange(330, 360))
end as lb
from my_table
</code>```

Is there a better way to do this? Any pointers will be highly appreciated.

答:
at first I thought to use window function here, but then I realized that you dont need ANY column from my_table for this. Try:

updated to reflect notes from OP (note, that you will need to define lowest boundary explicitly - here I used zero)

```<code>t=# with p as (select id,angle from generate_series(30,360,30) with ordinality as g(angle,id)) select *,coalesce(lag(angle) over (order by id),0) lb from p;
 id | angle | lb
----+-------+-----
  1 |    30 |   0
  2 |    60 |  30
  3 |    90 |  60
  4 |   120 |  90
  5 |   150 | 120
  6 |   180 | 150
  7 |   210 | 180
  8 |   240 | 210
  9 |   270 | 240
 10 |   300 | 270
 11 |   330 | 300
 12 |   360 | 330
(12 rows)
</code>```

update
rewrite OP query I'd use CTE to avoid listing cases in window function:

```<code>t=# with a as (Select
id,
Case    when id = 1 then 30
        when id = 2 then 60
        when id = 3 then 90
        when id = 4 then 120
        when id = 5 then 150
        when id = 6 then 180
        when id = 7 then 210
        when id = 8 then 240
        when id = 9 then 270
        when id = 10 then 300
        when id = 11 then 330
        when id = 12 then 360
end as angle
from my_table)
select *,coalesce(lag(angle) over (order by id),0)
from a;
 id | angle | coalesce
----+-------+----------
  1 |    30 |        0
  2 |    60 |       30
  3 |    90 |       60
  4 |   120 |       90
  5 |   150 |      120
  6 |   180 |      150
  7 |   210 |      180
  8 |   240 |      210
  9 |   270 |      240
 10 |   300 |      270
 11 |   330 |      300
 12 |   360 |      330
(12 rows)

Time: 0.462 ms
</code>```

Body:
I have a table (12 rows) in my PostgreSQL 9.5 database with two columns ID and geometry. Table structure from PgAdmin3 is:

CREATE TABLE public.my_table
(
id integer,
geom geometry
)

The geometry represents triangles starting from true north having ID as 1 and so on. The ID for each row is unique i.e., 1 - 12. Based on this ID, I am trying to update angles and their lower and upper bounds. My approach has been:

Select
id,
Case    when id = 1 then 30
        when id = 2 then 60
        when id = 3 then 90
        when id = 4 then 120
        when id = 5 then 150
        when id = 6 then 180
        when id = 7 then 210
        when id = 8 then 240
        when id = 9 then 270
        when id = 10 then 300
        when id = 11 then 330
        when id = 12 then 360
end as angle,
case    when id = 1 then lower(numrange(0, 30))
        when id = 2 then lower(numrange(30, 60))
        when id = 3 then lower(numrange(60, 90))
        when id = 4 then lower(numrange(90, 120))
        when id = 5 then lower(numrange(120, 150))
        when id = 6 then lower(numrange(150, 180))
        when id = 7 then lower(numrange(180, 210))
        when id = 8 then lower(numrange(210, 240))
        when id = 9 then lower(numrange(240, 270))
        when id = 10 then lower(numrange(270, 300))
        when id = 11 then lower(numrange(300, 330))
        when id = 12 then lower(numrange(330, 360))
end as lb
from my_table

Is there a better way to do this? Any pointers will be highly appreciated.

Body:
at first I thought to use window function here, but then I realized that you dont need ANY column from my_table for this. Try:

updated to reflect notes from OP (note, that you will need to define lowest boundary explicitly - here I used zero)

t=# with p as (select id,angle from generate_series(30,360,30) with ordinality as g(angle,id)) select *,coalesce(lag(angle) over (order by id),0) lb from p;
 id | angle | lb
----+-------+-----
  1 |    30 |   0
  2 |    60 |  30
  3 |    90 |  60
  4 |   120 |  90
  5 |   150 | 120
  6 |   180 | 150
  7 |   210 | 180
  8 |   240 | 210
  9 |   270 | 240
 10 |   300 | 270
 11 |   330 | 300
 12 |   360 | 330
(12 rows)

update
rewrite OP query I'd use CTE to avoid listing cases in window function:

t=# with a as (Select
id,
Case    when id = 1 then 30
        when id = 2 then 60
        when id = 3 then 90
        when id = 4 then 120
        when id = 5 then 150
        when id = 6 then 180
        when id = 7 then 210
        when id = 8 then 240
        when id = 9 then 270
        when id = 10 then 300
        when id = 11 then 330
        when id = 12 then 360
end as angle
from my_table)
select *,coalesce(lag(angle) over (order by id),0)
from a;
 id | angle | coalesce
----+-------+----------
  1 |    30 |        0
  2 |    60 |       30
  3 |    90 |       60
  4 |   120 |       90
  5 |   150 |      120
  6 |   180 |      150
  7 |   210 |      180
  8 |   240 |      210
  9 |   270 |      240
 10 |   300 |      270
 11 |   330 |      300
 12 |   360 |      330
(12 rows)

Time: 0.462 ms


问:
how should be the resources name while am doing localization
May I know how should be the resource names while doing localization, whether it's should be as Resources.en-US.resx or Resources.en.resx, which one best practice? and why?</p>

答:
You need to mention the appropiate culture code append to the resource file name as like below

"Resources.en-US.resx"

Please refer below the link,

https://msdn.microsoft.com/library/aa992030.aspx


问:
Timeline with UICollectionView in Swift
I'm trying to code a Timeline for my app. I designed it on sketch in order to give you an insight:

I'm not an expert in Swift so I don't really know how to code it. I've thought about creating a UICollectionView, and play with the indexPath in order to change the design of the cell if it's even or odd.

What do you think ?

答:
If I understand you correctly, you want to know how can this design done?

you have two way to implement like this design:

First one (easiest way):
What you need is just a tableView with timeline view (UICollectionView) at the top with 2 custom collection view cells one for odd and the other for even
tableview will have 2 cells also one for text with image and the other for plane text

how to render time line:

```<code>func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    if (indexPath.row + 1) % 2 == 0 {
        return even cell
    } else {
        return odd cell
    }
</code>```

how to detect even or odd by calculate indexPath while the user scroll through timeline :

```<code>@IBOutlet weak var collectionViewTimeLine: UICollectionView!
func scrollViewDidScroll(_ scrollView: UIScrollView) {
    if let timeline = scrollView as? collectionViewTimeLine {
        // calculate and find selected indexPath
        // reload data
    }
}
</code>```

The second way:
This way is used when you want to smoothly animate content while the user scroll through timeline

You need a 2 UICollectionView the first for time line and the second for content
When user scroll timeline you scroll the collectionViewContent

```<code>@IBOutlet weak var collectionViewTimeLine: UICollectionView!
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        if let timeline = scrollView as? collectionViewTimeLine {
            // calculate and find selected indexPath
            // scroll collectionViewContent with selected indexPath
        }
    }
</code>```

Title: Timeline with UICollectionView in Swift

Body:
If I understand you correctly, you want to know how can this design done?

you have two way to implement like this design:

First one (easiest way):
What you need is just a tableView with timeline view (UICollectionView) at the top with 2 custom collection view cells one for odd and the other for even
tableview will have 2 cells also one for text with image and the other for plane text

how to render time line:

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    if (indexPath.row + 1) % 2 == 0 {
        return even cell
    } else {
        return odd cell
    }

how to detect even or odd by calculate indexPath while the user scroll through timeline :

@IBOutlet weak var collectionViewTimeLine: UICollectionView!
func scrollViewDidScroll(_ scrollView: UIScrollView) {
    if let timeline = scrollView as? collectionViewTimeLine {
        // calculate and find selected indexPath
        // reload data
    }
}

The second way:
This way is used when you want to smoothly animate content while the user scroll through timeline

You need a 2 UICollectionView the first for time line and the second for content
When user scroll timeline you scroll the collectionViewContent

@IBOutlet weak var collectionViewTimeLine: UICollectionView!
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        if let timeline = scrollView as? collectionViewTimeLine {
            // calculate and find selected indexPath
            // scroll collectionViewContent with selected indexPath
        }
    }


问:
How to decide whether to split up a VB.Net application and, if so, how to split it up?
I have 2 1/2 years experience of VB.Net, mostly self taught, so please bear with me if I seem rather noobish still and do not know some of the basics. I would recommend you grab a cup of tea before starting on this, as it appears to have got quite long...

I currently have a rather large application (VB.Net website) of over 15000 lines of code at the last count. It does not do retail or anything particularly complex like that - it is literally just a wholesale viewing website with admin frontend, catalogue / catalogue management system and pageview system.

I don't really know much about how .Net applications work in the background - whether they are all loaded on the same thread or if each has its own thread... I just know how to code them, or at least like to think I do... :-)

Basically my application is set up as follows:

There are two different areas - the customer area and the administration frontend.

The main part of the customer frontend is the Catalogue. The MasterPage will load a list of products but that's all, and this is common to all the customer frontend pages.

I tend to work on only one or several parts of the application at a time before uploading the changes. So, for example, I may alter the hierarchy of the Catalogue and change the Catalogue page to match the hierarchy change whilst leaving everything else alone.

The pageview database is getting really quite large and so it is getting rather slow when the application is first requested due to the way it works.

The application timeout is set to 5 minutes - don't know how to change it, I have even tried asking this question on here and seem to remember the solution was quite complex and I was recommended not to change it, but if a customer requests the application 5 minutes after the last page view then it will reload the application from scratch. This means there is a very slow page load whenever it exceeds 5 minutes of inactivity.

I am not sure if this needs consideration to determine how best to split the application up, if at all, but each part of the catalogue system is set up as follows:

A Manager class at the top level, which is used by the admin frontend to add, edit and remove items of the specified type and the customer frontend to retrieve a list of items of the specified type. For example the "RangeManager" will contain a list of product "Ranges" and will be used to interact with these from the customer frontend.

An Item class, for example Range, which contains a list of Attributes. For example Name, Description, Visible, Created, CreatedBy and so on. The form for adding / editing loops through these to display relevant controls for the administrator. For example a Checkbox for BooleanAttribute.

An Attribute class, which can be of type StringAttribute, BooleanAttribute, IntegerAttribute and so on. There are also custom Attributes (not just datatypes) such as RangeAttribute, UserAttribute and so on. These are given a data field which is used to get a piece of data specific to the item it is contained in when it is first requested. Basically the Item is given a DataRow which is stored and accessed by Attributes only when they are first requested.

When one item is requested from a specific manager is requested, the manager will loop through all the items in the database and create a new instance of the item class. For example when a Range is requested from the RangeManager, the RangeManager will loop through all of the DataRows in the Ranges table and create a new instance of Range for each one. As stated above it simply creates a new instance with the DataRow, rather than loading all the data into it there and then. The Attributes themselves fetch the relevant data from the DataRow as and when they're first requested.

It just seems a tad stupid, in my mind, to recompile and upload the entire application every time I fix a minor bug or a spelling mistake for a word which is in the code behind (for example if I set the text of a Label dynamically). A fix / change to the Catalogue page, the way it is now, may mean a customer trying to view the Contact page, which is in no way related to the Catalogue page apart from by having the same MasterPage, cannot do so because the DLL is being uploaded.

Basically my question is, given my current situation, how would people suggest I change the architecture of the application by way of splitting it into multiple applications? I mean would it be just customer / admin, or customer / admin and pageviews, or some other way? Or not at all? Are there any other alternatives which I have not mentioned here? Could web services come in handy here? Like split the catalogue itself into a different application and just have the masterpage for all the other pages use a web service to get the names of the products to list on the left hand side? Am I just way WAY over-complicating things? Judging by the length of this question I probably am, and it wouldn't be the first time... I have tried to keep it short, but I always fail... :-)

Many thanks in advance, and sorry if I have just totally confused you!

Regards,

Richard

答:
15000 LOC is not really all that big.

It sounds like you are not pre-compiling your site for publishing.  You may want to read this: http://msdn.microsoft.com/en-us/library/1y1404zt(v=vs.80).aspx

Recompiling and uploading the application is the best way to do it.  If all you are changing is your markup, that can be uploaded individually (e.g. changing some html layout in an aspx page).

I don't know what you mean here by application timeout, but if your app domain recycles every 5 minutes, then that doesn't seem right at all.   You should look into this.

Also, if you find yourself working on various different parts of the site (i.e. many different changes), but need to deploy only some items in isolation, then you should look into how you are using your source control tools (you are using one, aren't you?).  Look into something like GIT and branching/merging.


问:
How to cache js, css and images
I don't know much about caching a wp site.  I am using Super Cache and it is working but the pagespeed tools is showing that the site is running at 44/100.  Under enable compression it says I could reduce the transfer size by 70% if I compress some js and css files.  It doesn't look like SuperCache offers an option to compress or cache particular files, so my question is just that.  How do I compress and cache certain js and css files that were not affected by SuperCache?</p>

答:
To compress the files (js,css and others) you need to put the following code inside .htaccess file,

```<code><IfModule mod_gzip.c>
mod_gzip_on Yes
mod_gzip_dechunk Yes
mod_gzip_item_include file \.(html?|txt|css|js|php|pl)$
mod_gzip_item_include handler ^cgi-script$
mod_gzip_item_include mime ^text/.*
mod_gzip_item_include mime ^application/x-javascript.*
mod_gzip_item_exclude mime ^image/.*
mod_gzip_item_exclude rspheader ^Content-Encoding:.*gzip.*
</IfModule>
</code>```

To cache the images,

```<code>## EXPIRES CACHING ##
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType image/jpg "access plus 1 month"
ExpiresByType image/jpeg "access plus 1 month"
ExpiresByType image/gif "access plus 1 month"
ExpiresByType image/png "access plus 1 month"
ExpiresByType text/css "access plus 1 month"
ExpiresByType application/pdf "access plus 1 month"
ExpiresByType text/x-javascript "access plus 1 month"
ExpiresByType application/x-shockwave-flash "access plus 1 month"
ExpiresByType image/x-icon "access plus 1 month"
ExpiresDefault "access plus 7 days"
</IfModule>
## EXPIRES CACHING ##
</code>```

To deflate,

```<code><IfModule mod_deflate.c>
  # Compress HTML, CSS, JavaScript, Text, XML and fonts
  AddOutputFilterByType DEFLATE application/javascript
  AddOutputFilterByType DEFLATE application/rss+xml
  AddOutputFilterByType DEFLATE application/vnd.ms-fontobject
  AddOutputFilterByType DEFLATE application/x-font
  AddOutputFilterByType DEFLATE application/x-font-opentype
  AddOutputFilterByType DEFLATE application/x-font-otf
  AddOutputFilterByType DEFLATE application/x-font-truetype
  AddOutputFilterByType DEFLATE application/x-font-ttf
  AddOutputFilterByType DEFLATE application/x-javascript
  AddOutputFilterByType DEFLATE application/xhtml+xml
  AddOutputFilterByType DEFLATE application/xml
  AddOutputFilterByType DEFLATE font/opentype
  AddOutputFilterByType DEFLATE font/otf
  AddOutputFilterByType DEFLATE font/ttf
  AddOutputFilterByType DEFLATE image/svg+xml
  AddOutputFilterByType DEFLATE image/x-icon
  AddOutputFilterByType DEFLATE text/css
  AddOutputFilterByType DEFLATE text/html
  AddOutputFilterByType DEFLATE text/javascript
  AddOutputFilterByType DEFLATE text/plain
  AddOutputFilterByType DEFLATE text/xml

  # Remove browser bugs (only needed for really old browsers)
  BrowserMatch ^Mozilla/4 gzip-only-text/html
  BrowserMatch ^Mozilla/4\.0[678] no-gzip
  BrowserMatch \bMSIE !no-gzip !gzip-only-text/html
  Header append Vary User-Agent
</IfModule>
</code>```

Add this all to the .htaccess file , it will increase the page speed results.

Title: How to cache js, css and images

Body:
To compress the files (js,css and others) you need to put the following code inside .htaccess file,

<IfModule mod_gzip.c>
mod_gzip_on Yes
mod_gzip_dechunk Yes
mod_gzip_item_include file \.(html?|txt|css|js|php|pl)$
mod_gzip_item_include handler ^cgi-script$
mod_gzip_item_include mime ^text/.*
mod_gzip_item_include mime ^application/x-javascript.*
mod_gzip_item_exclude mime ^image/.*
mod_gzip_item_exclude rspheader ^Content-Encoding:.*gzip.*
</IfModule>

To cache the images,

## EXPIRES CACHING ##
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType image/jpg "access plus 1 month"
ExpiresByType image/jpeg "access plus 1 month"
ExpiresByType image/gif "access plus 1 month"
ExpiresByType image/png "access plus 1 month"
ExpiresByType text/css "access plus 1 month"
ExpiresByType application/pdf "access plus 1 month"
ExpiresByType text/x-javascript "access plus 1 month"
ExpiresByType application/x-shockwave-flash "access plus 1 month"
ExpiresByType image/x-icon "access plus 1 month"
ExpiresDefault "access plus 7 days"
</IfModule>
## EXPIRES CACHING ##

To deflate,

<IfModule mod_deflate.c>
  # Compress HTML, CSS, JavaScript, Text, XML and fonts
  AddOutputFilterByType DEFLATE application/javascript
  AddOutputFilterByType DEFLATE application/rss+xml
  AddOutputFilterByType DEFLATE application/vnd.ms-fontobject
  AddOutputFilterByType DEFLATE application/x-font
  AddOutputFilterByType DEFLATE application/x-font-opentype
  AddOutputFilterByType DEFLATE application/x-font-otf
  AddOutputFilterByType DEFLATE application/x-font-truetype
  AddOutputFilterByType DEFLATE application/x-font-ttf
  AddOutputFilterByType DEFLATE application/x-javascript
  AddOutputFilterByType DEFLATE application/xhtml+xml
  AddOutputFilterByType DEFLATE application/xml
  AddOutputFilterByType DEFLATE font/opentype
  AddOutputFilterByType DEFLATE font/otf
  AddOutputFilterByType DEFLATE font/ttf
  AddOutputFilterByType DEFLATE image/svg+xml
  AddOutputFilterByType DEFLATE image/x-icon
  AddOutputFilterByType DEFLATE text/css
  AddOutputFilterByType DEFLATE text/html
  AddOutputFilterByType DEFLATE text/javascript
  AddOutputFilterByType DEFLATE text/plain
  AddOutputFilterByType DEFLATE text/xml

  # Remove browser bugs (only needed for really old browsers)
  BrowserMatch ^Mozilla/4 gzip-only-text/html
  BrowserMatch ^Mozilla/4\.0[678] no-gzip
  BrowserMatch \bMSIE !no-gzip !gzip-only-text/html
  Header append Vary User-Agent
</IfModule>

Add this all to the .htaccess file , it will increase the page speed results.


问:
Cannot get user email with facebook integration
I'm trying to get the user's email after they press Continue with Facebook on my site. I've looked on Stackoverflow and through the Facebook Developer documentation and cannot see a reason why what I am trying isn't working.

JAVASCRIPT

```<code>window.fbAsyncInit = function() {
  FB.init({
    appId      : '1882306058687148',
    cookie     : true,
    xfbml      : true,
    version    : 'v2.8'
  });
  FB.AppEvents.logPageView();
  FB.getLoginStatus(function(response) {
    statusChangeCallback(response);
  });
};

(function(d, s, id){
  var js, fjs = d.getElementsByTagName(s)[0];
  if (d.getElementById(id)) {return;}
  js = d.createElement(s); js.id = id;
  js.src = "//connect.facebook.net/en_US/sdk.js";
  fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));

function checkLoginState() {
  FB.getLoginStatus(function(response) {
    console.log(response);
    statusChangeCallback(response)
  });
}

function statusChangeCallback(response) {
  console.log('statusChangeCallback');
  console.log(response);
  if (response.status === 'connected') {
    runAPI();
  }
}

function runAPI() {
  FB.api('/me', { locale: 'en_US', fields: 'name, email' }, function(response) {
    console.log(response);
    document.getElementById('name').value = response.name;
    document.getElementById('email').value = response.email;
    document.getElementById('fb-login').style.display = 'none'
  });
}
</code>```

** HTML **

```<code><fb:login-button scope="public_profile,email" onlogin="checkLoginState();">
</fb:login-button>
</code>```

What's confusing me the most though is that this IS pulling the name through and that is definitely working.

答:
You will only get an email address back if the user has a verified one set in their profile.

And even then, there are apparently some edge cases where privacy settings can still make it not return one at all. Of course, they might not have one set at all, if they registered using only their mobile. If your app needs and email address, then you should implement an additional step for users to input one manually. (Verification is your responsibility as well in that case.)

Body:
I'm trying to get the user's email after they press Continue with Facebook on my site. I've looked on Stackoverflow and through the Facebook Developer documentation and cannot see a reason why what I am trying isn't working.

JAVASCRIPT

window.fbAsyncInit = function() {
  FB.init({
    appId      : '1882306058687148',
    cookie     : true,
    xfbml      : true,
    version    : 'v2.8'
  });
  FB.AppEvents.logPageView();
  FB.getLoginStatus(function(response) {
    statusChangeCallback(response);
  });
};

(function(d, s, id){
  var js, fjs = d.getElementsByTagName(s)[0];
  if (d.getElementById(id)) {return;}
  js = d.createElement(s); js.id = id;
  js.src = "//connect.facebook.net/en_US/sdk.js";
  fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));

function checkLoginState() {
  FB.getLoginStatus(function(response) {
    console.log(response);
    statusChangeCallback(response)
  });
}

function statusChangeCallback(response) {
  console.log('statusChangeCallback');
  console.log(response);
  if (response.status === 'connected') {
    runAPI();
  }
}

function runAPI() {
  FB.api('/me', { locale: 'en_US', fields: 'name, email' }, function(response) {
    console.log(response);
    document.getElementById('name').value = response.name;
    document.getElementById('email').value = response.email;
    document.getElementById('fb-login').style.display = 'none'
  });
}

** HTML **

<fb:login-button scope="public_profile,email" onlogin="checkLoginState();">
</fb:login-button>

What's confusing me the most though is that this IS pulling the name through and that is definitely working.


问:
Alexa Unable to link your OAuth Skill
I am trying to link my skill to my OAuth 2.0 server.
I am using "Auth Code Grant".

In my server I receive from Alexa this:

{ client_id: 'alexa-skill',
  response_type: 'code',
  state: 'eyJpbml0VmVjdG9yIjoiTWYyemxRaGh6MGtScm9wUW8rRlE4dz09IiwicGF5bG9hZCI6InFQOTBDNW1TY2xueEcxbXFpaEpkcEJqYjRBNTFOa0VIazJHSjJLWERHL1NYQTRaa0tQL1MwMk5lVUlYSkE4NExXdVhXdkx5Q0JWVU52R28waTV0UkRqOGxZVk4rdEpxVmVEQ0ljT1hldXBnWkRseWZFUHY5MmJqb05CSk9ZWjFSYnh5ck5WdzB6NTRmOWU4a2JwRWJHMGVGRWJXS0ErMmhQSzRlajFLT3pjY2dxeVNxNm1hNS9UWENoU3lwYTJRS1k3ekdnN2VXbFNhd2FhN0twVjVhVlltbDRnMVFBY2h1QnBZVjdIUnEzVm5RVnVTY0JFVnlpbFJnOXludFIyRWpJY3JwTTArNjlESW53L3lqY05mdEJSaHdjSTNSQzdVbjd0TDQ5Q1NnZjB1cGFXS3pWNElFbWFZTVRPWERFc3d5cC9nWjd0eDF1SExnaHpEcCtCSVpNWXdzOWMrK2xib2N1YWl0UmhzaUFGbjJxTmxwV0ZOQzh4TkE5OXhVcUJxSVA0dDJXSkhCdUxnLzJzakJtMG1Wd0lySzFBUUhrUkkrVE5Cc0ROemFnUGhMVjdRQzgyZVdneG1EeFdVSThHZFNkRjJEL2ozb0NNYi83b1pGMlp3SXhIWG9WTGJ6azJOWGNwTk5WUkVzQ3ByODgyYW1MeFR3SUlhUWFQL1VVRFQydy85ckxBenVDUi9pN2UxREZxZW5kaXJzRXlwSnJ0RDQ4Wm05ZmtpTzR5YktiSUYwY2RPVU8vMi8yclJpcmZ5ZWFOWmt6SVNJNkRLUi9mQllXc0FVR3M2MXU0WTlaaktTc21DNCtPUWxieFRhOE1GeWFDNUFiaWJoLzFYR2xEQUpsaHIrVEloeWxrUDU0N1ltNWU4MGQyYndxSkxmVmNtcU1OelFHQUtkMWV3VjZyd3hwMXJiWTlnOGNVT3pqWUtYc05jMlRaSUVpUVN4U2FzQ2MxRVVQKzV1aldpeTdYMWlCb0VYZEtBRTBlQzM3MTFvbGlZNVVjL0FDS1pOWW1KUTBqUHJDdmpjU0Uxbk5KT2toaFJJOEhzUnArdjZlYmdWc2V2aDUwWk9aVm9RNlQ5bU5UZmhONzBDVFRVMjNLeS92am4vaE42c1N2YzNNeW4xT0lJMmNkODRRQVp5TFZJVkwwcjhWVWg0TFV2UTdaazV6ZW1OaTRDTTl0Vi95T2RiMUJkUGhSZ2hHQVozU1VOR3Z5aDA5QT09IiwidmVyc2lvbiI6MX0',
  redirect_uri: 'https://pitangui.amazon.com/api/skill/link/1111111111' }

After this I try to redirect to following url:

https://pitangui.amazon.com/api/skill/link/1111111111?state=eyJpbml0VmVjdG9yIjoiTWYyemxRaGh6MGtScm9wUW8rRlE4dz09IiwicGF5bG9hZCI6InFQOTBDNW1TY2xueEcxbXFpaEpkcEJqYjRBNTFOa0VIazJHSjJLWERHL1NYQTRaa0tQL1MwMk5lVUlYSkE4NExXdVhXdkx5Q0JWVU52R28waTV0UkRqOGxZVk4rdEpxVmVEQ0ljT1hldXBnWkRseWZFUHY5MmJqb05CSk9ZWjFSYnh5ck5WdzB6NTRmOWU4a2JwRWJHMGVGRWJXS0ErMmhQSzRlajFLT3pjY2dxeVNxNm1hNS9UWENoU3lwYTJRS1k3ekdnN2VXbFNhd2FhN0twVjVhVlltbDRnMVFBY2h1QnBZVjdIUnEzVm5RVnVTY0JFVnlpbFJnOXludFIyRWpJY3JwTTArNjlESW53L3lqY05mdEJSaHdjSTNSQzdVbjd0TDQ5Q1NnZjB1cGFXS3pWNElFbWFZTVRPWERFc3d5cC9nWjd0eDF1SExnaHpEcCtCSVpNWXdzOWMrK2xib2N1YWl0UmhzaUFGbjJxTmxwV0ZOQzh4TkE5OXhVcUJxSVA0dDJXSkhCdUxnLzJzakJtMG1Wd0lySzFBUUhrUkkrVE5Cc0ROemFnUGhMVjdRQzgyZVdneG1EeFdVSThHZFNkRjJEL2ozb0NNYi83b1pGMlp3SXhIWG9WTGJ6azJOWGNwTk5WUkVzQ3ByODgyYW1MeFR3SUlhUWFQL1VVRFQydy85ckxBenVDUi9pN2UxREZxZW5kaXJzRXlwSnJ0RDQ4Wm05ZmtpTzR5YktiSUYwY2RPVU8vMi8yclJpcmZ5ZWFOWmt6SVNJNkRLUi9mQllXc0FVR3M2MXU0WTlaaktTc21DNCtPUWxieFRhOE1GeWFDNUFiaWJoLzFYR2xEQUpsaHIrVEloeWxrUDU0N1ltNWU4MGQyYndxSkxmVmNtcU1OelFHQUtkMWV3VjZyd3hwMXJiWTlnOGNVT3pqWUtYc05jMlRaSUVpUVN4U2FzQ2MxRVVQKzV1aldpeTdYMWlCb0VYZEtBRTBlQzM3MTFvbGlZNVVjL0FDS1pOWW1KUTBqUHJDdmpjU0Uxbk5KT2toaFJJOEhzUnArdjZlYmdWc2V2aDUwWk9aVm9RNlQ5bU5UZmhONzBDVFRVMjNLeS92am4vaE42c1N2YzNNeW4xT0lJMmNkODRRQVp5TFZJVkwwcjhWVWg0TFV2UTdaazV6ZW1OaTRDTTl0Vi95T2RiMUJkUGhSZ2hHQVozU1VOR3Z5aDA5QT09IiwidmVyc2lvbiI6MX0&code=Akasa7I91495468793321

Alexa APP load page with message "Unable to link your OAuth Skill"

What I am doing wrong?

答:
Verify if the token returned from the Oauth2.0 system is in this format :

```<code>{
   "access_token":"2YotnFZFEjr1zCsicMWpAA",
   "token_type":"example",
   "expires_in":3600,
   "refresh_token":"tGzv3JOkF0XG5Qx2TlKWIA",
   "example_parameter":"example_value"
 }
</code>```

Please refer to this Oauth2.0 documentation here

Title: Alexa Unable to link your OAuth Skill

Body:
Verify if the token returned from the Oauth2.0 system is in this format :

{
   "access_token":"2YotnFZFEjr1zCsicMWpAA",
   "token_type":"example",
   "expires_in":3600,
   "refresh_token":"tGzv3JOkF0XG5Qx2TlKWIA",
   "example_parameter":"example_value"
 }

Please refer to this Oauth2.0 documentation here


问:
Bypass excel csv formula conversion on fields starting with + or -
I have a csv file with contents:

```<code>"x","y","-z"
</code>```

When I import it I get:

How can I bypass this conversion?

Update

If you try:

```<code>   "x","y",="-z,a"
</code>```

The ",a" is not imported.

If you put a space in front:

```<code>   "x","y",=" -z"
</code>```

or

```<code>   "x","y"," -z"
</code>```

it will work fine

答:
Prefix the values with equals signs</p>

```<code>="x",="y",="-z"
</code>```

Body:
I have a csv file with contents:

"x","y","-z"

When I import it I get:

How can I bypass this conversion?

Update

If you try:

   "x","y",="-z,a"

The ",a" is not imported.

If you put a space in front:

   "x","y",=" -z"

or

   "x","y"," -z"

it will work fine

Body:
Prefix the values with equals signs

="x",="y",="-z"


问:
Hide a button in SSRS pdf view but show in online view
I have a button in the SSRS report Report1. This buttons opens other report called DetailReport. In online view of the report for faster rendering the button on report1 opens the DetailReport. But when on pdf view the Button appears on the report, which is of no use.

I have found way to hide and show the entire page by passing parameter.

Using code for visiblity as :

```<code>=IIF(Parameters!ShowDetaiReport.Value=true,false,true)
</code>```

But the button is shown or hidden both online and in pdf.

Is there any way to show button in the online view but hide it when I download pdf or word. Can i replace the Button with report itself when I download it.

FYI: I am using SSRS 2012

答:
You can check to see what type of report is being rendered using the Globals!RenderFormat Built-in Field.  You can either use .Name to check for a specific render format - such as PDF or Excel - or you can simply use .IsInteractive to check if the user can actually click things.

You can apply this check in the Button's Visibility -> Show or hide based on an expression property value as follows: =iif(Globals!RenderFormat.IsInteractive, False, True)

If you want to test this without exporting your reports, you can preview in Print Layout, which isn't interactive.

Body:
I have a button in the SSRS report Report1. This buttons opens other report called DetailReport. In online view of the report for faster rendering the button on report1 opens the DetailReport. But when on pdf view the Button appears on the report, which is of no use.

I have found way to hide and show the entire page by passing parameter.

Using code for visiblity as :

=IIF(Parameters!ShowDetaiReport.Value=true,false,true)

But the button is shown or hidden both online and in pdf.

Is there any way to show button in the online view but hide it when I download pdf or word. Can i replace the Button with report itself when I download it.

FYI: I am using SSRS 2012


问:
Qt - How to show a QLabel in fullscreen on my laptop?
I have a ui with a QButton and a QLabel. I would like the QLabel to be displayed on fullscreen on my laptop whenever I push that button.

I tried the following code:

```<code>void MainWindow::on_fullScreenBtn_clicked()
{
    // ui->myImage is a QLabel*
    ui->myImage->setText("going full screen");
    ui->myImage->showMaximized();
    ui->myImage->QWidget::showFullScreen();
}
</code>```

I can see this function gets executed, but this doesn't display my label in full screen. What am I doing incorrectly/ missing?

I am using QtCreator 3.5.1 and made my gui using the built-in graphical interface.

EDIT: The variable myImage is a QLabel containing an image

答:
Are you calling the show() method on your MainWindow instance, in your main function? Something like that:</p>

```<code>int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow window;

    window.showMaximized();

    return a.exec();
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a ui with a QButton and a QLabel. I would like the QLabel to be displayed on fullscreen on my laptop whenever I push that button.

I tried the following code:

void MainWindow::on_fullScreenBtn_clicked()
{
    // ui->myImage is a QLabel*
    ui->myImage->setText("going full screen");
    ui->myImage->showMaximized();
    ui->myImage->QWidget::showFullScreen();
}

I can see this function gets executed, but this doesn't display my label in full screen. What am I doing incorrectly/ missing?

I am using QtCreator 3.5.1 and made my gui using the built-in graphical interface.

EDIT: The variable myImage is a QLabel containing an image

Body:
Are you calling the show() method on your MainWindow instance, in your main function? Something like that:

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow window;

    window.showMaximized();

    return a.exec();
}


问:
Dynamic attribute name
I defined this constant:

```<code>constant('countries', [{
            NAME_IT: "Francia",
            NAME_US: "France"
        },
        {
            NAME_IT: "Italy",
            NAME_US: "Italia"
        }
    ]);
</code>```

I want to display the name of the country following a language (IT or US) that I define in my controller language:

```<code><ul>
    <li ng-repeat="cc in ctrl.countries">
        <!-- cc.NAME_US or cc.NAME_IT -->
    </li>
</ul>
</code>```

I can't find a way to display the dynamic attribute NAME_US or NAME_IT. How can I do that?

Thanks!

答:
I finally created a method in my controller that returns the value of the name like this:

```<code>getCountryName(country) {
        return country["NAME_" + this.profile.language];
    }
</code>```

This way I no longer have a problem of a dynamic attibute name, I just call my method:

```<code><li ng-repeat="cc in countriesList">
      {{ctrl.getCountryName()}}
</li>
</code>```

Title: Dynamic attribute name

Body:
I defined this constant:

constant('countries', [{
            NAME_IT: "Francia",
            NAME_US: "France"
        },
        {
            NAME_IT: "Italy",
            NAME_US: "Italia"
        }
    ]);

I want to display the name of the country following a language (IT or US) that I define in my controller language:

I can't find a way to display the dynamic attribute NAME_US or NAME_IT. How can I do that?

Thanks!

Body:
I finally created a method in my controller that returns the value of the name like this:

getCountryName(country) {
        return country["NAME_" + this.profile.language];
    }

This way I no longer have a problem of a dynamic attibute name, I just call my method:

<li ng-repeat="cc in countriesList">
      {{ctrl.getCountryName()}}
</li>


问:
Some times Toast is not visible in activity or inside fragment when added inside handler
Requirement is that toast will be show some delay in fragment  so add inside the handler.
But sometime that toast is not visible. There are some loader operations and fragment transaction action before toast.</p>

```<code>final Handler handler = new Handler(getMainLooper());
    handler.postDelayed(new Runnable() {
        @Override
        public void run() {
            //Do something after 100ms\
        Toast.makeText(getActivity,message,Toast.LENGTH_SHORT).show();

        }
    }, 100);
</code>```

答:
Use Log tag.</p>

```<code>final Handler handler = new Handler(getMainLooper());
handler.postDelayed(new Runnable() {
    @Override
    public void run() {
        //Do something after 100ms\
        Log.d("MyLogTag", message);
    }
}, 100);
</code>```

Body:
Requirement is that toast will be show some delay in fragment  so add inside the handler.
But sometime that toast is not visible. There are some loader operations and fragment transaction action before toast.

final Handler handler = new Handler(getMainLooper());
    handler.postDelayed(new Runnable() {
        @Override
        public void run() {
            //Do something after 100ms\
        Toast.makeText(getActivity,message,Toast.LENGTH_SHORT).show();

        }
    }, 100);

Body:
Use Log tag.

final Handler handler = new Handler(getMainLooper());
handler.postDelayed(new Runnable() {
    @Override
    public void run() {
        //Do something after 100ms\
        Log.d("MyLogTag", message);
    }
}, 100);


问:
How do I detect unicode characters in a Java string?
Suppose I have a string that contains Ü. How would I find all those unicode characters? Should I test for their code? How would I do that?

For example, given the string "AÜXÜ", I'd like to transform it to "AYXY". I'd like to do the same for other unicode characters, and I would hate to have to store them in a translation map of some sort.

答:
The class Character also offers some interesting methods. Take a look at it.

```<code>Character.UnicodeBlock.of('a') == Character.UnicodeBlock.BASIC_LATIN; //true

Character.UnicodeBlock.of('�') == Character.UnicodeBlock.BASIC_LATIN; //false
</code>```

Body:
The class Character also offers some interesting methods. Take a look at it.

Character.UnicodeBlock.of('a') == Character.UnicodeBlock.BASIC_LATIN; //true

Character.UnicodeBlock.of('�') == Character.UnicodeBlock.BASIC_LATIN; //false


问:
How do I refactor Swift in Xcode?
Is there a way to refactor swift in Xcode 7.1?

When I try to rename a variable (e.g. highlight, right-click, refactor > rename), Xcode pops up an error dialog saying:

Can't refactor Swift code. Xcode can only refactor C and Objective-C code.

Is there a workaround for this?

答:
Xcode 9 - 10

Xcode 9 now supports refactoring in Swift. This was announced in WWDC 2017.

Title: How do I refactor Swift in Xcode?


问:
Difference between init() and main() method in java
I want to know the difference between init and main method of java </p>

答:
static void main is usually the declaration for a method which allows an entry point for launching the Java file/application. however, main can also be used to name any random method.

while init is one of the many random names which can be selected for naming a method [satisfying the basic rules for naming methods]. typically, programmers, in Java or any other programming language, like to name a method init if there's some initialisation routine to be run.


问:
Easiest way to check ip address against a range of values using c#
We are writing a feature that allows an administrator to block/allow ranges of ip addresses.

Is this easy enough to do with c#?

I was thinking of looking at each number [here].[here].[here].[here] and then mathing it with the ranges and just seeing if each number was between the two?

Will that work for standard ip v4 addresses?

答:
I'd convert them to integers and then compare the integer. But what's correct depends on how you define ranges.

```<code>UInt32 Ip4ToInt(string ip)
{
  UInt32[] parts=ip.Split('.').Select(s=>UInt32.Parse(s)).ToArray();
  if (parts.Length != 4)
    throw new ArgumentException("InvalidIP");
  return (parts[0]<<24) | (parts[1]<<16) | (parts[2]<<8) | parts[3];
}
</code>```

For example should 1.1.1.99 be part of the range 1.1.1.1 - 1.1.2.2? When comparing each group it isn't, when comparing the integers it is.

Body:
I'd convert them to integers and then compare the integer. But what's correct depends on how you define ranges.

UInt32 Ip4ToInt(string ip)
{
  UInt32[] parts=ip.Split('.').Select(s=>UInt32.Parse(s)).ToArray();
  if (parts.Length != 4)
    throw new ArgumentException("InvalidIP");
  return (parts[0]<<24) | (parts[1]<<16) | (parts[2]<<8) | parts[3];
}

For example should 1.1.1.99 be part of the range 1.1.1.1 - 1.1.2.2? When comparing each group it isn't, when comparing the integers it is.