问:
KDB - Compare value to value x rows back (deltas but going back x rows)
I have a table with Instrument, Time, Price

```<code>Instrument   Time                            Price
Stock x      2019.05.17D10:01:00.000000000   1.2
Stock x      2019.05.17D10:02:00.000000000   1.4
Stock x      2019.05.17D10:03:00.000000000   1.3
Stock x      2019.05.17D10:04:00.000000000   1.2
Stock x      2019.05.17D10:05:00.000000000   1.4
Stock x      2019.05.17D10:06:00.000000000   1.6
Stock x      2019.05.17D10:07:00.000000000   2.3
Stock x      2019.05.17D10:08:00.000000000   2.4
Stock x      2019.05.17D10:09:00.000000000   2.2
Stock x      2019.05.17D10:10:00.000000000   2.5
</code>```

Then i want to compare the deltas price development over a running window, going x minutes back.

If i do something like

```<code>     newdata:({0,1_deltas x}(close))%(close) by Instrument from Table
</code>```

I get the comparison going 1 row back. (1.2/1.4 // 1.4/1.3 // 1.3/1.2)

A:
I would like to do the deltas - but going back several rows.
Meaning with x=5 rows 1.2/1.6 // 1.4/2.3 // etc..

B:
If I lack minute data at some point - Deltas will not take into account the minutes difference (and price development would not be as easily comparable) - So i would like to know, how i can make a solution, that is not only comparing with x rows prior, but also specificly focused on the time difference, when going the comparison in hindsight.

答:
If you want to purely base the look back on x rows, then you can use xprev.

```<code>tab:([]sym:10#`MSFT;time:(2019.05.01D10:00:00.000000+/:00:01+til 10);price:(1.2;1.4;1.3;1.2;1.4;1.6;2.3;2.4;2.2;2.5))

//Can adjust the row lookback value
update diff:(lookback-price) from update lookback:{y xprev x}[;5] price by sym from tab
</code>```

This should also account for Scenario B, as it will return a null which can be discarded from any price development calculations. However, if your data wasn't bucketed into 1-minute slots and you wanted to do a look back on time you will need to create some kind of window-join, a good example can be found here Rolling window in multi groups

Body:
I have a table with Instrument, Time, Price

Instrument   Time                            Price
Stock x      2019.05.17D10:01:00.000000000   1.2
Stock x      2019.05.17D10:02:00.000000000   1.4
Stock x      2019.05.17D10:03:00.000000000   1.3
Stock x      2019.05.17D10:04:00.000000000   1.2
Stock x      2019.05.17D10:05:00.000000000   1.4
Stock x      2019.05.17D10:06:00.000000000   1.6
Stock x      2019.05.17D10:07:00.000000000   2.3
Stock x      2019.05.17D10:08:00.000000000   2.4
Stock x      2019.05.17D10:09:00.000000000   2.2
Stock x      2019.05.17D10:10:00.000000000   2.5

Then i want to compare the deltas price development over a running window, going x minutes back.

If i do something like

     newdata:({0,1_deltas x}(close))%(close) by Instrument from Table

I get the comparison going 1 row back. (1.2/1.4 // 1.4/1.3 // 1.3/1.2)

A:
I would like to do the deltas - but going back several rows.
Meaning with x=5 rows 1.2/1.6 // 1.4/2.3 // etc..

B:
If I lack minute data at some point - Deltas will not take into account the minutes difference (and price development would not be as easily comparable) - So i would like to know, how i can make a solution, that is not only comparing with x rows prior, but also specificly focused on the time difference, when going the comparison in hindsight.

Body:
If you want to purely base the look back on x rows, then you can use xprev.

tab:([]sym:10#`MSFT;time:(2019.05.01D10:00:00.000000+/:00:01+til 10);price:(1.2;1.4;1.3;1.2;1.4;1.6;2.3;2.4;2.2;2.5))

//Can adjust the row lookback value
update diff:(lookback-price) from update lookback:{y xprev x}[;5] price by sym from tab

This should also account for Scenario B, as it will return a null which can be discarded from any price development calculations. However, if your data wasn't bucketed into 1-minute slots and you wanted to do a look back on time you will need to create some kind of window-join, a good example can be found here Rolling window in multi groups


来源: stackexchange

问:
How to make a navigation drawer outside of the Appbar?
I am trying to make a container which contains a navigation drawer and a search box. I don't want to use an Appbar. I achieved the search box, but I cannot make a navigation drawer without an Appbar. I want it to look like the google maps app.

I have tried using Row(), Scaffold(), Align(), etc. but I haven't been a able to achieve it.

答: Just use a Scaffold, add a Drawer and open it programmatically using ScaffoldState.openDrawer(). You don't have to add an AppBar if you don't want to.</p>

ContentLicense: CC BY-SA 4.0


问:
Should I declare a double array with the GPU block number on the inner or outer dimension?
Should I declare a double array with the GPU block number on the inner or outer dimension?

E.g., should I do

```<code>int payload[LEN][BLOCKS];
</code>```

or

```<code>int payload[BLOCKS][LEN];
</code>```

where LEN is  a very large number.

I plan to have each block traverse the double array, holding the block dimension constant and iterating over the LEN dimension.

答:
Assuming you're going to access the data in a block-oriented manner, you want to do the latter.  This is presumably because when you load the first element of the "len" dimension, you've already paid the cost for missing in the cache for the subsequent 7ish elements.  In the first option, there's probably sharing of cache lines between GPU blocks, but the sharing is relatively limited and not as low level.

Indeed, the below code reports that the second option requires 0.481 seconds to execute, and the first option requires 0.979 seconds.  Arranging the data with the block on the outer dimension is about twice as performant.

```<code>#include <cuda_runtime_api.h>
#include <cuda.h>

#include <string>
#include <chrono>
#include <iostream>

#define BLOCKS 80
#define LEN (1 << 20)

void CheckCudaErrorAux (const char *file, unsigned line, const char *statement, cudaError_t err) {
    if (err == cudaSuccess)
        return;
    std::cerr << statement<<" returned " << cudaGetErrorString(err) << "("<<err<< ") at "<<file<<":"<<line << std::endl;
    exit (1);
}
#define CUDA_CHECK_RETURN(value) CheckCudaErrorAux(__FILE__,__LINE__, #value, value)

struct Data1 {
    int payload[LEN][BLOCKS];
};

struct Data2 {
    int payload[BLOCKS][LEN];
};

__global__ void f1(Data1 * data1) {
    int sum = 0;
    for (int i = 0; i < LEN; ++i) {
        sum += data1->payload[i][blockIdx.x];
    }
    printf("block %i has f1 sum %i\n", blockIdx.x, sum);
}

__global__ void f2(Data2 * data2) {
    int sum = 0;
    for (int i = 0; i < LEN; ++i) {
        sum += data2->payload[blockIdx.x][i];
    }
    printf("block %i has f2 sum %i\n", blockIdx.x, sum);
}

int main() {

    Data1 * data1 = (Data1 *) malloc(sizeof(Data1));
    Data2 * data2 = (Data2 *) malloc(sizeof(Data2));;

    for (int i = 0; i < LEN; ++i) {
        for (int b = 0; b < BLOCKS; ++b) {
            data1->payload[i][b] = i * b;
            data2->payload[b][i] = i * b;
        }
    }

    Data1 * data1_on_gpu;
    CUDA_CHECK_RETURN(cudaMalloc(&data1_on_gpu, sizeof(Data1)));
    Data2 * data2_on_gpu;
    cudaMalloc(&data2_on_gpu, sizeof(Data2));
    CUDA_CHECK_RETURN(cudaDeviceSynchronize());
    cudaMemcpy(data1_on_gpu, data1, sizeof(Data1), cudaMemcpyHostToDevice);
    cudaMemcpy(data2_on_gpu, data2, sizeof(Data1), cudaMemcpyHostToDevice);
    CUDA_CHECK_RETURN(cudaDeviceSynchronize());

    std::chrono::time_point<std::chrono::system_clock> t1 = std::chrono::system_clock::now();

    f1<<<80,1>>>(data1_on_gpu);
    CUDA_CHECK_RETURN(cudaDeviceSynchronize());
    std::chrono::time_point<std::chrono::system_clock> t2 = std::chrono::system_clock::now();

    f2<<<80,1>>>(data2_on_gpu);
    CUDA_CHECK_RETURN(cudaDeviceSynchronize());
    std::chrono::time_point<std::chrono::system_clock> t3 = std::chrono::system_clock::now();

    std::chrono::duration<double> duration_1_to_2 = t2 - t1;
    std::chrono::duration<double> duration_2_to_3 = t3 - t2;
    duration_1_to_2.count();

    printf("timer for 1st took %.3lf\n", duration_1_to_2.count());
    printf("timer for 2nd took %.3lf\n", duration_2_to_3.count());

}
</code>```

Body:
Should I declare a double array with the GPU block number on the inner or outer dimension?

E.g., should I do

int payload[LEN][BLOCKS];

or

int payload[BLOCKS][LEN];

where LEN is  a very large number.

I plan to have each block traverse the double array, holding the block dimension constant and iterating over the LEN dimension.

Body:
Assuming you're going to access the data in a block-oriented manner, you want to do the latter.  This is presumably because when you load the first element of the "len" dimension, you've already paid the cost for missing in the cache for the subsequent 7ish elements.  In the first option, there's probably sharing of cache lines between GPU blocks, but the sharing is relatively limited and not as low level.

Indeed, the below code reports that the second option requires 0.481 seconds to execute, and the first option requires 0.979 seconds.  Arranging the data with the block on the outer dimension is about twice as performant.

#include <cuda_runtime_api.h>
#include <cuda.h>

#include <string>
#include <chrono>
#include <iostream>

#define BLOCKS 80
#define LEN (1 << 20)

void CheckCudaErrorAux (const char *file, unsigned line, const char *statement, cudaError_t err) {
    if (err == cudaSuccess)
        return;
    std::cerr << statement<<" returned " << cudaGetErrorString(err) << "("<<err<< ") at "<<file<<":"<<line << std::endl;
    exit (1);
}
#define CUDA_CHECK_RETURN(value) CheckCudaErrorAux(__FILE__,__LINE__, #value, value)

struct Data1 {
    int payload[LEN][BLOCKS];
};

struct Data2 {
    int payload[BLOCKS][LEN];
};

__global__ void f1(Data1 * data1) {
    int sum = 0;
    for (int i = 0; i < LEN; ++i) {
        sum += data1->payload[i][blockIdx.x];
    }
    printf("block %i has f1 sum %i\n", blockIdx.x, sum);
}

__global__ void f2(Data2 * data2) {
    int sum = 0;
    for (int i = 0; i < LEN; ++i) {
        sum += data2->payload[blockIdx.x][i];
    }
    printf("block %i has f2 sum %i\n", blockIdx.x, sum);
}

int main() {

    Data1 * data1 = (Data1 *) malloc(sizeof(Data1));
    Data2 * data2 = (Data2 *) malloc(sizeof(Data2));;

    for (int i = 0; i < LEN; ++i) {
        for (int b = 0; b < BLOCKS; ++b) {
            data1->payload[i][b] = i * b;
            data2->payload[b][i] = i * b;
        }
    }

    Data1 * data1_on_gpu;
    CUDA_CHECK_RETURN(cudaMalloc(&data1_on_gpu, sizeof(Data1)));
    Data2 * data2_on_gpu;
    cudaMalloc(&data2_on_gpu, sizeof(Data2));
    CUDA_CHECK_RETURN(cudaDeviceSynchronize());
    cudaMemcpy(data1_on_gpu, data1, sizeof(Data1), cudaMemcpyHostToDevice);
    cudaMemcpy(data2_on_gpu, data2, sizeof(Data1), cudaMemcpyHostToDevice);
    CUDA_CHECK_RETURN(cudaDeviceSynchronize());

    std::chrono::time_point<std::chrono::system_clock> t1 = std::chrono::system_clock::now();

    f1<<<80,1>>>(data1_on_gpu);
    CUDA_CHECK_RETURN(cudaDeviceSynchronize());
    std::chrono::time_point<std::chrono::system_clock> t2 = std::chrono::system_clock::now();

    f2<<<80,1>>>(data2_on_gpu);
    CUDA_CHECK_RETURN(cudaDeviceSynchronize());
    std::chrono::time_point<std::chrono::system_clock> t3 = std::chrono::system_clock::now();

    std::chrono::duration<double> duration_1_to_2 = t2 - t1;
    std::chrono::duration<double> duration_2_to_3 = t3 - t2;
    duration_1_to_2.count();

    printf("timer for 1st took %.3lf\n", duration_1_to_2.count());
    printf("timer for 2nd took %.3lf\n", duration_2_to_3.count());

}


