问:
Where do you store user uploaded content within a Symfony 4 application?
I have a section within my site where the user can upload their own profile pictures which is stored in the output directory and tracked in the database like so:

```<code>    $form = $this->createForm(ProfileUpdateForm::class);
    $form->handleRequest($request);
    if ($form->isSubmitted() && $form->isValid())
    {
        $user = $this->getUser();
        $firstname = $form->get('firstname')->getData();
        $lastname = $form->get('lastname')->getData();
        $picture = $form->get('profilepicture')->getData();

        if($picture == null)
        {
            $user
            ->setFirstName($firstname)
            ->setLastName($lastname);
        }
        else
        {
            $originalFilename = pathinfo($picture->getClientOriginalName(), PATHINFO_FILENAME);
            // this is needed to safely include the file name as part of the URL
            $safeFilename = strtolower(str_replace(' ', '', $originalFilename));
            $newFilename = $safeFilename.'-'.uniqid().'.'.$picture->guessExtension();

            try {
                $picture->move(
                    'build/images/user_profiles/',
                    $newFilename
                );
            } catch (FileException $e) {
                $this->addFlash("error", "Something happened with the file upload, try again.");
                return $this->redirect($request->getUri());
            }

            // updates the 'picture' property to store the image file name
            // instead of its contents
            $user
            ->setProfilePicture($newFilename)
            ->setFirstName($firstname)
            ->setLastName($lastname);
        }

        $entityManager = $this->getDoctrine()->getManager();
        $entityManager->persist($user);
        $entityManager->flush();

        $this->addFlash("success", "Your profile was updated!");
        return $this->redirectToRoute('account');
    }

    return $this->render('account/profile.html.twig', [
        'profileform' => $form->createView()
    ]);
</code>```

That issue I've found is that every time I compile my (local) project, the image is then deleted (because the public/build directory gets built by deleting and creating again).

If I'm not mistaken, isn't that how deployments work too? And if so, is that the right way to upload an image? What's the right way of going about this?

答:
I'm not sure why, but your public/ directory shouldn't be deleted.

If you're using Webpack Encore, then public/build/ content is deleted and created again when you compile assets. But not public/ itself.

For uploads, we create public/upload/ directory.

Then, most of the time, we set some globals, which allow us to save the file name only.

Globals for Twig in config/packages/twig.yaml which "root" will be in your public/ directory

```<code>twig:
    globals:
        app_ul_avatar: '/upload/avatar/'
        app_ul_document: '/upload/document/'
</code>```

And globals for your controllers, repositories, etc in config/services.yaml

```<code>parameters:
    app_ul_avatar: '%kernel.root_dir%/../public/upload/avatar/'
    app_ul_document: '%kernel.root_dir%/../public/upload/document/'
</code>```

It's handy because, as I just said, you only get to save the file name in the database.

Which mean that, if you got a public/upload/img/ folder, and want to also generates thumbnails, you can then create public/upload/img/thumbnail/ and nothing will change in your database, nor do you have to save an extra path.

Just create a new global app_ul_img_thumbnail, and you're set.

Then all you have to do is call your globals when you need them, and contact with the file name:

In Twig:

```<code>{{ app_ul_avatar~dbResult.filename }}
</code>```

Or in Controller:

```<code>$this->getParameter('app_ul_avatar').$dbResult->getFilename();
</code>```

Body:
I have a section within my site where the user can upload their own profile pictures which is stored in the output directory and tracked in the database like so:

    $form = $this->createForm(ProfileUpdateForm::class);
    $form->handleRequest($request);
    if ($form->isSubmitted() && $form->isValid())
    {
        $user = $this->getUser();
        $firstname = $form->get('firstname')->getData();
        $lastname = $form->get('lastname')->getData();
        $picture = $form->get('profilepicture')->getData();

        if($picture == null)
        {
            $user
            ->setFirstName($firstname)
            ->setLastName($lastname);
        }
        else
        {
            $originalFilename = pathinfo($picture->getClientOriginalName(), PATHINFO_FILENAME);
            // this is needed to safely include the file name as part of the URL
            $safeFilename = strtolower(str_replace(' ', '', $originalFilename));
            $newFilename = $safeFilename.'-'.uniqid().'.'.$picture->guessExtension();

            try {
                $picture->move(
                    'build/images/user_profiles/',
                    $newFilename
                );
            } catch (FileException $e) {
                $this->addFlash("error", "Something happened with the file upload, try again.");
                return $this->redirect($request->getUri());
            }

            // updates the 'picture' property to store the image file name
            // instead of its contents
            $user
            ->setProfilePicture($newFilename)
            ->setFirstName($firstname)
            ->setLastName($lastname);
        }

        $entityManager = $this->getDoctrine()->getManager();
        $entityManager->persist($user);
        $entityManager->flush();

        $this->addFlash("success", "Your profile was updated!");
        return $this->redirectToRoute('account');
    }

    return $this->render('account/profile.html.twig', [
        'profileform' => $form->createView()
    ]);

That issue I've found is that every time I compile my (local) project, the image is then deleted (because the public/build directory gets built by deleting and creating again).

If I'm not mistaken, isn't that how deployments work too? And if so, is that the right way to upload an image? What's the right way of going about this?

Body:
I'm not sure why, but your public/ directory shouldn't be deleted.

If you're using Webpack Encore, then public/build/ content is deleted and created again when you compile assets. But not public/ itself.

For uploads, we create public/upload/ directory.

Then, most of the time, we set some globals, which allow us to save the file name only.

Globals for Twig in config/packages/twig.yaml which "root" will be in your public/ directory

twig:
    globals:
        app_ul_avatar: '/upload/avatar/'
        app_ul_document: '/upload/document/'

And globals for your controllers, repositories, etc in config/services.yaml

parameters:
    app_ul_avatar: '%kernel.root_dir%/../public/upload/avatar/'
    app_ul_document: '%kernel.root_dir%/../public/upload/document/'

It's handy because, as I just said, you only get to save the file name in the database.

Which mean that, if you got a public/upload/img/ folder, and want to also generates thumbnails, you can then create public/upload/img/thumbnail/ and nothing will change in your database, nor do you have to save an extra path.

Just create a new global app_ul_img_thumbnail, and you're set.

Then all you have to do is call your globals when you need them, and contact with the file name:

In Twig:

{{ app_ul_avatar~dbResult.filename }}

Or in Controller:

$this->getParameter('app_ul_avatar').$dbResult->getFilename();


来源: stackexchange

问:
Access the Resolve Value of a Promise
I have a promise that resolves a variable this.data in a Read Excel Service as shown below,

  parseExcel(excelFile): Promise<any>
  {
    /* wire up file reader */
    const target: DataTransfer = <DataTransfer>(excelFile.target);
    if (target.files.length !== 1) throw new Error('Cannot use multiple files');
    const reader: FileReader = new FileReader();
    return new Promise((resolve, reject) => {
        reader.onload = (e: any) =>
        {
          /* read workbook */
          const bstr: string = e.target.result;
          const wb: XLSX.WorkBook = XLSX.read(bstr, { type: 'binary' });

          /* grab first sheet */
          const wsname: string = wb.SheetNames[0];
          const ws: XLSX.WorkSheet = wb.Sheets[wsname];

          /* save data */
          this.data = <AOA>(XLSX.utils.sheet_to_json(ws, { header: 1 }));
          console.log("BOM PARSE SERVICE LOG: " , this.data)
          resolve(this.data);
        };
        reader.readAsBinaryString(target.files[0]);
    })
}
```

<p>I am now trying to access the resolved array here</p>

<pre class="lang-js prettyprint-override"><code>async ReadExcel(event)
  {
    return new Promise<Object>((resolve, reject) =>
    {
      var excelContents = this.parser.parseExcel(event).then(function(value)
      {
        return value
      }
      console.log("New Quote Component Log: ", excelContents)
      //need var excelContents to only contain the array and not contain the value of the promise object
    }
  )}
}
</code>```

the log statement in the latter function brings me back this...

Is there a way that I can have the variable excelContents only take on the value of the array rather than the entire value of the promise?

答:
Whatever you do, you will need to so something asynchronous to get the real, promised data. There is obviously no hope in getting it synchronously.

Your attempt with yet another new promise is not helping you to get any closer (in fact, it employs the promise constructor antipattern). Just do:

```<code>async ReadExcel(event) {
    var excelContents = await this.parser.parseExcel(event);
    console.log("New Quote Component Log: ", excelContents);
}
</code>```

To be clear: don't be tricked into thinking that returning excelContents in this latter function is going to give you synchronous access to it. That would not bring you any benefit, because you will need to await that returned value again, in yet another async function. So... this is it. Do everything you need to do with excelContents, right there, in that async function, after await.

ContentLicense: CC BY-SA 4.0

Title: Access the Resolve Value of a Promise

Body:
I have a promise that resolves a variable this.data in a Read Excel Service as shown below,

  parseExcel(excelFile): Promise<any>
  {
    /* wire up file reader */
    const target: DataTransfer = <DataTransfer>(excelFile.target);
    if (target.files.length !== 1) throw new Error('Cannot use multiple files');
    const reader: FileReader = new FileReader();
    return new Promise((resolve, reject) => {
        reader.onload = (e: any) =>
        {
          /* read workbook */
          const bstr: string = e.target.result;
          const wb: XLSX.WorkBook = XLSX.read(bstr, { type: 'binary' });

          /* grab first sheet */
          const wsname: string = wb.SheetNames[0];
          const ws: XLSX.WorkSheet = wb.Sheets[wsname];

          /* save data */
          this.data = <AOA>(XLSX.utils.sheet_to_json(ws, { header: 1 }));
          console.log("BOM PARSE SERVICE LOG: " , this.data)
          resolve(this.data);
        };
        reader.readAsBinaryString(target.files[0]);
    })
}

I am now trying to access the resolved array here

async ReadExcel(event)
  {
    return new Promise<Object>((resolve, reject) =>
    {
      var excelContents = this.parser.parseExcel(event).then(function(value)
      {
        return value
      }
      console.log("New Quote Component Log: ", excelContents)
      //need var excelContents to only contain the array and not contain the value of the promise object
    }
  )}
}

the log statement in the latter function brings me back this...

Is there a way that I can have the variable excelContents only take on the value of the array rather than the entire value of the promise?

Body:
Whatever you do, you will need to so something asynchronous to get the real, promised data. There is obviously no hope in getting it synchronously.

