问:
Subset dataframe based on duplicate values in multiple rows
How can I subset the dataframe below to show only the rows were columns AAA:CCC all have the same value and retain the IndID field?

```<code>Dat <- data.frame(IndID = LETTERS[seq(1,10)],
                  AAA = c(1,5,3,2,3,1,5,4,6,2),
                  BBB = c(1,8,5,2,5,4,8,4,4,5),
                  CCC = c(1,5,3,2,3,5,5,4,6,5))

> Dat
   IndID AAA BBB CCC
1      A   1   1   1
2      B   5   8   5
3      C   3   5   3
4      D   2   2   2
5      E   3   5   3
6      F   1   4   5
7      G   5   8   5
8      H   4   4   4
9      I   6   4   6
10     J   2   5   5
</code>```

I would like to return the following result.

```<code>Result <- data.frame(IndID = c("A", "D", "H"),
                  AAA = c(1,2,4),
                  BBB = c(1,2,4),
                  CCC = c(1,2,4))

> Result
  IndID AAA BBB CCC
1     A   1   1   1
2     D   2   2   2
3     H   4   4   4
</code>```

I have found a number of related posts including Find duplicated rows (based on 2 columns) in Data Frame in R and Find duplicated elements with dplyr, among others, but have not been able to reproduce the desired result with three columns. For example, while close the code below shows all distinct rows, but with the undesired result of including rows were only two of the values are equal.

```<code>Dat %>% distinct(AAA, BBB, CCC)
</code>```

I suspect the solution involves filter but an not sure how to obtain the desired result from the example mentioned above. A dplyr solution is preferred.

Addition
I also wonder if this could be applied to multiple factors. For example with the data below, which contains an IndID and three dates stored as factors, can a similar result be produced by either allowing factors or changing the factors to numeric values?

```<code>Dat <- structure(list(GenIndID = structure(c(1L, 2L, 6L, 7L, 3L, 4L,
8L, 5L), .Label = c("BHS_601", "BHS_603", "BHS_604", "BHS_605",
"BHS_631", "BHS_635", "BHS_636", "BHS_637"), class = "factor"),
    CptrDate = structure(c(1L, 2L, 3L, 3L, 2L, 2L, 3L, 4L), .Label = c("2016-02-01",
    "2016-02-02", "2016-02-04", "2016-12-11"), class = "factor"),
    DtLastAlive = structure(c(2L, 2L, 1L, 1L, 2L, 2L, 1L, 3L), .Label = c("2016-02-04",
    "2017-07-13", "2017-08-27"), class = "factor"), DtFnlFate = structure(c(2L,
    2L, 1L, 1L, 2L, 2L, 1L, 3L), .Label = c("2016-02-04", "2017-07-13",
    "2017-08-27"), class = "factor")), .Names = c("GenIndID",
"CptrDate", "DtLastAlive", "DtFnlFate"), row.names = c(82L, 83L,
224L, 225L, 84L, 85L, 226L, 360L), class = "data.frame")

> Dat
    GenIndID   CptrDate DtLastAlive  DtFnlFate
82   BHS_601 2016-02-01  2017-07-13 2017-07-13
83   BHS_603 2016-02-02  2017-07-13 2017-07-13
224  BHS_635 2016-02-04  2016-02-04 2016-02-04
225  BHS_636 2016-02-04  2016-02-04 2016-02-04
84   BHS_604 2016-02-02  2017-07-13 2017-07-13
85   BHS_605 2016-02-02  2017-07-13 2017-07-13
226  BHS_637 2016-02-04  2016-02-04 2016-02-04
360  BHS_631 2016-12-11  2017-08-27 2017-08-27
</code>```

with the desired result being

```<code>> Dat[c(3, 4, 7),]
    GenIndID   CptrDate DtLastAlive  DtFnlFate
224  BHS_635 2016-02-04  2016-02-04 2016-02-04
225  BHS_636 2016-02-04  2016-02-04 2016-02-04
226  BHS_637 2016-02-04  2016-02-04 2016-02-04
</code>```

答:
You can have a vectorized solution:</p>

```<code>Dat[do.call(function(...) pmax(...) - pmin(...), Dat[, -1]) == 0,]
#  IndID AAA BBB CCC
#1     A   1   1   1
#4     D   2   2   2
#8     H   4   4   4
</code>```

Body:
How can I subset the dataframe below to show only the rows were columns AAA:CCC all have the same value and retain the IndID field?

Dat <- data.frame(IndID = LETTERS[seq(1,10)],
                  AAA = c(1,5,3,2,3,1,5,4,6,2),
                  BBB = c(1,8,5,2,5,4,8,4,4,5),
                  CCC = c(1,5,3,2,3,5,5,4,6,5))

> Dat
   IndID AAA BBB CCC
1      A   1   1   1
2      B   5   8   5
3      C   3   5   3
4      D   2   2   2
5      E   3   5   3
6      F   1   4   5
7      G   5   8   5
8      H   4   4   4
9      I   6   4   6
10     J   2   5   5

I would like to return the following result.

Result <- data.frame(IndID = c("A", "D", "H"),
                  AAA = c(1,2,4),
                  BBB = c(1,2,4),
                  CCC = c(1,2,4))

> Result
  IndID AAA BBB CCC
1     A   1   1   1
2     D   2   2   2
3     H   4   4   4

I have found a number of related posts including Find duplicated rows (based on 2 columns) in Data Frame in R and Find duplicated elements with dplyr, among others, but have not been able to reproduce the desired result with three columns. For example, while close the code below shows all distinct rows, but with the undesired result of including rows were only two of the values are equal.

Dat %>% distinct(AAA, BBB, CCC)

I suspect the solution involves filter but an not sure how to obtain the desired result from the example mentioned above. A dplyr solution is preferred.

Addition
I also wonder if this could be applied to multiple factors. For example with the data below, which contains an IndID and three dates stored as factors, can a similar result be produced by either allowing factors or changing the factors to numeric values?

Dat <- structure(list(GenIndID = structure(c(1L, 2L, 6L, 7L, 3L, 4L,
8L, 5L), .Label = c("BHS_601", "BHS_603", "BHS_604", "BHS_605",
"BHS_631", "BHS_635", "BHS_636", "BHS_637"), class = "factor"),
    CptrDate = structure(c(1L, 2L, 3L, 3L, 2L, 2L, 3L, 4L), .Label = c("2016-02-01",
    "2016-02-02", "2016-02-04", "2016-12-11"), class = "factor"),
    DtLastAlive = structure(c(2L, 2L, 1L, 1L, 2L, 2L, 1L, 3L), .Label = c("2016-02-04",
    "2017-07-13", "2017-08-27"), class = "factor"), DtFnlFate = structure(c(2L,
    2L, 1L, 1L, 2L, 2L, 1L, 3L), .Label = c("2016-02-04", "2017-07-13",
    "2017-08-27"), class = "factor")), .Names = c("GenIndID",
"CptrDate", "DtLastAlive", "DtFnlFate"), row.names = c(82L, 83L,
224L, 225L, 84L, 85L, 226L, 360L), class = "data.frame")

> Dat
    GenIndID   CptrDate DtLastAlive  DtFnlFate
82   BHS_601 2016-02-01  2017-07-13 2017-07-13
83   BHS_603 2016-02-02  2017-07-13 2017-07-13
224  BHS_635 2016-02-04  2016-02-04 2016-02-04
225  BHS_636 2016-02-04  2016-02-04 2016-02-04
84   BHS_604 2016-02-02  2017-07-13 2017-07-13
85   BHS_605 2016-02-02  2017-07-13 2017-07-13
226  BHS_637 2016-02-04  2016-02-04 2016-02-04
360  BHS_631 2016-12-11  2017-08-27 2017-08-27

with the desired result being

> Dat[c(3, 4, 7),]
    GenIndID   CptrDate DtLastAlive  DtFnlFate
224  BHS_635 2016-02-04  2016-02-04 2016-02-04
225  BHS_636 2016-02-04  2016-02-04 2016-02-04
226  BHS_637 2016-02-04  2016-02-04 2016-02-04

Body:
You can have a vectorized solution:

Dat[do.call(function(...) pmax(...) - pmin(...), Dat[, -1]) == 0,]
#  IndID AAA BBB CCC
#1     A   1   1   1
#4     D   2   2   2
#8     H   4   4   4


来源: stackexchange

问:
Object reference not set to an instance of an object when opening cshtml files in visual studio 2013
When I try to open .cshtml files in Visual Studio 2013 I get this error:

```<code>Object reference not set to an instance of an object
</code>```

I have tried the solution given here but it did not work.
Here is my appsettings section in the web.config:

```<code><appSettings>
   <add key="Port" value="25" />
   <add key="webpages:Version" value="3.0.0.0" />
   <add key="webpages:Enabled" value="false" />
   <add key="ClientValidationEnabled" value="true" />
   <add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>
</code>```

i do not think that the problem is about this particular project, because all my other MVC projects have same problem.

答:
Try this;
In my visual studio 2015 resolved by deleting all files in the% LocalAppData% \ Microsoft \ VisualStudio \ 14.0 \ ComponentModelCache
it's work.</p>

ContentLicense: CC BY-SA 3.0

Body:
When I try to open .cshtml files in Visual Studio 2013 I get this error:

Object reference not set to an instance of an object

I have tried the solution given here but it did not work.
Here is my appsettings section in the web.config:

<appSettings>
   <add key="Port" value="25" />
   <add key="webpages:Version" value="3.0.0.0" />
   <add key="webpages:Enabled" value="false" />
   <add key="ClientValidationEnabled" value="true" />
   <add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>

i do not think that the problem is about this particular project, because all my other MVC projects have same problem.


问:
c++ multithread optimization
in my code I have 2/4 threads performing montecarlo simulations. Each of them runs a number of experiments and they all collect the results into a stl vector.
My question is this: suppose each thread runs 1000 experiments sequentially. Is is better to store the result into the shared vector one at the time, or every once in a while? If they wait until they have some consistent amount of data, writing into the vector will take longer, so I'm not sure whether the second solution is necessarily better than the first one.

PS each experiment is numerical computation, so no IO operations.

Thanks

答:
If you are going to wait until all the results are computed before you use any of the results, preallocate space for 4,000 results in the vector and have each thread write into one range of elements in the vector.  No locking is required because no two threads access the same element in the vector.

If you want to use the results as they are computed, use some sort of a concurrent queue data structure instead of a vector.

ContentLicense: CC BY-SA 2.5

Title: c++ multithread optimization


问:
Modify an array element after finding it in swift does not work
I wrote a model like this as an exercise :

```<code>struct Store {
    var name : String
    var bills : Array<Bill>
    var category : Category?
}

struct Bill {
    var date : String
    var amount : Float
}

struct Category {
    var name : String
    var tags : Array<String>
}
</code>```

and when I'm searching if a store already exist to add a bill to it instead of creating a new store, my code doesn't work. It acts like if the result of the search is a copy of the Array element . I would like to have a reference.

```<code>var stores : Array <Store> = Array()
for billStatment in billStatements! {
    let billParts = billStatment.split(separator: ",")
    if billParts.count > 0 {
        let bill : Bill = Bill(date:String(billParts[0]), amount: Float(billParts[2])!)
        var store : Store = Store(name:String(billParts[1]), bills: [bill], category: nil)

        if var alreadyAddedStore = stores.first(where: {$0.name == String(billParts[1])}) {
            alreadyAddedStore.bills.append(bill)
            print("yeah found it \(alreadyAddedStore)") // the debugger breaks here so I know the "first" method is working. If I print alreadyAddedStore here I have one more element, that's fine.
        } else {
            stores.append(store)
        }

    }
}

 print("\(stores.count)") // If I break here for a given store that should contains multiple elements, I will see only the first one added in the else statement.
</code>```

Can anyone tell me what I am doing wrong?

答:
As already noted, you're confusing value (struct) semantics with reference (class) semantics.

