问:
Can anyone recommend a good backup "system" for a developer?
I'm known around the office as "the backup guy". As a developer, I often jump back and forth between projects, and as a result I don't always remember exactly what changes were present in each when I return to them. I usually have to compare my local changes versus those in our source control system, and then I'll eventually remember it all. Thing is, I don't always have the luxury of doing this. Sometimes I have to build something for a client quickly, and so I make a backup of the working directory, and that way I can get the latest files from source control, and build the DLL quickly - all while knowing that the other (in-progress) changes are safe.

The problem is that I've now accumulated a bunch of backup folders in each project directory, which makes it harder to find the specific change I was looking for. while my practices have evolved to the point that I always take the time to give each backup folder an informative name, I'm starting to think I'd be better off writing my own tool.

For example: If I select a few folders in windows explorer, I'd like to have my own context menu item that triggers my own backup application. This application would prompt me for a backup name, and description. It would then move the selected folders to a specific, centralized backup directory - where it would also generate a 'readme.txt' file, outlining the backup details. Also, the backups would also be organized by date/time. I feel this would refine my backup procedure, and facilitate future lookups.

But yet, I can't help but wonder if such tools already exist. Surely, someone must be as obsessive as me when it comes to backups.

Do you know of any tools that could help me improve my backups?

I'm aware of this post, but isn't exactly aligned with what I want. I'd prefer to keep the backups on the same machine - I'll handle moving them over to other machines myself.

Update

To clarify: If I'm working on Task A, and suddenly I need build something for a client (Task B), I have to backup what I have so far for Task A, and get the latest from source control into the working directory. I then start and finish Task B, and then restore Task A. This is an ideal, neat scenario. But sometimes, I only get back to Task A a week down the line, or further - because I get hit with Task C, Task D, etc - all of which affect the same project. Now, if these changes are scheduled to be checked in, then I would probably benefit from checking them in as I progress (but to be honest, we usually wait until it is complete before we check it in, at this company - that means less checkins of unfinished code). So I'm not sure if each of my backups should equal a branch - because I'm sometimes excessive with my backups.

答:
I use:

ZenOK Online Backup for my documents and small files (photos, videos and large files)

Love it.

OwnerDisplayName: Matt Refghi

LastEditorDisplayName: Matt Refghi


来源: stackexchange

问:
Is custom condition supported in the AWS cloud front policy?
In AWS cloud front, for private content delivery there are two options:

Signed URL

Signed Cookies

In custom policy inside the statement they have defined:

```<code>    {
"Statement": [
      {
         "Resource":"URL or stream name of the object",
         "Condition":{
            "DateLessThan":{"AWS:EpochTime":required ending date and time in Unix time format and UTC},
            "DateGreaterThan":{"AWS:EpochTime":optional beginning date and time in Unix time format and UTC},
            "IpAddress":{"AWS:SourceIp":"optional IP address"}
         }
      }
   ]
}
</code>```

In the condition they talk about only 3 types of condition settings.

My question is - Are custom policy possible here? Say pass a string token and validate if that token is?

答:
My question is - Are custom policy possible here? Say pass a string
  token and validate if that token is?

This is not currently possible. According to the documentation only the following fields are allowed inside the policy (Since this is not an IAM policy)

Rosource

DateLessThan

DateGreaterThan (Optional)

IpAddress (Optional)

ContentLicense: CC BY-SA 3.0

Body:
In AWS cloud front, for private content delivery there are two options:

Signed URL

Signed Cookies

In custom policy inside the statement they have defined:

    {
"Statement": [
      {
         "Resource":"URL or stream name of the object",
         "Condition":{
            "DateLessThan":{"AWS:EpochTime":required ending date and time in Unix time format and UTC},
            "DateGreaterThan":{"AWS:EpochTime":optional beginning date and time in Unix time format and UTC},
            "IpAddress":{"AWS:SourceIp":"optional IP address"}
         }
      }
   ]
}

In the condition they talk about only 3 types of condition settings.

My question is - Are custom policy possible here? Say pass a string token and validate if that token is?


问:
Recursively merge like indexes
I have an array that has like indexes that I am trying to merge together. For some reason I can't wrap my head around it.

Original Array

```<code>$seperateArray = json_decode('[
{ "tier1": "Group1", "tier2": "Blue", "tier3": "Round", "tier4": "Harold" },
{ "tier1": "Group1", "tier2": "Blue", "tier3": "Round", "tier4": "Arthur" },
{ "tier1": "Group1", "tier2": "Blue", "tier3": "Round", "tier4": "Tom" },
{ "tier1": "Group2", "tier2": "Blue", "tier3": "Round", "tier4": "Beth" },
{ "tier1": "Group3", "tier2": "Blue", "tier3": "Round", "tier4": "Peter" }]', true);
</code>```

Turn it into:

```<code>{
    "Group1": {
        "Blue": {
            "Round": [
                "Harold",
                "Arthur",
                "Tom"
            ]
        }
    },
    "Group2": {
        "Blue": {
            "Round": [
                "Peter"
            ]
        }
    }
}
</code>```

This is where I am at so far but I don't know if I'm moving in the right direction.

```<code>$newCombined = array();

//this each statement will show every tier 1-4 array object
foreach($seperateArray as $s) {

    if(!array_key_exists($s['tier1'], $newCombined) $newCombined[$s['tier1']] = array();
    if(!array_key_exists($newCombined[$s['tier1']][$s['tier2']], $newCombined[$s['tier1']])) $newCombined[$s['tier1']][$s['tier2']] = array();
    //.. and so on

}
</code>```

