问:
os.rename module raises WindowsError, don't understand why
Here is a snippet of code.

```<code>import os
def rename_files():
file_list = os.listdir(r"C:\Users\Oleg\Desktop\prank\prank")
print (file_list)
saved_path = os.getcwd()
print("Current Working Directory Is "+saved_path)
for x in file_list:
    print x
    x1 = x.translate(None,"0123456789")
    print x1
    os.rename(x, x1)
rename_files()`
</code>```

The problem is that it is giving me an error...

Traceback (most recent call last):
File "C:/Python27/rename_files.py", line 13, in <module>
rename_files()
File "C:/Python27/rename_files.py", line 11, in rename_files
os.rename(x, x1)
WindowsError: [Error 2] ?? ??????? ????? ????????? ????
```

答:
You're not using the path you're listing when renaming the files, try with:</p>

```<code>import os

def rename_files(path):
    file_list = os.listdir(path)
    print(file_list)
    for x in file_list:
        print(x)
        x1 = x.translate(None,"0123456789")
        print(x1)
        os.rename(os.path.join(path, x), os.path.join(path, x1))

rename_files(r"C:\Users\Oleg\Desktop\prank\prank")
</code>```

Body:
Here is a snippet of code.

import os
def rename_files():
file_list = os.listdir(r"C:\Users\Oleg\Desktop\prank\prank")
print (file_list)
saved_path = os.getcwd()
print("Current Working Directory Is "+saved_path)
for x in file_list:
    print x
    x1 = x.translate(None,"0123456789")
    print x1
    os.rename(x, x1)
rename_files()`

The problem is that it is giving me an error...

Traceback (most recent call last):
File "C:/Python27/rename_files.py", line 13, in <module>
rename_files()
File "C:/Python27/rename_files.py", line 11, in rename_files
os.rename(x, x1)
WindowsError: [Error 2] ?? ??????? ????? ????????? ????

Body:
You're not using the path you're listing when renaming the files, try with:

import os

def rename_files(path):
    file_list = os.listdir(path)
    print(file_list)
    for x in file_list:
        print(x)
        x1 = x.translate(None,"0123456789")
        print(x1)
        os.rename(os.path.join(path, x), os.path.join(path, x1))

rename_files(r"C:\Users\Oleg\Desktop\prank\prank")


来源: stackexchange

问:
Stuck in a while loop in python
I'm very new to python so bear with me. I have this code below which I've inserted a while loop to make sure every time a name is given it checks to verify that name is in the csv and then if it isn't it gives and error and asks for a new name. My problem is that I can't seem to get out of the loop. Even with a new name that I know for a fact is in the csv it still sticks in the loop. My question is how can I get this code to run through a loop and verify the name is in there? any help would be great. I am even open to changing the entire code if there's a better way to write this.

Here's what I got:

```<code>import csv

full_name = input('Enter your full name: ').lower()

with open('Report1.csv') as csvfile:
    hour_summation = {}
    read_csv = csv.reader(csvfile, delimiter=',')
    for row in read_csv:
        while (' '.join((row[0], row[1]))).lower() != full_name.strip().lower():
            print('Name is not in system')
            full_name = input('Enter your full name: ').lower()
        if(' '.join((row[0], row[1]))).lower() == full_name.strip().lower():
            hour_summation[row[2]] = hour_summation.get(row[2], 0) + int(float(row[3]))
print('This is {} full hours report:'.format(full_name))
for k, v in hour_summation.items():
    print(k + ': ' + str(v) + ' hours')
</code>```

Here's the result when I give an input:
fyi. Steve Miller is not in the csv file so that first response is correct. However, Sri Mantri is in the file and it should continue on and print out all the listings under her name.

```<code>Enter your full name: Steve Miller
Name is not in system
Enter your full name: Sri Mantri
Name is not in system
</code>```

Here's what the output should look like when the code runs.

```<code>Enter your full name: Sri mantri
This is sri mantri full hours report:
Beeline Blank: 28 hours
SRV-0001 Service Requests for Base and Direct Services: 4 hours
SUP-0001 Support Requests with a CISM Ticket: 129 hours
SUP-2503 Web Application Maintenance & Support: 72 hours
0026184229 Margin Controlling Java Rewrite: 4 hours
0033472751 PRE-AFE 2017 - CMS Enhancements: 2 hours
0033472863 PRE-AFE 2017 - BPM Enhancements: 67 hours
APP-10008 Pre-Series (Non-Mainframe): 4 hours
APP-10146 Logistics (Non-Mainframe): 3 hours
APP-10195 Vehicle Labor System (Mainframe): 3 hours
APP-10354 Web PartsPro (Non-Mainframe): 1 hours
APP-10431 VIPService (Non-Mainframe): 1 hours
APP-10432 VIPService (Mainframe): 3 hours
APP-10536 Truck Invoice Adjustments (Mainframe): 2 hours
</code>```

and the csv looks like this:

```<code>First Name  Last Name   Activity    Hours
Sri Mantri  SUP-2503 Web Application Maintenance & Support  11
Sri Mantri  SUP-2503 Web Application Maintenance & Support  3
Sri Mantri  SUP-2503 Web Application Maintenance & Support  5
Sri Mantri  SUP-2503 Web Application Maintenance & Support  2
Jeff    Moore   SUP-2503 Web Application Maintenance & Support  3
David   Ayers   SUP-2507  NAFTA MFTS OS Support 10
Prasanth    Musunuru    0020826809 Vertex 6.0 at the NDC    4
Prasanth    Musunuru    0020826809 Vertex 6.0 at the NDC    3
Prasanth    Musunuru    0020826809 Vertex 6.0 at the NDC    1
Prasanth    Musunuru    0020826809 Vertex 6.0 at the NDC    1
Jeff    Moore   0024480049 Fuel Tanks (infrastructure) - time tracking  1
Jeff    Moore   0024480049 Fuel Tanks (infrastructure) - time tracking  1
Jeff    Moore   0024480049 Fuel Tanks (infrastructure) - time tracking  4
</code>```

答:
You're asking for input inside the while loop that never checks any row other then the current row. It looks like you're trying to iterate over the entire list to see if the name is anywhere in there (which is rough performance wise but I won't confuse you by getting into that xD) so your input check and loops need to be moved around a bit like so:</p>

```<code>import csv

with open('Report1.csv') as csvfile:
  hour_summation = {}
  read_csv = csv.reader(csvfile, delimiter=',')
  name_found = False
  while not name_found:
    # take user input for name
    full_name = input('Enter your full name: ').lower()
    # start search at top of file. Have to do this or each loop will
    # start at the end of the file after the first check.
    csvfile.seek(0)
    for row in read_csv:
      # check to see if row matches name
      if(' '.join((row[0], row[1]))).lower() == full_name.strip().lower():
        name_found = True
        hour_summation[row[2]] = hour_summation.get(row[2], 0) + int(float(row[3]))

    # name wasn't found, so repeat process
    if not name_found:
      # name wasn't found, go back to start of while loop
      print('Name is not in system')
    else:
      # break out of while loop. Technically not required since while
      # will exit here anyway, but clarity is nice
      break

print('This is {} full hours report:'.format(full_name))
for k, v in hour_summation.items():
    print(k + ': ' + str(v) + ' hours')