One simple fix would be the change stores to a dictionary with the name as your key:

```<code>var stores : Dictionary<String, Store> = [:]
</code>```

and use it like this:

```<code>if(stores[store.name] == nil) {
    stores[store.name] = store
}
else {
    stores[storeName].bills.append(bill)
}
</code>```

Body:
I wrote a model like this as an exercise :

struct Store {
    var name : String
    var bills : Array<Bill>
    var category : Category?
}

struct Bill {
    var date : String
    var amount : Float
}

struct Category {
    var name : String
    var tags : Array<String>
}

and when I'm searching if a store already exist to add a bill to it instead of creating a new store, my code doesn't work. It acts like if the result of the search is a copy of the Array element . I would like to have a reference.

var stores : Array <Store> = Array()
for billStatment in billStatements! {
    let billParts = billStatment.split(separator: ",")
    if billParts.count > 0 {
        let bill : Bill = Bill(date:String(billParts[0]), amount: Float(billParts[2])!)
        var store : Store = Store(name:String(billParts[1]), bills: [bill], category: nil)

        if var alreadyAddedStore = stores.first(where: {$0.name == String(billParts[1])}) {
            alreadyAddedStore.bills.append(bill)
            print("yeah found it \(alreadyAddedStore)") // the debugger breaks here so I know the "first" method is working. If I print alreadyAddedStore here I have one more element, that's fine.
        } else {
            stores.append(store)
        }

    }
}

 print("\(stores.count)") // If I break here for a given store that should contains multiple elements, I will see only the first one added in the else statement.

Can anyone tell me what I am doing wrong?

Body:
As already noted, you're confusing value (struct) semantics with reference (class) semantics.

One simple fix would be the change stores to a dictionary with the name as your key:

var stores : Dictionary<String, Store> = [:]

and use it like this:

if(stores[store.name] == nil) {
    stores[store.name] = store
}
else {
    stores[storeName].bills.append(bill)
}


问:
Lua require not working
I am trying to make one lua file require another. I am following this guide: http://lua-users.org/wiki/ModulesTutorial

My basic test, which should be a trivial hello world, does not work, and I can't figure out why.

Here's a console log which shows all files and all errors:

```<code>C:\Users\TestUser\Desktop\LuaTest>dir
 Volume in drive C has no label.
 Volume Serial Number is XXXX-XXXX

 Directory of C:\Users\TestUser\Desktop\LuaTest

11/15/2017  03:03 PM    <DIR>          .
11/15/2017  03:03 PM    <DIR>          ..
11/15/2017  02:53 PM    <DIR>          Bar
11/15/2017  03:04 PM                92 BazModule.lua
11/15/2017  02:53 PM    <DIR>          Foo
11/15/2017  03:08 PM               139 main.lua
               2 File(s)            231 bytes
               4 Dir(s)  253,774,073,856 bytes free

C:\Users\TestUser\Desktop\LuaTest>lua main.lua
lua: main.lua:1: module 'BazModule' not found:
        no field package.preload['BazModule']
        no file 'C:\dev\LuaDist\bin'
        no file '.\BazModule.dll'
        no file 'C:\dev\LuaDist\bin\..\lib\lua\BazModule.dll'
        no file 'C:\dev\LuaDist\bin\..\lib\lua\loadall.dll'
stack traceback:
        [C]: in function 'require'
        main.lua:1: in main chunk
        [C]: ?

C:\Users\TestUser\Desktop\LuaTest>type main.lua
local baz = require("BazModule")
baz.Baz()

local bar = require("Bar.BarModule")
bar.Bar()

local foo = require("Foo.FooModule")
foo.Foo()

C:\Users\TestUser\Desktop\LuaTest>type BazModule.lua
local BazModule = {}

function BazModule.Baz()
    print("Hello Baz!")
end

return BazModule

C:\Users\TestUser\Desktop\LuaTest>lua -v
Lua 5.1.5  Copyright (C) 1994-2012 Lua.org, PUC-Rio
</code>```

The expected output should be

```<code>Hello Baz!
Hello Bar!
Hello Foo!
</code>```

But it can't find any of the files adjacent to main.lua and I don't understand why.

答:
require searches in directories listed in package.path (for Lua files) and package.cpath (for compiled libraries).

Your error message…

```<code>lua: main.lua:1: module 'BazModule' not found:
        no field package.preload['BazModule']
        no file 'C:\dev\LuaDist\bin'
        no file '.\BazModule.dll'
        no file 'C:\dev\LuaDist\bin\..\lib\lua\BazModule.dll'
        no file 'C:\dev\LuaDist\bin\..\lib\lua\loadall.dll'
</code>```

indicates the paths that require searched in.  It seems that package.path is completely empty, or maybe there's a single malformed path pattern in there. (Which would be C:\dev\LuaDist\bin.)

The way the search for a module foo.bar works is that ? is substituted by foo/bar (or foo\bar – depending on OS) and so ./?.lua would find ./foo/bar.lua.

So the way to fix this is to (a) fix the place where you (or something that you installed) are/is mangling the package.path (via environment variable, startup script, …?) and/or (b) add the current directory to the search path.

Title: Lua require not working

Body:
I am trying to make one lua file require another. I am following this guide: http://lua-users.org/wiki/ModulesTutorial

My basic test, which should be a trivial hello world, does not work, and I can't figure out why.

Here's a console log which shows all files and all errors:

C:\Users\TestUser\Desktop\LuaTest>dir
 Volume in drive C has no label.
 Volume Serial Number is XXXX-XXXX

 Directory of C:\Users\TestUser\Desktop\LuaTest

11/15/2017  03:03 PM    <DIR>          .
11/15/2017  03:03 PM    <DIR>          ..
11/15/2017  02:53 PM    <DIR>          Bar
11/15/2017  03:04 PM                92 BazModule.lua
11/15/2017  02:53 PM    <DIR>          Foo
11/15/2017  03:08 PM               139 main.lua
               2 File(s)            231 bytes
               4 Dir(s)  253,774,073,856 bytes free

C:\Users\TestUser\Desktop\LuaTest>lua main.lua
lua: main.lua:1: module 'BazModule' not found:
        no field package.preload['BazModule']
        no file 'C:\dev\LuaDist\bin'
        no file '.\BazModule.dll'
        no file 'C:\dev\LuaDist\bin\..\lib\lua\BazModule.dll'
        no file 'C:\dev\LuaDist\bin\..\lib\lua\loadall.dll'
stack traceback:
        [C]: in function 'require'
        main.lua:1: in main chunk
        [C]: ?

C:\Users\TestUser\Desktop\LuaTest>type main.lua
local baz = require("BazModule")
baz.Baz()

local bar = require("Bar.BarModule")
bar.Bar()

local foo = require("Foo.FooModule")
foo.Foo()

C:\Users\TestUser\Desktop\LuaTest>type BazModule.lua
local BazModule = {}

function BazModule.Baz()
    print("Hello Baz!")
end

return BazModule

C:\Users\TestUser\Desktop\LuaTest>lua -v
Lua 5.1.5  Copyright (C) 1994-2012 Lua.org, PUC-Rio

The expected output should be

Hello Baz!
Hello Bar!
Hello Foo!

But it can't find any of the files adjacent to main.lua and I don't understand why.

Body:
require searches in directories listed in package.path (for Lua files) and package.cpath (for compiled libraries).

Your error message…

lua: main.lua:1: module 'BazModule' not found:
        no field package.preload['BazModule']
        no file 'C:\dev\LuaDist\bin'
        no file '.\BazModule.dll'
        no file 'C:\dev\LuaDist\bin\..\lib\lua\BazModule.dll'
        no file 'C:\dev\LuaDist\bin\..\lib\lua\loadall.dll'

indicates the paths that require searched in.  It seems that package.path is completely empty, or maybe there's a single malformed path pattern in there. (Which would be C:\dev\LuaDist\bin.)

The way the search for a module foo.bar works is that ? is substituted by foo/bar (or foo\bar – depending on OS) and so ./?.lua would find ./foo/bar.lua.

So the way to fix this is to (a) fix the place where you (or something that you installed) are/is mangling the package.path (via environment variable, startup script, …?) and/or (b) add the current directory to the search path.


问:
Generate a series of random numbers that add up to N in c#
How do I generate 30 random numbers between 1-9, that all add up to 200 (or some arbitrary N), in C#?

I'm trying to generate a string of digits that can add together to be N.

答:
If you want an unbiased algorithm then the naive implementation is something like:

```<code>while (true) {
  numbers = [];
  total = 0;
  for (i = 0; i < COUNT; ++i) {
    next = rand(BOUNDS);
    total += next;
    numbers.push(next);
  }

  if (total == TARGET) {
    return numbers;
  }
}
</code>```

This is non-terminating and slow but it is not biased. If you want a unbiased algorithm I'm not convinced the algorithms posted here are unbiased.

LastEditorDisplayName: Simucal

Body:
If you want an unbiased algorithm then the naive implementation is something like:

while (true) {
  numbers = [];
  total = 0;
  for (i = 0; i < COUNT; ++i) {
    next = rand(BOUNDS);
    total += next;
    numbers.push(next);
  }

  if (total == TARGET) {
    return numbers;
  }
}

This is non-terminating and slow but it is not biased. If you want a unbiased algorithm I'm not convinced the algorithms posted here are unbiased.

OwnerDisplayName: drscroogemcduck

LastEditorDisplayName: lc


问:
How to create custom string column of concatenated values in Excel(PivotTable Report)
How do you create a custom string column in Excel 2016(using PivotTable Report) with a concatenated string of one of the base table's columns?

I'm trying to roll up all the products within an associated brand(i.e. a brand has multiple products).

Sample data:

```<code>Brand   Product      MPG
-----   -------      ------
Toyota  RAV4         20
Toyota  Camry        25
Toyota  4Runner      18
Nissan  Pathfinder   18
Nissan  Versa        25
</code>```

I want the output of the summarized data to be like this:

```<code>Brand     Products               Brand Avg MPG
-------   --------               --------
Toyota    RAV4, Camry, 4Runner   21.00
Nissan    Pathfinder, Versa      21.50
</code>```

Thanks!

答:
You can use the PivotTable Grouping feature to do this.

This will make your PivotTable look like a mess initially:

Drag the Product field out of the PivotTable Fields List, leaving the new Product2 field:

Then click on the Group1 label and overtype it with what you want:

Then repeat for the other field:

It will be possible to write some VBA that does this automatically, if there are too many to do manually.

It also may be possible to use PowerQuery/PowerPivot to do this, but I'd need to know exactly what version AND SKU of Excel is involved i.e. not just the year number but also the highlighted bit in the screenshot below:

Body:
How do you create a custom string column in Excel 2016(using PivotTable Report) with a concatenated string of one of the base table's columns?

I'm trying to roll up all the products within an associated brand(i.e. a brand has multiple products).

Sample data:

Brand   Product      MPG
-----   -------      ------
Toyota  RAV4         20
Toyota  Camry        25
Toyota  4Runner      18
Nissan  Pathfinder   18
Nissan  Versa        25

I want the output of the summarized data to be like this:

Brand     Products               Brand Avg MPG
-------   --------               --------
Toyota    RAV4, Camry, 4Runner   21.00
Nissan    Pathfinder, Versa      21.50

Thanks!


问:
Overwriting nested styles in React Bootstrap using Styled-Components
I'm using styled-components with React Bootstrap. We want a tab (Tab 3 in this example) to be colored based on a status. It works well when the tab is not active, but when it's active, the Bootstrap style overwrites the style.

I've identified the style that's overwriting my color in the console. When I use console to turn off the style, I see my intended tab color.

I'm just not sure how to target this style using style-components. I've tried experimenting with different ideas from the official doc but haven't been able to get it working.

My styled component:

```<code> export const TabNavItem = styled(NavItem)`
      background-color: ${props => (props.colorize ? 'orange' : 'white')};
      }
    `;
</code>```

