问:
Can I remove some lines from some files when archiving them with Gradle?
I have a task to archive some required files in my Gradle config:

```<code>task zip4BuildServer(type: Zip) {
    classifier = 'src'
    from projectDir
    include 'src/**/*'
    include 'lib/**/*'
    include 'gradle/**/*'
    include 'build.gradle'
    include 'settings.gradle'
    include 'data_source.xml'
    include 'gradlew'
    include 'gradlew.bat'
    archiveName "${baseName}-${getDate()}-${revision}.${extension}"
}
</code>```

I would like to remove some lines from build.gradle inside archive (not in source place).

How to do that?

If I write this way

```<code>    from projectDir
    {
        eachFile { FileCopyDetails details ->
            if(details.file.text.contains("some word")) {
            }
        }
    }
</code>```

it says

```<code>212: Ambiguous expression could be a parameterless closure expression, an isolated open code block, or it may continue a previous statement;
   solution: Add an explicit parameter list, e.g. {it -> ...}, or force it to be treated as an open block by giving it a label, e.g. L:{...}, and also either remove the previous newline, or add an explicit semicolon ';' @ line 212, column 5.
       {
       ^

1 error
</code>```

How to fix? I don't understand the error message.

答:
It should work this way:</p>

```<code>task zip4BuildServer(type: Zip) {
    classifier = 'src'
    from projectDir
    include 'src/**/*'
    include 'lib/**/*'
    include 'gradle/**/*'
    include 'build.gradle'
    include 'settings.gradle'
    include 'data_source.xml'
    include 'gradlew'
    include 'gradlew.bat'
    archiveName "${baseName}-${getDate()}-${revision}.${extension}"
    eachFile { FileCopyDetails details ->
       if(details.file.text.contains("some word")) {
       }
    }
}
</code>```

Body:
I have a task to archive some required files in my Gradle config:

task zip4BuildServer(type: Zip) {
    classifier = 'src'
    from projectDir
    include 'src/**/*'
    include 'lib/**/*'
    include 'gradle/**/*'
    include 'build.gradle'
    include 'settings.gradle'
    include 'data_source.xml'
    include 'gradlew'
    include 'gradlew.bat'
    archiveName "${baseName}-${getDate()}-${revision}.${extension}"
}

I would like to remove some lines from build.gradle inside archive (not in source place).

How to do that?

If I write this way

    from projectDir
    {
        eachFile { FileCopyDetails details ->
            if(details.file.text.contains("some word")) {
            }
        }
    }

it says

212: Ambiguous expression could be a parameterless closure expression, an isolated open code block, or it may continue a previous statement;
   solution: Add an explicit parameter list, e.g. {it -> ...}, or force it to be treated as an open block by giving it a label, e.g. L:{...}, and also either remove the previous newline, or add an explicit semicolon ';' @ line 212, column 5.
       {
       ^

1 error

How to fix? I don't understand the error message.

Body:
It should work this way:

task zip4BuildServer(type: Zip) {
    classifier = 'src'
    from projectDir
    include 'src/**/*'
    include 'lib/**/*'
    include 'gradle/**/*'
    include 'build.gradle'
    include 'settings.gradle'
    include 'data_source.xml'
    include 'gradlew'
    include 'gradlew.bat'
    archiveName "${baseName}-${getDate()}-${revision}.${extension}"
    eachFile { FileCopyDetails details ->
       if(details.file.text.contains("some word")) {
       }
    }
}


来源: stackexchange

问:
How to open a Bootstrap Modal on change of select Box
I am trying to open a modal on the change event of select Box?

This is My Modal

```<code><!-- Modal when adding comment for upload -->
  <div class="modal fade" id="fileUploadModal" role="dialog">
    <div class="modal-dialog">
      <!-- Modal content-->
      <div class="modal-content">
        <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal">×</button>
          <h4 class="modal-title">Add Comment</h4>
        </div>
        <div class="modal-body">
          <p><textarea id = "commentsUpload"class="form-control custom-control" rows="3" style="resize:none"></textarea></p>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-default" onclick="submitXYX()" data-dismiss="modal">Submit</button>
        </div>
      </div>
    </div>
  </div>
</code>```

And select Box is:

```<code><select class="selectpicker" id = "selectNEWBox">
    <option value = "1">New</option>
    <option value = "2">Old</option>
    <option value = "3">Scrap</option>
</select>
</code>```

What I need to do is to open the Modal on change event of select Box.

What I have tried

In $(document).ready(function () {});

Approach 1

```<code>$("#selectNEWBox").change(function(){
    $('#fileUploadModal').modal({
    show: true
  });
});
</code>```

Approach 2

```<code>$("#selectNEWBox").change(function (){
    $('#fileUploadModal').modal('show');
});
</code>```

but these are not working.

Am I missing something?

答:
Finally resolved the issue.
It seems the issue was because of conflict of Jquery versions.

Removed the conflict and it's working now. :)

ContentLicense: CC BY-SA 3.0

Body:
I am trying to open a modal on the change event of select Box?

This is My Modal

          <button type="button" class="close" data-dismiss="modal">×</button>

Add Comment

<textarea id = "commentsUpload"class="form-control custom-control" rows="3" style="resize:none"></textarea>

          <button type="button" class="btn btn-default" onclick="submitXYX()" data-dismiss="modal">Submit</button>

And select Box is:

<select class="selectpicker" id = "selectNEWBox">
    <option value = "1">New</option>
    <option value = "2">Old</option>
    <option value = "3">Scrap</option>
</select>

What I need to do is to open the Modal on change event of select Box.

What I have tried

In $(document).ready(function () {});

Approach 1

$("#selectNEWBox").change(function(){
    $('#fileUploadModal').modal({
    show: true
  });
});

Approach 2

$("#selectNEWBox").change(function (){
    $('#fileUploadModal').modal('show');
});

but these are not working.

Am I missing something?


问:
Error in wins in coin flip program
For some reason my program is not printing the percentage you got right correctly. I don't know if I set it up wrong, but I am at a loss. If someone could point me in the right direction that would be awesome. Its a simple program that tosses a coin where the user guesses if its head or tails and then it tells them if they won or not. The issue I am having is with counting the number of wins when the user wants to continue to play. </p>

```<code>public static void main(String[] args) throws InterruptedException {
        // This program asks the user to predict a toss of a coin.

        Scanner in = new Scanner(System.in);
        boolean done = false;
        String continuePlay = "";
        float count = 0;
        float wins =0;
        do{
        System.out.printf("Do you predict heads or tails for the coin toss: ");
        String prediction = in.next();

        System.out.print("Tossing the coin");
        TimeUnit.SECONDS.sleep(1);
        System.out.print(".");
        TimeUnit.SECONDS.sleep(1);
        System.out.print(".");
        TimeUnit.SECONDS.sleep(1);
        System.out.print(".");
        TimeUnit.SECONDS.sleep(1);
        System.out.println(".");
        TimeUnit.SECONDS.sleep(1);

        Random rand = new Random();
        int toss = Math.abs(rand.nextInt()) % 2;
        if(toss == 0){
            System.out.print("It came up heads.");

        }else{
            System.out.print("It came up tails.");

        }
        if(prediction.equals("h") && toss==0){
            System.out.print(" You win.");
            wins ++;
        }else if(prediction.equals("h") && toss !=0){
            System.out.print(" You loose.");
        }else if(prediction.equals("t") && toss==1){
            System.out.print(" You win.");
            wins ++;
        }else if(prediction.equals("t") && toss!=1){
            System.out.print(" You loose.");
        }

        // Ask user if they want to continue to play
        System.out.print("\nDo you want to play again? (\"c\" to continue \"q\" to quit): ");
        continuePlay = in.next();
        if (continuePlay.equals("c")){
            done = false;
        } else done = true;

        count ++;

        }while(done == false);

        double percentWon = (wins / count) * 100;

        System.out.printf("Thanks for playing. You guessed my number %.0f%% of the time.\n", percentWon);
            in.close();

        }

    }
</code>```

答:
Probably the error is in your win increment... I think that every time you get a win, you reset the win count to 1... in here

```<code> }
        if(prediction.equals("h") && toss==0){
            System.out.print(" You win.");
            wins =1;
        }else if(prediction.equals("h") && toss !=0){
            System.out.print(" You loose.");
        }else if(prediction.equals("t") && toss==1){
            System.out.print(" You win.");
            wins=1;
        }else if(prediction.equals("t") && toss!=1){
            System.out.print(" You loose.");
        }
</code>```

try changing to...

```<code> }
        if(prediction.equals("h") && toss==0){
            System.out.print(" You win.");
            wins ++;
        }else if(prediction.equals("h") && toss !=0){
            System.out.print(" You loose.");
        }else if(prediction.equals("t") && toss==1){
            System.out.print(" You win.");
            wins++;
        }else if(prediction.equals("t") && toss!=1){
            System.out.print(" You loose.");
        }
</code>```

and take the win++; in the end out.

Title: Error in wins in coin flip program

Body:
For some reason my program is not printing the percentage you got right correctly. I don't know if I set it up wrong, but I am at a loss. If someone could point me in the right direction that would be awesome. Its a simple program that tosses a coin where the user guesses if its head or tails and then it tells them if they won or not. The issue I am having is with counting the number of wins when the user wants to continue to play.

public static void main(String[] args) throws InterruptedException {
        // This program asks the user to predict a toss of a coin.

        Scanner in = new Scanner(System.in);
        boolean done = false;
        String continuePlay = "";
        float count = 0;
        float wins =0;
        do{
        System.out.printf("Do you predict heads or tails for the coin toss: ");
        String prediction = in.next();

        System.out.print("Tossing the coin");
        TimeUnit.SECONDS.sleep(1);
        System.out.print(".");
        TimeUnit.SECONDS.sleep(1);
        System.out.print(".");
        TimeUnit.SECONDS.sleep(1);
        System.out.print(".");
        TimeUnit.SECONDS.sleep(1);
        System.out.println(".");
        TimeUnit.SECONDS.sleep(1);

        Random rand = new Random();
        int toss = Math.abs(rand.nextInt()) % 2;
        if(toss == 0){
            System.out.print("It came up heads.");

        }else{
            System.out.print("It came up tails.");

        }
        if(prediction.equals("h") && toss==0){
            System.out.print(" You win.");
            wins ++;
        }else if(prediction.equals("h") && toss !=0){
            System.out.print(" You loose.");
        }else if(prediction.equals("t") && toss==1){
            System.out.print(" You win.");
            wins ++;
        }else if(prediction.equals("t") && toss!=1){
            System.out.print(" You loose.");
        }

        // Ask user if they want to continue to play
        System.out.print("\nDo you want to play again? (\"c\" to continue \"q\" to quit): ");
        continuePlay = in.next();
        if (continuePlay.equals("c")){
            done = false;
        } else done = true;

        count ++;

        }while(done == false);

        double percentWon = (wins / count) * 100;

        System.out.printf("Thanks for playing. You guessed my number %.0f%% of the time.\n", percentWon);
            in.close();

        }

    }

