问:
Zenity GUI for chattr and lsattr
Description:

Hello Stackers, i'm currently making a zenity GUI for the command chattr. What i'm trying to do is to show and change the attributes of a file using zenity --list --checklist to tick the attributes that i want an so, but the main issue that i'm facing is that i do not know whats the order of lsattr output, something like: -------------e-- file

Code sample:

```<code>attr=("A" "Solo escritura" "a" "No actualizar" "c" "Comprimido" "C" "No copiar en escritura" "D" "Actualización de directorio sincrónica" "d" "Ignorar en backup" "E" "Error de compreción" "e" "Usando extents" "h" "Archivo enorme" "I" "Indexación hashed trees" "i" "Archivo inmutable" "j" "Registro de datos" "s" "Borrado seguro" "S" "Actualización sincrónica" "T" "Directorio tope" "t" "Archivo sin cola" "u" "Deshacer borrado" "X" "Acceso crudo dec compreción" "Z" "Archivo comprimido sucio" "-v" "Generar verción de archivo")

fileattr=$(lsattr "$file") ; j=0 ; k=1

for (( i=1; i<=15; i++ )); do
    [[ "${fileattr:$i:1}" != "-" ]] && values+="true ${attr[$j]} ${attr[$k]//' '/_} " && setted+="${attr[$j]} " ||\
    values+="false ${attr[$j]} ${attr[$k]//' '/_} "
    ((j+=2)) ; ((k+=2))
done

zenity --list --checklist --column="Estado" --column="Atributo" --column="Descripción" ${values}
</code>```

Code explanation:

attr is an array and is ordered using this page