Usage:

```<code>  render() {
    const { children, active, colorize } = this.props;
    return (
      <TabNavItem onClick={this.handleChangeLocation} active={active} colorize={colorize}>
        {children}
      </TabNavItem>
    );
  }
</code>```

Color works fine when tab is not active:

When tab is active, color is covered by Bootstrap styles:

This is the style I need to overwrite (background-color):

答:
I have a couple of suggestions for how you might be able to fix this particular issue. You might not like either of them, as they aren't very elegant, but here goes.

Approach 1

Override the style using a more specific selector. You know how styled components can leverage Sass to their advantage? Well, you can use that to create a selector for your tabs that will be at least as specific as the one in Bootstrap. Assuming the component you are styling is the li in this equation, you could do something like this (hacky, I know).

```<code>body .nav-tabs > & {
    &.active > a {
        background-color: blue; // whatever
    }
}
</code>```

The initial & refers of course to the li in question, so would give you a selector like body .nav-tabs > li.active > a

Approach 2

A little bit simpler would be the idea of using the !important flag at the end of the CSS rule, like so:

```<code>export const TabNavItem = styled(NavItem)`
  background-color: ${props => (props.colorize ? 'orange' : 'white')} !important;
`;
</code>```

Body:
I'm using styled-components with React Bootstrap. We want a tab (Tab 3 in this example) to be colored based on a status. It works well when the tab is not active, but when it's active, the Bootstrap style overwrites the style.

I've identified the style that's overwriting my color in the console. When I use console to turn off the style, I see my intended tab color.

I'm just not sure how to target this style using style-components. I've tried experimenting with different ideas from the official doc but haven't been able to get it working.

My styled component:

 export const TabNavItem = styled(NavItem)`
      background-color: ${props => (props.colorize ? 'orange' : 'white')};
      }
    `;

Usage:

  render() {
    const { children, active, colorize } = this.props;
    return (
      <TabNavItem onClick={this.handleChangeLocation} active={active} colorize={colorize}>
        {children}
      </TabNavItem>
    );
  }

Color works fine when tab is not active:

When tab is active, color is covered by Bootstrap styles:

This is the style I need to overwrite (background-color):

Body:
I have a couple of suggestions for how you might be able to fix this particular issue. You might not like either of them, as they aren't very elegant, but here goes.

Approach 1

Override the style using a more specific selector. You know how styled components can leverage Sass to their advantage? Well, you can use that to create a selector for your tabs that will be at least as specific as the one in Bootstrap. Assuming the component you are styling is the li in this equation, you could do something like this (hacky, I know).

body .nav-tabs > & {
    &.active > a {
        background-color: blue; // whatever
    }
}

The initial & refers of course to the li in question, so would give you a selector like body .nav-tabs > li.active > a

Approach 2

A little bit simpler would be the idea of using the !important flag at the end of the CSS rule, like so:

export const TabNavItem = styled(NavItem)`
  background-color: ${props => (props.colorize ? 'orange' : 'white')} !important;
`;


问:
How to expand/collapse status bar through ADB?
Is there any way to expand/collapse status bar of Android phone over ADB?

答:
Another way. By using "adb shell cmd"

Expand

adb shell cmd statusbar expand-notifications

Collapse

adb shell cmd statusbar collapse

You can expand quick settings also

adb shell cmd statusbar expand-settings

Please check help for more:

adb shell cmd statusbar help

ContentLicense: CC BY-SA 4.0


问:
Contour of KNN model in ggplot?
I have a KNN model which I am plotting using the contour function.  This is a simple example of the kind of thing that I'm doing (based on this Purdue exam):

```<code>library(class)
library(nnet)

TrainC<-read.table("http://miner.chem.purdue.edu/Exam1/TrainC.dat")
names(TrainC)<-c("x1","x2","y")

K=15

p <- as.matrix(TrainC[, -3])
xp <- seq(min(TrainC$x1), max(TrainC$x1), length = 50); np <- length(xp)
yp <- seq(min(TrainC$x2), max(TrainC$x2), length = 50)
tp<-TrainC$y

yhat <- knn(p, p, tp, k = K)

plot(TrainC[, 1], TrainC[, 2], xlab = "x1", ylab = "x2", col=as.numeric(TrainC$y)+1)
pt <- expand.grid(x1 = xp, x2 = yp)
Z <- knn(p, pt, tp, k = K)
zp<-class.ind(Z)[,1] - class.ind(Z)[,2]

contour(xp, yp, matrix(zp, np), add = T, levels = 0, labex = 0)
</code>```

My question is: how can I make this same plot in ggplot?  In particular, how I can I do the equivalent of contour?

答:
```<code>d <- transform(melt(matrix(zp, np)), xp=xp[X1], yp=yp[X2])
ggplot(d, aes(xp, yp, z=value)) +
  geom_contour() +
  geom_point(aes(x1, x2, colour=y, z=NULL), data=TrainC)
</code>```

Title: Contour of KNN model in ggplot?

Body:
I have a KNN model which I am plotting using the contour function.  This is a simple example of the kind of thing that I'm doing (based on this Purdue exam):

library(class)
library(nnet)

TrainC<-read.table("http://miner.chem.purdue.edu/Exam1/TrainC.dat")
names(TrainC)<-c("x1","x2","y")

K=15

p <- as.matrix(TrainC[, -3])
xp <- seq(min(TrainC$x1), max(TrainC$x1), length = 50); np <- length(xp)
yp <- seq(min(TrainC$x2), max(TrainC$x2), length = 50)
tp<-TrainC$y

yhat <- knn(p, p, tp, k = K)

plot(TrainC[, 1], TrainC[, 2], xlab = "x1", ylab = "x2", col=as.numeric(TrainC$y)+1)
pt <- expand.grid(x1 = xp, x2 = yp)
Z <- knn(p, pt, tp, k = K)
zp<-class.ind(Z)[,1] - class.ind(Z)[,2]

contour(xp, yp, matrix(zp, np), add = T, levels = 0, labex = 0)

My question is: how can I make this same plot in ggplot?  In particular, how I can I do the equivalent of contour?


问:
Which security protocol do you use in OAuth if starting at Google?
Say you have a website www.site.come and you click 'Log in with Google', the google log in page shows up, you sign in and then directed back to www.site.com but now logged in as the proper user.

What protocol would you use if you started at Google? So for instance you start at google.com, log directly into google and as a logged in user, there exists a button which goes to www.site.com which when you click it will bring you to the www.site.com but signed in based on some information that is passed when the button is clicked. Would this be equivalent to SAML? Or more to OpenId?

答: It's OAuth 2.0. You can test it with https://developers.google.com/oauthplayground/</p>


问:
What does the error "double cannot be dereferenced" mean?
I understand that the ArrayList can't hold any primitive data
but how can i call my method horseFeed() into the driver alongside my Arraylist constructor so that i don't get a double dereferenced error

Also can someone explain to me what a double dereferenced error is and why I'm getting it, please help

The method is in my class

```<code>public class horse
{
  .
  .
  .

  //took out a lot of code as it was not important to the problem

  public String horseFeed(double w)
  {
    double sFeed= w*.015;
    double eFeed= w*.013;
    String range = sFeed + " < " + eFeed;
    return range;
  }
}
</code>```

This is the ArrayList class

```<code>import java.util.*;
public class horseStable
{
 .
 .
 .
 public double findHorseFeed(int i)
 {
   double weight = horseList.get(i).getWeight();
   return weight;

  }
}
</code>```

This is the Driver

```<code>public class Main
{
  public static void main(String args[])
  {
  //returns the weight of the horse works fine
  System.out.println(stable1.findHorseFeed(1));
  // This is supposed to use the horseFeed method in the class by using the horse's weight. Where can i place the horseFeed method without getting an error?
  System.out.println(stable1.findHorseFeed(1).horseFeed());
  }
 }
</code>```

答:
That error means that you tried to invoke a method on a double value - in Java, double is a primitive type and you can't call methods on it:

```<code>stable1.findHorseFeed(1).horseFeed()
             ^               ^
      returns a double   can't call any method on it
</code>```

You need to invoke the method on the correct object, with the expected parameters - something like this:

```<code>Horse aHorse = new Horse(...);
aHorse.horseFeed(stable1.findHorseFeed(1));
</code>```

The method horseFeed() is in the Horse class, and it receives a parameter of type double, which is returned by the method findHorseFeed() in the HorseStable class. Clearly, first you need to create an instance of type Horse to invoke it.

Also, please follow the convention that class names start with an uppercase character.

Body:
I understand that the ArrayList can't hold any primitive data
but how can i call my method horseFeed() into the driver alongside my Arraylist constructor so that i don't get a double dereferenced error

Also can someone explain to me what a double dereferenced error is and why I'm getting it, please help

The method is in my class

public class horse
{
  .
  .
  .

  //took out a lot of code as it was not important to the problem

  public String horseFeed(double w)
  {
    double sFeed= w*.015;
    double eFeed= w*.013;
    String range = sFeed + " < " + eFeed;
    return range;
  }
}

This is the ArrayList class

import java.util.*;
public class horseStable
{
 .
 .
 .
 public double findHorseFeed(int i)
 {
   double weight = horseList.get(i).getWeight();
   return weight;

  }
}

This is the Driver

public class Main
{
  public static void main(String args[])
  {
  //returns the weight of the horse works fine
  System.out.println(stable1.findHorseFeed(1));
  // This is supposed to use the horseFeed method in the class by using the horse's weight. Where can i place the horseFeed method without getting an error?
  System.out.println(stable1.findHorseFeed(1).horseFeed());
  }
 }

Body:
That error means that you tried to invoke a method on a double value - in Java, double is a primitive type and you can't call methods on it:

stable1.findHorseFeed(1).horseFeed()
             ^               ^
      returns a double   can't call any method on it

You need to invoke the method on the correct object, with the expected parameters - something like this:

Horse aHorse = new Horse(...);
aHorse.horseFeed(stable1.findHorseFeed(1));

The method horseFeed() is in the Horse class, and it receives a parameter of type double, which is returned by the method findHorseFeed() in the HorseStable class. Clearly, first you need to create an instance of type Horse to invoke it.

Also, please follow the convention that class names start with an uppercase character.


问:
docker-compose.yml invalid type
docker-compose.yml

```<code>version: '2.0'
services:
  asdf-db:
    container_name: asdf-db
    build: ./asdf/db
    ports:
      - 5435:5432 # expose ports - HOST:CONTAINER
    environment:
      - POSTGRES_USER=postgres
      - POSTGRES_PASSWORD=postgres
    healthcheck:
      test: exit 0

  asdf-service:
    container_name: asdf-service
    build: ./
    volumes:
      - '.:/usr/src/asdf'
    ports:
      - 5001:5000 # expose ports - HOST:CONTAINER
    environment:
      - APP_SETTINGS=asdf.config.DevelopmentConfig
      - DATABASE_URL=postgres://postgres:postgres@asdf-db:5432/asdf_dev
      - DATABASE_TEST_URL=postgres://postgres:postgres@asdf-db:5432/asdf_test
    depends_on:
      asdf-db:
        condition: service_healthy
      links:
        - asdf-db
</code>```

when i run docker-compose up -d i get the following error message:

```<code>ERROR: The Compose file '.\docker-compose.yml' is invalid because:
Unsupported config option for services.asdf-db: 'healthcheck'
services.asdf-service.depends_on contains an invalid type, it should be an array
</code>```

I've tried switching the version to 2.1 and then i get the following error message:

```<code>ERROR: The Compose file '.\docker-compose.yml' is invalid because:
services.asdf-service.depends_on.links contains ["asdf-db"], which is an invalid type, it should be an object
</code>```

How do I change asdf-db to an object?

答:
Healthcheck was added in 2.1 so you need at least that version.

In 2.1 version, you have links within depends_on, whereas it should be in the same level.

