问:
Uima Ruta Out of Memory issue in spark context
I'm running an UIMA application on apache spark. There are million of pages coming into batches to be processed by UIMA RUTA for calculation. But some time i'm facing out of memory exception.It throws exception sometime as it successfully process 2000 pages but some time fail on 500 pages.

Application Log

```<code>Caused by: java.lang.OutOfMemoryError: Java heap space
        at org.apache.uima.internal.util.IntArrayUtils.expand_size(IntArrayUtils.java:57)
        at org.apache.uima.internal.util.IntArrayUtils.ensure_size(IntArrayUtils.java:39)
        at org.apache.uima.cas.impl.Heap.grow(Heap.java:187)
        at org.apache.uima.cas.impl.Heap.add(Heap.java:241)
        at org.apache.uima.cas.impl.CASImpl.ll_createFS(CASImpl.java:2844)
        at org.apache.uima.cas.impl.CASImpl.createFS(CASImpl.java:489)
        at org.apache.uima.cas.impl.CASImpl.createAnnotation(CASImpl.java:3837)
        at org.apache.uima.ruta.rule.RuleMatch.getMatchedAnnotations(RuleMatch.java:172)
        at org.apache.uima.ruta.rule.RuleMatch.getMatchedAnnotationsOf(RuleMatch.java:68)
        at org.apache.uima.ruta.rule.RuleMatch.getLastMatchedAnnotation(RuleMatch.java:73)
        at org.apache.uima.ruta.rule.ComposedRuleElement.mergeDisjunctiveRuleMatches(ComposedRuleElement.java:330)
        at org.apache.uima.ruta.rule.ComposedRuleElement.continueMatch(ComposedRuleElement.java:213)
        at org.apache.uima.ruta.rule.ComposedRuleElement.continueOwnMatch(ComposedRuleElement.java:362)
        at org.apache.uima.ruta.rule.ComposedRuleElement.fallbackContinue(ComposedRuleElement.java:459)
        at org.apache.uima.ruta.rule.ComposedRuleElement.continueMatch(ComposedRuleElement.java:225)
        at org.apache.uima.ruta.rule.ComposedRuleElement.continueOwnMatch(ComposedRuleElement.java:362)
        at org.apache.uima.ruta.rule.ComposedRuleElement.fallbackContinue(ComposedRuleElement.java:459)
        at org.apache.uima.ruta.rule.ComposedRuleElement.continueMatch(ComposedRuleElement.java:225)
        at org.apache.uima.ruta.rule.ComposedRuleElement.continueOwnMatch(ComposedRuleElement.java:362)
        at org.apache.uima.ruta.rule.ComposedRuleElement.fallbackContinue(ComposedRuleElement.java:459)
        at org.apache.uima.ruta.rule.ComposedRuleElement.continueMatch(ComposedRuleElement.java:225)
        at org.apache.uima.ruta.rule.ComposedRuleElement.continueOwnMatch(ComposedRuleElement.java:362)
        at org.apache.uima.ruta.rule.ComposedRuleElement.fallbackContinue(ComposedRuleElement.java:459)
        at org.apache.uima.ruta.rule.ComposedRuleElement.continueMatch(ComposedRuleElement.java:225)
        at org.apache.uima.ruta.rule.ComposedRuleElement.continueOwnMatch(ComposedRuleElement.java:362)
        at org.apache.uima.ruta.rule.ComposedRuleElement.fallbackContinue(ComposedRuleElement.java:459)
        at org.apache.uima.ruta.rule.ComposedRuleElement.continueMatch(ComposedRuleElement.java:225)
        at org.apache.uima.ruta.rule.ComposedRuleElement.continueOwnMatch(ComposedRuleElement.java:362)
        at org.apache.uima.ruta.rule.ComposedRuleElement.fallbackContinue(ComposedRuleElement.java:459)
        at org.apache.uima.ruta.rule.ComposedRuleElement.continueMatch(ComposedRuleElement.java:225)
        at org.apache.uima.ruta.rule.ComposedRuleElement.continueOwnMatch(ComposedRuleElement.java:362)
        at org.apache.uima.ruta.rule.ComposedRuleElement.fallbackContinue(ComposedRuleElement.java:459)
</code>```

UIMA RUTA SCRIPT

```<code>WORDLIST EnglishStopWordList = 'stopWords.txt';
WORDLIST FiltersList = 'AnchorFilters.txt';
DECLARE Filters, EnglishStopWords;
DECLARE Anchors, SpanStart,SpanClose;

DocumentAnnotation{-> ADDRETAINTYPE(MARKUP)};

DocumentAnnotation{-> MARKFAST(Filters, FiltersList)};

STRING MixCharacterRegex = "[0-9]+[a-zA-Z]+";

DocumentAnnotation{-> MARKFAST(EnglishStopWords, EnglishStopWordList,true)};
(SW | CW | CAP ) { -> MARK(Anchors, 1, 2)};
Anchors{CONTAINS(EnglishStopWords) -> UNMARK(Anchors)};

(SPECIAL{REGEXP("['\"-=()\\[\\]]")}| PM) (SW | CW | CAP ) (SPECIAL{REGEXP("['\"-=()\\[\\]]")}| PM) EnglishStopWords? { -> MARK(Anchors, 1, 4)};
(SPECIAL{REGEXP("['\"-=()\\[\\]]")}| PM)? (SW | CW | CAP ) (SPECIAL{REGEXP("['\"-=()\\[\\]]")}| PM) EnglishStopWords? { -> MARK(Anchors, 1, 4)};
(SPECIAL{REGEXP("['\"-=()\\[\\]]")}| PM) (SW | CW | CAP ) (SPECIAL{REGEXP("['\"-=()\\[\\]]")}| PM)? EnglishStopWords? { -> MARK(Anchors, 1, 4)};
(SW | CW | CAP ) (SPECIAL{REGEXP("['\"-=()\\[\\]]")}| PM) EnglishStopWords? { -> MARK(Anchors, 1, 3)};

Anchors{CONTAINS(MARKUP) -> UNMARK(Anchors)};
MixCharacterRegex -> Anchors;

"<Value>"  -> SpanStart;
"</Value>" -> SpanClose;

Anchors{-> CREATE(ExtractedData, "type" = "ANCHOR", "value" = Anchors)};

SpanStart Filters? SPACE? ExtractedData SPACE? Filters? SpanClose{-> GATHER(Data, 2, 6, "ExtractedData" = 4)};
</code>```

答:
Normally, the reasons for high memory usage in UIMA Ruta can be found in RutaBasic (many annotation, coverage information) or in RuleMatch (inefficient rules, many rule element matches).

This your example, the problem seems to origin somewhere else. The stacktrace indicates that the memory is used up by some disjunctive rule element, which requires to create new annotations for storing the match information.

It seems that the version of UIMA Ruta is rather old since line number do not match at all with the source I am looking at.

There are seven (!!!) calls of continueOwnMatch in the stacktrace. I was looking for a rule that could cause something like this but found none. This could be a old flaw which has been fixed in newer versions, or some preprocessing added additional CW/SW/CAP annotations.

As a first advice, I would suggest two things:

Update to UIMA Ruta 2.6.0

Get rid of all disjunctive rule elements

The disjunctive rule elements are not really needed in your script. In general, they should not used at all if not really required. I do not use them at all in productive rules.

Instead of (SW | CW | CAP ) you can simply write W.

Instead of (SPECIAL{REGEXP("['\"-=()\\[\\]]")}| PM) you can write ANY{OR(REGEXP("['\"-=()\\[\\]]"),IS(PM))}.

Using ANY as a matching condition can reduce the runtime performance. In this example, two rules instead of the rule lement rewrite might be better, e.g., something like

```<code>SPECIAL{REGEXP("['\"-=()\\[\\]]")} W ANY?{OR(REGEXP("['\"-=()\\[\\]]"),IS(PM))} EnglishStopWords? { -> MARK(Anchors, 1, 4)};
PM W ANY?{OR(REGEXP("['\"-=()\\[\\]]"),IS(PM))} EnglishStopWords? { -> MARK(Anchors, 1, 4)};
</code>```

(optional rule elements at the start of a rule without any anchors in the rule are not optional)

btw, there is a lot of room for optimization in your rules. If I had to guess, I'd say you can get rid at least of half the rules and 90% of all created annotations, which would also considerably reduce the memory usage.

DISCLAIMER: I am a developer of UIMA Ruta

Body:
I'm running an UIMA application on apache spark. There are million of pages coming into batches to be processed by UIMA RUTA for calculation. But some time i'm facing out of memory exception.It throws exception sometime as it successfully process 2000 pages but some time fail on 500 pages.

Application Log

Caused by: java.lang.OutOfMemoryError: Java heap space
        at org.apache.uima.internal.util.IntArrayUtils.expand_size(IntArrayUtils.java:57)
        at org.apache.uima.internal.util.IntArrayUtils.ensure_size(IntArrayUtils.java:39)
        at org.apache.uima.cas.impl.Heap.grow(Heap.java:187)
        at org.apache.uima.cas.impl.Heap.add(Heap.java:241)
        at org.apache.uima.cas.impl.CASImpl.ll_createFS(CASImpl.java:2844)
        at org.apache.uima.cas.impl.CASImpl.createFS(CASImpl.java:489)
        at org.apache.uima.cas.impl.CASImpl.createAnnotation(CASImpl.java:3837)
        at org.apache.uima.ruta.rule.RuleMatch.getMatchedAnnotations(RuleMatch.java:172)
        at org.apache.uima.ruta.rule.RuleMatch.getMatchedAnnotationsOf(RuleMatch.java:68)
        at org.apache.uima.ruta.rule.RuleMatch.getLastMatchedAnnotation(RuleMatch.java:73)
        at org.apache.uima.ruta.rule.ComposedRuleElement.mergeDisjunctiveRuleMatches(ComposedRuleElement.java:330)
        at org.apache.uima.ruta.rule.ComposedRuleElement.continueMatch(ComposedRuleElement.java:213)
        at org.apache.uima.ruta.rule.ComposedRuleElement.continueOwnMatch(ComposedRuleElement.java:362)
        at org.apache.uima.ruta.rule.ComposedRuleElement.fallbackContinue(ComposedRuleElement.java:459)
        at org.apache.uima.ruta.rule.ComposedRuleElement.continueMatch(ComposedRuleElement.java:225)
        at org.apache.uima.ruta.rule.ComposedRuleElement.continueOwnMatch(ComposedRuleElement.java:362)
        at org.apache.uima.ruta.rule.ComposedRuleElement.fallbackContinue(ComposedRuleElement.java:459)
        at org.apache.uima.ruta.rule.ComposedRuleElement.continueMatch(ComposedRuleElement.java:225)
        at org.apache.uima.ruta.rule.ComposedRuleElement.continueOwnMatch(ComposedRuleElement.java:362)
        at org.apache.uima.ruta.rule.ComposedRuleElement.fallbackContinue(ComposedRuleElement.java:459)
        at org.apache.uima.ruta.rule.ComposedRuleElement.continueMatch(ComposedRuleElement.java:225)
        at org.apache.uima.ruta.rule.ComposedRuleElement.continueOwnMatch(ComposedRuleElement.java:362)
        at org.apache.uima.ruta.rule.ComposedRuleElement.fallbackContinue(ComposedRuleElement.java:459)
        at org.apache.uima.ruta.rule.ComposedRuleElement.continueMatch(ComposedRuleElement.java:225)
        at org.apache.uima.ruta.rule.ComposedRuleElement.continueOwnMatch(ComposedRuleElement.java:362)
        at org.apache.uima.ruta.rule.ComposedRuleElement.fallbackContinue(ComposedRuleElement.java:459)
        at org.apache.uima.ruta.rule.ComposedRuleElement.continueMatch(ComposedRuleElement.java:225)
        at org.apache.uima.ruta.rule.ComposedRuleElement.continueOwnMatch(ComposedRuleElement.java:362)
        at org.apache.uima.ruta.rule.ComposedRuleElement.fallbackContinue(ComposedRuleElement.java:459)
        at org.apache.uima.ruta.rule.ComposedRuleElement.continueMatch(ComposedRuleElement.java:225)
        at org.apache.uima.ruta.rule.ComposedRuleElement.continueOwnMatch(ComposedRuleElement.java:362)
        at org.apache.uima.ruta.rule.ComposedRuleElement.fallbackContinue(ComposedRuleElement.java:459)

