问:
Pom.xml downloading unmentioned dependencies
I have a simple pom.xml which have only JUnit dependency and exec-maven-plugin.

But when I say "mvn install" I see lot of dependencies downloading.

Are this mandatory dependencies by maven?

I am listing a few here :

```<code>ClassWorlds
Commons-logging-api
log4j
backport-util-concurrent
</code>```

答:
Are this mandatory dependencies by maven

Yes, those are transitive dependencies.

This allows you to avoid needing to discover and specify the libraries that your own dependencies require, and including them automatically

See "Resolving conflicts using the dependency tree"

A project's dependency tree can be expanded to display dependency conflicts. For example, to find out why Commons Collections 2.0 is being used by the Maven Dependency Plugin, we can execute the following in the project's directory:

```<code>mvn dependency:tree -Dverbose -Dincludes=commons-collections
</code>```

Body:
I have a simple pom.xml which have only JUnit dependency and exec-maven-plugin.

But when I say "mvn install" I see lot of dependencies downloading.

Are this mandatory dependencies by maven?

I am listing a few here :

ClassWorlds
Commons-logging-api
log4j
backport-util-concurrent

Body:
Are this mandatory dependencies by maven

Yes, those are transitive dependencies.

This allows you to avoid needing to discover and specify the libraries that your own dependencies require, and including them automatically

See "Resolving conflicts using the dependency tree"

A project's dependency tree can be expanded to display dependency conflicts. For example, to find out why Commons Collections 2.0 is being used by the Maven Dependency Plugin, we can execute the following in the project's directory:

mvn dependency:tree -Dverbose -Dincludes=commons-collections


来源: stackexchange

问:
Django file now showing in the template
My file is being uploaded in the correct path but I have an issues with it:

Whenever I refresh my HTML page the file gets uploaded again and again. How do I solve this? Also
Please help me with the code or suggest me.

Thanks in advance:)

My views.py

```<code>def about_experiment(request, ex_link_name):
  researcher = None
  study = None
  posts = None
  exp = get_object_or_404(Experiment,link_name = ex_link_name)
  high_scores = ScoreItem.objects.filter(experiment=exp,active=True)
  context = {
    'request': request,
    'exp':exp,
    'high_scores': high_scores,
    'awards':AwardItem.objects.filter(experiment=exp,visible=True),
  }

  if exp.about_file:
    context['about_file'] = settings.EXPERIMENT_DIRS+exp.about_file.get_include_path()
    return render(request, 'about_experiment.html', context)

  if request.method == 'POST':
        form = AboutHelp(request.POST, request.FILES)
        posts = Help.objects.filter().order_by('-date')[0]
        documents = Help.objects.all()
        if form.is_valid():
            obj = form.save(commit = False)
            obj.save()
            researcher = form.cleaned_data['researcher']
            study = form.cleaned_data['study']
            document = form.cleaned_data['document']

  else:
      form = AboutHelp()
      posts = Help.objects.filter().order_by('-date')[0]
      documents = Help.objects.all()
      return render(request, 'about_experiment.html', {'posts': posts})

  return render(request, 'about_experiment.html', {'posts': posts})
</code>```

Source page

```<code><form action="{% url 'lazer.views.about_experiment' exp.link_name %}" method="POST" name="form" enctype="multipart/form-data">
  {% csrf_token %}
      <label>Researcher Name(s):
        <input type="text" name="researcher"><br>
      <lable>Study Summary
        <textarea rows="10" cols="50" placeholder="Start typing..." maxlength="500" class="form-control" name="study"></textarea>
      <br>
      <label>Upload your IRB approval letter:
        <input type ="file" id="irb-file" class="file_input" name="document"></label>
      <br>
      <input type = "submit" value="Submit" class="btn btn-primary" />
  </form>
</code>```

destination page

```<code><div class="tab-pane" id="irb">
          <h4> List of file(s) uploaded:</h4>

        <!--File upload-->
          {% if documents %}
              <ul>
              {% for file in documents %}
                  <li><a href="{{ file.document.url }}"> {{ file.document.name }} </a></li>
              {% endfor %}
              </ul>
          {% else %}
              <p>No such documents available.</p>
          {% endif %}
        <!--File upload ends-->
          </div>

          {% if high_scores %}
          {% for hs in high_scores %}
          <div class="tab-pane" id="{{ hs.link_name }}">
            {% high_score request exp.link_name hs.link_name %}
          </div>
          {% endfor %}
          {% endif %}
</code>```

答:
As @almost a beginner pointed out, you should be redirecting to some other view, if your form is submitted successfully. If not, (in your case), when the page reloads, the code for POST request is executed again. ie, your form is submitted again. I could suggest some changes in your view,

```<code>def about_experiment(request, ex_link_name):
    exp = get_object_or_404(Experiment,link_name = ex_link_name)
    high_scores = ScoreItem.objects.filter(experiment=exp,active=True)
    context = {
      'request': request,
      'exp':exp,
      'high_scores': high_scores,
      'awards':AwardItem.objects.filter(experiment=exp,visible=True),
      'posts':Help.objects.filter().order_by('-date')[0],
      'documents':Help.objects.all()
    }

    if exp.about_file:
        context['about_file'] = settings.EXPERIMENT_DIRS+exp.about_file.get_include_path()

    if request.method == 'POST':
        form = AboutHelp(request.POST, request.FILES)

        if form.is_valid():
            obj = form.save(commit = False)
            obj.save()
            return redirect(reverse('lazer.views.about_experiment', kwargs={ 'ex_link_name':obj.link_name }))
    else:
        form = AboutHelp()

    return render(request, 'about_experiment.html', context)
</code>```

Here, I merely assumed your obj has a field link_name. You may need to change that according to your models.

ContentLicense: CC BY-SA 3.0

Title: Django file now showing in the template

Body:
My file is being uploaded in the correct path but I have an issues with it:

Whenever I refresh my HTML page the file gets uploaded again and again. How do I solve this? Also
Please help me with the code or suggest me.

Thanks in advance:)

My views.py

def about_experiment(request, ex_link_name):
  researcher = None
  study = None
  posts = None
  exp = get_object_or_404(Experiment,link_name = ex_link_name)
  high_scores = ScoreItem.objects.filter(experiment=exp,active=True)
  context = {
    'request': request,
    'exp':exp,
    'high_scores': high_scores,
    'awards':AwardItem.objects.filter(experiment=exp,visible=True),
  }

  if exp.about_file:
    context['about_file'] = settings.EXPERIMENT_DIRS+exp.about_file.get_include_path()
    return render(request, 'about_experiment.html', context)

  if request.method == 'POST':
        form = AboutHelp(request.POST, request.FILES)
        posts = Help.objects.filter().order_by('-date')[0]
        documents = Help.objects.all()
        if form.is_valid():
            obj = form.save(commit = False)
            obj.save()
            researcher = form.cleaned_data['researcher']
            study = form.cleaned_data['study']
            document = form.cleaned_data['document']

  else:
      form = AboutHelp()
      posts = Help.objects.filter().order_by('-date')[0]
      documents = Help.objects.all()
      return render(request, 'about_experiment.html', {'posts': posts})

  return render(request, 'about_experiment.html', {'posts': posts})

Source page

<form action="{% url 'lazer.views.about_experiment' exp.link_name %}" method="POST" name="form" enctype="multipart/form-data">
  {% csrf_token %}
      Researcher Name(s):
        <input type="text" name="researcher">

      <lable>Study Summary
        <textarea rows="10" cols="50" placeholder="Start typing..." maxlength="500" class="form-control" name="study"></textarea>

      Upload your IRB approval letter:
        <input type ="file" id="irb-file" class="file_input" name="document">

      <input type = "submit" value="Submit" class="btn btn-primary" />
  </form>

destination page

 List of file(s) uploaded:

          {% if documents %}

              {% for file in documents %}

 {{ file.document.name }}

              {% endfor %}

          {% else %}

No such documents available.

          {% endif %}

          {% if high_scores %}
          {% for hs in high_scores %}

            {% high_score request exp.link_name hs.link_name %}

          {% endfor %}
          {% endif %}

Body:
As @almost a beginner pointed out, you should be redirecting to some other view, if your form is submitted successfully. If not, (in your case), when the page reloads, the code for POST request is executed again. ie, your form is submitted again. I could suggest some changes in your view,

def about_experiment(request, ex_link_name):
    exp = get_object_or_404(Experiment,link_name = ex_link_name)
    high_scores = ScoreItem.objects.filter(experiment=exp,active=True)
    context = {
      'request': request,
      'exp':exp,
      'high_scores': high_scores,
      'awards':AwardItem.objects.filter(experiment=exp,visible=True),
      'posts':Help.objects.filter().order_by('-date')[0],
      'documents':Help.objects.all()
    }

    if exp.about_file:
        context['about_file'] = settings.EXPERIMENT_DIRS+exp.about_file.get_include_path()

    if request.method == 'POST':
        form = AboutHelp(request.POST, request.FILES)

        if form.is_valid():
            obj = form.save(commit = False)
            obj.save()
            return redirect(reverse('lazer.views.about_experiment', kwargs={ 'ex_link_name':obj.link_name }))
    else:
        form = AboutHelp()

    return render(request, 'about_experiment.html', context)

Here, I merely assumed your obj has a field link_name. You may need to change that according to your models.


问:
Hide WooCommerce Add To Cart button when price is zero
I need to hide my add to cart button on the condition where the price = 0.00. If the price is greater than 0.00 i would like the button to reappear.

