问:
Can operations be generalized?
I just wrote this code:

```<code>private double PerformOperation(OperationEnum operation, double aggregateValue,
                                double sourceValue)
{
    if (operation == OperationEnum.Sum)
        return aggregateValue + sourceValue;
    if (operation == OperationEnum.Subtract)
        return aggregateValue - sourceValue;
    if (operation == OperationEnum.Multiply)
        return aggregateValue * sourceValue;
    if (operation == OperationEnum.Divide)
        return aggregateValue / sourceValue;
    throw new InvalidOperationException("Unsupported Aggregation Operation");
}
</code>```

It seems very repetitive.  Is there a way to generalize this?  So I don't have to have 4 lines that are the same except a different sign?

(Note: if there is a better way that does not use the OperationEnum that is great)

答:
A switch would be prettier at least :) and the code will be more efficient (array look-ups etc.). Furthermore, the compiler and IDE can give you some hints when you miss certain options etc.

But as stated in my comment, this isn't really an answer just general code improving.

```<code>switch (operation)
{
    case OperationEnum.Sum:
        return aggregateValue + sourceValue;
    case OperationEnum.Subtract:
        return aggregateValue - sourceValue;
    case OperationEnum.Multiply:
        return aggregateValue * sourceValue;
    case OperationEnum.Divide:
        return aggregateValue / sourceValue;
    default:
        throw new InvalidOperationException("Unsupported Aggregation Operation");
}
</code>```

Title: Can operations be generalized?

Body:
I just wrote this code:

private double PerformOperation(OperationEnum operation, double aggregateValue,
                                double sourceValue)
{
    if (operation == OperationEnum.Sum)
        return aggregateValue + sourceValue;
    if (operation == OperationEnum.Subtract)
        return aggregateValue - sourceValue;
    if (operation == OperationEnum.Multiply)
        return aggregateValue * sourceValue;
    if (operation == OperationEnum.Divide)
        return aggregateValue / sourceValue;
    throw new InvalidOperationException("Unsupported Aggregation Operation");
}

It seems very repetitive.  Is there a way to generalize this?  So I don't have to have 4 lines that are the same except a different sign?

(Note: if there is a better way that does not use the OperationEnum that is great)

Body:
A switch would be prettier at least :) and the code will be more efficient (array look-ups etc.). Furthermore, the compiler and IDE can give you some hints when you miss certain options etc.

But as stated in my comment, this isn't really an answer just general code improving.

switch (operation)
{
    case OperationEnum.Sum:
        return aggregateValue + sourceValue;
    case OperationEnum.Subtract:
        return aggregateValue - sourceValue;
    case OperationEnum.Multiply:
        return aggregateValue * sourceValue;
    case OperationEnum.Divide:
        return aggregateValue / sourceValue;
    default:
        throw new InvalidOperationException("Unsupported Aggregation Operation");
}


来源: stackexchange

问:
Lock holds thread without acquiring the lock
I have an

```<code>ReentrantLock lock = new ReentrantLock();
</code>```

and 2 methods

```<code>public void m1(){
        lock.lock();
        try {
            System.out.println("m1");
        } finally {
            lock.unlock();
        }
}

public void m2(){
        lock.lock();
        try {
            System.out.println("m2");
        } finally {
            lock.unlock();
        }
}
</code>```

I want only method m2 to held the lock and m1 to just check if the lock is held then wait until is unlocked and execute the code, but I don't want m1 to acquire any lock.

For example:

```<code>T1 -> m1 // no lock acquired
T2 -> m1 // no lock acquired
T3 -> m2 // lock acquired
T4 -> m1 // wait until T3 finish executing m2 then execute m1
</code>```

答:
One way to do it, is to use a Condition and wait on a boolean till the condition is true

```<code>Condition methodM2finished= lock.newCondition();
boolean m2done=false;
</code>```

in method m1

```<code>public void m1(){
        lock.lock();
        try {
         while(!m2done){//wait till this flag becomes true
           try{
                methodM2finished.await();
              }
           catch(InterruptedException e){
               e.printStackTrace();
            }
         }
            System.out.println("m1");
        } finally {
            lock.unlock();
        }
}
</code>```

And in m2

```<code>public void m2(){
        lock.lock();
        try {
            System.out.println("m2");
            //after all the business logic is done
           m2done=true;
           methodM2finished.signalAll();
        } finally {
            lock.unlock();
        }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have an

ReentrantLock lock = new ReentrantLock();

and 2 methods

public void m1(){
        lock.lock();
        try {
            System.out.println("m1");
        } finally {
            lock.unlock();
        }
}

public void m2(){
        lock.lock();
        try {
            System.out.println("m2");
        } finally {
            lock.unlock();
        }
}

I want only method m2 to held the lock and m1 to just check if the lock is held then wait until is unlocked and execute the code, but I don't want m1 to acquire any lock.

For example:

T1 -> m1 // no lock acquired
T2 -> m1 // no lock acquired
T3 -> m2 // lock acquired
T4 -> m1 // wait until T3 finish executing m2 then execute m1

Body:
One way to do it, is to use a Condition and wait on a boolean till the condition is true

Condition methodM2finished= lock.newCondition();
boolean m2done=false;

in method m1

public void m1(){
        lock.lock();
        try {
         while(!m2done){//wait till this flag becomes true
           try{
                methodM2finished.await();
              }
           catch(InterruptedException e){
               e.printStackTrace();
            }
         }
            System.out.println("m1");
        } finally {
            lock.unlock();
        }
}

And in m2

public void m2(){
        lock.lock();
        try {
            System.out.println("m2");
            //after all the business logic is done
           m2done=true;
           methodM2finished.signalAll();
        } finally {
            lock.unlock();
        }
}


问:
How do I print out a sentence using linked list in C++?
I just started learning C++.
I want to print out a sentence or at least a word.
I could just use cout<<"hello world";
but I want to use linked list.
Is that possible?</p>

答:
You could do it this way, which uses a linked list and output printing a word or space at a time...</p>

```<code>#include <list>
#include <iostream>
#include <string>

int main() {
  std::list<std::string> words;
  words.push_back("hello");
  words.push_back(" ");
  words.push_back("world");
  for (auto const& word : words) {
    std::cout << word;
  }
  std::cout << std::endl;
}
</code>```

Body:
You could do it this way, which uses a linked list and output printing a word or space at a time...

#include <list>
#include <iostream>
#include <string>

int main() {
  std::list<std::string> words;
  words.push_back("hello");
  words.push_back(" ");
  words.push_back("world");
  for (auto const& word : words) {
    std::cout << word;
  }
  std::cout << std::endl;
}


问:
Html parser to dataframe
I am struggled trying to convert a html table to a dataframe. I would like to write the table in a csv file.

```<code>from requests import session
import sys
import csv
from bs4 import BeautifulSoup

c = session()

outfile = open("Weather2017.csv", 'wb')
response = c.get('http://www.wunderground.com/history/airport/EGLL/2017/1/1/CustomHistory.html?dayend=31&monthend=12&yearend=2017&req_city=NA&req_state=NA&req_statename=NA')
soup = BeautifulSoup(response.text, "html.parser")
soup = soup.find(id="obsTable").text.replace('\n','',1)
outfile.write(soup.replace('\n',',London\n'))
</code>```

the type error is the following

```<code>---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-11-1e149d844e15> in <module>()
     11 soup = BeautifulSoup(response.text, "html.parser")
     12 soup = soup.find(id="obsTable").text.replace('\n','',1)
---> 13 outfile.write(soup.replace('\n',',London\n'))
     14
     15

TypeError: a bytes-like object is required, not 'str'
</code>```

this is the table I want to covert in to a csv file

Can anyone help me?

Thanks in advance!

答:
The things causing a problem in your code when applying BeautifulSoup() are these tags:
tbody , /tbody , thead, /thead. if you get rid of them everything will work well!

Here is a solution using pandas, regex and some other libs :)

```<code>#needed imports
import pandas as pd
import numpy as numpy
from bs4 import BeautifulSoup
import requests
import re

# get page html code
url = 'https://www.wunderground.com/history/airport/EGLL/2017/1/1/CustomHistory.html?dayend=31&monthend=12&yearend=2017&req_city=NA&req_state=NA&req_statename=NA'
req = requests.get(url)
html = req.text
soup = (BeautifulSoup(html, 'html.parser'))

#removing tags that cause problems using re library
patterns = ['<tbody>','</tbody>','<thead>','</thead>']

cleaned_html= soup.prettify()
for pat in patterns:
    cleaned_html = re.sub(pat, '', cleaned_html)

df = pd.read_html(cleaned_html, attrs={'id':'obsTable'})[0]

df.head()
</code>```

```<code># build a hierarchical columns
df.columns = [['2017',
            'Temp. (°C)','Temp. (°C)','Temp. (°C)',
            'Dew Point (°C)','Dew Point (°C)','Dew Point (°C)',
            'Humidity (%)','Humidity (%)','Humidity (%)',
            'Sea Level Press. (hPa)','Sea Level Press. (hPa)','Sea Level Press. (hPa)',
            'Visibility (km)','Visibility (km)','Visibility (km)',
            'Wind (km/h)', 'Wind (km/h)','Wind (km/h)',
            'Precip. (mm)', 'Events'],

            ['Jan',
            'high','avg','low',
            'high','avg','low',
            'high','avg','low',
            'high','avg','low',
            'high','avg','low',
            'high','avg','high',
            'sum',
            'nan']]