The for loop runs 15 times (it's equal to the amount of file attributes returned by lsattr), and in each go it validates for not setted attributes "-", if an attribute is set then append "true attr[j] attr[k]" to values and append the attribute to setted (for later on purposes) or append "false attr[j] attr[k]" to values

Finally call zenity with the collected values

Launching output:

Zenity window
It tells me that the "s" attribute is set but thats not true because the lsattr output is -------------e-- file. I have noticed that there are more attributes in the page than in the lsattr output

Note:

I know, maybe i'm not using the correct aproach, so if you can find a better way to do it, i'm all ears.

Thanks.

答:
Associative arrays will be useful in this task.

Let's define a list of all the possible attributes:

```<code>valueList=acdeijstuACDST
</code>```

Let's define an associative array to store the values:

```<code>declare -A valueMap
</code>```

Initialize the map with all false values for all attributes:

```<code>for ((i = 0; i < ${#valueList}; i++)); do
    name=${valueList:i:1}
    valueMap[$name]=false
done
</code>```

Loop over characters in fileattr to update values in the map to true:

```<code>for ((i = 0; i < 16; i++)); do
    name=${fileattr:i:1}
    [[ $name != - ]] && valueMap[$name]=true
done
</code>```

Combine valueMap and your original attr to create an array of values to pass to Zenity:

```<code>zenityValues=()
for ((i = 0; i < ${#attr[@]}; i+=2)); do
    name=${attr[i]}
    description=${attr[i+1]}
    zenityValues+=(${valueMap[name]} "$name" "$description")
done
</code>```

And finally call Zenity as you did, but passing zenityValues as an array:

```<code>zenity ... "${zenityValues[@]}"
</code>```

Title: Zenity GUI for chattr and lsattr

Body:
Description:

Hello Stackers, i'm currently making a zenity GUI for the command chattr. What i'm trying to do is to show and change the attributes of a file using zenity --list --checklist to tick the attributes that i want an so, but the main issue that i'm facing is that i do not know whats the order of lsattr output, something like: -------------e-- file

Code sample:

attr=("A" "Solo escritura" "a" "No actualizar" "c" "Comprimido" "C" "No copiar en escritura" "D" "Actualización de directorio sincrónica" "d" "Ignorar en backup" "E" "Error de compreción" "e" "Usando extents" "h" "Archivo enorme" "I" "Indexación hashed trees" "i" "Archivo inmutable" "j" "Registro de datos" "s" "Borrado seguro" "S" "Actualización sincrónica" "T" "Directorio tope" "t" "Archivo sin cola" "u" "Deshacer borrado" "X" "Acceso crudo dec compreción" "Z" "Archivo comprimido sucio" "-v" "Generar verción de archivo")

fileattr=$(lsattr "$file") ; j=0 ; k=1

for (( i=1; i<=15; i++ )); do
    [[ "${fileattr:$i:1}" != "-" ]] && values+="true ${attr[$j]} ${attr[$k]//' '/_} " && setted+="${attr[$j]} " ||\
    values+="false ${attr[$j]} ${attr[$k]//' '/_} "
    ((j+=2)) ; ((k+=2))
done

zenity --list --checklist --column="Estado" --column="Atributo" --column="Descripción" ${values}

Code explanation:

attr is an array and is ordered using this page

The for loop runs 15 times (it's equal to the amount of file attributes returned by lsattr), and in each go it validates for not setted attributes "-", if an attribute is set then append "true attr[j] attr[k]" to values and append the attribute to setted (for later on purposes) or append "false attr[j] attr[k]" to values

Finally call zenity with the collected values

Launching output:

Zenity window
It tells me that the "s" attribute is set but thats not true because the lsattr output is -------------e-- file. I have noticed that there are more attributes in the page than in the lsattr output

Note:

I know, maybe i'm not using the correct aproach, so if you can find a better way to do it, i'm all ears.

Thanks.

Body:
Associative arrays will be useful in this task.

Let's define a list of all the possible attributes:

valueList=acdeijstuACDST

Let's define an associative array to store the values:

declare -A valueMap

Initialize the map with all false values for all attributes:

for ((i = 0; i < ${#valueList}; i++)); do
    name=${valueList:i:1}
    valueMap[$name]=false
done

Loop over characters in fileattr to update values in the map to true:

for ((i = 0; i < 16; i++)); do
    name=${fileattr:i:1}
    [[ $name != - ]] && valueMap[$name]=true
done

Combine valueMap and your original attr to create an array of values to pass to Zenity:

zenityValues=()
for ((i = 0; i < ${#attr[@]}; i+=2)); do
    name=${attr[i]}
    description=${attr[i+1]}
    zenityValues+=(${valueMap[name]} "$name" "$description")
done

And finally call Zenity as you did, but passing zenityValues as an array:

zenity ... "${zenityValues[@]}"


来源: stackexchange

问:
Automation using AWS Elastic Beanstalk vs AWS CodeDeploy
I am using AWS Elastic Beanstalk and have deployed my nodejs app on it. Now I want to automate this process i.e committing changes to Github and then automatically reflecting those changes in app. Now I have two options, use whether Elastic Beanstalk or using Code Deploy.
I have searched on both services,

I can automate using deployBot with elastic beanstalk or using
jenkins plugin for automation (AWS Elastic Beanstalk Deployment
Plugin) for elastic beanstalk.
Also found this link to automate:
https://aws.amazon.com/blogs/devops/building-continuous-deployment-on-aws-with-aws-codepipeline-jenkins-and-aws-elastic-beanstalk/

I can also use AWS CodeDeploy service for automation to deploy my app on EC2
instances using CodeCommit , code pipeline.
In case of code deploy I can also do by using this:
https://aws.amazon.com/blogs/devops/automatically-deploy-from-github-using-aws-codedeploy/

Now both services can be used , but which one is more suitable to use. That will automate my process whether using AWS Elastic Beanstalk or AWS Code Deploy.

答: Use the second option instead of using third party tools as AWS platform is supporting to deploy your app using git or bitbucket using python based scripts.</p>

ContentLicense: CC BY-SA 4.0

ContentLicense: CC BY-SA 3.0


问:
image recognition and detection algorithm based on depth image
I get a depth camera whose output is grayscale image with depth information. Is there any image recognition and detection algorithm based on depth image (especially for embedded system)?</p>

答: Any image processing algorithm can be applied to depth images. Human interpretation is slightly different. Mathematically it's the same as any other 2d image.</p>


问:
Running multiple Angular Apps on common node server
I am new to the mean stack. I want to build application having admin and client. So I built two angular 2 apps in my node. But I am not able to render admin app and client app based on router. For example when router is / my client app should render and on /admin my admin app should render.

Please help me to structure my directory an solution to my problem .I am using express for Routing.

答:
You have to assign different port to your both apps.

```<code>ng serve --port 4210 --live-reload-port 4950
</code>```

Open your second project and fire above command.

See : Click here

Body:
You have to assign different port to your both apps.

ng serve --port 4210 --live-reload-port 4950

Open your second project and fire above command.

See : Click here


问:
How to find index in AngularJS through directive?
I have tried to get index like this

this is my html

```<code>  <div ng-repeat="item in items" ng-click="findindex($index)"></div>
</code>```

this is controller

```<code> $sceop.findinedx=function(index)
{
    alert(index);
}
</code>```

here i am able to get index value.but i want to get index value through directive

this is my html

```<code> <div ng-repeat="item in items" my-directive></div>
</code>```

this is my directive

```<code>   app.directive('myDirective',function()
   {
        return function(scope, elem, attrs,$index)
        {
              elem.bind('click', function($index)
              {
                   alert($index);
              });
        });
   };
</code>```

here i am not able to get index..so how to get index value in directive?

答:
Use in the directive attribute "let ind=index"

For example :

```<code><ul>
    <li *ngFor="let i of items; let ind= index">
        {{i}}
        <span (click)="removeItem()" class="remove_link">X</span>
    </li>
</ul>
</code>```

Body:
I have tried to get index like this

this is my html

this is controller

 $sceop.findinedx=function(index)
{
    alert(index);
}

here i am able to get index value.but i want to get index value through directive

this is my html

this is my directive

   app.directive('myDirective',function()
   {
        return function(scope, elem, attrs,$index)
        {
              elem.bind('click', function($index)
              {
                   alert($index);
              });
        });
   };

here i am not able to get index..so how to get index value in directive?

Body:
Use in the directive attribute "let ind=index"

For example :

<ul>
    <li *ngFor="let i of items; let ind= index">
        {{i}}
        <span (click)="removeItem()" class="remove_link">X</span>
    </li>
</ul>


问:
How to fetch (extract) text from image which is in gallery and search that text - Android?
I want to do that I have thousands of images on my phone and I want to fetch text from an image like below image: for example, i have above image on my phone and I want to fetch text "Sample Source Code" which is written in image. so how can we do that in android I have to try Google Vision API also gives sometimes correct text but sometimes not accurate. so is there any other option for this?

答:
First you need to create a Demo for

Optical Character Recognition on Android – OCR

to fetch text from images.

Here posted some helpful links:-

1.Android OCR Library

2.https://github.com/abbyysdk/ocrsdk.com

3.http://www.truiton.com/2016/11/optical-character-recognition-android-ocr/

4.https://github.com/renard314/textfairy

5.https://github.com/rmtheis/android-ocr

6.https://github.com/priyankvex/Easy-Ocr-Scanner-Android

Many Examples you get from internet just Google it. hope this helps you.


问:
new Random().nextInt(999999) sometimes generates 5 digit number
I am using new Random().nextInt(999999) to generate a 6 digit random number. But sometimes it generates 5 digit numbers. And I explicitly have to check if generated number is not 6 digit.

Why this method does that? And is there any other way to be pretty sure it generate only 6 digit random number.

答:
Random().nextInt(999999) generates 5 digits number sometimes, because it generates random values between 0 and 999999.

Use the following snippet for generating random numbers in a range:

```<code>Random random = new Random();
minimum + random.nextInt(maximum - minimum + 1);
</code>```

Body:
Random().nextInt(999999) generates 5 digits number sometimes, because it generates random values between 0 and 999999.

Use the following snippet for generating random numbers in a range:

Random random = new Random();
minimum + random.nextInt(maximum - minimum + 1);


问:
Populating values for DropDownListFor from Database
I have 2 dropdownlist whose values should be populated from database.
I have checked the stored proc and its giving correct results. I have even debugged upto controller and it looks like I am getting right values.

I need help in figuring out the @Html.DropDownlistFor syntax. What i am using is incorrect. Any help?

Model:

```<code>  public class DropDownConfiguration
        {
            public string Project { get; set; }

            public string LineID { get; set; }

        }
</code>```

Controller:

```<code>[ActionName("DetailsForm")]
        [HttpGet]
        public ActionResult DetailsForm()
        {
            try
            {
                IEnumerable<DropDownConfiguration> dropConfig = new List<DropDownConfiguration>();

                dropConfig = floorService.DropDownList();

                DetailsViewModel model = new DetailsViewModel()
             {

                 dropConfig = dropConfig,
             };
                return View("DetailsForm",model);

            }
            catch (Exception ex)
            {
                return View("_error");
            }

        }
</code>```

Repository:

```<code> public IEnumerable<DropDownConfiguration> DropDownList()
          {
              var model = new List<DropDownConfiguration>();

              using (var dbCmd = defaultDB.GetStoredProcCommand("dbo.GetLineIDProject"))
              {

                  var varCmd = defaultDB.ExecuteReader(dbCmd);

                  while (varCmd.Read())
                  {
                      model.Add(new DropDownConfiguration()
                        {
                            LineID = varCmd.IsDBNull(0) ? "" : varCmd.GetString(0),
                            Project = varCmd.IsDBNull(1) ? "" : varCmd.GetString(1),
                            Quarter = varCmd.IsDBNull(2) ? 0 : varCmd.GetInt32(2),
                            Year = varCmd.IsDBNull(3) ? 0 : varCmd.GetInt32(3)

                        });

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

Html (Here are the 2 dropdown list LineID, Project)-----NEED HELP HERE------

```<code>@Html.DropDownListFor(m => m.dropConfig.FirstOrDefault().LineID, "--Select LineID--", new { @class = "form-control" })

@Html.DropDownListFor(m => m.dropConfig.FirstOrDefault().Project, "--Select Project--", new { @class = "form-control" })
</code>```

On debugging @Controller:

答:
What you need to do, is to create a new select list.

```<code>  public class DropDownConfiguration
        {
            public string Project { get; set; }

            public string LineID { get; set; }

            public SelectList dropDownSelectList{ get; set; }

        }

[ActionName("DetailsForm")]
        [HttpGet]
        public ActionResult DetailsForm()
        {
            try
            {
             DropDownConfiguration dropConfig = new DropDownConfiguration();

       IEnumrebale<DropDownConfiguration> selectList = floorService.DropDownList();

                DetailsViewModel model = new DetailsViewModel()
             {

                 dropConfig = selecrList ,
             };
                dropConfig.dropDownSelectList  = new SelectList(selectList, "Value", "Text");
                return View("DetailsForm",model);

            }
            catch (Exception ex)
            {
                return View("_error");
            }

        }
</code>```

Your View:

```<code>@Html.DropDownListFor(m => m.LineID, Model.dropDownSelectList, "--Select LineID--", new { @class = "form-control" })
</code>```

Your code is unclear. Controller model and repository is not written properly, I have no idea why you have separated the model and create repository class (as business logic should be in the model.
There is no clue as to what your DetailsViewModel includes and it seems you have no use for it either.

And when you user first of default in your view the way you did, it means that when you submit the form, you will always get the value of the first field or null, as you didn't populate any values and furthermore if your aim was to populate the drop down list, you would have populated only one field.

Review your code, make the necessary changes as I have shown in the snippet and make sure your code is clear.

Body:
I have 2 dropdownlist whose values should be populated from database.
I have checked the stored proc and its giving correct results. I have even debugged upto controller and it looks like I am getting right values.

I need help in figuring out the @Html.DropDownlistFor syntax. What i am using is incorrect. Any help?

Model:

  public class DropDownConfiguration
        {
            public string Project { get; set; }

            public string LineID { get; set; }

        }

Controller:

[ActionName("DetailsForm")]
        [HttpGet]
        public ActionResult DetailsForm()
        {
            try
            {
                IEnumerable<DropDownConfiguration> dropConfig = new List<DropDownConfiguration>();

                dropConfig = floorService.DropDownList();

                DetailsViewModel model = new DetailsViewModel()
             {

                 dropConfig = dropConfig,
             };
                return View("DetailsForm",model);

            }
            catch (Exception ex)
            {
                return View("_error");
            }

        }

Repository:

 public IEnumerable<DropDownConfiguration> DropDownList()
          {
              var model = new List<DropDownConfiguration>();

              using (var dbCmd = defaultDB.GetStoredProcCommand("dbo.GetLineIDProject"))
              {

                  var varCmd = defaultDB.ExecuteReader(dbCmd);

                  while (varCmd.Read())
                  {
                      model.Add(new DropDownConfiguration()
                        {
                            LineID = varCmd.IsDBNull(0) ? "" : varCmd.GetString(0),
                            Project = varCmd.IsDBNull(1) ? "" : varCmd.GetString(1),
                            Quarter = varCmd.IsDBNull(2) ? 0 : varCmd.GetInt32(2),
                            Year = varCmd.IsDBNull(3) ? 0 : varCmd.GetInt32(3)

                        });

                  }
              }
              return model;
          }

Html (Here are the 2 dropdown list LineID, Project)-----NEED HELP HERE------

@Html.DropDownListFor(m => m.dropConfig.FirstOrDefault().LineID, "--Select LineID--", new { @class = "form-control" })

@Html.DropDownListFor(m => m.dropConfig.FirstOrDefault().Project, "--Select Project--", new { @class = "form-control" })

On debugging @Controller:

Body:
What you need to do, is to create a new select list.

  public class DropDownConfiguration
        {
            public string Project { get; set; }

            public string LineID { get; set; }

            public SelectList dropDownSelectList{ get; set; }

        }

[ActionName("DetailsForm")]
        [HttpGet]
        public ActionResult DetailsForm()
        {
            try
            {
             DropDownConfiguration dropConfig = new DropDownConfiguration();

       IEnumrebale<DropDownConfiguration> selectList = floorService.DropDownList();

                DetailsViewModel model = new DetailsViewModel()
             {

                 dropConfig = selecrList ,
             };
                dropConfig.dropDownSelectList  = new SelectList(selectList, "Value", "Text");
                return View("DetailsForm",model);

            }
            catch (Exception ex)
            {
                return View("_error");
            }

        }

Your View:

@Html.DropDownListFor(m => m.LineID, Model.dropDownSelectList, "--Select LineID--", new { @class = "form-control" })

Your code is unclear. Controller model and repository is not written properly, I have no idea why you have separated the model and create repository class (as business logic should be in the model.
There is no clue as to what your DetailsViewModel includes and it seems you have no use for it either.

And when you user first of default in your view the way you did, it means that when you submit the form, you will always get the value of the first field or null, as you didn't populate any values and furthermore if your aim was to populate the drop down list, you would have populated only one field.

Review your code, make the necessary changes as I have shown in the snippet and make sure your code is clear.


问:
PHP - File upload - What is happening internally?
For image upload  we use FILE html controller.

How this html controller able to browse in the local system?

After selecting a file , it will be copied and moved to server location.

If the php is ale to copy the local file and move to server , will it be able to do any other manipulations of that file ? like delete!

What is happening actually on file upload?

答:
The HTML control is provided by the browser. The browser is a local application and has access to the user's file system. The file's contents are sent to the receiving script by the browser using standard methods.

PHP has no access to the user's file system at any point, just the copy provided by the browser. Deleting or even reading files on the user's file system is not possible.

ContentLicense: CC BY-SA 2.5


问:
php include from file loader object no keeping variable
First I will explain what I'm trying to do, I'm working on a php router for experimenting on how they work and in a object I'm instanciating the router object and I can create routes no problem there.

Now I'm trying something a bit more complicated, I want to be able to load routes from files included from a folder named routes where I won't know in advance the files name. Still no problem there, pretty simple.

Doing my inclusion, I thought, why leave the include inside the object, I should create à fileLoader object that will be dedicated to recursively load the files from a folder. I did it, and made a new object.

Now when calling my loader object, the $router variable that should be set, isn't and I can't create routes because of undefined variable. A bit of code for explanation.

This is the function that call the router object:

```<code>private function projectRooting(){

        $router = new Router\Router($this->baseUri);

        $fileLoader = new FileLoader();
        $fileLoader -> loadFolder($this->fullDirName, "/routes");

        // include_once($this->fullDirName."/routes/web.php");

        $router->run();
    }
</code>```

This is the function from the fileLoader:

```<code>public function loadFolder(string $path, string $directory){
        $theDirectory = $path. "/" .$directory;
        $files = scandir($theDirectory);

        foreach($files as $file){
            if(is_file($theDirectory. "/" .$file))
                include_once($theDirectory. "/" .$file);
            else{
                if($file != "." && $file != "..")
                    $this->loadFolder($path, $directory. "/" .$file);
            }
        }
    }
</code>```

A route example from the include file:

```<code>$router->get("/", function(){echo "Welcome on the home page!";});
</code>```

Now with the uncommented code, it won't work, but if I comment the $fileLoader part and uncomment the include_once, everything goes on again.

Have I missed something in the way include works when called from another object?

Thanks in advance if you reply, and sorry for my poor english.

答:
I think you are with scope problems, your $route variable is not acessible inside the included file. Try use global variables scope:

```<code>private function projectRooting(){
  global $router;
  $router = new Router\Router($this->baseUri);
  ...
</code>```

Then, inside your included file put it

```<code>global $router;
$router->get("/", function(){echo "Welcome on the home page!";});
</code>```

It probably must works, now, why the simply include_once works?

The problem is the loadFolder function, when you call it the include_once inside this function has no reference to $router variable, it means if you paste all loadFolder content inside projectRooting function then it will probably works.

Another way to solve it is to pass $router by argument to loadFolder function.

Body:
First I will explain what I'm trying to do, I'm working on a php router for experimenting on how they work and in a object I'm instanciating the router object and I can create routes no problem there.

Now I'm trying something a bit more complicated, I want to be able to load routes from files included from a folder named routes where I won't know in advance the files name. Still no problem there, pretty simple.

Doing my inclusion, I thought, why leave the include inside the object, I should create à fileLoader object that will be dedicated to recursively load the files from a folder. I did it, and made a new object.

Now when calling my loader object, the $router variable that should be set, isn't and I can't create routes because of undefined variable. A bit of code for explanation.

This is the function that call the router object:

private function projectRooting(){

        $router = new Router\Router($this->baseUri);

        $fileLoader = new FileLoader();
        $fileLoader -> loadFolder($this->fullDirName, "/routes");

        // include_once($this->fullDirName."/routes/web.php");

        $router->run();
    }

This is the function from the fileLoader:

public function loadFolder(string $path, string $directory){
        $theDirectory = $path. "/" .$directory;
        $files = scandir($theDirectory);

        foreach($files as $file){
            if(is_file($theDirectory. "/" .$file))
                include_once($theDirectory. "/" .$file);
            else{
                if($file != "." && $file != "..")
                    $this->loadFolder($path, $directory. "/" .$file);
            }
        }
    }

A route example from the include file:

$router->get("/", function(){echo "Welcome on the home page!";});

Now with the uncommented code, it won't work, but if I comment the $fileLoader part and uncomment the include_once, everything goes on again.

Have I missed something in the way include works when called from another object?

Thanks in advance if you reply, and sorry for my poor english.

Body:
I think you are with scope problems, your $route variable is not acessible inside the included file. Try use global variables scope:

private function projectRooting(){
  global $router;
  $router = new Router\Router($this->baseUri);
  ...

Then, inside your included file put it

global $router;
$router->get("/", function(){echo "Welcome on the home page!";});

It probably must works, now, why the simply include_once works?

The problem is the loadFolder function, when you call it the include_once inside this function has no reference to $router variable, it means if you paste all loadFolder content inside projectRooting function then it will probably works.

Another way to solve it is to pass $router by argument to loadFolder function.


问:
How to type in Android Emulator using PC-Keyboard
I can not type in Emulator using PC-Keyboard.

can anyone help me ?

答:
Android Studio -> Tools -> Android -> AVD Manager -> Will show list of Virtual devices
Edit(pencil icon) of device you want to update settings ->Show Advanced Settings  -> Keyboard -> Check Enable Keyboard Input ->Finish.


问:
declare variable inside or outside a loop, does it make big difference?
for example

```<code>int i, a, c, d; // these vars will only be used in while
while(bigNumber--) {
    i = doSomething();
    // **

}
</code>```

and

```<code>while(bigNumber--) {
   int i, a, b, c; // i'd like to put it here for readability
   i = doSomething();
   // **
}
</code>```

Does it make big difference in terms of performance?

答:
The only difference I can see in assembly results is the location of a movl    $0, -4(%rbp) instruction. In theory there may be a performance penalty for codes that use data which is spread more widely among memory (that will make your code less cache-friendly in theory)

In practise there will be no difference. Cache is big enough, Optimization will make both codes generate the same assembly, and most probably the code will be re-ordered. Following is a simple test case with all optimizations turned off and on.

Assembly results:

Code:

Turning on optimizers will generate exact same result:

Body:
for example

int i, a, c, d; // these vars will only be used in while
while(bigNumber--) {
    i = doSomething();
    // **

}

and

while(bigNumber--) {
   int i, a, b, c; // i'd like to put it here for readability
   i = doSomething();
   // **
}

Does it make big difference in terms of performance?


问:
Spring MVC @ModelAttribute not working with user defined dependency

I am trying to bind the data using @ModelAttribute. I have two user-defined classes named Address and Student. The structure of the these two data classes are as follows:

Address.java :

```<code>package org.manya.dataClasses;

public class Address {

    private String city;
    private String state;

    public Address(String city,String state)
    {
        this.city = city;
        this.state = state;
        System.out.println("from the constructor of Address");
    }

    public Address()
    {
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public String getState() {
        return state;
    }

    public void setState(String state) {
        this.state = state;
    }

}
</code>```

Student.java :

```<code>package org.manya.dataClasses;

public class Student {

    private String name;
    private int age;
    private Address studentAddress;

    public Student(String name,int age,Address studentAddress)
    {
        System.out.println("from the constructor of Student = ");
        if(studentAddress == null)
        {
            System.out.println("address is null");
        }
        this.name = name;
        this.age = age;
        this.studentAddress= studentAddress;
    }

    public Student()
    {

    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public Address getAddress() {
        return studentAddress;
    }

    public void setAddress(Address studentAddress) {
        this.studentAddress = studentAddress;
    }

}
</code>```

Using @ModelAttribute i am trying to bind the Student object but only the
  String and int properties are getting binded but the Address dependency is  null only.

web.xml

```<code>    <?xml version="1.0" encoding="UTF-8"?>
    <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://java.sun.com/xml/ns/javaee   http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
      <display-name>Archetype Created Web Application</display-name>

     <servlet>
        <servlet-name>frontController</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
     </servlet>

     <servlet-mapping>
        <servlet-name>frontController</servlet-name>
        <url-pattern>/</url-pattern>
     </servlet-mapping>

    </web-app>

**frontController-servlet.xml**

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:context = "http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
                        http://www.springframework.org/schema/context
                        http://www.springframework.org/schema/context/spring-context-3.0.xsd
                        http://www.springframework.org/schema/mvc
                        http://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <context:annotation-config/>
    <context:component-scan base-package="org.manya.Controllers"></context:component-scan>
    <mvc:annotation-driven/>
    <!-- <mvc:resources location="/resources/**" mapping="/home/*"></mvc:resources>
 -->

    <mvc:resources location="/resources/**" mapping="/static/**"/>
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
    <!-- <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/resources/"/>
        <property name="suffix" value=".html"/>
    </bean> -->

</beans>
</code>```

StudentController.java

```<code>package org.manya.Controllers;

import org.manya.dataClasses.Address;
import org.manya.dataClasses.Student;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping("/student")
public class StudentController {

    @GetMapping("/studentForm")
    public String admissionForm()
    {
        return "admissionForm";
    }

    @PostMapping("/submitted")
    public ModelAndView submitted(@ModelAttribute("student") Student stud)
    {
        ModelAndView mv = new ModelAndView("submitted");
        return mv;

    }
}
</code>```

admissionForm.jsp

```<code><%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>

<!-- <form action="./submitted" method="post">
    NAME : <input name="name"/>
    AGE : <input name="age"/>
    CITY : <input type="text" name="city"/>
    STATE : <input type="text" name="state"/>
    SUBMIT : <input type="submit"/>
</form> -->

<form action="./submitted" method="post">
    NAME : <input name="name"/>
    AGE : <input name="age"/>
    CITY : <input type="text" name="studentAddress.city"/>
    STATE : <input type="text" name="studentAddress.state"/>
    SUBMIT : <input type="submit"/>
</form>

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

答: In the Student class you have getter and setter for studentAddress field as getAddress() and setAddress. I think you need to change these method names to getStudentAddress() and setStudentAddress(). Let me know if it works.

Body:
I am trying to bind the data using @ModelAttribute. I have two user-defined classes named Address and Student. The structure of the these two data classes are as follows:

Address.java :

package org.manya.dataClasses;

public class Address {

    private String city;
    private String state;

    public Address(String city,String state)
    {
        this.city = city;
        this.state = state;
        System.out.println("from the constructor of Address");
    }

    public Address()
    {
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public String getState() {
        return state;
    }

    public void setState(String state) {
        this.state = state;
    }

}

Student.java :

package org.manya.dataClasses;

public class Student {

    private String name;
    private int age;
    private Address studentAddress;

    public Student(String name,int age,Address studentAddress)
    {
        System.out.println("from the constructor of Student = ");
        if(studentAddress == null)
        {
            System.out.println("address is null");
        }
        this.name = name;
        this.age = age;
        this.studentAddress= studentAddress;
    }

    public Student()
    {

    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public Address getAddress() {
        return studentAddress;
    }

    public void setAddress(Address studentAddress) {
        this.studentAddress = studentAddress;
    }

}

Using @ModelAttribute i am trying to bind the Student object but only the
  String and int properties are getting binded but the Address dependency is  null only.

web.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://java.sun.com/xml/ns/javaee   http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
      <display-name>Archetype Created Web Application</display-name>

     <servlet>
        <servlet-name>frontController</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
     </servlet>

     <servlet-mapping>
        <servlet-name>frontController</servlet-name>
        <url-pattern>/</url-pattern>
     </servlet-mapping>

    </web-app>

**frontController-servlet.xml**

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:context = "http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
                        http://www.springframework.org/schema/context
                        http://www.springframework.org/schema/context/spring-context-3.0.xsd
                        http://www.springframework.org/schema/mvc
                        http://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <context:annotation-config/>
    <context:component-scan base-package="org.manya.Controllers"></context:component-scan>
    <mvc:annotation-driven/>

    <mvc:resources location="/resources/**" mapping="/static/**"/>
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/"/>
        <property name="suffix" value=".jsp"/>
    </bean>

</beans>

StudentController.java

package org.manya.Controllers;

import org.manya.dataClasses.Address;
import org.manya.dataClasses.Student;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping("/student")
public class StudentController {

    @GetMapping("/studentForm")
    public String admissionForm()
    {
        return "admissionForm";
    }

    @PostMapping("/submitted")
    public ModelAndView submitted(@ModelAttribute("student") Student stud)
    {
        ModelAndView mv = new ModelAndView("submitted");
        return mv;

    }
}

admissionForm.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>

<form action="./submitted" method="post">
    NAME : <input name="name"/>
    AGE : <input name="age"/>
    CITY : <input type="text" name="studentAddress.city"/>
    STATE : <input type="text" name="studentAddress.state"/>
    SUBMIT : <input type="submit"/>
</form>


问:
issue with xaml alignment xamarin forms
I am working on Xamarin form cross app. I am using Navigation drawer where I need to show items/subitems . Single are showing properly but issue is with items and subitem.. in that case.. text is showing vertically.

This is screen shot of current code

Now you can see that text are appearing vertically and same for sub menu items..
I actually want to show like below

My xaml is as below

```<code><MasterDetailPage.Master>
    <ContentPage Title="Menu" BackgroundColor="{StaticResource WhiteColor}">
        <ScrollView>
        <StackLayout Orientation="Vertical">

            <!--
         This StackLayout you can use for other
         data that you want to have in your menu drawer
    -->
            <StackLayout BackgroundColor="{StaticResource BlueColor}"
                         HeightRequest="75">

                <Label Text="Menu"
                       FontSize="20"
                       VerticalOptions="CenterAndExpand"
                       TextColor="White"
                       HorizontalOptions="Center"/>
            </StackLayout>

                <StackLayout>

                    <!--DashBoard-->

                <StackLayout VerticalOptions="CenterAndExpand"
                             Orientation="Horizontal"
                             Padding="20,10,0,0"
                             Spacing="20">

                    <Image Source="dashbaordmenuicon.png"
                           WidthRequest="30"
                           HeightRequest="30"
                           VerticalOptions="Center" />

                    <Label Text="Dashboards"
                           FontSize="18"
                           VerticalOptions="Center"
                           FontFamily="ProximaNova"
                           TextColor="#637188"/>

                    <StackLayout VerticalOptions="CenterAndExpand"
                                 Orientation="Horizontal"
                                 Padding="30,5,0,10"
                                 Spacing="20">

                        <Image Source="summarymenuicon.png"
                               WidthRequest="30"
                               HeightRequest="30"
                               VerticalOptions="Center" />

                        <Label Text="Summary"
                               FontSize="15"
                               VerticalOptions="Center"
                               FontFamily="ProximaNova"
                               TextColor="#98a4b4"/>
                    </StackLayout>

                    <StackLayout VerticalOptions="CenterAndExpand"
                                 Orientation="Horizontal"
                                 Padding="30,5,0,10"
                                 Spacing="20">

                        <Image Source="spendinghistoryicon.png"
                               WidthRequest="30"
                               HeightRequest="30"
                               VerticalOptions="Center" />

                        <Label Text="pending History"
                               FontSize="18"
                               VerticalOptions="Center"
                               FontFamily="ProximaNova"
                               TextColor="#98a4b4"/>
                    </StackLayout>

                </StackLayout>
                </StackLayout>
                <!--Dreams-->

                <StackLayout VerticalOptions="FillAndExpand"
                             Orientation="Horizontal"
                             Padding="20,10,0,0"
                             Spacing="20">

                    <Image Source="dreamsicon.png"
                           WidthRequest="30"
                           HeightRequest="30"
                           VerticalOptions="Center" />

                    <Label Text="Dreams"
                           FontSize="18"
                           VerticalOptions="Center"
                           FontFamily="ProximaNova"
                           TextColor="#637188"/>

                    <StackLayout VerticalOptions="FillAndExpand"
                                 Orientation="Horizontal"
                                 Padding="30,5,0,10"
                                 Spacing="20">

                        <Image Source="adddreamicon.png"
                               WidthRequest="30"
                               HeightRequest="30"
                               VerticalOptions="Center" />

                        <Label Text="Add Dream"
                               FontSize="15"
                               VerticalOptions="Center"
                               FontFamily="ProximaNova"
                               TextColor="#98a4b4"/>
                    </StackLayout>

                </StackLayout>

                <!--Financial Management-->

            <StackLayout VerticalOptions="FillAndExpand"
                         Orientation="Horizontal"
                         Padding="20,10,0,0"
                         Spacing="20">

                    <Image Source="financialmanagementicon.png"
                       WidthRequest="30"
                       HeightRequest="30"
                       VerticalOptions="Center" />

                    <Label Text="Financial Management"
                       FontSize="18"
                       VerticalOptions="Center"
                       FontFamily="ProximaNova"
                       TextColor="#637188"/>

                <StackLayout VerticalOptions="FillAndExpand"
                             Orientation="Horizontal"
                             Padding="30,5,0,10"
                             Spacing="20">

                        <Image Source="addicon.png"
                           WidthRequest="30"
                           HeightRequest="30"
                           VerticalOptions="Center" />

                        <Label Text="Add Income"
                           FontSize="15"
                           VerticalOptions="Center"
                           FontFamily="ProximaNova"
                           TextColor="#98a4b4"/>
                </StackLayout>

                    <StackLayout VerticalOptions="FillAndExpand"
                                 Orientation="Horizontal"
                                 Padding="30,5,0,10"
                                 Spacing="20">

                        <Image Source="addicon.png"
                               WidthRequest="30"
                               HeightRequest="30"
                               VerticalOptions="Center" />

                        <Label Text="Add Expense"
                               FontSize="15"
                               VerticalOptions="Center"
                               FontFamily="ProximaNova"
                               TextColor="#98a4b4"/>
                    </StackLayout>

                <StackLayout VerticalOptions="FillAndExpand"
                             Orientation="Horizontal"
                             Padding="30,5,0,10"
                             Spacing="20">

                    <Image Source="addicon.png"
                           WidthRequest="30"
                           HeightRequest="30"
                           VerticalOptions="Center" />

                        <Label Text="Add Virtual Account"
                           FontSize="15"
                           VerticalOptions="Center"
                           FontFamily="ProximaNova"
                           TextColor="#98a4b4"/>
                </StackLayout>

                    <StackLayout VerticalOptions="FillAndExpand"
                                 Orientation="Horizontal"
                                 Padding="30,5,0,10"
                                 Spacing="20">

                        <Image Source="linkaccounticon.png"
                               WidthRequest="30"
                               HeightRequest="30"
                               VerticalOptions="Center" />

                        <Label Text="Link Account"
                               FontSize="15"
                               VerticalOptions="Center"
                               FontFamily="ProximaNova"
                               TextColor="#98a4b4"/>
                    </StackLayout>

                <StackLayout VerticalOptions="FillAndExpand"
                             Orientation="Horizontal"
                             Padding="30,5,0,10"
                             Spacing="20">

                        <Image Source="budgeticon.png"
                           WidthRequest="29"
                           HeightRequest="30"
                           VerticalOptions="Center" />

                        <Label Text="Budget"
                           FontSize="15"
                           VerticalOptions="Center"
                           FontFamily="ProximaNova"
                           TextColor="#98a4b4"/>
                </StackLayout>

                </StackLayout>

            <!--Settings-->

            <StackLayout VerticalOptions="FillAndExpand"
                         Orientation="Horizontal"
                         Padding="20,10,0,0"
                         Spacing="20">

                    <Image Source="settingsicon.png"
                       WidthRequest="30"
                       HeightRequest="30"
                       VerticalOptions="Center" />

                    <Label Text="Settings"
                       FontSize="18"
                       VerticalOptions="Center"
                       FontFamily="ProximaNova"
                       TextColor="#637188"/>

            </StackLayout>

            <!--Subcription-->
            <StackLayout VerticalOptions="FillAndExpand"
                         Orientation="Horizontal"
                         Padding="20,10,0,0"
                         Spacing="20">

                    <Image Source="subscriptionicon.png"
                       WidthRequest="30"
                       HeightRequest="30"
                       VerticalOptions="Center" />

                    <Label Text="Subcription"
                       FontSize="18"
                       VerticalOptions="Center"
                       FontFamily="ProximaNova"
                       TextColor="#637188"/>

            </StackLayout>

            <!--Feedback-->
            <StackLayout VerticalOptions="FillAndExpand"
                         Orientation="Horizontal"
                         Padding="20,10,0,0"
                         Spacing="20">

                    <Image Source="feedbackicon.png"
                       WidthRequest="30"
                       HeightRequest="30"
                       VerticalOptions="Center" />

                    <Label Text="Feedback"
                       FontSize="18"
                       VerticalOptions="Center"
                       FontFamily="ProximaNova"
                       TextColor="#637188"/>

            </StackLayout>

            </StackLayout>
        </ScrollView>
    </ContentPage>
</MasterDetailPage.Master>
</code>```

答:
You need to add parent stack layout like :</p>

```<code><StackLayout>
    <StackLayout VerticalOptions="CenterAndExpand"
                 Orientation="Horizontal"
                 Padding="20,10,0,0"
                 Spacing="20">

        <Image Source="dashbaordmenuicon.png"
               WidthRequest="40"
               HeightRequest="40"
               VerticalOptions="Center" />

        <Label Text="Dashboards"
               FontSize="18"
               VerticalOptions="Center"
               FontFamily="ProximaNova"
               TextColor="#637188"/>

    </StackLayout>

    <StackLayout VerticalOptions="CenterAndExpand"
                     Orientation="Horizontal"
                     Padding="30,5,0,10"
                     Spacing="20">

            <Image Source="summarymenuicon.png"
                   WidthRequest="40"
                   HeightRequest="40"
                   VerticalOptions="Center" />

            <Label Text="Summary"
                   FontSize="15"
                   VerticalOptions="Center"
                   FontFamily="ProximaNova"
                   TextColor="#98a4b4"/>
        </StackLayout>

    <StackLayout VerticalOptions="CenterAndExpand"
                 Orientation="Horizontal"
                 Padding="30,5,0,10"
                 Spacing="20">

        <Image Source="spendinghistoryicon.png"
               WidthRequest="40"
               HeightRequest="40"
               VerticalOptions="Center" />

        <Label Text="pending History"
               FontSize="18"
               VerticalOptions="Center"
               FontFamily="ProximaNova"
               TextColor="#98a4b4"/>
    </StackLayout>

</StackLayout>
</code>```

Title: issue with xaml alignment xamarin forms

Body:
I am working on Xamarin form cross app. I am using Navigation drawer where I need to show items/subitems . Single are showing properly but issue is with items and subitem.. in that case.. text is showing vertically.

This is screen shot of current code

Now you can see that text are appearing vertically and same for sub menu items..
I actually want to show like below

My xaml is as below

<MasterDetailPage.Master>
    <ContentPage Title="Menu" BackgroundColor="{StaticResource WhiteColor}">
        <ScrollView>
        <StackLayout Orientation="Vertical">

            <StackLayout BackgroundColor="{StaticResource BlueColor}"
                         HeightRequest="75">

            </StackLayout>

                <StackLayout>

                <StackLayout VerticalOptions="CenterAndExpand"
                             Orientation="Horizontal"
                             Padding="20,10,0,0"
                             Spacing="20">

                    <Image Source="dashbaordmenuicon.png"
                           WidthRequest="30"
                           HeightRequest="30"
                           VerticalOptions="Center" />

                    <StackLayout VerticalOptions="CenterAndExpand"
                                 Orientation="Horizontal"
                                 Padding="30,5,0,10"
                                 Spacing="20">

                        <Image Source="summarymenuicon.png"
                               WidthRequest="30"
                               HeightRequest="30"
                               VerticalOptions="Center" />

                    </StackLayout>

                    <StackLayout VerticalOptions="CenterAndExpand"
                                 Orientation="Horizontal"
                                 Padding="30,5,0,10"
                                 Spacing="20">

                        <Image Source="spendinghistoryicon.png"
                               WidthRequest="30"
                               HeightRequest="30"
                               VerticalOptions="Center" />

                    </StackLayout>

                </StackLayout>
                </StackLayout>

                <StackLayout VerticalOptions="FillAndExpand"
                             Orientation="Horizontal"
                             Padding="20,10,0,0"
                             Spacing="20">

                    <Image Source="dreamsicon.png"
                           WidthRequest="30"
                           HeightRequest="30"
                           VerticalOptions="Center" />

                    <StackLayout VerticalOptions="FillAndExpand"
                                 Orientation="Horizontal"
                                 Padding="30,5,0,10"
                                 Spacing="20">

                        <Image Source="adddreamicon.png"
                               WidthRequest="30"
                               HeightRequest="30"
                               VerticalOptions="Center" />

                    </StackLayout>

                </StackLayout>

            <StackLayout VerticalOptions="FillAndExpand"
                         Orientation="Horizontal"
                         Padding="20,10,0,0"
                         Spacing="20">

                    <Image Source="financialmanagementicon.png"
                       WidthRequest="30"
                       HeightRequest="30"
                       VerticalOptions="Center" />

                <StackLayout VerticalOptions="FillAndExpand"
                             Orientation="Horizontal"
                             Padding="30,5,0,10"
                             Spacing="20">

                        <Image Source="addicon.png"
                           WidthRequest="30"
                           HeightRequest="30"
                           VerticalOptions="Center" />

                </StackLayout>

                    <StackLayout VerticalOptions="FillAndExpand"
                                 Orientation="Horizontal"
                                 Padding="30,5,0,10"
                                 Spacing="20">

                        <Image Source="addicon.png"
                               WidthRequest="30"
                               HeightRequest="30"
                               VerticalOptions="Center" />

                    </StackLayout>

                <StackLayout VerticalOptions="FillAndExpand"
                             Orientation="Horizontal"
                             Padding="30,5,0,10"
                             Spacing="20">

                    <Image Source="addicon.png"
                           WidthRequest="30"
                           HeightRequest="30"
                           VerticalOptions="Center" />

                </StackLayout>

                    <StackLayout VerticalOptions="FillAndExpand"
                                 Orientation="Horizontal"
                                 Padding="30,5,0,10"
                                 Spacing="20">

                        <Image Source="linkaccounticon.png"
                               WidthRequest="30"
                               HeightRequest="30"
                               VerticalOptions="Center" />

                    </StackLayout>

                <StackLayout VerticalOptions="FillAndExpand"
                             Orientation="Horizontal"
                             Padding="30,5,0,10"
                             Spacing="20">

                        <Image Source="budgeticon.png"
                           WidthRequest="29"
                           HeightRequest="30"
                           VerticalOptions="Center" />

                </StackLayout>

                </StackLayout>

            <StackLayout VerticalOptions="FillAndExpand"
                         Orientation="Horizontal"
                         Padding="20,10,0,0"
                         Spacing="20">

                    <Image Source="settingsicon.png"
                       WidthRequest="30"
                       HeightRequest="30"
                       VerticalOptions="Center" />

            </StackLayout>

            <StackLayout VerticalOptions="FillAndExpand"
                         Orientation="Horizontal"
                         Padding="20,10,0,0"
                         Spacing="20">

                    <Image Source="subscriptionicon.png"
                       WidthRequest="30"
                       HeightRequest="30"
                       VerticalOptions="Center" />

            </StackLayout>

            <StackLayout VerticalOptions="FillAndExpand"
                         Orientation="Horizontal"
                         Padding="20,10,0,0"
                         Spacing="20">

                    <Image Source="feedbackicon.png"
                       WidthRequest="30"
                       HeightRequest="30"
                       VerticalOptions="Center" />

            </StackLayout>

            </StackLayout>
        </ScrollView>
    </ContentPage>
</MasterDetailPage.Master>

Body:
You need to add parent stack layout like :

<StackLayout>
    <StackLayout VerticalOptions="CenterAndExpand"
                 Orientation="Horizontal"
                 Padding="20,10,0,0"
                 Spacing="20">

        <Image Source="dashbaordmenuicon.png"
               WidthRequest="40"
               HeightRequest="40"
               VerticalOptions="Center" />

        <Label Text="Dashboards"
               FontSize="18"
               VerticalOptions="Center"
               FontFamily="ProximaNova"
               TextColor="#637188"/>

    </StackLayout>

    <StackLayout VerticalOptions="CenterAndExpand"
                     Orientation="Horizontal"
                     Padding="30,5,0,10"
                     Spacing="20">

            <Image Source="summarymenuicon.png"
                   WidthRequest="40"
                   HeightRequest="40"
                   VerticalOptions="Center" />

            <Label Text="Summary"
                   FontSize="15"
                   VerticalOptions="Center"
                   FontFamily="ProximaNova"
                   TextColor="#98a4b4"/>
        </StackLayout>

    <StackLayout VerticalOptions="CenterAndExpand"
                 Orientation="Horizontal"
                 Padding="30,5,0,10"
                 Spacing="20">

        <Image Source="spendinghistoryicon.png"
               WidthRequest="40"
               HeightRequest="40"
               VerticalOptions="Center" />

        <Label Text="pending History"
               FontSize="18"
               VerticalOptions="Center"
               FontFamily="ProximaNova"
               TextColor="#98a4b4"/>
    </StackLayout>

</StackLayout>


问:
Can't create Windows Server Failover Cluster. Static address was not found on any cluster network
I'm trying to create a Windows Server Failover Cluster on Windows Server 2016 in Azure, using this article https://clusteringformeremortals.com/2016/04/23/deploying-microsoft-sql-server-2014-failover-clusters-in-azure-resource-manager-arm/
However, when I execute New-Cluster -Name sql-sql-cls -Node sql-sql-0,sql-sql-1 -StaticAddress 10.0.192.101 -NoStorage I get New-Cluster : Static address '10.0.192.101' was not found on any cluster network. My VM1 has 10.0.192.5 IP, and VM2 has 10.0.192.6 IP. How can I fix this?

答: Add a load balancer to the same subnet as the network cards that clister is on and use the ip address that gets assigned to the load balancer.</p>


问:
NVD3, Clear svg before loading new chart
I have several different NVD3 charts that I call upon in the same svg.
I use buttons to call functions, each containing a new chart that uses its own data.

Is there a way to clear my single svg without deleting it?
I wish to press a button to call my chart, but clear the svg before the new chart is loaded.

It's not an issue when using the kind of chart... calling two multibarhorizontal charts, for example, just updates the shapes, which is fine.
The problem is loading two different charts, like a line and a bar.

EDIT - The answers must be something like d3.select("svg").remove() but that just deletes the svg. I only want to clear it.

答:
If you are developing a dashboard having multiple widget showing different d3 charts then use the following

```<code>d3.selectAll("#d3-donutChart > *").remove();
</code>```

this will only clear the specific chart, not all the svg's in the webpage.

Add this line just after subscribing to data in angular 2.

Body:
If you are developing a dashboard having multiple widget showing different d3 charts then use the following

d3.selectAll("#d3-donutChart > *").remove();

this will only clear the specific chart, not all the svg's in the webpage.

Add this line just after subscribing to data in angular 2.


问:
Extract function argument from string
I have something as follows:

```<code>mystring="myobject"
def foo(object):
    pass
</code>```

And I would like to call foo(myobject) using mystring directly, in the same way like getattr(myclass, "mymethod").

Any help would be welcome. Thanks

答:
You can resolve the value of myobjectfrom the module where it is defined with getattr. If it is in the main module, this should work:

```<code>import __main__

mystring = 'This is a test.'

def foo(object):
    print object

variableName = 'mystring'
foo(getattr(__main__, variableName))
variableName = 'variableName'
foo(getattr(__main__, variableName))
</code>```

This should print

This is a test.

variableName

The import of the main module is necessary for variables from the main scope.

Edit: You can also get the content of the string with very dangerous eval(). Just replace foo(getattr(__main__, variableName)) with foo(eval(variableName)).

Title: Extract function argument from string

Body:
I have something as follows:

mystring="myobject"
def foo(object):
    pass

And I would like to call foo(myobject) using mystring directly, in the same way like getattr(myclass, "mymethod").

Any help would be welcome. Thanks

Body:
You can resolve the value of myobjectfrom the module where it is defined with getattr. If it is in the main module, this should work:

import __main__

mystring = 'This is a test.'

def foo(object):
    print object

variableName = 'mystring'
foo(getattr(__main__, variableName))
variableName = 'variableName'
foo(getattr(__main__, variableName))

This should print

This is a test.

variableName

The import of the main module is necessary for variables from the main scope.

Edit: You can also get the content of the string with very dangerous eval(). Just replace foo(getattr(__main__, variableName)) with foo(eval(variableName)).


问:
How to remove focus from SearchView?
I want to remove focus and text from SearchView in onResume().

I tried searchView.clearFocus() but it is not working.

This is my xml code:

```<code><SearchView
    android:id="@+id/searchView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignBottom="@+id/toolbar"
    android:layout_alignTop="@+id/toolbar"
    android:layout_centerVertical="true"
    android:layout_marginBottom="4dp"
    android:layout_marginTop="4dp"
    android:iconifiedByDefault="false"
    android:paddingLeft="16dp"
    android:paddingRight="16dp" />
</code>```

答:
I had just request focus to some other viewgroup and it removed focus from th searchview. Like in the parent viewgroup eg(Linearlayout, RelativeLayout) in which searchview is present, add

```<code>focusable = false; focusableInTouchMode=true
</code>```

to the parent viewgroup.

Title: How to remove focus from SearchView?

Body:
I want to remove focus and text from SearchView in onResume().

I tried searchView.clearFocus() but it is not working.

This is my xml code:

<SearchView
    android:id="@+id/searchView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignBottom="@+id/toolbar"
    android:layout_alignTop="@+id/toolbar"
    android:layout_centerVertical="true"
    android:layout_marginBottom="4dp"
    android:layout_marginTop="4dp"
    android:iconifiedByDefault="false"
    android:paddingLeft="16dp"
    android:paddingRight="16dp" />

Body:
I had just request focus to some other viewgroup and it removed focus from th searchview. Like in the parent viewgroup eg(Linearlayout, RelativeLayout) in which searchview is present, add

focusable = false; focusableInTouchMode=true

to the parent viewgroup.


答: Actually php is not accessing local system. After you choose a file and click upload at upload form. The whole file(not location) is sent via POST request. And php just recieves that POST request with the whole file, and stores at server.</p>

Title: PHP - File upload - What is happening internally?

Body:
For image upload  we use FILE html controller.

How this html controller able to browse in the local system?

After selecting a file , it will be copied and moved to server location.

If the php is ale to copy the local file and move to server , will it be able to do any other manipulations of that file ? like delete!

What is happening actually on file upload?


问:
Attaching click to anchor tag in angular
I am trying to attach click event to anchor tags (coming from ajax) and block the default redirection. How can I do it in angular ?

abc

abc1

abc2

abc3

```

<p><strong>In ts file:</strong> </p>

<pre class="lang-js prettyprint-override"><code>constructor(elementRef: ElementRef, renderer: Renderer) {
    this.listenFunc = renderer.listen(elementRef.nativeElement, 'click', (event) => {
        event.preventDefault();
        let target = event.target || event.srcElement || event.currentTarget;
        console.log(target);
    });
}
</code>```

This will attach event to all elements, how can I limit this to anchor tag only ?

All helps appreciated.

答:
I was able to implement this successfully</p>

```<code><a [routerLink]="['/login']">abc</a>
</code>```

Body:
I am trying to attach click event to anchor tags (coming from ajax) and block the default redirection. How can I do it in angular ?

abc

abc1

abc2

abc3

In ts file:

constructor(elementRef: ElementRef, renderer: Renderer) {
    this.listenFunc = renderer.listen(elementRef.nativeElement, 'click', (event) => {
        event.preventDefault();
        let target = event.target || event.srcElement || event.currentTarget;
        console.log(target);
    });
}

This will attach event to all elements, how can I limit this to anchor tag only ?

All helps appreciated.

Body:
I was able to implement this successfully

<a [routerLink]="['/login']">abc</a>


问:
Is it a bad design to expect a sorted List?
Lets say I wish to solve the problem - Find maximum product of 3 numbers in an array  in Java .

As its easy to solve the problem provided input List is already sorted so if my API method expects a sorted input , would that be a bad design ?

I am assuming the scenario where my API method wouldn't be controlling the source of data & input list population. That I suppose is the usual assumption when you are writing an API.

I would also assume that input could be very very large ( a million items or so ).

Is it too restrictive to impose such restrictions on upstream ?

Related Question

EDIT : I quoted that problem as an example. I meant to say, does it make more sense to keep a numerical list sorted from the very beginning ( when elements were inserted ) ? Since most problems on a collection of numbers are usually easy when collection is already sorted OR a numerical list being sorted from the very beginning of data flow has some kind of disadvantages too?

答:
The JDK method Collections.binarySearch() specifies in its documentation:

The list must be sorted into ascending order according to the natural
  ordering of its elements (as by the sort(List) method) prior to
  making this call.  If it is not sorted, the results are undefined.  If
  the list contains multiple elements equal to the specified object,
  there is no guarantee which one will be found.

This of course requires that you've read and understood the prerequisites for this method. Problematic is also that in case the list isn't sorted, you don't get an error, but undefined behaviour (i.e. usually the wrong index returned). That certainly doesn't sound like good design.

However, what are the alternatives? You can't call sort() inside the method, that would be too expensive when the lists are already sorted, not to mention confusing when the side-effect of calling the method would be sorting the list.

So as you see, in some cases we need to make some prerequisites to avoid even worse design. If a programmer doesn't read the documentation, it's not really the API maker's fault. Of course you want to make your code intuitive and easy to use, but sometimes it's just not possible or realistic.


问:
How to print ajax response to span class
I wanted to show ajax response to following  HTML where initially 0 available slot which could be changed on ajax response.
and based on data response dropdown_wrapper class
 will come automatically.
How do i make it dynamic?

```<code><span class="selected_item">0 available Slots</span>
<div class="form_item_dropdown">
    <div class="dropdown_wrapper">
        <li class="timeSlot" id="time1">
            <i class="icon fa fa-clock-o" aria-hidden="true">
            </i>
            <span class="item_title">10am - 4pm (value comes through Ajax)</span>
        </li>
    </div>
</div>
</code>```

Ajax code :

```<code>   $(".school_title").on("click", function (argument) {
        var id = $(this).attr('id');
        var info=$.get("{{url('school-slot')}}",{id:id});
        info.done(function(data){
            console.log(data.length);
  /*        $.each(data,function(index,subcatObj){
            });  */
        });
    });
</code>```

Here is the response :

```<code>{id: 3, school_id: 3, break_time: "10am - 8pm"}

{id: 4, school_id: 3, break_time: "10am - 4:30pm"}
</code>```

答:
If i understand your problem. May be You try this:-

```<code><span class="selected_item">0 available Slots</span>
<div class="form_item_dropdown">
<div class="dropdown_wrapper">
    <li class="timeSlot" id="time1">
        <i class="icon fa fa-clock-o" aria-hidden="true">
        </i>
        <span id="GiveDyanmicIdhere3" class="item_title">10am - 4pm (value comes through Ajax)</span> Give dyanmic id here
    </li>
  </div>
</div>
<div class="form_item_dropdown">
<div class="dropdown_wrapper">
    <li class="timeSlot" id="time1">
        <i class="icon fa fa-clock-o" aria-hidden="true">
        </i>
        <span id="GiveDyanmicIdhere4" class="item_title">10am - 4pm (value comes through Ajax)</span>  // Give dyanmic id here
    </li>
</div>
</code>```

```<code> var data = [
    {id: 3, school_id: 3, break_time: "10am - 8pm"}

    {id: 4, school_id: 3, break_time: "10am - 4:30pm"}
 ]; // save respone in one variable

 $.each(data, function(i, item) {
   $("#GiveDyanmicIdhere"+data[i].id).append(data[i].break_time);
                  Or
    $("#GiveDyanmicIdhere"+data[i].id).text(data[i].break_time);
 });
</code>```

You can try append, text, html according to your requirement

Body:
I wanted to show ajax response to following  HTML where initially 0 available slot which could be changed on ajax response.
and based on data response dropdown_wrapper class
 will come automatically.
How do i make it dynamic?

0 available Slots

            10am - 4pm (value comes through Ajax)

Ajax code :

   $(".school_title").on("click", function (argument) {
        var id = $(this).attr('id');
        var info=$.get("{{url('school-slot')}}",{id:id});
        info.done(function(data){
            console.log(data.length);
  /*        $.each(data,function(index,subcatObj){
            });  */
        });
    });

Here is the response :

{id: 3, school_id: 3, break_time: "10am - 8pm"}

{id: 4, school_id: 3, break_time: "10am - 4:30pm"}

Body:
If i understand your problem. May be You try this:-

<span class="selected_item">0 available Slots</span>
<div class="form_item_dropdown">
<div class="dropdown_wrapper">
    <li class="timeSlot" id="time1">
        <i class="icon fa fa-clock-o" aria-hidden="true">
        </i>
        <span id="GiveDyanmicIdhere3" class="item_title">10am - 4pm (value comes through Ajax)</span> Give dyanmic id here
    </li>
  </div>
</div>
<div class="form_item_dropdown">
<div class="dropdown_wrapper">
    <li class="timeSlot" id="time1">
        <i class="icon fa fa-clock-o" aria-hidden="true">
        </i>
        <span id="GiveDyanmicIdhere4" class="item_title">10am - 4pm (value comes through Ajax)</span>  // Give dyanmic id here
    </li>
</div>

 var data = [
    {id: 3, school_id: 3, break_time: "10am - 8pm"}

    {id: 4, school_id: 3, break_time: "10am - 4:30pm"}
 ]; // save respone in one variable

 $.each(data, function(i, item) {
   $("#GiveDyanmicIdhere"+data[i].id).append(data[i].break_time);
                  Or
    $("#GiveDyanmicIdhere"+data[i].id).text(data[i].break_time);
 });

You can try append, text, html according to your requirement


问:
How do I set the value of a React controlled component with jQuery in Puppeteer?
I am using Puppeteer to do some testing on a React app. The problem is that controlled inputs do not save their values into the Virtual DOM or state of the application when interacting with them by simply setting the DOM value.

After several days of research I came up with the following solution based on this reply:

```<code>describe('<HomePage />', async () => {
  eval('jasmine.DEFAULT_TIMEOUT_INTERVAL = 50000;'); //eslint-disable-line
  it('should make some new element visible', async () => {
    const browser = await puppeteer.launch({ headless: false });
    const page = await browser.newPage();
    await page.goto('http://localhost:3000/links');
    await page.waitForSelector('input', { visible: true });
    await page.addScriptTag({ url: 'https://code.jquery.com/jquery-3.2.1.min.js' });
    const someNewElement = await page.evaluate(() => {
      const $ = window.$;

      function doEvent(obj, event) {
      /* Created by David@Refoua.me */
        const newEvent = new Event(event, { target: obj, bubbles: true });
        return obj ? obj.dispatchEvent(newEvent) : false;
      }

      const mySelect = $('[name="mySelect"]')[0];
      mySelect.value = 'MakeSomeNewElementVisible';

      // for input dispatch -> input, for select dispatch -> change
      doEvent(mySelect, 'change');

      return $('#someNewElement_was_made_visible').length;
    });
    expect(someNewElement).toEqual(1);
    setTimeout(() => { browser.close(); }, 3000);
  });
});
</code>```

My question is: How do I replace the doEvent function with some jQuery function?

答:
Here is a far better solution for your problem,
I assume you are trying to select an option from a list, in that case, simply use the following,

```<code>page.select('[name="mySelect"]', 'MakeSomeNewElementVisible');
</code>```

You can tweak the selector if this was not the appropriate one. I'd suggest letting puppeteer do the heavy lifting for you.

If you still need to dispatch some event using .evaluate, you can look into this answer,  or this one.

Make sure to wait for a while after you do some event, some event might have some transition/delay added to them. Otherwise you might end up returning the result even before the element is visible in the dom.

Body:
I am using Puppeteer to do some testing on a React app. The problem is that controlled inputs do not save their values into the Virtual DOM or state of the application when interacting with them by simply setting the DOM value.

After several days of research I came up with the following solution based on this reply:

describe('<HomePage />', async () => {
  eval('jasmine.DEFAULT_TIMEOUT_INTERVAL = 50000;'); //eslint-disable-line
  it('should make some new element visible', async () => {
    const browser = await puppeteer.launch({ headless: false });
    const page = await browser.newPage();
    await page.goto('http://localhost:3000/links');
    await page.waitForSelector('input', { visible: true });
    await page.addScriptTag({ url: 'https://code.jquery.com/jquery-3.2.1.min.js' });
    const someNewElement = await page.evaluate(() => {
      const $ = window.$;

      function doEvent(obj, event) {
      /* Created by David@Refoua.me */
        const newEvent = new Event(event, { target: obj, bubbles: true });
        return obj ? obj.dispatchEvent(newEvent) : false;
      }

      const mySelect = $('[name="mySelect"]')[0];
      mySelect.value = 'MakeSomeNewElementVisible';

      // for input dispatch -> input, for select dispatch -> change
      doEvent(mySelect, 'change');

      return $('#someNewElement_was_made_visible').length;
    });
    expect(someNewElement).toEqual(1);
    setTimeout(() => { browser.close(); }, 3000);
  });
});

My question is: How do I replace the doEvent function with some jQuery function?

Body:
Here is a far better solution for your problem,
I assume you are trying to select an option from a list, in that case, simply use the following,

page.select('[name="mySelect"]', 'MakeSomeNewElementVisible');

You can tweak the selector if this was not the appropriate one. I'd suggest letting puppeteer do the heavy lifting for you.

If you still need to dispatch some event using .evaluate, you can look into this answer,  or this one.

Make sure to wait for a while after you do some event, some event might have some transition/delay added to them. Otherwise you might end up returning the result even before the element is visible in the dom.


问:
Add filter on column which subtract to columns
i have long store procedure in whcih i want Add filter on this Column

```<code>select (PaymentAmount-PaymentPosted) as Unapplied, BalancDue from ERAMaster
 where Unapplied = 22
</code>```

but i run the query they give me error invalid column name. any one tell me the write way to Add filter on Unapplied Column

答:
You can do it like below :

```<code>select * from
(
    select (PaymentAmount-PaymentPosted) as Unapplied, BalancDue from ERAMaster
) as T where Unapplied = 22
</code>```

Or like this :

```<code>select (PaymentAmount-PaymentPosted) as Unapplied, BalancDue from ERAMaster
where PaymentAmount-PaymentPosted = 22
</code>```

Body:
i have long store procedure in whcih i want Add filter on this Column

select (PaymentAmount-PaymentPosted) as Unapplied, BalancDue from ERAMaster
 where Unapplied = 22

but i run the query they give me error invalid column name. any one tell me the write way to Add filter on Unapplied Column

Body:
You can do it like below :

select * from
(
    select (PaymentAmount-PaymentPosted) as Unapplied, BalancDue from ERAMaster
) as T where Unapplied = 22

Or like this :

select (PaymentAmount-PaymentPosted) as Unapplied, BalancDue from ERAMaster
where PaymentAmount-PaymentPosted = 22


问:
HTML upload file small manipulation
When I use this code on IE8, the file is sent through the HTTP request fine:

```<code><form action="http:localhost:8080/myApp"
enctype="multipart/form-data" method="post">
<p>
Type some text (if you like):<br>
<input type="text" name="textline" size="30">
</p>
<p>
Please specify a file<br>
<input type="file" name="datafile" size="40">
</p>
<div>
<input type="submit" value="Send">
</div>
</form>
</code>```

but when I add another intermediate button, 'Add file', as you can see below instead of pressing the 'browse' button itself, the file isn't sent to the server side, why??

```<code><form action="http:localhost:8080/myApp"
enctype="multipart/form-data" method="post">
<p>
Type some text (if you like):<br>
<input type="text" name="textline" size="30">
</p>
<p>
Please specify a file<br>
<input id="fileChooser" type="file" name="datafile" size="40">
</p>
<button onclick="document.getElementById('fileChooser').click()">Add File</button>
<div>
<input type="submit" value="Send">
</div>
</form>
</code>```

答:
OK read some articles. Apparently that's just impossible.
I hope that HTML5 and IE9 will improve the customization of the annoying upload button, in many aspects.</p>

Title: HTML upload file small manipulation

Body:
When I use this code on IE8, the file is sent through the HTTP request fine:

<form action="http:localhost:8080/myApp"
enctype="multipart/form-data" method="post">

Type some text (if you like):

<input type="text" name="textline" size="30">

Please specify a file

<input type="file" name="datafile" size="40">

<input type="submit" value="Send">

</form>

but when I add another intermediate button, 'Add file', as you can see below instead of pressing the 'browse' button itself, the file isn't sent to the server side, why??

<form action="http:localhost:8080/myApp"
enctype="multipart/form-data" method="post">

Type some text (if you like):

<input type="text" name="textline" size="30">

Please specify a file

<input id="fileChooser" type="file" name="datafile" size="40">

<button onclick="document.getElementById('fileChooser').click()">Add File</button>

<input type="submit" value="Send">

</form>


问:
Communicate with a subprocess using pyzmq
I'm trying to communicate with a subprocess which I start using multiprocessing.Process via a ZeroMQ socket.  I know that there exist solutions to communicate with subprocesses within the multiprocessing module but I want to ultimately communicate with a function from a shared library written in C++.  Without further ado, here is the self-contained code:

```<code>import time
import zmq
import multiprocessing

def perform(nseconds, endpoint):
    context = zmq.Context()
    publisher = context.socket(zmq.PUB)
    publisher.connect(endpoint)

    for i in range(5):
        time.sleep(nseconds)
        publisher.send_string("{}".format(i))
    publisher.send_string(">>END")

if __name__ == "__main__":
    multiprocessing.freeze_support()
    context = zmq.Context()
    socket = context.socket(zmq.SUB)
    socket.bind("tcp://*:*")
    socket.setsockopt_string(zmq.SUBSCRIBE, u"")
    endpoint = socket.getsockopt_string(zmq.LAST_ENDPOINT)

    print("Binding via {}".format(endpoint))

    t = multiprocessing.Process(target=perform, args=(1,endpoint))
    t.start()

    string = ""
    while not ">>END" in string:
        string = socket.recv_string()
        print(string)

    t.join()
</code>```

This code runs perfectly fine on GNU/Linux with the expected output:

Binding via tcp://0.0.0.0:34149
0
1
2
3
4
>>END
```

<p>But running this on Windows with Python from Anaconda and <code>pyzmq</code> version 16.0.2 installed with <code>conda install pyzmq</code> it crashes with the following error:</p>

<pre class="lang-none prettyprint-override"><code>Binding via tcp://0.0.0.0:52019
Assertion failed: Can't assign requested address (bundled\zeromq\src\tcp_connect
er.cpp:341)
</code>```

How do I fix this?  Or am I doing it wrong?  And if I am doing it wrong, why is it platform dependent?

答:
Remove the wildcard in socket.bind( "tcp://*:*" )

First,

this is very platform specific, one ought never rely on how the wildcard expansion will get handled on unknown ecosystem details in production. Be explicit.

Next,

this is on the very contrary to the concise, state-of-art resources management practice in Distributed-systems design and there could be hardly a worse idea from the architecture point of view, than to .bind() straight on all ports on all localhost available addresses. Just imagine what this causes inside the Context()-instance, to manage all that herd of endpoints and their associated resources' pools ready and sniffing for a potentially incoming connection request ( just in case one such may appear ). No.

Never do this.

Performance sins and other aspects  - ref. my criticism on Amdahl's Law v/s costs

Well, having seen your publications, I will not expand this a lot, but yet have to add, the Distributed-computing realm requires a lot of care spent on details -- never expect a few SLOCs to perform any good for HPC computations.

The worst sins come from a good will to improve some process. If a code spins-off a process ( what the multiprocessing is exactly designed to do ), not many people also associate with such a SLOC the actual costs, that have to be paid, before the departed code gets it's first chance to start processing ( replica of the complete python execution environment ( so as to escape from the original local-GIL etc ) -- so your code has to pay in both [TIME] and [SPACE] for a huge memory-to-memory transfer, next your proposed code instantiates another "remote"-process Context()-engine. While this may look smart, your code has to pay for it again all costs - and spend just a few SLOCs to process. Next, always use rather a .setsockopt(  zmq.LINGER, 0 ), so as not to leave your resources infinitely blocking a graceful termination. While this seems as a "nice-to-have" preventive step, it is rather a "must-do" lifesaver, before hunting "what went wrong this time?" on a big and expensive computing infrastructure...

Many other performance tweaking deserves to be done before shelling out multiprocessing.Process( ... ), which goes way beyond the scope of this post. But worth mastering, definitely before running many-times inefficient code.

Body:
I'm trying to communicate with a subprocess which I start using multiprocessing.Process via a ZeroMQ socket.  I know that there exist solutions to communicate with subprocesses within the multiprocessing module but I want to ultimately communicate with a function from a shared library written in C++.  Without further ado, here is the self-contained code:

import time
import zmq
import multiprocessing

def perform(nseconds, endpoint):
    context = zmq.Context()
    publisher = context.socket(zmq.PUB)
    publisher.connect(endpoint)

    for i in range(5):
        time.sleep(nseconds)
        publisher.send_string("{}".format(i))
    publisher.send_string(">>END")

if __name__ == "__main__":
    multiprocessing.freeze_support()
    context = zmq.Context()
    socket = context.socket(zmq.SUB)
    socket.bind("tcp://*:*")
    socket.setsockopt_string(zmq.SUBSCRIBE, u"")
    endpoint = socket.getsockopt_string(zmq.LAST_ENDPOINT)

    print("Binding via {}".format(endpoint))

    t = multiprocessing.Process(target=perform, args=(1,endpoint))
    t.start()

    string = ""
    while not ">>END" in string:
        string = socket.recv_string()
        print(string)

    t.join()

This code runs perfectly fine on GNU/Linux with the expected output:

Binding via tcp://0.0.0.0:34149
0
1
2
3
4
>>END

But running this on Windows with Python from Anaconda and pyzmq version 16.0.2 installed with conda install pyzmq it crashes with the following error:

Binding via tcp://0.0.0.0:52019
Assertion failed: Can't assign requested address (bundled\zeromq\src\tcp_connect
er.cpp:341)

How do I fix this?  Or am I doing it wrong?  And if I am doing it wrong, why is it platform dependent?


问:
bing spell check saves user's data?
I use the Bing Spell Check in my app and I can't find information regarding non-persistent mode.
I want to make sure that this service configured to no-storage. (I know in LUIS there is some flag I need to enable so I assume this is also the case but I can't find the flag)

How to make sure no data regarding the text I send is being saved?

答:
Just to be clear there is a difference in non-persistent and non-logging data modes (the first term is not in context of the http mode). The first one is for non-personalized responses - logging may/may not happen - and the second one is no logging altogether.

LUIS supports no-logging (with log=off) mode. Bing spell check, for now, seems to support non-persistent mode only, which is also the default mode. If query doesn't contain ClientID, User-agent, ClientIP, or SessionID (all optional parameters), there is no way to trace back to particular user/browser/IP/session.

Title: bing spell check saves user's data?


问:
How to create an event in google calendar from another Alexa Skill Kit?
I am building a Alexa Skill Set which returns list of events. I would like to my skill to book an appointment for selected events by the user.

If the user says "Alexa book appointment for the last event", I want my skill to handle it and book an event in the linked calendar.

How do I get access to the linked calendar within my skill?

答:
For this, you need to get access to the user's calendar, which you can get via account linking. You can find more information by Amazon here: Link an Alexa User with a User in Your System.

In the account linking process, you then need to use Google Sign-In. Here's another helpful link for Google Calendar specifically:
Authorizing Requests to the Google Calendar API.


问:
How to properly overload functions
Hi I was just wondering how I would go about properly overloading functions in a Binary Search Tree. Heres the Code I have:

```<code>int LessThan(E itm1, E itm2) {
  if (itm1 < itm2) {return -1;}
  else if (itm1 > itm2) {return 1;}
  else if (itm1 == itm2) {return 0;}
}

int LessThan(string s1, string s2) { // Incase it is a string, we need to define <= and >= differently
  return this->compare(s1, s2);
}
</code>```

Unfortunately I'm getting the following errors:

```<code>binarySearchTree.h:33:9: error: ‘int binarySearchTree<E>::LessThan(std::__cxx11::string, std::__cxx11::string) [with E = std::__cxx11::basic_string<char>; std::__cxx11::string = std::__cxx11::basic_string<char>]’ cannot be overloaded
 int LessThan(string s1, string s2) { // Incase it is a string, we need to define <= and >= differently
     ^
binarySearchTree.h:27:9: error: with ‘int binarySearchTree<E>::LessThan(E, E) [with E = std::__cxx11::basic_string<char>]’
 int LessThan(E itm1, E itm2) {
     ^
</code>```

答:
Overloading isn't the answer to your problem. You are trying to have a specific behavior when your template is instantiated with a std::string. The proper technique is explicit specialization. Add the following under your template definition, like so:

```<code>template<>
int binarySearchTree<std::string>::LessThan(std::string s1, std::string s2) {
  return this->compare(s1, s2);
}
</code>```

Title: How to properly overload functions

Body:
Hi I was just wondering how I would go about properly overloading functions in a Binary Search Tree. Heres the Code I have:

int LessThan(E itm1, E itm2) {
  if (itm1 < itm2) {return -1;}
  else if (itm1 > itm2) {return 1;}
  else if (itm1 == itm2) {return 0;}
}

int LessThan(string s1, string s2) { // Incase it is a string, we need to define <= and >= differently
  return this->compare(s1, s2);
}

Unfortunately I'm getting the following errors:

binarySearchTree.h:33:9: error: ‘int binarySearchTree<E>::LessThan(std::__cxx11::string, std::__cxx11::string) [with E = std::__cxx11::basic_string<char>; std::__cxx11::string = std::__cxx11::basic_string<char>]’ cannot be overloaded
 int LessThan(string s1, string s2) { // Incase it is a string, we need to define <= and >= differently
     ^
binarySearchTree.h:27:9: error: with ‘int binarySearchTree<E>::LessThan(E, E) [with E = std::__cxx11::basic_string<char>]’
 int LessThan(E itm1, E itm2) {
     ^

Body:
Overloading isn't the answer to your problem. You are trying to have a specific behavior when your template is instantiated with a std::string. The proper technique is explicit specialization. Add the following under your template definition, like so:

template<>
int binarySearchTree<std::string>::LessThan(std::string s1, std::string s2) {
  return this->compare(s1, s2);
}