</code>```

ContentLicense: CC BY-SA 3.0

Title: Stuck in a while loop in python

Body:
I'm very new to python so bear with me. I have this code below which I've inserted a while loop to make sure every time a name is given it checks to verify that name is in the csv and then if it isn't it gives and error and asks for a new name. My problem is that I can't seem to get out of the loop. Even with a new name that I know for a fact is in the csv it still sticks in the loop. My question is how can I get this code to run through a loop and verify the name is in there? any help would be great. I am even open to changing the entire code if there's a better way to write this.

Here's what I got:

import csv

full_name = input('Enter your full name: ').lower()

with open('Report1.csv') as csvfile:
    hour_summation = {}
    read_csv = csv.reader(csvfile, delimiter=',')
    for row in read_csv:
        while (' '.join((row[0], row[1]))).lower() != full_name.strip().lower():
            print('Name is not in system')
            full_name = input('Enter your full name: ').lower()
        if(' '.join((row[0], row[1]))).lower() == full_name.strip().lower():
            hour_summation[row[2]] = hour_summation.get(row[2], 0) + int(float(row[3]))
print('This is {} full hours report:'.format(full_name))
for k, v in hour_summation.items():
    print(k + ': ' + str(v) + ' hours')

Here's the result when I give an input:
fyi. Steve Miller is not in the csv file so that first response is correct. However, Sri Mantri is in the file and it should continue on and print out all the listings under her name.

Enter your full name: Steve Miller
Name is not in system
Enter your full name: Sri Mantri
Name is not in system

Here's what the output should look like when the code runs.

Enter your full name: Sri mantri
This is sri mantri full hours report:
Beeline Blank: 28 hours
SRV-0001 Service Requests for Base and Direct Services: 4 hours
SUP-0001 Support Requests with a CISM Ticket: 129 hours
SUP-2503 Web Application Maintenance & Support: 72 hours
0026184229 Margin Controlling Java Rewrite: 4 hours
0033472751 PRE-AFE 2017 - CMS Enhancements: 2 hours
0033472863 PRE-AFE 2017 - BPM Enhancements: 67 hours
APP-10008 Pre-Series (Non-Mainframe): 4 hours
APP-10146 Logistics (Non-Mainframe): 3 hours
APP-10195 Vehicle Labor System (Mainframe): 3 hours
APP-10354 Web PartsPro (Non-Mainframe): 1 hours
APP-10431 VIPService (Non-Mainframe): 1 hours
APP-10432 VIPService (Mainframe): 3 hours
APP-10536 Truck Invoice Adjustments (Mainframe): 2 hours

and the csv looks like this:

First Name  Last Name   Activity    Hours
Sri Mantri  SUP-2503 Web Application Maintenance & Support  11
Sri Mantri  SUP-2503 Web Application Maintenance & Support  3
Sri Mantri  SUP-2503 Web Application Maintenance & Support  5
Sri Mantri  SUP-2503 Web Application Maintenance & Support  2
Jeff    Moore   SUP-2503 Web Application Maintenance & Support  3
David   Ayers   SUP-2507  NAFTA MFTS OS Support 10
Prasanth    Musunuru    0020826809 Vertex 6.0 at the NDC    4
Prasanth    Musunuru    0020826809 Vertex 6.0 at the NDC    3
Prasanth    Musunuru    0020826809 Vertex 6.0 at the NDC    1
Prasanth    Musunuru    0020826809 Vertex 6.0 at the NDC    1
Jeff    Moore   0024480049 Fuel Tanks (infrastructure) - time tracking  1
Jeff    Moore   0024480049 Fuel Tanks (infrastructure) - time tracking  1
Jeff    Moore   0024480049 Fuel Tanks (infrastructure) - time tracking  4

Body:
You're asking for input inside the while loop that never checks any row other then the current row. It looks like you're trying to iterate over the entire list to see if the name is anywhere in there (which is rough performance wise but I won't confuse you by getting into that xD) so your input check and loops need to be moved around a bit like so:

import csv

with open('Report1.csv') as csvfile:
  hour_summation = {}
  read_csv = csv.reader(csvfile, delimiter=',')
  name_found = False
  while not name_found:
    # take user input for name
    full_name = input('Enter your full name: ').lower()
    # start search at top of file. Have to do this or each loop will
    # start at the end of the file after the first check.
    csvfile.seek(0)
    for row in read_csv:
      # check to see if row matches name
      if(' '.join((row[0], row[1]))).lower() == full_name.strip().lower():
        name_found = True
        hour_summation[row[2]] = hour_summation.get(row[2], 0) + int(float(row[3]))

    # name wasn't found, so repeat process
    if not name_found:
      # name wasn't found, go back to start of while loop
      print('Name is not in system')
    else:
      # break out of while loop. Technically not required since while
      # will exit here anyway, but clarity is nice
      break

print('This is {} full hours report:'.format(full_name))
for k, v in hour_summation.items():
    print(k + ': ' + str(v) + ' hours')


问:
Getting docker containers output from another docker container
I have an application that runs dockerized commands via docker run --rm .... Is it possible to dockerize this application?

E.g. I want the app RUNNER to run app RUNNABLE and read the stdout result.
(I need multiple instances of RUNNABLE in async calling fashion but that's RUNNER application business)

I know it is possible to just export root access to docker socket to the RUNNER application but this doesn't feel right. Especially with no-root-running rule for *nix applications.

Is there any other method to communicate containers rather than exporting socket to the container? Am I doing the system design wrong?

答:
Basically it's possible to let the container communicate over host based files. Take a look at the following example.

```<code># create a test dir
mkdir -p docker_test/bin
cd docker_test
# an endless running script that writes output in a file
vim bin/printDate.sh
chmod 700 bin/*.sh
# start docker container from debian image
# the container got a local host mount of /tmp to container /opt/output
# printDate.sh writes its output to container /opt/output/printDate.txt
docker run --name cont-1 \
  -v /tmp:/opt/output -it -v `pwd`/bin:/opt/test \
  debian /opt/test/printDate.sh

# start a second container in another terminal and mount /tmp again
docker run --name cont-2 -v /tmp:/opt/output -it \
  debian tail -f /opt/output/printDate.txt
# the second container prints the output of program in cont-1
</code>```

The endless script for container 1 output

```<code>#!/bin/bash
while true; do
     sleep 1
     date >> /opt/output/printDate.txt
done
</code>```

Body:
Basically it's possible to let the container communicate over host based files. Take a look at the following example.

# create a test dir
mkdir -p docker_test/bin
cd docker_test
# an endless running script that writes output in a file
vim bin/printDate.sh
chmod 700 bin/*.sh
# start docker container from debian image
# the container got a local host mount of /tmp to container /opt/output
# printDate.sh writes its output to container /opt/output/printDate.txt
docker run --name cont-1 \
  -v /tmp:/opt/output -it -v `pwd`/bin:/opt/test \
  debian /opt/test/printDate.sh

# start a second container in another terminal and mount /tmp again
docker run --name cont-2 -v /tmp:/opt/output -it \
  debian tail -f /opt/output/printDate.txt
# the second container prints the output of program in cont-1

The endless script for container 1 output

#!/bin/bash
while true; do
     sleep 1
     date >> /opt/output/printDate.txt
done


问:
How can I translate printf("%c",M); from C to Java for my DES implementation?
I'm a German student and for computer classes I need to implement the DES-encryption in Java (by myself, not by using the Java-API) and explain it in detail. I didn't find any Java-code-examples using google, however I did find an easy implementation in C. (I do not know C, I know a little C++, but not that well, pointer still get me now and then.)

So I tried simply converting the code from C to Java, which did work out about halfway, however I'm having a problem with the last part, especially with the example using:

```<code>printf("%c",M);
</code>```

Which, from what Google told me, seems to be converting numbers(Integer) to ASCII-Characters, but I'm not really sure. My Code seems to be working until that last part, so I would be thankful for anyone that can give me fix/hint.

My Code:

```<code>import java.util.Scanner;

public class DES {

    /**
     * @param args
     */
    public static void main(String[] args) {

        Scanner eingabe = new Scanner(System.in);

        int p, q, key2, fn, encryption_key, temp1 , temp2 ,
            t, s =0 , privatekey1=1, b=0 , passwort_s=0, klartext;
        int[] Cipher = new int [100];
        String passwort;

        System.out.println("Enter the value of p and q");

        p = eingabe.nextInt();
        q = eingabe.nextInt();

        System.out.println(p);
        System.out.println(q);

        key2= p*q;

        fn=(p-1)*(q-1);
        System.out.println("Enter Enryption key e: ");
        encryption_key = eingabe.nextInt();

        do {

            s=(privatekey1*encryption_key)%fn;
            privatekey1++;

        } while (s!=1);

        privatekey1=privatekey1-1;

        System.out.println("Public Key : "+ encryption_key + ","+ key2 );
        System.out.println("Private Key: "+ privatekey1 + "," +key2 );
        System.out.println("Enter Message: ");
        passwort= eingabe.next();
        for ( temp2 = 0; temp2 < passwort.length(); temp2++)
        {
            t = passwort.charAt(temp2);
            passwort_s=1;
            for(temp1 =0 ; temp1< encryption_key ; temp1++){
                passwort_s= passwort_s*t%key2;
            }
            passwort_s= passwort_s%key2;
            System.out.println(passwort_s);
        }

        System.out.println("Enter cipher Text: ");
        for(temp1=0;temp1< passwort.length(); temp1++ )
        {
            Cipher[temp1]= eingabe.nextInt();
        }

        System.out.println("Plainttext: ");
        for(temp2 =0; temp2 < passwort.length(); temp2++);
        {
            klartext=1;

            for(temp1 =0; temp1 < privatekey1; temp1 ++){
                klartext=klartext*Cipher[temp2]%key2;
            }
            klartext=klartext%key2;
            System.out.println(klartext);
        }
    }
}
</code>```

How can I convert the

```<code>printf("%c",M);
</code>```

to Java, and is this then a full DES implementation?

答:
Des is actually a fairly tough algotrithm to get your head around. I was about to blog about it but when I dug down. I couldn't break it down into pieces I was happy with.

Here is how very roughtly DES works.

Choose a 64bit key. (throw away 8bits)

For each 64bit block split in half

Do some  xor based perumutation based on sub-keys genererated and do the same to the other half.

Do some substitution.

Do more permutatation

to Decrypt run in reverse number.

*this is a gross simplification.

Body:
I'm a German student and for computer classes I need to implement the DES-encryption in Java (by myself, not by using the Java-API) and explain it in detail. I didn't find any Java-code-examples using google, however I did find an easy implementation in C. (I do not know C, I know a little C++, but not that well, pointer still get me now and then.)

So I tried simply converting the code from C to Java, which did work out about halfway, however I'm having a problem with the last part, especially with the example using:

printf("%c",M);

Which, from what Google told me, seems to be converting numbers(Integer) to ASCII-Characters, but I'm not really sure. My Code seems to be working until that last part, so I would be thankful for anyone that can give me fix/hint.

My Code:

import java.util.Scanner;

public class DES {

    /**
     * @param args
     */
    public static void main(String[] args) {

        Scanner eingabe = new Scanner(System.in);

        int p, q, key2, fn, encryption_key, temp1 , temp2 ,
            t, s =0 , privatekey1=1, b=0 , passwort_s=0, klartext;
        int[] Cipher = new int [100];
        String passwort;

        System.out.println("Enter the value of p and q");

        p = eingabe.nextInt();
        q = eingabe.nextInt();

        System.out.println(p);
        System.out.println(q);

        key2= p*q;

        fn=(p-1)*(q-1);
        System.out.println("Enter Enryption key e: ");
        encryption_key = eingabe.nextInt();

        do {

            s=(privatekey1*encryption_key)%fn;
            privatekey1++;

        } while (s!=1);

        privatekey1=privatekey1-1;

        System.out.println("Public Key : "+ encryption_key + ","+ key2 );
        System.out.println("Private Key: "+ privatekey1 + "," +key2 );
        System.out.println("Enter Message: ");
        passwort= eingabe.next();
        for ( temp2 = 0; temp2 < passwort.length(); temp2++)
        {
            t = passwort.charAt(temp2);
            passwort_s=1;
            for(temp1 =0 ; temp1< encryption_key ; temp1++){
                passwort_s= passwort_s*t%key2;
            }
            passwort_s= passwort_s%key2;
            System.out.println(passwort_s);
        }

        System.out.println("Enter cipher Text: ");
        for(temp1=0;temp1< passwort.length(); temp1++ )
        {
            Cipher[temp1]= eingabe.nextInt();
        }

        System.out.println("Plainttext: ");
        for(temp2 =0; temp2 < passwort.length(); temp2++);
        {
            klartext=1;

            for(temp1 =0; temp1 < privatekey1; temp1 ++){
                klartext=klartext*Cipher[temp2]%key2;
            }
            klartext=klartext%key2;
            System.out.println(klartext);
        }
    }
}

How can I convert the

printf("%c",M);

to Java, and is this then a full DES implementation?

LastEditorDisplayName: John Nolan

OwnerDisplayName: John Nolan

ContentLicense: CC BY-SA 2.5


问:
What is the correct way to inject some paragraphs with rich text in a Word content control?
I'm trying to inject some paragraphs in a Word content control using Open Xml SDK.

My code seems to work (paragraphs are visible in the word file). However, control controls cannot be edited. I can only erase the whole content before inserting new content.

How to mimic a manual copy/paste into a content control ?

FYI, here's my code:

```<code>var mainPart = package.MainDocumentPart;

var sdtRuns = mainPart.Document.Descendants<SdtElement>().Where(run => run.SdtProperties.GetFirstChild<Tag>().Val.Value == "TagOfMyContentControl");

foreach (var sdtBlock in sdtRuns)
{
    List<Paragraphs> paragraphs = GetParapraphsFromSomewhere();
    var contentControlParagraph = sdtBlock.Descendants<SdtContentBlock>().First();
    contentControlParagraph.RemoveAllChildren();
    contentControlParagraph.Append(paragraphs);
}

mainPart.Document.Save();
</code>```

PS: I a more general way, is there any resource that explains purpose and hierarchy of Word ML elements?

答:
Your code is close to mimic copy paste into a content control. The following two lines are the lines that are removing all of the paragraphs in your content control:

```<code>var contentControlParagraph = sdtBlock.Descendants<SdtContentBlock>().First();
contentControlParagraph.RemoveAllChildren();
</code>```

Instead, you need to determine where you want to place your paragraph and Append it there.

For example, I have a docx with the rich text content control named CopyPasteCC.  This image shows the doc in developer mode.  The content control has 3 existing paragraphs.

Then, I replace your code with the following:

```<code>        var mainPart = document.MainDocumentPart;

        var sdtRuns = mainPart.Document.Descendants<SdtElement>().Where(run => run.SdtProperties.GetFirstChild<Tag>().Val.Value == "CopyPasteCC");

        sdtRuns.ElementAt(0).Descendants<Paragraph>().ElementAt(1).InsertAfterSelf(
            new Paragraph(new Run(new Text("Hello - this is new Copy Paste paragraph")))
            );

        mainPart.Document.Save();
