问:
Rails strong parameters for infinitely nestable model
I have a model, QueryElement, with a child class, QueryGroup.
QueryGroup can contain nested QueryElements.

Say QueryGroup has a propertyname, and QueryElement has a property filter (just for example)

So for strong parameters I have something like:

```<code>params.fetch(:query).permit(:name, :filter, :query_elements => [:name, :filter, :query_elements => [...]
</code>```

And so on.

I could permit all (defeating the security of strong parameters, which I'd rather avoid), or manually step through the tree, which is much slower. That's my current approach.

Is there a better way?

答:
Something like this:

```<code>REQUIRED = %i( name ).freeze
ALLOWED = (%i( filter query_elements ) + REQUIRED).freeze
MAX_DEPTH = 5

def ensure_params(hash, nest_level = 0) # ah I never come up with good names...
  raise 'you went too deep man' if nest_level > MAX_DEPTH
  hash.fetch_values(*REQUIRED)
  hash[:query_elements] = ensure_params(hash[:query_elements], nest_level + 1) if hash[:query_elements]
  hash.slice(*ALLOWED)
end
</code>```

In IRB:

```<code>> ensure_params({ :filter => 2, :name => 'test', unpermitted_param: :something, :query_elements => { filter: 3, name: 'test', nested_unpermitted: 13 } })
# => {:filter=>2, :query_elements=>{:filter=>3, :name=>"test"}, :name=>"test"}
> ensure_params({ name: 1, query_elements: { notname: 1 } })
KeyError: key not found: :name
> MAX_DEPTH = 3
# => 3
> ensure_params({ name: 1, query_elements: { name: 1, query_elements: { name: 1, query_elements: { name: 1, query_elements: { name: 1, query_elements: { name: 1 } } } } }})
RuntimeError: you went too deep man
</code>```

There is probably some improvements that could be done, like converting the keys to symbols, have a better error message to tell you at which nest level there is a missing key, etc.

Body:
I have a model, QueryElement, with a child class, QueryGroup.
QueryGroup can contain nested QueryElements.

Say QueryGroup has a propertyname, and QueryElement has a property filter (just for example)

So for strong parameters I have something like:

params.fetch(:query).permit(:name, :filter, :query_elements => [:name, :filter, :query_elements => [...]

And so on.

I could permit all (defeating the security of strong parameters, which I'd rather avoid), or manually step through the tree, which is much slower. That's my current approach.

Is there a better way?

Body:
Something like this:

REQUIRED = %i( name ).freeze
ALLOWED = (%i( filter query_elements ) + REQUIRED).freeze
MAX_DEPTH = 5

def ensure_params(hash, nest_level = 0) # ah I never come up with good names...
  raise 'you went too deep man' if nest_level > MAX_DEPTH
  hash.fetch_values(*REQUIRED)
  hash[:query_elements] = ensure_params(hash[:query_elements], nest_level + 1) if hash[:query_elements]
  hash.slice(*ALLOWED)
end

In IRB:

> ensure_params({ :filter => 2, :name => 'test', unpermitted_param: :something, :query_elements => { filter: 3, name: 'test', nested_unpermitted: 13 } })
# => {:filter=>2, :query_elements=>{:filter=>3, :name=>"test"}, :name=>"test"}
> ensure_params({ name: 1, query_elements: { notname: 1 } })
KeyError: key not found: :name
> MAX_DEPTH = 3
# => 3
> ensure_params({ name: 1, query_elements: { name: 1, query_elements: { name: 1, query_elements: { name: 1, query_elements: { name: 1, query_elements: { name: 1 } } } } }})
RuntimeError: you went too deep man

There is probably some improvements that could be done, like converting the keys to symbols, have a better error message to tell you at which nest level there is a missing key, etc.


来源: stackexchange

问:
Radiobutton in Android Quiz app
I am working on quiz app for Android and I use RadioButtons in RadioGroup. I want to achieve that when someone checks the right answer (this case its id/krzyzyk) the score will increase by one point. I made this code:

```<code>int score = 2;

public void onRadioButtonClicked(View view) {
    RadioButton radiobutton1 = (RadioButton) findViewById(R.id.krzyzyk);

    if (radiobutton1.isChecked()) {
        score = score + 1;
    }
}
</code>```

It works but when I run the app and click in another RadioButton and again id/krzyzyk the score will update again. Can you help me to fix this problem?

答:
Your code will always increment the score when the user taps on the RadioButton krzyzyk.

I'll suggest you to Submit the answer and go to the next question incrementing the score if the selected RadioButton is correct.

Change your code to something like:

```<code>public void onRadioButtonClicked(View view) {
    // Is the button now checked?
    boolean checked = ((RadioButton) view).isChecked();

    // Check which radio button was clicked
    switch(view.getId()) {
        case R.id.correct_answer: // this is id/krzyzyk
            if (checked)
                score++;
                // Go to next question
            break;
        case R.id.wrong_answer:
            if (checked)
                // Go to next question.
            break;
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Radiobutton in Android Quiz app

Body:
I am working on quiz app for Android and I use RadioButtons in RadioGroup. I want to achieve that when someone checks the right answer (this case its id/krzyzyk) the score will increase by one point. I made this code:

int score = 2;

public void onRadioButtonClicked(View view) {
    RadioButton radiobutton1 = (RadioButton) findViewById(R.id.krzyzyk);

    if (radiobutton1.isChecked()) {
        score = score + 1;
    }
}

It works but when I run the app and click in another RadioButton and again id/krzyzyk the score will update again. Can you help me to fix this problem?

Body:
Your code will always increment the score when the user taps on the RadioButton krzyzyk.

I'll suggest you to Submit the answer and go to the next question incrementing the score if the selected RadioButton is correct.

Change your code to something like:

public void onRadioButtonClicked(View view) {
    // Is the button now checked?
    boolean checked = ((RadioButton) view).isChecked();

    // Check which radio button was clicked
    switch(view.getId()) {
        case R.id.correct_answer: // this is id/krzyzyk
            if (checked)
                score++;
                // Go to next question
            break;
        case R.id.wrong_answer:
            if (checked)
                // Go to next question.
            break;
    }
}


问:
How to achieve row level locking in cassandra
I have a Cassandra cluster setup like Node N1, Node N2 and Node N3

I have a user table, I need to write create a row level locking for it across the nodes in the cluster, So could you please guide me by answering the following questions?

1) What is the maximum level of locking possible in Cassandra?

2) What is lightweight transaction? How much it is possible to achieve row level locking?

3) Is there an alternate way to achieve the row level locking in Cassandra?

答:
None, but you might stretch it to say column level.

It uses paxos for consensus and can perform conditional updates. It doesnt do locking. It will either succeed or not if another update occurred, if it doesnt succeed you can try again. If it does succeed everything in "transaction" (poor naming) will apply. However, theres still no isolation within it and if multiple columns in row are updated you may read between them being applied. details here

Design data model so you dont need locking.

ContentLicense: CC BY-SA 4.0


问:
How to plot combinations of vectors and their elements
I need to plot many graphs with all the combination of the elemts of a matrix.

I have three columns. I would like to plot the time series of the elements named     A corresponding to     W1, then the time series of the elements named     B corresponding to     W1. Same with     W2; In reality my matrix is huge, but the idea should apply.

In particular, I would like to learn how to tell R to group together all the elements of     W1 separating them by the elements of     name.

Furthermore, what is the most efficient way to plot all these graphs (in the example below, I would need 4 graphs)?

```<code>name    W1   W2
A       123  24
A       754  7245
A       475  257
A       623  2457
A       525  27
A       256  72
A       352  725
B       257  572
B       572  577
B       75   257
B       27   257
B       247  7522
B       257  724
</code>```

答:
I use ggplot2 package for plotting, and the reshape2 package for converting wide data to long data.

```<code># get x values for your plots
df$x = ave(df$W1, df$name, FUN = seq_along)
# conver wide data to long
df_long = reshape2::melt(df, id.vars = c("name", "x"))

library(ggplot2)
# plot
ggplot(df_long, aes(x = x, y = value)) + geom_line() +
  facet_grid(name ~ variable)
</code>```

Using this data:

```<code>df = read.table(text = "name    W1   W2
A       123  24
A       754  7245
A       475  257
A       623  2457
A       525  27
A       256  72
A       352  725
B       257  572
B       572  577
B       75   257
B       27   257
B       247  7522
B       257  724", header= T)
</code>```

Body:
I need to plot many graphs with all the combination of the elemts of a matrix.

I have three columns. I would like to plot the time series of the elements named     A corresponding to     W1, then the time series of the elements named     B corresponding to     W1. Same with     W2; In reality my matrix is huge, but the idea should apply.

In particular, I would like to learn how to tell R to group together all the elements of     W1 separating them by the elements of     name.

Furthermore, what is the most efficient way to plot all these graphs (in the example below, I would need 4 graphs)?

name    W1   W2
A       123  24
A       754  7245
A       475  257
A       623  2457
A       525  27
A       256  72
A       352  725
B       257  572
B       572  577
B       75   257
B       27   257
B       247  7522
B       257  724

Body:
I use ggplot2 package for plotting, and the reshape2 package for converting wide data to long data.

# get x values for your plots
df$x = ave(df$W1, df$name, FUN = seq_along)
# conver wide data to long
df_long = reshape2::melt(df, id.vars = c("name", "x"))

library(ggplot2)
# plot
ggplot(df_long, aes(x = x, y = value)) + geom_line() +
  facet_grid(name ~ variable)

Using this data:

df = read.table(text = "name    W1   W2
A       123  24
A       754  7245
A       475  257
A       623  2457
A       525  27
A       256  72
A       352  725
B       257  572
B       572  577
B       75   257
B       27   257
B       247  7522
B       257  724", header= T)


问:
Is there a way to have change female to male voice during the conversation in DialogFlow (Api.ai)
We a building a chatbot app for Google Home using Api.ai (Dialogflow now) which has both male and female historical figures. We are using Actions on google. Google lets you default to a male or female voice when deploying the app. Is there a way to switch between male to female voice dynamically, for example, using code in webhook?</p>

答:
Maybe. Although SSML supports a <voice> tag, the documentation for Actions does not list it as supported. However, as you noted, there appears to be some support. The gender and variant attributes seem to work, at least for en-US. The languages attribute doesn't seem to be. So something like this might work:

```<code><speech>
    <voice gender="male" variant="1">male</voice>
    <voice gender="male" variant="2">male</voice>
    <voice gender="female" variant="1">female</voice>
    <voice gender="female" variant="2">female</voice>
</speech>
</code>```

However what is documented as working is to adjust the pitch of the default voice (whichever one you pick) using the <prosody> SSML tag. Here is an example you can use to see how it sounds if you vary the pitch:

```<code><speech>
    test
    <prosody pitch="-1st">test</prosody>
    <prosody pitch="-2st">test</prosody>
    <prosody pitch="-3st">test</prosody>
    <prosody pitch="-4st">test</prosody>
    <prosody pitch="-5st">test</prosody>
    <prosody pitch="-6st">test</prosody>
    <prosody pitch="-7st">test</prosody>
    <prosody pitch="-8st">test</prosody>
    <prosody pitch="-9st">test</prosody>
    <prosody pitch="+1st">test</prosody>
    <prosody pitch="+2st">test</prosody>
    <prosody pitch="+3st">test</prosody>
    <prosody pitch="+4st">test</prosody>
    <prosody pitch="+5st">test</prosody>
    <prosody pitch="+6st">test</prosody>
    <prosody pitch="+7st">test</prosody>
    <prosody pitch="+8st">test</prosody>
    <prosody pitch="+9st">test</prosody>
</speech>
</code>```

You can also combine the two tags.

Body:
Maybe. Although SSML supports a <voice> tag, the documentation for Actions does not list it as supported. However, as you noted, there appears to be some support. The gender and variant attributes seem to work, at least for en-US. The languages attribute doesn't seem to be. So something like this might work:

<speech>
    <voice gender="male" variant="1">male</voice>
    <voice gender="male" variant="2">male</voice>
    <voice gender="female" variant="1">female</voice>
    <voice gender="female" variant="2">female</voice>
</speech>

However what is documented as working is to adjust the pitch of the default voice (whichever one you pick) using the <prosody> SSML tag. Here is an example you can use to see how it sounds if you vary the pitch:

<speech>
    test
    <prosody pitch="-1st">test</prosody>
    <prosody pitch="-2st">test</prosody>
    <prosody pitch="-3st">test</prosody>
    <prosody pitch="-4st">test</prosody>
    <prosody pitch="-5st">test</prosody>
    <prosody pitch="-6st">test</prosody>
    <prosody pitch="-7st">test</prosody>
    <prosody pitch="-8st">test</prosody>
    <prosody pitch="-9st">test</prosody>
    <prosody pitch="+1st">test</prosody>
    <prosody pitch="+2st">test</prosody>
    <prosody pitch="+3st">test</prosody>
    <prosody pitch="+4st">test</prosody>
    <prosody pitch="+5st">test</prosody>
    <prosody pitch="+6st">test</prosody>
    <prosody pitch="+7st">test</prosody>
    <prosody pitch="+8st">test</prosody>
    <prosody pitch="+9st">test</prosody>
</speech>

You can also combine the two tags.


问:
Provide one of object types in typescript
If I type the following:

```<code>interface A {
    x: number
}
interface B {
    y: number
}

type Z = A | B;

// here it allows me to create a variable of type Z with both members of type A and B.
let z: Z = {
    x: 5,
    y: 6,
}
</code>```

I'm not able to ensure that object of type Z does contain all members of A but does not contain members of B (or the opposite). Is it possible at all with TypeScript? After much research I'm leaning to the "no" answer but I'm not sure.

答:
By default unions merge all options offered into one, but there are two options for you. What you want exactly is not available in TypeScript, but there are similar issues in the TS project's list (status: "open" at this time) as well as two good workarounds.

One option is not available: At this time there are no exact types in TypeScript (unlike in Flow). There is TS issue #12936 "Exact Types"  that right now still is open.

There is another issue/proposal in TS's list of open issues that asks exactly for what your question is about: #14094 "Proposal: Allow exclusive unions using logical or (^) operator between types"

You can use these workarounds:

Option #1

In TypeScript as well as in Flow you can use tagged types to created an XOR union instead of an OR one.

```<code>interface A {
    kind: 'A',
    x: number
}
interface B {
    kind: 'B',
    y: number
}

type Z = A | B;

// here it DOES NOT allow to create a variable of type Z with both members of type A and B.
let z: Z = {
    kind: 'A',
    x: 5
    // y: 6 will produce an error
}
</code>```

TS documentation on Discriminated Unions

Blog post about tagged union types introduced in TS 2.0 (link).

Option #2

The second option is to set all properties on all types, but set those that are not supposed to exist to undefined:

```<code>interface A {
    x: number,
    y?: undefined
}
interface B {
    x?: undefined,
    y: number
}

type Z = A | B;

let z: Z = {
    y: 5
    // y: 6 will produce an error
}
</code>```

For the record, in Facebook's type system Flow you can solve the problem by using a disjoint union  (XOR) instead of just a union (OR) or by using exact object types or as for TS above setting the undesirable property to undefined. I made a Flow demo with your example (link). In this case the code is the same for Flow as for TS.

Body:
If I type the following:

interface A {
    x: number
}
interface B {
    y: number
}

type Z = A | B;

// here it allows me to create a variable of type Z with both members of type A and B.
let z: Z = {
    x: 5,
    y: 6,
}

I'm not able to ensure that object of type Z does contain all members of A but does not contain members of B (or the opposite). Is it possible at all with TypeScript? After much research I'm leaning to the "no" answer but I'm not sure.

Body:
By default unions merge all options offered into one, but there are two options for you. What you want exactly is not available in TypeScript, but there are similar issues in the TS project's list (status: "open" at this time) as well as two good workarounds.

One option is not available: At this time there are no exact types in TypeScript (unlike in Flow). There is TS issue #12936 "Exact Types"  that right now still is open.

There is another issue/proposal in TS's list of open issues that asks exactly for what your question is about: #14094 "Proposal: Allow exclusive unions using logical or (^) operator between types"

You can use these workarounds:

Option #1

In TypeScript as well as in Flow you can use tagged types to created an XOR union instead of an OR one.

interface A {
    kind: 'A',
    x: number
}
interface B {
    kind: 'B',
    y: number
}

type Z = A | B;

// here it DOES NOT allow to create a variable of type Z with both members of type A and B.
let z: Z = {
    kind: 'A',
    x: 5
    // y: 6 will produce an error
}

TS documentation on Discriminated Unions

Blog post about tagged union types introduced in TS 2.0 (link).

Option #2

The second option is to set all properties on all types, but set those that are not supposed to exist to undefined:

interface A {
    x: number,
    y?: undefined
}
interface B {
    x?: undefined,
    y: number
}

type Z = A | B;

let z: Z = {
    y: 5
    // y: 6 will produce an error
}

For the record, in Facebook's type system Flow you can solve the problem by using a disjoint union  (XOR) instead of just a union (OR) or by using exact object types or as for TS above setting the undesirable property to undefined. I made a Flow demo with your example (link). In this case the code is the same for Flow as for TS.


问:
How to navigate through multiple links on website using vba internet explorer
I want to select options on multiple pages using vba internet explorer and i am able to open multiple tabs and multiple links using vba but only able to navigate on first page. Please check the coding given below for your reference:-

```<code>Sub mmtlink2()

Dim IE As New SHDocVw.InternetExplorer
Dim st As String
Dim htmldoc As MSHTML.HTMLDocument

Dim i As Long, d As Long, b As Long

'Set IE = CreateObject("InternetExplorer.Application")

IE.Visible = True

d = 2

For i = 1 To d

If i = 1 Then
    IE.navigate "https://www.makemytrip.com/air/search?tripType=O&itinerary=BOM-DXB-D-02Dec2017&paxType=A-1&cabinClass=E"

Else
    IE.Navigate2 "https://www.makemytrip.com/air/search?tripType=O&itinerary=BOM-DXB-D-03Dec2017&paxType=A-1&cabinClass=E", 2048
End If

 Do While IE.Busy = True Or IE.readyState <> 4
 Loop

    Set htmldoc = IE.document

    htmldoc.getElementById("Non stop").Click
Next i

End Sub
</code>```

Please provide any solution to navigate on second page as well.

答:
Correct your syntax within the Else Statement:

```<code>Else
    IE.Navigate url, 2048
</code>```

instead of

```<code>Else
    IE.Navigate2 url, 2048
</code>```

Body:
I want to select options on multiple pages using vba internet explorer and i am able to open multiple tabs and multiple links using vba but only able to navigate on first page. Please check the coding given below for your reference:-

Sub mmtlink2()

Dim IE As New SHDocVw.InternetExplorer
Dim st As String
Dim htmldoc As MSHTML.HTMLDocument

Dim i As Long, d As Long, b As Long

'Set IE = CreateObject("InternetExplorer.Application")

IE.Visible = True

d = 2

For i = 1 To d

If i = 1 Then
    IE.navigate "https://www.makemytrip.com/air/search?tripType=O&itinerary=BOM-DXB-D-02Dec2017&paxType=A-1&cabinClass=E"

Else
    IE.Navigate2 "https://www.makemytrip.com/air/search?tripType=O&itinerary=BOM-DXB-D-03Dec2017&paxType=A-1&cabinClass=E", 2048
End If

 Do While IE.Busy = True Or IE.readyState <> 4
 Loop

    Set htmldoc = IE.document

    htmldoc.getElementById("Non stop").Click
Next i

End Sub

Please provide any solution to navigate on second page as well.

Body:
Correct your syntax within the Else Statement:

Else
    IE.Navigate url, 2048

instead of

Else
    IE.Navigate2 url, 2048


问:
shiny renderUI resets unnecessarily with NavBar change
I am using a combination of NavBar page and Dashboard so that I can have a sidebar as well as different navbar tabs. I have a renderUI that changes based on which tab you are on.

I noticed that my renderUI does not stay constant as you switch among the navabs. This problem only occurs when the renderUi is dependent on the tab selected.

Can this be fixed?? I would like the input selected while someone is on Tab2 to stay selected if they go to Tab3.

See my minimum example here:

```<code>library(shiny)
ui <- dashboardPage(
  dashboardHeader(),
  dashboardSidebar(
    selectInput("filter1","Filter1",c("a","b","c")),
    uiOutput("test")),
  dashboardBody(
    fluidPage(
      navbarPage(
    header="",title=NULL,id="navbar" ,collapsible = TRUE,fluid = TRUE,inverse = TRUE,
        tabPanel("Tab1",
             box(width=12,
                 h3("hello world"))),
        tabPanel("Tab2",
             box(width = 12,
                 h3(textOutput("txt")))),
        tabPanel("Tab3",
             box(width = 12,
                 h3(textOutput("txt2"))))
  ))))

server <- function(input, output,session){
  output$test<-renderUI({
    if (input$navbar == "Tab1"){

    }else{
      selectInput("test","Test",c("a","b","c"))
    }
  })

  output$txt<-renderText({
    paste0("You selected: ",as.character(input$test))
  })

  output$txt2<-renderText({
    paste0("You selected: ",as.character(input$test))
  })
}

shinyApp(ui = ui, server = server)
</code>```

Also, I know that I could make conditional sidebar, but in my real app I have a ton of stuff in the sidebar and I really don't want to completely duplicate it... There must be a better  way!

答:
You can use conditionalPanel rather than renderUI. Replace uiOutput("test") with the following code.

```<code>conditionalPanel(
  "input.navbar != 'Tab1'",
  selectInput("test","Test",c("a","b","c"))
)
</code>```

Edit

If you want filter1 to disappear as well, add it to the conditionalpanel like so.

```<code>conditionalPanel(
  "input.navbar != 'Tab1'",
  selectInput("filter1", "Filter1", c("a", "b", "c")),
  selectInput("test", "Test", c("a", "b", "c"))
)
</code>```

Body:
I am using a combination of NavBar page and Dashboard so that I can have a sidebar as well as different navbar tabs. I have a renderUI that changes based on which tab you are on.

I noticed that my renderUI does not stay constant as you switch among the navabs. This problem only occurs when the renderUi is dependent on the tab selected.

Can this be fixed?? I would like the input selected while someone is on Tab2 to stay selected if they go to Tab3.

See my minimum example here:

library(shiny)
ui <- dashboardPage(
  dashboardHeader(),
  dashboardSidebar(
    selectInput("filter1","Filter1",c("a","b","c")),
    uiOutput("test")),
  dashboardBody(
    fluidPage(
      navbarPage(
    header="",title=NULL,id="navbar" ,collapsible = TRUE,fluid = TRUE,inverse = TRUE,
        tabPanel("Tab1",
             box(width=12,
                 h3("hello world"))),
        tabPanel("Tab2",
             box(width = 12,
                 h3(textOutput("txt")))),
        tabPanel("Tab3",
             box(width = 12,
                 h3(textOutput("txt2"))))
  ))))

server <- function(input, output,session){
  output$test<-renderUI({
    if (input$navbar == "Tab1"){

    }else{
      selectInput("test","Test",c("a","b","c"))
    }
  })

  output$txt<-renderText({
    paste0("You selected: ",as.character(input$test))
  })

  output$txt2<-renderText({
    paste0("You selected: ",as.character(input$test))
  })
}

shinyApp(ui = ui, server = server)

Also, I know that I could make conditional sidebar, but in my real app I have a ton of stuff in the sidebar and I really don't want to completely duplicate it... There must be a better  way!

Body:
You can use conditionalPanel rather than renderUI. Replace uiOutput("test") with the following code.

conditionalPanel(
  "input.navbar != 'Tab1'",
  selectInput("test","Test",c("a","b","c"))
)

Edit

If you want filter1 to disappear as well, add it to the conditionalpanel like so.

conditionalPanel(
  "input.navbar != 'Tab1'",
  selectInput("filter1", "Filter1", c("a", "b", "c")),
  selectInput("test", "Test", c("a", "b", "c"))
)


答:
To give you an idea how bloated this will get with low-level tools like scipy's linprog as we have to mimic their standard-form:

The basic idea is to:

add an auxiliary-variable for the mean, like Erwin proposed

add n-auxiliary-variables to handle the absolute values like documented in lpsolve's docs

(and i'm using n-extra-aux-vars as temp-vars for x-mean)

Now this example works.

For your data you have to be careful in regards to the bounds. Make sure, the problem stays feasible. The problem itself is pretty unstable as hard-constraints are used for Ax=b; usually you would minimize some norm / least-squares here (no LP anymore; QP/SOCP) and add this error to the objective)!

It might be needed to switch the solver from method='simplex' to method='interior-point' at some point (only available since scipy 1.0).

Alternative:

Using cvxpy, formulation is much easier (both variants mentioned) and you get quite a good solver (ECOS) for free.

Code:

```<code>import numpy as np
import scipy.optimize as spo
np.set_printoptions(linewidth=120)
np.random.seed(1)

""" Create random data """
M, N = 2, 3
A = np.random.random(size=(M,N))
x_hidden = np.random.random(size=N)
b = A.dot(x_hidden)  # target
n = N

print('Original A')
print(A)
print('hidden x: ', x_hidden)
print('target: ', b)

""" Optimize as LP """
def solve(A, b, n):
    print('Reformulation')
    am, an = A.shape

    # Introduce aux-vars
    # 1: y = mean
    # n: z = x - mean
    # n: abs(z)
    n_plus_aux_vars = 3*n + 1

    # Equality constraint: y = mean
    eq_mean_A = np.zeros(n_plus_aux_vars)
    eq_mean_A[:n] = 1. / n
    eq_mean_A[n] = -1.
    eq_mean_b = np.array([0])

    print('y = mean A:')
    print(eq_mean_A)
    print('y = mean b:')
    print(eq_mean_b)

    # Equality constraints: Ax = b
    eq_A = np.zeros((am, n_plus_aux_vars))
    eq_A[:, :n] = A[:, :n]
    eq_b = np.copy(b)

    print('Ax=b A:')
    print(eq_A)
    print('Ax=b b:')
    print(eq_b)

    # Equality constraints: z = x - mean
    eq_mean_A_z = np.hstack([-np.eye(n), np.ones((n, 1)), + np.eye(n), np.zeros((n, n))])
    eq_mean_b_z = np.zeros(n)

    print('z = x - mean A:')
    print(eq_mean_A_z)
    print('z = x - mean b:')
    print(eq_mean_b_z)

    # Inequality constraints: absolute values -> x <= x' ; -x <= x'

    ineq_abs_0_A = np.hstack([np.zeros((n, n)), np.zeros((n, 1)), np.eye(n), -np.eye(n)])
    ineq_abs_0_b = np.zeros(n)

    ineq_abs_1_A = np.hstack([np.zeros((n, n)), np.zeros((n, 1)), -np.eye(n), -np.eye(n)])
    ineq_abs_1_b = np.zeros(n)

    # Bounds
    # REMARK: Do not touch anything besides the first bounds-row!
    bounds = [(0., 1.) for i in range(n)] +     \
             [(None, None)] +                   \
             [(None, None) for i in range(n)] + \
             [(0, None) for i in range(n)]

    # Objective
    c = np.zeros(n_plus_aux_vars)
    c[-n:] = 1

    A_eq = np.vstack((eq_mean_A, eq_A, eq_mean_A_z))
    b_eq = np.hstack([eq_mean_b, eq_b, eq_mean_b_z])

    A_ineq = np.vstack((ineq_abs_0_A, ineq_abs_1_A))
    b_ineq = np.hstack([ineq_abs_0_b, ineq_abs_1_b])

    print('solve...')
    result = spo.linprog(c, A_ineq, b_ineq, A_eq, b_eq, bounds=bounds, method='simplex')
    print(result)
    x = result.x[:n]
    print('x: ', x)
    print('residual Ax-b: ', A.dot(x) - b)
    print('mean: ', result.x[n])
    print('x - mean: ', x - result.x[n])
    print('l1-norm(x - mean) / objective: ', np.linalg.norm(x - result.x[n], 1))

solve(A, b, n)
</code>```

Output:

```<code>Original A
[[  4.17022005e-01   7.20324493e-01   1.14374817e-04]
 [  3.02332573e-01   1.46755891e-01   9.23385948e-02]]
hidden x:  [ 0.18626021  0.34556073  0.39676747]
target:  [ 0.32663584  0.14366255]
Reformulation
y = mean A:
[ 0.33333333  0.33333333  0.33333333 -1.          0.          0.          0.          0.          0.          0.        ]
y = mean b:
[0]
Ax=b A:
[[  4.17022005e-01   7.20324493e-01   1.14374817e-04   0.00000000e+00   0.00000000e+00   0.00000000e+00   0.00000000e+00
    0.00000000e+00   0.00000000e+00   0.00000000e+00]
 [  3.02332573e-01   1.46755891e-01   9.23385948e-02   0.00000000e+00   0.00000000e+00   0.00000000e+00   0.00000000e+00
    0.00000000e+00   0.00000000e+00   0.00000000e+00]]
Ax=b b:
[ 0.32663584  0.14366255]
z = x - mean A:
[[-1. -0. -0.  1.  1.  0.  0.  0.  0.  0.]
 [-0. -1. -0.  1.  0.  1.  0.  0.  0.  0.]
 [-0. -0. -1.  1.  0.  0.  1.  0.  0.  0.]]
z = x - mean b:
[ 0.  0.  0.]
solve...
     fun: 0.078779576294411263
 message: 'Optimization terminated successfully.'
     nit: 10
   slack: array([ 0.07877958,  0.        ,  0.        ,  0.        ,  0.07877958,  0.        ,  0.76273076,  0.68395118,
        0.72334097])
  status: 0
 success: True
       x: array([ 0.23726924,  0.31604882,  0.27665903,  0.27665903, -0.03938979,  0.03938979,  0.        ,  0.03938979,
        0.03938979,  0.        ])
x:  [ 0.23726924  0.31604882  0.27665903]
residual Ax-b:  [  5.55111512e-17   0.00000000e+00]
mean:  0.276659030053
x - mean:  [-0.03938979  0.03938979  0.        ]
l1-norm(x - mean) / objective:  0.0787795762944
</code>```

Now for your original data, things get tough!

You need to:

scale your data as the magnitude of your variables will hurt the solver

depending on your task you might need to analyze the effects of scaling / invert it

use the interior-point solver

be careful with the bounds

Example:

```<code>A = np.array([[3582.000000, 3394.000000, 3356.000000, 3256.000000, 3415.000000,
        3505.000000, 3442.000000, 3381.000000, 3392.000000],
       [233445193.000000, 217344811.000000, 237746918.000000,
        219204892.000000, 225272825.000000, 242819442.000000,
        215258725.000000, 227681178.000000, 215189377.000000],
       [559090945.000000, 496500751.000000, 493639029.000000,
        461547877.000000, 501057960.000000, 505073223.000000,
        490458632.000000, 503102998.000000, 487026744.000000]])
b = np.array([8531., 1079115532., 429386951.])

A /= 10000.  # scaling
b /= 10000.  # scaling

bounds = [(-50., 50.) for i in range(n)] +     \
...

result = spo.linprog(c, A_ineq, b_ineq, A_eq, b_eq, bounds=bounds, method='interior-point')
</code>```

Output:

```<code>solve...
     con: array([  3.98410760e-09,   1.18067724e-08,   8.12879938e-04,   1.75969041e-03,  -3.93853838e-09,  -3.96305566e-09,
        -4.10043555e-09,  -3.94957667e-09,  -3.88362764e-09,  -3.89452381e-09,  -3.95134592e-09,  -3.92182287e-09,
        -3.85762178e-09])
     fun: 52.742900697626389
 message: 'Optimization terminated successfully.'
     nit: 8
   slack: array([  5.13245265e+01,   1.89309145e-08,   1.83429094e-09,   4.28687782e-09,   1.03726911e-08,   2.77000474e-09,
         1.41837413e+00,   6.75769654e-09,   8.65285462e-10,   2.78501844e-09,   3.09591539e-09,   5.27429006e+01,
         1.30944103e-08,   5.32994799e-09,   3.15369669e-08,   2.51943821e-09,   7.54848797e-09,   3.22510447e-09])
  status: 0
 success: True
       x: array([ -2.51938304e+01,   4.68432810e-01,   2.68398831e+01,   4.68432822e-01,   4.68432815e-01,   4.68432832e-01,
        -2.40754247e-01,   4.68432818e-01,   4.68432819e-01,   4.68432822e-01,  -2.56622633e+01,  -7.91749954e-09,
         2.63714503e+01,   4.40376624e-09,  -2.52137156e-09,   1.43834811e-08,  -7.09187065e-01,   3.95395716e-10,
         1.17990950e-09,   2.56622633e+01,   1.10134149e-08,   2.63714503e+01,   8.69064406e-09,   7.85131955e-09,
         1.71534858e-08,   7.09187068e-01,   7.15309226e-09,   2.04519496e-09])
x:  [-25.19383044   0.46843281  26.83988313   0.46843282   0.46843282   0.46843283  -0.24075425   0.46843282   0.46843282]
residual Ax-b:  [ -1.18067724e-08  -8.12879938e-04  -1.75969041e-03]
mean:  0.468432821891
x - mean:  [ -2.56622633e+01  -1.18805552e-08   2.63714503e+01   4.54189575e-10  -6.40499920e-09   1.04889573e-08  -7.09187069e-01
  -3.52642715e-09  -2.67771227e-09]
l1-norm(x - mean) / objective:  52.7429006758
</code>```

Edit

Here a SOCP-based least-squares (soft-constrained) approach, which i would recommend in terms of numerical-stability! This approach can and should be tuned for whatever you need. It's implemented using the already mentioned cvxpy modelling-tool using the ECOS solver.

The basic idea:

instead of: min(l1-norm(x - mean(x)) st. Ax=b

solve: min(l2-norm(Ax-b) + c * l1-norm(x - mean(x)))

where c is the nonnegative trade-off parameter

small c: Ax=b is more important

big c: x - mean(x) is more important

Example code & output for your data and bounds of -50, 50 and c=1e-3:

```<code>import numpy as np
import cvxpy as cvx

""" DATA """
A = np.array([[3582.000000, 3394.000000, 3356.000000, 3256.000000, 3415.000000,
        3505.000000, 3442.000000, 3381.000000, 3392.000000],
       [233445193.000000, 217344811.000000, 237746918.000000,
        219204892.000000, 225272825.000000, 242819442.000000,
        215258725.000000, 227681178.000000, 215189377.000000],
       [559090945.000000, 496500751.000000, 493639029.000000,
        461547877.000000, 501057960.000000, 505073223.000000,
        490458632.000000, 503102998.000000, 487026744.000000]])
b = np.array([8531., 1079115532., 429386951.])
n = 9

# A /= 10000.  scaling would be a good idea
# b /= 10000.  """

""" SOCP-based least-squares approach """
def solve(A, b, n, c=1e-1):
    x = cvx.Variable(n)
    y = cvx.Variable(1)             # mean

    lower_bounds = np.zeros(n) - 50  # -50
    upper_bounds = np.zeros(n) + 50  #  50

    constraints = []
    constraints.append(x >= lower_bounds)
    constraints.append(x <= upper_bounds)
    constraints.append(y == cvx.sum_entries(x) / n)

    objective = cvx.Minimize(cvx.norm(A*x-b, 2) + c * cvx.norm(x - y, 1))
    problem = cvx.Problem(objective, constraints)

    problem.solve(solver=cvx.ECOS, verbose=True)

    print('Objective: ', problem.value)
    print('x: ', x.T.value)
    print('mean: ', y.value)
    print('Ax-b: ')
    print((A*x - b).value)
    print('x - mean: ', (x - y).T.value)

solve(A, b, n)
</code>```

Output:

```<code> ECOS 2.0.4 - (C) embotech GmbH, Zurich Switzerland, 2012-15. Web: www.embotech.com/ECOS

It     pcost       dcost      gap   pres   dres    k/t    mu     step   sigma     IR    |   BT
 0  +2.637e-17  -1.550e+06  +7e+08  1e-01  2e-04  1e+00  2e+07    ---    ---    1  1  - |  -  -
 1  -8.613e+04  -1.014e+05  +8e+06  1e-03  2e-06  2e+03  2e+05  0.9890  1e-04   2  1  1 |  0  0
 2  -1.287e+03  -1.464e+03  +1e+05  1e-05  9e-08  4e+01  3e+03  0.9872  1e-04   3  1  1 |  0  0
 3  +1.794e+02  +1.900e+02  +2e+03  2e-07  1e-07  1e+01  5e+01  0.9890  5e-03   5  3  4 |  0  0
 4  -1.388e+00  -6.826e-01  +1e+02  1e-08  7e-08  9e-01  3e+00  0.9458  4e-03   7  6  6 |  0  0
 5  +5.491e+00  +5.683e+00  +1e+01  1e-09  8e-09  2e-01  3e-01  0.9617  6e-02   1  1  1 |  0  0
 6  +6.480e+00  +6.505e+00  +1e+00  2e-10  5e-10  3e-02  4e-02  0.8928  2e-02   1  1  1 |  0  0
 7  +6.746e+00  +6.746e+00  +2e-02  3e-12  5e-10  5e-04  6e-04  0.9890  5e-03   1  0  0 |  0  0
 8  +6.759e+00  +6.759e+00  +3e-04  2e-12  2e-10  6e-06  7e-06  0.9890  1e-04   1  0  0 |  0  0
 9  +6.759e+00  +6.759e+00  +3e-06  2e-13  2e-10  6e-08  8e-08  0.9890  1e-04   2  0  0 |  0  0
10  +6.758e+00  +6.758e+00  +3e-08  5e-14  2e-10  7e-10  9e-10  0.9890  1e-04   1  0  0 |  0  0

OPTIMAL (within feastol=2.0e-10, reltol=4.7e-09, abstol=3.2e-08).
Runtime: 0.002901 seconds.

Objective:  6.757722879805085
x:  [[-18.09169736  -5.55768047  11.12130645  11.48355878  -1.13982006
   12.4290884   -3.00165819  -1.05158589  -2.4468432 ]]
mean:  0.416074272576
Ax-b:
[[  2.17051777e-03]
 [  1.90734863e-06]
 [ -5.72204590e-06]]
x - mean:  [[-18.50777164  -5.97375474  10.70523218  11.0674845   -1.55589434
   12.01301413  -3.41773246  -1.46766016  -2.86291747]]
</code>```

This approach will always output a feasible solution (for our task) and you can then decide on the observed residual if it works for you.

As you observed, a lower-bound of 0 is deadly, in all formulations (look at the magnitude difference in your data!).

Here a lower-bound of 0 will get you a solution with some high residual-error.

E.g.:

c=1e-7

bounds = 0 / 15

Output:

```<code>Objective:  785913288.2410747
x:  [[ -5.57966858e-08  -4.74997454e-08   1.56066068e+00   1.68021234e-07
   -3.55602958e-08   1.75340641e-06  -4.69609562e-08  -3.10216680e-08
   -4.39482554e-08]]
mean:  0.173406926909
Ax-b:
[[ -3.29341696e+03]
 [ -7.08072860e+08]
 [  3.41016903e+08]]
x - mean:  [[-0.17340698 -0.17340697  1.38725375 -0.17340676 -0.17340696 -0.17340517
  -0.17340697 -0.17340696 -0.17340697]]
</code>```

Title: scipy.optimize Constrained Minimization SLSQP - Cannot Match the target 100%

Body:
I am trying to get the minimized weight that's closer to average weight combined. My current problem is using the SLSQP solver I cannot find the right weight that meet the target 100%. Is there another solver I could use to solve my problem? Or any math suggestions. Please help.

My math right now is

           **min(∑|x-mean(x)|)**

           **s.t.** Aw-b=0, w>=0

           **bound** 0.2'<'x<0.5

Data

  nRow# Variable1   Variable2   Variable3

  1 3582.00 233445193.00    559090945.00

  2 3394.00 217344811.00    496500751.00

  3 3356.00 237746918.00    493639029.00

  4 3256.00 219204892.00    461547877.00

  5 3415.00 225272825.00    501057960.00

  6 3505.00 242819442.00    505073223.00

  7 3442.00 215258725.00    490458632.00

  8 3381.00 227681178.00    503102998.00

  9 3392.00 215189377.00    487026744.00

    w1          w2                     w3
  Target    8531.00 429386951.00    1079115532.00

Question: Find the minimized weight that are closer to average

Python Code:

A = np.array([[3582.000000, 3394.000000, 3356.000000, 3256.000000, 3415.000000,
        3505.000000, 3442.000000, 3381.000000, 3392.000000],
       [233445193.000000, 217344811.000000, 237746918.000000,
        219204892.000000, 225272825.000000, 242819442.000000,
        215258725.000000, 227681178.000000, 215189377.000000],
       [559090945.000000, 496500751.000000, 493639029.000000,
        461547877.000000, 501057960.000000, 505073223.000000,
        490458632.000000, 503102998.000000, 487026744.000000]])

b = np.array([8531, 1079115532, 429386951])

n=9
def fsolveMin(A,b,n):

    # The constraints: Ax = b

    def cons(x):
        return A.dot(x)-b

    cons = ({'type':'eq','fun':cons},

            {'type':'ineq','fun':lambda x:x[0]})

    # The minimizing constraints: the total absolute difference between the coefficients

    def fn(x):
        return np.sum(np.abs(x-np.mean(x)))

    # Initialize the coefficients randomly
    z0 = abs(np.random.randn(len(A[1,:])))

    # Set up bound
   # bnds = [(0, None)]*n

    # Solve the problem

    sol = minimize(fn, x0 = z0, constraints = cons, method = 'SLSQP', options={'disp': True})

    #expected 35%
    print(sol.x)
    print(A.dot(sol.x))

    #print(fn(sol.x))

print(str(fsolveMin(A,b,n))+"\n\n")

Body:
To give you an idea how bloated this will get with low-level tools like scipy's linprog as we have to mimic their standard-form:

The basic idea is to:

add an auxiliary-variable for the mean, like Erwin proposed

add n-auxiliary-variables to handle the absolute values like documented in lpsolve's docs

(and i'm using n-extra-aux-vars as temp-vars for x-mean)

Now this example works.

For your data you have to be careful in regards to the bounds. Make sure, the problem stays feasible. The problem itself is pretty unstable as hard-constraints are used for Ax=b; usually you would minimize some norm / least-squares here (no LP anymore; QP/SOCP) and add this error to the objective)!

It might be needed to switch the solver from method='simplex' to method='interior-point' at some point (only available since scipy 1.0).

Alternative:

Using cvxpy, formulation is much easier (both variants mentioned) and you get quite a good solver (ECOS) for free.

Code:

import numpy as np
import scipy.optimize as spo
np.set_printoptions(linewidth=120)
np.random.seed(1)

""" Create random data """
M, N = 2, 3
A = np.random.random(size=(M,N))
x_hidden = np.random.random(size=N)
b = A.dot(x_hidden)  # target
n = N

print('Original A')
print(A)
print('hidden x: ', x_hidden)
print('target: ', b)

""" Optimize as LP """
def solve(A, b, n):
    print('Reformulation')
    am, an = A.shape

    # Introduce aux-vars
    # 1: y = mean
    # n: z = x - mean
    # n: abs(z)
    n_plus_aux_vars = 3*n + 1

    # Equality constraint: y = mean
    eq_mean_A = np.zeros(n_plus_aux_vars)
    eq_mean_A[:n] = 1. / n
    eq_mean_A[n] = -1.
    eq_mean_b = np.array([0])

    print('y = mean A:')
    print(eq_mean_A)
    print('y = mean b:')
    print(eq_mean_b)

    # Equality constraints: Ax = b
    eq_A = np.zeros((am, n_plus_aux_vars))
    eq_A[:, :n] = A[:, :n]
    eq_b = np.copy(b)

    print('Ax=b A:')
    print(eq_A)
    print('Ax=b b:')
    print(eq_b)

    # Equality constraints: z = x - mean
    eq_mean_A_z = np.hstack([-np.eye(n), np.ones((n, 1)), + np.eye(n), np.zeros((n, n))])
    eq_mean_b_z = np.zeros(n)

    print('z = x - mean A:')
    print(eq_mean_A_z)
    print('z = x - mean b:')
    print(eq_mean_b_z)

    # Inequality constraints: absolute values -> x <= x' ; -x <= x'

    ineq_abs_0_A = np.hstack([np.zeros((n, n)), np.zeros((n, 1)), np.eye(n), -np.eye(n)])
    ineq_abs_0_b = np.zeros(n)

    ineq_abs_1_A = np.hstack([np.zeros((n, n)), np.zeros((n, 1)), -np.eye(n), -np.eye(n)])
    ineq_abs_1_b = np.zeros(n)

    # Bounds
    # REMARK: Do not touch anything besides the first bounds-row!
    bounds = [(0., 1.) for i in range(n)] +     \
             [(None, None)] +                   \
             [(None, None) for i in range(n)] + \
             [(0, None) for i in range(n)]

    # Objective
    c = np.zeros(n_plus_aux_vars)
    c[-n:] = 1

    A_eq = np.vstack((eq_mean_A, eq_A, eq_mean_A_z))
    b_eq = np.hstack([eq_mean_b, eq_b, eq_mean_b_z])

    A_ineq = np.vstack((ineq_abs_0_A, ineq_abs_1_A))
    b_ineq = np.hstack([ineq_abs_0_b, ineq_abs_1_b])

    print('solve...')
    result = spo.linprog(c, A_ineq, b_ineq, A_eq, b_eq, bounds=bounds, method='simplex')
    print(result)
    x = result.x[:n]
    print('x: ', x)
    print('residual Ax-b: ', A.dot(x) - b)
    print('mean: ', result.x[n])
    print('x - mean: ', x - result.x[n])
    print('l1-norm(x - mean) / objective: ', np.linalg.norm(x - result.x[n], 1))

solve(A, b, n)

Output:

Original A
[[  4.17022005e-01   7.20324493e-01   1.14374817e-04]
 [  3.02332573e-01   1.46755891e-01   9.23385948e-02]]
hidden x:  [ 0.18626021  0.34556073  0.39676747]
target:  [ 0.32663584  0.14366255]
Reformulation
y = mean A:
[ 0.33333333  0.33333333  0.33333333 -1.          0.          0.          0.          0.          0.          0.        ]
y = mean b:
[0]
Ax=b A:
[[  4.17022005e-01   7.20324493e-01   1.14374817e-04   0.00000000e+00   0.00000000e+00   0.00000000e+00   0.00000000e+00
    0.00000000e+00   0.00000000e+00   0.00000000e+00]
 [  3.02332573e-01   1.46755891e-01   9.23385948e-02   0.00000000e+00   0.00000000e+00   0.00000000e+00   0.00000000e+00
    0.00000000e+00   0.00000000e+00   0.00000000e+00]]
Ax=b b:
[ 0.32663584  0.14366255]
z = x - mean A:
[[-1. -0. -0.  1.  1.  0.  0.  0.  0.  0.]
 [-0. -1. -0.  1.  0.  1.  0.  0.  0.  0.]
 [-0. -0. -1.  1.  0.  0.  1.  0.  0.  0.]]
z = x - mean b:
[ 0.  0.  0.]
solve...
     fun: 0.078779576294411263
 message: 'Optimization terminated successfully.'
     nit: 10
   slack: array([ 0.07877958,  0.        ,  0.        ,  0.        ,  0.07877958,  0.        ,  0.76273076,  0.68395118,
        0.72334097])
  status: 0
 success: True
       x: array([ 0.23726924,  0.31604882,  0.27665903,  0.27665903, -0.03938979,  0.03938979,  0.        ,  0.03938979,
        0.03938979,  0.        ])
x:  [ 0.23726924  0.31604882  0.27665903]
residual Ax-b:  [  5.55111512e-17   0.00000000e+00]
mean:  0.276659030053
x - mean:  [-0.03938979  0.03938979  0.        ]
l1-norm(x - mean) / objective:  0.0787795762944

Now for your original data, things get tough!

You need to:

scale your data as the magnitude of your variables will hurt the solver

depending on your task you might need to analyze the effects of scaling / invert it

use the interior-point solver

be careful with the bounds

Example:

A = np.array([[3582.000000, 3394.000000, 3356.000000, 3256.000000, 3415.000000,
        3505.000000, 3442.000000, 3381.000000, 3392.000000],
       [233445193.000000, 217344811.000000, 237746918.000000,
        219204892.000000, 225272825.000000, 242819442.000000,
        215258725.000000, 227681178.000000, 215189377.000000],
       [559090945.000000, 496500751.000000, 493639029.000000,
        461547877.000000, 501057960.000000, 505073223.000000,
        490458632.000000, 503102998.000000, 487026744.000000]])
b = np.array([8531., 1079115532., 429386951.])

A /= 10000.  # scaling
b /= 10000.  # scaling

bounds = [(-50., 50.) for i in range(n)] +     \
...

result = spo.linprog(c, A_ineq, b_ineq, A_eq, b_eq, bounds=bounds, method='interior-point')

Output:

solve...
     con: array([  3.98410760e-09,   1.18067724e-08,   8.12879938e-04,   1.75969041e-03,  -3.93853838e-09,  -3.96305566e-09,
        -4.10043555e-09,  -3.94957667e-09,  -3.88362764e-09,  -3.89452381e-09,  -3.95134592e-09,  -3.92182287e-09,
        -3.85762178e-09])
     fun: 52.742900697626389
 message: 'Optimization terminated successfully.'
     nit: 8
   slack: array([  5.13245265e+01,   1.89309145e-08,   1.83429094e-09,   4.28687782e-09,   1.03726911e-08,   2.77000474e-09,
         1.41837413e+00,   6.75769654e-09,   8.65285462e-10,   2.78501844e-09,   3.09591539e-09,   5.27429006e+01,
         1.30944103e-08,   5.32994799e-09,   3.15369669e-08,   2.51943821e-09,   7.54848797e-09,   3.22510447e-09])
  status: 0
 success: True
       x: array([ -2.51938304e+01,   4.68432810e-01,   2.68398831e+01,   4.68432822e-01,   4.68432815e-01,   4.68432832e-01,
        -2.40754247e-01,   4.68432818e-01,   4.68432819e-01,   4.68432822e-01,  -2.56622633e+01,  -7.91749954e-09,
         2.63714503e+01,   4.40376624e-09,  -2.52137156e-09,   1.43834811e-08,  -7.09187065e-01,   3.95395716e-10,
         1.17990950e-09,   2.56622633e+01,   1.10134149e-08,   2.63714503e+01,   8.69064406e-09,   7.85131955e-09,
         1.71534858e-08,   7.09187068e-01,   7.15309226e-09,   2.04519496e-09])
x:  [-25.19383044   0.46843281  26.83988313   0.46843282   0.46843282   0.46843283  -0.24075425   0.46843282   0.46843282]
residual Ax-b:  [ -1.18067724e-08  -8.12879938e-04  -1.75969041e-03]
mean:  0.468432821891
x - mean:  [ -2.56622633e+01  -1.18805552e-08   2.63714503e+01   4.54189575e-10  -6.40499920e-09   1.04889573e-08  -7.09187069e-01
  -3.52642715e-09  -2.67771227e-09]
l1-norm(x - mean) / objective:  52.7429006758

Edit

Here a SOCP-based least-squares (soft-constrained) approach, which i would recommend in terms of numerical-stability! This approach can and should be tuned for whatever you need. It's implemented using the already mentioned cvxpy modelling-tool using the ECOS solver.

The basic idea:

instead of: min(l1-norm(x - mean(x)) st. Ax=b

solve: min(l2-norm(Ax-b) + c * l1-norm(x - mean(x)))

where c is the nonnegative trade-off parameter

small c: Ax=b is more important

big c: x - mean(x) is more important

Example code & output for your data and bounds of -50, 50 and c=1e-3:

import numpy as np
import cvxpy as cvx

""" DATA """
A = np.array([[3582.000000, 3394.000000, 3356.000000, 3256.000000, 3415.000000,
        3505.000000, 3442.000000, 3381.000000, 3392.000000],
       [233445193.000000, 217344811.000000, 237746918.000000,
        219204892.000000, 225272825.000000, 242819442.000000,
        215258725.000000, 227681178.000000, 215189377.000000],
       [559090945.000000, 496500751.000000, 493639029.000000,
        461547877.000000, 501057960.000000, 505073223.000000,
        490458632.000000, 503102998.000000, 487026744.000000]])
b = np.array([8531., 1079115532., 429386951.])
n = 9

# A /= 10000.  scaling would be a good idea
# b /= 10000.  """

""" SOCP-based least-squares approach """
def solve(A, b, n, c=1e-1):
    x = cvx.Variable(n)
    y = cvx.Variable(1)             # mean

    lower_bounds = np.zeros(n) - 50  # -50
    upper_bounds = np.zeros(n) + 50  #  50

    constraints = []
    constraints.append(x >= lower_bounds)
    constraints.append(x <= upper_bounds)
    constraints.append(y == cvx.sum_entries(x) / n)

    objective = cvx.Minimize(cvx.norm(A*x-b, 2) + c * cvx.norm(x - y, 1))
    problem = cvx.Problem(objective, constraints)

    problem.solve(solver=cvx.ECOS, verbose=True)

    print('Objective: ', problem.value)
    print('x: ', x.T.value)
    print('mean: ', y.value)
    print('Ax-b: ')
    print((A*x - b).value)
    print('x - mean: ', (x - y).T.value)

solve(A, b, n)

Output:

 ECOS 2.0.4 - (C) embotech GmbH, Zurich Switzerland, 2012-15. Web: www.embotech.com/ECOS

It     pcost       dcost      gap   pres   dres    k/t    mu     step   sigma     IR    |   BT
 0  +2.637e-17  -1.550e+06  +7e+08  1e-01  2e-04  1e+00  2e+07    ---    ---    1  1  - |  -  -
 1  -8.613e+04  -1.014e+05  +8e+06  1e-03  2e-06  2e+03  2e+05  0.9890  1e-04   2  1  1 |  0  0
 2  -1.287e+03  -1.464e+03  +1e+05  1e-05  9e-08  4e+01  3e+03  0.9872  1e-04   3  1  1 |  0  0
 3  +1.794e+02  +1.900e+02  +2e+03  2e-07  1e-07  1e+01  5e+01  0.9890  5e-03   5  3  4 |  0  0
 4  -1.388e+00  -6.826e-01  +1e+02  1e-08  7e-08  9e-01  3e+00  0.9458  4e-03   7  6  6 |  0  0
 5  +5.491e+00  +5.683e+00  +1e+01  1e-09  8e-09  2e-01  3e-01  0.9617  6e-02   1  1  1 |  0  0
 6  +6.480e+00  +6.505e+00  +1e+00  2e-10  5e-10  3e-02  4e-02  0.8928  2e-02   1  1  1 |  0  0
 7  +6.746e+00  +6.746e+00  +2e-02  3e-12  5e-10  5e-04  6e-04  0.9890  5e-03   1  0  0 |  0  0
 8  +6.759e+00  +6.759e+00  +3e-04  2e-12  2e-10  6e-06  7e-06  0.9890  1e-04   1  0  0 |  0  0
 9  +6.759e+00  +6.759e+00  +3e-06  2e-13  2e-10  6e-08  8e-08  0.9890  1e-04   2  0  0 |  0  0
10  +6.758e+00  +6.758e+00  +3e-08  5e-14  2e-10  7e-10  9e-10  0.9890  1e-04   1  0  0 |  0  0

OPTIMAL (within feastol=2.0e-10, reltol=4.7e-09, abstol=3.2e-08).
Runtime: 0.002901 seconds.

Objective:  6.757722879805085
x:  [[-18.09169736  -5.55768047  11.12130645  11.48355878  -1.13982006
   12.4290884   -3.00165819  -1.05158589  -2.4468432 ]]
mean:  0.416074272576
Ax-b:
[[  2.17051777e-03]
 [  1.90734863e-06]
 [ -5.72204590e-06]]
x - mean:  [[-18.50777164  -5.97375474  10.70523218  11.0674845   -1.55589434
   12.01301413  -3.41773246  -1.46766016  -2.86291747]]

This approach will always output a feasible solution (for our task) and you can then decide on the observed residual if it works for you.

As you observed, a lower-bound of 0 is deadly, in all formulations (look at the magnitude difference in your data!).

Here a lower-bound of 0 will get you a solution with some high residual-error.

E.g.:

c=1e-7

bounds = 0 / 15

Output:

Objective:  785913288.2410747
x:  [[ -5.57966858e-08  -4.74997454e-08   1.56066068e+00   1.68021234e-07
   -3.55602958e-08   1.75340641e-06  -4.69609562e-08  -3.10216680e-08
   -4.39482554e-08]]
mean:  0.173406926909
Ax-b:
[[ -3.29341696e+03]
 [ -7.08072860e+08]
 [  3.41016903e+08]]
x - mean:  [[-0.17340698 -0.17340697  1.38725375 -0.17340676 -0.17340696 -0.17340517
  -0.17340697 -0.17340696 -0.17340697]]


问:
Batch how to copy all contents of a file
I have done a TON of research on this topic, and I can't find an answer. Let's say  I have this as a file:

@echo off
cls
echo Hello World!
echo %ALLCONTENTS%>Helloworldduplicate.bat

but I want the copy to also have the code that makes a duplicate. For example,

```<code>@echo off
cls
echo hello!
pause
ENTER CODE THAT COPIES EVERYTHING, INCLUDING THIS LINE, HERE
exit
</code>```

Please help

Thanks

答:
Either as JosefZ commented or:</p>

```<code>@echo off
cls
echo hello!
pause
type %0>Helloworldduplicate.bat
exit
</code>```

Body:
I have done a TON of research on this topic, and I can't find an answer. Let's say  I have this as a file:

@echo off
cls
echo Hello World!
echo %ALLCONTENTS%>Helloworldduplicate.bat

but I want the copy to also have the code that makes a duplicate. For example,

@echo off
cls
echo hello!
pause
ENTER CODE THAT COPIES EVERYTHING, INCLUDING THIS LINE, HERE
exit

Please help

Thanks

Body:
Either as JosefZ commented or:

@echo off
cls
echo hello!
pause
type %0>Helloworldduplicate.bat
exit


问:
Keras prediction after the model is trained
I have trained a Keras model and saved the model and the weights to two separate files. My training data and validation data are divided into two classes like this:

training_data/
    positive/
    negative
validation_data/
    positive/
    negative/
```

<p>Both training data directories contain 900k samples each, the validation data directories contain 20k samples each. All the samples are 43x43px.</p>

<p>My model and the learning process are defined like this:</p>

<pre class="lang-python prettyprint-override"><code>def get_model(img_width, img_height):
    model = Sequential()
    model.add(Conv2D(32, (3, 3), input_shape=(img_width, img_height, 3)))
    model.add(Activation('relu'))
    model.add(MaxPooling2D(pool_size=(2, 2)))

    model.add(Conv2D(32, (3, 3)))
    model.add(Activation('relu'))
    model.add(MaxPooling2D(pool_size=(2, 2)))

    model.add(Conv2D(64, (3, 3)))
    model.add(Activation('relu'))
    model.add(MaxPooling2D(pool_size=(2, 2)))

    model.add(Flatten())
    model.add(Dense(64))
    model.add(Activation('relu'))
    model.add(Dropout(0.5))
    model.add(Dense(1))
    model.add(Activation('sigmoid'))

    return model

model = get_model(43, 43)
model.compile(loss='binary_crossentropy', optimizer='rmsprop',
              metrics=['accuracy'])

train_datagen = ImageDataGenerator(
    rescale=1. / 255,
    shear_range=0.2,
    zoom_range=0.2,
    rotation_range=20,
    width_shift_range=0.2,
    height_shift_range=0.2)

test_datagen = ImageDataGenerator(rescale=1. / 255)

train_generator = train_datagen.flow_from_directory(
    train_data_dir,
    target_size=(img_width, img_height),
    batch_size=batch_size,
    class_mode='binary')

validation_generator = test_datagen.flow_from_directory(
    validation_data_dir,
    target_size=(img_width, img_height),
    batch_size=batch_size,
    class_mode='binary')

history = model.fit_generator(
    train_generator,
    steps_per_epoch=nb_train_samples // batch_size,
    epochs=epochs,
    validation_data=validation_generator,
    validation_steps=nb_validation_samples // batch_size)

model.save(os.path.join('model.h5'))
model.save_weights(os.path.join('weights.h5'))
save_model_info(params)
</code>```

The training process for 20 epochs, batch size of 1024, 1.800.000 training samples, and 40.000 validation samples took about 5 hours. The history object is here because I am also saving the accuracy and learning graphs.

Now, I am trying to make this model predict which of trained two classed is present in given testing sample. So, I create the model, load the weights and trying to run the prediction.

model = get_model(43, 43)
model.load_weights(args.weights_file)
model.compile(loss='binary_crossentropy', optimizer='rmsprop',
              metrics=['accuracy'])

result = []
files = os.listdir(input_dir)
for file in files:
    image = load_img(file)
    image = np.asarray(image)
    image = np.expand_dims(image, axis=0)
    result.append(model.predict(image))

print(result)
```

<p>It is working, but not the way I would like it to. The output is like this:</p>

<pre class="lang-python prettyprint-override"><code>[array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32)]
</code>```

And here is my question. I need it for each given file to make prediction like

{'negative': 0.925, 'positive': 0.0725}
```

The format is not relevant here. My point is, how to get the probability for each class that has been trained? I think I tried to use all the model prediction methods, but none of them gave me what I need. Am I doing something wrong in the code or it needs to be done somehow different?

答:
I managed to fix the issue and it is working. The problem was that I added the rescale parameter in the ImageGenerator while training the model:

```<code>train_datagen = ImageDataGenerator(
    rescale=1. / 255,
    shear_range=0.2,
    zoom_range=0.2,
    rotation_range=20,
    width_shift_range=0.2,
    height_shift_range=0.2)
</code>```

And I did not add this while running predictions:

```<code>for file in files:
    image = load_img(file)
    image = np.asarray(image)
    image = np.expand_dims(image, axis=0)
    result.append(model.predict(image))
</code>```

I change this line

```<code>image = np.expand_dims(image, axis=0)
</code>```

And now it looks like this

```<code>img = np.expand_dims(img / 255, axis=0)
</code>```

I also updated loading the model, changed there lines (but just for prediction, not the training):

```<code>model = get_model(43, 43)
model.load_weights(args.weights_file)
model.compile(loss='binary_crossentropy', optimizer='rmsprop',
          metrics=['accuracy'])
</code>```

into this:

```<code>model = load_model(args.model_file)
</code>```

I run the prediction with all my samples and fill a numpy array with the results, then change that array to image and it's working. Thank you all for help and sorry again for the amount of code.

Body:
I have trained a Keras model and saved the model and the weights to two separate files. My training data and validation data are divided into two classes like this:

training_data/
    positive/
    negative
validation_data/
    positive/
    negative/

Both training data directories contain 900k samples each, the validation data directories contain 20k samples each. All the samples are 43x43px.

My model and the learning process are defined like this:

def get_model(img_width, img_height):
    model = Sequential()
    model.add(Conv2D(32, (3, 3), input_shape=(img_width, img_height, 3)))
    model.add(Activation('relu'))
    model.add(MaxPooling2D(pool_size=(2, 2)))

    model.add(Conv2D(32, (3, 3)))
    model.add(Activation('relu'))
    model.add(MaxPooling2D(pool_size=(2, 2)))

    model.add(Conv2D(64, (3, 3)))
    model.add(Activation('relu'))
    model.add(MaxPooling2D(pool_size=(2, 2)))

    model.add(Flatten())
    model.add(Dense(64))
    model.add(Activation('relu'))
    model.add(Dropout(0.5))
    model.add(Dense(1))
    model.add(Activation('sigmoid'))

    return model

model = get_model(43, 43)
model.compile(loss='binary_crossentropy', optimizer='rmsprop',
              metrics=['accuracy'])

train_datagen = ImageDataGenerator(
    rescale=1. / 255,
    shear_range=0.2,
    zoom_range=0.2,
    rotation_range=20,
    width_shift_range=0.2,
    height_shift_range=0.2)

test_datagen = ImageDataGenerator(rescale=1. / 255)

train_generator = train_datagen.flow_from_directory(
    train_data_dir,
    target_size=(img_width, img_height),
    batch_size=batch_size,
    class_mode='binary')

validation_generator = test_datagen.flow_from_directory(
    validation_data_dir,
    target_size=(img_width, img_height),
    batch_size=batch_size,
    class_mode='binary')

history = model.fit_generator(
    train_generator,
    steps_per_epoch=nb_train_samples // batch_size,
    epochs=epochs,
    validation_data=validation_generator,
    validation_steps=nb_validation_samples // batch_size)

model.save(os.path.join('model.h5'))
model.save_weights(os.path.join('weights.h5'))
save_model_info(params)

The training process for 20 epochs, batch size of 1024, 1.800.000 training samples, and 40.000 validation samples took about 5 hours. The history object is here because I am also saving the accuracy and learning graphs.

Now, I am trying to make this model predict which of trained two classed is present in given testing sample. So, I create the model, load the weights and trying to run the prediction.

model = get_model(43, 43)
model.load_weights(args.weights_file)
model.compile(loss='binary_crossentropy', optimizer='rmsprop',
              metrics=['accuracy'])

result = []
files = os.listdir(input_dir)
for file in files:
    image = load_img(file)
    image = np.asarray(image)
    image = np.expand_dims(image, axis=0)
    result.append(model.predict(image))

print(result)

It is working, but not the way I would like it to. The output is like this:

[array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32), array([[ 0.]], dtype=float32)]

And here is my question. I need it for each given file to make prediction like

{'negative': 0.925, 'positive': 0.0725}

The format is not relevant here. My point is, how to get the probability for each class that has been trained? I think I tried to use all the model prediction methods, but none of them gave me what I need. Am I doing something wrong in the code or it needs to be done somehow different?

Body:
I managed to fix the issue and it is working. The problem was that I added the rescale parameter in the ImageGenerator while training the model:

train_datagen = ImageDataGenerator(
    rescale=1. / 255,
    shear_range=0.2,
    zoom_range=0.2,
    rotation_range=20,
    width_shift_range=0.2,
    height_shift_range=0.2)

And I did not add this while running predictions:

for file in files:
    image = load_img(file)
    image = np.asarray(image)
    image = np.expand_dims(image, axis=0)
    result.append(model.predict(image))

I change this line

image = np.expand_dims(image, axis=0)

And now it looks like this

img = np.expand_dims(img / 255, axis=0)

I also updated loading the model, changed there lines (but just for prediction, not the training):

model = get_model(43, 43)
model.load_weights(args.weights_file)
model.compile(loss='binary_crossentropy', optimizer='rmsprop',
          metrics=['accuracy'])

into this:

model = load_model(args.model_file)

I run the prediction with all my samples and fill a numpy array with the results, then change that array to image and it's working. Thank you all for help and sorry again for the amount of code.


问:
Animate a border with CSS
I want to recreate a CSS animation in my computer (local) but it's not working, when I try the code in Codepen it's working, what am I doing wrong?

Here is the code: https://codepen.io/jvera/pen/gXxgXx

{
  background: none;
  border: 0;
  box-sizing: border-box;
  box-shadow: inset 0 0 0 2px #f45e61;
  color: #f45e61;
  font-size: inherit;
  font-weight: 700;
  margin: 1em;
  padding: 1em 2em;
  text-align: center;
  text-transform: capitalize;
  vertical-align: middle;
}
.draw {
  overflow: hidden;
  position: relative;
}
.draw::before, .draw::after {
  content: '';
  box-sizing: border-box;
  position: absolute;
  border: 2px solid transparent;
  width: 0;
  height: 0;
}
.draw::before {
  top: 0;
  left: 0;
  border-top-color: #60daaa;
  border-right-color: #60daaa;
  animation: border 2s infinite;
}
.draw::after {
  bottom: 0;
  right: 0;
  animation: border 2s 1s infinite, borderColor 2s 1s infinite;
}

@keyframes border {
  0% {
    width: 0;
    height: 0;
  }
  25% {
    width: 100%;
    height: 0;
  }
  50% {
    width: 100%;
    height: 100%;
  }
  100% {
    width: 100%;
    height: 100%;
  }
}
@keyframes borderColor {
  0% {
    border-bottom-color: #60daaa;
    border-left-color: #60daaa;
  }
  50% {
    border-bottom-color: #60daaa;
    border-left-color: #60daaa;
  }
  51% {
    border-bottom-color: transparent;
    border-left-color: transparent;
  }
  100% {
    border-bottom-color: transparent;
    border-left-color: transparent;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><center><h2 class="draw">Titulo</h2><center></code>```

I created the two files and put them into the folder, when I run the HTML file I can't see the animation effect (like the demo) so, what can I do? why I'm not seeing the results?

Thanks.

答:
I don't know about your HTML & CSS skills but maybe you are doing something wrong with the linking of your stylesheet:

```<code><link rel="stylesheet" href="styles.css">
</code>```

Be sure to corectly set the paths (look at this example : External CSS) and maybe give a glimpse at the basics of HTML, just in case?

HTML Introduction

Also, check if the path is relative or absolute:

Relative Paths:

index.html

/graphics/image.png

/help/articles/how-do-i-set-up-a-webpage.html

Absolute Paths:

http://www.example.com

http://www.example.com/graphics/image.png

http://www.example.com/help/articles/how-do-i-set-up-a-webpage.html

See the Full reference about the paths.

Hope I helped.

Title: Animate a border with CSS

Body:
I want to recreate a CSS animation in my computer (local) but it's not working, when I try the code in Codepen it's working, what am I doing wrong?

Here is the code: https://codepen.io/jvera/pen/gXxgXx

{
  background: none;
  border: 0;
  box-sizing: border-box;
  box-shadow: inset 0 0 0 2px #f45e61;
  color: #f45e61;
  font-size: inherit;
  font-weight: 700;
  margin: 1em;
  padding: 1em 2em;
  text-align: center;
  text-transform: capitalize;
  vertical-align: middle;
}
.draw {
  overflow: hidden;
  position: relative;
}
.draw::before, .draw::after {
  content: '';
  box-sizing: border-box;
  position: absolute;
  border: 2px solid transparent;
  width: 0;
  height: 0;
}
.draw::before {
  top: 0;
  left: 0;
  border-top-color: #60daaa;
  border-right-color: #60daaa;
  animation: border 2s infinite;
}
.draw::after {
  bottom: 0;
  right: 0;
  animation: border 2s 1s infinite, borderColor 2s 1s infinite;
}

@keyframes border {
  0% {
    width: 0;
    height: 0;
  }
  25% {
    width: 100%;
    height: 0;
  }
  50% {
    width: 100%;
    height: 100%;
  }
  100% {
    width: 100%;
    height: 100%;
  }
}
@keyframes borderColor {
  0% {
    border-bottom-color: #60daaa;
    border-left-color: #60daaa;
  }
  50% {
    border-bottom-color: #60daaa;
    border-left-color: #60daaa;
  }
  51% {
    border-bottom-color: transparent;
    border-left-color: transparent;
  }
  100% {
    border-bottom-color: transparent;
    border-left-color: transparent;
  }
}

Titulo

I created the two files and put them into the folder, when I run the HTML file I can't see the animation effect (like the demo) so, what can I do? why I'm not seeing the results?

Thanks.

Body:
I don't know about your HTML & CSS skills but maybe you are doing something wrong with the linking of your stylesheet:

<link rel="stylesheet" href="styles.css">

Be sure to corectly set the paths (look at this example : External CSS) and maybe give a glimpse at the basics of HTML, just in case?

HTML Introduction

Also, check if the path is relative or absolute:

Relative Paths:

index.html

/graphics/image.png

/help/articles/how-do-i-set-up-a-webpage.html

Absolute Paths:

http://www.example.com

http://www.example.com/graphics/image.png

http://www.example.com/help/articles/how-do-i-set-up-a-webpage.html

See the Full reference about the paths.

Hope I helped.


问:
Divide values by lists of three and comparing elements in it
I have some values coming from sensor. My task is to divide them into lists of three elements.  If two consecutive elements differ by at least 10, I should ignore the rest of the list.

From this:

```<code>values = [1,3,6,8,9,11,15,17,28,29]
</code>```

I should get:

```<code>[1,3,6]
[8,9,11]
[15,17]
</code>```

I've managed to divide values by list of three:

```<code>list_of_values = [1,3,6,8,9,11,15,17,28,29]
def divide(values, size):
    return (values[pos:pos + size] for pos in range(0, len(values), size))
for group in divide(list_of_values, 3):
    print(group)
</code>```

But I can't figure out how to compare previous and next value like the task says.

答:
Before you break the list into triples, you need to find that break point.  Iterate through the loop, looking for that difference.  For ease of reading, I'm going to call your list vals instead of list_of_values.

```<code>for gap in range(1, len(vals)):
    if vals[gap] - vals[gap-1] >= 10:
        break
</code>```

At this point, gap is the position of the frist element you exclude.

```<code>vals = vals[:gap]
</code>```

Now you're ready to split your list.

Body:
I have some values coming from sensor. My task is to divide them into lists of three elements.  If two consecutive elements differ by at least 10, I should ignore the rest of the list.

From this:

values = [1,3,6,8,9,11,15,17,28,29]

I should get:

[1,3,6]
[8,9,11]
[15,17]

I've managed to divide values by list of three:

list_of_values = [1,3,6,8,9,11,15,17,28,29]
def divide(values, size):
    return (values[pos:pos + size] for pos in range(0, len(values), size))
for group in divide(list_of_values, 3):
    print(group)

But I can't figure out how to compare previous and next value like the task says.

Body:
Before you break the list into triples, you need to find that break point.  Iterate through the loop, looking for that difference.  For ease of reading, I'm going to call your list vals instead of list_of_values.

for gap in range(1, len(vals)):
    if vals[gap] - vals[gap-1] >= 10:
        break

At this point, gap is the position of the frist element you exclude.

vals = vals[:gap]

Now you're ready to split your list.


问:
Uncaught TypeError: s.map is not a function in ReactJs
I'm trying to use ReactTable using the examples, this is the code for this:

```<code>class UsersTable extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            data: []
        };
    };

    render() {
        return (
            <div>
                <ReactTable
                    data={this.state.data}
                    columns={[
                        {
                            Header: "ID",
                            accessor: "id"
                        },
                        {
                            Header: "Name",
                            accessor: "name"
                        }
                    ]}
                    onFetchData={(state, instance) => {
                        let request = new XMLHttpRequest();
                        request.open("GET", '/get/roles', true);
                        request.send();
                        request.onload = function() {
                            if (request.status === 200) {
                                let response = JSON.parse(request.responseText);
                                let responseInfo = JSON.stringify(response);

                                this.setState({
                                    data: responseInfo
                                })
                            }
                        }.bind(this);
                    }}
                    defaultPageSize={5}
                    className="-striped -highlight"
                    manual
                />
            </div>
        );
    }
}
</code>```

My GET call gets a Json that is saved in setState :

```<code>[{"id":4732298045947904,"name":"ROLE_EXECUTIVE"},{"id":5207287069147136,"name":"ROLE_ADMIN"},{"id":5858197952790528,"name":"ROLE_PLAYER"},{"id":6333186975989760,"name":"ROLE_USER"},{"id":6561885394567168,"name":"ROLE_TAKER"}]
</code>```

But when I run the browser the table is not printing any row, but I can not find what the problem is:

```<code>Uncaught TypeError: s.map is not a function
    at t.value (react-table.js:6)
    at t.value (react-table.js:6)
    at p.updateComponent (react-dom.min.js:13)
    at p.receiveComponent (react-dom.min.js:13)
    ...
</code>```

答:
You are setting data in your state to a string here:

```<code>...

let responseInfo = JSON.stringify(response)

this.setState({
  data: responseInfo
})

...
</code>```

...but ReactTable is expecting an array.

Strings don’t have a map method, which is most likely why you are getting the error.

Perhaps use response instead, provided it is an array:

```<code>...

let response = JSON.parse(request.responseText)

this.setState({
  data: response
})

...
</code>```

Body:
I'm trying to use ReactTable using the examples, this is the code for this:

class UsersTable extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            data: []
        };
    };

    render() {
        return (

                <ReactTable
                    data={this.state.data}
                    columns={[
                        {
                            Header: "ID",
                            accessor: "id"
                        },
                        {
                            Header: "Name",
                            accessor: "name"
                        }
                    ]}
                    onFetchData={(state, instance) => {
                        let request = new XMLHttpRequest();
                        request.open("GET", '/get/roles', true);
                        request.send();
                        request.onload = function() {
                            if (request.status === 200) {
                                let response = JSON.parse(request.responseText);
                                let responseInfo = JSON.stringify(response);

                                this.setState({
                                    data: responseInfo
                                })
                            }
                        }.bind(this);
                    }}
                    defaultPageSize={5}
                    className="-striped -highlight"
                    manual
                />

        );
    }
}

My GET call gets a Json that is saved in setState :

[{"id":4732298045947904,"name":"ROLE_EXECUTIVE"},{"id":5207287069147136,"name":"ROLE_ADMIN"},{"id":5858197952790528,"name":"ROLE_PLAYER"},{"id":6333186975989760,"name":"ROLE_USER"},{"id":6561885394567168,"name":"ROLE_TAKER"}]

But when I run the browser the table is not printing any row, but I can not find what the problem is:

Uncaught TypeError: s.map is not a function
    at t.value (react-table.js:6)
    at t.value (react-table.js:6)
    at p.updateComponent (react-dom.min.js:13)
    at p.receiveComponent (react-dom.min.js:13)
    ...

Body:
You are setting data in your state to a string here:

...

let responseInfo = JSON.stringify(response)

this.setState({
  data: responseInfo
})

...

...but ReactTable is expecting an array.

Strings don’t have a map method, which is most likely why you are getting the error.

Perhaps use response instead, provided it is an array:

...

let response = JSON.parse(request.responseText)

this.setState({
  data: response
})

...


问:
Direct3D window opens to white screen
In the source code I'm using my program is opening a window which displays a white screen and immediately becomes unresponsive. Please help me find the issue with my code.

Windows.cpp

```<code>#include "DirectX.h"

using namespace std;
bool gameover = false;

//Windows event handler
LRESULT WINAPI WinProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) {
    switch (msg) {
    case WM_DESTROY:
        gameover = true;
        PostQuitMessage(0);
        return 0;
    }

    return DefWindowProc(hwnd, msg, wParam, lParam);
}

//Windows entry point
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
    LPSTR lpCmdLine, int nCmdShow) {

    //initializes window settings
    WNDCLASSEX wc;
    wc.cbSize = sizeof(WNDCLASSEX);
    wc.style = CS_HREDRAW | CS_VREDRAW;
    wc.lpfnWndProc = (WNDPROC)WinProc;
    wc.cbClsExtra = 0;
    wc.cbWndExtra = 0;
    wc.hInstance = hInstance;
    wc.hIcon = NULL;
    wc.hCursor = LoadCursor(NULL, IDC_ARROW);
    wc.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH);
    wc.lpszMenuName = NULL;
    wc.lpszClassName = L"MainWindowClass";
    wc.hIconSm = NULL;
    RegisterClassEx(&wc);

    //create a new window
    HWND window = CreateWindow(L"MainWindowClass", APPTITLE,
        WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT,
        SCREENW, SCREENH, NULL, NULL, hInstance, NULL);

    if (window == 0) return 0;

    //display the window
    ShowWindow(window, nCmdShow);
    UpdateWindow(window);

    //initialize the game
    if (!Game_Init(window)) return 0;

    //main message loop
    MSG message;
    while (!gameover) {
        if (PeekMessage(&message, NULL, 0, 0, PM_REMOVE)) {
            TranslateMessage(&message);
            DispatchMessage(&message);
        }

        //process game loop
        Game_Run(window);
    }

    //shutdown game
    Game_End();
    return message.wParam;
}
</code>```

DirectX.cpp
I assume this is where the problem is happening

```<code>bool Direct3D_Init(HWND window, int width, int height, bool fullscreen)
{
    //initialize Direct3D
    d3d = Direct3DCreate9(D3D_SDK_VERSION);
    if (!d3d) return false;

    //set Direct3D presentation parameters
    D3DPRESENT_PARAMETERS d3dpp;
    ZeroMemory(&d3dpp, sizeof(d3dpp));
    d3dpp.Windowed = !fullscreen;
    d3dpp.SwapEffect = D3DSWAPEFFECT_COPY;
    d3dpp.BackBufferFormat = D3DFMT_X8R8G8B8;
    d3dpp.BackBufferCount = 1;
    d3dpp.BackBufferWidth = width;
    d3dpp.BackBufferHeight = height;
    d3dpp.hDeviceWindow = window;

    //create Direct3D device
    d3d->CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, window,
        D3DCREATE_SOFTWARE_VERTEXPROCESSING, &d3dpp, &d3ddev);
    if (!d3ddev) return false;

    //get a pointer to the back buffer surface
    d3ddev->GetBackBuffer(0, 0, D3DBACKBUFFER_TYPE_MONO, &backbuffer);

    //create sprite object
    D3DXCreateSprite(d3ddev, &spriteobj);

    return true;
}
</code>```

答:
My Game project just have the same issue. The Game was built success but when I start it. It show white screen.
I've just fixed this error. If you have a GPU (NVidia or ...) you should disable it. Like I did in this image.enter image description here</p>

Title: Direct3D window opens to white screen

Body:
In the source code I'm using my program is opening a window which displays a white screen and immediately becomes unresponsive. Please help me find the issue with my code.

Windows.cpp

#include "DirectX.h"

using namespace std;
bool gameover = false;

//Windows event handler
LRESULT WINAPI WinProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) {
    switch (msg) {
    case WM_DESTROY:
        gameover = true;
        PostQuitMessage(0);
        return 0;
    }

    return DefWindowProc(hwnd, msg, wParam, lParam);
}

//Windows entry point
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
    LPSTR lpCmdLine, int nCmdShow) {

    //initializes window settings
    WNDCLASSEX wc;
    wc.cbSize = sizeof(WNDCLASSEX);
    wc.style = CS_HREDRAW | CS_VREDRAW;
    wc.lpfnWndProc = (WNDPROC)WinProc;
    wc.cbClsExtra = 0;
    wc.cbWndExtra = 0;
    wc.hInstance = hInstance;
    wc.hIcon = NULL;
    wc.hCursor = LoadCursor(NULL, IDC_ARROW);
    wc.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH);
    wc.lpszMenuName = NULL;
    wc.lpszClassName = L"MainWindowClass";
    wc.hIconSm = NULL;
    RegisterClassEx(&wc);

    //create a new window
    HWND window = CreateWindow(L"MainWindowClass", APPTITLE,
        WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT,
        SCREENW, SCREENH, NULL, NULL, hInstance, NULL);

    if (window == 0) return 0;

    //display the window
    ShowWindow(window, nCmdShow);
    UpdateWindow(window);

    //initialize the game
    if (!Game_Init(window)) return 0;

    //main message loop
    MSG message;
    while (!gameover) {
        if (PeekMessage(&message, NULL, 0, 0, PM_REMOVE)) {
            TranslateMessage(&message);
            DispatchMessage(&message);
        }

        //process game loop
        Game_Run(window);
    }

    //shutdown game
    Game_End();
    return message.wParam;
}

DirectX.cpp
I assume this is where the problem is happening

bool Direct3D_Init(HWND window, int width, int height, bool fullscreen)
{
    //initialize Direct3D
    d3d = Direct3DCreate9(D3D_SDK_VERSION);
    if (!d3d) return false;

    //set Direct3D presentation parameters
    D3DPRESENT_PARAMETERS d3dpp;
    ZeroMemory(&d3dpp, sizeof(d3dpp));
    d3dpp.Windowed = !fullscreen;
    d3dpp.SwapEffect = D3DSWAPEFFECT_COPY;
    d3dpp.BackBufferFormat = D3DFMT_X8R8G8B8;
    d3dpp.BackBufferCount = 1;
    d3dpp.BackBufferWidth = width;
    d3dpp.BackBufferHeight = height;
    d3dpp.hDeviceWindow = window;

    //create Direct3D device
    d3d->CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, window,
        D3DCREATE_SOFTWARE_VERTEXPROCESSING, &d3dpp, &d3ddev);
    if (!d3ddev) return false;

    //get a pointer to the back buffer surface
    d3ddev->GetBackBuffer(0, 0, D3DBACKBUFFER_TYPE_MONO, &backbuffer);

    //create sprite object
    D3DXCreateSprite(d3ddev, &spriteobj);

    return true;
}


问:
Alternative for deleted copy constrctor of ifstream
I want to extract data from a csv file but I have to get the number of rows and columns of the table first.

What I have so far is the following:

```<code>        std::ifstream myfile(filename); // filename is a string and passed in by the constructor
        if (myfile.is_open())
        {
            // First step: Get number of rows and columns of the matrix to initialize it.
            // We have to close and re-open the file each time we want to work with it.
            int rows = getRows(myfile);
            std::ifstream myfile1(filename);
            int columns = getColumns(myfile1);

            if (rows == columns) // Matrix has to be quadratic.
            {
                std::ifstream myfile2(filename);
                abwicklungsdreieck.set_Matrix(QuantLib::Matrix(rows, columns, 0)); // abwicklungsdreieck is initialised before
                //...
            }
            else
            {
                std::cout << "\nNumber of rows has to equal number of columns.";
            }
        }
    // [...]
    int getRows(std::ifstream &myfile)
    {
        std::string line;
        int rows = 0;

        while (std::getline(myfile, line)) // While-loop simply counts rows.
        {
            rows++;
        }
        myfile.close();
        return rows - 1;
    }

    int getColumns(std::ifstream &myfile)
    {
        std::string line;
        char delimiter = ';';
        size_t pos = 0;
        int columns = 0;

        while (std::getline(myfile, line) && columns == 0) // Consider first line in the .csv file.
        {
            line = line + ";";
            while ((pos = line.find(delimiter)) != std::string::npos) // Counts columns.
            {
                line.erase(0, pos + 1);
                columns++;
            }
        }
        myfile.close();
        return columns - 1;
    }