Body:
Probably the error is in your win increment... I think that every time you get a win, you reset the win count to 1... in here

 }
        if(prediction.equals("h") && toss==0){
            System.out.print(" You win.");
            wins =1;
        }else if(prediction.equals("h") && toss !=0){
            System.out.print(" You loose.");
        }else if(prediction.equals("t") && toss==1){
            System.out.print(" You win.");
            wins=1;
        }else if(prediction.equals("t") && toss!=1){
            System.out.print(" You loose.");
        }

try changing to...

 }
        if(prediction.equals("h") && toss==0){
            System.out.print(" You win.");
            wins ++;
        }else if(prediction.equals("h") && toss !=0){
            System.out.print(" You loose.");
        }else if(prediction.equals("t") && toss==1){
            System.out.print(" You win.");
            wins++;
        }else if(prediction.equals("t") && toss!=1){
            System.out.print(" You loose.");
        }

and take the win++; in the end out.


问:
Ignore in assertion dialog is disabled in Visual Studio
I am coding in C++ using Visual Studio 2015 Professional (update 3).

My problem is: When an assert() is triggered the assertion dialog did not pop up any more! Instead the exception dialog opens.

It looks like all asserts will be handled as exceptions.

I have re-installed the whole Visual Studio 2015 IDE, disabled all extensions, resetted my settings, etc. But it seems there is one setting stored in the registry that changed the assertion behaviour.

How do I bring back the assertion dialog?

答:
Replace following ucrtbased.dll with version 10.0.10240 </p>

```<code>C:\Windows\SysWOW64\ucrtbased.dll  //32bit 10.0.14393 (not ok)

C:\Windows\System32\ucrtbased.dll  //64bit 10.0.14393 (not ok)
</code>```

Body:
Replace following ucrtbased.dll with version 10.0.10240

C:\Windows\SysWOW64\ucrtbased.dll  //32bit 10.0.14393 (not ok)

C:\Windows\System32\ucrtbased.dll  //64bit 10.0.14393 (not ok)


问:
Linq to SQL: Is it better to have a small DataContext for each page or a global one?
I am trying out Linq to SQL in an ASP.NET application that uses a large database with lots of foreign keys (100+ tables).  I am impressed with how Linq permits you to create a datacontext with all of your relationships intact and to then create Linq statements that automatically join tables.  However, this leads to a question: if I am submitting a Linq statement that just works with one or two tables, is it better to have a datacontext that just has the necessary table/tables? It seems to me that if I build a datacontext with all of the tables in the database, it would be quite massive and loading it for every use of Linq would have a negative impact on performance.  Am I right?

Comment: I know to create the datacontext only as needed (but thank you nonetheless for mentioning it).  The question is really about whether I should have lots of little datacontexts or whether it would be Ok to build one big one.

答:
You should have one DataContext per one group of connected tables. In most applications, this means one DataContext for everything. If you happen to have several sets of tables that you do not need to modify together, you might consider several DataContexts. If you even might need to query across DataContexts, do not separate them.

A DataContext is not just a set of tables - it is meant to be an implementation of the Data Gateway pattern - you can fill it with methods that return the data you need, so you don't have to hardcode queries into every corner of your application. Now, if you had multiple DataContexts, one per page, you would very likely end up having to stick your common functionality (think MyDataContext.GetActiveCustomers()) in every one of them. This would be horrible duplication.

So the answer is that it is usually not OK to build many small DataContexts. This is only feasible if your data is completely separate (different logical or physical databases) or if you are using DataContext as simply a Connection object, which it is not meant to be.

Do note however, that DataContexts should be short-lived - they are an implementation of the Unit of Work pattern and thus their lifetime should be equal to one logical operation (e.g. loading a set of products or inserting a new order). DataContexts are cheap to create and destroy, so do not waste time caching them just because.

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Sander


问:
Implementing isset() in a setter method
Is there any way to implement isset() in a setter method? That is, have the setter method check if the variable exists? From what I can tell no, but hopefully someone can confirm that for me. In a nutshell, I'm looking to avoid having to do

```<code>if (isset($arr[0])) $foo->setId($arr[0])
</code>```

and simply just do

```<code>$foo->setId($arr[0])
</code>```

and somehow implement the isset() logic in the setter method. Thanks!

答:
No, you not can subscript a missing array element and expect it to work. The subscript will be evaluated before being sent to the method. This means the subscript will fail before the method even receives the argument.

Example

```<code>$arr = array(0 => 'a', 1 => 'b', 2 => 'c');
</code>```

If I do $foo->setId($arr[0]) then $foo->setId() will receive a as a string, and it will never know it was subscripted from an array (not does it want to know).

So a $foo->setId($arr[3]) would give an error...

Undefined offset

Title: Implementing isset() in a setter method

Body:
Is there any way to implement isset() in a setter method? That is, have the setter method check if the variable exists? From what I can tell no, but hopefully someone can confirm that for me. In a nutshell, I'm looking to avoid having to do

if (isset($arr[0])) $foo->setId($arr[0])

and simply just do

$foo->setId($arr[0])

and somehow implement the isset() logic in the setter method. Thanks!

Body:
No, you not can subscript a missing array element and expect it to work. The subscript will be evaluated before being sent to the method. This means the subscript will fail before the method even receives the argument.

Example

$arr = array(0 => 'a', 1 => 'b', 2 => 'c');

If I do $foo->setId($arr[0]) then $foo->setId() will receive a as a string, and it will never know it was subscripted from an array (not does it want to know).

So a $foo->setId($arr[3]) would give an error...

Undefined offset


问:
preg_match: check birthday format (dd/mm/yyyy)
How do I make the expression which checks the birthday input to match a format like this dd/mm/yyyy? Below is what I came out so far, but it takes this too if I put 99/99/9999!

```<code>if (!preg_match("/[0-9]{2}\/[0-9]{2}\/[0-9]{4}/", $cnt_birthday))
  {
   $error = true;
   echo '<error elementid="cnt_birthday" message="BIRTHDAY - Only this birthday format - dd/mm/yyyy - is accepted."/>';
  }
</code>```

How can I make sure that its only 01 to 31 for dd and 01 to 12 for mm? but I am sure how to restrict yyyy... I think theoritical 9999 should be acceptable...  let me know if you have a better idea!

thanks,
Lau

答:
I'm late to see this, but this solved my problem

```<code>    if (1 !== preg_match('/(0[1-9]|1[0-9]|2[0-9]|3(0|1))\/(0[1-9]|1[0-2])\/\d{4}/',$value)) {
        $this->form_validation->set_message('validate_emaildate','Date needs to have a valid date format - dd/mm/yyyy');
        return FALSE;
    }
</code>```

Courtesy the following posts:

Regex format here.. thanks Abin.

