问:
How can I define multiple jobs dynamically in Spring Batch?
I have an application that uses Spring Batch to define a preset number of jobs, which are currently all defined in the XML.

We add more jobs over time which requires updating the XML, however these jobs are always based on the same parent and can easily be predetermined using a simple SQL query.

So I've been trying to switch to use some combination of XML configuration and Java-based configuration but am quickly getting confused.

Even though we have many jobs, each job definition falls into essentially one of two categories. All of the jobs inherit from one or the other parent job and are effectively identical, besides having different names. The job name is used in the process to select different data from the database.

I've come up with some code much like the following but have run into problems getting it to work.

Full disclaimer that I'm also not entirely sure I'm going about this in the right way. More on that in a second; first, the code:

```<code>@Configuration
@EnableBatchProcessing
public class DynamicJobConfigurer extends DefaultBatchConfigurer implements InitializingBean {

    @Autowired
    private JobBuilderFactory jobBuilderFactory;
    @Autowired
    private JobRegistry jobRegistry;
    @Autowired
    private DataSource dataSource;
    @Autowired
    private CustomJobDefinitionService customJobDefinitionService;

    private Flow injectedFlow1;
    private Flow injectedFlow2;

    public void setupJobs() throws DuplicateJobException {

        List<JobDefinition> jobDefinitions = customJobDefinitionService.getAllJobDefinitions();

        for (JobDefinition jobDefinition : jobDefinitions) {

            Job job = null;
            if (jobDefinition.getType() == 1) {
                job = jobBuilderFactory.get(jobDefinition.getName())
                        .start(injectedFlow1).build()
                        .build();
            } else if (jobDefinition.getType() == 2) {
                job = jobBuilderFactory.get(jobDefinition.getName())
                        .start(injectedFlow2).build()
                        .build();
            }

            if (job != null) {
                jobRegistry.register(new ReferenceJobFactory(job));
            }
        }
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        setupJobs();
    }

    public void setInjectedFlow1(Flow injectedFlow1) {
        this.injectedFlow1 = injectedFlow1;
    }

    public void setInjectedFlow2(Flow injectedFlow2) {
        this.injectedFlow2 = injectedFlow2;
    }
}
</code>```

I have the flows that get injected defined in the XML, much like this:

```<code><batch:flow id="injectedFlow1">

    <batch:step id="InjectedFlow1.Step1" next="InjectedFlow1.Step2">
        <batch:flow parent="InjectedFlow.Step1" />
    </batch:step>

    <batch:step id="InjectedFlow1.Step2">
        <batch:flow parent="InjectedFlow.Step2" />
    </batch:step>

</batch:flow>
</code>```

So as you can see, I'm effectively kicking off the setupJobs() method (which is intended to dynamically create these job definitions) from the afterPropertiesSet() method of InitializingBean. I'm not sure that's right. It is running, but I'm not sure if there's a different entry point that's better intended for this purpose. Also I'm not sure what the point of the @Configuration annotation is to be honest.

The problem I'm currently running into is as soon as I call register() from JobRegistry, it throws the following IllegalStateException:

To use the default BatchConfigurer the context must contain no more than one DataSource, found 2.

Note: my project actually has two data sources defined. The first is the default dataSource bean which connects to the database that Spring Batch uses. The second data source is an external database, and this second one contains all the information I need to define my list of jobs. But the main one does use the default name "dataSource" so I'm not quite sure how else I can tell it to use that one.

答:
First of all - I don't recommend using a combination of XML as well as Java Configuration. Use only one, preferably Java one as its not much of an effort to convert XML config to Java config. (Unless you have some very good reasons to do it - that you haven't explained)

I haven't used Spring Batch alone as I have always used it with Spring Boot and I have a project where I have defined multiple jobs and it always worked well for similar code that you have shown.

For your issue, there are some answers on SO like this OR this which are basically trying to say that you need to write your own BatchConfigurer and not rely on default one.

Now coming to solution using Spring Boot

With Spring Boot, You should try segregate job definitions and job executions.
You should first try to just define jobs and initialize Spring context without enabling jobs (spring.batch.job.enabled=false)

In your Spring Boot main method, when you start app with something like - SpringApplication.run(Application.class, args); ...you will get ApplicationContext ctx

Now you can get your relevant beans from this context & launch specif jobs by getting names from property or command line etc & using JobLauncher.run(...) method.

You can refer my this answer if willing to order job executions. You can also write job schedulers using Java.

Point being, you separate your job building / bean configurations & job execution concerns.

Challenge

Keeping multiple jobs in a single project can be challenging when you try to have different settings for each job as application.properties file is environment specific and not job specific i.e. spring boot properties will apply to all jobs.

Body:
I have an application that uses Spring Batch to define a preset number of jobs, which are currently all defined in the XML.

We add more jobs over time which requires updating the XML, however these jobs are always based on the same parent and can easily be predetermined using a simple SQL query.

So I've been trying to switch to use some combination of XML configuration and Java-based configuration but am quickly getting confused.

Even though we have many jobs, each job definition falls into essentially one of two categories. All of the jobs inherit from one or the other parent job and are effectively identical, besides having different names. The job name is used in the process to select different data from the database.

I've come up with some code much like the following but have run into problems getting it to work.

Full disclaimer that I'm also not entirely sure I'm going about this in the right way. More on that in a second; first, the code:

@Configuration
@EnableBatchProcessing
public class DynamicJobConfigurer extends DefaultBatchConfigurer implements InitializingBean {

    @Autowired
    private JobBuilderFactory jobBuilderFactory;
    @Autowired
    private JobRegistry jobRegistry;
    @Autowired
    private DataSource dataSource;
    @Autowired
    private CustomJobDefinitionService customJobDefinitionService;

    private Flow injectedFlow1;
    private Flow injectedFlow2;

    public void setupJobs() throws DuplicateJobException {

        List<JobDefinition> jobDefinitions = customJobDefinitionService.getAllJobDefinitions();

        for (JobDefinition jobDefinition : jobDefinitions) {

            Job job = null;
            if (jobDefinition.getType() == 1) {
                job = jobBuilderFactory.get(jobDefinition.getName())
                        .start(injectedFlow1).build()
                        .build();
            } else if (jobDefinition.getType() == 2) {
                job = jobBuilderFactory.get(jobDefinition.getName())
                        .start(injectedFlow2).build()
                        .build();
            }

            if (job != null) {
                jobRegistry.register(new ReferenceJobFactory(job));
            }
        }
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        setupJobs();
    }

    public void setInjectedFlow1(Flow injectedFlow1) {
        this.injectedFlow1 = injectedFlow1;
    }

    public void setInjectedFlow2(Flow injectedFlow2) {
        this.injectedFlow2 = injectedFlow2;
    }
}

I have the flows that get injected defined in the XML, much like this:

<batch:flow id="injectedFlow1">

    <batch:step id="InjectedFlow1.Step1" next="InjectedFlow1.Step2">
        <batch:flow parent="InjectedFlow.Step1" />
    </batch:step>

    <batch:step id="InjectedFlow1.Step2">
        <batch:flow parent="InjectedFlow.Step2" />
    </batch:step>

</batch:flow>

So as you can see, I'm effectively kicking off the setupJobs() method (which is intended to dynamically create these job definitions) from the afterPropertiesSet() method of InitializingBean. I'm not sure that's right. It is running, but I'm not sure if there's a different entry point that's better intended for this purpose. Also I'm not sure what the point of the @Configuration annotation is to be honest.

The problem I'm currently running into is as soon as I call register() from JobRegistry, it throws the following IllegalStateException:

To use the default BatchConfigurer the context must contain no more than one DataSource, found 2.

Note: my project actually has two data sources defined. The first is the default dataSource bean which connects to the database that Spring Batch uses. The second data source is an external database, and this second one contains all the information I need to define my list of jobs. But the main one does use the default name "dataSource" so I'm not quite sure how else I can tell it to use that one.


来源: stackexchange

问:
IntelliJ idea stucked on "loading project" screen
This is a Monday morning nightmare on top of existing bugs I have!!

I have couple of projects which i open simultaneously using intellj. One of the project was not showing all directory structures inside it so i took some advice and deleted the .idea folder. Now all hell broke loose on me.

I am stucked here from the dawn of mankind now

Intellij logs

```<code>2017-12-04 09:46:59,444 [   9036]   INFO -                git4idea.GitVcs - Git version: 2.14.3.0
2017-12-04 09:46:59,533 [   9125]   INFO - pl.projectlevelman.NewMappings - VCS Root: [Git] - [/codebase/plutus]
2017-12-04 09:47:01,309 [  10901]   INFO - tor.impl.FileEditorManagerImpl - Project opening took 6353 ms
2017-12-04 09:47:02,913 [  12505]   INFO - .diagnostic.PerformanceWatcher - Indexable file iteration took 4772ms; general responsiveness: ok; EDT responsiveness: 2/5 sluggish, 1/5 very slow
2017-12-04 09:47:05,252 [  14844]   INFO - ellij.project.impl.ProjectImpl - 18 project components initialized in 52 ms

# ----- ^^ all good till here, below is when i start open new project

2017-12-04 09:47:26,455 [  36047]   INFO - og4jmonitor.Log4JWindowManager - creating new LoggingReceiver on port:=4454
2017-12-04 09:47:26,496 [  36088]   INFO - ellij.project.impl.ProjectImpl - 153 project components initialized in 165 ms
2017-12-04 09:47:26,497 [  36089]   INFO - le.impl.ModuleManagerComponent - 0 module(s) loaded in 0 ms
2017-12-04 09:47:26,645 [  36237]   INFO - CompilerBackwardReferenceIndex - backward reference index version differ due to: class java.io.FileNotFoundException
</code>```

Two errors i see on my screen are :

Intellij version

Any help would draw your chances of not having monday morning blues and nightmare like me! :)

Thank you!

答:
[from comments]
Warning: While it works, if you invalidate the cache, it destroys all histories of all projects

So apparently, solution was simple but difficult to find.Here is how it worked :

close all projects in intellij, don't close IDE, just all projects.

delete the .idea/ folder from the project which was getting stucked.

open the same project in intellij

do File -> invalidate caches and restart

done

ContentLicense: CC BY-SA 3.0

Body:
This is a Monday morning nightmare on top of existing bugs I have!!

I have couple of projects which i open simultaneously using intellj. One of the project was not showing all directory structures inside it so i took some advice and deleted the .idea folder. Now all hell broke loose on me.

I am stucked here from the dawn of mankind now

Intellij logs

2017-12-04 09:46:59,444 [   9036]   INFO -                git4idea.GitVcs - Git version: 2.14.3.0
2017-12-04 09:46:59,533 [   9125]   INFO - pl.projectlevelman.NewMappings - VCS Root: [Git] - [/codebase/plutus]
2017-12-04 09:47:01,309 [  10901]   INFO - tor.impl.FileEditorManagerImpl - Project opening took 6353 ms
2017-12-04 09:47:02,913 [  12505]   INFO - .diagnostic.PerformanceWatcher - Indexable file iteration took 4772ms; general responsiveness: ok; EDT responsiveness: 2/5 sluggish, 1/5 very slow
2017-12-04 09:47:05,252 [  14844]   INFO - ellij.project.impl.ProjectImpl - 18 project components initialized in 52 ms

