问:
Copy table from Excel into Outlook and send to multiple people in Excel sheet
I want to copy a table (with all formatting intact) from Excel into an email and then send separate emails to people on a list in Excel. Ron de Bruin has two sets of code on his website.

One does the first part, while the other does the second part. How can I combine these?

http://www.rondebruin.nl/win/s1/outlook/bmail2.htm

```<code>Sub Mail_Selection_Range_Outlook_Body()
'For Tips see: http://www.rondebruin.nl/win/winmail/Outlook/tips.htm
'Don't forget to copy the function RangetoHTML in the module.
'Working in Excel 2000-2016
    Dim rng As Range
    Dim OutApp As Object
    Dim OutMail As Object

    Set rng = Nothing
    On Error Resume Next
    'Only the visible cells in the selection
    Set rng = Selection.SpecialCells(xlCellTypeVisible)
    'You can also use a fixed range if you want

    On Error GoTo 0

    If rng Is Nothing Then
        MsgBox "The selection is not a range or the sheet is protected" & _
               vbNewLine & "please correct and try again.", vbOKOnly
        Exit Sub
    End If

    With Application
        .EnableEvents = False
        .ScreenUpdating = False
    End With

    Set OutApp = CreateObject("Outlook.Application")
    Set OutMail = OutApp.CreateItem(0)

    On Error Resume Next
    With OutMail
        .To = "ron@debruin.nl"
        .CC = ""
        .BCC = ""
        .Subject = "This is the Subject line"
        .HTMLBody = RangetoHTML(rng)
        .Send   'or use .Display
    End With
    On Error GoTo 0

    With Application
        .EnableEvents = True
        .ScreenUpdating = True
    End With

    Set OutMail = Nothing
    Set OutApp = Nothing
End Sub
</code>```

http://www.rondebruin.nl/win/s1/outlook/bmail5.htm

```<code>Sub Test1()
'For Tips see: http://www.rondebruin.nl/win/winmail/Outlook/tips.htm
'Working in Office 2000-2016
    Dim OutApp As Object
    Dim OutMail As Object
    Dim cell As Range

    Application.ScreenUpdating = False
    Set OutApp = CreateObject("Outlook.Application")

    On Error GoTo cleanup
    For Each cell In Columns("B").Cells.SpecialCells(xlCellTypeConstants)
        If cell.Value Like "?*@?*.?*" And _
           LCase(Cells(cell.Row, "C").Value) = "yes" Then

            Set OutMail = OutApp.CreateItem(0)
            On Error Resume Next
            With OutMail
                .To = cell.Value
                .Subject = "Reminder"
                .Body = "Dear " & Cells(cell.Row, "A").Value _
                      & vbNewLine & vbNewLine & _
                        "Please contact us to discuss bringing " & _
                        "your account up to date"
                'You can add files also like this
                '.Attachments.Add ("C:\test.txt")
                .Send  'Or use Display
            End With
            On Error GoTo 0
            Set OutMail = Nothing
        End If
    Next cell

cleanup:
    Set OutApp = Nothing
    Application.ScreenUpdating = True
End Sub
</code>```

答:
Simply replace the following

```<code>Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(0)

On Error Resume Next
With OutMail
    .To = "ron@debruin.nl"
    .CC = ""
    .BCC = ""
    .Subject = "This is the Subject line"
    .HTMLBody = RangetoHTML(rng)
    .Send   'or use .Display
End With
On Error GoTo 0
</code>```

With this

```<code>Set OutApp = CreateObject("Outlook.Application")

For Each cell In Columns("B").Cells.SpecialCells(xlCellTypeConstants)
    If cell.Value Like "?*@?*.?*" And _
       LCase(Cells(cell.Row, "C").Value) = "yes" Then

        Set OutMail = OutApp.CreateItem(0)
        On Error Resume Next
        With OutMail
            .To = cell.Value
            .Subject = "Reminder"
            .Body = "Dear " & Cells(cell.Row, "A").Value _
                  & vbNewLine & vbNewLine & _
                    "Please contact us to discuss bringing " & _
                    "your account up to date"
            'You can add files also like this
            '.Attachments.Add ("C:\test.txt")
            .Send  'Or use Display
        End With
        On Error GoTo 0
        Set OutMail = Nothing
    End If
Next cell
</code>```

Then change this

```<code>        .Body = "Dear " & Cells(cell.Row, "A").Value _
              & vbNewLine & vbNewLine & _
                "Please contact us to discuss bringing " & _
                "your account up to date"
</code>```

With this

```<code>.HTMLBody = RangetoHTML(rng)
</code>```

Body:
I want to copy a table (with all formatting intact) from Excel into an email and then send separate emails to people on a list in Excel. Ron de Bruin has two sets of code on his website.

One does the first part, while the other does the second part. How can I combine these?

http://www.rondebruin.nl/win/s1/outlook/bmail2.htm

Sub Mail_Selection_Range_Outlook_Body()
'For Tips see: http://www.rondebruin.nl/win/winmail/Outlook/tips.htm
'Don't forget to copy the function RangetoHTML in the module.
'Working in Excel 2000-2016
    Dim rng As Range
    Dim OutApp As Object
    Dim OutMail As Object

    Set rng = Nothing
    On Error Resume Next
    'Only the visible cells in the selection
    Set rng = Selection.SpecialCells(xlCellTypeVisible)
    'You can also use a fixed range if you want

    On Error GoTo 0

    If rng Is Nothing Then
        MsgBox "The selection is not a range or the sheet is protected" & _
               vbNewLine & "please correct and try again.", vbOKOnly
        Exit Sub
    End If

    With Application
        .EnableEvents = False
        .ScreenUpdating = False
    End With

    Set OutApp = CreateObject("Outlook.Application")
    Set OutMail = OutApp.CreateItem(0)

    On Error Resume Next
    With OutMail
        .To = "ron@debruin.nl"
        .CC = ""
        .BCC = ""
        .Subject = "This is the Subject line"
        .HTMLBody = RangetoHTML(rng)
        .Send   'or use .Display
    End With
    On Error GoTo 0

    With Application
        .EnableEvents = True
        .ScreenUpdating = True
    End With

    Set OutMail = Nothing
    Set OutApp = Nothing
End Sub

http://www.rondebruin.nl/win/s1/outlook/bmail5.htm

Sub Test1()
'For Tips see: http://www.rondebruin.nl/win/winmail/Outlook/tips.htm
'Working in Office 2000-2016
    Dim OutApp As Object
    Dim OutMail As Object
    Dim cell As Range

    Application.ScreenUpdating = False
    Set OutApp = CreateObject("Outlook.Application")

    On Error GoTo cleanup
    For Each cell In Columns("B").Cells.SpecialCells(xlCellTypeConstants)
        If cell.Value Like "?*@?*.?*" And _
           LCase(Cells(cell.Row, "C").Value) = "yes" Then

            Set OutMail = OutApp.CreateItem(0)
            On Error Resume Next
            With OutMail
                .To = cell.Value
                .Subject = "Reminder"
                .Body = "Dear " & Cells(cell.Row, "A").Value _
                      & vbNewLine & vbNewLine & _
                        "Please contact us to discuss bringing " & _
                        "your account up to date"
                'You can add files also like this
                '.Attachments.Add ("C:\test.txt")
                .Send  'Or use Display
            End With
            On Error GoTo 0
            Set OutMail = Nothing
        End If
    Next cell

cleanup:
    Set OutApp = Nothing
    Application.ScreenUpdating = True
End Sub

Body:
Simply replace the following

Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(0)

On Error Resume Next
With OutMail
    .To = "ron@debruin.nl"
    .CC = ""
    .BCC = ""
    .Subject = "This is the Subject line"
    .HTMLBody = RangetoHTML(rng)
    .Send   'or use .Display
End With
On Error GoTo 0

With this

Set OutApp = CreateObject("Outlook.Application")

For Each cell In Columns("B").Cells.SpecialCells(xlCellTypeConstants)
    If cell.Value Like "?*@?*.?*" And _
       LCase(Cells(cell.Row, "C").Value) = "yes" Then

        Set OutMail = OutApp.CreateItem(0)
        On Error Resume Next
        With OutMail
            .To = cell.Value
            .Subject = "Reminder"
            .Body = "Dear " & Cells(cell.Row, "A").Value _
                  & vbNewLine & vbNewLine & _
                    "Please contact us to discuss bringing " & _
                    "your account up to date"
            'You can add files also like this
            '.Attachments.Add ("C:\test.txt")
            .Send  'Or use Display
        End With
        On Error GoTo 0
        Set OutMail = Nothing
    End If
Next cell

Then change this

        .Body = "Dear " & Cells(cell.Row, "A").Value _
              & vbNewLine & vbNewLine & _
                "Please contact us to discuss bringing " & _
                "your account up to date"

With this

.HTMLBody = RangetoHTML(rng)


来源: stackexchange

问:
'Start rollout to beta' disabled in Play Store Developer Console
I am ready to send my first app to beta testers, so i click on 'Manage Beta' > 'Manage testers'

.

and 'Save' and 'Resume'

APK is uploaded > 'Review'

The review summary says 'This release is ready to be rolled out.', but the button labled with 'Start to rollout to beta' is disabled: .

答: Saranga is right from my experience.  Before I could send out a beta version I had to ensure I had the images under store listing included.  Just look at the side bar (see image) and see whats greyed out and thats where the problem was for me.

ContentLicense: CC BY-SA 4.0

ContentLicense: CC BY-SA 3.0


问:
pointer to object == pointer to first member?
Why does the if condition in the following code yield true?

```<code>struct A
{
    int firstMember;
} a1;

if (&a1 == static_cast<void*>(&a1.firstMember)) std::cout << "equal";
</code>```

I got a bit confused when reading Stroustrup's FAQ on empty classes, specifically the statement below:

```<code>if (p1 == p2) cout << "nice: good optimizer";
</code>```

答: Yes, you cannot depend on it. Especially, in 64 bit OS, compiler may adjust the addresses to account for alignment in memory.</p>

ContentLicense: CC BY-SA 2.5

Body:
Why does the if condition in the following code yield true?

struct A
{
    int firstMember;
} a1;

if (&a1 == static_cast<void*>(&a1.firstMember)) std::cout << "equal";

I got a bit confused when reading Stroustrup's FAQ on empty classes, specifically the statement below:

if (p1 == p2) cout << "nice: good optimizer";


问:
Python: How to import zip from a different directory
I am deploying some python scripts as Azure Web Jobs and ran into an issue with importing some shared modules (in the form of zip files). Everything works fine if I copy the zip files to the same directory as the script file. But if I move the zip files to a different directory, things stop working.

Now for the specifics.

1) This works

Directory structure:

```<code>App_data
  jobs
    continuous
      firstjob
        azure.zip
        job1.py
      secondjob
        azure.zip
        job2.py
</code>```

In job1.py (and job2.py), I add the following code:

```<code>  sys.path.insert(0, 'azure.zip')
  from azure.storage.blob import *
</code>```

1) This does NOT work

Directory structure:

```<code>App_data
  pylib
    azure.zip
  jobs
    continuous
      firstjob
        job1.py
      secondjob
        job2.py
</code>```

In job1.py (and job2.py), I add the following code:
  # Azure places the scripts one level lower than it appears in the solution, hence the extra '..'!