df.head()
</code>```

```<code>#removing the first un-needed rows
df = df.drop([0,1], axis=0)
df.reset_index(inplace=True, drop=True)
df.head()
</code>```

```<code>#save the result to CSV file
df.to_csv('weather.csv')
</code>```

Title: Html parser to dataframe

Body:
I am struggled trying to convert a html table to a dataframe. I would like to write the table in a csv file.

from requests import session
import sys
import csv
from bs4 import BeautifulSoup

c = session()

outfile = open("Weather2017.csv", 'wb')
response = c.get('http://www.wunderground.com/history/airport/EGLL/2017/1/1/CustomHistory.html?dayend=31&monthend=12&yearend=2017&req_city=NA&req_state=NA&req_statename=NA')
soup = BeautifulSoup(response.text, "html.parser")
soup = soup.find(id="obsTable").text.replace('\n','',1)
outfile.write(soup.replace('\n',',London\n'))

the type error is the following

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-11-1e149d844e15> in <module>()
     11 soup = BeautifulSoup(response.text, "html.parser")
     12 soup = soup.find(id="obsTable").text.replace('\n','',1)
---> 13 outfile.write(soup.replace('\n',',London\n'))
     14
     15

TypeError: a bytes-like object is required, not 'str'

this is the table I want to covert in to a csv file

Can anyone help me?

Thanks in advance!

Body:
The things causing a problem in your code when applying BeautifulSoup() are these tags:
tbody , /tbody , thead, /thead. if you get rid of them everything will work well!

Here is a solution using pandas, regex and some other libs :)

#needed imports
import pandas as pd
import numpy as numpy
from bs4 import BeautifulSoup
import requests
import re

# get page html code
url = 'https://www.wunderground.com/history/airport/EGLL/2017/1/1/CustomHistory.html?dayend=31&monthend=12&yearend=2017&req_city=NA&req_state=NA&req_statename=NA'
req = requests.get(url)
html = req.text
soup = (BeautifulSoup(html, 'html.parser'))

#removing tags that cause problems using re library
patterns = ['<tbody>','</tbody>','<thead>','</thead>']

cleaned_html= soup.prettify()
for pat in patterns:
    cleaned_html = re.sub(pat, '', cleaned_html)

df = pd.read_html(cleaned_html, attrs={'id':'obsTable'})[0]

df.head()

# build a hierarchical columns
df.columns = [['2017',
            'Temp. (°C)','Temp. (°C)','Temp. (°C)',
            'Dew Point (°C)','Dew Point (°C)','Dew Point (°C)',
            'Humidity (%)','Humidity (%)','Humidity (%)',
            'Sea Level Press. (hPa)','Sea Level Press. (hPa)','Sea Level Press. (hPa)',
            'Visibility (km)','Visibility (km)','Visibility (km)',
            'Wind (km/h)', 'Wind (km/h)','Wind (km/h)',
            'Precip. (mm)', 'Events'],

            ['Jan',
            'high','avg','low',
            'high','avg','low',
            'high','avg','low',
            'high','avg','low',
            'high','avg','low',
            'high','avg','high',
            'sum',
            'nan']]

df.head()

#removing the first un-needed rows
df = df.drop([0,1], axis=0)
df.reset_index(inplace=True, drop=True)
df.head()

#save the result to CSV file
df.to_csv('weather.csv')


问:
java login and add new user program
I need the solution to these errors for this login program and the follow up code to add a new user.
many Thanks.

I need the solution to these errors for this login program and the follow up code to add a new user.
many Thanks.

I need the solution to these errors for this login program and the follow up code to add a new user.
many Thanks.

```<code>package coursework111;

import java.util.Scanner;
import java.util.Random;
/**
 *
 * @author mcq13065590
 */
public class Coursework111 {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {

   // This will populate the contacts array
   // Case sensitive

    String[] contacts = new String[10];

    contacts [0] = "polyMay3378";
    contacts [1] = "john1234567";
    contacts [2] = "Sue22banks";
    contacts [3] = "carrieOak45";

    // This will populate the passwords array
    // Case sensitive
    String[] passwords = new String[10];

    passwords[0]= "Passw123";
    passwords[1]= "DoneTell4";
    passwords[2]= "eASYHac3";
    passwords[3]= "TPd7aqD4";

    // This will populate the memData array
    // Case sensitive
    String[] memData = new String[10];

    memData[0]= "flower23";
    memData[1]= "Belfast1";
    memData[2]= "Beach575";
    memData[3]= "Salou567";

    // variables stated

    String pass;
    String user;

    double randomNumber1;
    double randomNumber2;
    double randomNumber3;

    int index = 0;
    boolean vaildUser = false, vaildPass = false;

    // memorable data char variables

    char char1, char2, char3;

    boolean char1Valid = false;
    boolean char2Valid = false;
    boolean char3Valid = false;

    // add a scanner
    Scanner input = new Scanner(System.in);

    // Main Menu presented to the user

    System.out.println("Welcome to ");
    System.out.println("1 Login ");
    System.out.println("2 Add a new user ");

    int choice = input.nextInt();