Your attempt with yet another new promise is not helping you to get any closer (in fact, it employs the promise constructor antipattern). Just do:

async ReadExcel(event) {
    var excelContents = await this.parser.parseExcel(event);
    console.log("New Quote Component Log: ", excelContents);
}

To be clear: don't be tricked into thinking that returning excelContents in this latter function is going to give you synchronous access to it. That would not bring you any benefit, because you will need to await that returned value again, in yet another async function. So... this is it. Do everything you need to do with excelContents, right there, in that async function, after await.


问:
Saving the output of a str_which loop in R
I work with a sheet of data that lists a variety of scientific publications. Rows are publications,
columns are a variety of metrics describing each publication (author name and position, Pubmed IDs, Date etc...)
I want to filter for publications for each author and extract parts of them. The caveat is the format:
all author names (5-80 per cell) are lumped together in one cell for each row.

I managed to solve this with the use of str_which, saving the coordinates for each author and later extract. This works only for manual use. When I try to automate this process using a loop to draw on a list of authors I fail to save the output.

I am at a bit of a loss on how to store the results without overwriting previous ones.

```<code>sampleDat <-
  data.frame(var1 = c("Doe J, Maxwell M, Kim HE", "Cronauer R, Carst W, Theobald U", "Theobald U, Hey B, Joff S"),
             var2 = c(1:3),
             var3 = c("2016-01", "2016-03", "2017-05"))
</code>```

list of names that I want the coordinates for

```<code>namesOfInterest <-
  list(c("Doe J", "Theobald U"))
</code>```

the manual extraction, requiring me to type the exact name and output object

```<code>Doe <- str_which(sampleDat$var1, "Doe J")
Theobald <- str_which(sampleDat$var1, "Theobald U")
</code>```

one of many attempts that does not replicate the manual version.

```<code>results <- c()

for (i in namesOfInterest) {
  results[i] <- str_which(sampleDat$var1, i)
}
</code>```

答:
The for loop is set up incorrectly (it needs to be something like for(i in 1:n){do something}). Also, even if you fix that, you'll get an error related to the fact that str_which returns a vector of varying length, indicating the position of each of the matches it makes (and it can make multiple matches). Thus, indexing a vector in a loop won't work here because whenever a author has multiple matches, more than one entry will be saved to a single element, throwing an error.