```<code>  lib_path = os.path.realpath('..\..\..\pylib')
  sys.path.insert(0, os.path.join(lib_path, 'azure.zip'))
  # I verified by printing sys.path that the correct path is added for azure.zip
  from azure.storage.blob import *
</code>```

This gives an import error. Any ideas?

答:
When the azure webjob is executed, the content of the directory is copied in a temp subdirectory of your website "data" folder (at the root /data).

If you put the zip file in the same folder than your Python script, it will be copied too. If not, you need to use the absolute path "/site/wwwroot/mysite/App_data/pylib/"

That should work !

Body:
I am deploying some python scripts as Azure Web Jobs and ran into an issue with importing some shared modules (in the form of zip files). Everything works fine if I copy the zip files to the same directory as the script file. But if I move the zip files to a different directory, things stop working.

Now for the specifics.

1) This works

Directory structure:

App_data
  jobs
    continuous
      firstjob
        azure.zip
        job1.py
      secondjob
        azure.zip
        job2.py

In job1.py (and job2.py), I add the following code:

  sys.path.insert(0, 'azure.zip')
  from azure.storage.blob import *

1) This does NOT work

Directory structure:

App_data
  pylib
    azure.zip
  jobs
    continuous
      firstjob
        job1.py
      secondjob
        job2.py

In job1.py (and job2.py), I add the following code:
  # Azure places the scripts one level lower than it appears in the solution, hence the extra '..'!

  lib_path = os.path.realpath('..\..\..\pylib')
  sys.path.insert(0, os.path.join(lib_path, 'azure.zip'))
  # I verified by printing sys.path that the correct path is added for azure.zip
  from azure.storage.blob import *

This gives an import error. Any ideas?


问:
Double Join Query Rails
I have three models, JobPosting, Job, and Organization. The relations are below:

An Organization has many Jobs.

A Job belongs to an Organization and has many JobPostings.

A JobPosting belongs to a Job.

A Job has an attribute called job_type, and I am able to find all of the JobPostings that are related to a Job with a specific job_type using the query:

```<code>JobPosting.joins(:job).where(jobs: { :job_type => 'volunteer' })
</code>```

But what I am struggling with is doing the same kind of thing but with an Organization attribute. A Organization has a attribute called department, how can I query for the JobPosting's that relate to an organization through a Job that has a specific department. The reason I am having trouble is because Organizations are essentially two levels up, whereas Job's are only one.

Any help would be greatly appreciated.

答:
You can join the two relations as follows:

```<code>JobPosting.
  joins(job: :organization).
  where(jobs: { job_type: 'volunteer' }, organizations: { organizations_attr1: 'value_to_test' })
</code>```

joins(job: :organization) ensures you have inner joins between job_postings, jobs and organizations tables correctly. Try executing this in the rails console with .to_sql to check the generated query if you want to explore how Rails performs joins.

Title: Double Join Query Rails

Body:
I have three models, JobPosting, Job, and Organization. The relations are below:

An Organization has many Jobs.

A Job belongs to an Organization and has many JobPostings.

A JobPosting belongs to a Job.

A Job has an attribute called job_type, and I am able to find all of the JobPostings that are related to a Job with a specific job_type using the query:

JobPosting.joins(:job).where(jobs: { :job_type => 'volunteer' })

But what I am struggling with is doing the same kind of thing but with an Organization attribute. A Organization has a attribute called department, how can I query for the JobPosting's that relate to an organization through a Job that has a specific department. The reason I am having trouble is because Organizations are essentially two levels up, whereas Job's are only one.

Any help would be greatly appreciated.

Body:
You can join the two relations as follows:

JobPosting.
  joins(job: :organization).
  where(jobs: { job_type: 'volunteer' }, organizations: { organizations_attr1: 'value_to_test' })

joins(job: :organization) ensures you have inner joins between job_postings, jobs and organizations tables correctly. Try executing this in the rails console with .to_sql to check the generated query if you want to explore how Rails performs joins.


问:
Spring boot - 2 JNDI configuration

Posted my current configuration

答:
```<code>@Configuration
public class Config {
    @Value("${spring.datasource.primary.jndi-name}")
    private String primaryJndiName;

    @Value("${spring.datasource.secondary.jndi-name}")
    private String secondaryJndiName;

    @Primary
    @Bean(destroyMethod = "") // destroy method is disabled for Weblogic update app ability
    public DataSource primaryDs() {
        JndiDataSourceLookup lookup = new JndiDataSourceLookup();
        return lookup.getDataSource(primaryJndiName);
    }

    @Bean(destroyMethod = "") // destroy method is disabled for Weblogic update app ability
    public DataSource secondaryDs() {
        JndiDataSourceLookup lookup = new JndiDataSourceLookup();
        return lookup.getDataSource(secondaryJndiName);
   }
}
</code>```

Title: Spring boot - 2 JNDI configuration

Body: Posted my current configuration


问:
For loop doesn't add correct amount of values to array
My for loop should be adding 9 values to an array, but for some reason stops on 6. This only happens when I use the square bracket syntax to add the key and value to the array. Here's the code:

```<code>       $sentences = $this->sentences($sentence);
    $n = count($sentences);
    echo $n;
    $values = array();
    for($i = 0; $i < $n; $i++){
        $s1 = $sentences[$i];
        for($j = 0; $j < $n; $j++){
            $s2 = $sentences[$j];
            $values[$i][$j] = $this->checkvalues($s1,$s2);
        }
    }
    $sentences_dic = array();
    $other = array();
    $otherTwo = array();
    for($i = 0; $i < $n; $i++){
        $score = 0;
        for($j = 0; $j < $n; $j++){
            $score = $score+$values[$i][$j];

        }
        $other[$i] = $score;
        $otherTwo[$i] = $sentences[$i];
        $sentences_dic[($sentences[$i])]=$score;
        var_dump($otherTwo);
    }
    //maybe need
    return $sentences_dic;
</code>```

I am not sure why this is happening. The array is only printing
Here is what it is printing. It should be printing the seventh, eigth and ninth terms but it isnt. All the terms it isn't adding were all able to print in the other and otherTwo arrays.

```<code>Array
(
[first] => banana
[second] => banana2
[third] => banana3
[fourth] => banana4
[fifth] => banana5
[sixth] => banana6
)
</code>```

when it should be printing all 9 values and keys. I don't understand why I am able to add all sentences and scores to their full extent(9) to two seperate arrays, but when I try to use square bracket syntax it only goes to 6.

答:
Given your output $sentences appears to be an array and has duplicates. Array keys must be unique and duplicate keys are overwritten.

You could do something like this for a multidimensional array:

```<code>if(isset($sentences_dic[$sentences[$i]])) {
     $sentences_dic[$sentences[$i]][] = $score;
} else {
     $sentences_dic[$sentences[$i]] = $score;
}
</code>```

Or to sum the scores of duplicates:

```<code>if(isset($sentences_dic[$sentences[$i]])) {
     $sentences_dic[$sentences[$i]] += $score;
} else {
     $sentences_dic[$sentences[$i]] = $score;
}
</code>```

Body:
My for loop should be adding 9 values to an array, but for some reason stops on 6. This only happens when I use the square bracket syntax to add the key and value to the array. Here's the code:

       $sentences = $this->sentences($sentence);
    $n = count($sentences);
    echo $n;
    $values = array();
    for($i = 0; $i < $n; $i++){
        $s1 = $sentences[$i];
        for($j = 0; $j < $n; $j++){
            $s2 = $sentences[$j];
            $values[$i][$j] = $this->checkvalues($s1,$s2);
        }
    }
    $sentences_dic = array();
    $other = array();
    $otherTwo = array();
    for($i = 0; $i < $n; $i++){
        $score = 0;
        for($j = 0; $j < $n; $j++){
            $score = $score+$values[$i][$j];

        }
        $other[$i] = $score;
        $otherTwo[$i] = $sentences[$i];
        $sentences_dic[($sentences[$i])]=$score;
        var_dump($otherTwo);
    }
    //maybe need
    return $sentences_dic;

I am not sure why this is happening. The array is only printing
Here is what it is printing. It should be printing the seventh, eigth and ninth terms but it isnt. All the terms it isn't adding were all able to print in the other and otherTwo arrays.

Array
(
[first] => banana
[second] => banana2
[third] => banana3
[fourth] => banana4
[fifth] => banana5
[sixth] => banana6
)

when it should be printing all 9 values and keys. I don't understand why I am able to add all sentences and scores to their full extent(9) to two seperate arrays, but when I try to use square bracket syntax it only goes to 6.

Body:
Given your output $sentences appears to be an array and has duplicates. Array keys must be unique and duplicate keys are overwritten.

You could do something like this for a multidimensional array:

if(isset($sentences_dic[$sentences[$i]])) {
     $sentences_dic[$sentences[$i]][] = $score;
} else {
     $sentences_dic[$sentences[$i]] = $score;
}

Or to sum the scores of duplicates:

if(isset($sentences_dic[$sentences[$i]])) {
     $sentences_dic[$sentences[$i]] += $score;
} else {
     $sentences_dic[$sentences[$i]] = $score;
}


问:
How to use group_by variable as an exclusion value with dplyr?
Let's say I have the following data frame:

```<code>(dat  = data_frame(v1 = c(rep("a", 3), rep("b", 3), rep("c", 4)), v2 = 1:10))
# A tibble: 10 × 2
#       v1    v2
#    <chr> <int>
# 1      a     1
# 2      a     2
# 3      a     3
# 4      b     4
# 5      b     5
# 6      b     6
# 7      c     7
# 8      c     8
# 9      c     9
# 10     c    10
</code>```

What I want to be able to do is compute a sum for each group (i.e. "a", "b", and "c") that is equal to the sum of v2 where v1 is not equal to the grouping value. So it should look like this:

```<code># A tibble: 3 × 2
#      v1   sum
#   <chr> <int>
# 1     a    49
# 2     b    40
# 3     c    21
</code>```

Based on what I've been seeing online, this looks like a job for do, but I can't wrap my head around how to achieve this. I thought it would look something like this:

```<code>x %>%
  group_by(v1) %>%
  do(data.frame(sum=sum(.$v2[x$v1 != unique(.$v1)])))
</code>```

But this just gives me a dataframe with sum equal to NA for all three groups. How would I go about doing this?

答:
You can nest and then index the list column negatively:

```<code>library(tidyverse)

dat %>% nest(v2) %>% mutate(sum = map_int(seq(n()), ~sum(unlist(data[-.x]))))

## # A tibble: 3 × 3
##      v1             data   sum
##   <chr>           <list> <int>
## 1     a <tibble [3 × 1]>    49
## 2     b <tibble [3 × 1]>    40
## 3     c <tibble [4 × 1]>    21
</code>```

The advantage of this approach is that it's really easy to save the original data and align the computed values with them.

Body:
Let's say I have the following data frame:

(dat  = data_frame(v1 = c(rep("a", 3), rep("b", 3), rep("c", 4)), v2 = 1:10))
# A tibble: 10 × 2
#       v1    v2
#    <chr> <int>
# 1      a     1
# 2      a     2
# 3      a     3
# 4      b     4
# 5      b     5
# 6      b     6
# 7      c     7
# 8      c     8
# 9      c     9
# 10     c    10