UIMA RUTA SCRIPT

WORDLIST EnglishStopWordList = 'stopWords.txt';
WORDLIST FiltersList = 'AnchorFilters.txt';
DECLARE Filters, EnglishStopWords;
DECLARE Anchors, SpanStart,SpanClose;

DocumentAnnotation{-> ADDRETAINTYPE(MARKUP)};

DocumentAnnotation{-> MARKFAST(Filters, FiltersList)};

STRING MixCharacterRegex = "[0-9]+[a-zA-Z]+";

DocumentAnnotation{-> MARKFAST(EnglishStopWords, EnglishStopWordList,true)};
(SW | CW | CAP ) { -> MARK(Anchors, 1, 2)};
Anchors{CONTAINS(EnglishStopWords) -> UNMARK(Anchors)};

(SPECIAL{REGEXP("['\"-=()\\[\\]]")}| PM) (SW | CW | CAP ) (SPECIAL{REGEXP("['\"-=()\\[\\]]")}| PM) EnglishStopWords? { -> MARK(Anchors, 1, 4)};
(SPECIAL{REGEXP("['\"-=()\\[\\]]")}| PM)? (SW | CW | CAP ) (SPECIAL{REGEXP("['\"-=()\\[\\]]")}| PM) EnglishStopWords? { -> MARK(Anchors, 1, 4)};
(SPECIAL{REGEXP("['\"-=()\\[\\]]")}| PM) (SW | CW | CAP ) (SPECIAL{REGEXP("['\"-=()\\[\\]]")}| PM)? EnglishStopWords? { -> MARK(Anchors, 1, 4)};
(SW | CW | CAP ) (SPECIAL{REGEXP("['\"-=()\\[\\]]")}| PM) EnglishStopWords? { -> MARK(Anchors, 1, 3)};

Anchors{CONTAINS(MARKUP) -> UNMARK(Anchors)};
MixCharacterRegex -> Anchors;

"<Value>"  -> SpanStart;
"</Value>" -> SpanClose;

Anchors{-> CREATE(ExtractedData, "type" = "ANCHOR", "value" = Anchors)};

SpanStart Filters? SPACE? ExtractedData SPACE? Filters? SpanClose{-> GATHER(Data, 2, 6, "ExtractedData" = 4)};

Body:
Normally, the reasons for high memory usage in UIMA Ruta can be found in RutaBasic (many annotation, coverage information) or in RuleMatch (inefficient rules, many rule element matches).

This your example, the problem seems to origin somewhere else. The stacktrace indicates that the memory is used up by some disjunctive rule element, which requires to create new annotations for storing the match information.

It seems that the version of UIMA Ruta is rather old since line number do not match at all with the source I am looking at.

There are seven (!!!) calls of continueOwnMatch in the stacktrace. I was looking for a rule that could cause something like this but found none. This could be a old flaw which has been fixed in newer versions, or some preprocessing added additional CW/SW/CAP annotations.

As a first advice, I would suggest two things:

Update to UIMA Ruta 2.6.0

Get rid of all disjunctive rule elements

The disjunctive rule elements are not really needed in your script. In general, they should not used at all if not really required. I do not use them at all in productive rules.

Instead of (SW | CW | CAP ) you can simply write W.

Instead of (SPECIAL{REGEXP("['\"-=()\\[\\]]")}| PM) you can write ANY{OR(REGEXP("['\"-=()\\[\\]]"),IS(PM))}.

Using ANY as a matching condition can reduce the runtime performance. In this example, two rules instead of the rule lement rewrite might be better, e.g., something like

SPECIAL{REGEXP("['\"-=()\\[\\]]")} W ANY?{OR(REGEXP("['\"-=()\\[\\]]"),IS(PM))} EnglishStopWords? { -> MARK(Anchors, 1, 4)};
PM W ANY?{OR(REGEXP("['\"-=()\\[\\]]"),IS(PM))} EnglishStopWords? { -> MARK(Anchors, 1, 4)};

(optional rule elements at the start of a rule without any anchors in the rule are not optional)

btw, there is a lot of room for optimization in your rules. If I had to guess, I'd say you can get rid at least of half the rules and 90% of all created annotations, which would also considerably reduce the memory usage.

DISCLAIMER: I am a developer of UIMA Ruta


来源: stackexchange

问:
How to run ASP.NET Core on arm-based custom linux?
I want to build an ASP.NET Core Web API service to run on an arm (cortex-A7) device with an angstrom based linux.

Question: What is the best route to follow?

Compile CoreClr, CoreFx, and what-not for the arm7 device (could be possible, but I'm not sure about the angstrom linux). If that works, published bytecode should run on that device.

cross-compile my aspnet app using dotnet native and target arm. I couldn't find useful infos but it could be possible.

Something else? Like generate C++ code from my project?

Compile a different linux distro for the device (probably a no-go since we need IPC between the Linux Cortex-A7 CPU and the FreeRTOS Cotex-M4 CPU).

My main concern is the angstrom distribution, which is not supported by dotnet core out of the box. Any advice is welcome!

Edit, Open Questions:

Where can I download the correct pre-built dotnet binaries for an Cortex-A7 (I could not get https://github.com/dotnet/core-setup to work)?

What other prerequisites do I need (if any)?

答:
First, forget about angstrom. You will not get any of the native dependencies from that distro or its package manager. Neither will you find any useful resources for angstrom.

Instead, use yocto to build your own OpenEmbedded Core linux distro and add native dependencies during the build. At the time of writing, this can be managed with the meta-aspnet layer from Tragetaschen. The readme.md states mono as a requirement, which is not true (anymore?).

Once the native dependencies (libunwind, libicu, and many more) are available on the arm system, you can download the latest Linux (armhf) (for glibc based OS) build from https://github.com/dotnet/core-setup, unpack it into /opt/dotnet/, and create a symlink via ln -s /opt/dotnet/dotnet /usr/bin/. This is the OP's solution number 1 and generic bytecode projects (just dotnet publish) will work fine.

If you don't like to install dotnet on the target machine, you can compile for -r linux-arm (Martin Ulrich's suggestion), which produces a huge publish folder including coreclr and corefx. However, installing dotnet on the target machine is the smallest of all problems and separating your app from dotnet coreclr/fx/host is cleaner (imho).

The key problems are

Which dependencies are required? There is no clear answer, yet.

How to compile them for your machine?

The meta-aspnet layer seems to solve both problems (at the time of writing). You'll have to dig into it for more details or just use it as is.

ContentLicense: CC BY-SA 3.0


问:
How to make the java wait for x seconds and then execute
I making an app and I would run in to a problem that I can't fix.
I am using Android Studio and I need to make a Button that I have already made. Do more then it already does. I want it to after display a text also close the app. Do you know how I should program that. It would be very helpful. Thanks in advance.

Here is the Java code:

```<code>package test.myapplication;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}

public void buttonOnClick(View v) {
    Button button=(Button) v;
    ((Button) v).setText("Correct");
}

public void buttonAnClick(View q) {
    Button button=(Button) q;
    ((Button) q).setText("Niet goed");
}
</code>```

}

So I have already made the button in XML and told it:

android:onClick="buttonOnClick"

Hope you can help me out!

答:
If you want to pause then use java.util.concurrent.TimeUnit.

For example:

```<code>TimeUnit.SECONDS.sleep(1);
</code>```

Body:
I making an app and I would run in to a problem that I can't fix.
I am using Android Studio and I need to make a Button that I have already made. Do more then it already does. I want it to after display a text also close the app. Do you know how I should program that. It would be very helpful. Thanks in advance.

Here is the Java code:

package test.myapplication;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}

public void buttonOnClick(View v) {
    Button button=(Button) v;
    ((Button) v).setText("Correct");
}

public void buttonAnClick(View q) {
    Button button=(Button) q;
    ((Button) q).setText("Niet goed");
}

}

So I have already made the button in XML and told it:

android:onClick="buttonOnClick"

Hope you can help me out!

Body:
If you want to pause then use java.util.concurrent.TimeUnit.

For example:

TimeUnit.SECONDS.sleep(1);


问:
How to format axis number format to thousands with a comma
How can I change the format of the numbers in the x-axis to be like 10,000 instead of 10000?
Ideally, I would just like to do something like this:

```<code>x = format((10000.21, 22000.32, 10120.54), "#,###")
</code>```

Here is the code:

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

# create figure instance
fig1 = plt.figure(1)
fig1.set_figheight(15)
fig1.set_figwidth(20)

ax = fig1.add_subplot(2,1,1)

x = 10000.21, 22000.32, 10120.54

y = 1, 4, 15
ax.plot(x, y)

ax2 = fig1.add_subplot(2,1,2)

x2 = 10434, 24444, 31234
y2 = 1, 4, 9
ax2.plot(x2, y2)

