问:
Selecting text on focus using jQuery not working in Safari and Chrome
I have the following jQuery code (similar to this question)  that works in Firefox and IE, but fails (no errors, just doesn't work) in Chrome and Safari. Any ideas for a workaround?</p>

```<code>$("#souper_fancy").focus(function() { $(this).select() });
</code>```

答:
Use setSelectionRange() inside of a callback to requestAnimationFrame():

```<code>$(document).on('focus', '._selectTextOnFocus', (e) => {
    var input = e.currentTarget;
    var initialType = e.currentTarget.type;

    requestAnimationFrame(() => {
        // input.select() is not supported on iOS
        // If setSelectionRange is use on a number input in Chrome it throws an exception,
        // so here we switch to type text first.
        input.type = "text";
        input.setSelectionRange(0, Number.MAX_SAFE_INTEGER || 9999);
        input.type = initialType;
    });
});
</code>```

Use setSelectionRange() instead of select() since select() doesn't work in mobile Safari (see Programmatically selecting text in an input field on iOS devices (mobile Safari)).

It is necessary to wait using requestAnimationFrame before selecting the text, otherwise the element isn't correctly scrolled into view after the keyboard comes up on iOS.

When using setSelectionRange() it is important to set the input type to text, otherwise it may throw exceptions on Chrome (see selectionStart/selectionEnd on input type="number" no longer allowed in Chrome).

Body:
I have the following jQuery code (similar to this question)  that works in Firefox and IE, but fails (no errors, just doesn't work) in Chrome and Safari. Any ideas for a workaround?

$("#souper_fancy").focus(function() { $(this).select() });

Body:
Use setSelectionRange() inside of a callback to requestAnimationFrame():

$(document).on('focus', '._selectTextOnFocus', (e) => {
    var input = e.currentTarget;
    var initialType = e.currentTarget.type;

    requestAnimationFrame(() => {
        // input.select() is not supported on iOS
        // If setSelectionRange is use on a number input in Chrome it throws an exception,
        // so here we switch to type text first.
        input.type = "text";
        input.setSelectionRange(0, Number.MAX_SAFE_INTEGER || 9999);
        input.type = initialType;
    });
});

Use setSelectionRange() instead of select() since select() doesn't work in mobile Safari (see Programmatically selecting text in an input field on iOS devices (mobile Safari)).

It is necessary to wait using requestAnimationFrame before selecting the text, otherwise the element isn't correctly scrolled into view after the keyboard comes up on iOS.

When using setSelectionRange() it is important to set the input type to text, otherwise it may throw exceptions on Chrome (see selectionStart/selectionEnd on input type="number" no longer allowed in Chrome).


来源: stackexchange

问:
Kotlin - Android can we implement OnClickListener on Class?
I'm starting out with Kotlin and seems that onClick does not trigger if I implement it on an Activity Class

```<code>class MainActivity : AppCompatActivity(), View.OnClickListener{

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        tvTitle.text = "Hi There"

//        tvTitle.setOnClickListener { this } // NOT WORKING??
        tvTitle.setOnClickListener { doSomething() }
    }

    override fun onClick(v: View) {
        Log.d("click", "Hello")
    }

    fun doSomething(){
        Log.d("do", "Something")
    }
}
</code>```

I'm using Android Studio 3.0 with kotlin_version of 1.1.51, thank you in advance

答: try println("Something") first.

ContentLicense: CC BY-SA 3.0

Body:
I'm starting out with Kotlin and seems that onClick does not trigger if I implement it on an Activity Class

class MainActivity : AppCompatActivity(), View.OnClickListener{

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        tvTitle.text = "Hi There"

//        tvTitle.setOnClickListener { this } // NOT WORKING??
        tvTitle.setOnClickListener { doSomething() }
    }

    override fun onClick(v: View) {
        Log.d("click", "Hello")
    }

    fun doSomething(){
        Log.d("do", "Something")
    }
}

I'm using Android Studio 3.0 with kotlin_version of 1.1.51, thank you in advance

Body: try println("Something") first.


问:
Retrain Tensorflow Object detection API
I have read tutorials on how to train a new class using TensorFlow Object Detection API. But what I want to do is to add a new class to the already trained classes of a pre-trained model.

For example : MS-COCO pre-trained model has 90 classes. I want to add one more class and detect objects for 91 classes.

答:
Tensorflow object detection API supports starting from a pre-trained MS COCO checkpoint. Just set

```<code>fine_tune_checkpoint: "/usr/home/username/tmp/model.ckpt-#####"
from_detection_checkpoint: true
</code>```

In your detection pipeline. (Official reference: https://github.com/tensorflow/models/blob/master/research/object_detection/g3doc/configuring_jobs.md)

You should add the images with your extra class to the coco dataset and finetune for all 91 classes, or your network might forget what it learned previously and only detect the new object.

Title: Retrain Tensorflow Object detection API

Body:
Tensorflow object detection API supports starting from a pre-trained MS COCO checkpoint. Just set

fine_tune_checkpoint: "/usr/home/username/tmp/model.ckpt-#####"
from_detection_checkpoint: true

In your detection pipeline. (Official reference: https://github.com/tensorflow/models/blob/master/research/object_detection/g3doc/configuring_jobs.md)

You should add the images with your extra class to the coco dataset and finetune for all 91 classes, or your network might forget what it learned previously and only detect the new object.


问:
How do I prevent my JFrame from freezing?
So my problem is that sometimes when I press the JButtons in my JFrame, the whole frame freezes and can only be exited by terminating it through Eclipse. All of the JButtons have action listeners and I don't understand why they sometimes cause the JFrame to freeze and at other times do not.

Any help is appreciated.
Here is my code:

```<code>//objects
static JFrame frame = new JFrame("Flash cards revision");
static JButton beginButton = new JButton();
static JButton continueButton = new JButton("CONTINUE");
static JButton def1Button;
static JButton def2Button;
static JButton def3Button;
static JLabel keywordLabel = new JLabel();
static JLabel title = new JLabel("BIOLOGY FLASH CARDS");
static JLabel completionCount = new JLabel("Number of keywords completed - 0/15");
static JLabel message = new JLabel();

//variables
static Color backgroundColor = new Color(255, 204, 0);
static Color labelColor = new Color(44, 103, 0);
static Color buttonColor = new Color(146, 205, 0);
static Color highlightedButtonColor = new Color(255, 105, 0);
static Font textFont = new Font("Myriad Pro", Font.PLAIN, 15);
static Border border = BorderFactory.createLineBorder(Color.BLACK);
static String[] keywordsArray = new String[15];
static String[] definitionsArray = new String[15];
static boolean[] beenUsed = new boolean[15];
static int rDefNum;
static int rButtonNum;
static int rWDefNum;
static int numTimesCorrect = 0;
static int numComplete = 0;
static int originalY = 0;
static String keyword;
static String definition;
static String wDef1;
static String wDef2;

public static void main(String[] args) throws IOException
{
    prepareFrame();
    occupyKeywordsArray();
    occupyDefinitionsArray();
    prepareMenu();

    beginButton.addActionListener(new ActionListener()
    {
        public void actionPerformed(ActionEvent e)
        {
            beginButton.removeActionListener(beginButton.getActionListeners()[0]);
            prepareTest();
            getNewKeyword();
            getWrongDefinitions();
            prepareNewDefinition();
            addActionListeners();
        }
    });
}
static void prepareFrame()
{
    frame.setVisible(true);
    frame.setResizable(false);
    frame.setLayout(null);
    frame.setSize(800,600);
    frame.setLocation(500,200);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().setBackground(backgroundColor);
    frame.setIconImage(Toolkit.getDefaultToolkit().getImage("biologyIcon.png"));

}
static void prepareMenu()
{
    beginButton = new JButton("BEGIN TEST");
    frame.add(title);
    frame.add(beginButton);

    title.setOpaque(true);
    title.setSize(650,100);
    title.setLocation(75,60);
    title.setHorizontalAlignment(SwingConstants.CENTER);
    title.setBackground(labelColor);
    title.setForeground(buttonColor);
    title.setFont(textFont);
    title.setFont(title.getFont().deriveFont(60.0f));
    title.setBorder(border);

    beginButton.setBackground(buttonColor);
    beginButton.setLocation(240,220);
    beginButton.setForeground(labelColor);
    beginButton.setFont(textFont);
    beginButton.setFont(beginButton.getFont().deriveFont(55.0f));
    beginButton.setSize(320,100);
    beginButton.setFocusable(false);
    beginButton.setBorder(border);
}
static void prepareTest()
{
    def1Button = new JButton();
    def2Button = new JButton();
    def3Button = new JButton();
    continueButton = new JButton("CONTINUE");

    frame.remove(title);
    frame.remove(beginButton);
    frame.add(keywordLabel);
    frame.add(message);
    frame.add(completionCount);
    frame.add(def1Button);
    frame.add(def2Button);
    frame.add(def3Button);
    frame.add(continueButton);

    frame.repaint();
    frame.revalidate();

    keywordLabel.setOpaque(true);
    keywordLabel.setHorizontalAlignment(SwingConstants.CENTER);
    keywordLabel.setBackground(labelColor);
    keywordLabel.setForeground(buttonColor);
    keywordLabel.setFont(textFont);
    keywordLabel.setFont(keywordLabel.getFont().deriveFont(60.0f));
    keywordLabel.setBorder(border);

    message.setOpaque(true);
    message.setText("Try to match the keyword to the correct definition");
    message.setSize(450,35);
    message.setLocation(175,370);
    message.setHorizontalAlignment(SwingConstants.CENTER);
    message.setBackground(labelColor);
    message.setForeground(buttonColor);
    message.setFont(textFont);
    message.setFont(keywordLabel.getFont().deriveFont(20.0f));
    message.setBorder(border);

    completionCount.setOpaque(true);
    completionCount.setSize(340,35);
    completionCount.setLocation(230,20);
    completionCount.setHorizontalAlignment(SwingConstants.CENTER);
    completionCount.setBackground(labelColor);
    completionCount.setForeground(buttonColor);
    completionCount.setFont(textFont);
    completionCount.setFont(keywordLabel.getFont().deriveFont(20.0f));
    completionCount.setBorder(border);

    continueButton.setVisible(false);
    continueButton.setSize(300,100);
    continueButton.setLocation(250,370);
    continueButton.setBackground(buttonColor);
    continueButton.setForeground(labelColor);
    continueButton.setFont(textFont);
    continueButton.setFont(def1Button.getFont().deriveFont(50.0f));
    continueButton.setFocusable(false);
    continueButton.setBorder(border);

    def1Button.setBackground(buttonColor);
    def1Button.setForeground(labelColor);
    def1Button.setFont(textFont);
    def1Button.setFont(def1Button.getFont().deriveFont(20.0f));
    def1Button.setFocusable(false);
    def1Button.setBorder(border);

    def2Button.setBackground(buttonColor);
    def2Button.setForeground(labelColor);
    def2Button.setFont(textFont);
    def2Button.setFont(def2Button.getFont().deriveFont(20.0f));
    def2Button.setFocusable(false);
    def2Button.setBorder(border);

    def3Button.setBackground(buttonColor);
    def3Button.setForeground(labelColor);
    def3Button.setFont(textFont);
    def3Button.setFont(def3Button.getFont().deriveFont(20.0f));
    def3Button.setFocusable(false);
    def3Button.setBorder(border);
}
static void prepareNewDefinition()
{
    rButtonNum = r.nextInt(3)+1;//Chooses a random number - 1, 2 or 3

    switch(rButtonNum)
    {
    case 1:
        def1Button.setText(definition);
        def2Button.setText(wDef1);
        def3Button.setText(wDef2);
        break;
    case 2:
        def1Button.setText(wDef1);
        def2Button.setText(definition);
        def3Button.setText(wDef2);
        break;
    case 3:
        def1Button.setText(wDef1);
        def2Button.setText(wDef2);
        def3Button.setText(definition);
        break;
    }

    int b1Width = def1Button.getFontMetrics(def1Button.getFont()).stringWidth(def1Button.getText()) + 45;
    int b2Width = def2Button.getFontMetrics(def2Button.getFont()).stringWidth(def2Button.getText()) + 45;
    int b3Width = def3Button.getFontMetrics(def3Button.getFont()).stringWidth(def3Button.getText()) + 45;

    keywordLabel.setText(keyword);
    keywordLabel.setSize(keyword.length()*40,100);
    keywordLabel.setLocation(400-((keyword.length()*40)/2),80);

    def1Button.setSize(b1Width,30);
    def1Button.setLocation(400 - def1Button.getWidth() / 2,210);

    def2Button.setSize(b2Width,30);
    def2Button.setLocation(400 - def2Button.getWidth() / 2,260);

    def3Button.setSize(b3Width,30);
    def3Button.setLocation(400- def3Button.getWidth() / 2,310);

    optionsListener = new ActionListener()
    {
        public void actionPerformed(ActionEvent e)
        {
            def1Button.removeActionListener(optionsListener);
            def2Button.removeActionListener(optionsListener);
            def3Button.removeActionListener(optionsListener);
            if(e.getActionCommand().equals(definition))
            {
                correct();
            }
            else
            {
                incorrect();
            }
        }
    };
}
static void correct()
{
    numTimesCorrect++;
    if(numTimesCorrect == 1)
    {
        message.setText("Correct! Match this correctly once more to complete this keyword");
        message.setSize(550,35);
        message.setLocation(125,message.getY());
    }
    else
    {
        numComplete++;
        completionCount.setText("Number of keywords completed - "+numComplete+"/15");
        message.setText("Correct! Keyword complete!");
        message.setSize(250,35);
        message.setLocation(275,message.getY());
    }
    moveMessageDown();
    continueButton.addActionListener(new ActionListener()
    {
        public void actionPerformed(ActionEvent e)
        {
            System.out.println(continueButton.getActionListeners()[0]);
            continueButton.setVisible(false);
            continueButton.removeActionListener(continueButton.getActionListeners()[0]);
            if(numTimesCorrect == 1)
            {
                message.setSize(510,35);
                message.setLocation(145,message.getY());
                message.setText("Match this correctly once more to complete this keyword");
            }
            if(numTimesCorrect == 2)
            {
                message.setSize(450,35);
                message.setLocation(175,message.getY());
                message.setText("Try to match the keyword to the correct definition");
                getNewKeyword();
                numTimesCorrect = 0;
            }
            getWrongDefinitions();
            prepareNewDefinition();
            addActionListeners();
            moveMessageUp();
        }
    });
}
static void incorrect()
{
    numTimesCorrect = 0;
    message.setText("Incorrect! The correct definition is now highlighted");
    message.setForeground(highlightedButtonColor);

    if(def1Button.getText().equals(definition))
    {
        def1Button.setBackground(highlightedButtonColor);
    }
    if(def2Button.getText().equals(definition))
    {
        def2Button.setBackground(highlightedButtonColor);
    }
    if(def3Button.getText().equals(definition))
    {
        def3Button.setBackground(highlightedButtonColor);
    }
    message.setSize(450,35);
    message.setLocation(175,message.getY());
    moveMessageDown();

    continueButton.addActionListener(new ActionListener()
    {
        public void actionPerformed(ActionEvent e)
        {
            continueButton.setVisible(false);
            continueButton.removeActionListener(continueButton.getActionListeners()[0]);
            message.setForeground(buttonColor);
            getWrongDefinitions();
            prepareNewDefinition();
            def1Button.setBackground(buttonColor);
            def2Button.setBackground(buttonColor);
            def3Button.setBackground(buttonColor);
            message.setLocation(175,500);
            message.setText("Try to match the keyword to the correct definition");
            addActionListeners();
            moveMessageUp();
        }
    });
}
static void getNewKeyword()
{
    boolean validDef = false;

    while(validDef == false)
    {
        rDefNum = r.nextInt(15);
        if(beenUsed[rDefNum] == false)
        {
            validDef = true;
            beenUsed[rDefNum] = true;
            keyword = keywordsArray[rDefNum];
            definition = definitionsArray[rDefNum];
        }
    }
}
static void getWrongDefinitions()
{
    rWDefNum = r.nextInt(15);
    wDef1 = definitionsArray[rWDefNum];
    rWDefNum = r.nextInt(15);
    wDef2 = definitionsArray[rWDefNum];
    while(wDef1.equals(wDef2) || definition.equals(wDef1) || definition.equals(wDef2))
    {
        rWDefNum = r.nextInt(15);
        wDef1 = definitionsArray[rWDefNum];
        wDef2 = definitionsArray[rWDefNum];
    }
}
static void moveMessageDown()
{
    moveUpThread.stop();
    originalY = message.getY();
    moveDownThread = new Thread()
    {
        public void run()
        {
            try
            {
                Thread.sleep(200);
            }catch (InterruptedException e){}

            for(int loop = 0; loop <= 500-originalY; loop++)
            {
                try
                {
                    Thread.sleep(6);
                } catch (InterruptedException e){}

                message.setLocation(message.getX(),originalY+loop);
            }
            continueButton.setVisible(true);
        }
    };
    moveDownThread.start();
}
static void moveMessageUp()
{
    originalY = message.getY();
    moveUpThread = new Thread()
    {
        public void run()
        {

            try
            {
                Thread.sleep(200);
            }catch (InterruptedException e){}

            for(int loop = 0; loop <= 630 - originalY; loop++)
            {
                try
                {
                    Thread.sleep(6);
                } catch (InterruptedException e){}

                message.setLocation(message.getX(),500-loop);
            }
        }
    };
    moveUpThread.start();
}
static void addActionListeners()
{
    def1Button.addActionListener(optionsListener);
    def2Button.addActionListener(optionsListener);
    def3Button.addActionListener(optionsListener);
}
static void occupyKeywordsArray() throws IOException
{
    BufferedReader keywordsReader = new BufferedReader(new FileReader("keywords.txt"));
    for(int keywordsLoop = 0; keywordsLoop <= 14; keywordsLoop++)
    {
        keywordsArray[keywordsLoop] = keywordsReader.readLine();
        keywordsReader.readLine();
    }
    keywordsReader.close();
}
static void occupyDefinitionsArray() throws IOException
{
    BufferedReader definitionsReader = new BufferedReader(new FileReader("keywords.txt"));
    for(int definitionsLoop = 0; definitionsLoop <= 14; definitionsLoop++)
    {
        definitionsReader.readLine();
        definitionsArray[definitionsLoop] = definitionsReader.readLine();
    }
    definitionsReader.close();
}
 }
</code>```

答:
I did the same as @carexcer with an invokeLater call as follows and it works for me:</p>

```<code>public static void main(String[] args) {
//        EventQueue.invokeLater(() -> {
        Toolkit.getDefaultToolkit().setDynamicLayout(false);
        final JFrame frame = new JFrame();
        frame.setUndecorated(true);
        final JToggleButton backgroundButton = new JToggleButton("Break me!");
        backgroundButton.setSelected(true);
        backgroundButton.addActionListener(e -> {
            if(!backgroundButton.isSelected()) {
                EventQueue.invokeLater(new Runnable() {
                    @Override
                    public void run() {
                        frame.setBackground(new Color(0, 0, 0, 0));
                        backgroundButton.setText("Fix me!");
                    }
                });
            } else {
                EventQueue.invokeLater(new Runnable() {
                    @Override
                    public void run() {
                        frame.setBackground(UIManager.getColor("control"));
                        backgroundButton.setText("Break me!");
                    }
                });
            }
        });
        final JLabel label = new JLabel("Resize Here");
        label.setBorder(BorderFactory.createLineBorder(Color.RED));
        frame.getContentPane().add(backgroundButton);
        frame.getContentPane().add(label, BorderLayout.SOUTH);
        new ComponentResizer(frame);

        frame.pack();
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.setVisible(true);
//       });
}
</code>```

Body:
So my problem is that sometimes when I press the JButtons in my JFrame, the whole frame freezes and can only be exited by terminating it through Eclipse. All of the JButtons have action listeners and I don't understand why they sometimes cause the JFrame to freeze and at other times do not.

Any help is appreciated.
Here is my code:

//objects
static JFrame frame = new JFrame("Flash cards revision");
static JButton beginButton = new JButton();
static JButton continueButton = new JButton("CONTINUE");
static JButton def1Button;
static JButton def2Button;
static JButton def3Button;
static JLabel keywordLabel = new JLabel();
static JLabel title = new JLabel("BIOLOGY FLASH CARDS");
static JLabel completionCount = new JLabel("Number of keywords completed - 0/15");
static JLabel message = new JLabel();

//variables
static Color backgroundColor = new Color(255, 204, 0);
static Color labelColor = new Color(44, 103, 0);
static Color buttonColor = new Color(146, 205, 0);
static Color highlightedButtonColor = new Color(255, 105, 0);
static Font textFont = new Font("Myriad Pro", Font.PLAIN, 15);
static Border border = BorderFactory.createLineBorder(Color.BLACK);
static String[] keywordsArray = new String[15];
static String[] definitionsArray = new String[15];
static boolean[] beenUsed = new boolean[15];
static int rDefNum;
static int rButtonNum;
static int rWDefNum;
static int numTimesCorrect = 0;
static int numComplete = 0;
static int originalY = 0;
static String keyword;
static String definition;
static String wDef1;
static String wDef2;

public static void main(String[] args) throws IOException
{
    prepareFrame();
    occupyKeywordsArray();
    occupyDefinitionsArray();
    prepareMenu();

    beginButton.addActionListener(new ActionListener()
    {
        public void actionPerformed(ActionEvent e)
        {
            beginButton.removeActionListener(beginButton.getActionListeners()[0]);
            prepareTest();
            getNewKeyword();
            getWrongDefinitions();
            prepareNewDefinition();
            addActionListeners();
        }
    });
}
static void prepareFrame()
{
    frame.setVisible(true);
    frame.setResizable(false);
    frame.setLayout(null);
    frame.setSize(800,600);
    frame.setLocation(500,200);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().setBackground(backgroundColor);
    frame.setIconImage(Toolkit.getDefaultToolkit().getImage("biologyIcon.png"));

}
static void prepareMenu()
{
    beginButton = new JButton("BEGIN TEST");
    frame.add(title);
    frame.add(beginButton);

    title.setOpaque(true);
    title.setSize(650,100);
    title.setLocation(75,60);
    title.setHorizontalAlignment(SwingConstants.CENTER);
    title.setBackground(labelColor);
    title.setForeground(buttonColor);
    title.setFont(textFont);
    title.setFont(title.getFont().deriveFont(60.0f));
    title.setBorder(border);

    beginButton.setBackground(buttonColor);
    beginButton.setLocation(240,220);
    beginButton.setForeground(labelColor);
    beginButton.setFont(textFont);
    beginButton.setFont(beginButton.getFont().deriveFont(55.0f));
    beginButton.setSize(320,100);
    beginButton.setFocusable(false);
    beginButton.setBorder(border);
}
static void prepareTest()
{
    def1Button = new JButton();
    def2Button = new JButton();
    def3Button = new JButton();
    continueButton = new JButton("CONTINUE");

    frame.remove(title);
    frame.remove(beginButton);
    frame.add(keywordLabel);
    frame.add(message);
    frame.add(completionCount);
    frame.add(def1Button);
    frame.add(def2Button);
    frame.add(def3Button);
    frame.add(continueButton);

    frame.repaint();
    frame.revalidate();

    keywordLabel.setOpaque(true);
    keywordLabel.setHorizontalAlignment(SwingConstants.CENTER);
    keywordLabel.setBackground(labelColor);
    keywordLabel.setForeground(buttonColor);
    keywordLabel.setFont(textFont);
    keywordLabel.setFont(keywordLabel.getFont().deriveFont(60.0f));
    keywordLabel.setBorder(border);

    message.setOpaque(true);
    message.setText("Try to match the keyword to the correct definition");
    message.setSize(450,35);
    message.setLocation(175,370);
    message.setHorizontalAlignment(SwingConstants.CENTER);
    message.setBackground(labelColor);
    message.setForeground(buttonColor);
    message.setFont(textFont);
    message.setFont(keywordLabel.getFont().deriveFont(20.0f));
    message.setBorder(border);

    completionCount.setOpaque(true);
    completionCount.setSize(340,35);
    completionCount.setLocation(230,20);
    completionCount.setHorizontalAlignment(SwingConstants.CENTER);
    completionCount.setBackground(labelColor);
    completionCount.setForeground(buttonColor);
    completionCount.setFont(textFont);
    completionCount.setFont(keywordLabel.getFont().deriveFont(20.0f));
    completionCount.setBorder(border);

    continueButton.setVisible(false);
    continueButton.setSize(300,100);
    continueButton.setLocation(250,370);
    continueButton.setBackground(buttonColor);
    continueButton.setForeground(labelColor);
    continueButton.setFont(textFont);
    continueButton.setFont(def1Button.getFont().deriveFont(50.0f));
    continueButton.setFocusable(false);
    continueButton.setBorder(border);

    def1Button.setBackground(buttonColor);
    def1Button.setForeground(labelColor);
    def1Button.setFont(textFont);
    def1Button.setFont(def1Button.getFont().deriveFont(20.0f));
    def1Button.setFocusable(false);
    def1Button.setBorder(border);

    def2Button.setBackground(buttonColor);
    def2Button.setForeground(labelColor);
    def2Button.setFont(textFont);
    def2Button.setFont(def2Button.getFont().deriveFont(20.0f));
    def2Button.setFocusable(false);
    def2Button.setBorder(border);

    def3Button.setBackground(buttonColor);
    def3Button.setForeground(labelColor);
    def3Button.setFont(textFont);
    def3Button.setFont(def3Button.getFont().deriveFont(20.0f));
    def3Button.setFocusable(false);
    def3Button.setBorder(border);
}
static void prepareNewDefinition()
{
    rButtonNum = r.nextInt(3)+1;//Chooses a random number - 1, 2 or 3

    switch(rButtonNum)
    {
    case 1:
        def1Button.setText(definition);
        def2Button.setText(wDef1);
        def3Button.setText(wDef2);
        break;
    case 2:
        def1Button.setText(wDef1);
        def2Button.setText(definition);
        def3Button.setText(wDef2);
        break;
    case 3:
        def1Button.setText(wDef1);
        def2Button.setText(wDef2);
        def3Button.setText(definition);
        break;
    }

    int b1Width = def1Button.getFontMetrics(def1Button.getFont()).stringWidth(def1Button.getText()) + 45;
    int b2Width = def2Button.getFontMetrics(def2Button.getFont()).stringWidth(def2Button.getText()) + 45;
    int b3Width = def3Button.getFontMetrics(def3Button.getFont()).stringWidth(def3Button.getText()) + 45;

    keywordLabel.setText(keyword);
    keywordLabel.setSize(keyword.length()*40,100);
    keywordLabel.setLocation(400-((keyword.length()*40)/2),80);

    def1Button.setSize(b1Width,30);
    def1Button.setLocation(400 - def1Button.getWidth() / 2,210);

    def2Button.setSize(b2Width,30);
    def2Button.setLocation(400 - def2Button.getWidth() / 2,260);

    def3Button.setSize(b3Width,30);
    def3Button.setLocation(400- def3Button.getWidth() / 2,310);

    optionsListener = new ActionListener()
    {
        public void actionPerformed(ActionEvent e)
        {
            def1Button.removeActionListener(optionsListener);
            def2Button.removeActionListener(optionsListener);
            def3Button.removeActionListener(optionsListener);
            if(e.getActionCommand().equals(definition))
            {
                correct();
            }
            else
            {
                incorrect();
            }
        }
    };
}
static void correct()
{
    numTimesCorrect++;
    if(numTimesCorrect == 1)
    {
        message.setText("Correct! Match this correctly once more to complete this keyword");
        message.setSize(550,35);
        message.setLocation(125,message.getY());
    }
    else
    {
        numComplete++;
        completionCount.setText("Number of keywords completed - "+numComplete+"/15");
        message.setText("Correct! Keyword complete!");
        message.setSize(250,35);
        message.setLocation(275,message.getY());
    }
    moveMessageDown();
    continueButton.addActionListener(new ActionListener()
    {
        public void actionPerformed(ActionEvent e)
        {
            System.out.println(continueButton.getActionListeners()[0]);
            continueButton.setVisible(false);
            continueButton.removeActionListener(continueButton.getActionListeners()[0]);
            if(numTimesCorrect == 1)
            {
                message.setSize(510,35);
                message.setLocation(145,message.getY());
                message.setText("Match this correctly once more to complete this keyword");
            }
            if(numTimesCorrect == 2)
            {
                message.setSize(450,35);
                message.setLocation(175,message.getY());
                message.setText("Try to match the keyword to the correct definition");
                getNewKeyword();
                numTimesCorrect = 0;
            }
            getWrongDefinitions();
            prepareNewDefinition();
            addActionListeners();
            moveMessageUp();
        }
    });
}
static void incorrect()
{
    numTimesCorrect = 0;
    message.setText("Incorrect! The correct definition is now highlighted");
    message.setForeground(highlightedButtonColor);

    if(def1Button.getText().equals(definition))
    {
        def1Button.setBackground(highlightedButtonColor);
    }
    if(def2Button.getText().equals(definition))
    {
        def2Button.setBackground(highlightedButtonColor);
    }
    if(def3Button.getText().equals(definition))
    {
        def3Button.setBackground(highlightedButtonColor);
    }
    message.setSize(450,35);
    message.setLocation(175,message.getY());
    moveMessageDown();

    continueButton.addActionListener(new ActionListener()
    {
        public void actionPerformed(ActionEvent e)
        {
            continueButton.setVisible(false);
            continueButton.removeActionListener(continueButton.getActionListeners()[0]);
            message.setForeground(buttonColor);
            getWrongDefinitions();
            prepareNewDefinition();
            def1Button.setBackground(buttonColor);
            def2Button.setBackground(buttonColor);
            def3Button.setBackground(buttonColor);
            message.setLocation(175,500);
            message.setText("Try to match the keyword to the correct definition");
            addActionListeners();
            moveMessageUp();
        }
    });
}
static void getNewKeyword()
{
    boolean validDef = false;

    while(validDef == false)
    {
        rDefNum = r.nextInt(15);
        if(beenUsed[rDefNum] == false)
        {
            validDef = true;
            beenUsed[rDefNum] = true;
            keyword = keywordsArray[rDefNum];
            definition = definitionsArray[rDefNum];
        }
    }
}
static void getWrongDefinitions()
{
    rWDefNum = r.nextInt(15);
    wDef1 = definitionsArray[rWDefNum];
    rWDefNum = r.nextInt(15);
    wDef2 = definitionsArray[rWDefNum];
    while(wDef1.equals(wDef2) || definition.equals(wDef1) || definition.equals(wDef2))
    {
        rWDefNum = r.nextInt(15);
        wDef1 = definitionsArray[rWDefNum];
        wDef2 = definitionsArray[rWDefNum];
    }
}
static void moveMessageDown()
{
    moveUpThread.stop();
    originalY = message.getY();
    moveDownThread = new Thread()
    {
        public void run()
        {
            try
            {
                Thread.sleep(200);
            }catch (InterruptedException e){}

            for(int loop = 0; loop <= 500-originalY; loop++)
            {
                try
                {
                    Thread.sleep(6);
                } catch (InterruptedException e){}

                message.setLocation(message.getX(),originalY+loop);
            }
            continueButton.setVisible(true);
        }
    };
    moveDownThread.start();
}
static void moveMessageUp()
{
    originalY = message.getY();
    moveUpThread = new Thread()
    {
        public void run()
        {

            try
            {
                Thread.sleep(200);
            }catch (InterruptedException e){}

            for(int loop = 0; loop <= 630 - originalY; loop++)
            {
                try
                {
                    Thread.sleep(6);
                } catch (InterruptedException e){}

                message.setLocation(message.getX(),500-loop);
            }
        }
    };
    moveUpThread.start();
}
static void addActionListeners()
{
    def1Button.addActionListener(optionsListener);
    def2Button.addActionListener(optionsListener);
    def3Button.addActionListener(optionsListener);
}
static void occupyKeywordsArray() throws IOException
{
    BufferedReader keywordsReader = new BufferedReader(new FileReader("keywords.txt"));
    for(int keywordsLoop = 0; keywordsLoop <= 14; keywordsLoop++)
    {
        keywordsArray[keywordsLoop] = keywordsReader.readLine();
        keywordsReader.readLine();
    }
    keywordsReader.close();
}
static void occupyDefinitionsArray() throws IOException
{
    BufferedReader definitionsReader = new BufferedReader(new FileReader("keywords.txt"));
    for(int definitionsLoop = 0; definitionsLoop <= 14; definitionsLoop++)
    {
        definitionsReader.readLine();
        definitionsArray[definitionsLoop] = definitionsReader.readLine();
    }
    definitionsReader.close();
}
 }

Body:
I did the same as @carexcer with an invokeLater call as follows and it works for me:

public static void main(String[] args) {
//        EventQueue.invokeLater(() -> {
        Toolkit.getDefaultToolkit().setDynamicLayout(false);
        final JFrame frame = new JFrame();
        frame.setUndecorated(true);
        final JToggleButton backgroundButton = new JToggleButton("Break me!");
        backgroundButton.setSelected(true);
        backgroundButton.addActionListener(e -> {
            if(!backgroundButton.isSelected()) {
                EventQueue.invokeLater(new Runnable() {
                    @Override
                    public void run() {
                        frame.setBackground(new Color(0, 0, 0, 0));
                        backgroundButton.setText("Fix me!");
                    }
                });
            } else {
                EventQueue.invokeLater(new Runnable() {
                    @Override
                    public void run() {
                        frame.setBackground(UIManager.getColor("control"));
                        backgroundButton.setText("Break me!");
                    }
                });
            }
        });
        final JLabel label = new JLabel("Resize Here");
        label.setBorder(BorderFactory.createLineBorder(Color.RED));
        frame.getContentPane().add(backgroundButton);
        frame.getContentPane().add(label, BorderLayout.SOUTH);
        new ComponentResizer(frame);

        frame.pack();
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.setVisible(true);
//       });
}


问:
Is there a "null coalescing" operator in JavaScript?
Is there a null coalescing operator in Javascript?

For example, in C#, I can do this:

```<code>String someString = null;
var whatIWant = someString ?? "Cookies!";
</code>```

The best approximation I can figure out for Javascript is using the conditional operator:

```<code>var someString = null;
var whatIWant = someString ? someString : 'Cookies!';
</code>```

Which is sorta icky IMHO. Can I do better?

答:
beware of the JavaScript specific definition of null. there are two definitions for "no value" in javascript.
1. Null: when a variable is null, it means it contains no data in it, but the variable is already defined in the code. like this:

```<code>var myEmptyValue = 1;
myEmptyValue = null;
if ( myEmptyValue === null ) { window.alert('it is null'); }
// alerts
</code>```

in such case, the type of your variable is actually Object. test it.

```<code>window.alert(typeof myEmptyValue); // prints Object
</code>```

Undefined: when a variable has not been defined before in the code, and as expected, it does not contain any value. like this:

```<code>if ( myUndefinedValue === undefined ) { window.alert('it is undefined'); }
// alerts
</code>```

if such case, the type of your variable is 'undefined'.

notice that if you use the type-converting comparison operator (==), JavaScript will act equally for both of these empty-values. to distinguish between them, always use the type-strict comparison operator (===).

OwnerDisplayName: Daniel Schaffer

Body:
Is there a null coalescing operator in Javascript?

For example, in C#, I can do this:

String someString = null;
var whatIWant = someString ?? "Cookies!";

The best approximation I can figure out for Javascript is using the conditional operator:

var someString = null;
var whatIWant = someString ? someString : 'Cookies!';

Which is sorta icky IMHO. Can I do better?

LastEditorDisplayName: Daniel Schaffer

Body:
beware of the JavaScript specific definition of null. there are two definitions for "no value" in javascript.
1. Null: when a variable is null, it means it contains no data in it, but the variable is already defined in the code. like this:

var myEmptyValue = 1;
myEmptyValue = null;
if ( myEmptyValue === null ) { window.alert('it is null'); }
// alerts

in such case, the type of your variable is actually Object. test it.

window.alert(typeof myEmptyValue); // prints Object

Undefined: when a variable has not been defined before in the code, and as expected, it does not contain any value. like this:

if ( myUndefinedValue === undefined ) { window.alert('it is undefined'); }
// alerts

if such case, the type of your variable is 'undefined'.

notice that if you use the type-converting comparison operator (==), JavaScript will act equally for both of these empty-values. to distinguish between them, always use the type-strict comparison operator (===).

OwnerDisplayName: farzad


问:
If an object is passed as an argument in a function, does it create a new instance?
In this code:

```<code>function myFunction(obj) {
  console.log(obj);
}

var obj = {
  key : 'value',
  funct :  function(){},
  elem  :  document.getElementById('navigation').getElementsByTagName('a')
}

myFunction(obj);
</code>```

Is the object "obj" printed in the console inside myFunction the same object i defined or is a new instance?

Also, what if i pass it from myFunction to another function?

答:
That's easy enough to answer for yourself.  Try this code and see what happens:

```<code>function Test(obj) {
  obj.Whatever = "!";
}

var testObj = { original: true };
Test(testObj);
alert(testObj.Whatever);
</code>```

If the alert shows "undefined", then you made a copy when passing into the function.  If the alert shows "!", then you passed the object itself (or reference, or pointer) into the function.

I'm pretty sure you'll see the "!"

ContentLicense: CC BY-SA 2.5

Body:
In this code:

function myFunction(obj) {
  console.log(obj);
}

var obj = {
  key : 'value',
  funct :  function(){},
  elem  :  document.getElementById('navigation').getElementsByTagName('a')
}

myFunction(obj);

Is the object "obj" printed in the console inside myFunction the same object i defined or is a new instance?

Also, what if i pass it from myFunction to another function?

Body:
That's easy enough to answer for yourself.  Try this code and see what happens:

function Test(obj) {
  obj.Whatever = "!";
}

var testObj = { original: true };
Test(testObj);
alert(testObj.Whatever);

If the alert shows "undefined", then you made a copy when passing into the function.  If the alert shows "!", then you passed the object itself (or reference, or pointer) into the function.

I'm pretty sure you'll see the "!"


问:
Can I get the output of a independent background job again? (e.g. a job run in `screen`, and I close the terminal)
as described in title:

    first:I run screen in terminal

    second:run ping google.com

    then:I press CTRL-Ad to exit to normal terminal and close it

And I want to know if I can get the output of command ping google again?

答: After you press <c-a> d the screen session will continue running in background and closing the "normal terminal" would not kill the screen. Afterwards you can re-attach to the screen session with screen -r.


问:
How can I update all except the max value in a group by
I have the table below:

```<code>+----+----------+-----+-------
| ID | animal| pets | age
+----+----------+-----+------
|  1 | pig   | y    | 19
|  2 | pig   | y    | 21
|  3 | horse | y    | 23
|  4 | dog   | y    | 45
|  5 | dog   | y    | 56
|  6 | cat   | n    | 34
|  7 | cat   | y    | 56
</code>```

I need help building a query that sets Pets to 'n' for the rows of that kind of animal that have an age thats less than the maximum value of age for that animal that is set to 'y'. So there could only be one row for each animal set to 'y' and it must be that with the max age so the resulting table should look like this:

```<code>+----+----------+-----+-------
| ID | animal| pets | age
+----+----------+-----+------
|  1 | pig   | n    | 19
|  2 | pig   | y    | 21
|  3 | horse | y    | 23
|  4 | dog   | n    | 45
|  5 | dog   | y    | 56
|  6 | cat   | n    | 34
|  7 | cat   | y    | 56
</code>```

答:
TRY THIS: you can use subquery but in case of same ages it will not be updated:

```<code>UPDATE temp SET pets = 'n'
WHERE age in ( SELECT t.age
FROM temp t
INNER JOIN (SELECT animal, MAX(age) age
            FROM temp GROUP BY animal) t1 ON t1.animal = t.animal AND t1.age <> t.age)
</code>```

Body:
I have the table below:

+----+----------+-----+-------
| ID | animal| pets | age
+----+----------+-----+------
|  1 | pig   | y    | 19
|  2 | pig   | y    | 21
|  3 | horse | y    | 23
|  4 | dog   | y    | 45
|  5 | dog   | y    | 56
|  6 | cat   | n    | 34
|  7 | cat   | y    | 56

I need help building a query that sets Pets to 'n' for the rows of that kind of animal that have an age thats less than the maximum value of age for that animal that is set to 'y'. So there could only be one row for each animal set to 'y' and it must be that with the max age so the resulting table should look like this:

+----+----------+-----+-------
| ID | animal| pets | age
+----+----------+-----+------
|  1 | pig   | n    | 19
|  2 | pig   | y    | 21
|  3 | horse | y    | 23
|  4 | dog   | n    | 45
|  5 | dog   | y    | 56
|  6 | cat   | n    | 34
|  7 | cat   | y    | 56

Body:
TRY THIS: you can use subquery but in case of same ages it will not be updated:

UPDATE temp SET pets = 'n'
WHERE age in ( SELECT t.age
FROM temp t
INNER JOIN (SELECT animal, MAX(age) age
            FROM temp GROUP BY animal) t1 ON t1.animal = t.animal AND t1.age <> t.age)


答:
SQL Fiddle

Oracle 11g R2 Schema Setup:

```<code>CREATE TABLE Pets
    (ID int, ANIMAL varchar2(5), PETS varchar2(1), AGE int)
;

INSERT ALL
    INTO Pets (ID, ANIMAL, PETS, AGE)
         VALUES (1, 'pig', 'y', 19)
    INTO Pets (ID, ANIMAL, PETS, AGE)
         VALUES (2, 'pig', 'y', 21)
    INTO Pets (ID, ANIMAL, PETS, AGE)
         VALUES (3, 'horse', 'y', 23)
    INTO Pets (ID, ANIMAL, PETS, AGE)
         VALUES (4, 'dog', 'y', 45)
    INTO Pets (ID, ANIMAL, PETS, AGE)
         VALUES (5, 'dog', 'y', 56)
    INTO Pets (ID, ANIMAL, PETS, AGE)
         VALUES (6, 'cat', 'n', 34)
    INTO Pets (ID, ANIMAL, PETS, AGE)
         VALUES (7, 'cat', 'y', 56)
SELECT * FROM dual
;
</code>```

Query 1:

```<code>update pets
set pets = case when age = (select max(age) from pets p where pets.animal = p.animal)
                then 'Y'
                else 'N'
           end
;
</code>```

Results:

```<code>select
*
from pets

| ID | ANIMAL | PETS | AGE |
|----|--------|------|-----|
|  1 |    pig |    N |  19 |
|  2 |    pig |    Y |  21 |
|  3 |  horse |    Y |  23 |
|  4 |    dog |    N |  45 |
|  5 |    dog |    Y |  56 |
|  6 |    cat |    N |  34 |
|  7 |    cat |    Y |  56 |
</code>```

I'm not sure why you need this as an update. A view would be far simpler, e.g.

```<code>select ID, ANIMAL, AGE
      , case when AGE = max(AGE) over(partition by animal) then 'Y' else 'N' end pets_2
from pets
</code>```

Title: How can I update all except the max value in a group by

Body:
SQL Fiddle

Oracle 11g R2 Schema Setup:

CREATE TABLE Pets
    (ID int, ANIMAL varchar2(5), PETS varchar2(1), AGE int)
;

INSERT ALL
    INTO Pets (ID, ANIMAL, PETS, AGE)
         VALUES (1, 'pig', 'y', 19)
    INTO Pets (ID, ANIMAL, PETS, AGE)
         VALUES (2, 'pig', 'y', 21)
    INTO Pets (ID, ANIMAL, PETS, AGE)
         VALUES (3, 'horse', 'y', 23)
    INTO Pets (ID, ANIMAL, PETS, AGE)
         VALUES (4, 'dog', 'y', 45)
    INTO Pets (ID, ANIMAL, PETS, AGE)
         VALUES (5, 'dog', 'y', 56)
    INTO Pets (ID, ANIMAL, PETS, AGE)
         VALUES (6, 'cat', 'n', 34)
    INTO Pets (ID, ANIMAL, PETS, AGE)
         VALUES (7, 'cat', 'y', 56)
SELECT * FROM dual
;

Query 1:

update pets
set pets = case when age = (select max(age) from pets p where pets.animal = p.animal)
                then 'Y'
                else 'N'
           end
;

Results:

select
*
from pets

| ID | ANIMAL | PETS | AGE |
|----|--------|------|-----|
|  1 |    pig |    N |  19 |
|  2 |    pig |    Y |  21 |
|  3 |  horse |    Y |  23 |
|  4 |    dog |    N |  45 |
|  5 |    dog |    Y |  56 |
|  6 |    cat |    N |  34 |
|  7 |    cat |    Y |  56 |

I'm not sure why you need this as an update. A view would be far simpler, e.g.

select ID, ANIMAL, AGE
      , case when AGE = max(AGE) over(partition by animal) then 'Y' else 'N' end pets_2
from pets


问:
Why does this if true condition in js doesn't work
 I'm trying to display play or pause button when a user clicks on it. I know I can actually compare those links but I think using a variable would be easier to see?
 Thanks.

 `

```<code><!DOCTYPE html>
<html>
<head>
    <title>ch6</title>
</head>
<body>
    <h1>List</h1>
    <h2>audio note</h2>
    <p>Enter note name</p>
    <input type="text" >
<br>
    <img id="pic" onclick="click()" src="http://www.clker.com/cliparts/d/b/c/f/13652249372108434179Record%20Button%20Microphone.svg.hi.png" alt="record" style="width:50px;height:60px;">
<script type="text/javascript">
    function click(){
        var butt = true;
        if(butt === true)
        {
            document.getElementById("pic").src = "https://www.shareicon.net/download/2017/02/07/878546_media_512x512.png";
            butt = false;

        }
        else
        {
            document.getElementById("pic").src = "http://www.clker.com/cliparts/d/b/c/f/13652249372108434179Record%20Button%20Microphone.svg.hi.png";
            butt = true;
        }
    }

</script>

</body>
</html>
</code>```

`

 I hope to click to change the image.

 The image doesn't change when I click it.

答:
You need to take the variable initialization outside of the function itself</p>

```<code><script type="text/javascript">
    var butt = true;
    function click(){
        if(butt === true)
        {
            document.getElementById("pic").src = "https://www.shareicon.net/download/2017/02/07/878546_media_512x512.png";
            butt = false;

        }
        else
        {
            document.getElementById("pic").src = "http://www.clker.com/cliparts/d/b/c/f/13652249372108434179Record%20Button%20Microphone.svg.hi.png";
            butt = true;
        }
    }

</script>
</code>```

Body:
 I'm trying to display play or pause button when a user clicks on it. I know I can actually compare those links but I think using a variable would be easier to see?
 Thanks.

 `

<!DOCTYPE html>

    <title>ch6</title>

List

audio note

Enter note name

    <input type="text" >

`

 I hope to click to change the image.

 The image doesn't change when I click it.

Body:
You need to take the variable initialization outside of the function itself

<script type="text/javascript">
    var butt = true;
    function click(){
        if(butt === true)
        {
            document.getElementById("pic").src = "https://www.shareicon.net/download/2017/02/07/878546_media_512x512.png";
            butt = false;

        }
        else
        {
            document.getElementById("pic").src = "http://www.clker.com/cliparts/d/b/c/f/13652249372108434179Record%20Button%20Microphone.svg.hi.png";
            butt = true;
        }
    }

</script>


问:
Why is the Visual Studio 2015/2017/2019 Test Runner not discovering my xUnit v2 tests
UPDATE: Adding a 2019; the discovery/runner integration mechanism is same as per 2017 & 2015, so the key things that can go wrong are the same.

I've read Why is the xUnit runner not finding my tests, which covers reasons xUnit would never be able to find your tests but my problem is different - I'm confident there's nothing subtle going on with my tests; (they have worked in other environments, this seems to be just my machine) - the Visual Studio Test Runner in Visual Studio 2015 [Community Edition] is simply not showing any of my tests. I'm not doing anything remotely exciting; the tests target xUnit.net v2 on the Desktop.

I've looked in the Output window and am not seeing anything in at all under Test in the Show output from tabs.

答: I Cleared Temp, %Temp% and Prefetch. Then tried reopening VS and was able to find the test methods</p>

ContentLicense: CC BY-SA 4.0


问:
Could someone please explain how integers in the form of 0x0 etc work?
As the title says, could someone please explain how integers work, like those seen in memory addresses. Any answers would be greatly appreciated; the context of the situation is that I want to be able to view edit and delete data stored in a processes allocated memory.

Thanks :D

答: 0x00 notation means that the number is in Hexadecimal Format. Mostly these numbers are used for the memory location addresses or the read/write data packet formats. This  link might help.</p>


问:
Handling DateTime precision > 6 in Elixir
I have this function in my code:

```<code>  defp to_date({year, month, day}), do: NaiveDateTime.from_erl!({{year, month, day}, {0, 0, 0}}, {0, 6}) |> NaiveDateTime.to_string()
  defp to_date({{year, month, day}, {hour, min, sec, msec}}) when msec < 1000000,
    do: NaiveDateTime.from_erl!({{year, month, day}, {hour, min, sec}}, {msec, 6}) |> NaiveDateTime.to_string()

  defp to_date(x), do: x
</code>```

How would you handle cases when msec > 6-digits.

Pulling data from a SQLServer datetime2(7) with the Tds library works just fine:

```<code>iex(45)> r = Tds.Connection.query(:RMASDB, "select * from users where user_id = 1" , [])
{:ok,
 %Tds.Result{columns: ["user_id", "name", "email", "mobiles", "password", "roles", "active", "reset_required", "last_login", "has_picture", "last_modified", "last_modified_by"], command: nil, num_rows: 1,
  rows: [[1, "Charles Okwuagwu", "charleso@mydomain.com", "mobile1, mobile2", "/eNvuOyr5N6HxgYdz3fK7A==|QHx/sOa3Se0C3ZeLSNtT97SCsuWL11SJeLykms7faGY=", "Administrator", true, false,
    {{2017, 11, 30}, {18, 37, 26, 2690120}}, true, {{2017, 11, 30}, {0, 0, 0, 0}}, 1]]}}
</code>```

but processing the dates with my code below throws this exception:

```<code>iex(46)> DB.get(DB.Users, "select * from users where user_id = 1")
** (ArgumentError) cannot convert {{2017, 11, 30}, {18, 37, 26}} to naive datetime, reason: :invalid_time
    (elixir) lib/calendar/naive_datetime.ex:549: NaiveDateTime.from_erl!/2
    (rmas) lib/db.ex:34: DB.to_date/1
    (elixir) lib/enum.ex:1270: Enum."-map/2-lists^map/1-0-"/2
    (elixir) lib/enum.ex:1270: Enum."-map/2-lists^map/1-0-"/2
    (rmas) lib/db.ex:26: anonymous fn/3 in DB._objects/3
    (elixir) lib/enum.ex:1270: Enum."-map/2-lists^map/1-0-"/2
    (rmas) lib/db.ex:17: DB.get/3
</code>```

The source data-value is: {{2017, 11, 30}, {18, 37, 26, 2690120}}

答:
A datetime2(7) field stores with a precision of one-tenth of a microsecond. A NaiveDateTime only supports a precision of microseconds so you can divide the value by 10 to get the microseconds and use that:

```<code>defp to_date({{year, month, day}, {hour, min, sec, seven}}),
  do: NaiveDateTime.from_erl!({{year, month, day}, {hour, min, sec}}, {div(seven, 10), 6}) |> NaiveDateTime.to_string()
</code>```

We divide using div instead of / so that the result is an integer and not a float.

Body:
I have this function in my code:

  defp to_date({year, month, day}), do: NaiveDateTime.from_erl!({{year, month, day}, {0, 0, 0}}, {0, 6}) |> NaiveDateTime.to_string()
  defp to_date({{year, month, day}, {hour, min, sec, msec}}) when msec < 1000000,
    do: NaiveDateTime.from_erl!({{year, month, day}, {hour, min, sec}}, {msec, 6}) |> NaiveDateTime.to_string()

  defp to_date(x), do: x

How would you handle cases when msec > 6-digits.

Pulling data from a SQLServer datetime2(7) with the Tds library works just fine:

iex(45)> r = Tds.Connection.query(:RMASDB, "select * from users where user_id = 1" , [])
{:ok,
 %Tds.Result{columns: ["user_id", "name", "email", "mobiles", "password", "roles", "active", "reset_required", "last_login", "has_picture", "last_modified", "last_modified_by"], command: nil, num_rows: 1,
  rows: [[1, "Charles Okwuagwu", "charleso@mydomain.com", "mobile1, mobile2", "/eNvuOyr5N6HxgYdz3fK7A==|QHx/sOa3Se0C3ZeLSNtT97SCsuWL11SJeLykms7faGY=", "Administrator", true, false,
    {{2017, 11, 30}, {18, 37, 26, 2690120}}, true, {{2017, 11, 30}, {0, 0, 0, 0}}, 1]]}}

but processing the dates with my code below throws this exception:

iex(46)> DB.get(DB.Users, "select * from users where user_id = 1")
** (ArgumentError) cannot convert {{2017, 11, 30}, {18, 37, 26}} to naive datetime, reason: :invalid_time
    (elixir) lib/calendar/naive_datetime.ex:549: NaiveDateTime.from_erl!/2
    (rmas) lib/db.ex:34: DB.to_date/1
    (elixir) lib/enum.ex:1270: Enum."-map/2-lists^map/1-0-"/2
    (elixir) lib/enum.ex:1270: Enum."-map/2-lists^map/1-0-"/2
    (rmas) lib/db.ex:26: anonymous fn/3 in DB._objects/3
    (elixir) lib/enum.ex:1270: Enum."-map/2-lists^map/1-0-"/2
    (rmas) lib/db.ex:17: DB.get/3

The source data-value is: {{2017, 11, 30}, {18, 37, 26, 2690120}}

Body:
A datetime2(7) field stores with a precision of one-tenth of a microsecond. A NaiveDateTime only supports a precision of microseconds so you can divide the value by 10 to get the microseconds and use that:

defp to_date({{year, month, day}, {hour, min, sec, seven}}),
  do: NaiveDateTime.from_erl!({{year, month, day}, {hour, min, sec}}, {div(seven, 10), 6}) |> NaiveDateTime.to_string()

We divide using div instead of / so that the result is an integer and not a float.


问:
Inner Join in laravel missing P
I needed to combine the two table product_price and trade_channels, when I use inner join,

the ID of product_price is remove.

Here is my code

```<code>DB::table('product_price')->where('product_id',$id)->where('action','customer_price')
         ->join('customers','product_price.action_id','=','customers.id')
         ->get();
</code>```

答:
A good practise is to select a column that you actually want to use no need of all columns.

Suppose in this case you require all column of product_price table and only customer id from customer_price table then you can do something like this:

```<code>DB::table('product_price')
->select(['product_price.*','customer_price.id AS customer_id'])
->where('product_price.product_id',$id)
->where('product_price.action','customer_price')
->join('customers','product_price.action_id','=','customers.id')
->get();
</code>```

You can select any column but it's good to take alias of join table column in this case it is customer_price so it's not getting confusion if both table has same name column.

Good Luck

Title: Inner Join in laravel missing P

Body:
I needed to combine the two table product_price and trade_channels, when I use inner join,

the ID of product_price is remove.

Here is my code

DB::table('product_price')->where('product_id',$id)->where('action','customer_price')
         ->join('customers','product_price.action_id','=','customers.id')
         ->get();

Body:
A good practise is to select a column that you actually want to use no need of all columns.

Suppose in this case you require all column of product_price table and only customer id from customer_price table then you can do something like this:

DB::table('product_price')
->select(['product_price.*','customer_price.id AS customer_id'])
->where('product_price.product_id',$id)
->where('product_price.action','customer_price')
->join('customers','product_price.action_id','=','customers.id')
->get();

You can select any column but it's good to take alias of join table column in this case it is customer_price so it's not getting confusion if both table has same name column.

Good Luck


问:
Deploying Laravel on a shared hosting sub-directory
I'm trying to deploy laravel 5.5 inside a WordPress sub-directory on a shared hosting. I tried too many suggestions from google but I still can't make it work. It always returns a 404 error. WordPress is installed inside /public_html
and I need to install Laravel on /public_html/my-laravel-app
Here's what my .htaccess files look:

/public_html/.htaccess

```<code># BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

# END WordPress

# protect wpconfig.php
<files wp-config.php>
order allow,deny
deny from all
</files>

# protect the htaccess file
<files .htaccess>
order allow,deny
deny from all
</files>

# disable the server signature
ServerSignature Off
</code>```

/public_html/my-laravel-app/.htaccess

```<code><IfModule mod_rewrite.c>
   RewriteEngine On
   RewriteBase /my-laravel-app/
   RewriteCond %{REQUEST_FILENAME} !-f
   RewriteCond %{REQUEST_FILENAME} !-d
   RewriteRule . /my-laravel-app/public/index.php [L]
</IfModule>
</code>```

/public_html/my-laravel-app/public/.htaccess

```<code><IfModule mod_rewrite.c>
    <IfModule mod_negotiation.c>
        Options -MultiViews
    </IfModule>

    RewriteEngine On

    # Redirect Trailing Slashes If Not A Folder...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)/$ /$1 [L,R=301]

    # Handle Front Controller...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [L]

    # Handle Authorization Header
    RewriteCond %{HTTP:Authorization} .
    RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
</IfModule>
</code>```

/public_html/my-laravel-app/public/index.php (some part of index.php)

```<code>require __DIR__.'/../bootstrap/autoload.php';

/*
|--------------------------------------------------------------------------
| Turn On The Lights
|--------------------------------------------------------------------------
|
| We need to illuminate PHP development, so let us turn on the lights.
| This bootstraps the framework and gets it ready for use, then it
| will load up this application so that we can run it and send
| the responses back to the browser and delight our users.
|
*/

$app = require_once __DIR__.'/../bootstrap/app.php';
</code>```

答:
I forgot to update this question, but I already solved this problem.
It's not actually about WordPress' .htaccess, I get rid of my custom .htaccess settings.
What I did was, create a new folder on public_html/laravel-app then inside my laravel-app,
this is where I cloned the repo, so it became, public_html/laravel-app/my-app
then, I copied the files(except the folders) inside my-app/public directory and moved it to laravel-app/.

```<code>$ cd /public_html/laravel-app
$ cp -a my-app/public/*.* ./
</code>```

Then I created a symbolic link for the directories inside my-app/public by running

```<code>$ ln -sf my-app/public/*/ ./
</code>```

And lastly, I modified the public_html/laravel-app/index.php
on line 22 and line 36,

```<code>require __DIR__.'/my-app/bootstrap/autoload.php';
$app = require_once __DIR__.'/my-app/bootstrap/app.php';
</code>```

Then it's done.

Body:
I'm trying to deploy laravel 5.5 inside a WordPress sub-directory on a shared hosting. I tried too many suggestions from google but I still can't make it work. It always returns a 404 error. WordPress is installed inside /public_html
and I need to install Laravel on /public_html/my-laravel-app
Here's what my .htaccess files look:

/public_html/.htaccess

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

# END WordPress

# protect wpconfig.php
<files wp-config.php>
order allow,deny
deny from all
</files>

# protect the htaccess file
<files .htaccess>
order allow,deny
deny from all
</files>

# disable the server signature
ServerSignature Off

/public_html/my-laravel-app/.htaccess

<IfModule mod_rewrite.c>
   RewriteEngine On
   RewriteBase /my-laravel-app/
   RewriteCond %{REQUEST_FILENAME} !-f
   RewriteCond %{REQUEST_FILENAME} !-d
   RewriteRule . /my-laravel-app/public/index.php [L]
</IfModule>

/public_html/my-laravel-app/public/.htaccess

<IfModule mod_rewrite.c>
    <IfModule mod_negotiation.c>
        Options -MultiViews
    </IfModule>

    RewriteEngine On

    # Redirect Trailing Slashes If Not A Folder...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)/$ /$1 [L,R=301]

    # Handle Front Controller...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [L]

    # Handle Authorization Header
    RewriteCond %{HTTP:Authorization} .
    RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
</IfModule>

/public_html/my-laravel-app/public/index.php (some part of index.php)

require __DIR__.'/../bootstrap/autoload.php';

/*
|--------------------------------------------------------------------------
| Turn On The Lights
|--------------------------------------------------------------------------
|
| We need to illuminate PHP development, so let us turn on the lights.
| This bootstraps the framework and gets it ready for use, then it
| will load up this application so that we can run it and send
| the responses back to the browser and delight our users.
|
*/

$app = require_once __DIR__.'/../bootstrap/app.php';

Body:
I forgot to update this question, but I already solved this problem.
It's not actually about WordPress' .htaccess, I get rid of my custom .htaccess settings.
What I did was, create a new folder on public_html/laravel-app then inside my laravel-app,
this is where I cloned the repo, so it became, public_html/laravel-app/my-app
then, I copied the files(except the folders) inside my-app/public directory and moved it to laravel-app/.

$ cd /public_html/laravel-app
$ cp -a my-app/public/*.* ./

Then I created a symbolic link for the directories inside my-app/public by running

$ ln -sf my-app/public/*/ ./

And lastly, I modified the public_html/laravel-app/index.php
on line 22 and line 36,

require __DIR__.'/my-app/bootstrap/autoload.php';
$app = require_once __DIR__.'/my-app/bootstrap/app.php';

Then it's done.


问:
Should I consider study period as ordinal variable in multiple linear regression in r?
I have a response variable called per-capita income. It is associated with the predictor variable, study period. Study period is a factor with 3 levels, where the first period spanned between 2008-2009, the second spanned between 2010-2012 and the third, 2013-2015.

I would like to perform a multiple linear regression in r with these 2 variables and other variables (age and gender). In short, the formula is per-capita income ~ study period + age + gender.

I performed the regression in two ways:

Consider study period as nominal or non-ordered:

lm(PCI ~ factor(STUDY_PERIOD) + AGE + GENDER, data = df)

```<code># Coefficients:
# (Intercept)  factor(STUDY_PERIOD)2  factor(STUDY_PERIOD)3   AGE      GENDERM
# 356.07       63.15                 112.71                  -1.44     -43.73
</code>```

Consider study period as ordinal or ordered:

```<code>df$STUDY_PERIOD <- ordered(df$STUDY_PERIOD, levels =c(1, 2, 3))
lm(PCI ~ STUDY_PERIOD + AGE + GENDER, data = df)
</code>```

```<code>    # Coefficients:
    # (Intercept)  STUDY_PERIOD.L  STUDY_PERIOD.Q  AGE    GENDERM
    # 414.690      79.697          -5.551          -1.440   -43.728
</code>```

Both give different coefficients for the study periods.

My questions:

What should I consider STUDY_PERIOD as?

How do I interpret the coefficients in both cases?

Thank you!

答:
It depends on the question you are asking.  As a factor, you are asking for k-1 slope estimates, where k = number of categories.  The first estimate contrasts period 1 versus period 2 while the second contrasts period 1 versus period 3.

As a linear variable (not ordinal) you are asking "as time period increases does the PCI increase/decrease.  The slope here is the per period increase.

The linear is easiest to interpret, but may mask what the actual effects are.  Here, though, it may be linear since the estimate for factor(STUDY_PERIOD)3 is roughly twice the estimate for factor(STUDY_PERIOD)2.  A way to check is to just look at a plot.

Body:
I have a response variable called per-capita income. It is associated with the predictor variable, study period. Study period is a factor with 3 levels, where the first period spanned between 2008-2009, the second spanned between 2010-2012 and the third, 2013-2015.

I would like to perform a multiple linear regression in r with these 2 variables and other variables (age and gender). In short, the formula is per-capita income ~ study period + age + gender.

I performed the regression in two ways:

Consider study period as nominal or non-ordered:

lm(PCI ~ factor(STUDY_PERIOD) + AGE + GENDER, data = df)

# Coefficients:
# (Intercept)  factor(STUDY_PERIOD)2  factor(STUDY_PERIOD)3   AGE      GENDERM
# 356.07       63.15                 112.71                  -1.44     -43.73

Consider study period as ordinal or ordered:

df$STUDY_PERIOD <- ordered(df$STUDY_PERIOD, levels =c(1, 2, 3))
lm(PCI ~ STUDY_PERIOD + AGE + GENDER, data = df)

    # Coefficients:
    # (Intercept)  STUDY_PERIOD.L  STUDY_PERIOD.Q  AGE    GENDERM
    # 414.690      79.697          -5.551          -1.440   -43.728

Both give different coefficients for the study periods.

My questions:

What should I consider STUDY_PERIOD as?

How do I interpret the coefficients in both cases?

Thank you!


问:
java.lang.NoSuchMethodError on Activity.showDialog (int, Bundle)?
Here is what LogCat says:

```<code>01-21 17:20:06.057: ERROR/AndroidRuntime(27463): java.lang.NoSuchMethodError: com.mohit.geo2do.activities.TasksList.showDialog
01-21 17:20:06.057: ERROR/AndroidRuntime(27463):     at com.mohit.geo2do.activities.TasksList.onContextItemSelected(TasksList.java:190)
01-21 17:20:06.057: ERROR/AndroidRuntime(27463):     at android.app.Activity.onMenuItemSelected(Activity.java:2183)
01-21 17:20:06.057: ERROR/AndroidRuntime(27463):     at com.android.internal.policy.impl.PhoneWindow$ContextMenuCallback.onMenuItemSelected(PhoneWindow.java:2785)
01-21 17:20:06.057: ERROR/AndroidRuntime(27463):     at com.android.internal.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:140)
01-21 17:20:06.057: ERROR/AndroidRuntime(27463):     at com.android.internal.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:855)
01-21 17:20:06.057: ERROR/AndroidRuntime(27463):     at com.android.internal.view.menu.MenuDialogHelper.onClick(MenuDialogHelper.java:129)
01-21 17:20:06.057: ERROR/AndroidRuntime(27463):     at com.android.internal.app.AlertController$AlertParams$3.onItemClick(AlertController.java:898)
01-21 17:20:06.057: ERROR/AndroidRuntime(27463):     at android.widget.AdapterView.performItemClick(AdapterView.java:301)
01-21 17:20:06.057: ERROR/AndroidRuntime(27463):     at android.widget.ListView.performItemClick(ListView.java:3626)
01-21 17:20:06.057: ERROR/AndroidRuntime(27463):     at android.widget.AbsListView$PerformClick.run(AbsListView.java:3600)
01-21 17:20:06.057: ERROR/AndroidRuntime(27463):     at android.os.Handler.handleCallback(Handler.java:587)
01-21 17:20:06.057: ERROR/AndroidRuntime(27463):     at android.os.Handler.dispatchMessage(Handler.java:92)
01-21 17:20:06.057: ERROR/AndroidRuntime(27463):     at android.os.Looper.loop(Looper.java:123)
01-21 17:20:06.057: ERROR/AndroidRuntime(27463):     at android.app.ActivityThread.main(ActivityThread.java:4363)
01-21 17:20:06.057: ERROR/AndroidRuntime(27463):     at java.lang.reflect.Method.invokeNative(Native Method)
01-21 17:20:06.057: ERROR/AndroidRuntime(27463):     at java.lang.reflect.Method.invoke(Method.java:521)
01-21 17:20:06.057: ERROR/AndroidRuntime(27463):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:862)
01-21 17:20:06.057: ERROR/AndroidRuntime(27463):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:620)
01-21 17:20:06.057: ERROR/AndroidRuntime(27463):     at dalvik.system.NativeStart.main(Native Method)
</code>```

I get an error at this phrase:

```<code>Bundle args = new Bundle();
args.putLong("id", ...);           //Some arbitrary value
showDialog(DELETE_DIALOG, args);
</code>```

I have an onPrepareDialog method:

```<code>@Override
protected void onPrepareDialog(int id, Dialog dialog, Bundle args) {
    switch (id) {
    case DELETE_DIALOG:
        AlertDialog log = (AlertDialog) dialog;
        final Bundle bundle = args;
        log.setButton(DialogInterface.BUTTON_POSITIVE, "Ok", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                long id = bundle.getLong("id");

                getContentResolver().delete(Tasks.CONTENT_URI, Tasks._ID + "=" + id, null);
                adapter.notifyDataSetChanged();
            }
        });
        break;
    default:
        break;
    }
}
</code>```

What could be the problem?

答: Generally that means the class you compiled against and the class you're running against are different versions. The method you are calling was accessible to your compiler but is not available to the JVM at runtime.</p>

Body:
Here is what LogCat says:

01-21 17:20:06.057: ERROR/AndroidRuntime(27463): java.lang.NoSuchMethodError: com.mohit.geo2do.activities.TasksList.showDialog
01-21 17:20:06.057: ERROR/AndroidRuntime(27463):     at com.mohit.geo2do.activities.TasksList.onContextItemSelected(TasksList.java:190)
01-21 17:20:06.057: ERROR/AndroidRuntime(27463):     at android.app.Activity.onMenuItemSelected(Activity.java:2183)
01-21 17:20:06.057: ERROR/AndroidRuntime(27463):     at com.android.internal.policy.impl.PhoneWindow$ContextMenuCallback.onMenuItemSelected(PhoneWindow.java:2785)
01-21 17:20:06.057: ERROR/AndroidRuntime(27463):     at com.android.internal.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:140)
01-21 17:20:06.057: ERROR/AndroidRuntime(27463):     at com.android.internal.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:855)
01-21 17:20:06.057: ERROR/AndroidRuntime(27463):     at com.android.internal.view.menu.MenuDialogHelper.onClick(MenuDialogHelper.java:129)
01-21 17:20:06.057: ERROR/AndroidRuntime(27463):     at com.android.internal.app.AlertController$AlertParams$3.onItemClick(AlertController.java:898)
01-21 17:20:06.057: ERROR/AndroidRuntime(27463):     at android.widget.AdapterView.performItemClick(AdapterView.java:301)
01-21 17:20:06.057: ERROR/AndroidRuntime(27463):     at android.widget.ListView.performItemClick(ListView.java:3626)
01-21 17:20:06.057: ERROR/AndroidRuntime(27463):     at android.widget.AbsListView$PerformClick.run(AbsListView.java:3600)
01-21 17:20:06.057: ERROR/AndroidRuntime(27463):     at android.os.Handler.handleCallback(Handler.java:587)
01-21 17:20:06.057: ERROR/AndroidRuntime(27463):     at android.os.Handler.dispatchMessage(Handler.java:92)
01-21 17:20:06.057: ERROR/AndroidRuntime(27463):     at android.os.Looper.loop(Looper.java:123)
01-21 17:20:06.057: ERROR/AndroidRuntime(27463):     at android.app.ActivityThread.main(ActivityThread.java:4363)
01-21 17:20:06.057: ERROR/AndroidRuntime(27463):     at java.lang.reflect.Method.invokeNative(Native Method)
01-21 17:20:06.057: ERROR/AndroidRuntime(27463):     at java.lang.reflect.Method.invoke(Method.java:521)
01-21 17:20:06.057: ERROR/AndroidRuntime(27463):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:862)
01-21 17:20:06.057: ERROR/AndroidRuntime(27463):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:620)
01-21 17:20:06.057: ERROR/AndroidRuntime(27463):     at dalvik.system.NativeStart.main(Native Method)