What I want to be able to do is compute a sum for each group (i.e. "a", "b", and "c") that is equal to the sum of v2 where v1 is not equal to the grouping value. So it should look like this:

# A tibble: 3 × 2
#      v1   sum
#   <chr> <int>
# 1     a    49
# 2     b    40
# 3     c    21

Based on what I've been seeing online, this looks like a job for do, but I can't wrap my head around how to achieve this. I thought it would look something like this:

x %>%
  group_by(v1) %>%
  do(data.frame(sum=sum(.$v2[x$v1 != unique(.$v1)])))

But this just gives me a dataframe with sum equal to NA for all three groups. How would I go about doing this?

Body:
You can nest and then index the list column negatively:

library(tidyverse)

dat %>% nest(v2) %>% mutate(sum = map_int(seq(n()), ~sum(unlist(data[-.x]))))

## # A tibble: 3 × 3
##      v1             data   sum
##   <chr>           <list> <int>
## 1     a <tibble [3 × 1]>    49
## 2     b <tibble [3 × 1]>    40
## 3     c <tibble [4 × 1]>    21

The advantage of this approach is that it's really easy to save the original data and align the computed values with them.


问:
Using Actors to exploit cores
I'm new to Scala in general and Actors in particular and my problem is so basic, the online resources I have found don't cover it.

I have a CPU-intensive, easily parallelized algorithm that will be run on an n-core machine (I don't know n).  How do I implement this in Actors so that all available cores address the problem?

The first way I thought of was to simple break the problem into m pieces (where m is some medium number like 10,000) and create m Actors, one for each piece, give each Actor its little piece and let 'em go.

Somehow, this struck me as inefficient.  Zillions of Actors just hanging around, waiting for some CPU love, pointlessly switching contexts...

Then I thought, make some smaller number of Actors, and feed each one several pieces.  The problem was, there's no reason to expect the pieces are the same size, so one core might get bogged down, with many of its tasks still queued, while other cores are idle.

I noodled around with a Supervisor that knew which Actors were busy, and eventually realized that this has to be a solved problem.  There must be a standard pattern (maybe even a standard library) for dealing with this very generic issue.  Any suggestions?

答:
You should look into Futures I think. In fact, you probably need a threadpool which simply queues threads when a max number of threads has been reached.

Here is a small example involving futures: http://blog.tackley.net/2010/01/scala-futures.html

I would also suggest that you don't pay too much attention to the context switching since you really can't do anything but rely on the underlying implementation. Of course a rule of thumb would be to keep the active threads around the number of physical cores, but as I noted above this could be handled by a threadpool with a fifo-queue.

NOTE that I don't know if Actors in general or futures are implemented with this kind of pool.

For thread pools, look at this: http://www.scala-lang.org/api/current/scala/concurrent/ThreadPoolRunner.html

and maybe this: http://www.scala-lang.org/api/current/scala/actors/scheduler/ResizableThreadPoolScheduler.html

Good luck

EDIT

Check out this piece of code using futures:

```<code>import scala.actors.Futures._

object FibFut {
  def fib(i: Int): Int = if (i < 2) 1 else fib(i - 1) + fib(i - 2)
  def main(args: Array[String]) {
    val fibs = for (i <- 0 to 42) yield future { fib(i) }
    for (future <- fibs) println(future())
  }
}
</code>```

It showcases a very good point about futures, namely that you decide in which order to receive the results (as opposed to the normal mailbox-system which employs a fifo-system i.e. the fastest actor sends his result first).

Title: Using Actors to exploit cores

Body:
You should look into Futures I think. In fact, you probably need a threadpool which simply queues threads when a max number of threads has been reached.

Here is a small example involving futures: http://blog.tackley.net/2010/01/scala-futures.html

I would also suggest that you don't pay too much attention to the context switching since you really can't do anything but rely on the underlying implementation. Of course a rule of thumb would be to keep the active threads around the number of physical cores, but as I noted above this could be handled by a threadpool with a fifo-queue.

NOTE that I don't know if Actors in general or futures are implemented with this kind of pool.

For thread pools, look at this: http://www.scala-lang.org/api/current/scala/concurrent/ThreadPoolRunner.html

and maybe this: http://www.scala-lang.org/api/current/scala/actors/scheduler/ResizableThreadPoolScheduler.html

Good luck

EDIT

Check out this piece of code using futures:

import scala.actors.Futures._

object FibFut {
  def fib(i: Int): Int = if (i < 2) 1 else fib(i - 1) + fib(i - 2)
  def main(args: Array[String]) {
    val fibs = for (i <- 0 to 42) yield future { fib(i) }
    for (future <- fibs) println(future())
  }
}

It showcases a very good point about futures, namely that you decide in which order to receive the results (as opposed to the normal mailbox-system which employs a fifo-system i.e. the fastest actor sends his result first).


问:
Creating Key/Value JSON object with random integers and Flask
I recently was asked for homework to expand upon a Flask application so that a route is created which will roll two dice and return the outcome as a JSON object.

I thought I had completed the program correctly but was disappointed to find out that what my code is producing is not a JSON object?

Would anyone know how I would take the code below and return the dice roll as a key/value pair? At this point in time when I visit the rolldice route the output is Jsonified as the sum of the two dice rolls. I'm not sure how I can turn this into a key/value pair. Any help is appreciated, thanks again.

Here is my code:

```<code>from flask import Flask
from flask import jsonify
app = Flask(__name__)

import json
import random

@app.route('/')
def hello_world():
    return 'Hello World!'

# Create a route and function for rolling dice.
@app.route('/rolldice')
def dieobject():
    # Define rollcount
    rollcount = []
    # Define the number of times we will roll two dice.
    for i in range(0, 1):
        # Define rolling two dice.
        two_dieobject = random.randint(1, 6) + random.randint(1, 6)
        # Take output of our dice roll and pass it to rollcount.
        rollcount.append(two_dieobject)
    # Return the value of rollcount as JSON Data.
    # Data will be presented as one integer which is the sum of two dice rolls.
    return jsonify(rollcount)

if __name__ == '__main__':
    app.debug = True
    app.run()
</code>```

And for those who asked here is the output I am recieving:

```<code>[
  7
]
</code>```

Where the integer presented is the sum of the two dice rolls.

答:
Maybe something like this. It does the rolls in a loop and adds them together using the sum function.

```<code>from flask import Flask, jsonify
import random

app = Flask(__name__)

def roll(numrolls=1):
    return sum(random.randint(1, 6) for _ in range(numrolls))

@app.route('/rolldice')
def dieobject():

    # make dictionary here
    return jsonify({'value': roll(numrolls=2), 'rolls': 2})

if __name__ == '__main__':
    app.run(debug=True)
</code>```

I expanded it a bit. It returns a the roll value and the number of dice used to get that value. You could expand it again to have the flask service take a parameter stating how many dice to roll if you wanted.

Output

```<code>{
  "rolls": 2,
  "value": 7
}
</code>```

Body:
I recently was asked for homework to expand upon a Flask application so that a route is created which will roll two dice and return the outcome as a JSON object.

I thought I had completed the program correctly but was disappointed to find out that what my code is producing is not a JSON object?

Would anyone know how I would take the code below and return the dice roll as a key/value pair? At this point in time when I visit the rolldice route the output is Jsonified as the sum of the two dice rolls. I'm not sure how I can turn this into a key/value pair. Any help is appreciated, thanks again.

Here is my code:

from flask import Flask
from flask import jsonify
app = Flask(__name__)

import json
import random

@app.route('/')
def hello_world():
    return 'Hello World!'

# Create a route and function for rolling dice.
@app.route('/rolldice')
def dieobject():
    # Define rollcount
    rollcount = []
    # Define the number of times we will roll two dice.
    for i in range(0, 1):
        # Define rolling two dice.
        two_dieobject = random.randint(1, 6) + random.randint(1, 6)
        # Take output of our dice roll and pass it to rollcount.
        rollcount.append(two_dieobject)
    # Return the value of rollcount as JSON Data.
    # Data will be presented as one integer which is the sum of two dice rolls.
    return jsonify(rollcount)

if __name__ == '__main__':
    app.debug = True
    app.run()

And for those who asked here is the output I am recieving:

[
  7
]

Where the integer presented is the sum of the two dice rolls.

Body:
Maybe something like this. It does the rolls in a loop and adds them together using the sum function.

from flask import Flask, jsonify
import random

app = Flask(__name__)

def roll(numrolls=1):
    return sum(random.randint(1, 6) for _ in range(numrolls))

@app.route('/rolldice')
def dieobject():

    # make dictionary here
    return jsonify({'value': roll(numrolls=2), 'rolls': 2})

if __name__ == '__main__':
    app.run(debug=True)

I expanded it a bit. It returns a the roll value and the number of dice used to get that value. You could expand it again to have the flask service take a parameter stating how many dice to roll if you wanted.

Output

{
  "rolls": 2,
  "value": 7
}


问:
Logout for GoogleApiClient in Android application
Using such code it is possible to link my app and use account.

```<code>if (mGoogleApiClient == null) {
            mGoogleApiClient = new GoogleApiClient.Builder(this)
                    .addApi(Plus.API)
                    .addApi(Drive.API)
                    .addScope(Drive.SCOPE_FILE)
                    .addScope(Drive.SCOPE_APPFOLDER)
                    .addConnectionCallbacks(this)
                    .addOnConnectionFailedListener(this)
                    .build();
        }
        mGoogleApiClient.connect();
</code>```

But is where any way to 'logout' from this account once activated or switch to a new one?

答:
clearDefaultAccount() doesn't work. For sign out and clear selected account use Auth.GoogleSignInApi.signOut() like this:

```<code>private GoogleApiClient mGoogleApiClient;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Build a GoogleApiClient with access to the Google Sign-In API and the
    // options specified by gso.
    mGoogleApiClient = new GoogleApiClient.Builder(getApplicationContext()) //Use app context to prevent leaks using activity
            //.enableAutoManage(this /* FragmentActivity */, connectionFailedListener)
            .addApi(Auth.GOOGLE_SIGN_IN_API)
            .build();
}

@Override
protected void onStart() {
    super.onStart();
    mGoogleApiClient.connect();
}

@Override
protected void onStop() {
    super.onStop();
    if (mGoogleApiClient.isConnected()) {
        mGoogleApiClient.disconnect();
    }
}

private void signOut() {
    if (mGoogleApiClient.isConnected()) {
        Auth.GoogleSignInApi.signOut(mGoogleApiClient);
        mGoogleApiClient.disconnect();
        mGoogleApiClient.connect();
    }
}
</code>```

Body:
Using such code it is possible to link my app and use account.

if (mGoogleApiClient == null) {
            mGoogleApiClient = new GoogleApiClient.Builder(this)
                    .addApi(Plus.API)
                    .addApi(Drive.API)
                    .addScope(Drive.SCOPE_FILE)
                    .addScope(Drive.SCOPE_APPFOLDER)
                    .addConnectionCallbacks(this)
                    .addOnConnectionFailedListener(this)
                    .build();
        }
        mGoogleApiClient.connect();

But is where any way to 'logout' from this account once activated or switch to a new one?

Body:
clearDefaultAccount() doesn't work. For sign out and clear selected account use Auth.GoogleSignInApi.signOut() like this:

private GoogleApiClient mGoogleApiClient;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Build a GoogleApiClient with access to the Google Sign-In API and the
    // options specified by gso.
    mGoogleApiClient = new GoogleApiClient.Builder(getApplicationContext()) //Use app context to prevent leaks using activity
            //.enableAutoManage(this /* FragmentActivity */, connectionFailedListener)
            .addApi(Auth.GOOGLE_SIGN_IN_API)
            .build();
}