Function to check the format [here]
(Codeigniter's regex match)
.. thanks Hashem

+cheers

Body:
How do I make the expression which checks the birthday input to match a format like this dd/mm/yyyy? Below is what I came out so far, but it takes this too if I put 99/99/9999!

if (!preg_match("/[0-9]{2}\/[0-9]{2}\/[0-9]{4}/", $cnt_birthday))
  {
   $error = true;
   echo '<error elementid="cnt_birthday" message="BIRTHDAY - Only this birthday format - dd/mm/yyyy - is accepted."/>';
  }

How can I make sure that its only 01 to 31 for dd and 01 to 12 for mm? but I am sure how to restrict yyyy... I think theoritical 9999 should be acceptable...  let me know if you have a better idea!

thanks,
Lau

Body:
I'm late to see this, but this solved my problem

    if (1 !== preg_match('/(0[1-9]|1[0-9]|2[0-9]|3(0|1))\/(0[1-9]|1[0-2])\/\d{4}/',$value)) {
        $this->form_validation->set_message('validate_emaildate','Date needs to have a valid date format - dd/mm/yyyy');
        return FALSE;
    }

Courtesy the following posts:

Regex format here.. thanks Abin.

Function to check the format [here]
(Codeigniter's regex match)
.. thanks Hashem

+cheers


问:
Access Controller method from another controller in Laravel 5
I have two controllers SubmitPerformanceController and PrintReportController.

In PrintReportController I have a method called getPrintReport.

How to access this method in SubmitPerformanceController?

答:
Here the trait fully emulates running controller by laravel router (including support of middlewares and dependency injection). Tested only with 5.4 version

<?php

namespace App\Traits;

use Illuminate\Pipeline\Pipeline;
use Illuminate\Routing\ControllerDispatcher;
use Illuminate\Routing\MiddlewareNameResolver;
use Illuminate\Routing\SortedMiddleware;

trait RunsAnotherController
{
    public function runController($controller, $method = 'index')
    {
        $middleware = $this->gatherControllerMiddleware($controller, $method);

        $middleware = $this->sortMiddleware($middleware);

        return $response = (new Pipeline(app()))
            ->send(request())
            ->through($middleware)
            ->then(function ($request) use ($controller, $method) {
                return app('router')->prepareResponse(
                    $request, (new ControllerDispatcher(app()))->dispatch(
                    app('router')->current(), $controller, $method
                )
                );
            });
    }

    protected function gatherControllerMiddleware($controller, $method)
    {
        return collect($this->controllerMidlleware($controller, $method))->map(function ($name) {
            return (array)MiddlewareNameResolver::resolve($name, app('router')->getMiddleware(), app('router')->getMiddlewareGroups());
        })->flatten();
    }

    protected function controllerMidlleware($controller, $method)
    {
        return ControllerDispatcher::getMiddleware(
            $controller, $method
        );
    }

    protected function sortMiddleware($middleware)
    {
        return (new SortedMiddleware(app('router')->middlewarePriority, $middleware))->all();
    }
}
```

<p>Then just add it to your class and run the controller. Note, that dependency injection will be assigned with your current route.</p>

<pre class="lang-php prettyprint-override"><code>class CustomController extends Controller {
    use RunsAnotherController;

    public function someAction()
    {
        $controller = app()->make('App\Http\Controllers\AnotherController');

        return $this->runController($controller, 'doSomething');
    }
}
</code>```

Body:
Here the trait fully emulates running controller by laravel router (including support of middlewares and dependency injection). Tested only with 5.4 version

<?php

namespace App\Traits;

use Illuminate\Pipeline\Pipeline;
use Illuminate\Routing\ControllerDispatcher;
use Illuminate\Routing\MiddlewareNameResolver;
use Illuminate\Routing\SortedMiddleware;

trait RunsAnotherController
{
    public function runController($controller, $method = 'index')
    {
        $middleware = $this->gatherControllerMiddleware($controller, $method);

        $middleware = $this->sortMiddleware($middleware);

        return $response = (new Pipeline(app()))
            ->send(request())
            ->through($middleware)
            ->then(function ($request) use ($controller, $method) {
                return app('router')->prepareResponse(
                    $request, (new ControllerDispatcher(app()))->dispatch(
                    app('router')->current(), $controller, $method
                )
                );
            });
    }

    protected function gatherControllerMiddleware($controller, $method)
    {
        return collect($this->controllerMidlleware($controller, $method))->map(function ($name) {
            return (array)MiddlewareNameResolver::resolve($name, app('router')->getMiddleware(), app('router')->getMiddlewareGroups());
        })->flatten();
    }

    protected function controllerMidlleware($controller, $method)
    {
        return ControllerDispatcher::getMiddleware(
            $controller, $method
        );
    }

    protected function sortMiddleware($middleware)
    {
        return (new SortedMiddleware(app('router')->middlewarePriority, $middleware))->all();
    }
}

Then just add it to your class and run the controller. Note, that dependency injection will be assigned with your current route.

class CustomController extends Controller {
    use RunsAnotherController;

    public function someAction()
    {
        $controller = app()->make('App\Http\Controllers\AnotherController');

        return $this->runController($controller, 'doSomething');
    }
}


问:
Rounded corners in GroupBox control
How can I get rounded corners in a GroupBox in my form? Is there any option in the property tab?</p>

答:
Take a look at this open source controls:
http://roundedgroupbox.codeplex.com/</p>

Title: Rounded corners in GroupBox control


问:
Add tags in Rally C# API ( to userStory or Task)
I'm struggling with the syntax to update or create a TASK in the Rally REST API with tags.

here is my code:

```<code>//Tag Holder
ArrayList tagArray = new ArrayList();
tagArray.Add(tag._ref);

//the Task itself
DynamicJsonObject toCreate = new DynamicJsonObject();
toCreate["WorkProduct"] = storyRef;

  //i need to pass the tags as a parameter
   NameValueCollection parameters = new NameValueCollection();
  //this is where I am stuck, how do I attach the tags to the parameters

 //call the API to create the task
 CreateResult resultX = api.Create("task", toCreate, parameters );
</code>```

Thanks so much for any help!

答:
Thanks to @Kyle Morse for giving me the answer to this, in the interest of completeness for anyone else who needs to do this, below is my code for CREATING a task with tags in the Rally API</p>

```<code>//task object
DynamicJsonObject toCreate = new DynamicJsonObject();
toCreate["WorkProduct"] = storyRef;

//Tag Holder
ArrayList tagArray = new ArrayList();

//loop through your tags
foreach(tag in tags)
{
     DynamicJsonObject tagObj = new DynamicJsonObject();
     tagObj["_ref"] = tag._ref;
     tagArray.Add(tagObj);
}

//this is where you attach the tags
toCreate["Tags"] = tagArray;

//call the API to create the task
CreateResult result = api.Create(WorkSpace._ref,"task", toCreate );
</code>```

Body:
I'm struggling with the syntax to update or create a TASK in the Rally REST API with tags.

here is my code:

//Tag Holder
ArrayList tagArray = new ArrayList();
tagArray.Add(tag._ref);

//the Task itself
DynamicJsonObject toCreate = new DynamicJsonObject();
toCreate["WorkProduct"] = storyRef;

  //i need to pass the tags as a parameter
   NameValueCollection parameters = new NameValueCollection();
  //this is where I am stuck, how do I attach the tags to the parameters

 //call the API to create the task
 CreateResult resultX = api.Create("task", toCreate, parameters );

Thanks so much for any help!

Body:
Thanks to @Kyle Morse for giving me the answer to this, in the interest of completeness for anyone else who needs to do this, below is my code for CREATING a task with tags in the Rally API

//task object
DynamicJsonObject toCreate = new DynamicJsonObject();
toCreate["WorkProduct"] = storyRef;

//Tag Holder
ArrayList tagArray = new ArrayList();

//loop through your tags
foreach(tag in tags)
{
     DynamicJsonObject tagObj = new DynamicJsonObject();
     tagObj["_ref"] = tag._ref;
     tagArray.Add(tagObj);
}

//this is where you attach the tags
toCreate["Tags"] = tagArray;

//call the API to create the task
CreateResult result = api.Create(WorkSpace._ref,"task", toCreate );


问:
Regular expression matches the pattern instead of minimum length instead of the desired maximum
The below code as an example returns 'ol' when the objective was to return the word 'cool'

```<code>import re
re.search( r'.*([a-z]{2,}).*', 'this is very cool').group(1)
</code>```

That is, regex matched "at least 2 characters" and did not check if more could be matched. How to get regex to match the maximum possible number of characters instead of the minimum?

That is, how to achieve the output of 'cool'?

答:
The reason you get ol is that the initial .*  in your pattern grabs the whole string at once, and then backtracking occurs to accommodate for the subsequent subpatterns. When ol is "freed" from the grabbed text, the [a-z]{1,2} matches that substring and the regex engine calls it a day and returns the match (the trailing .* is of no importance here).

You may use a word boundary to make sure the .* backtracks to the beginning of the last word that starts with 2 lowercase letters and may have more:

```<code>.*\b([a-z]{2,})
</code>```

See the regex demo

Python demo:

```<code>import re
rx = r".*\b([a-z]{2,})"
s = "this is very cool"
m = re.search(rx, s)
if m:
    print(m.group(1))
# => cool
</code>```

Body:
The below code as an example returns 'ol' when the objective was to return the word 'cool'

import re
re.search( r'.*([a-z]{2,}).*', 'this is very cool').group(1)

That is, regex matched "at least 2 characters" and did not check if more could be matched. How to get regex to match the maximum possible number of characters instead of the minimum?

That is, how to achieve the output of 'cool'?

Body:
The reason you get ol is that the initial .*  in your pattern grabs the whole string at once, and then backtracking occurs to accommodate for the subsequent subpatterns. When ol is "freed" from the grabbed text, the [a-z]{1,2} matches that substring and the regex engine calls it a day and returns the match (the trailing .* is of no importance here).

You may use a word boundary to make sure the .* backtracks to the beginning of the last word that starts with 2 lowercase letters and may have more:

.*\b([a-z]{2,})

See the regex demo

Python demo:

import re
rx = r".*\b([a-z]{2,})"
s = "this is very cool"
m = re.search(rx, s)
if m:
    print(m.group(1))
# => cool


问:
jQuery get meta content in div
I need to get some data stored in a div and in a meta tag.

Here the div:

```<code><div id="qtip-0" class="qtip simcal-default-calendar simcal-event-bubble qtip-pos-tc qtip-fixed qtip-focus" tracking="false" role="alert" aria-live="polite" aria-atomic="false" aria-describedby="qtip-0-content" aria-hidden="false" data-qtip-id="0" >
<div class="qtip-tip">
    <canvas width="16" height="16" style="background-color: transparent !important; border: 0px !important; width: 8px; height: 8px;"></canvas>
</div>
<div class="qtip-content" id="qtip-0-content" aria-atomic="true">
    <div class="simcal-event-details simcal-tooltip-content" style="display: block; visibility: visible;">
        <div class="col-xs-12 title-event-container">
            <span class="simcal-event-title" itemprop="name">Riunione intenra Scali ferroviari</span>
        </div>
        <p><label>Luogo:</label><br>
        <span class="simcal-event-address simcal-event-start-location" itemprop="location" itemscope="" itemtype="http://schema.org/Place"><meta itemprop="name" content="Palazzo Marino - Comune di Milano
Piazza della Scala 2, 20121 Milano, Italia"><meta itemprop="address" content="Palazzo Marino - Comune di Milano
Piazza della Scala 2, 20121 Milano, Italia">Palazzo Marino - Comune di Milano
Piazza della Scala 2, 20121 Milano, Italia</span></p>
        <div id="map">Mappa</div>
        <p>
            <a href="//maps.google.com?q=Palazzo+Marino+-+Comune+di+MilanoPiazza+della+Scala+2%2C+20121+Milano%2C+Italia" target="_blank">Vedi mappa ingrandita</a>
        </p>
    </div>
</div>
</code>```

I need to access to:

```<code><meta itemprop="address" content="Palazzo Marino - Comune di Milano
Piazza della Scala 2, 20121 Milano, Italia">
</code>```

to get the content attribute.

Here what I have tried:

```<code>var currentEventAddress = $('#qtip-0 span').find('meta[itemprop="address"]').attr('content');

console.log(currentEventAddress);
</code>```

But I get undefined

答:
You don't need find.

Use like this:

$(".btn").on("click", function() {
 var currentEventAddress = $('meta[itemprop="address"]').attr('content');
  alert(currentEventAddress)
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="btn">Get Meta</button>

<div id="qtip-0" class="qtip simcal-default-calendar simcal-event-bubble qtip-pos-tc qtip-fixed qtip-focus" tracking="false" role="alert" aria-live="polite" aria-atomic="false" aria-describedby="qtip-0-content" aria-hidden="false" data-qtip-id="0" >
<div class="qtip-tip">
    <canvas width="16" height="16" style="background-color: transparent !important; border: 0px !important; width: 8px; height: 8px;"></canvas>
</div>
<div class="qtip-content" id="qtip-0-content" aria-atomic="true">
    <div class="simcal-event-details simcal-tooltip-content" style="display: block; visibility: visible;">
        <div class="col-xs-12 title-event-container">
            <span class="simcal-event-title" itemprop="name">Riunione intenra Scali ferroviari</span>
        </div>
        <p><label>Luogo:</label><br>
        <span class="simcal-event-address simcal-event-start-location" itemprop="location" itemscope="" itemtype="http://schema.org/Place"><meta itemprop="name" content="Palazzo Marino - Comune di Milano
Piazza della Scala 2, 20121 Milano, Italia"><meta itemprop="address" content="Palazzo Marino - Comune di Milano
Piazza della Scala 2, 20121 Milano, Italia">Palazzo Marino - Comune di Milano
Piazza della Scala 2, 20121 Milano, Italia</span></p>
        <div id="map">Mappa</div>
        <p>
            Vedi mappa ingrandita
        </p>
    </div>
</div></code>```

Title: jQuery get meta content in div

Body:
I need to get some data stored in a div and in a meta tag.

Here the div:

    <canvas width="16" height="16" style="background-color: transparent !important; border: 0px !important; width: 8px; height: 8px;"></canvas>

            Riunione intenra Scali ferroviari

Luogo:

        <meta itemprop="name" content="Palazzo Marino - Comune di Milano
Piazza della Scala 2, 20121 Milano, Italia"><meta itemprop="address" content="Palazzo Marino - Comune di Milano
Piazza della Scala 2, 20121 Milano, Italia">Palazzo Marino - Comune di Milano
Piazza della Scala 2, 20121 Milano, Italia

Mappa

            Vedi mappa ingrandita

I need to access to:

<meta itemprop="address" content="Palazzo Marino - Comune di Milano
Piazza della Scala 2, 20121 Milano, Italia">

to get the content attribute.

Here what I have tried:

var currentEventAddress = $('#qtip-0 span').find('meta[itemprop="address"]').attr('content');

console.log(currentEventAddress);

But I get undefined

Body:
You don't need find.

Use like this:

$(".btn").on("click", function() {
 var currentEventAddress = $('meta[itemprop="address"]').attr('content');
  alert(currentEventAddress)
})

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="btn">Get Meta</button>

<div id="qtip-0" class="qtip simcal-default-calendar simcal-event-bubble qtip-pos-tc qtip-fixed qtip-focus" tracking="false" role="alert" aria-live="polite" aria-atomic="false" aria-describedby="qtip-0-content" aria-hidden="false" data-qtip-id="0" >
<div class="qtip-tip">
    <canvas width="16" height="16" style="background-color: transparent !important; border: 0px !important; width: 8px; height: 8px;"></canvas>
</div>
<div class="qtip-content" id="qtip-0-content" aria-atomic="true">
    <div class="simcal-event-details simcal-tooltip-content" style="display: block; visibility: visible;">
        <div class="col-xs-12 title-event-container">
            <span class="simcal-event-title" itemprop="name">Riunione intenra Scali ferroviari</span>
        </div>
        <p><label>Luogo:</label><br>
        <span class="simcal-event-address simcal-event-start-location" itemprop="location" itemscope="" itemtype="http://schema.org/Place"><meta itemprop="name" content="Palazzo Marino - Comune di Milano
Piazza della Scala 2, 20121 Milano, Italia"><meta itemprop="address" content="Palazzo Marino - Comune di Milano
Piazza della Scala 2, 20121 Milano, Italia">Palazzo Marino - Comune di Milano
Piazza della Scala 2, 20121 Milano, Italia</span></p>
        <div id="map">Mappa</div>
        <p>
            <a href="//maps.google.com?q=Palazzo+Marino+-+Comune+di+MilanoPiazza+della+Scala+2%2C+20121+Milano%2C+Italia" target="_blank">Vedi mappa ingrandita</a>
        </p>
    </div>
</div>


问:
Django filter multiple value in the same column
I have set up the column where one of the table is called Establishment_Type

Now, I am trying to filter according to Establishment_Type.

Here is my view.py code

```<code>class ShopDetailAPIView(ListAPIView):
    serializer_class = ShopDetailSerializer
    def get_queryset(self):
        queryset = Shop.objects.all()
        type = self.request.query_params.get('type', None)
        type2 = self.request.query_params.get('type2', None)
        if type is not None and type2 is None:
            queryset = queryset.filter(Establishment_Type = type)
        elif type is not None and type2 is not None:
            queryset = queryset.filter(Q(Establishment_Type = type) | Q(Establishment_Type = type2))
        return queryset
</code>```

In the url, I query by typing:

```<code>http://127.0.0.1:8000/shop/search/?type=Restaurant&type2=Petrol%20Station
</code>```

Which only filter Establishment_Type = Restaurant but not include Establishment_Type = Petrol Station

Here is my urls.py within my app called shop:

```<code>urlpatterns = [

    url(r'^$', ShopListAPIView.as_view(), name = 'list' ),
    #####
    url(r'^create/$', ShopCreateAPIView.as_view(), name = 'create' ),
    url(r'^search/$', ShopDetailAPIView.as_view(), name = 'detail'),
]
</code>```

Was my url for filtering 2 Establishment type wrong?

Do I need to change something in my code in order to filter 2 values in column Establishment_Type?

答:
Thanks @Thyrst' for advising me to use Establishment_Type__in=types

I have modify my code this way for my filter to work

```<code>class ShopDetailAPIView(ListAPIView):
    serializer_class = ShopDetailSerializer
    def get_queryset(self):
        queryset = Shop.objects.all()
        type = self.request.query_params.get('type', None)
        type = type.split(',')
        if type is not None:
            queryset = queryset.filter(Establishment_Type__in = type)
        return queryset
</code>```

so type is now list, therefore when entered the url:

```<code>http://127.0.0.1:8000/shop/search/?type=Restaurant,Petrol%20Station
</code>```

it filters according to Restaurant and Petrol Station.

it also works when entering just 1 value or more.

This is good for now but I feel like there might be a better way to implement this.

Body:
I have set up the column where one of the table is called Establishment_Type

Now, I am trying to filter according to Establishment_Type.

Here is my view.py code

class ShopDetailAPIView(ListAPIView):
    serializer_class = ShopDetailSerializer
    def get_queryset(self):
        queryset = Shop.objects.all()
        type = self.request.query_params.get('type', None)
        type2 = self.request.query_params.get('type2', None)
        if type is not None and type2 is None:
            queryset = queryset.filter(Establishment_Type = type)
        elif type is not None and type2 is not None:
            queryset = queryset.filter(Q(Establishment_Type = type) | Q(Establishment_Type = type2))
        return queryset

In the url, I query by typing:

http://127.0.0.1:8000/shop/search/?type=Restaurant&type2=Petrol%20Station

Which only filter Establishment_Type = Restaurant but not include Establishment_Type = Petrol Station

Here is my urls.py within my app called shop:

urlpatterns = [

    url(r'^$', ShopListAPIView.as_view(), name = 'list' ),
    #####
    url(r'^create/$', ShopCreateAPIView.as_view(), name = 'create' ),
    url(r'^search/$', ShopDetailAPIView.as_view(), name = 'detail'),
]

Was my url for filtering 2 Establishment type wrong?

Do I need to change something in my code in order to filter 2 values in column Establishment_Type?

Body:
Thanks @Thyrst' for advising me to use Establishment_Type__in=types

I have modify my code this way for my filter to work

class ShopDetailAPIView(ListAPIView):
    serializer_class = ShopDetailSerializer
    def get_queryset(self):
        queryset = Shop.objects.all()
        type = self.request.query_params.get('type', None)
        type = type.split(',')
        if type is not None:
            queryset = queryset.filter(Establishment_Type__in = type)
        return queryset

so type is now list, therefore when entered the url:

http://127.0.0.1:8000/shop/search/?type=Restaurant,Petrol%20Station

it filters according to Restaurant and Petrol Station.

it also works when entering just 1 value or more.

This is good for now but I feel like there might be a better way to implement this.


问:
Two Way binding not working when set via Code behind
I am creating dynamic control in code behind and setting it's visibility property binding to the property in the code behind. But when the property value is changed, it's not updating visibility of the control.

Binding:

```<code>        Binding assetsVisibilityBinding = new Binding();
        assetsVisibilityBinding.Source = this;
        assetsVisibilityBinding.Path = new PropertyPath("IsLocalSearchEnabled");
        assetsVisibilityBinding.Mode = BindingMode.TwoWay;
        assetsVisibilityBinding.Converter = Resources["BooleanToVisibilityConverter"] as IValueConverter;
        assetsStackPanel.SetBinding(StackPanel.VisibilityProperty, assetsVisibilityBinding);
</code>```

Property(Using fody):

```<code>  public bool IsLocalSearchEnabled { get; set; }
</code>```

答:
Thanks. But as mentioned in the post I am actually using
  Fody(github.com/Fody/PropertyChanged). Which automatically implements
  that

I have checked the complied class, by using Fody PropertyChanged the property changed notification wasn't successfully implemented.

```<code>[ImplementPropertyChanged]
public sealed partial class MainPage : Page
{
    public bool IsLocalSearchEnabled { get; set; }

    public MainPage()
    {
        this.InitializeComponent();
        SetBinding();
        this.DataContext = this;
    }

    public void SetBinding()
    {
        Binding assetsVisibilityBinding = new Binding();
        assetsVisibilityBinding.Source = this;
        assetsVisibilityBinding.Path = new PropertyPath("IsLocalSearchEnabled");
        assetsVisibilityBinding.Mode = BindingMode.TwoWay;
        assetsVisibilityBinding.Converter = Resources["BooleanToVisibilityConverter"] as IValueConverter;
        assetsStackPanel.SetBinding(StackPanel.VisibilityProperty, assetsVisibilityBinding);
    }
}
</code>```

I would suggest you reporting issue to Fody to fix it.

The standard way as follows:

```<code>public sealed partial class MainPage : Page, INotifyPropertyChanged
{
    bool isLocalSearchEnabled;
    public bool IsLocalSearchEnabled
    {
        get { return isLocalSearchEnabled; }
        set
        {
            if (value != isLocalSearchEnabled)
            {
                isLocalSearchEnabled = value;
                OnPropertyChanged("IsLocalSearchEnabled");
            }
        }
    }

    public MainPage()
    {
        this.InitializeComponent();
        SetBinding();
        this.DataContext = this;
    }

    public void SetBinding()
    {
        Binding assetsVisibilityBinding = new Binding();
        assetsVisibilityBinding.Source = this;
        assetsVisibilityBinding.Path = new PropertyPath("IsLocalSearchEnabled");
        assetsVisibilityBinding.Mode = BindingMode.TwoWay;
        assetsVisibilityBinding.Converter = Resources["BooleanToVisibilityConverter"] as IValueConverter;
        assetsStackPanel.SetBinding(StackPanel.VisibilityProperty, assetsVisibilityBinding);
    }

    public event PropertyChangedEventHandler PropertyChanged;

    public void OnPropertyChanged(string propertyName)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}
</code>```

Or you can easily use a wrapper class: BindableBase

Body:
I am creating dynamic control in code behind and setting it's visibility property binding to the property in the code behind. But when the property value is changed, it's not updating visibility of the control.

Binding:

        Binding assetsVisibilityBinding = new Binding();
        assetsVisibilityBinding.Source = this;
        assetsVisibilityBinding.Path = new PropertyPath("IsLocalSearchEnabled");
        assetsVisibilityBinding.Mode = BindingMode.TwoWay;
        assetsVisibilityBinding.Converter = Resources["BooleanToVisibilityConverter"] as IValueConverter;
        assetsStackPanel.SetBinding(StackPanel.VisibilityProperty, assetsVisibilityBinding);

Property(Using fody):

  public bool IsLocalSearchEnabled { get; set; }

Body:
Thanks. But as mentioned in the post I am actually using
  Fody(github.com/Fody/PropertyChanged). Which automatically implements
  that

I have checked the complied class, by using Fody PropertyChanged the property changed notification wasn't successfully implemented.

[ImplementPropertyChanged]
public sealed partial class MainPage : Page
{
    public bool IsLocalSearchEnabled { get; set; }

    public MainPage()
    {
        this.InitializeComponent();
        SetBinding();
        this.DataContext = this;
    }

    public void SetBinding()
    {
        Binding assetsVisibilityBinding = new Binding();
        assetsVisibilityBinding.Source = this;
        assetsVisibilityBinding.Path = new PropertyPath("IsLocalSearchEnabled");
        assetsVisibilityBinding.Mode = BindingMode.TwoWay;
        assetsVisibilityBinding.Converter = Resources["BooleanToVisibilityConverter"] as IValueConverter;
        assetsStackPanel.SetBinding(StackPanel.VisibilityProperty, assetsVisibilityBinding);
    }
}

I would suggest you reporting issue to Fody to fix it.

The standard way as follows:

public sealed partial class MainPage : Page, INotifyPropertyChanged
{
    bool isLocalSearchEnabled;
    public bool IsLocalSearchEnabled
    {
        get { return isLocalSearchEnabled; }
        set
        {
            if (value != isLocalSearchEnabled)
            {
                isLocalSearchEnabled = value;
                OnPropertyChanged("IsLocalSearchEnabled");
            }
        }
    }

    public MainPage()
    {
        this.InitializeComponent();
        SetBinding();
        this.DataContext = this;
    }

    public void SetBinding()
    {
        Binding assetsVisibilityBinding = new Binding();
        assetsVisibilityBinding.Source = this;
        assetsVisibilityBinding.Path = new PropertyPath("IsLocalSearchEnabled");
        assetsVisibilityBinding.Mode = BindingMode.TwoWay;
        assetsVisibilityBinding.Converter = Resources["BooleanToVisibilityConverter"] as IValueConverter;
        assetsStackPanel.SetBinding(StackPanel.VisibilityProperty, assetsVisibilityBinding);
    }

    public event PropertyChangedEventHandler PropertyChanged;

    public void OnPropertyChanged(string propertyName)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}

Or you can easily use a wrapper class: BindableBase


问:
Sikuli doesn't see the game I'm trying to automate
I'm running Sikuli API from Java on a game we are running in the company on full screen. The problem is that Sikuli sees the layer beneath the game (the desktop) but not the game itself. It's like the game is transparent to Sikuli. I took a screenshot through RobotFW and also, the image I'm getting is the layer beneath. So this looks like a general issue and not specific to Sikuli.

What can I do?

The games are developed in Unity

答:
What if you use a App.focus(<appName>) before executing your code?

By using App.focus() you pull that application to the foreground.


问:
Write a program in C that outputs the smallest natural number greater or equal to n whose all digits are even
Write a program in C that will take a natural number n and output the smallest natural number greater or equal to n whose all digits are even in decimal. For example, if n = 16, it should output 20, and if n = 41, it should output 42.
What I have tried:

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

int main(void) {
  int n, i, condition = 0;

  scanf("%d", &n);
  for (i = n; i >= n; i++) {
    if (i % 2 == 0) {
      i = i / 10;
      while (i > 0) {
        if (i % 2 == 0) {
          i = i / 10;
          condition = 1;
        } else {
          break;
        }
      }
    } else {
      condition = 0;
    }
    if (condition == 1) {
      printf("%d", i);
      break;
    }
  }
  return 0;
}
</code>```

Why doesn't this work?

答:
The solutions published so far search all numbers greater than or equal to n until they find one with all-even digits. This is terribly inefficient.

A much better method is to scan the digits once from right to left and to adjust them to get the desired result directly:

```<code>// assume n >= 0
int next (int n)
{
    int r = 0; // result
    int c = 1; // coefficient (power of ten) of the current digit

    // Scan digits from right to left.
    while (n) {
        // current digit
        int d = n % 10;

        if (d % 2 == 0) {
            r += c * d;
        }
        else {
            // Make sure we handle the case d == 9 correctly.
            n++;
            d = n % 10;

            r += c * d;

            // Since we are incrementing the current digit (or a more
            // significant one), we must set every less significant
            // digits to zero.
            r -= r % c;
        }

        c *= 10;
        n /= 10;
    }

    return r;
}
</code>```

Body:
Write a program in C that will take a natural number n and output the smallest natural number greater or equal to n whose all digits are even in decimal. For example, if n = 16, it should output 20, and if n = 41, it should output 42.
What I have tried:

#include <stdio.h>

int main(void) {
  int n, i, condition = 0;

  scanf("%d", &n);
  for (i = n; i >= n; i++) {
    if (i % 2 == 0) {
      i = i / 10;
      while (i > 0) {
        if (i % 2 == 0) {
          i = i / 10;
          condition = 1;
        } else {
          break;
        }
      }
    } else {
      condition = 0;
    }
    if (condition == 1) {
      printf("%d", i);
      break;
    }
  }
  return 0;
}

Why doesn't this work?

Body:
The solutions published so far search all numbers greater than or equal to n until they find one with all-even digits. This is terribly inefficient.

A much better method is to scan the digits once from right to left and to adjust them to get the desired result directly:

// assume n >= 0
int next (int n)
{
    int r = 0; // result
    int c = 1; // coefficient (power of ten) of the current digit

    // Scan digits from right to left.
    while (n) {
        // current digit
        int d = n % 10;

        if (d % 2 == 0) {
            r += c * d;
        }
        else {
            // Make sure we handle the case d == 9 correctly.
            n++;
            d = n % 10;

            r += c * d;

            // Since we are incrementing the current digit (or a more
            // significant one), we must set every less significant
            // digits to zero.
            r -= r % c;
        }

        c *= 10;
        n /= 10;
    }

    return r;
}

ContentLicense: CC BY-SA 4.0


问:
How to migrate coredata into Action extension in iOS 10
I am new to core data, I've used this to perform certain steps but from iOS 10 below methods are created by defaults, </p>

```<code>- (NSPersistentContainer *)persistentContainer {
// The persistent container for the application. This implementation creates and returns a container, having loaded the store for the application to it.
@synchronized (self) {
    if (_persistentContainer == nil) {
        _persistentContainer = [[NSPersistentContainer alloc] initWithName:@"namanCoreData"];
        [_persistentContainer loadPersistentStoresWithCompletionHandler:^(NSPersistentStoreDescription *storeDescription, NSError *error) {
            if (error != nil) {
                // Replace this implementation with code to handle the error appropriately.
                // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.

                /*
                 Typical reasons for an error here include:
                 * The parent directory does not exist, cannot be created, or disallows writing.
                 * The persistent store is not accessible, due to permissions or data protection when the device is locked.
                 * The device is out of space.
                 * The store could not be migrated to the current model version.
                 Check the error message to determine what the actual problem was.
                */
                NSLog(@"Unresolved error %@, %@", error, error.userInfo);
                abort();
            }
        }];
    }
}

return _persistentContainer;}
</code>```

<p>any idea/link/suggestion about how to use core data into  Action Extension? Help . . . </p>

答: You can do the same thing.  Just after the initWithName and before the loadPersistentStoresWithCompletionHandler create a NSPersistentStoreDescription object, set its URL and then set the _persistentContainer's persistentStoreDescriptions property to it.

Body:
I am new to core data, I've used this to perform certain steps but from iOS 10 below methods are created by defaults,

- (NSPersistentContainer *)persistentContainer {
// The persistent container for the application. This implementation creates and returns a container, having loaded the store for the application to it.
@synchronized (self) {
    if (_persistentContainer == nil) {
        _persistentContainer = [[NSPersistentContainer alloc] initWithName:@"namanCoreData"];
        [_persistentContainer loadPersistentStoresWithCompletionHandler:^(NSPersistentStoreDescription *storeDescription, NSError *error) {
            if (error != nil) {
                // Replace this implementation with code to handle the error appropriately.
                // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.

                /*
                 Typical reasons for an error here include:
                 * The parent directory does not exist, cannot be created, or disallows writing.
                 * The persistent store is not accessible, due to permissions or data protection when the device is locked.
                 * The device is out of space.
                 * The store could not be migrated to the current model version.
                 Check the error message to determine what the actual problem was.
                */
                NSLog(@"Unresolved error %@, %@", error, error.userInfo);
                abort();
            }
        }];
    }
}

return _persistentContainer;}

any idea/link/suggestion about how to use core data into  Action Extension? Help . . .


问:
IllegalArgumentException: No view found for id for fragment --- ViewPager in ViewPager
I've met the problem that trouble me for days.

There is a ViewPager in the main activity which holds 3 Fragments as tab fragments. In the first fragment there is a ListView which holds some views, and which is the most important, another ViewPager. I want to hold some photos in the sub ViewPager, and use some more fragments here.

Now there is the trouble:

When the first Fragment is stopped (The third fragment in the parent ViewPager is seen on screen) and resumed (the user switch to the second fragment), the app crashes and the debugger says:

```<code>java.lang.IllegalArgumentException: No view found for id 0x7f05008b (com.example.viewpager:id/sub_viewpager) for fragment ScreenSlidePageFragment
</code>```

I've already use the getChildFragmentManager() as this is a situation of nested fragments.

Here is the key code of list adapter corresponding to the first fragment in the parent ViewPager:

```<code>@Override
public View getView(int position, View convertView, ViewGroup parent) {
    int type = getItemViewType(position);
    switch (type) {
        case TYPE_BANNER:
            if (convertView == null) {
                convertView = mBannerView.getBannerView(parent);
            }
            mBannerView.update(convertView);
            break;
        case TYPE_ITEM:
            break;
    }
    return convertView;
}
</code>```

Here is the code of mBannerView:

```<code>public class BannerView {

    private static final DisplayImageOptions IMAGE_OPTIONS_SCALE_STRETCHED =
            new DisplayImageOptions.Builder()
                    .cacheInMemory()
                    .cacheOnDisc()
                    .imageScaleType(ImageScaleType.EXACTLY_STRETCHED)
                    .build();

    private FragmentActivity mActivity;
    private Fragment mFragment;
    private List<Banner> mBanners;
    private ScreenSlidePagerAdapter mPagerAdapter;
    private ViewPager mViewPager;

    public BannerView(FragmentActivity activity, Fragment fragment) {
        mActivity = activity;
        mFragment = fragment;
    }

    public void update(View convertView) {
        mViewPager = (ViewPager) convertView;
        if (mBanners != null && !mBanners.isEmpty()) {
            if (mPagerAdapter == null) {
                mPagerAdapter = new ScreenSlidePagerAdapter(mFragment.getChildFragmentManager());
                mViewPager.setAdapter(mPagerAdapter);
            }
        }
        mViewPager.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mOnBannerClickListener != null) {
                    mOnBannerClickListener.onBannerClick();
                }
            }
        });
    }

    class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter {
        public ScreenSlidePagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            return new ScreenSlidePageFragment(mBanners.get(position).getImageUrl());
        }

        @Override
        public int getCount() {
            return mBanners == null ? 0 : mBanners.size();
        }
    }

    class ScreenSlidePageFragment extends Fragment {

        private String mUrl;

        ScreenSlidePageFragment(String url) {
            super();
            mUrl = url;
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            View view = inflater.inflate(R.layout.item_banner, container, false);
            if (view != null) {
                ImageView imageView = (ImageView) view.findViewById(R.id.item_banner_image);
                imageView.setLayoutParams(new LinearLayout.LayoutParams(
                        LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT));
                ImageLoader.getInstance().displayImage(mUrl, imageView, IMAGE_OPTIONS_SCALE_STRETCHED);
            }
            return view;
        }
    }
}
</code>```

Here is the detailed error list:

```<code>11-10 18:12:19.217    1444-1444/? E/MessageQueue-JNI﹕ java.lang.IllegalArgumentException: No view found for id 0x7f05008b (com.example.viewpager:id/sub_viewpager) for fragment ScreenSlidePageFragment{428d8ea0 #0 id=0x7f05008b}
        at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:919)
        at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1104)
        at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1086)
        at android.support.v4.app.FragmentManagerImpl.dispatchActivityCreated(FragmentManager.java:1884)
        at android.support.v4.app.Fragment.performActivityCreated(Fragment.java:1514)
        at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:947)
        at android.support.v4.app.FragmentManagerImpl.attachFragment(FragmentManager.java:1280)
        at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:672)
        at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1467)
        at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:472)
        at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:141)
        at android.support.v4.view.ViewPager.populate(ViewPager.java:1068)
        at android.support.v4.view.ViewPager.populate(ViewPager.java:914)
        at android.support.v4.view.ViewPager$3.run(ViewPager.java:244)
        at android.support.v4.view.ViewPager.completeScroll(ViewPager.java:1761)
        at android.support.v4.view.ViewPager.onInterceptTouchEvent(ViewPager.java:1896)
        at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:1854)
        at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2211)
        at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:1912)
        at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2211)
        at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:1912)
        at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2211)
        at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:1912)
        at com.android.internal.policy.impl.PhoneWindow$DecorView.superDispatchTouchEvent(PhoneWindow.java:2228)
        at com.android.internal.policy.impl.PhoneWindow.superDispatchTouchEvent(PhoneWindow.java:1471)
        at android.app.Activity.dispatchTouchEvent(Activity.java:2424)
        at com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchTouchEvent(PhoneWindow.java:2176)
        at android.view.View.dispatchPointerEvent(View.java:7571)
        at android.view.ViewRootImpl$ViewPostImeInputStage.processPointerEvent(ViewRootImpl.java:3883)
        at android.view.ViewRootImpl$ViewPostImeInputStage.onProcess(ViewRootImpl.java:3778)
        at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3379)
        at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:3429)
        at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:3398)
        at android.view.ViewRootImpl$AsyncInputStage.forward(ViewRootImpl.java:3483)
        at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:3406)
        at android.view.ViewRootImpl$AsyncInputStage.apply(ViewRootImpl.java:3540)
        at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3379)
        at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:3429)
        at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:3398)
        at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:3406)
        at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3379)
        at android.view.ViewRootImpl.deliverInputEvent(ViewRootImpl.java:5419)
        at android.view.ViewRootImpl.doProcessInputEvents(ViewRootImpl.java:5399)
        at android.view.ViewRootImpl.enqueueInputEvent(ViewRootImpl.java:5370)
        at android.view.ViewRootImpl$WindowInputEventReceiver.onInputEvent(ViewRootImpl.java:5493)
        at android.view.InputEventReceiver.dispatchInputEvent(InputEventReceiver.java:182)
        at android.os.MessageQueue.nativePollOnce(Native Method)
        at android.os.MessageQueue.next(MessageQueue.java:132)
        at android.os.Looper.loop(Looper.java:124)
        at android.app.ActivityThread.main(ActivityThread.java:5289)
        at java.lang
</code>```

答:
Although Xieyi's solution works perfectly fine, it's pretty much based on doing a reflection, which isn't really a good thing to do.

As an alternative answer, I managed to remove the child fragments using fragment transaction instead, which I believe should be the preferred approach in here.

First, register a fragment lifecycle callback to child fragment manager so that we can keep reference to the child fragments.

```<code>private List<Fragment> mFragments = new ArrayList<>();

@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);

    …(DO YOUR STUFF)
    //register a fragment lifecycle callback
    getChildFragmentManager().registerFragmentLifecycleCallbacks(new FragmentManager.FragmentLifecycleCallbacks() {

        @Override
        public void onFragmentCreated(FragmentManager fm, Fragment f, Bundle savedInstanceState) {
            super.onFragmentCreated(fm, f, savedInstanceState);
            mFragments.add(f);
        }

        @Override
        public void onFragmentDestroyed(FragmentManager fm, Fragment f) {
            super.onFragmentDestroyed(fm, f);
            mFragments.remove(f);
        }
    }, false);
</code>```

Next, we only need to iterate over the fragments list to remove them from the child fragment manager, inside onCreateView:

```<code>@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
                         @Nullable Bundle savedInstanceState) {
    //remove child fragments before inflating view
    Iterator<Fragment> iterator = mFragments.iterator();
    while (iterator.hasNext()) {
        Fragment fragment = iterator.next();
        iterator.remove();
        getChildFragmentManager().beginTransaction()
                .remove(fragment)
                .commitNow();
    }
    return inflater.inflate(R.layout.your_fragment, container, false);
}
</code>```

That's it.

Body:
I've met the problem that trouble me for days.

There is a ViewPager in the main activity which holds 3 Fragments as tab fragments. In the first fragment there is a ListView which holds some views, and which is the most important, another ViewPager. I want to hold some photos in the sub ViewPager, and use some more fragments here.

Now there is the trouble:

When the first Fragment is stopped (The third fragment in the parent ViewPager is seen on screen) and resumed (the user switch to the second fragment), the app crashes and the debugger says:

java.lang.IllegalArgumentException: No view found for id 0x7f05008b (com.example.viewpager:id/sub_viewpager) for fragment ScreenSlidePageFragment

I've already use the getChildFragmentManager() as this is a situation of nested fragments.

Here is the key code of list adapter corresponding to the first fragment in the parent ViewPager:

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    int type = getItemViewType(position);
    switch (type) {
        case TYPE_BANNER:
            if (convertView == null) {
                convertView = mBannerView.getBannerView(parent);
            }
            mBannerView.update(convertView);
            break;
        case TYPE_ITEM:
            break;
    }
    return convertView;
}

Here is the code of mBannerView:

public class BannerView {

    private static final DisplayImageOptions IMAGE_OPTIONS_SCALE_STRETCHED =
            new DisplayImageOptions.Builder()
                    .cacheInMemory()
                    .cacheOnDisc()
                    .imageScaleType(ImageScaleType.EXACTLY_STRETCHED)
                    .build();

    private FragmentActivity mActivity;
    private Fragment mFragment;
    private List<Banner> mBanners;
    private ScreenSlidePagerAdapter mPagerAdapter;
    private ViewPager mViewPager;

    public BannerView(FragmentActivity activity, Fragment fragment) {
        mActivity = activity;
        mFragment = fragment;
    }

    public void update(View convertView) {
        mViewPager = (ViewPager) convertView;
        if (mBanners != null && !mBanners.isEmpty()) {
            if (mPagerAdapter == null) {
                mPagerAdapter = new ScreenSlidePagerAdapter(mFragment.getChildFragmentManager());
                mViewPager.setAdapter(mPagerAdapter);
            }
        }
        mViewPager.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mOnBannerClickListener != null) {
                    mOnBannerClickListener.onBannerClick();
                }
            }
        });
    }

    class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter {
        public ScreenSlidePagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            return new ScreenSlidePageFragment(mBanners.get(position).getImageUrl());
        }

        @Override
        public int getCount() {
            return mBanners == null ? 0 : mBanners.size();
        }
    }

    class ScreenSlidePageFragment extends Fragment {

        private String mUrl;

        ScreenSlidePageFragment(String url) {
            super();
            mUrl = url;
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            View view = inflater.inflate(R.layout.item_banner, container, false);
            if (view != null) {
                ImageView imageView = (ImageView) view.findViewById(R.id.item_banner_image);
                imageView.setLayoutParams(new LinearLayout.LayoutParams(
                        LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT));
                ImageLoader.getInstance().displayImage(mUrl, imageView, IMAGE_OPTIONS_SCALE_STRETCHED);
            }
            return view;
        }
    }
}