Title: docker-compose.yml invalid type

Body:
docker-compose.yml

version: '2.0'
services:
  asdf-db:
    container_name: asdf-db
    build: ./asdf/db
    ports:
      - 5435:5432 # expose ports - HOST:CONTAINER
    environment:
      - POSTGRES_USER=postgres
      - POSTGRES_PASSWORD=postgres
    healthcheck:
      test: exit 0

  asdf-service:
    container_name: asdf-service
    build: ./
    volumes:
      - '.:/usr/src/asdf'
    ports:
      - 5001:5000 # expose ports - HOST:CONTAINER
    environment:
      - APP_SETTINGS=asdf.config.DevelopmentConfig
      - DATABASE_URL=postgres://postgres:postgres@asdf-db:5432/asdf_dev
      - DATABASE_TEST_URL=postgres://postgres:postgres@asdf-db:5432/asdf_test
    depends_on:
      asdf-db:
        condition: service_healthy
      links:
        - asdf-db

when i run docker-compose up -d i get the following error message:

ERROR: The Compose file '.\docker-compose.yml' is invalid because:
Unsupported config option for services.asdf-db: 'healthcheck'
services.asdf-service.depends_on contains an invalid type, it should be an array

I've tried switching the version to 2.1 and then i get the following error message:

ERROR: The Compose file '.\docker-compose.yml' is invalid because:
services.asdf-service.depends_on.links contains ["asdf-db"], which is an invalid type, it should be an object

How do I change asdf-db to an object?


问:
How to change the input to an OP in tensorflow
I need to change the intput to a tesor after it was constructed. Take the following simplified example: x (constant=42.0), s (x^2), and x_new (constant=4.0).

I want to change the input to s from being x to being x_new. After performing this operation I expect s.eval() == 16.0

```<code>x = tf.constant(42.0, name='x')
s = tf.square(x, name='s')
x_new = tf.constant(4.0, name='x_new')

tf.get_default_graph().as_graph_def()

Out[6]:
node {
  name: "x"
  op: "Const"
  attr {
    key: "dtype"
    value {
      type: DT_FLOAT
    }
  }
  attr {
    key: "value"
    value {
      tensor {
        dtype: DT_FLOAT
        tensor_shape {
        }
        float_val: 42.0
      }
    }
  }
}
node {
  name: "s"
  op: "Square"
  input: "x"
  attr {
    key: "T"
    value {
      type: DT_FLOAT
    }
  }
}
node {
  name: "x_new"
  op: "Const"
  attr {
    key: "dtype"
    value {
      type: DT_FLOAT
    }
  }
  attr {
    key: "value"
    value {
      tensor {
        dtype: DT_FLOAT
        tensor_shape {
        }
        float_val: 4.0
      }
    }
  }
}
versions {
  producer: 24
}
</code>```

I've tried using tf.contrib.graph_editor.reroute_inputs, but for the life of me I can't figure out what to do with the subgraphs it returns.

I've also tried playing with tf.import_graph_def as vaguely described in this git issue (https://github.com/tensorflow/tensorflow/issues/1758), but no matter how many ways I try to do it, I don't get s to change intputs from x to x_new.

Anyone know how to use either of these approaches to accomplish this trivial example?

答:
You can use a placeholder instead of a constant.

For example:

```<code>import tensorflow as tf

x = tf.placeholder(tf.int32, shape=[])
s = tf.square(x)

with tf.Session() as sess:
  print(s.eval({x: 5}))
  print(s.eval({x: 4}))
</code>```

Body:
I need to change the intput to a tesor after it was constructed. Take the following simplified example: x (constant=42.0), s (x^2), and x_new (constant=4.0).

I want to change the input to s from being x to being x_new. After performing this operation I expect s.eval() == 16.0

x = tf.constant(42.0, name='x')
s = tf.square(x, name='s')
x_new = tf.constant(4.0, name='x_new')

tf.get_default_graph().as_graph_def()

Out[6]:
node {
  name: "x"
  op: "Const"
  attr {
    key: "dtype"
    value {
      type: DT_FLOAT
    }
  }
  attr {
    key: "value"
    value {
      tensor {
        dtype: DT_FLOAT
        tensor_shape {
        }
        float_val: 42.0
      }
    }
  }
}
node {
  name: "s"
  op: "Square"
  input: "x"
  attr {
    key: "T"
    value {
      type: DT_FLOAT
    }
  }
}
node {
  name: "x_new"
  op: "Const"
  attr {
    key: "dtype"
    value {
      type: DT_FLOAT
    }
  }
  attr {
    key: "value"
    value {
      tensor {
        dtype: DT_FLOAT
        tensor_shape {
        }
        float_val: 4.0
      }
    }
  }
}
versions {
  producer: 24
}

I've tried using tf.contrib.graph_editor.reroute_inputs, but for the life of me I can't figure out what to do with the subgraphs it returns.

I've also tried playing with tf.import_graph_def as vaguely described in this git issue (https://github.com/tensorflow/tensorflow/issues/1758), but no matter how many ways I try to do it, I don't get s to change intputs from x to x_new.

Anyone know how to use either of these approaches to accomplish this trivial example?

Body:
You can use a placeholder instead of a constant.

For example:

import tensorflow as tf

x = tf.placeholder(tf.int32, shape=[])
s = tf.square(x)

with tf.Session() as sess:
  print(s.eval({x: 5}))
  print(s.eval({x: 4}))


问:
Dynamically Displaying Text with TextView (Android)
Basically what I want to do in my Android app is use TextView to display two different pieces of text at once. So in code, I want to be able to do something like this:

```<code>    LinearLayout ll = new LinearLayout(this);
    TextView text = new TextView(this);
    text.setTextColor(0xFF000000);
    text.setGravity(Gravity.CENTER_HORIZONTAL);
    text.setTextSize(20f);
    text.setText("Text1");
    text.setTextSize(14f);
    text.setColor(0xFF0000FF);
    text.setText("\nText2");
    ll.addView(text);
</code>```

To clarify, I am trying to display a black "Text1" and a blue "Text2" at once using only a single TextView. Obviously this doesn't work out using the code above. I've considered using a second TextView but that seems like a waste of effort and memory to me. I'm sure the brilliant minds here can come up with the best solution to this.

Thank you very much in advance for your time and your assistance.

答:
when do you plan to update the textview ? If it is on click of a button then get a reference to the textview and in the onClickListener() update the text, color, etc whatever you want to do.

After seeing your other comments, I think SpannableString is what you are looking for

Body:
Basically what I want to do in my Android app is use TextView to display two different pieces of text at once. So in code, I want to be able to do something like this:

    LinearLayout ll = new LinearLayout(this);
    TextView text = new TextView(this);
    text.setTextColor(0xFF000000);
    text.setGravity(Gravity.CENTER_HORIZONTAL);
    text.setTextSize(20f);
    text.setText("Text1");
    text.setTextSize(14f);
    text.setColor(0xFF0000FF);
    text.setText("\nText2");
    ll.addView(text);

To clarify, I am trying to display a black "Text1" and a blue "Text2" at once using only a single TextView. Obviously this doesn't work out using the code above. I've considered using a second TextView but that seems like a waste of effort and memory to me. I'm sure the brilliant minds here can come up with the best solution to this.

Thank you very much in advance for your time and your assistance.


问:
Load lib files in production
I've upgraded one of my apps from Rails 4.2.6 to Rails 5.0.0. The Upgrade Guide says, that the Autoload feature is now disabled in production by default.

Now I always get an error on my production server since I load all lib files with autoload in the application.rb file.

```<code>module MyApp
    class Application < Rails::Application
        config.autoload_paths += %W( lib/ )
    end
end
</code>```

For now, I've set the config.enable_dependency_loading to true but I wonder if there is a better solution to this. There must be a reason that Autoloading is disabled in production by default.

答:
Moving the lib folder to app helped solve a problem, my Twitter api would not run in production. I had "uninitialized constant TwitterApi" and my Twitter API was in my lib folder.
I had config.autoload_paths += Dir["#{Rails.root}/app/lib"] in my application.rb but it didn't work before moving the folder.

This did the trick

Title: Load lib files in production

Body:
I've upgraded one of my apps from Rails 4.2.6 to Rails 5.0.0. The Upgrade Guide says, that the Autoload feature is now disabled in production by default.

Now I always get an error on my production server since I load all lib files with autoload in the application.rb file.

module MyApp
    class Application < Rails::Application
        config.autoload_paths += %W( lib/ )
    end
end

For now, I've set the config.enable_dependency_loading to true but I wonder if there is a better solution to this. There must be a reason that Autoloading is disabled in production by default.


问:
Stitching panorama on iOS crashes with cvflann::anyimpl::bad_any_cast
I have no experience with c++ but i need to interface with OpenCV in an iOS app. I have it building correctly but it crashes when calling some c++ code.

The code below crashes with this message: libc++abi.dylib: libc++abi.dylib: terminating with uncaught exception of type cvflann::anyimpl::bad_any_cast
terminating with uncaught exception of type cvflann::anyimpl::bad_any_cast

```<code>bool stitch(const std::vector <cv::Mat> & images, cv::Mat &result) {
    Stitcher stitcher = Stitcher::createDefault(false);

    Stitcher::Status status = stitcher.stitch(images, result); <-- Crash!

    if (status != Stitcher::OK) {
        return false;
    }

    return true;
}
</code>```

I assume this is because the input or output to stitch(...) is an incorrect type but i cannot figure out what i need to give it or how to convert it.

The function I'm calling is defined as such:

```<code>Status stitch(InputArrayOfArrays images, OutputArray pano);
</code>```

Where InputArrayOfArrays and OutputArray are all aliases of _InputArray

What to do?

Edit: This is using OpenCV 3.0 where i think the example code I'm using was for OpenCV 2.4. Maybe that is the problem.

答:
Dropping the include of opencv.hpp in favor of the minimal set of includes worked for me as well.  Here are the includes I ended up with in my case.

```<code>#import <opencv2/calib3d.hpp>
#import <opencv2/features2d.hpp>
#import <opencv2/xfeatures2d.hpp>
#import <opencv2/imgproc/imgproc.hpp>
</code>```

I was getting the bad_any_cast from somewhere within a call to FlannBasedMatcher::knnMatch at the time and had tried many "corrections" before finding this solution.

Thank you!

Body:
I have no experience with c++ but i need to interface with OpenCV in an iOS app. I have it building correctly but it crashes when calling some c++ code.

The code below crashes with this message: libc++abi.dylib: libc++abi.dylib: terminating with uncaught exception of type cvflann::anyimpl::bad_any_cast
terminating with uncaught exception of type cvflann::anyimpl::bad_any_cast

bool stitch(const std::vector <cv::Mat> & images, cv::Mat &result) {
    Stitcher stitcher = Stitcher::createDefault(false);

    Stitcher::Status status = stitcher.stitch(images, result); <-- Crash!

    if (status != Stitcher::OK) {
        return false;
    }

    return true;
}

I assume this is because the input or output to stitch(...) is an incorrect type but i cannot figure out what i need to give it or how to convert it.

The function I'm calling is defined as such:

Status stitch(InputArrayOfArrays images, OutputArray pano);

Where InputArrayOfArrays and OutputArray are all aliases of _InputArray

What to do?

Edit: This is using OpenCV 3.0 where i think the example code I'm using was for OpenCV 2.4. Maybe that is the problem.

Body:
Dropping the include of opencv.hpp in favor of the minimal set of includes worked for me as well.  Here are the includes I ended up with in my case.

#import <opencv2/calib3d.hpp>
#import <opencv2/features2d.hpp>
#import <opencv2/xfeatures2d.hpp>
#import <opencv2/imgproc/imgproc.hpp>

I was getting the bad_any_cast from somewhere within a call to FlannBasedMatcher::knnMatch at the time and had tried many "corrections" before finding this solution.

Thank you!