I get an error at this phrase:

Bundle args = new Bundle();
args.putLong("id", ...);           //Some arbitrary value
showDialog(DELETE_DIALOG, args);

I have an onPrepareDialog method:

@Override
protected void onPrepareDialog(int id, Dialog dialog, Bundle args) {
    switch (id) {
    case DELETE_DIALOG:
        AlertDialog log = (AlertDialog) dialog;
        final Bundle bundle = args;
        log.setButton(DialogInterface.BUTTON_POSITIVE, "Ok", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                long id = bundle.getLong("id");

                getContentResolver().delete(Tasks.CONTENT_URI, Tasks._ID + "=" + id, null);
                adapter.notifyDataSetChanged();
            }
        });
        break;
    default:
        break;
    }
}

What could be the problem?


问:
Run the QtQuick application
I create a project on QtQuick in QT Creator 4.3.1 without using the ui form.
Here's the code main.qml:

```<code>    import QtQuick 2.6
    import QtQuick.Window 2.2

    Window {
        visible: true
        width: 640
        height: 480
        title: qsTr("Hello World")

        MouseArea {
            anchors.fill: parent
            onClicked: {
                console.log(qsTr('Clicked on background. Text: "' + textEdit.text + '"'))
            }
        }

        TextEdit {
            id: textEdit
            text: qsTr("Enter some text...")
            verticalAlignment: Text.AlignVCenter
            anchors.top: parent.top
            anchors.horizontalCenter: parent.horizontalCenter
            anchors.topMargin: 20
            Rectangle {
                anchors.fill: parent
                anchors.margins: -10
                color: "transparent"
                border.width: 1
            }
        }
    }
</code>```