Here is the detailed error list:

11-10 18:12:19.217    1444-1444/? E/MessageQueue-JNI﹕ java.lang.IllegalArgumentException: No view found for id 0x7f05008b (com.example.viewpager:id/sub_viewpager) for fragment ScreenSlidePageFragment{428d8ea0 #0 id=0x7f05008b}
        at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:919)
        at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1104)
        at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1086)
        at android.support.v4.app.FragmentManagerImpl.dispatchActivityCreated(FragmentManager.java:1884)
        at android.support.v4.app.Fragment.performActivityCreated(Fragment.java:1514)
        at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:947)
        at android.support.v4.app.FragmentManagerImpl.attachFragment(FragmentManager.java:1280)
        at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:672)
        at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1467)
        at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:472)
        at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:141)
        at android.support.v4.view.ViewPager.populate(ViewPager.java:1068)
        at android.support.v4.view.ViewPager.populate(ViewPager.java:914)
        at android.support.v4.view.ViewPager$3.run(ViewPager.java:244)
        at android.support.v4.view.ViewPager.completeScroll(ViewPager.java:1761)
        at android.support.v4.view.ViewPager.onInterceptTouchEvent(ViewPager.java:1896)
        at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:1854)
        at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2211)
        at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:1912)
        at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2211)
        at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:1912)
        at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2211)
        at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:1912)
        at com.android.internal.policy.impl.PhoneWindow$DecorView.superDispatchTouchEvent(PhoneWindow.java:2228)
        at com.android.internal.policy.impl.PhoneWindow.superDispatchTouchEvent(PhoneWindow.java:1471)
        at android.app.Activity.dispatchTouchEvent(Activity.java:2424)
        at com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchTouchEvent(PhoneWindow.java:2176)
        at android.view.View.dispatchPointerEvent(View.java:7571)
        at android.view.ViewRootImpl$ViewPostImeInputStage.processPointerEvent(ViewRootImpl.java:3883)
        at android.view.ViewRootImpl$ViewPostImeInputStage.onProcess(ViewRootImpl.java:3778)
        at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3379)
        at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:3429)
        at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:3398)
        at android.view.ViewRootImpl$AsyncInputStage.forward(ViewRootImpl.java:3483)
        at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:3406)
        at android.view.ViewRootImpl$AsyncInputStage.apply(ViewRootImpl.java:3540)
        at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3379)
        at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:3429)
        at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:3398)
        at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:3406)
        at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3379)
        at android.view.ViewRootImpl.deliverInputEvent(ViewRootImpl.java:5419)
        at android.view.ViewRootImpl.doProcessInputEvents(ViewRootImpl.java:5399)
        at android.view.ViewRootImpl.enqueueInputEvent(ViewRootImpl.java:5370)
        at android.view.ViewRootImpl$WindowInputEventReceiver.onInputEvent(ViewRootImpl.java:5493)
        at android.view.InputEventReceiver.dispatchInputEvent(InputEventReceiver.java:182)
        at android.os.MessageQueue.nativePollOnce(Native Method)
        at android.os.MessageQueue.next(MessageQueue.java:132)
        at android.os.Looper.loop(Looper.java:124)
        at android.app.ActivityThread.main(ActivityThread.java:5289)
        at java.lang

