问:
pip install returning invalid syntax
I've just installed python 3.6 which comes with pip

However, in Windows command prompt, when I do: 'pip install bs4' it returns 'SyntaxError: invalid syntax' under the install word.

Typing 'python' returns the version, which means it is installed correctly. What could be the problem?

答:
try this.

```<code>python -m  pip ...
</code>```

-m module-name Searches sys.path for the named module and runs the corresponding .py file as a script.

Sometimes the OS can't find pip so python or py -m may solve the problem because it is python itself searching for pip.

Title: pip install returning invalid syntax

Body:
try this.

python -m  pip ...

-m module-name Searches sys.path for the named module and runs the corresponding .py file as a script.

Sometimes the OS can't find pip so python or py -m may solve the problem because it is python itself searching for pip.


来源: stackexchange

问:
How do I convert an array of Strings to an Array of Int in Kotlin
I am looking to convert an List<String> to an List<Int> in Kotlin.

```<code>val stringArray = "1 2 3 4 5 6".split(" ")
val intArray = MutableList<Int>(0, {0})
for (item in stringArray) {
    intArray.add(item.toInt())
}
</code>```

The above will do it, but it feels as if there is a better way of doing this (possible with lambdas and streams?).

答:
If your input really has delimiters, you can split as already suggested. Afterwards map is what you need. This will do the trick:

```<code>val numbers = "1 2 3 4 5 6"
val result = numbers.split(" ").map(String::toInt)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am looking to convert an List<String> to an List<Int> in Kotlin.

val stringArray = "1 2 3 4 5 6".split(" ")
val intArray = MutableList<Int>(0, {0})
for (item in stringArray) {
    intArray.add(item.toInt())
}

The above will do it, but it feels as if there is a better way of doing this (possible with lambdas and streams?).

Body:
If your input really has delimiters, you can split as already suggested. Afterwards map is what you need. This will do the trick:

val numbers = "1 2 3 4 5 6"
val result = numbers.split(" ").map(String::toInt)


问:
How to create actors transparently across an Akka cluster
I have an actor system shown in the following graph.

Master
|
|--Monitor
|
|--Supervisor
      |
      |--Device #1
      |--Device #2
      |-- ...
      |--Device #N
```

<p>The Master actor starts the Monitor actor and the Supervisor actor.</p>

<p>The Monitor actor fires a message telling itself to check the device inventory every 30 seconds. For each device that exists in the inventory, it sends a message to the Supervisor actor to register the device.</p>

<p>The Supervisor actor starts the device actor when it receives the message from the Monitor actor to register the device.</p>

<p>The code is available here on github.</p>

<p>Everything works pretty well in a single JVM instance, but when it comes to cluster mode, I start to be confused.</p>

<p>As I expected, with the following configuration, the previous actor tree should run transparently in the cluster machines. All the actors should be created across the cluster, and I should not care on which machine the actors are created.</p>

<p>On instance #1:</p>

<pre class="lang-html prettyprint-override"><code>akka {
  actor {
    provider = "cluster"
  }
  remote {
    log-remote-lifecycle-events = off
    netty.tcp {
      hostname = "127.0.0.1"
      port = 2551
    }
  }

  cluster {
    seed-nodes = [
      "akka.tcp://example@127.0.0.1:2551",
    ]
  }
}
</code>```

On instance #2:

akka {
  actor {
    provider = "cluster"
  }
  remote {
    log-remote-lifecycle-events = off
    netty.tcp {
      hostname = "127.0.0.1"
      port = 2552
    }
  }

  cluster {
    seed-nodes = [
      "akka.tcp://example@127.0.0.1:2551",
    ]
  }
}
```

<p>What I expected:</p>

<pre class="lang-html prettyprint-override"><code>Master (On node 1)
|
|--Monitor (On node 2)
|
|--Supervisor (On node 2)
      |
      |--Device #1 (On node 1)
      |--Device #2 (On node 1)
      |-- ...
      |--Device #N (On node 2)
</code>```

But, it ends up running two identical actor trees in the cluster: each node runs one actor tree separately as the following graph shows:

Node 1             |   Node2
                   |
Master             |   Master
|                  |   |
|--Monitor         |   |--Monitor
|                  |   |
|--Supervisor      |   |--Supervisor
    |              |       |
    |--Device #1   |       |--Device #1
    |--Device #2   |       |--Device #2
    |-- ...        |       |-- ...
    |--Device #N   |       |--Device #N
```

I also tried to run the Master actor as a singleton actor in the cluster, but it ends up running a single actor tree on the very node on which the Master is started.

So, my question is, how could I create an actor across the cluster by calling context.actorOf(DeviceActor.props(deviceId)), without carefully designing the actor tree with cluster singleton and cluster sharding?

答:
What you describe is the exact definition of Akka cluster sharding.

Cluster sharding is useful when you need to distribute actors across several nodes in the cluster and want to be able to interact with them using their logical identifier, but without having to care about their physical location in the cluster, which might also change over time.

It's pretty simple to set it up, especially if you already have a cluster. Monitor would be a Cluster Singleton so that there's only one alive on the cluster, and each Device would be an entity identified by the device ID.

Body:
I have an actor system shown in the following graph.

Master
|
|--Monitor
|
|--Supervisor
      |
      |--Device #1
      |--Device #2
      |-- ...
      |--Device #N

The Master actor starts the Monitor actor and the Supervisor actor.

The Monitor actor fires a message telling itself to check the device inventory every 30 seconds. For each device that exists in the inventory, it sends a message to the Supervisor actor to register the device.

The Supervisor actor starts the device actor when it receives the message from the Monitor actor to register the device.

The code is available here on github.

Everything works pretty well in a single JVM instance, but when it comes to cluster mode, I start to be confused.

As I expected, with the following configuration, the previous actor tree should run transparently in the cluster machines. All the actors should be created across the cluster, and I should not care on which machine the actors are created.

On instance #1:

akka {
  actor {
    provider = "cluster"
  }
  remote {
    log-remote-lifecycle-events = off
    netty.tcp {
      hostname = "127.0.0.1"
      port = 2551
    }
  }

  cluster {
    seed-nodes = [
      "akka.tcp://example@127.0.0.1:2551",
    ]
  }
}

On instance #2:

akka {
  actor {
    provider = "cluster"
  }
  remote {
    log-remote-lifecycle-events = off
    netty.tcp {
      hostname = "127.0.0.1"
      port = 2552
    }
  }

  cluster {
    seed-nodes = [
      "akka.tcp://example@127.0.0.1:2551",
    ]
  }
}

What I expected:

Master (On node 1)
|
|--Monitor (On node 2)
|
|--Supervisor (On node 2)
      |
      |--Device #1 (On node 1)
      |--Device #2 (On node 1)
      |-- ...
      |--Device #N (On node 2)

But, it ends up running two identical actor trees in the cluster: each node runs one actor tree separately as the following graph shows:

Node 1             |   Node2
                   |
Master             |   Master
|                  |   |
|--Monitor         |   |--Monitor
|                  |   |
|--Supervisor      |   |--Supervisor
    |              |       |
    |--Device #1   |       |--Device #1
    |--Device #2   |       |--Device #2
    |-- ...        |       |-- ...
    |--Device #N   |       |--Device #N

I also tried to run the Master actor as a singleton actor in the cluster, but it ends up running a single actor tree on the very node on which the Master is started.

So, my question is, how could I create an actor across the cluster by calling context.actorOf(DeviceActor.props(deviceId)), without carefully designing the actor tree with cluster singleton and cluster sharding?


问:
How to computed and add a new column in SQL
I have two tables

[Table_1] - Amount of money in a specific currency.

```<code>Currency  | Amount
USD       |  243
USD       |  212
USD       |  432
EUR       |  578
EUR       |  112
EUR       |  578
GBP       |  965
GBP       |  309
</code>```

And [Table_2] - Exchange rate EUR and GBP to USD

```<code>Cur |   FX
GBP | 1.43
EUR | 1.18
USD | 1
</code>```

I need to permanently add a new column [Amount in USD] into [Table_1] which converts all currencies into USD. Basically I need the corresponding currencies to be multiplied by the exchange rates given in [Table_2]. The final result should look like this.

```<code>Currency  | Amount  |Amount in USD
USD       |   243   |   243
USD       |   212   |   212
USD       |   432   |   432
EUR       |   578   |   682
EUR       |   112   |   132
EUR       |   578   |   682
GBP       |   965   |   1380
GBP       |   309   |   442
</code>```

I would appreciate if someone could help out. Thanks in advance.

答:
Try this approach

```<code>SELECT
    Currency
    ,Amount
    ,CEILING(ROUND((Amount*FX),1)) AS [Amount in USD]
FROM Table_1 c1
INNER JOIN Table_2 c2
ON c2.Cur=c1.Currency
</code>```

Result

```<code>Currency    Amount  Amount in USD
-----------------------------------
USD          243       243
USD          212       212
USD          432       432
EUR          578       682
EUR          112       133
EUR          578       682
GBP          965       1380
GBP          309       442
</code>```

Body:
I have two tables

[Table_1] - Amount of money in a specific currency.

Currency  | Amount
USD       |  243
USD       |  212
USD       |  432
EUR       |  578
EUR       |  112
EUR       |  578
GBP       |  965
GBP       |  309

And [Table_2] - Exchange rate EUR and GBP to USD

Cur |   FX
GBP | 1.43
EUR | 1.18
USD | 1

I need to permanently add a new column [Amount in USD] into [Table_1] which converts all currencies into USD. Basically I need the corresponding currencies to be multiplied by the exchange rates given in [Table_2]. The final result should look like this.

Currency  | Amount  |Amount in USD
USD       |   243   |   243
USD       |   212   |   212
USD       |   432   |   432
EUR       |   578   |   682
EUR       |   112   |   132
EUR       |   578   |   682
GBP       |   965   |   1380
GBP       |   309   |   442

I would appreciate if someone could help out. Thanks in advance.

Body:
Try this approach

SELECT
    Currency
    ,Amount
    ,CEILING(ROUND((Amount*FX),1)) AS [Amount in USD]
FROM Table_1 c1
INNER JOIN Table_2 c2
ON c2.Cur=c1.Currency

Result

Currency    Amount  Amount in USD
-----------------------------------
USD          243       243
USD          212       212
USD          432       432
EUR          578       682
EUR          112       133
EUR          578       682
GBP          965       1380
GBP          309       442


问:
Run different class based on variable name?
Let's say we have a few different classes: ClassA, ClassB, ClassC, and ClassD. I have a variable I will set based on different circumstances. I know what it will be ahead of time, but I don't want to have to rewrite many different lines of code in different files each time I need to change it. It is NOT user set.

So now we have
Variable = ClassX

So, Let's say I set Variable to ClassA. How can I make it call ClassA using just that? For example, I know I can do this:

```<code>Variable = ClassA
if Variable == ClassA:
     # Call ClassA and run it
elif Variable == ClassB:
     # Call ClassB and run it
elif Variable == ClassC:
     # Call ClassC and run it
elif Variable == ClassD:
     # Call ClassD and run it
</code>```

However, I want to do something like this:

```<code>Variable = ClassA
V = Variable()
</code>```

Is this possible?

EDIT:
A little more detail...

So I have 3 files that are used in this scenario.

File1.py:

```<code># Class = ClassA
# Class = ClassB
Class = ClassC
# Class = ClassD
...
if Class == "ClassA":
    c = ClassSystem.ClassA
    short_name = c.get_short_name()
elif Class == "ClassB":
    c = ClassSystem.ClassB
    short_name = c.get_short_name()
elif Class == "ClassC":
    c = ClassSystem.ClassC
    short_name = c.get_short_name()
elif Class == "ClassD":
    c = ClassSystem.ClassD
    short_name = c.get_short_name()
...
</code>```

File2.py:

```<code>from Folder.File1 import short_name
from Folder.ClassSystem import *
...
S = short_name()
S.get_information()
</code>```

This doesn't seem to work. File2 is referencing the variable from file1. I then need File2 to use the variable from File1 to run the same class in ClassSystem.

答:
Yes, completely possible. Instead of doing it with ifs though, the most compact approach would include a dictionary of class names to class objects.

You can then key the dictionary and call the resulting class:

```<code>cls_dict = {c.__name__: c for c in {ClassA, ClassB}}
v = 'ClassA'
cls_dict[v]()
</code>```

the set of classes can, of course, be altered to include any additional objects you wish.

Body:
Let's say we have a few different classes: ClassA, ClassB, ClassC, and ClassD. I have a variable I will set based on different circumstances. I know what it will be ahead of time, but I don't want to have to rewrite many different lines of code in different files each time I need to change it. It is NOT user set.

So now we have
Variable = ClassX

So, Let's say I set Variable to ClassA. How can I make it call ClassA using just that? For example, I know I can do this:

Variable = ClassA
if Variable == ClassA:
     # Call ClassA and run it
elif Variable == ClassB:
     # Call ClassB and run it
elif Variable == ClassC:
     # Call ClassC and run it
elif Variable == ClassD:
     # Call ClassD and run it

However, I want to do something like this:

Variable = ClassA
V = Variable()

Is this possible?

EDIT:
A little more detail...

So I have 3 files that are used in this scenario.

File1.py:

# Class = ClassA
# Class = ClassB
Class = ClassC
# Class = ClassD
...
if Class == "ClassA":
    c = ClassSystem.ClassA
    short_name = c.get_short_name()
elif Class == "ClassB":
    c = ClassSystem.ClassB
    short_name = c.get_short_name()
elif Class == "ClassC":
    c = ClassSystem.ClassC
    short_name = c.get_short_name()
elif Class == "ClassD":
    c = ClassSystem.ClassD
    short_name = c.get_short_name()
...

File2.py:

from Folder.File1 import short_name
from Folder.ClassSystem import *
...
S = short_name()
S.get_information()

This doesn't seem to work. File2 is referencing the variable from file1. I then need File2 to use the variable from File1 to run the same class in ClassSystem.

Body:
Yes, completely possible. Instead of doing it with ifs though, the most compact approach would include a dictionary of class names to class objects.

You can then key the dictionary and call the resulting class:

cls_dict = {c.__name__: c for c in {ClassA, ClassB}}
v = 'ClassA'
cls_dict[v]()

the set of classes can, of course, be altered to include any additional objects you wish.


问:
Problem with perl signal INT
I have the following perl code on windows activestate perl 5.8

```<code>  $SIG{INT}=\&clean;

  ...
  sub clean {

  print 'cleaning...';
  ...
  ...
  exit 0;

  }
</code>```

but when i try to close my program by Ctrl^c it didn't enter the sub clean at all could someone help why did i miss something ?

答:
It seems that Windows doesn't provide signals as in Unix.

From man perlwin32:

Signal handling may not behave as on Unix platforms (where it doesn't
      exactly "behave", either :).  For instance, calling "die()" or "exit()"
      from signal handlers will cause an exception, since most implementations
      of "signal()" on Win32 are severely crippled.  Thus, signals may
      work only for simple things like setting a flag variable in the handler.
      Using signals under this port should currently be considered
      unsupported.

ContentLicense: CC BY-SA 2.5

Title: Problem with perl signal INT

Body:
I have the following perl code on windows activestate perl 5.8

  $SIG{INT}=\&clean;

  ...
  sub clean {

  print 'cleaning...';
  ...
  ...
  exit 0;

  }

but when i try to close my program by Ctrl^c it didn't enter the sub clean at all could someone help why did i miss something ?


问:
Custom authentication in nodejs using a json file
I have numbers of api for which i need to do custom Authentication for admin and user. Json file will be having permission for user and admin.These are codes files. Is it correct way what i am doing ? and here am not getting into getUSers function as it get struck in authAdmin or authUser.
Kindly help

```<code>router.js
router.get('/getUsers',testAuth, getUsers);

data.json
{
    "data": {
    admin": {
            "read": true,
            "write": true
    },
    "user": {
            "read": true,
            "write": false
    }
}
}

authentication.js
exports.testAuth = function(req, res, next) {
    var token = req.query.token;
    if (!token) {
        return res.status(401).send({
            error: 'please give token'
        });
    } else {
        db.query('select * from users where token = $1 AND "tokenExpires" > $2', [token, moment().utc().toDate()], function(err, user) {
            if (err) return next(err);
            if (user.rows.length == 0) {
                return res.status(401).send({
                    error: "User not found"
                })
            } else {
                if(user.rows[0].name == 'admin'){
                    exports.authAdmin();
                }
                if(user.rows[0].name == 'user'){
                    exports.authUser();
                }

            }
        })
    }
}

var authAdmin = function(req, res, next) {
    if(data.admin.read != true && data.admin.write != true){
        return res.status(401).send({
                error: "Please Login"
            })
    }else{
         next();
    }
}

var authUser = function(req, res, next) {
    if(data.user.read != true && data.user.write != true){
        return res.status(401).send({
                error: "Please Login"
            })
    }else{
        return next();
    }
}

exports.authAdmin = authAdmin;
exports.authUser = authUser;
</code>```

答:
```<code>router.js
router.get('/getUsers',testAuth, getUsers);

data.json
{
    "data": {
    admin": {
            "read": true,
            "write": true
    },
    "user": {
            "read": true,
            "write": false
    }
}
}

authentication.js
exports.testAuth = function(req, res, next) {
    var token = req.query.token;
    if (!token) {
        return res.status(401).send({
            error: 'please give token'
        });
    } else {
        db.query('select * from users where token = $1 AND "tokenExpires" > $2', [token, moment().utc().toDate()], function(err, user) {
            if (err) return next(err);
            if (user.rows.length == 0) {
                return res.status(401).send({
                    error: "User not found"
                })
            } else {
                if(user.rows[0].name == 'admin'){
                    authAdmin(req,res,next);
                }
                if(user.rows[0].name == 'user'){
                    authUser(req,res,next);
                }

            }
        })
    }
}

var authAdmin = function(req, res, next) {
    if(data.admin.read != true && data.admin.write != true){
        return res.status(401).send({
                error: "Please Login"
            })
    }else{
         next();
    }
}

var authUser = function(req, res, next) {
    if(data.user.read != true && data.user.write != true){
        return res.status(401).send({
                error: "Please Login"
            })
    }else{
        return next();
    }
}

exports.authAdmin = authAdmin;
exports.authUser = authUser;
</code>```

Body:
I have numbers of api for which i need to do custom Authentication for admin and user. Json file will be having permission for user and admin.These are codes files. Is it correct way what i am doing ? and here am not getting into getUSers function as it get struck in authAdmin or authUser.
Kindly help

router.js
router.get('/getUsers',testAuth, getUsers);

data.json
{
    "data": {
    admin": {
            "read": true,
            "write": true
    },
    "user": {
            "read": true,
            "write": false
    }
}
}

authentication.js
exports.testAuth = function(req, res, next) {
    var token = req.query.token;
    if (!token) {
        return res.status(401).send({
            error: 'please give token'
        });
    } else {
        db.query('select * from users where token = $1 AND "tokenExpires" > $2', [token, moment().utc().toDate()], function(err, user) {
            if (err) return next(err);
            if (user.rows.length == 0) {
                return res.status(401).send({
                    error: "User not found"
                })
            } else {
                if(user.rows[0].name == 'admin'){
                    exports.authAdmin();
                }
                if(user.rows[0].name == 'user'){
                    exports.authUser();
                }

            }
        })
    }
}

var authAdmin = function(req, res, next) {
    if(data.admin.read != true && data.admin.write != true){
        return res.status(401).send({
                error: "Please Login"
            })
    }else{
         next();
    }
}

var authUser = function(req, res, next) {
    if(data.user.read != true && data.user.write != true){
        return res.status(401).send({
                error: "Please Login"
            })
    }else{
        return next();
    }
}

exports.authAdmin = authAdmin;
exports.authUser = authUser;


问:
Objective-C can't find Swift protocol
This question is basically the same as this one, but that one went unanswered.

TL;DR: Protocol does not show up in MyProject-Swift.h secret bridging file. And so (not unexpectedly) the Obj-C code can't find it.

I have been able to duplicate it in a from-scratch project. Here is what I did.

Create new one-view iOS Objective-C project.

Add a new Swift UIView subclass via "New File" menu.

Confirm that MyProject-Bridging-Header.h was created. (Visibly)

Confirm that the secret MyProject-Swift.h file was automatically created. (Way down there in DerivedData/.../DerivedSources).

Add an instance of this View to my ViewController.m.

Include the MyProject-Swift.h file in ViewController.m.

Successfully build -- sanity check

Now for the weirdness...

Add a Swift protocol file via "New File" menu.

Make ViewController conform to and implement this protocol.

Build fails at this spot in ViewController.m:

#import "MyProject-Swift.h"
@interface ViewController () <MyProtocol> // Can't find protocol declaration

Examining the MyProject-Swift.h file confirms that the protocol is not in there. But poking around some big pre-existing hybrid projects (that do build) I don't see any protocols in any of their -Swift.h files.

How do Swift protocols get recognized in Objective-C?

答:
I have done this for my project

while defining protocol you can add @objc before the protocol definition

```<code>@objc protocol NewViewControllerDelegate {

}
</code>```

And you are done

Note : I think @objc makes swift protocols and classes visible to objective c

Title: Objective-C can't find Swift protocol

Body:
I have done this for my project

while defining protocol you can add @objc before the protocol definition

@objc protocol NewViewControllerDelegate {

}

And you are done

Note : I think @objc makes swift protocols and classes visible to objective c


问:
Multiple Line Scala List
When I input a single array into my function, I get the correct result.  Now, instead, I would like to feed into my function a multiple line List (or some other Type that I can make from a multiple line String).

```<code>val inputLine = "foo, bar, bar, foo".split(", ").toList
</code>```

That works.  But I want to pass multiple lines into my function.

```<code>val inputList = List("""foo, bar, bar, foo,
bar, foo, foo, bar,
foo, bar, bar, foo""")
</code>```

Thank you!

答:
Well... first of all, lets understand few things so that you can explain your question more clearly.

```<code>// This is a single-line string
val singleLineString = "I am a single line string"

// This is a multi-line string
val multiLineString = """I am a
multiline
string"""

// This is a List of Strings
val list1 = List("string1", "string2")

// List just looks at String... it does not care whether the strings are mutli-line or single-line
val list2 = List(singleLineString, multiLineString)
</code>```

Now... if you have a multi-line String,

```<code>val inputMultiLineString = """blah1, blah2, blah3, blah4,
blah5, blah6, blah7, blah8,
blah9, blah10, blah11, blah12"""
</code>```