Solve this by working with lists, because lists can hold vectors of arbitrary length. Index the list with double bracket notation: [[.

```<code>library(stringr)
sampleDat <-
  data.frame(var1 = c("Doe J, Maxwell M, Kim HE", "Cronauer R, Carst W, Theobald U", "Theobald U, Hey B, Joff S"),
             var2 = c(1:3),
             var3 = c("2016-01", "2016-03", "2017-05"))

# no need for list here. a simple vector will do
namesOfInterest <- c("Doe J", "Theobald U")

# initalize list
results <- vector("list", length = length(namesOfInterest))

# loop over list, saving output of `str_which` in each list element.
# seq_along(x) is similar to 1:length(x)
for (i in seq_along(namesOfInterest)) {
  results[[i]] <- str_which(sampleDat$var1, namesOfInterest[i])
}
</code>```

which returns:

```<code>> results
[[1]]
[1] 1

[[2]]
[1] 2 3
</code>```

The way to understand the output above is that the ith element of the list, results[[i]] contains the output of str_which(sampleDat$var1, namesOfInterest[i]), where namesOfInterest[i] is always exactly one author. However, the length of results[[i]] can be longer than one:

```<code>> sapply(results, length)
[1] 1 2
</code>```

indicating that a single author can be mentioned multiple times. In the example above, sapply counts the length of each vector along the list results, showing that namesOfInterest[1] has one paper, and namesOfInterest[2] has 2. `

Body:
I work with a sheet of data that lists a variety of scientific publications. Rows are publications,
columns are a variety of metrics describing each publication (author name and position, Pubmed IDs, Date etc...)
I want to filter for publications for each author and extract parts of them. The caveat is the format:
all author names (5-80 per cell) are lumped together in one cell for each row.

I managed to solve this with the use of str_which, saving the coordinates for each author and later extract. This works only for manual use. When I try to automate this process using a loop to draw on a list of authors I fail to save the output.

I am at a bit of a loss on how to store the results without overwriting previous ones.

sampleDat <-
  data.frame(var1 = c("Doe J, Maxwell M, Kim HE", "Cronauer R, Carst W, Theobald U", "Theobald U, Hey B, Joff S"),
             var2 = c(1:3),
             var3 = c("2016-01", "2016-03", "2017-05"))

list of names that I want the coordinates for

namesOfInterest <-
  list(c("Doe J", "Theobald U"))

the manual extraction, requiring me to type the exact name and output object

Doe <- str_which(sampleDat$var1, "Doe J")
Theobald <- str_which(sampleDat$var1, "Theobald U")

one of many attempts that does not replicate the manual version.

results <- c()

for (i in namesOfInterest) {
  results[i] <- str_which(sampleDat$var1, i)
}

Body:
The for loop is set up incorrectly (it needs to be something like for(i in 1:n){do something}). Also, even if you fix that, you'll get an error related to the fact that str_which returns a vector of varying length, indicating the position of each of the matches it makes (and it can make multiple matches). Thus, indexing a vector in a loop won't work here because whenever a author has multiple matches, more than one entry will be saved to a single element, throwing an error.

Solve this by working with lists, because lists can hold vectors of arbitrary length. Index the list with double bracket notation: [[.

library(stringr)
sampleDat <-
  data.frame(var1 = c("Doe J, Maxwell M, Kim HE", "Cronauer R, Carst W, Theobald U", "Theobald U, Hey B, Joff S"),
             var2 = c(1:3),
             var3 = c("2016-01", "2016-03", "2017-05"))

# no need for list here. a simple vector will do
namesOfInterest <- c("Doe J", "Theobald U")

# initalize list
results <- vector("list", length = length(namesOfInterest))

# loop over list, saving output of `str_which` in each list element.
# seq_along(x) is similar to 1:length(x)
for (i in seq_along(namesOfInterest)) {
  results[[i]] <- str_which(sampleDat$var1, namesOfInterest[i])
}

which returns:

> results
[[1]]
[1] 1

[[2]]
[1] 2 3

The way to understand the output above is that the ith element of the list, results[[i]] contains the output of str_which(sampleDat$var1, namesOfInterest[i]), where namesOfInterest[i] is always exactly one author. However, the length of results[[i]] can be longer than one:

> sapply(results, length)
[1] 1 2

indicating that a single author can be mentioned multiple times. In the example above, sapply counts the length of each vector along the list results, showing that namesOfInterest[1] has one paper, and namesOfInterest[2] has 2. `


问:
How to reduce duplicate nested dictionary levels while serializing python object
I have an example python script below where, Market object has fruits object  which contains dictionary of different type of fruit objects.
While serializing the market object as shown below,

```<code>import json

class Fruit:
    def __init__(self, name, color):
        self.name = name
        self.color = color

    def __str__(self):
        return f"name:{self.name}, color:{self.color} \n"

    def as_dict(self):
        return self

class Fruits:
    def __init__(self):
        self.fruits = {}

    def add(self, name, color):
        fruit = Fruit(name, color)
        self.fruits[fruit.name] = fruit

    def __str__(self):
        text = ["Fruits: \n"]
        for exp_id in self.fruits:
            text.append(str(self.fruits[exp_id]))
        sep = ""
        return sep.join(text)

    def as_dict(self):
        return self.fruits

class Market:
    def __init__(self, name):
        self.name = name
        self.fruits = Fruits()

    def __str__(self):
        return f"Market name: {self.name}, \n Fruits: {str(self.fruits)}"

    def as_dict(self):
        return self

m= Market("Grocery market")
m.fruits.add("apple", "red")
m.fruits.add("banana", "yellow")
m.fruits.add("mango", "green")
js = (lambda x: x.__dict__)(m)
s = json.dumps(js, default=lambda x: x.__dict__)

print(s)
</code>```

the output json comes out as:

```<code>{
  "name": "Grocery market",
  "fruits": {
    "fruits": {
      "apple": { "name": "apple", "color": "red" },
      "banana": { "name": "banana", "color": "yellow" },
      "mango": { "name": "mango", "color": "green" }
    }
  }
}
</code>```

I am trying to reduce the 2 Fruits level to just 1 as shown below:

```<code>{
  "name": "Grocery market",
  "fruits": {
    "apple": { "name": "apple", "color": "red" },
    "banana": { "name": "banana", "color": "yellow" },
    "mango": { "name": "mango", "color": "green" }
  }
}
</code>```

I need help in understanding what would be the best way to go about it?
I tried overloading dict for fruits class, but realized it couldn't be overloaded.

Any help is appreciated.

答:
I would remove the Fruits class and add a method like the following in your market class:

```<code>def addFruit(self, name, color):
        self.fruits[name] = color
</code>```

Then you can call your methods like this:

```<code>m.addFruit("apple", "red")
m.addFruit("banana", "yellow")
m.addFruit("mango", "green")
</code>```

After doing it you get the following output:

```<code>{"name": "Grocery market", "fruits": {"apple": "red", "banana": "yellow", "mango": "green"}}
</code>```

Body:
I have an example python script below where, Market object has fruits object  which contains dictionary of different type of fruit objects.
While serializing the market object as shown below,

import json

class Fruit:
    def __init__(self, name, color):
        self.name = name
        self.color = color

    def __str__(self):
        return f"name:{self.name}, color:{self.color} \n"

    def as_dict(self):
        return self

class Fruits:
    def __init__(self):
        self.fruits = {}

    def add(self, name, color):
        fruit = Fruit(name, color)
        self.fruits[fruit.name] = fruit

    def __str__(self):
        text = ["Fruits: \n"]
        for exp_id in self.fruits:
            text.append(str(self.fruits[exp_id]))
        sep = ""
        return sep.join(text)

    def as_dict(self):
        return self.fruits

class Market:
    def __init__(self, name):
        self.name = name
        self.fruits = Fruits()

    def __str__(self):
        return f"Market name: {self.name}, \n Fruits: {str(self.fruits)}"

    def as_dict(self):
        return self

m= Market("Grocery market")
m.fruits.add("apple", "red")
m.fruits.add("banana", "yellow")
m.fruits.add("mango", "green")
js = (lambda x: x.__dict__)(m)
s = json.dumps(js, default=lambda x: x.__dict__)

print(s)

the output json comes out as:

{
  "name": "Grocery market",
  "fruits": {
    "fruits": {
      "apple": { "name": "apple", "color": "red" },
      "banana": { "name": "banana", "color": "yellow" },
      "mango": { "name": "mango", "color": "green" }
    }
  }
}

I am trying to reduce the 2 Fruits level to just 1 as shown below:

{
  "name": "Grocery market",
  "fruits": {
    "apple": { "name": "apple", "color": "red" },
    "banana": { "name": "banana", "color": "yellow" },
    "mango": { "name": "mango", "color": "green" }
  }
}

I need help in understanding what would be the best way to go about it?
I tried overloading dict for fruits class, but realized it couldn't be overloaded.

Any help is appreciated.

Body:
I would remove the Fruits class and add a method like the following in your market class:

def addFruit(self, name, color):
        self.fruits[name] = color

Then you can call your methods like this:

m.addFruit("apple", "red")
m.addFruit("banana", "yellow")
m.addFruit("mango", "green")

After doing it you get the following output:

{"name": "Grocery market", "fruits": {"apple": "red", "banana": "yellow", "mango": "green"}}


问:
Tar cannot expand subfolders from .tar archive
I'm trying to expand tarball native archive (not a Gzipped version) from bash script using separate commands for a reason.

Tar archive format:

```<code>File1
File2
folder1/file3
folder1/file4
</code>```

Then i execute next commands:

```<code>tar xvf archive.tar -C $TEMP_DIR/ File1
tar xvf archive.tar -C $TEMP_DIR/ File2
</code>```

Both succesful

Next I execute separate commands for file 3 and 4:

```<code>tar xvf archive.tar -C $TEMP_DIR/ folder1/file3
tar xvf archive.tar -C $TEMP_DIR/ folder1/file4
</code>```

Both fails for:

```<code>Tar: folder: Permission denied
Tar: file: No such file or directory
</code>```

Please advise!

答:
You need to make sure archive.tar is in the correct place,
Following script reproduce the whole process :</p>

```<code>#!/usr/bin/env bash
mkdir -p /tmp/{dest,src/folder1}
cd /tmp/src
touch File{1,2} folder1/file{3,4}

tar cvf ../archive.tar *

TEMP_DIR=/tmp/dest

cd /tmp
tar xvf archive.tar -C $TEMP_DIR/ File{1,2}
ls  -l $TEMP_DIR
read -pEnter
tar xvf archive.tar -C $TEMP_DIR/ folder1/file{3,4}
ls  -l $TEMP_DIR/folder1
</code>```

Body:
I'm trying to expand tarball native archive (not a Gzipped version) from bash script using separate commands for a reason.

Tar archive format:

File1
File2
folder1/file3
folder1/file4

Then i execute next commands:

tar xvf archive.tar -C $TEMP_DIR/ File1
tar xvf archive.tar -C $TEMP_DIR/ File2

Both succesful

Next I execute separate commands for file 3 and 4:

tar xvf archive.tar -C $TEMP_DIR/ folder1/file3
tar xvf archive.tar -C $TEMP_DIR/ folder1/file4

Both fails for:

Tar: folder: Permission denied
Tar: file: No such file or directory

Please advise!

Body:
You need to make sure archive.tar is in the correct place,
Following script reproduce the whole process :

#!/usr/bin/env bash
mkdir -p /tmp/{dest,src/folder1}
cd /tmp/src
touch File{1,2} folder1/file{3,4}

tar cvf ../archive.tar *

TEMP_DIR=/tmp/dest

cd /tmp
tar xvf archive.tar -C $TEMP_DIR/ File{1,2}
ls  -l $TEMP_DIR
read -pEnter
tar xvf archive.tar -C $TEMP_DIR/ folder1/file{3,4}
ls  -l $TEMP_DIR/folder1


问:
spyder4 - hide background variables in variable explorer on Mac?

I think that the variable explorer is showing background variables of spyder. How can I hide them?

答: (Spyder maintainer here) Unfortunately, those variables can't be hidden anymore. And that's a good thing because it's a reminder that you're importing pylab by default in your consoles (which is a bad practice because your code won't be portable outside Spyder).


问:
Create a WCF Proxy for a Rest Web Service
I have a complex WCF Rest service which take multiple inputs and objects. I cannot simply call it by doing an HTTP POST in Fiddler because there is too much data to provide (I could, but it will take me forever). So I would like to do it in code using a proxy. Is there a way to generate a proxy for a .NET 4 WCF Rest Service? Otherwise, what do you propose to allow me to easily test the service?

Thanks.

答:
You can create a proxy using the same steps you would for a non-RESTful WCF service:</p>

```<code>// Create the proxy
ChannelFactory<IContract> channelFactory = new ChannelFactory<IContract>("endpointName");
var restfulProxy = factory.CreateChannel();

// Invoke a method
var response = proxy.MyRestfulMethod("param1", "param2");
</code>```

ContentLicense: CC BY-SA 3.0

Body:
You can create a proxy using the same steps you would for a non-RESTful WCF service:

// Create the proxy
ChannelFactory<IContract> channelFactory = new ChannelFactory<IContract>("endpointName");
var restfulProxy = factory.CreateChannel();

// Invoke a method
var response = proxy.MyRestfulMethod("param1", "param2");


问:
Making app to count time since first time used
How to make an app to count the time since the first time opened? I have no idea which class to use. Is it possible to achieve this with a stopwatch or something similar? Can someone pls share some code? I don't know what to search on the internet just have an idea of what I want to build. Or just tell me an idea with what I can achieve this and how?</p>

```<code> statisticLayout.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
          if (plusiliminus==0){
              Toast.makeText(getActivity(),R.string.toaststatistic,Toast.LENGTH_SHORT).show();
          } else {
              Fragment fragmentstatistic=new Statistic();
              FragmentTransaction transaction=getActivity().getSupportFragmentManager().beginTransaction();
              transaction.replace(R.id.frameLayout,fragmentstatistic).commit();
          }
      }
  });
</code>```

答:
You have basically to do two things.

Get the current time when you start the app, or press a button using something like

```<code>Date currentTime = Calendar.getInstance().getTime();
</code>```

This is a good beginning, you get the time, then you have to parse this time in a format you want to show to the user then you manage a stop and reset button as showed for instance in this tutorial

So you build a TextView and you show in real time the seconds, parsed in the way you need

```<code>import android.os.Handler;
import android.os.SystemClock;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    TextView timer ;
    Button start, pause, reset;
    long MillisecondTime, StartTime, TimeBuff, UpdateTime = 0L ;
    Handler handler;
    int Seconds, Minutes, MilliSeconds ;

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

        timer = (TextView)findViewById(R.id.tvTimer);
        start = (Button)findViewById(R.id.btStart);
        pause = (Button)findViewById(R.id.btPause);
        reset = (Button)findViewById(R.id.btReset);

        handler = new Handler() ;

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

                StartTime = SystemClock.uptimeMillis();
                handler.postDelayed(runnable, 0);

                reset.setEnabled(false);

            }
        });

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

                TimeBuff += MillisecondTime;

                handler.removeCallbacks(runnable);

                reset.setEnabled(true);

            }
        });

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

                MillisecondTime = 0L ;
                StartTime = 0L ;
                TimeBuff = 0L ;
                UpdateTime = 0L ;
                Seconds = 0 ;
                Minutes = 0 ;
                MilliSeconds = 0 ;

                timer.setText("00:00:00");

            }
        });

    }

    public Runnable runnable = new Runnable() {

        public void run() {

            MillisecondTime = SystemClock.uptimeMillis() - StartTime;

            UpdateTime = TimeBuff + MillisecondTime;

            Seconds = (int) (UpdateTime / 1000);

            Minutes = Seconds / 60;

            Seconds = Seconds % 60;

            MilliSeconds = (int) (UpdateTime % 1000);

            timer.setText("" + Minutes + ":"
                    + String.format("%02d", Seconds) + ":"
                    + String.format("%03d", MilliSeconds));

            handler.postDelayed(this, 0);
        }

    };

}

</code>```

and the view of activity_main.xml

```<code> <?xml version="1.0" encoding="utf-8"?>
    <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/colorPrimary"
        tools:context="in.amitsin6h.stopwatch.MainActivity">

            <RelativeLayout
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:layout_marginLeft="10dp"
                android:layout_marginRight="10dp"
                android:paddingBottom="90dp">

               <TextView
                   android:text="00:00:00"
                   android:layout_width="wrap_content"
                   android:layout_height="wrap_content"
                   android:id="@+id/tvTimer"
                   android:textSize="50dp"
                   android:textStyle="bold"
                   android:textColor="#ffffff"
                   android:layout_marginTop="120dp"
                   android:paddingBottom="50dp"
                   android:layout_alignParentTop="true"
                   android:layout_centerHorizontal="true" />

               <Button
                   android:text="Start"
                   android:background="#ffffff"
                   android:layout_width="wrap_content"
                   android:layout_height="wrap_content"
                   android:layout_below="@+id/tvTimer"
                   android:layout_alignParentLeft="true"
                   android:layout_alignParentStart="true"
                   android:layout_marginTop="41dp"
                   android:id="@+id/btStart" />

               <Button
                   android:text="Pause"
                   android:background="#ffffff"
                   android:layout_width="wrap_content"
                   android:layout_height="wrap_content"
                   android:id="@+id/btPause"
                   android:layout_alignBaseline="@+id/btStart"
                   android:layout_alignBottom="@+id/btStart"
                   android:layout_centerHorizontal="true" />

               <Button
                   android:text="Reset"
                   android:background="#ffffff"
                   android:layout_width="wrap_content"
                   android:layout_height="wrap_content"
                   android:layout_alignTop="@+id/btPause"
                   android:layout_alignParentRight="true"
                   android:layout_alignParentEnd="true"
                   android:id="@+id/btReset" />

            </RelativeLayout>

    </android.support.constraint.ConstraintLayout>
</code>```

Body:
How to make an app to count the time since the first time opened? I have no idea which class to use. Is it possible to achieve this with a stopwatch or something similar? Can someone pls share some code? I don't know what to search on the internet just have an idea of what I want to build. Or just tell me an idea with what I can achieve this and how?

 statisticLayout.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
          if (plusiliminus==0){
              Toast.makeText(getActivity(),R.string.toaststatistic,Toast.LENGTH_SHORT).show();
          } else {
              Fragment fragmentstatistic=new Statistic();
              FragmentTransaction transaction=getActivity().getSupportFragmentManager().beginTransaction();
              transaction.replace(R.id.frameLayout,fragmentstatistic).commit();
          }
      }
  });