Body:
Although Xieyi's solution works perfectly fine, it's pretty much based on doing a reflection, which isn't really a good thing to do.

As an alternative answer, I managed to remove the child fragments using fragment transaction instead, which I believe should be the preferred approach in here.

First, register a fragment lifecycle callback to child fragment manager so that we can keep reference to the child fragments.

private List<Fragment> mFragments = new ArrayList<>();

@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);

    …(DO YOUR STUFF)
    //register a fragment lifecycle callback
    getChildFragmentManager().registerFragmentLifecycleCallbacks(new FragmentManager.FragmentLifecycleCallbacks() {

        @Override
        public void onFragmentCreated(FragmentManager fm, Fragment f, Bundle savedInstanceState) {
            super.onFragmentCreated(fm, f, savedInstanceState);
            mFragments.add(f);
        }

        @Override
        public void onFragmentDestroyed(FragmentManager fm, Fragment f) {
            super.onFragmentDestroyed(fm, f);
            mFragments.remove(f);
        }
    }, false);

Next, we only need to iterate over the fragments list to remove them from the child fragment manager, inside onCreateView:

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
                         @Nullable Bundle savedInstanceState) {
    //remove child fragments before inflating view
    Iterator<Fragment> iterator = mFragments.iterator();
    while (iterator.hasNext()) {
        Fragment fragment = iterator.next();
        iterator.remove();
        getChildFragmentManager().beginTransaction()
                .remove(fragment)
                .commitNow();
    }
    return inflater.inflate(R.layout.your_fragment, container, false);
}