# ----- ^^ all good till here, below is when i start open new project

2017-12-04 09:47:26,455 [  36047]   INFO - og4jmonitor.Log4JWindowManager - creating new LoggingReceiver on port:=4454
2017-12-04 09:47:26,496 [  36088]   INFO - ellij.project.impl.ProjectImpl - 153 project components initialized in 165 ms
2017-12-04 09:47:26,497 [  36089]   INFO - le.impl.ModuleManagerComponent - 0 module(s) loaded in 0 ms
2017-12-04 09:47:26,645 [  36237]   INFO - CompilerBackwardReferenceIndex - backward reference index version differ due to: class java.io.FileNotFoundException

Two errors i see on my screen are :

Intellij version

Any help would draw your chances of not having monday morning blues and nightmare like me! :)

Thank you!

ContentLicense: CC BY-SA 4.0


问:
Assigning an array element to another array element with conditional statement

I will give you two strings. I want you to transform stringOne into stringTwo one letter at a time.

Example:

stringOne = 'bubble gum';
stringTwo = 'turtle ham';

Result:
bubble gum,
tubble gum,
turble gum,
turtle gum,
turtle hum,
turtle ham

```<code> function mutateMyStrings(stringOne, stringTwo){
  var result = stringOne + "\n";
  var stringOneArr = [...stringOne];
  var stringTwoArr = [...stringTwo];
  for (var i = 0; i < stringOneArr.length; i++) {
    if (stringOneArr[i] !== stringTwoArr[i]) {
      console.log(stringOneArr);
      stringOneArr[i] = stringTwoArr[i]
      result += (stringOneArr.join('') + "\n")
    }
  }
  return result;
}
console.log(mutateMyStrings('dog','cat'));
</code>```

Please Read this, most important.

```<code>if (stringOneArr[i] !== stringTwoArr[i]) {
  stringOneArr[i] = stringTwoArr[i]
  result += (stringOneArr.join('') + "\n")
}
</code>```

I do not understand why we need the if (stringOneArr[i] !== stringTwoArr[i])
statement.  I wrote this code without it and didnt get the corrent answer

```<code>stringOneArr[i] = stringTwoArr[i]
result += (stringOneArr.join('') + "\n")
</code>```

I get this error:

```<code>Expected: 'bubble gum\ntubble gum\nturble gum\nturtle gum\nturtle hum\nturtle ham\n',
instead got: 'bubble gum\ntubble gum\ntubble gum\nturble gum\nturtle gum\nturtle gum\nturtle gum\nturtle gum\nturtle hum\nturtle ham\nturtle ham\n'
</code>```

Can someone tell me why in my for loop I cant just assign stringOneArr[i] = stringTwoArr[i].  to me If i just iterate through the string and assign each string1 element to string2 element than it should come out correctly.

but instead the only way to do it correctly and get corrent output is if I say if string1 element doesnt equal string2 element.  and than I assign it to string1 element to string2 element.  why i dont understand why it wont work with out this conditional.

答: You're not wrong, you can just assign stringOneArr[i] = stringTwoArr[i].  But it looks like the testbed you're running it against expects you to skip matching characters.  So it is necessary to check if stringOneArr[i] !== stringTwoArr[i] and skip matching characters.  It's just what the test wants.

Body:
I will give you two strings. I want you to transform stringOne into stringTwo one letter at a time.

Example:

stringOne = 'bubble gum';
stringTwo = 'turtle ham';

Result:
bubble gum,
tubble gum,
turble gum,
turtle gum,
turtle hum,
turtle ham

 function mutateMyStrings(stringOne, stringTwo){
  var result = stringOne + "\n";
  var stringOneArr = [...stringOne];
  var stringTwoArr = [...stringTwo];
  for (var i = 0; i < stringOneArr.length; i++) {
    if (stringOneArr[i] !== stringTwoArr[i]) {
      console.log(stringOneArr);
      stringOneArr[i] = stringTwoArr[i]
      result += (stringOneArr.join('') + "\n")
    }
  }
  return result;
}
console.log(mutateMyStrings('dog','cat'));

Please Read this, most important.

if (stringOneArr[i] !== stringTwoArr[i]) {
  stringOneArr[i] = stringTwoArr[i]
  result += (stringOneArr.join('') + "\n")
}

I do not understand why we need the if (stringOneArr[i] !== stringTwoArr[i])
statement.  I wrote this code without it and didnt get the corrent answer

stringOneArr[i] = stringTwoArr[i]
result += (stringOneArr.join('') + "\n")

I get this error:

Expected: 'bubble gum\ntubble gum\nturble gum\nturtle gum\nturtle hum\nturtle ham\n',
instead got: 'bubble gum\ntubble gum\ntubble gum\nturble gum\nturtle gum\nturtle gum\nturtle gum\nturtle gum\nturtle hum\nturtle ham\nturtle ham\n'

Can someone tell me why in my for loop I cant just assign stringOneArr[i] = stringTwoArr[i].  to me If i just iterate through the string and assign each string1 element to string2 element than it should come out correctly.

but instead the only way to do it correctly and get corrent output is if I say if string1 element doesnt equal string2 element.  and than I assign it to string1 element to string2 element.  why i dont understand why it wont work with out this conditional.


问:
Reading methods from a text file for Java
I am working on an assignment and was wondering how one can read a method with  a parameter stated in a text file. For example, in my assignment the addFirst method will have a string right after it (addFirst New York). Also, The addFirst method name may be all lowercase. I've been looking around the net and this is what I already worked on:

```<code>import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;

public class Assignment2 {

  static DequeUsingStacks<String> deq = new DequeUsingStacks<String>();

  public static void main(String[] args) {

    try{
        FileInputStream fstream = new FileInputStream("Assignment2.txt");
        BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
        String m;

        while((m = br.readLine()) != null){

                if(m.equalsIgnoreCase("size"))
                    System.out.println(deq.size());

                if(m.equalsIgnoreCase("addFirst")) /*I want to be able to
                                                     use the string after
                                                     the method as the new
                                                     Value. So new
                                                     Value should equal to
                                                    "New York"*/

                deq.addFirst(new value);

        }

        fstream.close();
</code>```

DequeUsingStacks is another class with all the methods. I guess I just want to know how to read a line in a textfile with multiple strings. "New Value" is the string stated after the method in the text file. For example, (addFirst New York), the string "New York" should be the "New Value". I'm thinking that the line read should be put into an array. But I am not sure how to do that.

答:
Well, there is a way

```<code>   if ( m.toLowerCase().indexOf("addFirst".toLowerCase()) != -1 ) {
        deq.addFirst(m.replaceAll("addFirst".toLowerCase(), "").trim());
        }
</code>```

assign your method name to a string and use it for checking instead of hard coding as "addFirst".

Body:
I am working on an assignment and was wondering how one can read a method with  a parameter stated in a text file. For example, in my assignment the addFirst method will have a string right after it (addFirst New York). Also, The addFirst method name may be all lowercase. I've been looking around the net and this is what I already worked on:

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;

public class Assignment2 {

  static DequeUsingStacks<String> deq = new DequeUsingStacks<String>();