However i also use the WooTheme Wish List extension and i need the add to wish list button to remain. I would also like to change the text from Free to "Subscription Product" when the value is 0.00.

This is only needed on the single product page as we do not show the add to cart anywhere else.

Currently if the price is set to 0.00 i get the text at the top of the single product page saying "free" and the add to cart button remains as does the add to wish list button. If i remove the price all together the buttons also disappear hence why i need to "hide" the button to retain the wish list one.

I have tried the following Code inserted into my functions.php file

```<code><?php
 /*
    * Swop the 'Free!' price notice and hide the cart with 'POA' in WooCommerce
 */
    add_filter( 'woocommerce_variable_free_price_html',  'hide_free_price_notice' );
    add_filter( 'woocommerce_free_price_html',           'hide_free_price_notice' );
    add_filter( 'woocommerce_variation_free_price_html', 'hide_free_price_notice' );

function hide_free_price_notice( $price ) {
    remove_action ( 'woocommerce_after_shop_loop_item', 'woocommerce_template_loop_add_to_cart', 10 );
    remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_add_to_cart', 30 );
    return 'POA';
}
?>
</code>```

However, although it did work in that it changed the "Free" text to "POA" and also hid the "Add to Cart button" the "Add to Wishlist" button also disappeared.

If i changed the value to 0.01 everything appeared again so it nearly there... i just need the Wish List button to stay.

Any help or pointers would be greatly appreciated. Many Thanks...

Just for info, the reason i need to do this is because we run a subscription service, so products that are included in a subscription service do not need a price but do need to be shown so they can be added to a wish list. However sometimes we sell the products off so when they have a value i need the button to reappear so they can be added to the cart.
 Simply having zero doesn't work because believe it or not people think they are free and try to add them to the cart to purchase !

答:
Please add below code in your active theme functions.php and check it.

```<code>function wpcustom_is_purchasable( $purchasable, $product ){
    if( $product->get_price() == 0 )
        $purchasable = false;
    return $purchasable;
}
add_filter( 'woocommerce_is_purchasable', 'wpcustom_is_purchasable', 10, 2 );
</code>```

Body:
I need to hide my add to cart button on the condition where the price = 0.00. If the price is greater than 0.00 i would like the button to reappear.

However i also use the WooTheme Wish List extension and i need the add to wish list button to remain. I would also like to change the text from Free to "Subscription Product" when the value is 0.00.

This is only needed on the single product page as we do not show the add to cart anywhere else.

Currently if the price is set to 0.00 i get the text at the top of the single product page saying "free" and the add to cart button remains as does the add to wish list button. If i remove the price all together the buttons also disappear hence why i need to "hide" the button to retain the wish list one.

I have tried the following Code inserted into my functions.php file

<?php
 /*
    * Swop the 'Free!' price notice and hide the cart with 'POA' in WooCommerce
 */
    add_filter( 'woocommerce_variable_free_price_html',  'hide_free_price_notice' );
    add_filter( 'woocommerce_free_price_html',           'hide_free_price_notice' );
    add_filter( 'woocommerce_variation_free_price_html', 'hide_free_price_notice' );

function hide_free_price_notice( $price ) {
    remove_action ( 'woocommerce_after_shop_loop_item', 'woocommerce_template_loop_add_to_cart', 10 );
    remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_add_to_cart', 30 );
    return 'POA';
}
?>

However, although it did work in that it changed the "Free" text to "POA" and also hid the "Add to Cart button" the "Add to Wishlist" button also disappeared.

If i changed the value to 0.01 everything appeared again so it nearly there... i just need the Wish List button to stay.

Any help or pointers would be greatly appreciated. Many Thanks...

Just for info, the reason i need to do this is because we run a subscription service, so products that are included in a subscription service do not need a price but do need to be shown so they can be added to a wish list. However sometimes we sell the products off so when they have a value i need the button to reappear so they can be added to the cart.
 Simply having zero doesn't work because believe it or not people think they are free and try to add them to the cart to purchase !

Body:
Please add below code in your active theme functions.php and check it.

function wpcustom_is_purchasable( $purchasable, $product ){
    if( $product->get_price() == 0 )
        $purchasable = false;
    return $purchasable;
}
add_filter( 'woocommerce_is_purchasable', 'wpcustom_is_purchasable', 10, 2 );


问:
simple_form I'm getting No input found for citext
I have a basic text input in the simple_form:

```<code>= f.input :title, label: "Name:", placeholder: "New make"
</code>```

I fetch this exception when I'm trying to render the view:

```<code>No input found for citext
</code>```

How can I solve it?

答:
You can also put following line in the initializer to define custom input mappings.</p>

```<code>SimpleForm::FormBuilder.map_type :citext, to: SimpleForm::Inputs::TextInput
</code>```

Body:
I have a basic text input in the simple_form:

= f.input :title, label: "Name:", placeholder: "New make"

I fetch this exception when I'm trying to render the view:

No input found for citext

How can I solve it?

Body:
You can also put following line in the initializer to define custom input mappings.

SimpleForm::FormBuilder.map_type :citext, to: SimpleForm::Inputs::TextInput


问:
D3 Json request getting XmlHttpRequest error: Origin null is not allowed by Access-Control-Allow-Origin
I'm using d3.json() to request a json object and parse/visualize it...

It's being requested from a java servlet doGet function...I know for a fact that my java server is successful sending the json to the browser. However, I'm running into a problem trying to parse the json. d3.json is supposed to do an http get request, but for some reason, it is returning an XML request error:

XMLHttpRequest cannot load "http://localhost:8080/cluster". Origin null is not allowed by Access-Control-Allow-Origin.

Is there some further set up I should know about with d3.json or is it supposed to just work out of the box? Here is my code..

```<code>    d3.json("http://localhost:8080/cluster", function(json) {

            //do visualization
            var node = vis.data([json]).selectAll("g.node")
             .data(pack.nodes)
             .enter().append("g")
             .attr("class", function(d) {return d.children ? "node" : "leaf node" ;})
             .attr("transform", function(d) {return "translate(" + d.x + "," + d.y +")"; });

            node.append("title")
                .text(function(d) { return d.name + (d.children ? "" : ": " + format(d.size)); });

            node.append("circle")
            .attr("r", function(d) { return d.r; });

            node.filter(function(d) { return !d.children; }).append("text")
            .attr("text-anchor", "middle")
            .attr("dy", ".3em")
            .text(function(d) { return d.name.substring(0, d.r / 3); });
    }
</code>```

Am I doing something wrong here? I'm mainly confused because d3.json is supposed to do an HTTP get by default, but its returning an XMLHTTPrequest error...