That's it.


问:
angular2 and rxjs: ngIf according to a Subject
I've created this Subject:

```<code>private componentsState$: Subject<{[key: string]: boolean}> = new Subject();
</code>```

I'm subscribing to it using async pipe into my template:

```<code><div *ngIf="(componentsState$ | async).list" payment-list></div>
<div *ngIf="(componentsState$ | async).form" payment-form></div>
<div *ngIf="(componentsState$ | async).detail" payment-detail></div>
</code>```

payment-list, payment-form and payment-detail are subcomponents are swapped according to componentsState$ subject between each others.

on onNgInit:

```<code>ngOnInit(): void {
  this.swapToList();
}
</code>```

And,

```<code>swapToList(): void {
  this.swapComponent('list');
}

swapComponent(componentName: string): void {
  let componentsState = {
    'list': (): void => this.componentsState$.next(this.getListComponentState()),
    'form': (): void => this.componentsState$.next(this.getFormComponentState()),
    'detail': (): void => this.componentsState$.next(this.getDetailComponentState()),,
  };

  componentsState[componentName]();
}
</code>```

And getListComponentState, returns the key: boolean object:

```<code>private getListComponentState(): {[key: string]: boolean} {
  return { list: true, form: false, detail: false};
}
</code>```

And getFormComponentState