@Override
protected void onStart() {
    super.onStart();
    mGoogleApiClient.connect();
}

@Override
protected void onStop() {
    super.onStop();
    if (mGoogleApiClient.isConnected()) {
        mGoogleApiClient.disconnect();
    }
}

private void signOut() {
    if (mGoogleApiClient.isConnected()) {
        Auth.GoogleSignInApi.signOut(mGoogleApiClient);
        mGoogleApiClient.disconnect();
        mGoogleApiClient.connect();
    }
}


问:
Inferring language attribute while traversing the dom
I'm working on a site where there there are multiple language attributes declared throughout it. I'm trying to extract all of the text from each language, but sometimes the language is inferred from a parent element, so each element itself may not have the attribute. Sometimes, the element which set the language attribute can be many levels above the node.

For example, if the website structure is like so (simplified):

```<code><html>
<body lang="en">
  <header lang="ko">
    <span>氏氏氏氏</span>
    <p lang="en">A whole new world</p>
  </header>
  <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit</p>
  <p lang="cn">也称乱数假文或者哑元文本</p>
  <p>Sed ut perspiciatis unde omnis iste natus error sit voluptatem</p>
  <footer lang="ja">
    <ul>
      <li>金金金金</li>
      <li>金或金或</li>
      <li lang="ko">중중중중중</li>
      <li>数假</li>
    </ul>
  <footer>
</body>
</html>
</body>
</code>```

Getting all of the elements that have the lang attribute is not a good solution, because then the nodes without a lang tag are no longer included. I've tried creating a solution with this code, but it does not work well if the parent was set many previous elements above. Perhaps there is a different approach I could take? Or maybe there is an adjustment to this solution that would work well?

```<code>var findTextNodesWithLangAttribute = function(parentNode, selectedLanguage){
    var treeWalker = document.createTreeWalker(
        parentNode,
        // Only consider nodes that are text nodes (nodeType 3)
        NodeFilter.SHOW_TEXT,
        // Object containing the function to use for the acceptNode method
        // of the NodeFilter
        { acceptNode: function(node) {
              // Logic to determine whether to accept, reject or skip node
              // In this case, only accept nodes that have content
              // other than whitespace
              if ( ! /^\s*$/.test(node.data) ) {
                    // Test the language attribute
                    if(node.parentElement.hasAttribute("lang")) {
                        var nodeLang = node.parentElement.attributes["lang"].value;
                    } else if(node.parentNode.parentElement.hasAttribute("lang")) {
          var nodeLang = node.parentNode.parentElement.attributes["lang"].value;
        } else if(node.parentElement.parentElement.hasAttribute("lang")) {
          var nodeLang = node.parentElement.parentElement.attributes["lang"].value;
                    };
                  if(nodeLang == selectedLanguage) {
                        return NodeFilter.FILTER_ACCEPT;
                    }
              }
          }
        },
        false
    );

    var nodeList = [];

    while(treeWalker.nextNode()) nodeList.push(treeWalker.currentNode);

    return nodeList;
}
</code>```

答:
You will have to backtrack up the parent path to find the nearest parent with a lang and see if it matches with the requested language. Here is a snippet that has the modifications to your code.

var findTextNodesWithLangAttribute = function(parentNode, selectedLanguage) {
  var treeWalker = document.createTreeWalker(
    parentNode,
    // Only consider nodes that are text nodes (nodeType 3)
    NodeFilter.SHOW_TEXT,
    // Object containing the function to use for the acceptNode method
    // of the NodeFilter
    {
      acceptNode: function(node) {
        // Logic to determine whether to accept, reject or skip node
        // In this case, only accept nodes that have content
        // other than whitespace
        if (!/^\s*$/.test(node.data)) {
          // Test the language attribute
          var nearestParentWithLang = node.parentElement;
          if (!nearestParentWithLang.hasAttribute("lang")) {
            nearestParentWithLang = _findNearestParentElementWithLang(node.parentElement);
          }
          if ( nearestParentWithLang.attributes["lang"].value == selectedLanguage) {
            return NodeFilter.FILTER_ACCEPT;
          }
        }
      }
    },
    false
  );

  var nodeList = [];

  while (treeWalker.nextNode()) nodeList.push(treeWalker.currentNode);

  return nodeList;
}

 function _findNearestParentElementWithLang(textParent) {
   if(!textParent) return textParent;
   while(textParent){
      if(textParent.hasAttribute("lang")) return textParent;
        else textParent = textParent.parentElement;
    }
 }

var langNodes = findTextNodesWithLangAttribute(document.body, "ja");