答: If you are loading you HTML file using the file protocol (file:///) then you will run into this issue. Try to load the html file also using localhost, and that should resolve the issue.</p>

Body:
I'm using d3.json() to request a json object and parse/visualize it...

It's being requested from a java servlet doGet function...I know for a fact that my java server is successful sending the json to the browser. However, I'm running into a problem trying to parse the json. d3.json is supposed to do an http get request, but for some reason, it is returning an XML request error:

XMLHttpRequest cannot load "http://localhost:8080/cluster". Origin null is not allowed by Access-Control-Allow-Origin.

Is there some further set up I should know about with d3.json or is it supposed to just work out of the box? Here is my code..

    d3.json("http://localhost:8080/cluster", function(json) {

            //do visualization
            var node = vis.data([json]).selectAll("g.node")
             .data(pack.nodes)
             .enter().append("g")
             .attr("class", function(d) {return d.children ? "node" : "leaf node" ;})
             .attr("transform", function(d) {return "translate(" + d.x + "," + d.y +")"; });

            node.append("title")
                .text(function(d) { return d.name + (d.children ? "" : ": " + format(d.size)); });

            node.append("circle")
            .attr("r", function(d) { return d.r; });

            node.filter(function(d) { return !d.children; }).append("text")
            .attr("text-anchor", "middle")
            .attr("dy", ".3em")
            .text(function(d) { return d.name.substring(0, d.r / 3); });
    }

Am I doing something wrong here? I'm mainly confused because d3.json is supposed to do an HTTP get by default, but its returning an XMLHTTPrequest error...


问:
AngularJS checkbox avoid counting when uncheck checkBox
Here is my running code in Plunker

I got a bug: When I uncheck the answer, I do not want to count how many times we select this answer? We will only count the number when we check the answer. For example, I check "Yes", I uncheck "Yes", I check "Yes" again, I will only show "Yes" was selected 2 times, instead of 3 times.

I read some posts about this issue, but cannot make it work by using checked property?

```<code><input type="checkbox" ng-change="answerSelected(ans)" ng-model="checkAnswer">{{ans.answer}}
</code>```

答:
You can call the function conditionally only when the checbox is checked:

```<code><input type="checkbox" ng-change="!checkAnswer || answerSelected(ans)" ng-model="checkAnswer">{{ans.answer}}
</code>```

When the checkbox is checked, checkAnswer will evaluate to true, and the function will be called.

When the checkbox is unchecked, checkAnswer will evaluate to false, and the function will not be called.

Here's a plunker

Body:
Here is my running code in Plunker

I got a bug: When I uncheck the answer, I do not want to count how many times we select this answer? We will only count the number when we check the answer. For example, I check "Yes", I uncheck "Yes", I check "Yes" again, I will only show "Yes" was selected 2 times, instead of 3 times.

I read some posts about this issue, but cannot make it work by using checked property?

<input type="checkbox" ng-change="answerSelected(ans)" ng-model="checkAnswer">{{ans.answer}}

Body:
You can call the function conditionally only when the checbox is checked:

<input type="checkbox" ng-change="!checkAnswer || answerSelected(ans)" ng-model="checkAnswer">{{ans.answer}}

When the checkbox is checked, checkAnswer will evaluate to true, and the function will be called.

When the checkbox is unchecked, checkAnswer will evaluate to false, and the function will not be called.

Here's a plunker


问:
Unable to execute Maven project in Jenkins
Thanks for reading this question. I am very new to Maven and Jenkins and trying to implement it for learning purpose. I am getting the below output in jenkins console. I am well aware that there is a silly mistake but I couldnt find it. Please advice.</p>

```<code>Parsing POMs
[naukri] $ "C:\Program Files (x86)\Java\jdk1.6.0_24/bin/java" -cp C:\Users\Badri\.jenkins\plugins\maven-plugin\WEB-INF\lib\maven31-agent-1.5.jar;C:\Users\Badri\.jenkins\tools\hudson.tasks.Maven_MavenInstallation\MAVEN\boot\plexus-classworlds-2.5.2.jar;C:\Users\Badri\.jenkins\tools\hudson.tasks.Maven_MavenInstallation\MAVEN/conf/logging jenkins.maven3.agent.Maven31Main C:\Users\Badri\.jenkins\tools\hudson.tasks.Maven_MavenInstallation\MAVEN C:\Users\Badri\.jenkins\war\WEB-INF\lib\remoting-2.49.jar C:\Users\Badri\.jenkins\plugins\maven-plugin\WEB-INF\lib\maven31-interceptor-1.5.jar C:\Users\Badri\.jenkins\plugins\maven-plugin\WEB-INF\lib\maven3-interceptor-commons-1.5.jar 52941
<===[JENKINS REMOTING CAPACITY]===>channel started
ERROR: Failed to parse POMs
java.io.IOException: Remote call on Channel to Maven [C:\Program Files (x86)\Java\jdk1.6.0_24/bin/java, -cp, C:\Users\Badri\.jenkins\plugins\maven-plugin\WEB-INF\lib\maven31-agent-1.5.jar;C:\Users\Badri\.jenkins\tools\hudson.tasks.Maven_MavenInstallation\MAVEN\boot\plexus-classworlds-2.5.2.jar;C:\Users\Badri\.jenkins\tools\hudson.tasks.Maven_MavenInstallation\MAVEN/conf/logging, jenkins.maven3.agent.Maven31Main, C:\Users\Badri\.jenkins\tools\hudson.tasks.Maven_MavenInstallation\MAVEN, C:\Users\Badri\.jenkins\war\WEB-INF\lib\remoting-2.49.jar, C:\Users\Badri\.jenkins\plugins\maven-plugin\WEB-INF\lib\maven31-interceptor-1.5.jar, C:\Users\Badri\.jenkins\plugins\maven-plugin\WEB-INF\lib\maven3-interceptor-commons-1.5.jar, 52941] failed
    at hudson.remoting.Channel.call(Channel.java:760)
    at hudson.maven.ProcessCache$MavenProcess.call(ProcessCache.java:161)
    at hudson.maven.MavenModuleSetBuild$MavenModuleSetBuildExecution.doRun(MavenModuleSetBuild.java:840)
    at hudson.model.AbstractBuild$AbstractBuildExecution.run(AbstractBuild.java:536)
    at hudson.model.Run.execute(Run.java:1718)
    at hudson.maven.MavenModuleSetBuild.run(MavenModuleSetBuild.java:529)
    at hudson.model.ResourceController.execute(ResourceController.java:89)
    at hudson.model.Executor.run(Executor.java:240)
Caused by: java.lang.ClassFormatError: Failed to load hudson.maven.Maven3Builder$JenkinsEventSpy
    at hudson.remoting.RemoteClassLoader.loadClassFile(RemoteClassLoader.java:325)
    at hudson.remoting.RemoteClassLoader.findClass(RemoteClassLoader.java:237)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:248)
    at java.lang.Class.getDeclaredFields0(Native Method)
    at java.lang.Class.privateGetDeclaredFields(Class.java:2291)
    at java.lang.Class.getDeclaredField(Class.java:1880)
    at java.io.ObjectStreamClass.getDeclaredSUID(ObjectStreamClass.java:1610)
    at java.io.ObjectStreamClass.access$700(ObjectStreamClass.java:52)
    at java.io.ObjectStreamClass$2.run(ObjectStreamClass.java:425)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.io.ObjectStreamClass.<init>(ObjectStreamClass.java:413)
    at java.io.ObjectStreamClass.lookup(ObjectStreamClass.java:310)
    at java.io.ObjectStreamClass.initNonProxy(ObjectStreamClass.java:547)
    at java.io.ObjectInputStream.readNonProxyDesc(ObjectInputStream.java:1582)
    at java.io.ObjectInputStream.readClassDesc(ObjectInputStream.java:1495)
    at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1731)
    at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1328)
    at java.io.ObjectInputStream.readObject(ObjectInputStream.java:350)
    at hudson.remoting.UserRequest.deserialize(UserRequest.java:185)
    at hudson.remoting.UserRequest.perform(UserRequest.java:99)
    at hudson.remoting.UserRequest.perform(UserRequest.java:49)
    at hudson.remoting.Request$2.run(Request.java:324)
    at hudson.remoting.InterceptingExecutorService$1.call(InterceptingExecutorService.java:68)
    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)
    at java.util.concurrent.FutureTask.run(FutureTask.java:138)
    at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
    at java.lang.Thread.run(Thread.java:662)
    at ......remote call to Channel to Maven [C:\Program Files (x86)\Java\jdk1.6.0_24/bin/java, -cp, C:\Users\Badri\.jenkins\plugins\maven-plugin\WEB-INF\lib\maven31-agent-1.5.jar;C:\Users\Badri\.jenkins\tools\hudson.tasks.Maven_MavenInstallation\MAVEN\boot\plexus-classworlds-2.5.2.jar;C:\Users\Badri\.jenkins\tools\hudson.tasks.Maven_MavenInstallation\MAVEN/conf/logging, jenkins.maven3.agent.Maven31Main, C:\Users\Badri\.jenkins\tools\hudson.tasks.Maven_MavenInstallation\MAVEN, C:\Users\Badri\.jenkins\war\WEB-INF\lib\remoting-2.49.jar, C:\Users\Badri\.jenkins\plugins\maven-plugin\WEB-INF\lib\maven31-interceptor-1.5.jar, C:\Users\Badri\.jenkins\plugins\maven-plugin\WEB-INF\lib\maven3-interceptor-commons-1.5.jar, 52941](Native Method)
    at hudson.remoting.Channel.attachCallSiteStackTrace(Channel.java:1356)
    at hudson.remoting.UserResponse.retrieve(UserRequest.java:221)
    at hudson.remoting.Channel.call(Channel.java:752)
    ... 7 more
Caused by: java.lang.UnsupportedClassVersionError: org/apache/maven/eventspy/EventSpy : Unsupported major.minor version 51.0
    at java.lang.ClassLoader.defineClass1(Native Method)
    at java.lang.ClassLoader.defineClassCond(ClassLoader.java:632)
    at java.lang.ClassLoader.defineClass(ClassLoader.java:616)
    at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:141)
    at java.net.URLClassLoader.defineClass(URLClassLoader.java:283)
    at java.net.URLClassLoader.access$000(URLClassLoader.java:58)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:197)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
    at org.codehaus.plexus.classworlds.realm.ClassRealm.loadClassFromSelf(ClassRealm.java:401)
    at org.codehaus.plexus.classworlds.strategy.SelfFirstStrategy.loadClass(SelfFirstStrategy.java:42)
    at org.codehaus.plexus.classworlds.realm.ClassRealm.unsynchronizedLoadClass(ClassRealm.java:271)
    at org.codehaus.plexus.classworlds.realm.ClassRealm.loadClass(ClassRealm.java:254)
    at org.codehaus.plexus.classworlds.realm.ClassRealm.loadClass(ClassRealm.java:239)
    at org.codehaus.plexus.classworlds.realm.ClassRealm.loadClassFromParent(ClassRealm.java:445)
    at org.codehaus.plexus.classworlds.strategy.SelfFirstStrategy.loadClass(SelfFirstStrategy.java:46)
    at org.codehaus.plexus.classworlds.realm.ClassRealm.unsynchronizedLoadClass(ClassRealm.java:271)
    at org.codehaus.plexus.classworlds.realm.ClassRealm.loadClass(ClassRealm.java:254)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:296)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:248)
    at java.lang.ClassLoader.defineClass1(Native Method)
    at java.lang.ClassLoader.defineClassCond(ClassLoader.java:632)
    at java.lang.ClassLoader.defineClass(ClassLoader.java:616)
    at java.lang.ClassLoader.defineClass(ClassLoader.java:466)
    at hudson.remoting.RemoteClassLoader.loadClassFile(RemoteClassLoader.java:323)
    at hudson.remoting.RemoteClassLoader.findClass(RemoteClassLoader.java:237)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:248)
    at java.lang.Class.getDeclaredFields0(Native Method)
    at java.lang.Class.privateGetDeclaredFields(Class.java:2291)
    at java.lang.Class.getDeclaredField(Class.java:1880)
    at java.io.ObjectStreamClass.getDeclaredSUID(ObjectStreamClass.java:1610)
    at java.io.ObjectStreamClass.access$700(ObjectStreamClass.java:52)
    at java.io.ObjectStreamClass$2.run(ObjectStreamClass.java:425)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.io.ObjectStreamClass.<init>(ObjectStreamClass.java:413)
    at java.io.ObjectStreamClass.lookup(ObjectStreamClass.java:310)
    at java.io.ObjectStreamClass.initNonProxy(ObjectStreamClass.java:547)
    at java.io.ObjectInputStream.readNonProxyDesc(ObjectInputStream.java:1582)
    at java.io.ObjectInputStream.readClassDesc(ObjectInputStream.java:1495)
    at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1731)
    at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1328)
    at java.io.ObjectInputStream.readObject(ObjectInputStream.java:350)
    at hudson.remoting.UserRequest.deserialize(UserRequest.java:185)
    at hudson.remoting.UserRequest.perform(UserRequest.java:99)
    at hudson.remoting.UserRequest.perform(UserRequest.java:49)
    at hudson.remoting.Request$2.run(Request.java:324)
    at hudson.remoting.InterceptingExecutorService$1.call(InterceptingExecutorService.java:68)
    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)
    at java.util.concurrent.FutureTask.run(FutureTask.java:138)
    at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
    at java.lang.Thread.run(Thread.java:662)
channel stopped
Finished: FAILURE
</code>```

答: By the error you must use at least JDK 7 in your runtime environment.</p>

Body:
Thanks for reading this question. I am very new to Maven and Jenkins and trying to implement it for learning purpose. I am getting the below output in jenkins console. I am well aware that there is a silly mistake but I couldnt find it. Please advice.

Parsing POMs
[naukri] $ "C:\Program Files (x86)\Java\jdk1.6.0_24/bin/java" -cp C:\Users\Badri\.jenkins\plugins\maven-plugin\WEB-INF\lib\maven31-agent-1.5.jar;C:\Users\Badri\.jenkins\tools\hudson.tasks.Maven_MavenInstallation\MAVEN\boot\plexus-classworlds-2.5.2.jar;C:\Users\Badri\.jenkins\tools\hudson.tasks.Maven_MavenInstallation\MAVEN/conf/logging jenkins.maven3.agent.Maven31Main C:\Users\Badri\.jenkins\tools\hudson.tasks.Maven_MavenInstallation\MAVEN C:\Users\Badri\.jenkins\war\WEB-INF\lib\remoting-2.49.jar C:\Users\Badri\.jenkins\plugins\maven-plugin\WEB-INF\lib\maven31-interceptor-1.5.jar C:\Users\Badri\.jenkins\plugins\maven-plugin\WEB-INF\lib\maven3-interceptor-commons-1.5.jar 52941
<===[JENKINS REMOTING CAPACITY]===>channel started
ERROR: Failed to parse POMs
java.io.IOException: Remote call on Channel to Maven [C:\Program Files (x86)\Java\jdk1.6.0_24/bin/java, -cp, C:\Users\Badri\.jenkins\plugins\maven-plugin\WEB-INF\lib\maven31-agent-1.5.jar;C:\Users\Badri\.jenkins\tools\hudson.tasks.Maven_MavenInstallation\MAVEN\boot\plexus-classworlds-2.5.2.jar;C:\Users\Badri\.jenkins\tools\hudson.tasks.Maven_MavenInstallation\MAVEN/conf/logging, jenkins.maven3.agent.Maven31Main, C:\Users\Badri\.jenkins\tools\hudson.tasks.Maven_MavenInstallation\MAVEN, C:\Users\Badri\.jenkins\war\WEB-INF\lib\remoting-2.49.jar, C:\Users\Badri\.jenkins\plugins\maven-plugin\WEB-INF\lib\maven31-interceptor-1.5.jar, C:\Users\Badri\.jenkins\plugins\maven-plugin\WEB-INF\lib\maven3-interceptor-commons-1.5.jar, 52941] failed
    at hudson.remoting.Channel.call(Channel.java:760)
    at hudson.maven.ProcessCache$MavenProcess.call(ProcessCache.java:161)
    at hudson.maven.MavenModuleSetBuild$MavenModuleSetBuildExecution.doRun(MavenModuleSetBuild.java:840)
    at hudson.model.AbstractBuild$AbstractBuildExecution.run(AbstractBuild.java:536)
    at hudson.model.Run.execute(Run.java:1718)
    at hudson.maven.MavenModuleSetBuild.run(MavenModuleSetBuild.java:529)
    at hudson.model.ResourceController.execute(ResourceController.java:89)
    at hudson.model.Executor.run(Executor.java:240)
Caused by: java.lang.ClassFormatError: Failed to load hudson.maven.Maven3Builder$JenkinsEventSpy
    at hudson.remoting.RemoteClassLoader.loadClassFile(RemoteClassLoader.java:325)
    at hudson.remoting.RemoteClassLoader.findClass(RemoteClassLoader.java:237)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:248)
    at java.lang.Class.getDeclaredFields0(Native Method)
    at java.lang.Class.privateGetDeclaredFields(Class.java:2291)
    at java.lang.Class.getDeclaredField(Class.java:1880)
    at java.io.ObjectStreamClass.getDeclaredSUID(ObjectStreamClass.java:1610)
    at java.io.ObjectStreamClass.access$700(ObjectStreamClass.java:52)
    at java.io.ObjectStreamClass$2.run(ObjectStreamClass.java:425)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.io.ObjectStreamClass.<init>(ObjectStreamClass.java:413)
    at java.io.ObjectStreamClass.lookup(ObjectStreamClass.java:310)
    at java.io.ObjectStreamClass.initNonProxy(ObjectStreamClass.java:547)
    at java.io.ObjectInputStream.readNonProxyDesc(ObjectInputStream.java:1582)
    at java.io.ObjectInputStream.readClassDesc(ObjectInputStream.java:1495)
    at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1731)
    at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1328)
    at java.io.ObjectInputStream.readObject(ObjectInputStream.java:350)
    at hudson.remoting.UserRequest.deserialize(UserRequest.java:185)
    at hudson.remoting.UserRequest.perform(UserRequest.java:99)
    at hudson.remoting.UserRequest.perform(UserRequest.java:49)
    at hudson.remoting.Request$2.run(Request.java:324)
    at hudson.remoting.InterceptingExecutorService$1.call(InterceptingExecutorService.java:68)
    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)
    at java.util.concurrent.FutureTask.run(FutureTask.java:138)
    at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
    at java.lang.Thread.run(Thread.java:662)
    at ......remote call to Channel to Maven [C:\Program Files (x86)\Java\jdk1.6.0_24/bin/java, -cp, C:\Users\Badri\.jenkins\plugins\maven-plugin\WEB-INF\lib\maven31-agent-1.5.jar;C:\Users\Badri\.jenkins\tools\hudson.tasks.Maven_MavenInstallation\MAVEN\boot\plexus-classworlds-2.5.2.jar;C:\Users\Badri\.jenkins\tools\hudson.tasks.Maven_MavenInstallation\MAVEN/conf/logging, jenkins.maven3.agent.Maven31Main, C:\Users\Badri\.jenkins\tools\hudson.tasks.Maven_MavenInstallation\MAVEN, C:\Users\Badri\.jenkins\war\WEB-INF\lib\remoting-2.49.jar, C:\Users\Badri\.jenkins\plugins\maven-plugin\WEB-INF\lib\maven31-interceptor-1.5.jar, C:\Users\Badri\.jenkins\plugins\maven-plugin\WEB-INF\lib\maven3-interceptor-commons-1.5.jar, 52941](Native Method)
    at hudson.remoting.Channel.attachCallSiteStackTrace(Channel.java:1356)
    at hudson.remoting.UserResponse.retrieve(UserRequest.java:221)
    at hudson.remoting.Channel.call(Channel.java:752)
    ... 7 more