And you want to break each of these lines into words while keeping them separate.

```<code>val yourSeparatedLines = inputMultiLineString
  .split("\n")
  .map(line => line.split(",").map(word => word.trim).toList)
  .toList

// yourSeparatedLines: List[List[String]] = List(List(blah1, blah2, blah3, blah4), List(blah5, blah6, blah7, blah8), List(blah9, blah10, blah11, blah12))
</code>```

Title: Multiple Line Scala List

Body:
When I input a single array into my function, I get the correct result.  Now, instead, I would like to feed into my function a multiple line List (or some other Type that I can make from a multiple line String).

val inputLine = "foo, bar, bar, foo".split(", ").toList

That works.  But I want to pass multiple lines into my function.

val inputList = List("""foo, bar, bar, foo,
bar, foo, foo, bar,
foo, bar, bar, foo""")

Thank you!

Body:
Well... first of all, lets understand few things so that you can explain your question more clearly.

// This is a single-line string
val singleLineString = "I am a single line string"

// This is a multi-line string
val multiLineString = """I am a
multiline
string"""

// This is a List of Strings
val list1 = List("string1", "string2")

// List just looks at String... it does not care whether the strings are mutli-line or single-line
val list2 = List(singleLineString, multiLineString)

Now... if you have a multi-line String,

val inputMultiLineString = """blah1, blah2, blah3, blah4,
blah5, blah6, blah7, blah8,
blah9, blah10, blah11, blah12"""

And you want to break each of these lines into words while keeping them separate.

val yourSeparatedLines = inputMultiLineString
  .split("\n")
  .map(line => line.split(",").map(word => word.trim).toList)
  .toList

// yourSeparatedLines: List[List[String]] = List(List(blah1, blah2, blah3, blah4), List(blah5, blah6, blah7, blah8), List(blah9, blah10, blah11, blah12))


问:
convert an encoding to just alphabetical expression
I have a city name string such as

```<code>a='A Coruña'
</code>```

How can I convert this into 'A Coruna'?

Best

答:
The Unidecode module looks like it should do what you want.

Install it with:

```<code>pip install Unidecode
</code>```

Python 3

In Python 3 it's pretty simple:

```<code>>>> from unidecode import unidecode
>>> a='A Coruña'
>>> unidecode(a)
'A Coruna'
</code>```

Python 2

With Python 2, you'll need to either define your string as a Unicode string from the beginning:

```<code>a = u'A Coruña'
</code>```

Or, if you've already got it as a string, you'll need to convert it to a Unicode string using .decode():

```<code>a = 'A Coruña'.decode('utf-8')
</code>```

And then you can run unidecode(a) as in the example for Python 3.

Body:
I have a city name string such as

a='A Coruña'

How can I convert this into 'A Coruna'?

Best

Body:
The Unidecode module looks like it should do what you want.

Install it with:

pip install Unidecode

Python 3

In Python 3 it's pretty simple:

>>> from unidecode import unidecode
>>> a='A Coruña'
>>> unidecode(a)
'A Coruna'

Python 2

With Python 2, you'll need to either define your string as a Unicode string from the beginning:

a = u'A Coruña'

Or, if you've already got it as a string, you'll need to convert it to a Unicode string using .decode():

a = 'A Coruña'.decode('utf-8')

And then you can run unidecode(a) as in the example for Python 3.


问:
return Observable.fromPromise throws an error
I'm using redux-observable and my epic has the following code

```<code>return action$.ofType('SEARCH').mergeMap((action) =>
        return Observable.fromPromise(axios.get(SEARCHURL)).map(result => {
            const filteredStoresAsActions = result.data.stores.map(store => ({
                type: 'SEARCH_RESULTS',
                searchText: action.SearchText.toLowerCase().trim(),
                store
            }));
            // Create the interval to emit an item every second
            return Observable.interval(1000)
                .take(filteredStoresAsActions.length).map(t => filteredStoresAsActions[t]);
        });
);
</code>```

Now when I run the code I get the following error

PromiseObservable.js?7552:76 Uncaught Error: Actions must be plain objects. Use custom middleware for async actions.

I'm not sure why this error is being thrown and how to fix it.  Plus another question I have is if I return Observable.fromPromise then who interprets this and how does this work?

答:
The outer .map() should return an action object, not an Observable. Try using .concatMap() instead:

return action$.ofType('SEARCH').mergeMap((action) =>
  return Observable.fromPromise(axios.get(SEARCHURL)).concatMap(result => {
    const filteredStoresAsActions = result.data.stores.map(store => ({
      type: 'SEARCH_RESULTS',
      searchText: action.SearchText.toLowerCase().trim(),
      store
    }));

    // Create the interval to emit an item every second
    return Observable.interval(1000)
      .take(filteredStoresAsActions.length).map(t => filteredStoresAsActions[t]);
  });
);
```

Body:
I'm using redux-observable and my epic has the following code

return action$.ofType('SEARCH').mergeMap((action) =>
        return Observable.fromPromise(axios.get(SEARCHURL)).map(result => {
            const filteredStoresAsActions = result.data.stores.map(store => ({
                type: 'SEARCH_RESULTS',
                searchText: action.SearchText.toLowerCase().trim(),
                store
            }));
            // Create the interval to emit an item every second
            return Observable.interval(1000)
                .take(filteredStoresAsActions.length).map(t => filteredStoresAsActions[t]);
        });
);

Now when I run the code I get the following error

PromiseObservable.js?7552:76 Uncaught Error: Actions must be plain objects. Use custom middleware for async actions.

I'm not sure why this error is being thrown and how to fix it.  Plus another question I have is if I return Observable.fromPromise then who interprets this and how does this work?

ContentLicense: CC BY-SA 4.0


问:
strtotime converts ints to timestamps
For a program I was working on, I am looping through data, and I needed to know if a certain piece of data was a date or not.

For simplicity, I made a function called is_date, it looked like this:

```<code>function is_date($date){
    return strtotime($date) !== FALSE;
}
</code>```

This seemed to work, but for some reason, it returned TRUE for ints (which aren't dates).

For example:

```<code>is_date('bob') //FALSE
is_date('01/05/2009') //TRUE
is_date('March 16, 2010') //TRUE
is_date(165000) //TRUE
</code>```

Why does is_date(165000) return TRUE?  How can strtotime convert 165000 to a timestamp?

As a fix, I changed my is_date function to this:

```<code>function is_date($date){
    return !is_numeric($date) && strtotime($date) !== FALSE;
}
</code>```

答:
I actually just figured this out.  strtotime, as a format, can accept times without colons.

Therefore, strtotime(165000) is the same as strtotime('16:50:00').

http://ideone.com/Z4hwQ

Title: strtotime converts ints to timestamps

Body:
For a program I was working on, I am looping through data, and I needed to know if a certain piece of data was a date or not.

For simplicity, I made a function called is_date, it looked like this:

function is_date($date){
    return strtotime($date) !== FALSE;
}

This seemed to work, but for some reason, it returned TRUE for ints (which aren't dates).

For example:

is_date('bob') //FALSE
is_date('01/05/2009') //TRUE
is_date('March 16, 2010') //TRUE
is_date(165000) //TRUE

Why does is_date(165000) return TRUE?  How can strtotime convert 165000 to a timestamp?

As a fix, I changed my is_date function to this:

function is_date($date){
    return !is_numeric($date) && strtotime($date) !== FALSE;
}


问:
Inner loop on condition in list comprehension
I have a function to check availability of product and its variations. both model has quantity_left field.

If a product has variations i want to get quantity_left from variation, otherwise i will take quantity_left from product.

```<code>def check_quota(products):
    q_list = []
    for p in products:
        if p.has_variations:
            for v in p.variations:
                q_list.append(v.quantity_left)
        else:
            q_list.append(p.quantity_left)
    return sum(q_list)
</code>```

So above function will return either 0 or any number. if it is zero means product sold out.

Above code is working fine, but i want to optimize this function using list comprehension.

I tried this but this doesn't seems to work.

```<code>return sum([v.quantity_left if p.has_variations else p.quantity_left for p in products for v in i.variations])
</code>```

How can i apply if p.has_variations on inner loop.

UPDATE

suppose i have 3 products under shirt category

```<code>[
  {
    "name":"full sleve",
    "has_variations": True,
    "variations":[
       {
         "type": "S size",
         "quantity_left": 3
       },
       {
         "type": "L size",
         "quantity_left": 0
       }
     ]
  },
  {
    "name":"half sleve",
    "has_variations": False,
    "quantity_left": 0
  },
  {
    "name":"sleve less",
    "has_variations": False,
    "quantity_left": 10
  }
]

# it will return 13 means not sold out.
</code>```

答:
The code below should do the trick.

```<code>def check_quota(products):
    return sum(sum(v.quantity_left for v in p.variations) if p.has_variations else p.quantity_left for p in products)
</code>```

Without the actual data, or any example of input-desired output, it is hard to come up with a working solution. The above code is a blind translation.

From your EDIT, it seems that you are working with dictionaries and not classes. If that is indeed the case, use the following instead:

```<code>def check_quota(products):
    return sum(sum(v['quantity_left'] for v in p['variations']) if p['has_variations'] else p['quantity_left'] for p in products)
</code>```

Body:
I have a function to check availability of product and its variations. both model has quantity_left field.

If a product has variations i want to get quantity_left from variation, otherwise i will take quantity_left from product.

def check_quota(products):
    q_list = []
    for p in products:
        if p.has_variations:
            for v in p.variations:
                q_list.append(v.quantity_left)
        else:
            q_list.append(p.quantity_left)
    return sum(q_list)

So above function will return either 0 or any number. if it is zero means product sold out.

Above code is working fine, but i want to optimize this function using list comprehension.

I tried this but this doesn't seems to work.

return sum([v.quantity_left if p.has_variations else p.quantity_left for p in products for v in i.variations])

How can i apply if p.has_variations on inner loop.

UPDATE

suppose i have 3 products under shirt category

[
  {
    "name":"full sleve",
    "has_variations": True,
    "variations":[
       {
         "type": "S size",
         "quantity_left": 3
       },
       {
         "type": "L size",
         "quantity_left": 0
       }
     ]
  },
  {
    "name":"half sleve",
    "has_variations": False,
    "quantity_left": 0
  },
  {
    "name":"sleve less",
    "has_variations": False,
    "quantity_left": 10
  }
]

# it will return 13 means not sold out.

Body:
The code below should do the trick.

def check_quota(products):
    return sum(sum(v.quantity_left for v in p.variations) if p.has_variations else p.quantity_left for p in products)

Without the actual data, or any example of input-desired output, it is hard to come up with a working solution. The above code is a blind translation.

From your EDIT, it seems that you are working with dictionaries and not classes. If that is indeed the case, use the following instead:

def check_quota(products):
    return sum(sum(v['quantity_left'] for v in p['variations']) if p['has_variations'] else p['quantity_left'] for p in products)


问:
provide close button to div while creation in Dojo
I am creating a div dynamically.

```<code>var item = domConstruct.create("div", null, test);
item.innerHTML = "New Div";
</code>```

On creation I am getting a div with label "New Div". I want the user to add the name to div and a close button so that they can delete the div after creation.
Image of div with edit and delete button

Any help on this will be great.

Thanks
Kumar

答:
From my point of view defining such div with all controls as templated widget would be a better approach. Instead of domConstruct you'll have to create new instance of your templated widget.
Inside of widget you'll be able to attach event to close button to delete your div. Like this:

MyDiv.js

```<code>    define([
    "dojo/_base/declare",
    "dijit/_WidgetBase",
    "dijit/_TemplatedMixin",
    "dojo/text!MyDiv.html"
], function (
    declare,
    _WidgetBase,
    _TemplatedMixin,
    template
) {
    return declare("MyDiv", [_WidgetBase, _TemplatedMixin], {
        templateString: template,
        deleteDiv: function () {
            //do some stuff
            this.destroy(); //destroy widget and its dom node

        }
    });
});
</code>```

MyDiv.html may look like this:

```<code><div>
    <span>Some text</span>
    <span data-dojo-attach-event="click: deleteDiv">Close Me</span>