```<code>private getFormComponentState(): {[key: string]: boolean} {
  return { list: false, form: true, detail: false};
}
</code>```

And getDetailComponentState

```<code>private getDetailComponentState(): {[key: string]: boolean} {
  return { list: false, form: false, detail: true};
}
</code>```

Nevertheless, any component is shown when template is rendered. Any ideas?

I've to say, it fails only the first time the component parent component os loaded.

答:
I've solved it using BehaviorSubject instead of Subject:

```<code>private componentsState$: BehaviorSubject<{[key: string]: boolean}> = new BehaviorSubject(this.getListComponentState());
</code>```

So, then I'm able to set an initial value and avoid to call a next() on onNgInit method.

Body:
I've created this Subject:

private componentsState$: Subject<{[key: string]: boolean}> = new Subject();

I'm subscribing to it using async pipe into my template:

payment-list, payment-form and payment-detail are subcomponents are swapped according to componentsState$ subject between each others.

on onNgInit:

ngOnInit(): void {
  this.swapToList();
}

And,

swapToList(): void {
  this.swapComponent('list');
}

swapComponent(componentName: string): void {
  let componentsState = {
    'list': (): void => this.componentsState$.next(this.getListComponentState()),
    'form': (): void => this.componentsState$.next(this.getFormComponentState()),
    'detail': (): void => this.componentsState$.next(this.getDetailComponentState()),,
  };

  componentsState[componentName]();
}

And getListComponentState, returns the key: boolean object:

private getListComponentState(): {[key: string]: boolean} {
  return { list: true, form: false, detail: false};
}

And getFormComponentState

private getFormComponentState(): {[key: string]: boolean} {
  return { list: false, form: true, detail: false};
}

And getDetailComponentState

private getDetailComponentState(): {[key: string]: boolean} {
  return { list: false, form: false, detail: true};
}

Nevertheless, any component is shown when template is rendered. Any ideas?

I've to say, it fails only the first time the component parent component os loaded.

Body:
I've solved it using BehaviorSubject instead of Subject:

private componentsState$: BehaviorSubject<{[key: string]: boolean}> = new BehaviorSubject(this.getListComponentState());

So, then I'm able to set an initial value and avoid to call a next() on onNgInit method.


问:
List passed by ref - help me explain this behaviour
Take a look at the following program:

```<code>class Test
{
    List<int> myList = new List<int>();

    public void TestMethod()
    {
        myList.Add(100);
        myList.Add(50);
        myList.Add(10);

        ChangeList(myList);

        foreach (int i in myList)
        {
            Console.WriteLine(i);
        }
    }

    private void ChangeList(List<int> myList)
    {
        myList.Sort();

        List<int> myList2 = new List<int>();
        myList2.Add(3);
        myList2.Add(4);

        myList = myList2;
    }
}
</code>```

I assumed myList would have passed by ref, and the output would

```<code>3
4
</code>```

The list is indeed "passed by ref", but only the sort function takes effect. The following statement myList = myList2; has no effect.

So the output is in fact:

```<code>10
50
100
</code>```

Can you help me explain this behavior? If indeed myList is not passed-by-ref (as it appears from myList = myList2 not taking effect), how does myList.Sort() take effect?

I was assuming even that statement to not take effect and the output to be:

```<code>100
50
10
</code>```

答:
Use the ref keyword.

Look at the definitive reference here to understand passing parameters.

To be specific, look at this, to understand the behavior of the code.

EDIT: Sort works on the same reference (that is passed by value) and hence the values are ordered. However, assigning a new instance to the parameter won't work because parameter is passed by value, unless you put ref.

Putting ref lets you change the pointer to the reference to a new instance of List in your case. Without ref, you can work on the existing parameter, but can't make it point to something else.

Body:
Take a look at the following program:

class Test
{
    List<int> myList = new List<int>();

    public void TestMethod()
    {
        myList.Add(100);
        myList.Add(50);
        myList.Add(10);

        ChangeList(myList);

        foreach (int i in myList)
        {
            Console.WriteLine(i);
        }
    }

    private void ChangeList(List<int> myList)
    {
        myList.Sort();

        List<int> myList2 = new List<int>();
        myList2.Add(3);
        myList2.Add(4);

        myList = myList2;
    }
}

I assumed myList would have passed by ref, and the output would

3
4

The list is indeed "passed by ref", but only the sort function takes effect. The following statement myList = myList2; has no effect.

So the output is in fact:

10
50
100

Can you help me explain this behavior? If indeed myList is not passed-by-ref (as it appears from myList = myList2 not taking effect), how does myList.Sort() take effect?

I was assuming even that statement to not take effect and the output to be:

100
50
10


问:
Must EOT be at the bebinning in the line?
```<code>if(...) {
    if(...) {
        echo <<<EOT
        xxxxxx
EOT;
    }
}
</code>```

or

```<code>if(...) {
    if(...) {
        echo <<<EOT
        xxxxx
        EOT;
    }
}
</code>```

I prefer the latter, because it won't break the structure of code.

But it seems that the latter will cause highlight error in most editors.

Are there any standard stipulate that we must write as the former one? If so, why they make such a unsatisfying standard?

And are there any alternatives for writing block strings in php that won't break the code structure as the former one does? It is really unsatisfying...

答:
Edit for PHP version 7.3:

Beginning in PHP version 7.3 the Heredoc and Nowdoc syntax has been made flexible, so the code in OP is now valid as is. The indentation of the closing statement determines how much whitespace is stripped from the string.

Official release statement with more info: https://www.php.net/manual/en/migration73.new-features.php#migration73.new-features.core.heredoc

Original answer valid for PHP versions <= 7.2:

As others have pointed out, the heredoc syntax is strict and the closing statement must be placed on its own line with no whitespace.

There are very legit reasons for using the heredoc, see this SO-question for example: What is the advantage of using Heredoc in PHP?

If that is the case for you, then moving the block string to an external file as other answers suggest might be the best option if you want to keep your indentation consistent.

Alternatives to heredoc

If single or double quoted strings contain text with line breaks, all the whitespace from the indentation is preserved in the output, but this is suppressed in browsers.

Depending on what you want with your output, you could write your own wrapper function, for example if you want to show the newlines in the browser output:

```<code>if( true ) {
  if( true ) {

    // Single quoted
    $single = 'some
    text';
    echo $single; // some text

    // Double quoted
    $double = "some
    text";
    echo $double; // some text

    // Custom function
    function block($s) {
      return preg_replace('/\s*\n\s*/', '<br/>', $s);
    }
    echo block("some
    text"); // some<br/>text
    // In a browser this is shown as:
    // some
    // text
  }
}
</code>```

This last example with the block function strips all the whitespace around the newline character (including the newline) and replaces it with a
 tag.

Body:
if(...) {
    if(...) {
        echo <<<EOT
        xxxxxx
EOT;
    }
}

or

if(...) {
    if(...) {
        echo <<<EOT
        xxxxx
        EOT;
    }
}

I prefer the latter, because it won't break the structure of code.

But it seems that the latter will cause highlight error in most editors.

Are there any standard stipulate that we must write as the former one? If so, why they make such a unsatisfying standard?