Caused by: java.lang.UnsupportedClassVersionError: org/apache/maven/eventspy/EventSpy : Unsupported major.minor version 51.0
    at java.lang.ClassLoader.defineClass1(Native Method)
    at java.lang.ClassLoader.defineClassCond(ClassLoader.java:632)
    at java.lang.ClassLoader.defineClass(ClassLoader.java:616)
    at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:141)
    at java.net.URLClassLoader.defineClass(URLClassLoader.java:283)
    at java.net.URLClassLoader.access$000(URLClassLoader.java:58)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:197)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
    at org.codehaus.plexus.classworlds.realm.ClassRealm.loadClassFromSelf(ClassRealm.java:401)
    at org.codehaus.plexus.classworlds.strategy.SelfFirstStrategy.loadClass(SelfFirstStrategy.java:42)
    at org.codehaus.plexus.classworlds.realm.ClassRealm.unsynchronizedLoadClass(ClassRealm.java:271)
    at org.codehaus.plexus.classworlds.realm.ClassRealm.loadClass(ClassRealm.java:254)
    at org.codehaus.plexus.classworlds.realm.ClassRealm.loadClass(ClassRealm.java:239)
    at org.codehaus.plexus.classworlds.realm.ClassRealm.loadClassFromParent(ClassRealm.java:445)
    at org.codehaus.plexus.classworlds.strategy.SelfFirstStrategy.loadClass(SelfFirstStrategy.java:46)
    at org.codehaus.plexus.classworlds.realm.ClassRealm.unsynchronizedLoadClass(ClassRealm.java:271)
    at org.codehaus.plexus.classworlds.realm.ClassRealm.loadClass(ClassRealm.java:254)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:296)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:248)
    at java.lang.ClassLoader.defineClass1(Native Method)
    at java.lang.ClassLoader.defineClassCond(ClassLoader.java:632)
    at java.lang.ClassLoader.defineClass(ClassLoader.java:616)
    at java.lang.ClassLoader.defineClass(ClassLoader.java:466)
    at hudson.remoting.RemoteClassLoader.loadClassFile(RemoteClassLoader.java:323)
    at hudson.remoting.RemoteClassLoader.findClass(RemoteClassLoader.java:237)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:248)
    at java.lang.Class.getDeclaredFields0(Native Method)
    at java.lang.Class.privateGetDeclaredFields(Class.java:2291)
    at java.lang.Class.getDeclaredField(Class.java:1880)
    at java.io.ObjectStreamClass.getDeclaredSUID(ObjectStreamClass.java:1610)
    at java.io.ObjectStreamClass.access$700(ObjectStreamClass.java:52)
    at java.io.ObjectStreamClass$2.run(ObjectStreamClass.java:425)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.io.ObjectStreamClass.<init>(ObjectStreamClass.java:413)
    at java.io.ObjectStreamClass.lookup(ObjectStreamClass.java:310)
    at java.io.ObjectStreamClass.initNonProxy(ObjectStreamClass.java:547)
    at java.io.ObjectInputStream.readNonProxyDesc(ObjectInputStream.java:1582)
    at java.io.ObjectInputStream.readClassDesc(ObjectInputStream.java:1495)
    at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1731)
    at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1328)
    at java.io.ObjectInputStream.readObject(ObjectInputStream.java:350)
    at hudson.remoting.UserRequest.deserialize(UserRequest.java:185)
    at hudson.remoting.UserRequest.perform(UserRequest.java:99)
    at hudson.remoting.UserRequest.perform(UserRequest.java:49)
    at hudson.remoting.Request$2.run(Request.java:324)
    at hudson.remoting.InterceptingExecutorService$1.call(InterceptingExecutorService.java:68)
    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)
    at java.util.concurrent.FutureTask.run(FutureTask.java:138)
    at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
    at java.lang.Thread.run(Thread.java:662)