Body:
You have basically to do two things.

Get the current time when you start the app, or press a button using something like

Date currentTime = Calendar.getInstance().getTime();

This is a good beginning, you get the time, then you have to parse this time in a format you want to show to the user then you manage a stop and reset button as showed for instance in this tutorial

So you build a TextView and you show in real time the seconds, parsed in the way you need

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

public class MainActivity extends AppCompatActivity {

    TextView timer ;
    Button start, pause, reset;
    long MillisecondTime, StartTime, TimeBuff, UpdateTime = 0L ;
    Handler handler;
    int Seconds, Minutes, MilliSeconds ;

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

        timer = (TextView)findViewById(R.id.tvTimer);
        start = (Button)findViewById(R.id.btStart);
        pause = (Button)findViewById(R.id.btPause);
        reset = (Button)findViewById(R.id.btReset);

        handler = new Handler() ;

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

                StartTime = SystemClock.uptimeMillis();
                handler.postDelayed(runnable, 0);

                reset.setEnabled(false);

            }
        });

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

                TimeBuff += MillisecondTime;

                handler.removeCallbacks(runnable);

                reset.setEnabled(true);

            }
        });

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

                MillisecondTime = 0L ;
                StartTime = 0L ;
                TimeBuff = 0L ;
                UpdateTime = 0L ;
                Seconds = 0 ;
                Minutes = 0 ;
                MilliSeconds = 0 ;

                timer.setText("00:00:00");

            }
        });

    }

    public Runnable runnable = new Runnable() {

        public void run() {

            MillisecondTime = SystemClock.uptimeMillis() - StartTime;

            UpdateTime = TimeBuff + MillisecondTime;

            Seconds = (int) (UpdateTime / 1000);

            Minutes = Seconds / 60;

            Seconds = Seconds % 60;

            MilliSeconds = (int) (UpdateTime % 1000);

            timer.setText("" + Minutes + ":"
                    + String.format("%02d", Seconds) + ":"
                    + String.format("%03d", MilliSeconds));

            handler.postDelayed(this, 0);
        }

    };

}

and the view of activity_main.xml

 <?xml version="1.0" encoding="utf-8"?>
    <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/colorPrimary"
        tools:context="in.amitsin6h.stopwatch.MainActivity">

            <RelativeLayout
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:layout_marginLeft="10dp"
                android:layout_marginRight="10dp"
                android:paddingBottom="90dp">

               <TextView
                   android:text="00:00:00"
                   android:layout_width="wrap_content"
                   android:layout_height="wrap_content"
                   android:id="@+id/tvTimer"
                   android:textSize="50dp"
                   android:textStyle="bold"
                   android:textColor="#ffffff"
                   android:layout_marginTop="120dp"
                   android:paddingBottom="50dp"
                   android:layout_alignParentTop="true"
                   android:layout_centerHorizontal="true" />

               <Button
                   android:text="Start"
                   android:background="#ffffff"
                   android:layout_width="wrap_content"
                   android:layout_height="wrap_content"
                   android:layout_below="@+id/tvTimer"
                   android:layout_alignParentLeft="true"
                   android:layout_alignParentStart="true"
                   android:layout_marginTop="41dp"
                   android:id="@+id/btStart" />

               <Button
                   android:text="Pause"
                   android:background="#ffffff"
                   android:layout_width="wrap_content"
                   android:layout_height="wrap_content"
                   android:id="@+id/btPause"
                   android:layout_alignBaseline="@+id/btStart"
                   android:layout_alignBottom="@+id/btStart"
                   android:layout_centerHorizontal="true" />

               <Button
                   android:text="Reset"
                   android:background="#ffffff"
                   android:layout_width="wrap_content"
                   android:layout_height="wrap_content"
                   android:layout_alignTop="@+id/btPause"
                   android:layout_alignParentRight="true"
                   android:layout_alignParentEnd="true"
                   android:id="@+id/btReset" />

            </RelativeLayout>

    </android.support.constraint.ConstraintLayout>


问:
Java String generation at compile time or runtime
Given this code:

```<code>if(somecondition) {
    String one = "one";
    //print one;
}
</code>```

This string will only be generated when that condition is true?

Appreciate any help.

Edit:

With String pooling, is it safe to say that String one will be added to the pool regardless of a condition.

So, if a variable needs to be resolved from an object, what will happen?

Say,

```<code>String hello = "Hello Mr " + user.firstName();
</code>```

How will this be added to String pool? And when it does get added to String pool, it will not create new String literals right (unless user.firstName() changes).

答:
The string is generated at the time you typed it; but, for that answer to make sense, we need to walk it's life through the transformations in the build and launch of the application.

First you typed it into the *.java file.

Then the compiler copied it into the *.class file as part of the constant pool entries.

Then the program was run, and the class was requested, which triggered the class loader to copy the file from disk to RAM, triggering a object meta-data entry being created to wrap the constant in the constant pool.

So, there's multiple places where it could be "created" depending on your definition of which kind of "creation" you wish to use.

Now, in your first example, the String object isn't realized when you use the string, but when you use the *.class file.  However, it's not reference by the running program until you enter the method.

Finally, with String pooling, every time a string is about to be created, the existing pool of strings is searched, and if a matching entry is found, the matching entry is used instead of creating a new string.  This reduces the number of strings in a runtime, at the cost of a lot of string searching.

Due to the details of your code, you have three different strings that are eligible for pooling ("Hello Mr ", the value of user.firstName(), and the string combining them both).  "Hello Mr " would be pooled with the class loading (assuming pooling is being done).  The value of user.firstName() would have happened when the value for the return was originally created.  The resulting combined string would be pooled just before the assignment (or reference from the pool, if it already exists in the pool).

Body:
Given this code:

if(somecondition) {
    String one = "one";
    //print one;
}

This string will only be generated when that condition is true?

Appreciate any help.

Edit:

With String pooling, is it safe to say that String one will be added to the pool regardless of a condition.

So, if a variable needs to be resolved from an object, what will happen?

Say,

String hello = "Hello Mr " + user.firstName();

How will this be added to String pool? And when it does get added to String pool, it will not create new String literals right (unless user.firstName() changes).


问:
Reducing time and memory used in loop calculation when locating earthquakes
I'm trying to locate tremor, which is a type of earthquake with smaller amplitude. I use grid search, which is a method that finds the coordinate where 'the difference between theoretical value and observed value of differential time in seismic wave arrival' becomes minimum.

The code I made is as follows. First I defined two functions that calculate distance between earthquake source and each point on grid, and that calculate travel time of seismic waves using obspy.

```<code>def distance(a,i):
    return math.sqrt(((ste[a].stats.sac.stla-la[i])**2)+((ste[a].stats.sac.stlo-lo[i])**2))

def traveltime(a):
    return model.get_travel_times(source_depth_in_km=35, distance_in_degree=a, phase_list=["S"], receiver_depth_in_km=0)[0].time
</code>```

Then I conducted grid search using following codes.

```<code>di=[(la[i],lo[i],distance(a,i), distance(b,i)) for i in range(len(lo))
    for a in range(len(ste))
    for b in range(len(ste)) if a<b]

didf=pd.DataFrame(di)

latot=didf[0]
lotot=didf[1]
dia=didf[2]
dib=didf[3]
</code>```

```<code>tt=[]
for i in range(len(di)):
    try:
        tt.append((latot[i],lotot[i],traveltime(dia[i])-traveltime(dib[i])))
    except IndexError:
        continue

ttdf=pd.DataFrame(tt)
</code>```

```<code>final=[(win[j],ttdf[0][i],ttdf[1][i],(ttdf[2][i]-shift[j])**2) for i in range(len(ttdf))
      for j in range(len(ccdf))]
</code>```

where la and lo are the list of latitude and longitude coordinates with 0.01 degree interval, and ste is the list of the east components seismogram of each station. I have to get the list 'final' to proceed to the next step.

However, the problem is that it takes too much time to calculate three segments of codes written above. Moreover, the result I get after tens of hours of calculation is 'out of memory' error message. Is there any solution that can reduce both time and memory?

答:
Without access to your dataset, it's a little difficult to debug, but here are a few suggestions for you.

```<code>for i in range(len(di)):
    try:
        tt.append((latot[i],lotot[i],traveltime(dia[i])-traveltime(dib[i])))
    except IndexError:
        continue
</code>```

•  Given the size of these lists, I think that the Garbage Collector might be slowing down this for loop; you might consider turning it off for the duration of the loop (gc.disable()).

•  In theory, the Append statement shouldn't be the source of your performance problems, since it over-allocates:

```<code>/* This over-allocates proportional to the list size, making room
 * for additional growth.  The over-allocation is mild, but is
 * enough to give linear-time amortized behavior over a long
 * sequence of appends() in the presence of a poorly-performing
 * system realloc().
 * The growth pattern is:  0, 4, 8, 16, 25, 35, 46, 58, 72, 88, ...
 */
new_allocated = (newsize >> 3) + (newsize < 9 ? 3 : 6);
</code>```

but you already know the size of the array, so you might consider using numpy.zeroes() to fill the list before the for-loop, and use the index to directly address each element.  Alternatively, you could just use list comprehensions, as you did earlier, and avoid the problem altogether.

• I see that you've tagged the question with python-3.x, so range() shouldn't be an issue like it was in 2.x (otherwise you would want to consider using xrange()).

If you update your question with more details, I could probably provide a more detailed answer...hope this helps.

Body:
I'm trying to locate tremor, which is a type of earthquake with smaller amplitude. I use grid search, which is a method that finds the coordinate where 'the difference between theoretical value and observed value of differential time in seismic wave arrival' becomes minimum.

The code I made is as follows. First I defined two functions that calculate distance between earthquake source and each point on grid, and that calculate travel time of seismic waves using obspy.

def distance(a,i):
    return math.sqrt(((ste[a].stats.sac.stla-la[i])**2)+((ste[a].stats.sac.stlo-lo[i])**2))

def traveltime(a):
    return model.get_travel_times(source_depth_in_km=35, distance_in_degree=a, phase_list=["S"], receiver_depth_in_km=0)[0].time

Then I conducted grid search using following codes.

di=[(la[i],lo[i],distance(a,i), distance(b,i)) for i in range(len(lo))
    for a in range(len(ste))
    for b in range(len(ste)) if a<b]

didf=pd.DataFrame(di)