问:
How to align JButtons using 2 JPanel objects to form a basic java GUI
I'm attempting to re-create the following, extremely basic GUI seen here:

My output is as follows:

I'm having a difficult time formatting the JButtons.  For one thing, no matter what I do I cannot get the second Panel, the 'shapePane' to display below the first Panel the 'colorPane' secondly, I am unable to correctly make the y axis of the buttons larger to give them a fatter appearance.  Further, the top panel the 'shapePane' seems to dynamically move as the window is resized whereas, the second 'colorPane' stays in a fixed position regardless of the window resizing.

If someone could please provide a bit of assistance I would be immensely grateful

my code thus far is as follows:

```<code>import java.util.*;
import javax.swing.*;
import javax.swing.border.*;
import java.awt.*;
import java.awt.event.*;

public class GUI extends JFrame implements ActionListener, WindowListener
{
private JButton circleButton;
private JButton rectangleButton;
private JButton redButton;
private JButton greenButton;
private JButton blueButton;
private JButton exitButton;
private JTextField textField1;
private JLabel label1;
private JPanel contentPane;
private JPanel colorPane;
private JPanel shapePane;
private JFrame contentFrame;
private int count;

public GUI (String title)
{
    super(title);

    //setResizable(false);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    //setBounds(100, 100, 945, 580);

    //contentFrame = new JFrame();
    //contentPane = new JPanel();
    //contentFrame.add(contentPane);
    //contentPane.setBorder(new LineBorder(new Color(50, 5, 232), 4, true));

    //setContentPane(contentPane);
    //contentPane.setLayout(null);

    colorPane = new JPanel();
    //colorPane.setBorder(new LineBorder(new Color(34, 174, 82), 1, true));
    colorPane.setBounds(10, 32, 515, 125);

    //contentPane.add(colorPane);
    //colorPane.setLayout(null);

    shapePane = new JPanel();
    shapePane.setBounds(10, 165, 515, 315);
    //shapePane.setBorder(new LineBorder(new Color(34, 174, 82), 1, true));

    //contentPane.add(shapePane);
    //shapePane.setLayout(null);

    circleButton = new JButton("Circle");
    circleButton.setHorizontalAlignment(SwingConstants.LEFT);
    rectangleButton = new JButton("Rectangle");
    rectangleButton.setHorizontalAlignment(SwingConstants.LEFT);
    greenButton = new JButton("Green");
    redButton = new JButton("Red");
    blueButton = new JButton("Blue");
    exitButton = new JButton("Exit");
    textField1 = new JTextField(20);
    label1 = new JLabel("current time here");

    colorPane.add(redButton, BorderLayout.CENTER);
    colorPane.add(greenButton, BorderLayout.CENTER);
    colorPane.add(blueButton, BorderLayout.CENTER);

    shapePane.add(rectangleButton, BorderLayout.SOUTH);
    shapePane.add(circleButton, BorderLayout.SOUTH);
    shapePane.add(exitButton, BorderLayout.SOUTH);

    getContentPane().add(textField1, BorderLayout.EAST);
    getContentPane().add(label1, BorderLayout.WEST);

    getContentPane().add(colorPane, BorderLayout.CENTER);
    //contentFrame.add(colorPane);
    getContentPane().add(shapePane, BorderLayout.CENTER);
    //contentFrame.add(shapePane);
}

@Override
public void windowOpened(WindowEvent e) {
    // TODO Auto-generated method stub

}

@Override
public void windowClosing(WindowEvent e)
{
    System.exit(0);

}

@Override
public void windowClosed(WindowEvent e) {
    // TODO Auto-generated method stub

}

@Override
public void windowIconified(WindowEvent e) {
    // TODO Auto-generated method stub

}

@Override
public void windowDeiconified(WindowEvent e) {
    // TODO Auto-generated method stub

}

@Override
public void windowActivated(WindowEvent e) {
    // TODO Auto-generated method stub

}

@Override
public void windowDeactivated(WindowEvent e) {
    // TODO Auto-generated method stub

}

@Override
public void actionPerformed(ActionEvent e) {
    // TODO Auto-generated method stub

}

}
</code>```

答:
The following should get you started:

Set label's vertical and horizontal position so it appears in the bottom left
and and its desired width. For more layout flexibility consider warping it in a JPanel:

```<code>    label1 = new JLabel("current time here");
    label1.setVerticalAlignment(SwingConstants.BOTTOM);
    label1.setHorizontalAlignment(SwingConstants.LEFT);
    label1.setPreferredSize(new Dimension(200, 0)); //height is set by the layout manger
    getContentPane().add(label1, BorderLayout.WEST);
</code>```

Use a GridLayout for the buttons pane:

```<code>    colorPane = new JPanel();
    colorPane.setLayout(new GridLayout(2, 3));
</code>```

Initialize buttons and add them one by one to the grid pane:

```<code>    redButton = makeButton("Red");
    colorPane.add(redButton);
</code>```

Where makeButton is a method implemented to avoid duplicating code:

```<code>private JButton makeButton(String text) {
    JButton b = new JButton(text);
    b.setHorizontalAlignment(SwingConstants.LEFT);
    b.addActionListener(this);
    b.setPreferredSize(new Dimension(125, 55)); //set preferred and let Layout manager do its work
    return b;
}
</code>```

Set the text area number of columns. Its height is set by the layout manger:

```<code>textArea = new JTextArea(0,20);
getContentPane().add(textArea, BorderLayout.EAST);
</code>```

Putting it all together:

```<code>import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.SwingConstants;

public class GUI extends JFrame implements ActionListener
{
    private final JButton circleButton, rectangleButton, redButton;
    private final JButton greenButton, blueButton, exitButton;
    private final JTextArea textArea;
    private final JLabel label1;
    private final JPanel colorPane;

    private static final int ROWS = 2, COLS = 3;

    public GUI (String title)
    {
        super(title);

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        //set label's vertical and horizontal position so it appears in the bottom left
        //and and its desired width
        //for more layout flexibility consider warping it in a JFrame
        label1 = new JLabel("current time here");
        label1.setVerticalAlignment(SwingConstants.BOTTOM);
        label1.setHorizontalAlignment(SwingConstants.LEFT);
        label1.setPreferredSize(new Dimension(200, 0)); //height is set by the layout manger
        getContentPane().add(label1, BorderLayout.WEST);

        //use a GridLayout for the buttons pane
        colorPane = new JPanel();
        colorPane.setLayout(new GridLayout(ROWS, COLS));
        getContentPane().add(colorPane, BorderLayout.CENTER);//each BorderLayout position can hold ONE component

        redButton = makeButton("Red");
        colorPane.add(redButton);
        greenButton = makeButton("Green");
        colorPane.add(greenButton);
        blueButton = makeButton("Blue");
        colorPane.add(blueButton);
        rectangleButton = makeButton("Rectangle");
        colorPane.add(rectangleButton);
        circleButton = makeButton("Circle");
        colorPane.add(circleButton);
        exitButton = makeButton("Exit");
        colorPane.add(exitButton);

        //set the text area number of columns. Its height is set by the layout manger
        textArea = new JTextArea(0,20);
        getContentPane().add(textArea, BorderLayout.EAST);

        pack();
    }

    private JButton makeButton(String text) {
        JButton b = new JButton(text);
        b.setHorizontalAlignment(SwingConstants.LEFT);
        b.addActionListener(this);
        b.setPreferredSize(new Dimension(125, 55)); //set preferred and let Layout manager do its work
        return b;
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        System.out.println(((JButton)e.getSource()).getText()+ " button pressed");
    }

    public static void main(String[] args) {
        new GUI("My Gui").setVisible(true);
    }
}
</code>```

A simple enhancement could be storing all button references in a Map:

```<code>public class GUI extends JFrame implements ActionListener
{
    private Map <String, JButton> buttons; // a map to hold references to all buttons
    private final JTextArea textArea;
    private final JLabel label1;
    private final JPanel colorPane;

    private static final int ROWS = 2, COLS = 3;
    private static final String[] BUTTON_LABELS = {"Red","Green", "Blue", "Rectangle", "Circle", "Exit"};

    public GUI (String title)
    {
        super(title);
        buttons = new HashMap<>();
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        //set label's vertical and horizontal position so it appears in the bottom left
        //and and its desired width
        //for more layout flexibility consider warping it in a JFrame
        label1 = new JLabel("current time here");
        label1.setVerticalAlignment(SwingConstants.BOTTOM);
        label1.setHorizontalAlignment(SwingConstants.LEFT);
        label1.setPreferredSize(new Dimension(200, 0)); //height is set by the layout manger
        getContentPane().add(label1, BorderLayout.WEST);

        //use a GridLayout for the buttons pane
        colorPane = new JPanel();
        colorPane.setLayout(new GridLayout(ROWS, COLS));
        getContentPane().add(colorPane, BorderLayout.CENTER);//each BorderLayout position can hold ONE component

        for(String text : BUTTON_LABELS){
            JButton button = makeButton(text);
            colorPane.add(button);
            buttons.put(text, button);
        }

        //set the text area number of columns. Its height is set by the layout manger
        textArea = new JTextArea(0,20);
        getContentPane().add(textArea, BorderLayout.EAST);

        pack();
    }

    private JButton makeButton(String text) {
        JButton b = new JButton(text);
        b.setHorizontalAlignment(SwingConstants.LEFT);
        b.addActionListener(this);
        b.setPreferredSize(new Dimension(125, 55)); //set preferred and let Layout manager do its work
        return b;
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        System.out.println(((JButton)e.getSource()).getText()+ " button pressed");
    }

    public static void main(String[] args) {
        new GUI("My Gui").setVisible(true);
    }
}
</code>```

Body:
I'm attempting to re-create the following, extremely basic GUI seen here:

My output is as follows:

I'm having a difficult time formatting the JButtons.  For one thing, no matter what I do I cannot get the second Panel, the 'shapePane' to display below the first Panel the 'colorPane' secondly, I am unable to correctly make the y axis of the buttons larger to give them a fatter appearance.  Further, the top panel the 'shapePane' seems to dynamically move as the window is resized whereas, the second 'colorPane' stays in a fixed position regardless of the window resizing.

If someone could please provide a bit of assistance I would be immensely grateful

my code thus far is as follows:

import java.util.*;
import javax.swing.*;
import javax.swing.border.*;
import java.awt.*;
import java.awt.event.*;