And are there any alternatives for writing block strings in php that won't break the code structure as the former one does? It is really unsatisfying...

Body:
Edit for PHP version 7.3:

Beginning in PHP version 7.3 the Heredoc and Nowdoc syntax has been made flexible, so the code in OP is now valid as is. The indentation of the closing statement determines how much whitespace is stripped from the string.

Official release statement with more info: https://www.php.net/manual/en/migration73.new-features.php#migration73.new-features.core.heredoc

Original answer valid for PHP versions <= 7.2:

As others have pointed out, the heredoc syntax is strict and the closing statement must be placed on its own line with no whitespace.

There are very legit reasons for using the heredoc, see this SO-question for example: What is the advantage of using Heredoc in PHP?

If that is the case for you, then moving the block string to an external file as other answers suggest might be the best option if you want to keep your indentation consistent.

Alternatives to heredoc

If single or double quoted strings contain text with line breaks, all the whitespace from the indentation is preserved in the output, but this is suppressed in browsers.

Depending on what you want with your output, you could write your own wrapper function, for example if you want to show the newlines in the browser output:

if( true ) {
  if( true ) {

    // Single quoted
    $single = 'some
    text';
    echo $single; // some text

    // Double quoted
    $double = "some
    text";
    echo $double; // some text

    // Custom function
    function block($s) {
      return preg_replace('/\s*\n\s*/', '<br/>', $s);
    }
    echo block("some
    text"); // some<br/>text
    // In a browser this is shown as:
    // some
    // text
  }
}

This last example with the block function strips all the whitespace around the newline character (including the newline) and replaces it with a <br/> tag.


答:
It's normal.Each time you train the model,it will randomly initialize the parameters.If you set the number of iterations big enough,it will converge together.

you should use km.train() not KMeans.train()

Title: mllib KMeans show random behavior

Body:
I am using Scala Spark version 1.6.1 of KMeans and observe random behavior.

From my understanding the only random part is the initial centers initialization, which I addressed.

The experiment goes as follows: I run KMeans once and get the model - in the first time the centers are initialized randomly. After I get the model I run the following code:

//val latestModel: KMeansModel was trained earlier

val km:KMeans = new KMeans()
km.setK(numberOfClusters)
km.setMaxIterations(20)
if(previousModel != null)
{
  if(latestModel.k == numberOfClusters)
  {
    logger.info("Using cluster centers from previous model")
    km.setInitialModel(latestModel) //Set initial cluster centers
  }

}

kmeansModel = KMeans.train(dataAfterPCA, numberOfClusters, 20)
println("Run#1")
kmeansModel.clusterCenters.foreach(t => println(t))
kmeansModel = KMeans.train(dataAfterPCA, numberOfClusters, 20)
println("Run#2")
kmeansModel.clusterCenters.foreach(t => println(t))

As you can see I used the centers from latestModel and observed the printing.

Clusters centers are different:

Run#1
[0.20910608631141306,0.2008812839967183,0.27863526709646663,0.17173268189352492,0.4068108508134425,1.5978368739711135,-0.03644171546864227,-0.034547377483902755,-0.30757069112989693,-0.04681453873202328,-0.03432819320158391,-0.0229510885384198,0.16155254061277455]
[-0.9986167379861676,-0.4228356715735266,-0.9797043073290139,-0.48157892793353135,-0.7818198908298358,-0.3991524190947045,-0.09142025949212684,-0.034547396992719734,-0.4149601436468508,-0.04681453873202326,56.38182990388363,-0.027308795774228338,-0.8567167533956337]
[0.40443230723847245,0.40753014996762926,0.48063940183378684,0.37038231765864527,0.615561235153811,-0.1546334408565992,1.1517155044090817,-0.034547396992719734,0.17947924999402878,22.44497403279252,-0.04625456310989393,-0.027308795774228335,0.3521192856019467]
[0.44614142085922764,0.39183992738993073,0.5599716298711428,0.31737580128115594,0.8674951428275776,0.799192261554564,1.090005738447001,-0.034547396992719734,-0.10481785131247881,-0.04681453873202326,-0.04625456310989393,41.936484571639795,0.4864344010461224]
[0.3506753428299332,0.3395786568210998,0.45443729624612045,0.3115089688709545,0.4762387976829325,11.3438592782776,0.04041394221229458,-0.03454735647587367,1.0065342405811888,-0.046814538732023264,-0.04625456310989393,-0.02730879577422834,0.19094114706893608]
[0.8238890515931856,0.8366348841253755,0.9862410283176735,0.7635549199270218,1.1877685458769478,0.7813626284105487,38.470668704621396,-0.03452467509554947,-0.4149294724823659,-0.04681453873202326,1.2214455451195836,-0.0212002267696445,1.1580099782670004]
[0.21425069771110813,0.22469514482272127,0.30113774986108593,0.182605001533264,0.4637631333393578,0.029033109984974183,-0.002029301682406235,-0.03454739699271971,2.397309416381941,0.011941957462594896,-0.046254563109893905,-0.018931196565979497,0.35297479589140024]
[-0.6546798328639079,-0.6358370654999287,-0.7928424675098332,-0.5071485895971765,-0.7400917528763642,-0.39717704681705857,-0.08938412993092051,-0.02346229974103403,-0.40690957159820434,-0.04681453873202331,-0.023692354206657835,-0.024758557139368385,-0.6068025631839297]
[-0.010895214450242299,-0.023949109470308646,-0.07602949287623037,-0.018356772906618683,-0.39876455727035937,-0.21260655806916112,-0.07991736890951397,-0.03454278343886248,-0.3644711133467814,-0.04681453873202319,-0.03250578362850749,-0.024761896110663685,-0.09605183996736125]
[0.14061295519424166,0.14152409771288327,0.1988841951819923,0.10943684592384875,0.3404665467004296,-0.06397788416055701,0.030711112793548753,0.044173951636969355,-0.08950950493941498,-0.039099833378049946,-0.03265898863536165,-0.02406954910363843,0.16029254891067157]
Run#2
[0.11726347529467256,0.11240236056044385,0.145845029386598,0.09061870140058333,0.15437020046635777,0.03499211466800115,-0.007112193875767524,-0.03449302405046689,-0.20652827212743696,-0.041880871009984943,-0.042927843040582066,-0.024409659630584803,0.10595250123068904]
[-0.9986167379861676,-0.4228356715735266,-0.9797043073290139,-0.48157892793353135,-0.7818198908298358,-0.3991524190947045,-0.09142025949212684,-0.034547396992719734,-0.4149601436468508,-0.04681453873202326,56.38182990388363,-0.027308795774228338,-0.8567167533956337]
[0.40443230723847245,0.40753014996762926,0.48063940183378684,0.37038231765864527,0.615561235153811,-0.1546334408565992,1.1517155044090817,-0.034547396992719734,0.17947924999402878,22.44497403279252,-0.04625456310989393,-0.027308795774228335,0.3521192856019467]
[0.44614142085922764,0.39183992738993073,0.5599716298711428,0.31737580128115594,0.8674951428275776,0.799192261554564,1.090005738447001,-0.034547396992719734,-0.10481785131247881,-0.04681453873202326,-0.04625456310989393,41.936484571639795,0.4864344010461224]
[0.056657434641233205,0.03626919750209713,0.1229690343482326,0.015190756508711958,-0.278078039715814,-0.3991255672375599,0.06613236052364684,28.98230095429352,-0.4149601436468508,-0.04681453873202326,-0.04625456310989393,-0.027308795774228338,-0.31945629161893124]
[0.8238890515931856,0.8366348841253755,0.9862410283176735,0.7635549199270218,1.1877685458769478,0.7813626284105487,38.470668704621396,-0.03452467509554947,-0.4149294724823659,-0.04681453873202326,1.2214455451195836,-0.0212002267696445,1.1580099782670004]
[-0.17971932675588306,-7.925508727413683E-4,-0.08990036350145142,-0.033456211225756705,-0.1514393713761394,-0.08538399305051374,-0.09132371177664707,-0.034547396992719734,-0.19858350916572132,-0.04681453873202326,4.873470425033645,-0.023394262810850164,0.15064661243568334]
[-0.4488579509785471,-0.4428314704219248,-0.5776049270843375,-0.3580559344350086,-0.6787807800457122,-0.378841125619109,-0.08742047856626034,-0.027746008987067004,-0.3951588549839565,-0.046814538732023264,-0.04625456310989399,-0.02448638761790114,-0.4757072927512256]
[0.2986301685357443,0.2895405124404614,0.39435230210861016,0.2549716029318805,0.5238783183359862,5.629286423487358,0.012002410566794644,-0.03454737293733725,0.1657346440290886,-0.046814538732023264,-0.03653898382838679,-0.025149508122450703,0.2715302163354414]
[0.2072253546037051,0.21958064267615496,0.29431697644435456,0.17741927849917147,0.4521349932664591,-0.010031680919536882,3.9433761322307554E-4,-0.03454739699271971,2.240412962951767,0.005598926623403161,-0.046254563109893905,-0.018412129948368845,0.33990882056156724]

I am trying to understand what is the source of this random behavior and how can it be avoided, couldn't find anything on the Git source either.

Any ideas/suggestions? having a stable behavior is mandatory for me.


问:
Model is running iOS 10.2 (14C92), which may not be supported by this version of Xcode
I am facing this error, i am done with research on that.

I conclude the result, i need one file for device support 10.2(14C92)

Please share that file.

GoTo:

Right click on Xcode 8 or Newer version of your Xcode, select "Show
Package Contents", "Contents", "Developer", "Platforms",
"iPhoneOS.Platform", "Device Support"

Copy the 10.2(14C92) folder (or above for later version).

I need that folder.

Thanks.

答:
Here I have this file for 10.3 or 11.3 or 11.4 into Xcode 8+.
You can download file from this link.
10.3:-
https://www.dropbox.com/s/i1f7q8w3vgr2ozl/10.3%20%2814E269%29.zip?dl=0

11.3:-
https://www.dropbox.com/s/wya3eu2j5db7tpt/11.3%20%2815E217%29.zip?dl=0

11.4:-
https://www.dropbox.com/s/86i9zjunpsy9b0b/11.4%20%2815F79%29.zip?dl=0

9 -> 12 All Files:
https://github.com/mendaparadarshit/xcode-9-ios-12-support

Steps:-

Download above Zip file and extract them.

Click on "Finder" in MAC OS, You can see in Topbar all menus, Click on "Go"

Click on "Go to Folder" ()

Paste this path over their (make sure that you have installed xcode with named : "Xcode.app")
/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/DeviceSupport

Paste your extracted "10.3 (14E269)" directory to that place.

quite Xcode and restart it. you can run your projects successfully in your real device.

Thank you,

Darshit