latot=didf[0]
lotot=didf[1]
dia=didf[2]
dib=didf[3]

tt=[]
for i in range(len(di)):
    try:
        tt.append((latot[i],lotot[i],traveltime(dia[i])-traveltime(dib[i])))
    except IndexError:
        continue

ttdf=pd.DataFrame(tt)

final=[(win[j],ttdf[0][i],ttdf[1][i],(ttdf[2][i]-shift[j])**2) for i in range(len(ttdf))
      for j in range(len(ccdf))]

where la and lo are the list of latitude and longitude coordinates with 0.01 degree interval, and ste is the list of the east components seismogram of each station. I have to get the list 'final' to proceed to the next step.

However, the problem is that it takes too much time to calculate three segments of codes written above. Moreover, the result I get after tens of hours of calculation is 'out of memory' error message. Is there any solution that can reduce both time and memory?

Body:
Without access to your dataset, it's a little difficult to debug, but here are a few suggestions for you.

for i in range(len(di)):
    try:
        tt.append((latot[i],lotot[i],traveltime(dia[i])-traveltime(dib[i])))
    except IndexError:
        continue

•  Given the size of these lists, I think that the Garbage Collector might be slowing down this for loop; you might consider turning it off for the duration of the loop (gc.disable()).

•  In theory, the Append statement shouldn't be the source of your performance problems, since it over-allocates:

/* This over-allocates proportional to the list size, making room
 * for additional growth.  The over-allocation is mild, but is
 * enough to give linear-time amortized behavior over a long
 * sequence of appends() in the presence of a poorly-performing
 * system realloc().
 * The growth pattern is:  0, 4, 8, 16, 25, 35, 46, 58, 72, 88, ...
 */
new_allocated = (newsize >> 3) + (newsize < 9 ? 3 : 6);

but you already know the size of the array, so you might consider using numpy.zeroes() to fill the list before the for-loop, and use the index to directly address each element.  Alternatively, you could just use list comprehensions, as you did earlier, and avoid the problem altogether.

• I see that you've tagged the question with python-3.x, so range() shouldn't be an issue like it was in 2.x (otherwise you would want to consider using xrange()).

If you update your question with more details, I could probably provide a more detailed answer...hope this helps.


问:
Make swi prolog to return the predicate name
sorry i just want to return the predicate name america

```<code>america('kin').
novelist('kin').
writer(X):- novelist(X).
</code>```

when i query swi below
writer(A),novelist(A)

it just match
A = 'kin'
how to change the swi to make it return america?

答:
Does america(X) mean "X lives in America"? I'd suggest to make america an atom instead of a predicate, then define facts like:

```<code>lives_in(kin, america).
</code>```

That allows you to define rules like:

```<code>novelist_living_in(X, Y) :- novelist(X), lives_in(X, Y).
</code>```

so that you can do queries like:

```<code>novelist_living_in(kin, Y).
</code>```

Body:
sorry i just want to return the predicate name america

america('kin').
novelist('kin').
writer(X):- novelist(X).

when i query swi below
writer(A),novelist(A)

it just match
A = 'kin'
how to change the swi to make it return america?

Body:
Does america(X) mean "X lives in America"? I'd suggest to make america an atom instead of a predicate, then define facts like:

lives_in(kin, america).

That allows you to define rules like:

novelist_living_in(X, Y) :- novelist(X), lives_in(X, Y).

so that you can do queries like:

novelist_living_in(kin, Y).


问:
Best way to convert a Java Future to a Twitter Future
In my application, I am converting a java.concurrent.future to a Twitter Future like so:

```<code>val myTwitterFuture = FuturePool.unboundedPool{ myJavaFuture.get}
</code>```

Is this the correct way to do so, or is there a preferred method?

答:
If your Java future is just a java.util.concurrent.Future, then what you have is basically the best you can do, because it's a very poor type. If you have a java.util.concurrent.CompletableFuture, you basically combine the answers to convert it to a scala.concurrent.Future and convert Scala future to a Twitter future:

```<code>import java.util.concurrent.{Future => JFuture, CompletableFuture}
import com.twitter.util.{Future => TwitterFuture, Promise => TwitterPromise}
import scala.util.{Success, Failure}

implicit class FutureWrapper[A](private val jf: JFuture[A]) extends AnyVal {
  def asTwitter: TwitterFuture[A] = jf match {
    case jf: CompletableFuture[A] =>
      val promise = new TwitterPromise[A]()
      jf.whenComplete { (result, exception) =>
        if (exception != null)
          promise.setException(exception)
        else
          promise.setValue(result)
      }
      promise
    case _ =>
      FuturePool.unboundedPool{ jf.get }
  }
}
</code>```

Body:
In my application, I am converting a java.concurrent.future to a Twitter Future like so:

val myTwitterFuture = FuturePool.unboundedPool{ myJavaFuture.get}

Is this the correct way to do so, or is there a preferred method?

Body:
If your Java future is just a java.util.concurrent.Future, then what you have is basically the best you can do, because it's a very poor type. If you have a java.util.concurrent.CompletableFuture, you basically combine the answers to convert it to a scala.concurrent.Future and convert Scala future to a Twitter future:

import java.util.concurrent.{Future => JFuture, CompletableFuture}
import com.twitter.util.{Future => TwitterFuture, Promise => TwitterPromise}
import scala.util.{Success, Failure}

implicit class FutureWrapper[A](private val jf: JFuture[A]) extends AnyVal {
  def asTwitter: TwitterFuture[A] = jf match {
    case jf: CompletableFuture[A] =>
      val promise = new TwitterPromise[A]()
      jf.whenComplete { (result, exception) =>
        if (exception != null)
          promise.setException(exception)
        else
          promise.setValue(result)
      }
      promise
    case _ =>
      FuturePool.unboundedPool{ jf.get }
  }
}


问:
Split Dataframe into list of one-row Dataframes
I would like to split a dataframe

```<code>df <- data.frame(a = 1:4, b = letters[1:4])

  a b
1 1 a
2 2 b
3 3 c
4 4 d
</code>```

into a list of one-row dataframes

```<code>list(
    data.frame(a = 1, b = letters[1])
    , data.frame(a = 2, b = letters[2])
    , data.frame(a = 3, b = letters[3])
    , data.frame(a = 4, b = letters[4])
)

[[1]]
  a b
1 1 a

[[2]]
  a b
1 2 b

[[3]]
  a b
1 3 c

[[4]]
  a b
1 4 d
</code>```

Is there an elegant solution to this?

答:
Using dplyr:

```<code>df %>%
 rowid_to_column() %>%
 group_split(rowid, keep = FALSE)

[[1]]
# A tibble: 1 x 2
      a b
  <int> <fct>
1     1 a

[[2]]
# A tibble: 1 x 2
      a b
  <int> <fct>
1     2 b

[[3]]
# A tibble: 1 x 2
      a b
  <int> <fct>
1     3 c

[[4]]
# A tibble: 1 x 2
      a b
  <int> <fct>
1     4 d
</code>```

Or:

```<code>df %>%
 mutate(rowid = 1:n()) %>%
 group_split(rowid, keep = FALSE)
</code>```

Or a shortened version (provided by @arg0naut91):

```<code>group_split(df, row_number(), keep = FALSE)
</code>```

Body:
I would like to split a dataframe

df <- data.frame(a = 1:4, b = letters[1:4])

  a b
1 1 a
2 2 b
3 3 c
4 4 d

into a list of one-row dataframes

list(
    data.frame(a = 1, b = letters[1])
    , data.frame(a = 2, b = letters[2])
    , data.frame(a = 3, b = letters[3])
    , data.frame(a = 4, b = letters[4])
)

[[1]]
  a b
1 1 a

[[2]]
  a b
1 2 b

[[3]]
  a b
1 3 c

[[4]]
  a b
1 4 d

Is there an elegant solution to this?

Body:
Using dplyr:

df %>%
 rowid_to_column() %>%
 group_split(rowid, keep = FALSE)

[[1]]
# A tibble: 1 x 2
      a b
  <int> <fct>
1     1 a

[[2]]
# A tibble: 1 x 2
      a b
  <int> <fct>
1     2 b

[[3]]
# A tibble: 1 x 2
      a b
  <int> <fct>
1     3 c

[[4]]
# A tibble: 1 x 2
      a b
  <int> <fct>
1     4 d

Or:

df %>%
 mutate(rowid = 1:n()) %>%
 group_split(rowid, keep = FALSE)

Or a shortened version (provided by @arg0naut91):

group_split(df, row_number(), keep = FALSE)


问:
Neo4J what is the fastest structure when you have 3 main entities?
Say you have zip codes, services and customers. Given a zip and service, I want to find the corresponding customers as fast as possible.

Options:

Customers are connected to zips via a "service" relationship. this seems like the smallest version, search for a particular zip and only one type of relationship (the targeted service)

Customers are connected to service areas, which point to different zips and services. Here we search for all service areas that point to the targeted service and the targeted zip.

Zips each connect to a service node unique to them, which are then connected to customers. so when you search, you go to the zip you want, go to the service, then anything connected to there is what you want (this feels like i may be overly hand holding for neo4J)

Do these different versions have different performance? I am having trouble understanding the theoretical difference in search formats in Neo4J. 2 is an example where the results are limited on two sides at once, where for 1 and 3, you can travel linearly on the graph as you filter, does that make a difference?

Thanks,
Brian

答:
Approach 1 has several major drawbacks. All data about a "service" (which I assume is a company that provides services) would have to be duplicated in every associated service relationship. That wastes storage space in the DB. Also, if you wanted to find all the customers for a specific service (regardless of zip code), you'd have to scan every service relationship.

Approach 2 introduces an extra "service area" layer to the data model that seems to provide no advantage and just makes processing your use case more complicated and slower.

Approach 3 (in which I assume every "service" has a unique node) should be the way to go. There is no data duplication, and no scanning is needed to find the desired customers (whether you start from a zip code, or from a service).


问:
iOS 7: UITableView shows under status bar
The first screen of my application is a UITableViewController without a navigation bar, which means that the content flows under the status bar so there's a lot of text collisions. I've adjusted both the properties for Under top bars and Adjust scroll view insets which do actually stop it from scrolling under, but at the cost of keeping the top of the table view under. I've attempted to set the UITableView frame to offset by 20 pixels, but it doesn't appear to take effect and as I currently need the app to be compatible with iOS 6 I can't jump to iOS 7 Storyboards to force autolayout to use the top height guide. Has anyone found a solution that works for both versions?