public class GUI extends JFrame implements ActionListener, WindowListener
{
private JButton circleButton;
private JButton rectangleButton;
private JButton redButton;
private JButton greenButton;
private JButton blueButton;
private JButton exitButton;
private JTextField textField1;
private JLabel label1;
private JPanel contentPane;
private JPanel colorPane;
private JPanel shapePane;
private JFrame contentFrame;
private int count;

public GUI (String title)
{
    super(title);

    //setResizable(false);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    //setBounds(100, 100, 945, 580);

    //contentFrame = new JFrame();
    //contentPane = new JPanel();
    //contentFrame.add(contentPane);
    //contentPane.setBorder(new LineBorder(new Color(50, 5, 232), 4, true));

    //setContentPane(contentPane);
    //contentPane.setLayout(null);

    colorPane = new JPanel();
    //colorPane.setBorder(new LineBorder(new Color(34, 174, 82), 1, true));
    colorPane.setBounds(10, 32, 515, 125);

    //contentPane.add(colorPane);
    //colorPane.setLayout(null);

    shapePane = new JPanel();
    shapePane.setBounds(10, 165, 515, 315);
    //shapePane.setBorder(new LineBorder(new Color(34, 174, 82), 1, true));

    //contentPane.add(shapePane);
    //shapePane.setLayout(null);

    circleButton = new JButton("Circle");
    circleButton.setHorizontalAlignment(SwingConstants.LEFT);
    rectangleButton = new JButton("Rectangle");
    rectangleButton.setHorizontalAlignment(SwingConstants.LEFT);
    greenButton = new JButton("Green");
    redButton = new JButton("Red");
    blueButton = new JButton("Blue");
    exitButton = new JButton("Exit");
    textField1 = new JTextField(20);
    label1 = new JLabel("current time here");

    colorPane.add(redButton, BorderLayout.CENTER);
    colorPane.add(greenButton, BorderLayout.CENTER);
    colorPane.add(blueButton, BorderLayout.CENTER);

    shapePane.add(rectangleButton, BorderLayout.SOUTH);
    shapePane.add(circleButton, BorderLayout.SOUTH);
    shapePane.add(exitButton, BorderLayout.SOUTH);

    getContentPane().add(textField1, BorderLayout.EAST);
    getContentPane().add(label1, BorderLayout.WEST);

    getContentPane().add(colorPane, BorderLayout.CENTER);
    //contentFrame.add(colorPane);
    getContentPane().add(shapePane, BorderLayout.CENTER);
    //contentFrame.add(shapePane);
}

@Override
public void windowOpened(WindowEvent e) {
    // TODO Auto-generated method stub

}

@Override
public void windowClosing(WindowEvent e)
{
    System.exit(0);

}

@Override
public void windowClosed(WindowEvent e) {
    // TODO Auto-generated method stub

}

@Override
public void windowIconified(WindowEvent e) {
    // TODO Auto-generated method stub

}

@Override
public void windowDeiconified(WindowEvent e) {
    // TODO Auto-generated method stub

}

@Override
public void windowActivated(WindowEvent e) {
    // TODO Auto-generated method stub

}

@Override
public void windowDeactivated(WindowEvent e) {
    // TODO Auto-generated method stub

}

@Override
public void actionPerformed(ActionEvent e) {
    // TODO Auto-generated method stub

}

}

Body:
The following should get you started:

Set label's vertical and horizontal position so it appears in the bottom left
and and its desired width. For more layout flexibility consider warping it in a JPanel:

    label1 = new JLabel("current time here");
    label1.setVerticalAlignment(SwingConstants.BOTTOM);
    label1.setHorizontalAlignment(SwingConstants.LEFT);
    label1.setPreferredSize(new Dimension(200, 0)); //height is set by the layout manger
    getContentPane().add(label1, BorderLayout.WEST);

Use a GridLayout for the buttons pane:

    colorPane = new JPanel();
    colorPane.setLayout(new GridLayout(2, 3));

Initialize buttons and add them one by one to the grid pane:

    redButton = makeButton("Red");
    colorPane.add(redButton);

Where makeButton is a method implemented to avoid duplicating code:

private JButton makeButton(String text) {
    JButton b = new JButton(text);
    b.setHorizontalAlignment(SwingConstants.LEFT);
    b.addActionListener(this);
    b.setPreferredSize(new Dimension(125, 55)); //set preferred and let Layout manager do its work
    return b;
}

Set the text area number of columns. Its height is set by the layout manger:

textArea = new JTextArea(0,20);
getContentPane().add(textArea, BorderLayout.EAST);

Putting it all together:

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.SwingConstants;

public class GUI extends JFrame implements ActionListener
{
    private final JButton circleButton, rectangleButton, redButton;
    private final JButton greenButton, blueButton, exitButton;
    private final JTextArea textArea;
    private final JLabel label1;
    private final JPanel colorPane;

    private static final int ROWS = 2, COLS = 3;

    public GUI (String title)
    {
        super(title);

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        //set label's vertical and horizontal position so it appears in the bottom left
        //and and its desired width
        //for more layout flexibility consider warping it in a JFrame
        label1 = new JLabel("current time here");
        label1.setVerticalAlignment(SwingConstants.BOTTOM);
        label1.setHorizontalAlignment(SwingConstants.LEFT);
        label1.setPreferredSize(new Dimension(200, 0)); //height is set by the layout manger
        getContentPane().add(label1, BorderLayout.WEST);

        //use a GridLayout for the buttons pane
        colorPane = new JPanel();
        colorPane.setLayout(new GridLayout(ROWS, COLS));
        getContentPane().add(colorPane, BorderLayout.CENTER);//each BorderLayout position can hold ONE component

        redButton = makeButton("Red");
        colorPane.add(redButton);
        greenButton = makeButton("Green");
        colorPane.add(greenButton);
        blueButton = makeButton("Blue");
        colorPane.add(blueButton);
        rectangleButton = makeButton("Rectangle");
        colorPane.add(rectangleButton);
        circleButton = makeButton("Circle");
        colorPane.add(circleButton);
        exitButton = makeButton("Exit");
        colorPane.add(exitButton);

        //set the text area number of columns. Its height is set by the layout manger
        textArea = new JTextArea(0,20);
        getContentPane().add(textArea, BorderLayout.EAST);

        pack();
    }

    private JButton makeButton(String text) {
        JButton b = new JButton(text);
        b.setHorizontalAlignment(SwingConstants.LEFT);
        b.addActionListener(this);
        b.setPreferredSize(new Dimension(125, 55)); //set preferred and let Layout manager do its work
        return b;
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        System.out.println(((JButton)e.getSource()).getText()+ " button pressed");
    }

    public static void main(String[] args) {
        new GUI("My Gui").setVisible(true);
    }
}

A simple enhancement could be storing all button references in a Map:

public class GUI extends JFrame implements ActionListener
{
    private Map <String, JButton> buttons; // a map to hold references to all buttons
    private final JTextArea textArea;
    private final JLabel label1;
    private final JPanel colorPane;

    private static final int ROWS = 2, COLS = 3;
    private static final String[] BUTTON_LABELS = {"Red","Green", "Blue", "Rectangle", "Circle", "Exit"};

    public GUI (String title)
    {
        super(title);
        buttons = new HashMap<>();
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        //set label's vertical and horizontal position so it appears in the bottom left
        //and and its desired width
        //for more layout flexibility consider warping it in a JFrame
        label1 = new JLabel("current time here");
        label1.setVerticalAlignment(SwingConstants.BOTTOM);
        label1.setHorizontalAlignment(SwingConstants.LEFT);
        label1.setPreferredSize(new Dimension(200, 0)); //height is set by the layout manger
        getContentPane().add(label1, BorderLayout.WEST);

        //use a GridLayout for the buttons pane
        colorPane = new JPanel();
        colorPane.setLayout(new GridLayout(ROWS, COLS));
        getContentPane().add(colorPane, BorderLayout.CENTER);//each BorderLayout position can hold ONE component

        for(String text : BUTTON_LABELS){
            JButton button = makeButton(text);
            colorPane.add(button);
            buttons.put(text, button);
        }

        //set the text area number of columns. Its height is set by the layout manger
        textArea = new JTextArea(0,20);
        getContentPane().add(textArea, BorderLayout.EAST);

        pack();
    }

    private JButton makeButton(String text) {
        JButton b = new JButton(text);
        b.setHorizontalAlignment(SwingConstants.LEFT);
        b.addActionListener(this);
        b.setPreferredSize(new Dimension(125, 55)); //set preferred and let Layout manager do its work
        return b;
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        System.out.println(((JButton)e.getSource()).getText()+ " button pressed");
    }

    public static void main(String[] args) {
        new GUI("My Gui").setVisible(true);
    }
}


问:
Session must be bound error using Squeryl
Update:
Okay, I fixed the problem I was having, but I'm still not quite sure what I was doing wrong. In any case, I wrote the following method in IRCDB:

```<code>def tryit[T](p: => T) = {
    Class.forName("org.h2.Driver") //what's the point in this...?

    SessionFactory.concreteFactory = Some(() =>
        Session.create(java.sql.DriverManager.getConnection("jdbc:h2:~/irc","ScalaIRC",""), new H2Adapter))

    transaction {
        p
    }
}
</code>```

Then used it like so:

```<code> val query = from(IRCDB.channels)(c => select(c))
 IRCDB.tryit {
     for (r <- query) println("chan: " + r.name)
 }
</code>```

And it now works. From my understanding, I believed that once the session was created using the SessionFactory, I'd be able to use transaction { ... } anywhere that has the proper import. Apparently, my understanding is incorrect.

If anyone has anything to add please do.

So, I just started using Squeryl for a project I'm working on so this might just be an oversight on my part. So, first the code:

I have the following imports:

```<code>import org.squeryl.PrimitiveTypeMode._
import java.sql.Timestamp
import java.sql.DriverManager
import java.util.Date
import org.squeryl.adapters.H2Adapter
import org.squeryl.dsl.{OneToMany, ManyToOne, CompositeKey2}
import org.squeryl._
</code>```

I have the following table defined:

```<code>class ChannelTable(val id: Long, val name : String,
               val p_mode : Boolean, val s_mode : Boolean,
               val i_mode : Boolean, val t_mode : Boolean,
               val n_mode : Boolean, val m_mode : Boolean,
               val key : Option[String]) extends KeyedEntity[Long] {
    def this() = this(0,"", false, false, false, false, false, false, Some(""))

    lazy val bans:OneToMany[ChannelBanTable] = IRCDB.channelToChanBans.left(this)
    lazy val users = IRCDB.channelUsers.left(this)
    lazy val invites = IRCDB.channelInvites.left(this)
}
</code>```

And the following Schema defined:

```<code>object IRCDB extends Schema {
    val channels = table[ChannelTable]

    on(channels)(c => declare(
      c.p_mode defaultsTo(false),
      c.s_mode defaultsTo(false),
      c.i_mode defaultsTo(false),
      c.t_mode defaultsTo(false),
      c.n_mode defaultsTo(false),
      c.m_mode defaultsTo(false),
      c.name is(unique, indexed)
    ))

    def init {
        Class.forName("org.h2.Driver") //what's the point in this...?

        SessionFactory.concreteFactory = Some(() =>
          Session.create(DriverManager.getConnection("jdbc:h2:~/irc","ScalaIRC",""), new H2Adapter))
    }
    def getAllChannels = transaction { from(channels)(c => select(c))}
}
</code>```

I have been able to insert into the table with the following at the Console:

```<code>scala> import db._;import org.squeryl.PrimitiveTypeMode._
import db._
import org.squeryl.PrimitiveTypeMode._
scala> IRCDB.init
scala> transaction { IRCDB.channels.insert(new ChannelTable(0,"#chan_name", false, false, false, false, false, false, None)) }
res3: db.ChannelTable = db.ChannelTable@4
</code>```

I can confirm with the H2 Console that this does indeed occur. However, when I call IRCDB.getAllChannels (in both the Scala Console and in code) I get the following error:

```<code>java.lang.RuntimeException: no session is bound to current thread, a session must be created via Session.create
and bound to the thread via 'work' or 'bindToCurrentThread'
    at scala.Predef$.error(Predef.scala:58)
    at org.squeryl.Session$$anonfun$currentSession$1.apply(Session.scala:117)
    at org.squeryl.Session$$anonfun$currentSession$1.apply(Session.scala:117)
    at scala.Option.getOrElse(Option.scala:59)
    at org.squeryl.Session$.currentSession(Session.scala:116)
    at org.squeryl.dsl.AbstractQuery.org$squeryl$dsl$AbstractQuery$$_dbAdapter(AbstractQuery.scala:136)
    at org.squeryl.dsl.AbstractQuery$$anon$1.<init>(AbstractQuery.scala:140)
    at org.squeryl.dsl.AbstractQuery.iterator(AbstractQuery.scala:138)
    at scala.collection.IterableLike$class.foreach(IterableLike.scala:79)
    at org.squeryl.dsl.AbstractQuery.foreach(AbstractQuery.scala:27)
    at scala.collection.TraversableLike$class.map(TraversableLike.scala:206)
    at org.squeryl.dsl.AbstractQuery.map(AbstractQuery.scala:27)
    at scala.runtime.ScalaRunTime$.inner$1(ScalaRunTime.scala:255)
    at scala.runtime.ScalaRunTime$.stringOf(ScalaRunTime.scala:258)
    at RequestResult$line7$object$.<init>(<console>:12)
    at RequestResult$line7$object$.<clinit>(<console>)
    at RequestResult$line7$object.scala_repl_result(<console>)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at scala.tools.nsc.Interpreter$Request$$anonfun$loadAndRun$1$$anonfun$apply$18.apply(Interpreter.scala:981)
    at scala.tools.nsc.Interpreter$Request$$anonfun$loadAndRun$1$$anonfun$apply$18.apply(Interpreter.scala:981)
    at scala.util.control.Exception$Catch.apply(Exception.scala:79)
    at scala.tools.nsc.Interpreter$Request$$anonfun$loadAndRun$1.apply(Interpreter.scala:980)
    at scala.tools.nsc.Interpreter$Request$$anonfun$loadAndRun$1.apply(Interpreter.scala:980)
    at scala.util.control.Exception$Catch.apply(Exception.scala:79)
    at scala.tools.nsc.Interpreter$Request.loadAndRun(Interpreter.scala:979)
    at scala.tools.nsc.Interpreter.loadAndRunReq$1(Interpreter.scala:578)
    at scala.tools.nsc.Interpreter.interpret(Interpreter.scala:597)
    at scala.tools.nsc.Interpreter.interpret(Interpreter.scala:575)
    at scala.tools.nsc.InterpreterLoop.reallyInterpret$1(InterpreterLoop.scala:471)
    at scala.tools.nsc.InterpreterLoop.interpretStartingWith(InterpreterLoop.scala:514)
    at scala.tools.nsc.InterpreterLoop.command(InterpreterLoop.scala:361)
    at scala.tools.nsc.InterpreterLoop.processLine$1(InterpreterLoop.scala:242)
    at scala.tools.nsc.InterpreterLoop.repl(InterpreterLoop.scala:248)
    at scala.tools.nsc.InterpreterLoop.main(InterpreterLoop.scala:558)
    at scala.tools.nsc.InterpreterLoop.main(InterpreterLoop.scala:609)
    at org.jetbrains.plugins.scala.compiler.rt.ConsoleRunner.main(ConsoleRunner.java:33)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:115)
</code>```

I don't understand why I would be getting this error if I was able to insert rows into the table doing nearly the same way. If I try to execute transaction { from(IRCDB.channels)(c => select(c)) } at the Console I get the same error.

Edit: I've added the full stack trace. Also, I rewrote the getAllChannels function like this:

```<code>def getAllChannels = transaction {
  val ret = from(channels)(c => select(c))
  println("sql: " + ret)
  ret
}
</code>```

I still receive an error, but it does print the query out first -- I thought this may be useful:

```<code>sql: 'QueryExpressionNode[root:1a0d111]:rsm='ResultSetMapper:fdf48d()--
    'FieldSelectElement:ChannelTable1_name
        org.squeryl.dsl.ast.FieldSelectElement$$anon$3
    'FieldSelectElement:ChannelTable1_i_mode
        org.squeryl.dsl.ast.FieldSelectElement$$anon$3
    'FieldSelectElement:ChannelTable1_s_mode
        org.squeryl.dsl.ast.FieldSelectElement$$anon$3
    'FieldSelectElement:ChannelTable1_key
        org.squeryl.dsl.ast.FieldSelectElement$$anon$3
    'FieldSelectElement:ChannelTable1_n_mode
        org.squeryl.dsl.ast.FieldSelectElement$$anon$3
    'FieldSelectElement:ChannelTable1_m_mode
        org.squeryl.dsl.ast.FieldSelectElement$$anon$3
    'FieldSelectElement:ChannelTable1_id
        org.squeryl.dsl.ast.FieldSelectElement$$anon$3
    'FieldSelectElement:ChannelTable1_t_mode
        org.squeryl.dsl.ast.FieldSelectElement$$anon$3
    'FieldSelectElement:ChannelTable1_p_mode
        org.squeryl.dsl.ast.FieldSelectElement$$anon$3
    'ViewExpressionNode[sample:ChannelTable[16e3f87]]:rsm='ResultSetMapper:442b95($(1->ChannelTable.name:java.lang.String),$(2->ChannelTable.i_mode:java.lang.Boolean),$(3->ChannelTable.s_mode:java.lang.Boolean),$(4->ChannelTable.key:Option[java.lang.String]),$(5->ChannelTable.n_mode:java.lang.Boolean),$(6->ChannelTable.m_mode:java.lang.Boolean),$(7->ChannelTable.id:java.lang.Long),$(8->ChannelTable.t_mode:java.lang.Boolean),$(9->ChannelTable.p_mode:java.lang.Boolean))--*

Select
  ChannelTable1.name as ChannelTable1_name,
  ChannelTable1.i_mode as ChannelTable1_i_mode,
  ChannelTable1.s_mode as ChannelTable1_s_mode,
  ChannelTable1.key as ChannelTable1_key,
  ChannelTable1.n_mode as ChannelTable1_n_mode,
  ChannelTable1.m_mode as ChannelTable1_m_mode,
  ChannelTable1.id as ChannelTable1_id,
  ChannelTable1.t_mode as ChannelTable1_t_mode,
  ChannelTable1.p_mode as ChannelTable1_p_mode
From
  ChannelTable ChannelTable1
java.lang.RuntimeException: no session is bound to current thread, a session must be created via Session.create
and bound to the thread via 'work' or 'bindToCurrentThread'
    at scala.Predef$.error(Predef.scala:58)
    at org.squeryl.Session$$anonfun$currentSession$1.apply(Session.scala:117)
    at org.squeryl.Session$$anonfun$currentSession$1.apply(Session.scala:117)
    at scala.Option.getOrElse(Option.scala:59)
    at org.squeryl.Session$.currentSession(Session.scala:116)
    at org.squeryl.dsl.AbstractQuery.org$squeryl$dsl$AbstractQuery$$_dbAdapter(AbstractQuery.scala:136)
    at org.squeryl.dsl.AbstractQuery$$anon$1.<init>(AbstractQuery.scala:140)
    at org.squeryl.dsl.AbstractQuery.iterator(AbstractQuery.scala:138)
    at scala.collection.IterableLike$class.foreach(IterableLike.scala:79)
    at org.squeryl....
</code>```

答: Maybe, error appears while printing the result to console and the query was ok. Please, provide full stacktrace.</p>

ContentLicense: CC BY-SA 3.0

Body:
Update:
Okay, I fixed the problem I was having, but I'm still not quite sure what I was doing wrong. In any case, I wrote the following method in IRCDB:

def tryit[T](p: => T) = {
    Class.forName("org.h2.Driver") //what's the point in this...?

    SessionFactory.concreteFactory = Some(() =>
        Session.create(java.sql.DriverManager.getConnection("jdbc:h2:~/irc","ScalaIRC",""), new H2Adapter))

    transaction {
        p
    }
}

Then used it like so:

 val query = from(IRCDB.channels)(c => select(c))
 IRCDB.tryit {
     for (r <- query) println("chan: " + r.name)
 }

And it now works. From my understanding, I believed that once the session was created using the SessionFactory, I'd be able to use transaction { ... } anywhere that has the proper import. Apparently, my understanding is incorrect.

If anyone has anything to add please do.

So, I just started using Squeryl for a project I'm working on so this might just be an oversight on my part. So, first the code:

I have the following imports:

import org.squeryl.PrimitiveTypeMode._
import java.sql.Timestamp
import java.sql.DriverManager
import java.util.Date
import org.squeryl.adapters.H2Adapter
import org.squeryl.dsl.{OneToMany, ManyToOne, CompositeKey2}
import org.squeryl._

I have the following table defined:

class ChannelTable(val id: Long, val name : String,
               val p_mode : Boolean, val s_mode : Boolean,
               val i_mode : Boolean, val t_mode : Boolean,
               val n_mode : Boolean, val m_mode : Boolean,
               val key : Option[String]) extends KeyedEntity[Long] {
    def this() = this(0,"", false, false, false, false, false, false, Some(""))

    lazy val bans:OneToMany[ChannelBanTable] = IRCDB.channelToChanBans.left(this)
    lazy val users = IRCDB.channelUsers.left(this)
    lazy val invites = IRCDB.channelInvites.left(this)
}

And the following Schema defined:

object IRCDB extends Schema {
    val channels = table[ChannelTable]

    on(channels)(c => declare(
      c.p_mode defaultsTo(false),
      c.s_mode defaultsTo(false),
      c.i_mode defaultsTo(false),
      c.t_mode defaultsTo(false),
      c.n_mode defaultsTo(false),
      c.m_mode defaultsTo(false),
      c.name is(unique, indexed)
    ))

    def init {
        Class.forName("org.h2.Driver") //what's the point in this...?

        SessionFactory.concreteFactory = Some(() =>
          Session.create(DriverManager.getConnection("jdbc:h2:~/irc","ScalaIRC",""), new H2Adapter))
    }
    def getAllChannels = transaction { from(channels)(c => select(c))}
}

I have been able to insert into the table with the following at the Console:

scala> import db._;import org.squeryl.PrimitiveTypeMode._
import db._
import org.squeryl.PrimitiveTypeMode._
scala> IRCDB.init
scala> transaction { IRCDB.channels.insert(new ChannelTable(0,"#chan_name", false, false, false, false, false, false, None)) }
res3: db.ChannelTable = db.ChannelTable@4

I can confirm with the H2 Console that this does indeed occur. However, when I call IRCDB.getAllChannels (in both the Scala Console and in code) I get the following error:

java.lang.RuntimeException: no session is bound to current thread, a session must be created via Session.create
and bound to the thread via 'work' or 'bindToCurrentThread'
    at scala.Predef$.error(Predef.scala:58)
    at org.squeryl.Session$$anonfun$currentSession$1.apply(Session.scala:117)
    at org.squeryl.Session$$anonfun$currentSession$1.apply(Session.scala:117)
    at scala.Option.getOrElse(Option.scala:59)
    at org.squeryl.Session$.currentSession(Session.scala:116)
    at org.squeryl.dsl.AbstractQuery.org$squeryl$dsl$AbstractQuery$$_dbAdapter(AbstractQuery.scala:136)
    at org.squeryl.dsl.AbstractQuery$$anon$1.<init>(AbstractQuery.scala:140)
    at org.squeryl.dsl.AbstractQuery.iterator(AbstractQuery.scala:138)
    at scala.collection.IterableLike$class.foreach(IterableLike.scala:79)
    at org.squeryl.dsl.AbstractQuery.foreach(AbstractQuery.scala:27)
    at scala.collection.TraversableLike$class.map(TraversableLike.scala:206)
    at org.squeryl.dsl.AbstractQuery.map(AbstractQuery.scala:27)
    at scala.runtime.ScalaRunTime$.inner$1(ScalaRunTime.scala:255)
    at scala.runtime.ScalaRunTime$.stringOf(ScalaRunTime.scala:258)
    at RequestResult$line7$object$.<init>(<console>:12)
    at RequestResult$line7$object$.<clinit>(<console>)
    at RequestResult$line7$object.scala_repl_result(<console>)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at scala.tools.nsc.Interpreter$Request$$anonfun$loadAndRun$1$$anonfun$apply$18.apply(Interpreter.scala:981)
    at scala.tools.nsc.Interpreter$Request$$anonfun$loadAndRun$1$$anonfun$apply$18.apply(Interpreter.scala:981)
    at scala.util.control.Exception$Catch.apply(Exception.scala:79)
    at scala.tools.nsc.Interpreter$Request$$anonfun$loadAndRun$1.apply(Interpreter.scala:980)
    at scala.tools.nsc.Interpreter$Request$$anonfun$loadAndRun$1.apply(Interpreter.scala:980)
    at scala.util.control.Exception$Catch.apply(Exception.scala:79)
    at scala.tools.nsc.Interpreter$Request.loadAndRun(Interpreter.scala:979)
    at scala.tools.nsc.Interpreter.loadAndRunReq$1(Interpreter.scala:578)
    at scala.tools.nsc.Interpreter.interpret(Interpreter.scala:597)
    at scala.tools.nsc.Interpreter.interpret(Interpreter.scala:575)
    at scala.tools.nsc.InterpreterLoop.reallyInterpret$1(InterpreterLoop.scala:471)
    at scala.tools.nsc.InterpreterLoop.interpretStartingWith(InterpreterLoop.scala:514)
    at scala.tools.nsc.InterpreterLoop.command(InterpreterLoop.scala:361)
    at scala.tools.nsc.InterpreterLoop.processLine$1(InterpreterLoop.scala:242)
    at scala.tools.nsc.InterpreterLoop.repl(InterpreterLoop.scala:248)
    at scala.tools.nsc.InterpreterLoop.main(InterpreterLoop.scala:558)
    at scala.tools.nsc.InterpreterLoop.main(InterpreterLoop.scala:609)
    at org.jetbrains.plugins.scala.compiler.rt.ConsoleRunner.main(ConsoleRunner.java:33)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:115)