The program runs and works.
Now I want to get rid of Window and replace it with Rectangle:

```<code>import QtQuick 2.6

Rectangle {
    id: root
    width: 200; height: 200;
    color: "#ffffff"
}
</code>```

But when the program starts, nothing happens, the form does not open
What am I doing wrong?

main.cpp code. code in the same in both cases:

```<code>#include <QGuiApplication>
#include <QQmlApplicationEngine>

int main(int argc, char *argv[])
{
    QGuiApplication app(argc, argv);

    QQmlApplicationEngine engine;
    engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
    if (engine.rootObjects().isEmpty())
        return -1;

    return app.exec();
}
</code>```

答:
In a Qt application you must have at least one window that is the top-level, that is, the window where other components are placed.

When you create your project, you should get the default main.cpp:

main.cpp

```<code>#include <QGuiApplication>
#include <QQmlApplicationEngine>

int main(int argc, char *argv[])
{
    QGuiApplication app(argc, argv);

    QQmlApplicationEngine engine;
    engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
    if (engine.rootObjects().isEmpty())
        return -1;

    return app.exec();
}
</code>```

main.qml

```<code>Window {
    visible: true
    width: 640
    height: 480
    title: qsTr("Hello World")
}
</code>```

So let's analyze the elements and use the documentation for it:

QQmlApplicationEngine:

QQmlApplicationEngine provides a convenient way to load an application from a single QML file.

[...]

Unlike QQuickView, QQmlApplicationEngine does not automatically create a root window. If you are using visual items from Qt Quick, you will need to place them inside of a Window.

That is, QQmlApplicationEngine does not create a top-level, so if we want the window to be shown you must use another element, and as recommended, an option is to use Window{}

In your second test you are using an item, e.g. Rectangle, and this is only a component and is not able to create a top-level, so for that it is advisable to use QQuickView:

The QQuickView class provides a window for displaying a Qt Quick user interface.

[...]

So if you want to show the Rectangle you should use the following in your main.cpp:

main.cpp

```<code>#include <QGuiApplication>
#include <QQuickView>

int main(int argc, char *argv[])
{
    QGuiApplication app(argc, argv);

    QQuickView view;
    view.setSource(QUrl(QStringLiteral("qrc:/main.qml")));
    view.setResizeMode(QQuickView::SizeRootObjectToView);
    view.show();

    return app.exec();
}
</code>```

main.qml

```<code>import QtQuick 2.6

Rectangle {
    id: root
    width: 200; height: 200;
    color: "#ffffff"
}
</code>```

Title: Run the QtQuick application

Body:
I create a project on QtQuick in QT Creator 4.3.1 without using the ui form.
Here's the code main.qml:

    import QtQuick 2.6
    import QtQuick.Window 2.2

    Window {
        visible: true
        width: 640
        height: 480
        title: qsTr("Hello World")

        MouseArea {
            anchors.fill: parent
            onClicked: {
                console.log(qsTr('Clicked on background. Text: "' + textEdit.text + '"'))
            }
        }

        TextEdit {
            id: textEdit
            text: qsTr("Enter some text...")
            verticalAlignment: Text.AlignVCenter
            anchors.top: parent.top
            anchors.horizontalCenter: parent.horizontalCenter
            anchors.topMargin: 20
            Rectangle {
                anchors.fill: parent
                anchors.margins: -10
                color: "transparent"
                border.width: 1
            }
        }
    }