</code>```

The third line selects all of the paragraphs inside the content control found on the second line.  Then it inserts a new paragraph after the second existing paragraph.  The following image is the above file after this code has ran:

To answer your PS question - there is the formal OpenXML Specification you can try to read.  This is not easy reading, but it is the authoritative specification.  There is a more general (but dated) free e-book titled OpenXml Explained.

I reference each of these once a month for information.  The first chapter of OpenXml Explained covers WordprocessingML, and on page 39 there is a section on Structured Document Tags which has an overview of content controls.

Body:
I'm trying to inject some paragraphs in a Word content control using Open Xml SDK.

My code seems to work (paragraphs are visible in the word file). However, control controls cannot be edited. I can only erase the whole content before inserting new content.

How to mimic a manual copy/paste into a content control ?

FYI, here's my code:

var mainPart = package.MainDocumentPart;

var sdtRuns = mainPart.Document.Descendants<SdtElement>().Where(run => run.SdtProperties.GetFirstChild<Tag>().Val.Value == "TagOfMyContentControl");

foreach (var sdtBlock in sdtRuns)
{
    List<Paragraphs> paragraphs = GetParapraphsFromSomewhere();
    var contentControlParagraph = sdtBlock.Descendants<SdtContentBlock>().First();
    contentControlParagraph.RemoveAllChildren();
    contentControlParagraph.Append(paragraphs);
}

mainPart.Document.Save();

PS: I a more general way, is there any resource that explains purpose and hierarchy of Word ML elements?

Body:
Your code is close to mimic copy paste into a content control. The following two lines are the lines that are removing all of the paragraphs in your content control:

var contentControlParagraph = sdtBlock.Descendants<SdtContentBlock>().First();
contentControlParagraph.RemoveAllChildren();

Instead, you need to determine where you want to place your paragraph and Append it there.

For example, I have a docx with the rich text content control named CopyPasteCC.  This image shows the doc in developer mode.  The content control has 3 existing paragraphs.

Then, I replace your code with the following:

        var mainPart = document.MainDocumentPart;

        var sdtRuns = mainPart.Document.Descendants<SdtElement>().Where(run => run.SdtProperties.GetFirstChild<Tag>().Val.Value == "CopyPasteCC");

        sdtRuns.ElementAt(0).Descendants<Paragraph>().ElementAt(1).InsertAfterSelf(
            new Paragraph(new Run(new Text("Hello - this is new Copy Paste paragraph")))
            );

        mainPart.Document.Save();

The third line selects all of the paragraphs inside the content control found on the second line.  Then it inserts a new paragraph after the second existing paragraph.  The following image is the above file after this code has ran:

To answer your PS question - there is the formal OpenXML Specification you can try to read.  This is not easy reading, but it is the authoritative specification.  There is a more general (but dated) free e-book titled OpenXml Explained.

I reference each of these once a month for information.  The first chapter of OpenXml Explained covers WordprocessingML, and on page 39 there is a section on Structured Document Tags which has an overview of content controls.


问:
How to convert an existing AngularJS 2 web app to a Cordova app?
I have a webapp which I build with Angularjs 2.0, I want to convert it to android apk and install it on android phone and test.

I dont have any experience in building mobile native app or converting webapp to native app.

I have gone through How to convert an existing AngularJS web app to a Cordova app?
Any suggestion/guidance will be helpful.

答:
The most simple explanation is you will need to put your angular files in the www folder, setup your configuration file, make sure the android platform is installed, then run the Android emulate and/or build command to see if it works. That's a very oversimplified version.

Once you've got it working there's a process to go through to prepare the apk to be uploaded to the Google Play Store. You have to be a registered developer for the play store, which is $25/year.

https://scotch.io/@vijayk036/building-hybrid-mobile-apps-using-cordova-and-angularjs-for-android
https://thebhwgroup.com/blog/converting-angularjs-website-cordova-app-ios-and-android


问:
Fighting client-side caching in Django
I'm using the render_to_response shortcut and don't want to craft a specific Response object to add additional headers to prevent client-side caching.

I'd like to have a response that contains:

Pragma: no-cache

Cache-control : no-cache

Cache-control: must-revalidate

And all the other nifty ways that browsers will hopefully interpret as directives to avoid caching.

Is there a no-cache middleware or something similar that can do the trick with minimal code intrusion?

答:
Here is a rewrite of @Meilo's answer for Django 1.10+:</p>

```<code>from django.utils.cache import add_never_cache_headers

class DisableClientCachingMiddleware(object):
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        response = self.get_response(request)
        add_never_cache_headers(response)
        return response
</code>```

Title: Fighting client-side caching in Django

Body:
Here is a rewrite of @Meilo's answer for Django 1.10+:

from django.utils.cache import add_never_cache_headers

class DisableClientCachingMiddleware(object):
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        response = self.get_response(request)
        add_never_cache_headers(response)
        return response


问:
Which one to go first, Grails or Groovy?
I wanted to create a web application. I thought of selecting Groovy or Grails. But I don't know from where to start! To start with Groovy or Grails?</p>

答:
Based on your situation, I would start with grails. Here is the Quick Start tutorial: http://grails.org/Quick+Start

At some point you may want something lighter. When that happens check out Ratpack at https://github.com/bleedingwolf/Ratpack#readme


问:
Angular 2/4/5 Material Dialog problems with ngModel
I feel this is a silly question, but I just can't figure out why it's not working...

I have a material 2 dialog, here's the dialog component

```<code>import { AfterViewInit, Component, Injectable } from '@angular/core';
import { FlexLayoutModule } from '@angular/flex-layout';
import { MatDialog, MatDialogRef } from '@angular/material';

import 'rxjs/add/operator/toPromise';

// services
import { DialogService } from '../../../services/dialog.service';

@Component({
  selector: 'app-dialog-asset-upload',
  templateUrl: './dialog-asset-upload.component.html',
})

@Injectable()
export class DialogAssetUploadComponent {

  constructor(private dialog: MatDialog, private dialogS: DialogService) { }

  // open dialog
  open(): Promise<any[]> {

    // open dialog
    let dialogRef = this.dialog.open(DialogAssetUploadComponentDialog, {});

    return dialogRef.afterClosed().toPromise().then(res => {

      console.log('in asset upload',res);
      return res;
    });
  }
}

@Component({
  selector: 'app-dialog-asset-upload-dialog',
  templateUrl: './dialog-asset-upload.component.html',
})
export class DialogAssetUploadComponentDialog {

  fieldValues = {};

  constructor(
    public dialogRef: MatDialogRef<DialogAssetUploadComponentDialog>,
    private dialogS: DialogService,
    ) { }

  onNoClick(): void {

    this.dialogRef.close();
  }

  save() {

    this.dialogRef.close({ fieldValues: this.fieldValues });
  }
}
</code>```

The HTML for the dialog looks like this:

```<code>  <mat-dialog-content>
    <mat-checkbox [(ngModel)]="fieldValues['is_blog']">Blog</mat-checkbox>
    </mat-checkbox>
  </mat-dialog-content>
</code>```

But no matter what I do I'm getting the error:

```<code>Template parse errors:
Can't bind to 'ngModel' since it isn't a known property of 'mat-checkbox'.
1. If 'mat-checkbox' is an Angular component and it has 'ngModel' input, then verify that it is part of this module.
2. If 'mat-checkbox' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message.
3. To allow any property add 'NO_ERRORS_SCHEMA' to the '@NgModule.schemas' of this component.
</code>```

It would make sense that FormsModule is missing, but it's not -- I have it in the list of imports in my module.ts file. So why is the dialog not able to find it? Any ideas?

**

Edited...

Here's my app.module:

```<code>import { NgModule } from '@angular/core';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { BrowserModule } from '@angular/platform-browser';
import { HttpClientModule } from '@angular/common/http';

// core
import { CoreModule } from './core/core.module';

// shared app/admin
import { SharedModule } from './shared/shared.module';

// routing
import { AppRoutingModule } from './app-routing.module';

// components
import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent,
  ],

  imports: [
    AppRoutingModule,
    BrowserAnimationsModule,
    BrowserModule,
    CoreModule,
    HttpClientModule,
    SharedModule,
  ],

  bootstrap: [AppComponent]
})
export class AppModule { }
</code>```

Here's the shared.module:

```<code>import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { DatePipe, DecimalPipe } from '@angular/common';
import { FlexLayoutModule } from '@angular/flex-layout';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { MatAutocompleteModule, MatButtonModule, MatButtonToggleModule, MatCardModule, MatCheckboxModule, MatChipsModule, MatDatepickerModule, MatDialogModule, MatExpansionModule, MatFormFieldModule, MatGridListModule, MatIconModule, MatInputModule, MatMenuModule, MatNativeDateModule, MatPaginatorModule, MatProgressSpinnerModule, MatSelectModule, MatSidenavModule, MatSlideToggleModule, MatSnackBarModule, MatSortModule, MatTableModule, MatToolbarModule } from '@angular/material';

// dialogs
import { DialogAssetPickerComponent, DialogAssetPickerComponentDialog } from './dialogs/dialog-asset-picker/dialog-asset-picker.component';
import { DialogAssetUploadComponent, DialogAssetUploadComponentDialog } from './dialogs/dialog-asset-upload/dialog-asset-upload.component';
import { DialogConfirmComponent, DialogConfirmComponentDialog } from './dialogs/dialog-confirm/dialog-confirm.component';
import { DialogSearchFilterComponent } from './dialogs/search-filter/search-filter.component';
import { PaginateDialogComponent } from './dialogs/paginate/paginate.component';

// pipes
import { FilterPipe } from './pipes/filter.pipe';
import { ObjArrPipe } from './pipes/objarr.pipe';
import { SafehtmlPipe } from './pipes/safehtml.pipe';

// quill wysiwyg editor
import { QuillModule } from 'ngx-quill';

@NgModule({

  imports: [
    CommonModule,
    FlexLayoutModule,
    MatAutocompleteModule, MatButtonModule, MatButtonToggleModule, MatCardModule, MatCheckboxModule, MatChipsModule, MatDatepickerModule, MatDialogModule, MatExpansionModule, MatFormFieldModule, MatGridListModule, MatIconModule, MatInputModule, MatMenuModule, MatNativeDateModule, MatPaginatorModule, MatProgressSpinnerModule, MatSelectModule, MatSidenavModule, MatSlideToggleModule, MatSnackBarModule, MatSortModule, MatTableModule, MatToolbarModule,
  ],

  entryComponents: [
    DialogAssetPickerComponentDialog,
    DialogAssetUploadComponentDialog,
    DialogConfirmComponentDialog,
  ],

  declarations: [
    DialogAssetPickerComponentDialog,
    DialogAssetUploadComponentDialog,
    DialogConfirmComponentDialog,
    DialogSearchFilterComponent,
    FilterPipe,
    ObjArrPipe,
    PaginateDialogComponent,
    SafehtmlPipe,
  ],

  exports: [
    CommonModule,
    FilterPipe,
    FlexLayoutModule,
    FormsModule,
    ObjArrPipe,
    MatAutocompleteModule, MatButtonModule, MatButtonToggleModule, MatCardModule, MatCheckboxModule, MatChipsModule, MatDatepickerModule, MatDialogModule, MatExpansionModule, MatFormFieldModule, MatGridListModule, MatIconModule, MatInputModule, MatMenuModule, MatNativeDateModule, MatPaginatorModule, MatProgressSpinnerModule, MatSelectModule, MatSidenavModule, MatSlideToggleModule, MatSnackBarModule, MatSortModule, MatTableModule, MatToolbarModule,
    QuillModule,
    ReactiveFormsModule,
    SafehtmlPipe,
  ],

  providers: [
    DatePipe,
    DecimalPipe,
    DialogAssetPickerComponent,
    DialogAssetUploadComponent,
    DialogConfirmComponent,
    ObjArrPipe,
  ],

})
export class SharedModule { }
</code>```

And the admin.module then does this

```<code>import { SharedModule } from '../shared/shared.module';
...
  imports: [
    SharedModule,
  ],