channel stopped
Finished: FAILURE


问:
How can I make a combination array which contains maximum length?
I have these three arrays:

```<code>$arr1 = ['one', 'two', 'three'];
$arr2 = ['three', 'four'];
$arr3 = ['two', 'five', 'six', 'seven'];
</code>```

And this is expected result:

```<code>/* Array
   (
       [0] => one
       [1] => two
       [3] => three
       [4] => four
       [5] => five
       [6] => six
       [7] => seven
   )
</code>```

Here is my solution which doesn't work as expected:

```<code>print_r( array_unique( $arr1 + $arr2 + $arr3) );
/* Array
   (
       [0] => one
       [1] => two
       [2] => three
       [3] => seven
   )
</code>```

How can I do that?

答:
Use this:

```<code>array_unique(array_merge($arr1,$arr2,$arr3), SORT_REGULAR);
</code>```

this will merge the arrays into one, then removes all duplicates

Tested Here

It outputs:

```<code>Array
(
    [0] => one
    [1] => two
    [2] => three
    [4] => four
    [6] => five
    [7] => six
    [8] => seven
)
</code>```

Body:
I have these three arrays:

$arr1 = ['one', 'two', 'three'];
$arr2 = ['three', 'four'];
$arr3 = ['two', 'five', 'six', 'seven'];

And this is expected result:

/* Array
   (
       [0] => one
       [1] => two
       [3] => three
       [4] => four
       [5] => five
       [6] => six
       [7] => seven
   )

Here is my solution which doesn't work as expected:

print_r( array_unique( $arr1 + $arr2 + $arr3) );
/* Array
   (
       [0] => one
       [1] => two
       [2] => three
       [3] => seven
   )

How can I do that?

Body:
Use this:

array_unique(array_merge($arr1,$arr2,$arr3), SORT_REGULAR);

this will merge the arrays into one, then removes all duplicates

Tested Here

It outputs:

Array
(
    [0] => one
    [1] => two
    [2] => three
    [4] => four
    [6] => five
    [7] => six
    [8] => seven
)


问:
Database design - defining a basic many-to-one relationship
This is a basic database design question. I want a table (or multiple tables) defining relationships between customers. I want it so PrimaryCustomer can be linked to multiple SecondaryCustomers, and can have many SecondaryCustomers with the same relationship.

```<code>PrimaryCustomerID  RelationshipID  SecondaryCustomerID
</code>```

1) If the primary key is {PrimaryCustomerID} then I can only have one linked customer of any kind.

2) If the primary key is {PrimaryCustomerID, RelationshipID}, then I can only have one linked customer for each relationship type.

3) If the primary key is {PrimaryCustomerID, RelationshipID, SecondaryCustomerID}, then I can have whatever I like, but having all columns as the primary key seems completely wrong.

What's the right way to set things up?

答: Number 3 is the right way to go for this data model. Linking tables often have all the columns in a join as all they do is link to other tables. </p>

ContentLicense: CC BY-SA 2.5

Body:
This is a basic database design question. I want a table (or multiple tables) defining relationships between customers. I want it so PrimaryCustomer can be linked to multiple SecondaryCustomers, and can have many SecondaryCustomers with the same relationship.

PrimaryCustomerID  RelationshipID  SecondaryCustomerID

1) If the primary key is {PrimaryCustomerID} then I can only have one linked customer of any kind.

2) If the primary key is {PrimaryCustomerID, RelationshipID}, then I can only have one linked customer for each relationship type.

3) If the primary key is {PrimaryCustomerID, RelationshipID, SecondaryCustomerID}, then I can have whatever I like, but having all columns as the primary key seems completely wrong.

What's the right way to set things up?


问:
STM32 LwiP Multiple TCP Server
I tried to do a 3 or 4 tcp server on my STM32F107. I'm using freeRTOS and LwIP (and the CubeMX + ST HAL library).

I create a task tcp_server, and inside the task, I create 3 netconn structure each with different tcp port.
Callback:

```<code>void socket_callback(struct netconn * conn, enum netconn_evt evt, u16_t len)
{
    queue_event_t msg;
    if (evt == NETCONN_EVT_RCVPLUS)
    {
            msg.cmd = MSG_TEST;
            if (conn == user_conn.conn_modbus)
                msg.cmd = MSG_MODBUS;
            else if (conn == user_conn.conn_modbus_listen)
                msg.cmd = MSG_MODBUS_LISTEN;
            else if (conn == user_conn.conn_rs232)
                msg.cmd = MSG_RS232;
            else if (conn == user_conn.conn_rs232_listen)
                msg.cmd = MSG_RS232_LISTEN;
            else if (conn == user_conn.conn_rs485)
                msg.cmd = MSG_RS485;
            else if (conn == user_conn.conn_rs485_listen)
                msg.cmd = MSG_RS485_LISTEN;
            xQueueSend(user_conn.evtQueue, &msg, 1000);
    }
}
</code>```

Server creation :

```<code>static struct netconn * createServer(int port)
{
    struct netconn * conn;
    err_t err;

    conn = netconn_new_with_callback(NETCONN_TCP, socket_callback);
    if (conn == NULL)
    {
          char *msg = "Cannot create netconn\n\r";
          HAL_UART_Transmit(&huart3, (uint8_t*)msg, strlen(msg), 0xFFFF);
          return NULL;
    }

    err = netconn_bind(conn, NULL, port);
    if (err != ERR_OK)
    {
        char *msg = "Error in Binding \n\r";
        HAL_UART_Transmit(&huart3, (uint8_t*)msg, strlen(msg), 0xFFFF);
        print_error(err);
        netconn_delete(conn);
        return NULL;
    }
    err = netconn_listen(conn);
    if (err != ERR_OK)
    {
      char *msg = "Error in listenning \n\r";
      HAL_UART_Transmit(&huart3, (uint8_t*)msg, strlen(msg), 0xFFFF);
        print_error(err);
        netconn_delete(conn);
        return NULL;
    }
    return conn;
}
</code>```

Thread :

```<code>static void servertcp_thread()
{
    queue_event_t evt;
    user_conn.evtQueue = xQueueCreate(10, sizeof (queue_event_t));
    user_conn.conn_modbus_listen = createServer(502);
    user_conn.conn_rs232_listen = createServer(10001);
    user_conn.conn_rs485_listen = createServer(50001);

    while(1)
   {
        waitServer(&user_conn, &evt);
        send_rs232(&user_conn);
        send_rs485(&user_conn);
        if((user_conn.conn_modbus_listen != NULL) && (evt.cmd == MSG_MODBUS_LISTEN))
            processModbusListen(&user_conn);
        if((user_conn.conn_rs232_listen != NULL) && (evt.cmd == MSG_RS232_LISTEN))
            processRS232Listen(&user_conn);
        if((user_conn.conn_rs485_listen != NULL) && (evt.cmd == MSG_RS485_LISTEN))
            processRS485Listen(&user_conn);
        if((user_conn.conn_modbus != NULL) && (evt.cmd == MSG_MODBUS))
            modbus_tcp_server(&user_conn);
        if((user_conn.conn_rs232 != NULL) && (evt.cmd == MSG_RS232))
            rs232_tcp_server(&user_conn);
        if((user_conn.conn_rs485 != NULL) && (evt.cmd == MSG_RS485))
            rs485_tcp_server(&user_conn);
   }
}
</code>```

The creation is successful (netconn_new_with_callback / netconn_bind and netconn_listen with no error).

When I tried to connect to 1 tcp port, it is accepted and everything is ok.

But when I tried to connect to a second port while the first connexion is still alive, the callback is called, but the netconn_accept(conn, &newconn); failed and report ERR_ABRT and I don't know why.

The 3 function (processModbusListen, processRS232Listen and processRS485Listen) are coded following the same prototype:

```<code>static int processXXXListen(user_conn_t * user_data)
{
    struct netconn *newconn;
    err_t error_accept;
    error_accept = netconn_accept(user_data->conn_XXX_listen, &newconn);
    if (error_accept == ERR_OK)
    {
        if (user_data->conn_rs485)
        {
            // Close unwanted connection
            netconn_close(newconn);
            netconn_delete(newconn);
            char *msg = "Error XXX Connection during establishement\n\r";
            HAL_UART_Transmit(&huart3, (uint8_t*)msg, strlen(msg), 0xFFFF);
        }
        else
        {
            // connection established
            char *msg = "XXX Connection established\n\r";
            HAL_UART_Transmit(&huart3, (uint8_t*)msg, strlen(msg), 0xFFFF);
            user_data->conn_XXX = newconn;
        }
    }
    else
    {
        char *msg = "Error in acceptation TCP XXX connection\n\r";
        HAL_UART_Transmit(&huart3, (uint8_t*)msg, strlen(msg), 0xFFFF);
        print_error(error_accept);
    }
    return 0;
}
</code>```

The strange thing is, that when i only create 2 netconn structure, i have no problem with the 2 connection in the same time.

What can cause the connexion aborted ?
How can i get the 3 connection in the same time ?
If it is possible of course ...

答:
Ok, yes after 1day of testing,
the param

```<code>#define MEMP_NUM_NETCONN 4
</code>```

is definetly what makes me troubl.
i just have to set it to 10, and everything works like a charm

Title: STM32 LwiP Multiple TCP Server

Body:
I tried to do a 3 or 4 tcp server on my STM32F107. I'm using freeRTOS and LwIP (and the CubeMX + ST HAL library).

I create a task tcp_server, and inside the task, I create 3 netconn structure each with different tcp port.
Callback:

void socket_callback(struct netconn * conn, enum netconn_evt evt, u16_t len)
{
    queue_event_t msg;
    if (evt == NETCONN_EVT_RCVPLUS)
    {
            msg.cmd = MSG_TEST;
            if (conn == user_conn.conn_modbus)
                msg.cmd = MSG_MODBUS;
            else if (conn == user_conn.conn_modbus_listen)
                msg.cmd = MSG_MODBUS_LISTEN;
            else if (conn == user_conn.conn_rs232)
                msg.cmd = MSG_RS232;
            else if (conn == user_conn.conn_rs232_listen)
                msg.cmd = MSG_RS232_LISTEN;
            else if (conn == user_conn.conn_rs485)
                msg.cmd = MSG_RS485;
            else if (conn == user_conn.conn_rs485_listen)
                msg.cmd = MSG_RS485_LISTEN;
            xQueueSend(user_conn.evtQueue, &msg, 1000);
    }
}

Server creation :

static struct netconn * createServer(int port)
{
    struct netconn * conn;
    err_t err;

    conn = netconn_new_with_callback(NETCONN_TCP, socket_callback);
    if (conn == NULL)
    {
          char *msg = "Cannot create netconn\n\r";
          HAL_UART_Transmit(&huart3, (uint8_t*)msg, strlen(msg), 0xFFFF);
          return NULL;
    }

    err = netconn_bind(conn, NULL, port);
    if (err != ERR_OK)
    {
        char *msg = "Error in Binding \n\r";
        HAL_UART_Transmit(&huart3, (uint8_t*)msg, strlen(msg), 0xFFFF);
        print_error(err);
        netconn_delete(conn);
        return NULL;
    }
    err = netconn_listen(conn);
    if (err != ERR_OK)
    {
      char *msg = "Error in listenning \n\r";
      HAL_UART_Transmit(&huart3, (uint8_t*)msg, strlen(msg), 0xFFFF);
        print_error(err);
        netconn_delete(conn);
        return NULL;
    }
    return conn;
}

Thread :

static void servertcp_thread()
{
    queue_event_t evt;
    user_conn.evtQueue = xQueueCreate(10, sizeof (queue_event_t));
    user_conn.conn_modbus_listen = createServer(502);
    user_conn.conn_rs232_listen = createServer(10001);
    user_conn.conn_rs485_listen = createServer(50001);

    while(1)
   {
        waitServer(&user_conn, &evt);
        send_rs232(&user_conn);
        send_rs485(&user_conn);
        if((user_conn.conn_modbus_listen != NULL) && (evt.cmd == MSG_MODBUS_LISTEN))
            processModbusListen(&user_conn);
        if((user_conn.conn_rs232_listen != NULL) && (evt.cmd == MSG_RS232_LISTEN))
            processRS232Listen(&user_conn);
        if((user_conn.conn_rs485_listen != NULL) && (evt.cmd == MSG_RS485_LISTEN))
            processRS485Listen(&user_conn);
        if((user_conn.conn_modbus != NULL) && (evt.cmd == MSG_MODBUS))
            modbus_tcp_server(&user_conn);
        if((user_conn.conn_rs232 != NULL) && (evt.cmd == MSG_RS232))
            rs232_tcp_server(&user_conn);
        if((user_conn.conn_rs485 != NULL) && (evt.cmd == MSG_RS485))
            rs485_tcp_server(&user_conn);
   }
}

The creation is successful (netconn_new_with_callback / netconn_bind and netconn_listen with no error).

When I tried to connect to 1 tcp port, it is accepted and everything is ok.

But when I tried to connect to a second port while the first connexion is still alive, the callback is called, but the netconn_accept(conn, &newconn); failed and report ERR_ABRT and I don't know why.

The 3 function (processModbusListen, processRS232Listen and processRS485Listen) are coded following the same prototype:

static int processXXXListen(user_conn_t * user_data)
{
    struct netconn *newconn;
    err_t error_accept;
    error_accept = netconn_accept(user_data->conn_XXX_listen, &newconn);
    if (error_accept == ERR_OK)
    {
        if (user_data->conn_rs485)
        {
            // Close unwanted connection
            netconn_close(newconn);
            netconn_delete(newconn);
            char *msg = "Error XXX Connection during establishement\n\r";
            HAL_UART_Transmit(&huart3, (uint8_t*)msg, strlen(msg), 0xFFFF);
        }
        else
        {
            // connection established
            char *msg = "XXX Connection established\n\r";
            HAL_UART_Transmit(&huart3, (uint8_t*)msg, strlen(msg), 0xFFFF);
            user_data->conn_XXX = newconn;
        }
    }
    else
    {
        char *msg = "Error in acceptation TCP XXX connection\n\r";
        HAL_UART_Transmit(&huart3, (uint8_t*)msg, strlen(msg), 0xFFFF);
        print_error(error_accept);
    }
    return 0;
}

The strange thing is, that when i only create 2 netconn structure, i have no problem with the 2 connection in the same time.

What can cause the connexion aborted ?
How can i get the 3 connection in the same time ?
If it is possible of course ...

Body:
Ok, yes after 1day of testing,
the param

#define MEMP_NUM_NETCONN 4

is definetly what makes me troubl.
i just have to set it to 10, and everything works like a charm


问:
Delphi - writing a large dynamic array to disk using stream
In a Delphi program, I have a dynamic array with 4,000,000,001 cardinals.  I'm trying to write (and later read) it do a drive.  I used the following:

```<code>const Billion = 1000000000;

stream := tFileStream.Create( 'f:\data\BigList.data', fmCreate);
stream.WriteBuffer( Pointer( BigArray)^, (4 * billion + 1) * SizeOf( cardinal));
stream.free;
</code>```

It bombed out with: ...raised exception class EWriteError with message 'Stream write error'.

The size of the file it wrote is only 3,042,089KB.

Am I doing something wrong?  Is there a limit to the size that can be written at once (about 3GB)?

答:
The Count parameter of WriteBuffer is a 32 bit integer so you cannot pass the required value in that parameter. You will need to write the file with multiple separate calls to WriteBuffer, where each call passes a count that does not exceed this limit.

I suggest that you write it something like this.

```<code>var
  Count, Index, N: Int64;
....
Count := Length(BigArray);
Index := 0;
while Count > 0 do begin
  N := Min(Count, 8192);
  stream.WriteBuffer(BigArray[Index], N*SizeOf(BigArray[0]));
  inc(Index, N);
  dec(Count, N);
end;
</code>```

An additional benefit is that you can readily display progress.

Body:
In a Delphi program, I have a dynamic array with 4,000,000,001 cardinals.  I'm trying to write (and later read) it do a drive.  I used the following:

const Billion = 1000000000;

stream := tFileStream.Create( 'f:\data\BigList.data', fmCreate);
stream.WriteBuffer( Pointer( BigArray)^, (4 * billion + 1) * SizeOf( cardinal));
stream.free;

It bombed out with: ...raised exception class EWriteError with message 'Stream write error'.

The size of the file it wrote is only 3,042,089KB.

Am I doing something wrong?  Is there a limit to the size that can be written at once (about 3GB)?

Body:
The Count parameter of WriteBuffer is a 32 bit integer so you cannot pass the required value in that parameter. You will need to write the file with multiple separate calls to WriteBuffer, where each call passes a count that does not exceed this limit.

I suggest that you write it something like this.

var
  Count, Index, N: Int64;
....
Count := Length(BigArray);
Index := 0;
while Count > 0 do begin
  N := Min(Count, 8192);
  stream.WriteBuffer(BigArray[Index], N*SizeOf(BigArray[0]));
  inc(Index, N);
  dec(Count, N);
end;

An additional benefit is that you can readily display progress.


答:
change the ng-model to object property like ng-model="ans.checkAnswer"

```<code><input type="checkbox" ng-change="answerSelected(ans)" ng-model="ans.checkAnswer">{{ans.answer}}
</code>```

Then change the function like this

```<code>$scope.answerSelected = function(checkAnswer) {
    if (checkAnswer.checkAnswer) {
        checkAnswer.count++;
    }
    $scope.answerBoxSelected = true;
};
</code>```

Demo

Title: AngularJS checkbox avoid counting when uncheck checkBox

Body:
change the ng-model to object property like ng-model="ans.checkAnswer"

<input type="checkbox" ng-change="answerSelected(ans)" ng-model="ans.checkAnswer">{{ans.answer}}

Then change the function like this

$scope.answerSelected = function(checkAnswer) {
    if (checkAnswer.checkAnswer) {
        checkAnswer.count++;
    }
    $scope.answerBoxSelected = true;
};

Demo


问:
tensorflow:Casting <dtype: 'int64'> labels to bool
I'm running the wide and deep tutorial code and without changes I get the error:

```<code>WARNING:tensorflow:Casting <dtype: 'int64'> labels to bool.
</code>```

My question is: what does this mean and how does this afect other models where I want to predict more than 2 possible results?

This error appears in a situation/tutorial where the prediction is preety much a boolean, yes/no situation. But if I have labels with three possible values I think this boolean conversion will kill my results right?

What is the origin of this warning and how to avoid it so I can train a network with more than 2 possible results?

答:
I encountered exactly the same error when using DNNClassifier. To resolve it, I need to specify n_classes parameter to the number of classes in your target.

The n_classes parameter is to specify how many classes in your target.By default, it presume there are only two classes in your target, so it convert target value to bool.

```<code>m = tf.contrib.learn.DNNClassifier(
        model_dir=model_dir,
        n_classes=10, # <---------
        feature_columns=deep_columns,
        hidden_units=[400,50],
        optimizer=tf.train.ProximalAdagradOptimizer(
            learning_rate=0.001,
            l1_regularization_strength=0.001
        ))
</code>```

Body:
I'm running the wide and deep tutorial code and without changes I get the error:

WARNING:tensorflow:Casting <dtype: 'int64'> labels to bool.

My question is: what does this mean and how does this afect other models where I want to predict more than 2 possible results?

This error appears in a situation/tutorial where the prediction is preety much a boolean, yes/no situation. But if I have labels with three possible values I think this boolean conversion will kill my results right?

What is the origin of this warning and how to avoid it so I can train a network with more than 2 possible results?

Body:
I encountered exactly the same error when using DNNClassifier. To resolve it, I need to specify n_classes parameter to the number of classes in your target.

The n_classes parameter is to specify how many classes in your target.By default, it presume there are only two classes in your target, so it convert target value to bool.

m = tf.contrib.learn.DNNClassifier(
        model_dir=model_dir,
        n_classes=10, # <---------
        feature_columns=deep_columns,
        hidden_units=[400,50],
        optimizer=tf.train.ProximalAdagradOptimizer(
            learning_rate=0.001,
            l1_regularization_strength=0.001
        ))


问:
jQuery: child firing an event for its parent element
I have several nested div elements like this:

```<code><div class="main">
    blah blah blah <div class="clickme">clickme</div>
</div>

<div class="main">
    bleh bleh bleh <div class="clickme">clickme</div>
</div>

<div class="main">
    blih blih blih <div class="clickme">clickme</div>
</div>
</code>```

I want to fire a toggle event that will show/hide the div marked with the class "main" by clicking on the corresponding clickme text inside its child div tag with "clickme" class. Sorry, I can't figure out how to do this. Thanks.

答:
```<code>$(".clickme").click(function() {
    $(this).parent("div.main").toggle();
});
</code>```

In regards to your second problem, you need to add:

```<code>$(this).unbind('click');
</code>```

At the end of either of your toggle functions, and it will work as you intend. Good luck.

EDIT: in response to your latest problem, this should do it:

```<code>$(".abrefecha").click( function() {
    var that = this; // save this in that :)
    jQuery(this).parent().toggle(
        function () {
            var itemId = jQuery(this).attr("id");
            var itemIndex = $(".showhide").index(this);
            var currentItemHeight = b[itemIndex] + 30 + 'px'
            jQuery(this).css("overflow","auto");
            jQuery(this).animate( { height: currentItemHeight } , 500 );
            $(that).html('close'); // change html inside pink to 'close'
            $(this).unbind('click');
        },
        function () {
            jQuery(this).css("overflow","hidden")
            jQuery(this).animate( { height:"60px" } , 500 );
            $(that).html('abrefecha'); // change html back to 'abrefecha'
            $(this).unbind('click');
        }
    );
});
</code>```

OwnerDisplayName: Marcos Buarque

ContentLicense: CC BY-SA 4.0

Body:
I have several nested div elements like this:

    blah blah blah
clickme

    bleh bleh bleh
clickme

    blih blih blih
clickme

I want to fire a toggle event that will show/hide the div marked with the class "main" by clicking on the corresponding clickme text inside its child div tag with "clickme" class. Sorry, I can't figure out how to do this. Thanks.

LastEditorDisplayName: Paolo Bergantino

Body:
$(".clickme").click(function() {
    $(this).parent("div.main").toggle();
});

In regards to your second problem, you need to add:

$(this).unbind('click');

At the end of either of your toggle functions, and it will work as you intend. Good luck.

EDIT: in response to your latest problem, this should do it:

$(".abrefecha").click( function() {
    var that = this; // save this in that :)
    jQuery(this).parent().toggle(
        function () {
            var itemId = jQuery(this).attr("id");
            var itemIndex = $(".showhide").index(this);
            var currentItemHeight = b[itemIndex] + 30 + 'px'
            jQuery(this).css("overflow","auto");
            jQuery(this).animate( { height: currentItemHeight } , 500 );
            $(that).html('close'); // change html inside pink to 'close'
            $(this).unbind('click');
        },
        function () {
            jQuery(this).css("overflow","hidden")
            jQuery(this).animate( { height:"60px" } , 500 );
            $(that).html('abrefecha'); // change html back to 'abrefecha'
            $(this).unbind('click');
        }
    );
});

OwnerDisplayName: Paolo Bergantino


问:
How to have two password fields controlled by one checkbox?
```<code><form>
<fieldset>
Password: <span id="capsalert">CAPS LOCK = on</span><br>
<input type="password" id="pwd">
<script type="text/javascript">
  document.write(
    '<input type="checkbox" name="masking" onclick="unmask(this.checked)"> ' +
    'Show the password as I type'
  );
</script>
<br>
Password2:<br>
<input type="password" id="pwd2">
</fieldset>
</form>
<script type="text/javascript">
function chkCaps(e) {
ev = (e ? e : window.event);
kc = (ev.which ? ev.which : (ev.keyCode ? ev.keyCode : false));
sk = (ev.shiftKey ? ev.shiftKey : (ev.modifiers ? !!(ev.modifiers & 4) : false));
if(
  (kc >= 97 && kc <= 122 && sk) ||
  (kc >= 65 && kc <= 90 && !sk)
) {
  document.getElementById('capsalert').style.display = 'inline';
}
else {
  document.getElementById('capsalert').style.display = 'none';
}//end if
}//end function
function unmask(truefalse) {
oldElem = document.getElementById('pwd');
elem = document.createElement('input');
elem.setAttribute('type', (truefalse == true ? 'text' : 'password'));
elem.setAttribute('value', document.getElementById('pwd').value);
elem.id = 'pwd';
oldElem.parentNode.replaceChild(elem,oldElem);

document.getElementById('pwd').onkeypress = function(e) { chkCaps(e); };
}//end function
document.getElementById('pwd').onkeypress = function(e) { chkCaps(e); };
</script>
</code>```

I'm using the above code in a slightly more complex form.

I have two separate "password" fields on the form.  With the current code I can have the first password field show the characters as they are typed when the checkbox is ticked.

Also, the code notifies the user if they are typing with CAPS Lock enabled.

I would like to have both password fields exhibiting the same behavior rather than the first field only.  Unfortunately, I do not know how to make that happen.

Thanks for the help.

EDIT:

A simple solution might be easier to find with the following code.  I'm willing to use either one.

```<code><script>
function changeType()
{
    document.myform.pass.type=(document.myform.option.value=(document.myform.option.value==1)?'-1':'1')=='1'?'password':'text';
}
</script>

<body>
<form name="myform">
   <input type="password" name="pass" />
   <input type="password" name="pass2" />
   <input type="checkbox" name="option" value='1' onchange="changeType()" />
</form>
</body>
</code>```

答:
jQuery caps lock test/function?
set both fields to class of password and:</p>

```<code>jQuery('.password').caps(function(caps){
    if(jQuery.browser.safari) return; // Safari already indicates caps lock
    // "this" is current element
    if(caps){
        alert('Your caps lock is on!');
    }else{
        // no caps lock on
    }
});
</code>```

Body:
<form>
<fieldset>
Password: CAPS LOCK = on

<input type="password" id="pwd">

Password2:

<input type="password" id="pwd2">
</fieldset>
</form>

I'm using the above code in a slightly more complex form.

I have two separate "password" fields on the form.  With the current code I can have the first password field show the characters as they are typed when the checkbox is ticked.

Also, the code notifies the user if they are typing with CAPS Lock enabled.

I would like to have both password fields exhibiting the same behavior rather than the first field only.  Unfortunately, I do not know how to make that happen.

Thanks for the help.

EDIT:

A simple solution might be easier to find with the following code.  I'm willing to use either one.

<form name="myform">
   <input type="password" name="pass" />
   <input type="password" name="pass2" />
   <input type="checkbox" name="option" value='1' onchange="changeType()" />
</form>

Body:
jQuery caps lock test/function?
set both fields to class of password and:

jQuery('.password').caps(function(caps){
    if(jQuery.browser.safari) return; // Safari already indicates caps lock
    // "this" is current element
    if(caps){
        alert('Your caps lock is on!');
    }else{
        // no caps lock on
    }
});


问:
How to use mysql trigger between 2 database server
I have 2 database server from different computer. Let says that my branch PC have their own database and I need the branch data automatically update to my own PC. I need a trigger in my branch MYSQL that update the data to my PC MYSQL.</p>

答:
In the simplest sense, MySQL does not allow connections to other servers1. It allows replication, but that's not quite the same thing. You also probably don't want to make your home PC a read-only replication of the production DB. That often is very messy.

It would not be a trigger, but polling could work. You would need to have some application-level logic to copy information from one server into another. You might run this daily, hourly, etc. to actively copy the data.

1. marriadb does have a sense of table replication, but not triggers.


问:
IOS/Objective-C/CoreData: Delete object from NSSet
I have an NSSet of books related in a many to one relationship to an author object in core data.

There is a view where the user may edit these, including leaving them blank. The user can also add new ones. This leads to a situation where:

1) we end up the same number of books, only edited
2) we end up with fewer books, meaning some should be deleted from the NSSet
3) we end up with more books, meaning some should be added to the NSSet.

My original approach was to convert the items into an NSMutableArray, make changes in the mutablearray, convert back to an NSSet and relate the NSSet to the object.

However, while this works in core data's object graph, it does not seem to delete the actual underlying objects in the persistent store.

Alternatively, since NSSet lacks an index, I cannot identify a way to delete a specific object in the NSSet.

The following code edits the names of the books assuming the number of books does not change.  However, if the number of books is less after the edit, from what I can tell it does not delete the missing book from the persistent store.  It just changes the related objects in core data's object graph.  This creates problems when I sync the persistent store to a server.

So basically looking for way to identify and delete an item in an NSSet in the absence of an index.  Thanks for any suggestions.

```<code>NSSet *booksForAuthor = _author.books;
    NSMutableArray *theBooks = [[booksForAuthor allObjects] mutableCopy];

    NSSortDescriptor *sortDescriptor= [[NSSortDescriptor alloc] initWithKey:@"bid"
                                                 ascending:YES];
    NSArray *booksArray = [theBooks sortedArrayUsingDescriptors:@[sortDescriptor]];
    _numStartingBooks = [booksArray count];
    _booksOnLoad = booksArray; //Now have an array of books before edit
 NSMutableArray <NSString*> *bookNames=[NSMutableArray arrayWithCapacity:20];
   //now collect new set of books from user into array (code omitted)
    [bookNames removeObject:@""];//remove any blanks
    _numBooks = [bookNames count];//number of books after edit
    int i;
        for (i = 0; i < _numStartingBooks; i++) {
            [theNewBooks addObject:_booksOnLoad[i]];
            theNewBooks[i].name = bookNames[i];
        }
     NSSet *theBookSet = [NSSet setWithArray:theNewBooks];
     _author.books = theBookSet;
</code>```

At this point, we have set the NSSet to the new number of books, but from what I can tell, not deleted the underlying extra managed objects present at the beginning.

答:
I think maybe your whole approach and architecture is overly complicated.

First of all, please download this sample project from Apple.  In case Apple breaks the link, search for it.  It is called CoreDataBooks.  Take a day or two to study it.  You see it is written in Objective-C, like your code.  And, like your project, it has books and authors.  CoreDataBooks is pretty much the perfect example for you!

I am recommending this because it appears that your code interposes these NSMutableSets and NSMutableArrays between your view and your model (Core Data).  You shouldn't need to do that.  As a matter of fact, I just searched that Apple project for the symbols NSSet, NSMutableSet, NSArray and NSMutableArray.  I found only one, an array of sort descriptors!  There are no sets or arrays of authors or books anywhere in Apple's sample project.

Regarding synchronizing data to a server, this is done by creating a secondary managed object context connected to the same persistent store.  In a proper design, it will not be involved with your user interface at all, so don't worry about it for now.  Get your user interface working with the local Core Data store first, as in CoreDataBooks, and by then you will have learned much and will be in a much better position to tackle syncing :)

Body:
I have an NSSet of books related in a many to one relationship to an author object in core data.

There is a view where the user may edit these, including leaving them blank. The user can also add new ones. This leads to a situation where:

1) we end up the same number of books, only edited
2) we end up with fewer books, meaning some should be deleted from the NSSet
3) we end up with more books, meaning some should be added to the NSSet.

My original approach was to convert the items into an NSMutableArray, make changes in the mutablearray, convert back to an NSSet and relate the NSSet to the object.

However, while this works in core data's object graph, it does not seem to delete the actual underlying objects in the persistent store.

Alternatively, since NSSet lacks an index, I cannot identify a way to delete a specific object in the NSSet.

The following code edits the names of the books assuming the number of books does not change.  However, if the number of books is less after the edit, from what I can tell it does not delete the missing book from the persistent store.  It just changes the related objects in core data's object graph.  This creates problems when I sync the persistent store to a server.

So basically looking for way to identify and delete an item in an NSSet in the absence of an index.  Thanks for any suggestions.

NSSet *booksForAuthor = _author.books;
    NSMutableArray *theBooks = [[booksForAuthor allObjects] mutableCopy];

    NSSortDescriptor *sortDescriptor= [[NSSortDescriptor alloc] initWithKey:@"bid"
                                                 ascending:YES];
    NSArray *booksArray = [theBooks sortedArrayUsingDescriptors:@[sortDescriptor]];
    _numStartingBooks = [booksArray count];
    _booksOnLoad = booksArray; //Now have an array of books before edit
 NSMutableArray <NSString*> *bookNames=[NSMutableArray arrayWithCapacity:20];
   //now collect new set of books from user into array (code omitted)
    [bookNames removeObject:@""];//remove any blanks
    _numBooks = [bookNames count];//number of books after edit
    int i;
        for (i = 0; i < _numStartingBooks; i++) {
            [theNewBooks addObject:_booksOnLoad[i]];
            theNewBooks[i].name = bookNames[i];
        }
     NSSet *theBookSet = [NSSet setWithArray:theNewBooks];
     _author.books = theBookSet;

At this point, we have set the NSSet to the new number of books, but from what I can tell, not deleted the underlying extra managed objects present at the beginning.


问:
Issue with CodeIgniter redirect
Here i'm creating a login system. Once the user is verified the controller redirects the page to home.php.

There are 2 pages here login_registration.php and home.php

login_registration.php consists login and registration form from here the user is redirected to home.php. both the files are in path C:\wamp\www\CI-Project_1\application\views\login

The issue is it show 404 Page Not Found when redirected.

```<code> class Login extends CI_Controller {
    public function __construct(){
        parent::__construct();
                $this->load->helper('url');
        //LOAD MODELS HERE
        $this->load->model('Login_model');
    }

    public function index(){
        $this->load->view('login/login_registration.php');
    }

    function login_user(){
        $login_btn = $this->input->post('login_btn');

        if($login_btn == TRUE){
            $arr['login'] = array(
                'username'=>$this->input->post('username'),
                'password'=>$this->input->post('password')
            );

            $query = $this->Login_model->users_login($arr);

            if($query->num_rows() > 0 && $query->num_rows() == 1){
                $this->load->library('session');
                $this->session->set_userdata($arr['login']);
                redirect('login/home.php', 'location');
            }
            else
            {
                $this->index();
            }
        }
        else
        {
            $this->index();
        }
    }
}
</code>```

THANKS IN ADVANCE

答:
According to codeigniter views documentation

The .php file extension does not need to be specified unless you use something other than .php.

So, the correct code is as follow:

```<code>$this->load->view('login/login_registration');
</code>```

Also you are not using the redirect function correctly, as i don't see any home function inside login controller. If you somehow have home function inside login controller then why are you using .php after function name?

Check the codeigniter redirect documentation for more info.

Title: Issue with CodeIgniter redirect

Body:
Here i'm creating a login system. Once the user is verified the controller redirects the page to home.php.

There are 2 pages here login_registration.php and home.php

login_registration.php consists login and registration form from here the user is redirected to home.php. both the files are in path C:\wamp\www\CI-Project_1\application\views\login

The issue is it show 404 Page Not Found when redirected.

 class Login extends CI_Controller {
    public function __construct(){
        parent::__construct();
                $this->load->helper('url');
        //LOAD MODELS HERE
        $this->load->model('Login_model');
    }

    public function index(){
        $this->load->view('login/login_registration.php');
    }

    function login_user(){
        $login_btn = $this->input->post('login_btn');

        if($login_btn == TRUE){
            $arr['login'] = array(
                'username'=>$this->input->post('username'),
                'password'=>$this->input->post('password')
            );

            $query = $this->Login_model->users_login($arr);

            if($query->num_rows() > 0 && $query->num_rows() == 1){
                $this->load->library('session');
                $this->session->set_userdata($arr['login']);
                redirect('login/home.php', 'location');
            }
            else
            {
                $this->index();
            }
        }
        else
        {
            $this->index();
        }
    }
}

THANKS IN ADVANCE

Body:
According to codeigniter views documentation

The .php file extension does not need to be specified unless you use something other than .php.

So, the correct code is as follow:

$this->load->view('login/login_registration');

Also you are not using the redirect function correctly, as i don't see any home function inside login controller. If you somehow have home function inside login controller then why are you using .php after function name?

Check the codeigniter redirect documentation for more info.