I don't understand why I would be getting this error if I was able to insert rows into the table doing nearly the same way. If I try to execute transaction { from(IRCDB.channels)(c => select(c)) } at the Console I get the same error.

Edit: I've added the full stack trace. Also, I rewrote the getAllChannels function like this:

def getAllChannels = transaction {
  val ret = from(channels)(c => select(c))
  println("sql: " + ret)
  ret
}

I still receive an error, but it does print the query out first -- I thought this may be useful:

sql: 'QueryExpressionNode[root:1a0d111]:rsm='ResultSetMapper:fdf48d()--
    'FieldSelectElement:ChannelTable1_name
        org.squeryl.dsl.ast.FieldSelectElement$$anon$3
    'FieldSelectElement:ChannelTable1_i_mode
        org.squeryl.dsl.ast.FieldSelectElement$$anon$3
    'FieldSelectElement:ChannelTable1_s_mode
        org.squeryl.dsl.ast.FieldSelectElement$$anon$3
    'FieldSelectElement:ChannelTable1_key
        org.squeryl.dsl.ast.FieldSelectElement$$anon$3
    'FieldSelectElement:ChannelTable1_n_mode
        org.squeryl.dsl.ast.FieldSelectElement$$anon$3
    'FieldSelectElement:ChannelTable1_m_mode
        org.squeryl.dsl.ast.FieldSelectElement$$anon$3
    'FieldSelectElement:ChannelTable1_id
        org.squeryl.dsl.ast.FieldSelectElement$$anon$3
    'FieldSelectElement:ChannelTable1_t_mode
        org.squeryl.dsl.ast.FieldSelectElement$$anon$3
    'FieldSelectElement:ChannelTable1_p_mode
        org.squeryl.dsl.ast.FieldSelectElement$$anon$3
    'ViewExpressionNode[sample:ChannelTable[16e3f87]]:rsm='ResultSetMapper:442b95($(1->ChannelTable.name:java.lang.String),$(2->ChannelTable.i_mode:java.lang.Boolean),$(3->ChannelTable.s_mode:java.lang.Boolean),$(4->ChannelTable.key:Option[java.lang.String]),$(5->ChannelTable.n_mode:java.lang.Boolean),$(6->ChannelTable.m_mode:java.lang.Boolean),$(7->ChannelTable.id:java.lang.Long),$(8->ChannelTable.t_mode:java.lang.Boolean),$(9->ChannelTable.p_mode:java.lang.Boolean))--*

Select
  ChannelTable1.name as ChannelTable1_name,
  ChannelTable1.i_mode as ChannelTable1_i_mode,
  ChannelTable1.s_mode as ChannelTable1_s_mode,
  ChannelTable1.key as ChannelTable1_key,
  ChannelTable1.n_mode as ChannelTable1_n_mode,
  ChannelTable1.m_mode as ChannelTable1_m_mode,
  ChannelTable1.id as ChannelTable1_id,
  ChannelTable1.t_mode as ChannelTable1_t_mode,
  ChannelTable1.p_mode as ChannelTable1_p_mode
From
  ChannelTable ChannelTable1
java.lang.RuntimeException: no session is bound to current thread, a session must be created via Session.create
and bound to the thread via 'work' or 'bindToCurrentThread'
    at scala.Predef$.error(Predef.scala:58)
    at org.squeryl.Session$$anonfun$currentSession$1.apply(Session.scala:117)
    at org.squeryl.Session$$anonfun$currentSession$1.apply(Session.scala:117)
    at scala.Option.getOrElse(Option.scala:59)
    at org.squeryl.Session$.currentSession(Session.scala:116)
    at org.squeryl.dsl.AbstractQuery.org$squeryl$dsl$AbstractQuery$$_dbAdapter(AbstractQuery.scala:136)
    at org.squeryl.dsl.AbstractQuery$$anon$1.<init>(AbstractQuery.scala:140)
    at org.squeryl.dsl.AbstractQuery.iterator(AbstractQuery.scala:138)
    at scala.collection.IterableLike$class.foreach(IterableLike.scala:79)
    at org.squeryl....


问:
Powershell script to handle multi line data in excel cell and convert to csv using Import-excel or Import-csv
Q: I want to convert excel to csv but the excel contains multiline data in a cell along with ";" as delimiter. The desired output is a csv file with "|" as separator for columns but "," as separator for data within same cell. I cannot use excel hence I am using the module "ImportExcel".

Input Excel Format (attached file at end of Question) :-

```<code>Row1# c1# c2#                    c3#         c4#
Row2#
Row3#
Row4#     HEADER1                HEADER2     HEADER3
Row5#     04.05 test & t     test        TEST
Row5#     04.06.01 test test                 TEST
Row5#     04.07.01 test test
Row5#     04.10.02 test & t
</code>```

Row# represents the row of the excel and c# represent the column while HEADER# represent the title of the columns. As can be seen, ROW 1-3 and first column of the excel are empty. The text of second and fourth column is multiline but in the same cell(same row Row5).

I tried to Import the excel then for each object and replace the new line character with "," finally export it to csv using(export-csv) with "|" as delimiter.

The script I made is as follows :-

```<code>$test = Import-excel -NoHeader -StartRow(4) test.xlsx

$test | foreach-object {

if($_.HEADER1) {
$_.HEADER1 = $_.HEADER1.replace("\n",", ")
$_.HEADER1 = $_.HEADER1.replace("&","& ")
   }
}

$test | Export-csv new-test.csv -Delimiter '|' -NoTypeInformation
</code>```

Output CSV FILE I GET :-

```<code>Row1# c1# c2#                       c3#
Row2#     HEADER1|HEADER2|HEADER3
Row3#     04.05 test &amp            t
Row4#     04.06.01 test test
Row5#     04.07.01 test test
Row6#     04.10.02 test &amp         t
Row7#     test|TEST
Row8#     TEST
</code>```

As can be seen, the text after the delimeter ";" in the input goes to another column and the multiline is still parsed into separate rows. I want all this multiline to be merged into one with "," as separator along with the text after the "';" delimeter.

Desired CSV FILE :-

```<code>Row1# c1# c2#
Row2#     HEADER1|HEADER2|HEADER3
Row3#     04.05 test &  t,04.06.01 test test,04.07.01 test test,04.10.02 test & t|test|TEST,TEST
</code>```

I have tried a lot of questions from stackoverflow related to this but for some reason none of the existing solution seems to be working for me.

Attached is the sample Excel file I am trying to convert. test.xlsx

答:
The problem with your code is that you specify the -NoHeader parameter.

and you have to specify `n instead of \n as a newline character in Replace() method.

```<code>$test = Import-Excel test.xlsx -StartRow 4
$test | ForEach-Object {
    if($_.HEADER1) {
        $_.HEADER1 = $_.HEADER1.Replace("`n", ", ")
        $_.HEADER1 = $_.HEADER1.Replace("&", "&")
    }
    if($_.HEADER3) {
        $_.HEADER3 = $_.HEADER3.Replace("`n", ", ")
    }
}

$test | Export-Csv new-test.csv -Delimiter "|" -NoTypeInformation
</code>```

the output:

```<code>"HEADER1"|"HEADER2"|"HEADER3"
"04.05 test & t, 04.06.01 test test, 04.10.02 test & t, 04.07.01 test test"|"test"|"TEST, TEST"
</code>```

It is useful to use the $obj.psobject.Properties property to replace the values of all properties.

```<code># import
$data = Import-Excel test.xlsx -StartRow 4

# replace the values of all properties
$data | ForEach-Object { $_.psobject.Properties } | Where-Object Value -is string |
ForEach-Object { $_.Value = $_.Value.Replace("`n",", ").Replace("&", "&") }

# export
$data | Export-Csv new-test.csv -Delimiter "|" -NoTypeInformation
</code>```

If you want to insert empty rows and columns, add them after converting by ConvertTo-CSV.

```<code>$data | ConvertTo-Csv -Delimiter "|" -NoTypeInformation | ForEach-Object { "" } { "|" + $_ } | Out-File new-test.csv
</code>```

the output:

```<code>
|"HEADER1"|"HEADER2"|"HEADER3"
|"04.05 test & t, 04.06.01 test test, 04.10.02 test & t, 04.07.01 test test"|"test"|"TEST, TEST"
</code>```

If the headers are duplicated, the -NoHeader parameter is required. And remove the automatically attached headers before saving.

```<code>$data = Import-Excel test.xlsx -StartRow 4 -StartColumn 2 -NoHeader
$data | foreach { $_.psobject.Properties } | where Value -is string | foreach { $_.Value = $_.Value.Replace("`n",", ").Replace("&", "&") }

$data | ConvertTo-Csv -Delimiter "|" -NoTypeInformation | Select-Object -Skip 1 | Out-File new-test.csv
</code>```

Body:
Q: I want to convert excel to csv but the excel contains multiline data in a cell along with ";" as delimiter. The desired output is a csv file with "|" as separator for columns but "," as separator for data within same cell. I cannot use excel hence I am using the module "ImportExcel".

Input Excel Format (attached file at end of Question) :-

Row1# c1# c2#                    c3#         c4#
Row2#
Row3#
Row4#     HEADER1                HEADER2     HEADER3
Row5#     04.05 test & t     test        TEST
Row5#     04.06.01 test test                 TEST
Row5#     04.07.01 test test
Row5#     04.10.02 test & t

Row# represents the row of the excel and c# represent the column while HEADER# represent the title of the columns. As can be seen, ROW 1-3 and first column of the excel are empty. The text of second and fourth column is multiline but in the same cell(same row Row5).

I tried to Import the excel then for each object and replace the new line character with "," finally export it to csv using(export-csv) with "|" as delimiter.

The script I made is as follows :-

$test = Import-excel -NoHeader -StartRow(4) test.xlsx

$test | foreach-object {

if($_.HEADER1) {
$_.HEADER1 = $_.HEADER1.replace("\n",", ")
$_.HEADER1 = $_.HEADER1.replace("&","& ")
   }
}

$test | Export-csv new-test.csv -Delimiter '|' -NoTypeInformation

Output CSV FILE I GET :-

Row1# c1# c2#                       c3#
Row2#     HEADER1|HEADER2|HEADER3
Row3#     04.05 test &amp            t
Row4#     04.06.01 test test
Row5#     04.07.01 test test
Row6#     04.10.02 test &amp         t
Row7#     test|TEST
Row8#     TEST

As can be seen, the text after the delimeter ";" in the input goes to another column and the multiline is still parsed into separate rows. I want all this multiline to be merged into one with "," as separator along with the text after the "';" delimeter.

Desired CSV FILE :-

Row1# c1# c2#
Row2#     HEADER1|HEADER2|HEADER3
Row3#     04.05 test &  t,04.06.01 test test,04.07.01 test test,04.10.02 test & t|test|TEST,TEST

I have tried a lot of questions from stackoverflow related to this but for some reason none of the existing solution seems to be working for me.

Attached is the sample Excel file I am trying to convert. test.xlsx

Body:
The problem with your code is that you specify the -NoHeader parameter.

and you have to specify `n instead of \n as a newline character in Replace() method.

$test = Import-Excel test.xlsx -StartRow 4
$test | ForEach-Object {
    if($_.HEADER1) {
        $_.HEADER1 = $_.HEADER1.Replace("`n", ", ")
        $_.HEADER1 = $_.HEADER1.Replace("&amp;", "&")
    }
    if($_.HEADER3) {
        $_.HEADER3 = $_.HEADER3.Replace("`n", ", ")
    }
}

$test | Export-Csv new-test.csv -Delimiter "|" -NoTypeInformation

the output:

"HEADER1"|"HEADER2"|"HEADER3"
"04.05 test & t, 04.06.01 test test, 04.10.02 test & t, 04.07.01 test test"|"test"|"TEST, TEST"

It is useful to use the $obj.psobject.Properties property to replace the values of all properties.