The program runs and works.
Now I want to get rid of Window and replace it with Rectangle:

import QtQuick 2.6

Rectangle {
    id: root
    width: 200; height: 200;
    color: "#ffffff"
}

But when the program starts, nothing happens, the form does not open
What am I doing wrong?

main.cpp code. code in the same in both cases:

#include <QGuiApplication>
#include <QQmlApplicationEngine>

int main(int argc, char *argv[])
{
    QGuiApplication app(argc, argv);

    QQmlApplicationEngine engine;
    engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
    if (engine.rootObjects().isEmpty())
        return -1;

    return app.exec();
}

Body:
In a Qt application you must have at least one window that is the top-level, that is, the window where other components are placed.

When you create your project, you should get the default main.cpp:

main.cpp

#include <QGuiApplication>
#include <QQmlApplicationEngine>

int main(int argc, char *argv[])
{
    QGuiApplication app(argc, argv);

    QQmlApplicationEngine engine;
    engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
    if (engine.rootObjects().isEmpty())
        return -1;

    return app.exec();
}

main.qml

Window {
    visible: true
    width: 640
    height: 480
    title: qsTr("Hello World")
}

So let's analyze the elements and use the documentation for it:

QQmlApplicationEngine:

QQmlApplicationEngine provides a convenient way to load an application from a single QML file.