</code>```

答:
You need to import the FormsModule in order to use it for your dependencies; currently, you are just exporting it and your DialogAssetUploadComponentDialog can not find it. Here's what your shared module should look like.

```<code>import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { DatePipe, DecimalPipe } from '@angular/common';
import { FlexLayoutModule } from '@angular/flex-layout';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { MatAutocompleteModule, MatButtonModule, MatButtonToggleModule, MatCardModule, MatCheckboxModule, MatChipsModule, MatDatepickerModule, MatDialogModule, MatExpansionModule, MatFormFieldModule, MatGridListModule, MatIconModule, MatInputModule, MatMenuModule, MatNativeDateModule, MatPaginatorModule, MatProgressSpinnerModule, MatSelectModule, MatSidenavModule, MatSlideToggleModule, MatSnackBarModule, MatSortModule, MatTableModule, MatToolbarModule } from '@angular/material';

// dialogs
import { DialogAssetPickerComponent, DialogAssetPickerComponentDialog } from './dialogs/dialog-asset-picker/dialog-asset-picker.component';
import { DialogAssetUploadComponent, DialogAssetUploadComponentDialog } from './dialogs/dialog-asset-upload/dialog-asset-upload.component';
import { DialogConfirmComponent, DialogConfirmComponentDialog } from './dialogs/dialog-confirm/dialog-confirm.component';
import { DialogSearchFilterComponent } from './dialogs/search-filter/search-filter.component';
import { PaginateDialogComponent } from './dialogs/paginate/paginate.component';

// pipes
import { FilterPipe } from './pipes/filter.pipe';
import { ObjArrPipe } from './pipes/objarr.pipe';
import { SafehtmlPipe } from './pipes/safehtml.pipe';

// quill wysiwyg editor
import { QuillModule } from 'ngx-quill';

@NgModule({

  imports: [
    CommonModule,
    FlexLayoutModule,
    FormsModule, // ADDED HERE
    MatAutocompleteModule, MatButtonModule, MatButtonToggleModule, MatCardModule, MatCheckboxModule, MatChipsModule, MatDatepickerModule, MatDialogModule, MatExpansionModule, MatFormFieldModule, MatGridListModule, MatIconModule, MatInputModule, MatMenuModule, MatNativeDateModule, MatPaginatorModule, MatProgressSpinnerModule, MatSelectModule, MatSidenavModule, MatSlideToggleModule, MatSnackBarModule, MatSortModule, MatTableModule, MatToolbarModule,
  ],

  entryComponents: [
    DialogAssetPickerComponentDialog,
    DialogAssetUploadComponentDialog,
    DialogConfirmComponentDialog,
  ],

  declarations: [
    DialogAssetPickerComponentDialog,
    DialogAssetUploadComponentDialog,
    DialogConfirmComponentDialog,
    DialogSearchFilterComponent,
    FilterPipe,
    ObjArrPipe,
    PaginateDialogComponent,
    SafehtmlPipe,
  ],

  exports: [
    CommonModule,
    FilterPipe,
    FlexLayoutModule,
    FormsModule,
    ObjArrPipe,
    MatAutocompleteModule, MatButtonModule, MatButtonToggleModule, MatCardModule, MatCheckboxModule, MatChipsModule, MatDatepickerModule, MatDialogModule, MatExpansionModule, MatFormFieldModule, MatGridListModule, MatIconModule, MatInputModule, MatMenuModule, MatNativeDateModule, MatPaginatorModule, MatProgressSpinnerModule, MatSelectModule, MatSidenavModule, MatSlideToggleModule, MatSnackBarModule, MatSortModule, MatTableModule, MatToolbarModule,
    QuillModule,
    ReactiveFormsModule,
    SafehtmlPipe,
  ],

  providers: [
    DatePipe,
    DecimalPipe,
    DialogAssetPickerComponent,
    DialogAssetUploadComponent,
    DialogConfirmComponent,
    ObjArrPipe,
  ],

})
export class SharedModule { }
</code>```

Body:
I feel this is a silly question, but I just can't figure out why it's not working...

I have a material 2 dialog, here's the dialog component

import { AfterViewInit, Component, Injectable } from '@angular/core';
import { FlexLayoutModule } from '@angular/flex-layout';
import { MatDialog, MatDialogRef } from '@angular/material';

import 'rxjs/add/operator/toPromise';

// services
import { DialogService } from '../../../services/dialog.service';

@Component({
  selector: 'app-dialog-asset-upload',
  templateUrl: './dialog-asset-upload.component.html',
})

@Injectable()
export class DialogAssetUploadComponent {

  constructor(private dialog: MatDialog, private dialogS: DialogService) { }

  // open dialog
  open(): Promise<any[]> {

    // open dialog
    let dialogRef = this.dialog.open(DialogAssetUploadComponentDialog, {});

    return dialogRef.afterClosed().toPromise().then(res => {

      console.log('in asset upload',res);
      return res;
    });
  }
}

@Component({
  selector: 'app-dialog-asset-upload-dialog',
  templateUrl: './dialog-asset-upload.component.html',
})
export class DialogAssetUploadComponentDialog {

  fieldValues = {};

  constructor(
    public dialogRef: MatDialogRef<DialogAssetUploadComponentDialog>,
    private dialogS: DialogService,
    ) { }

  onNoClick(): void {

    this.dialogRef.close();
  }

  save() {

    this.dialogRef.close({ fieldValues: this.fieldValues });
  }
}

The HTML for the dialog looks like this:

  <mat-dialog-content>
    <mat-checkbox [(ngModel)]="fieldValues['is_blog']">Blog</mat-checkbox>
    </mat-checkbox>
  </mat-dialog-content>

But no matter what I do I'm getting the error:

Template parse errors:
Can't bind to 'ngModel' since it isn't a known property of 'mat-checkbox'.
1. If 'mat-checkbox' is an Angular component and it has 'ngModel' input, then verify that it is part of this module.
2. If 'mat-checkbox' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message.
3. To allow any property add 'NO_ERRORS_SCHEMA' to the '@NgModule.schemas' of this component.

It would make sense that FormsModule is missing, but it's not -- I have it in the list of imports in my module.ts file. So why is the dialog not able to find it? Any ideas?

**

Edited...

Here's my app.module:

import { NgModule } from '@angular/core';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { BrowserModule } from '@angular/platform-browser';
import { HttpClientModule } from '@angular/common/http';

// core
import { CoreModule } from './core/core.module';

// shared app/admin
import { SharedModule } from './shared/shared.module';

// routing
import { AppRoutingModule } from './app-routing.module';

// components
import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent,
  ],

  imports: [
    AppRoutingModule,
    BrowserAnimationsModule,
    BrowserModule,
    CoreModule,
    HttpClientModule,
    SharedModule,
  ],

  bootstrap: [AppComponent]
})
export class AppModule { }

Here's the shared.module:

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { DatePipe, DecimalPipe } from '@angular/common';
import { FlexLayoutModule } from '@angular/flex-layout';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { MatAutocompleteModule, MatButtonModule, MatButtonToggleModule, MatCardModule, MatCheckboxModule, MatChipsModule, MatDatepickerModule, MatDialogModule, MatExpansionModule, MatFormFieldModule, MatGridListModule, MatIconModule, MatInputModule, MatMenuModule, MatNativeDateModule, MatPaginatorModule, MatProgressSpinnerModule, MatSelectModule, MatSidenavModule, MatSlideToggleModule, MatSnackBarModule, MatSortModule, MatTableModule, MatToolbarModule } from '@angular/material';

// dialogs
import { DialogAssetPickerComponent, DialogAssetPickerComponentDialog } from './dialogs/dialog-asset-picker/dialog-asset-picker.component';
import { DialogAssetUploadComponent, DialogAssetUploadComponentDialog } from './dialogs/dialog-asset-upload/dialog-asset-upload.component';
import { DialogConfirmComponent, DialogConfirmComponentDialog } from './dialogs/dialog-confirm/dialog-confirm.component';
import { DialogSearchFilterComponent } from './dialogs/search-filter/search-filter.component';
import { PaginateDialogComponent } from './dialogs/paginate/paginate.component';

// pipes
import { FilterPipe } from './pipes/filter.pipe';
import { ObjArrPipe } from './pipes/objarr.pipe';
import { SafehtmlPipe } from './pipes/safehtml.pipe';

// quill wysiwyg editor
import { QuillModule } from 'ngx-quill';

@NgModule({

  imports: [
    CommonModule,
    FlexLayoutModule,
    MatAutocompleteModule, MatButtonModule, MatButtonToggleModule, MatCardModule, MatCheckboxModule, MatChipsModule, MatDatepickerModule, MatDialogModule, MatExpansionModule, MatFormFieldModule, MatGridListModule, MatIconModule, MatInputModule, MatMenuModule, MatNativeDateModule, MatPaginatorModule, MatProgressSpinnerModule, MatSelectModule, MatSidenavModule, MatSlideToggleModule, MatSnackBarModule, MatSortModule, MatTableModule, MatToolbarModule,
  ],

  entryComponents: [
    DialogAssetPickerComponentDialog,
    DialogAssetUploadComponentDialog,
    DialogConfirmComponentDialog,
  ],

  declarations: [
    DialogAssetPickerComponentDialog,
    DialogAssetUploadComponentDialog,
    DialogConfirmComponentDialog,
    DialogSearchFilterComponent,
    FilterPipe,
    ObjArrPipe,
    PaginateDialogComponent,
    SafehtmlPipe,
  ],

  exports: [
    CommonModule,
    FilterPipe,
    FlexLayoutModule,
    FormsModule,
    ObjArrPipe,
    MatAutocompleteModule, MatButtonModule, MatButtonToggleModule, MatCardModule, MatCheckboxModule, MatChipsModule, MatDatepickerModule, MatDialogModule, MatExpansionModule, MatFormFieldModule, MatGridListModule, MatIconModule, MatInputModule, MatMenuModule, MatNativeDateModule, MatPaginatorModule, MatProgressSpinnerModule, MatSelectModule, MatSidenavModule, MatSlideToggleModule, MatSnackBarModule, MatSortModule, MatTableModule, MatToolbarModule,
    QuillModule,
    ReactiveFormsModule,
    SafehtmlPipe,
  ],

  providers: [
    DatePipe,
    DecimalPipe,
    DialogAssetPickerComponent,
    DialogAssetUploadComponent,
    DialogConfirmComponent,
    ObjArrPipe,
  ],

})
export class SharedModule { }

And the admin.module then does this

import { SharedModule } from '../shared/shared.module';
...
  imports: [
    SharedModule,
  ],

Body:
You need to import the FormsModule in order to use it for your dependencies; currently, you are just exporting it and your DialogAssetUploadComponentDialog can not find it. Here's what your shared module should look like.

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { DatePipe, DecimalPipe } from '@angular/common';
import { FlexLayoutModule } from '@angular/flex-layout';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { MatAutocompleteModule, MatButtonModule, MatButtonToggleModule, MatCardModule, MatCheckboxModule, MatChipsModule, MatDatepickerModule, MatDialogModule, MatExpansionModule, MatFormFieldModule, MatGridListModule, MatIconModule, MatInputModule, MatMenuModule, MatNativeDateModule, MatPaginatorModule, MatProgressSpinnerModule, MatSelectModule, MatSidenavModule, MatSlideToggleModule, MatSnackBarModule, MatSortModule, MatTableModule, MatToolbarModule } from '@angular/material';

// dialogs
import { DialogAssetPickerComponent, DialogAssetPickerComponentDialog } from './dialogs/dialog-asset-picker/dialog-asset-picker.component';
import { DialogAssetUploadComponent, DialogAssetUploadComponentDialog } from './dialogs/dialog-asset-upload/dialog-asset-upload.component';
import { DialogConfirmComponent, DialogConfirmComponentDialog } from './dialogs/dialog-confirm/dialog-confirm.component';
import { DialogSearchFilterComponent } from './dialogs/search-filter/search-filter.component';
import { PaginateDialogComponent } from './dialogs/paginate/paginate.component';

// pipes
import { FilterPipe } from './pipes/filter.pipe';
import { ObjArrPipe } from './pipes/objarr.pipe';
import { SafehtmlPipe } from './pipes/safehtml.pipe';

// quill wysiwyg editor
import { QuillModule } from 'ngx-quill';

@NgModule({

  imports: [
    CommonModule,
    FlexLayoutModule,
    FormsModule, // ADDED HERE
    MatAutocompleteModule, MatButtonModule, MatButtonToggleModule, MatCardModule, MatCheckboxModule, MatChipsModule, MatDatepickerModule, MatDialogModule, MatExpansionModule, MatFormFieldModule, MatGridListModule, MatIconModule, MatInputModule, MatMenuModule, MatNativeDateModule, MatPaginatorModule, MatProgressSpinnerModule, MatSelectModule, MatSidenavModule, MatSlideToggleModule, MatSnackBarModule, MatSortModule, MatTableModule, MatToolbarModule,
  ],

  entryComponents: [
    DialogAssetPickerComponentDialog,
    DialogAssetUploadComponentDialog,
    DialogConfirmComponentDialog,
  ],

  declarations: [
    DialogAssetPickerComponentDialog,
    DialogAssetUploadComponentDialog,
    DialogConfirmComponentDialog,
    DialogSearchFilterComponent,
    FilterPipe,
    ObjArrPipe,
    PaginateDialogComponent,
    SafehtmlPipe,
  ],

  exports: [
    CommonModule,
    FilterPipe,
    FlexLayoutModule,
    FormsModule,
    ObjArrPipe,
    MatAutocompleteModule, MatButtonModule, MatButtonToggleModule, MatCardModule, MatCheckboxModule, MatChipsModule, MatDatepickerModule, MatDialogModule, MatExpansionModule, MatFormFieldModule, MatGridListModule, MatIconModule, MatInputModule, MatMenuModule, MatNativeDateModule, MatPaginatorModule, MatProgressSpinnerModule, MatSelectModule, MatSidenavModule, MatSlideToggleModule, MatSnackBarModule, MatSortModule, MatTableModule, MatToolbarModule,
    QuillModule,
    ReactiveFormsModule,
    SafehtmlPipe,
  ],

  providers: [
    DatePipe,
    DecimalPipe,
    DialogAssetPickerComponent,
    DialogAssetUploadComponent,
    DialogConfirmComponent,
    ObjArrPipe,
  ],

})
export class SharedModule { }


问:
ManyToMany query
I'm trying to execute a many to many query.

This MySQL query gives me exactly what I want:

```<code>select * from service_offer
left join service on service.id_service = service_offer.id_service
left join user on user.id_user = service_offer.id_user
</code>```

How do I have to do with Symfony?

I tried something like:

```<code>public function findAllServiceOffers(){
    $query = $this->getEntityManager()
        ->createQuery(
        'SELECT s, u FROM AppBundle:Service s
        INNER JOIN AppBundle:User u'
    );

    try {
        return $query->getResult();
    } catch (\Doctrine\ORM\NoResultException $e) {
        return null;
    }
}
</code>```

But I get that error:

[Syntax Error] line 0, col -1: Error: Expected Doctrine\ORM\Query\Lexer::T_WITH, got end of string.

If I add a WHERE or WITH clause, the query executes, but I have NULLs values...

Thanks in advance.

答:
I'm going to give you two examples quickly:

```<code>//use Doctrine\DBAL\Connection;