Things I've tried: setting edgesForExtendedLayout, changing the settings within Storyboard for Under top bars and Adjust scroll view, forcing the frame to a new area.

A picture is worth a thousand words:

答: I found the easiest way to do this, especially if you're adding your table view inside of tab bar is to first add a view and then add the table view inside that view. This gives you the top margin guides you're looking for.


问:
Not able to figure out the logical error in C program
A program that prints its input one word per line.

```<code>int main() {

    int c;

    while ((c=getchar()) != EOF) {

        if (c== ' ' || c== '\n' ||c == '\t')
                putchar('\n');
        else {
            putchar(c);
        }
    }
    return 0;
}
</code>```

The above program prints the result correctly, one word per line. After changing the condition accordingly, I was expecting the program below to also print one word per line. However I am not getting the correct result. Am I making some silly mistake or is something wrong?

```<code>int main() {

    int c;

    while ((c=getchar()) != EOF) {

        if (c != ' ' || c != '\n' || c != '\t')
            putchar(c);
        else {
            putchar('\n');
        }
    }

    return 0;

}
</code>```

答:
You need to change the ||s to &&s, i.e. change

```<code>        if (c != ' ' || c != '\n' || c != '\t')
</code>```

to

```<code>        if (c != ' ' && c != '\n' && c != '\t')
</code>```

i.e. "IF c not equal to space AND c not equal to return AND c not equal to tab THEN ..."

Body:
A program that prints its input one word per line.

int main() {

    int c;

    while ((c=getchar()) != EOF) {

        if (c== ' ' || c== '\n' ||c == '\t')
                putchar('\n');
        else {
            putchar(c);
        }
    }
    return 0;
}

The above program prints the result correctly, one word per line. After changing the condition accordingly, I was expecting the program below to also print one word per line. However I am not getting the correct result. Am I making some silly mistake or is something wrong?

int main() {

    int c;

    while ((c=getchar()) != EOF) {

        if (c != ' ' || c != '\n' || c != '\t')
            putchar(c);
        else {
            putchar('\n');
        }
    }

    return 0;

}

Body:
You need to change the ||s to &&s, i.e. change

        if (c != ' ' || c != '\n' || c != '\t')

to

        if (c != ' ' && c != '\n' && c != '\t')

i.e. "IF c not equal to space AND c not equal to return AND c not equal to tab THEN ..."


问:
Conversion exception while reading binary field data to byte[] field in ES 7.5.x
I have my entity class defined as follows:

```<code>@Document(indexName = "payload-pojo")
public class PayloadPojo {
    @Id
    private String id;

    @Field(index = false,type = FieldType.Binary)
    byte[] payload;

}
</code>```

and the Repository defined as follows:

```<code>public interface PayloadRepository  extends ElasticsearchRepository<PayloadPojo, String>  {
}
</code>```

In the ES 6.8.1 (Spring Data Elasticsearch 3.2.0) I managed to store and read the binary data without any problem.

Now I'd like to move to ES 7.5.2, so I migrated the project to use Spring Data Elasticsearch 4.0.0. Since then when I try to call something like payloadRepo.findAll() I get conversion exception:
Failed to convert from type [java.lang.String] to type [byte].
The data is stored as base64 encoded string.

Do you have any idea of what has changed and how to change my code in order to read this value correctly?

Thanks

答:
FieldType.Binary was added for the 4.0 release. What still was missing until now was a internal converter to convert between byte[] and base64 encoded strings (field type binary in elasticsearch is always base64 encoded).

I just added this, should be in the next snapshot release.

As for the date types: We have added support for the different Elasticsearch date formats and support custom date patterns as well - as Elasticsearch does. This support is available for the classes implementing the java.time.TemporalAccessor interface - basically the java.time.* classes.

We dropped the internal support of the old java.util.Date classes in favour of the java.time classes - java.sql.Timestamp is derived from java.util.Date.

We have breaking changes for the 4.0 release and this is one of them (reminds to update the docs).

Body:
I have my entity class defined as follows:

@Document(indexName = "payload-pojo")
public class PayloadPojo {
    @Id
    private String id;

    @Field(index = false,type = FieldType.Binary)
    byte[] payload;

}

and the Repository defined as follows:

public interface PayloadRepository  extends ElasticsearchRepository<PayloadPojo, String>  {
}

In the ES 6.8.1 (Spring Data Elasticsearch 3.2.0) I managed to store and read the binary data without any problem.

Now I'd like to move to ES 7.5.2, so I migrated the project to use Spring Data Elasticsearch 4.0.0. Since then when I try to call something like payloadRepo.findAll() I get conversion exception:
Failed to convert from type [java.lang.String] to type [byte].
The data is stored as base64 encoded string.

Do you have any idea of what has changed and how to change my code in order to read this value correctly?

Thanks


问:
VBA Loop Through a File Path and Run a Code
I have the code below that I would like to run to all of the available excel files in a folder. Ideally, I would like to input the path of the folder into cell C3 in Sheet1 and the macro to apply the code to all of the existing files.

The code will simply save the second sheet of each file into a PDF version, it works perfectly standalone.

Sample Folder Path:
C:\Users\MMMM\Desktop\Project X\ Project II

Suggestions on how to approach this?

```<code>Private Sub CommandButton1_Click()

    Dim MyFolder As String, MyFile As String

    With Application.FileDialog(msoFileDialogFolderPicker)

       .AllowMultiSelect = False

       .Show

       MyFolder = .SelectedItems(1)

       Err.Clear

    End With

    Application.ScreenUpdating = False

    Application.DisplayStatusBar = False

    Application.EnableEvents = False

    Application.Calculation = xlCalculationManual

    MyFile = Dir(MyFolder & "\", vbReadOnly)

    Do While MyFile <> ""

        DoEvents

        On Error GoTo 0

        Workbooks.Open Filename:=MyFolder & "\" & MyFile, UpdateLinks:=False

Dim ReportSheet As Worksheet

Dim allColumns As Range

    Set allColumns = Sheets("RT").Columns("N:S")

    allColumns.Hidden = True

    With Worksheets("RT").PageSetup

     .Zoom = False

     .FitToPagesWide = 1

    End With

Filename = ActiveWorkbook.Name

Cell = Replace(Filename, ".xlsx", ".PDF")

Set ReportSheet = Sheets("RT")

Sheets("RT").Select

Sheets("RT").PageSetup.Orientation = xlLandscape

ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _

    ThisWorkbook.Path & "\" & Cell, _

    Quality:=xlQualityStandard, IncludeDocProperties:=True, _

    IgnorePrintAreas:=True, OpenAfterPublish:=True

0

        Workbooks(MyFile).Close SaveChanges:=False

        MyFile = Dir

    Loop

    'turns settings back on that you turned off before looping folders

    Application.ScreenUpdating = True

    Application.DisplayStatusBar = True

    Application.EnableEvents = True

    Application.Calculation = xlCalculationManual

End Sub
</code>```

答:
This needs a reference (see this link)

It's untested (so let me know if anything comes up)

Basically:

As suggested by SmileyFtW it asks you for the root folder

Scans the subfolders for excel files (adjust the extension in code)

Process the DoSomething procedure where you export the file

EDIT: Added handle user cancel file select dialog

Code:

```<code>Option Explicit

' Add a reference to Microsoft Scripting Runtime
' See https://vbaf1.com/filesystemobject/create-microsoft-scripting-runtime-library-reference/

Private Sub ProcessAllFilesInFolder()

    Dim FileSystem As Scripting.FileSystemObject
    Dim fileDialogResult As Office.FileDialog

    Dim folderPath As String

    Set FileSystem = New Scripting.FileSystemObject

    Set fileDialogResult = Application.FileDialog(msoFileDialogFolderPicker)

    With fileDialogResult
        .AllowMultiSelect = False
        .Title = "Select a folder"
        If .Show = True Then
            folderPath = .SelectedItems(1)
        End If
        If .SelectedItems.Count = 0 Then Exit Sub
    End With

    ProcessFolder FileSystem.GetFolder(folderPath)

End Sub

Private Sub ProcessFolder(ByVal targetFolder As Scripting.Folder)
    Dim FileSystem As Scripting.FileSystemObject
    Dim File As Scripting.File
    Dim SubFolder As Scripting.Folder

    Set FileSystem = New Scripting.FileSystemObject

    For Each SubFolder In targetFolder.SubFolders
        ProcessFolder SubFolder
    Next

    For Each File In targetFolder.Files
        If FileSystem.GetExtensionName(File.Name) Like "xls?" And File.Name <> ThisWorkbook.Name Then
            DoSomething File.Path
        End If
    Next
End Sub

Private Sub DoSomething(ByVal filePath As String)

    Dim FileSystem As Scripting.FileSystemObject
    Dim ReportSheet As Worksheet

    Dim targetFileName As String

    targetFileName = Replace(ThisWorkbook.Name, ".xlsm", ".PDF")
    Set ReportSheet = ThisWorkbook.Worksheets("Sheet2")

    ReportSheet.PageSetup.Orientation = xlLandscape
    ReportSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
                    ThisWorkbook.Path & "\" & targetFileName, _
                    Quality:=xlQualityStandard, IncludeDocProperties:=True, _
                    IgnorePrintAreas:=True, OpenAfterPublish:=True
End Sub
</code>```

Let me know if it works!

Body:
I have the code below that I would like to run to all of the available excel files in a folder. Ideally, I would like to input the path of the folder into cell C3 in Sheet1 and the macro to apply the code to all of the existing files.

The code will simply save the second sheet of each file into a PDF version, it works perfectly standalone.

Sample Folder Path:
C:\Users\MMMM\Desktop\Project X\ Project II

Suggestions on how to approach this?