[...]

Unlike QQuickView, QQmlApplicationEngine does not automatically create a root window. If you are using visual items from Qt Quick, you will need to place them inside of a Window.

That is, QQmlApplicationEngine does not create a top-level, so if we want the window to be shown you must use another element, and as recommended, an option is to use Window{}

In your second test you are using an item, e.g. Rectangle, and this is only a component and is not able to create a top-level, so for that it is advisable to use QQuickView:

The QQuickView class provides a window for displaying a Qt Quick user interface.

[...]

So if you want to show the Rectangle you should use the following in your main.cpp:

main.cpp

#include <QGuiApplication>
#include <QQuickView>

int main(int argc, char *argv[])
{
    QGuiApplication app(argc, argv);

    QQuickView view;
    view.setSource(QUrl(QStringLiteral("qrc:/main.qml")));
    view.setResizeMode(QQuickView::SizeRootObjectToView);
    view.show();

    return app.exec();
}

main.qml

import QtQuick 2.6

Rectangle {
    id: root
    width: 200; height: 200;
    color: "#ffffff"
}


问:
How to get form to save data and show on page later without erasing it
I've created a form, and figured out how to put the data where I am wanting it to show up. I want to know how to make it stay, when the page or app is refreshed/exited/etc.

```<code><article>

<div align="center">    <script language="JavaScript">
function showInput() {
    document.getElementById('display').innerHTML =
                document.getElementById("user_input").value;
}
</script>
    <form>
<label><b>Enter Your Amount:</b></label>
<input type="text" name="message" id="user_input">
</form><br />

<input class="button" type="submit" onclick="showInput();"><br/>
<p><span id='display'></span></p></div>

  </article>
</code>```