/** @var Connection $conn */
$conn = $this->getDoctrine()->getConnection();
$aResults = $conn->executeQuery($sql)->fetchAll();
</code>```

OR

```<code>//use Doctrine\DBAL\Connection;

/** @var Connection $conn */
$conn = $this->getDoctrine()->getConnection();
$query = $conn->createQueryBuilder()->select('fields')->from('table1','alias_table1');
$query->leftJoin('alias_table1','table2','alias_table2','alias_table1.ID = alias_table2.ID');
$aResults = $query->execute()->fetchAll();
</code>```

OR

```<code>//use Doctrine\ORM\EntityManager;
/** @var EntityManager $em */
$em = $this->getDoctrine()->getManager();
$sSQL = $em->createQuery("SELECT t1,t2 FROM YourBundle:Table1 t1 LEFT JOIN t1.fieldOfEntityDoctrine t2 WHERE t2.ID = 'example'")->getSQL();
</code>```

Title: ManyToMany query

Body:
I'm trying to execute a many to many query.

This MySQL query gives me exactly what I want:

select * from service_offer
left join service on service.id_service = service_offer.id_service
left join user on user.id_user = service_offer.id_user

How do I have to do with Symfony?

I tried something like:

public function findAllServiceOffers(){
    $query = $this->getEntityManager()
        ->createQuery(
        'SELECT s, u FROM AppBundle:Service s
        INNER JOIN AppBundle:User u'
    );

    try {
        return $query->getResult();
    } catch (\Doctrine\ORM\NoResultException $e) {
        return null;
    }
}

But I get that error:

[Syntax Error] line 0, col -1: Error: Expected Doctrine\ORM\Query\Lexer::T_WITH, got end of string.

If I add a WHERE or WITH clause, the query executes, but I have NULLs values...

Thanks in advance.

Body:
I'm going to give you two examples quickly:

//use Doctrine\DBAL\Connection;

/** @var Connection $conn */
$conn = $this->getDoctrine()->getConnection();
$aResults = $conn->executeQuery($sql)->fetchAll();

OR

//use Doctrine\DBAL\Connection;

/** @var Connection $conn */
$conn = $this->getDoctrine()->getConnection();
$query = $conn->createQueryBuilder()->select('fields')->from('table1','alias_table1');
$query->leftJoin('alias_table1','table2','alias_table2','alias_table1.ID = alias_table2.ID');
$aResults = $query->execute()->fetchAll();

OR

//use Doctrine\ORM\EntityManager;
/** @var EntityManager $em */
$em = $this->getDoctrine()->getManager();
$sSQL = $em->createQuery("SELECT t1,t2 FROM YourBundle:Table1 t1 LEFT JOIN t1.fieldOfEntityDoctrine t2 WHERE t2.ID = 'example'")->getSQL();


问:
When defining class method, why there an equals sign in argument e.g. func(foo=3)
I'm learning python, trying to figure out how does this code actually work:

```<code>def func(**args):
    class BindArgs(object):
       foo = args['foo']
       print 'foo is ', foo
       def __init__(self,args):
           print "hello i am here"
    return BindArgs(args) #return an instance of the class

f = func(foo=2)
</code>```

Output:

foo is  2
hello i am here

But it's very confused that in the argument of a function func(foo=2) that takes equation mark in it. Could you please explain how the flow works?

答:
Here is an abstract:
You call the function func and pass a dictionary as the argument to it.
In the func function, you define a class named BindArgs, and then in the return statement, you first make an object (instance) from the BindArgs class and then return that instance.
Notice that the statement foo = args['foo'] get the key value of 'foo' from the args dictionary (that is 2 in your sample code).
the init also will be run as the constructor of the class when you are creating an object.

Body:
I'm learning python, trying to figure out how does this code actually work:

def func(**args):
    class BindArgs(object):
       foo = args['foo']
       print 'foo is ', foo
       def __init__(self,args):
           print "hello i am here"
    return BindArgs(args) #return an instance of the class

f = func(foo=2)

Output:

foo is  2
hello i am here

But it's very confused that in the argument of a function func(foo=2) that takes equation mark in it. Could you please explain how the flow works?


问:
Akka stream get current value of an infinite stream from outside world
What is the best way to get the current value of an infinite stream which aggregates values and by definition never complete

```<code>Source.repeat(1)
  .scan(0)(_+_)
  .to(Sink.ignore)
</code>```

I would like to query from Akka HTTP the current counter value. Should I use dynamic stream ? The broadcastHub  and then from Akka http subscribe to the infinite stream on GET request ?

答:
One solution could be to use an actor to keep the state you need. Sink.actorRef will wrap an existing actor ref in a sink, e.g.

```<code>class Keeper extends Actor {
  var i: Int = 0

  override def receive: Receive = {
    case n: Int ⇒ i = n
    case Keeper.Get ⇒ sender ! i
  }
}

object Keeper {
  case object Get
}

val actorRef = system.actorOf(Props(classOf[Keeper]))

val q = Source.repeat(1)
  .scan(0)(_+_)
  .runWith(Sink.actorRef(actorRef, PoisonPill))

val result = (actorRef ? Keeper.Get).mapTo[Int]
</code>```

Note that backpressure is not preserved when using Sink.actorRef. This can be improved by using Sink.actorRefWithAck. More about this can be found in the docs.

Body:
What is the best way to get the current value of an infinite stream which aggregates values and by definition never complete

Source.repeat(1)
  .scan(0)(_+_)
  .to(Sink.ignore)

I would like to query from Akka HTTP the current counter value. Should I use dynamic stream ? The broadcastHub  and then from Akka http subscribe to the infinite stream on GET request ?

Body:
One solution could be to use an actor to keep the state you need. Sink.actorRef will wrap an existing actor ref in a sink, e.g.

class Keeper extends Actor {
  var i: Int = 0

  override def receive: Receive = {
    case n: Int ⇒ i = n
    case Keeper.Get ⇒ sender ! i
  }
}

object Keeper {
  case object Get
}

val actorRef = system.actorOf(Props(classOf[Keeper]))

val q = Source.repeat(1)
  .scan(0)(_+_)
  .runWith(Sink.actorRef(actorRef, PoisonPill))

val result = (actorRef ? Keeper.Get).mapTo[Int]

Note that backpressure is not preserved when using Sink.actorRef. This can be improved by using Sink.actorRefWithAck. More about this can be found in the docs.


问:
Regex to change numbers to the next one in line
I'm stuck trying to figure how to implement an idea to my files, my idea is to change numbers to the next one in order, so:

0 to 1

1 to 2

3 to 4 and so on.

This can easily be done with find and replace boxes, but the problem is if I start finding and replacing, the numbers I just increased will change again, I know this kinda doesn't make sense but I need a regex that changes all numbers in the file once to the next number in line

So let's say a line has a 0 and I change it to a 1, I need it to stay a to a 1 and not a 2 when I find and replace 1 to 2, I don't know if I'm explaining myself please anyone help

Examples

```<code>Order66
fight01
fly45
</code>```

I need to be

```<code>Order77
Flight12
fly56
</code>```

If I keep changing them manually with find and replace, they will turn out way different since I keep finding and replacing, that's why I need one regex to do it all at once

答:
Brief

In Notepad++ you can use conditional replacements with regex. See this post by Wiktor for more information.

Code

```<code>(0)|(1)|(2)|(3)|(4)|(5)|(6)|(7)|(8)|(9)
</code>```

Replacement

```<code>(?{1}1)(?{2}2)(?{3}3)(?{4}4)(?{5}5)(?{6}6)(?{7}7)(?{8}8)(?{9}9)(?{10}0)
</code>```

Results

Input

```<code>Order66
fight01
fly45
</code>```

Output

Below output after clicking on Replace All in Notepad++

```<code>Order77
Flight12
fly56
</code>```

Explanation

Each digit is enclosed in its own group i.e. (0).

Each group is given a different identifier. i.e. (0) is group 1

In the replacement we can conditionally target groups that contain values and, as such (?{1}1) targets the first capture group and replaces its contents with 1 ((?{1}) references capture group 1)

Body:
I'm stuck trying to figure how to implement an idea to my files, my idea is to change numbers to the next one in order, so:

0 to 1

1 to 2

3 to 4 and so on.

This can easily be done with find and replace boxes, but the problem is if I start finding and replacing, the numbers I just increased will change again, I know this kinda doesn't make sense but I need a regex that changes all numbers in the file once to the next number in line

So let's say a line has a 0 and I change it to a 1, I need it to stay a to a 1 and not a 2 when I find and replace 1 to 2, I don't know if I'm explaining myself please anyone help

Examples

Order66
fight01
fly45

I need to be

Order77
Flight12
fly56

If I keep changing them manually with find and replace, they will turn out way different since I keep finding and replacing, that's why I need one regex to do it all at once

Body:
Brief

In Notepad++ you can use conditional replacements with regex. See this post by Wiktor for more information.

Code

(0)|(1)|(2)|(3)|(4)|(5)|(6)|(7)|(8)|(9)

Replacement

(?{1}1)(?{2}2)(?{3}3)(?{4}4)(?{5}5)(?{6}6)(?{7}7)(?{8}8)(?{9}9)(?{10}0)

Results

Input

Order66
fight01
fly45

Output

Below output after clicking on Replace All in Notepad++

Order77
Flight12
fly56

Explanation

Each digit is enclosed in its own group i.e. (0).

Each group is given a different identifier. i.e. (0) is group 1

In the replacement we can conditionally target groups that contain values and, as such (?{1}1) targets the first capture group and replaces its contents with 1 ((?{1}) references capture group 1)


问:
fillna does fill the dataframe in the NaN cells
What am I missing? fillna doesn't fill NaN values:

```<code>#filling multi columns df with values..