  public static void main(String[] args) {

    try{
        FileInputStream fstream = new FileInputStream("Assignment2.txt");
        BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
        String m;

        while((m = br.readLine()) != null){

                if(m.equalsIgnoreCase("size"))
                    System.out.println(deq.size());

                if(m.equalsIgnoreCase("addFirst")) /*I want to be able to
                                                     use the string after
                                                     the method as the new
                                                     Value. So new
                                                     Value should equal to
                                                    "New York"*/

                deq.addFirst(new value);

        }

        fstream.close();

DequeUsingStacks is another class with all the methods. I guess I just want to know how to read a line in a textfile with multiple strings. "New Value" is the string stated after the method in the text file. For example, (addFirst New York), the string "New York" should be the "New Value". I'm thinking that the line read should be put into an array. But I am not sure how to do that.

Body:
Well, there is a way

   if ( m.toLowerCase().indexOf("addFirst".toLowerCase()) != -1 ) {
        deq.addFirst(m.replaceAll("addFirst".toLowerCase(), "").trim());
        }

assign your method name to a string and use it for checking instead of hard coding as "addFirst".


问:
How to detect Safari, Chrome, IE, Firefox and Opera browsers?
I have 5 addons/extensions for Firefox, Chrome, Internet Explorer(IE), Opera, and Safari.

How can I correctly recognize the user browser and redirect (once an install button has been clicked) to download the corresponding addon?

答:
Here you find out which browser is it running.</p>

```<code>function isValidBrowser(navigator){

            var isChrome =  navigator.indexOf('chrome'),
            isFireFox= navigator.indexOf('firefox'),
            isIE = navigator.indexOf('trident') ,
            isValidChromeVer = parseInt(navigator.substring(isChrome+7, isChrome+8)) >= 4,
            isValidFireForVer = parseInt(navigator.substring(isFireFox+8, isFireFox+9)) >= 3,
            isValidIEVer = parseInt(navigator.substring(isIE+8, isIE+9)) >= 7;

            if((isChrome > -1 && isValidChromeVer){ console.log("Chrome Browser")}

            if(isFireFox > -1 && isValidFireForVer){ console.log("FireFox  Browser")}

            if(isIE > -1 && isValidIEVer)){ console.log("IE Browser")}

        }
</code>```

Body:
Here you find out which browser is it running.

function isValidBrowser(navigator){

            var isChrome =  navigator.indexOf('chrome'),
            isFireFox= navigator.indexOf('firefox'),
            isIE = navigator.indexOf('trident') ,
            isValidChromeVer = parseInt(navigator.substring(isChrome+7, isChrome+8)) >= 4,
            isValidFireForVer = parseInt(navigator.substring(isFireFox+8, isFireFox+9)) >= 3,
            isValidIEVer = parseInt(navigator.substring(isIE+8, isIE+9)) >= 7;

            if((isChrome > -1 && isValidChromeVer){ console.log("Chrome Browser")}

            if(isFireFox > -1 && isValidFireForVer){ console.log("FireFox  Browser")}

            if(isIE > -1 && isValidIEVer)){ console.log("IE Browser")}

        }


问:
new never fails?
In C++, we usually see and write code like,

```<code>Sample sample=new Sample();
if ( sample == NULL )
{
     std::cout<<"Memory allocation failed" << std::endl;
}
</code>```

But in C#, I rarely see this: (at least I've never seen this)

```<code>Sample sample = new Sample();
if ( sample == null )
{
     Console.WriteLine("Memory allocation failed\n");
}
</code>```

Means, in C#, we rarely check if a new failed or not. Why is it so? Does it have something to do with "In C#, new never fails"?  Is there such a thing in C# that new never fails?

If it fails, then why such "check" is so rare in C#? I'm not talking about OutOfMemoryException, that is after all exception, not "check". I'm talking about the coding style.

答:
In C++ new can return NULL when using a non compliant compiler (see Will new return NULL in any case?)

But, the proper way in C++ is that new throws an exception when out of memory, just like C#.

The check for NULL is only needed on certain compilers.

ContentLicense: CC BY-SA 2.5

Title: new never fails?

Body:
In C++, we usually see and write code like,

Sample sample=new Sample();
if ( sample == NULL )
{
     std::cout<<"Memory allocation failed" << std::endl;
}

But in C#, I rarely see this: (at least I've never seen this)

Sample sample = new Sample();
if ( sample == null )
{
     Console.WriteLine("Memory allocation failed\n");
}

Means, in C#, we rarely check if a new failed or not. Why is it so? Does it have something to do with "In C#, new never fails"?  Is there such a thing in C# that new never fails?

If it fails, then why such "check" is so rare in C#? I'm not talking about OutOfMemoryException, that is after all exception, not "check". I'm talking about the coding style.


问:
apply + list comprehension gives ValueError when returned list length is same as number of data frame columns
This question is born of this comment thread.  Using Pandas 0.20.3.

I'm trying to understand why an apply() operation throws the error:

ValueError: Wrong number of items passed 2, placement implies 1

This specific flavor of Pandas ValueError is not uncommon, but it usually comes from a more obvious attempt to cram a bunch of elements into a data structure that is designed for a lesser capacity.  The same thing must be going on here, but I can't figure out why.

Given a data frame with columns of integers A and B:

```<code>import pandas as pd

df = pd.DataFrame({'A': [1,2], 'B': [3,4]})
df
   A  B
0  1  3
1  2  4
</code>```

I can construct a new column, C, which is a column of lists.

Each list in C contains values from A and B.

C should look like:

```<code>     C
[1, 3]
[2, 4]
</code>```

I am choosing to build C using apply() and a list comprehension:

```<code>df['C'] = df.apply(lambda x: [val for val in x], axis=1)
</code>```

(For now, please overlook the possibility that this is not the most elegant way to achieve this goal - it's mainly a route to get to the error I'm confused about.)

This throws the ValueError noted above.

But, I can create lists with more items per row without difficulty:

```<code>df['C'] = df.apply(lambda x: [val for val in x]+[1], axis=1)
df
   A  B          C
0  1  3  [1, 3, 1]
1  2  4  [2, 4, 1]
</code>```

I would have thought that I'd get the same error, just with Wrong number of items passed 3... instead of 2.

I can also create C with fewer items:

```<code>df['C'] = df.apply(lambda x: [val for val in x][:1], axis=1)
df
   A  B    C
0  1  3  [1]
1  2  4  [2]
</code>```

Additionally, C builds when the first row's list length is shorter or longer than [1,3], but fails when the first row's list length matches len([1,3]), even if subsequent list lengths are different:

```<code>df['C'] = df.apply(lambda x: [val for val in x if val != 1], axis=1) # this works
df['C'] = df.apply(lambda x: [val for val in x if val != 4], axis=1) # this fails
</code>```

Given all of these different cases, I don't understand what placement implies 1 is referring to, and why I can't just make the lists in C with the elements of A and B, using this approach.

How am I misinterpreting this error message?

答:
It seems that this behavior results from a mix of (a) .apply() trying to be helpful and (b) abusing .apply() as a means of outputting non-scalar values.  It has been fixed in Pandas version 0.21.

I've cobbled together this explanation from various Pandas Github issues pages [1, 2, 3], some of which are also linked to in this answer.  It's not really an explanation of why this happens at the implementation level, but it at least substantively answers the question.

Happy to accept any relevannt updates/edits.

On .apply() trying to be helpful:

If a multi-dimensional value is returned that has the same shape as the input DataFrame, apply will infer a DataFrame as output:

TomAugspurger: DataFrame.apply tries to infer an output based on the result. The result of your output is inferred to be a DataFrame with the same columns. [ref]

jreback: The issue is .apply has to try to figure out what you are returning and how that maps to the starting data. [ref]

On abusing .apply() as a means of outputting non-scalar values:

In short, don't if you can avoid it.  If you must, expect occasionally funny results.

jreback: Note that returning non-scalars is generally not recommended and is not efficiently supported. [ref]

Body:
This question is born of this comment thread.  Using Pandas 0.20.3.

I'm trying to understand why an apply() operation throws the error:

ValueError: Wrong number of items passed 2, placement implies 1

This specific flavor of Pandas ValueError is not uncommon, but it usually comes from a more obvious attempt to cram a bunch of elements into a data structure that is designed for a lesser capacity.  The same thing must be going on here, but I can't figure out why.

Given a data frame with columns of integers A and B:

import pandas as pd

df = pd.DataFrame({'A': [1,2], 'B': [3,4]})
df
   A  B
0  1  3
1  2  4

I can construct a new column, C, which is a column of lists.

Each list in C contains values from A and B.

C should look like:

     C
[1, 3]
[2, 4]

I am choosing to build C using apply() and a list comprehension:

df['C'] = df.apply(lambda x: [val for val in x], axis=1)

(For now, please overlook the possibility that this is not the most elegant way to achieve this goal - it's mainly a route to get to the error I'm confused about.)

This throws the ValueError noted above.

But, I can create lists with more items per row without difficulty:

df['C'] = df.apply(lambda x: [val for val in x]+[1], axis=1)
df
   A  B          C
0  1  3  [1, 3, 1]
1  2  4  [2, 4, 1]

I would have thought that I'd get the same error, just with Wrong number of items passed 3... instead of 2.

I can also create C with fewer items:

df['C'] = df.apply(lambda x: [val for val in x][:1], axis=1)
df
   A  B    C
0  1  3  [1]
1  2  4  [2]

Additionally, C builds when the first row's list length is shorter or longer than [1,3], but fails when the first row's list length matches len([1,3]), even if subsequent list lengths are different:

df['C'] = df.apply(lambda x: [val for val in x if val != 1], axis=1) # this works
df['C'] = df.apply(lambda x: [val for val in x if val != 4], axis=1) # this fails

Given all of these different cases, I don't understand what placement implies 1 is referring to, and why I can't just make the lists in C with the elements of A and B, using this approach.

How am I misinterpreting this error message?


问:
How to properly convert an unsigned char array into an uint32_t
So, I'm trying to convert an array of unsigned chars into an uint32_t, but keep getting different results each time:

```<code>unsigned char buffer[] = {0x80, 0x00, 0x00, 0x00};;
uint32_t num = (uint32_t*)&buffer;
</code>```

Now, I keep getting this warning:

warning: initialization makes integer from pointer without a cast

When I change num to *num i don't get that warning, but that's not actually the real problem (UPDATE: well, those might be related now that I think of it.), because every time I run the code there is different results. Secondly the num, once it's cast properly, should be 128, but If I need to change the endianness of the buffer I could manage to do that myself, I think.

Thanks!

答:
Borrowing from @Mr. R. above, my approach for converting a 3 byte big endian unsigned char array within a structure to a little endian unsigned int...</p>

```<code>struct mystruct {
  int stuff;
  int stuff2;
  unsigned char x[3]    // big endian
}
mystruct z;
unsigned int y  // little endian

memcpy(&y, z->x, 3);
y=be32toh(y<<8);`
</code>```

Body:
So, I'm trying to convert an array of unsigned chars into an uint32_t, but keep getting different results each time:

unsigned char buffer[] = {0x80, 0x00, 0x00, 0x00};;
uint32_t num = (uint32_t*)&buffer;

Now, I keep getting this warning:

warning: initialization makes integer from pointer without a cast

When I change num to *num i don't get that warning, but that's not actually the real problem (UPDATE: well, those might be related now that I think of it.), because every time I run the code there is different results. Secondly the num, once it's cast properly, should be 128, but If I need to change the endianness of the buffer I could manage to do that myself, I think.

Thanks!

Body:
Borrowing from @Mr. R. above, my approach for converting a 3 byte big endian unsigned char array within a structure to a little endian unsigned int...

struct mystruct {
  int stuff;
  int stuff2;
  unsigned char x[3]    // big endian
}
mystruct z;
unsigned int y  // little endian

memcpy(&y, z->x, 3);
y=be32toh(y<<8);`


问:
Maintaining Heap Property

Brief Background: I am studying the steps for maintaining a heap property when insertion occurs. Here is an interesting problem:

Question: There are two general strategies that could be used to maintain the heap properties:

Make sure that the tree is complete and then fix the ordering or

Make sure the ordering is correct first and then check for completeness.

Which is better (1 or 2)?

Reference: http://www.cs.sfu.ca/CourseCentral/225/johnwill/cmpt225_09heaps.pdf  (Heap Insertion - slide 16) written by Dr. John Edgar.

It would be great if you guys can clarify why one of the methods above is better?

答:
With a binary heap implemented as an array, there are in general two ways to implement insertion: top-down or bottom-up. Slide 17 of the linked PDF describes the bottom-up way of doing things. It adds the new item at the end of the heap (bottom-most, left-most position), and bubbles it up. That is an implementation of strategy 1 shown on Slide 16.

From a performance standpoint, this is the better method simply because, on average, it requires fewer iterations to fix the ordering. See Argument for O(1) average-case complexity of heap insertion for a detailed explanation of why that is.

The top-down approach, which corresponds to strategy 2 on Slide 16, requires that every insertion make O(log n) comparisons. This strategy starts at the root and sifts the item down through the heap. If the new item is smaller (in a min-heap) than the node it's being compared against, it replaces the item at that node, and the just-replaced item has to be pushed down. This continues until you reach the bottom of the heap. There is no "early out" possible because you have to end up putting a new item in the heap at the leaf level.

I never really thought of it as making sure of the ordering first, and then ensuring completeness, but that's essentially what the top-down method is doing.

The second strategy requires more iterations per insertion, and also does more work during each iteration to maintain the ordering.

Title: Maintaining Heap Property


问:
How to keep mouse position relative to screen and disregard component rotation?
How would one go about rotating the mouse coordinate system when a rotation is applied to a Canvas? When I rotate the Canvas, the mouse stays in the same position relative to the rotated components. I would like to have the mouse coordinates consider the rotation of the component, instead of the coordinates being the position relative to the window, with no consideration for rotation.

I've provided a picture to illustrate more of what I'm getting at. The black box represents a shape for reference, and the purple box lies on the mouse coordinates. Rotation example image

Leftmost picture - Unrotated Canvas
Middle picture - Rotated Canvas as Java sees it
Rightmost picture - Desired outcome

My example code simulates a Canvas that rotates by pressing the left or right arrow keys. This simulation shows how the mouse stays in a position relative to rotated components, rather than relative to my mouse on screen.

Is there a way to transform or calculate these new coordinates (shown in the rightmost image) so that they lock onto my mouse in the window, regardless of rotation?

```<code> package rotation;

    import java.awt.Canvas;
    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.MouseInfo;
    import java.awt.Point;
    import java.awt.event.KeyAdapter;
    import java.awt.event.KeyEvent;
    import java.awt.geom.AffineTransform;
    import java.awt.image.BufferStrategy;

    import javax.swing.JFrame;

    @SuppressWarnings("serial")
    public class RotationExample extends Canvas implements Runnable{

        boolean isRunning = false;
        boolean left = false;
        boolean right = false;
        AffineTransform transform = new AffineTransform();
        double rotation = 0.0d;

        public RotationExample() {
            //Create jframe
            JFrame f = new JFrame();
            f.setSize(500, 500);
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.setResizable(false);
            f.setUndecorated(true);

            //Add key listener
            this.addKeyListener(new KeyAdapter() {
                public void keyPressed(KeyEvent e) {
                    int k = e.getKeyCode();
                    //Set left and right variables
                    if(k == KeyEvent.VK_LEFT) left = true;
                    if(k == KeyEvent.VK_RIGHT) right = true;
                }

                public void keyReleased(KeyEvent e) {
                    int k = e.getKeyCode();
                    if(k == KeyEvent.VK_LEFT) left = false;
                    if(k == KeyEvent.VK_RIGHT) right = false;
                }
            });

            f.add(this);
            f.setVisible(true);
            start();
        }

        public void render() {
            BufferStrategy bs = this.getBufferStrategy();
            if(bs == null){
                this.createBufferStrategy(3);
                return;
            }

            Graphics g = bs.getDrawGraphics();
            Graphics2D gt = (Graphics2D) g;

            gt.setTransform(transform);

            gt.clearRect(0, 0, 500, 500);

            //Increment rotation based on left or right variables
            if(left) rotation += 0.001;
            else if(right) rotation -= 0.001;

            //Rotate around middle of frame
            gt.rotate(rotation, 250, 250);

            //Draw black rectangle in middle
            gt.setColor(Color.BLACK);
            gt.fillRect(175, 175, 150, 150);

            //Draw red up arrow
            gt.setColor(Color.RED);
            gt.fillPolygon(new int[] {250, 300, 270, 270, 230, 230, 200}, new int[] {200, 250, 250, 300, 300, 250, 250}, 7);

            //Draw rectangle at mouse coordinates
            gt.setColor(Color.MAGENTA);
            Point m = MouseInfo.getPointerInfo().getLocation();
            gt.fillRect((int) m.getX() - 8, (int) m.getY() - 8, 16, 16);

            bs.show();
            gt.dispose();
        }

        public static void main(String[] args) {
            new RotationExample();
        }

        public void start() {
            isRunning = true;
            new Thread(this).start();
        }

        public void run() {
            //Continuous rendering
            while(isRunning) {
                render();
            }

        }
    }
</code>```

答:
The mouse position is reported in absolute, but the box drawing is after transform.  You need to do the inverse transform for the mouse position to bring it back to the pointer.</p>

```<code>        //Draw rectangle at mouse coordinates
        gt.setColor(Color.MAGENTA);
        Point m = MouseInfo.getPointerInfo().getLocation();
        try {
            gt.getTransform().createInverse().transform(m, m);
            gt.fillRect((int) m.getX() - 8, (int) m.getY() - 8, 16, 16);
        } catch (java.awt.geom.NoninvertibleTransformException e) {
            System.err.println(e);
        }
</code>```

Body:
How would one go about rotating the mouse coordinate system when a rotation is applied to a Canvas? When I rotate the Canvas, the mouse stays in the same position relative to the rotated components. I would like to have the mouse coordinates consider the rotation of the component, instead of the coordinates being the position relative to the window, with no consideration for rotation.

I've provided a picture to illustrate more of what I'm getting at. The black box represents a shape for reference, and the purple box lies on the mouse coordinates. Rotation example image

Leftmost picture - Unrotated Canvas
Middle picture - Rotated Canvas as Java sees it
Rightmost picture - Desired outcome

My example code simulates a Canvas that rotates by pressing the left or right arrow keys. This simulation shows how the mouse stays in a position relative to rotated components, rather than relative to my mouse on screen.

Is there a way to transform or calculate these new coordinates (shown in the rightmost image) so that they lock onto my mouse in the window, regardless of rotation?

 package rotation;

    import java.awt.Canvas;
    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.MouseInfo;
    import java.awt.Point;
    import java.awt.event.KeyAdapter;
    import java.awt.event.KeyEvent;
    import java.awt.geom.AffineTransform;
    import java.awt.image.BufferStrategy;

    import javax.swing.JFrame;

    @SuppressWarnings("serial")
    public class RotationExample extends Canvas implements Runnable{

        boolean isRunning = false;
        boolean left = false;
        boolean right = false;
        AffineTransform transform = new AffineTransform();
        double rotation = 0.0d;

        public RotationExample() {
            //Create jframe
            JFrame f = new JFrame();
            f.setSize(500, 500);
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.setResizable(false);
            f.setUndecorated(true);

            //Add key listener
            this.addKeyListener(new KeyAdapter() {
                public void keyPressed(KeyEvent e) {
                    int k = e.getKeyCode();
                    //Set left and right variables
                    if(k == KeyEvent.VK_LEFT) left = true;
                    if(k == KeyEvent.VK_RIGHT) right = true;
                }

                public void keyReleased(KeyEvent e) {
                    int k = e.getKeyCode();
                    if(k == KeyEvent.VK_LEFT) left = false;
                    if(k == KeyEvent.VK_RIGHT) right = false;
                }
            });

            f.add(this);
            f.setVisible(true);
            start();
        }

        public void render() {
            BufferStrategy bs = this.getBufferStrategy();
            if(bs == null){
                this.createBufferStrategy(3);
                return;
            }

            Graphics g = bs.getDrawGraphics();
            Graphics2D gt = (Graphics2D) g;

            gt.setTransform(transform);

            gt.clearRect(0, 0, 500, 500);

            //Increment rotation based on left or right variables
            if(left) rotation += 0.001;
            else if(right) rotation -= 0.001;

            //Rotate around middle of frame
            gt.rotate(rotation, 250, 250);

            //Draw black rectangle in middle
            gt.setColor(Color.BLACK);
            gt.fillRect(175, 175, 150, 150);

            //Draw red up arrow
            gt.setColor(Color.RED);
            gt.fillPolygon(new int[] {250, 300, 270, 270, 230, 230, 200}, new int[] {200, 250, 250, 300, 300, 250, 250}, 7);

            //Draw rectangle at mouse coordinates
            gt.setColor(Color.MAGENTA);
            Point m = MouseInfo.getPointerInfo().getLocation();
            gt.fillRect((int) m.getX() - 8, (int) m.getY() - 8, 16, 16);

            bs.show();
            gt.dispose();
        }

        public static void main(String[] args) {
            new RotationExample();
        }

        public void start() {
            isRunning = true;
            new Thread(this).start();
        }

        public void run() {
            //Continuous rendering
            while(isRunning) {
                render();
            }

        }
    }

Body:
The mouse position is reported in absolute, but the box drawing is after transform.  You need to do the inverse transform for the mouse position to bring it back to the pointer.

        //Draw rectangle at mouse coordinates
        gt.setColor(Color.MAGENTA);
        Point m = MouseInfo.getPointerInfo().getLocation();
        try {
            gt.getTransform().createInverse().transform(m, m);
            gt.fillRect((int) m.getX() - 8, (int) m.getY() - 8, 16, 16);
        } catch (java.awt.geom.NoninvertibleTransformException e) {
            System.err.println(e);
        }


问:
Adding an hyperlink in MSWord by using python-docx
I am trying to add an hyperlink in a MS Word document using docx module for Python.

I searched everywhere (official doc, StackOverflow, Google) but found nothing.

I would like to do something like:

```<code>from docx import Document

document = Document()

p = document.add_paragraph('A plain paragraph having some ')
p.add_hyperlink('Link to my site', target="http://supersitedelamortquitue.fr")
</code>```

Anyone got an idea on how to do that?

答:
Yes we can do it. Reference</p>

```<code>import docx
from docx.enum.dml import MSO_THEME_COLOR_INDEX

def add_hyperlink(paragraph, text, url):
    # This gets access to the document.xml.rels file and gets a new relation id value
    part = paragraph.part
    r_id = part.relate_to(url, docx.opc.constants.RELATIONSHIP_TYPE.HYPERLINK, is_external=True)

    # Create the w:hyperlink tag and add needed values
    hyperlink = docx.oxml.shared.OxmlElement('w:hyperlink')
    hyperlink.set(docx.oxml.shared.qn('r:id'), r_id, )

    # Create a w:r element and a new w:rPr element
    new_run = docx.oxml.shared.OxmlElement('w:r')
    rPr = docx.oxml.shared.OxmlElement('w:rPr')

    # Join all the xml elements together add add the required text to the w:r element
    new_run.append(rPr)
    new_run.text = text
    hyperlink.append(new_run)

    # Create a new Run object and add the hyperlink into it
    r = paragraph.add_run ()
    r._r.append (hyperlink)

    # A workaround for the lack of a hyperlink style (doesn't go purple after using the link)
    # Delete this if using a template that has the hyperlink style in it
    r.font.color.theme_color = MSO_THEME_COLOR_INDEX.HYPERLINK
    r.font.underline = True

    return hyperlink

document = docx.Document()
p = document.add_paragraph('A plain paragraph having some ')
add_hyperlink(p, 'Link to my site', "http://supersitedelamortquitue.fr")
document.save('demo_hyperlink.docx')
</code>```

Body:
I am trying to add an hyperlink in a MS Word document using docx module for Python.

I searched everywhere (official doc, StackOverflow, Google) but found nothing.

I would like to do something like:

from docx import Document

document = Document()

p = document.add_paragraph('A plain paragraph having some ')
p.add_hyperlink('Link to my site', target="http://supersitedelamortquitue.fr")

Anyone got an idea on how to do that?

Body:
Yes we can do it. Reference

import docx
from docx.enum.dml import MSO_THEME_COLOR_INDEX

def add_hyperlink(paragraph, text, url):
    # This gets access to the document.xml.rels file and gets a new relation id value
    part = paragraph.part
    r_id = part.relate_to(url, docx.opc.constants.RELATIONSHIP_TYPE.HYPERLINK, is_external=True)

    # Create the w:hyperlink tag and add needed values
    hyperlink = docx.oxml.shared.OxmlElement('w:hyperlink')
    hyperlink.set(docx.oxml.shared.qn('r:id'), r_id, )

    # Create a w:r element and a new w:rPr element
    new_run = docx.oxml.shared.OxmlElement('w:r')
    rPr = docx.oxml.shared.OxmlElement('w:rPr')

    # Join all the xml elements together add add the required text to the w:r element
    new_run.append(rPr)
    new_run.text = text
    hyperlink.append(new_run)

    # Create a new Run object and add the hyperlink into it
    r = paragraph.add_run ()
    r._r.append (hyperlink)

    # A workaround for the lack of a hyperlink style (doesn't go purple after using the link)
    # Delete this if using a template that has the hyperlink style in it
    r.font.color.theme_color = MSO_THEME_COLOR_INDEX.HYPERLINK
    r.font.underline = True

    return hyperlink

document = docx.Document()
p = document.add_paragraph('A plain paragraph having some ')
add_hyperlink(p, 'Link to my site', "http://supersitedelamortquitue.fr")
document.save('demo_hyperlink.docx')


问:
Is there a best .NET algorithm for credit card encryption?
The .NET System.Security.Cryptography namespace has a rather bewildering collection of algorithms that I could use for encryption of credit card details. Which is the best?

It clearly needs to be secure for a relatively short string.

EDIT: I'm in the UK, where I understand we're OK storing encrypted credit card details so long as the three-digit CVV number is never stored. And thanks all for the great responses.

答:
Encrypt the credit card with a public key. Give the private key to the payment processor machine only. The payment processor machine then can query the database and do the work, and nobody else, even the machine which added the entry, will be able to decrypt it.

Something like PHP's openssl_seal, though if you want perhaps with a different algorithm.

OwnerDisplayName: JeremyMcGee

LastEditorDisplayName: JeremyMcGee


问:
Output ArrayList to String without [,] (brackets) appearing
OK, so I have an ArrayList that I need to return as a String. Right now I am using this approach:

```<code>List<Customer> customers = new ArrayList<>();
List<Account> accounts = new ArrayList<>();

public String customerList()
{
    String list = Arrays.toString(customers.toArray());
    return list;
}

public String accountList()
{
    String account = Arrays.toString(accounts.toArray());
    return account;
}
</code>```

This works fine, but the problem is that I get brackets around the text. I am getting stuff like:

```<code> Customer list:
 --------------
 [Name: Last, First
 , Name: Last, First
 , Name: Last, First
 ]
</code>```

When I want something like this:

```<code> Customer list:
 --------------
 Name: Last, First
 Name: Last, First
 Name: Last, First
</code>```

However, unlike similar questions, I don't simply want to output line by line. I need to store the ArrayList in a String without the brackets so I can work with it.

EDIT: It should be noted that the one comma in the version I want it to look like was placed there by a method in a different class:

```<code>public final String getName()
    {
        return getLast() + ", " + getFirst();
    }
</code>```

EDIT 2: I was able to find a complete solution by adapting the two answers I was given. It was difficult deciding which was the "answer" because I found both useful, but went with the one that I could use more selectively.

```<code>public String customerList()
{
    String list = Arrays.toString(customers.toArray()).replace(", N", "N").replace(", N", "N");
    return list.substring(1,list.length()-1);
}
</code>```

To remove the brackets I used the modified return. Removing the comma required me to focus on the fact that each line will start with an "N", but the flaw in this approach is that the code would break if I forget to change it here if I change it there. Still, it solves my specific problem, and I can always notate to myself in both places as needed.

答:
You can use the method substring() to remove starting and ending brackets without tampering any entries in the ArrayList.
I used something like this to convert a ArrayList<String> to String

```<code>String str = list.toString().substring(1, list.toString().length() - 1);
</code>```

Body:
OK, so I have an ArrayList that I need to return as a String. Right now I am using this approach:

List<Customer> customers = new ArrayList<>();
List<Account> accounts = new ArrayList<>();

public String customerList()
{
    String list = Arrays.toString(customers.toArray());
    return list;
}

public String accountList()
{
    String account = Arrays.toString(accounts.toArray());
    return account;
}

This works fine, but the problem is that I get brackets around the text. I am getting stuff like:

 Customer list:
 --------------
 [Name: Last, First
 , Name: Last, First
 , Name: Last, First
 ]

When I want something like this:

 Customer list:
 --------------
 Name: Last, First
 Name: Last, First
 Name: Last, First

However, unlike similar questions, I don't simply want to output line by line. I need to store the ArrayList in a String without the brackets so I can work with it.

EDIT: It should be noted that the one comma in the version I want it to look like was placed there by a method in a different class:

public final String getName()
    {
        return getLast() + ", " + getFirst();
    }

EDIT 2: I was able to find a complete solution by adapting the two answers I was given. It was difficult deciding which was the "answer" because I found both useful, but went with the one that I could use more selectively.

public String customerList()
{
    String list = Arrays.toString(customers.toArray()).replace(", N", "N").replace(", N", "N");
    return list.substring(1,list.length()-1);
}

To remove the brackets I used the modified return. Removing the comma required me to focus on the fact that each line will start with an "N", but the flaw in this approach is that the code would break if I forget to change it here if I change it there. Still, it solves my specific problem, and I can always notate to myself in both places as needed.

Body:
You can use the method substring() to remove starting and ending brackets without tampering any entries in the ArrayList.
I used something like this to convert a ArrayList<String> to String

String str = list.toString().substring(1, list.toString().length() - 1);


问:
CodeIgniter Redirect issue
I am testing a server on http://example.com:8080, my CI app is here http://example.com:8080/app/

I have a port forward from 8080 (external) to 80 (internal)

My config.php looks like this:

```<code>...
$config['base_url'] = 'http://' . $_SERVER['HTTP_HOST'] . '/app';
...
$config['index_page'] = '';
</code>```

How should look the .htaccess file in order to get the site working. Also I have used this https://www.codeigniter.com/userguide3/general/urls.html with success on port 80, but cant get it work on 8080. If I leave the index.php in the url then everything works well also on port 8080.

Thanks for any suggestion.

答:
Try this .taccess:

```<code>RewriteEngine on
RewriteCond $1 !^(index\.php|resources|robots\.txt)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L,QSA]
</code>```

Its not clear your question why your redirect not working. Hope this help you. Always put what you have tried so far so everyone can understand better.

Greetings!

Title: CodeIgniter Redirect issue

Body:
I am testing a server on http://example.com:8080, my CI app is here http://example.com:8080/app/

I have a port forward from 8080 (external) to 80 (internal)

My config.php looks like this:

...
$config['base_url'] = 'http://' . $_SERVER['HTTP_HOST'] . '/app';
...
$config['index_page'] = '';

How should look the .htaccess file in order to get the site working. Also I have used this https://www.codeigniter.com/userguide3/general/urls.html with success on port 80, but cant get it work on 8080. If I leave the index.php in the url then everything works well also on port 8080.

Thanks for any suggestion.

Body:
Try this .taccess:

RewriteEngine on
RewriteCond $1 !^(index\.php|resources|robots\.txt)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L,QSA]

Its not clear your question why your redirect not working. Hope this help you. Always put what you have tried so far so everyone can understand better.

Greetings!


问:
enable/disable button using case statement

Hello, need help pleaseI already tried adding a break on both end of condition ..I Have 5 Textboxes, 1 Button and a Javascript for their function. What i want to do is this..

CASE 1: When the value of Stat variable is "N", The program must require an input on Area, Capital and Code for the ADD button to enable else it will disable.

CASE 2 When the value of Stat variable is "R", The program must require an input on Area, Gross and Code textboxes for the ADD button to enable else it will disable. I have tried to code it this way.. But it didn't work.

```<code>function SetButtonStatus() {

        var Stat = document.getElementById('<%=_oTextBoxNRC.ClientID%>').value;
        var Area = document.getElementById('<%=_oTextBoxArea.ClientID%>').value;
        var Capital = document.getElementById('<%=_oTextBoxCapital.ClientID%>').value;
        var Code = document.getElementById('<%= _oTextboxBusLineCode.ClientID%>').value;
        var Gross = document.getElementById('<%=_oTextBoxGrossRec.ClientID%>').value;
        //Change these conditions as your requirement

        switch (Stat) {

            case 'N':

                if (parseFloat(Area) >= 1 && parseFloat(Capital) >= 1 && Code.length >= 1)
                    document.getElementById('<%=_oButtonAdd.ClientID%>').disabled = false;
                else
                    document.getElementById('<%=_oButtonAdd.ClientID%>').disabled = true;
                break;
            case 'R':

                if (parseFloat(Area) >= 1 && parseFloat(Gross) >= 1 && Code.length >= 1)
                    document.getElementById('<%=_oButtonAdd.ClientID%>').disabled = false;
                else
                    document.getElementById('<%=_oButtonAdd.ClientID%>').disabled = true;
                break;
        }

    }
</code>```

答:
Use setAttribute and removeAttribute like this:

```<code> if (parseFloat(Area) >= 1 && parseFloat(Capital) >= 1 && Code.length >= 1)
 {
     document.getElementById('<%=_oButtonAdd.ClientID%>')
         .setAttribute("disabled","disabled");
 }
 else
 {
     document.getElementById('<%=_oButtonAdd.ClientID%>')
         .removeAttribute('disabled');
 }
</code>```

Body:
Hello, need help pleaseI already tried adding a break on both end of condition ..I Have 5 Textboxes, 1 Button and a Javascript for their function. What i want to do is this..

CASE 1: When the value of Stat variable is "N", The program must require an input on Area, Capital and Code for the ADD button to enable else it will disable.

CASE 2 When the value of Stat variable is "R", The program must require an input on Area, Gross and Code textboxes for the ADD button to enable else it will disable. I have tried to code it this way.. But it didn't work.

function SetButtonStatus() {

        var Stat = document.getElementById('<%=_oTextBoxNRC.ClientID%>').value;
        var Area = document.getElementById('<%=_oTextBoxArea.ClientID%>').value;
        var Capital = document.getElementById('<%=_oTextBoxCapital.ClientID%>').value;
        var Code = document.getElementById('<%= _oTextboxBusLineCode.ClientID%>').value;
        var Gross = document.getElementById('<%=_oTextBoxGrossRec.ClientID%>').value;
        //Change these conditions as your requirement

        switch (Stat) {

            case 'N':

                if (parseFloat(Area) >= 1 && parseFloat(Capital) >= 1 && Code.length >= 1)
                    document.getElementById('<%=_oButtonAdd.ClientID%>').disabled = false;
                else
                    document.getElementById('<%=_oButtonAdd.ClientID%>').disabled = true;
                break;
            case 'R':

                if (parseFloat(Area) >= 1 && parseFloat(Gross) >= 1 && Code.length >= 1)
                    document.getElementById('<%=_oButtonAdd.ClientID%>').disabled = false;
                else
                    document.getElementById('<%=_oButtonAdd.ClientID%>').disabled = true;
                break;
        }

    }

Body:
Use setAttribute and removeAttribute like this:

 if (parseFloat(Area) >= 1 && parseFloat(Capital) >= 1 && Code.length >= 1)
 {
     document.getElementById('<%=_oButtonAdd.ClientID%>')
         .setAttribute("disabled","disabled");
 }
 else
 {
     document.getElementById('<%=_oButtonAdd.ClientID%>')
         .removeAttribute('disabled');
 }


问:
Python How to specify which character to index if there are duplicates
So I am doing an exercise for class where I need to print out which characters occur, and where they occur. I did that with the following code:

```<code>def letterInString(string):
   index = 0
   pos = ""
   stringList = list(string)
   positions = []
   counter = 0
   occurences = {}
   for l in string:
       for x in string:
           if x == l:
               counter += 1
               positions.append(stringList.index(x))
            for item in positions:
                if index == 0:
                    pos = str(positions[index])
                    index += 1
                else:
                    pos = pos + "," + str(positions[index])
                    index += 1
            occurences[l.upper()] = str(counter) + "(" + pos + ")"
            index = 0
            positions = []
        counter = 0
    for key,value in occurences.items():
        print(key + ": " + str(value))

letterInString("hello")
</code>```

The code works just fine for words with no duplicates but when there are duplicates, it doesn't know which letter to index. The last part in my code was just to test certain cases. Please Help!!!

Any help is appreciated!!

答:
I think your code may be unnecessarily complicated. How about

```<code>def analyze(str_):
    data = [(c, str_.count(c), i) for i, c in enumerate(str_)]
    return "\n".join(["{}: count = {}. index = {}".format(*d) for d in data])

print analyze("hello")

# h: count = 1. index = 0
# e: count = 1. index = 1
# l: count = 2. index = 2
# l: count = 2. index = 3
# o: count = 1. index = 4
</code>```

Note well the use of list comprehension, string substitution and the count method for strings. You may wish to rewrite this function to return the data in a different format (i.e. not as a string).

Body:
So I am doing an exercise for class where I need to print out which characters occur, and where they occur. I did that with the following code:

def letterInString(string):
   index = 0
   pos = ""
   stringList = list(string)
   positions = []
   counter = 0
   occurences = {}
   for l in string:
       for x in string:
           if x == l:
               counter += 1
               positions.append(stringList.index(x))
            for item in positions:
                if index == 0:
                    pos = str(positions[index])
                    index += 1
                else:
                    pos = pos + "," + str(positions[index])
                    index += 1
            occurences[l.upper()] = str(counter) + "(" + pos + ")"
            index = 0
            positions = []
        counter = 0
    for key,value in occurences.items():
        print(key + ": " + str(value))

letterInString("hello")

The code works just fine for words with no duplicates but when there are duplicates, it doesn't know which letter to index. The last part in my code was just to test certain cases. Please Help!!!

Any help is appreciated!!

Body:
I think your code may be unnecessarily complicated. How about

def analyze(str_):
    data = [(c, str_.count(c), i) for i, c in enumerate(str_)]
    return "\n".join(["{}: count = {}. index = {}".format(*d) for d in data])

print analyze("hello")

# h: count = 1. index = 0
# e: count = 1. index = 1
# l: count = 2. index = 2
# l: count = 2. index = 3
# o: count = 1. index = 4

Note well the use of list comprehension, string substitution and the count method for strings. You may wish to rewrite this function to return the data in a different format (i.e. not as a string).


问:
Opening spinner by clicking on EditText
Sorry to bother you guys, but I've been strangling to get this to work.

What I want it to do:

EditText to display hint.

User clicks on EditText, opens spinner and selects their sex. That then get's turned into a string and put inside the EditText(gender)

What it is actually doing:
"Male" the first element in my spinner is already put inside my EditText before the user even clicks on it.(I never see my hint: "Sex")....and the spinner won't open at all when I try clicking on the EditText(gender)

What's going on?

My code:

```<code>    private Spinner sexSpinner;
    String[] arrayForSpinner = {"Male", "Female"};

    //Inside OnCreate method:
    sexSpinner = (Spinner)findViewById(R.id.spinner);
    adapter = new ArrayAdapter<String>(this, R.layout.spinner_row, arrayForSpinner);
    sexSpinner.setAdapter(adapter);

sexSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

        @Override
        public void onItemSelected(AdapterView<?> parent, View view,int position, long id) {
            gender.setText(sexSpinner.getSelectedItem().toString());

        }

gender.setOnFocusChangeListener(new View.OnFocusChangeListener() {

        @Override
        public void onFocusChange(View arg0, boolean hasFocus) {
            // TODO Auto-generated method stub
            if(hasFocus){
                sexSpinner.performClick();
            }
        }
    });
</code>```

Layout:

```<code><EditText
        android:layout_width="75dp"
        android:layout_height="wrap_content"
        android:layout_marginBottom="12dp"
        android:focusable="false"
        android:longClickable="false"
        android:clickable="true"
        android:inputType="date"
        android:maxLines="1"
        android:singleLine="true"
        android:hint="Gender"
        android:textColorHint="@color/white"
        android:textColor="@color/white"
        android:ems="10"
        android:id="@+id/signup_input_gender"
        android:layout_below="@+id/signup_input_birthday"
        android:layout_centerHorizontal="true"
        android:backgroundTint="@android:color/white"/>

<Spinner
        android:background="@color/Blue"
        android:id="@+id/spinner"
        android:paddingLeft="0dp"
        android:layout_width="75dp"
        android:layout_height="40dp"
        android:layout_marginRight="40dp"
        android:layout_marginBottom="6dp"
        android:layout_below="@+id/linearlayout"
        android:visibility="invisible" />
</code>```

答:
you had not made the spinner visiable while clicking on it so you cant see it</p>

```<code>sexSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

    @Override
    public void onItemSelected(AdapterView<?> parent, View view,int position, long id) {
sexSpinner.setVisibility(View.Invisible)
        gender.setText(sexSpinner.getSelectedItem().toString());

    }

gender.setOnFocusChangeListener(new View.OnFocusChangeListener() {

    @Override
    public void onFocusChange(View arg0, boolean hasFocus) {
        // TODO Auto-generated method stub
        if(hasFocus){
sexSpinner.setVisibility(View.Visible)
            sexSpinner.performClick();
        }
    }
});
</code>```

Title: Opening spinner by clicking on EditText

Body:
Sorry to bother you guys, but I've been strangling to get this to work.

What I want it to do:

EditText to display hint.

User clicks on EditText, opens spinner and selects their sex. That then get's turned into a string and put inside the EditText(gender)

What it is actually doing:
"Male" the first element in my spinner is already put inside my EditText before the user even clicks on it.(I never see my hint: "Sex")....and the spinner won't open at all when I try clicking on the EditText(gender)

What's going on?

My code:

    private Spinner sexSpinner;
    String[] arrayForSpinner = {"Male", "Female"};

    //Inside OnCreate method:
    sexSpinner = (Spinner)findViewById(R.id.spinner);
    adapter = new ArrayAdapter<String>(this, R.layout.spinner_row, arrayForSpinner);
    sexSpinner.setAdapter(adapter);

sexSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

        @Override
        public void onItemSelected(AdapterView<?> parent, View view,int position, long id) {
            gender.setText(sexSpinner.getSelectedItem().toString());

        }

gender.setOnFocusChangeListener(new View.OnFocusChangeListener() {

        @Override
        public void onFocusChange(View arg0, boolean hasFocus) {
            // TODO Auto-generated method stub
            if(hasFocus){
                sexSpinner.performClick();
            }
        }
    });

Layout:

<EditText
        android:layout_width="75dp"
        android:layout_height="wrap_content"
        android:layout_marginBottom="12dp"
        android:focusable="false"
        android:longClickable="false"
        android:clickable="true"
        android:inputType="date"
        android:maxLines="1"
        android:singleLine="true"
        android:hint="Gender"
        android:textColorHint="@color/white"
        android:textColor="@color/white"
        android:ems="10"
        android:id="@+id/signup_input_gender"
        android:layout_below="@+id/signup_input_birthday"
        android:layout_centerHorizontal="true"
        android:backgroundTint="@android:color/white"/>

<Spinner
        android:background="@color/Blue"
        android:id="@+id/spinner"
        android:paddingLeft="0dp"
        android:layout_width="75dp"
        android:layout_height="40dp"
        android:layout_marginRight="40dp"
        android:layout_marginBottom="6dp"
        android:layout_below="@+id/linearlayout"
        android:visibility="invisible" />

Body:
you had not made the spinner visiable while clicking on it so you cant see it

sexSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

    @Override
    public void onItemSelected(AdapterView<?> parent, View view,int position, long id) {
sexSpinner.setVisibility(View.Invisible)
        gender.setText(sexSpinner.getSelectedItem().toString());

    }

gender.setOnFocusChangeListener(new View.OnFocusChangeListener() {

    @Override
    public void onFocusChange(View arg0, boolean hasFocus) {
        // TODO Auto-generated method stub
        if(hasFocus){
sexSpinner.setVisibility(View.Visible)
            sexSpinner.performClick();
        }
    }
});


问:
Add production into development React Webpack config
I have a simplest possible React environment.
That is very efficient in development.

```<code>var webpack = require('webpack');

const config = {
  entry: "./index.js",
  output: { filename: "bundle.js" },
  devtool: 'eval',
module: {
   loaders: [
    {  test: /\.js$/, loader: 'babel-loader', exclude: /node_modules/, query: { presets: ['react', 'env'] }  }
   ]
  }
};

module.exports = config;
</code>```

What I want to do is to add a production build so as to run in console script like this: npm run build, which is defined in package.json:

"build": "webpack --config webpack.config.js"

How can I add production plugins and devtool: "cheap-module-source-map" so that they will work only in production and were not included into development. By production plugins I meant these:

```<code>new webpack.DefinePlugin({ 'process.env.NODE_ENV': JSON.stringify('production') }),
new webpack.optimize.UglifyJsPlugin()
</code>```

I failed to use

```<code>var debug = process.env.NODE_ENV !== "production";
</code>```

with devtool: debug ? "cheap-module-source-map" : "eval",
and

plugins: debug ? [] : [//production plugins here ]

答:
It sounds like you are having trouble with the environment variables, which is definitely the way to go. If you post more details I can help figure out the problem.

As an alternative, you can copy your dev config to a file called webpack-prod.config.js and add your production stuff there. Then run it using "build": "webpack --config webpack-prod.config.js"

Body:
I have a simplest possible React environment.
That is very efficient in development.

var webpack = require('webpack');

const config = {
  entry: "./index.js",
  output: { filename: "bundle.js" },
  devtool: 'eval',
module: {
   loaders: [
    {  test: /\.js$/, loader: 'babel-loader', exclude: /node_modules/, query: { presets: ['react', 'env'] }  }
   ]
  }
};

module.exports = config;

What I want to do is to add a production build so as to run in console script like this: npm run build, which is defined in package.json:

"build": "webpack --config webpack.config.js"

How can I add production plugins and devtool: "cheap-module-source-map" so that they will work only in production and were not included into development. By production plugins I meant these:

new webpack.DefinePlugin({ 'process.env.NODE_ENV': JSON.stringify('production') }),
new webpack.optimize.UglifyJsPlugin()

I failed to use

var debug = process.env.NODE_ENV !== "production";

with devtool: debug ? "cheap-module-source-map" : "eval",
and

plugins: debug ? [] : [//production plugins here ]


问:
access c multidemensional array with only one argument?
I am reading this C code, and I find it difficult to understand what's going on.

Here is the array:

```<code>static const char   gradient[32][4] =
{
{ 1,  1,  1,  0}, { 1,  1,  0,  1}, { 1,  0,  1,  1}, { 0,  1,  1,  1},
{ 1,  1, -1,  0}, { 1,  1,  0, -1}, { 1,  0,  1, -1}, { 0,  1,  1, -1},
{ 1, -1,  1,  0}, { 1, -1,  0,  1}, { 1,  0, -1,  1}, { 0,  1, -1,  1},
{ 1, -1, -1,  0}, { 1, -1,  0, -1}, { 1,  0, -1, -1}, { 0,  1, -1, -1},
{-1,  1,  1,  0}, {-1,  1,  0,  1}, {-1,  0,  1,  1}, { 0, -1,  1,  1},
{-1,  1, -1,  0}, {-1,  1,  0, -1}, {-1,  0,  1, -1}, { 0, -1,  1, -1},
{-1, -1,  1,  0}, {-1, -1,  0,  1}, {-1,  0, -1,  1}, { 0, -1, -1,  1},
{-1, -1, -1,  0}, {-1, -1,  0, -1}, {-1,  0, -1, -1}, { 0, -1, -1, -1},
};
</code>```

and it's 32*4, this is another part of the code that trying to access this array:

```<code>const char * g0000 = gradient[Indice (x1, y1, z1, t1)];
</code>```

Indice is a function that returns an int. So what is this g0000 (I know it's a pointer), say Indice returns 1, what is the value g0000 holds? I mostly code in C# to my understanding if you want to access multidimensional array you would need several arguments, but here is only one, I am really confused...

答:
The way a static multidimensional array is stored in memory as a 1D array (in C).

For example if you have the following array:

```<code>int ray[2][3] = {{1, 2, 3}, {4, 5, 6}};
</code>```

the memory allocation is exactly the same as in:

```<code>int ray[6] = {1, 2, 3, 4, 5, 6};
</code>```

This can be shown by the following snippet:

```<code>int ray[2][2] = {1, 2, 3, 4};
int *rayP = (int *) ray;
printf("%d\n", rayP[3]);     //PRINTS 4
</code>```

The reason that you can use multiple indices is just C making your life easier in using it as a 2D array abstraction.

So if you access the element ray[x][y] of an array ray[a][b], the element you actually access is ray[x * b + y], even though C won't let you do that to keep the abstraction clear.

Instead, if you try to access element ray[x] directly, it will return you &ray[x * b], which is exactly what you want here:

A pointer to the beginning of the desired sub-array, which you can treat as an array.

Body:
I am reading this C code, and I find it difficult to understand what's going on.

Here is the array:

static const char   gradient[32][4] =
{
{ 1,  1,  1,  0}, { 1,  1,  0,  1}, { 1,  0,  1,  1}, { 0,  1,  1,  1},
{ 1,  1, -1,  0}, { 1,  1,  0, -1}, { 1,  0,  1, -1}, { 0,  1,  1, -1},
{ 1, -1,  1,  0}, { 1, -1,  0,  1}, { 1,  0, -1,  1}, { 0,  1, -1,  1},
{ 1, -1, -1,  0}, { 1, -1,  0, -1}, { 1,  0, -1, -1}, { 0,  1, -1, -1},
{-1,  1,  1,  0}, {-1,  1,  0,  1}, {-1,  0,  1,  1}, { 0, -1,  1,  1},
{-1,  1, -1,  0}, {-1,  1,  0, -1}, {-1,  0,  1, -1}, { 0, -1,  1, -1},
{-1, -1,  1,  0}, {-1, -1,  0,  1}, {-1,  0, -1,  1}, { 0, -1, -1,  1},
{-1, -1, -1,  0}, {-1, -1,  0, -1}, {-1,  0, -1, -1}, { 0, -1, -1, -1},
};

and it's 32*4, this is another part of the code that trying to access this array:

const char * g0000 = gradient[Indice (x1, y1, z1, t1)];

Indice is a function that returns an int. So what is this g0000 (I know it's a pointer), say Indice returns 1, what is the value g0000 holds? I mostly code in C# to my understanding if you want to access multidimensional array you would need several arguments, but here is only one, I am really confused...

Body:
The way a static multidimensional array is stored in memory as a 1D array (in C).

For example if you have the following array:

int ray[2][3] = {{1, 2, 3}, {4, 5, 6}};

the memory allocation is exactly the same as in:

int ray[6] = {1, 2, 3, 4, 5, 6};

This can be shown by the following snippet:

int ray[2][2] = {1, 2, 3, 4};
int *rayP = (int *) ray;
printf("%d\n", rayP[3]);     //PRINTS 4

The reason that you can use multiple indices is just C making your life easier in using it as a 2D array abstraction.

So if you access the element ray[x][y] of an array ray[a][b], the element you actually access is ray[x * b + y], even though C won't let you do that to keep the abstraction clear.

Instead, if you try to access element ray[x] directly, it will return you &ray[x * b], which is exactly what you want here:

A pointer to the beginning of the desired sub-array, which you can treat as an array.


问:
Creating a bootstrap nav bar for a wordpress theme
i am trying to make my own word press theme. at the moment i can not get my nav bar to work properly with bootstrap. i am getting having trouble styling it from my style.css file and also when the site goes into a mobile version the button does not expand the navbar for the user to see.

this is my navigation bar in my header.php:

```<code><nav class="navbar navbar-expand-lg navbar-light bg-light">
      <a class="navbar-brand" href="#">Navbar</a>
      <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
        <span class="navbar-toggler-icon"></span>
      </button>
      <div class="collapse navbar-collapse" id="navbarNav">
        <?php /* Primary navigation */
    wp_nav_menu( array(
      'menu' => 'top_menu',
      'depth' => 2,
      'container' => false,
      'menu_class' => 'nav',
      //Process nav menu using our custom nav walker
      'walker' => new wp_bootstrap_navwalker())
    );
    ?>

      </div>
    </nav>
</code>```

This is the function i have in my functions.php:

```<code>// Register Nav Walker class_alias
require_once('wp_bootstrap_navwalker.php');

// Theme Support
function wpb_theme_setup(){
  add_theme_support('post-thumbnails');

  // Nav Menus
  register_nav_menus(array(
    'primary' => __('Primary Menu')
  ));

  // Post Formats
  add_theme_support('post-formats', array('aside', 'gallery'));
}

add_action('after_setup_theme','wpb_theme_setup');
</code>```

i have heard for drop down functionality i need to use the bootstrap nav walker and that is why it is there.

答:
function.php

```<code>register_nav_menus( array(
  'primary' => esc_html__( 'Primary', 'yourwebsite' ),
) );

require_once('wp_bootstrap_navwalker.php');
</code>```

header.php

```<code><header id="masthead" class="site-header" role="banner">
    <nav class="navbar navbar-default" role="navigation">
      <div class="container-fluid">
        <!-- Brand and toggle get grouped for better mobile display -->
        <div class="navbar-header">
          <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
            <span class="sr-only">Toggle navigation</span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
          </button>
          <a class="navbar-brand" href="<?php echo home_url(); ?>">
                    <?php bloginfo('name'); ?>
                </a>
        </div>

            <?php
                wp_nav_menu( array(
                    'menu'              => 'primary',
                    'theme_location'    => 'primary',
                    'depth'             => 2,
                    'container'         => 'div',
                    'container_class'   => 'collapse navbar-collapse',
            'container_id'      => 'bs-example-navbar-collapse-1',
                    'menu_class'        => 'nav navbar-nav',
                    'fallback_cb'       => 'wp_bootstrap_navwalker::fallback',
                    'walker'            => new wp_bootstrap_navwalker())
                );
            ?>
        </div>
    </nav>
</header>
</code>```

Body:
i am trying to make my own word press theme. at the moment i can not get my nav bar to work properly with bootstrap. i am getting having trouble styling it from my style.css file and also when the site goes into a mobile version the button does not expand the navbar for the user to see.

this is my navigation bar in my header.php:

      Navbar
      <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">

      </button>

        <?php /* Primary navigation */
    wp_nav_menu( array(
      'menu' => 'top_menu',
      'depth' => 2,
      'container' => false,
      'menu_class' => 'nav',
      //Process nav menu using our custom nav walker
      'walker' => new wp_bootstrap_navwalker())
    );
    ?>

This is the function i have in my functions.php:

// Register Nav Walker class_alias
require_once('wp_bootstrap_navwalker.php');

// Theme Support
function wpb_theme_setup(){
  add_theme_support('post-thumbnails');

  // Nav Menus
  register_nav_menus(array(
    'primary' => __('Primary Menu')
  ));

  // Post Formats
  add_theme_support('post-formats', array('aside', 'gallery'));
}

add_action('after_setup_theme','wpb_theme_setup');

i have heard for drop down functionality i need to use the bootstrap nav walker and that is why it is there.

Body:
function.php

register_nav_menus( array(
  'primary' => esc_html__( 'Primary', 'yourwebsite' ),
) );

require_once('wp_bootstrap_navwalker.php');

header.php

<header id="masthead" class="site-header" role="banner">
    <nav class="navbar navbar-default" role="navigation">
      <div class="container-fluid">
        <!-- Brand and toggle get grouped for better mobile display -->
        <div class="navbar-header">
          <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
            <span class="sr-only">Toggle navigation</span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
          </button>
          <a class="navbar-brand" href="<?php echo home_url(); ?>">
                    <?php bloginfo('name'); ?>
                </a>
        </div>

            <?php
                wp_nav_menu( array(
                    'menu'              => 'primary',
                    'theme_location'    => 'primary',
                    'depth'             => 2,
                    'container'         => 'div',
                    'container_class'   => 'collapse navbar-collapse',
            'container_id'      => 'bs-example-navbar-collapse-1',
                    'menu_class'        => 'nav navbar-nav',
                    'fallback_cb'       => 'wp_bootstrap_navwalker::fallback',
                    'walker'            => new wp_bootstrap_navwalker())
                );
            ?>
        </div>
    </nav>
</header>


问:
perl from user input of a number, add each digit

I am very new to perl and I am learning this is not like c++. So The user will enter a number of any length, and I want to add each digit and print the sum.

```<code>#!/usr/bin/perl -w
use strict;
use warnings;

print "Enter a number :";

my $num = <STDIN>;

my @array = $num;
my $sum=0;
for my $arr (@array){

    $sum += $arr;

print $sum;
}
</code>```

 For example the user enters 1234, the sum: 10

the actual result I get is 1234.

答:
You need to break the input string $num into separate digits. Try replacing my @array = $num with my @array = split //, $num. Read more by running perldoc -f split.

In Perl both strings and numbers are classified as SCALARs. A scalar is automatically treated as a number if arithmetic operations (like +) are done with them, so the summation inside the for loop works as expected.

Body:
I am very new to perl and I am learning this is not like c++. So The user will enter a number of any length, and I want to add each digit and print the sum.

#!/usr/bin/perl -w
use strict;
use warnings;

print "Enter a number :";

my $num = <STDIN>;

my @array = $num;
my $sum=0;
for my $arr (@array){

    $sum += $arr;

print $sum;
}

 For example the user enters 1234, the sum: 10

the actual result I get is 1234.


问:
Python. Detect changes in vector direction
I have a vector y that either increments or decrements by 1. What I want is to create a another vector y2 that shows when y1 changed direction.

I can't figure out how to do this in numpy.

EDIT updated plot, due to missing comma in y

```<code>import matplotlib.pyplot as plt
import numpy as np
</code>```

EDIT: Fixed missing comma in y

```<code>import matplotlib.pyplot as plt
import numpy as np

y = np.array([0,0,1,1,2,2,1,0,-1,-1,0,0,1])

x = np.arange(len(y))

y2 = np.array([0,0,1,0,0,0,-1,0,0,0,1,0,0])

plt.plot(x, y, label='y - Actual')
plt.plot(x, y2, label='y2 - Desired')
plt.legend()
plt.show()
</code>```

Body:
I have a vector y that either increments or decrements by 1. What I want is to create a another vector y2 that shows when y1 changed direction.

I can't figure out how to do this in numpy.

EDIT updated plot, due to missing comma in y

import matplotlib.pyplot as plt
import numpy as np

EDIT: Fixed missing comma in y

import matplotlib.pyplot as plt
import numpy as np

y = np.array([0,0,1,1,2,2,1,0,-1,-1,0,0,1])

x = np.arange(len(y))

y2 = np.array([0,0,1,0,0,0,-1,0,0,0,1,0,0])

plt.plot(x, y, label='y - Actual')
plt.plot(x, y2, label='y2 - Desired')
plt.legend()
plt.show()

Body:
Here's one way -

def detect_ups_downs(y):
    s0 = np.flatnonzero(y[1:] > y[:-1])+1
    s1 = np.flatnonzero(y[1:] < y[:-1])+1

    idx0 = np.searchsorted(s1,s0,'right')
    s0c = s0[np.r_[True,idx0[1:] > idx0[:-1]]]

    idx1 = np.searchsorted(s0c,s1,'right')
    s1c = s1[np.r_[True,idx1[1:] > idx1[:-1]]]

    out = np.zeros(len(y),dtype=int)
    out[s0c] = 1
    out[s1c] = -1
    return out

Sample run -

In [92]: y = np.array([0,0,1,2,3,4,1,0,-1-1,0,0,1,0,8,8,9,-4,-6,4,-2,2])

In [93]: np.c_[y, detect_ups_downs(y)]
Out[93]:
array([[ 0,  0],
       [ 0,  0],
       [ 1,  1],
       [ 2,  0],
       [ 3,  0],
       [ 4,  0],
       [ 1, -1],
       [ 0,  0],
       [-2,  0],
       [ 0,  1],
       [ 0,  0],
       [ 1,  0],
       [ 0, -1],
       [ 8,  1],
       [ 8,  0],
       [ 9,  0],
       [-4, -1],
       [-6,  0],
       [ 4,  1],
       [-2, -1],
       [ 2,  1]])


答:
Two methods :

You can do something with dict:

```<code>data='hello'

dict_1={}
for i,j in enumerate(data):
    if j not in dict_1:
        dict_1[j]=[(i,j)]
    else:
        dict_1[j].append((i,j))

for key,value in dict_1.items():
    if len(value)>1:
        print(value)
</code>```

output:

```<code>[(2, 'l'), (3, 'l')]
</code>```

second method using defaultdict:

```<code>import collections

d=collections.defaultdict(list)
for key1,value1 in enumerate(data):
    d[value1].append(key1)

print(d)

print([(key1,value1) for key1,value1 in d.items() if len(value1)>1])
</code>```

output:

```<code>[('l', [2, 3])]
</code>```

Title: Python How to specify which character to index if there are duplicates

Body:
Two methods :

You can do something with dict:

data='hello'

dict_1={}
for i,j in enumerate(data):
    if j not in dict_1:
        dict_1[j]=[(i,j)]
    else:
        dict_1[j].append((i,j))

for key,value in dict_1.items():
    if len(value)>1:
        print(value)

output:

[(2, 'l'), (3, 'l')]

second method using defaultdict:

import collections

d=collections.defaultdict(list)
for key1,value1 in enumerate(data):
    d[value1].append(key1)

print(d)

print([(key1,value1) for key1,value1 in d.items() if len(value1)>1])

output:

[('l', [2, 3])]


问:
How can I use threads in Java?
I use Thread in Java. I create a class that extend Thread and it's fine, but the problem is, when call this Thread, I don't know the number of instances of this class, since the user must enter this number.  For example:

```<code>multiThread multiThreadInstance = new multiThread(/* number entered from user */);
multiThreadInstance.start();
</code>```

This will call this thread once, but if i write:

```<code>multiThread multiThreadInstance1 = new multiThread(/* number entered from user */)
multiThreadInstance1.start()
multiThread multiThreadInstance2 = new multiThread(/* number entered from user */)
multiThreadInstance2.start()
</code>```

This will call it twice at the same time, and so on.

If I put it in a for loop, then if user enters 3 for example, then start1 runs, when start1 finishes, start2 runs, when start2 finishes, start3 runs.  I need to keep these instances of thread running in at the same time.  How can i do this?

答:
You need to use java high level concurrency utilities to do this. Look at countdownlatches and executors. The following is a code that would do what you want. I recommend you read up on java concurrency utilities.

```<code>import java.util.concurrent.*;

public class ConcurrentTimer {
    private ConcurrentTimer() { } // Noninstantiable

    public static long time(Executor executor, int concurrency,
            final Runnable action) throws InterruptedException {
        final CountDownLatch ready = new CountDownLatch(concurrency);
        final CountDownLatch start = new CountDownLatch(1);
        final CountDownLatch done = new CountDownLatch(concurrency);

        for (int i = 0; i < concurrency; i++) {
            executor.execute(new Runnable() {
                public void run() {
                    ready.countDown(); // Tell timer we're ready
                    try {
                        start.await(); // Wait till peers are ready
                        action.run();
                    } catch (InterruptedException e) {
                        Thread.currentThread().interrupt();
                    } finally {
                        done.countDown();  // Tell timer we're done
                    }
                }
            });
        }

        ready.await();     // Wait for all workers to be ready
        long startNanos = System.nanoTime();
        start.countDown(); // And they're off!
        done.await();      // Wait for all workers to finish
        return System.nanoTime() - startNanos;
    }
}
</code>```

A runnable version of the code example provided above: (Edited)

```<code>import java.util.concurrent.*;

public class ConcurrentTimer {

    public static void main(String[] args) {

        try {
            Runnable action = new Runnable() {
                    public void run() {

                        System.out.println("Thread Running");

                    }
                };

            time (3, action);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private ConcurrentTimer() { } // Noninstantiable

    public static long time(int concurrency,
            final Runnable action) throws InterruptedException {

        Executor executor = Executors.newFixedThreadPool(concurrency);

        final CountDownLatch ready = new CountDownLatch(concurrency);
        final CountDownLatch start = new CountDownLatch(1);
        final CountDownLatch done = new CountDownLatch(concurrency);

        for (int i = 0; i < concurrency; i++) {
            executor.execute(new Runnable() {
                public void run() {
                    ready.countDown(); // Tell timer we're ready
                    try {
                        start.await(); // Wait till peers are ready
                        action.run();
                    } catch (InterruptedException e) {
                        Thread.currentThread().interrupt();
                    } finally {
                        done.countDown();  // Tell timer we're done
                    }
                }
            });
        }

        ready.await();     // Wait for all workers to be ready
        long startNanos = System.nanoTime();
        start.countDown(); // And they're off!
        done.await();      // Wait for all workers to finish
        return System.nanoTime() - startNanos;
    }
}
</code>```

Title: How can I use threads in Java?

Body:
I use Thread in Java. I create a class that extend Thread and it's fine, but the problem is, when call this Thread, I don't know the number of instances of this class, since the user must enter this number.  For example:

multiThread multiThreadInstance = new multiThread(/* number entered from user */);
multiThreadInstance.start();

This will call this thread once, but if i write:

multiThread multiThreadInstance1 = new multiThread(/* number entered from user */)
multiThreadInstance1.start()
multiThread multiThreadInstance2 = new multiThread(/* number entered from user */)
multiThreadInstance2.start()

This will call it twice at the same time, and so on.

If I put it in a for loop, then if user enters 3 for example, then start1 runs, when start1 finishes, start2 runs, when start2 finishes, start3 runs.  I need to keep these instances of thread running in at the same time.  How can i do this?

Body:
You need to use java high level concurrency utilities to do this. Look at countdownlatches and executors. The following is a code that would do what you want. I recommend you read up on java concurrency utilities.

import java.util.concurrent.*;

public class ConcurrentTimer {
    private ConcurrentTimer() { } // Noninstantiable

    public static long time(Executor executor, int concurrency,
            final Runnable action) throws InterruptedException {
        final CountDownLatch ready = new CountDownLatch(concurrency);
        final CountDownLatch start = new CountDownLatch(1);
        final CountDownLatch done = new CountDownLatch(concurrency);

        for (int i = 0; i < concurrency; i++) {
            executor.execute(new Runnable() {
                public void run() {
                    ready.countDown(); // Tell timer we're ready
                    try {
                        start.await(); // Wait till peers are ready
                        action.run();
                    } catch (InterruptedException e) {
                        Thread.currentThread().interrupt();
                    } finally {
                        done.countDown();  // Tell timer we're done
                    }
                }
            });
        }

        ready.await();     // Wait for all workers to be ready
        long startNanos = System.nanoTime();
        start.countDown(); // And they're off!
        done.await();      // Wait for all workers to finish
        return System.nanoTime() - startNanos;
    }
}

A runnable version of the code example provided above: (Edited)

import java.util.concurrent.*;

public class ConcurrentTimer {

    public static void main(String[] args) {

        try {
            Runnable action = new Runnable() {
                    public void run() {

                        System.out.println("Thread Running");

                    }
                };

            time (3, action);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private ConcurrentTimer() { } // Noninstantiable

    public static long time(int concurrency,
            final Runnable action) throws InterruptedException {

        Executor executor = Executors.newFixedThreadPool(concurrency);

        final CountDownLatch ready = new CountDownLatch(concurrency);
        final CountDownLatch start = new CountDownLatch(1);
        final CountDownLatch done = new CountDownLatch(concurrency);

        for (int i = 0; i < concurrency; i++) {
            executor.execute(new Runnable() {
                public void run() {
                    ready.countDown(); // Tell timer we're ready
                    try {
                        start.await(); // Wait till peers are ready
                        action.run();
                    } catch (InterruptedException e) {
                        Thread.currentThread().interrupt();
                    } finally {
                        done.countDown();  // Tell timer we're done
                    }
                }
            });
        }

        ready.await();     // Wait for all workers to be ready
        long startNanos = System.nanoTime();
        start.countDown(); // And they're off!
        done.await();      // Wait for all workers to finish
        return System.nanoTime() - startNanos;
    }
}