Private Sub CommandButton1_Click()

    Dim MyFolder As String, MyFile As String

    With Application.FileDialog(msoFileDialogFolderPicker)

       .AllowMultiSelect = False

       .Show

       MyFolder = .SelectedItems(1)

       Err.Clear

    End With

    Application.ScreenUpdating = False

    Application.DisplayStatusBar = False

    Application.EnableEvents = False

    Application.Calculation = xlCalculationManual

    MyFile = Dir(MyFolder & "\", vbReadOnly)

    Do While MyFile <> ""

        DoEvents

        On Error GoTo 0

        Workbooks.Open Filename:=MyFolder & "\" & MyFile, UpdateLinks:=False

Dim ReportSheet As Worksheet

Dim allColumns As Range

    Set allColumns = Sheets("RT").Columns("N:S")

    allColumns.Hidden = True

    With Worksheets("RT").PageSetup

     .Zoom = False

     .FitToPagesWide = 1

    End With

Filename = ActiveWorkbook.Name

Cell = Replace(Filename, ".xlsx", ".PDF")

Set ReportSheet = Sheets("RT")

Sheets("RT").Select

Sheets("RT").PageSetup.Orientation = xlLandscape

ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _

    ThisWorkbook.Path & "\" & Cell, _

    Quality:=xlQualityStandard, IncludeDocProperties:=True, _

    IgnorePrintAreas:=True, OpenAfterPublish:=True

0

        Workbooks(MyFile).Close SaveChanges:=False

        MyFile = Dir

    Loop

    'turns settings back on that you turned off before looping folders

    Application.ScreenUpdating = True

    Application.DisplayStatusBar = True

    Application.EnableEvents = True

    Application.Calculation = xlCalculationManual

End Sub

Body:
This needs a reference (see this link)

It's untested (so let me know if anything comes up)

Basically:

As suggested by SmileyFtW it asks you for the root folder

Scans the subfolders for excel files (adjust the extension in code)

Process the DoSomething procedure where you export the file

EDIT: Added handle user cancel file select dialog

Code:

Option Explicit

' Add a reference to Microsoft Scripting Runtime
' See https://vbaf1.com/filesystemobject/create-microsoft-scripting-runtime-library-reference/

Private Sub ProcessAllFilesInFolder()

    Dim FileSystem As Scripting.FileSystemObject
    Dim fileDialogResult As Office.FileDialog

    Dim folderPath As String

    Set FileSystem = New Scripting.FileSystemObject

    Set fileDialogResult = Application.FileDialog(msoFileDialogFolderPicker)

    With fileDialogResult
        .AllowMultiSelect = False
        .Title = "Select a folder"
        If .Show = True Then
            folderPath = .SelectedItems(1)
        End If
        If .SelectedItems.Count = 0 Then Exit Sub
    End With

    ProcessFolder FileSystem.GetFolder(folderPath)

End Sub

Private Sub ProcessFolder(ByVal targetFolder As Scripting.Folder)
    Dim FileSystem As Scripting.FileSystemObject
    Dim File As Scripting.File
    Dim SubFolder As Scripting.Folder

    Set FileSystem = New Scripting.FileSystemObject

    For Each SubFolder In targetFolder.SubFolders
        ProcessFolder SubFolder
    Next

    For Each File In targetFolder.Files
        If FileSystem.GetExtensionName(File.Name) Like "xls?" And File.Name <> ThisWorkbook.Name Then
            DoSomething File.Path
        End If
    Next
End Sub

Private Sub DoSomething(ByVal filePath As String)

    Dim FileSystem As Scripting.FileSystemObject
    Dim ReportSheet As Worksheet

    Dim targetFileName As String

    targetFileName = Replace(ThisWorkbook.Name, ".xlsm", ".PDF")
    Set ReportSheet = ThisWorkbook.Worksheets("Sheet2")

    ReportSheet.PageSetup.Orientation = xlLandscape
    ReportSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
                    ThisWorkbook.Path & "\" & targetFileName, _
                    Quality:=xlQualityStandard, IncludeDocProperties:=True, _
                    IgnorePrintAreas:=True, OpenAfterPublish:=True
End Sub

Let me know if it works!


问:
Unable to pushasync in iOS after Validation in MainPage
I have a Cross-platform App in Xamarin, at the moment is working perfectly in Android, however, I'm now debugging it on iOS using iPhoneSimulator on Windows Computer (I'm Connected with MAC in Cloud Service).

I have put a stopping point on my Controller in the section where it does the consult in the Webservice and I do see that my Username and Password parameters are being filled with the information from the view (MainPage, or Logging Page).

My Current problem is that when I click on my access Button on the MainPage (which is my Logging Page), it doesn't do anything it just stays there.

At the moment this is the Main Page XAML Code:

```<code><Image Source="taber.png"
       FlexLayout.Order="-1"
       FlexLayout.AlignSelf="Center"
                   WidthRequest="180"
                   HeightRequest="180" Aspect="AspectFit" />

<Label>

</Label>
<Frame
CornerRadius="15"
Padding="0"
BackgroundColor="#507BF5"
Margin="15,10,15,10"
HasShadow="False"
>
<Label
Margin="5"
Text="Usuario"
HorizontalOptions="Center"
BackgroundColor="Transparent"
FontSize="Large"
TextColor="White"
FontAttributes="Bold"
/>
</Frame>
<Frame
CornerRadius="15"
Padding="0"
Margin="15,10,15,10"
 >
    <Entry Placeholder="Usuario"
x:Name="txtUsuario"
HorizontalTextAlignment="Center"
TextChanged="OnChangeUser"
/>
</Frame>
<Frame
CornerRadius="15"
Padding="0"
BackgroundColor="#507BF5"
Margin="15,10,15,10"
HasShadow="False"
>
    <Label
Margin="5"
Text="Contraseña"
HorizontalOptions="Center"
BackgroundColor="Transparent"
FontSize="Large"
TextColor="White"
FontAttributes="Bold"
/>
</Frame>
<Frame
CornerRadius="15"
Padding="0"
Margin="15,10,15,10"
 >
<Entry IsPassword="True"
       Placeholder="Contraseña"
       x:Name="txtPassword"
       HorizontalTextAlignment="Center"
/>
</Frame>
<Label FlexLayout.Grow="1" />
<Button
      BorderColor="#507BF5"
      BorderRadius="5"
      BorderWidth="2"
      Margin="15,10,15,10"
      x:Name="bntIngresar"
      Text="Ingresar"
      TextColor="White"
      Clicked="btnIngresar_click"
      BackgroundColor="#507BF5"/>
</code>```

I use the btnIngresar_click method to validate the information through the PHP Web service here is the Code behind in the XAML.CS for btnIngresar_click:

```<code>private async void btnIngresar_click(object sender, EventArgs e)
        {
            try
            {
                string input = txtPassword.Text;
                string encryptedPass;

                MD5 md5 = MD5.Create();
                byte[] inputBytes = Encoding.ASCII.GetBytes(input);
                byte[] hash = md5.ComputeHash(inputBytes);

                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < hash.Length; i++)
                {
                    sb.Append(hash[i].ToString("X2"));
                }

                encryptedPass = sb.ToString();

                UseManager manager = new UseManager();
                var result = await manager.userLogin(txtUsuario.Text.ToString(), encryptedPass);

                if (result.Count() > 0)
                {
                    foreach (var nuser in result)
                    {
                        servidor = nuser.id_servidor;
                        acceso = nuser.id_acceso;
                        usuario = nuser.id;
                    }
                    //await Navigation.PushAsync(new Principal(servidor, acceso, usuario));
                    await Navigation.PushAsync(new SplashPage(servidor, acceso, usuario));
                }
                else
                {
                    await DisplayAlert("Error", "Usuario o Contraseña Incorrectos", "Accept", "Cancel");
                }
            }
            catch (Exception e1)
            {

            }
        }
</code>```

Now here is the Method userLogin which takes me to the Web Service in PHP: (FYI as mentioned on top I put a Stop Point in the line: var result = await cliente.GetAsync(URL + "login.php?username=" + username + "&password=" + password); and I can see that the Username Variable is being captured and the Password one as well.)

```<code> public async Task<IEnumerable<user>> userLogin(string username, string password)
        {
            HttpClient cliente = getClient();

            var result = await cliente.GetAsync(URL + "login.php?username=" + username + "&password=" + password);

            if (result.IsSuccessStatusCode)
            {
                var content = await result.Content.ReadAsStringAsync();
                return JsonConvert.DeserializeObject<IEnumerable<user>>(content);
            }
            return Enumerable.Empty<user>();
        }
</code>```

Finally here is the Webservice in PHP:

```<code><?php

$username= $_REQUEST['username'];
$password= $_REQUEST['password'];

$cnx=new PDO("mysql: host=localhost; dbname=securitb","DBUSERNAME","DBPASSWORD");
$res=$cnx->query("select * from usuarios where username ='$username' and password ='$password'");

$datos = array();

foreach ($res as $row){
    array_push($datos, array(
    'id' => $row['id'],
    'username' => $row['username'],
    'password' => $row['password'],
    'activo' => $row['activo'],
    'id_acceso' => $row['id_acceso'],
    'id_servidor' => $row['id_servidor'],
    ));
}
echo utf8_encode(json_encode($datos));
?>
</code>```

Why it might be that my iOS app is not moving to the Splash Screen?

答:
First problem is that you are making multiple requests with your code:

```<code>private HttpClient getClient()
{
    HttpClient client = new HttpClient();
    client.DefaultRequestHeaders.Add("Accept", "application/json"); client.DefaultRequestHeaders.Add("Connection", "close");
    return client;
}
</code>```

Personally I think that main problem is here:

```<code>    try
    {
        HttpClient cliente = getClient();

        var result = await cliente.GetAsync(URL + "login.php?username=" + username + "&password=" + password);

        if (result.IsSuccessStatusCode)
        {
            var content = await result.Content.ReadAsStringAsync();
            return JsonConvert.DeserializeObject<IEnumerable<user>>(content);
        }
        return Enumerable.Empty<user>();
    }
    catch (Exception)
    {

    }
</code>```

Try to catch here for exceptions. I think there is a problem with object deserialization.

Body:
I have a Cross-platform App in Xamarin, at the moment is working perfectly in Android, however, I'm now debugging it on iOS using iPhoneSimulator on Windows Computer (I'm Connected with MAC in Cloud Service).

I have put a stopping point on my Controller in the section where it does the consult in the Webservice and I do see that my Username and Password parameters are being filled with the information from the view (MainPage, or Logging Page).

My Current problem is that when I click on my access Button on the MainPage (which is my Logging Page), it doesn't do anything it just stays there.

At the moment this is the Main Page XAML Code:

<Image Source="taber.png"
       FlexLayout.Order="-1"
       FlexLayout.AlignSelf="Center"
                   WidthRequest="180"
                   HeightRequest="180" Aspect="AspectFit" />

<Frame
CornerRadius="15"
Padding="0"
BackgroundColor="#507BF5"
Margin="15,10,15,10"
HasShadow="False"
>

</Frame>
<Frame
CornerRadius="15"
Padding="0"
Margin="15,10,15,10"
 >
    <Entry Placeholder="Usuario"