# import
$data = Import-Excel test.xlsx -StartRow 4

# replace the values of all properties
$data | ForEach-Object { $_.psobject.Properties } | Where-Object Value -is string |
ForEach-Object { $_.Value = $_.Value.Replace("`n",", ").Replace("&amp;", "&") }

# export
$data | Export-Csv new-test.csv -Delimiter "|" -NoTypeInformation

If you want to insert empty rows and columns, add them after converting by ConvertTo-CSV.

$data | ConvertTo-Csv -Delimiter "|" -NoTypeInformation | ForEach-Object { "" } { "|" + $_ } | Out-File new-test.csv

the output:

|"HEADER1"|"HEADER2"|"HEADER3"
|"04.05 test & t, 04.06.01 test test, 04.10.02 test & t, 04.07.01 test test"|"test"|"TEST, TEST"

If the headers are duplicated, the -NoHeader parameter is required. And remove the automatically attached headers before saving.

$data = Import-Excel test.xlsx -StartRow 4 -StartColumn 2 -NoHeader
$data | foreach { $_.psobject.Properties } | where Value -is string | foreach { $_.Value = $_.Value.Replace("`n",", ").Replace("&amp;", "&") }

$data | ConvertTo-Csv -Delimiter "|" -NoTypeInformation | Select-Object -Skip 1 | Out-File new-test.csv


问:
Why does error ';' expected occur in my app.js file when no semi-colon should be necessary?
I'm creating a Chrome extension with React which uses an Airtable database, copying code verbatim from a tutorial.  In my app.js, I am following directions for adding a method called 'componentDidMount' underneath a constructor method, which calls the Airtable API to get the data values from it.

I'm receiving an error on the opening curly brace in the first line:

```<code>componentDidMount() {
  fetch('https://api.airtable.com/v0/app172rHs45CgT8UH/Favorites? api_key=YOUR_API_KEY')
  .then((resp) => resp.json())
  .then(data => {
     this.setState({ movies: data.records });
  }).catch(err => {

  });
}
</code>```

The exact error is ';' expected. ts(1005)

I copied the code line for line from the tutorial and have set up my Airtable. I've also pasted my unique ID key, so I'm confused as to why this error occurs. I figure the problem is not really the semi-colon, because I've tried adding one and it still throws that error. I've included a screenshot of the code that comes immediately before and after the problem line, as well as the relevant section of the tutorial.

Here is the tutorial link, though of course I wouldn't expect anyone to actually read it.  If it's helpful to see context, this part of the tutorial is just past the halfway point, under the heading: "Integrating React and Airtable"

https://upmostly.com/tutorials/create-simple-web-app-react-airtable/#introduction

I'd appreciate if anyone could tell me what may be going on. My understanding of this particular code is not very strong yet, as I'm just trying to complete the tutorial and understand each part of it.

If there is other information/code you need in order to know what is wrong, please let me know. Thank you so much!

答:
Method componentDidMount() should go inside the class App (where the constructor is):

```<code>class App extends Component {

    constructor(props) {
        super(props);
        this.state = {
          movies: [],
        };
    }

    componentDidMount() {
        fetch('https://api.airtable.com/v0/appgOPm5an5ZzNvkk/favorites?api_key=YOUR_API_KEY')
        .then((resp) => resp.json())
        .then(data => {
           this.setState({ movies: data.records });
        }).catch(err => {
            // Error
        });
    }
}
</code>```

This makes componentDidMount() a member method of class App. Classes are a way to logically group related methods and variables together into a single object.

Just adding function fixes the syntax error, but does not remove the underlying problem: your program will not behave in the way expected! In this case, React will be looking for a method componentDidMount() in your App class. Since React can't find it, your code will not be executed; the default behavior will run instead.

Some tips for how to recognize componentDidMount() should be wrapped inside a class:

componentDidMount() looks like a function, but there is no function keyword. Methods in classes are allowed to omit the function keyword.

componentDidMount() is indented. This is a convention for indicating the code is inside a code block.

The ... ellipses before and after componentDidMount() indicate code has been "hidden." If you're following that tutorial, this should make you wonder what code should come after componentDidMount(). The ... ellipses in the previous code snippet hint that something should be inserted there.

A basic understanding of JavaScript classes will also help a lot. Here are two good resources. A short reference and a detailed excerpt from a great book on JavaScript:

The Secret Life of Objects, Eloquent JavaScript

Classes reference on MDN

BTW, componentDidMount() is part of the React API.

Body:
I'm creating a Chrome extension with React which uses an Airtable database, copying code verbatim from a tutorial.  In my app.js, I am following directions for adding a method called 'componentDidMount' underneath a constructor method, which calls the Airtable API to get the data values from it.

I'm receiving an error on the opening curly brace in the first line:

componentDidMount() {
  fetch('https://api.airtable.com/v0/app172rHs45CgT8UH/Favorites? api_key=YOUR_API_KEY')
  .then((resp) => resp.json())
  .then(data => {
     this.setState({ movies: data.records });
  }).catch(err => {

  });
}

The exact error is ';' expected. ts(1005)

I copied the code line for line from the tutorial and have set up my Airtable. I've also pasted my unique ID key, so I'm confused as to why this error occurs. I figure the problem is not really the semi-colon, because I've tried adding one and it still throws that error. I've included a screenshot of the code that comes immediately before and after the problem line, as well as the relevant section of the tutorial.

Here is the tutorial link, though of course I wouldn't expect anyone to actually read it.  If it's helpful to see context, this part of the tutorial is just past the halfway point, under the heading: "Integrating React and Airtable"

https://upmostly.com/tutorials/create-simple-web-app-react-airtable/#introduction

I'd appreciate if anyone could tell me what may be going on. My understanding of this particular code is not very strong yet, as I'm just trying to complete the tutorial and understand each part of it.

If there is other information/code you need in order to know what is wrong, please let me know. Thank you so much!

Body:
Method componentDidMount() should go inside the class App (where the constructor is):

class App extends Component {

    constructor(props) {
        super(props);
        this.state = {
          movies: [],
        };
    }

    componentDidMount() {
        fetch('https://api.airtable.com/v0/appgOPm5an5ZzNvkk/favorites?api_key=YOUR_API_KEY')
        .then((resp) => resp.json())
        .then(data => {
           this.setState({ movies: data.records });
        }).catch(err => {
            // Error
        });
    }
}

This makes componentDidMount() a member method of class App. Classes are a way to logically group related methods and variables together into a single object.

Just adding function fixes the syntax error, but does not remove the underlying problem: your program will not behave in the way expected! In this case, React will be looking for a method componentDidMount() in your App class. Since React can't find it, your code will not be executed; the default behavior will run instead.

Some tips for how to recognize componentDidMount() should be wrapped inside a class:

componentDidMount() looks like a function, but there is no function keyword. Methods in classes are allowed to omit the function keyword.

componentDidMount() is indented. This is a convention for indicating the code is inside a code block.

The ... ellipses before and after componentDidMount() indicate code has been "hidden." If you're following that tutorial, this should make you wonder what code should come after componentDidMount(). The ... ellipses in the previous code snippet hint that something should be inserted there.

A basic understanding of JavaScript classes will also help a lot. Here are two good resources. A short reference and a detailed excerpt from a great book on JavaScript:

The Secret Life of Objects, Eloquent JavaScript

Classes reference on MDN

BTW, componentDidMount() is part of the React API.


问:
PostgreSQL JSON Querying
I have a JSON type column called "person" and the data stored in it is in the format

```<code>{
   "clients":{
      "nbr":"2",
      "info":[
         {
            "nom":"Baptiste",
            "genre":"male",
            "age":"48"
         },
         {
            "nom":"Lisa",
            "genre":"female",
            "age":"29"
         }
      ]
   }
}
</code>```

I want to retrieve the names of clients.

答:
You may use json_array_elements

```<code>select json_array_elements(person->'clients'->'info')->>'nom'  as name
    from t;
</code>```

Title: PostgreSQL JSON Querying

Body:
I have a JSON type column called "person" and the data stored in it is in the format

{
   "clients":{
      "nbr":"2",
      "info":[
         {
            "nom":"Baptiste",
            "genre":"male",
            "age":"48"
         },
         {
            "nom":"Lisa",
            "genre":"female",
            "age":"29"
         }
      ]
   }
}

I want to retrieve the names of clients.

Body:
You may use json_array_elements

select json_array_elements(person->'clients'->'info')->>'nom'  as name
    from t;


问:
How to add items into two tables in the same express function (mysql)
I'm creating a cart for a virtual store, and when pressing "submit" button I need to insert the order into the "order" table and the items into the "orderitems" table.

I've been using express to insert things in only one table each function, but now I need to put both in the same... I'm trying to do it with promisses.

This is my html:

                    Product name
                    Price
                    Quantity

                    {{product.name}}
                    {{product.price | currency}}
                    <input type="text" class="input-group-text" v-model="product.quantity">

                    Frete: {{fare | currency}}

                    Total: {{total | currency}}

        <button class="btn btn-info" @click="registerTransaction()">Submit cart</button>
```

<p>this is the function I call:</p>

```registerTransaction(){
            const date = new Date()
            const dateTime = {
                day: date.getUTCDate(),
                month: date.getUTCMonth(),
                year: date.getUTCFullYear(),
                hour: date.getUTCHours() - 3,
                minute: date.getUTCMinutes(),
                sec: date.getUTCSeconds()
            }
            const transaction = {
                date: new Date(`${dateTime.year}-${dateTime.month}-${dateTime.day}T${dateTime.hour}:${dateTime.minute}:${dateTime.sec}Z`)
            }
            transaction.userid = 1
            transaction.fare = parseFloat(this.fare)
            transaction.total = parseFloat(this.total)
            transaction.cart = this.cart

            axios.post(`${baseApiUrl}/checkout`, transaction)
                .then(() => this.$toasted.global.defaultSuccess())
                .catch(showError)
        }
```

<p>and this is my backend for axios:</p>

```const save = (req, res) =>{
        const transaction = {...req.body}

        try{
            existsOrError(transaction.date, "Error: transaction date is invalid")
            existsOrError(transaction.userid, "Error in the user authentication")
            //existsOrError(transaction.fare, "Error in calculating the fare")
            existsOrError(transaction.total, "Error in the total value")
        }
        catch(msg){
            return res.status(400).send(msg)
        }

        app.db('orders')
            .insert(transaction)
            .then(console.log('feito!'))
            .then(saveProducts(transaction))
            .catch(err => res.status(500).send(err))

    }

    const saveProducts = (transaction) => {
        const orderId = app.db(`orders`).select(`idOrder`) .where({idClient: transaction.userid}).last()
        console.log('Done')
        for(let i = 0; i < transaction.cart.length; i++){
            quantity = app.db('products').select('quantity').where({id: transaction.cart[i].id}).first()
            quantity -= transaction.cart[i].quantity
            app.db('products').update(quantity).where({id: transaction.cart[i].id})
            const orderedProduct = {idOrder: parseInt(orderId), idProduct: parseInt(transaction.cart[i].id), quantity: parseInt(transaction.cart[i].quantity)}
            app.db('orderedproducts').insert(orderedProduct).then(console.log('produto inserido')).catch(err => res.status(500).send(err))
        }
        return
    }
```

I expected it to save first my order, call the saveProducts function to save the products in it, and return, but it's returning a error as if it's not allowed to do...

答:
I went through the documentation and found the folllowing, which basically means that query methods has a promise interface meaning we can attach a then and catch method. It also means that we can use async/await on it.

```<code>knex.select('*')
  .from('users')
  .where({name: 'Tim'})
  .then(function(rows) {
    return knex.insert({user_id: rows[0].id, name: 'Test'}, 'id').into('accounts');
  })
  .then(function(id) {
    console.log('Inserted Account ' + id);
  })
  .catch(function(error) { console.error(error); });
</code>```

For your code I have added async/await, if you like you can use then method.

```<code>const save = (req, res) => {
  const transaction = { ...req.body };

  try {
    existsOrError(transaction.date, "Error: transaction date is invalid");
    existsOrError(transaction.userid, "Error in the user authentication");
    //existsOrError(transaction.fare, "Error in calculating the fare")
    existsOrError(transaction.total, "Error in the total value");
  } catch (msg) {
    return res.status(400).send(msg);
  }

  try {
    let orderId = await app
      .db("orders")
      .insert(transaction);
    console.log('order inserted :' + orderId);

    await saveProducts(transaction);
    console.log("saved all the products");
  } catch(err) {
    console.log(err);
  }
};