So far I have this and it's working fine, except for saving the response. The project I'm working on is a budget tracker for a family member, so I want the form data to be saved and not erased every time they refresh or exit.

This is probably  a pretty noob question, but I can't seem to find an answer that will work for me.

答:
Sounds like a job for local storage. Local storage is just how it sounds local to the browser you are using you cannot access this data from anywhere but the computer/browser its stored in.

```<code>//this checks to see if local storage is available

if (typeof(Storage) !== "undefined") {

} else {

}

//grabbing your data i assume "user_input" and set it to a variable called "storage_var"

var storage_var = document.getElementById("user_input").value;

// For storing said data "to_the_ether"  variable name and can be w/e u want

localStorage.setItem("to_the_ether", storage_var);

// to get the value and pass it back into the display (im assuming a div?)

document.getElementById("display").innerHTML = localStorage.getItem("to_the_ether");
</code>```

Hope that helps. If you need more accessible storage you need a DB,

Body:
I've created a form, and figured out how to put the data where I am wanting it to show up. I want to know how to make it stay, when the page or app is refreshed/exited/etc.

    <form>
Enter Your Amount:
<input type="text" name="message" id="user_input">
</form>

<input class="button" type="submit" onclick="showInput();">

So far I have this and it's working fine, except for saving the response. The project I'm working on is a budget tracker for a family member, so I want the form data to be saved and not erased every time they refresh or exit.