</code>```

This code is working. However, I have to open the file for three times which I do not like. Is there a way to evade this?

I was thinking about working with tempfiles in getRows() and getColumns() but the copying streams isn't possible since it doesn't make sense as I learned recently.

So, is there another way do that? Or can I for example evade the getline() and the line.erase() methods?

答:
You can read the file line by line, convert each line to a stream, then read the columns on the stream:

```<code>std::ifstream myfile(filename);
if(!myfile) return 0;

std::string line;
while(std::getline(myfile, line))
{
    std::stringstream ss(line);
    std::string column;
    while(std::getline(ss, column, ';'))
    {
        cout << column;
    }
    cout << "\n";
}
</code>```

getline(myfile, line) will copy each row in to line.

Convert line to ss stream.

getline(ss, column, ';') will break the line in to columns.

Use std::stoi to convert the string in to integer.

If your matrix is based on std::vector, you can grow the vector one row at a time, so you don't need to know the size in advance.

```<code>#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <vector>

void readfile(const std::string &filename)
{
    std::vector<std::vector<int>> matrix;
    std::ifstream myfile(filename);
    if(!myfile) return;
    std::string buf;
    while(std::getline(myfile, buf))
    {
        int maxrow = matrix.size();
        std::stringstream ss(buf);
        matrix.resize(maxrow + 1);
        cout << "break in to columns:" << buf << "\n";
        while(std::getline(ss, buf, ';'))
        {
            try {
                int num = std::stoi(buf);
                matrix[maxrow].push_back(num);
            }
            catch(...) { }
        }
    }

    for(auto &row : matrix) {
        for(auto col : row)
            cout << col << "|";
        cout << "\n";
    }
}
</code>```

Body:
I want to extract data from a csv file but I have to get the number of rows and columns of the table first.

What I have so far is the following:

        std::ifstream myfile(filename); // filename is a string and passed in by the constructor
        if (myfile.is_open())
        {
            // First step: Get number of rows and columns of the matrix to initialize it.
            // We have to close and re-open the file each time we want to work with it.
            int rows = getRows(myfile);
            std::ifstream myfile1(filename);
            int columns = getColumns(myfile1);

            if (rows == columns) // Matrix has to be quadratic.
            {
                std::ifstream myfile2(filename);
                abwicklungsdreieck.set_Matrix(QuantLib::Matrix(rows, columns, 0)); // abwicklungsdreieck is initialised before
                //...
            }
            else
            {
                std::cout << "\nNumber of rows has to equal number of columns.";
            }
        }
    // [...]
    int getRows(std::ifstream &myfile)
    {
        std::string line;
        int rows = 0;

        while (std::getline(myfile, line)) // While-loop simply counts rows.
        {
            rows++;
        }
        myfile.close();
        return rows - 1;
    }

    int getColumns(std::ifstream &myfile)
    {
        std::string line;
        char delimiter = ';';
        size_t pos = 0;
        int columns = 0;

        while (std::getline(myfile, line) && columns == 0) // Consider first line in the .csv file.
        {
            line = line + ";";
            while ((pos = line.find(delimiter)) != std::string::npos) // Counts columns.
            {
                line.erase(0, pos + 1);
                columns++;
            }
        }
        myfile.close();
        return columns - 1;
    }

This code is working. However, I have to open the file for three times which I do not like. Is there a way to evade this?

I was thinking about working with tempfiles in getRows() and getColumns() but the copying streams isn't possible since it doesn't make sense as I learned recently.

So, is there another way do that? Or can I for example evade the getline() and the line.erase() methods?

Body:
You can read the file line by line, convert each line to a stream, then read the columns on the stream:

std::ifstream myfile(filename);
if(!myfile) return 0;

std::string line;
while(std::getline(myfile, line))
{
    std::stringstream ss(line);
    std::string column;
    while(std::getline(ss, column, ';'))
    {
        cout << column;
    }
    cout << "\n";
}

getline(myfile, line) will copy each row in to line.

Convert line to ss stream.

getline(ss, column, ';') will break the line in to columns.

Use std::stoi to convert the string in to integer.

If your matrix is based on std::vector, you can grow the vector one row at a time, so you don't need to know the size in advance.

#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <vector>

void readfile(const std::string &filename)
{
    std::vector<std::vector<int>> matrix;
    std::ifstream myfile(filename);
    if(!myfile) return;
    std::string buf;
    while(std::getline(myfile, buf))
    {
        int maxrow = matrix.size();
        std::stringstream ss(buf);
        matrix.resize(maxrow + 1);
        cout << "break in to columns:" << buf << "\n";
        while(std::getline(ss, buf, ';'))
        {
            try {
                int num = std::stoi(buf);
                matrix[maxrow].push_back(num);
            }
            catch(...) { }
        }
    }

    for(auto &row : matrix) {
        for(auto col : row)
            cout << col << "|";
        cout << "\n";
    }
}


问:
calculate average using onchange event handler
I need to calculate the average of 5 numbers using onchange event handler. I'm new to coding and don't fully understand how onchange works. I also am confused on how to have the return # for my calcAvg function displayin my in 'result' box</p>

```<code><! doctype html >