const saveProducts = async transaction => {
  const orderId = await app
    .db(`orders`)
    .select(`idOrder`)
    .where({ idClient: transaction.userid })
    .last();
  console.log("orderId : " + orderId);
  let quantity;
  for (let i = 0; i < transaction.cart.length; i++) {
    quantity = await app
      .db("products")
      .select("quantity")
      .where({ id: transaction.cart[i].id })
      .first();
    quantity -= transaction.cart[i].quantity;
    await app
      .db("products")
      .update(quantity)
      .where({ id: transaction.cart[i].id });
    const orderedProduct = {
      idOrder: parseInt(orderId),
      idProduct: parseInt(transaction.cart[i].id),
      quantity: parseInt(transaction.cart[i].quantity)
    };
    let insertedId = await app
      .db("orderedproducts")
      .insert(orderedProduct)
      .catch(err => res.status(500).send(err));
    console.log("inserted ordered product");
  }
  return;
};
</code>```

NOTE:  I have not executed the code so I can't guarantee that it will
  work the way you want it to be, but I am sure this will give you an
  idea how to move forward.

Body:
I'm creating a cart for a virtual store, and when pressing "submit" button I need to insert the order into the "order" table and the items into the "orderitems" table.

I've been using express to insert things in only one table each function, but now I need to put both in the same... I'm trying to do it with promisses.

This is my html:

                    Product name
                    Price
                    Quantity

                    {{product.name}}
                    {{product.price | currency}}
                    <input type="text" class="input-group-text" v-model="product.quantity">

                    Frete: {{fare | currency}}

                    Total: {{total | currency}}

        <button class="btn btn-info" @click="registerTransaction()">Submit cart</button>

this is the function I call:

registerTransaction(){
            const date = new Date()
            const dateTime = {
                day: date.getUTCDate(),
                month: date.getUTCMonth(),
                year: date.getUTCFullYear(),
                hour: date.getUTCHours() - 3,
                minute: date.getUTCMinutes(),
                sec: date.getUTCSeconds()
            }
            const transaction = {
                date: new Date(`${dateTime.year}-${dateTime.month}-${dateTime.day}T${dateTime.hour}:${dateTime.minute}:${dateTime.sec}Z`)
            }
            transaction.userid = 1
            transaction.fare = parseFloat(this.fare)
            transaction.total = parseFloat(this.total)
            transaction.cart = this.cart

            axios.post(`${baseApiUrl}/checkout`, transaction)
                .then(() => this.$toasted.global.defaultSuccess())
                .catch(showError)
        }

and this is my backend for axios:

const save = (req, res) =>{
        const transaction = {...req.body}

        try{
            existsOrError(transaction.date, "Error: transaction date is invalid")
            existsOrError(transaction.userid, "Error in the user authentication")
            //existsOrError(transaction.fare, "Error in calculating the fare")
            existsOrError(transaction.total, "Error in the total value")
        }
        catch(msg){
            return res.status(400).send(msg)
        }

        app.db('orders')
            .insert(transaction)
            .then(console.log('feito!'))
            .then(saveProducts(transaction))
            .catch(err => res.status(500).send(err))

    }

    const saveProducts = (transaction) => {
        const orderId = app.db(`orders`).select(`idOrder`) .where({idClient: transaction.userid}).last()
        console.log('Done')
        for(let i = 0; i < transaction.cart.length; i++){
            quantity = app.db('products').select('quantity').where({id: transaction.cart[i].id}).first()
            quantity -= transaction.cart[i].quantity
            app.db('products').update(quantity).where({id: transaction.cart[i].id})
            const orderedProduct = {idOrder: parseInt(orderId), idProduct: parseInt(transaction.cart[i].id), quantity: parseInt(transaction.cart[i].quantity)}
            app.db('orderedproducts').insert(orderedProduct).then(console.log('produto inserido')).catch(err => res.status(500).send(err))
        }
        return
    }

I expected it to save first my order, call the saveProducts function to save the products in it, and return, but it's returning a error as if it's not allowed to do...

Body:
I went through the documentation and found the folllowing, which basically means that query methods has a promise interface meaning we can attach a then and catch method. It also means that we can use async/await on it.

knex.select('*')
  .from('users')
  .where({name: 'Tim'})
  .then(function(rows) {
    return knex.insert({user_id: rows[0].id, name: 'Test'}, 'id').into('accounts');
  })
  .then(function(id) {
    console.log('Inserted Account ' + id);
  })
  .catch(function(error) { console.error(error); });

For your code I have added async/await, if you like you can use then method.

const save = (req, res) => {
  const transaction = { ...req.body };

  try {
    existsOrError(transaction.date, "Error: transaction date is invalid");
    existsOrError(transaction.userid, "Error in the user authentication");
    //existsOrError(transaction.fare, "Error in calculating the fare")
    existsOrError(transaction.total, "Error in the total value");
  } catch (msg) {
    return res.status(400).send(msg);
  }

  try {
    let orderId = await app
      .db("orders")
      .insert(transaction);
    console.log('order inserted :' + orderId);

    await saveProducts(transaction);
    console.log("saved all the products");
  } catch(err) {
    console.log(err);
  }
};

const saveProducts = async transaction => {
  const orderId = await app
    .db(`orders`)
    .select(`idOrder`)
    .where({ idClient: transaction.userid })
    .last();
  console.log("orderId : " + orderId);
  let quantity;
  for (let i = 0; i < transaction.cart.length; i++) {
    quantity = await app
      .db("products")
      .select("quantity")
      .where({ id: transaction.cart[i].id })
      .first();
    quantity -= transaction.cart[i].quantity;
    await app
      .db("products")
      .update(quantity)
      .where({ id: transaction.cart[i].id });
    const orderedProduct = {
      idOrder: parseInt(orderId),
      idProduct: parseInt(transaction.cart[i].id),
      quantity: parseInt(transaction.cart[i].quantity)
    };
    let insertedId = await app
      .db("orderedproducts")
      .insert(orderedProduct)
      .catch(err => res.status(500).send(err));
    console.log("inserted ordered product");
  }
  return;
};

NOTE:  I have not executed the code so I can't guarantee that it will
  work the way you want it to be, but I am sure this will give you an
  idea how to move forward.


问:
How to create a regular expression to find out repeated character in string?
Eg:

HelloWorld - repeated characters are 5 (l is repeating 3 times and o is repeating 2 times)

Smart2000,  repeated characters = 3?(0 is repeating 3 times)

Smart@200@12, repeated characters = 6

I tried with iterating over string

Here is my code with string iteration to find out the repeated character in string.

```<code>func countRepeatDigitsIn(keyword : String) -> Int
{
    // To keep track of processed symbols
    var uniqueCharacters = ""
    var repeatCharacterCount = 0

    for char in keyword.uppercased() {
        let alphabet = String(char)

        // If this is already counted, skip it
        if (uniqueCharacters.contains(alphabet))
        {
            repeatCharacterCount += 1
        }

        // Otherwise, add it to processed symbols
        uniqueCharacters += alphabet
    }

    return repeatCharacterCount
}
</code>```

答:
HelloWorld - repeated characters are 5 (l is repeating 3 times and o is repeating 2 times

The simplest way to get that result is to take a histogram and then add up all the values that are not 1.

Example:

```<code>func histogram(_ s:String) -> [Character:Int] {
    var d = [Character:Int]()
    for c in s {
        d[c, default:0] += 1
    }
    return d
}
let reps = histogram("helloworld").values.filter{$0 > 1}.reduce(0, +) // 5
let reps2 = histogram("smart2000").values.filter{$0 > 1}.reduce(0, +) // 3
let reps3 = histogram("Smart@200@12").values.filter{$0 > 1}.reduce(0, +) // 6
</code>```

Body:
Eg:

HelloWorld - repeated characters are 5 (l is repeating 3 times and o is repeating 2 times)

Smart2000,  repeated characters = 3?(0 is repeating 3 times)

Smart@200@12, repeated characters = 6

I tried with iterating over string

Here is my code with string iteration to find out the repeated character in string.

func countRepeatDigitsIn(keyword : String) -> Int
{
    // To keep track of processed symbols
    var uniqueCharacters = ""
    var repeatCharacterCount = 0

    for char in keyword.uppercased() {
        let alphabet = String(char)

        // If this is already counted, skip it
        if (uniqueCharacters.contains(alphabet))
        {
            repeatCharacterCount += 1
        }

        // Otherwise, add it to processed symbols
        uniqueCharacters += alphabet
    }

    return repeatCharacterCount
}

Body:
HelloWorld - repeated characters are 5 (l is repeating 3 times and o is repeating 2 times

The simplest way to get that result is to take a histogram and then add up all the values that are not 1.

Example:

func histogram(_ s:String) -> [Character:Int] {
    var d = [Character:Int]()
    for c in s {
        d[c, default:0] += 1
    }
    return d
}
let reps = histogram("helloworld").values.filter{$0 > 1}.reduce(0, +) // 5
let reps2 = histogram("smart2000").values.filter{$0 > 1}.reduce(0, +) // 3
let reps3 = histogram("Smart@200@12").values.filter{$0 > 1}.reduce(0, +) // 6


问:
Why only the first row is read by the CSV Helper using ASP.Net MVC?
I have a problem when reading a CSV file using CSVHelper because it only returns the first row of the csv with the header.

I've used this code on reading the CSV file.

```<code> using (var reader = new StreamReader(filePath))
 using (var csv = new CsvReader(reader))
 {
     csv.Configuration.RegisterClassMap<FundTransferMapSingle>();
     var json = JsonConvert.SerializeObject(csv.GetRecords<FundTransferSingle>());
 }