langNodes.forEach(function(val, ind) {
 console.log(val.nodeValue);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body lang="en">
  <header lang="ko">
    <span>氏氏氏氏氏</span>
    <p lang="en">A whole new world</p>
  </header>
  <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit</p>
  <p lang="cn">也称乱数假文或者哑元文本</p>
  <p>Sed ut perspiciatis unde omnis iste natus error sit voluptatem</p>
  <footer lang="ja">
    <ul>
      <li>金金金金</li>
      <li>金金金金</li>
      <li lang="ko">중중중중중</li>
    </ul>
  </footer>
</body></code>```

Body:
I'm working on a site where there there are multiple language attributes declared throughout it. I'm trying to extract all of the text from each language, but sometimes the language is inferred from a parent element, so each element itself may not have the attribute. Sometimes, the element which set the language attribute can be many levels above the node.

For example, if the website structure is like so (simplified):

    氏氏氏氏

A whole new world

Lorem ipsum dolor sit amet, consectetur adipiscing elit

也称乱数假文或者哑元文本

Sed ut perspiciatis unde omnis iste natus error sit voluptatem

金金金金

金或金或

중중중중중

数假

Getting all of the elements that have the lang attribute is not a good solution, because then the nodes without a lang tag are no longer included. I've tried creating a solution with this code, but it does not work well if the parent was set many previous elements above. Perhaps there is a different approach I could take? Or maybe there is an adjustment to this solution that would work well?

var findTextNodesWithLangAttribute = function(parentNode, selectedLanguage){
    var treeWalker = document.createTreeWalker(
        parentNode,
        // Only consider nodes that are text nodes (nodeType 3)
        NodeFilter.SHOW_TEXT,
        // Object containing the function to use for the acceptNode method
        // of the NodeFilter
        { acceptNode: function(node) {
              // Logic to determine whether to accept, reject or skip node
              // In this case, only accept nodes that have content
              // other than whitespace
              if ( ! /^\s*$/.test(node.data) ) {
                    // Test the language attribute
                    if(node.parentElement.hasAttribute("lang")) {
                        var nodeLang = node.parentElement.attributes["lang"].value;
                    } else if(node.parentNode.parentElement.hasAttribute("lang")) {
          var nodeLang = node.parentNode.parentElement.attributes["lang"].value;
        } else if(node.parentElement.parentElement.hasAttribute("lang")) {
          var nodeLang = node.parentElement.parentElement.attributes["lang"].value;
                    };
                  if(nodeLang == selectedLanguage) {
                        return NodeFilter.FILTER_ACCEPT;
                    }
              }
          }
        },
        false
    );

    var nodeList = [];

    while(treeWalker.nextNode()) nodeList.push(treeWalker.currentNode);

    return nodeList;
}

Body:
You will have to backtrack up the parent path to find the nearest parent with a lang and see if it matches with the requested language. Here is a snippet that has the modifications to your code.

var findTextNodesWithLangAttribute = function(parentNode, selectedLanguage) {
  var treeWalker = document.createTreeWalker(
    parentNode,
    // Only consider nodes that are text nodes (nodeType 3)
    NodeFilter.SHOW_TEXT,
    // Object containing the function to use for the acceptNode method
    // of the NodeFilter
    {
      acceptNode: function(node) {
        // Logic to determine whether to accept, reject or skip node
        // In this case, only accept nodes that have content
        // other than whitespace
        if (!/^\s*$/.test(node.data)) {
          // Test the language attribute
          var nearestParentWithLang = node.parentElement;
          if (!nearestParentWithLang.hasAttribute("lang")) {
            nearestParentWithLang = _findNearestParentElementWithLang(node.parentElement);
          }
          if ( nearestParentWithLang.attributes["lang"].value == selectedLanguage) {
            return NodeFilter.FILTER_ACCEPT;
          }
        }
      }
    },
    false
  );

  var nodeList = [];

  while (treeWalker.nextNode()) nodeList.push(treeWalker.currentNode);

  return nodeList;
}

 function _findNearestParentElementWithLang(textParent) {
   if(!textParent) return textParent;
   while(textParent){
      if(textParent.hasAttribute("lang")) return textParent;
        else textParent = textParent.parentElement;
    }
 }

var langNodes = findTextNodesWithLangAttribute(document.body, "ja");

langNodes.forEach(function(val, ind) {
 console.log(val.nodeValue);
});

<body lang="en">
  <header lang="ko">
    <span>氏氏氏氏氏</span>
    <p lang="en">A whole new world</p>
  </header>
  <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit</p>
  <p lang="cn">也称乱数假文或者哑元文本</p>
  <p>Sed ut perspiciatis unde omnis iste natus error sit voluptatem</p>
  <footer lang="ja">
    <ul>
      <li>金金金金</li>
      <li>金金金金</li>
      <li lang="ko">중중중중중</li>
    </ul>
  </footer>
</body>


问:
How do you inspect websocket traffic with Chrome Developer Tools?
I'm trying to inspect websocket traffic using Chrome Developer Tools. From my research it seems you should be able to see it using the network tab - and it even has a filter for 'ws'.

However I've been inspecting sites that I know are using websockets and can't find a way to inspect the messages being sent back and forth. Using Chrome v56, also tried Safari with no luck...

Does anyone know how this can be achieved?

答:
You need to reload the page with the network tab open and filter by type 'ws'. This will show you a connection being made with a websocket. You can then click on the connection to show the traffic being sent back and forth with the server on the 'Messages' tab

https://developer.chrome.com/docs/devtools/network/reference/#frames


问:
Fastest Way To Calculate Directory Sizes
what is the best and fastest way to calculate directory sizes? For example we will have the following structure:

```<code>/users
      /a
      /b
      /c
      /...
</code>```

We need the output to be per user directory:

```<code>a = 1224KB
b = 3533KB
c = 3324KB
...
</code>```

We plan on having tens maybe even hundred of thousands of directories under /users. The following shell command works:

```<code>du -cms /users/a | grep total | awk '{print $1}'
</code>```

But, we will have to call it N number of times. The entire point, is that the output; each users directory size will be stored in our database. Also, we would love to have it update as frequently as possible, but without blocking all the resources on the server. Is it even possible to have it calculate users directory size every minute? How about every 5 minutes?

Now that I am thinking about it some more, would it make sense to use node.js? That way, we can calculate directory sizes, and even insert into the database all in one transaction. We could do that as well in PHP and Python, but not sure it is as fast.

Thanks.

答:
I think what you are looking for is:

```<code>du -cm --max-depth=1 /users | awk '{user = substr($2,7,300);
>                                   ans = user ": " $1;
>                                   print ans}'
</code>```

The magic numbers 7 is taking away the substring /users/, and 300 is just an arbitrary big number (awk is not one of my best languages =D, but I am guessing that part is not going to be written in awk anyways.) It's faster since you don't involve greping for the total and the loop is contained inside du. I bet it can be done faster, but this should be fast enough.

Body:
what is the best and fastest way to calculate directory sizes? For example we will have the following structure:

/users
      /a
      /b
      /c
      /...

We need the output to be per user directory:

a = 1224KB
b = 3533KB
c = 3324KB
...

We plan on having tens maybe even hundred of thousands of directories under /users. The following shell command works:

du -cms /users/a | grep total | awk '{print $1}'

But, we will have to call it N number of times. The entire point, is that the output; each users directory size will be stored in our database. Also, we would love to have it update as frequently as possible, but without blocking all the resources on the server. Is it even possible to have it calculate users directory size every minute? How about every 5 minutes?

Now that I am thinking about it some more, would it make sense to use node.js? That way, we can calculate directory sizes, and even insert into the database all in one transaction. We could do that as well in PHP and Python, but not sure it is as fast.

Thanks.

Body:
I think what you are looking for is:

du -cm --max-depth=1 /users | awk '{user = substr($2,7,300);
>                                   ans = user ": " $1;
>                                   print ans}'

The magic numbers 7 is taking away the substring /users/, and 300 is just an arbitrary big number (awk is not one of my best languages =D, but I am guessing that part is not going to be written in awk anyways.) It's faster since you don't involve greping for the total and the loop is contained inside du. I bet it can be done faster, but this should be fast enough.


问:
Laravel BelongsToMany Yielding Nothing
I'm trying to get the output of a belongstoMany relationship between users and sections database, which are tied to User and Section model, respectively.

User model has this method:

```<code>public function section()
    {
        return $this->belongsToMany('App\Models\Section','user_section')->withTimestamps();
    }
</code>```

Section model has this method:

```<code>public function user()
    {
        return $this->belongsToMany('App\Models\User','user_section')->withTimestamps();
    }
</code>```

My user_section table looks like this:

```<code>+----+---------+------------+------------+------------+
| id | user_id | section_id | created_at | updated_at |
+----+---------+------------+------------+------------+
|  1 |       1 |          1 | NULL       | NULL       |
|  2 |       2 |          1 | NULL       | NULL       |
+----+---------+------------+------------+------------+
2 rows in set (0.00 sec)
</code>```

So why when I do this in the business logic:

```<code>$user = User::where("id",Auth::user()->id)->first(); //user with id of 1 in my case
return json_encode($user->section());
</code>```

Do I get {} as output?

答: $user->section() will return the BelongsToMany relationship instead of the model object itself. You can do $user->section instead to load the relationship and have the model returned.

Title: Laravel BelongsToMany Yielding Nothing

Body:
I'm trying to get the output of a belongstoMany relationship between users and sections database, which are tied to User and Section model, respectively.

User model has this method:

public function section()
    {
        return $this->belongsToMany('App\Models\Section','user_section')->withTimestamps();
    }

Section model has this method:

public function user()
    {
        return $this->belongsToMany('App\Models\User','user_section')->withTimestamps();
    }

My user_section table looks like this:

+----+---------+------------+------------+------------+
| id | user_id | section_id | created_at | updated_at |
+----+---------+------------+------------+------------+
|  1 |       1 |          1 | NULL       | NULL       |
|  2 |       2 |          1 | NULL       | NULL       |
+----+---------+------------+------------+------------+
2 rows in set (0.00 sec)

So why when I do this in the business logic:

$user = User::where("id",Auth::user()->id)->first(); //user with id of 1 in my case
return json_encode($user->section());

Do I get {} as output?


问:
Use CakePHP Http Client with Magento2 rest API search criteria
I'm trying to send a GET request to a local Magento2 rest API to get all the orders after a certain time.  I'm following http://devdocs.magento.com/guides/v2.1/howdoi/webapi/search-criteria.html#simple-search-using-a-timestamp. I'm using CakePHP 3.4's Http Client (https://book.cakephp.org/3.0/en/core-libraries/httpclient.html) and have successfully integrated with Magento using Oauth1 and have no problems with simpler GET requests like http://www.magento.dev.com/rest/V1/stockItems/:productSku. It is a problem with passing the search criteria. The response is always a 401 Invalid Signature.

Using Postman, I can get a valid response to http://www.magento.dev.com/rest/V1/orders?searchCriteria[filter_groups][0][filters][0][field]=created_at&searchCriteria[filter_groups][0][filters][0][value]=2016-07-01 00:00:00&searchCriteria[filter_groups][0][filters][0][condition_type]=gt

This is what I have so far/how I'm sending the request:

In Model/Table/OrdersTable.php:

```<code>public function importNewOrders(\App\Model\Entity\OauthIntegration $integrationDetails)
    {
       $this->OauthIntegrations = TableRegistry::get('OauthIntegrations');
       $this->Orders = TableRegistry::get('Orders');
       $timeCutOff = '2015-01-01 00:00:00';
       $search = [
           'searchCriteria' => [
                'filterGroups' => [
                    0 => [
                        'filters' => [
                            0 => [
                                'field' => 'created_at',
                                'value' => $timeCutOff,
                                'condition_type' => 'gt'
                            ]
                        ]
                    ]
                ]
           ]
        ];
//           'searchCriteria[filter_groups][0][filters][0][field]' => 'created_at',
//           'searchCriteria[filter_groups][0][filters][0][value]' => $timeCutOff,
//           'searchCriteria[filter_groups][0][filters][0][condition_type]' => 'gt'

       $action = '/V1/orders';

       $type = "GET";
       $response = $this->OauthIntegrations->sendRequest(
               $integrationDetails,
               $action,
               $type,
               '',
               $search);

       Log::write('debug', $response->body());
       return $response;
    }
</code>```

and in Model\Table\OauthIntegrationsTable.php:

```<code>public function sendRequest(\App\Model\Entity\OauthIntegration $integrationDetails,
            string $action, string $method = "GET", string $data = '', array $search = null)
    {

        $http = new Client([
            'auth' => [
                'type' => 'oauth',
                'consumerKey' => $integrationDetails->oauth_consumer_key,
                'consumerSecret' => $integrationDetails->oauth_consumer_secret,
                'token' => $integrationDetails->oauth_token,
                'tokenSecret' => $integrationDetails->oauth_token_secret
              ]
          ]);
        $url = $integrationDetails->store_base_url . 'rest' . $action;
        if ($method == 'GET'){
            if (!isset($search)){
                $search = [];
            }
            $response = $http->get($url, $search, []);

        } else if ($method == 'POST'){

            $response = $http->post($url, $data, [
              'type' => 'json',

            ]);

        } else if($method == 'PUT'){
            $response = $http->put($url, $data, [
              'type' => 'json',
            ]);
        }
        Log::write('debug', 'url: ' . $url . ' and status code: ' . $response->getStatusCode());
        return $response;
    }
</code>```

and this is the error (I'm hoping) is the cause of the Invalid Signature response:

```<code>2017-03-28 10:07:01 Notice: Notice (8): Array to string conversion in [/var/www/cakephp/html/beacon/vendor/cakephp/cakephp/src/Http/Client/Auth/Oauth.php, line 315]
Trace:
Cake\Error\BaseErrorHandler::handleError() - CORE/src/Error/BaseErrorHandler.php, line 153
Cake\Http\Client\Auth\Oauth::_normalizedParams() - CORE/src/Http/Client/Auth/Oauth.php, line 315
Cake\Http\Client\Auth\Oauth::baseString() - CORE/src/Http/Client/Auth/Oauth.php, line 246
Cake\Http\Client\Auth\Oauth::_hmacSha1() - CORE/src/Http/Client/Auth/Oauth.php, line 143
Cake\Http\Client\Auth\Oauth::authentication() - CORE/src/Http/Client/Auth/Oauth.php, line 61
Cake\Http\Client::_addAuthentication() - CORE/src/Http/Client.php, line 501
Cake\Http\Client::_createRequest() - CORE/src/Http/Client.php, line 448
Cake\Http\Client::_doRequest() - CORE/src/Http/Client.php, line 341
Cake\Http\Client::get() - CORE/src/Http/Client.php, line 211
App\Model\Table\OauthIntegrationsTable::sendRequest() - APP/Model/Table/OauthIntegrationsTable.php, line 134
App\Model\Table\OrdersTable::importNewOrders() - APP/Model/Table/OrdersTable.php, line 672
App\Shell\MagentoShell::main() - APP/Shell/MagentoShell.php, line 36
Cake\Console\Shell::runCommand() - CORE/src/Console/Shell.php, line 472
Cake\Console\ShellDispatcher::_dispatch() - CORE/src/Console/ShellDispatcher.php, line 227
Cake\Console\ShellDispatcher::dispatch() - CORE/src/Console/ShellDispatcher.php, line 182
Cake\Console\ShellDispatcher::run() - CORE/src/Console/ShellDispatcher.php, line 128
[main] - ROOT/bin/cake.php, line 33
</code>```

Code from Http\Client\Oauth.php where error occurs:

```<code>        $pairs = [];
        foreach ($args as $k => $val) {
            if (is_array($val)) {
                sort($val, SORT_STRING);
                Log::write('debug', 'about to go through foreach($val as $nestedVal)');
                foreach ($val as $nestedVal) {
                    Log::write('debug', $nestedVal);
                    $pairs[] = "$k=$nestedVal"; // <<< HERE
                }
            } else {
                $pairs[] = "$k=$val";
            }
        }
</code>```

debugging from above results in:

```<code>2017-03-28 10:07:01 Debug: about to go through foreach($val as $nestedVal)
2017-03-28 10:07:01 Debug: Array
(
    [0] => Array
        (
            [filters] => Array
                (
                    [0] => Array
                        (
                            [field] => created_at
                            [value] => 2015-01-01 00:00:00
                            [condition_type] => gt
                        )

                )

        )

)
</code>```

In summary, is it possible to pass a multi-dimensional array to the 2nd parameter in a get request using Cake's Http Client?

```<code>// Is it possible to replace ['q' => 'widget'] with a multi-dimensional array??
$response = $http->get('http://example.com/search', ['q' => 'widget']);
</code>```

If not, what would be the best way to use Cake's Http Client to send GET request to: http://www.magento.dev.com/rest/V1/orders?searchCriteria[filter_groups][0][filters][0][field]=created_at&searchCriteria[filter_groups][0][filters][0][value]=2016-07-01 00:00:00&searchCriteria[filter_groups][0][filters][0][condition_type]=gt ?

Thanks in advance!!!

答:
Possible bug

This may be considered as a possible bug. I don't think the OAuth specs take this PHP style bracket stuff in URLs into account, and therefore sorting/encoding the parameters is limited to flat key=value sets, ie a key would be

```<code>searchCriteria[filter_groups][0][filters][0][field]
</code>```

and the value would be

```<code>created_at
</code>```

The CakePHP OAuth adapter however parses the requests query string into a possibly deeply nested array structure, which will then fail, as it doesn't handle that case.

I'd suggest that you report this as a possible bug. Further problems may occour as encoding seems to be ment to be applied before sorting, where in the CakePHP implementation, additonal parameter encoding is applied after sorting (that may actually be fine though, I'm not sure).

Try a custom OAuth adapter as a workaround

Until this is being fixed/enhanced, you could use a custom OAuth adapter that handles things "properly" (whatever that means in this context). Here's a quick and dirty example (works for me with the Magento API).

Create src/Http/Client/Auth/AppOAuth.php

```<code><?php
namespace App\Http\Client\Auth;

use Cake\Http\Client\Auth\Oauth;

class AppOAuth extends Oauth
{
    protected function _normalizedParams($request, $oauthValues)
    {
        $query = parse_url($request->url(), PHP_URL_QUERY);
        parse_str($query, $queryArgs);

        $post = [];
        $body = $request->body();
        if (is_string($body) &&
            $request->getHeaderLine('content-type') === 'application/x-www-form-urlencoded'
        ) {
            parse_str($body, $post);
        }
        if (is_array($body)) {
            $post = $body;
        }

        $args = array_merge($queryArgs, $oauthValues, $post);
        $query = http_build_query($args);

        $args = [];
        foreach (explode('&', $query) as $value) {
            $pair = explode('=', $value, 2);
            $args[] =
                rawurlencode(rawurldecode($pair[0])) .
                '=' .
                rawurlencode(rawurldecode($pair[1]));
        }
        usort($args, 'strcmp');

        return implode('&', $args);
    }
}
</code>```

Compare to \Cake\Http\Client\Auth\Oauth::_normalizedParams()

Use it by specifying the classname in the type option for your client instance:

```<code>'type' => 'AppOAuth',
</code>```

ps

shouldn't it be filter_groups instead of filterGroups in your $search array?

Body:
I'm trying to send a GET request to a local Magento2 rest API to get all the orders after a certain time.  I'm following http://devdocs.magento.com/guides/v2.1/howdoi/webapi/search-criteria.html#simple-search-using-a-timestamp. I'm using CakePHP 3.4's Http Client (https://book.cakephp.org/3.0/en/core-libraries/httpclient.html) and have successfully integrated with Magento using Oauth1 and have no problems with simpler GET requests like http://www.magento.dev.com/rest/V1/stockItems/:productSku. It is a problem with passing the search criteria. The response is always a 401 Invalid Signature.

Using Postman, I can get a valid response to http://www.magento.dev.com/rest/V1/orders?searchCriteria[filter_groups][0][filters][0][field]=created_at&searchCriteria[filter_groups][0][filters][0][value]=2016-07-01 00:00:00&searchCriteria[filter_groups][0][filters][0][condition_type]=gt

This is what I have so far/how I'm sending the request:

In Model/Table/OrdersTable.php:

public function importNewOrders(\App\Model\Entity\OauthIntegration $integrationDetails)
    {
       $this->OauthIntegrations = TableRegistry::get('OauthIntegrations');
       $this->Orders = TableRegistry::get('Orders');
       $timeCutOff = '2015-01-01 00:00:00';
       $search = [
           'searchCriteria' => [
                'filterGroups' => [
                    0 => [
                        'filters' => [
                            0 => [
                                'field' => 'created_at',
                                'value' => $timeCutOff,
                                'condition_type' => 'gt'
                            ]
                        ]
                    ]
                ]
           ]
        ];
//           'searchCriteria[filter_groups][0][filters][0][field]' => 'created_at',
//           'searchCriteria[filter_groups][0][filters][0][value]' => $timeCutOff,
//           'searchCriteria[filter_groups][0][filters][0][condition_type]' => 'gt'

       $action = '/V1/orders';

       $type = "GET";
       $response = $this->OauthIntegrations->sendRequest(
               $integrationDetails,
               $action,
               $type,
               '',
               $search);

       Log::write('debug', $response->body());
       return $response;
    }

and in Model\Table\OauthIntegrationsTable.php:

public function sendRequest(\App\Model\Entity\OauthIntegration $integrationDetails,
            string $action, string $method = "GET", string $data = '', array $search = null)
    {

        $http = new Client([
            'auth' => [
                'type' => 'oauth',
                'consumerKey' => $integrationDetails->oauth_consumer_key,
                'consumerSecret' => $integrationDetails->oauth_consumer_secret,
                'token' => $integrationDetails->oauth_token,
                'tokenSecret' => $integrationDetails->oauth_token_secret
              ]
          ]);
        $url = $integrationDetails->store_base_url . 'rest' . $action;
        if ($method == 'GET'){
            if (!isset($search)){
                $search = [];
            }
            $response = $http->get($url, $search, []);

        } else if ($method == 'POST'){

            $response = $http->post($url, $data, [
              'type' => 'json',

            ]);

        } else if($method == 'PUT'){
            $response = $http->put($url, $data, [
              'type' => 'json',
            ]);
        }
        Log::write('debug', 'url: ' . $url . ' and status code: ' . $response->getStatusCode());
        return $response;
    }

and this is the error (I'm hoping) is the cause of the Invalid Signature response:

2017-03-28 10:07:01 Notice: Notice (8): Array to string conversion in [/var/www/cakephp/html/beacon/vendor/cakephp/cakephp/src/Http/Client/Auth/Oauth.php, line 315]
Trace:
Cake\Error\BaseErrorHandler::handleError() - CORE/src/Error/BaseErrorHandler.php, line 153
Cake\Http\Client\Auth\Oauth::_normalizedParams() - CORE/src/Http/Client/Auth/Oauth.php, line 315
Cake\Http\Client\Auth\Oauth::baseString() - CORE/src/Http/Client/Auth/Oauth.php, line 246
Cake\Http\Client\Auth\Oauth::_hmacSha1() - CORE/src/Http/Client/Auth/Oauth.php, line 143
Cake\Http\Client\Auth\Oauth::authentication() - CORE/src/Http/Client/Auth/Oauth.php, line 61
Cake\Http\Client::_addAuthentication() - CORE/src/Http/Client.php, line 501
Cake\Http\Client::_createRequest() - CORE/src/Http/Client.php, line 448
Cake\Http\Client::_doRequest() - CORE/src/Http/Client.php, line 341
Cake\Http\Client::get() - CORE/src/Http/Client.php, line 211
App\Model\Table\OauthIntegrationsTable::sendRequest() - APP/Model/Table/OauthIntegrationsTable.php, line 134
App\Model\Table\OrdersTable::importNewOrders() - APP/Model/Table/OrdersTable.php, line 672
App\Shell\MagentoShell::main() - APP/Shell/MagentoShell.php, line 36
Cake\Console\Shell::runCommand() - CORE/src/Console/Shell.php, line 472
Cake\Console\ShellDispatcher::_dispatch() - CORE/src/Console/ShellDispatcher.php, line 227
Cake\Console\ShellDispatcher::dispatch() - CORE/src/Console/ShellDispatcher.php, line 182
Cake\Console\ShellDispatcher::run() - CORE/src/Console/ShellDispatcher.php, line 128
[main] - ROOT/bin/cake.php, line 33

Code from Http\Client\Oauth.php where error occurs:

        $pairs = [];
        foreach ($args as $k => $val) {
            if (is_array($val)) {
                sort($val, SORT_STRING);
                Log::write('debug', 'about to go through foreach($val as $nestedVal)');
                foreach ($val as $nestedVal) {
                    Log::write('debug', $nestedVal);
                    $pairs[] = "$k=$nestedVal"; // <<< HERE
                }
            } else {
                $pairs[] = "$k=$val";
            }
        }

debugging from above results in:

2017-03-28 10:07:01 Debug: about to go through foreach($val as $nestedVal)
2017-03-28 10:07:01 Debug: Array
(
    [0] => Array
        (
            [filters] => Array
                (
                    [0] => Array
                        (
                            [field] => created_at
                            [value] => 2015-01-01 00:00:00
                            [condition_type] => gt
                        )

                )

        )

)

In summary, is it possible to pass a multi-dimensional array to the 2nd parameter in a get request using Cake's Http Client?

// Is it possible to replace ['q' => 'widget'] with a multi-dimensional array??
$response = $http->get('http://example.com/search', ['q' => 'widget']);

If not, what would be the best way to use Cake's Http Client to send GET request to: http://www.magento.dev.com/rest/V1/orders?searchCriteria[filter_groups][0][filters][0][field]=created_at&searchCriteria[filter_groups][0][filters][0][value]=2016-07-01 00:00:00&searchCriteria[filter_groups][0][filters][0][condition_type]=gt ?

Thanks in advance!!!

Body:
Possible bug

This may be considered as a possible bug. I don't think the OAuth specs take this PHP style bracket stuff in URLs into account, and therefore sorting/encoding the parameters is limited to flat key=value sets, ie a key would be

searchCriteria[filter_groups][0][filters][0][field]

and the value would be

created_at

The CakePHP OAuth adapter however parses the requests query string into a possibly deeply nested array structure, which will then fail, as it doesn't handle that case.

I'd suggest that you report this as a possible bug. Further problems may occour as encoding seems to be ment to be applied before sorting, where in the CakePHP implementation, additonal parameter encoding is applied after sorting (that may actually be fine though, I'm not sure).

Try a custom OAuth adapter as a workaround

Until this is being fixed/enhanced, you could use a custom OAuth adapter that handles things "properly" (whatever that means in this context). Here's a quick and dirty example (works for me with the Magento API).

Create src/Http/Client/Auth/AppOAuth.php

<?php
namespace App\Http\Client\Auth;

use Cake\Http\Client\Auth\Oauth;

class AppOAuth extends Oauth
{
    protected function _normalizedParams($request, $oauthValues)
    {
        $query = parse_url($request->url(), PHP_URL_QUERY);
        parse_str($query, $queryArgs);

        $post = [];
        $body = $request->body();
        if (is_string($body) &&
            $request->getHeaderLine('content-type') === 'application/x-www-form-urlencoded'
        ) {
            parse_str($body, $post);
        }
        if (is_array($body)) {
            $post = $body;
        }

        $args = array_merge($queryArgs, $oauthValues, $post);
        $query = http_build_query($args);

        $args = [];
        foreach (explode('&', $query) as $value) {
            $pair = explode('=', $value, 2);
            $args[] =
                rawurlencode(rawurldecode($pair[0])) .
                '=' .
                rawurlencode(rawurldecode($pair[1]));
        }
        usort($args, 'strcmp');

        return implode('&', $args);
    }
}

Compare to \Cake\Http\Client\Auth\Oauth::_normalizedParams()

Use it by specifying the classname in the type option for your client instance:

'type' => 'AppOAuth',

ps

shouldn't it be filter_groups instead of filterGroups in your $search array?


问:
Android: Setting a Variable to a spinner item for later use
So I am trying to Work on a tutorial to learn how to code in C# for mobile applications. I have been working on a tutorial that was originally inteded for Windows Forms and I have been trying to format the code into an android version so I can test it on my phone.
What I am currently having issues with is grabbing a value from a spinner and using it later. What I would like to do is grab a "weapon" from a spinner, and then use that weapon to do damage to a monster.
The original code looked like this for Windows Forms:

```<code> private void btnUseWeapon_Click(object sender, EventArgs e)
        {
            // Get the currently selected weapon from the cboWeapons ComboBox
            Weapon currentWeapon = (Weapon)cboWeapons.SelectedItem;

            // Determine the amount of damage to do to the monster
            int damageToMonster = RandomNumberGenerator.NumberBetween(currentWeapon.MinimumDamage, currentWeapon.MaximumDamage);

            // Apply the damage to the monster's CurrentHitPoints
            _currentMonster.CurrentHitPoints -= damageToMonster;

            // Display message
            rtbMessages.Text += "You hit the " + _currentMonster.Name + " for " + damageToMonster.ToString() + " points." + Environment.NewLine;

            // Check if the monster is dead
            if(_currentMonster.CurrentHitPoints <= 0)
            {
                // Monster is dead
                rtbMessages.Text += Environment.NewLine;
                rtbMessages.Text += "You defeated the " + _currentMonster.Name + Environment.NewLine;

                // Give player experience points for killing the monster
                _player.ExperiencePoints += _currentMonster.RewardExperiencePoints;
                rtbMessages.Text += "You receive " + _currentMonster.RewardExperiencePoints.ToString() + " experience points" + Environment.NewLine;

                // Give player gold for killing the monster
                _player.Gold += _currentMonster.RewardGold;
                rtbMessages.Text += "You receive " + _currentMonster.RewardGold.ToString() + " gold" + Environment.NewLine;

                // Get random loot items from the monster
                List<InventoryItem> lootedItems = new List<InventoryItem>();

                // Add items to the lootedItems list, comparing a random number to the drop percentage
                foreach(LootItem lootItem in _currentMonster.LootTable)
                {
                    if(RandomNumberGenerator.NumberBetween(1, 100) <= lootItem.DropPercentage)
                    {
                        lootedItems.Add(new InventoryItem(lootItem.Details, 1));
                    }
                }

                // If no items were randomly selected, then add the default loot item(s).
                if(lootedItems.Count == 0)
                {
                    foreach(LootItem lootItem in _currentMonster.LootTable)
                    {
                        if(lootItem.IsDefaultItem)
                        {
                            lootedItems.Add(new InventoryItem(lootItem.Details, 1));
                        }
                    }
                }

                // Add the looted items to the player's inventory
                foreach(InventoryItem inventoryItem in lootedItems)
                {
                    _player.AddItemToInventory(inventoryItem.Details);

                    if(inventoryItem.Quantity == 1)
                    {
                        rtbMessages.Text += "You loot " + inventoryItem.Quantity.ToString() + " " + inventoryItem.Details.Name +Environment.NewLine;
                    }
                    else
                    {
                        rtbMessages.Text += "You loot " + inventoryItem.Quantity.ToString() + " " + inventoryItem.Details.NamePlural + Environment.NewLine;
                    }
                }

                // Refresh player information and inventory controls
                lblHitPoints.Text = _player.CurrentHitPoints.ToString();
                lblGold.Text = _player.Gold.ToString();
                lblExperience.Text = _player.ExperiencePoints.ToString();
                lblLevel.Text = _player.Level.ToString();

                UpdateInventoryListInUI();
                UpdateWeaponListInUI();
                UpdatePotionListInUI();

                // Add a blank line to the messages box, just for appearance.
                rtbMessages.Text += Environment.NewLine;

                // Move player to current location (to heal player and create a new monster to fight)
                MoveTo(_player.CurrentLocation);
            }
            else
            {
                // Monster is still alive

                // Determine the amount of damage the monster does to the player
                int damageToPlayer = RandomNumberGenerator.NumberBetween(0, _currentMonster.MaximumDamage);

                // Display message
                rtbMessages.Text += "The " + _currentMonster.Name + " did " + damageToPlayer.ToString() + " points of damage." + Environment.NewLine;

                // Subtract damage from player
                _player.CurrentHitPoints -= damageToPlayer;

                // Refresh player data in UI
                lblHitPoints.Text = _player.CurrentHitPoints.ToString();

                if(_player.CurrentHitPoints <= 0)
                {
                    // Display message
                    rtbMessages.Text += "The " + _currentMonster.Name + " killed you." + Environment.NewLine;

                    // Move player to "Home"
                    MoveTo(World.LocationByID(World.LOCATION_ID_HOME));
                }
            }
        }
</code>```

The cboWeapons in Windows Forms is a combobox.
I kept the same naming in my code but it is a spinner.

```<code>Spinner cboWeapons = (Spinner)FindViewById(Resource.Id.cboWeapons);
// Create an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter<Weapon> adapter = new ArrayAdapter<Weapon>(this,
Android.Resource.Layout.SimpleSpinnerItem, weapons);
adapter.SetDropDownViewResource(Android.Resource.Layout.SimpleSpinnerDropDownItem);
cboWeapons.Adapter = adapter;