<html lang = "en">
<head>
<title> Calculate Average </title>
</head>

<body>
    Number 1:<input type="number" id="number 1" Value="0"
onchange="calcAvg()"> </br> //do I put anything in between the ()of
onchange?
    Number 2:<input type="number" id="number 2" Value="0"
onchange="calcAvg()"> </br>
    Number 3:<input type="number" id="number 3" Value="0"
onchange="calcAvg()"> </br>
    Number 4:<input type="number" id="number 4" Value="0"
onchange="calcAvg()"> </br>
    Number 5:<input type="number" id="number 5" Value="0"
onchange="calcAvg()"> </br>
    Result :<input type=" number" id="result"> </br>
    <input type= 'button' value='calculate' id= 'calculate'>
    <div id= "result"> </div>//

    <script>
        function calcAvg ( number 1, number 2 ,number 3, number 4, number 5)
{
        return ((number 1 + number 2 +number 3+ number 4+ number 5)/5)
        }
    </script>

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

答:
I changed your code a little bit and added classes to the input flieds, instead of ids.

first you should call the onchange event directly in javascript, that way you have to write less code.

html:

```<code><input class="number" />
</code>```

js:

```<code>var numInput = $('.number');

function calcAvg() {
var sum = 0;
// add the current val of each input field to the sum variable
numInput.each(function() {
  sum += Number($(this).val());
  });
  // set the avg to the #result input field
  $('#result').val(sum / numInput.length);
};

// run the calcAvg function everytime the input changes
numInput.change(calcAvg);
</code>```