fig1.show()
</code>```

答:
I always find myself on this same page everytime I try to do this. Sure, the other answers get the job done, but aren't easy to remember for next time! ex: import ticker and use lambda, custom def, etc.

Here's a simple solution if you have an axes named ax:

```<code>ax.set_yticklabels(['{:,}'.format(int(x)) for x in ax.get_yticks().tolist()])
</code>```

ContentLicense: CC BY-SA 4.0

Body:
How can I change the format of the numbers in the x-axis to be like 10,000 instead of 10000?
Ideally, I would just like to do something like this:

x = format((10000.21, 22000.32, 10120.54), "#,###")

Here is the code:

import matplotlib.pyplot as plt

# create figure instance
fig1 = plt.figure(1)
fig1.set_figheight(15)
fig1.set_figwidth(20)

ax = fig1.add_subplot(2,1,1)

x = 10000.21, 22000.32, 10120.54

y = 1, 4, 15
ax.plot(x, y)

ax2 = fig1.add_subplot(2,1,2)

x2 = 10434, 24444, 31234
y2 = 1, 4, 9
ax2.plot(x2, y2)

fig1.show()

Body:
I always find myself on this same page everytime I try to do this. Sure, the other answers get the job done, but aren't easy to remember for next time! ex: import ticker and use lambda, custom def, etc.

Here's a simple solution if you have an axes named ax:

ax.set_yticklabels(['{:,}'.format(int(x)) for x in ax.get_yticks().tolist()])


问:
Replacing items in list with multiple "keys" in one index
I am trying to change my list items to their actual values.  For example, this is how my data looks right now:

```<code>data = [
['student1', '"answer 1"', '"answer 2"', '"answer 3"'],
['student2', '"answer 10"', '"answer 2"', '"answer 3", "answer 4"']
</code>```

As seen in the last item in data[1], there can be multiple responses to a singular question.  My code right now is this:

```<code>def answer_replace(data):
    replaced_data = []
    for element in data:
        replaced_element = []
        for index, item in enumerate(element):
            print (index)
            print (item)
            if index in answer_replacement:
                replaced_element.append(answer_replacement[index].get(item, item))
            else:  # no replacement available for this index
                replaced_element.append(item)
            print (replaced_element)
        replaced_data.append(replaced_element)
    return replaced_data
</code>```

It works fine except for the cases with multiple answers.  I was trying to use re.sub, but couldn't get it to work. (The answers I want to change the values to are stored in the dictionary answer_replacement)

答:
I believe you want to remove "answer" from the student's response. You can try this:

```<code>data = [ ['student1', "answer 1", "answer 2", "answer 3"], ['student2', "answer 10", "answer 2", "answer 3", "answer 4"]]

student_data = {i[0]:[b.replace("answer", "replacement") for b in i[1:]] for i in data}
</code>```

Output:

```<code>{'student2': ['replacement 10', 'replacement 2', 'replacement 3', 'replacement 4'], 'student1': ['replacement 1', 'replacement 2', 'replacement 3']}
</code>```

Body:
I am trying to change my list items to their actual values.  For example, this is how my data looks right now:

data = [
['student1', '"answer 1"', '"answer 2"', '"answer 3"'],
['student2', '"answer 10"', '"answer 2"', '"answer 3", "answer 4"']

As seen in the last item in data[1], there can be multiple responses to a singular question.  My code right now is this:

def answer_replace(data):
    replaced_data = []
    for element in data:
        replaced_element = []
        for index, item in enumerate(element):
            print (index)
            print (item)
            if index in answer_replacement:
                replaced_element.append(answer_replacement[index].get(item, item))
            else:  # no replacement available for this index
                replaced_element.append(item)
            print (replaced_element)
        replaced_data.append(replaced_element)
    return replaced_data

It works fine except for the cases with multiple answers.  I was trying to use re.sub, but couldn't get it to work. (The answers I want to change the values to are stored in the dictionary answer_replacement)

Body:
I believe you want to remove "answer" from the student's response. You can try this:

data = [ ['student1', "answer 1", "answer 2", "answer 3"], ['student2', "answer 10", "answer 2", "answer 3", "answer 4"]]

student_data = {i[0]:[b.replace("answer", "replacement") for b in i[1:]] for i in data}

Output:

{'student2': ['replacement 10', 'replacement 2', 'replacement 3', 'replacement 4'], 'student1': ['replacement 1', 'replacement 2', 'replacement 3']}


问:
Unable to show profile in view ASP.NET MVC
Since i am new to asp.net mvc
Getting this error
I want to show Profile to user in View
"The name 'o' does not exist in the current context"

View

```<code>@model Test.Models.Customer

          Name:  @o.CST_Name
          Email:  @o.CST_Email
          Gender:  @o.CST_Gender
</code>```

Controller

```<code>public ActionResult ViewProfileCustomer(string id)
        {
            var user = db.Customers.Single(u => u.CST_Username == id);

            return View(user);
        }
</code>```

It shows this error Pic

答:
That error shows up when View is trying to access property on NULL object, so 'no object' = 'no property'. Make sure that user object has some data in after Action call, but this code should display view content anyway.

Controller

```<code>public ActionResult ViewProfileCustomer(string id)
{
   var user = db.Customer.FirstOrDefault(u => u.CST_Username == id);

   return View(user);
}
</code>```

View
@model Test.Models.Customer

```<code>  Name:  @Html.DisplayFor(model => model.CST_Name)
  Email:  @Html.DisplayFor(model => model..CST_Email
  Gender:  @Html.DisplayFor(model => model..CST_Gender)
</code>```

Body:
Since i am new to asp.net mvc
Getting this error
I want to show Profile to user in View
"The name 'o' does not exist in the current context"

View

@model Test.Models.Customer

          Name:  @o.CST_Name
          Email:  @o.CST_Email
          Gender:  @o.CST_Gender

Controller

public ActionResult ViewProfileCustomer(string id)
        {
            var user = db.Customers.Single(u => u.CST_Username == id);

            return View(user);
        }

It shows this error Pic

Body:
That error shows up when View is trying to access property on NULL object, so 'no object' = 'no property'. Make sure that user object has some data in after Action call, but this code should display view content anyway.

Controller

public ActionResult ViewProfileCustomer(string id)
{
   var user = db.Customer.FirstOrDefault(u => u.CST_Username == id);

   return View(user);
}

View
@model Test.Models.Customer

  Name:  @Html.DisplayFor(model => model.CST_Name)
  Email:  @Html.DisplayFor(model => model..CST_Email
  Gender:  @Html.DisplayFor(model => model..CST_Gender)


问:
ASP.NET Core display Action route parameter through AngularJS on page load
Put simply, I'm trying to have it so that an ID, if passed as an additional Action parameter, can be caught by Angular, or passed in as a variable.

As an example, if my Routing was set up as template: "{action}/{id?}", then someone visiting:

localhost/Waitlist/SpringBash

(where Waitlist is the action and SpringBash is the id)

Could reach a page that says:

```<code>You're viewing the SpringBash event!

Event1 Name Date
Event2 Name Date
Event3 Name Date
</code>```

I'm handling all of my routes through ASP.Net Core's MapRoute and the Startup class, and don't intend on converting to an AngularJS routing system.

That said, here's the relevant code I have in Startup.cs:

```<code>routes.MapRoute(
    name: "root",
    template: "{action}/{id?}",
    defaults: new { controller = "Home", action = "Index" } );
</code>```

My HomeController.cs has this ready for a particular page:

```<code>public IActionResult Waitlist(string eventName)
{
    return View(_context.Waitlist.Where(a => a.Event.Equals(eventName)));
}
</code>```

Under Views -> Home, I have my Waitlist.cshtml:

```<code>@section Scripts {
    <script src="~/js/waitlistController.js"></script>
}

<div ng-controller="waitlistController"></div>
</code>```

And in my waitlistController.js, I have:

```<code>wddApp.controller('urlsController', function ($scope, $http) {
    // I don't know what to put here to have access to the {id} parameter of the URL
});
</code>```

Can anyone help me out?

答:
Could you use window.location.href?

https://plnkr.co/edit/z9yRTfYI1nDY5feloDzi?p=preview

```<code>wddApp.controller('urlsController', function ($scope, $http, $location) {
    // I don't know what to put here to have access to the {id} parameter of the URL

    var parts = window.location.href.split('/');

    // TODO: probably grab the last one; it's blank for this plunker so
    // grabbing the second to last one, instead
    $scope.id = parts[parts.length - 2];
});
</code>```

Body:
Put simply, I'm trying to have it so that an ID, if passed as an additional Action parameter, can be caught by Angular, or passed in as a variable.

As an example, if my Routing was set up as template: "{action}/{id?}", then someone visiting:

localhost/Waitlist/SpringBash

(where Waitlist is the action and SpringBash is the id)

Could reach a page that says:

You're viewing the SpringBash event!

Event1 Name Date
Event2 Name Date
Event3 Name Date

I'm handling all of my routes through ASP.Net Core's MapRoute and the Startup class, and don't intend on converting to an AngularJS routing system.

That said, here's the relevant code I have in Startup.cs:

routes.MapRoute(
    name: "root",
    template: "{action}/{id?}",
    defaults: new { controller = "Home", action = "Index" } );

My HomeController.cs has this ready for a particular page:

public IActionResult Waitlist(string eventName)
{
    return View(_context.Waitlist.Where(a => a.Event.Equals(eventName)));
}

Under Views -> Home, I have my Waitlist.cshtml:

@section Scripts {

}

And in my waitlistController.js, I have:

wddApp.controller('urlsController', function ($scope, $http) {
    // I don't know what to put here to have access to the {id} parameter of the URL
});

Can anyone help me out?

Body:
Could you use window.location.href?

https://plnkr.co/edit/z9yRTfYI1nDY5feloDzi?p=preview

wddApp.controller('urlsController', function ($scope, $http, $location) {
    // I don't know what to put here to have access to the {id} parameter of the URL

    var parts = window.location.href.split('/');

    // TODO: probably grab the last one; it's blank for this plunker so
    // grabbing the second to last one, instead
    $scope.id = parts[parts.length - 2];
});


答:
If you are trying to get something done with a delay when a button is pressed then do it something like this:</p>

```<code>public void buttonOnClick(View v) {
    Button button=(Button) v;
    button.setText("Correct");
    button.postDelayed(new Runnable(){
       public void run() {
           //runs after 1 second delay on UI thread
       }
    }, 1000L);
}
</code>```

Title: How to make the java wait for x seconds and then execute

Body:
If you are trying to get something done with a delay when a button is pressed then do it something like this:

public void buttonOnClick(View v) {
    Button button=(Button) v;
    button.setText("Correct");
    button.postDelayed(new Runnable(){
       public void run() {
           //runs after 1 second delay on UI thread
       }
    }, 1000L);
}


问:
Data structure for looking up values based on keys being in a range
I'm looking for an alternative to a dictionary that will allow me to efficiently use ranges as keys. Presumably the data structure needs to be sorted - maybe something like a b tree? I haven't found a good python implementation.

For example, given the following dictionary-like data structure:

d = {'38.1003827193': 'value1', '58.29932891733': 'value2'}

Searching for the range 38 -> 38.337 should return value1

答:
Not sure if this is what you meant, but I think this is what you meant:

```<code>d = {'38.1003827193': 'value1', '58.29932891733': 'value2'}
d_keys = list(d.keys())

bound_names = ["lower bound", "upper bound"]
bounds = []
for i in range (0, 2):
    while True:
        try:
            bound = float(input("Enter the {} number: ".format(bound_names[i])))
        except ValueError:
            print("Number not entered.")
            continue
        else:
            break
    bounds.append(bound)

for n in range(len(d_keys)):
    if bounds[0] <= d_keys[n] <= bounds[1]:
        print(d[d_keys[n]])
</code>```

If 38 (lower bound) and 38.3 (upper bound) are entered value1 is printed.

Alternatively you can have search for numbers based on the part before the decimal:

```<code>d = {'38.1003827193': 'value1', '58.29932891733': 'value2'}
d_keys = list(d.keys())

bound_names = [["lower bound", "inclusive"], ["upper bound", "exclusive"]]
bounds = []
for n in range(0, 2):
    while True:
        try:
            number_to_search = int(input("Enter {} number ({}): ".format(bound_names[n][0], bound_names[n][1])))
        except ValueError:
            print("Integer not entered.")
            continue
        else:
            break
    bounds.append(number_to_search)

for n in range(len(d_keys)):
    if int(d_keys[n]) in range(bounds[0], bounds[1]):
        print(d[d_keys[n]])
</code>```

When 37 (lower bound) and 39 (upper bound) are entered the code prints: value1, but when 38 is entered as upper bound value1 is not printed.

If you dont want it to print you can  have it return a list of all the values that are that number.
All you would have to do is change the print(d[d_keys[n]]) to numbers_in_range.append(d[d_keys[n]]) and adding numbers_in_range = [] somewhere above.

Body:
Not sure if this is what you meant, but I think this is what you meant:

d = {'38.1003827193': 'value1', '58.29932891733': 'value2'}
d_keys = list(d.keys())

bound_names = ["lower bound", "upper bound"]
bounds = []
for i in range (0, 2):
    while True:
        try:
            bound = float(input("Enter the {} number: ".format(bound_names[i])))
        except ValueError:
            print("Number not entered.")
            continue
        else:
            break
    bounds.append(bound)

for n in range(len(d_keys)):
    if bounds[0] <= d_keys[n] <= bounds[1]:
        print(d[d_keys[n]])

If 38 (lower bound) and 38.3 (upper bound) are entered value1 is printed.

Alternatively you can have search for numbers based on the part before the decimal:

d = {'38.1003827193': 'value1', '58.29932891733': 'value2'}
d_keys = list(d.keys())

bound_names = [["lower bound", "inclusive"], ["upper bound", "exclusive"]]
bounds = []
for n in range(0, 2):
    while True:
        try:
            number_to_search = int(input("Enter {} number ({}): ".format(bound_names[n][0], bound_names[n][1])))
        except ValueError:
            print("Integer not entered.")
            continue
        else:
            break
    bounds.append(number_to_search)

for n in range(len(d_keys)):
    if int(d_keys[n]) in range(bounds[0], bounds[1]):
        print(d[d_keys[n]])

When 37 (lower bound) and 39 (upper bound) are entered the code prints: value1, but when 38 is entered as upper bound value1 is not printed.

If you dont want it to print you can  have it return a list of all the values that are that number.
All you would have to do is change the print(d[d_keys[n]]) to numbers_in_range.append(d[d_keys[n]]) and adding numbers_in_range = [] somewhere above.


问:
Is it possible to 'protect' a property and exclude it from select statements
I'd like to protect certain properties on the data-layer level. For example I'd like to protect the password hash I store in the database for a user, so that it doesn't show up in arbitrary select-statements.

This way only when it's explicitly requested in a select property, property2 statement.

答:
TypeORM goes well with routing-controllers so you should use it, behind the scenes it uses class-transformer to serialize and deserialize your data. So you can use the @Exclude decorator from that library to prevent certain properties being sent down to the clients.

It also uses the class-validator library to validate the data when specifying it as the type in the controller functions. These are powerful toys. Here is a small example of how you can leverage both:

```<code>import { Entity, Column, PrimaryGeneratedColumn, Index, OneToMany } from "typeorm";
import { Exclude, Expose } from "class-transformer";
import { IsNotEmpty, IsEmail, MinLength, MaxLength, Min, Max, IsNumber, IsString } from "class-validator";

@Entity()
export class User extends BaseEntity {

  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  @IsNotEmpty()
  @IsEmail()
  @Index({ unique: true })
  email: string;

  @Exclude()
  @Column()
  passwordHash: string;

  @Column()
  @IsNotEmpty()
  @IsString()
  firstName: string;

  @Column()
  @IsNotEmpty()
  @IsString()
  lastName: string;

  @Column({ type: 'integer', default: Gender.NotSpecified })
  @IsNumber()
  @Min(1)
  @Max(3)
  gender: Gender;

  @Expose()
  get admin() {
    return this.role == Role.Admin;
  }

  @Expose()
  get stylist() {
    return this.role == Role.Stylist;
  }
}
</code>```

If you use an another server-side library you can still take advantage of class-transformer and class-validator. You just need to call the validate function manually in your routes, for example for restify you can write:

```<code>import {validate } from "class-validator";
import {plainToClass} from "class-transformer";
// ... more code

server.post('/hello', function create(req, res, next) {
   let bodyJSON = parseBodyTheWayYouWant(req.body);
   let post = plainToClass(bodyJSON);
   validate(post)
   return next();
});
</code>```

Body:
TypeORM goes well with routing-controllers so you should use it, behind the scenes it uses class-transformer to serialize and deserialize your data. So you can use the @Exclude decorator from that library to prevent certain properties being sent down to the clients.

It also uses the class-validator library to validate the data when specifying it as the type in the controller functions. These are powerful toys. Here is a small example of how you can leverage both:

import { Entity, Column, PrimaryGeneratedColumn, Index, OneToMany } from "typeorm";
import { Exclude, Expose } from "class-transformer";
import { IsNotEmpty, IsEmail, MinLength, MaxLength, Min, Max, IsNumber, IsString } from "class-validator";

@Entity()
export class User extends BaseEntity {

  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  @IsNotEmpty()
  @IsEmail()
  @Index({ unique: true })
  email: string;

  @Exclude()
  @Column()
  passwordHash: string;

  @Column()
  @IsNotEmpty()
  @IsString()
  firstName: string;

  @Column()
  @IsNotEmpty()
  @IsString()
  lastName: string;

  @Column({ type: 'integer', default: Gender.NotSpecified })
  @IsNumber()
  @Min(1)
  @Max(3)
  gender: Gender;

  @Expose()
  get admin() {
    return this.role == Role.Admin;
  }

  @Expose()
  get stylist() {
    return this.role == Role.Stylist;
  }
}

If you use an another server-side library you can still take advantage of class-transformer and class-validator. You just need to call the validate function manually in your routes, for example for restify you can write:

import {validate } from "class-validator";
import {plainToClass} from "class-transformer";
// ... more code

server.post('/hello', function create(req, res, next) {
   let bodyJSON = parseBodyTheWayYouWant(req.body);
   let post = plainToClass(bodyJSON);
   validate(post)
   return next();
});


问:
Lazy evaluation example with NULL in Advanced R
In Hadley Wickham's Advanced R, I'm having some trouble understanding one of the lazy evaluation examples.

Copied from the book, chapter on functions:

Laziness is useful in if statements — the second statement below will be >evaluated only if the first is true. If it wasn’t, the statement would return >an error because NULL > 0 is a logical vector of length 0 and not a valid input >to if.

```<code>x <- NULL
if (!is.null(x) && x > 0) {

}
</code>```

As I understand the example, if R was not using lazy evaluation, the !is.null() and > 0 functions would be evaluated simultaneously, throwing an error since NULL is not a permissible argument to the ">" function. Is this correct? Is it thus generally advisable to include !is.null() in R statements when we expect that a variable could be NULL?

答:
This is just the way the && operator works.  It's called short-circuiting and is separate from lazy evaluation.

Lazy evaluation refers to the way function arguments are evaluated.  In particular arguments are only evaluated when (if) they are actually used in the function.  For example, consider the following function

```<code>f <- function(a, b) NULL
</code>```

that does nothing and returns NULL. The arguments a and b are never evaluated because they are unused.  They don't appear in the body of f, so you can call f with any expressions you want (as long as it's syntactically correct) as arguments because the expressions won't be evaluated.  E.g.

```<code>> f(1, 2)
NULL
> f(43$foo, unboundvariableblablabla)
NULL
</code>```

Without lazy evaluation the arguments are evaluated first and then passed to the function, so the call above would fail because if you try to evaluate 43$foo you'll get an error

```<code>> 43$foo
Error in 43$foo : $ operator is invalid for atomic vectors
</code>```

Body:
In Hadley Wickham's Advanced R, I'm having some trouble understanding one of the lazy evaluation examples.

Copied from the book, chapter on functions:

Laziness is useful in if statements — the second statement below will be >evaluated only if the first is true. If it wasn’t, the statement would return >an error because NULL > 0 is a logical vector of length 0 and not a valid input >to if.

x <- NULL
if (!is.null(x) && x > 0) {

}

As I understand the example, if R was not using lazy evaluation, the !is.null() and > 0 functions would be evaluated simultaneously, throwing an error since NULL is not a permissible argument to the ">" function. Is this correct? Is it thus generally advisable to include !is.null() in R statements when we expect that a variable could be NULL?

Body:
This is just the way the && operator works.  It's called short-circuiting and is separate from lazy evaluation.

Lazy evaluation refers to the way function arguments are evaluated.  In particular arguments are only evaluated when (if) they are actually used in the function.  For example, consider the following function

f <- function(a, b) NULL

that does nothing and returns NULL. The arguments a and b are never evaluated because they are unused.  They don't appear in the body of f, so you can call f with any expressions you want (as long as it's syntactically correct) as arguments because the expressions won't be evaluated.  E.g.

> f(1, 2)
NULL
> f(43$foo, unboundvariableblablabla)
NULL

Without lazy evaluation the arguments are evaluated first and then passed to the function, so the call above would fail because if you try to evaluate 43$foo you'll get an error

> 43$foo
Error in 43$foo : $ operator is invalid for atomic vectors


问:
How to recognize caller's name and address in VXML?
I have recently got a chance to work on Plum Voice VXML. I am writing an IVR for a food ordering company in which it is required to ask name and address from the caller to save in database and to deliver the order later. For voice recognition we have to provide grammar but how can I write a grammar to recognize names as thousands of names exists.</p>

答:
Some VoiceXML IVR (like Voximal) embedded SpeechToText ressources.
Those allows you to convert speech to text, and so, allows you to get the user's name.
You will probably reach limitations with foreign or exotic names...
But, engines like Google Speech API allows you to add extra names to increase the recognition.</p>


问:
NHibernate.Caches.MemCache web.config for cache expiration time
I'm migrating to Nhibernate 2.0 GA but have some trouble with setting cache expirations in memcached provider.

I see in the NHibernate.Caches.MemCache sources that there is a property for expiration and a default value for 300 seconds.

There are also properties for cache regions but the config section handler does not seem to map them.

Is there some other way cache expiration times are set that is not provider specific --

Here is functional web config section (without an expiration settings obviously).

```<code><memcache>
    <memcached host="127.0.0.1" port="11211"/>
    <!-- or multiples -->
</memcache>

<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
    <session-factory>
        <property name="show_sql">true</property>
        <property name="connection.provider" >NHibernate.Connection.DriverConnectionProvider</property>
        <property name="dialect">NHibernate.Dialect.MsSql2000Dialect</property>
        <property name="connection.driver_class">NHibernate.Driver.SqlClientDriver</property>
                <!--    <property name="hibernate.cache.provider_class" value="NHibernate.Caches.MemCache.MemCacheProvider,NHibernate.Caches.MemCache" /> -->
        <property name="connection.connection_string">Data Source=stage2.ripple6.com;Initial Catalog=r6stage;User Id=sa;Password=mworld7650;Application Name=Hibernate;</property>
        <property name="connection.isolation">ReadCommitted</property>
        <property name="cache.use_second_level_cache">true</property>
        <property name="cache.provider_class">NHibernate.Caches.MemCache.MemCacheProvider,NHibernate.Caches.MemCache</property>
        <property name="default_schema" >r6stage.dbo</property>
    </session-factory>

</hibernate-configuration>
</code>```

答:
Use expiration.

```<code><property name="expiration" >YOUR_INTERVAL_IN_SECONDS</property>
</code>```

After that, when you run app with logging you can see:

```<code>NHibernate.Caches.MemCache.MemCacheClient: 20:57:55,762 DEBUG MemCacheClient:0 - using expiration of YOUR_INTERVAL_IN_SECONDS seconds
</code>```

OwnerDisplayName: malsmith

ContentLicense: CC BY-SA 2.5

Body:
I'm migrating to Nhibernate 2.0 GA but have some trouble with setting cache expirations in memcached provider.

I see in the NHibernate.Caches.MemCache sources that there is a property for expiration and a default value for 300 seconds.

There are also properties for cache regions but the config section handler does not seem to map them.

Is there some other way cache expiration times are set that is not provider specific --

Here is functional web config section (without an expiration settings obviously).

<memcache>
    <memcached host="127.0.0.1" port="11211"/>

</memcache>

<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
    <session-factory>
        <property name="show_sql">true</property>
        <property name="connection.provider" >NHibernate.Connection.DriverConnectionProvider</property>
        <property name="dialect">NHibernate.Dialect.MsSql2000Dialect</property>
        <property name="connection.driver_class">NHibernate.Driver.SqlClientDriver</property>

        <property name="connection.connection_string">Data Source=stage2.ripple6.com;Initial Catalog=r6stage;User Id=sa;Password=mworld7650;Application Name=Hibernate;</property>
        <property name="connection.isolation">ReadCommitted</property>
        <property name="cache.use_second_level_cache">true</property>
        <property name="cache.provider_class">NHibernate.Caches.MemCache.MemCacheProvider,NHibernate.Caches.MemCache</property>
        <property name="default_schema" >r6stage.dbo</property>
    </session-factory>

</hibernate-configuration>

LastEditorDisplayName: malsmith

Body:
Use expiration.

<property name="expiration" >YOUR_INTERVAL_IN_SECONDS</property>

After that, when you run app with logging you can see:

NHibernate.Caches.MemCache.MemCacheClient: 20:57:55,762 DEBUG MemCacheClient:0 - using expiration of YOUR_INTERVAL_IN_SECONDS seconds

OwnerDisplayName: jsevcik


问:
Searching using NSOperation
I am trying to make a searchbar to search for things I receive using NSURLConnection.
right now, if I search for something, that string is send away as an URL with an asynchronous request, which gives me data.

```<code>NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:urlString] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:20.0];
    [theConnection cancel];
    [theConnection release];

theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
</code>```

That data is parsed and when it is successful I post a notification

```<code>-(void)connectionDidFinishLoading:(NSURLConnection *)connection
     {
         xmlParser = [[NSXMLParser alloc] data];
         [xmlParser setDelegate:xmlGeocoder];
         BOOL success = [xmlParser parse];

         if(success == YES){
             NSLog(@"No Errors");

             [[NSNotificationCenter defaultCenter] postNotificationName:@"getArray" object:self];

         }else{
             NSLog(@"Error Error Error!!!");
             [[NSNotificationCenter defaultCenter] postNotificationName:@"failToGetArray" object:self];
         }
}
</code>```

and my searchresultsTableView is reloaded.

```<code>self.array1 = [array2 copy];
    [self.searchDisplayController.searchResultsTableView reloadData];
</code>```

All these methods are depending on eachother, so B can't be executed, when A is still busy.
I am using NSNotificationCenter to tell them to execute those code.

But I want to try NSOperation and I have no idea HOW to implement that.
Do I have to put my search requests in an operation or every method I'm using?

Can someone give me a sample code to give me the idea how this should be done?
Thanks in advance...

答:
NSOperation is very useful. To use it you extend NSOperation and override the "main" method.
In the main method you do your calculations/web request etc. So NSOperation is best for tasks you can wrap into a few simple steps, after each step you test if everything is good and either continue to the next step or cancel the operation. Once this is done you can simply instantiate your custom NSOperation and hand it off to a NSOperationQueue object and it will take care of the threading, starting, stopping cleaning up etc.

In the example below I have written a protocol to handle the completion of the task, I would advise you take this approach instead of using notification - unless you have multiple objects that needs to be notified instantly.

Make a new class that extends the NSOperation class:

```<code>//This object takes a "searchTerm" and waits to be "started".
#import <Foundation/Foundation.h>