df.fillna(method='ffill', inplace=True)
df.fillna(method='bfill', inplace=True)

#just for kicks
df = df.fillna(method='ffill')
df = df.fillna(method='bfill')

#retun true
print df.isnull().values.any()
</code>```

I verified it - I actually see NaN values in some first cells..

Edit
So I'm trying to write it myself:

```<code>def bfill(df):
    for column in df:
        for cell in df[column]:
            if cell is not None:
                tmpValue = cell
                break

        for cell in df[column]:
            if cell is not None:
                break
            cell = tmpValue
</code>```

However it doesn't work... Isn't the cell is by ref?

答: ffill fills rows with values from the previous row if they weren't NaN, bfill fills rows with the values from the NEXT row if they weren't NaN.  In both cases, if you have NaNs on the first and/or last row, they won't get filled.  Try doing both one after the other.  If any columns have entirely NaN values then you will need to fill again with axis=1, (although I get a NotImplementedError when I try to do this with inplace=True on python 3.6, which is super annoying, pandas!).

Body:
What am I missing? fillna doesn't fill NaN values:

#filling multi columns df with values..

df.fillna(method='ffill', inplace=True)
df.fillna(method='bfill', inplace=True)

#just for kicks
df = df.fillna(method='ffill')
df = df.fillna(method='bfill')

#retun true
print df.isnull().values.any()

I verified it - I actually see NaN values in some first cells..

Edit
So I'm trying to write it myself:

def bfill(df):
    for column in df:
        for cell in df[column]:
            if cell is not None:
                tmpValue = cell
                break

        for cell in df[column]:
            if cell is not None:
                break
            cell = tmpValue

However it doesn't work... Isn't the cell is by ref?


问:
When use AWS Lambda to process mails from mailgun, can't get mails in JSON format
What I am tried to do is to have a lambda function proccess emails forwarded by mailgun.

So far, I have setup mailgun's route so it will forward emails to a AWS api gateway, then the api gateway triggers a lambda function.

The problem comes when I try to process the mail, instead of getting a pretty Json that I am expecting inside the lambda's event.body, I m getting raw post form data like

--cff4e6b3-a3a4-4131-bb8d-90a73f1b4c36\r\nContent-Disposition: form-data; name=\"Content-Type\"\r\n\r\nmultipart/mixed; boundary=\"001a1140216cee404d05440c49e7\"\r\n--cff4e6b3-a3a4-4131-bb8d-90a73f1b4c36\r\nContent-Disposition: form-data; name=\"Date\"\r\n\r\nTue, 20 Dec 2016 13:40:53 +1300\r\n--cff4e6b3-a3a4-4131-bb8d-90a73f1b4c36\r\nContent ......

My question is, what should I do to get the JSON version of the forwarded emails in lambda?

答:
Not sure if you ever came to a solution, but I have this working with the following settings.

Setup your API Gateway method to use "Use Lambda Proxy integration"

In your lambda (I use node.js) use busboy to work through the multi-part submission from mailgun. (use this post for help with busboy Busboy help)

Make sure that any code you are going to execute after all busboy is complete is executed in the 'finish' portion of the busboy code.


问:
Is it possible to use Glide with the AppIntro library?
I am using the AppIntro library for an app in Android and I want to download the images from my Firebase Storage, I am familiar with Glide and I have actually used it. The problem is that I haven't found any solution on how to access the ImageView so that I can use the into() function from Glide, and I haven't found a way to get the picture as a Drawable resource.

答:
Yes it is possible .... But you will need to implement your firebase functionality within Fragments.

You can set your own fragments in APP INTRO LIBRARY with your own
  views and functionalities.


问:
Builder Vs Decorator pattern
From When would you use the Builder Pattern?,

It is said that builder pattern is appropriate for Pizza example.

Why not Decorator ?
by treating Cheese, Pepperoni, Bacon as additional decorations on a base pizza.

Is it for the reason that Cheese/Pepperoni have to be built seperately. I don't think, they need to be built seperately as they can be available readymade.

Pls clarify.
Am also looking for a good real-world example of decorator pattern and reason why it is the apt for that particular example. Thank you.

答:
From wikipedia's decorator pattern article:

In object-oriented programming, the
  decorator pattern is a design pattern
  that allows new/additional behaviour
  to be added to an existing object
  dynamically.

There's no need to add toppings to a Pizza after it has been fully constructed. You don't eat half a pizza and then add another topping to it.

In other words, the Builder Pattern makes it easy to construct an object which is extensible in independent directions at construction time, while the Decorator Pattern lets you add extensions to functionality to an object after construction time. Using the decorator pattern to construct objects is bad because it leaves the object in an inconsistent (or at least incorrect) state until all the required decorators are in place - similar to the JavaBean problem of using setters to specify optional constructor arguments.

Title: Builder Vs Decorator pattern


问:
How to add an Array to firebase using Swift (Xcode)
Here is my JSON Structure (Ignore the username to email part of it, that is for a test)

```<code>{
  "Username" : {
    "Username" : {
      "email" : "test@gmail.com"
    }
  },
  "uid_0" : {
    "Song List" : [ "The National Anthem" ]
  }
}
</code>```

I am making a very simplistic app using Swift and Xcode. Basically, the user signs into their account after they register. From there the user is able to choose their favorite songs from a band's discography into an empty array. The user is then able to click a button that segues them to a table view controller that contains the songs they added. The way the user adds songs is through a view controller that contains labels that have the song names and buttons next to each song name. When the user clicks the button the label is added to the array.

I want to be able to save the array to firebase so that each user will have their own favorite songs. I have done a decent amount of research and can not find anything to steer me in the right direction as this is incredibly simple. The labels have no keys and are literally just labels being added to an array.

I have the firebase storage and database pods installed as well and I am able to upload images to fire base and have the user save that image to their specific account but how to do the same thing for an array? Here is my code for the array so you can get an idea of how it works.

```<code>import UIKit
import Firebase
import FirebaseStorage
import FirebaseAuth
import LocalAuthentication
import FirebaseDatabase

//var refSongs: DatabaseReference! {
//  return Database.database().reference()

//}

var list = [String]()
class SongsViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    var ref: DatabaseReference!

    override func viewDidLoad() {
        super.viewDidLoad()
        self.ref = Database.database().reference()
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return list.count
    }

    @IBAction func saveSongs(_ sender: Any) {
        //upload array to firebase storage
        //let defaults = UserDefaults.standard.set(list, forKey: "KeySave")
        //addSongs()

        // create add list reference in fire database
        // let addListRef = refSongs.child("Song List").childByAutoId()

        // let addList1 = list

        // addListRef.setValue(addList1)

        let ref = self.ref.child("uid_0").child("Song List")
        // let songArray = [list] *** Removed this
        ref.setValue(list) //changed to list
        retriveList()
    }

    func retriveList() {
        let ref = self.ref.child("uid_0").child("Song List")
        ref.observeSingleEvent(of: .value, with: {snapshot in
            var mySongArray = [String]()
            for child in snapshot.children {
                let snap = child as! DataSnapshot
                let song = snap.value as! String //!! Program crashes here!!
                mySongArray.append(song)
            }
            print(mySongArray)
        })
    }

    // add labels to array
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: "cell")
        cell.textLabel?.text = list[indexPath.row]
        return (cell)
    }

    func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
        if editingStyle == UITableViewCellEditingStyle.delete
        {
            list.remove(at: indexPath.row)
            myTableView.reloadData()
        }
    }

    override func viewDidAppear(_ animated: Bool) {
        myTableView.reloadData()
    }

    @IBOutlet weak var myTableView: UITableView!
}
</code>```

答:
Writing an array to Firebase is incredibly easy and Firebase does most of the work for you.

Suppose the user selects three songs and now you want to store them in the users playlist

```<code>let ref = self.ref.child("uid_0").child("playlist")
let songArray = ["Us and Them", "Get Back", "Children of the Sun"]
ref.setValue(songArray)
</code>```

will result in

```<code>uid_0
  playlist
    0: "Us and Them"
    1: "Get Back"
    2: "Children of the Sun"
</code>```

Now the user selects another song to add to the playlist and you want to save it. Oh wait.. snap.  Firebase treats the array as one object so you have to read the node, delete that node and re-write the node with the new data.

Now suppose the user wants to query for the title of song #2. Can't do that either! Firebase Can't query inside an array.

Ok, so you have 100 users and want to add a feature to show the users whose favorite song is Children of the Sun. Can't do that either.

What if the user wants to have multiple playists?

Basically Arrays Are Evil and limited and there are usually much better options for storing data.

That being said, arrays can be useful in some cases - two options are shown here.

Here's an example

```<code>song_library
   song_0
     title: "Us and Them"
     artist: "Pink Floyd"
     play_count: 100
     total_likes: 167
   song_1
     title: "Get Back"
     artist: "Beatles"
     play_count: 50
     total_likes: 87
   song_2
     title: "Children of the Sun"
     artist: "Billy Thorpe"
     play_count: 98
     total_likes: 1050
   song_3
     title: "21st Century Man"
     artist: "Billy Thorpe"
     play_count: 36
     total_likes: 688
   song_4
     title: "East of Edens Gate"
     artist: "Billy Thorpe"
     play_count: 45
     total_likes: 927

uid_0
   playlist_0
     song_1: 2
     song_2: 0
     song_4: 1
     //or use an array here
     //0: song_2
     //1: song_4
     //2: song_0
   playlist_1
     song_3: 0
     song_4: 1