Here is a working fiddle:
https://jsfiddle.net/o2gxgz9r/18748/

Body:
I need to calculate the average of 5 numbers using onchange event handler. I'm new to coding and don't fully understand how onchange works. I also am confused on how to have the return # for my calcAvg function displayin my in 'result' box

<! doctype html >

<title> Calculate Average </title>

    Number 1:<input type="number" id="number 1" Value="0"
onchange="calcAvg()">
 //do I put anything in between the ()of
onchange?
    Number 2:<input type="number" id="number 2" Value="0"
onchange="calcAvg()">

    Number 3:<input type="number" id="number 3" Value="0"
onchange="calcAvg()">

    Number 4:<input type="number" id="number 4" Value="0"
onchange="calcAvg()">

    Number 5:<input type="number" id="number 5" Value="0"
onchange="calcAvg()">

    Result :<input type=" number" id="result">

    <input type= 'button' value='calculate' id= 'calculate'>

//

Body:
I changed your code a little bit and added classes to the input flieds, instead of ids.

first you should call the onchange event directly in javascript, that way you have to write less code.

html:

<input class="number" />

js:

var numInput = $('.number');

function calcAvg() {
var sum = 0;
// add the current val of each input field to the sum variable
numInput.each(function() {
  sum += Number($(this).val());
  });
  // set the avg to the #result input field
  $('#result').val(sum / numInput.length);
};

// run the calcAvg function everytime the input changes
numInput.change(calcAvg);

Here is a working fiddle:
https://jsfiddle.net/o2gxgz9r/18748/


问:
how to move NSTextField
I know how to create a NSTextField programmatically in Xcode, but what I want to know is how do I move this around the window?

How do I move an NSTextField from point A to point B?

答:
NSTextField inherits from NSView, which means the way you set its location is with setFrame:.

Take a look at the View Programming Guide for a full explanation of the concepts of a view's frame & bounds.

ContentLicense: CC BY-SA 2.5

Title: how to move NSTextField