@protocol ISSearchOperationDelegate

- (void) searchDataReady:(NSArray*) searchResult;

@end

@interface ISSearchOperation : NSOperation {

    id <ISSearchOperationDelegate> delegate;

    NSString *searchTerm;
}

@property(nonatomic, retain) NSString *searchTerm;

@property(nonatomic, assign) id delegate;

- (id) initWithSearchTerm:(NSString*) searchString;

@end
</code>```

When an object extending NSOperation is added to an NSOperationQueue, the queue object
tries to call a "main" method on the NSOperation, you must therefore wrap your task in this method.
(notice that after each completed sub-task I test if it went well and "return" if not. The NSOperation class
has a property called isCancelled This property can be set by the NSOperationQueue, so you must also
test if that has been set during your completion of main. So to recap, you test from the inside of main if each step went as you wanted and you test if something on the outside has cancelled your task.):

```<code>- (id) initWithSearchTerm:(NSString*) searchString {

    if (self = [super init]) {

        [self setSearchTerm:searchString];
    }

    return self;
}

- (void) main {

    [self performSelector:@selector(timeOut) withObject:nil afterDelay:4.0];
    if ([self isCancelled]) return;
    NSData *resultData = [self searchWebServiceForString:self.searchTerm];
    if (resultData == nil) return;
    if ([self isCancelled]) return;
    NSArray *result = [self parseJSONResult:resultData];
    if ([self isCancelled]) return;
    if (result == nil) return;
    [NSObject cancelPreviousPerformRequestsWithTarget:self];
    [delegate performSelectorOnMainThread:@selector(searchDataReady:) withObject:result waitUntilDone:YES];
}
</code>```

//I have not copied the implementation of all the methods I call during main, but I hope you understand that they are just "tasks" that each must be successfully completed before the next sub-task can be computed.
So first of I put a timeout test in there, then I get my data from the web service and then I parse it.

Ok to get all this going you need a queue.

So in the class you want to be the delegate for this operation you do this:

somewhere set up a queue:

```<code>NSOperationQueue *q = [[NSOperationQueue alloc] init];
[self setQueue:q];
[q release];

- (void) doSearch:(NSString*) searchString {

    [queue cancelAllOperations];
    ISSearchOperation *searchOperation = [[ISSearchOperation alloc] initWithSearchTerm:searchString];
    [searchOperation setDelegate:self];
    [queue addOperation:searchOperation]; //this makes the NSOperationQueue call the main method in the NSOperation
    [searchOperation release];
}

//the delegate method called from inside the NSOperation
- (void) searchDataReady:(NSArray*) results {

    //Data is here!
}
</code>```

Some of the advantages with NSOperations is that from the caller point of view, we simply make an object, set a delegate, wait for the reply. But behind the scenes a series of threaded tasks that can be cancelled at any time is run, and in a manner that can handle if threaded stuff fails.

As you can see in the doSearch method it starts out by canceling any previous operations, I did this in an app where I would search a web service each time a user typed a letter in a word. That means that if the user searched for "hello world" - I would do a search for "h", then "he", then "hel", then hell", then "hello" etc.
I wanted to stop and clean up the "h" task as soon as the user typed the "e", because it was then obsolete.
I found out NSOperation was the only way that gave the responsiveness of threading and none of the mess that usually comes with spawning many threads on top of each other.

Hope you can use it to get started:)

Title: Searching using NSOperation

Body:
I am trying to make a searchbar to search for things I receive using NSURLConnection.
right now, if I search for something, that string is send away as an URL with an asynchronous request, which gives me data.

NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:urlString] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:20.0];
    [theConnection cancel];
    [theConnection release];

theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];

That data is parsed and when it is successful I post a notification

-(void)connectionDidFinishLoading:(NSURLConnection *)connection
     {
         xmlParser = [[NSXMLParser alloc] data];
         [xmlParser setDelegate:xmlGeocoder];
         BOOL success = [xmlParser parse];

         if(success == YES){
             NSLog(@"No Errors");

             [[NSNotificationCenter defaultCenter] postNotificationName:@"getArray" object:self];

         }else{
             NSLog(@"Error Error Error!!!");
             [[NSNotificationCenter defaultCenter] postNotificationName:@"failToGetArray" object:self];
         }
}

and my searchresultsTableView is reloaded.

self.array1 = [array2 copy];
    [self.searchDisplayController.searchResultsTableView reloadData];

All these methods are depending on eachother, so B can't be executed, when A is still busy.
I am using NSNotificationCenter to tell them to execute those code.

But I want to try NSOperation and I have no idea HOW to implement that.
Do I have to put my search requests in an operation or every method I'm using?

Can someone give me a sample code to give me the idea how this should be done?
Thanks in advance...

Body:
NSOperation is very useful. To use it you extend NSOperation and override the "main" method.
In the main method you do your calculations/web request etc. So NSOperation is best for tasks you can wrap into a few simple steps, after each step you test if everything is good and either continue to the next step or cancel the operation. Once this is done you can simply instantiate your custom NSOperation and hand it off to a NSOperationQueue object and it will take care of the threading, starting, stopping cleaning up etc.

In the example below I have written a protocol to handle the completion of the task, I would advise you take this approach instead of using notification - unless you have multiple objects that needs to be notified instantly.

Make a new class that extends the NSOperation class:

//This object takes a "searchTerm" and waits to be "started".
#import <Foundation/Foundation.h>

@protocol ISSearchOperationDelegate

- (void) searchDataReady:(NSArray*) searchResult;

@end

@interface ISSearchOperation : NSOperation {

    id <ISSearchOperationDelegate> delegate;

    NSString *searchTerm;
}

@property(nonatomic, retain) NSString *searchTerm;

@property(nonatomic, assign) id delegate;

- (id) initWithSearchTerm:(NSString*) searchString;

@end

When an object extending NSOperation is added to an NSOperationQueue, the queue object
tries to call a "main" method on the NSOperation, you must therefore wrap your task in this method.
(notice that after each completed sub-task I test if it went well and "return" if not. The NSOperation class
has a property called isCancelled This property can be set by the NSOperationQueue, so you must also
test if that has been set during your completion of main. So to recap, you test from the inside of main if each step went as you wanted and you test if something on the outside has cancelled your task.):

- (id) initWithSearchTerm:(NSString*) searchString {

    if (self = [super init]) {

        [self setSearchTerm:searchString];
    }

    return self;
}

- (void) main {

    [self performSelector:@selector(timeOut) withObject:nil afterDelay:4.0];
    if ([self isCancelled]) return;
    NSData *resultData = [self searchWebServiceForString:self.searchTerm];
    if (resultData == nil) return;
    if ([self isCancelled]) return;
    NSArray *result = [self parseJSONResult:resultData];
    if ([self isCancelled]) return;
    if (result == nil) return;
    [NSObject cancelPreviousPerformRequestsWithTarget:self];
    [delegate performSelectorOnMainThread:@selector(searchDataReady:) withObject:result waitUntilDone:YES];
}

//I have not copied the implementation of all the methods I call during main, but I hope you understand that they are just "tasks" that each must be successfully completed before the next sub-task can be computed.
So first of I put a timeout test in there, then I get my data from the web service and then I parse it.

Ok to get all this going you need a queue.

So in the class you want to be the delegate for this operation you do this:

somewhere set up a queue:

NSOperationQueue *q = [[NSOperationQueue alloc] init];
[self setQueue:q];
[q release];

- (void) doSearch:(NSString*) searchString {

    [queue cancelAllOperations];
    ISSearchOperation *searchOperation = [[ISSearchOperation alloc] initWithSearchTerm:searchString];
    [searchOperation setDelegate:self];
    [queue addOperation:searchOperation]; //this makes the NSOperationQueue call the main method in the NSOperation
    [searchOperation release];
}

//the delegate method called from inside the NSOperation
- (void) searchDataReady:(NSArray*) results {

    //Data is here!
}

Some of the advantages with NSOperations is that from the caller point of view, we simply make an object, set a delegate, wait for the reply. But behind the scenes a series of threaded tasks that can be cancelled at any time is run, and in a manner that can handle if threaded stuff fails.

As you can see in the doSearch method it starts out by canceling any previous operations, I did this in an app where I would search a web service each time a user typed a letter in a word. That means that if the user searched for "hello world" - I would do a search for "h", then "he", then "hel", then hell", then "hello" etc.
I wanted to stop and clean up the "h" task as soon as the user typed the "e", because it was then obsolete.
I found out NSOperation was the only way that gave the responsiveness of threading and none of the mess that usually comes with spawning many threads on top of each other.

Hope you can use it to get started:)


问:
How the least square method work with a given function
I have some data and I have used below numpy function to make the fitting. The fitting was fine but I need some explanation how it works.  What does p[1],p[2],p[0] stands for.It will be nice if I get the mathematical expression for that. what actually the least square is doing?</p>

```<code>fitfuncvx = lambda p, x: p[2]+p[0]*np.exp(-x/p[1])
errfuncvx = lambda p, x, y: y - fitfuncvx(p, x)
sig_fit=np.where(Sig<12)
pinit = [1, 100,0.1]
pfinal, success = optimize.leastsq(errfuncvx, pinit[:], args=(Sig[sig_fit], vx[sig_fit]))
</code>```

答:
What are p[0], p[1], p[2]?

The scipy.optimize functions typically return an array of parameters p.  For example, given a linear equation:

p includes the intercept and successive coefficients (or weights) of a linear equation:

Thus in the latter example, p[0] and p[1] pertain to an intercept and slope of a line respectively.  Of course more parameters (...) can be optimized as well for higher order polynomials. The OP uses an exponential function, where the parameters can be rewritten as follows:

```<code>def fitfuncvx(p, x):
    b0, b1, b2 = p
    return b2 + b0*np.exp(-x/b1)