</code>```

With this structure, you can re-use songs in playlists, the sequence can be easily modified, songs and be removed or added and data duplication is significantly reduced as the playlists just keep references to the actual song data.

EDIT:

To read that node back into an array, here's one option

```<code>let ref = self.ref.child("uid_0").child("playlist")
ref.observeSingleEvent(of: .value, with: { snapshot in
    var mySongArray = [String]()
    for child in snapshot.children {
        let snap = child as! DataSnapshot
        let song = snap.value as! String
        mySongArray.append(song)
    }
    print(mySongArray)
})
</code>```

Note there are other options but this guarantees the order.

Edit 2

This is to help the OP define their class vars correctly.

```<code>class ViewController: UIViewController {

    var ref: DatabaseReference!

    override func viewDidLoad() {
        super.viewDidLoad()
        self.ref = Database.database().reference()
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Here is my JSON Structure (Ignore the username to email part of it, that is for a test)

{
  "Username" : {
    "Username" : {
      "email" : "test@gmail.com"
    }
  },
  "uid_0" : {
    "Song List" : [ "The National Anthem" ]
  }
}

I am making a very simplistic app using Swift and Xcode. Basically, the user signs into their account after they register. From there the user is able to choose their favorite songs from a band's discography into an empty array. The user is then able to click a button that segues them to a table view controller that contains the songs they added. The way the user adds songs is through a view controller that contains labels that have the song names and buttons next to each song name. When the user clicks the button the label is added to the array.

I want to be able to save the array to firebase so that each user will have their own favorite songs. I have done a decent amount of research and can not find anything to steer me in the right direction as this is incredibly simple. The labels have no keys and are literally just labels being added to an array.

I have the firebase storage and database pods installed as well and I am able to upload images to fire base and have the user save that image to their specific account but how to do the same thing for an array? Here is my code for the array so you can get an idea of how it works.

import UIKit
import Firebase
import FirebaseStorage
import FirebaseAuth
import LocalAuthentication
import FirebaseDatabase

//var refSongs: DatabaseReference! {
//  return Database.database().reference()

//}

var list = [String]()
class SongsViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    var ref: DatabaseReference!

    override func viewDidLoad() {
        super.viewDidLoad()
        self.ref = Database.database().reference()
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return list.count
    }

    @IBAction func saveSongs(_ sender: Any) {
        //upload array to firebase storage
        //let defaults = UserDefaults.standard.set(list, forKey: "KeySave")
        //addSongs()

        // create add list reference in fire database
        // let addListRef = refSongs.child("Song List").childByAutoId()

        // let addList1 = list

        // addListRef.setValue(addList1)

        let ref = self.ref.child("uid_0").child("Song List")
        // let songArray = [list] *** Removed this
        ref.setValue(list) //changed to list
        retriveList()
    }

    func retriveList() {
        let ref = self.ref.child("uid_0").child("Song List")
        ref.observeSingleEvent(of: .value, with: {snapshot in
            var mySongArray = [String]()
            for child in snapshot.children {
                let snap = child as! DataSnapshot
                let song = snap.value as! String //!! Program crashes here!!
                mySongArray.append(song)
            }
            print(mySongArray)
        })
    }

    // add labels to array
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: "cell")
        cell.textLabel?.text = list[indexPath.row]
        return (cell)
    }

    func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
        if editingStyle == UITableViewCellEditingStyle.delete
        {
            list.remove(at: indexPath.row)
            myTableView.reloadData()
        }
    }

    override func viewDidAppear(_ animated: Bool) {
        myTableView.reloadData()
    }

    @IBOutlet weak var myTableView: UITableView!
}

Body:
Writing an array to Firebase is incredibly easy and Firebase does most of the work for you.

Suppose the user selects three songs and now you want to store them in the users playlist

let ref = self.ref.child("uid_0").child("playlist")
let songArray = ["Us and Them", "Get Back", "Children of the Sun"]
ref.setValue(songArray)

will result in

uid_0
  playlist
    0: "Us and Them"
    1: "Get Back"
    2: "Children of the Sun"

Now the user selects another song to add to the playlist and you want to save it. Oh wait.. snap.  Firebase treats the array as one object so you have to read the node, delete that node and re-write the node with the new data.

Now suppose the user wants to query for the title of song #2. Can't do that either! Firebase Can't query inside an array.

Ok, so you have 100 users and want to add a feature to show the users whose favorite song is Children of the Sun. Can't do that either.

What if the user wants to have multiple playists?

Basically Arrays Are Evil and limited and there are usually much better options for storing data.

That being said, arrays can be useful in some cases - two options are shown here.

Here's an example

song_library
   song_0
     title: "Us and Them"
     artist: "Pink Floyd"
     play_count: 100
     total_likes: 167
   song_1
     title: "Get Back"
     artist: "Beatles"
     play_count: 50
     total_likes: 87
   song_2
     title: "Children of the Sun"
     artist: "Billy Thorpe"
     play_count: 98
     total_likes: 1050
   song_3
     title: "21st Century Man"
     artist: "Billy Thorpe"
     play_count: 36
     total_likes: 688
   song_4
     title: "East of Edens Gate"
     artist: "Billy Thorpe"
     play_count: 45
     total_likes: 927

uid_0
   playlist_0
     song_1: 2
     song_2: 0
     song_4: 1
     //or use an array here
     //0: song_2
     //1: song_4
     //2: song_0
   playlist_1
     song_3: 0
     song_4: 1

With this structure, you can re-use songs in playlists, the sequence can be easily modified, songs and be removed or added and data duplication is significantly reduced as the playlists just keep references to the actual song data.

EDIT:

To read that node back into an array, here's one option

let ref = self.ref.child("uid_0").child("playlist")
ref.observeSingleEvent(of: .value, with: { snapshot in
    var mySongArray = [String]()
    for child in snapshot.children {
        let snap = child as! DataSnapshot
        let song = snap.value as! String
        mySongArray.append(song)
    }
    print(mySongArray)
})

Note there are other options but this guarantees the order.

Edit 2

This is to help the OP define their class vars correctly.

class ViewController: UIViewController {

    var ref: DatabaseReference!

    override func viewDidLoad() {
        super.viewDidLoad()
        self.ref = Database.database().reference()


问:
Create generic data filter on pandas dataframe in Python
I am trying to create a generic filter on some data. Consider a boiled down example:

```<code>my_data = pd.DataFrame(some_data)
my_filter = {"value": 100, "direction": ">"}
</code>```

now I want to leverage numpy's where to do something like:

```<code>np.where(my_data (...) my_filter["value"])
</code>```

where, as "(...)", I want my_filter["direction"]. Sure, I can use something like "eval(...)" by putting together an appropriate string.

Question But I was wondering if there is a way to do this without eval(...)?

Follow-up on "already answered" claim: The key here is that I need the direction to be generic. Sub-selecting data based on values is easy "np.where(my_data == my_filter["value"])", e.g.

答:
You can use the operator module.
Here is one example

```<code>import pandas as pd
import operator
my_data = pd.DataFrame([[1,1],[1,1]])
my_filter = {"value": 1, "direction": operator.ge}
print(my_data.loc[my_filter["direction"](my_data[0],my_filter["value"])])
</code>```

This should ideally do the job.
Otherwise you can use np.where with some modifications(personally I haven't used np.where much).

Body:
I am trying to create a generic filter on some data. Consider a boiled down example:

my_data = pd.DataFrame(some_data)
my_filter = {"value": 100, "direction": ">"}

now I want to leverage numpy's where to do something like:

np.where(my_data (...) my_filter["value"])

where, as "(...)", I want my_filter["direction"]. Sure, I can use something like "eval(...)" by putting together an appropriate string.

Question But I was wondering if there is a way to do this without eval(...)?

Follow-up on "already answered" claim: The key here is that I need the direction to be generic. Sub-selecting data based on values is easy "np.where(my_data == my_filter["value"])", e.g.

Body:
You can use the operator module.
Here is one example

import pandas as pd
import operator
my_data = pd.DataFrame([[1,1],[1,1]])
my_filter = {"value": 1, "direction": operator.ge}
print(my_data.loc[my_filter["direction"](my_data[0],my_filter["value"])])

This should ideally do the job.
Otherwise you can use np.where with some modifications(personally I haven't used np.where much).


问:
JPA/Hibernate - Embedding an Attribute
I am having a trouble mapping an embedded attribute of a class.  I have created some classes that are similar to what I am trying to do to illustrate.  Basically, I have an @Embeddable class hierarchy that uses Inheritance.  The top level class "Part Number" has only one attribute, and the extending classes add no attributes to the "Part Number" class, they only add some validation/logic.

Here is what I mean:

PART

```<code>@Entity
@Table(name="PART")
public class Part {
    private Integer id;
    private String name;
    private PartNumber partNumber;

    @Id
    @GeneratedValue(strategy=GenerationType.SEQUENCE)
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }

    @Column(name="PART_NAME")
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }

    @Embedded
    public PartNumber getPartNumber() {
        return partNumber;
    }
    public void setPartNumber(PartNumber partNumber) {
        this.partNumber = partNumber;
    }

}
</code>```

PARTNUMBER

```<code>@Embeddable
public abstract class PartNumber {

    protected String partNumber;
    private String generalPartNumber;
    private String specificPartNumber;

    private PartNumber() {

    }

    public PartNumber(String partNumber) {
        this.partNumber = partNumber;

    }

    @Column(name = "PART_NUMBER")
    public String getPartNumber() {
        return partNumber;
    }

    public void setPartNumber(String partNumber) {
        this.partNumber = partNumber;
    }

    /**
     * @param partNumber
     * @return
     */
    public boolean validate(String partNumber) {
        // do some validation
        return true;
    }

    /**
     * Returns the first half of the Part Number
     *
     * @return generalPartNumber
     */
    @Transient
    public String getGeneralPartNumber() {
        return generalPartNumber;

    }

    /**
     * Returns the last half of the Part Number
     * which is specific to each Car Brand
     *
     * @return specificPartNumber
     */
    @Transient
    public String getSpecificPartNumber() {
        return specificPartNumber;

    }

}
</code>```

FORD PARTNUMBER

```<code>public class FordPartNumber extends PartNumber {

    /**
     * Ford Part Number is formatted as 1234-#1234
     *
     * @param partNumber
     */
    public FordPartNumber(String partNumber) {
        super(partNumber);
        validate(partNumber);
    }

    /*
     * (non-Javadoc)
     *
     * @see com.test.PartNumber#validate(java.lang.String)
     */
    @Override
    public boolean validate(String partNumber) {
        // do some validation
        return true;
    }

    /*
     * (non-Javadoc)
     *
     * @see com.test.PartNumber#getGeneralPartNumber()
     */
    @Override
    public String getGeneralPartNumber() {
        return partNumber;

    }

    /*
     * (non-Javadoc)
     *
     * @see com.test.PartNumber#getSpecificPartNumber()
     */
    @Override
    public String getSpecificPartNumber() {
        return partNumber;

    }

}
</code>```

CHEVY PARTNUMBER

```<code>public class ChevyPartNumber extends PartNumber {

    /**
     * Chevy Part Number is formatted as 1234-$1234
     *
     * @param partNumber
     */
    public ChevyPartNumber(String partNumber) {
        super(partNumber);
        validate(partNumber);
    }

    /*
     * (non-Javadoc)
     *
     * @see com.test.PartNumber#validate(java.lang.String)
     */
    @Override
    public boolean validate(String partNumber) {
        // do some validation
        return true;
    }

    /*
     * (non-Javadoc)
     *
     * @see com.test.PartNumber#getGeneralPartNumber()
     */
    @Override
    public String getGeneralPartNumber() {
        return partNumber;

    }

    /*
     * (non-Javadoc)
     *
     * @see com.test.PartNumber#getSpecificPartNumber()
     */
    @Override
    public String getSpecificPartNumber() {
        return partNumber;

    }
}
</code>```

Of course this does not work, because Hibernate ignores the Inheritance Hierarchy and doesn't like the fact that PartNumber is abstract.  Is there some way to do this using JPA or Hibernate Annotations?  I have tried using the @Inheritance JPA annotation.

I am not able to refactor the "PartNumber" part of the hierarchy because the original Developer wants to be able to extend PartNumber with N many XXXXPartNumber classes.

Does anyone know if anything like this will be a part of the JPA 2.0 or a new version of Hibernate?

答:
As it is mentioned in other answers it seems Hibernate doesn't support inheritance of the embeddables (at least I failed to make it work).
I have come up with few workarounds (thanks @ChssPly76 for the inspiration):

1) Replace @Embaddable by @Entity and store PartNumber hierarchy in dedicated table. Of course it requires @OneToOne relation to be used with the composite class (Part).

2) Introduce intermediate entity class which fully reflects the structure of the database table. And then map entity to your domain model classes (and back) manually. This approach provides extreme flexibility at the price of the manual work to write and test mapping code.

3) Store PartNumber descendants in serialized form and rely on serializer which have to be able to instantiate right class during deserialization.

For my task I have chosen third approach. I use Hibernate Types to serialize objects into JSON and store the result in jsonb column of the PostgreSQL. Hibernate Types use Jackson under the hood so all its annotations (including those which controls polymorphic behaviour) are at your disposal. In your case code would be like this:

```<code>@Entity
public class Part {
    // ...

    @Type(type = "com.vladmihalcea.hibernate.type.json.JsonBinaryType")
    private PartNumber partNumber;

}

@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type")
@JsonSubTypes(value = [
    JsonSubTypes.Type(value = FordPartNumber::class, name = "FordPartNumber"),
    JsonSubTypes.Type(value = ChevyPartNumber::class, name = "ChevyPartNumber")
])
public abstract class PartNumber { /* ... */ }

public class FordPartNumber extends PartNumber { /* ... */ }

public class ChevyPartNumber extends PartNumber { /* ... */ }
</code>```

The resulting JSON in database will be looked like

```<code>{
    "type": "FordPartNumber",
    // ... other serialized properties of the FordPartNumber class
}
</code>```

Title: JPA/Hibernate - Embedding an Attribute

Body:
I am having a trouble mapping an embedded attribute of a class.  I have created some classes that are similar to what I am trying to do to illustrate.  Basically, I have an @Embeddable class hierarchy that uses Inheritance.  The top level class "Part Number" has only one attribute, and the extending classes add no attributes to the "Part Number" class, they only add some validation/logic.

Here is what I mean:

PART

@Entity
@Table(name="PART")
public class Part {
    private Integer id;
    private String name;
    private PartNumber partNumber;