问:
Python Dataframe: Remove duplicate words in the same cell within a column in Python
Below shows a column with data I have and another column with the de-duplicated data I want.

I honestly don't even know how to start doing this in Python code.  I've read a couple of posts on this in R, but not in Python.

答:
If you're looking to get rid of consecutive duplicates only, this should suffice:

```<code>df['Desired'] = df['Current'].str.replace(r'\b(\w+)(\s+\1)+\b', r'\1')
df

           Current          Desired
0       Racoon Dog       Racoon Dog
1          Cat Cat              Cat
2  Dog Dog Dog Dog              Dog
3  Rat Fox Chicken  Rat Fox Chicken
</code>```

Details

```<code>\b        # word boundary
(\w+)     # 1st capture group of a single word
(
\s+       # 1 or more spaces
\1        # reference to first group
)+        # one or more repeats
\b
</code>```

Regex from here.

To remove non-consecutive duplicates, I'd suggest a solution involving the OrderedDict data structure:

```<code>from collections import OrderedDict

df['Desired'] = (df['Current'].str.split()
                              .apply(lambda x: OrderedDict.fromkeys(x).keys())
                              .str.join(' '))
df

           Current          Desired
0       Racoon Dog       Racoon Dog
1          Cat Cat              Cat
2  Dog Dog Dog Dog              Dog
3  Rat Fox Chicken  Rat Fox Chicken
</code>```

Body:
If you're looking to get rid of consecutive duplicates only, this should suffice:

df['Desired'] = df['Current'].str.replace(r'\b(\w+)(\s+\1)+\b', r'\1')
df

           Current          Desired
0       Racoon Dog       Racoon Dog
1          Cat Cat              Cat
2  Dog Dog Dog Dog              Dog
3  Rat Fox Chicken  Rat Fox Chicken

Details

\b        # word boundary
(\w+)     # 1st capture group of a single word
(
\s+       # 1 or more spaces
\1        # reference to first group
)+        # one or more repeats
\b

Regex from here.

To remove non-consecutive duplicates, I'd suggest a solution involving the OrderedDict data structure:

from collections import OrderedDict

df['Desired'] = (df['Current'].str.split()
                              .apply(lambda x: OrderedDict.fromkeys(x).keys())
                              .str.join(' '))
df

           Current          Desired
0       Racoon Dog       Racoon Dog
1          Cat Cat              Cat
2  Dog Dog Dog Dog              Dog
3  Rat Fox Chicken  Rat Fox Chicken


问:
brew link php71: Could not symlink sbin/php-fpm
I'm trying to install Laravel Valet, which requires php 7.1, but when i run brew install php71, I get the following error:

```<code>==> Pouring php71-7.1.10_21.high_sierra.bottle.tar.gz
Error: The `brew link` step did not complete successfully
The formula built, but is not symlinked into /usr/local
Could not symlink sbin/php-fpm
/usr/local/sbin is not writable.
</code>```

I get the same error when i run brew link php71. If i run php -v, I actually see that I'm currently running PHP 7.1.7.

But when I run valet install, I get:

```<code>  [DomainException]
  Unable to determine linked PHP.
</code>```

I don't even have an sbin directory in /usr/local.

Any suggestions?

答: Installing Laravel Valet, I had a similar issue with sbin not being writable. I had to make the directory, then utilized the solution included at this page. This finally allowed me the proper permissions to run a brew link command with a previously installed version of php 7.1.</p>

Body:
I'm trying to install Laravel Valet, which requires php 7.1, but when i run brew install php71, I get the following error:

==> Pouring php71-7.1.10_21.high_sierra.bottle.tar.gz
Error: The `brew link` step did not complete successfully
The formula built, but is not symlinked into /usr/local
Could not symlink sbin/php-fpm
/usr/local/sbin is not writable.

I get the same error when i run brew link php71. If i run php -v, I actually see that I'm currently running PHP 7.1.7.

But when I run valet install, I get:

  [DomainException]
  Unable to determine linked PHP.

I don't even have an sbin directory in /usr/local.

Any suggestions?


问:
How to update multiple fields using JsonResult and Ajax DropDown
I have JsonResult list of Articles  and it looked like this:

```<code>[
    {
        "tbl_dobavuvaci": null,
        "tbl_fakDet": null,
        "tbl_fakMas": null,
        "tbl_kompanii": null,
        "tbl_useri": null,
        "artID": 1,
        "artKompID": 1,
        "artUserID": 1,
        "artCode": 25456658845646540,
        "artIme": "Artikal 1 Ime",
        "artCenaNab": 10,
        "artCenaProd": 15,
        "artDDV": 18,
        "artDobavuvac": 1
    },
    {
        "tbl_dobavuvaci": null,
        "tbl_fakDet": null,
        "tbl_fakMas": null,
        "tbl_kompanii": null,
        "tbl_useri": null,
        "artID": 2,
        "artKompID": 1,
        "artUserID": 1,
        "artCode": 8606010872303,
        "artIme": "TestName",
        "artCenaNab": 25,
        "artCenaProd": 30,
        "artDDV": 18,
        "artDobavuvac": 1
    }
]
</code>```

Now in HTML View i have javascript:

```<code>  $(document).ready(function () {
        $.getJSON("/fakturi/getArticles", function (data) {
            $.each(data, function (i, data) {
                $('<option>',
                   {
                       value: data.artID,
                       text: data.artCode
                   }).html;
            });
        })
        $(function () {
            $("[name='bar']").on("change", function () {
                $("#artikal").val($(this).val());
            });
        });
    });
</code>```

Now When i change artCod named dropdown with artCode values from Json, corectly updated second field with artIme name.

HTML CODE:

```<code>@Html.DropDownList("bar", null, string.Empty, htmlAttributes: new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.tbl_artikli, "", new { @class = "text-danger",})

@Html.DropDownList("artikal", null, string.Empty, htmlAttributes: new { @class = "form-control" })
                @Html.ValidationMessageFor(model => model.tbl_artikli, "", new { @class = "text-danger", })

 @Html.TextBox("artCenaProd", "", new { @class = "form-control", @id = "artCenaProd", style = "width:60pt" })
</code>```

My Question is how to update third field named artCenaProd when I will change dropdown?