</div>
</code>```

Here link to dojo docs on this topic:
_TemplatedMixin

Body:
I am creating a div dynamically.

var item = domConstruct.create("div", null, test);
item.innerHTML = "New Div";

On creation I am getting a div with label "New Div". I want the user to add the name to div and a close button so that they can delete the div after creation.
Image of div with edit and delete button

Any help on this will be great.

Thanks
Kumar

Body:
From my point of view defining such div with all controls as templated widget would be a better approach. Instead of domConstruct you'll have to create new instance of your templated widget.
Inside of widget you'll be able to attach event to close button to delete your div. Like this:

MyDiv.js

    define([
    "dojo/_base/declare",
    "dijit/_WidgetBase",
    "dijit/_TemplatedMixin",
    "dojo/text!MyDiv.html"
], function (
    declare,
    _WidgetBase,
    _TemplatedMixin,
    template
) {
    return declare("MyDiv", [_WidgetBase, _TemplatedMixin], {
        templateString: template,
        deleteDiv: function () {
            //do some stuff
            this.destroy(); //destroy widget and its dom node

        }
    });
});

MyDiv.html may look like this:

<div>
    <span>Some text</span>
    <span data-dojo-attach-event="click: deleteDiv">Close Me</span>
</div>

Here link to dojo docs on this topic:
_TemplatedMixin


问:
SCSS arithmetic operation with string
```<code>.selector {
    $width: '10px';
    width: (#{$width}/2); // output: "10px", but expected: 5px
}
</code>```

The code above is self explanatory. Please correct me.

答:
You can use calc function.

```<code>.selector  {
  $width: '10px';
  width: calc(#{$width}/2);
}
</code>```

Update:

Solution based on "Casting a string to a number in Sass" article.

Sassmeister demo.

to-number function

input: '10px', output: 10;

input: 10px, output: 10px

```<code>@function to-number($value) {
  @if type-of($value) == 'number' {
    @return $value;
  } @else if type-of($value) != 'string' {
    @error 'Value for `to-number` should be a number or a string.';
  }

  $result: 0;
  $digits: 0;
  $minus: str-slice($value, 1, 1) == '-';
  $numbers: ('0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9);

  @for $i from if($minus, 2, 1) through str-length($value) {
    $character: str-slice($value, $i, $i);

    @if (index(map-keys($numbers), $character) or $character == '.') {
      @if $character == '.' {
        $digits: 1;
      } @else if $digits == 0 {
        $result: $result * 10 + map-get($numbers, $character);
      } @else {
        $digits: $digits * 10;
        $result: $result + map-get($numbers, $character) / $digits;
      }
    }
  }

  @return if($minus, -$result, $result);;
}
</code>```

to-unit function

input: '20px', output: 1px;

input: '35%', output: 1%

```<code>@function to-unit($value) {
  @if type-of($value) != 'string' {
    @error 'Value for `to-unit` should be a string.';
  }

  $units: ('px': 1px, 'cm': 1cm, 'mm': 1mm, '%': 1%, 'ch': 1ch, 'pc': 1pc, 'in': 1in, 'em': 1em, 'rem': 1rem, 'pt': 1pt, 'ex': 1ex, 'vw': 1vw, 'vh': 1vh, 'vmin': 1vmin, 'vmax': 1vmax);
  $parsed-unit: false;

  @each $unit in $units {
    // str-index - find substring in a string
    // 'px' in '10px' for example

    // $unit is a pair of ['px': 1px] (item in $units)
    // nth(['px': 1px], 1) returns 'px'
    // nth(['px': 1px], 2) returns 1px

    @if (str-index($value, nth($unit, 1))) {
      $parsed-unit: nth($unit, 2);
    }
  }

  @if (not $parsed-unit) {
    @error 'Invalid unit `#{$value}`.';
  }

  @return $parsed-unit;
}
</code>```

Functions usage. At first get the number from string. Second, get the unit from string. Then multiply the number by the unit:

```<code>.selector {
  $size: '10px';

  $number: to-number($size);
  $unit: to-unit($size);
  width: ($number * $unit) / 2;
}
</code>```

Generated css:

```<code>.selector {
  width: 5px;
}
</code>```

Title: SCSS arithmetic operation with string

Body:
.selector {
    $width: '10px';
    width: (#{$width}/2); // output: "10px", but expected: 5px
}

The code above is self explanatory. Please correct me.

Body:
You can use calc function.

.selector  {
  $width: '10px';
  width: calc(#{$width}/2);
}

Update:

Solution based on "Casting a string to a number in Sass" article.

Sassmeister demo.

to-number function

input: '10px', output: 10;

input: 10px, output: 10px

@function to-number($value) {
  @if type-of($value) == 'number' {
    @return $value;
  } @else if type-of($value) != 'string' {
    @error 'Value for `to-number` should be a number or a string.';
  }

  $result: 0;
  $digits: 0;
  $minus: str-slice($value, 1, 1) == '-';
  $numbers: ('0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9);

  @for $i from if($minus, 2, 1) through str-length($value) {
    $character: str-slice($value, $i, $i);

    @if (index(map-keys($numbers), $character) or $character == '.') {
      @if $character == '.' {
        $digits: 1;
      } @else if $digits == 0 {
        $result: $result * 10 + map-get($numbers, $character);
      } @else {
        $digits: $digits * 10;
        $result: $result + map-get($numbers, $character) / $digits;
      }
    }
  }

  @return if($minus, -$result, $result);;
}

to-unit function

input: '20px', output: 1px;

input: '35%', output: 1%

@function to-unit($value) {
  @if type-of($value) != 'string' {
    @error 'Value for `to-unit` should be a string.';
  }

  $units: ('px': 1px, 'cm': 1cm, 'mm': 1mm, '%': 1%, 'ch': 1ch, 'pc': 1pc, 'in': 1in, 'em': 1em, 'rem': 1rem, 'pt': 1pt, 'ex': 1ex, 'vw': 1vw, 'vh': 1vh, 'vmin': 1vmin, 'vmax': 1vmax);
  $parsed-unit: false;

  @each $unit in $units {
    // str-index - find substring in a string
    // 'px' in '10px' for example

    // $unit is a pair of ['px': 1px] (item in $units)
    // nth(['px': 1px], 1) returns 'px'
    // nth(['px': 1px], 2) returns 1px

    @if (str-index($value, nth($unit, 1))) {
      $parsed-unit: nth($unit, 2);
    }
  }

  @if (not $parsed-unit) {
    @error 'Invalid unit `#{$value}`.';
  }

  @return $parsed-unit;
}

Functions usage. At first get the number from string. Second, get the unit from string. Then multiply the number by the unit:

.selector {
  $size: '10px';

  $number: to-number($size);
  $unit: to-unit($size);
  width: ($number * $unit) / 2;
}

Generated css:

.selector {
  width: 5px;
}


问:
why are Threads loading data from array randomly?
I'm new with threads and I’m trying to create a program where four threads do some parallel computations using values from a global array. But, The problem that the threads are not loading the data in order.

```<code>#define QUARTER 64
#define RANGE_STEP 256

struct thread_data
{
  unsigned          start;
  unsigned          stop;
  __m256*           re_fc;
  __m256*           im_fc;
};

#define         NUM_THREADS                 4
struct          thread_data                 thread_data_array[NUM_THREADS];

void *routine(void *thread_info)
{
  int n,t;
  unsigned t_start,t_stop;
  __m256 *Re_fac    , *Im_fac;
  struct thread_data *mydata;
  mydata = (struct thread_data*) thread_info;
  t_start   = mydata->start;
  t_stop    = mydata->stop;
  Re_fac        = mydata->re_fc;
  Im_fac        = mydata->im_fc;

  t = t_start;
  for (n = t_start; n < t_stop; n += 8)
  {
    // computations
    RE_m256_fac = Re_fac[t];
    IM_m256_fac = Im_fac[t];
    // computations
    t++;
  }
  pthread_exit(NULL);
}

int main()
{
  unsigned t,i=0;
  for(t=0;t<RANGE_STEP;t+=QUARTER)
  {
    thread_data_array[i].start      = t;
    thread_data_array[i].stop       = t+QUARTER;
    thread_data_array[i].re_fc      = RE_factors;
    thread_data_array[i].im_fc      = IM_factors;
    pthread_create(&threads[i],NULL,routine,(void *)&thread_data_array[i]);
    i++;
  }
  for(i=0; i<NUM_THREADS; i++)
  {
     int rc = pthread_join(threads[i], NULL);
     if (rc)
     {
         fprintf(stderr, "failed to join thread #%u - %s\n",i, strerror(rc));
     }
  }
}
</code>```

The problem that I am talking about is occurring in the routine of the thread inside the for() loop exactly with these two load instructions RE_m256_fac = Re_fac[t];and IM_m256_fac = Im_fac[t]; the loaded data is not correct ... I think the index t is a local variable so no synchros is needed , or I am wrong?

答:
After some digging it turned to be that since I am reading from a global shared array I have to use the mutex mechanism to prevent the mutual exclusion  as so:

```<code>void *routine(void *thread_info)
{
  int n,t;
  unsigned t_start,t_stop;
 __m256 *Re_fac    , *Im_fac;
 struct thread_data *mydata;
 mydata = (struct thread_data*) thread_info;
 t_start   = mydata->start;
 t_stop    = mydata->stop;
 Re_fac        = mydata->re_fc;
 Im_fac        = mydata->im_fc;

 t = t_start;
 for (n = t_start; n < t_stop; n += 8)
 {
   pthread_mutex_lock(&mutex);
   // computations
   RE_m256_fac = Re_fac[t];
   IM_m256_fac = Im_fac[t];
   // computations
   pthread_mutex_unlock(&mutex);
   t++;
 }
 pthread_exit(NULL);
}
</code>```

and since then, I can see that the threads are loading the values correctly from the shared array.

Body:
I'm new with threads and I’m trying to create a program where four threads do some parallel computations using values from a global array. But, The problem that the threads are not loading the data in order.

#define QUARTER 64
#define RANGE_STEP 256

struct thread_data
{
  unsigned          start;
  unsigned          stop;
  __m256*           re_fc;
  __m256*           im_fc;
};

#define         NUM_THREADS                 4
struct          thread_data                 thread_data_array[NUM_THREADS];

void *routine(void *thread_info)
{
  int n,t;
  unsigned t_start,t_stop;
  __m256 *Re_fac    , *Im_fac;
  struct thread_data *mydata;
  mydata = (struct thread_data*) thread_info;
  t_start   = mydata->start;
  t_stop    = mydata->stop;
  Re_fac        = mydata->re_fc;
  Im_fac        = mydata->im_fc;

  t = t_start;
  for (n = t_start; n < t_stop; n += 8)
  {
    // computations
    RE_m256_fac = Re_fac[t];
    IM_m256_fac = Im_fac[t];
    // computations
    t++;
  }
  pthread_exit(NULL);
}

int main()
{
  unsigned t,i=0;
  for(t=0;t<RANGE_STEP;t+=QUARTER)
  {
    thread_data_array[i].start      = t;
    thread_data_array[i].stop       = t+QUARTER;
    thread_data_array[i].re_fc      = RE_factors;
    thread_data_array[i].im_fc      = IM_factors;
    pthread_create(&threads[i],NULL,routine,(void *)&thread_data_array[i]);
    i++;
  }
  for(i=0; i<NUM_THREADS; i++)
  {
     int rc = pthread_join(threads[i], NULL);
     if (rc)
     {
         fprintf(stderr, "failed to join thread #%u - %s\n",i, strerror(rc));
     }
  }
}

The problem that I am talking about is occurring in the routine of the thread inside the for() loop exactly with these two load instructions RE_m256_fac = Re_fac[t];and IM_m256_fac = Im_fac[t]; the loaded data is not correct ... I think the index t is a local variable so no synchros is needed , or I am wrong?

Body:
After some digging it turned to be that since I am reading from a global shared array I have to use the mutex mechanism to prevent the mutual exclusion  as so:

void *routine(void *thread_info)
{
  int n,t;
  unsigned t_start,t_stop;
 __m256 *Re_fac    , *Im_fac;
 struct thread_data *mydata;
 mydata = (struct thread_data*) thread_info;
 t_start   = mydata->start;
 t_stop    = mydata->stop;
 Re_fac        = mydata->re_fc;
 Im_fac        = mydata->im_fc;

 t = t_start;
 for (n = t_start; n < t_stop; n += 8)
 {
   pthread_mutex_lock(&mutex);
   // computations
   RE_m256_fac = Re_fac[t];
   IM_m256_fac = Im_fac[t];
   // computations
   pthread_mutex_unlock(&mutex);
   t++;
 }
 pthread_exit(NULL);
}

and since then, I can see that the threads are loading the values correctly from the shared array.


问:
BucketedRandomProjectionLSHModel approxNearestNeighbors function on entire dataframe

I'm trying to evaluate an entire DataFrame through the approxNearestNeighbors function of BucketedRandomProjectionLSHModel

What I expect:

A DataFrame containing the following information:

```<code>cookieId    NN
id1         [id3, id5, id7]
id2         [id8, id9]
...
</code>```

Input DataFrame (daily_content_transformed):

```<code>cookieID   features(a sparse vector)
id1        sparse vector with features
id2        sparse vector with features
...
</code>```

This works:

```<code>val key = Vectors.sparse(37599,
  Array(1,4,6,7,16,57,81,104,166,225,290,692,763),
  Array(1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0))
model.approxNearestNeighbors(daily_content_transformed, key, 20).show(20, false)
</code>```

It returns a DataFrame with 21 rows. I could extract the cookieId column from this DataFrame and store it in the expected DataFrame.

Where I'm stuck:

instead of hard coding the key to retrieve NN from, run the method for every row in the input dataframe, and make a dataframe as expected above

Any help?

Edit in reply to first response:

After playing around with the suggestion to use approxSimilarityJoin instead of approxNearestNeighbors I came to the following conclusions:

the suggested solution works well for daily_content_transformed.limit(3000)

starting from daily_content_transformed.limit(5000), my spark job terminates with an java.lang.OutOfMemoryError.

my input table contains +- 800 000 unique cookieID's (rows).

Although the suggested solution works for small inputs, scalability is an issue.

答:
BucketedRandomProjectionLSHModel doesn't provide required API. I think you approximate it using approxSimilarityJoin:

```<code>import org.apache.spark.sql.functions.{struct, udf, collect_list. sort_array}

val threshold: Double
val n: Int

def take(n: Int) = udf((xs: Seq[String]) => xs.take(n))

model
  .approxNearestNeighbors(
    daily_content_transformed.alias("left"),
    daily_content_transformed.alias("right"))
  .groupBy($"datasetA.id" as "cookieId")
  // Collect pairs (dist, id)
  .agg(collect_list(struct($"distCol", $"datasetB.id" as "id") as "NN"))
  // Sort by dist, drop dist and take n
  .withColumn("NN" take(n)(sort_array($"NN", false).getItem("id")))
</code>```

This guarantees to preserve at most n neighbors.

Body:
I'm trying to evaluate an entire DataFrame through the approxNearestNeighbors function of BucketedRandomProjectionLSHModel

What I expect:

A DataFrame containing the following information:

cookieId    NN
id1         [id3, id5, id7]
id2         [id8, id9]
...

Input DataFrame (daily_content_transformed):

cookieID   features(a sparse vector)
id1        sparse vector with features
id2        sparse vector with features
...

This works:

val key = Vectors.sparse(37599,
  Array(1,4,6,7,16,57,81,104,166,225,290,692,763),
  Array(1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0))
model.approxNearestNeighbors(daily_content_transformed, key, 20).show(20, false)

It returns a DataFrame with 21 rows. I could extract the cookieId column from this DataFrame and store it in the expected DataFrame.

Where I'm stuck:

instead of hard coding the key to retrieve NN from, run the method for every row in the input dataframe, and make a dataframe as expected above

Any help?

Edit in reply to first response:

After playing around with the suggestion to use approxSimilarityJoin instead of approxNearestNeighbors I came to the following conclusions:

the suggested solution works well for daily_content_transformed.limit(3000)

starting from daily_content_transformed.limit(5000), my spark job terminates with an java.lang.OutOfMemoryError.

my input table contains +- 800 000 unique cookieID's (rows).

Although the suggested solution works for small inputs, scalability is an issue.

Body:
BucketedRandomProjectionLSHModel doesn't provide required API. I think you approximate it using approxSimilarityJoin:

import org.apache.spark.sql.functions.{struct, udf, collect_list. sort_array}

val threshold: Double
val n: Int

def take(n: Int) = udf((xs: Seq[String]) => xs.take(n))

model
  .approxNearestNeighbors(
    daily_content_transformed.alias("left"),
    daily_content_transformed.alias("right"))
  .groupBy($"datasetA.id" as "cookieId")
  // Collect pairs (dist, id)
  .agg(collect_list(struct($"distCol", $"datasetB.id" as "id") as "NN"))
  // Sort by dist, drop dist and take n
  .withColumn("NN" take(n)(sort_array($"NN", false).getItem("id")))

This guarantees to preserve at most n neighbors.


问:
Map a network drive to be used by a service
Suppose some Windows service uses code that wants mapped network drives and no UNC paths. How can I make the drive mapping available to the service's session when the service is started? Logging in as the service user and creating a persistent mapping will not establish the mapping in the context of the actual service.</p>

答:
Use this at your own risk. (I have tested it on XP and Server 2008 x64 R2)

For this hack you will need SysinternalsSuite by Mark Russinovich:

Step one:
Open an elevated cmd.exe prompt (Run as administrator)

Step two:
Elevate again to root using PSExec.exe:
Navigate to the folder containing SysinternalsSuite and execute the following command
psexec -i -s cmd.exe
you are now inside of a prompt that is nt authority\system and you can prove this by typing whoami. The -i is needed because drive mappings need to interact with the user

Step Three:
Create the persistent mapped drive as the SYSTEM account with the following command
net use z: \\servername\sharedfolder /persistent:yes

It's that easy!

WARNING: You can only remove this mapping the same way you created it, from the SYSTEM account. If you need to remove it, follow steps 1 and 2 but change the command on step 3 to net use z: /delete.

NOTE: The newly created mapped drive will now appear for ALL users of this system but they will see it displayed as "Disconnected Network Drive (Z:)". Do not let the name fool you. It may claim to be disconnected but it will work for everyone. That's how you can tell this hack is not supported by M$.

OwnerDisplayName: VoidPointer


问:
how to find the minimum value of each row and column from given table
i want to find the minimum value of each row also minimum value of each column

add input to each row and column produced after the table generation

want to find minimum value of each row and minimum value of each column

also minimum value of whole table

i want to input the user values instead of default value cell in fiddle given below

[fiddle][1]

(function (window, document, undefined) {
    "use strict";

    var wrap = document.getElementById("wrap"),
        setColumn = document.getElementById("column"),
        setRow = document.getElementById("row"),
        btnGen = document.getElementById("btnGen"),
        btnCopy = document.getElementById("btnCopy");

    btnGen.addEventListener("click", generateTable);
    btnCopy.addEventListener("click", copyTo);

    function generateTable(e) {
        var newTable = document.createElement("table"),
            tBody = newTable.createTBody(),
            nOfColumns = parseInt(setColumn.value, 10),
            nOfRows = parseInt(setRow.value, 10),
            row;

        newTable.createCaption().appendChild(document.createTextNode("Generated Table"));

        for (var i = 0; i < nOfRows; i++) {
            row = generateRow(nOfColumns);
            tBody.appendChild(row.cloneNode(true));
        }

        (wrap.hasChildNodes() ? wrap.replaceChild : wrap.appendChild).call(wrap, newTable, wrap.children[0]);
    }

    function generateRow(n) {
        var row = document.createElement("tr"),
            text;

        for (var i = 0; i < n; i++) {
            text = document.createTextNode(Math.trunc(100 * Math.random()));
            row.insertCell().appendChild(text.cloneNode(true));
        }

        return row.cloneNode(true);
    }

    function copyTo(e) {
        prompt("Copy to clipboard: Ctrl+C, Enter", wrap.innerHTML);
    }
}(window, window.document));```
<pre class="snippet-code-css lang-css prettyprint-override"><code>ul {
    margin-left: 0;
    padding-left: 0;
    width: 200px;
}
ul li {
    list-style: none;
    padding-bottom: 1em;
}
input[type=number] {
    width: 70px;
    float: right;
}
table, td {
    border: 1px solid #000;
    padding: 5px;
    border-spacing: 0;
    border-collapse: collapse;
    caption-side: bottom;
}</code>```

        Add a Column
        <input type="number" id="column" validate />

        Add a Row
        <input type="number" id="row" />

        <input type="button" value="Generate" id="btnGen" />
        <input type="button" value="Copy to Clipboard" id="btnCopy" />

```

please give me suggestion about it

also i want to store the minimum value of each row and column.

答:
Check this

const generate = document.getElementById('generate');
function handleTable(cont) {
  const table = cont.getElementsByTagName('table')[0],
    cells = table.getElementsByClassName('cell'),
    all_cells = table.getElementsByTagName('td'),
    size = cells.length;
  let currentValue, minimum;
  const p = document.createElement('p'),
    text = document.createTextNode('Minimum is: '),
    minValue = document.createElement('span');
  p.appendChild(text);
  p.appendChild(minValue);
  cont.appendChild(p);
const rowsNum = table.getElementsByTagName('tr').length,
  colsNum = table.getElementsByTagName('td').length/(rowsNum);
const addInput = function(e){
  currentValue = e.target.innerHTML;
  e.target.innerHTML = '';
  let myInput = document.createElement('input');
  myInput.classList.add('my_input');
  e.target.appendChild(myInput).focus();
}
const getMinimum = function(){
  let cur_rows = [],
    temp2 = rowsNum-1;
  while(temp2--)
    cur_rows.push([]);
  let cur_cols = [],
    temp1 = colsNum-1;
  while(temp1--)
    cur_cols.push([]);
  let values = [];
  for (let i = 0; i < size; i++){
    let item = cells[i].innerHTML;
    if(item){
      values.push(item);
      let cur_x = i % (colsNum-1),
        cur_y = (i - cur_x) / (colsNum-1);
      cur_cols[cur_x].push(item);
      cur_rows[cur_y].push(item);
    }
  }
  let cur_min = Math.min.apply(null, values);
  minValue.innerHTML = ((cur_min && (cur_min != Infinity)) || (cur_min == 0)) ? cur_min : '';
  let cur_min_rows = [];
  for (let i = 0; i<cur_rows.length; i++)
    cur_min_rows[i] = Math.min.apply(null, cur_rows[i]);
  let cur_min_cols = [];
  for (let i = 0; i < cur_cols.length; i++)
    cur_min_cols[i] = Math.min.apply(null, cur_cols[i]);
  for (let i = 0; i < all_cells.length; i++)
    if (all_cells[i].classList.contains('result')){
      let cur_x = i % colsNum,
        cur_y = (i - cur_x)/(colsNum);
      all_cells[i].innerHTML = '';
      if ((cur_x == colsNum-1) && (cur_min_rows[cur_y] != Infinity))
        all_cells[i].innerHTML = cur_min_rows[cur_y];
      if ((cur_y == rowsNum-1) && (cur_min_cols[cur_x] != Infinity))
        all_cells[i].innerHTML = cur_min_cols[cur_x];
    }
}
const removeInput = function(e){
  let elem = e.target;
  if (!elem.classList.contains('my_input')) {
    for (let i = size; i--;){
      let input = cells[i].getElementsByClassName('my_input')[0];
      if(input) {
        let value = input.value;
        cells[i].removeChild(input);
        if(value){
          value = value.replace(/ /g,'');
          cells[i].innerHTML = value;
          getMinimum();
        }
        else {
          cells[i].innerHTML = currentValue;
          currentValue = '';
        }
      }
    }
  }
}
for (let i = size; i--;)
  cells[i].addEventListener('click', addInput);
document.body.addEventListener('click', removeInput, true);
};
const generateRow = function(cols, isLast){
  let row = document.createElement('tr');
  const className = (isLast) ? 'result' : 'cell';
  for (let i = cols; i--;) {
    let cell = document.createElement('td');
    cell.classList.add(className);
    row.appendChild(cell);
  }
  let cell = document.createElement('td');
  cell.classList.add('result');
  row.appendChild(cell);
  if(isLast)
    cell.classList.remove('result');
  return row;
}
const generateTable = function(e){
  const wrap = document.getElementById('wrap'),
    rows = document.getElementById('rows'),
    columns = document.getElementById('columns'),
    newTable = document.createElement('table');
  let row;
  for (let i = 0; i <= rows.value; i++ ){
    if(i == rows.value)
      row = generateRow(columns.value, true);
    else
      row = generateRow(columns.value, false);
    newTable.appendChild(row);
  }
  if (wrap.hasChildNodes())
    wrap.innerHTML = '';
  wrap.appendChild(newTable);
  handleTable(wrap);
};
generate.addEventListener('click', generateTable);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.result, .cell{
  width:30px;
  height: 30px;
  text-align:center;
}
.cell {
  border:1px solid;
}
table {
  border-collapse: collapse;
}
.my_input {
  width: 25px;
  text-align:center;
  border:none;
  outline:none;
}
ul {
  width: 200px;
}
ul li {
  list-style: none;
  margin-bottom: 12px;
}
input[type=number] {
  width: 70px;
  float: right;
}</code>```

<form>

      Rows
      <input type="number" id="rows" value="">

      Columns
      <input type="number" id="columns" value="">

      <input type="button" value="Generate" id="generate">

</form>

```

Body:
i want to find the minimum value of each row also minimum value of each column

add input to each row and column produced after the table generation

want to find minimum value of each row and minimum value of each column

also minimum value of whole table

i want to input the user values instead of default value cell in fiddle given below

[fiddle][1]

(function (window, document, undefined) {
    "use strict";

    var wrap = document.getElementById("wrap"),
        setColumn = document.getElementById("column"),
        setRow = document.getElementById("row"),
        btnGen = document.getElementById("btnGen"),
        btnCopy = document.getElementById("btnCopy");

    btnGen.addEventListener("click", generateTable);
    btnCopy.addEventListener("click", copyTo);

    function generateTable(e) {
        var newTable = document.createElement("table"),
            tBody = newTable.createTBody(),
            nOfColumns = parseInt(setColumn.value, 10),
            nOfRows = parseInt(setRow.value, 10),
            row;

        newTable.createCaption().appendChild(document.createTextNode("Generated Table"));

        for (var i = 0; i < nOfRows; i++) {
            row = generateRow(nOfColumns);
            tBody.appendChild(row.cloneNode(true));
        }

        (wrap.hasChildNodes() ? wrap.replaceChild : wrap.appendChild).call(wrap, newTable, wrap.children[0]);
    }

    function generateRow(n) {
        var row = document.createElement("tr"),
            text;

        for (var i = 0; i < n; i++) {
            text = document.createTextNode(Math.trunc(100 * Math.random()));
            row.insertCell().appendChild(text.cloneNode(true));
        }

        return row.cloneNode(true);
    }

    function copyTo(e) {
        prompt("Copy to clipboard: Ctrl+C, Enter", wrap.innerHTML);
    }
}(window, window.document));

ul {
    margin-left: 0;
    padding-left: 0;
    width: 200px;
}
ul li {
    list-style: none;
    padding-bottom: 1em;
}
input[type=number] {
    width: 70px;
    float: right;
}
table, td {
    border: 1px solid #000;
    padding: 5px;
    border-spacing: 0;
    border-collapse: collapse;
    caption-side: bottom;
}

        Add a Column
        <input type="number" id="column" validate />

        Add a Row
        <input type="number" id="row" />

        <input type="button" value="Generate" id="btnGen" />
        <input type="button" value="Copy to Clipboard" id="btnCopy" />

please give me suggestion about it

also i want to store the minimum value of each row and column.

Body:
Check this

const generate = document.getElementById('generate');
function handleTable(cont) {
  const table = cont.getElementsByTagName('table')[0],
    cells = table.getElementsByClassName('cell'),
    all_cells = table.getElementsByTagName('td'),
    size = cells.length;
  let currentValue, minimum;
  const p = document.createElement('p'),
    text = document.createTextNode('Minimum is: '),
    minValue = document.createElement('span');
  p.appendChild(text);
  p.appendChild(minValue);
  cont.appendChild(p);
const rowsNum = table.getElementsByTagName('tr').length,
  colsNum = table.getElementsByTagName('td').length/(rowsNum);
const addInput = function(e){
  currentValue = e.target.innerHTML;
  e.target.innerHTML = '';
  let myInput = document.createElement('input');
  myInput.classList.add('my_input');
  e.target.appendChild(myInput).focus();
}
const getMinimum = function(){
  let cur_rows = [],
    temp2 = rowsNum-1;
  while(temp2--)
    cur_rows.push([]);
  let cur_cols = [],
    temp1 = colsNum-1;
  while(temp1--)
    cur_cols.push([]);
  let values = [];
  for (let i = 0; i < size; i++){
    let item = cells[i].innerHTML;
    if(item){
      values.push(item);
      let cur_x = i % (colsNum-1),
        cur_y = (i - cur_x) / (colsNum-1);
      cur_cols[cur_x].push(item);
      cur_rows[cur_y].push(item);
    }
  }
  let cur_min = Math.min.apply(null, values);
  minValue.innerHTML = ((cur_min && (cur_min != Infinity)) || (cur_min == 0)) ? cur_min : '';
  let cur_min_rows = [];
  for (let i = 0; i<cur_rows.length; i++)
    cur_min_rows[i] = Math.min.apply(null, cur_rows[i]);
  let cur_min_cols = [];
  for (let i = 0; i < cur_cols.length; i++)
    cur_min_cols[i] = Math.min.apply(null, cur_cols[i]);
  for (let i = 0; i < all_cells.length; i++)
    if (all_cells[i].classList.contains('result')){
      let cur_x = i % colsNum,
        cur_y = (i - cur_x)/(colsNum);
      all_cells[i].innerHTML = '';
      if ((cur_x == colsNum-1) && (cur_min_rows[cur_y] != Infinity))
        all_cells[i].innerHTML = cur_min_rows[cur_y];
      if ((cur_y == rowsNum-1) && (cur_min_cols[cur_x] != Infinity))
        all_cells[i].innerHTML = cur_min_cols[cur_x];
    }
}
const removeInput = function(e){
  let elem = e.target;
  if (!elem.classList.contains('my_input')) {
    for (let i = size; i--;){
      let input = cells[i].getElementsByClassName('my_input')[0];
      if(input) {
        let value = input.value;
        cells[i].removeChild(input);
        if(value){
          value = value.replace(/ /g,'');
          cells[i].innerHTML = value;
          getMinimum();
        }
        else {
          cells[i].innerHTML = currentValue;
          currentValue = '';
        }
      }
    }
  }
}
for (let i = size; i--;)
  cells[i].addEventListener('click', addInput);
document.body.addEventListener('click', removeInput, true);
};
const generateRow = function(cols, isLast){
  let row = document.createElement('tr');
  const className = (isLast) ? 'result' : 'cell';
  for (let i = cols; i--;) {
    let cell = document.createElement('td');
    cell.classList.add(className);
    row.appendChild(cell);
  }
  let cell = document.createElement('td');
  cell.classList.add('result');
  row.appendChild(cell);
  if(isLast)
    cell.classList.remove('result');
  return row;
}
const generateTable = function(e){
  const wrap = document.getElementById('wrap'),
    rows = document.getElementById('rows'),
    columns = document.getElementById('columns'),
    newTable = document.createElement('table');
  let row;
  for (let i = 0; i <= rows.value; i++ ){
    if(i == rows.value)
      row = generateRow(columns.value, true);
    else
      row = generateRow(columns.value, false);
    newTable.appendChild(row);
  }
  if (wrap.hasChildNodes())
    wrap.innerHTML = '';
  wrap.appendChild(newTable);
  handleTable(wrap);
};
generate.addEventListener('click', generateTable);

.result, .cell{
  width:30px;
  height: 30px;
  text-align:center;
}
.cell {
  border:1px solid;
}
table {
  border-collapse: collapse;
}
.my_input {
  width: 25px;
  text-align:center;
  border:none;
  outline:none;
}
ul {
  width: 200px;
}
ul li {
  list-style: none;
  margin-bottom: 12px;
}
input[type=number] {
  width: 70px;
  float: right;
}

<form>
  <ul>
    <li>
      <label>Rows</label>
      <input type="number" id="rows" value="">
    </li>
    <li>
      <label>Columns</label>
      <input type="number" id="columns" value="">
    </li>
    <li>
      <input type="button" value="Generate" id="generate">
    </li>
  </ul>
</form>
<div id="wrap"></div>


问:
Spring PlatformTransactionManager - concurrent transactions
I'm implementing a JDBC database access API (basically a wrapper) and I'm usnig Spring JdbcTemplate with PlatformTransactionManager to handle transactional operations. Everything looks ok, but I cannot understand how jdbcTemplate manage concurrent transactions.
I'll give you a simplified example based on the creation of students to make my point. Let's create 2 students, John and Jack. The first without erros and the seconds with one error, there's the steps and the code below.

John starts a transaction

Execute John insert without commit

Wait for Jack insert

Jack starts a transaction

Execute Jack insert with an error (age as null but database required NON  - NULL)

Rollback Jack transaction

Commit John trasaction

StudentDAO

```<code>public class StudentJDBCTemplate implements StudentDAO {

   private DataSource dataSource;
   private JdbcTemplate jdbcTemplateObject;
   private PlatformTransactionManager transactionManager;

   // constructor, getters and setters

  public TransactionStatus startTransaction() throws TransactionException {
      TransactionDefinition def = new DefaultTransactionDefinition();
      transactionManager.getTransaction(def);
  }

  public void commitTransaction(TransactionStatus status) throws TransactionException {
      transactionManager.commit(status);
  }

  public void rollbackTransaction(TransactionStatus status) throws TransactionException {
      transactionManager.rollback(status);
  }

   public void create(String name, Integer age){
      String SQL1 = "insert into Student (name, age) values (?, ?)";
      jdbcTemplateObject.update( SQL1, name, age);
      return;
   }
}
</code>```

MainApp

```<code>public class MainApp {
    public static void main(String[] args){
        // setup db connection etc

       StudentJDBCTemplate studentDao = new StudentJDBCTemplate();

       TransactionStatus txJohn = studentDao.startTransaction();
       TransactionStatus txJack = studentDao.startTransaction();

       studentDao.create("John", 20);

       try {
           studentDao.create("Jack", null); // **FORCE EXCEPTION**
       } catch(Exception e){
           studentDao.rollback(txJack);
       }
       studentDao.commit(txJohn);
    }
}
</code>```

How JdbcTemplate knows that 1 transaction is ok but the other is not? From my undertanding, despite we have created 2 transactions, JdbcTemplate will rollback Jack AND John transactions, because query, execute and update methods does not require TransactionStatus as a parameter. That means that Spring jdbcTemplate only supports 1 transaction at time?!

答:
All the operations in a single transaction are always executed as a single unit so either all will be committed or none.

If John starts a transaction which insert and then update then either both (insert and update) will succeed or none and will not be impacted by the transaction started by Jack.

Now how the concurrent transactions interfere with each other is controlled by isolation level i.e. how a transaction sees data modified by another concurrent transaction.

Body:
I'm implementing a JDBC database access API (basically a wrapper) and I'm usnig Spring JdbcTemplate with PlatformTransactionManager to handle transactional operations. Everything looks ok, but I cannot understand how jdbcTemplate manage concurrent transactions.
I'll give you a simplified example based on the creation of students to make my point. Let's create 2 students, John and Jack. The first without erros and the seconds with one error, there's the steps and the code below.

John starts a transaction

Execute John insert without commit

Wait for Jack insert

Jack starts a transaction

Execute Jack insert with an error (age as null but database required NON  - NULL)

Rollback Jack transaction

Commit John trasaction

StudentDAO

public class StudentJDBCTemplate implements StudentDAO {

   private DataSource dataSource;
   private JdbcTemplate jdbcTemplateObject;
   private PlatformTransactionManager transactionManager;

   // constructor, getters and setters

  public TransactionStatus startTransaction() throws TransactionException {
      TransactionDefinition def = new DefaultTransactionDefinition();
      transactionManager.getTransaction(def);
  }

  public void commitTransaction(TransactionStatus status) throws TransactionException {
      transactionManager.commit(status);
  }

  public void rollbackTransaction(TransactionStatus status) throws TransactionException {
      transactionManager.rollback(status);
  }

   public void create(String name, Integer age){
      String SQL1 = "insert into Student (name, age) values (?, ?)";
      jdbcTemplateObject.update( SQL1, name, age);
      return;
   }
}

MainApp

public class MainApp {
    public static void main(String[] args){
        // setup db connection etc

       StudentJDBCTemplate studentDao = new StudentJDBCTemplate();

       TransactionStatus txJohn = studentDao.startTransaction();
       TransactionStatus txJack = studentDao.startTransaction();

       studentDao.create("John", 20);

       try {
           studentDao.create("Jack", null); // **FORCE EXCEPTION**
       } catch(Exception e){
           studentDao.rollback(txJack);
       }
       studentDao.commit(txJohn);
    }
}

How JdbcTemplate knows that 1 transaction is ok but the other is not? From my undertanding, despite we have created 2 transactions, JdbcTemplate will rollback Jack AND John transactions, because query, execute and update methods does not require TransactionStatus as a parameter. That means that Spring jdbcTemplate only supports 1 transaction at time?!


问:
android TextView : Change Text Color on click
I have a textfield that behaves like a local link, clicking on it fetches an image from database and shows it. It doesn't ping to server all the time.

Here is the xml code for the text view

```<code><TextView android:layout_marginLeft="2dp" android:linksClickable="true"
            android:layout_marginRight="2dp" android:layout_width="wrap_content"
            android:text="@string/Beatles" android:clickable="true" android:id="@+id/Beatles"
            android:textColor="@color/Black"
            android:textSize="12dp" android:layout_height="wrap_content" android:textColorHighlight="@color/yellow" android:textColorLink="@color/yellow"  android:autoLink="all"></TextView>
</code>```

The question is i want to see the color of text view should be changed in yellow, instead of the same black color,

Just Like the button behavior but instead of changing the background color i want to change a text color

答:
I like what Cristian suggests, but extending TextView seems like overkill. In addition, his solution doesn't handle the MotionEvent.ACTION_CANCEL event, making it likely that your text will stay selected even after the clicking is done.

To achieve this effect, I implemented my own onTouchListener in a separate file:

```<code>public class CustomTouchListener implements View.OnTouchListener {
    public boolean onTouch(View view, MotionEvent motionEvent) {
    switch(motionEvent.getAction()){
            case MotionEvent.ACTION_DOWN:
            ((TextView)view).setTextColor(0xFFFFFFFF); //white
                break;
            case MotionEvent.ACTION_CANCEL:
            case MotionEvent.ACTION_UP:
            ((TextView)view).setTextColor(0xFF000000); //black
                break;
    }
        return false;
    }
}
</code>```

Then you can assign this to whatever TextView you wish:

newTextView.setOnTouchListener(new CustomTouchListener());

Body:
I have a textfield that behaves like a local link, clicking on it fetches an image from database and shows it. It doesn't ping to server all the time.

Here is the xml code for the text view

<TextView android:layout_marginLeft="2dp" android:linksClickable="true"
            android:layout_marginRight="2dp" android:layout_width="wrap_content"
            android:text="@string/Beatles" android:clickable="true" android:id="@+id/Beatles"
            android:textColor="@color/Black"
            android:textSize="12dp" android:layout_height="wrap_content" android:textColorHighlight="@color/yellow" android:textColorLink="@color/yellow"  android:autoLink="all"></TextView>

The question is i want to see the color of text view should be changed in yellow, instead of the same black color,

Just Like the button behavior but instead of changing the background color i want to change a text color

Body:
I like what Cristian suggests, but extending TextView seems like overkill. In addition, his solution doesn't handle the MotionEvent.ACTION_CANCEL event, making it likely that your text will stay selected even after the clicking is done.

To achieve this effect, I implemented my own onTouchListener in a separate file:

public class CustomTouchListener implements View.OnTouchListener {
    public boolean onTouch(View view, MotionEvent motionEvent) {
    switch(motionEvent.getAction()){
            case MotionEvent.ACTION_DOWN:
            ((TextView)view).setTextColor(0xFFFFFFFF); //white
                break;
            case MotionEvent.ACTION_CANCEL:
            case MotionEvent.ACTION_UP:
            ((TextView)view).setTextColor(0xFF000000); //black
                break;
    }
        return false;
    }
}

Then you can assign this to whatever TextView you wish:

newTextView.setOnTouchListener(new CustomTouchListener());


问:
how to use 'actions-on-google' libray in aws lambda
In actions-on-google , both the request and response object need to provide as input to this library. but in lambda function, only the request object exists.

So how can i override it ?

in aws lambda the format is

```<code>exports.handler = function (event, context, callback) { // event is the request object , the response is provided using the callback() functon
}
</code>```

the actions-on-google object is created as :

```<code>const DialogflowApp = require('actions-on-google').DialogflowApp;
const app = new DialogflowApp({ request: request, response: response });
</code>```

答:
This is only a half answer:
Ok, so I dont think I can tell you how to make the action on google sdk correct working on AWS Lambda.
Maybe its easy, I just dont know and need to read everything to know it.

My, "easy to go", but at the end you will maybe have more work solution, would be just interprete the request jsons by yourself and responde with a message as shown below

This here would be a extrem trivial javascript function to create a extrem trivial JSON response.

Parameters:
Message is the string you would like to add as answer.
Slots should be an array that can be used to bias the speech recognition.
(you can just give an empty array to this function if you dont want to bias the speech).

And State is any kind of serilizable javascript object this is for your self to maintain states or something else It will be transfered between all the intents.

This is an standard response on an speech request.
You can add other plattforms than speech for this, by adding different initial prompts please see the JSON tabs from the documentation:
https://developers.google.com/actions/assistant/responses#json

```<code>function answerWithMessage(message,slots,state){
      let newmessage = message.toLowerCase();
      let jsonResponse = {
            conversationToken: JSON.stringify(state),
            expectUserResponse: true,
            expectedInputs: [
                {
                    inputPrompt: {
                        initialPrompts: [
                            {
                                textToSpeech: newmessage
                            }
                        ],
                        noInputPrompts: []
                    },
                    possibleIntents: [
                        {
                            intent: "actions.intent.TEXT"
                        }
                    ],
                  speechBiasingHints: slots
                }
            ]
        };
      return JSON.stringify(jsonResponse,null, 4);
    }
</code>```

Body:
In actions-on-google , both the request and response object need to provide as input to this library. but in lambda function, only the request object exists.

So how can i override it ?

in aws lambda the format is

exports.handler = function (event, context, callback) { // event is the request object , the response is provided using the callback() functon
}

the actions-on-google object is created as :

const DialogflowApp = require('actions-on-google').DialogflowApp;
const app = new DialogflowApp({ request: request, response: response });

Body:
This is only a half answer:
Ok, so I dont think I can tell you how to make the action on google sdk correct working on AWS Lambda.
Maybe its easy, I just dont know and need to read everything to know it.

My, "easy to go", but at the end you will maybe have more work solution, would be just interprete the request jsons by yourself and responde with a message as shown below

This here would be a extrem trivial javascript function to create a extrem trivial JSON response.

Parameters:
Message is the string you would like to add as answer.
Slots should be an array that can be used to bias the speech recognition.
(you can just give an empty array to this function if you dont want to bias the speech).

And State is any kind of serilizable javascript object this is for your self to maintain states or something else It will be transfered between all the intents.

This is an standard response on an speech request.
You can add other plattforms than speech for this, by adding different initial prompts please see the JSON tabs from the documentation:
https://developers.google.com/actions/assistant/responses#json

function answerWithMessage(message,slots,state){
      let newmessage = message.toLowerCase();
      let jsonResponse = {
            conversationToken: JSON.stringify(state),
            expectUserResponse: true,
            expectedInputs: [
                {
                    inputPrompt: {
                        initialPrompts: [
                            {
                                textToSpeech: newmessage
                            }
                        ],
                        noInputPrompts: []
                    },
                    possibleIntents: [
                        {
                            intent: "actions.intent.TEXT"
                        }
                    ],
                  speechBiasingHints: slots
                }
            ]
        };
      return JSON.stringify(jsonResponse,null, 4);
    }


问:
Laravel dynamic scope only works first time
I'm missing something with how the global scopes work in Laravel 5.5.

In my controller, index , I am passing filters into a getter:

```<code>public function index(SaleFilters $filters)
{
    return new SaleCollection($this->getSales($filters));
}
</code>```

getSales:

```<code>protected function getSales(SaleFilters $filters)
{
    $sales = Sale::with('office')->filter($filters);

    return $sales->paginate(50);
}

protected function range($range)
{
    $dates = explode(" ", $range);
    if (count($dates) == 2) {
        $this->builder = Sale::with(['office', 'staff'])
            ->where('sale_date', '>=', $dates[0])
            ->where('sale_date', '<', $dates[1])
            ->orderBy('sale_date', 'desc');

        return $this->builder;
    }
    return false;
}
</code>```

I have a scope setup in the sale model as such, which I would have thought would apply to the above filter automatically ?  If not, do I have to reapply the same scope, duplicating the scope code in the filter ?

```<code>protected static function boot()
{
    parent::boot();

    $user = Auth::user();
    if (($user) && ($user['office_id'])) {
        return Sale::ofOffice($user['office_id'])->get();
    }
}

public function scopeOfOffice($query, $office)
{
    return $query->where('office_id', $office);
}
</code>```

So basically, IF the user has an office_id applied, it should apply the ofOffice scope, therefore it should only ever return the sales that apply to that office_id.

Basically it works on page load via axios GET request

```<code>Route::get('/sales', 'SalesController@index')->middleware('auth:api');

axios
    .get('api/sales/?range=" + this.rangeFilter)
</code>```

rangeFilter is basically a start and end date passed into the above filter query.

Can anyone shed some light on how the scopes really work or if anything is obvious as to why its not always working?  As I said, it works on page load where I provide default values for the rangeFilter, however when I change those days and it refetches via the same axios call, it seems to not be applying the scope, and I get ALL results instead of where office_id = 'x'

As far as i'm concerned, the range filter above would be executing on the first page load as well, so not sure why it would apply there, and not afterwards.

答:
You should not mix the use of dynamic scope with global one. Also, static boot function does not expect a return. In order to use dynamic scope, you need to call it every time you need it. Hence, the name is dynamic. Query applied is not always executed by default. There so,

```<code>protected function getSales(SaleFilters $filters)
{
    $sales = Sale::ofOffice($anyOfficeHere)->with('office')->filter($filters);

    return $sales->paginate(50);
}
</code>```

To suit your existing code, you may want to add an if statement in your model. Then call the scope function without argument.

```<code>public function scopeOfOffice($q)
{
    if (($user = \Auth::user()) && ($office = $user->office_id)) {
       $q->where('office_id', $office);
    }
}

// Your controller
protected function getSales(SaleFilters $filters)
{
    $sales = Sale::ofOffice()->with('office')->filter($filters);

    return $sales->paginate(50);
}
</code>```

If you feel so much cumbersome to type ofOffice repeatedly. A global scope is the way to go. Within your model static boot function, you can also apply anonymous function if you feel creating a separated class kinda bloat your apps.

```<code>protected static function boot()
{
    parent::boot();

    static::addGlobalScope('officeOrWhatNot', function ($q) {
        if (($user = \Auth::user()) && ($office = $user->office_id)) {
            $q->where('office_id', $office);
        }
    });
}

// Your controller. No more `ofOffice`, it's automatically applied.
protected function getSales(SaleFilters $filters)
{
    $sales = Sale::with('office')->filter($filters);

    return $sales->paginate(50);
}
</code>```

Body:
I'm missing something with how the global scopes work in Laravel 5.5.

In my controller, index , I am passing filters into a getter:

public function index(SaleFilters $filters)
{
    return new SaleCollection($this->getSales($filters));
}

getSales:

protected function getSales(SaleFilters $filters)
{
    $sales = Sale::with('office')->filter($filters);

    return $sales->paginate(50);
}

protected function range($range)
{
    $dates = explode(" ", $range);
    if (count($dates) == 2) {
        $this->builder = Sale::with(['office', 'staff'])
            ->where('sale_date', '>=', $dates[0])
            ->where('sale_date', '<', $dates[1])
            ->orderBy('sale_date', 'desc');

        return $this->builder;
    }
    return false;
}

I have a scope setup in the sale model as such, which I would have thought would apply to the above filter automatically ?  If not, do I have to reapply the same scope, duplicating the scope code in the filter ?

protected static function boot()
{
    parent::boot();

    $user = Auth::user();
    if (($user) && ($user['office_id'])) {
        return Sale::ofOffice($user['office_id'])->get();
    }
}

public function scopeOfOffice($query, $office)
{
    return $query->where('office_id', $office);
}

So basically, IF the user has an office_id applied, it should apply the ofOffice scope, therefore it should only ever return the sales that apply to that office_id.

Basically it works on page load via axios GET request

Route::get('/sales', 'SalesController@index')->middleware('auth:api');

axios
    .get('api/sales/?range=" + this.rangeFilter)

rangeFilter is basically a start and end date passed into the above filter query.

Can anyone shed some light on how the scopes really work or if anything is obvious as to why its not always working?  As I said, it works on page load where I provide default values for the rangeFilter, however when I change those days and it refetches via the same axios call, it seems to not be applying the scope, and I get ALL results instead of where office_id = 'x'

As far as i'm concerned, the range filter above would be executing on the first page load as well, so not sure why it would apply there, and not afterwards.

Body:
You should not mix the use of dynamic scope with global one. Also, static boot function does not expect a return. In order to use dynamic scope, you need to call it every time you need it. Hence, the name is dynamic. Query applied is not always executed by default. There so,

protected function getSales(SaleFilters $filters)
{
    $sales = Sale::ofOffice($anyOfficeHere)->with('office')->filter($filters);

    return $sales->paginate(50);
}

To suit your existing code, you may want to add an if statement in your model. Then call the scope function without argument.

public function scopeOfOffice($q)
{
    if (($user = \Auth::user()) && ($office = $user->office_id)) {
       $q->where('office_id', $office);
    }
}

// Your controller
protected function getSales(SaleFilters $filters)
{
    $sales = Sale::ofOffice()->with('office')->filter($filters);

    return $sales->paginate(50);
}

If you feel so much cumbersome to type ofOffice repeatedly. A global scope is the way to go. Within your model static boot function, you can also apply anonymous function if you feel creating a separated class kinda bloat your apps.

protected static function boot()
{
    parent::boot();

    static::addGlobalScope('officeOrWhatNot', function ($q) {
        if (($user = \Auth::user()) && ($office = $user->office_id)) {
            $q->where('office_id', $office);
        }
    });
}

// Your controller. No more `ofOffice`, it's automatically applied.
protected function getSales(SaleFilters $filters)
{
    $sales = Sale::with('office')->filter($filters);

    return $sales->paginate(50);
}


问:
How to computed and add a new column in SQL
I have two tables

[Table_1] - Amount of money in a specific currency.

```<code>Currency  | Amount
USD       |  243
USD       |  212
USD       |  432
EUR       |  578
EUR       |  112
EUR       |  578
GBP       |  965
GBP       |  309
</code>```

And [Table_2] - Exchange rate EUR and GBP to USD

```<code>Cur |   FX
GBP | 1.43
EUR | 1.18
USD | 1
</code>```

I need to permanently add a new column [Amount in USD] into [Table_1] which converts all currencies into USD. Basically I need the corresponding currencies to be multiplied by the exchange rates given in [Table_2]. The final result should look like this.

```<code>Currency  | Amount  |Amount in USD
USD       |   243   |   243
USD       |   212   |   212
USD       |   432   |   432
EUR       |   578   |   682
EUR       |   112   |   132
EUR       |   578   |   682
GBP       |   965   |   1380
GBP       |   309   |   442
</code>```

I would appreciate if someone could help out. Thanks in advance.

答:
Try This

```<code>CREATE  TABLE #Currency (Currency NVARCHAR(10),AMOUNT INT)
CREATE TABLE #Exchange_Rate (Currency NVARCHAR(10),FX DECIMAL(15,2))

INSERT INTO #Exchange_Rate
SELECT 'GBP', 1.43    UNION ALL
SELECT 'EUR', 1.18     UNION ALL
SELECT 'USD' , 1

INSERT INTO #Currency
SELECT 'USD' ,243   UNION ALL
SELECT 'USD',212    UNION ALL
SELECT 'USD', 432   UNION ALL
SELECT 'EUR',578    UNION ALL
SELECT 'EUR',112    UNION ALL
SELECT 'EUR', 578   UNION ALL
SELECT 'GBP', 965   UNION ALL
SELECT 'GBP',309

SELECT * FROM #Exchange_Rate

SELECT a.Currency,AMOUNT,a.AMOUNT * b.FX [Amount IN USD]
FROM #Currency a INNER JOIN #Exchange_Rate b ON a.Currency=b.Currency
</code>```

Body:
I have two tables

[Table_1] - Amount of money in a specific currency.

Currency  | Amount
USD       |  243
USD       |  212
USD       |  432
EUR       |  578
EUR       |  112
EUR       |  578
GBP       |  965
GBP       |  309

And [Table_2] - Exchange rate EUR and GBP to USD

Cur |   FX
GBP | 1.43
EUR | 1.18
USD | 1

I need to permanently add a new column [Amount in USD] into [Table_1] which converts all currencies into USD. Basically I need the corresponding currencies to be multiplied by the exchange rates given in [Table_2]. The final result should look like this.

Currency  | Amount  |Amount in USD
USD       |   243   |   243
USD       |   212   |   212
USD       |   432   |   432
EUR       |   578   |   682
EUR       |   112   |   132
EUR       |   578   |   682
GBP       |   965   |   1380
GBP       |   309   |   442

I would appreciate if someone could help out. Thanks in advance.

Body:
Try This

CREATE  TABLE #Currency (Currency NVARCHAR(10),AMOUNT INT)
CREATE TABLE #Exchange_Rate (Currency NVARCHAR(10),FX DECIMAL(15,2))

INSERT INTO #Exchange_Rate
SELECT 'GBP', 1.43    UNION ALL
SELECT 'EUR', 1.18     UNION ALL
SELECT 'USD' , 1

INSERT INTO #Currency
SELECT 'USD' ,243   UNION ALL
SELECT 'USD',212    UNION ALL
SELECT 'USD', 432   UNION ALL
SELECT 'EUR',578    UNION ALL
SELECT 'EUR',112    UNION ALL
SELECT 'EUR', 578   UNION ALL
SELECT 'GBP', 965   UNION ALL
SELECT 'GBP',309

SELECT * FROM #Exchange_Rate

SELECT a.Currency,AMOUNT,a.AMOUNT * b.FX [Amount IN USD]
FROM #Currency a INNER JOIN #Exchange_Rate b ON a.Currency=b.Currency