x:Name="txtUsuario"
HorizontalTextAlignment="Center"
TextChanged="OnChangeUser"
/>
</Frame>
<Frame
CornerRadius="15"
Padding="0"
BackgroundColor="#507BF5"
Margin="15,10,15,10"
HasShadow="False"
>

</Frame>
<Frame
CornerRadius="15"
Padding="0"
Margin="15,10,15,10"
 >
<Entry IsPassword="True"
       Placeholder="Contraseña"
       x:Name="txtPassword"
       HorizontalTextAlignment="Center"
/>
</Frame>

<Button
      BorderColor="#507BF5"
      BorderRadius="5"
      BorderWidth="2"
      Margin="15,10,15,10"
      x:Name="bntIngresar"
      Text="Ingresar"
      TextColor="White"
      Clicked="btnIngresar_click"
      BackgroundColor="#507BF5"/>

I use the btnIngresar_click method to validate the information through the PHP Web service here is the Code behind in the XAML.CS for btnIngresar_click:

private async void btnIngresar_click(object sender, EventArgs e)
        {
            try
            {
                string input = txtPassword.Text;
                string encryptedPass;

                MD5 md5 = MD5.Create();
                byte[] inputBytes = Encoding.ASCII.GetBytes(input);
                byte[] hash = md5.ComputeHash(inputBytes);

                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < hash.Length; i++)
                {
                    sb.Append(hash[i].ToString("X2"));
                }

                encryptedPass = sb.ToString();

                UseManager manager = new UseManager();
                var result = await manager.userLogin(txtUsuario.Text.ToString(), encryptedPass);

                if (result.Count() > 0)
                {
                    foreach (var nuser in result)
                    {
                        servidor = nuser.id_servidor;
                        acceso = nuser.id_acceso;
                        usuario = nuser.id;
                    }
                    //await Navigation.PushAsync(new Principal(servidor, acceso, usuario));
                    await Navigation.PushAsync(new SplashPage(servidor, acceso, usuario));
                }
                else
                {
                    await DisplayAlert("Error", "Usuario o Contraseña Incorrectos", "Accept", "Cancel");
                }
            }
            catch (Exception e1)
            {

            }
        }

Now here is the Method userLogin which takes me to the Web Service in PHP: (FYI as mentioned on top I put a Stop Point in the line: var result = await cliente.GetAsync(URL + "login.php?username=" + username + "&password=" + password); and I can see that the Username Variable is being captured and the Password one as well.)

 public async Task<IEnumerable<user>> userLogin(string username, string password)
        {
            HttpClient cliente = getClient();

            var result = await cliente.GetAsync(URL + "login.php?username=" + username + "&password=" + password);

            if (result.IsSuccessStatusCode)
            {
                var content = await result.Content.ReadAsStringAsync();
                return JsonConvert.DeserializeObject<IEnumerable<user>>(content);
            }
            return Enumerable.Empty<user>();
        }

Finally here is the Webservice in PHP:

<?php

$username= $_REQUEST['username'];
$password= $_REQUEST['password'];

$cnx=new PDO("mysql: host=localhost; dbname=securitb","DBUSERNAME","DBPASSWORD");
$res=$cnx->query("select * from usuarios where username ='$username' and password ='$password'");

$datos = array();

foreach ($res as $row){
    array_push($datos, array(
    'id' => $row['id'],
    'username' => $row['username'],
    'password' => $row['password'],
    'activo' => $row['activo'],
    'id_acceso' => $row['id_acceso'],
    'id_servidor' => $row['id_servidor'],
    ));
}
echo utf8_encode(json_encode($datos));
?>

Why it might be that my iOS app is not moving to the Splash Screen?

Body:
First problem is that you are making multiple requests with your code:

private HttpClient getClient()
{
    HttpClient client = new HttpClient();
    client.DefaultRequestHeaders.Add("Accept", "application/json"); client.DefaultRequestHeaders.Add("Connection", "close");
    return client;
}

Personally I think that main problem is here:

    try
    {
        HttpClient cliente = getClient();

        var result = await cliente.GetAsync(URL + "login.php?username=" + username + "&password=" + password);

        if (result.IsSuccessStatusCode)
        {
            var content = await result.Content.ReadAsStringAsync();
            return JsonConvert.DeserializeObject<IEnumerable<user>>(content);
        }
        return Enumerable.Empty<user>();
    }
    catch (Exception)
    {

    }

Try to catch here for exceptions. I think there is a problem with object deserialization.


问:
Why is NumPy’s "boolean indexing" slower here then "filter"
I have a question regarding the speed of NumPy’s boolean indexing: I expected it to be faster then pythons regular filter method. Did I utilized it wrong? Thank you for your help in advance!</p>

```<code>L = np.arange(499999, 1000000)
index = (L % 6 == 1) | (L % 3 != 1)
L = L[index]
#9.53 ms ± 370 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

L = range(499999, 1000000)
L = filter(lambda x:(x % 6 == 1) or (x%3 != 1), L)
#338 ns ± 1.13 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each) much much faster!!!

L = [x for x in range(499999, 1000000) if (x % 6 == 1) or (x%3 != 1)]
#51.5 ms ± 1.7 ms per loop (mean ± std. dev. of 7 runs, 10 loops each) I expected this to be faster too!?
</code>```

答:
In python-3.x, filter is lazy. That means that if you call filter(lambda x:(x % 6 == 1) or (x%3 != 1), L), it will not do anything. It will just create a filter object, but not filter the iterable at all.

It is only when you iterate over that object, that it will start enumerating over the underlying source, and each time try to find the next element of that source that satisfies the given predicate.

So constructing a filter is done in constant time. If you however use something like list(..) that will materialize the list, we obtain for 10 runs:

```<code>>>> timeit(lambda: list(filter(lambda x:(x % 6 == 1) or (x%3 != 1), L)), number=10)
2.855049993000648
</code>```

so on average, it takes 0.2855 seconds to filter the entire list L.

Body:
I have a question regarding the speed of NumPy’s boolean indexing: I expected it to be faster then pythons regular filter method. Did I utilized it wrong? Thank you for your help in advance!

L = np.arange(499999, 1000000)
index = (L % 6 == 1) | (L % 3 != 1)
L = L[index]
#9.53 ms ± 370 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

L = range(499999, 1000000)
L = filter(lambda x:(x % 6 == 1) or (x%3 != 1), L)
#338 ns ± 1.13 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each) much much faster!!!

L = [x for x in range(499999, 1000000) if (x % 6 == 1) or (x%3 != 1)]
#51.5 ms ± 1.7 ms per loop (mean ± std. dev. of 7 runs, 10 loops each) I expected this to be faster too!?

Body:
In python-3.x, filter is lazy. That means that if you call filter(lambda x:(x % 6 == 1) or (x%3 != 1), L), it will not do anything. It will just create a filter object, but not filter the iterable at all.

It is only when you iterate over that object, that it will start enumerating over the underlying source, and each time try to find the next element of that source that satisfies the given predicate.

So constructing a filter is done in constant time. If you however use something like list(..) that will materialize the list, we obtain for 10 runs:

>>> timeit(lambda: list(filter(lambda x:(x % 6 == 1) or (x%3 != 1), L)), number=10)
2.855049993000648

so on average, it takes 0.2855 seconds to filter the entire list L.


问:
How can I add spacebar on Header Nav Bar
So I made a navigation bar and a section lists and I successfully done it but the only problem is that the lists are not spaced. How do I fix this?

How the Page looks like

header {
  width:    100%;
  height:    80px;
  position:   fixed;
  top:    0;
  left:    0;
  background:   white;
  box-shadow:   0 32px 55px rgba(0, 0, 0, 0.5);
  z-index:    999;
}

header nav {
  float:    none;
  margin:    30px;
}

header nav ul li {
  display:    inline-block;
}

header nav ul li a {
  font-size:   16px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code> <header>

  <nav id="nav-main">
   <ul>
    <li>Home</li>
    <li>Elektro One</li>
    <li>Über uns</li>
    <li>Kontakt</li>
    <li>Impressum</li>
   </ul>
  </nav>

 </header></code>```

答:
If you want to display evenly across the navbar and be responsive with screen then try using:

```<code><ul id="even-space">
    <li>..</li>
    ..
</ul>
</code>```

and css

```<code>#even-space {
    display: flex;
    justify-content: space-between;
}
</code>```

Body:
So I made a navigation bar and a section lists and I successfully done it but the only problem is that the lists are not spaced. How do I fix this?

How the Page looks like

header {
  width:    100%;
  height:    80px;
  position:   fixed;
  top:    0;
  left:    0;
  background:   white;
  box-shadow:   0 32px 55px rgba(0, 0, 0, 0.5);
  z-index:    999;
}

header nav {
  float:    none;
  margin:    30px;
}

header nav ul li {
  display:    inline-block;
}

header nav ul li a {
  font-size:   16px;
}

Home

Elektro One

Über uns

Kontakt

Impressum

Body:
If you want to display evenly across the navbar and be responsive with screen then try using:

<ul id="even-space">
    <li>..</li>
    ..
</ul>

and css

#even-space {
    display: flex;
    justify-content: space-between;
}


问:
RatingBar with pink background when holding
My RatingBar is pretty regular, when selected appears like this

But when touching (and holding) them, all unrated stars are pink, like this

Why does this happen?

The xml:

```<code><RatingBar
    android:id="@+id/ratingBarSchedulesRatingTour"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="4dp"
    android:numStars="5"
    android:progressTint="@color/yellow_star"
    android:secondaryProgressTint="@color/yellow_star"
    android:stepSize="1" />
</code>```

@color/yellow_star is on colors.xml as #F1CD1E

答:
You can use android:progressBackgroundTint attribute on RatingBar to override background color:

```<code>android:progressBackgroundTint="#ABABAB"
</code>```

Body:
My RatingBar is pretty regular, when selected appears like this

But when touching (and holding) them, all unrated stars are pink, like this

Why does this happen?

The xml:

<RatingBar
    android:id="@+id/ratingBarSchedulesRatingTour"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="4dp"
    android:numStars="5"
    android:progressTint="@color/yellow_star"
    android:secondaryProgressTint="@color/yellow_star"
    android:stepSize="1" />

@color/yellow_star is on colors.xml as #F1CD1E

Body:
You can use android:progressBackgroundTint attribute on RatingBar to override background color:

android:progressBackgroundTint="#ABABAB"