    @Id
    @GeneratedValue(strategy=GenerationType.SEQUENCE)
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }

    @Column(name="PART_NAME")
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }

    @Embedded
    public PartNumber getPartNumber() {
        return partNumber;
    }
    public void setPartNumber(PartNumber partNumber) {
        this.partNumber = partNumber;
    }

}

PARTNUMBER

@Embeddable
public abstract class PartNumber {

    protected String partNumber;
    private String generalPartNumber;
    private String specificPartNumber;

    private PartNumber() {

    }

    public PartNumber(String partNumber) {
        this.partNumber = partNumber;

    }

    @Column(name = "PART_NUMBER")
    public String getPartNumber() {
        return partNumber;
    }

    public void setPartNumber(String partNumber) {
        this.partNumber = partNumber;
    }

    /**
     * @param partNumber
     * @return
     */
    public boolean validate(String partNumber) {
        // do some validation
        return true;
    }

    /**
     * Returns the first half of the Part Number
     *
     * @return generalPartNumber
     */
    @Transient
    public String getGeneralPartNumber() {
        return generalPartNumber;

    }

    /**
     * Returns the last half of the Part Number
     * which is specific to each Car Brand
     *
     * @return specificPartNumber
     */
    @Transient
    public String getSpecificPartNumber() {
        return specificPartNumber;

    }

}

FORD PARTNUMBER

public class FordPartNumber extends PartNumber {

    /**
     * Ford Part Number is formatted as 1234-#1234
     *
     * @param partNumber
     */
    public FordPartNumber(String partNumber) {
        super(partNumber);
        validate(partNumber);
    }

    /*
     * (non-Javadoc)
     *
     * @see com.test.PartNumber#validate(java.lang.String)
     */
    @Override
    public boolean validate(String partNumber) {
        // do some validation
        return true;
    }

    /*
     * (non-Javadoc)
     *
     * @see com.test.PartNumber#getGeneralPartNumber()
     */
    @Override
    public String getGeneralPartNumber() {
        return partNumber;

    }

    /*
     * (non-Javadoc)
     *
     * @see com.test.PartNumber#getSpecificPartNumber()
     */
    @Override
    public String getSpecificPartNumber() {
        return partNumber;

    }

}

CHEVY PARTNUMBER

public class ChevyPartNumber extends PartNumber {

    /**
     * Chevy Part Number is formatted as 1234-$1234
     *
     * @param partNumber
     */
    public ChevyPartNumber(String partNumber) {
        super(partNumber);
        validate(partNumber);
    }

    /*
     * (non-Javadoc)
     *
     * @see com.test.PartNumber#validate(java.lang.String)
     */
    @Override
    public boolean validate(String partNumber) {
        // do some validation
        return true;
    }

    /*
     * (non-Javadoc)
     *
     * @see com.test.PartNumber#getGeneralPartNumber()
     */
    @Override
    public String getGeneralPartNumber() {
        return partNumber;

    }

    /*
     * (non-Javadoc)
     *
     * @see com.test.PartNumber#getSpecificPartNumber()
     */
    @Override
    public String getSpecificPartNumber() {
        return partNumber;

    }
}

Of course this does not work, because Hibernate ignores the Inheritance Hierarchy and doesn't like the fact that PartNumber is abstract.  Is there some way to do this using JPA or Hibernate Annotations?  I have tried using the @Inheritance JPA annotation.

I am not able to refactor the "PartNumber" part of the hierarchy because the original Developer wants to be able to extend PartNumber with N many XXXXPartNumber classes.

Does anyone know if anything like this will be a part of the JPA 2.0 or a new version of Hibernate?

Body:
As it is mentioned in other answers it seems Hibernate doesn't support inheritance of the embeddables (at least I failed to make it work).
I have come up with few workarounds (thanks @ChssPly76 for the inspiration):

1) Replace @Embaddable by @Entity and store PartNumber hierarchy in dedicated table. Of course it requires @OneToOne relation to be used with the composite class (Part).

2) Introduce intermediate entity class which fully reflects the structure of the database table. And then map entity to your domain model classes (and back) manually. This approach provides extreme flexibility at the price of the manual work to write and test mapping code.

3) Store PartNumber descendants in serialized form and rely on serializer which have to be able to instantiate right class during deserialization.

For my task I have chosen third approach. I use Hibernate Types to serialize objects into JSON and store the result in jsonb column of the PostgreSQL. Hibernate Types use Jackson under the hood so all its annotations (including those which controls polymorphic behaviour) are at your disposal. In your case code would be like this:

@Entity
public class Part {
    // ...

    @Type(type = "com.vladmihalcea.hibernate.type.json.JsonBinaryType")
    private PartNumber partNumber;

}

@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type")
@JsonSubTypes(value = [
    JsonSubTypes.Type(value = FordPartNumber::class, name = "FordPartNumber"),
    JsonSubTypes.Type(value = ChevyPartNumber::class, name = "ChevyPartNumber")
])
public abstract class PartNumber { /* ... */ }

public class FordPartNumber extends PartNumber { /* ... */ }

public class ChevyPartNumber extends PartNumber { /* ... */ }

The resulting JSON in database will be looked like

{
    "type": "FordPartNumber",
    // ... other serialized properties of the FordPartNumber class
}


问:
Returning frequencies of words in a dictionary
I think I have the right idea on how to solve this function, but I'm not sure
why I don't get the desired results shown in the docstring. Can anyone please help me fix this?</p>

```<code>def list_to_dict(word_list):
'''(list of str) -> dict
Given a list of str (a list of English words) return a dictionary that keeps
track of word length and frequency of length. Each key is a word length and
the corresponding value is the number of words in the given list of that
length.
>>> d = list_to_dict(['This', 'is', 'some', 'text'])
>>> d == {2:1, 4:3}
True
>>> d = list_to_dict(['A', 'little', 'sentence', 'to', 'create', 'a',
'dictionary'])
>>> d == {1:2, 6:2, 8:1, 2:1, 10:1}
True
'''
d = {}
count = 0
for i in range(len(word_list)):
length = len(i)
if length not in d:
    count = count + length
    d[length] = {count}
    count += 1
return d
</code>```

答:
Using Counter definitely is the best option:

```<code>In [ ]: from collections import Counter
   ...: d = Counter(map(len, s))
   ...: d == {1:2, 6:2, 8:1, 2:1, 10:1}
Out[ ]: True
</code>```

Without using "fancy stuff", we use generator expressions, something I consider to be equally fancy:

```<code>Counter(len(i) for i in s)
</code>```

If by "ordinarily" you mean using for loops, we can do that like so:

```<code>d = {}
for i in s:
    if len(i) not in d:
        d[len(i)] = 1
    else:
        d[len(i)] += 1
</code>```

Body:
I think I have the right idea on how to solve this function, but I'm not sure
why I don't get the desired results shown in the docstring. Can anyone please help me fix this?

def list_to_dict(word_list):
'''(list of str) -> dict
Given a list of str (a list of English words) return a dictionary that keeps
track of word length and frequency of length. Each key is a word length and
the corresponding value is the number of words in the given list of that
length.
>>> d = list_to_dict(['This', 'is', 'some', 'text'])
>>> d == {2:1, 4:3}
True
>>> d = list_to_dict(['A', 'little', 'sentence', 'to', 'create', 'a',
'dictionary'])
>>> d == {1:2, 6:2, 8:1, 2:1, 10:1}
True
'''
d = {}
count = 0
for i in range(len(word_list)):
length = len(i)
if length not in d:
    count = count + length
    d[length] = {count}
    count += 1
return d

Body:
Using Counter definitely is the best option:

In [ ]: from collections import Counter
   ...: d = Counter(map(len, s))
   ...: d == {1:2, 6:2, 8:1, 2:1, 10:1}
Out[ ]: True

Without using "fancy stuff", we use generator expressions, something I consider to be equally fancy:

Counter(len(i) for i in s)

If by "ordinarily" you mean using for loops, we can do that like so:

d = {}
for i in s:
    if len(i) not in d:
        d[len(i)] = 1
    else:
        d[len(i)] += 1


问:
Hoptoad v. Exceptional v. exception_notification v. exception_logger
Which of the following exception notification solutions is the best?

Exceptional

Hoptoad

exception_notification

exception_logger

答:
We got one more which is free and very cool.

it's free for many projects.

Checkout http://errorapp.com


问:
What happens when a SQL query runs out of memory?

I want to set up a Postgres server on AWS, the biggest table will be 10GB - do I have to select 10GB of memory for this instance?

What happens when my query result is larger than 10GB?

答:
Nothing will happen, the entire result set is not loaded into memory.  The maximum available memory will be used and re-used as needed while the result is prepared and will spill over to disk as needed.

See PostgreSQL resource documentation for more info.

Specifically, look at work_mem:

work_mem (integer)
  Specifies the amount of memory to be used by internal sort operations and hash tables before writing to temporary disk files.

As long as you don't run out of working memory on a single operation or set of parallel operations you are fine.

Edit: The above was an answer to the question What happens when you query a 10GB table without 10GB of memory on the server/instance?

Here is an updated answer to the updated question:

Only server side resources are used to produce the result set

Assuming JDBC drivers are used, by default, the entire result set is sent to your local computer which could cause out of memory errors

This behavior can be changed by altering the fetch size through the use of a cursor.

Reference to this behavior here

Getting results based on a cursor