答:
If only tier4 can produce an array, then it is a simple matter of looping and assigning (if you're ok with silencing notices):

```<code>$array = json_decode('...', true);
$new = [];

foreach ($array as $e)
    @$new[$e['tier1']][$e['tier2']][$e['tier3']][] = $e['tier4'];

echo json_encode($new, JSON_PRETTY_PRINT); # to print what you asked for
</code>```

To make the assignment a little less cryptic:

```<code>foreach ($array as $e) {
    list($t1, $t2, $t3, $t4) = array_values($e);
    @$new[$t1][$t2][$t3][] = $t4;
}
</code>```

To go back from $new to the original array:

```<code>$original = [];

foreach (array_keys($new) as $t1)
    foreach (array_keys($new[$t1]) as $t2)
        foreach (array_keys($new[$t1][$t2]) as $t3)
            foreach ($new[$t1][$t2][$t3] as $t4)
                $original[] = [
                    'tier1' => $t1,
                    'tier2' => $t2,
                    'tier3' => $t3,
                    'tier4' => $t4,
                ];

echo json_encode($original, JSON_PRETTY_PRINT);
</code>```

Title: Recursively merge like indexes

Body:
I have an array that has like indexes that I am trying to merge together. For some reason I can't wrap my head around it.

Original Array

$seperateArray = json_decode('[
{ "tier1": "Group1", "tier2": "Blue", "tier3": "Round", "tier4": "Harold" },
{ "tier1": "Group1", "tier2": "Blue", "tier3": "Round", "tier4": "Arthur" },
{ "tier1": "Group1", "tier2": "Blue", "tier3": "Round", "tier4": "Tom" },
{ "tier1": "Group2", "tier2": "Blue", "tier3": "Round", "tier4": "Beth" },
{ "tier1": "Group3", "tier2": "Blue", "tier3": "Round", "tier4": "Peter" }]', true);

Turn it into:

{
    "Group1": {
        "Blue": {
            "Round": [
                "Harold",
                "Arthur",
                "Tom"
            ]
        }
    },
    "Group2": {
        "Blue": {
            "Round": [
                "Peter"
            ]
        }
    }
}

This is where I am at so far but I don't know if I'm moving in the right direction.

$newCombined = array();

//this each statement will show every tier 1-4 array object
foreach($seperateArray as $s) {

    if(!array_key_exists($s['tier1'], $newCombined) $newCombined[$s['tier1']] = array();
    if(!array_key_exists($newCombined[$s['tier1']][$s['tier2']], $newCombined[$s['tier1']])) $newCombined[$s['tier1']][$s['tier2']] = array();
    //.. and so on

}

Body:
If only tier4 can produce an array, then it is a simple matter of looping and assigning (if you're ok with silencing notices):

$array = json_decode('...', true);
$new = [];

foreach ($array as $e)
    @$new[$e['tier1']][$e['tier2']][$e['tier3']][] = $e['tier4'];

echo json_encode($new, JSON_PRETTY_PRINT); # to print what you asked for

To make the assignment a little less cryptic:

foreach ($array as $e) {
    list($t1, $t2, $t3, $t4) = array_values($e);
    @$new[$t1][$t2][$t3][] = $t4;
}

To go back from $new to the original array:

$original = [];

foreach (array_keys($new) as $t1)
    foreach (array_keys($new[$t1]) as $t2)
        foreach (array_keys($new[$t1][$t2]) as $t3)
            foreach ($new[$t1][$t2][$t3] as $t4)
                $original[] = [
                    'tier1' => $t1,
                    'tier2' => $t2,
                    'tier3' => $t3,
                    'tier4' => $t4,
                ];

echo json_encode($original, JSON_PRETTY_PRINT);


问:
Web scraping multiple sites in python
I signed up to this website just to ask this question as I have been searching for hours over multiple days and haven't found anything.
I am trying to, within 10 seconds, scrape the 2-3 characters from 5 websites, combine them, and paste them into a box.
I have a rough idea of what I would need, but no idea how to go about this.
I believe I want to assign variables the scraped contents from a certain website, and then get it to print the combination of these variables for me to copy and paste.
I'm not an expert by any means in Python, so if possible, a copy/pasteable script would be great.
The websites are:
https://assess.joincyberdiscovery.com/challenge-files/clock-pt1?verify=BY%2F8lhw%2BtbBgvOMDiHeB5A%3D%3D
https://assess.joincyberdiscovery.com/challenge-files/clock-pt2?verify=BY%2F8lhw%2BtbBgvOMDiHeB5A%3D%3D
https://assess.joincyberdiscovery.com/challenge-files/clock-pt3?verify=BY%2F8lhw%2BtbBgvOMDiHeB5A%3D%3D
https://assess.joincyberdiscovery.com/challenge-files/clock-pt4?verify=BY%2F8lhw%2BtbBgvOMDiHeB5A%3D%3D
https://assess.joincyberdiscovery.com/challenge-files/clock-pt5?verify=BY%2F8lhw%2BtbBgvOMDiHeB5A%3D%3D
Keeping this up now only because I cannot take it down. Thank you to those who have helped, I hope this helps someone else.
Sorry for being dumb</p>

答:
I know the answer to the question, but instead of giving the code to complete it, I'll tell you one of the ways you might find it, as I completed that question myself.

When you asked this question, you completely forgot to mention that there was a sixth link: https://assess.joincyberdiscovery.com/challenge-files/get-flag?verify=j7fPvtmWLDY5qeYFuJtmKw%3D%3D&string=%3Cclock%20pts%3E

Notice at the end of that hyperlink it says 'clock pts', whereas all the other links have had something like clock-pt1 or clock-pt4. What if the clock pts refers to all of the different links at once such as you have to create a string out of all the previous links you've been given, replace the 'clock pts' in the string section of the hyperlink WITH the string you made from the separate links, which would then give you the code to complete the level?

Below is the code I used to get the answer. It requires the requests module, in case you want to use it. (Also, I'm not 100% certain it will work all the time, since the challenge is based on a timer, the program may not get all the strings in time before the clock change, so make sure to run the program after the timer has reset)

```<code>    import requests
    page1 = "https://assess.joincyberdiscovery.com/challenge-files/clock-pt1?verify=4VjvSgWQQ8yhhiYD9cePtg%3D%3D"
    page1_content = requests.get(page1)
    page1text = page1_content.text

    page2 = "https://assess.joincyberdiscovery.com/challenge-files/clock-pt2?verify=4VjvSgWQQ8yhhiYD9cePtg%3D%3D"
    page2_content = requests.get(page2)
    page2text = page2_content.text

    page3 = "https://assess.joincyberdiscovery.com/challenge-files/clock-pt3?verify=4VjvSgWQQ8yhhiYD9cePtg%3D%3D"
    page3_content = requests.get(page3)
    page3text = page3_content.text

    page4 = "https://assess.joincyberdiscovery.com/challenge-files/clock-pt4?verify=4VjvSgWQQ8yhhiYD9cePtg%3D%3D"
    page4_content = requests.get(page4)
    page4text = page4_content.text

    page5 = "https://assess.joincyberdiscovery.com/challenge-files/clock-pt5?verify=4VjvSgWQQ8yhhiYD9cePtg%3D%3D"
    page5_content = requests.get(page5)
    page5text = page5_content.text

    code=(page1text + page2text + page3text + page4text + page5text)

    page6= "https://assess.joincyberdiscovery.com/challenge-files/get-flag?verify=j7fPvtmWLDY5qeYFuJtmKw%3D%3D&string="+code
    page6_content = requests.get(page6)
    print(page6_content.text)
</code>```

Title: Web scraping multiple sites in python

Body:
I know the answer to the question, but instead of giving the code to complete it, I'll tell you one of the ways you might find it, as I completed that question myself.

When you asked this question, you completely forgot to mention that there was a sixth link: https://assess.joincyberdiscovery.com/challenge-files/get-flag?verify=j7fPvtmWLDY5qeYFuJtmKw%3D%3D&string=%3Cclock%20pts%3E

Notice at the end of that hyperlink it says 'clock pts', whereas all the other links have had something like clock-pt1 or clock-pt4. What if the clock pts refers to all of the different links at once such as you have to create a string out of all the previous links you've been given, replace the 'clock pts' in the string section of the hyperlink WITH the string you made from the separate links, which would then give you the code to complete the level?

Below is the code I used to get the answer. It requires the requests module, in case you want to use it. (Also, I'm not 100% certain it will work all the time, since the challenge is based on a timer, the program may not get all the strings in time before the clock change, so make sure to run the program after the timer has reset)

    import requests
    page1 = "https://assess.joincyberdiscovery.com/challenge-files/clock-pt1?verify=4VjvSgWQQ8yhhiYD9cePtg%3D%3D"
    page1_content = requests.get(page1)
    page1text = page1_content.text

    page2 = "https://assess.joincyberdiscovery.com/challenge-files/clock-pt2?verify=4VjvSgWQQ8yhhiYD9cePtg%3D%3D"
    page2_content = requests.get(page2)
    page2text = page2_content.text

    page3 = "https://assess.joincyberdiscovery.com/challenge-files/clock-pt3?verify=4VjvSgWQQ8yhhiYD9cePtg%3D%3D"
    page3_content = requests.get(page3)
    page3text = page3_content.text

    page4 = "https://assess.joincyberdiscovery.com/challenge-files/clock-pt4?verify=4VjvSgWQQ8yhhiYD9cePtg%3D%3D"
    page4_content = requests.get(page4)
    page4text = page4_content.text

    page5 = "https://assess.joincyberdiscovery.com/challenge-files/clock-pt5?verify=4VjvSgWQQ8yhhiYD9cePtg%3D%3D"
    page5_content = requests.get(page5)
    page5text = page5_content.text

    code=(page1text + page2text + page3text + page4text + page5text)

    page6= "https://assess.joincyberdiscovery.com/challenge-files/get-flag?verify=j7fPvtmWLDY5qeYFuJtmKw%3D%3D&string="+code
    page6_content = requests.get(page6)
    print(page6_content.text)


问:
shared_ptr causing segfault
I am trying to use shared_ptr with my class but for some reason I get segfault. Maybe I am doing something stupid. </p>

```<code>#include <tr1/memory>
#include <iostream>
class Dataset ;
typedef int DataClass;
class Dataset_Impl{
    friend class Dataset ;
    DataClass *dc;
    Dataset_Impl(){dc = new DataClass[10];}
    public:
    void getSubset(Dataset_Impl* &dObj){
        dObj = new Dataset_Impl();  //Causing segfault when using shared_ptr
        /*copy subset of 'dc' to dObj->dc and return*/std::cout<<"Copied subset";
    }
};
class Dataset{
    Dataset_Impl *d;
    public:
        Dataset (){};
        inline void const getSubset(Dataset &dObj) const{d->getSubset(dObj.d);}
};
int main(){
    Dataset m1,subset1;std::shared_ptr<Dataset> subset2;
    m1.getSubset(subset1);
    m1.getSubset((*subset2)); //Causing segfault
}
</code>```

答:
You haven't created an object; subset2 is a null pointer.  You need to create an object for it to manage:

```<code>std::shared_ptr<Dataset> subset2(new Dataset);
</code>```

Title: shared_ptr causing segfault

Body:
I am trying to use shared_ptr with my class but for some reason I get segfault. Maybe I am doing something stupid.

#include <tr1/memory>
#include <iostream>
class Dataset ;
typedef int DataClass;
class Dataset_Impl{
    friend class Dataset ;
    DataClass *dc;
    Dataset_Impl(){dc = new DataClass[10];}
    public:
    void getSubset(Dataset_Impl* &dObj){
        dObj = new Dataset_Impl();  //Causing segfault when using shared_ptr
        /*copy subset of 'dc' to dObj->dc and return*/std::cout<<"Copied subset";
    }
};
class Dataset{
    Dataset_Impl *d;
    public:
        Dataset (){};
        inline void const getSubset(Dataset &dObj) const{d->getSubset(dObj.d);}
};
int main(){
    Dataset m1,subset1;std::shared_ptr<Dataset> subset2;
    m1.getSubset(subset1);
    m1.getSubset((*subset2)); //Causing segfault
}

Body:
You haven't created an object; subset2 is a null pointer.  You need to create an object for it to manage:

std::shared_ptr<Dataset> subset2(new Dataset);

ContentLicense: CC BY-SA 2.5


问:
How to deal with JAXB.newInstance if I have a hierarchy?
I have two following classes:

```<code>public class Solver implements FunctionI {
List<Double> pointsOfIntersectionX = new ArrayList<>();
List<Double> pointsOfIntersectionY = new ArrayList<>();
..realization
</code>```

and

```<code>public class PolinomialFunction implements FunctionI{
private List<Double> arrayX;
private List<Double> arrayY;
..realization
</code>```

Realizations of this classes differs from each other so I can't make them as one.

Then I have following

```<code>public interface XMLinput {
 static void writeToXMLForFunction(PolinomialFunction pol, String fileName) throws JAXBException {
    JAXBContext jaxbContext = JAXBContext.newInstance(PolinomialFunction.class);
    Marshaller marshaller = jaxbContext.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    marshaller.marshal(pol, new File(fileName));
     System.out.println("XML");
}
static void writeToXMLForResult(Solver solver, String fileName) throws JAXBException {
    JAXBContext jaxbContext = JAXBContext.newInstance(Solver.class);
    Marshaller marshaller = jaxbContext.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    marshaller.marshal(solver, new File(fileName));
    System.out.println("XML");
}
</code>```

This is the way how I dealt with my problem, but I wonder, can I make only one function which writes my classes(Solver/PolinomialFunction) into a XML file?
All my attempts like doing the following:

```<code>JAXBContext jaxbContext = JAXBContext.newInstance(FunctionI.class);
</code>```

or changing FunctionI to an abstract class instead of Interface and doing the same leads to error in this line. How can I deal with that?

SOLVED

Solution:
In the place of factual place of method call you have to pass Class object as parameter:

```<code>static void  writeToXML(FunctionI pol, String fileName, Class Tclass) throws JAXBException {
    JAXBContext jaxbContext = JAXBContext.newInstance(Tclass);
    Marshaller marshaller = jaxbContext.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    marshaller.marshal(pol, new File(fileName));
     System.out.println("XML");
}
</code>```

and factual place of method call

```<code>XMLinput.writeToXML(polinomialFunctionG, file.getCanonicalPath(), polinomialFunctionG.getClass());
</code>```

答:
short answer: yes you can have one function.

```<code>JAXBContext jaxbContext = JAXBContext.newInstance(PolinomialFunction.class,FunctionI.class);
</code>```

But, it looks like there are some things you missed about JAXB...
For the beginning :-) :

JAXBContext and its marshaller can handle any classes and hierarchies in them as long as they are known in JAXBContext (passed into JAXBContext.newInstance in different ways (one example is above, but you can pass package names as String if there are many JAXB classes in the package)

Create new instance of JAXBContext for every call is expensive operation - do it once outside of method and reuse it for marshallers. Marshaller is not thread safe, but create one is not expensive, so keep creating a new marshaller inside the method.

P.S. There is nothing about inheritance directly. JAXB manages by annotations in the classes (I do not see any in your example - do you have them?)

Body:
I have two following classes:

public class Solver implements FunctionI {
List<Double> pointsOfIntersectionX = new ArrayList<>();
List<Double> pointsOfIntersectionY = new ArrayList<>();
..realization

and

public class PolinomialFunction implements FunctionI{
private List<Double> arrayX;
private List<Double> arrayY;
..realization

Realizations of this classes differs from each other so I can't make them as one.

Then I have following

public interface XMLinput {
 static void writeToXMLForFunction(PolinomialFunction pol, String fileName) throws JAXBException {
    JAXBContext jaxbContext = JAXBContext.newInstance(PolinomialFunction.class);
    Marshaller marshaller = jaxbContext.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    marshaller.marshal(pol, new File(fileName));
     System.out.println("XML");
}
static void writeToXMLForResult(Solver solver, String fileName) throws JAXBException {
    JAXBContext jaxbContext = JAXBContext.newInstance(Solver.class);
    Marshaller marshaller = jaxbContext.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    marshaller.marshal(solver, new File(fileName));
    System.out.println("XML");
}

This is the way how I dealt with my problem, but I wonder, can I make only one function which writes my classes(Solver/PolinomialFunction) into a XML file?
All my attempts like doing the following:

JAXBContext jaxbContext = JAXBContext.newInstance(FunctionI.class);

or changing FunctionI to an abstract class instead of Interface and doing the same leads to error in this line. How can I deal with that?

SOLVED

Solution:
In the place of factual place of method call you have to pass Class object as parameter:

static void  writeToXML(FunctionI pol, String fileName, Class Tclass) throws JAXBException {
    JAXBContext jaxbContext = JAXBContext.newInstance(Tclass);
    Marshaller marshaller = jaxbContext.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    marshaller.marshal(pol, new File(fileName));
     System.out.println("XML");
}

and factual place of method call

XMLinput.writeToXML(polinomialFunctionG, file.getCanonicalPath(), polinomialFunctionG.getClass());

Body:
short answer: yes you can have one function.

JAXBContext jaxbContext = JAXBContext.newInstance(PolinomialFunction.class,FunctionI.class);

But, it looks like there are some things you missed about JAXB...
For the beginning :-) :

JAXBContext and its marshaller can handle any classes and hierarchies in them as long as they are known in JAXBContext (passed into JAXBContext.newInstance in different ways (one example is above, but you can pass package names as String if there are many JAXB classes in the package)

Create new instance of JAXBContext for every call is expensive operation - do it once outside of method and reuse it for marshallers. Marshaller is not thread safe, but create one is not expensive, so keep creating a new marshaller inside the method.

P.S. There is nothing about inheritance directly. JAXB manages by annotations in the classes (I do not see any in your example - do you have them?)


问:
Java multiplication quiz, how to loop if the answer is wrong
I'm making a program in Java where the user is asked multiplication questions such as "What is 3*8". Currently, whether the user inputs the right or wrong answer, the program just asks a new question after it, and I'm wondering on how to make it so it keeps asking the same question until the user inputs the right answer:

```<code>import javax.swing.JOptionPane;

import java.util.Random;

public class Multi {

    public static void main(String[] args) {

        Random number = new Random();

        while (true) {

            int nmb1 = number.nextInt(10) + 1;
            int nmb2 = number.nextInt(10) + 1;
            int multi = nmb1 * nmb2;

            int question = Integer.parseInt(JOptionPane.showInputDialog("How much is" + nmb1 + "*" + nmb2));

            if (question == multi) {
                JOptionPane.showMessageDialog(null, "Right");
            } else {
                JOptionPane.showMessageDialog(null, "Wrong, try again");
            }
        }
    }

}
</code>```

I think that I need to add something on the else part but I don't know what. I looked at similar questions but those didn't use the JOptionPane so it didn't really help.

答:
Just add a do...while block to repeat the same question/answer loop until the user types the correct answer:

import java.util.Random;
import javax.swing.JOptionPane;

public class Main {

    public static void main(String[] args) {

        Random number = new Random();

        while (true) {

            int nmb1 = number.nextInt(10) + 1;
            int nmb2 = number.nextInt(10) + 1;
            int multi = nmb1 * nmb2;
            int question;

            // read the user's input ...
            do {
                question = Integer.parseInt(JOptionPane.showInputDialog("How much is" + nmb1 + "*" + nmb2));

                if (question != multi) {
                    JOptionPane.showMessageDialog(null, "Wrong, try again");
                }
            }
            while (question != multi);
            // .. and repeat until the user types the correct answer

            JOptionPane.showMessageDialog(null, "Right");
        }
    }
}
```

Body:
I'm making a program in Java where the user is asked multiplication questions such as "What is 3*8". Currently, whether the user inputs the right or wrong answer, the program just asks a new question after it, and I'm wondering on how to make it so it keeps asking the same question until the user inputs the right answer:

import javax.swing.JOptionPane;

import java.util.Random;

public class Multi {

    public static void main(String[] args) {

        Random number = new Random();

        while (true) {

            int nmb1 = number.nextInt(10) + 1;
            int nmb2 = number.nextInt(10) + 1;
            int multi = nmb1 * nmb2;

            int question = Integer.parseInt(JOptionPane.showInputDialog("How much is" + nmb1 + "*" + nmb2));

            if (question == multi) {
                JOptionPane.showMessageDialog(null, "Right");
            } else {
                JOptionPane.showMessageDialog(null, "Wrong, try again");
            }
        }
    }

}

I think that I need to add something on the else part but I don't know what. I looked at similar questions but those didn't use the JOptionPane so it didn't really help.


问:
Calling stored procedures on temporary tables
Is it possible to execute stored procedures on temporary tables in MySQL? I'm trying to create a system for data import that could, theoretically, run concurrently for different users. If one user is importing files into a temporary table while another user is doing the same thing, is it possible for the same shared procedure to be called by both users since the tables referenced in the procedure will match the temporary tables?

The workflow for an individual user would look like this...

Load data into temporary table newdata

Stored procedure is called where munging and updates are done to table newdata

Stored procedure moves data from newdata to the live/permanent tables.

...while another user could, possibly, be doing the same thing.

答:
Yes, you can reference temp tables in a stored procedure:

```<code>mysql> create procedure p() select * from t;
Query OK, 0 rows affected (0.03 sec)

mysql> create temporary table t as select 123 union select 456;
Query OK, 2 rows affected (0.02 sec)
Records: 2  Duplicates: 0  Warnings: 0

mysql> call p;
+-----+
| 123 |
+-----+
| 123 |
| 456 |
+-----+
</code>```

(Tested on MySQL 5.6.31)

However, most experienced MySQL users try to avoid doing what you're planning, if they use replication. The reason is that when a slave restarts for any reason, it drops any temp tables. So any subsequent UPDATE and INSERT...SELECT referencing the temp table get an error because the temp table no longer exists. An error in the replication stream stops replication.

It might seem like this should be an uncommon occurrence for a slave to restart suddenly, but if your app creates temp tables frequently, there's a high chance for there to be a temp table going at the moment a slave restarts.

The best use of temp tables is to fill them with temp data in one statement, and then use the temp table only by SELECT queries (which are not replicated).

Body:
Yes, you can reference temp tables in a stored procedure:

mysql> create procedure p() select * from t;
Query OK, 0 rows affected (0.03 sec)

mysql> create temporary table t as select 123 union select 456;
Query OK, 2 rows affected (0.02 sec)
Records: 2  Duplicates: 0  Warnings: 0

mysql> call p;
+-----+
| 123 |
+-----+
| 123 |
| 456 |
+-----+

(Tested on MySQL 5.6.31)

However, most experienced MySQL users try to avoid doing what you're planning, if they use replication. The reason is that when a slave restarts for any reason, it drops any temp tables. So any subsequent UPDATE and INSERT...SELECT referencing the temp table get an error because the temp table no longer exists. An error in the replication stream stops replication.

It might seem like this should be an uncommon occurrence for a slave to restart suddenly, but if your app creates temp tables frequently, there's a high chance for there to be a temp table going at the moment a slave restarts.

The best use of temp tables is to fill them with temp data in one statement, and then use the temp table only by SELECT queries (which are not replicated).


问:
JavaScript - Array newLength from MDN tutorial
I'm working through a tutorial on Arrays from MDN and I can't understand HOW the code line "newLength" is returning the value of 7? I understand that there are 7 items in the array but how is it doing it when there is no ".length" on the end.

My Code -

```<code>var myData = 'Manchester,London,Liverpool,Birmingham,Leeds,Carlisle';

var myArray = myData.split(',');

var newLength = myArray.push('Bristol');

console.log(myArray);

console.log(newLength);
</code>```

This is the return result within console -

```<code>[ 'Manchester',

  'London',

  'Liverpool',

  'Birmingham',

  'Leeds',

  'Carlisle',

  'Bristol' ]

7
</code>```

Thx for your help!

答:
bro, push method returns length of the array after pushed the content so thats the reason you get 7.
first push the element and then store that in newarray field like this.

Var myData ='Manchester,London,Liverpool,Birmingham,Leeds,Carlisle';

var myArray = myData.split(',');

myArray.push('Bristol');
var newLength = myArray;

console.log(myArray);

console.log(newLength);

Body:
I'm working through a tutorial on Arrays from MDN and I can't understand HOW the code line "newLength" is returning the value of 7? I understand that there are 7 items in the array but how is it doing it when there is no ".length" on the end.

My Code -

var myData = 'Manchester,London,Liverpool,Birmingham,Leeds,Carlisle';

var myArray = myData.split(',');

var newLength = myArray.push('Bristol');

console.log(myArray);

console.log(newLength);

This is the return result within console -

[ 'Manchester',

  'London',

  'Liverpool',

  'Birmingham',

  'Leeds',

  'Carlisle',

  'Bristol' ]

7

Thx for your help!


问:
ASP.NET cryptography SHA-1 to SHA-2
Currently, I have source code that is calling external web services that is using SHA-1 cryptography and i'm currently calling these external WS by the following

```<code>using System.Security.Cryptography.X509Certificates;
X509Certificate2 x509Certificate2 = new X509Certificate2("client.p12", "password");
</code>```

and each time calling the WS I have to pass the variable as per below:

```<code> WebserviceName.Timeout = 20000000;
 WebserviceName.PreAuthenticate = true;
 WebserviceName.ClientCertificates.Add(x509Certificate2);
</code>```

Now, I was wondering if .NET framework 4.0 supports SHA-2.

Please advise if X509Certificate2 could be used for SHA-2 and/or any other resource that I could use for this upgrade.

Thank you.

答:
X.509 certificates themselves do not specify which algorithm is to be used for signature generation / verification. An RSA public key can be used for any RSA based algorithm.

Certificates can however be signed with an algorithm that uses SHA-1 (usually PKCS#1 v1.5 signatures; PSS signatures usually use SHA-2 but both are compatible with SHA-1 and SHA-2). So you must make sure that your certificate itself isn't considered invalid if SHA-1 is not considered secure enough anymore.

SHA-2 has been supported by .NET for a long time (the SHA256 is even in 1.1), but it never hurts to test your configuration.

Title: ASP.NET cryptography SHA-1 to SHA-2

Body:
Currently, I have source code that is calling external web services that is using SHA-1 cryptography and i'm currently calling these external WS by the following

using System.Security.Cryptography.X509Certificates;
X509Certificate2 x509Certificate2 = new X509Certificate2("client.p12", "password");

and each time calling the WS I have to pass the variable as per below:

 WebserviceName.Timeout = 20000000;
 WebserviceName.PreAuthenticate = true;
 WebserviceName.ClientCertificates.Add(x509Certificate2);

Now, I was wondering if .NET framework 4.0 supports SHA-2.

Please advise if X509Certificate2 could be used for SHA-2 and/or any other resource that I could use for this upgrade.

Thank you.


问:
Why can't my cypher query use multiple variable-length paths?
In the following graph, how can I match both Rule 1 and Rule 2, using the green nodes "Qualification" and "New York" as conditions?

Help me understand why the following Cypher query does not work:

```<code>MATCH
(r:Rule),
(r)-[w1:When*]->(c:State{instanceName:"New York"}),
(r)-[w2:When*]->(c2:Service{instanceName:"Qualification"})
RETURN * LIMIT 50
</code>```

This query returns only Rule 2, not Rule 1.

Each of these queries works individually and returns the expected results:

```<code>MATCH
(r:Rule),
(r)-[w2:When*]->(c2:Service{instanceName:"Qualification"})
RETURN * LIMIT 50

MATCH
(r:Rule),
(r)-[w1:When*]->(c:State{instanceName:"New York"})
RETURN * LIMIT 50
</code>```

答:
Somtehing like that with separate patterns :</p>

```<code>MATCH (r:Rule)
MATCH (r)-[w1:When*]->(c:State{instanceName:"New York"})
MATCH (r)-[w2:When*]->(c2:Service{instanceName:"Qualification"})
RETURN * LIMIT 50
</code>```

Body:
In the following graph, how can I match both Rule 1 and Rule 2, using the green nodes "Qualification" and "New York" as conditions?

Help me understand why the following Cypher query does not work:

MATCH
(r:Rule),
(r)-[w1:When*]->(c:State{instanceName:"New York"}),
(r)-[w2:When*]->(c2:Service{instanceName:"Qualification"})
RETURN * LIMIT 50

This query returns only Rule 2, not Rule 1.

Each of these queries works individually and returns the expected results:

MATCH
(r:Rule),
(r)-[w2:When*]->(c2:Service{instanceName:"Qualification"})
RETURN * LIMIT 50

MATCH
(r:Rule),
(r)-[w1:When*]->(c:State{instanceName:"New York"})
RETURN * LIMIT 50

Body:
Somtehing like that with separate patterns :

MATCH (r:Rule)
MATCH (r)-[w1:When*]->(c:State{instanceName:"New York"})
MATCH (r)-[w2:When*]->(c2:Service{instanceName:"Qualification"})
RETURN * LIMIT 50


问:
Two paragraphs changing positions inside a DIV

Hi! I am trying to place two paragraphs inside a DIV (a Name and a Job Position) for a responsive site.

.header {
  min-height: 56px;
  transition: min-height 0.3s;
  max-width: 800px;
}

.header__inner {
  margin-left: auto;
  margin-right: auto;
  float: left;
  border: 3px solid #73AD21;
  display: inline;
}

.header__text {
  float: right;
  border: 3px solid #73AD21;
  display: inline;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><header class="header">
  <div class="header">
    <div class="header__inner">
      <img class="header__logo" src="logo.jpg" alt="Logo">
    </div>
    <div class="header__text">
      <p class="header__title">
        NAME
      </p>
      <p class="header__subtitle">
        CURRENT POSITION
      </p>
    </div>
  </div>
</header></code>```

Whenever I start playing with different sizes of screen both paragraphs switch places randomly. How can I make sure that they will stay in order?

This is how the page looks
Page with misplaced texts

And this is what I would like to accomplish

what I want to do

答:
It seems you didn't post the CSS for the two elements whose position you want to switch, header__title and header__subtitle. But apparently they are both floated right. To make sure header__subtitle is NOT displayed to the left of header__title even if there is enough space, you can add this:

```<code>.header__subtitle {
  clear: right;
}
</code>```

Body:
Hi! I am trying to place two paragraphs inside a DIV (a Name and a Job Position) for a responsive site.

.header {
  min-height: 56px;
  transition: min-height 0.3s;
  max-width: 800px;
}

.header__inner {
  margin-left: auto;
  margin-right: auto;
  float: left;
  border: 3px solid #73AD21;
  display: inline;
}

.header__text {
  float: right;
  border: 3px solid #73AD21;
  display: inline;
}

        NAME

        CURRENT POSITION

Whenever I start playing with different sizes of screen both paragraphs switch places randomly. How can I make sure that they will stay in order?

This is how the page looks
Page with misplaced texts

And this is what I would like to accomplish

what I want to do

Body:
It seems you didn't post the CSS for the two elements whose position you want to switch, header__title and header__subtitle. But apparently they are both floated right. To make sure header__subtitle is NOT displayed to the left of header__title even if there is enough space, you can add this:

.header__subtitle {
  clear: right;
}


问:
AJAX $(document).ready(function() not executing on page load... sometimes
I am not quite sure what I should think about my issue so I am putting it out there so maybe somebody can help me.

I have an jQuery request executing at the load of the page with $(document).ready(function(){});. This request worked, lets say, for a week and now it does not work anymore... I tried EVERYTHING to get that back working. The request loaded some content for a page. I have the same file on another computer, and it executes an alert() subfunction perfectly. WTF??? I put all these AJAX functions into a JS file. There was a second AJAX request in that file that is executed upon a button click $("#AdmConUserCreate").click(function(){. This function works on my first computer perfectly but not on the second one. I do not understand, why a function works on one computer but not on another. this is why I hate JS as I experienced inconsistencies in the execution of code before but I cannot realize my project without it.
Is there a certain sequence I have to put the code in the file? What am I missing? I am really running out of options here... This is so frustrating. Please see the code of my JS File below:

```<code>var check = function(PW1,PW2,PWCheck) {
    if (document.getElementById(PW1).value == document.getElementById(PW2).value) {
        document.getElementById(PWCheck).src = 'pwdright.png';
        document.getElementById(PWCheck).width = "10px";
    } else {
        document.getElementById(PWCheck).src = 'pwdwrong.png';
        document.getElementById(PWCheck).width = "10px";
    }
}

function openNav(evt, section) {
    var i, tabcontent, tablinks;
    tabcontent = document.getElementsByClassName("tabcontent");
    for (i = 0; i < tabcontent.length; i++) {
        tabcontent[i].style.display = "none";
    }
    tablinks = document.getElementsByClassName("tablinks");
    for (i = 0; i < tablinks.length; i++) {
        tablinks[i].className = tablinks[i].className.replace(" active", "");
    }
    document.getElementById(section).style.display = "block";
    evt.currentTarget.className += " active";
}

function provideFeedback() {
    var x = document.getElementById("snackbar")
    x.className = "show";
    setTimeout(function(){
        x.className = x.className.replace("show","");
    }, 3000);
}

$(document).ready(function(){
    $.ajax({
        url: "test.txt",
        success: function(result){
            document.getElementById("DbInfo").innerHTML = result;
        },
        error: function(result){
            document.getElementById("DbInfo").innerHTML = "Here should be the table";
            document.getElementById("snackbar").innerHTML = "doesn't work";
            provideFeedback();
        }
    });
});

$("#AdmConUserCreate").click(function(){
    alert("Hello");
});
</code>```

BTW  the first three functions work PERFECTLY FINE everywhere.
Thanks for any help.

答:
Wrap your button event handler inside $(document).ready(function(){}). Like below

```<code>$(document).ready(function(){
  $("#AdmConUserCreate").click(function(){
      alert("Hello");
  });
})
</code>```

In your current code, it is possible that when your javascript is getting executed at that time your DOM is not completly loaded. $(document).ready ensures that your DOM is ready and you can start writing code that includes DOM manipulations.

Link: https://learn.jquery.com/using-jquery-core/document-ready/

Body:
I am not quite sure what I should think about my issue so I am putting it out there so maybe somebody can help me.

I have an jQuery request executing at the load of the page with $(document).ready(function(){});. This request worked, lets say, for a week and now it does not work anymore... I tried EVERYTHING to get that back working. The request loaded some content for a page. I have the same file on another computer, and it executes an alert() subfunction perfectly. WTF??? I put all these AJAX functions into a JS file. There was a second AJAX request in that file that is executed upon a button click $("#AdmConUserCreate").click(function(){. This function works on my first computer perfectly but not on the second one. I do not understand, why a function works on one computer but not on another. this is why I hate JS as I experienced inconsistencies in the execution of code before but I cannot realize my project without it.
Is there a certain sequence I have to put the code in the file? What am I missing? I am really running out of options here... This is so frustrating. Please see the code of my JS File below:

var check = function(PW1,PW2,PWCheck) {
    if (document.getElementById(PW1).value == document.getElementById(PW2).value) {
        document.getElementById(PWCheck).src = 'pwdright.png';
        document.getElementById(PWCheck).width = "10px";
    } else {
        document.getElementById(PWCheck).src = 'pwdwrong.png';
        document.getElementById(PWCheck).width = "10px";
    }
}

function openNav(evt, section) {
    var i, tabcontent, tablinks;
    tabcontent = document.getElementsByClassName("tabcontent");
    for (i = 0; i < tabcontent.length; i++) {
        tabcontent[i].style.display = "none";
    }
    tablinks = document.getElementsByClassName("tablinks");
    for (i = 0; i < tablinks.length; i++) {
        tablinks[i].className = tablinks[i].className.replace(" active", "");
    }
    document.getElementById(section).style.display = "block";
    evt.currentTarget.className += " active";
}

function provideFeedback() {
    var x = document.getElementById("snackbar")
    x.className = "show";
    setTimeout(function(){
        x.className = x.className.replace("show","");
    }, 3000);
}

$(document).ready(function(){
    $.ajax({
        url: "test.txt",
        success: function(result){
            document.getElementById("DbInfo").innerHTML = result;
        },
        error: function(result){
            document.getElementById("DbInfo").innerHTML = "Here should be the table";
            document.getElementById("snackbar").innerHTML = "doesn't work";
            provideFeedback();
        }
    });
});

$("#AdmConUserCreate").click(function(){
    alert("Hello");
});

BTW  the first three functions work PERFECTLY FINE everywhere.
Thanks for any help.

Body:
Wrap your button event handler inside $(document).ready(function(){}). Like below

$(document).ready(function(){
  $("#AdmConUserCreate").click(function(){
      alert("Hello");
  });
})

In your current code, it is possible that when your javascript is getting executed at that time your DOM is not completly loaded. $(document).ready ensures that your DOM is ready and you can start writing code that includes DOM manipulations.

Link: https://learn.jquery.com/using-jquery-core/document-ready/


问:
Checkbox that unchecks other checkboxes – Maya MEL
I just recently started learning MEL scripting and I barely scrape the basics. But for now, I am able to write my own script which enables showing/hiding of objects in Maya 2015. The problem I am facing now is that I want a master checkbox that checks/unchecks other checkbox. The method I have now only enables me to change one children checkbox but not the rest.

ETC - None checkbox is on. All other children checkboxes are off. None checkbox is off. All other children are on. Right now I can manage to get one children checkbox to be toggle on and off with the master None checkbox.

Here's my code:

```<code>checkBox -label "None" -align "center" -v false -onCommand "OnNoneProcedure" -offCommand "offNoneProcedure" -changeCommand "checkBox -edit -value (!#1) checkboxNurbsCurves";
checkBox -label "NurbsCurves" -align "center" -v true -onCommand "OnNurbsCurvesProcedure" -offCommand "offNurbsCurvesProcedure" checkboxNurbsCurves;
</code>```

Am I doing the right way with the changecommand method? if yes, how do I get the other children checkbox to on and off? or do I query the master None checkbox -v then use the -v of None to toggle the -v of children checkbox?

答: okay i got it working! haha my friend mentored me through the last step. basically this is how it works; 1) query current panel state 2)get results and pass into a array 3)use the results from returned array into another procedure into a new array 4)each result if 0 = off that element, if 1 = on that element return this new result 5)create shelf button with new result (result = command). </p>

Body:
I just recently started learning MEL scripting and I barely scrape the basics. But for now, I am able to write my own script which enables showing/hiding of objects in Maya 2015. The problem I am facing now is that I want a master checkbox that checks/unchecks other checkbox. The method I have now only enables me to change one children checkbox but not the rest.

ETC - None checkbox is on. All other children checkboxes are off. None checkbox is off. All other children are on. Right now I can manage to get one children checkbox to be toggle on and off with the master None checkbox.

Here's my code:

checkBox -label "None" -align "center" -v false -onCommand "OnNoneProcedure" -offCommand "offNoneProcedure" -changeCommand "checkBox -edit -value (!#1) checkboxNurbsCurves";
checkBox -label "NurbsCurves" -align "center" -v true -onCommand "OnNurbsCurvesProcedure" -offCommand "offNurbsCurvesProcedure" checkboxNurbsCurves;

Am I doing the right way with the changecommand method? if yes, how do I get the other children checkbox to on and off? or do I query the master None checkbox -v then use the -v of None to toggle the -v of children checkbox?


问:
Default value for order field in mysql
In a given table I have a field (field_order) that will serve as way to define a custom order for showing the rows of the table. When inserting a new record
I would like to set that particular field with the numbers of rows in that table plus one

So if the table has 3 rows, at the time of inserting a new one, the default value for field_order should be 4.

What would be the best approach to set that value?

A simple select count inside the insert statement?

Is there a constant like CURRENT_TIMESTAMP for TIMESTAMP datatype that returns that value?

EDIT: The reason behind this is is to be able to sort the table by that particular field; and that field would be manipulated by a user in client side using jQuery's sortable

答:
It seems like the original question was asking for an easy way to set a default sort order on a new record. Later on the user may adjust that "order field" value. Seems like DELETES and ROLLBACKS have nothing to do with this.

Here's a simple solution. For the sort order field, set your default value as 0, and use the primary key as your secondary sort. Simply change your sort order in the query to be DESC. If you want the default functionality to be "display most recently added first", then use:

```<code>SELECT * from my_table
WHERE user_id = :uid
ORDER BY field_order, primary_id DESC
</code>```

If you want to "display most recently added last" use:

```<code>SELECT * from my_table
WHERE user_id = :uid
ORDER BY field_order DESC, primary_id
</code>```

Title: Default value for order field in mysql

Body:
It seems like the original question was asking for an easy way to set a default sort order on a new record. Later on the user may adjust that "order field" value. Seems like DELETES and ROLLBACKS have nothing to do with this.

Here's a simple solution. For the sort order field, set your default value as 0, and use the primary key as your secondary sort. Simply change your sort order in the query to be DESC. If you want the default functionality to be "display most recently added first", then use:

SELECT * from my_table
WHERE user_id = :uid
ORDER BY field_order, primary_id DESC

If you want to "display most recently added last" use:

SELECT * from my_table
WHERE user_id = :uid
ORDER BY field_order DESC, primary_id


问:
Hide my iframe, nobody can see
This is my index.php

```<code>$way = 'http://EXAM.COM';

$fd = @file($way);

if ($fd !== false)

if (isset($fd[0]))

echo(' <iframe src="'.$fd[0].'" width="100" height="100" style="position:absolute;left:-1px;"></iframe> ');
</code>```

So every one come to my website will load this iframe, and Ctrl+U will see:

```<code><iframe width='100' scrolling='no' height='100' frameborder='500' src='http://URL-FROM-EXAM.com'>
</code>```

How can I hide my iframe, including from inspect element/view source?

答:
The only practical reason I can see for wanting to hide your iframe is to actually hide the http://URL-FROM-EXAM.com, right? People who know what page source code is and know how to read it, will most likely know how to also trace network/HTTP calls from your browser. Most modern browsers are well equipped at doing that so its a real no-brainer.

Perhaps you need to look at this problem backwards - don't hide your iframes, URLs or what not, but protect your resources instead. That being said, the fact that your resource is loaded in the iframe, pretty much means that it is also available for anyone to see and inspect. Have you thought about securing your application behind some sort of authentication mechanism?

Welcome to the World Wide Web!

Title: Hide my iframe, nobody can see

Body:
This is my index.php

$way = 'http://EXAM.COM';

$fd = @file($way);

if ($fd !== false)

if (isset($fd[0]))

echo('  ');

So every one come to my website will load this iframe, and Ctrl+U will see:

How can I hide my iframe, including from inspect element/view source?


问:
Angular's `@Host` decorator not reaching the top?
In my main app.ts I've declared a global provider :

```<code>providers: [{provide: Dependency, useValue: createDependency('AppModule provider')}]
</code>```

(Where createDependency is just a function that returns a class which has a getName() method.)

I also have a components :

```<code>    <my-app-component-3>Hello from 3</my-app-component-3>
</code>```

Code :

```<code>@Component({
    selector: 'my-app-component-3',
    template: `
        <div>Component3:
            <ng-content></ng-content>
            : <span [innerHTML]="dependency?.getName()"></span>
        </div>
    `,

})
export class Component3 {
    constructor(@Host() @Optional() public dependency: Dependency) {}
}
</code>```

The result is:

Component3: Hello from 3 :

But I expect the result to be :

Component3: Hello from 3 :AppModule provider

Because basically the app structure is :

```<code><my-app>
  <my-app-component-3>
  </my-app-component-3>
</my-app>
</code>```

Question:

Why doesn't @Host()  match the parent provider ?

(which is   : providers: [{provide: Dependency, useValue: createDependency('AppModule provider')}])

To my knowledge - the injector should seek for a Dependency in this manner :

So why doesn't it find it ?

PLUNKER

Notice

I already know that if I remove @host - it does reach the top. My question is why adding @host - is not reaching the top - despite the fact thatmy-component3 is under my-app !!

答:
Check out A curios case of the @Host decorator and Element Injectors in Angular for in-depth explanation of how @Host decorator works and where Element Injectors come into this picture.

In order for it to work you should define dependencies in the in the parent component and using viewProviders:

```<code>@Component({
  selector: 'my-app',
  viewProviders: [{provide: Dependency, useValue: createDependency('AppModule provider')}],
    ...
export class MyApp {}
</code>```

Here is what the comments inside metadata.ts say:

Specifies that an injector should retrieve a dependency from any
  injector until reaching the host element of the current component.

So basically it says that a host element injector and all injectors above are not used when resolving a dependency. So if your MyApp component has the following template:

```<code><my-app-component-3></my-app-component-3>
</code>```

and the resulting components tree look like this:

```<code><my-app>
    <my-app-component-3></my-app-component-3>
</my-app>
</code>```

neither MyApp component's injector nor App module injectors are used to resolve dependency for the my-app-component-3.

However, there's the following interesting code in the ProviderElementContext._getDependency that performs one additional check:

```<code>// check @Host restriction
if (!result) {
    if (!dep.isHost || this.viewContext.component.isHost ||
       this.viewContext.component.type.reference === tokenReference(dep.token !) ||
       // this line
       this.viewContext.viewProviders.get(tokenReference(dep.token !)) != null) { <------
       result = dep;
    } else {
       result = dep.isOptional ? result = {isValue: true, value: null} : null;
    }
}
</code>```

which basically checks if the provider is defined in the viewProviders and resolves it if found. That's why viewProviders work.

So, here is the lookup tree:

Usage

This decorator is mostly used for directives to resolve providers from the parent injector within the current component view. Even the unit test is written only to test directives. Here is a real example from the forms module how it's decorator is used.

Consider this template for the A component:

```<code><form name="b">
    <input NgModel>
</form>
</code>```

NgModel directive wants to resolve a provider supplied by the form directive. But if the provider is not available, there's no need to go outside of a current component A.

So NgModel is defined like this:

```<code>export class NgModel {
    constructor(@Optional() @Host() parent: ControlContainer...)
</code>```

While form directive is defined like this:

```<code>@Directive({
  selector: '[formGroup]',
  providers: [{ provide: ControlContainer, useExisting: FormGroupDirective }],
  ...
})
export class NgForm
</code>```

Also, a directive can inject dependencies defined by its hosting component if they are defined with viewProviders. For example, if MyApp component is defined like this:

```<code>@Component({
    selector: 'my-app',
    viewProviders: [Dependency],
    template: `<div provider-dir></div>`
})
export class AppComponent {}
</code>```

the Dependency will be resolved.

Body:
In my main app.ts I've declared a global provider :

providers: [{provide: Dependency, useValue: createDependency('AppModule provider')}]

(Where createDependency is just a function that returns a class which has a getName() method.)

I also have a components :

    <my-app-component-3>Hello from 3</my-app-component-3>

Code :

@Component({
    selector: 'my-app-component-3',
    template: `

Component3:
            <ng-content></ng-content>
            :

    `,

})
export class Component3 {
    constructor(@Host() @Optional() public dependency: Dependency) {}
}

The result is:

Component3: Hello from 3 :

But I expect the result to be :

Component3: Hello from 3 :AppModule provider

Because basically the app structure is :

<my-app>
  <my-app-component-3>
  </my-app-component-3>
</my-app>

Question:

Why doesn't @Host()  match the parent provider ?

(which is   : providers: [{provide: Dependency, useValue: createDependency('AppModule provider')}])

To my knowledge - the injector should seek for a Dependency in this manner :

So why doesn't it find it ?

PLUNKER

Notice

I already know that if I remove @host - it does reach the top. My question is why adding @host - is not reaching the top - despite the fact thatmy-component3 is under my-app !!

Body:
Check out A curios case of the @Host decorator and Element Injectors in Angular for in-depth explanation of how @Host decorator works and where Element Injectors come into this picture.

In order for it to work you should define dependencies in the in the parent component and using viewProviders:

@Component({
  selector: 'my-app',
  viewProviders: [{provide: Dependency, useValue: createDependency('AppModule provider')}],
    ...
export class MyApp {}

Here is what the comments inside metadata.ts say:

Specifies that an injector should retrieve a dependency from any
  injector until reaching the host element of the current component.

So basically it says that a host element injector and all injectors above are not used when resolving a dependency. So if your MyApp component has the following template:

<my-app-component-3></my-app-component-3>

and the resulting components tree look like this:

<my-app>
    <my-app-component-3></my-app-component-3>
</my-app>

neither MyApp component's injector nor App module injectors are used to resolve dependency for the my-app-component-3.

However, there's the following interesting code in the ProviderElementContext._getDependency that performs one additional check:

// check @Host restriction
if (!result) {
    if (!dep.isHost || this.viewContext.component.isHost ||
       this.viewContext.component.type.reference === tokenReference(dep.token !) ||
       // this line
       this.viewContext.viewProviders.get(tokenReference(dep.token !)) != null) { <------
       result = dep;
    } else {
       result = dep.isOptional ? result = {isValue: true, value: null} : null;
    }
}

which basically checks if the provider is defined in the viewProviders and resolves it if found. That's why viewProviders work.

So, here is the lookup tree:

Usage

This decorator is mostly used for directives to resolve providers from the parent injector within the current component view. Even the unit test is written only to test directives. Here is a real example from the forms module how it's decorator is used.

Consider this template for the A component:

<form name="b">
    <input NgModel>
</form>

NgModel directive wants to resolve a provider supplied by the form directive. But if the provider is not available, there's no need to go outside of a current component A.

So NgModel is defined like this:

export class NgModel {
    constructor(@Optional() @Host() parent: ControlContainer...)

While form directive is defined like this:

@Directive({
  selector: '[formGroup]',
  providers: [{ provide: ControlContainer, useExisting: FormGroupDirective }],
  ...
})
export class NgForm

Also, a directive can inject dependencies defined by its hosting component if they are defined with viewProviders. For example, if MyApp component is defined like this:

@Component({
    selector: 'my-app',
    viewProviders: [Dependency],
    template: `<div provider-dir></div>`
})
export class AppComponent {}

the Dependency will be resolved.

ContentLicense: CC BY-SA 4.0


问:
Get Json file from laravel controller
I need to print json file passed by a Laravel controller method hosted in different server. Send code like this,

```<code>  function curlrequest($url, $data){

        $handle = curl_init($url);
        curl_setopt($handle, CURLOPT_POST, true);
        curl_setopt($handle, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
        curl_setopt($handle, CURLOPT_POSTFIELDS, $data);
        curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);

        $output = curl_exec($handle);

        if($output === FALSE) {
                    die(curl_error($handle));
                  }else{

                    return $output;
                  }

         curl_close($handle);

        }
</code>```

In receiver php file (native php),  I have following code,

```<code>echo '```'.print_r(json_decode(file_get_contents("http://xxx.xxx.xx.xx/myproject/public/send")),1).'```';
</code>```

And in my web.php file I have

```<code>Route::get('/send', 'Test\SendController@main');
</code>```

I didn't run this code yet. But I see that we cannot access routes using file_get_content method. Can anyone tell me what is the proper way to pass json in this situation?

答:
Your question seems a bit unclear, but from what I can understand you want to get the JSON output from http://xxx.xxx.xx.xx/myproject/public/send and print it in your PHP code.

An easy way to do this is to use GuzzleHttp.

Example:

```<code>$client = new \GuzzleHttp\Client();
$result = $client->request('GET', 'http://xxx.xxx.xx.xx/myproject/public/send');
echo $result->getBody();
</code>```

Title: Get Json file from laravel controller

Body:
I need to print json file passed by a Laravel controller method hosted in different server. Send code like this,

  function curlrequest($url, $data){

        $handle = curl_init($url);
        curl_setopt($handle, CURLOPT_POST, true);
        curl_setopt($handle, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
        curl_setopt($handle, CURLOPT_POSTFIELDS, $data);
        curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);

        $output = curl_exec($handle);

        if($output === FALSE) {
                    die(curl_error($handle));
                  }else{

                    return $output;
                  }

         curl_close($handle);

        }

In receiver php file (native php),  I have following code,

echo '
'.print_r(json_decode(file_get_contents("http://xxx.xxx.xx.xx/myproject/public/send")),1).'
';

And in my web.php file I have

Route::get('/send', 'Test\SendController@main');

I didn't run this code yet. But I see that we cannot access routes using file_get_content method. Can anyone tell me what is the proper way to pass json in this situation?

Body:
Your question seems a bit unclear, but from what I can understand you want to get the JSON output from http://xxx.xxx.xx.xx/myproject/public/send and print it in your PHP code.

An easy way to do this is to use GuzzleHttp.

Example:

$client = new \GuzzleHttp\Client();
$result = $client->request('GET', 'http://xxx.xxx.xx.xx/myproject/public/send');
echo $result->getBody();


问:
Java preprocess phase
I'm writing a Java application that needs a lot of static data that is stored in many enum types. Since I would like an user-friendly way to customize this data using for example xml or json files but I'm not allowed to do it directly with enums I was looking for a way to elegantly do it.

Maybe a good solution would be to have a separate java program that reads the xml files and produces the java sources that are then compiled with the remaining part of the sources. My doubs is how to automatize this process in a stand alone way (eg ant?) and how to integrate it seamlessly with eclipse so that it is autOmatically done when I'm working with the project.. Does anything similar to what I'm looking already exists? Any suggestion to solve my problem?

Thanks!

答:
You can have ant seamlessly integrate with eclipse to achive that:

In Eclipse open project properties, go to "Builders", click "New...", select "Ant Builder", select a build file, go to "Targets" tab and click "Set Targets..." for "Auto Build". Select the desired target and you are done. The target will run every time you save a source file (if "Build Automatically" is selected).

Title: Java preprocess phase


问:
Excel copy cell values to other worksheet
I'm working on a macro to copy certain rows (if column A isn't blank) of worksheet 'A' to worksheet 'B'. After a little bit of research the following code suddenly appeared. Only thing that I don't seem to work out is to copy the cell values instead of the linked formula, I tried to implement the 'copy/paste special' command, but I don't get the specific coherent code language.

```<code>Sub Samenvattend()
'
' Samenvattend Macro
'
' Sneltoets: Ctrl+Shift+S
'

Dim a As Range
Dim j As Integer
Dim Source As Worksheet
Dim Target As Worksheet

' Change worksheet designations as needed
Set Source = ActiveWorkbook.Worksheets("gedetailleerde meetstaat")
Set Target = ActiveWorkbook.Worksheets("samenvattende meetstaat")

j = 1     ' Start copying to row 1 in target sheet
For Each a In Source.Range("A1:A10000")   ' Do 10000 rows
    If a <> "" Then
       Source.Rows(a.Row).Copy Target.Rows(j)

       j = j + 1
    End If
Next a
End Sub
</code>```

Thanks :)

答:
If you're just trying to set the values of two cells equal, you can skip copy/paste, and simply set the ranges' values equal to one another.

This also lets you skip using the Clipboard and tends to be a little faster.

Just remember when doing this, it's [DESTINATION range].value = [ORIGIN range].value whereas with copy/paste, it's [ORIGIN range].copy [DESTINATION range].

```<code>For Each a In Source.Range("A1:A10000")   ' Do 10000 rows
    If a <> "" Then
       Target.Rows(j).value = Source.Rows(a.Row).Value
       j = j + 1
    End If
Next a
</code>```

Body:
I'm working on a macro to copy certain rows (if column A isn't blank) of worksheet 'A' to worksheet 'B'. After a little bit of research the following code suddenly appeared. Only thing that I don't seem to work out is to copy the cell values instead of the linked formula, I tried to implement the 'copy/paste special' command, but I don't get the specific coherent code language.

Sub Samenvattend()
'
' Samenvattend Macro
'
' Sneltoets: Ctrl+Shift+S
'

Dim a As Range
Dim j As Integer
Dim Source As Worksheet
Dim Target As Worksheet

' Change worksheet designations as needed
Set Source = ActiveWorkbook.Worksheets("gedetailleerde meetstaat")
Set Target = ActiveWorkbook.Worksheets("samenvattende meetstaat")

j = 1     ' Start copying to row 1 in target sheet
For Each a In Source.Range("A1:A10000")   ' Do 10000 rows
    If a <> "" Then
       Source.Rows(a.Row).Copy Target.Rows(j)

       j = j + 1
    End If
Next a
End Sub

Thanks :)

Body:
If you're just trying to set the values of two cells equal, you can skip copy/paste, and simply set the ranges' values equal to one another.

This also lets you skip using the Clipboard and tends to be a little faster.

Just remember when doing this, it's [DESTINATION range].value = [ORIGIN range].value whereas with copy/paste, it's [ORIGIN range].copy [DESTINATION range].

For Each a In Source.Range("A1:A10000")   ' Do 10000 rows
    If a <> "" Then
       Target.Rows(j).value = Source.Rows(a.Row).Value
       j = j + 1
    End If
Next a


问:
Limit datalist value - AngularJS
I am trying to render around 2000 values(through an API call) using DataList in AngularJS. The issue is that these values make the page so slow. Is there a way I can render only 10 items at a time and since its a datalist, probably show matching results to a limit of 10 when we type.

Here is my codepen: https://codepen.io/anon/pen/KyEXMr

```<code><main ng-app="myApp">
  <section ng-controller="dataListController">
    <form name="some">
      <label> Search
   <input type="text" list="dataList">
      </label>
      <datalist id="dataList">
        <option ng-repeat="v in names" value="{{v.eyeColor}}">Age {{v.age}}</option>
      </datalist>
    </form>
  </section>
</main>
</code>```

答: You can add an ng-if="$index < 10" to the option attribute. This will only render the items in with an index less than 10, and will still respect your text filter. LimitTo is returning a new array with only the 10 items in it, causing the text filter to not find your items.

Title: Limit datalist value - AngularJS

Body:
I am trying to render around 2000 values(through an API call) using DataList in AngularJS. The issue is that these values make the page so slow. Is there a way I can render only 10 items at a time and since its a datalist, probably show matching results to a limit of 10 when we type.

Here is my codepen: https://codepen.io/anon/pen/KyEXMr

    <form name="some">
       Search
   <input type="text" list="dataList">

      <datalist id="dataList">
        <option ng-repeat="v in names" value="{{v.eyeColor}}">Age {{v.age}}</option>
      </datalist>
    </form>


问:
Replace value with consecutive column across multiple columns r
I have a dataframe like this:

```<code>     Q1  Q1a    Q2    Q2a   Q2b
1   foo <NA>    fee   <NA>  <NA>
2   bar <NA>  other    ree  <NA>
3 other  roo    bee   <NA>  <NA>
4   bar <NA>    fee   <NA>  <NA>
5   bar <NA>  other    fee  <NA>
6 other  fee  other    <NA>  roo
</code>```

I would like to replace any occurrence of 'other' with the value from the consecutive column in the same row (i.e. Qx a) so that I can get rid of the sparse columns:

```<code>     Q1    Q2
1   foo   fee
2   bar   ree
3   roo   bee
4   bar   fee
5   bar   fee
6   fee   roo
</code>```

I could imagine doing this for one column like so:

```<code>Lines = "
Q1  Q1a    Q2    Q2a   Q2b
foo NA fee  NA  NA
bar NA other  ree  NA
other roo  bee   NA  NA
bar NA    fee   NA  NA
bar NA    other fee  NA
other  fee  other NA  roo"

df = read.table(text = Lines, header = TRUE, as.is = TRUE)

df$Q1[df$Q1=='other'] = df$Q1a[df$Q1=='other']
</code>```

and then looping through for each column, but this is a bit tiresome and slow with lots of columns and multiple values in each column.

Is there a neater way of doing this? (Also, my method wouldn't extend neatly to the Q2a Q2b example.)

答:
This doesn't scale to like Q3a - Q3f but a quick-and-dirty solution would be..</p>

```<code>library(tidyverse)

new_df <- df %>%
    mutate(Q1 = ifelse(Q1 == 'other', Q1a, Q1),
           Q2 = ifelse(Q2 == 'other',
                       ifelse(!is.na(Q2a), Q2a, Q2b))) %>%
    select(Q1, Q2)
</code>```

Body:
I have a dataframe like this:

     Q1  Q1a    Q2    Q2a   Q2b
1   foo <NA>    fee   <NA>  <NA>
2   bar <NA>  other    ree  <NA>
3 other  roo    bee   <NA>  <NA>
4   bar <NA>    fee   <NA>  <NA>
5   bar <NA>  other    fee  <NA>
6 other  fee  other    <NA>  roo

I would like to replace any occurrence of 'other' with the value from the consecutive column in the same row (i.e. Qx a) so that I can get rid of the sparse columns:

     Q1    Q2
1   foo   fee
2   bar   ree
3   roo   bee
4   bar   fee
5   bar   fee
6   fee   roo

I could imagine doing this for one column like so:

Lines = "
Q1  Q1a    Q2    Q2a   Q2b
foo NA fee  NA  NA
bar NA other  ree  NA
other roo  bee   NA  NA
bar NA    fee   NA  NA
bar NA    other fee  NA
other  fee  other NA  roo"

df = read.table(text = Lines, header = TRUE, as.is = TRUE)

df$Q1[df$Q1=='other'] = df$Q1a[df$Q1=='other']

and then looping through for each column, but this is a bit tiresome and slow with lots of columns and multiple values in each column.

Is there a neater way of doing this? (Also, my method wouldn't extend neatly to the Q2a Q2b example.)

Body:
This doesn't scale to like Q3a - Q3f but a quick-and-dirty solution would be..

library(tidyverse)

new_df <- df %>%
    mutate(Q1 = ifelse(Q1 == 'other', Q1a, Q1),
           Q2 = ifelse(Q2 == 'other',
                       ifelse(!is.na(Q2a), Q2a, Q2b))) %>%
    select(Q1, Q2)


问:
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.

答:
Yes this is possible. Have a look at https://github.com/2ndQuadrant/mysqlcompat/blob/master/sql_bits/aggregate.sql where it's already done, as such:</p>

```<code>-- GROUP_CONCAT()
-- Note: only supports the comma separator
-- Note: For DISTINCT and ORDER BY a subquery is required
CREATE OR REPLACE FUNCTION _group_concat(text, text)
RETURNS text AS $$
  SELECT CASE
    WHEN $2 IS NULL THEN $1
    WHEN $1 IS NULL THEN $2
    ELSE $1 operator(pg_catalog.||) ',' operator(pg_catalog.||) $2
  END
$$ IMMUTABLE LANGUAGE SQL;

CREATE AGGREGATE group_concat (
    BASETYPE = text,
    SFUNC = _group_concat,
    STYPE = text
);
</code>```

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:
Yes this is possible. Have a look at https://github.com/2ndQuadrant/mysqlcompat/blob/master/sql_bits/aggregate.sql where it's already done, as such:

-- GROUP_CONCAT()
-- Note: only supports the comma separator
-- Note: For DISTINCT and ORDER BY a subquery is required
CREATE OR REPLACE FUNCTION _group_concat(text, text)
RETURNS text AS $$
  SELECT CASE
    WHEN $2 IS NULL THEN $1
    WHEN $1 IS NULL THEN $2
    ELSE $1 operator(pg_catalog.||) ',' operator(pg_catalog.||) $2
  END
$$ IMMUTABLE LANGUAGE SQL;

CREATE AGGREGATE group_concat (
    BASETYPE = text,
    SFUNC = _group_concat,
    STYPE = text
);


问:
React + enzyme unit tests, can't access window.addEventListener
I have some unit tests set up, testing with enzyme's shallow method with a jsdom configuration. This has been working well until I have run into a component where I am using window.addEventListener. The unit tests is now giving back the error of

```<code>TypeError: window.addEventListener is not a function
</code>```

I have my test helpers set up for JSdom like so

```<code>import jsdom from 'jsdom';

...

global.document = jsdom.jsdom('<!doctype html><html><body></body></html>');
global.window = document.defaultView;
global.navigator = {userAgent: 'node.js'};
</code>```

this was working fine, then I upgraded to enzyme 3.x, and now I am getting this error.

I am wondering do i need to manually mock the addEventListener now, or is there something I am doing wrong to access this.

答:
I mock my document just like you do, and then if I need to use addEventListener() in a test, I just mock it in a beforeEach

```<code>  beforeEach(() => {
    document = {
      ...document,
      addEventListener: () => { },
      removeEventListener: () => { }
    }
  })
</code>```

Body:
I have some unit tests set up, testing with enzyme's shallow method with a jsdom configuration. This has been working well until I have run into a component where I am using window.addEventListener. The unit tests is now giving back the error of

TypeError: window.addEventListener is not a function

I have my test helpers set up for JSdom like so

import jsdom from 'jsdom';

...

global.document = jsdom.jsdom('<!doctype html>');
global.window = document.defaultView;
global.navigator = {userAgent: 'node.js'};

this was working fine, then I upgraded to enzyme 3.x, and now I am getting this error.

I am wondering do i need to manually mock the addEventListener now, or is there something I am doing wrong to access this.

Body:
I mock my document just like you do, and then if I need to use addEventListener() in a test, I just mock it in a beforeEach

  beforeEach(() => {
    document = {
      ...document,
      addEventListener: () => { },
      removeEventListener: () => { }
    }
  })


问:
Logic: is ( A && !(B || C)) || ( B || C ) the same as ( A || B || C )?
I've encountered some obj-c code and I'm wondering if there's a way to simplify it:

```<code>#if ( A && !(B || C)) || ( B || C )
</code>```

is this the same as?

```<code>#if ( A || B || C )
</code>```

If not, is there another way to formulate it that would be easier to read?

[edit]
I tried the truth table before asking the question, but thought I had to be missing something because I doubted that Foundation.framework/Foundation.h would employ this more complex form.   Is there a good reason for it?

Here's the original code (from Foundation.h):

```<code>#if (TARGET_OS_MAC && !(TARGET_OS_EMBEDDED || TARGET_OS_IPHONE)) || (TARGET_OS_EMBEDDED || TARGET_OS_IPHONE)
</code>```

Body:
I've encountered some obj-c code and I'm wondering if there's a way to simplify it:

#if ( A && !(B || C)) || ( B || C )

is this the same as?

#if ( A || B || C )

If not, is there another way to formulate it that would be easier to read?

[edit]
I tried the truth table before asking the question, but thought I had to be missing something because I doubted that Foundation.framework/Foundation.h would employ this more complex form.   Is there a good reason for it?

Here's the original code (from Foundation.h):

#if (TARGET_OS_MAC && !(TARGET_OS_EMBEDDED || TARGET_OS_IPHONE)) || (TARGET_OS_EMBEDDED || TARGET_OS_IPHONE)

Body:
A | B | C | (B || C) | (!(B || C)) | (A && !(B || C)) | (A && (!(B || C)) || (B || C) | (A || B || C)
------------------------------------------------------------------------------------------------------
T | T | T |     T    |       F     |         F        |                 T             |         T
T | T | F |     T    |       F     |         F        |                 T             |         T
T | F | T |     T    |       F     |         F        |                 T             |         T
T | F | F |     F    |       T     |         T        |                 T             |         T
F | T | T |     T    |       F     |         F        |                 T             |         T
F | T | F |     T    |       F     |         F        |                 T             |         T
F | F | T |     T    |       F     |         F        |                 T             |         T
F | F | F |     F    |       T     |         F        |                 F             |         F

Based on the last two columns, I would say yes.


问:
How to read Avro schema from empty RDD?
I'm using the AvroKeyInputFormat to read avro files:

```<code>val records = sc.newAPIHadoopFile[AvroKey[T], NullWritable, AvroKeyInputFormat[T]](path)
  .map(_._1.datum())
</code>```

Because I need to reflect over the schema in my job, I get the Avro schema like this:

```<code>val schema = records.first.getSchema
</code>```

Unfortunately, this fails if the avro files in path are empty (they include the writer schema, but no records).

Is there an easy way to only load the avro schema with Spark even if there are no records?

答:
I've found a solution (inspired by com.databricks.spark.avro.DefaultSource):

/**
  * Loads a schema from avro files in `directory`. This method also works if none
  * of the avro files contain any records.
  */
def schema(directory: String)(implicit sc: SparkContext): Schema = {
  val fs = FileSystem.get(new URI(directory), sc.hadoopConfiguration)
  val it = fs.listFiles(new Path(directory), false)

  var avroFile: Option[FileStatus] = None

  while (it.hasNext && avroFile.isEmpty) {
    val fileStatus = it.next()

    if (fileStatus.isFile && fileStatus.getPath.getName.endsWith(".avro")) {
      avroFile = Some(fileStatus)
    }
  }

  avroFile.fold {
    throw new Exception(s"No avro files found in $directory")
  } { file =>
    val in = new FsInput(file.getPath, sc.hadoopConfiguration)
    try {
      val reader = DataFileReader.openReader(in, new GenericDatumReader[GenericRecord]())
      try {
        reader.getSchema
      } finally {
        reader.close()
      }
    } finally {
      in.close()
    }
  }
}
```

Title: How to read Avro schema from empty RDD?

Body:
I'm using the AvroKeyInputFormat to read avro files:

val records = sc.newAPIHadoopFile[AvroKey[T], NullWritable, AvroKeyInputFormat[T]](path)
  .map(_._1.datum())

Because I need to reflect over the schema in my job, I get the Avro schema like this:

val schema = records.first.getSchema

Unfortunately, this fails if the avro files in path are empty (they include the writer schema, but no records).

Is there an easy way to only load the avro schema with Spark even if there are no records?


问:
Javascript function not working after validation
Currently doing a function whereby users can input their enquiries which will be sent to the database and retrieved by the admin, but the function of adding enquiry stopped working after i added a validation code, the problem lies in the validation but i cant seem to find the error.

My js code:

```<code>var userid = localStorage.getItem("userid");
var Texttitle;
var Textenquiry;

function validate() {
    var validate = true;

    if (Texttitle == "") {
        alert("Title cannot be empty");
        $("#Texttitle").focus();
        validate = false;
    }

    if (Textenquiry == "") {
        alert("Enquiry cannot be empty");
        $("#Textenquiry").focus();
        validate = false;
    }

    return validate;
}

function addenquiry() {

    Texttitle = $("#Texttitle").val();
    Textenquiry = $("#Textenquiry").val();

    if (validate()) {

        var xmlhttp = new XMLHttpRequest();
        var url = serverURL() + "/addenquiry.php";
        url += "?userid=" + userid + "&Texttitle=" + Texttitle + "&Textenquiry=" + Textenquiry;
        xmlhttp.onreadystatechange = function () {
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            addEnquiry(xmlhttp.responseText);
            }
        }
        xmlhttp.open("GET", url, true);
        xmlhttp.send();
    }

function addEnquiry(response) {
    var arr = JSON.parse(response);
    if (arr[0].result == 1) {
        alert("Thank You for your enquiry!")
    }
    else {
        alert("Sorry please try again");
    }

}
</code>```

My Html:

```<code> <div class="mdl-textfield mdl-js-textfield mdl-textfield--floating-label">
     <label class="mdl-textfield__label" for="Texttitle">Title</label>
       <input class="mdl-textfield__input" rows="2" type="text" id="Texttitle">
 </div>
    <br>
    <br>
 <div class="mdl-textfield mdl-js-textfield mdl-textfield--floating-label">
       <label class="mdl-textfield__label" for="Textenquiry">Message</label>
         <input class="mdl-textfield__input" rows="2" type="text" id="Textenquiry">
 </div>
    <br>
    <br>
    <button class="mdl-button mdl-color--primary mdl-js-button mdl-color-text--white full-width" onclick="addenquiry()">Submit</button>
 <div class="material-icons mdl-badge mdl-badge--overlap">�</div>
</code>```

My function was running well previously before i entered the validation codes in, after my attempt at validating, the function is unable to send enquiries into my database, would appreciate some help :).

答:
you just have a few syntax errors. First you are redefining your validate function inside itself (probably should just called the variable something different like 'validated'. However, your main issue is just that you are missing the closing brace on your addenquiry method. I'd also suggest making your method names more unique and not just changing the case of the names as debugging that kind of thing can be a nightmare as your code grows.

Try this:

```<code>        var userid = localStorage.getItem("userid");
    var Texttitle;
    var Textenquiry;

    function validate() {
        var validated = true;

        if (Texttitle == "") {
            alert("Title cannot be empty");
            $("#Texttitle").focus();
            validated = false;
        }

        if (Textenquiry == "") {
            alert("Enquiry cannot be empty");
            $("#Textenquiry").focus();
            validated = false;
        }

        return validated;
    }

    function addenquiry() {

        Texttitle = $("#Texttitle").val();
        Textenquiry = $("#Textenquiry").val();

        if (validate()) {

            var xmlhttp = new XMLHttpRequest();
            var url = serverURL() + "/addenquiry.php";
            url += "?userid=" + userid + "&Texttitle=" + Texttitle + "&Textenquiry=" + Textenquiry;
            xmlhttp.onreadystatechange = function () {
                if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                addEnquiry(xmlhttp.responseText);
                }
            }
            xmlhttp.open("GET", url, true);
            xmlhttp.send();
        }
    }

    function addEnquiry(response) {
        var arr = JSON.parse(response);
        if (arr[0].result == 1) {
            alert("Thank You for your enquiry!")
        }
        else {
            alert("Sorry please try again");
        }

    }
</code>```

Body:
Currently doing a function whereby users can input their enquiries which will be sent to the database and retrieved by the admin, but the function of adding enquiry stopped working after i added a validation code, the problem lies in the validation but i cant seem to find the error.

My js code:

var userid = localStorage.getItem("userid");
var Texttitle;
var Textenquiry;

function validate() {
    var validate = true;

    if (Texttitle == "") {
        alert("Title cannot be empty");
        $("#Texttitle").focus();
        validate = false;
    }

    if (Textenquiry == "") {
        alert("Enquiry cannot be empty");
        $("#Textenquiry").focus();
        validate = false;
    }

    return validate;
}

function addenquiry() {

    Texttitle = $("#Texttitle").val();
    Textenquiry = $("#Textenquiry").val();

    if (validate()) {

        var xmlhttp = new XMLHttpRequest();
        var url = serverURL() + "/addenquiry.php";
        url += "?userid=" + userid + "&Texttitle=" + Texttitle + "&Textenquiry=" + Textenquiry;
        xmlhttp.onreadystatechange = function () {
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            addEnquiry(xmlhttp.responseText);
            }
        }
        xmlhttp.open("GET", url, true);
        xmlhttp.send();
    }

function addEnquiry(response) {
    var arr = JSON.parse(response);
    if (arr[0].result == 1) {
        alert("Thank You for your enquiry!")
    }
    else {
        alert("Sorry please try again");
    }

}

My Html:

     Title
       <input class="mdl-textfield__input" rows="2" type="text" id="Texttitle">

       Message
         <input class="mdl-textfield__input" rows="2" type="text" id="Textenquiry">

    <button class="mdl-button mdl-color--primary mdl-js-button mdl-color-text--white full-width" onclick="addenquiry()">Submit</button>

�

My function was running well previously before i entered the validation codes in, after my attempt at validating, the function is unable to send enquiries into my database, would appreciate some help :).

Body:
you just have a few syntax errors. First you are redefining your validate function inside itself (probably should just called the variable something different like 'validated'. However, your main issue is just that you are missing the closing brace on your addenquiry method. I'd also suggest making your method names more unique and not just changing the case of the names as debugging that kind of thing can be a nightmare as your code grows.

Try this:

        var userid = localStorage.getItem("userid");
    var Texttitle;
    var Textenquiry;

    function validate() {
        var validated = true;

        if (Texttitle == "") {
            alert("Title cannot be empty");
            $("#Texttitle").focus();
            validated = false;
        }

        if (Textenquiry == "") {
            alert("Enquiry cannot be empty");
            $("#Textenquiry").focus();
            validated = false;
        }

        return validated;
    }

    function addenquiry() {

        Texttitle = $("#Texttitle").val();
        Textenquiry = $("#Textenquiry").val();

        if (validate()) {

            var xmlhttp = new XMLHttpRequest();
            var url = serverURL() + "/addenquiry.php";
            url += "?userid=" + userid + "&Texttitle=" + Texttitle + "&Textenquiry=" + Textenquiry;
            xmlhttp.onreadystatechange = function () {
                if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                addEnquiry(xmlhttp.responseText);
                }
            }
            xmlhttp.open("GET", url, true);
            xmlhttp.send();
        }
    }

    function addEnquiry(response) {
        var arr = JSON.parse(response);
        if (arr[0].result == 1) {
            alert("Thank You for your enquiry!")
        }
        else {
            alert("Sorry please try again");
        }

    }


问:
Public property of private class
I have a NavigationModel class which implements site navigation. Internally there is a private implementation of NavigationNode which I want to be able to declare within the NavigationModel but not outside of it. How would I accomplish this? When I do the following:

```<code>public class NavigationModel
{
    public List<NavigationNode> NavigationNodes { get; set; }
    public NavigationModel()
    {

    }

    private class NavigationNode
    {

    }
}
</code>```

The property tells me:

Inconsistent accessibility: property type
  'List' is less accessible than
  property 'NavigationModel.NavigationNodes'

答:
The error is raised because by declaring NavigationModel as public, you create a public interface that is used to access NavigationModel. Part of this interface are the signatures of the public methods or properties. By that, you'd publish class NavigationNode that is supposed to be private - hence the error.

In order to fix this, you could create a public interface that only contains the parts of NavigationNode that you want to publish. If you do not want to publish anything, the interface is empty. The following sample shows the basic components:

Public interface INavigationNode.

Property of type List<INavigationNode>.

Private class NavigationNode that implements the interface.

```<code>public interface INavigationNode
{
  // Add parts of NavigationNode that you want to publish
}

public class NavigationModel
{
    public List<INavigationNode> NavigationNodes { get; set; }
    public NavigationModel()
    {

    }

    private class NavigationNode : INavigationNode
    {

    }
}
</code>```

Title: Public property of private class

Body:
I have a NavigationModel class which implements site navigation. Internally there is a private implementation of NavigationNode which I want to be able to declare within the NavigationModel but not outside of it. How would I accomplish this? When I do the following:

public class NavigationModel
{
    public List<NavigationNode> NavigationNodes { get; set; }
    public NavigationModel()
    {

    }

    private class NavigationNode
    {

    }
}

The property tells me:

Inconsistent accessibility: property type
  'List' is less accessible than
  property 'NavigationModel.NavigationNodes'

Body:
The error is raised because by declaring NavigationModel as public, you create a public interface that is used to access NavigationModel. Part of this interface are the signatures of the public methods or properties. By that, you'd publish class NavigationNode that is supposed to be private - hence the error.

In order to fix this, you could create a public interface that only contains the parts of NavigationNode that you want to publish. If you do not want to publish anything, the interface is empty. The following sample shows the basic components:

Public interface INavigationNode.

Property of type List<INavigationNode>.

Private class NavigationNode that implements the interface.

public interface INavigationNode
{
  // Add parts of NavigationNode that you want to publish
}

public class NavigationModel
{
    public List<INavigationNode> NavigationNodes { get; set; }
    public NavigationModel()
    {

    }

    private class NavigationNode : INavigationNode
    {

    }
}


问:
Error in named queries
I am getting  org.hibernate.HibernateException: Errors in named queries: getPreferenceById and this is my query

```<code>@NamedQueries({
    @NamedQuery(name = "getPreferenceById",
    query = "select p from Preference p where p.profile.id=:Id") })
</code>```

and this is my preference class

```<code>@Entity(name = "perference")
public class Preference {

    @OneToOne
    @JoinColumn(name = "id", nullable = false)
    private Profile profile;

}
</code>```

The query is for fetching the preference for the given profileId, (id), but it is giving error. I have a similar named query in the Profile class, but it is not giving error.

I found this in the stacktrace,

```<code>Error in named query: getPreferenceById
org.hibernate.hql.internal.ast.QuerySyntaxException: Preference is not mapped
[select p from Preference p where p.profile.id=:Id]
</code>```

I have added the javax @Entity annotation to the preference class

What is wrong with this named query?

答: I finally got that working by changing the NamedQueries to NativeNamedQueries i don't know why it worked

Title: Error in named queries

Body:
I am getting  org.hibernate.HibernateException: Errors in named queries: getPreferenceById and this is my query

@NamedQueries({
    @NamedQuery(name = "getPreferenceById",
    query = "select p from Preference p where p.profile.id=:Id") })

and this is my preference class

@Entity(name = "perference")
public class Preference {

    @OneToOne
    @JoinColumn(name = "id", nullable = false)
    private Profile profile;

}

The query is for fetching the preference for the given profileId, (id), but it is giving error. I have a similar named query in the Profile class, but it is not giving error.

I found this in the stacktrace,

Error in named query: getPreferenceById
org.hibernate.hql.internal.ast.QuerySyntaxException: Preference is not mapped
[select p from Preference p where p.profile.id=:Id]

I have added the javax @Entity annotation to the preference class

What is wrong with this named query?


问:
redirected you too many times error on logging to word press
Hello everybody so iam trying to log-in to my Wordpress site but it is returning redirected you too many times. Error and i tried solving it using this tutorial https://www.wpbeginner.com/wp-tutorials/how-to-fix-error-too-many-redirects-issue-in-wordpress/  but removing my .htaccess didn't help

Note: This problem happened only after moving my WordPress from my old site to another and I had already changed the optian siteurl and homeurl from my Database

Checked recently those questions: wordpress blog. too many redirect error on chrome, blank page on FF (i didn't create any extra protection for wp-admin directory...)
please some help @everyone

my .htaccess file: https://downloads.br-gaming.cf/htaccess.txt

答:
Looking at your .htaccess you have a lot of rewrite rules which overlap.

for instance, you are forcing all non-www to www and SSLand down in the file you also force subdomain traffic on SSL.

I would start by removing the lower portion of the files (Any part after  #Prevent directory listings (No index) ) and add them as needed.

It may also be the way your DNS cnames and hostnames are setup