    if(choice==1)
    {

        System.out.println("Please enter your username");
        user = input.next();

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

             if(user.equals(contacts[i]))
            {
                index = i;
                vaildUser = true;
            }

        System.out.println("Please enter your password");
        pass = input.next();

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

            if(pass.equals(passwords[index]))
            {
                vaildPass = true;
            }

         // adding random char input

       randomNumber1 = (int)(Math.random()*8+1);
       randomNumber2 = (int)(Math.random()*8+1);
       randomNumber3 = (int)(Math.random()*8+1);

        System.out.println("Please enter characrer" + randomNumber1  + "from your memerable data");

        char1 = input.next().charAt(0);

       if(char1== memData.charAt(randomNumber1))

        {

             char1Valid = true;

        }

        System.out.println("Please enter characrer" + randomNumber2  + "from your memerable data");

        char2 = input.next().charAt(0);

        if(char2== memData.charAt(randomNumber2))

         {

            char2Valid = true;

        }

        System.out.println("Please enter characrer" + randomNumber3  + "from your memerable data");

        char3 = input.next().charAt(0);

        if(char3== memData.charAt(randomNumber3))

         {

            char3Valid = true;

        }

        if(vaildPass== true && vaildUser== true && char1Valid== true && char2Valid== true && char3Valid== true)

        {
            System.out.println("Welcome to SWC Bank.");
        }

        else{
            System.out.println("Please try again.");
        }
</code>```

答:
Please say what you have tried and what do you expect exactly next time. Stack overflow community is a helpful community but not a code error finding service.

In this case, you have this block wrong.

```<code>/*memData is a string array
* You can only use the charAt method for a string, NOT for an array.
**/
if(char1== memData.charAt(randomNumber1)) {
    char1Valid = true;
}
</code>```

Title: java login and add new user program

Body:
I need the solution to these errors for this login program and the follow up code to add a new user.
many Thanks.

I need the solution to these errors for this login program and the follow up code to add a new user.
many Thanks.

I need the solution to these errors for this login program and the follow up code to add a new user.
many Thanks.

package coursework111;

import java.util.Scanner;
import java.util.Random;
/**
 *
 * @author mcq13065590
 */
public class Coursework111 {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {

   // This will populate the contacts array
   // Case sensitive

    String[] contacts = new String[10];

    contacts [0] = "polyMay3378";
    contacts [1] = "john1234567";
    contacts [2] = "Sue22banks";
    contacts [3] = "carrieOak45";

    // This will populate the passwords array
    // Case sensitive
    String[] passwords = new String[10];

    passwords[0]= "Passw123";
    passwords[1]= "DoneTell4";
    passwords[2]= "eASYHac3";
    passwords[3]= "TPd7aqD4";

    // This will populate the memData array
    // Case sensitive
    String[] memData = new String[10];

    memData[0]= "flower23";
    memData[1]= "Belfast1";
    memData[2]= "Beach575";
    memData[3]= "Salou567";

    // variables stated

    String pass;
    String user;

    double randomNumber1;
    double randomNumber2;
    double randomNumber3;

    int index = 0;
    boolean vaildUser = false, vaildPass = false;

    // memorable data char variables

    char char1, char2, char3;

    boolean char1Valid = false;
    boolean char2Valid = false;
    boolean char3Valid = false;

    // add a scanner
    Scanner input = new Scanner(System.in);

    // Main Menu presented to the user

    System.out.println("Welcome to ");
    System.out.println("1 Login ");
    System.out.println("2 Add a new user ");

    int choice = input.nextInt();

    if(choice==1)
    {

        System.out.println("Please enter your username");
        user = input.next();

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

             if(user.equals(contacts[i]))
            {
                index = i;
                vaildUser = true;
            }

        System.out.println("Please enter your password");
        pass = input.next();

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

            if(pass.equals(passwords[index]))
            {
                vaildPass = true;
            }

         // adding random char input

       randomNumber1 = (int)(Math.random()*8+1);
       randomNumber2 = (int)(Math.random()*8+1);
       randomNumber3 = (int)(Math.random()*8+1);

        System.out.println("Please enter characrer" + randomNumber1  + "from your memerable data");

        char1 = input.next().charAt(0);

       if(char1== memData.charAt(randomNumber1))

        {

             char1Valid = true;

        }

        System.out.println("Please enter characrer" + randomNumber2  + "from your memerable data");

        char2 = input.next().charAt(0);

        if(char2== memData.charAt(randomNumber2))

         {

            char2Valid = true;

        }

        System.out.println("Please enter characrer" + randomNumber3  + "from your memerable data");

        char3 = input.next().charAt(0);

        if(char3== memData.charAt(randomNumber3))

         {

            char3Valid = true;

        }

        if(vaildPass== true && vaildUser== true && char1Valid== true && char2Valid== true && char3Valid== true)

        {
            System.out.println("Welcome to SWC Bank.");
        }

        else{
            System.out.println("Please try again.");
        }

Body:
Please say what you have tried and what do you expect exactly next time. Stack overflow community is a helpful community but not a code error finding service.

In this case, you have this block wrong.

/*memData is a string array
* You can only use the charAt method for a string, NOT for an array.
**/
if(char1== memData.charAt(randomNumber1)) {
    char1Valid = true;
}


问:
Peterson's algorithm: Can deadlock occur
if in peterson's algo, A process is preempted just after comming out of critical region before setting its flag to false. Then will not be there a deadlock. ??
plz help !</p>

答: This cannot cause deadlock, because there is nothing that is blocking the process which just exited the critical section from proceeding.</p>

ContentLicense: CC BY-SA 2.5


问:
Pattern Matching In java for repeated pattern
I want my string to match a pattern like this +cat,+dog,-name,+cat

So basically it should start with + or - followed by variable name and then ","

So I want to have a regex for the same for matching the string.

Could you please tell the regex for this pattern ?

答:
Try this ==> ^[+-]\w*[,]

Hope this help!


问:
Using watchdog of python to monitoring afp shared folder from linux
I want linux machine(Raspberry pi) to monitor a shared folder by AFP(Apple file protocol, macbook is host).

I can mount shared folder by mount_afp, and installed watchdog python library to monitor a shared folder. The problem is that watchdog can monitor only modifications from linux machine itself.

If a monitoring folder has been modified by the host machine(Apple macbook) or other pc, linux machine couldn't find out the change. No logs came out.

After I tested the same watchdog python file in host machine(Apple macbook), I can get every logs of modifications by other machine.

Host machine can get every modifications of file or folder. But other machine(guest machine) can not monitor modifications of file from host or others.

Is it normal status of watchdog? Or is there any problem in account and permission?

Here is watchdog sample.

```<code>  import time
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler

class Watcher:
    DIRECTORY_TO_WATCH = "/path/to/my/directory"

    def __init__(self):
        self.observer = Observer()

    def run(self):
        event_handler = Handler()
        self.observer.schedule(event_handler, self.DIRECTORY_TO_WATCH, recursive=True)
        self.observer.start()
        try:
            while True:
                time.sleep(5)
        except:
            self.observer.stop()
            print "Error"

        self.observer.join()

class Handler(FileSystemEventHandler):

    @staticmethod
    def on_any_event(event):
        if event.is_directory:
            return None

        elif event.event_type == 'created':
            # Take any action here when a file is first created.
            print "Received created event - %s." % event.src_path

        elif event.event_type == 'modified':
            # Taken any action here when a file is modified.
            print "Received modified event - %s." % event.src_path

if __name__ == '__main__':
    w = Watcher()
    w.run()
</code>```

答:
For network mounts, the usual filesystem events don't always get emitted. In such cases, instead of using Observer, try using PollingObserver -- i.e., change from:

```<code>   self.observer = Observer()
</code>```

to

```<code>   from watchdog.observers.polling import PollingObserver
   ...
   self.observer = PollingObserver()
</code>```

There is also a PollingObserverVFS class you could experiment with.

Documentation: https://pythonhosted.org/watchdog/api.html#module-watchdog.observers.polling

Body:
I want linux machine(Raspberry pi) to monitor a shared folder by AFP(Apple file protocol, macbook is host).

I can mount shared folder by mount_afp, and installed watchdog python library to monitor a shared folder. The problem is that watchdog can monitor only modifications from linux machine itself.

If a monitoring folder has been modified by the host machine(Apple macbook) or other pc, linux machine couldn't find out the change. No logs came out.

After I tested the same watchdog python file in host machine(Apple macbook), I can get every logs of modifications by other machine.

Host machine can get every modifications of file or folder. But other machine(guest machine) can not monitor modifications of file from host or others.

Is it normal status of watchdog? Or is there any problem in account and permission?

Here is watchdog sample.

  import time
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler

class Watcher:
    DIRECTORY_TO_WATCH = "/path/to/my/directory"

    def __init__(self):
        self.observer = Observer()

    def run(self):
        event_handler = Handler()
        self.observer.schedule(event_handler, self.DIRECTORY_TO_WATCH, recursive=True)
        self.observer.start()
        try:
            while True:
                time.sleep(5)
        except:
            self.observer.stop()
            print "Error"

        self.observer.join()

class Handler(FileSystemEventHandler):

    @staticmethod
    def on_any_event(event):
        if event.is_directory:
            return None

        elif event.event_type == 'created':
            # Take any action here when a file is first created.
            print "Received created event - %s." % event.src_path

        elif event.event_type == 'modified':
            # Taken any action here when a file is modified.
            print "Received modified event - %s." % event.src_path

if __name__ == '__main__':
    w = Watcher()
    w.run()

Body:
For network mounts, the usual filesystem events don't always get emitted. In such cases, instead of using Observer, try using PollingObserver -- i.e., change from:

   self.observer = Observer()

to

   from watchdog.observers.polling import PollingObserver
   ...
   self.observer = PollingObserver()

There is also a PollingObserverVFS class you could experiment with.

Documentation: https://pythonhosted.org/watchdog/api.html#module-watchdog.observers.polling

ContentLicense: CC BY-SA 4.0


问:
How to select max price using multiple query
i have create tow table,  table and data inserting value are given below :

```<code>create table product (
pid number(10) primary key,
pname varchar2(30)
);

INSERT INTO product values(100,'Apple');
INSERT INTO product values(101,'Banana');
INSERT INTO product values(102,'Pinaple');
INSERT INTO product values(103,'Orange');

create table purchase(
invid  number(10) primary key,
pid number(10),
pprice number(10)
);
alter table purchase add(constraint pid_fk FOREIGN KEY (pid) references  product(pid));

INSERT INTO  purchase values(10,101,30);
INSERT INTO  purchase values(11,103,35);
INSERT INTO  purchase values(12,103,9);
INSERT INTO  purchase values(13,103,22);
INSERT INTO  purchase values(14,101,12);
</code>```

now i have select table purchase show give data

```<code>invid    pid  pprice
10       101   30
11       103   35
12       103    9
13       103   22
14       101   12
</code>```

now i want to be last insert price pid=103
now need show  pprice=22
i have all ready done the task using two query  such as:

select max(invid) from purchase where pid=103;

result is 22  and running next statement

select max(pprice) from purchase where invid=13;

show result =22
 i want to show result 22 using  running one statment,

答:
Probably the most direct way is to use a subquery:

```<code>SELECT MAX(pprice)
FROM purchase
WHERE invid = (SELECT MAX(invid) FROM purchase WHERE pid = 103)
</code>```

Side note, you don't need to MAX() pprice based on your sample data, but I left it that way in case you need it for your real data set.

Body:
i have create tow table,  table and data inserting value are given below :

create table product (
pid number(10) primary key,
pname varchar2(30)
);

INSERT INTO product values(100,'Apple');
INSERT INTO product values(101,'Banana');
INSERT INTO product values(102,'Pinaple');
INSERT INTO product values(103,'Orange');

create table purchase(
invid  number(10) primary key,
pid number(10),
pprice number(10)
);
alter table purchase add(constraint pid_fk FOREIGN KEY (pid) references  product(pid));

INSERT INTO  purchase values(10,101,30);
INSERT INTO  purchase values(11,103,35);
INSERT INTO  purchase values(12,103,9);
INSERT INTO  purchase values(13,103,22);
INSERT INTO  purchase values(14,101,12);

now i have select table purchase show give data

invid    pid  pprice
10       101   30
11       103   35
12       103    9
13       103   22
14       101   12

now i want to be last insert price pid=103
now need show  pprice=22
i have all ready done the task using two query  such as:

select max(invid) from purchase where pid=103;

result is 22  and running next statement

select max(pprice) from purchase where invid=13;

show result =22
 i want to show result 22 using  running one statment,

Body:
Probably the most direct way is to use a subquery:

SELECT MAX(pprice)
FROM purchase
WHERE invid = (SELECT MAX(invid) FROM purchase WHERE pid = 103)

Side note, you don't need to MAX() pprice based on your sample data, but I left it that way in case you need it for your real data set.


问:
A javascript upload progress display in HTML5
I am very new to js and html programming. I am using following code to make a progress-bar which displays file upload progress. But it is not working on tryit editor

```<code><!DOCTYPE html>
<head>
<meta charset="UTF-8">
<style>
.progress-wrapper {
    width:100%;
}
.progress-wrapper .progress {
    background-color:green;
    width:0%;
    padding:5px 0px 5px 0px;
}
</style>
<script>
function postFile() {
    var formdata = new FormData();

    formdata.append('file1', $('#file1')[0].files[0]);

    var request = new XMLHttpRequest();

    request.upload.addEventListener('progress', function (e) {
        var file1Size = $('#file1')[0].files[0].size;

        if (e.loaded <= file1Size) {
            var percent = Math.round(e.loaded / file1Size * 100);
            $('#progress-bar-file1').width(percent + '%').html(percent + '%');
        }

        if(e.loaded == e.total){
            $('#progress-bar-file1').width(100 + '%').html(100 + '%');
        }
    });

    request.open('post', '/echo/html/');
    request.timeout = 45000;
    request.send(formdata);
}
</script>
</head>
<form id="form1">
    <input id="file1" type="file" />
    <div class="progress-wrapper">
        <div id="progress-bar-file1" class="progress"></div>
    </div>
    <button type="button" onclick="postFile()">Upload File</button>
</form>
</html>
</code>```

I have tried on my local system too,it is not working here too. What I am doing wrong? Please tell me how can I improve the code. I want to display a progress-bar which shows upload percentage of file using ajax calls.

答:
You need to add reference of JQuery in your head before writing any JavaScript. Please see correct version below.

```<code><!DOCTYPE html>
<head>
<meta charset="UTF-8">
<style>
.progress-wrapper {
    width:100%;
}
.progress-wrapper .progress {
    background-color:green;
    width:0%;
    padding:5px 0px 5px 0px;
}
</style>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.js"></script>
<script>
function postFile() {
    var formdata = new FormData();

    formdata.append('file1', $('#file1')[0].files[0]);

    var request = new XMLHttpRequest();

    request.upload.addEventListener('progress', function (e) {
        var file1Size = $('#file1')[0].files[0].size;

        if (e.loaded <= file1Size) {
            var percent = Math.round(e.loaded / file1Size * 100);
            $('#progress-bar-file1').width(percent + '%').html(percent + '%');
        }

        if(e.loaded == e.total){
            $('#progress-bar-file1').width(100 + '%').html(100 + '%');
        }
    });

    request.open('post', '/echo/html/');
    request.timeout = 45000;
    request.send(formdata);
}
</script>
</head>
<form id="form1">
    <input id="file1" type="file" />
    <div class="progress-wrapper">
        <div id="progress-bar-file1" class="progress"></div>
    </div>
    <button type="button" onclick="postFile()">Upload File</button>
</form>
</html>
</code>```

Body:
I am very new to js and html programming. I am using following code to make a progress-bar which displays file upload progress. But it is not working on tryit editor

<!DOCTYPE html>

<meta charset="UTF-8">

<form id="form1">
    <input id="file1" type="file" />

    <button type="button" onclick="postFile()">Upload File</button>
</form>

I have tried on my local system too,it is not working here too. What I am doing wrong? Please tell me how can I improve the code. I want to display a progress-bar which shows upload percentage of file using ajax calls.

Body:
You need to add reference of JQuery in your head before writing any JavaScript. Please see correct version below.

<!DOCTYPE html>
<head>
<meta charset="UTF-8">
<style>
.progress-wrapper {
    width:100%;
}
.progress-wrapper .progress {
    background-color:green;
    width:0%;
    padding:5px 0px 5px 0px;
}
</style>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.js"></script>
<script>
function postFile() {
    var formdata = new FormData();

    formdata.append('file1', $('#file1')[0].files[0]);

    var request = new XMLHttpRequest();

    request.upload.addEventListener('progress', function (e) {
        var file1Size = $('#file1')[0].files[0].size;

        if (e.loaded <= file1Size) {
            var percent = Math.round(e.loaded / file1Size * 100);
            $('#progress-bar-file1').width(percent + '%').html(percent + '%');
        }

        if(e.loaded == e.total){
            $('#progress-bar-file1').width(100 + '%').html(100 + '%');
        }
    });

    request.open('post', '/echo/html/');
    request.timeout = 45000;
    request.send(formdata);
}
</script>
</head>
<form id="form1">
    <input id="file1" type="file" />
    <div class="progress-wrapper">
        <div id="progress-bar-file1" class="progress"></div>
    </div>
    <button type="button" onclick="postFile()">Upload File</button>
</form>
</html>


问:
determine selector validity
I have a function like this:

```<code>function parseValue(value, defaultValue) {
    if ($.isFunction(value))
        return value();

    if (!value)
        return defaultValue;

    if ($(value).size() > 0)
        return $(value).val();

    return value;
};
</code>```

value can be a function, a "value", or a jquery selector.  My problem is how do I determine that the selector is valid (finds a control).

for example, when value equals 56.87 $(value).size() > 0 evaluates to true.  I want it to be false.  Even if something like #invalidcontrolid was passed in, if it doesn't actually exist on the page, I want to get false back so I can return the value.  Any ideas?

答:
.size() is just a wrapper method for .length property. So this should (and does) work:

http://www.jsfiddle.net/EawgE/

You should check within your parseValue method if value actually is a number. If so, just return false or whatever but don't pass it into the jQuery constructor.

```<code>if( typeof value === 'number' ) {}
</code>```

or

```<code>if( $.type(value) === 'number' ) {}
</code>```

Example:

```<code>function parseValue(value, defaultValue) {
    if ($.isFunction(value))
        return value();

    if ( $.type(value) === 'number' )
        return value; // ?

    if ( $.type(value) === 'string' && $(value).length )
        return $(value).val();

    return defaultValue;
};
</code>```

Title: determine selector validity

Body:
I have a function like this:

function parseValue(value, defaultValue) {
    if ($.isFunction(value))
        return value();

    if (!value)
        return defaultValue;

    if ($(value).size() > 0)
        return $(value).val();

    return value;
};

value can be a function, a "value", or a jquery selector.  My problem is how do I determine that the selector is valid (finds a control).

for example, when value equals 56.87 $(value).size() > 0 evaluates to true.  I want it to be false.  Even if something like #invalidcontrolid was passed in, if it doesn't actually exist on the page, I want to get false back so I can return the value.  Any ideas?

Body:
.size() is just a wrapper method for .length property. So this should (and does) work:

http://www.jsfiddle.net/EawgE/

You should check within your parseValue method if value actually is a number. If so, just return false or whatever but don't pass it into the jQuery constructor.

if( typeof value === 'number' ) {}

or

if( $.type(value) === 'number' ) {}

Example:

function parseValue(value, defaultValue) {
    if ($.isFunction(value))
        return value();

    if ( $.type(value) === 'number' )
        return value; // ?

    if ( $.type(value) === 'string' && $(value).length )
        return $(value).val();

    return defaultValue;
};


问:
How to make a button show a table onclick
I am trying to embed a table inside a button to no avail, such that when the button is clicked the table shows and when it is clicked again, the table disappears. Here is a copy of my code:

function myfunction(){
  document.getElementById("displaytable").style.display = "none";
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="button" value="Button1" onclick='myfunction();'>
<div id="displaytable" style="visibility: hidden">
  <table id="displaytable" style="display: none; width: 100%" cellpadding="1" cellspacing="0" border="3">
    <tr align="center">
      <td class="lbl">column1</td>
      <td class="lbl">column2</td>
      <td class="lbl">column3</td>
    </tr>
    <tr>
      <td align="center">1</td>
      <td align="center">2</td>
      <td align="center">33</td>
    </tr>
    <tr>
      <td align="center">4</td>
      <td align="center">5</td>
      <td align="center">6</td>
    </tr>
  </table>
</div></code>```

答:
This a bit rework on your code. Vanilla only. HTML is just a bit different, with some new id's.

```<code><input id="toggleVisibilityButton" type="button" value="Button1"/>
<table  id="displaytable" style="display:none" width="100%" cellpadding="1" cellspacing="0" border="3">
    <tr align="center">
            <td class="lbl">column1</td>
            <td class="lbl">column2</td>
            <td class="lbl">column3</td>
            </tr>
    <tr>
            <td align="center">1</td>
            <td align="center">2</td>
             <td align="center">33</td>
            </tr>
            <tr>
            <td align="center">4</td>
            <td align="center">5</td>
           <td align="center">6</td>
            </tr>
</table>
</code>```

And JS I kept as simple as possible, since I assume you are the beginner and don't need something more elegant:

```<code>document.getElementById("toggleVisibilityButton").addEventListener("click", function(button) {
   if (document.getElementById("displaytable").style.display === "none")             document.getElementById("displaytable").style.display = "block";
   else document.getElementById("displaytable").style.display = "none";
});
</code>```

You can test it here:
fiddle JS

NOTE:

I changed the way you bind your actions to elements. You are trying to do it directly from HTML and on to a function that you haven't stored as variable. This is not the best practice.

Instead I followed an approach referred to as:
Unobtrusive JavaScript

Body:
I am trying to embed a table inside a button to no avail, such that when the button is clicked the table shows and when it is clicked again, the table disappears. Here is a copy of my code:

function myfunction(){
  document.getElementById("displaytable").style.display = "none";
}

<input type="button" value="Button1" onclick='myfunction();'>

      column1
      column2
      column3

      1
      2
      33

      4
      5
      6

Body:
This a bit rework on your code. Vanilla only. HTML is just a bit different, with some new id's.

<input id="toggleVisibilityButton" type="button" value="Button1"/>
<table  id="displaytable" style="display:none" width="100%" cellpadding="1" cellspacing="0" border="3">
    <tr align="center">
            <td class="lbl">column1</td>
            <td class="lbl">column2</td>
            <td class="lbl">column3</td>
            </tr>
    <tr>
            <td align="center">1</td>
            <td align="center">2</td>
             <td align="center">33</td>
            </tr>
            <tr>
            <td align="center">4</td>
            <td align="center">5</td>
           <td align="center">6</td>
            </tr>
</table>

And JS I kept as simple as possible, since I assume you are the beginner and don't need something more elegant:

document.getElementById("toggleVisibilityButton").addEventListener("click", function(button) {
   if (document.getElementById("displaytable").style.display === "none")             document.getElementById("displaytable").style.display = "block";
   else document.getElementById("displaytable").style.display = "none";
});

You can test it here:
fiddle JS

NOTE:

I changed the way you bind your actions to elements. You are trying to do it directly from HTML and on to a function that you haven't stored as variable. This is not the best practice.

Instead I followed an approach referred to as:
Unobtrusive JavaScript


问:
selenium throwing element not visible exception error when element is actually visible in the page
I am trying to login in the sandbox Paypal application using the given url but,It throws element not visible exception error when trying to find the email id and password field in the page using the below code.

Code to reproduce an issue

```<code>driver.get("https://www.sandbox.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token=EC-7NA824468C3295748#/checkout/login");
Thread.sleep(20000);
driver.findElement(By.cssSelector("input[id='email']")).sendKeys("shariftest@gmail.com");
driver.findElement(By.cssSelector("input[id='password']")).sendKeys("test@1234");
driver.findElement(By.id("btnLogin")).click();
Thread.sleep(6000);
</code>```

Its very strange that these element locators are absolutely correct and its visible in the page, but still throw an error when trying to find the element using selenium.

Please try the above code to reproduce the issue.

答:
Try using Javascript implementation:</p>

```<code>JavascriptExecutor jse = (JavascriptExecutor)driver
jse.executeScript("document.getElementById('email').setAttribute('value', 'shariftest@gmail.com')");
</code>```

Body:
I am trying to login in the sandbox Paypal application using the given url but,It throws element not visible exception error when trying to find the email id and password field in the page using the below code.

Code to reproduce an issue

driver.get("https://www.sandbox.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token=EC-7NA824468C3295748#/checkout/login");
Thread.sleep(20000);
driver.findElement(By.cssSelector("input[id='email']")).sendKeys("shariftest@gmail.com");
driver.findElement(By.cssSelector("input[id='password']")).sendKeys("test@1234");
driver.findElement(By.id("btnLogin")).click();
Thread.sleep(6000);

Its very strange that these element locators are absolutely correct and its visible in the page, but still throw an error when trying to find the element using selenium.

Please try the above code to reproduce the issue.

Body:
Try using Javascript implementation:

JavascriptExecutor jse = (JavascriptExecutor)driver
jse.executeScript("document.getElementById('email').setAttribute('value', 'shariftest@gmail.com')");


问:
Creating Dictionary (English dictionary ) with python
Recently I made a English word definition dictionary as described in a course in udemy.

They have used a  data.json file which contains a dictionary inside it with all the words and their meaning as key value pair, so it was an easy task.

Are there some more ways to create dictionary and what data to use, like if I don't have a dictionary (key value pair).

Any ideas ??

答: A python dictionary would definitely be the easiest way to store word : definitions (key-value pairs), and you can import from or export to a json file as well. Of course, there are other structures like lists, but they are far less optimal. A pandas dataframe could work and would be useful if you wanted to have multiple entries with the same key but different definitions: e.g. key + def 1, key + def 2, key + def 3, since much like an excel sheet, each entry could be its own row which are then sorted based on key.</p>


问:
How to have objects contiguous in memory without loosing OOP?
Consider a code where we have a list of countries that contain a list of cities that contains a list of streets. Each City in a given Country contains exactly the same number of Streets (nbStreetsPerCity) and this number of streets per City is constant over time.

```<code>class Street
{

};

class City
{
   // Attribute
   std::vector<Street> Streets;

   // getter
   Street& getStreet(int street_index) {return Streets[street_index];}
   // More stuff

};

class Country
{
   // Attribute
   std::vector<City> Cities;

   // getter
   City& getCity(int city_index) {return Cities[city_index];}

   // More stuff

};
</code>```

I have to loop through each Street and the process is quite fast when I have many Streets and few Cityies but is quite slow when I have many Cityies with few Streets

With such code, the Streets of all Cityies of a given Country are not contiguous in memory. For performance reasons, I would like to try a code with having all Streets of a given Country being contiguous in memory. I can't think of a way to have all the Streets contiguous in memory without destroying part of the object oriented programming.

```<code>class Street
{

};

class Country
{
   // Attribute
   std::vector<Street> Streets;
   int nbStreetsPerCity;

   // getter
   City getStreet(int city_index, int street_index)
   {
       Streets[city_index*nbStreetsPerCity + street_index]
   };

   // More stuff

};
</code>```

With such code, all Streets of a given country are contiguous in memory, however, I lost the City object and therefore lost the advantage of OOP.

Is there a way to have all streets being contiguous in memory without loosing the advantage of OOP?

A very simple example would be very welcome!

答:
It can be done for the lowest level of such a fan-out but it would be a massive pain, for one thing you would have to know how many streets a city has before the allocation, and for another each street would have to be an equal sized object (meaning street names would have a maximum length).

You would replace the vector with a count and zero-sized array at the end of the city object, and instead of allocating with new you would have to use malloc or some other allocator and then use placement new to initialize the city into that buffer. You would then go through the list of steets and copy them into the array that actually exits after the city object.

Like I said, it can be done but is a pain. Make sure you actually have reason to do something like thins before going down such a path.

Body:
Consider a code where we have a list of countries that contain a list of cities that contains a list of streets. Each City in a given Country contains exactly the same number of Streets (nbStreetsPerCity) and this number of streets per City is constant over time.

class Street
{

};

class City
{
   // Attribute
   std::vector<Street> Streets;

   // getter
   Street& getStreet(int street_index) {return Streets[street_index];}
   // More stuff

};

class Country
{
   // Attribute
   std::vector<City> Cities;

   // getter
   City& getCity(int city_index) {return Cities[city_index];}

   // More stuff

};

I have to loop through each Street and the process is quite fast when I have many Streets and few Cityies but is quite slow when I have many Cityies with few Streets

With such code, the Streets of all Cityies of a given Country are not contiguous in memory. For performance reasons, I would like to try a code with having all Streets of a given Country being contiguous in memory. I can't think of a way to have all the Streets contiguous in memory without destroying part of the object oriented programming.

class Street
{

};

class Country
{
   // Attribute
   std::vector<Street> Streets;
   int nbStreetsPerCity;

   // getter
   City getStreet(int city_index, int street_index)
   {
       Streets[city_index*nbStreetsPerCity + street_index]
   };

   // More stuff

};

With such code, all Streets of a given country are contiguous in memory, however, I lost the City object and therefore lost the advantage of OOP.

Is there a way to have all streets being contiguous in memory without loosing the advantage of OOP?

A very simple example would be very welcome!


问:
Google Compute Engine loses static ip when started and stopped
I had a Google Compute Engine Wordpress application running on a dedicated ip number, with cloud DNS also set up. I needed to start and stop the apache web server in order to change the debut settings of php.ini. So I looked around for how to do it from gcloud or google's gui based interface, and decided after reading about stopping and starting and instance that that would be the way to go.

When I restarted the instance though, it had now assigned a 'ephemeral' ip address to the instance. To add insult to injury the ephemeral instance would not allow outside connections. Nor does the old static ip work.

I'm not pleased with having to delete everything and start from scratch, but I may have to .

Can anybody tell me what I did wrong. How should I reboot the virtual machine without losing my ip and my stored configurations?

答:
The restart of the virtual machine wouldn't release the reserved static IP address. Check in VPC network > External IP addresses. There you should be able to find the IP that was attached to the instance.

If it isn't there, means you never really reserved it, and a ephemeral one was attach to your instance.

I believe you already have read it, but I attach the docs anyways if it can help you.

By the way, you shouldn't need to remake everything, just attach the IP to your instance again.


问:
load multiple tables in one spreadsheet into R
I have an Excel worksheet containing multiple tables that I want to import into R (import as multiple data frame). I know how to do that if these tables are stored in different tabs, but the raw file that I'm using has several tables in one tab.

Part view of my spreadsheet

I'm wondering if it is possible to have R read each table into a separate data frame by a certain function. Say once R reads a blank row, it just stops and imports all above rows into one table, then restart the process to read the second table, for example. Or do I have to manually save each table into a separate tab/sheet to let R read them?

Note: I cannot use nrow=n in the read.table package as the row of each table might be changing. I need to find a more universal way to make the whole process automatic, regardless of the structure of each table.

答:
If you reliably have blank rows delimiting your sheets, you might try reading each tab in as a big table, then splitting it that way.</p>

```<code>library(tidyverse)
library(readxl)

# read the whole thing into a single file
wholeworksheet  <- read_excel('myfile.xlsx')

# find the blank rows
blankrows  <- data_frame(
    blanks = which(is.na(wholeworksheet[1]))
  ) %>%
  mutate(
      dif = blanks - lag(blanks)
    , rownum = row_number()

    # maybe someone can suggest a better way to handle using dplyr::lag()
    , startrow = ifelse(rownum == 1, 1, NA)
    , startrow = coalesce(ifelse(dif == 1, lag(startrow, default =1), lag(blanks + 1)), 1)
  )

# get the end rows of each table
endrows  <- blankrows %>%
  group_by(startrow) %>%
  summarize(
    endrow = min(blanks)
  )

# combine start and end rows into a single table
tableindex <- blankrows %>%
  left_join(endrows, by = 'startrow') %>%
  distinct(startrow, endrow)

# the last blank row is probably just before the last table in the sheet
if(nrow(wholeworksheet) > max(blankrows$blanks)) {

  lasttable  <- data_frame(startrow = max(blankrows$blanks) + 1, endrow = nrow(wholeworksheet))
  tableindex  <- tableindex %>%
    bind_rows(lasttable)
}

# split your tables up into a list of tables
alistoftables  <- map(1:nrow(tableindex), ~ wholeworksheet[tableindex$startrow[.x]:tableindex$endrow[.x] , ]  )
</code>```

Body:
If you reliably have blank rows delimiting your sheets, you might try reading each tab in as a big table, then splitting it that way.

library(tidyverse)
library(readxl)

# read the whole thing into a single file
wholeworksheet  <- read_excel('myfile.xlsx')

# find the blank rows
blankrows  <- data_frame(
    blanks = which(is.na(wholeworksheet[1]))
  ) %>%
  mutate(
      dif = blanks - lag(blanks)
    , rownum = row_number()

    # maybe someone can suggest a better way to handle using dplyr::lag()
    , startrow = ifelse(rownum == 1, 1, NA)
    , startrow = coalesce(ifelse(dif == 1, lag(startrow, default =1), lag(blanks + 1)), 1)
  )

# get the end rows of each table
endrows  <- blankrows %>%
  group_by(startrow) %>%
  summarize(
    endrow = min(blanks)
  )

# combine start and end rows into a single table
tableindex <- blankrows %>%
  left_join(endrows, by = 'startrow') %>%
  distinct(startrow, endrow)

# the last blank row is probably just before the last table in the sheet
if(nrow(wholeworksheet) > max(blankrows$blanks)) {

  lasttable  <- data_frame(startrow = max(blankrows$blanks) + 1, endrow = nrow(wholeworksheet))
  tableindex  <- tableindex %>%
    bind_rows(lasttable)
}

# split your tables up into a list of tables
alistoftables  <- map(1:nrow(tableindex), ~ wholeworksheet[tableindex$startrow[.x]:tableindex$endrow[.x] , ]  )


问:
Select only latest record for every employees and for specific employee in MySQL
I have a MySQL DB and in it there's a table with activity logs of employees.

```<code>+-------------------------------------------------+
| log_id | employee_id | date_time  | action_type |
+-------------------------------------------------+
|   1    |      1      | 2015/02/03 |   action1   |
|   2    |      2      | 2015/02/01 |   action1   |
|   3    |      2      | 2017/01/02 |   action2   |
|   4    |      3      | 2016/02/12 |   action1   |
|   5    |      1      | 2016/10/12 |   action2   |
+-------------------------------------------------+
</code>```

And I would need 2 queries. First, to get for every employee his last action. So from this example table I would need to get row 3,4 and 5 with all columns. And second, get the latest action only for specified employee.

Any ideas how to achieve this? I'm using Spring Data JPA, but raw SQL Query would be also great.

Thank you in advance.

答:
Ready for a fred ed...</p>

```<code>SELECT x.*
  FROM my_table x
  JOIN
     ( SELECT employee_id
            , MAX(date_time) date_time
         FROM my_table
        GROUP
           BY employee_id
     ) y
    ON y.employee_id = x.employee_id
   AND y.date_time = x.date_time;
</code>```

Body:
I have a MySQL DB and in it there's a table with activity logs of employees.

+-------------------------------------------------+
| log_id | employee_id | date_time  | action_type |
+-------------------------------------------------+
|   1    |      1      | 2015/02/03 |   action1   |
|   2    |      2      | 2015/02/01 |   action1   |
|   3    |      2      | 2017/01/02 |   action2   |
|   4    |      3      | 2016/02/12 |   action1   |
|   5    |      1      | 2016/10/12 |   action2   |
+-------------------------------------------------+

And I would need 2 queries. First, to get for every employee his last action. So from this example table I would need to get row 3,4 and 5 with all columns. And second, get the latest action only for specified employee.

Any ideas how to achieve this? I'm using Spring Data JPA, but raw SQL Query would be also great.

Thank you in advance.

Body:
Ready for a fred ed...

SELECT x.*
  FROM my_table x
  JOIN
     ( SELECT employee_id
            , MAX(date_time) date_time
         FROM my_table
        GROUP
           BY employee_id
     ) y
    ON y.employee_id = x.employee_id
   AND y.date_time = x.date_time;


问:
Angular 2+ refreshing real time data conditionally without refreshing the page
I get a transaction from API service, the condition is if the transaction status is 'pending', keep reloading and subscribing the transaction until the transaction status is 'completed' or 'rejected'. My code only works for the first time, then next time visit, the page is blank but the data still runs in console even though I unsubscribed it.

Here is my code:

```<code>export class TransactionSummaryComponent implements OnInit, OnDestroy {

  transaction: Models.Transaction = <Models.Transaction>{};

  cancelling: boolean = false;
  goToPayment: boolean = false;

  private dataRefreshSub: Subscription;
  private subscribeToDataSub: Subscription;
  private timer: Observable<any>;

  constructor(
    private route: ActivatedRoute,
    private router: Router,
    private apiService: ApiService,
    private zone: NgZone,
    @Inject(PLATFORM_ID) private platformId: Object) { }

  ngOnInit() {
    if (isPlatformBrowser(this.platformId)) {
      this.getTransaction();
    }
  }

  getTransaction() {
    this.route.paramMap
    .switchMap((params: ParamMap) => this.apiService.getTransaction(params.get('id')))
    .subscribe((transaction: Models.Transaction) => {
      this.transaction = transaction;

      if (this.transaction.status === 'Pending') {
        this.refreshData();
      }
    });
  }

  refreshData() {
    this.dataRefreshSub = this.route.paramMap
      .switchMap((params: ParamMap) => this.apiService.getTransaction(params.get('id')))
      .subscribe((transaction: Models.Transaction) => {
        this.transaction = transaction;
        this.subscribeToData();
      });
  }

  subscribeToData() {
    this.zone.runOutsideAngular(() => {
      NgZone.assertNotInAngularZone();
      this.timer = Observable.timer(1, 5000);
      this.subscribeToDataSub = this.timer
        .subscribe(() => {
          this.refreshData();
        });
    });
  }

  ngOnDestroy() {
    if (this.dataRefreshSub !== undefined) {
      this.dataRefreshSub.unsubscribe();
    }
    if (this.subscribeToDataSub !== undefined) {
      this.subscribeToDataSub.unsubscribe();
    }
  }
}
</code>```

答:
I couldn't come up with a solution that doesn't use side effects, but I think it may help you. Rxjs has a retry() operator, which will rerun the subscription for you when it throws. So I'd do something like this:

```<code>getTransaction() {
    this.route.paramMap
        .switchMap((params: ParamMap) => this.apiService
            .getTransaction(params.get('id'))
            .do(transaction => this.transaction = transaction) // Bad side effect here, I'm not sure how can this be cleaned out.
            .map(transaction => {
                if(transaction.status === 'Pending') {
                    throw 'Pending';
                }
                return transaction;
            })
            // use .retry(N) to retry at most N times. This will infinitely retry
            .retryWhen(errors => errors)
        )
        .subscribe((transaction: Models.Transaction) => {
            // Here transaction will be 'Completed' or 'Rejected'
        });
}
</code>```

With this you can delete all other subscriptions, in theory.

Body:
I get a transaction from API service, the condition is if the transaction status is 'pending', keep reloading and subscribing the transaction until the transaction status is 'completed' or 'rejected'. My code only works for the first time, then next time visit, the page is blank but the data still runs in console even though I unsubscribed it.

Here is my code:

export class TransactionSummaryComponent implements OnInit, OnDestroy {

  transaction: Models.Transaction = <Models.Transaction>{};

  cancelling: boolean = false;
  goToPayment: boolean = false;

  private dataRefreshSub: Subscription;
  private subscribeToDataSub: Subscription;
  private timer: Observable<any>;

  constructor(
    private route: ActivatedRoute,
    private router: Router,
    private apiService: ApiService,
    private zone: NgZone,
    @Inject(PLATFORM_ID) private platformId: Object) { }

  ngOnInit() {
    if (isPlatformBrowser(this.platformId)) {
      this.getTransaction();
    }
  }

  getTransaction() {
    this.route.paramMap
    .switchMap((params: ParamMap) => this.apiService.getTransaction(params.get('id')))
    .subscribe((transaction: Models.Transaction) => {
      this.transaction = transaction;

      if (this.transaction.status === 'Pending') {
        this.refreshData();
      }
    });
  }

  refreshData() {
    this.dataRefreshSub = this.route.paramMap
      .switchMap((params: ParamMap) => this.apiService.getTransaction(params.get('id')))
      .subscribe((transaction: Models.Transaction) => {
        this.transaction = transaction;
        this.subscribeToData();
      });
  }

  subscribeToData() {
    this.zone.runOutsideAngular(() => {
      NgZone.assertNotInAngularZone();
      this.timer = Observable.timer(1, 5000);
      this.subscribeToDataSub = this.timer
        .subscribe(() => {
          this.refreshData();
        });
    });
  }

  ngOnDestroy() {
    if (this.dataRefreshSub !== undefined) {
      this.dataRefreshSub.unsubscribe();
    }
    if (this.subscribeToDataSub !== undefined) {
      this.subscribeToDataSub.unsubscribe();
    }
  }
}

Body:
I couldn't come up with a solution that doesn't use side effects, but I think it may help you. Rxjs has a retry() operator, which will rerun the subscription for you when it throws. So I'd do something like this:

getTransaction() {
    this.route.paramMap
        .switchMap((params: ParamMap) => this.apiService
            .getTransaction(params.get('id'))
            .do(transaction => this.transaction = transaction) // Bad side effect here, I'm not sure how can this be cleaned out.
            .map(transaction => {
                if(transaction.status === 'Pending') {
                    throw 'Pending';
                }
                return transaction;
            })
            // use .retry(N) to retry at most N times. This will infinitely retry
            .retryWhen(errors => errors)
        )
        .subscribe((transaction: Models.Transaction) => {
            // Here transaction will be 'Completed' or 'Rejected'
        });
}

With this you can delete all other subscriptions, in theory.


问:
Can operations be generalized?
I just wrote this code:

```<code>private double PerformOperation(OperationEnum operation, double aggregateValue,
                                double sourceValue)
{
    if (operation == OperationEnum.Sum)
        return aggregateValue + sourceValue;
    if (operation == OperationEnum.Subtract)
        return aggregateValue - sourceValue;
    if (operation == OperationEnum.Multiply)
        return aggregateValue * sourceValue;
    if (operation == OperationEnum.Divide)
        return aggregateValue / sourceValue;
    throw new InvalidOperationException("Unsupported Aggregation Operation");
}
</code>```

It seems very repetitive.  Is there a way to generalize this?  So I don't have to have 4 lines that are the same except a different sign?

(Note: if there is a better way that does not use the OperationEnum that is great)

答:
Yes, using List<Func<double, double, double>>:

List<T> accessor works mush faster than Dictionary<> accessor, and comparable to switch statement ;)

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace test
{
    class Program
    {
        enum OperationEnum : int { Sum, Muiltiply, Divide, Subtract }
        static List<Func<double, double, double>> actions = new List<Func<double, double, double>>()
        {
            { (a,b) => a+b },
            { (a,b) => a*b },
            { (a,b) => a/b },
            { (a,b) => a-b },
        };
        static void Main(string[] args)
        {
            Console.WriteLine(string.Format("{0}", actions[(int)OperationEnum.Sum](1, 3));
        }
    }
}
</code>```

Title: Can operations be generalized?

Body:
I just wrote this code:

private double PerformOperation(OperationEnum operation, double aggregateValue,
                                double sourceValue)
{
    if (operation == OperationEnum.Sum)
        return aggregateValue + sourceValue;
    if (operation == OperationEnum.Subtract)
        return aggregateValue - sourceValue;
    if (operation == OperationEnum.Multiply)
        return aggregateValue * sourceValue;
    if (operation == OperationEnum.Divide)
        return aggregateValue / sourceValue;
    throw new InvalidOperationException("Unsupported Aggregation Operation");
}

It seems very repetitive.  Is there a way to generalize this?  So I don't have to have 4 lines that are the same except a different sign?

(Note: if there is a better way that does not use the OperationEnum that is great)

Body:
Yes, using List<Func<double, double, double>>:

List<T> accessor works mush faster than Dictionary<> accessor, and comparable to switch statement ;)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace test
{
    class Program
    {
        enum OperationEnum : int { Sum, Muiltiply, Divide, Subtract }
        static List<Func<double, double, double>> actions = new List<Func<double, double, double>>()
        {
            { (a,b) => a+b },
            { (a,b) => a*b },
            { (a,b) => a/b },
            { (a,b) => a-b },
        };
        static void Main(string[] args)
        {
            Console.WriteLine(string.Format("{0}", actions[(int)OperationEnum.Sum](1, 3));
        }
    }
}


问:
Error when converting List to IEnumerable
I am trying to display the default index page for a model. But I get the below error.

The model item passed into the dictionary is of type
  'System.Collections.Generic.List 1[System.Boolean]', but this
  dictionary requires a model item of type
  'System.Collections.Generic.IEnumerable`1[EDIWebsite.Models.Error_Details]'.

Controller

```<code> public ActionResult FindRelatedBols(string bolnumber)
        {
            if (bolnumber == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            var error_Summaries = db.Error_Details.Select(r => r.BOL == bolnumber);
            if (error_Summaries == null)
            {
                return HttpNotFound();
            }
            return PartialView("~/Views/Error_Details/Index.cshtml",error_Summaries.ToList());
        }
</code>```

View

```<code>@model IEnumerable<EDIWebsite.Models.Error_Details>

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

<p>
    @Html.ActionLink("Create New", "Create")
</p>
<table class="table">
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.Source_System)
        </th>
.
.
.
            @Html.ActionLink("Edit", "Edit", new { /* id=item.PrimaryKey */ }) |
            @Html.ActionLink("Details", "Details", new { /* id=item.PrimaryKey */ }) |
            @Html.ActionLink("Delete", "Delete", new { /* id=item.PrimaryKey */ })
        </td>
    </tr>
}

</table>
</code>```

答:
The error is self explanatory. Your view is strongly typed to a collection of Error_Details objects.Your current code is generating IQueryable<bool> as the type of error_Summaries variable and you are later calling the ToList() on that, which will generate a list of boolean values(List<bool>).

Your view is expecting something(IEnumerable<Error_Details>) and your action method is passing something else(List<bool>), hence getting that type mismatch exception!

You need to pass a collection of Error_Details objects to the view. I assume you wanted to pass a filtered list of items which is has the same BOL value as your bolnumber parameter. You can use the LINQ Where method to do the filtering.

```<code>var items =  db.Error_Details.Where(a=>a.BOL == bolnumber).ToList();
return PartialView("~/Views/Error_Details/Index.cshtml",items);
</code>```

Assuming the BOL property on Error_Details class is of string type.

Body:
I am trying to display the default index page for a model. But I get the below error.

The model item passed into the dictionary is of type
  'System.Collections.Generic.List 1[System.Boolean]', but this
  dictionary requires a model item of type
  'System.Collections.Generic.IEnumerable`1[EDIWebsite.Models.Error_Details]'.

Controller

 public ActionResult FindRelatedBols(string bolnumber)
        {
            if (bolnumber == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            var error_Summaries = db.Error_Details.Select(r => r.BOL == bolnumber);
            if (error_Summaries == null)
            {
                return HttpNotFound();
            }
            return PartialView("~/Views/Error_Details/Index.cshtml",error_Summaries.ToList());
        }

View

@model IEnumerable<EDIWebsite.Models.Error_Details>

@{
    ViewBag.Title = "Index";
}

Index

    @Html.ActionLink("Create New", "Create")

            @Html.DisplayNameFor(model => model.Source_System)

.
.
.
            @Html.ActionLink("Edit", "Edit", new { /* id=item.PrimaryKey */ }) |
            @Html.ActionLink("Details", "Details", new { /* id=item.PrimaryKey */ }) |
            @Html.ActionLink("Delete", "Delete", new { /* id=item.PrimaryKey */ })

}

Body:
The error is self explanatory. Your view is strongly typed to a collection of Error_Details objects.Your current code is generating IQueryable<bool> as the type of error_Summaries variable and you are later calling the ToList() on that, which will generate a list of boolean values(List<bool>).

Your view is expecting something(IEnumerable<Error_Details>) and your action method is passing something else(List<bool>), hence getting that type mismatch exception!

You need to pass a collection of Error_Details objects to the view. I assume you wanted to pass a filtered list of items which is has the same BOL value as your bolnumber parameter. You can use the LINQ Where method to do the filtering.

var items =  db.Error_Details.Where(a=>a.BOL == bolnumber).ToList();
return PartialView("~/Views/Error_Details/Index.cshtml",items);

Assuming the BOL property on Error_Details class is of string type.


问:
Why doesn't setSpan work after the screen rotates?
I made a minimal repro of what appears to be a bug in my code. Create an empty app and paste the following in:

```<code><!-- content_main.xml -->

<EditText
    android:id="@+id/main_editText"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

// MainActivity.java

private static SpannableStringBuilder sText;

private EditText mEditText;

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

    if (sText == null) {
        sText = new SpannableStringBuilder("Hello world!");
    }

    mEditText = (EditText) findViewById(R.id.main_editText);
    mEditText.setEditableFactory(new Editable.Factory() {
        @Override
        public Editable newEditable(CharSequence source) {
            return (Editable) source;
        }
    });
    mEditText.setText(sText, TextView.BufferType.EDITABLE);

    workLoop(0);
}

private void workLoop(final int index) {
    SpannableStringBuilder text = sText;
    if (index == text.length()) {
        return;
    }

    text.setSpan(new ForegroundColorSpan(Color.BLUE), index, index + 1, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
    Handler uiThreadHandler = new Handler(Looper.getMainLooper());
    uiThreadHandler.postDelayed(new Runnable() {
        @Override
        public void run() {
            workLoop(index + 1);
        }
    }, 5000);
}
</code>```

Explanation: This code will put the text Hello, world! in an EditText, then proceed to color each letter blue after 5-second intervals.

However, if I rotate the screen, causing the Activity to be destroyed/re-created, the text stops being colored. Why does this happen?

答:
It happens, because after rotation Activity calls onRestoreInstanceState() callback method and overrides value of EditText. You should add something like this:

```<code>@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
    super.onRestoreInstanceState(savedInstanceState);
    mEditText.setText(sText, TextView.BufferType.EDITABLE);
}
</code>```

Also pay attention at this line:

```<code>uiThreadHandler.postDelayed(new Runnable() {
    @Override
    public void run() {
        workLoop(index + 1);
    }
}, 5000);
</code>```

Anonymous Runnable stay runned and references to old MainActivity instance after new instance of MainActivity created due to screen rotation. I recommend to clear Handler's callbacks in Activity.onDestroy() method.

Body:
I made a minimal repro of what appears to be a bug in my code. Create an empty app and paste the following in:

<EditText
    android:id="@+id/main_editText"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

// MainActivity.java

private static SpannableStringBuilder sText;

private EditText mEditText;

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

    if (sText == null) {
        sText = new SpannableStringBuilder("Hello world!");
    }

    mEditText = (EditText) findViewById(R.id.main_editText);
    mEditText.setEditableFactory(new Editable.Factory() {
        @Override
        public Editable newEditable(CharSequence source) {
            return (Editable) source;
        }
    });
    mEditText.setText(sText, TextView.BufferType.EDITABLE);

    workLoop(0);
}

private void workLoop(final int index) {
    SpannableStringBuilder text = sText;
    if (index == text.length()) {
        return;
    }

    text.setSpan(new ForegroundColorSpan(Color.BLUE), index, index + 1, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
    Handler uiThreadHandler = new Handler(Looper.getMainLooper());
    uiThreadHandler.postDelayed(new Runnable() {
        @Override
        public void run() {
            workLoop(index + 1);
        }
    }, 5000);
}

Explanation: This code will put the text Hello, world! in an EditText, then proceed to color each letter blue after 5-second intervals.

However, if I rotate the screen, causing the Activity to be destroyed/re-created, the text stops being colored. Why does this happen?

Body:
It happens, because after rotation Activity calls onRestoreInstanceState() callback method and overrides value of EditText. You should add something like this:

@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
    super.onRestoreInstanceState(savedInstanceState);
    mEditText.setText(sText, TextView.BufferType.EDITABLE);
}

Also pay attention at this line:

uiThreadHandler.postDelayed(new Runnable() {
    @Override
    public void run() {
        workLoop(index + 1);
    }
}, 5000);

Anonymous Runnable stay runned and references to old MainActivity instance after new instance of MainActivity created due to screen rotation. I recommend to clear Handler's callbacks in Activity.onDestroy() method.


问:
Android Room Cannot figure out how to save this field into database
I'm try to using save values to database via room persistance library. My SettingsValueModelConverter is wrong somethings are missing. How I can save SettingsKeyContract objects best way?

Logcat:

```<code>SettingsModel

Error:(14, 1) error: Cannot figure out how to save this field into database. You can consider adding a type converter for it.
</code>```

Codes:

```<code>object SETTING_CONS{
    const val TABLE = "Content_Setting"
    const val ID    = "uid"
    const val KEY   = "key"
    const val VALUE = "value"
}

class SettingsValueModel(var value: SettingsKeyContract)
class SettingsValueModelConverter {

    @TypeConverter
    fun fromString(value: String): SettingsKeyContract = Gson().fromJson(value, object : TypeToken<SettingsKeyContract>() {}.type)

    @TypeConverter
    fun fromModel(value: SettingsKeyContract): String = Gson().toJson(value)

}

@Entity(tableName = SETTING_CONS.TABLE)
class SettingsModel(@ColumnInfo(name = SETTING_CONS.KEY) @SETTINGS var key: String,
                    @ColumnInfo(name = SETTING_CONS.VALUE) var value: SettingsValueModel) {

    @ColumnInfo(name = SETTING_CONS.ID)
    @PrimaryKey(autoGenerate = true)
    var uid: Int = 0

}

@Dao
interface SettingsDao {

    @Query("SELECT * FROM ${SETTING_CONS.TABLE} WHERE ${SETTING_CONS.ID} = :key")
    fun get(@SETTINGS key: String): LiveData<SettingsModel>

    @get:Query("SELECT * FROM ${SETTING_CONS.TABLE}")
    val all: LiveData<MutableList<SettingsModel>>

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    fun insert(model: SettingsModel): Long

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    fun insertAll(vararg models: SettingsModel): LongArray

    @Query("DELETE FROM ${SETTING_CONS.TABLE} WHERE ${SETTING_CONS.KEY} = :key")
    fun delete(@SETTINGS key: String)

    @Query("DELETE FROM ${SETTING_CONS.TABLE}")
    fun clear()

}

interface SettingsKeyContract { val key: String }
interface TypeSettingsKeyContract<out T : Any> : SettingsKeyContract { val default: T }

sealed class SETTING(override val key: String) : SettingsKeyContract {

    object FIRST_LAUNCH_DATE : SETTING("first_launch_date"), TypeSettingsKeyContract<Long> { override val default = 0L }

}
</code>```

答:
Where do you define your database?
You should have the option there to specify which converter to use, like such :</p>

```<code>@Database(entities = arrayOf(SettingsModel::class) , version = 1, exportSchema = false)
@TypeConverters(SettingsValueModelConverter::class)
abstract class AppDatabase: RoomDatabase() {
    abstract fun SettingsDao(): SettingsDao
}
</code>```

Body:
I'm try to using save values to database via room persistance library. My SettingsValueModelConverter is wrong somethings are missing. How I can save SettingsKeyContract objects best way?

Logcat:

SettingsModel

Error:(14, 1) error: Cannot figure out how to save this field into database. You can consider adding a type converter for it.

Codes:

object SETTING_CONS{
    const val TABLE = "Content_Setting"
    const val ID    = "uid"
    const val KEY   = "key"
    const val VALUE = "value"
}

class SettingsValueModel(var value: SettingsKeyContract)
class SettingsValueModelConverter {