</code>```

I've used some mapping for this

```<code>public class FundTransferMapSingle : ClassMap<FundTransferSingle>
    {
        public FundTransferMapSingle()
        {
            Map(m => m.senderRefId).Name("senderRefId");
            Map(m => m.transRequestDate).Name("transRequestDate");
            Map(m => m.particulars).Name("particulars");

            Map(m => m.sender).ConvertUsing(row =>
            {
                var senderlist = new List<Sender>
                {
                    new Sender { name = row.GetField("senderName"),
                                 address = new List<Address>
                                    {
                                        new Address {line1 = row.GetField("senderAddrLine1"),
                                            line2 = row.GetField("senderAddrLine2"),
                                            city = row.GetField("senderAddrCity"),
                                            province = row.GetField("senderProvince"),
                                            zipCode = row.GetField("senderAddrZipcode"),
                                            country = row.GetField("senderAddrCountry")}
                                    }
                               }
                };
                return senderlist;
            });

}
</code>```

This is the CSV file that I'm reading

```<code>senderRefId,transRequestDate,particulars,senderName,senderAddrLine1
TRANSFER0001,2018-08-10T08:40:45.897,particulars,Name1,Address1
TRANSFER0002,2018-08-10T08:40:45.897,particulars,Name2,Address2
</code>```

I get the result through my variable json.

答:
Try to load the data into a DataTable using CsvReader:

```<code>DataTable csvTable = new DataTable();
using (CsvReader csvReader = new CsvReader(new StreamReader(stream), true))
{
    csvTable.Load(csvReader);
}
</code>```

Then get the json from the DataTable:

```<code>using Newtonsoft.JSON;

public string DataTableToJSONWithJSONNet(DataTable table) {
   string JSONString=string.Empty;
   JSONString = JSONConvert.SerializeObject(table);
   return JSONString;
}
</code>```

Body:
I have a problem when reading a CSV file using CSVHelper because it only returns the first row of the csv with the header.

I've used this code on reading the CSV file.

 using (var reader = new StreamReader(filePath))
 using (var csv = new CsvReader(reader))
 {
     csv.Configuration.RegisterClassMap<FundTransferMapSingle>();
     var json = JsonConvert.SerializeObject(csv.GetRecords<FundTransferSingle>());
 }

I've used some mapping for this

public class FundTransferMapSingle : ClassMap<FundTransferSingle>
    {
        public FundTransferMapSingle()
        {
            Map(m => m.senderRefId).Name("senderRefId");
            Map(m => m.transRequestDate).Name("transRequestDate");
            Map(m => m.particulars).Name("particulars");

            Map(m => m.sender).ConvertUsing(row =>
            {
                var senderlist = new List<Sender>
                {
                    new Sender { name = row.GetField("senderName"),
                                 address = new List<Address>
                                    {
                                        new Address {line1 = row.GetField("senderAddrLine1"),
                                            line2 = row.GetField("senderAddrLine2"),
                                            city = row.GetField("senderAddrCity"),
                                            province = row.GetField("senderProvince"),
                                            zipCode = row.GetField("senderAddrZipcode"),
                                            country = row.GetField("senderAddrCountry")}
                                    }
                               }
                };
                return senderlist;
            });

}

This is the CSV file that I'm reading

senderRefId,transRequestDate,particulars,senderName,senderAddrLine1
TRANSFER0001,2018-08-10T08:40:45.897,particulars,Name1,Address1
TRANSFER0002,2018-08-10T08:40:45.897,particulars,Name2,Address2

I get the result through my variable json.

Body:
Try to load the data into a DataTable using CsvReader:

DataTable csvTable = new DataTable();
using (CsvReader csvReader = new CsvReader(new StreamReader(stream), true))
{
    csvTable.Load(csvReader);
}

Then get the json from the DataTable:

using Newtonsoft.JSON;

public string DataTableToJSONWithJSONNet(DataTable table) {
   string JSONString=string.Empty;
   JSONString = JSONConvert.SerializeObject(table);
   return JSONString;
}


问:
How to convert month name to number in unix?
Input :

```<code>01-DEC-18|"0308"|"RUB"
01-DEC-18|"0308"|"RUB"
01-DEC-18|"0308"|"RUB"
01-DEC-18|"0308"|"RUB"
</code>```

Expected output :

```<code>01-12-18|"0308"|"RUB"
01-12-18|"0308"|"RUB"
01-12-18|"0308"|"RUB"
01-12-18|"0308"|"RUB"
</code>```

How do I convert the abbreviated month name to month number and achieve the expected output?

答:
Using GNU awk (easily converted to other awks by ditching strftile() and related (ie. lines 3-5) and defining m["JAN"]="01";m["FEB"]="02";etc.):

```<code>$ awk 'BEGIN {                                             # prime a hash for month abbr.
    FS=OFS="-"                                             # split at -
    Ms=28*24*60*60                                         # "month seconds"
    for(t=1;t<=12;t++)                                     # iterate all month numbers
        m[toupper(strftime("%b",t*Ms))]=sprintf("%02d",t)  # hash m["JAN"]="01"
}
{
    $2=m[$2]                                               # retrieve month # from hash
}1' file                                                   # output
</code>```

Output with your data:

```<code>01-12-18|"0308"|"RUB"
01-12-18|"0308"|"RUB"
01-12-18|"0308"|"RUB"
01-12-18|"0308"|"RUB"
</code>```

For a million records of your data this script ran 1.7 s:

```<code>real    0m1.719s
user    0m1.688s
sys     0m0.032s
</code>```

Body:
Input :

01-DEC-18|"0308"|"RUB"
01-DEC-18|"0308"|"RUB"
01-DEC-18|"0308"|"RUB"
01-DEC-18|"0308"|"RUB"

Expected output :

01-12-18|"0308"|"RUB"
01-12-18|"0308"|"RUB"
01-12-18|"0308"|"RUB"
01-12-18|"0308"|"RUB"

How do I convert the abbreviated month name to month number and achieve the expected output?

Body:
Using GNU awk (easily converted to other awks by ditching strftile() and related (ie. lines 3-5) and defining m["JAN"]="01";m["FEB"]="02";etc.):

$ awk 'BEGIN {                                             # prime a hash for month abbr.
    FS=OFS="-"                                             # split at -
    Ms=28*24*60*60                                         # "month seconds"
    for(t=1;t<=12;t++)                                     # iterate all month numbers
        m[toupper(strftime("%b",t*Ms))]=sprintf("%02d",t)  # hash m["JAN"]="01"
}
{
    $2=m[$2]                                               # retrieve month # from hash
}1' file                                                   # output

Output with your data:

01-12-18|"0308"|"RUB"
01-12-18|"0308"|"RUB"
01-12-18|"0308"|"RUB"
01-12-18|"0308"|"RUB"

For a million records of your data this script ran 1.7 s:

real    0m1.719s
user    0m1.688s
sys     0m0.032s


问:
Ionic 4 change ion-tab-button with custom icon
I'm trying to change ion-icon with custom src after ion-tab-button is clicked

What I have tried, using (click) event to trigger function and change the [src]="..." inside the ion-icon

Is there any proper way to change this hackish style?

HTML:

```<code> <ion-tabs>
  <ion-tab-bar slot="bottom">
    <ion-tab-button tab="news/home" (click)="changeNewsIcon()">
      <ion-icon [src]="newsIcon"></ion-icon>
      <ion-label class="tab-title">News</ion-label>
    </ion-tab-button>
    <ion-tab-button tab="user" (click)="changeSearchIcon()">
      <ion-icon [src]="searchIcon"></ion-icon>
      <ion-label class="tab-title">Search</ion-label>
    </ion-tab-button>
    <ion-tab-button tab="networking" (click)="changeNetworkIcon()">
      <ion-icon [src]="notiIcon"></ion-icon>
      <ion-label class="tab-title">Networking</ion-label>
    </ion-tab-button>
    <ion-tab-button tab="chat" (click)="changeChatIcon()">
      <ion-icon [src]="chatIcon"></ion-icon>
      <ion-label class="tab-title">Chat</ion-label>
    </ion-tab-button>
    <ion-tab-button tab="profile" (click)="changeProfIcon()">
      <ion-icon [src]="profIcon"></ion-icon>
      <ion-label class="tab-title">Profile</ion-label>
    </ion-tab-button>
  </ion-tab-bar>
</ion-tabs>
</code>```

TS :

```<code>newsIcon = './assets/tabs/home.svg';
searchIcon = './assets/tabs/search.svg';
notiIcon = './assets/tabs/group.svg';
chatIcon = './assets/tabs/chat.svg';
profIcon = './assets/tabs/user.svg';

changeNewsIcon(): void {
  // change news icon
  this.newsIcon = './assets/tabs/clicked-home.svg';

  // reset others icon
  this.searchIcon = './assets/tabs/search.svg';
  this.notiIcon = './assets/tabs/group.svg';
  this.chatIcon = './assets/tabs/chat.svg';
  this.profIcon = './assets/tabs/user.svg';
}

changeSearchIcon(): void {
  // change user icon
  this.searchIcon = './assets/tabs/clicked-search.svg';

  // reset others icon
  this.newsIcon = './assets/tabs/home.svg';
  this.notiIcon = './assets/tabs/group.svg';
  this.chatIcon = './assets/tabs/chat.svg';
  this.profIcon = './assets/tabs/user.svg';
}

...
</code>```

Appreciate if anyone would help

答:
I am not sure that my approach is better, but this could be another way of doing the same thing.

HTML:

```<code><ion-tabs>
    <ion-tab-bar slot="bottom">
      <ion-tab-button tab="news/home" (click)="changeNewsIcon()">
        <ion-icon [src]="isNewsSelected ? newsIcon : clickedNewsIcon"></ion-icon>
        <ion-label class="tab-title">News</ion-label>
      </ion-tab-button>
      <ion-tab-button tab="user" (click)="changeSearchIcon()">
        <ion-icon [src]="isSearchSelected ? searchIcon clickedSearchIcon"></ion-icon>
        <ion-label class="tab-title">Search</ion-label>
      </ion-tab-button>
    </ion-tab-bar>
</ion-tabs>
</code>```

TypeScript Component:

```<code>export class SomeComponent {

  newsIcon = './assets/tabs/home.svg';
  clickedNewsIcon = './assets/tabs/clicked-home.svg';
  searchIcon = './assets/tabs/search.svg';
  clickedSsearchIcon = './assets/tabs/clicked-search.svg';

  isNewsSelected = false;
  isSearchSelected= false;

  changeNewsIcon(): void {
    resetAll();
    this.isNewsSelected = true;
  }

  changeSearchIcon(): void {
   resetAll();
   this.isSearchSelected = true;
  }

  resetAll(){
    this.isNewsSelected = false;
    this.isSearchSelected= false;
  }
}
</code>```

Body:
I'm trying to change ion-icon with custom src after ion-tab-button is clicked

What I have tried, using (click) event to trigger function and change the [src]="..." inside the ion-icon

Is there any proper way to change this hackish style?

HTML:

 <ion-tabs>
  <ion-tab-bar slot="bottom">
    <ion-tab-button tab="news/home" (click)="changeNewsIcon()">
      <ion-icon [src]="newsIcon"></ion-icon>
      <ion-label class="tab-title">News</ion-label>
    </ion-tab-button>
    <ion-tab-button tab="user" (click)="changeSearchIcon()">
      <ion-icon [src]="searchIcon"></ion-icon>
      <ion-label class="tab-title">Search</ion-label>
    </ion-tab-button>
    <ion-tab-button tab="networking" (click)="changeNetworkIcon()">
      <ion-icon [src]="notiIcon"></ion-icon>
      <ion-label class="tab-title">Networking</ion-label>
    </ion-tab-button>
    <ion-tab-button tab="chat" (click)="changeChatIcon()">
      <ion-icon [src]="chatIcon"></ion-icon>
      <ion-label class="tab-title">Chat</ion-label>
    </ion-tab-button>
    <ion-tab-button tab="profile" (click)="changeProfIcon()">
      <ion-icon [src]="profIcon"></ion-icon>
      <ion-label class="tab-title">Profile</ion-label>
    </ion-tab-button>
  </ion-tab-bar>
</ion-tabs>

TS :

newsIcon = './assets/tabs/home.svg';
searchIcon = './assets/tabs/search.svg';
notiIcon = './assets/tabs/group.svg';
chatIcon = './assets/tabs/chat.svg';
profIcon = './assets/tabs/user.svg';

changeNewsIcon(): void {
  // change news icon
  this.newsIcon = './assets/tabs/clicked-home.svg';

  // reset others icon
  this.searchIcon = './assets/tabs/search.svg';
  this.notiIcon = './assets/tabs/group.svg';
  this.chatIcon = './assets/tabs/chat.svg';
  this.profIcon = './assets/tabs/user.svg';
}

changeSearchIcon(): void {
  // change user icon
  this.searchIcon = './assets/tabs/clicked-search.svg';

  // reset others icon
  this.newsIcon = './assets/tabs/home.svg';
  this.notiIcon = './assets/tabs/group.svg';
  this.chatIcon = './assets/tabs/chat.svg';
  this.profIcon = './assets/tabs/user.svg';
}

...

Appreciate if anyone would help

Body:
I am not sure that my approach is better, but this could be another way of doing the same thing.

HTML:

<ion-tabs>
    <ion-tab-bar slot="bottom">
      <ion-tab-button tab="news/home" (click)="changeNewsIcon()">
        <ion-icon [src]="isNewsSelected ? newsIcon : clickedNewsIcon"></ion-icon>
        <ion-label class="tab-title">News</ion-label>
      </ion-tab-button>
      <ion-tab-button tab="user" (click)="changeSearchIcon()">
        <ion-icon [src]="isSearchSelected ? searchIcon clickedSearchIcon"></ion-icon>
        <ion-label class="tab-title">Search</ion-label>
      </ion-tab-button>
    </ion-tab-bar>
</ion-tabs>

TypeScript Component:

export class SomeComponent {

  newsIcon = './assets/tabs/home.svg';
  clickedNewsIcon = './assets/tabs/clicked-home.svg';
  searchIcon = './assets/tabs/search.svg';
  clickedSsearchIcon = './assets/tabs/clicked-search.svg';

  isNewsSelected = false;
  isSearchSelected= false;

  changeNewsIcon(): void {
    resetAll();
    this.isNewsSelected = true;
  }

  changeSearchIcon(): void {
   resetAll();
   this.isSearchSelected = true;
  }

  resetAll(){
    this.isNewsSelected = false;
    this.isSearchSelected= false;
  }
}