public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
{
// On selecting a spinner item
object CurrentWeapon =parent.GetItemAtPosition(position);
 Weapon currentWeapon = new CurrentWeapon();
}
</code>```

My Weapon Class is defined in an Engine Project and I am having issues with making currentWeapon something that I can reference in the later code like the Windows Forms does.

答:
This is what I use to get selected item:

```<code>var TheSelectedIten = string.Format("{0}", SimpleSpinner.GetItemAtPosition(SimpleSpinner.SelectedItemPosition));
</code>```

It works for me on a spinner list of strings.

R/
Prescott ...

Body:
So I am trying to Work on a tutorial to learn how to code in C# for mobile applications. I have been working on a tutorial that was originally inteded for Windows Forms and I have been trying to format the code into an android version so I can test it on my phone.
What I am currently having issues with is grabbing a value from a spinner and using it later. What I would like to do is grab a "weapon" from a spinner, and then use that weapon to do damage to a monster.
The original code looked like this for Windows Forms:

 private void btnUseWeapon_Click(object sender, EventArgs e)
        {
            // Get the currently selected weapon from the cboWeapons ComboBox
            Weapon currentWeapon = (Weapon)cboWeapons.SelectedItem;

            // Determine the amount of damage to do to the monster
            int damageToMonster = RandomNumberGenerator.NumberBetween(currentWeapon.MinimumDamage, currentWeapon.MaximumDamage);

            // Apply the damage to the monster's CurrentHitPoints
            _currentMonster.CurrentHitPoints -= damageToMonster;

            // Display message
            rtbMessages.Text += "You hit the " + _currentMonster.Name + " for " + damageToMonster.ToString() + " points." + Environment.NewLine;

            // Check if the monster is dead
            if(_currentMonster.CurrentHitPoints <= 0)
            {
                // Monster is dead
                rtbMessages.Text += Environment.NewLine;
                rtbMessages.Text += "You defeated the " + _currentMonster.Name + Environment.NewLine;

                // Give player experience points for killing the monster
                _player.ExperiencePoints += _currentMonster.RewardExperiencePoints;
                rtbMessages.Text += "You receive " + _currentMonster.RewardExperiencePoints.ToString() + " experience points" + Environment.NewLine;

                // Give player gold for killing the monster
                _player.Gold += _currentMonster.RewardGold;
                rtbMessages.Text += "You receive " + _currentMonster.RewardGold.ToString() + " gold" + Environment.NewLine;

                // Get random loot items from the monster
                List<InventoryItem> lootedItems = new List<InventoryItem>();

                // Add items to the lootedItems list, comparing a random number to the drop percentage
                foreach(LootItem lootItem in _currentMonster.LootTable)
                {
                    if(RandomNumberGenerator.NumberBetween(1, 100) <= lootItem.DropPercentage)
                    {
                        lootedItems.Add(new InventoryItem(lootItem.Details, 1));
                    }
                }

                // If no items were randomly selected, then add the default loot item(s).
                if(lootedItems.Count == 0)
                {
                    foreach(LootItem lootItem in _currentMonster.LootTable)
                    {
                        if(lootItem.IsDefaultItem)
                        {
                            lootedItems.Add(new InventoryItem(lootItem.Details, 1));
                        }
                    }
                }

                // Add the looted items to the player's inventory
                foreach(InventoryItem inventoryItem in lootedItems)
                {
                    _player.AddItemToInventory(inventoryItem.Details);

                    if(inventoryItem.Quantity == 1)
                    {
                        rtbMessages.Text += "You loot " + inventoryItem.Quantity.ToString() + " " + inventoryItem.Details.Name +Environment.NewLine;
                    }
                    else
                    {
                        rtbMessages.Text += "You loot " + inventoryItem.Quantity.ToString() + " " + inventoryItem.Details.NamePlural + Environment.NewLine;
                    }
                }

                // Refresh player information and inventory controls
                lblHitPoints.Text = _player.CurrentHitPoints.ToString();
                lblGold.Text = _player.Gold.ToString();
                lblExperience.Text = _player.ExperiencePoints.ToString();
                lblLevel.Text = _player.Level.ToString();

                UpdateInventoryListInUI();
                UpdateWeaponListInUI();
                UpdatePotionListInUI();

                // Add a blank line to the messages box, just for appearance.
                rtbMessages.Text += Environment.NewLine;

                // Move player to current location (to heal player and create a new monster to fight)
                MoveTo(_player.CurrentLocation);
            }
            else
            {
                // Monster is still alive

                // Determine the amount of damage the monster does to the player
                int damageToPlayer = RandomNumberGenerator.NumberBetween(0, _currentMonster.MaximumDamage);

                // Display message
                rtbMessages.Text += "The " + _currentMonster.Name + " did " + damageToPlayer.ToString() + " points of damage." + Environment.NewLine;

                // Subtract damage from player
                _player.CurrentHitPoints -= damageToPlayer;

                // Refresh player data in UI
                lblHitPoints.Text = _player.CurrentHitPoints.ToString();

                if(_player.CurrentHitPoints <= 0)
                {
                    // Display message
                    rtbMessages.Text += "The " + _currentMonster.Name + " killed you." + Environment.NewLine;

                    // Move player to "Home"
                    MoveTo(World.LocationByID(World.LOCATION_ID_HOME));
                }
            }
        }

The cboWeapons in Windows Forms is a combobox.
I kept the same naming in my code but it is a spinner.

Spinner cboWeapons = (Spinner)FindViewById(Resource.Id.cboWeapons);
// Create an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter<Weapon> adapter = new ArrayAdapter<Weapon>(this,
Android.Resource.Layout.SimpleSpinnerItem, weapons);
adapter.SetDropDownViewResource(Android.Resource.Layout.SimpleSpinnerDropDownItem);
cboWeapons.Adapter = adapter;

public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
{
// On selecting a spinner item
object CurrentWeapon =parent.GetItemAtPosition(position);
 Weapon currentWeapon = new CurrentWeapon();
}

My Weapon Class is defined in an Engine Project and I am having issues with making currentWeapon something that I can reference in the later code like the Windows Forms does.

Body:
This is what I use to get selected item:

var TheSelectedIten = string.Format("{0}", SimpleSpinner.GetItemAtPosition(SimpleSpinner.SelectedItemPosition));

It works for me on a spinner list of strings.

R/
Prescott ...


问:
How can I view my HTML webpage in a mobile emulator and make my code more efficient?

var Person= {};

Person.Character= function(firstName, lastName, gender, age)
{
    this.FirstName= firstName;
    this.LastName= lastName;
    this.Gender= gender;
    this.Age= age;
}

Person.Character.prototype.GetAllInformation= function()
{
      return this.FirstName + " " + this.LastName + " "  + this.Gender + " "  +
       + this.Age;
}

Person.Zack = new Person.Character("Zack", "Efron", "Male", 29);
Person.Shia = new Person.Character("Shia", "Labeouf","Male", 30);

document.getElementById("demo1").innerHTML = Person.Zack.GetAllInformation();

document.getElementById("demo2").innerHTML = Person.Shia.GetAllInformation();```
<pre class="snippet-code-css lang-css prettyprint-override"><code>@media screen and (max-width: 320px)
{
    #demo1{ width: 100px;}
    #demo2{ width: 100px;}
}