</code>```

We see the parameters in p are explicitly unpacked into separate weights b0, b1, b2, which directly correspond with p[0], p[1], p[2] respectively.

Details: How optimizers work?

The first returned value of the scipy.optimize.leastsq function is an array of optimized fitted parameters, started from your initial guess, that is computed by iteratively minimizing residuals.  The residual is the distance between the predicted response (or y-hat value) and the true response (y).  The second returned value is a covariance matrix, from which one can estimate the error in the calculation.

For reference, I include the first three arguments of the leastsq signature:

```<code>scipy.optimize.leastsq(func, x0, args=(), ...)
</code>```

func is the objective function you wish to optimize

x0 is the initial guessed parameter

args are additional variables required by the objective function (if any)

Body:
I have some data and I have used below numpy function to make the fitting. The fitting was fine but I need some explanation how it works.  What does p[1],p[2],p[0] stands for.It will be nice if I get the mathematical expression for that. what actually the least square is doing?

fitfuncvx = lambda p, x: p[2]+p[0]*np.exp(-x/p[1])
errfuncvx = lambda p, x, y: y - fitfuncvx(p, x)
sig_fit=np.where(Sig<12)
pinit = [1, 100,0.1]
pfinal, success = optimize.leastsq(errfuncvx, pinit[:], args=(Sig[sig_fit], vx[sig_fit]))

Body:
What are p[0], p[1], p[2]?

The scipy.optimize functions typically return an array of parameters p.  For example, given a linear equation:

p includes the intercept and successive coefficients (or weights) of a linear equation:

Thus in the latter example, p[0] and p[1] pertain to an intercept and slope of a line respectively.  Of course more parameters (...) can be optimized as well for higher order polynomials. The OP uses an exponential function, where the parameters can be rewritten as follows:

def fitfuncvx(p, x):
    b0, b1, b2 = p
    return b2 + b0*np.exp(-x/b1)

We see the parameters in p are explicitly unpacked into separate weights b0, b1, b2, which directly correspond with p[0], p[1], p[2] respectively.

Details: How optimizers work?

The first returned value of the scipy.optimize.leastsq function is an array of optimized fitted parameters, started from your initial guess, that is computed by iteratively minimizing residuals.  The residual is the distance between the predicted response (or y-hat value) and the true response (y).  The second returned value is a covariance matrix, from which one can estimate the error in the calculation.

For reference, I include the first three arguments of the leastsq signature:

scipy.optimize.leastsq(func, x0, args=(), ...)

func is the objective function you wish to optimize

x0 is the initial guessed parameter

args are additional variables required by the objective function (if any)


问:
Calling C function taking bool, not BOOL, from ObjC
Within my ObjC code, I am calling a function which has an argument of type bool (not BOOL).

Should I be passing YES to this argument from my ObjC code, or would passing true should be correct?

This question is about conventions, not functional correctness.

答:
The convention, if one exists in any formal sense, would be for bool/true/false and BOOL/YES/NO.

As for functional correctness you are correct that it is hard (but not impossible[1]) to "contrive an example which demonstrates a difference". Boolean logic in C is based on integers, "boolean" valued operators (>, &&, et al) return integers not any flavour of boolean.

HTH

[1] E.g. consider uses of @encode and different platforms (macOS, iOS, etc.) if you wish to contrive something.


问:
change the background-color of every other element
I want to change the background-color of every other element in the following:

```<code><div class="dets">
 <div>Simple Layout</div>
 <div>Few Pictures/Links</div>
 <div>Element Uniformity</div>
</div>
</code>```

So the first [Simple Layout] would be white, the second [Few Pictures/Links] would be black, and so on. I have three of these structures nested in some other div elements. I know about the :even,:odd methods, but it doesn't do as expected. It continues through each of the "dets" classes, increasing the index each time. I want odd rows white, even rows black. Is there a way to restart the natural index for each "dets" class? I do not want to use a table.

I am currently using the following jQuery to set the background-color:

```<code>$(".dets div:odd").css('background-color', 'white');
$(".dets div:even").css('background-color', 'black');
</code>```

答:
You could achieve this in css itself by using

.dets div:nth-child(odd){
  background-color:white;
  }
  .dets div:nth-child(even){
  background-color:black;
  }

Body:
I want to change the background-color of every other element in the following:

Simple Layout

Few Pictures/Links

Element Uniformity

So the first [Simple Layout] would be white, the second [Few Pictures/Links] would be black, and so on. I have three of these structures nested in some other div elements. I know about the :even,:odd methods, but it doesn't do as expected. It continues through each of the "dets" classes, increasing the index each time. I want odd rows white, even rows black. Is there a way to restart the natural index for each "dets" class? I do not want to use a table.

I am currently using the following jQuery to set the background-color:

$(".dets div:odd").css('background-color', 'white');
$(".dets div:even").css('background-color', 'black');


问:
Maximum stack size called using react/redux
I think I know what the problem is, but I am not sure how to fix it. I am wanting my state to update each time an "action/event/whatever" happens. I am trying to use componentWillReceiveProps, but then it's like my code goes into a never ending loop for some reason.

I have put two functions inside of this componentWillReceiveProps to be fire off each time something happens that way they will update. I will post the code here:

Just for information cart is an object that contains objects inside of it. It gets more items if people so choose to add them and it can delete those items also.

Component:

```<code>import React , { Component } from 'react';
import * as actions from '../../actions/cartActions';
import {Modal, Button} from 'react-bootstrap';
import {connect} from 'react-redux';
import _ from 'lodash';

class Cart extends Component {
  constructor() {
    super();
    this.state = {
      showModal: false,
    }

    this.getTotalAmount = this.getTotalAmount.bind(this);
  }

  componentWillReceiveProps(nextProps) {
    console.log(this.props.price);
    this.getTotalAmount(nextProps.cart);
    this.getTotalQuantity(nextProps.cart);
    return true;
  }

  open() {
    this.setState({
      showModal: true
    });
  }

  close() {
    this.setState({
      showModal: false
    });
  }

  getTotalAmount(cart) {
    this.props.addTotal(cart);
  }

  getTotalQuantity(cart) {
    this.props.getTotalQuantity(cart);
  }

  onDelete(_id) {
    this.props.deleteCartItem(_id);
  }

  onIncrement(_id) {
    this.props.updateCart(_id, 1);
  }

  onDecrement(_id, quantity) {
    if(quantity > 1) {
      this.props.updateCart(_id, -1)
    }
  }