    @TypeConverter
    fun fromString(value: String): SettingsKeyContract = Gson().fromJson(value, object : TypeToken<SettingsKeyContract>() {}.type)

    @TypeConverter
    fun fromModel(value: SettingsKeyContract): String = Gson().toJson(value)

}

@Entity(tableName = SETTING_CONS.TABLE)
class SettingsModel(@ColumnInfo(name = SETTING_CONS.KEY) @SETTINGS var key: String,
                    @ColumnInfo(name = SETTING_CONS.VALUE) var value: SettingsValueModel) {

    @ColumnInfo(name = SETTING_CONS.ID)
    @PrimaryKey(autoGenerate = true)
    var uid: Int = 0

}

@Dao
interface SettingsDao {

    @Query("SELECT * FROM ${SETTING_CONS.TABLE} WHERE ${SETTING_CONS.ID} = :key")
    fun get(@SETTINGS key: String): LiveData<SettingsModel>

    @get:Query("SELECT * FROM ${SETTING_CONS.TABLE}")
    val all: LiveData<MutableList<SettingsModel>>

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    fun insert(model: SettingsModel): Long

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    fun insertAll(vararg models: SettingsModel): LongArray

    @Query("DELETE FROM ${SETTING_CONS.TABLE} WHERE ${SETTING_CONS.KEY} = :key")
    fun delete(@SETTINGS key: String)