@media only screen and (orientation: portrait) {
    body {
        background-color: red;
    }
}</code>```

<meta name="viewport" content="width=device-width">
<title></title>
<link rel="stylesheet" type="text/css" href="example-style.css">

```

Hello Everyone,

I have created a webpage and used CSS to handle media queries so when I view my webpage on a mobile emulator, it will become active when I reduce the width size of the screen or when the screen is turned to portrait form. So basically I want to know how I can view HTML my page on the emulator (it doesn't see to work with on this website(http://www.mobilephoneemulator.com/)) and if I am doing my media queries right? I know they are right so far, but is there a way that I can combine the two media queries into one media query? This would then reduce the code I have in CSS. I have attached the code I have done so far in HTML, CSS, and JavaScript for anyone's viewing.

答:
How to view your website as mobile on desktop:

Chrome

Just go to your html page and then follow these steps:

```<code>1. CTRL + SHIFT + J | Open Developer Console

2. CTRL + SHIFT + M (in Developer Console) | Mobile Device View

3. Use the drop down to select your mobile screen you wish to preview in
</code>```

Firefox (credit : Will)

```<code>1. Ctrl + Shift + M (Cmd + Opt + M for OS X)
</code>```

Body:
var Person= {};

Person.Character= function(firstName, lastName, gender, age)
{
    this.FirstName= firstName;
    this.LastName= lastName;
    this.Gender= gender;
    this.Age= age;
}

Person.Character.prototype.GetAllInformation= function()
{
      return this.FirstName + " " + this.LastName + " "  + this.Gender + " "  +
       + this.Age;
}

Person.Zack = new Person.Character("Zack", "Efron", "Male", 29);
Person.Shia = new Person.Character("Shia", "Labeouf","Male", 30);

document.getElementById("demo1").innerHTML = Person.Zack.GetAllInformation();

document.getElementById("demo2").innerHTML = Person.Shia.GetAllInformation();

@media screen and (max-width: 320px)
{
    #demo1{ width: 100px;}
    #demo2{ width: 100px;}
}

@media only screen and (orientation: portrait) {
    body {
        background-color: red;
    }
}

<meta name="viewport" content="width=device-width">
<title></title>
<link rel="stylesheet" type="text/css" href="example-style.css">

Hello Everyone,

I have created a webpage and used CSS to handle media queries so when I view my webpage on a mobile emulator, it will become active when I reduce the width size of the screen or when the screen is turned to portrait form. So basically I want to know how I can view HTML my page on the emulator (it doesn't see to work with on this website(http://www.mobilephoneemulator.com/)) and if I am doing my media queries right? I know they are right so far, but is there a way that I can combine the two media queries into one media query? This would then reduce the code I have in CSS. I have attached the code I have done so far in HTML, CSS, and JavaScript for anyone's viewing.

Body:
How to view your website as mobile on desktop:

Chrome

Just go to your html page and then follow these steps:

1. CTRL + SHIFT + J | Open Developer Console

2. CTRL + SHIFT + M (in Developer Console) | Mobile Device View

3. Use the drop down to select your mobile screen you wish to preview in

Firefox (credit : Will)

1. Ctrl + Shift + M (Cmd + Opt + M for OS X)


问:
Bash - How to check if command gave no output without printing it?
I am writing a testing script. It executes program with *.in files passed as input and compares its output with *.out files using diff command.

However, I don't want to print diff output, but to check if there is any and if so, then add *.in file name to the list of failed tests.

The problem is I have no idea how to check if command produces output without printing it.

My script now:

```<code>failed_tests=""

for filename in $directory/*.in; do

    command=< ${filename} ./${program} | diff - ${filename%.in}.out

    # Check if command produces output.
    if command; then
        # Add filename to failed tests list.
        failed_tests="${failed_tests} ${filename}"
    fi

done

echo $failed_tests
</code>```

Thank you in advance for all the answers.

答:
Your approach is doable, however you must capture $command in either `` or $(), also, $filename should act as input but not redirecting its contents. On the side note, you may want to remove the curly braces in the variable, it should work as long as the adjacent character is not a separator e.g. _

```<code>command=$(./$program $filename | diff - -q $filename%.in.out)
</code>```

-q option in diff means to report only when .out is differ. if without square brackets only works with a program or command with exit status. e.g. grep

```<code>if [[ -n $command ]]; then
    # Add filename to failed tests list.
    failed_tests="$failed_tests $filename"
fi
</code>```

-n option means not empty

Finally, the same approach outside of the loop:

```<code>if [[ -n $failed_tests ]]; then
    #do something here
fi
</code>```

Body:
I am writing a testing script. It executes program with *.in files passed as input and compares its output with *.out files using diff command.

However, I don't want to print diff output, but to check if there is any and if so, then add *.in file name to the list of failed tests.

The problem is I have no idea how to check if command produces output without printing it.

My script now:

failed_tests=""

for filename in $directory/*.in; do

    command=< ${filename} ./${program} | diff - ${filename%.in}.out

    # Check if command produces output.
    if command; then
        # Add filename to failed tests list.
        failed_tests="${failed_tests} ${filename}"
    fi

done

echo $failed_tests

Thank you in advance for all the answers.

Body:
Your approach is doable, however you must capture $command in either `` or $(), also, $filename should act as input but not redirecting its contents. On the side note, you may want to remove the curly braces in the variable, it should work as long as the adjacent character is not a separator e.g. _

command=$(./$program $filename | diff - -q $filename%.in.out)

-q option in diff means to report only when .out is differ. if without square brackets only works with a program or command with exit status. e.g. grep

if [[ -n $command ]]; then
    # Add filename to failed tests list.
    failed_tests="$failed_tests $filename"
fi

-n option means not empty

Finally, the same approach outside of the loop:

if [[ -n $failed_tests ]]; then
    #do something here
fi


问:
Time Complexity - solving T(n) equations
i need some help with calculating time complexity..
this is the equations:

```<code>i) T(n) = 2T(n-1)-T(n-2)+5n+7
ii) T(n)=T(n-1)+logn
iii) T(n) = 2T(√n)+logn
</code>```

my teacher tried to explain this but no one understand... i cant use the way of n^logba beacause of the B is 1... there is other way to solve those equations?

答:
It sounds like you are asking if there is some method that is as easy as the Master Theorem is for problems of the form T(n) = aT(n/b)+n^d

As you mentioned, you cannot use the Master Theorem because there is no b

I am sorry to tell you, that you will not find a Method that is nice like the Master Theorem. You will have to follow it for a few steps and see if you can find a pattern. It won't be easy like problems in the form aT(n/b)+n^d

Body:
i need some help with calculating time complexity..
this is the equations:

i) T(n) = 2T(n-1)-T(n-2)+5n+7
ii) T(n)=T(n-1)+logn
iii) T(n) = 2T(√n)+logn

my teacher tried to explain this but no one understand... i cant use the way of n^logba beacause of the B is 1... there is other way to solve those equations?


问:
Check if various checkboxes that have being created programmatically are checked when you click a button in android
My question is:
How I can check if the checkboxes are checked and how can I get its id or text in a onclick event?
I have done it whit RadioGroup, but RadioGroup only let me check 1 RadioButton, and in this case I need to check more than one, but if Im wrong and there is a way to do it with RadioGroup it should work for me.
Thanks for the help
Here is the code where I create the checkboxes programmatically:</p>

```<code>protected void onCreate(Bundle savedInstanceState) {

    LinearLayout lg = (LinearLayout) findViewById(R.id.lg);
    Button botonenv = (Button) findViewById(R.id.botonenv);

    try{
        myJson = new JSONObject(data);

        JSONArray Solutions = myJson.getJSONArray("solutions");

        for (int i = 0; i < Solutions.length(); i++) {

            JSONObject JSonSol = Solutions.getJSONObject(i);
            final String idSt = JSonSol.getString("id");
            final String name = JSonSol.getString("name");
            String resp = name.toUpperCase();

            CheckBox cb1 = new CheckBox(this);

            cb1.setText(resp);

            LinearLayout.LayoutParams llg = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
            llg.setMargins(0, 30, 0, 0);

            cb1.setTextSize(15);
            cb1.setTextColor(Color.parseColor("#FF000000"));

            lg.addView(cb1);

            int id =Integer.parseInt(idSt);
            cb1.setId(id);

        }

    }catch(JSONException e){
        e.printStackTrace();
    }

        botonenv.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

           //HERE I MUST NOW WHAT CHECKBOXES ARE CHECKED AND THEIR IDS

        ..............
        }
    });

}
</code>```

答:
Add their references to list , then you can reuse those reference again in any where outside after creation .
like
List<CheckBox> checkBoxes = new ArrayList<>();
add checkbox to your list wherever your create a new one      checkBoxes.add(cb1);
inside your onClick you can check all of them .

Body:
My question is:
How I can check if the checkboxes are checked and how can I get its id or text in a onclick event?
I have done it whit RadioGroup, but RadioGroup only let me check 1 RadioButton, and in this case I need to check more than one, but if Im wrong and there is a way to do it with RadioGroup it should work for me.
Thanks for the help
Here is the code where I create the checkboxes programmatically:

protected void onCreate(Bundle savedInstanceState) {

    LinearLayout lg = (LinearLayout) findViewById(R.id.lg);
    Button botonenv = (Button) findViewById(R.id.botonenv);

    try{
        myJson = new JSONObject(data);

        JSONArray Solutions = myJson.getJSONArray("solutions");

        for (int i = 0; i < Solutions.length(); i++) {

            JSONObject JSonSol = Solutions.getJSONObject(i);
            final String idSt = JSonSol.getString("id");
            final String name = JSonSol.getString("name");
            String resp = name.toUpperCase();

            CheckBox cb1 = new CheckBox(this);

            cb1.setText(resp);

            LinearLayout.LayoutParams llg = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
            llg.setMargins(0, 30, 0, 0);

            cb1.setTextSize(15);
            cb1.setTextColor(Color.parseColor("#FF000000"));

            lg.addView(cb1);

            int id =Integer.parseInt(idSt);
            cb1.setId(id);

        }

    }catch(JSONException e){
        e.printStackTrace();
    }

        botonenv.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

           //HERE I MUST NOW WHAT CHECKBOXES ARE CHECKED AND THEIR IDS

        ..............
        }
    });

}