This is probably  a pretty noob question, but I can't seem to find an answer that will work for me.

Body:
Sounds like a job for local storage. Local storage is just how it sounds local to the browser you are using you cannot access this data from anywhere but the computer/browser its stored in.

//this checks to see if local storage is available

if (typeof(Storage) !== "undefined") {

} else {

}

//grabbing your data i assume "user_input" and set it to a variable called "storage_var"

var storage_var = document.getElementById("user_input").value;

// For storing said data "to_the_ether"  variable name and can be w/e u want

localStorage.setItem("to_the_ether", storage_var);

// to get the value and pass it back into the display (im assuming a div?)

document.getElementById("display").innerHTML = localStorage.getItem("to_the_ether");

Hope that helps. If you need more accessible storage you need a DB,


问:
In need to either convert Spring's default HAL format to JSON API, or make Ember Data accept HAL json format
My Ember.js front-end application is to consume REST API created in Spring (Boot). The problem is:
- Spring returns json response in HAL format
- Ember Data expect the response to be fully compliant with JSON API specs

So far I have found that there are at least two "adapters" for each side.

This one is supposed to convince Ember Data to use the Spring's response as it is:
ember-data-hal-9000

This one makes Spring's response compliant with JSON API specs:
Katharsis - HATEOAS for Java based on JSON API standard

I've read that both have its own problems but has anyone successfully employed either of them? Ideally both of them, so a comparison can be made?

答:
I worked for a client for a while who had gone with Katharsis. The backend developers disliked Katharsis (as it had made some non-spec compliant "decisions" that had to be worked around), but part of that may also have been due to a fairly messy backend data model. </p>

<p>It worked great on the Ember side of things </p>

Body:
I worked for a client for a while who had gone with Katharsis. The backend developers disliked Katharsis (as it had made some non-spec compliant "decisions" that had to be worked around), but part of that may also have been due to a fairly messy backend data model.

It worked great on the Ember side of things


答:
Seems like HTML/JS doesn't allow a function named click to be set to onclick. Please change

```<code>function click(){
</code>```

to

```<code>function clickk(){
</code>```

and

```<code><img id="pic" onclick="click()"
</code>```

to

```<code><img id="pic" onclick="clickk()"
</code>```

Also, move your var butt = true; outside the function.

Full example below:

<!DOCTYPE html>

  <title>ch6</title>

List

audio note

Enter note name

  <input type="text">

```

Title: Why does this if true condition in js doesn't work

Body:
Seems like HTML/JS doesn't allow a function named click to be set to onclick. Please change

function click(){

to

function clickk(){

and

<img id="pic" onclick="click()"

to

<img id="pic" onclick="clickk()"

Also, move your var butt = true; outside the function.

Full example below:

<!DOCTYPE html>
<html>

<head>
  <title>ch6</title>
</head>

<body>
  <h1>List</h1>
  <h2>audio note</h2>
  <p>Enter note name</p>
  <input type="text">
  <br>
  <img id="pic" onclick="clickk()" src="http://www.clker.com/cliparts/d/b/c/f/13652249372108434179Record%20Button%20Microphone.svg.hi.png" alt="record" style="width:50px;height:60px;">
  <script type="text/javascript">
    var butt = true;

    function clickk() {

      if (butt === true) {
        document.getElementById("pic").src = "https://www.shareicon.net/download/2017/02/07/878546_media_512x512.png";
        butt = false;

      } else {
        document.getElementById("pic").src = "http://www.clker.com/cliparts/d/b/c/f/13652249372108434179Record%20Button%20Microphone.svg.hi.png";
        butt = true;
      }
    }
  </script>

</body>

</html>


问:
Moving records from one collection to another PyMongo
What is the proper way of moving a number of records from one collection to another. I have come across several other SO posts such as this which deal with achieve the same goal but none have a python implementation.

```<code>#Taking a number of records from one database and returning the cursor
cursor_excess_new = db.test_collection_new.find().sort([("_id", 1)]).limit(excess_num)

# db.test.insert_many(doc for doc in cursor_excess_new).inserted_ids

# Iterating cursor and Trying to write to another database
# for doc in cursor_excess_new:
#     db.test_collection_old.insert_one(doc)
result = db.test_collection_old.bulk_write([
    for doc in cursor_excess_new:
        InsertMany(doc for each doc in cur)
        pprint(doc)
])
</code>```

If I use insert_many, I get the following error: pymongo.errors.OperationFailure: Writes to config servers must have batch size of 1, found 10

bulk_write is giving me a syntax error at the start of for loop.

What is the best practice and correct way of transferring records from one collection to another in pymongo so that it is atomic?

答:
Collection.bulk_write accepts as argument an iterable of query operations.

pymongo has pymongo.operations.InsertOne operation not <s>InsertMany</s>.

For your situation, you can build a list of InsertOne operations for each document in the source collection. Then do a bulk_write on the destination using the built-up list of operations.

```<code>from pymongo import InsertOne
...
cursor_excess_new = (
    db.test_collection_new
      .find()
      .sort([("_id", 1)])
      .limit(excess_num)
)

queries = [InsertOne(doc) for doc in cursor_excess_new]
db.test_collection_old.bulk_write(queries)
</code>```

Body:
What is the proper way of moving a number of records from one collection to another. I have come across several other SO posts such as this which deal with achieve the same goal but none have a python implementation.

#Taking a number of records from one database and returning the cursor
cursor_excess_new = db.test_collection_new.find().sort([("_id", 1)]).limit(excess_num)

# db.test.insert_many(doc for doc in cursor_excess_new).inserted_ids

# Iterating cursor and Trying to write to another database
# for doc in cursor_excess_new:
#     db.test_collection_old.insert_one(doc)
result = db.test_collection_old.bulk_write([
    for doc in cursor_excess_new:
        InsertMany(doc for each doc in cur)
        pprint(doc)
])

If I use insert_many, I get the following error: pymongo.errors.OperationFailure: Writes to config servers must have batch size of 1, found 10

bulk_write is giving me a syntax error at the start of for loop.

What is the best practice and correct way of transferring records from one collection to another in pymongo so that it is atomic?

Body:
Collection.bulk_write accepts as argument an iterable of query operations.

pymongo has pymongo.operations.InsertOne operation not <s>InsertMany</s>.

For your situation, you can build a list of InsertOne operations for each document in the source collection. Then do a bulk_write on the destination using the built-up list of operations.

from pymongo import InsertOne
...
cursor_excess_new = (
    db.test_collection_new
      .find()
      .sort([("_id", 1)])
      .limit(excess_num)
)

queries = [InsertOne(doc) for doc in cursor_excess_new]
db.test_collection_old.bulk_write(queries)


问:
Laravel 5.5: Route not catching/missing single parameter
It appears the parameter is not passing, but after various edits no luck, and no way to strip it down anymore than this.

Error:

```<code>Missing required parameters for [Route: request.new-request]
[URI: housing-request/{unit}].
(View: /vhosts/web.local/resources/views/requests/unit-1.blade.php)
</code>```

Link/URL:

```<code><a href="{{ route('request.new-request', ['unit' => 'single']) }}">
http://web.local/housing-request/single
</code>```

Route:

```<code>Route::get('/housing-request/{unit}', 'RequestsController@showHousingUnit')->name('request.new-request');
</code>```

Controller:

```<code>  public function showHousingUnit($unit)
  {

      if($unit == "single"){

         return view('requests.unit-1');

      } else if($unit == "double") {

        return view('requests.unit-2');

     }

  }
</code>```

答:
Just pass like this.</p>

```<code><a href="{{ route('request.new-request','single') }}">
http://web.local/housing-request/single </a>
</code>```

Body:
It appears the parameter is not passing, but after various edits no luck, and no way to strip it down anymore than this.

Error:

Missing required parameters for [Route: request.new-request]
[URI: housing-request/{unit}].
(View: /vhosts/web.local/resources/views/requests/unit-1.blade.php)

Link/URL:

 'single']) }}">
http://web.local/housing-request/single

Route:

Route::get('/housing-request/{unit}', 'RequestsController@showHousingUnit')->name('request.new-request');

Controller:

  public function showHousingUnit($unit)
  {

      if($unit == "single"){

         return view('requests.unit-1');

      } else if($unit == "double") {

        return view('requests.unit-2');

     }

  }

Body:
Just pass like this.

<a href="{{ route('request.new-request','single') }}">
http://web.local/housing-request/single </a>