    @Query("DELETE FROM ${SETTING_CONS.TABLE}")
    fun clear()

}

interface SettingsKeyContract { val key: String }
interface TypeSettingsKeyContract<out T : Any> : SettingsKeyContract { val default: T }

sealed class SETTING(override val key: String) : SettingsKeyContract {

    object FIRST_LAUNCH_DATE : SETTING("first_launch_date"), TypeSettingsKeyContract<Long> { override val default = 0L }

}

Body:
Where do you define your database?
You should have the option there to specify which converter to use, like such :

@Database(entities = arrayOf(SettingsModel::class) , version = 1, exportSchema = false)
@TypeConverters(SettingsValueModelConverter::class)
abstract class AppDatabase: RoomDatabase() {
    abstract fun SettingsDao(): SettingsDao
}


问:
showing popup window behind main window using javascript
i want to make my pop up window will showing behind main windows.
say it window 1 is main windows and window 2 is popup window.
so when someone click window 1, window 2 will pop up behind window 1.
im already try window.focus and window.blur but no one working. remember this, I'm just making this one for learning.

```<code>    <script type="text/javascript">
      var popup = function() {
        var lastShownTs = +localStorage.getItem("lastShown");
        var currentDate = new Date();
        currentDate.setHours(0, 0, 0, 0);
        var lastShown = null;
        if (!isNaN(lastShownTs)) {
          lastShown = new Date(lastShownTs);
          lastShown.setHours(0, 0, 0, 0);
        }
        if (lastShown == null || lastShown.getTime() != currentDate.getTime()) {
          window.open("example.com", "Window", "status=1,toolbar=1,width=1,height=1,left=5000,top=5000,scrollbars=1,resizable=1");
          localStorage.setItem("lastShown", currentDate.getTime());
        }
window.focus();
popup.blur();
      }
    </script>

    <body onclick="popup()"></body>
</code>```

答:
I believe what you are looking for is referred to as a "Pop-under".
See https://developer.mozilla.org/en-US/docs/Web/API/Window/open.

Alternately, here is a cheat using tabs ...

```<code><script>
    function popunder() {
        var currentURL = document.URL;
        window.open(currentURL, '_blank', 'toolbar=yes, location=yes, status=yes, menubar=yes, scrollbars=yes');
        window.location = 'http://www.stackoverflow.com';
    }

</script>
<a href="#" onclick="popunder()">Click here!</a>
</code>```

Tested Chrome 62.0.3202.62.

Body:
I believe what you are looking for is referred to as a "Pop-under".
See https://developer.mozilla.org/en-US/docs/Web/API/Window/open.

Alternately, here is a cheat using tabs ...

<script>
    function popunder() {
        var currentURL = document.URL;
        window.open(currentURL, '_blank', 'toolbar=yes, location=yes, status=yes, menubar=yes, scrollbars=yes');
        window.location = 'http://www.stackoverflow.com';
    }

</script>
<a href="#" onclick="popunder()">Click here!</a>

Tested Chrome 62.0.3202.62.


问:
C# yield return enumerator, continue from part the way through
I am using yield return to process some data, with a non-deterministic set of iterations. I want to start processing, but break from the loop once a condition has been hit (e.g. byte size), pass the enumerator to a new thread that will continue to process, and then return the results processed so far.

In effect I have a foreach loop which I will likely break out of before the end. How can I pass the IEnumerable to a new thread and 'continue' from where I left off rather than the beginning?

```<code>public static IEnumerable<String> Process()
{
    // static values added for simplicity, but will be a variable number of returns
    yield return "1";
    yield return "2";
    yield return "3";
    yield return "4";
    yield return "5";
    yield return "6";
}

List<String> main()
{
    List<String> retVal = new List<String>();
    IEnumerable<String> strList = Process();

    foreach(String strItem in strList)
    {
        retVal.Add(strItem);
        Console.WriteLine(strItem);
        // Time to send something back and continue in a new thread
        if (strItem.Equals("3"))
        {
            break;
        }
    }

    new Thread(() => ThreadFunc(strList)).Start();
    return retVal;
}

public static void ThreadFunc(IEnumerable<String> strList)
{
    List<String> retVal = new List<String>();
    foreach(String strItem in strList)
     {
        retVal.Add(strItem);
        Console.WriteLine(strItem);
     }
     // Send the rest of the data

}
</code>```

Desired output: 1 2 3 4 5 6

Actual output: 1 2 3 1 2 3 4 5 6

Thank You.

答:
Look at what the IEnumerable<T> interface actually does.

IEnumerable<T> is completely stateless; it just exposes a GetEnumerator() method, which hands back stateful enumerators that keep track of where they're up to.

You need to pass the same enumerator instance between your two loops.  foreach can only operate on IEnumerable<T> (or similar), so you'll need to replace them with while loops that use IEnumerator<T> directly.

Make sure to dispose the IEnumerator in all codepaths (otherwise, finally or using blocks won't run).

Body:
I am using yield return to process some data, with a non-deterministic set of iterations. I want to start processing, but break from the loop once a condition has been hit (e.g. byte size), pass the enumerator to a new thread that will continue to process, and then return the results processed so far.

In effect I have a foreach loop which I will likely break out of before the end. How can I pass the IEnumerable to a new thread and 'continue' from where I left off rather than the beginning?

public static IEnumerable<String> Process()
{
    // static values added for simplicity, but will be a variable number of returns
    yield return "1";
    yield return "2";
    yield return "3";
    yield return "4";
    yield return "5";
    yield return "6";
}

List<String> main()
{
    List<String> retVal = new List<String>();
    IEnumerable<String> strList = Process();

    foreach(String strItem in strList)
    {
        retVal.Add(strItem);
        Console.WriteLine(strItem);
        // Time to send something back and continue in a new thread
        if (strItem.Equals("3"))
        {
            break;
        }
    }

    new Thread(() => ThreadFunc(strList)).Start();
    return retVal;
}

public static void ThreadFunc(IEnumerable<String> strList)
{
    List<String> retVal = new List<String>();
    foreach(String strItem in strList)
     {
        retVal.Add(strItem);
        Console.WriteLine(strItem);
     }
     // Send the rest of the data

}

Desired output: 1 2 3 4 5 6

Actual output: 1 2 3 1 2 3 4 5 6

Thank You.


问:
Can we define a GROUP_CONCAT function in PostgreSQL?
I have several lines of SQL code for my legacy database with GROUP_CONCAT statements, as in:

```<code>SELECT SUM(age), GROUP_CONCAT(sal) FROM Users;
</code>```

In PostgreSQL, I can do the same with:

```<code>SELECT SUM(age), string_agg(sal, ', ') FROM Users;
</code>```

I would like to reuse the old SQL as much as possible. So I need to define a GROUP_CONCAT function that internally calls string_agg. Is this possible?

EDIT: The linked question is unrelated!

My question asks "How to define a function called group_concat?". The linked question says "How can we do something equivalent to group concat (without defining a new function)?". None of the answers, also match what I want.

The selected answer is spot on! Thankfully it was answered before getting closed.

答:
There is a string_agg() builtin which does what you want, but you specifically ask for it to be named group_concat for MySQL compatibility. Unfortunately, string_agg() uses an internal data type for accumulation (presumably to avoid copying the whole buffer on each append, I have not looked at the source though) and I didn't find a way to declare a SQL aggrerate identical to string_agg().

Defining group_concat() function would not work either, as pg has to be made aware that it is an aggregate, not a function with an aggregate hidden inside, which would not work. Such a function would operate on one row at a time: any aggregate inside would just aggregate a single row and return it unchanged...

Thus, this code will accumulate the elements into an array, then add the "," delimiters with array_to_string. I will use  the array_agg() declaration (before it became a built-in) as a model, and simply add a finalizer function which will convert the aggregated array into text.

```<code>CREATE OR REPLACE FUNCTION _group_concat_finalize(anyarray)
RETURNS text AS $$
    SELECT array_to_string($1,',')
$$ IMMUTABLE LANGUAGE SQL;

CREATE AGGREGATE group_concat(anyelement) (
   SFUNC=array_append,
   STYPE=anyarray,
   FFUNC=_group_concat_finalize,
   INITCOND='{}'
);

SELECT group_concat(x) FROM foo;
</code>```

The nice thing is that it should work fine for any type, without hassle, thanks to the generic types "anyarray" and "anyelement".

I would presume this would be slower than string_agg() if string_agg does indeed avoid to copy the whole aggregation array on each append. This should matter only if the number of rows to be grouped into each set is large, though. In this case, you probably can spend a minute editing the SQL query ;)

http://sqlfiddle.com/#!17/c452d/1

Body:
I have several lines of SQL code for my legacy database with GROUP_CONCAT statements, as in:

SELECT SUM(age), GROUP_CONCAT(sal) FROM Users;

In PostgreSQL, I can do the same with:

SELECT SUM(age), string_agg(sal, ', ') FROM Users;

I would like to reuse the old SQL as much as possible. So I need to define a GROUP_CONCAT function that internally calls string_agg. Is this possible?

EDIT: The linked question is unrelated!

My question asks "How to define a function called group_concat?". The linked question says "How can we do something equivalent to group concat (without defining a new function)?". None of the answers, also match what I want.

The selected answer is spot on! Thankfully it was answered before getting closed.

Body:
There is a string_agg() builtin which does what you want, but you specifically ask for it to be named group_concat for MySQL compatibility. Unfortunately, string_agg() uses an internal data type for accumulation (presumably to avoid copying the whole buffer on each append, I have not looked at the source though) and I didn't find a way to declare a SQL aggrerate identical to string_agg().

Defining group_concat() function would not work either, as pg has to be made aware that it is an aggregate, not a function with an aggregate hidden inside, which would not work. Such a function would operate on one row at a time: any aggregate inside would just aggregate a single row and return it unchanged...

Thus, this code will accumulate the elements into an array, then add the "," delimiters with array_to_string. I will use  the array_agg() declaration (before it became a built-in) as a model, and simply add a finalizer function which will convert the aggregated array into text.

CREATE OR REPLACE FUNCTION _group_concat_finalize(anyarray)
RETURNS text AS $$
    SELECT array_to_string($1,',')
$$ IMMUTABLE LANGUAGE SQL;

CREATE AGGREGATE group_concat(anyelement) (
   SFUNC=array_append,
   STYPE=anyarray,
   FFUNC=_group_concat_finalize,
   INITCOND='{}'
);

SELECT group_concat(x) FROM foo;

The nice thing is that it should work fine for any type, without hassle, thanks to the generic types "anyarray" and "anyelement".

I would presume this would be slower than string_agg() if string_agg does indeed avoid to copy the whole aggregation array on each append. This should matter only if the number of rows to be grouped into each set is large, though. In this case, you probably can spend a minute editing the SQL query ;)

http://sqlfiddle.com/#!17/c452d/1


问:
Script is telling me that it's not a function ERROR
Probably a really quick fix but I'm stuck on what it is - I'm getting information from an API (https://api.roleplay.co.uk/v1/player/76561198062083666) where the number of vehicles keeps changing, along with the classname and classtypes. I'm trying to create a list of the names of vehicles seperated by commas, and then give each vehicle name the class of its classtype as well so that I can colour them based on their type (i.e. car, boat, plane etc.). I believe my code down here isn't working because you can't put multiple variables behind the .join but how do i get past that?

```<code>var vehicleList = data.vehicles.map(v => v.classname);
var vehicleType = data.vehicles.map(v => v.classtype);

var content = ("<span class='" + vehicleType + "'>"+ vehicleList + "</span>).join(", ");

document.getElementById("vehicle").textContent = content;
</code>```

It's giving me the following error:

```<code>player.js:404 Uncaught TypeError: (((("<span class='" + vehicleType) + "'>") + vehicleList) + "</span>").join is not a function
    at Object.success (player.js:404)
    at i (jquery.min.js:2)
    at Object.fireWith [as resolveWith] (jquery.min.js:2)
    at A (jquery.min.js:4)
    at XMLHttpRequest.<anonymous> (jquery.min.js:4)
</code>```

答:
```<code>var carsText = data.vehicles.reduce((acc,vehicle)=>{
  return acc.concat(`<span class=${vehicle.classtype}>${vehicle.classname}</span>,`)
},'');

document.getElementById('vehicle').innerHTML = carsText.slice(0,-1); //slicing to omit the last extra comma
</code>```

This should achieve what you're trying to do.

Body:
Probably a really quick fix but I'm stuck on what it is - I'm getting information from an API (https://api.roleplay.co.uk/v1/player/76561198062083666) where the number of vehicles keeps changing, along with the classname and classtypes. I'm trying to create a list of the names of vehicles seperated by commas, and then give each vehicle name the class of its classtype as well so that I can colour them based on their type (i.e. car, boat, plane etc.). I believe my code down here isn't working because you can't put multiple variables behind the .join but how do i get past that?

var vehicleList = data.vehicles.map(v => v.classname);
var vehicleType = data.vehicles.map(v => v.classtype);

var content = (""+ vehicleList + ").join(", ");

document.getElementById("vehicle").textContent = content;

It's giving me the following error:

player.js:404 Uncaught TypeError: (((("") + vehicleList) + "").join is not a function
    at Object.success (player.js:404)
    at i (jquery.min.js:2)
    at Object.fireWith [as resolveWith] (jquery.min.js:2)
    at A (jquery.min.js:4)
    at XMLHttpRequest.<anonymous> (jquery.min.js:4)

Body:
var carsText = data.vehicles.reduce((acc,vehicle)=>{
  return acc.concat(`<span class=${vehicle.classtype}>${vehicle.classname}</span>,`)
},'');

document.getElementById('vehicle').innerHTML = carsText.slice(0,-1); //slicing to omit the last extra comma

This should achieve what you're trying to do.


问:
Interface Builder UIImageView not showing image, only black screen
I have a UIView in Interface Builder and set up different UIImageViews for the background images that I want displayed that are not going to move at all (thus I didn't think I needed IBOutlets for them).

However, when the view is loaded on the iPad, it shows a black screen, and none of the images are shown.

Does something need to be set in Interface Builder to show the images?

Thanks

答: You do need to use IBOutlets to do this</p>

Body: You do need to use IBOutlets to do this