  renderCart() {
    if(Object.keys(this.props.cart).length > 0) {
      const cartItemList = _.map(this.props.cart, (cartItem) => {
        return (
          <div key={cartItem._id} className="panel-body">
            <div className="well">
              <div className="row">
                <div className="col-xs-12 col-sm-2">
                  <h6>{cartItem.title}</h6><span>    </span>
                </div>
                <div className="col-xs-12 col-sm-2">
                  <h6>usd. {cartItem.price}</h6>
                </div>
                <div className="col-xs-12 col-sm-2">
                  <h6>qty. <label className="label label-success">{cartItem.quantity}</label></h6>
                </div>
                <div className="col-xs-6 col-sm-4">
                  <div className="btn-group" role="group">
                    <button
                      onClick={this.onDecrement.bind(this, cartItem._id, cartItem.quantity)}
                      className="btn btn-default btn-sm"
                    >-</button>
                    <button
                      onClick={this.onIncrement.bind(this, cartItem._id)}
                      className="btn btn-default btn-sm"
                    >+</button>
                    <span>     </span>
                    <button onClick={this.onDelete.bind(this, cartItem._id)} className="btn btn-danger btn-sm">Delete</button>
                  </div>
                </div>
              </div>
            </div>
          </div>
        );
      });
      return (
        <div className="panel-group">
          <div className="panel panel-primary">
            <div className="panel-heading">Cart</div>
            {cartItemList}
            <div className="row panel-body">
              <div className="col-xs-12">
                <h6>Total amount: {this.state.price.total}</h6>
                <button onClick={this.open.bind(this)} className="btn btn-success btn-sm">
                  PROCEED TO CHECKOUT
                </button>
              </div>
            </div>
            <Modal show={this.state.showModal} onHide={this.close.bind(this)}>
              <Modal.Header closeButton>
                <Modal.Title>Thank you!</Modal.Title>
              </Modal.Header>
              <Modal.Body>
                <h6>Your order has been saved</h6>
                <p>You will receive an email confirmation</p>
              </Modal.Body>
              <Modal.Footer>
                <div className="col-xs-6">
                  <h6>total $:</h6>
                </div>
                <Button onClick={this.close.bind(this)}>Close</Button>
              </Modal.Footer>
            </Modal>
          </div>
        </div>
      );
    } else {
      return (
        <div></div>
      );
    }
  }
  render() {

    return (
      <div>
        {this.renderCart()}
      </div>
    );
  }
}

function mapStateToProps(state){
  return {
    cart: state.cart,
    price: state.price
  };
}

export default connect(mapStateToProps, actions)(Cart);
</code>```

Actions:

```<code>export function addTotal(cart) {
  return {
    type: "ADD_TOTAL_PRICE",
    payload: cart
  }
}
export function getTotalQuantity(cart) {
  return {
    type: "ADD_QUANTITY",
    payload: cart
  }
}
</code>```

reducers:

```<code>import _ from 'lodash';

export default function(state = [], action) {
  switch(action.type) {
    case "ADD_TOTAL_PRICE":
    let totalAmount = _.map(action.payload, (item) => {
      return item.quantity * item.price;
    }).reduce(function(a, b) {
      return a + b;
    }, 0).toFixed(2);
    return {...state, total: totalAmount}
    break;
    case "ADD_QUANTITY":
    let totalQuantity = _.map(action.payload, (item) => {
      return item.quantity;
    }).reduce(function(a, b) {
      return a + b;
    }, 0);
    return {...state, quantity: totalQuantity};
  }
  return state;
}
</code>```

答:
When you have function calls in componentWillReceiveProps, you generally need to have conditional logic around them so that they're only called if specific props are actually changing.  Typically, this looks like:

```<code>if(this.props.someProp !== nextProps.someProp) {
    // call some function only when the prop has changed
}
</code>```

In your case, you're dispatching a Redux action every time the component receives any props, that dispatch causes a React re-render, and that repeats the cycle.

Body:
I think I know what the problem is, but I am not sure how to fix it. I am wanting my state to update each time an "action/event/whatever" happens. I am trying to use componentWillReceiveProps, but then it's like my code goes into a never ending loop for some reason.

I have put two functions inside of this componentWillReceiveProps to be fire off each time something happens that way they will update. I will post the code here:

Just for information cart is an object that contains objects inside of it. It gets more items if people so choose to add them and it can delete those items also.

Component:

import React , { Component } from 'react';
import * as actions from '../../actions/cartActions';
import {Modal, Button} from 'react-bootstrap';
import {connect} from 'react-redux';
import _ from 'lodash';

class Cart extends Component {
  constructor() {
    super();
    this.state = {
      showModal: false,
    }

    this.getTotalAmount = this.getTotalAmount.bind(this);
  }

  componentWillReceiveProps(nextProps) {
    console.log(this.props.price);
    this.getTotalAmount(nextProps.cart);
    this.getTotalQuantity(nextProps.cart);
    return true;
  }

  open() {
    this.setState({
      showModal: true
    });
  }

  close() {
    this.setState({
      showModal: false
    });
  }

  getTotalAmount(cart) {
    this.props.addTotal(cart);
  }

  getTotalQuantity(cart) {
    this.props.getTotalQuantity(cart);
  }

  onDelete(_id) {
    this.props.deleteCartItem(_id);
  }

  onIncrement(_id) {
    this.props.updateCart(_id, 1);
  }

  onDecrement(_id, quantity) {
    if(quantity > 1) {
      this.props.updateCart(_id, -1)
    }
  }

  renderCart() {
    if(Object.keys(this.props.cart).length > 0) {
      const cartItemList = _.map(this.props.cart, (cartItem) => {
        return (

{cartItem.title}

usd. {cartItem.price}

qty. {cartItem.quantity}

                    <button
                      onClick={this.onDecrement.bind(this, cartItem._id, cartItem.quantity)}
                      className="btn btn-default btn-sm"
                    >-</button>
                    <button
                      onClick={this.onIncrement.bind(this, cartItem._id)}
                      className="btn btn-default btn-sm"
                    >+</button>

                    <button onClick={this.onDelete.bind(this, cartItem._id)} className="btn btn-danger btn-sm">Delete</button>

        );
      });
      return (

Cart

            {cartItemList}

Total amount: {this.state.price.total}

                <button onClick={this.open.bind(this)} className="btn btn-success btn-sm">
                  PROCEED TO CHECKOUT
                </button>

            <Modal show={this.state.showModal} onHide={this.close.bind(this)}>
              <Modal.Header closeButton>
                <Modal.Title>Thank you!</Modal.Title>
              </Modal.Header>
              <Modal.Body>

Your order has been saved

You will receive an email confirmation

              </Modal.Body>
              <Modal.Footer>

total $:

                <Button onClick={this.close.bind(this)}>Close</Button>
              </Modal.Footer>
            </Modal>

      );
    } else {
      return (

      );
    }
  }
  render() {

    return (

        {this.renderCart()}

    );
  }
}

function mapStateToProps(state){
  return {
    cart: state.cart,
    price: state.price
  };
}

export default connect(mapStateToProps, actions)(Cart);

Actions:

export function addTotal(cart) {
  return {
    type: "ADD_TOTAL_PRICE",
    payload: cart
  }
}
export function getTotalQuantity(cart) {
  return {
    type: "ADD_QUANTITY",
    payload: cart
  }
}

reducers:

import _ from 'lodash';

export default function(state = [], action) {
  switch(action.type) {
    case "ADD_TOTAL_PRICE":
    let totalAmount = _.map(action.payload, (item) => {
      return item.quantity * item.price;
    }).reduce(function(a, b) {
      return a + b;
    }, 0).toFixed(2);
    return {...state, total: totalAmount}
    break;
    case "ADD_QUANTITY":
    let totalQuantity = _.map(action.payload, (item) => {
      return item.quantity;
    }).reduce(function(a, b) {
      return a + b;
    }, 0);
    return {...state, quantity: totalQuantity};
  }
  return state;
}

Body:
When you have function calls in componentWillReceiveProps, you generally need to have conditional logic around them so that they're only called if specific props are actually changing.  Typically, this looks like:

if(this.props.someProp !== nextProps.someProp) {
    // call some function only when the prop has changed
}

In your case, you're dispatching a Redux action every time the component receives any props, that dispatch causes a React re-render, and that repeats the cycle.


问:
How to keep track of flask session after a redirect?
I'm writing a webapp in Flask and I am taking in form data from users. After they pass in that data, I'm trying to automate the authentication with amazon.

So I send a GET with a query string and amazon sends me their login page

The user is suppose to login with their amazon account, but I'm trying to use selenium python webdriver to automatically log them in the information they submitted the first.

After they are logged in with the webdriver, Amazon redirects to an URL I passed in via the initial query string. And the redirected URL now has an access code that I need to grab and use as a part of the token authentication process.

Here's the problem:
After that last redirect, my Flask application loses everything that I stored in the session cookie. My intention was to use the session to keep track of a user_id so that I could update the user records with the access code retrieved.

So how do I not lose a session in Flask after redirecting to an external login site?

Update (code sample):

```<code>@app.route('/index', methods=['GET', 'POST'])
def index():

    if request.method == 'POST:
        # user is logged in and added to database here
        configs = request.files['config']
        session_id = b64encode(os.urandom(24))
        session['user_config'] = configs
        session['session_id'] = session_id

        user = User.query.filter_by(email=configs['email']).first()
        if user is None:
            # add user to database with data in configs dict file
            # ...
            return redirect(url_for("app.get_auth_code"))
        else:
            # no need to authenticate user
            # continue work as expected
            # ...

@app.route('/lwa', methods=['GET', 'POST'])
@login_required
def get_auth_code():

    auth_url = "https://www.amazon.com/ap/oa"
    redirect_uri = "http://localhost:5000" +  url_for("app.authresponse")

    sd = json.dumps({
        "alexa:all": {
            "productID": session['user_config']['DEVICE_TYPE_ID'],
            "productInstanceAttributes": {
                "deviceSerialNumber": "001"
            }
        }
    })
    payload = {
        "client_id": session['user_config']['CLIENT_ID'],
        "scope": "alexa:all",
        "scope_data": sd,
        "response_type": "code",
        "redirect_uri": redirect_uri
    }

    query_str = "?" + urlencode(payload, doseq=True)
    driver = webdriver.Firefox(executable_path='/tmp/geckodriver')
    driver.get(auth_url + query_str)

    wait = WebDriverWait(driver, 10)
    amazon_sign_in = wait.until(EC.title_contains("Amazon.com Sign In"))

    if amazon_sign_in:
        username = driver.find_element_by_id('ap_email')
        password = driver.find_element_by_id('ap_password')
        submit_button = driver.find_element_by_id("signInSubmit")

        # Fill in email and password
        username.send_keys(session['user_config']['EMAIL'])
        password.send_keys(session['user_config']['PASSWORD'])
        submit_button.click()
        # driver.close()
        return redirect(url_for("app.authresponse"))
    else:
        flash("Login With Amazon page not found")
        return redirect(url_for("app.index"))

    return redirect(url_for("app.index"))

## This is the function where I lose the session for the same user
## This is the callback route that amazon sends the auth code to after the user is logged in
@app.route('/authresponse', methods=['GET', 'POST'])
def authresponse():
    code = None
    if request.method == 'GET':
        code = request.args.get('code', None)
        if code:
            user = User.query.filter_by(session_id=session.get("session_id")).first()

            if user:
                user.auth_code = code
                db.session.commit()

                # retrieve access token with POST request
                url = "https://api.amazon.com/auth/o2/token"
                payload = {
                    "client_id": user.client_id,
                    "client_secret": user.client_secret,
                    "code": code,
                    "grant_type": "authorization_code",
                    "redirect_uri": "http://localhost:5000" + url_for("app.authresponse")
                }
                r = requests.post(url, data=payload, timeout=5)
                if r.status_code == 200:
                    print r.text
                    return r.text
                else:
                    print r.text, r.status_code
            else:
                print "User not found"
                flash("Auth code not found.")

    return """code:<div id="token">{}</div>""".format(code)