答:
You need to store the json array you receive from your ajax call to a local variable in your script. When the dropdown change event is fired, read the selected option and get the option value (artID). Now filter the local array for items with this id and get the subset (If the artID's are unique, you will get a sub array with one it.

```<code>$(document).ready(function () {

    var localData = [];
    var $bar = $("[name='bar']");

    $.getJSON("@Url.Action("/fakturi/getArticles")",
        function(data) {
            localData = data;
            $bar.empty();
            $.each(data,
                function(i, data) {
                    var t = $('<option>', { value: data.artID, text: data.artCode });
                    $bar.append(t);
                });
        });
    $bar.change(function() {
        var v = $(this).val();

        var filteredData = localData.filter(function(item) {
            return item.artID == v;
        });
        if (filteredData.length) {
            $("#artCenaProd").val(filteredData[0].artCenaProd);
        }

    });

});
</code>```

Also if you are populating the Dropdown's options using the ajax call, no need to use the DropDownList helper method! Simply write HTML markup for a SELECT element

```<code><SELECT name='bar'>

</SELECT>
</code>```

Body:
I have JsonResult list of Articles  and it looked like this:

[
    {
        "tbl_dobavuvaci": null,
        "tbl_fakDet": null,
        "tbl_fakMas": null,
        "tbl_kompanii": null,
        "tbl_useri": null,
        "artID": 1,
        "artKompID": 1,
        "artUserID": 1,
        "artCode": 25456658845646540,
        "artIme": "Artikal 1 Ime",
        "artCenaNab": 10,
        "artCenaProd": 15,
        "artDDV": 18,
        "artDobavuvac": 1
    },
    {
        "tbl_dobavuvaci": null,
        "tbl_fakDet": null,
        "tbl_fakMas": null,
        "tbl_kompanii": null,
        "tbl_useri": null,
        "artID": 2,
        "artKompID": 1,
        "artUserID": 1,
        "artCode": 8606010872303,
        "artIme": "TestName",
        "artCenaNab": 25,
        "artCenaProd": 30,
        "artDDV": 18,
        "artDobavuvac": 1
    }
]

Now in HTML View i have javascript:

  $(document).ready(function () {
        $.getJSON("/fakturi/getArticles", function (data) {
            $.each(data, function (i, data) {
                $('<option>',
                   {
                       value: data.artID,
                       text: data.artCode
                   }).html;
            });
        })
        $(function () {
            $("[name='bar']").on("change", function () {
                $("#artikal").val($(this).val());
            });
        });
    });

Now When i change artCod named dropdown with artCode values from Json, corectly updated second field with artIme name.

HTML CODE:

@Html.DropDownList("bar", null, string.Empty, htmlAttributes: new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.tbl_artikli, "", new { @class = "text-danger",})

@Html.DropDownList("artikal", null, string.Empty, htmlAttributes: new { @class = "form-control" })
                @Html.ValidationMessageFor(model => model.tbl_artikli, "", new { @class = "text-danger", })

 @Html.TextBox("artCenaProd", "", new { @class = "form-control", @id = "artCenaProd", style = "width:60pt" })

My Question is how to update third field named artCenaProd when I will change dropdown?

Body:
You need to store the json array you receive from your ajax call to a local variable in your script. When the dropdown change event is fired, read the selected option and get the option value (artID). Now filter the local array for items with this id and get the subset (If the artID's are unique, you will get a sub array with one it.

$(document).ready(function () {

    var localData = [];
    var $bar = $("[name='bar']");

    $.getJSON("@Url.Action("/fakturi/getArticles")",
        function(data) {
            localData = data;
            $bar.empty();
            $.each(data,
                function(i, data) {
                    var t = $('<option>', { value: data.artID, text: data.artCode });
                    $bar.append(t);
                });
        });
    $bar.change(function() {
        var v = $(this).val();

        var filteredData = localData.filter(function(item) {
            return item.artID == v;
        });
        if (filteredData.length) {
            $("#artCenaProd").val(filteredData[0].artCenaProd);
        }

    });

});

Also if you are populating the Dropdown's options using the ajax call, no need to use the DropDownList helper method! Simply write HTML markup for a SELECT element

<SELECT name='bar'>

</SELECT>


问:
Some issuing banks refusing 3D Secure requests
We have a commerce site we're attempting to get 3D Secure (Verified by VISA/Mastercard Securecode) set up with.

We are using DataCash as our payment provider.

We are seeing the following issue:

Some cards that are enrolled in these schemes are being successfully shown the 3D Secure pages, others are failing, and talking to the issuing banks hasn't helped as they are telling us they haven't seen the transaction.

We are getting messages from servers like "cap.securecode.com" stating:

Your authentication could not be completed because of a system error. If this happens consistently, please contact your CSR".

Or from "www.securesuite.co.uk":

You cannot access this page.

This may be due to one of two reasons:

The FI you are trying to access is deactivated

The access to the FI is restricted for specific IP addresses, and your address is not one of them

Has anyone else seen these errors returned from the verifying banks, and how can I resolve it?

I'm trying to get further details of any pattern to the successes and failures.

答: 3D secure is a mess - your payment processor will hand off to one of many sites depending on who issued your card.  Some of these sites accept a GET request and some only a POST request.  You may receive this error if you are sending a GET rather than POST.</p>


问:
Exception in thread main error?
Why am I getting this error? I need to read from the text file and allow them to login if the password and username match but I keep getting an error " no line is found ". But my text file has lines

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

public class Program7_4Part2 {

public static void main(String[] args) throws IOException {

    Scanner fileInput = new Scanner(new File("accounts.txt"));

    // PART 2

    ArrayList<String> userNames = new ArrayList<>();
    ArrayList<String> passwords = new ArrayList<>();

    // read data from file
    while (fileInput.hasNextLine()) {
        userNames.add(fileInput.next());
        String line = fileInput.nextLine();
        String[] userName = line.split(" ");
        userNames.add(userName[0]);
        passwords.add(userName[1]);
    }

    // login
    System.out.println("Login.");
    System.out.println("Username: ");
    String userNameLogin = fileInput.nextLine();
    System.out.println("Password: ");
    String pwLogin = fileInput.nextLine();

}
</code>```

}

答:
It would be helpful if you showed the actual error.  But I suspect you are getting the error from this line:

```<code>String userNameLogin = fileInput.nextLine();
</code>```

You've already read through the entire file in the while loop.  So here there is no next line left to read.

But you probably want to read from System.in here, not from the file.

Title: Exception in thread main error?

Body:
Why am I getting this error? I need to read from the text file and allow them to login if the password and username match but I keep getting an error " no line is found ". But my text file has lines

import java.util.*;
import java.io.*;

public class Program7_4Part2 {

public static void main(String[] args) throws IOException {

    Scanner fileInput = new Scanner(new File("accounts.txt"));

    // PART 2

    ArrayList<String> userNames = new ArrayList<>();
    ArrayList<String> passwords = new ArrayList<>();

    // read data from file
    while (fileInput.hasNextLine()) {
        userNames.add(fileInput.next());
        String line = fileInput.nextLine();
        String[] userName = line.split(" ");
        userNames.add(userName[0]);
        passwords.add(userName[1]);
    }

    // login
    System.out.println("Login.");
    System.out.println("Username: ");
    String userNameLogin = fileInput.nextLine();
    System.out.println("Password: ");
    String pwLogin = fileInput.nextLine();

}

}

Body:
It would be helpful if you showed the actual error.  But I suspect you are getting the error from this line:

String userNameLogin = fileInput.nextLine();

You've already read through the entire file in the while loop.  So here there is no next line left to read.

But you probably want to read from System.in here, not from the file.


问:
Running Dependent Queries with SparkSQL using Spark Session
We have 3 queries which are currently running on HIVE.

Using Spark 2.1.0

We are trying to Run that using Spark SQL but by using the SparkSession(like wrapping with Scala code making a Jar & then Submit using Spark-Submit)

Now for Example lets say :
Query-1 uses 3 tables (Table - a, b & c) and Insert into table --> Output_Table_1

Query-2 uses few other tables(performing Joins) and output_table_1 which is populated from the output of Query-1. This gives output_table_2

Similarly Query-3 uses few tables & may or may not use output_table_1 and/or output_table_2(we are not sure on this as still designing)

Currently the way i am doing this is writing all the queries in a property file and reading it in def main using Typesafe.ConfigFactory (Please suggest if there is any better way)

In the def main(){} what i am doing is :

```<code>val query_1 = spark.sql('query1')
query_1.write.mode("overwrite").insertInto("output_table_1")
</code>```

Now when i am doing the Below step It throws an Error - output_table_1 not found

```<code>val query_2 = spark.sql('query2')
query_2.write.mode("overwrite").insertInto("output_table_2")
</code>```

Similarly for the 3rd Query and table i am getting Same error. So basically i am trying to Chain the Queries & use the output of Initial queries in the later ones. I cannot break the queries into smaller Dataframes as they are complex.

How to go ahead with such scenario. Also let me know what is the Best Practice to achieve this ?

答:
Why don't you do</p>

```<code>query_1.registerTempTable("output_table_1")
</code>```

Body:
We have 3 queries which are currently running on HIVE.

Using Spark 2.1.0

We are trying to Run that using Spark SQL but by using the SparkSession(like wrapping with Scala code making a Jar & then Submit using Spark-Submit)

Now for Example lets say :
Query-1 uses 3 tables (Table - a, b & c) and Insert into table --> Output_Table_1

Query-2 uses few other tables(performing Joins) and output_table_1 which is populated from the output of Query-1. This gives output_table_2

Similarly Query-3 uses few tables & may or may not use output_table_1 and/or output_table_2(we are not sure on this as still designing)

Currently the way i am doing this is writing all the queries in a property file and reading it in def main using Typesafe.ConfigFactory (Please suggest if there is any better way)

In the def main(){} what i am doing is :

val query_1 = spark.sql('query1')
query_1.write.mode("overwrite").insertInto("output_table_1")

Now when i am doing the Below step It throws an Error - output_table_1 not found

val query_2 = spark.sql('query2')
query_2.write.mode("overwrite").insertInto("output_table_2")

Similarly for the 3rd Query and table i am getting Same error. So basically i am trying to Chain the Queries & use the output of Initial queries in the later ones. I cannot break the queries into smaller Dataframes as they are complex.

How to go ahead with such scenario. Also let me know what is the Best Practice to achieve this ?

Body:
Why don't you do

query_1.registerTempTable("output_table_1")


问:
Finding Most Frequent Element(s) In A File Of Integers
I am working on a program to find the most frequent element(s) in a text file. Thus far I have made the file read into a List then iterate through the list to find the occurrences of every value and map them in a SortedMap.

The issue is occurring with files where every digit occurs equally. My Map is not filling with all the data and will only contain one of the digits at the end.

Here is my code:

```<code>public class FileAnalyzer {
public static void main(String[] args) throws IOException, FileNotFoundException {

    System.out.print("Please Enter A File Name: ");
    String file = new Scanner(System.in).nextLine();

    final long startTime = System.currentTimeMillis();

    BufferedReader reader = new BufferedReader(new FileReader(file));
    List<Integer> numbers = new ArrayList<>();
    SortedMap<Integer, Integer> sortedMap = new TreeMap<>();
    String line;

    while ((line = reader.readLine()) != null) {
        numbers.add(Integer.parseInt(line));
    }

    Collections.sort(numbers);

    int frequency = 0;
    int tempNum = 0;

    for (int i = 0; i < numbers.size(); i++) {
        if (tempNum == numbers.get(i)) {
            frequency++;
        } else {
            if (frequency != 0) {
                sortedMap.put((frequency+1), tempNum);
            }
            frequency = 0;
            tempNum = numbers.get(i);
        }
    }
     if (frequency !=0) {
        sortedMap.put((frequency+1), tempNum);
    }

    final long duration = System.currentTimeMillis() - startTime;

        System.out.println(sortedMap);
        System.out.println("Runtime: " + duration + " ms\n");
        System.out.println("Least Frequent Digit(s): " + sortedMap.get(sortedMap.firstKey()) + "\nOccurences: " + sortedMap.firstKey());
    }
}
</code>```

Also this is the text file I am running into issues when reading from:

```<code>1
2
1
1
2
1
1
2
1
2
2
2
</code>```

Thanks in advance!

答: You should look up the Java Documentation for TreeMap. It is designed to not store duplicate keys, so since you are sorting on frequency as a key, values with the same frequency will be overwritten in your map!</p>

Body:
I am working on a program to find the most frequent element(s) in a text file. Thus far I have made the file read into a List then iterate through the list to find the occurrences of every value and map them in a SortedMap.

The issue is occurring with files where every digit occurs equally. My Map is not filling with all the data and will only contain one of the digits at the end.

Here is my code:

public class FileAnalyzer {
public static void main(String[] args) throws IOException, FileNotFoundException {

    System.out.print("Please Enter A File Name: ");
    String file = new Scanner(System.in).nextLine();

    final long startTime = System.currentTimeMillis();

    BufferedReader reader = new BufferedReader(new FileReader(file));
    List<Integer> numbers = new ArrayList<>();
    SortedMap<Integer, Integer> sortedMap = new TreeMap<>();
    String line;

    while ((line = reader.readLine()) != null) {
        numbers.add(Integer.parseInt(line));
    }

    Collections.sort(numbers);

    int frequency = 0;
    int tempNum = 0;

    for (int i = 0; i < numbers.size(); i++) {
        if (tempNum == numbers.get(i)) {
            frequency++;
        } else {
            if (frequency != 0) {
                sortedMap.put((frequency+1), tempNum);
            }
            frequency = 0;
            tempNum = numbers.get(i);
        }
    }
     if (frequency !=0) {
        sortedMap.put((frequency+1), tempNum);
    }

    final long duration = System.currentTimeMillis() - startTime;

        System.out.println(sortedMap);
        System.out.println("Runtime: " + duration + " ms\n");
        System.out.println("Least Frequent Digit(s): " + sortedMap.get(sortedMap.firstKey()) + "\nOccurences: " + sortedMap.firstKey());
    }
}

Also this is the text file I am running into issues when reading from:

1
2
1
1
2
1
1
2
1
2
2
2

Thanks in advance!


问:
How do I remove the objects I want from an array and add them to another array using .forEach?
This is a coding challenge I'm working on and can't seem to grasp what I need to do. Not sure if I am even going in the right direction.

Here is the instructions: Here we have an array called people. Some of them are our friends and some are not.
1. Create an empty array called friends.
2. Using .forEach, loop over people and add those that are our friend to the empty friends array.

Here is the provided code:

```<code>var people = [
  {name: "Landy",friend: true},
  {name: "Corey",friend: true},
  {name: "Ted",friend: false},
  {name: "Sperry",friend: true},
  {name: "Bill",friend: false}
];
</code>```

My code so far:

```<code>var friends = [];
people.forEach(function(people){
  if (people === true) {
    return name;
  } else {
    //
  }
});
</code>```

答:
```<code>var friends = [];
people.forEach(function(person){
  if (person.friend) friends.push(person)
});
</code>```

Body:
This is a coding challenge I'm working on and can't seem to grasp what I need to do. Not sure if I am even going in the right direction.

Here is the instructions: Here we have an array called people. Some of them are our friends and some are not.
1. Create an empty array called friends.
2. Using .forEach, loop over people and add those that are our friend to the empty friends array.

Here is the provided code:

var people = [
  {name: "Landy",friend: true},
  {name: "Corey",friend: true},
  {name: "Ted",friend: false},
  {name: "Sperry",friend: true},
  {name: "Bill",friend: false}
];

My code so far:

var friends = [];
people.forEach(function(people){
  if (people === true) {
    return name;
  } else {
    //
  }
});


问:
How should I do lowering the minimum SDK version?
I'm working on an Anrdoid app. It's almost finished. I've just noticed that the minSdkVersion is set to 21. Maybe I forgot it when I created the project. I'd like to lower it, because the app's users will likely to have older devices.

I don't think it's good idea to change the minSdkVersion to ~10, sit back, and hope it will compile and run fine in the future.

My idea was that I could check all the methods used in the project, their minimum API level, so I could know what I have to replace with alternatives. However, the project is a bit large. Searching for all methods' documentation one by one would take a lot of time.

Is it possible to automatically list the Android API specific methods used in my project, and their API level? Or somehow detect the highest API level that is required by an used method? Android Studio knows these numbers, it can fetch the documentation too. Or, is it safe to change the minSdkVersion and targetSdkVersion to a lower API level to know which methods aren't supported in an older device, and after I fix all errors/warnings the IDE will show me, will my app run fine?

答:
Android Studio will give you warnings when you use methods that require a higher sdk version than your specified minSdkVersion. You can access the whole list of these warnings for the complete project by leveraging the Analyze -> Code Cleanup functionality. So what you can do:

Lower the minSdkVersion.

Click Analyze -> Code Cleanup in Android Studio. Select "Whole Project"

The relevant errors are part of these sections:

Android Lint: Correctness -> Attribute unused on older versions

Android Lint: Correctness -> Calling new methods on older versions

Android Lint: Correctness -> using inlined constants on older versions

Android Lint: Internationalization -> Right-to-left text compatibility issues

By trying different version numbers you can see how many changes are necessary. To decide for the correct minSdkVersion, you might want to consider the Android API level device stats.

So a strategy for deciding for a targetSdkVersion or minSdkVersion typically looks like this: You set the targetSdkVersion to the highest version number that you have tested your app with. The minSdkVersion should be set to a lower value - low enough so enough devices are supported, but high enough so there are not to many version specific workarounds necessary. Find details about these two values in the Android documentation.


答:
One possible solution would be

```<code>var friends = [];
people.forEach(p => {
    if(p.friend)            // if person is a friend
        friends.push(p);    // push it to our friends array
});

// or

people.forEach(p => p.friend && friends.push(p));  // short-circuiting
</code>```

We can also do this if we don't have to use .forEach

```<code>// use the key ".friend" as the condition
var friends = people.filter(p => p.friend);
</code>```

Traditional way of doing it

```<code>var friends = [];
for(var i = 0; i < people.length; i++){
    p = people[i];          // get i-th people
    if(p.friend)            // if person is a friend
        friends.push(p);    // push it to our friends array
});
</code>```

Example:

var people = [
  {name: "Landy",friend: true},
  {name: "Corey",friend: true},
  {name: "Ted", friend: false},
  {name: "Sperry", friend: true},
  {name: "Bill",friend: false}
 ];

var friends = [];
people.forEach(p => {
  if(p.friend)
    friends.push(p);
});

console.log(friends);```

Title: How do I remove the objects I want from an array and add them to another array using .forEach?

Body:
One possible solution would be

var friends = [];
people.forEach(p => {
    if(p.friend)            // if person is a friend
        friends.push(p);    // push it to our friends array
});

// or

people.forEach(p => p.friend && friends.push(p));  // short-circuiting

We can also do this if we don't have to use .forEach

// use the key ".friend" as the condition
var friends = people.filter(p => p.friend);

Traditional way of doing it

var friends = [];
for(var i = 0; i < people.length; i++){
    p = people[i];          // get i-th people
    if(p.friend)            // if person is a friend
        friends.push(p);    // push it to our friends array
});

Example:

var people = [
  {name: "Landy",friend: true},
  {name: "Corey",friend: true},
  {name: "Ted", friend: false},
  {name: "Sperry", friend: true},
  {name: "Bill",friend: false}
 ];

var friends = [];
people.forEach(p => {
  if(p.friend)
    friends.push(p);
});

console.log(friends);


答:
findHorseFeed() returns a double, on which you cannot call the horseFeed() method (it returns a double, not a horse object)

First you need to write (and subsequently call) another method to return a horse object that you can then call horseFeed() on.

In class horseStable you'll want a method like

```<code>public horse findtHorse(int i) {
    horse myhorse = horseList.get(i);
    return myhorse
}
</code>```

You can probably also refactor findHorseFeed to just .getWeight() on getHorse():

```<code>public double findHorseFeed(horse myhorse) {
    double weight = myhorse.getWeight();
    return weight
}
</code>```

then you can call:

```<code>horse myHorse = stable1.findHorse(1);
String range = myHorse.horseFeed(stable1.findHorseFeed(myHorse));
</code>```

Title: What does the error "double cannot be dereferenced" mean?

Body:
I understand that the ArrayList can't hold any primitive data
but how can i call my method horseFeed() into the driver alongside my Arraylist constructor so that i don't get a double dereferenced error

Also can someone explain to me what a double dereferenced error is and why I'm getting it, please help

The method is in my class

public class horse
{
  .
  .
  .

  //took out a lot of code as it was not important to the problem

  public String horseFeed(double w)
  {
    double sFeed= w*.015;
    double eFeed= w*.013;
    String range = sFeed + " < " + eFeed;
    return range;
  }
}

This is the ArrayList class

import java.util.*;
public class horseStable
{
 .
 .
 .
 public double findHorseFeed(int i)
 {
   double weight = horseList.get(i).getWeight();
   return weight;

  }
}

This is the Driver

public class Main
{
  public static void main(String args[])
  {
  //returns the weight of the horse works fine
  System.out.println(stable1.findHorseFeed(1));
  // This is supposed to use the horseFeed method in the class by using the horse's weight. Where can i place the horseFeed method without getting an error?
  System.out.println(stable1.findHorseFeed(1).horseFeed());
  }
 }

Body:
findHorseFeed() returns a double, on which you cannot call the horseFeed() method (it returns a double, not a horse object)

First you need to write (and subsequently call) another method to return a horse object that you can then call horseFeed() on.

In class horseStable you'll want a method like

public horse findtHorse(int i) {
    horse myhorse = horseList.get(i);
    return myhorse
}

You can probably also refactor findHorseFeed to just .getWeight() on getHorse():

public double findHorseFeed(horse myhorse) {
    double weight = myhorse.getWeight();
    return weight
}

then you can call:

horse myHorse = stable1.findHorse(1);
String range = myHorse.horseFeed(stable1.findHorseFeed(myHorse));


问:
chef kitchen not working from Windows 10 integrated bash
I am receiving the following error when trying to run any command in 'kitchen':

```<code>bash: /mnt/c/opscode/chefdk/bin/kitchen: C:/opscode/chefdk/embedded/bin/ruby.exe: bad interpreter: No such file or directory
</code>```

It works from outside integrated bash when using the chefdk client, however I am trying to get this working from integrated bash.

Chef utility commands such as 'chef-client' and 'knife' seem to be working  so far.

答: We haven't set things up to work with WSL as the Windows ChefDK installers are native Windows-y builds of everything. I recommend using the bash from MSYS2 if you want that as a shell.</p>

Body:
I am receiving the following error when trying to run any command in 'kitchen':

bash: /mnt/c/opscode/chefdk/bin/kitchen: C:/opscode/chefdk/embedded/bin/ruby.exe: bad interpreter: No such file or directory

It works from outside integrated bash when using the chefdk client, however I am trying to get this working from integrated bash.

Chef utility commands such as 'chef-client' and 'knife' seem to be working  so far.


问:
get filenames in a directory without extension - Python
I am trying to get the filenames in a directory without getting the extension. With my current code -

```<code>import os

path = '/Users/vivek/Desktop/buffer/xmlTest/'
files = os.listdir(path)
print (files)
</code>```

I end up with an output like so:

```<code>['img_8111.jpg', 'img_8120.jpg', 'img_8127.jpg', 'img_8128.jpg', 'img_8129.jpg', 'img_8130.jpg']
</code>```

However I want the output to look more like so:

```<code>['img_8111', 'img_8120', 'img_8127', 'img_8128', 'img_8129', 'img_8130']
</code>```

How can I make this happen?

答:
You can use os's splitext.

```<code>import os

path = '/Users/vivek/Desktop/buffer/xmlTest/'
files = [os.path.splitext(filename)[0] for filename in os.listdir(path)]
print (files)
</code>```

Just a heads up: basename won't work for this.  basename doesn't remove the extension.

Body:
I am trying to get the filenames in a directory without getting the extension. With my current code -

import os

path = '/Users/vivek/Desktop/buffer/xmlTest/'
files = os.listdir(path)
print (files)

I end up with an output like so:

['img_8111.jpg', 'img_8120.jpg', 'img_8127.jpg', 'img_8128.jpg', 'img_8129.jpg', 'img_8130.jpg']

However I want the output to look more like so:

['img_8111', 'img_8120', 'img_8127', 'img_8128', 'img_8129', 'img_8130']

How can I make this happen?

Body:
You can use os's splitext.

import os

path = '/Users/vivek/Desktop/buffer/xmlTest/'
files = [os.path.splitext(filename)[0] for filename in os.listdir(path)]
print (files)

Just a heads up: basename won't work for this.  basename doesn't remove the extension.


问:
In what scenarios can the blockchain size decrease for bitcoin?
I am running a private bitcoin network for which I changed the target time between two blocks to 12 seconds and the difficulty adjustment to 25 blocks interval. I ran the network for about 4 hours with 50 nodes. In one of the node's logs I observed that the blockchain height increased up to a maximum of 181 and then started decreasing, all the way to 38. what could be an explanation for such a strange behaviour.

Please refer to the log below:

```<code>2015-11-04 01:58:47 receive version message: /Satoshi:0.11.99/: version 70011, blocks=181, us=0.0.0.0:0, peer=2, peeraddr=127.0.0.1:44117
2015-11-04 01:58:47 UpdateTip: new best=0000005265ca4ce01ad0d06f45cf475bf303de3d64e942c5cf1177e00f346c78  height=180  log2_work=37.083283  tx=30941  date=2015-11-04 01:53:17 progress=1.000000  cache=0.0MiB(1tx)
2015-11-04 01:58:47 UpdateTip: new best=00000052a34cedf3c5ddbeb46d36644654523db855c4cce984d2623e840dd219  height=179  log2_work=37.082953  tx=30940  date=2015-11-04 01:53:10 progress=1.000000  cache=0.0MiB(2tx)
2015-11-04 01:58:47 UpdateTip: new best=00000030fd7652affb883f05fe0c98e7fe3fbc3cfd74808e061ed05ec61c22e6  height=178  log2_work=37.082623  tx=30939  date=2015-11-04 01:52:55 progress=1.000000  cache=0.0MiB(3tx)
2015-11-04 01:58:47 AddToWallet c32bcbd8102c602a5e71ee717232e204435f331dce6fbfb9eb5d552698faa95b
2015-11-04 01:58:47 AddToWallet 1c91517aeadd12bcbcfdf4a1423b671d405543ae9abfbd87078969ce1971663f
2015-11-04 01:58:47 AddToWallet b11f9c2e3b1ab3d3983da63783bb95903d89405243d0716ea88272a9261b7a33
</code>```

答:
The log you provided shows you have two peers.
If that's the only nodes(2+1) in the network then your chain is not gonna be stable without more fine tuning on the variables.
My guess is that you changed some rules and a chain split&reorganization(soft fork) happened, the extra blocks become orphans after the reorganization.</p>

Body:
I am running a private bitcoin network for which I changed the target time between two blocks to 12 seconds and the difficulty adjustment to 25 blocks interval. I ran the network for about 4 hours with 50 nodes. In one of the node's logs I observed that the blockchain height increased up to a maximum of 181 and then started decreasing, all the way to 38. what could be an explanation for such a strange behaviour.

Please refer to the log below:

2015-11-04 01:58:47 receive version message: /Satoshi:0.11.99/: version 70011, blocks=181, us=0.0.0.0:0, peer=2, peeraddr=127.0.0.1:44117
2015-11-04 01:58:47 UpdateTip: new best=0000005265ca4ce01ad0d06f45cf475bf303de3d64e942c5cf1177e00f346c78  height=180  log2_work=37.083283  tx=30941  date=2015-11-04 01:53:17 progress=1.000000  cache=0.0MiB(1tx)
2015-11-04 01:58:47 UpdateTip: new best=00000052a34cedf3c5ddbeb46d36644654523db855c4cce984d2623e840dd219  height=179  log2_work=37.082953  tx=30940  date=2015-11-04 01:53:10 progress=1.000000  cache=0.0MiB(2tx)
2015-11-04 01:58:47 UpdateTip: new best=00000030fd7652affb883f05fe0c98e7fe3fbc3cfd74808e061ed05ec61c22e6  height=178  log2_work=37.082623  tx=30939  date=2015-11-04 01:52:55 progress=1.000000  cache=0.0MiB(3tx)
2015-11-04 01:58:47 AddToWallet c32bcbd8102c602a5e71ee717232e204435f331dce6fbfb9eb5d552698faa95b
2015-11-04 01:58:47 AddToWallet 1c91517aeadd12bcbcfdf4a1423b671d405543ae9abfbd87078969ce1971663f
2015-11-04 01:58:47 AddToWallet b11f9c2e3b1ab3d3983da63783bb95903d89405243d0716ea88272a9261b7a33


答:
Here are two options

```<code>import os
print(os.path.splitext("path_to_file")[0])
</code>```

Or

```<code>from os.path import basename
print(basename("/a/b/c.txt"))
</code>```

Title: get filenames in a directory without extension - Python

Body:
Here are two options

import os
print(os.path.splitext("path_to_file")[0])

Or

from os.path import basename
print(basename("/a/b/c.txt"))


问:
Capturing and reacting to custom windows events in wxPython
I'm in the process of writing an app to interface with a service running on another machine. When I ask this service for some information, this service adds the requested information to a separate queue, and sends a windows message to the calling application (my application) indicating there is a message waiting in this separate queue which needs to be decoded.

The windows message this service sends is a custom message, defined in the service code as having some constant int value. I've found examples of creating custom events in wxpython, and using TryBefore() and TryAfter() to react to these events in specific ways, but I haven't found any way to associate this NewEvent() with an int value so I can identify it when it comes in, much less any way to determine what an int value of an incoming event is.

Has anyone done this before or know of any functions I'm not aware of? I'm using python 3.6 and wxpython 4.0.

Thanks for your help, everyone.

答:
I think this is what you are looking for: https://wiki.wxpython.org/HookingTheWndProc

When you get the custom message from the hooked WndProc you can either react to it there, or you can turn it into a wx event and send it so it can be caught by binding an event handler like normal.  The wx.lib.newevent module has some helpers for creating a custom event class and an event binder. Its use is demonstrated in some of the demo samples and library modules.


问:
Does spark zipWithIndex keeps the order of lines when reading multiple files from s3
I'm loading multiple files from s3, for example

```<code>s3://bucket1/111
s3://bucket2/222
...
</code>```

Assume file 111 has lines

```<code>line0
line1
</code>```

and file 222 has lines

```<code>line2
line3
</code>```

I'm planning to use

```<code>sc.textFile("s3://bucket1/111,s3://bucket2/222...").zipWithIndex()
</code>```

to load all these files and add index to each of the lines.

My questions is whether the index will be based on the order of files as well as the order in the same file for the lines in the same file.

I would like the orders to be like

```<code>(line0, 0)
(line1, 1)
(line2, 2)
(line3, 3)
...
</code>```

答:
Yes it does. When in doubt check debug string:

```<code>scala> sc.textFile("README.md").zipWithIndex.toDebugString
res0: String =
(2) ZippedWithIndexRDD[2] at zipWithIndex at <console>:25 []
 |  README.md MapPartitionsRDD[1] at textFile at <console>:25 []
 |  README.md HadoopRDD[0] at textFile at <console>:25 []
</code>```

No shuffle (single stage) means order is preserved. Storage implementation doesn't matter.

Body:
I'm loading multiple files from s3, for example

s3://bucket1/111
s3://bucket2/222
...

Assume file 111 has lines

line0
line1

and file 222 has lines

line2
line3

I'm planning to use

sc.textFile("s3://bucket1/111,s3://bucket2/222...").zipWithIndex()

to load all these files and add index to each of the lines.

My questions is whether the index will be based on the order of files as well as the order in the same file for the lines in the same file.

I would like the orders to be like

(line0, 0)
(line1, 1)
(line2, 2)
(line3, 3)
...

Body:
Yes it does. When in doubt check debug string:

scala> sc.textFile("README.md").zipWithIndex.toDebugString
res0: String =
(2) ZippedWithIndexRDD[2] at zipWithIndex at <console>:25 []
 |  README.md MapPartitionsRDD[1] at textFile at <console>:25 []
 |  README.md HadoopRDD[0] at textFile at <console>:25 []

No shuffle (single stage) means order is preserved. Storage implementation doesn't matter.


问:
Set mySQL MAX value to java variable
Hey guys I'm trying to get the value from mySQL MAX function (trying to get highest customer ID)  and store it in a variable in my java code. Can't seem to get the thing to work.</p>

```<code>public static int findMaxID() {
    int maxID = 0;
    String updateStmt =
            "SELECT @maxID := MAX(idCustomer)\n" +
                    "FROM customers\n";
    try {
        DBUtil.dbExecuteQuery(updateStmt);
        System.out.println(maxID);
    } catch (SQLException e) {
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }
    return maxID;
}
</code>```

答:
Use a statement, ideally a prepared statement:

```<code>int maxID = 0;
String sql = "SELECT MAX(idCustomer) AS max_id FROM customers";
PreparedStatement ps = conn.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
if (rs.next()) {
    int maxID = rs.getInt("max_id");  // access the max value via its alias
}
</code>```

While your current query might be valid MySQL, the session variable @maxID is only available on MySQL and not in your Java code.  To access it you would need to yet again write another query.

Title: Set mySQL MAX value to java variable

Body:
Hey guys I'm trying to get the value from mySQL MAX function (trying to get highest customer ID)  and store it in a variable in my java code. Can't seem to get the thing to work.

public static int findMaxID() {
    int maxID = 0;
    String updateStmt =
            "SELECT @maxID := MAX(idCustomer)\n" +
                    "FROM customers\n";
    try {
        DBUtil.dbExecuteQuery(updateStmt);
        System.out.println(maxID);
    } catch (SQLException e) {
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }
    return maxID;
}

Body:
Use a statement, ideally a prepared statement:

int maxID = 0;
String sql = "SELECT MAX(idCustomer) AS max_id FROM customers";
PreparedStatement ps = conn.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
if (rs.next()) {
    int maxID = rs.getInt("max_id");  // access the max value via its alias
}

While your current query might be valid MySQL, the session variable @maxID is only available on MySQL and not in your Java code.  To access it you would need to yet again write another query.


问:
How to have checkbox items create a list
I am new to PHP and the project I am working on is a codeigniter php form writing back to a FileMaker database.

The checkboxes should be populating as a list field.

Here is my form

```<code><input name="fieldname[]" value="value1"<?php echo (set_checkbox('fieldname', $join->fieldname))?> type="checkbox" class="form-check-input"> value1
<input name="fieldname[]" value="value2"<?php echo (set_checkbox('fieldname', $join->fieldname))?> type="checkbox" class="form-check-input"> value2
</code>```

There are about 7 checkboxes.

I assume that I have to setup a foreach loop to get it to go thought to FileMaker's field, but unsure how to do that.

If I take away the array, the last one selected goes through to the layout.

Any help would be great.

答:
Presumably, these values mirror a valueList back in FileMaker. If so, it's best to assign the valueList to a variable:

```<code>$values = $layout->getValueList('pizzaToppings');
</code>```

And use that in your for loop:

```<code>foreach($values as $value)...
</code>```

In your if(isset()) block, post a return-delimited array to FileMaker:

```<code>// value(s)!
if ($_POST['fieldname']) {
    $valueArray = implode("\r", $_POST['fieldname']);
}

// pass the array to setField()
$record->setField('filemakerField', $valueArray);
</code>```

Body:
I am new to PHP and the project I am working on is a codeigniter php form writing back to a FileMaker database.

The checkboxes should be populating as a list field.

Here is my form

<input name="fieldname[]" value="value1"<?php echo (set_checkbox('fieldname', $join->fieldname))?> type="checkbox" class="form-check-input"> value1
<input name="fieldname[]" value="value2"<?php echo (set_checkbox('fieldname', $join->fieldname))?> type="checkbox" class="form-check-input"> value2

There are about 7 checkboxes.

I assume that I have to setup a foreach loop to get it to go thought to FileMaker's field, but unsure how to do that.

If I take away the array, the last one selected goes through to the layout.

Any help would be great.

Body:
Presumably, these values mirror a valueList back in FileMaker. If so, it's best to assign the valueList to a variable:

$values = $layout->getValueList('pizzaToppings');

And use that in your for loop:

foreach($values as $value)...

In your if(isset()) block, post a return-delimited array to FileMaker:

// value(s)!
if ($_POST['fieldname']) {
    $valueArray = implode("\r", $_POST['fieldname']);
}

// pass the array to setField()
$record->setField('filemakerField', $valueArray);


问:
c++ multithread optimization
in my code I have 2/4 threads performing montecarlo simulations. Each of them runs a number of experiments and they all collect the results into a stl vector.
My question is this: suppose each thread runs 1000 experiments sequentially. Is is better to store the result into the shared vector one at the time, or every once in a while? If they wait until they have some consistent amount of data, writing into the vector will take longer, so I'm not sure whether the second solution is necessarily better than the first one.

PS each experiment is numerical computation, so no IO operations.

Thanks

答:
If you're only putting 2000 to 4000 elements in the vector I doubt it would make much of a difference either way.

Do whatever is most natural for the algorithm.  If that doesn't work well enough look into doing it the other way.

After thinking about it for a bit, it might serve both purposes (simplicity and speed) to have each thread store results to a local vector then copy the contents of the local vector to the 'global' vector (protected by a lock) when the thread is done.  Of course, that's as long as whatever's waiting for the results can wait until a thread is fully finished before getting an update.

Title: c++ multithread optimization


问:
Passport local strategy not being called
Update: I have downloaded express-4.x-local-example and can't seem to get it working either. Is there something that I'm missing?

I'm trying to set a local strategy for passport but it's not being fired. After entering the credentials, the page redirects to failureRedirect.

app.js

```<code>const express = require('express')
    , app = express()
    , mainRouter = require('./controllers/mainRouter');

mainRouter(app);
</code>```

mainRouter.js

```<code>const bodyParser = require('body-parser')
    , passport = require('passport')
    , passportConfig = require('../config/passport');

passportConfig(passport);

module.exports = (app) => {
    app.use(bodyParser.json());
    app.use(bodyParser.urlencoded({ extended: true }));
    app.use(passport.initialize());
    app.use(passport.session());

    app.post('/login', passport.authenticate(('local'), {
        successRedirect: '/',
        failureRedirect: 'login/',
        })
    );
}
</code>```

passport.js

```<code>const LocalStrategy = require('passport-local').Strategy;

module.exports = (passport) => {
    passport.use(new LocalStrategy({usernameField: 'email'},
        (email, password, done) => {
            console.log('This message is not being logged.');
        })
    );
}
</code>```

答:
Your not actually calling the strategy in your mainRouter.js file.

Before the app.post, add passport.use(passportConfig);

Body:
Update: I have downloaded express-4.x-local-example and can't seem to get it working either. Is there something that I'm missing?

I'm trying to set a local strategy for passport but it's not being fired. After entering the credentials, the page redirects to failureRedirect.

app.js

const express = require('express')
    , app = express()
    , mainRouter = require('./controllers/mainRouter');

mainRouter(app);

mainRouter.js

const bodyParser = require('body-parser')
    , passport = require('passport')
    , passportConfig = require('../config/passport');

passportConfig(passport);

module.exports = (app) => {
    app.use(bodyParser.json());
    app.use(bodyParser.urlencoded({ extended: true }));
    app.use(passport.initialize());
    app.use(passport.session());

    app.post('/login', passport.authenticate(('local'), {
        successRedirect: '/',
        failureRedirect: 'login/',
        })
    );
}

passport.js

const LocalStrategy = require('passport-local').Strategy;

module.exports = (passport) => {
    passport.use(new LocalStrategy({usernameField: 'email'},
        (email, password, done) => {
            console.log('This message is not being logged.');
        })
    );
}


问:
Constants in Kotlin -- what's a recommended way to create them?
How is it recommended to create constants in Kotlin? And what's the naming convention? I've not found that in the documentation.

```<code>companion object {
    //1
    val MY_CONST = "something"

    //2
    const val MY_CONST = "something"

    //3
    val myConst = "something"
}
</code>```

Or ...?

答:
local constants:

```<code>const val NAME = "name"
</code>```

Global constants:

```<code>object MyConstants{
    val NAME = "name"
    val ID = "_id"
    var EMAIL = "email"
}
</code>```

access MyConstants.NAME

Body:
How is it recommended to create constants in Kotlin? And what's the naming convention? I've not found that in the documentation.

companion object {
    //1
    val MY_CONST = "something"

    //2
    const val MY_CONST = "something"

    //3
    val myConst = "something"
}

Or ...?

Body:
local constants:

const val NAME = "name"

Global constants:

object MyConstants{
    val NAME = "name"
    val ID = "_id"
    var EMAIL = "email"
}

access MyConstants.NAME