</code>```

答:
I was able to find a solution to have the user's information persist between different pages when making a Oauth2 request to amazon. I'm assuming the authentication process for other sites will be very similar so I am adding the solution I used.

Create a session ID and store in DB or Cache

Pass the state of your OAuth2 request into your payload via a "state" field, assign the state to be the session ID

```<code> payload = {

            "state": session_id,
            "client_id": user.client_id,
            "client_secret": user.client_secret,
            "code": code,
            "grant_type": "authorization_code",
            "redirect_uri": "http://localhost:5000"
        }
</code>```

In your redirect url that the authentication service sends the access token to, the STATE should appear in the query string of the redirect URI.

Grab the STATE from the query string and use it to fetch all the user information you want from the DB or Cache.

Amazon solution:

https://developer.amazon.com/public/apis/engage/login-with-amazon/docs/dynamically_redirect_users.html

https://developer.amazon.com/public/apis/engage/login-with-amazon/docs/cross_site_request_forgery.html

Body:
I'm writing a webapp in Flask and I am taking in form data from users. After they pass in that data, I'm trying to automate the authentication with amazon.

So I send a GET with a query string and amazon sends me their login page

The user is suppose to login with their amazon account, but I'm trying to use selenium python webdriver to automatically log them in the information they submitted the first.

After they are logged in with the webdriver, Amazon redirects to an URL I passed in via the initial query string. And the redirected URL now has an access code that I need to grab and use as a part of the token authentication process.

Here's the problem:
After that last redirect, my Flask application loses everything that I stored in the session cookie. My intention was to use the session to keep track of a user_id so that I could update the user records with the access code retrieved.

So how do I not lose a session in Flask after redirecting to an external login site?

Update (code sample):

@app.route('/index', methods=['GET', 'POST'])
def index():

    if request.method == 'POST:
        # user is logged in and added to database here
        configs = request.files['config']
        session_id = b64encode(os.urandom(24))
        session['user_config'] = configs
        session['session_id'] = session_id

        user = User.query.filter_by(email=configs['email']).first()
        if user is None:
            # add user to database with data in configs dict file
            # ...
            return redirect(url_for("app.get_auth_code"))
        else:
            # no need to authenticate user
            # continue work as expected
            # ...

@app.route('/lwa', methods=['GET', 'POST'])
@login_required
def get_auth_code():

    auth_url = "https://www.amazon.com/ap/oa"
    redirect_uri = "http://localhost:5000" +  url_for("app.authresponse")

    sd = json.dumps({
        "alexa:all": {
            "productID": session['user_config']['DEVICE_TYPE_ID'],
            "productInstanceAttributes": {
                "deviceSerialNumber": "001"
            }
        }
    })
    payload = {
        "client_id": session['user_config']['CLIENT_ID'],
        "scope": "alexa:all",
        "scope_data": sd,
        "response_type": "code",
        "redirect_uri": redirect_uri
    }

    query_str = "?" + urlencode(payload, doseq=True)
    driver = webdriver.Firefox(executable_path='/tmp/geckodriver')
    driver.get(auth_url + query_str)

    wait = WebDriverWait(driver, 10)
    amazon_sign_in = wait.until(EC.title_contains("Amazon.com Sign In"))

    if amazon_sign_in:
        username = driver.find_element_by_id('ap_email')
        password = driver.find_element_by_id('ap_password')
        submit_button = driver.find_element_by_id("signInSubmit")

        # Fill in email and password
        username.send_keys(session['user_config']['EMAIL'])
        password.send_keys(session['user_config']['PASSWORD'])
        submit_button.click()
        # driver.close()
        return redirect(url_for("app.authresponse"))
    else:
        flash("Login With Amazon page not found")
        return redirect(url_for("app.index"))

    return redirect(url_for("app.index"))

## This is the function where I lose the session for the same user
## This is the callback route that amazon sends the auth code to after the user is logged in
@app.route('/authresponse', methods=['GET', 'POST'])
def authresponse():
    code = None
    if request.method == 'GET':
        code = request.args.get('code', None)
        if code:
            user = User.query.filter_by(session_id=session.get("session_id")).first()

            if user:
                user.auth_code = code
                db.session.commit()

                # retrieve access token with POST request
                url = "https://api.amazon.com/auth/o2/token"
                payload = {
                    "client_id": user.client_id,
                    "client_secret": user.client_secret,
                    "code": code,
                    "grant_type": "authorization_code",
                    "redirect_uri": "http://localhost:5000" + url_for("app.authresponse")
                }
                r = requests.post(url, data=payload, timeout=5)
                if r.status_code == 200:
                    print r.text
                    return r.text
                else:
                    print r.text, r.status_code
            else:
                print "User not found"
                flash("Auth code not found.")

    return """code:
{}
""".format(code)

Body:
I was able to find a solution to have the user's information persist between different pages when making a Oauth2 request to amazon. I'm assuming the authentication process for other sites will be very similar so I am adding the solution I used.

Create a session ID and store in DB or Cache

Pass the state of your OAuth2 request into your payload via a "state" field, assign the state to be the session ID

 payload = {

            "state": session_id,
            "client_id": user.client_id,
            "client_secret": user.client_secret,
            "code": code,
            "grant_type": "authorization_code",
            "redirect_uri": "http://localhost:5000"
        }

In your redirect url that the authentication service sends the access token to, the STATE should appear in the query string of the redirect URI.

Grab the STATE from the query string and use it to fetch all the user information you want from the DB or Cache.

Amazon solution:

https://developer.amazon.com/public/apis/engage/login-with-amazon/docs/dynamically_redirect_users.html

https://developer.amazon.com/public/apis/engage/login-with-amazon/docs/cross_site_request_forgery.html


问:
Split a string into a String[] of a specific size
Assuming my delimiter is ',' (comma), I'm looking for a function split that will guarantee that the returned String[] array is a certain size (no more, no less):

```<code>String[] split(String str, int limit);

split("hello", 2);               => ["hello", ""]
split("hello,", 2);              => ["hello", ""]
split(",hello", 2);              => ["", "hello"]
split("hello,world", 2);         => ["hello", "world"]
split("hello,world,goodbye", 2); => ["hello", "world,goodbye"]
</code>```

See how the array size is always 2? I can get some of this behavior with Pattern.split, but not for every case... How can I do this?

答:
It seems that it would be easy enough to pad out a new array with empty strings. Here is a utility method you could use to perform this split.

```<code>public static String[] split(Pattern pattern, CharSequence input, int limit) {
    // perform the split
    tokens = pattern.split(input, limit);

    int tokenCount = tokens.length();
    if (tokenCount == limit) {
        // if no padding is necessary, return the result of pattern.split
        return tokens;
    } else {
        // create a new array, copy tokens into array, pad with empty string
        String[] padded = Arrays.copyOf(tokens, limit);
        for (int i = tokenCount; i < limit; i++) {
            padded[i] = "";
        }
        return padded;
    }
}
</code>```

Edit: Updated to shamelessly steal [Arrays.copyOf][1] from unholysampler's answer.

[1]: http://download.oracle.com/javase/6/docs/api/java/util/Arrays.html#copyOf(T[], int)

Body:
Assuming my delimiter is ',' (comma), I'm looking for a function split that will guarantee that the returned String[] array is a certain size (no more, no less):

String[] split(String str, int limit);

split("hello", 2);               => ["hello", ""]
split("hello,", 2);              => ["hello", ""]
split(",hello", 2);              => ["", "hello"]
split("hello,world", 2);         => ["hello", "world"]
split("hello,world,goodbye", 2); => ["hello", "world,goodbye"]

See how the array size is always 2? I can get some of this behavior with Pattern.split, but not for every case... How can I do this?

Body:
It seems that it would be easy enough to pad out a new array with empty strings. Here is a utility method you could use to perform this split.

public static String[] split(Pattern pattern, CharSequence input, int limit) {
    // perform the split
    tokens = pattern.split(input, limit);

    int tokenCount = tokens.length();
    if (tokenCount == limit) {
        // if no padding is necessary, return the result of pattern.split
        return tokens;
    } else {
        // create a new array, copy tokens into array, pad with empty string
        String[] padded = Arrays.copyOf(tokens, limit);
        for (int i = tokenCount; i < limit; i++) {
            padded[i] = "";
        }
        return padded;
    }
}

Edit: Updated to shamelessly steal [Arrays.copyOf][1] from unholysampler's answer.

[1]: http://download.oracle.com/javase/6/docs/api/java/util/Arrays.html#copyOf(T[], int)


问:
Login issues in Yii2
I have code result like this:

I want to login to an account, but I don't know how to modify the "welcome" message so that that message only come when we log in to an account. Does anyone know how to modify that? I'm using Yii2 framework.
Here is my code:
PATH: frontend\views\layout\main.php:

https://pastebin.com/Qqj1fb8f

and the index PATH: frontend\views\site\index:

https://pastebin.com/UwCezAmn

Please help me to solve that problem. Thanks in advance

答:
tipicallly  in you layout (eg: views\layout\main.php) you some code like this  login

```<code>    if (Yii::$app->user->isGuest) {
        $menuItems[] = ['label' => 'Login', 'url' => ['/user/login']];
    }
</code>```

asn you can use this menu item call for a  controller/action  (in this case /user/login)

then in the corresponding  controller/action

you should  have some  code like this

```<code>public function actionLogin()
{
    if (!\Yii::$app->user->isGuest) {
        $this->goHome();
    }

    $model = \Yii::createObject(LoginForm::className());

    $this->performAjaxValidation($model);

    if ($model->load(Yii::$app->getRequest()->post()) && $model->login()) {
        return $this->goBack();
    }

    return $this->render('login', [
        'model'  => $model,
        'module' => $this->module,
    ]);
}
</code>```

as you can see if the user is logged  (not isGuest)

```<code>  if (!\Yii::$app->user->isGuest) {
        $this->goHome();
    }
</code>```

in this case is invoked  the goHome  function

but you could invoke an your render for the view and you prefer with the welcome message you prefer
eg:

```<code>       return $this->render('my_welcome', [
        'model'  => $model,
     ]);
</code>```

Title: Login issues in Yii2

Body:
tipicallly  in you layout (eg: views\layout\main.php) you some code like this  login

    if (Yii::$app->user->isGuest) {
        $menuItems[] = ['label' => 'Login', 'url' => ['/user/login']];
    }

asn you can use this menu item call for a  controller/action  (in this case /user/login)

then in the corresponding  controller/action

you should  have some  code like this

public function actionLogin()
{
    if (!\Yii::$app->user->isGuest) {
        $this->goHome();
    }

    $model = \Yii::createObject(LoginForm::className());

    $this->performAjaxValidation($model);

    if ($model->load(Yii::$app->getRequest()->post()) && $model->login()) {
        return $this->goBack();
    }

    return $this->render('login', [
        'model'  => $model,
        'module' => $this->module,
    ]);
}

as you can see if the user is logged  (not isGuest)

  if (!\Yii::$app->user->isGuest) {
        $this->goHome();
    }

in this case is invoked  the goHome  function

but you could invoke an your render for the view and you prefer with the welcome message you prefer
eg:

       return $this->render('my_welcome', [
        'model'  => $model,
     ]);