问:
JTable displays true/false instead of a CheckBox although "getColumnClass" is implemented
I have a JTable in which I want to display Boolean-values in form of CheckBoxes, which should be able to be edited (get checked/unchecked).

In order to accomplish that, I have implemented a subclass of AbstractTableModel with all needed methods, getColumnClass and isCellEditable implemented.

The problem is, that instead of a CheckBox, true/false is displayed. Only when I click on the cell, the getColumnClass-Method is called and the CheckBox appears for a short period of time.

I have found out, that the JTable never calls "getColumnClass" in the beginning but just when I want to click in the cell.

```<code>public class OrderTableModel extends AbstractTableModel {
    private ArrayList<Orders> orders;
    private final String[] HEADER = {"Date", "isParty", "isHost"};

public OrderTableModel(ArrayList<Orders> orders)
{
    this.orders = orders;
}

public OrderTableModel(){
    orders = new ArrayList<>();
}

@Override
public String getColumnName(int column) {
    return HEADER[column];
}

@Override
public int getRowCount() {
    return orders.size() > 20 ? orders.size() : 20;
}

@Override
public int getColumnCount() {
    return HEADER.length;
}

@Override
public Class<?> getColumnClass(int columnIndex) {
    System.out.println("in getColumnClass");
    switch(columnIndex)
    {
        case 1: return Boolean.class;
        case 2: return Boolean.class;
        default: return String.class;
    }

}

@Override
public boolean isCellEditable(int rowIndex, int columnIndex) {
    return true;
}

@Override
public Object getValueAt(int rowIndex, int columnIndex) {
    ...
}
</code>```

答:
For what it's worth, I created my own MRE using your code, but fleshing it out so that it compiles, and runs, and the code works as expected: JCheckBoxes are seen where you would expect to see them. Please test this yourself to see:

```<code>import java.awt.BorderLayout;
import java.util.ArrayList;
import java.util.Random;

import javax.swing.*;
import javax.swing.table.AbstractTableModel;

@SuppressWarnings("serial")
public class OrderTableFun  extends JPanel {
    private OrderTableModel model = new OrderTableModel();
    private JTable table = new JTable(model);

    public OrderTableFun() {
        Random random = new Random();
        for (int i = 0; i < 20; i++) {
            String name = "name " + i;
            boolean party = random.nextBoolean();
            boolean host = random.nextBoolean();
            Orders order = new Orders(name, party, host);
            model.addOrders(order);
        }

        setLayout(new BorderLayout());
        add(new JScrollPane(table));
    }

    private static void createAndShowGui() {
        OrderTableFun mainPanel = new OrderTableFun();

        JFrame frame = new JFrame("OrderTableFun");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(mainPanel);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> createAndShowGui());
    }
}
</code>```

```<code>@SuppressWarnings("serial")
class OrderTableModel extends AbstractTableModel {
    private ArrayList<Orders> orders;
    private final String[] HEADER = { "Date", "isParty", "isHost" };

    public OrderTableModel(ArrayList<Orders> orders) {
        this.orders = orders;
    }

    public OrderTableModel() {
        orders = new ArrayList<>();
    }

    @Override
    public String getColumnName(int column) {
        return HEADER[column];
    }

    @Override
    public int getRowCount() {
        // !! return orders.size() > 20 ? orders.size() : 20;
        return orders.size(); // !!
    }

    @Override
    public int getColumnCount() {
        return HEADER.length;
    }

    @Override
    public Class<?> getColumnClass(int columnIndex) {
        System.out.println("in getColumnClass");
        switch (columnIndex) {
        case 1:
            return Boolean.class;
        case 2:
            return Boolean.class;
        default:
            return String.class;
        }

    }

    @Override
    public boolean isCellEditable(int rowIndex, int columnIndex) {
        return true;
    }

    @Override
    public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
        Orders order = (Orders) orders.get(rowIndex);
        switch (columnIndex) {
        case 0:
            String name = (String) aValue;
            order.setName(name);
            break;
        case 1:
            Boolean party = (Boolean) aValue;
            order.setParty(party);
        case 2:
            Boolean host = (Boolean) aValue;
            order.setHost(host);
        }
        fireTableRowsUpdated(rowIndex, rowIndex);
    }

    public void addOrders(Orders order) {
        orders.add(order);
        fireTableRowsInserted(getRowCount() - 1, getRowCount());
    }

    @Override
    public Object getValueAt(int rowIndex, int columnIndex) {
        Orders order = (Orders) orders.get(rowIndex);
        switch (columnIndex) {
        case 0:
            return order.getName();
        case 1:
            return order.isParty();
        case 2:
            return order.isHost();

        default:
            return null;
        }
    }
}
</code>```

```<code>class Orders {
    String name;
    boolean party;
    boolean host;

    public Orders(String name, boolean party, boolean host) {
        this.name = name;
        this.party = party;
        this.host = host;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public boolean isParty() {
        return party;
    }

    public void setParty(boolean party) {
        this.party = party;
    }

    public boolean isHost() {
        return host;
    }

    public void setHost(boolean host) {
        this.host = host;
    }

}
</code>```

I've changed getRowCount to reflect the real number of Orders objects available.

Body:
I have a JTable in which I want to display Boolean-values in form of CheckBoxes, which should be able to be edited (get checked/unchecked).

In order to accomplish that, I have implemented a subclass of AbstractTableModel with all needed methods, getColumnClass and isCellEditable implemented.

The problem is, that instead of a CheckBox, true/false is displayed. Only when I click on the cell, the getColumnClass-Method is called and the CheckBox appears for a short period of time.

I have found out, that the JTable never calls "getColumnClass" in the beginning but just when I want to click in the cell.

public class OrderTableModel extends AbstractTableModel {
    private ArrayList<Orders> orders;
    private final String[] HEADER = {"Date", "isParty", "isHost"};

public OrderTableModel(ArrayList<Orders> orders)
{
    this.orders = orders;
}

public OrderTableModel(){
    orders = new ArrayList<>();
}

@Override
public String getColumnName(int column) {
    return HEADER[column];
}

@Override
public int getRowCount() {
    return orders.size() > 20 ? orders.size() : 20;
}

@Override
public int getColumnCount() {
    return HEADER.length;
}

@Override
public Class<?> getColumnClass(int columnIndex) {
    System.out.println("in getColumnClass");
    switch(columnIndex)
    {
        case 1: return Boolean.class;
        case 2: return Boolean.class;
        default: return String.class;
    }

}

@Override
public boolean isCellEditable(int rowIndex, int columnIndex) {
    return true;
}

@Override
public Object getValueAt(int rowIndex, int columnIndex) {
    ...
}

Body:
For what it's worth, I created my own MRE using your code, but fleshing it out so that it compiles, and runs, and the code works as expected: JCheckBoxes are seen where you would expect to see them. Please test this yourself to see:

import java.awt.BorderLayout;
import java.util.ArrayList;
import java.util.Random;

import javax.swing.*;
import javax.swing.table.AbstractTableModel;

@SuppressWarnings("serial")
public class OrderTableFun  extends JPanel {
    private OrderTableModel model = new OrderTableModel();
    private JTable table = new JTable(model);

    public OrderTableFun() {
        Random random = new Random();
        for (int i = 0; i < 20; i++) {
            String name = "name " + i;
            boolean party = random.nextBoolean();
            boolean host = random.nextBoolean();
            Orders order = new Orders(name, party, host);
            model.addOrders(order);
        }

        setLayout(new BorderLayout());
        add(new JScrollPane(table));
    }

    private static void createAndShowGui() {
        OrderTableFun mainPanel = new OrderTableFun();

        JFrame frame = new JFrame("OrderTableFun");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(mainPanel);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> createAndShowGui());
    }
}

@SuppressWarnings("serial")
class OrderTableModel extends AbstractTableModel {
    private ArrayList<Orders> orders;
    private final String[] HEADER = { "Date", "isParty", "isHost" };

    public OrderTableModel(ArrayList<Orders> orders) {
        this.orders = orders;
    }

    public OrderTableModel() {
        orders = new ArrayList<>();
    }

    @Override
    public String getColumnName(int column) {
        return HEADER[column];
    }

    @Override
    public int getRowCount() {
        // !! return orders.size() > 20 ? orders.size() : 20;
        return orders.size(); // !!
    }

    @Override
    public int getColumnCount() {
        return HEADER.length;
    }

    @Override
    public Class<?> getColumnClass(int columnIndex) {
        System.out.println("in getColumnClass");
        switch (columnIndex) {
        case 1:
            return Boolean.class;
        case 2:
            return Boolean.class;
        default:
            return String.class;
        }

    }

    @Override
    public boolean isCellEditable(int rowIndex, int columnIndex) {
        return true;
    }

    @Override
    public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
        Orders order = (Orders) orders.get(rowIndex);
        switch (columnIndex) {
        case 0:
            String name = (String) aValue;
            order.setName(name);
            break;
        case 1:
            Boolean party = (Boolean) aValue;
            order.setParty(party);
        case 2:
            Boolean host = (Boolean) aValue;
            order.setHost(host);
        }
        fireTableRowsUpdated(rowIndex, rowIndex);
    }

    public void addOrders(Orders order) {
        orders.add(order);
        fireTableRowsInserted(getRowCount() - 1, getRowCount());
    }

    @Override
    public Object getValueAt(int rowIndex, int columnIndex) {
        Orders order = (Orders) orders.get(rowIndex);
        switch (columnIndex) {
        case 0:
            return order.getName();
        case 1:
            return order.isParty();
        case 2:
            return order.isHost();

        default:
            return null;
        }
    }
}

class Orders {
    String name;
    boolean party;
    boolean host;

    public Orders(String name, boolean party, boolean host) {
        this.name = name;
        this.party = party;
        this.host = host;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public boolean isParty() {
        return party;
    }

    public void setParty(boolean party) {
        this.party = party;
    }

    public boolean isHost() {
        return host;
    }

    public void setHost(boolean host) {
        this.host = host;
    }

}

I've changed getRowCount to reflect the real number of Orders objects available.


来源: stackexchange

问:
I have 'expression changed after it has been checked error 'if I use *ngif, but it not appears if i use [hidden]
I have a big doubt, case 1 produces an error, but if I substitute case 2 does not fail.

Case 1:

```<code> <div class="col-8" *ngIf="customstreetType">
    <app-input-text
      [valueIn]="_address?.custom_street_type"
      (valueOut)="_address.custom_street_type = $event; change()"
    ></app-input-text>
  </div>
</code>```

Case 2:

```<code>  <div class="col-8" [hidden]="!customstreetType">
    <app-input-text
      [valueIn]="_address?.custom_street_type"
      (valueOut)="_address.custom_street_type = $event; change()"
    ></app-input-text>
  </div>
</code>```

Error:

```<code>DemandsActionAddressComponent.html:21 ERROR Error: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'ngIf: false'. Current value: 'ngIf: true'.
    at viewDebugError (core.js:7594)
    at expressionChangedAfterItHasBeenCheckedError (core.js:7582)
    at checkBindingNoChanges (core.js:7684)
    at checkNoChangesNodeInline (core.js:10545)
    at checkNoChangesNode (core.js:10534)
    at debugCheckNoChangesNode (core.js:11137)
    at debugCheckDirectivesFn (core.js:11065)
    at Object.eval [as updateDirectives] (DemandsActionAddressComponent.html:21)
    at Object.debugUpdateDirectives [as updateDirectives] (core.js:11054)
    at checkNoChangesView (core.js:10433)
</code>```

I don't understand why it is happening. *ngIf is more fast than [hidden] or something like this?

答:
ngIF:

yes! ngIF might be slow while adding removing elements to the DOM because of intializations

No DOM element is added if ngIf evaluates to false.

Hidden :

DOM element will be added to HTML

As the element is already added to DOM showing and hiding are very fast

ContentLicense: CC BY-SA 4.0

Body:
I have a big doubt, case 1 produces an error, but if I substitute case 2 does not fail.

Case 1:

    <app-input-text
      [valueIn]="_address?.custom_street_type"
      (valueOut)="_address.custom_street_type = $event; change()"
    ></app-input-text>

Case 2:

    <app-input-text
      [valueIn]="_address?.custom_street_type"
      (valueOut)="_address.custom_street_type = $event; change()"
    ></app-input-text>

Error:

DemandsActionAddressComponent.html:21 ERROR Error: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'ngIf: false'. Current value: 'ngIf: true'.
    at viewDebugError (core.js:7594)
    at expressionChangedAfterItHasBeenCheckedError (core.js:7582)
    at checkBindingNoChanges (core.js:7684)
    at checkNoChangesNodeInline (core.js:10545)
    at checkNoChangesNode (core.js:10534)
    at debugCheckNoChangesNode (core.js:11137)
    at debugCheckDirectivesFn (core.js:11065)
    at Object.eval [as updateDirectives] (DemandsActionAddressComponent.html:21)
    at Object.debugUpdateDirectives [as updateDirectives] (core.js:11054)
    at checkNoChangesView (core.js:10433)

I don't understand why it is happening. *ngIf is more fast than [hidden] or something like this?


问:
Find all rows in another sheet matching key
I have two sheets in my Excel workbook, one called Customer and the other called Product:

I wish to make a Lookup table in the Customer sheet, where in for example cell G2, above the lookup table, I put in the customer_id I wish to find all rows for in the sheet called Product. So, for example if I in G2 put in "1", I will get the two matching rows in sheet "Product". I have tried using VLOOKUP, but I always just match the first row, and none of the others.

EDIT:
in the lookup table you will only get the information in the sheet named "Product": if you put in "1" you will get rows 2 and 3 from the Product sheet. Customer_id only has one row per customer_id in the sheet called "customer", whereas in the sheet called "Product" you can have many rows per customer_id

答:
Your source data for Pivot Table would be your Product Sheet:

Create a Pivot Table, and take Customer Field to filter section in the setup:

Just changing manually the number in Cell B2 will return the Product related To that customer id.

NOTE: If you input a Customer_id that is not in the Product Sheet, an alert Msgbox will pop up warning you about that. So if you see at any moment that alert, it means that customer_id has 0 records in PRoduct Sheet :)

Hope this helps


问:
How can I count the invocations of a method?
Use interceptors to count the number of invocations.

I created an application with java ee consisting of an ejb side and a client. Now I have to count the number of times the client invokes a method, for each method, using the interceptors.

I don't understand how to modify the interceptors class. This is my code.

```<code>import javax.interceptor.AroundInvoke;
import javax.interceptor.InvocationContext;

public class InterceptorsBean {

    @AroundInvoke
    public Object methodInterceptors (InvocationContext ctx) throws Exception {
        System.out.println("Method invocated: " + ctx.getMethod().getName());
        return ctx.proceed();
    }

}
</code>```

How can I add the function to count?

答:
Just initialize a field to 0 and then increment it whenever the method is entered.

If the method is static, then make it a static field.

And make the variable private and use an instance or static method as appropriate to retrieve it.  This is so others who can invoke the method can't change the variable.

If you want to do this for multiple methods, use a map and use the method name as a key to retrieve the appropriate counter.

public class MapCounterDemo {

   private Map<String, Integer> counters = new HashMap<>();

   public static void main(String[] args) {
      MapCounterDemo demo = new MapCounterDemo();
      demo.foo();
      demo.foo();
      demo.foo();
      demo.bar();
      demo.bar();
      System.out.println(demo.counters);
   }

   public void foo() {
      update("foo");

   }

   public void bar() {
      update("bar");
   }

   private void update(String method) {
      counters.compute(method,
            (k, v) -> v == null ? 1
                  : ++v);

   }

}

```

Body:
Use interceptors to count the number of invocations.

I created an application with java ee consisting of an ejb side and a client. Now I have to count the number of times the client invokes a method, for each method, using the interceptors.

I don't understand how to modify the interceptors class. This is my code.

import javax.interceptor.AroundInvoke;
import javax.interceptor.InvocationContext;

public class InterceptorsBean {

    @AroundInvoke
    public Object methodInterceptors (InvocationContext ctx) throws Exception {
        System.out.println("Method invocated: " + ctx.getMethod().getName());
        return ctx.proceed();
    }

}

How can I add the function to count?


问:
How to concatenate Sass variables
How can I concatenate a Sass variable?

This is the the code in the scss file.

```<code>$url = 'siteurl.com';

#some-div{
    background-image: url(+ $url +/images/img.jpg);
}
</code>```

I want the result in the CSS file to be:

```<code>#some-div{
    background-image: url('siteurl.com/images/img.jpg');
}
</code>```

I found this question, but it didn't worked for me:
Trying to concatenate Sass variable and a string

答:
Use this:</p>
```<code>$domain: 'domain.ru';
#some-div {
    background-image: url('#{$domain}/images/img.jpg');
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: How to concatenate Sass variables

Body:
How can I concatenate a Sass variable?

This is the the code in the scss file.

$url = 'siteurl.com';

#some-div{
    background-image: url(+ $url +/images/img.jpg);
}

I want the result in the CSS file to be:

#some-div{
    background-image: url('siteurl.com/images/img.jpg');
}

I found this question, but it didn't worked for me:
Trying to concatenate Sass variable and a string

Body:
Use this:

$domain: 'domain.ru';
#some-div {
    background-image: url('#{$domain}/images/img.jpg');
}


问:
how to get the objects from an observable collection?
I don't know if it's possible but I would like to add objects to an observable collection and reuse them later.

I have this in wpf:

```<code> <CheckBox Margin="0,9,0,5" IsChecked="{Binding Prise1.Monday, Mode=TwoWay}"/>
 <CheckBox Margin="0,10,0,5" IsChecked="{Binding Prise2.Monday, Mode=TwoWay}"/>
 <CheckBox Margin="0,10,0,5" IsChecked="{Binding Prise3.Monday, Mode=TwoWay}"/>
 <CheckBox Margin="0,9,0,0" IsChecked="{Binding Durée.Monday, Mode=TwoWay}"/>
</code>```

For all days of the week.
Class WeekValues :

```<code>    private bool _Monday;
    public bool Monday
    {
        get
        {
            return _Monday;
        }
        set
        {
            _Monday = value;
            RaisePropertyChanged(nameof(Monday));
        }
    }
    private bool _Tuesday;
    public bool Tuesday
    {
        get
        {
            return _Tuesday;
        }
        set
        {
            _Tuesday = value;
            RaisePropertyChanged(nameof(Tuesday));
        }
    }
    private bool _Wednesday;
    public bool Wednesday
    {
        get
        {
            return _Wednesday;
        }
        set
        {
            _Wednesday = value;
            RaisePropertyChanged(nameof(Wednesday));
        }
    }
    private bool _Thursday;
    public bool Thursday
    {
        get
        {
            return _Thursday;
        }
        set
        {
            _Thursday = value;
            RaisePropertyChanged(nameof(Thursday));
        }
    }
    private bool _Friday;
    public bool Friday
    {
        get
        {
            return _Friday;
        }
        set
        {
            _Friday = value;
            RaisePropertyChanged(nameof(Friday));
        }
    }
    private bool _Saturday;
    public bool Saturday
    {
        get
        {
            return _Saturday;
        }
        set
        {
            _Saturday = value;
            RaisePropertyChanged(nameof(Saturday));
        }
    }
    private bool _Sunday;
    public bool Sunday
    {
        get
        {
            return _Sunday;
        }
        set
        {
            _Sunday = value;
            RaisePropertyChanged(nameof(Sunday));
        }
    }
}
</code>```

And i want to do something like this:

```<code>   public ObservableCollection<WeekValues> allPrises = new ObservableCollection<WeekValues>();

   Prise1 = new WeekValues();
   Prise2 = new WeekValues();
   Prise3 = new WeekValues();
   Durée = new WeekValues();

   allPrises.Add(Prise1);
   allPrises.Add(Prise2);
   allPrises.Add(Prise3);
   allPrises.Add(Durée);
</code>```

And use a method like :

```<code>MyMethod(allPrises)
{
    foreach(var X in allPrises)
       {
           if(Prise1.Monday) ...do something
           if(Prise2.Monday) ... do something else
       }
</code>```

Is this clear?
So that's the idea, I'd like to know how to proceed, because when I make a foreach I only get trues / falses without "Prise1" or "Prise2".
Would you know how to solve this?
Thank you in advance

答:
You are iterating over all 4 WeekValues. So X is Prise1 in the first iteration and so on.

if (Prise2.Monday) could be written as if (allPrises[1].Monday) if you never change the order of the elements.

Body:
I don't know if it's possible but I would like to add objects to an observable collection and reuse them later.

I have this in wpf:

 <CheckBox Margin="0,9,0,5" IsChecked="{Binding Prise1.Monday, Mode=TwoWay}"/>
 <CheckBox Margin="0,10,0,5" IsChecked="{Binding Prise2.Monday, Mode=TwoWay}"/>
 <CheckBox Margin="0,10,0,5" IsChecked="{Binding Prise3.Monday, Mode=TwoWay}"/>
 <CheckBox Margin="0,9,0,0" IsChecked="{Binding Durée.Monday, Mode=TwoWay}"/>

For all days of the week.
Class WeekValues :

    private bool _Monday;
    public bool Monday
    {
        get
        {
            return _Monday;
        }
        set
        {
            _Monday = value;
            RaisePropertyChanged(nameof(Monday));
        }
    }
    private bool _Tuesday;
    public bool Tuesday
    {
        get
        {
            return _Tuesday;
        }
        set
        {
            _Tuesday = value;
            RaisePropertyChanged(nameof(Tuesday));
        }
    }
    private bool _Wednesday;
    public bool Wednesday
    {
        get
        {
            return _Wednesday;
        }
        set
        {
            _Wednesday = value;
            RaisePropertyChanged(nameof(Wednesday));
        }
    }
    private bool _Thursday;
    public bool Thursday
    {
        get
        {
            return _Thursday;
        }
        set
        {
            _Thursday = value;
            RaisePropertyChanged(nameof(Thursday));
        }
    }
    private bool _Friday;
    public bool Friday
    {
        get
        {
            return _Friday;
        }
        set
        {
            _Friday = value;
            RaisePropertyChanged(nameof(Friday));
        }
    }
    private bool _Saturday;
    public bool Saturday
    {
        get
        {
            return _Saturday;
        }
        set
        {
            _Saturday = value;
            RaisePropertyChanged(nameof(Saturday));
        }
    }
    private bool _Sunday;
    public bool Sunday
    {
        get
        {
            return _Sunday;
        }
        set
        {
            _Sunday = value;
            RaisePropertyChanged(nameof(Sunday));
        }
    }
}

And i want to do something like this:

   public ObservableCollection<WeekValues> allPrises = new ObservableCollection<WeekValues>();

   Prise1 = new WeekValues();
   Prise2 = new WeekValues();
   Prise3 = new WeekValues();
   Durée = new WeekValues();

   allPrises.Add(Prise1);
   allPrises.Add(Prise2);
   allPrises.Add(Prise3);
   allPrises.Add(Durée);

And use a method like :

MyMethod(allPrises)
{
    foreach(var X in allPrises)
       {
           if(Prise1.Monday) ...do something
           if(Prise2.Monday) ... do something else
       }

Is this clear?
So that's the idea, I'd like to know how to proceed, because when I make a foreach I only get trues / falses without "Prise1" or "Prise2".
Would you know how to solve this?
Thank you in advance


问:
I want to get the id of value in a loop in a view and use it on a query outside the view
Im making an page that shows instruction cards. All the steps are in another table but It shows a instruction card multiple time when using 1 big query. I now have 2 queries. I loop through 1 query but in the mean time I want to use the id from a instruction card and get all the steps related to it and show it on the screen.

This is the code in the controller

```<code>$instructiekaarten = DB::table('instructiekaarten')
                             ->join('instructiekaart_set', 'instructiekaart_set.instructiekaart_id' ,'=', 'instructiekaarten.id')
                             ->join('sets', 'sets.id' ,'=', 'instructiekaart_set.set_id')
                             ->join('instructiekaart_user', 'instructiekaart_user.instructiekaart_id' ,'=', 'instructiekaarten.id')
                             ->join('users', 'users.id' ,'=', 'instructiekaart_user.user_id')
                             ->join('instructiekaart_niveau', 'instructiekaart_niveau.instructiekaart_id' ,'=', 'instructiekaarten.id')
                             ->join('niveaus', 'niveaus.id' ,'=', 'instructiekaart_niveau.niveau_id')
                             ->select('sets.name AS sets_name','instructiekaarten.name AS instru_name', 'niveaus.name AS niveaus_name')
                             ->get();

$stappen = DB::table('instructiekaarten')
                              ->join('instructiekaart_stap', 'instructiekaart_stap.instructiekaart_id' ,'=', 'instructiekaarten.id')
                              ->join('stappen', 'stappen.id' ,'=', 'instructiekaart_stap.stap_id')
                              ->select('stappen.name as stap_name')
                              ->where('instructiekaarten.id', '$id')
                              ->get();
</code>```

This is the code in the view

```<code>    @if(count($instructiekaarten) > 0)
        @foreach($instructiekaarten as $instructiekaart)
            <div class="card">
                <a href="/instructiekaarten">
                    <h5 class="card-header">{{$instructiekaart->instru_name}}</h5>
                </a>
                    <div class="card-body">
                        <h5 class="card-title"></h5>
                        @if(count($stappen) > 0)
                            @foreach($stappen as $stap)
                                <p class="card-text">{{$stap->stap_name}}</p>
                            @endforeach
                        @endif
                    </div>
            </div>
        @endforeach
    @else
        <p>Geen instructiekaarten gevonden</p>
    @endif
</code>```

How can I get the id from a instruction card and use it in the second query?

答:
Simple answer is put the missing field into your select:

```<code>->select('stappen.name as stap_name', 'instructiekaarten.id AS instructiekaart_id')
</code>```

But you better delete your second query and add a ->with('stappen') relation in your first query and set it up as defined here: https://laravel.com/docs/5.8/eloquent-relationships#one-to-many

Body:
Im making an page that shows instruction cards. All the steps are in another table but It shows a instruction card multiple time when using 1 big query. I now have 2 queries. I loop through 1 query but in the mean time I want to use the id from a instruction card and get all the steps related to it and show it on the screen.

This is the code in the controller

$instructiekaarten = DB::table('instructiekaarten')
                             ->join('instructiekaart_set', 'instructiekaart_set.instructiekaart_id' ,'=', 'instructiekaarten.id')
                             ->join('sets', 'sets.id' ,'=', 'instructiekaart_set.set_id')
                             ->join('instructiekaart_user', 'instructiekaart_user.instructiekaart_id' ,'=', 'instructiekaarten.id')
                             ->join('users', 'users.id' ,'=', 'instructiekaart_user.user_id')
                             ->join('instructiekaart_niveau', 'instructiekaart_niveau.instructiekaart_id' ,'=', 'instructiekaarten.id')
                             ->join('niveaus', 'niveaus.id' ,'=', 'instructiekaart_niveau.niveau_id')
                             ->select('sets.name AS sets_name','instructiekaarten.name AS instru_name', 'niveaus.name AS niveaus_name')
                             ->get();

$stappen = DB::table('instructiekaarten')
                              ->join('instructiekaart_stap', 'instructiekaart_stap.instructiekaart_id' ,'=', 'instructiekaarten.id')
                              ->join('stappen', 'stappen.id' ,'=', 'instructiekaart_stap.stap_id')
                              ->select('stappen.name as stap_name')
                              ->where('instructiekaarten.id', '$id')
                              ->get();

This is the code in the view

    @if(count($instructiekaarten) > 0)
        @foreach($instructiekaarten as $instructiekaart)

{{$instructiekaart->instru_name}}

                        @if(count($stappen) > 0)
                            @foreach($stappen as $stap)

{{$stap->stap_name}}

                            @endforeach
                        @endif

        @endforeach
    @else

Geen instructiekaarten gevonden

    @endif

How can I get the id from a instruction card and use it in the second query?

Body:
Simple answer is put the missing field into your select:

->select('stappen.name as stap_name', 'instructiekaarten.id AS instructiekaart_id')

But you better delete your second query and add a ->with('stappen') relation in your first query and set it up as defined here: https://laravel.com/docs/5.8/eloquent-relationships#one-to-many


问:
Basic C question on copying char arrays to char pointers
I have some doubts in basic C programming.

I have a char array and I have to copy it to a char pointer. So I did the following:

```<code>char a[] = {0x3f, 0x4d};
char *p = a;
printf("a = %s\n",a);
printf("p = %s\n",p);
unsigned char str[] = {0x3b, 0x4b};
unsigned char *pstr =str;
memcpy(pstr, str, sizeof str);
printf("str = %s\n",str);
printf("pstr = %s\n",pstr);
</code>```

My printf statements for pstr and str get appended with the data "a".
If I remove memcpy I get junk. Can some C Guru enlighten me?

答:
Firstly, C strings (the %s in printf) are expected to be NUL-terminated. You're missing the terminators. Try char a[] = {0x3f, 0x4d, 0} (same goes for str).

Secondly, pstr and str point to the same memory, so your memcpy is a no-op. This is a minor point compared to the first one.

Body:
I have some doubts in basic C programming.

I have a char array and I have to copy it to a char pointer. So I did the following:

char a[] = {0x3f, 0x4d};
char *p = a;
printf("a = %s\n",a);
printf("p = %s\n",p);
unsigned char str[] = {0x3b, 0x4b};
unsigned char *pstr =str;
memcpy(pstr, str, sizeof str);
printf("str = %s\n",str);
printf("pstr = %s\n",pstr);

My printf statements for pstr and str get appended with the data "a".
If I remove memcpy I get junk. Can some C Guru enlighten me?


问:
Introduce spell checking in Django's template form
When I write a form in Django's template form,

In the opening browser of the form there's not any magic function but a plain blank text area.

How could I introduce the spelling check function to it?

答:
If you're happy with plain Browser spellchecking you can just pass the attribute "spellcheck"="true" along with the Textarea.

Example: (Assumes you're using Modelforms and SomeClass with the field text.)

```<code>from django.forms import Textarea

class SomeClassModelForm(ModelForm):
    class Meta:
        model = SomeClass
        fields = ['text']

        widgets = {
            'text': Textarea(attrs={'spellcheck': 'true', 'rows': 5})
        }
</code>```

Body:
If you're happy with plain Browser spellchecking you can just pass the attribute "spellcheck"="true" along with the Textarea.

Example: (Assumes you're using Modelforms and SomeClass with the field text.)

from django.forms import Textarea

class SomeClassModelForm(ModelForm):
    class Meta:
        model = SomeClass
        fields = ['text']

        widgets = {
            'text': Textarea(attrs={'spellcheck': 'true', 'rows': 5})
        }


问:
How do I access enum values in Kotlin
I'm trying to iterate over an enum but I cannot access any values they were set with.  Android Studio only sees the name and ordinal, but nothing else.

I'm not sure if this is an android studio problem as other online tutorials for kotlin enums seem to do what I do and work just fine.

```<code>    enum class TimeStamps(value : Long, text : String) {
        Hour(0, "Past Hour"),
        Day(3600000, "Today"),
        Yesterday(86400000, "Yesterday"),
        Week(172800000, "This week"),
        LastWeek(604800000, "Last week"),
        LastMonth(1209600000, "Last month"),
        LastYear(2628000000, "Last year"),
        LongTime(31540000000, "A long time ago")
    }

TimeStamps.LastMonth.value
TimeStamps.LastMonth.text  //Both of these are said to be undefined by Android Studio

enumValues<TimeStamps>().forEach {

            it.value //Also undefined
}
</code>```

I'm not exactly sure what is going on.  The only error message I get is the Unresolved Reference error.  Any help is greatly appreciated, thanks!

答:
You need to use val if you want it to be a property:

```<code>enum class TimeStamps(val value: Long, val text: String) {
    ...
}
</code>```

Title: How do I access enum values in Kotlin

Body:
I'm trying to iterate over an enum but I cannot access any values they were set with.  Android Studio only sees the name and ordinal, but nothing else.

I'm not sure if this is an android studio problem as other online tutorials for kotlin enums seem to do what I do and work just fine.

    enum class TimeStamps(value : Long, text : String) {
        Hour(0, "Past Hour"),
        Day(3600000, "Today"),
        Yesterday(86400000, "Yesterday"),
        Week(172800000, "This week"),
        LastWeek(604800000, "Last week"),
        LastMonth(1209600000, "Last month"),
        LastYear(2628000000, "Last year"),
        LongTime(31540000000, "A long time ago")
    }

TimeStamps.LastMonth.value
TimeStamps.LastMonth.text  //Both of these are said to be undefined by Android Studio

enumValues<TimeStamps>().forEach {

            it.value //Also undefined
}

I'm not exactly sure what is going on.  The only error message I get is the Unresolved Reference error.  Any help is greatly appreciated, thanks!

Body:
You need to use val if you want it to be a property:

enum class TimeStamps(val value: Long, val text: String) {
    ...
}


问:
How to convert array of string to simple string in JavaScript?
I have the following JavaScript array of strings:

```<code>arrayOfString = ['a', 'b,c', 'd,e', 'f'];
</code>```

And I would like to convert this array to an array similar to this:

```<code>myString = ["a", "b", "c", "d", "e", "f"];
</code>```

How I can accomplish that?

答:
Using join() and split()

Note: The default separator of join() is comma (,)

const arrayOfString = ['a', 'b,c', 'd,e', 'f']

const myString = arrayOfString.join().split(',')

console.log(myString)```

Body:
I have the following JavaScript array of strings:

arrayOfString = ['a', 'b,c', 'd,e', 'f'];

And I would like to convert this array to an array similar to this:

myString = ["a", "b", "c", "d", "e", "f"];

How I can accomplish that?


问:
Problems deleting records from a Shapefile using Editor() class in pyShp
I'm using pyShp to add three polygons in a new shapefile. I added the geometry and the records (attributes). So far no problem.

Later, I wanted to use the Editor() class to delete one of the three polygons. If I try to delete the last one 'P3', it works fine.

The problem appears when I try to delete any other of the polygons. For instance, if I delete the first one, the shape disappear but its attributes remain so the 'P2' polygon inherit them. The record that is deleted is the last one (originally linked to 'P3').

```<code>import shapefile
w = shapefile.Writer(shapefile.POLYGONZ)
print(w.shapeType)
w.poly(parts=[[[0,0],[5,0],[5,5],[0,5]]])
w.poly(parts=[[[10,0],[15,0],[15,10],[10,5]]])
w.poly(parts=[[[5,10],[10,10],[10,15],[5,15]]])

w.field('NAME', 'C',40)
w.record('P1')
w.record('P2')
w.record('P3')
w.save("polygons")

edit = shapefile.Editor("polygons")
edit.delete(0)
edit.save("polygonDeleted")
</code>```

I know I could select the two shapes that I want to keep and write them in a new shapefile but I'd like to understand why the Editor() class doesn't work as expected.

答: The newest version of pyshp removed the Editor() class so is no longer avalaible.</p>

Body:
I'm using pyShp to add three polygons in a new shapefile. I added the geometry and the records (attributes). So far no problem.

Later, I wanted to use the Editor() class to delete one of the three polygons. If I try to delete the last one 'P3', it works fine.

The problem appears when I try to delete any other of the polygons. For instance, if I delete the first one, the shape disappear but its attributes remain so the 'P2' polygon inherit them. The record that is deleted is the last one (originally linked to 'P3').

import shapefile
w = shapefile.Writer(shapefile.POLYGONZ)
print(w.shapeType)
w.poly(parts=[[[0,0],[5,0],[5,5],[0,5]]])
w.poly(parts=[[[10,0],[15,0],[15,10],[10,5]]])
w.poly(parts=[[[5,10],[10,10],[10,15],[5,15]]])

w.field('NAME', 'C',40)
w.record('P1')
w.record('P2')
w.record('P3')
w.save("polygons")

edit = shapefile.Editor("polygons")
edit.delete(0)
edit.save("polygonDeleted")

I know I could select the two shapes that I want to keep and write them in a new shapefile but I'd like to understand why the Editor() class doesn't work as expected.


问:
Finding a certain header and copying a certain amount of entries below it
I'm trying to search for a certain header (Header 1 in this example) and copy a certain amount of cells below this header to a range. The text of the header itself isn't supposed to get copied but everything below it.

The following code works, but it copies too many lines. When I use For x = 0 To 3 it copies the next 10 lines below "Header 1" instead of only 3. I can't find my mistake.

```<code>Sub FindCopyPasteV2()

    With Worksheets("Sheet1").Range("A:FF")

        Dim FindEQ3 As Range
        Dim TestR As Range
        Dim x As Long

           Set FindEQ3 = .Find(What:="Header 1", LookAt:=xlWhole, MatchCase:=True, SearchFormat:=False)

              For x = 0 To 3

                 Set FindEQ3 = FindEQ3.Resize(FindEQ3.Rows.Count + x).Offset(1)
                 Set TestR = .Range("K" & 5 + x)

                 FindEQ3.Copy TestR

              Next x

    End With

End Sub
</code>```

答:
I think your problem is just that you are doing something twice. The purpose of the loop is to make sure 3 rows get copied, but actually FindEQ3.Resize already does that.

This code should be closer to what you want. I mainly just took the loop out.

```<code>Sub FindCopyPasteV2()

    With Worksheets("Sheet1").Range("A:FF")

        Dim FindEQ3 As Range
        Dim TestR As Range

        Const NUM_ROWS_COPY As Long = 3

        Set FindEQ3 = .Find(What:="Header 1", LookAt:=xlWhole, MatchCase:=True, SearchFormat:=False)

        Set FindEQ3 = FindEQ3.Resize(NUM_ROWS_COPY).Offset(1)
        Set TestR = .Range("K" & 5)

        FindEQ3.Copy TestR

    End With

End Sub
</code>```

Body:
I'm trying to search for a certain header (Header 1 in this example) and copy a certain amount of cells below this header to a range. The text of the header itself isn't supposed to get copied but everything below it.

The following code works, but it copies too many lines. When I use For x = 0 To 3 it copies the next 10 lines below "Header 1" instead of only 3. I can't find my mistake.

Sub FindCopyPasteV2()

    With Worksheets("Sheet1").Range("A:FF")

        Dim FindEQ3 As Range
        Dim TestR As Range
        Dim x As Long

           Set FindEQ3 = .Find(What:="Header 1", LookAt:=xlWhole, MatchCase:=True, SearchFormat:=False)

              For x = 0 To 3

                 Set FindEQ3 = FindEQ3.Resize(FindEQ3.Rows.Count + x).Offset(1)
                 Set TestR = .Range("K" & 5 + x)

                 FindEQ3.Copy TestR

              Next x

    End With

End Sub

Body:
I think your problem is just that you are doing something twice. The purpose of the loop is to make sure 3 rows get copied, but actually FindEQ3.Resize already does that.

This code should be closer to what you want. I mainly just took the loop out.

Sub FindCopyPasteV2()

    With Worksheets("Sheet1").Range("A:FF")

        Dim FindEQ3 As Range
        Dim TestR As Range

        Const NUM_ROWS_COPY As Long = 3

        Set FindEQ3 = .Find(What:="Header 1", LookAt:=xlWhole, MatchCase:=True, SearchFormat:=False)

        Set FindEQ3 = FindEQ3.Resize(NUM_ROWS_COPY).Offset(1)
        Set TestR = .Range("K" & 5)

        FindEQ3.Copy TestR

    End With

End Sub


问:
Accessing a single field in a foreach using Linq Dapper
I am using dapper and I want to use Linq to be able to update a single field called status in one table I am trying to use.

```<code>public async Task<Int32> ProcessUnprocessedTransactions(IEnumerable<BomComponentData> items)
{
    IEnumerable<BomComponentData> _itemstoBeProcesed = items.Where(w => w.Status == (int)BomStatus.Scanned);

    foreach (BomComponentData item in _itemstoBeProcesed)
    {
        item.Status = (int)BomStatus.Completed;
    }

    return await database.UpdateAsync(_itemstoBeProcesed);
}
</code>```

My class is as follows:

```<code>public class BomComponentData
{
    public int Sequence { get; set; }

    public string BOMShortName { get; set; }
    public string OperationName { get; set; }
    public long BomId { get; set; }
    public long BOMLineID { get; set; }
    public long StockItemID { get; set; }
    public string BomLineType { get; set; }
    public int Quantity { get; set; }
    public long UnitID { get; set; }
    public decimal? MultipleOfBaseUnit { get; set; }
    public string Code { get; set; }
    public string Name { get; set; }
    public string Barcode { get; set; }
    public long ProductGroupID { get; set; }
    public string ProductGroupCode { get; set; }
    public int Status { get; set; }

    public int BinLocation { get; set; }
    public string BinName { get; set; }

    public string UOM { get; set; }
    public int CalculatedValue { get; set; }
    public int BomPickedCount { get; set; }

    public int TotalLeftTopick
    {
        get { return Quantity - BomPickedCount; }
    }

    public enum BomStatus
    {
        Listed=1,
        Scanned=2,
        Confirmed=3,
        Processed=4,
        Completed=4,
        InVisible=5
    }

    public override string ToString()
    {
        return Code;
    }
}
</code>```

But it does not work if I use a foreach like above. I am sure it should update the items properly but I think that because I'm going through singular items in my foreach and my list in the update it's not updating correct.

All I want to do is mark the items as completed and ready for transfer, I am doing so by the status column and an int enum.

Maybe I am missing a declaration of what is my primary key?

Edit 2

When I use a key declaration of the primary key I get the following:

Unhandled Exception: System.AggregateException: One or more errors occurred. (Constraint

Edit 3

I have set key of my class but as you see I have auotincrement on my db and it still crashes. How should insert be handled?

Edit 4

For example I am inserting into the database as follows. Shouldn't this work?

```<code>List<BomComponentData> _bomList = new List<BomComponentData>();
_bomList.Add(new BomComponentData { Sequence = 1, Barcode = "0000000001498", BinLocation = 23, BinName = "A", BOMShortName = "GYNE-TXX", OperationName = "Example Product", Code = "TB9175CEA", Name = "Tiburon Peri/Gynae Pack-10", Quantity = 1, UOM = "Each" });

await database.InsertAllAsync(_bomList,true);
</code>```

I have placed the tag key for the update that works ok but when I attempt to do an insert with the key it doesn't it says constraint error but the update works. Does anybody no how i can solve both the insert and update in Dapper contrib.

答:
This was actually the issue I had to decoate my class with the following Leaving this here so that anyone else has issue I was using the pcl libary but for some reason dapper contribe did not detect the key element it had to be declared as follows.</p>

```<code>[SQLite.PrimaryKey, SQLite.AutoIncrement]
public class StockTransferArgs
{
    [SQLite.PrimaryKey, SQLite.AutoIncrement]
    public int StockTransferArgsId { get; set; }
    public long StockItemID { get; set; }

    public string Code { get; set; }

    public string OperationName { get; set; }
    public string Description { get; set; }
    public decimal Quantity { get; set; }
    public long SourceWarehouseID { get; set; }
    public string SourceBinName { get; set; }
    public long TargetWarehouseID { get; set; }
    public string TargetBinName { get; set; }
    public string Reference { get; set; }
    public string SecondReference { get; set; }
    public string BarCode { get; set; }
    public int Status { get; set; }
}
</code>```

Body:
I am using dapper and I want to use Linq to be able to update a single field called status in one table I am trying to use.

public async Task<Int32> ProcessUnprocessedTransactions(IEnumerable<BomComponentData> items)
{
    IEnumerable<BomComponentData> _itemstoBeProcesed = items.Where(w => w.Status == (int)BomStatus.Scanned);

    foreach (BomComponentData item in _itemstoBeProcesed)
    {
        item.Status = (int)BomStatus.Completed;
    }

    return await database.UpdateAsync(_itemstoBeProcesed);
}

My class is as follows:

public class BomComponentData
{
    public int Sequence { get; set; }

    public string BOMShortName { get; set; }
    public string OperationName { get; set; }
    public long BomId { get; set; }
    public long BOMLineID { get; set; }
    public long StockItemID { get; set; }
    public string BomLineType { get; set; }
    public int Quantity { get; set; }
    public long UnitID { get; set; }
    public decimal? MultipleOfBaseUnit { get; set; }
    public string Code { get; set; }
    public string Name { get; set; }
    public string Barcode { get; set; }
    public long ProductGroupID { get; set; }
    public string ProductGroupCode { get; set; }
    public int Status { get; set; }

    public int BinLocation { get; set; }
    public string BinName { get; set; }

    public string UOM { get; set; }
    public int CalculatedValue { get; set; }
    public int BomPickedCount { get; set; }

    public int TotalLeftTopick
    {
        get { return Quantity - BomPickedCount; }
    }

    public enum BomStatus
    {
        Listed=1,
        Scanned=2,
        Confirmed=3,
        Processed=4,
        Completed=4,
        InVisible=5
    }

    public override string ToString()
    {
        return Code;
    }
}

But it does not work if I use a foreach like above. I am sure it should update the items properly but I think that because I'm going through singular items in my foreach and my list in the update it's not updating correct.

All I want to do is mark the items as completed and ready for transfer, I am doing so by the status column and an int enum.

Maybe I am missing a declaration of what is my primary key?

Edit 2

When I use a key declaration of the primary key I get the following:

Unhandled Exception: System.AggregateException: One or more errors occurred. (Constraint

Edit 3

I have set key of my class but as you see I have auotincrement on my db and it still crashes. How should insert be handled?

Edit 4

For example I am inserting into the database as follows. Shouldn't this work?

List<BomComponentData> _bomList = new List<BomComponentData>();
_bomList.Add(new BomComponentData { Sequence = 1, Barcode = "0000000001498", BinLocation = 23, BinName = "A", BOMShortName = "GYNE-TXX", OperationName = "Example Product", Code = "TB9175CEA", Name = "Tiburon Peri/Gynae Pack-10", Quantity = 1, UOM = "Each" });

await database.InsertAllAsync(_bomList,true);

I have placed the tag key for the update that works ok but when I attempt to do an insert with the key it doesn't it says constraint error but the update works. Does anybody no how i can solve both the insert and update in Dapper contrib.

Body:
This was actually the issue I had to decoate my class with the following Leaving this here so that anyone else has issue I was using the pcl libary but for some reason dapper contribe did not detect the key element it had to be declared as follows.

[SQLite.PrimaryKey, SQLite.AutoIncrement]
public class StockTransferArgs
{
    [SQLite.PrimaryKey, SQLite.AutoIncrement]
    public int StockTransferArgsId { get; set; }
    public long StockItemID { get; set; }

    public string Code { get; set; }

    public string OperationName { get; set; }
    public string Description { get; set; }
    public decimal Quantity { get; set; }
    public long SourceWarehouseID { get; set; }
    public string SourceBinName { get; set; }
    public long TargetWarehouseID { get; set; }
    public string TargetBinName { get; set; }
    public string Reference { get; set; }
    public string SecondReference { get; set; }
    public string BarCode { get; set; }
    public int Status { get; set; }
}


问:
Conda environments not showing up in Jupyter Notebook
I installed Anaconda (with Python 2.7), and installed Tensorflow in an environment called tensorflow. I can import Tensorflow successfully in that environment.

The problem is that Jupyter Notebook does not recognize the new environment I just created. No matter I start Jupyter Notebook from the GUI Navigator or from the command line within the tensorflow env, there is only one kernel in the menu called Python [Root], and Tensorflow cannot be imported. Of course, I clicked on that option multiple times, saved file, re-opened, but these did not help.

Strangely, I can see the two environments when I open the Conda tab on the front page of Jupyter. But when I open the Files tab, and try to new a notebook, I still end up with only one kernel.

I looked at this question:
Link Conda environment with Jupyter Notebook
But there isn't such a directory as ~/Library/Jupyter/kernels on my computer! This Jupyter directory only has one sub-directory called runtime.

I am really confused. Are Conda environments supposed to become kernels automatically? (I followed https://ipython.readthedocs.io/en/stable/install/kernel_install.html to manually set up the kernels, but was told that ipykernel was not found.)

答:
In my case, using Windows 10 and conda 4.6.11, by running the commands

```<code>conda install nb_conda

conda install -c conda-forge nb_conda_kernels
</code>```

from the terminal while having the environment active didn't do the job after I opened Jupyter from the same command line using conda jupyter notebook.

The solution was apparently to opened Jupyter from the Anaconda Navigator by going to my environment in Environments: Open Anaconda Navigator, select the environment in Environments, press on the "play" button on the chosen environment, and select 'open with Jupyter Notebook'.

Environments in Anaconda Navigator to run Jupyter from the selected environment

Body:
In my case, using Windows 10 and conda 4.6.11, by running the commands

conda install nb_conda

conda install -c conda-forge nb_conda_kernels

from the terminal while having the environment active didn't do the job after I opened Jupyter from the same command line using conda jupyter notebook.

The solution was apparently to opened Jupyter from the Anaconda Navigator by going to my environment in Environments: Open Anaconda Navigator, select the environment in Environments, press on the "play" button on the chosen environment, and select 'open with Jupyter Notebook'.

Environments in Anaconda Navigator to run Jupyter from the selected environment


问:
How to interrupt a Python subprocess
I'm trying to create a smart TV using a Raspberry Pi 3B+. I plan on using Tkinter to create a GUI for the TV and flask to create a remote that can be accessed via a smartphone.

I plan on running Flask and call the Tkinter via a subprocess. The issue I'm facing is when I need to pause a video, for example. The Flask process must interrupt the Tkinter subprocess to pause the video. I can't seem to find any solutions to how this might be done. One idea I had was to send a keyboard interrupt and handle pause\play, but since other forms of interrupts are also required such as volume and seek, I will need multiple different interrupts with data such as seek time, etc as well.

How can this be achieved using python subprocesses?

答:
You need to send signals between two processes. You can probably use celery for that. Or use a simple sqlite database shared by both processes. the Flask process writes, the tkinter reads changes

Or look at this: https://pymotw.com/2/multiprocessing/communication.html

Title: How to interrupt a Python subprocess


问:
How to restore certificate in Android?
I have uploaded an app on Google Play, unfortunately I have lost certificate of the uploaded app but I have password of the app. Now I want to upload new version of the app but I have no certificate, is there any way to recover the certificate of the app and upload the newer version of the app. Please help me in this respect, your help would be  cordially appreciated. Thanks in advance.</p>

答:
1)Generate new certificate:

keytool -genkey -v -keystore my-release-key.jks -keyalg RSA -keysize 2048 -validity 10000 -alias my-alias

2) Convert to .pem:

keytool -export -rfc -alias my-alias -file upload_certificate.pem -keystore my-release-key.jks

3) Send .pem to Contact Form:

General issues - Play Console Help

it takes 2 busines days to answer but this is the way if you dont want to re publish your app ;)

then you can sign your apk as you do before

(for me)

zipalign -v 4 android-release-unsigned.apk HelloWorld.apk

ReadMore

Manage your app signing keys

Title: How to restore certificate in Android?


问:
IPython notebook doubles up the qqplot
I just tested the statsmodels.api.qqplot function in an IPython notebook (Jupyter) running Python 3.6, and got two identical plots in a column (I only asked for one). What is going on?</p>

```<code>import statsmodels.api as sm
test = np.random.normal(0,1, 1000)
sm.qqplot(test, line='45')
</code>```

答:
Just add ";" is the simplest hack.

For example:

```<code>sm.qqplot(test, line='45');
</code>```

I got the answer from

@lightalchemist from github.com/statsmodels/statsmodels/issues/1265.

Title: IPython notebook doubles up the qqplot

Body:
I just tested the statsmodels.api.qqplot function in an IPython notebook (Jupyter) running Python 3.6, and got two identical plots in a column (I only asked for one). What is going on?

import statsmodels.api as sm
test = np.random.normal(0,1, 1000)
sm.qqplot(test, line='45')

Body:
Just add ";" is the simplest hack.

For example:

sm.qqplot(test, line='45');

I got the answer from

@lightalchemist from github.com/statsmodels/statsmodels/issues/1265.


问:
bash aliases set in while loop not persisting
Okay, I've written a shell script to read a file with the format:

shortcut1 /path/to/directory1

shortcut2 /path/to/directory2

and its supposed to read the file and build aliases such that typing shortcut1 cd's me into the mapped directory. The problem is, any of the aliases set in the loop don't persist outside of the script.

Firstly I tried just running the script.

. ./build_shortcuts.sh "~/.shortcuts"

where the file ~/.shortcuts contains

dl    ~/Downloads

  music /music

  dtop  ~/Desktop

This didn't work. Then I tried setting some aliases outside of the loop. Such as alias hello='world'; alias world='hellob'. I reran the script, typed alias to get a list of aliases and it did include hello and world as aliases, but not any of those set in the loop.

Then I thought maybe the loop isn't setting them at all, so I added alias as the final command in the script so it would print out the aliases at the end; in this case it did include the aliases but they still didn't persist in my session.

build_shortcuts.sh

script="$(cat $@ | sed -r -e 's/#[A-Za-z0-9 ]*$//' -e '/^\s+/s/^\s+//' -e '/^\s*$/d' -)"
# strip comments, entry level indentation & empty lines (in that order) from filestream

echo "${script}" | while read shortcut; do
    cut=$(echo  "${shortcut}" | awk '{         print $1 }')
    dest=$(echo "${shortcut}" | awk '{ $1=nil; print $0 }')
    dest="${dest:1}" # trim leading whitespace character

    alias "${cut}" &>/dev/null

    if [ $? = 0 ]; then
        echo "Warning: shortcut \"${cut}\" already exists" >&2
        continue # by default, skip overwriting shortcuts
    fi

    echo alias ${cut}="'cd ${dest}'"
    alias "${cut}"="'cd ${dest}'"
done

```

I want the aliases set in the loop within the script to exist outside of the script. Currently they don't.

I'm running on "GNU bash, version 5.0.7(1)-release (x86_64-pc-linux-gnu)" on arch linux.

答:
Your script can be reduced a bit: it doesn't need to call out to so many external tools.

```<code>while read -r cut dest; do
    if alias "${cut}" &>/dev/null; then
        echo "Warning: shortcut \"${cut}\" already exists" >&2
    else
        echo alias ${cut}="'cd ${dest}'"
        alias "${cut}"="'cd ${dest}'"
    fi
done < <(
    sed -E -e 's/#[A-Za-z0-9 ]*$//' -e '/^\s+/s/^\s+//' -e '/^\s*$/d' "$@"
)
</code>```

after "done", I'm redirecting input from a process substitution: this avoids the "while read" loop from running in a subshell.

Body:
Okay, I've written a shell script to read a file with the format:

shortcut1 /path/to/directory1

shortcut2 /path/to/directory2

and its supposed to read the file and build aliases such that typing shortcut1 cd's me into the mapped directory. The problem is, any of the aliases set in the loop don't persist outside of the script.

Firstly I tried just running the script.

. ./build_shortcuts.sh "~/.shortcuts"

where the file ~/.shortcuts contains

dl    ~/Downloads

  music /music

  dtop  ~/Desktop

This didn't work. Then I tried setting some aliases outside of the loop. Such as alias hello='world'; alias world='hellob'. I reran the script, typed alias to get a list of aliases and it did include hello and world as aliases, but not any of those set in the loop.

Then I thought maybe the loop isn't setting them at all, so I added alias as the final command in the script so it would print out the aliases at the end; in this case it did include the aliases but they still didn't persist in my session.

build_shortcuts.sh

script="$(cat $@ | sed -r -e 's/#[A-Za-z0-9 ]*$//' -e '/^\s+/s/^\s+//' -e '/^\s*$/d' -)"
# strip comments, entry level indentation & empty lines (in that order) from filestream

echo "${script}" | while read shortcut; do
    cut=$(echo  "${shortcut}" | awk '{         print $1 }')
    dest=$(echo "${shortcut}" | awk '{ $1=nil; print $0 }')
    dest="${dest:1}" # trim leading whitespace character

    alias "${cut}" &>/dev/null

    if [ $? = 0 ]; then
        echo "Warning: shortcut \"${cut}\" already exists" >&2
        continue # by default, skip overwriting shortcuts
    fi

    echo alias ${cut}="'cd ${dest}'"
    alias "${cut}"="'cd ${dest}'"
done

I want the aliases set in the loop within the script to exist outside of the script. Currently they don't.

I'm running on "GNU bash, version 5.0.7(1)-release (x86_64-pc-linux-gnu)" on arch linux.

Body:
Your script can be reduced a bit: it doesn't need to call out to so many external tools.

while read -r cut dest; do
    if alias "${cut}" &>/dev/null; then
        echo "Warning: shortcut \"${cut}\" already exists" >&2
    else
        echo alias ${cut}="'cd ${dest}'"
        alias "${cut}"="'cd ${dest}'"
    fi
done < <(
    sed -E -e 's/#[A-Za-z0-9 ]*$//' -e '/^\s+/s/^\s+//' -e '/^\s*$/d' "$@"
)

after "done", I'm redirecting input from a process substitution: this avoids the "while read" loop from running in a subshell.


问:
Make pop-up or dialog window with list of photos
I want to make dialog/pop-up window with list of photos(currently I`m trying to so it with smartPhoto.js, but there is some issues). That photos should become bigger, when clicking on that.

Do you have any ideas how to implement that? Any help appreciates

答:
start off with a placeholder div inside a new page window.

style the div so it has display:none, and takes up most of the screen. you can even give it a transparent black background, and you can say that when you click on a link or a thumbnail, that div will appear and you can put your photo with javascript through the onclick event on that div.

make sure you change the z-index of the div aswell.

finally since this is all happening inside a popup window, you just need a link with target=_blank to display the contents of your page in a popup.


问:
How to extract x-atmosphere-tracking-id from a string?
I am trying to extract X-Atmosphere-tracking-id from the response body.
I got the response in the following way:

```<code>40|41be6f15-2e19-4e1d-aaff-d4b92ae47e48|0||
</code>```

Now I want to extract only:

```<code>41be6f15-2e19-4e1d-aaff-d4b92ae47e48
</code>```

which is dynamically generated on every execution.

Also, It would be great if someone shares tips and tricks as well as reference videos/sites of load testing using JMeter for Vaading application.

答:
Here, we might just want to simply use a list of chars:

```<code>(?:\|)([a-z0-9-]+)(?:\|)
</code>```

The string that we wish to extract is in this capturing group:

```<code>([a-z0-9-]+)
</code>```

with two boundaries in its left and right side:

```<code>(?:\|)
</code>```

Based on The fourth bird's advice, we can also simplify our expression and remove the non-capturing groups:

```<code>\|([a-z0-9-]+)\|
</code>```

RegEx Circuit

jex.im visualizes regular expressions:

DEMO

Body:
I am trying to extract X-Atmosphere-tracking-id from the response body.
I got the response in the following way:

40|41be6f15-2e19-4e1d-aaff-d4b92ae47e48|0||

Now I want to extract only:

41be6f15-2e19-4e1d-aaff-d4b92ae47e48

which is dynamically generated on every execution.

Also, It would be great if someone shares tips and tricks as well as reference videos/sites of load testing using JMeter for Vaading application.

Body:
Here, we might just want to simply use a list of chars:

(?:\|)([a-z0-9-]+)(?:\|)

The string that we wish to extract is in this capturing group:

([a-z0-9-]+)

with two boundaries in its left and right side:

(?:\|)

Based on The fourth bird's advice, we can also simplify our expression and remove the non-capturing groups:

\|([a-z0-9-]+)\|

RegEx Circuit

jex.im visualizes regular expressions:

DEMO


问:
An error occurred while installing mysql2 (0.3.21), and Bundler cannot continue
Any reason why this error popped up when I tried bundling an application:
I have tried installing gem install mysql2 -v '0.3.21' as they recommend but it cant install properly. Also I am running this on macOS High Sierra. Sorry for my bad wording for this question because its my first time working with ruby.</p>

```<code> To see why this extension failed to compile, please check the mkmf.log which can be found here:

  /Users/yamanshrestha/Desktop/Dorsata/vendor/bundle/ruby/2.3.0/extensions/universal-darwin-17/2.3.0/mysql2-0.3.21/mkmf.log

current directory: /Users/yamanshrestha/Desktop/Dorsata/vendor/bundle/ruby/2.3.0/gems/mysql2-0.3.21/ext/mysql2
make "DESTDIR=" clean

current directory: /Users/yamanshrestha/Desktop/Dorsata/vendor/bundle/ruby/2.3.0/gems/mysql2-0.3.21/ext/mysql2
make "DESTDIR="
compiling infile.c
compiling client.c
client.c:439:3: error: use of undeclared identifier 'my_bool'
  my_bool res = mysql_read_query_result(client);
  ^
client.c:441:19: error: use of undeclared identifier 'res'
  return (void *)(res == 0 ? Qtrue : Qfalse);
                  ^
client.c:762:3: error: use of undeclared identifier 'my_bool'
  my_bool boolval;
  ^
client.c:793:7: error: use of undeclared identifier 'boolval'
      boolval = (value == Qfalse ? 0 : 1);
      ^
client.c:794:17: error: use of undeclared identifier 'boolval'
      retval = &boolval;
                ^
client.c:797:10: error: use of undeclared identifier 'MYSQL_SECURE_AUTH'; did you mean 'MYSQL_DEFAULT_AUTH'?
    case MYSQL_SECURE_AUTH:
         ^~~~~~~~~~~~~~~~~
         MYSQL_DEFAULT_AUTH
/usr/local/Cellar/mysql/8.0.11/include/mysql/mysql.h:188:3: note: 'MYSQL_DEFAULT_AUTH' declared here
  MYSQL_DEFAULT_AUTH,
  ^
client.c:798:7: error: use of undeclared identifier 'boolval'
      boolval = (value == Qfalse ? 0 : 1);
      ^
client.c:799:17: error: use of undeclared identifier 'boolval'
      retval = &boolval;
                ^
client.c:830:38: error: use of undeclared identifier 'boolval'
        wrapper->reconnect_enabled = boolval;
                                     ^
client.c:1185:38: error: use of undeclared identifier 'MYSQL_SECURE_AUTH'; did you mean 'MYSQL_DEFAULT_AUTH'?
  return _mysql_client_options(self, MYSQL_SECURE_AUTH, value);
                                     ^~~~~~~~~~~~~~~~~
                                     MYSQL_DEFAULT_AUTH
/usr/local/Cellar/mysql/8.0.11/include/mysql/mysql.h:188:3: note: 'MYSQL_DEFAULT_AUTH' declared here
  MYSQL_DEFAULT_AUTH,
  ^
10 errors generated.
make: *** [client.o] Error 1

make failed, exit code 2

Gem files will remain installed in /Users/yamanshrestha/Desktop/Dorsata/vendor/bundle/ruby/2.3.0/gems/mysql2-0.3.21 for inspection.
Results logged to /Users/yamanshrestha/Desktop/Dorsata/vendor/bundle/ruby/2.3.0/extensions/universal-darwin-17/2.3.0/mysql2-0.3.21/gem_make.out

An error occurred while installing mysql2 (0.3.21), and Bundler cannot continue.
Make sure that `gem install mysql2 -v '0.3.21' --source 'http://rubygems.org/'` succeeds before bundling.
</code>```

答: For me the solution was to install mysql-connector-c, brew install mysql-connector-c. In my particular case it was already installed but I had to re-link it with force overwrite (the messages in the console will tell you exactly what to do in your situation).

Body:
Any reason why this error popped up when I tried bundling an application:
I have tried installing gem install mysql2 -v '0.3.21' as they recommend but it cant install properly. Also I am running this on macOS High Sierra. Sorry for my bad wording for this question because its my first time working with ruby.

 To see why this extension failed to compile, please check the mkmf.log which can be found here:

  /Users/yamanshrestha/Desktop/Dorsata/vendor/bundle/ruby/2.3.0/extensions/universal-darwin-17/2.3.0/mysql2-0.3.21/mkmf.log

current directory: /Users/yamanshrestha/Desktop/Dorsata/vendor/bundle/ruby/2.3.0/gems/mysql2-0.3.21/ext/mysql2
make "DESTDIR=" clean

current directory: /Users/yamanshrestha/Desktop/Dorsata/vendor/bundle/ruby/2.3.0/gems/mysql2-0.3.21/ext/mysql2
make "DESTDIR="
compiling infile.c
compiling client.c
client.c:439:3: error: use of undeclared identifier 'my_bool'
  my_bool res = mysql_read_query_result(client);
  ^
client.c:441:19: error: use of undeclared identifier 'res'
  return (void *)(res == 0 ? Qtrue : Qfalse);
                  ^
client.c:762:3: error: use of undeclared identifier 'my_bool'
  my_bool boolval;
  ^
client.c:793:7: error: use of undeclared identifier 'boolval'
      boolval = (value == Qfalse ? 0 : 1);
      ^
client.c:794:17: error: use of undeclared identifier 'boolval'
      retval = &boolval;
                ^
client.c:797:10: error: use of undeclared identifier 'MYSQL_SECURE_AUTH'; did you mean 'MYSQL_DEFAULT_AUTH'?
    case MYSQL_SECURE_AUTH:
         ^~~~~~~~~~~~~~~~~
         MYSQL_DEFAULT_AUTH
/usr/local/Cellar/mysql/8.0.11/include/mysql/mysql.h:188:3: note: 'MYSQL_DEFAULT_AUTH' declared here
  MYSQL_DEFAULT_AUTH,
  ^
client.c:798:7: error: use of undeclared identifier 'boolval'
      boolval = (value == Qfalse ? 0 : 1);
      ^
client.c:799:17: error: use of undeclared identifier 'boolval'
      retval = &boolval;
                ^
client.c:830:38: error: use of undeclared identifier 'boolval'
        wrapper->reconnect_enabled = boolval;
                                     ^
client.c:1185:38: error: use of undeclared identifier 'MYSQL_SECURE_AUTH'; did you mean 'MYSQL_DEFAULT_AUTH'?
  return _mysql_client_options(self, MYSQL_SECURE_AUTH, value);
                                     ^~~~~~~~~~~~~~~~~
                                     MYSQL_DEFAULT_AUTH
/usr/local/Cellar/mysql/8.0.11/include/mysql/mysql.h:188:3: note: 'MYSQL_DEFAULT_AUTH' declared here
  MYSQL_DEFAULT_AUTH,
  ^
10 errors generated.
make: *** [client.o] Error 1

make failed, exit code 2

Gem files will remain installed in /Users/yamanshrestha/Desktop/Dorsata/vendor/bundle/ruby/2.3.0/gems/mysql2-0.3.21 for inspection.
Results logged to /Users/yamanshrestha/Desktop/Dorsata/vendor/bundle/ruby/2.3.0/extensions/universal-darwin-17/2.3.0/mysql2-0.3.21/gem_make.out

An error occurred while installing mysql2 (0.3.21), and Bundler cannot continue.
Make sure that `gem install mysql2 -v '0.3.21' --source 'http://rubygems.org/'` succeeds before bundling.


问:
How to use to_date for date like '1970-01-01 00:00:01.0'
I want to convert text '1970-01-01 00:00:01.0' into date by using to_date but I am not getting which format shoud I use.

If you check some examples like :
to_date('1970-01-01 00:00:01','yyyy-mm-dd HH24:MI:SS')
which works fine but in my case I am unable to find such a format.

Could you please help which date format should I use?

答:
Do you need to convert to date, or to timestamp?

If you need to convert to date, and ignore the fractional seconds, you can use the boilerplate format element in the date format model.

```<code>to_date('1970-01-01 00:00:01.0','yyyy-mm-dd HH24:MI:SS".0"')
</code>```

Notice what I added: a string in double quotes, namely .0. This will mask any decimal digit, not just 0 (but it must be a digit).

If some inputs may have more decimal places, you can expand the boilerplate text, for example to ".000000000"  If there are "too many zeros" in the format model (compared to the input), that will work; but if there are too few, it won't.

Body:
Do you need to convert to date, or to timestamp?

If you need to convert to date, and ignore the fractional seconds, you can use the boilerplate format element in the date format model.

to_date('1970-01-01 00:00:01.0','yyyy-mm-dd HH24:MI:SS".0"')

Notice what I added: a string in double quotes, namely .0. This will mask any decimal digit, not just 0 (but it must be a digit).

If some inputs may have more decimal places, you can expand the boilerplate text, for example to ".000000000"  If there are "too many zeros" in the format model (compared to the input), that will work; but if there are too few, it won't.


答: printf's %s expects a 0-terminated string, your strings aren't. The uninitialized memory following your arrays may however happen to start with a 0-byte, in which case your code will appear to be correct - it still isn't.

Title: Basic C question on copying char arrays to char pointers

Body:
I have some doubts in basic C programming.

I have a char array and I have to copy it to a char pointer. So I did the following:

char a[] = {0x3f, 0x4d};
char *p = a;
printf("a = %s\n",a);
printf("p = %s\n",p);
unsigned char str[] = {0x3b, 0x4b};
unsigned char *pstr =str;
memcpy(pstr, str, sizeof str);
printf("str = %s\n",str);
printf("pstr = %s\n",pstr);

My printf statements for pstr and str get appended with the data "a".
If I remove memcpy I get junk. Can some C Guru enlighten me?


问:
Grouping and ordering using ActiveRecord Query interface
I have a model, ConnectedUser, which belongs to 2 other models User and Station.

It is a simple model with just those relationships and a boolean active.

The results of the query I'm aiming for would be only each most recent ConnectedUser record for each User (where the Station is a specific id).

For example, if my ConnectedUser table looked like this...

```<code>+----+---------+------------+--------+------------+
| id | user_id | station_id | active | created_at |
+----+---------+------------+--------+------------+
|  1 |       1 |          1 | true   | 20 June    |
|  2 |       1 |          1 | false  | 19 June    |
|  3 |       1 |          2 | false  | 20 June    |
|  4 |       2 |          1 | false  | 18 June    |
|  5 |       2 |          1 | false  | 21 June    |
+----+---------+------------+--------+------------+
</code>```

And the station was the one with id 1 then I'd like the query to return...

```<code>[
<ConnectedUser id: 1, user_id: 1, station_id: 1, active: true, created_at: "2019-06-20">,
<ConnectedUser id: 5, user_id: 2, station_id: 1, active: false, created_at: "2019-06-21">
]
</code>```

To achieve this I've been trying to use group to and order

```<code>ConnectedUser.where(station: station).select(:user_id).group(:user_id).order(:created_at)
</code>```

but have kept getting errors like this:

ActiveRecord::StatementInvalid (PG::GroupingError: ERROR:  column
  "connected_users.created_at" must appear in the GROUP BY clause or be
  used in an aggregate function)

I am unable to get the specific ConnectedUser id, so feel like I'm missing some important understanding how to work with group and aggregate the results.

Is this possible in one ActiveRecord query?

Many thanks.

答:
You should use DISTINCT ON instead of GROUP. Here is how you can do it in Rails:

```<code>ConnectedUser.select("DISTINCT ON (station_id, user_id) *")
             .where(station_id: params[:station_id])
             .order(created_at: :desc)
</code>```

Of course with params[:station_id] is what you want to filter

Body:
I have a model, ConnectedUser, which belongs to 2 other models User and Station.

It is a simple model with just those relationships and a boolean active.

The results of the query I'm aiming for would be only each most recent ConnectedUser record for each User (where the Station is a specific id).

For example, if my ConnectedUser table looked like this...

+----+---------+------------+--------+------------+
| id | user_id | station_id | active | created_at |
+----+---------+------------+--------+------------+
|  1 |       1 |          1 | true   | 20 June    |
|  2 |       1 |          1 | false  | 19 June    |
|  3 |       1 |          2 | false  | 20 June    |
|  4 |       2 |          1 | false  | 18 June    |
|  5 |       2 |          1 | false  | 21 June    |
+----+---------+------------+--------+------------+

And the station was the one with id 1 then I'd like the query to return...

[
<ConnectedUser id: 1, user_id: 1, station_id: 1, active: true, created_at: "2019-06-20">,
<ConnectedUser id: 5, user_id: 2, station_id: 1, active: false, created_at: "2019-06-21">
]

To achieve this I've been trying to use group to and order

ConnectedUser.where(station: station).select(:user_id).group(:user_id).order(:created_at)

but have kept getting errors like this:

ActiveRecord::StatementInvalid (PG::GroupingError: ERROR:  column
  "connected_users.created_at" must appear in the GROUP BY clause or be
  used in an aggregate function)

I am unable to get the specific ConnectedUser id, so feel like I'm missing some important understanding how to work with group and aggregate the results.

Is this possible in one ActiveRecord query?

Many thanks.

Body:
You should use DISTINCT ON instead of GROUP. Here is how you can do it in Rails:

ConnectedUser.select("DISTINCT ON (station_id, user_id) *")
             .where(station_id: params[:station_id])
             .order(created_at: :desc)

Of course with params[:station_id] is what you want to filter


问:
Pass variable in a bottomTabNavigator
I want to pass a variable from one page through my bottomTabNavigator to another page, without having to use a stackNavigator or creating an extra 'tab' in my tabNavigator so to speak

I tried passing and recieving the variable like explained below.

How i try to pass the variable:

```<code>onPress={() => this.props.navigation.navigate('IndividualCardPage',
{"name":this.props.cards.name})}
</code>```

How i try to get the variable on the other page:

```<code>values = {
        name: this.props.navigation.getParam('name','empty')
    }
    componentDidMount() {
        console.log(this.values.name)
    }
</code>```

I expect to navigate to the 'IndividualCardPage' and be able to use the variable 'name' there.
What happens is either one of these two things:
 1. Nothing happens on the button click.
 2. Error message displays saying 'unable to find variable: name'.
Any ideas? Thanks in advance

答:
For the navigation onPress I had to use this code:

```<code>onPress={() => this.props.navigation.navigate('iCardPage',
{"name":this.props.cards.name})}
</code>```

I also had to create a stacknavigator:

```<code>import React from 'react';
import {createStackNavigator} from "react-navigation";
import IndividualCardPage from '../Pages/IndividualCardPage';
import Cards from "../Pages/CardPage";

export default createStackNavigator({
Cards: {
    screen: Cards,
    navigationOptions: ({ navigation }) => ({
        title: 'Selecteer een kaart',
        backgroundColor: '#7E007F',
    }),
},
iCardPage: {
    screen: IndividualCardPage,
    navigationOptions: ({ navigation }) => ({
        title: 'Individuele kaart',

    }),
},
},{
    initialRouteName: 'Cards'
});
</code>```

Then I also had to fire my stacknavigator's navigate event when pressing one of the tabs in my BottomTabNavigator like so:

```<code>const AppNavigator = createMaterialBottomTabNavigator({

Home: {
    screen: Deck,
    navigationOptions: ({ navigation }) => ({
        title: 'Deck',
        tabBarIcon: ({ tintColor }) => (<MaterialIcons name='home' size={25} color={tintColor} />)
    })
},
Card: {
    screen: StackNavigator,
    navigationOptions: ({ navigation }) => ({
        title: 'Cards',
        tabBarIcon: ({ tintColor }) => (<MaterialIcons name='style' size={25} color={tintColor} />)
    })
}
},{
initialRouteName: 'Home',
barStyle: {
    backgroundColor: '#7E007F',
},
});
</code>```

In the page I wanted to send the variable to I had to tweak the code for getting the variable ('parameter') a little like so:

```<code> state = {
  name: "empy"
};

async componentDidMount() {
    this.setState((prevstate) => {
        name: this.props.navigation.getParam("name","empty")
    });
    console.log(this.values.name);
}
</code>```

Title: Pass variable in a bottomTabNavigator

Body:
I want to pass a variable from one page through my bottomTabNavigator to another page, without having to use a stackNavigator or creating an extra 'tab' in my tabNavigator so to speak

I tried passing and recieving the variable like explained below.

How i try to pass the variable:

onPress={() => this.props.navigation.navigate('IndividualCardPage',
{"name":this.props.cards.name})}

How i try to get the variable on the other page:

values = {
        name: this.props.navigation.getParam('name','empty')
    }
    componentDidMount() {
        console.log(this.values.name)
    }

I expect to navigate to the 'IndividualCardPage' and be able to use the variable 'name' there.
What happens is either one of these two things:
 1. Nothing happens on the button click.
 2. Error message displays saying 'unable to find variable: name'.
Any ideas? Thanks in advance

Body:
For the navigation onPress I had to use this code:

onPress={() => this.props.navigation.navigate('iCardPage',
{"name":this.props.cards.name})}

I also had to create a stacknavigator:

import React from 'react';
import {createStackNavigator} from "react-navigation";
import IndividualCardPage from '../Pages/IndividualCardPage';
import Cards from "../Pages/CardPage";

export default createStackNavigator({
Cards: {
    screen: Cards,
    navigationOptions: ({ navigation }) => ({
        title: 'Selecteer een kaart',
        backgroundColor: '#7E007F',
    }),
},
iCardPage: {
    screen: IndividualCardPage,
    navigationOptions: ({ navigation }) => ({
        title: 'Individuele kaart',

    }),
},
},{
    initialRouteName: 'Cards'
});

Then I also had to fire my stacknavigator's navigate event when pressing one of the tabs in my BottomTabNavigator like so:

const AppNavigator = createMaterialBottomTabNavigator({

Home: {
    screen: Deck,
    navigationOptions: ({ navigation }) => ({
        title: 'Deck',
        tabBarIcon: ({ tintColor }) => (<MaterialIcons name='home' size={25} color={tintColor} />)
    })
},
Card: {
    screen: StackNavigator,
    navigationOptions: ({ navigation }) => ({
        title: 'Cards',
        tabBarIcon: ({ tintColor }) => (<MaterialIcons name='style' size={25} color={tintColor} />)
    })
}
},{
initialRouteName: 'Home',
barStyle: {
    backgroundColor: '#7E007F',
},
});

In the page I wanted to send the variable to I had to tweak the code for getting the variable ('parameter') a little like so:

 state = {
  name: "empy"
};

async componentDidMount() {
    this.setState((prevstate) => {
        name: this.props.navigation.getParam("name","empty")
    });
    console.log(this.values.name);
}


问:
Checkbox display content without using HTML and CSS only (no JS)
I'm setting up checkbox in a side navigation fashion in my html pages, I want the check box to display content upon selection. Example: Choose checkbox 1,2 display content only of that, No checkbox selected display all content.. How can i do this without Jquery/javascript. I want my webpage to maintain same functionality even if Javascript in browser is disabled. Can i do this by including w3.css as these styles are responsive without involving bootstrap</p>

答:
I would advise you to learn the ":checked" selector. Here is a simple example.

HTML

```<code><label for="trigger">Toggle box</label>
<div>
    OTHER HTML CONTENT
</div>
<input id="trigger" type="checkbox">
<div class="box">
  SHOW / HIDE BOX
</div>
</code>```

CSS

```<code>.box {
  display: none;
  background: #ccc;
  width: 200px;
  height: 100px;
}

#trigger {
  display: none;
}

#trigger:checked + .box {
  display: block;
}
</code>```

As you can see the ":checked" selector can show or hide the DIV block.
Here is an interesting article on this topic.

Body:
I would advise you to learn the ":checked" selector. Here is a simple example.

HTML

<label for="trigger">Toggle box</label>
<div>
    OTHER HTML CONTENT
</div>
<input id="trigger" type="checkbox">
<div class="box">
  SHOW / HIDE BOX
</div>

CSS

.box {
  display: none;
  background: #ccc;
  width: 200px;
  height: 100px;
}

#trigger {
  display: none;
}

#trigger:checked + .box {
  display: block;
}

As you can see the ":checked" selector can show or hide the DIV block.
Here is an interesting article on this topic.


问:
How to get results from a query which is inside of a function
I'm trying to make an "AdminCheck" system which will check if the user is admin and return user's admin level based on information gathered from database

I've did some research and realized my problem is with query being asynchronous, but I couldn't find more

function isAdmin(varr){
    let queryCheck = "SELECT AdminLVL FROM accounts WHERE username = ?"
    pool.query(queryCheck, [varr], (err,results) => {
        console.log(results[0].AdminLVL) // This gives me results
        if(err){
            console.log(err)
        }
        else {
            return results[0].AdminLVL
        }
    })
}
```

right where I commented "This gives me results" everything works fine, but I wanna be able to use the result, which let's think its "300", somewhere else.

答:
The problem is that the function calling isAdmin is running asynchronously, and not waiting for results. Change isAdmin to return a promise
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise
Then you can write the rest of your code in isAdmin(varr).then(res => { // your code })
Or you can use async await.

edit to add some code:
Do something along these lines (view the docs to get it to work exactly as you need it to)

```<code>  isAdmin(varr) {
    return new Promise((resolve, reject) => {
        let queryCheck = "SELECT AdminLVL FROM accounts WHERE username = ?"
        pool.query(queryCheck, [varr], (err,results) => {
            console.log(results[0].AdminLVL) // This gives me results
            if(err){
                reject(err);
            }
            else {
                resolve(results[0].AdminLVL);
            }
        });
  });
</code>```

Body:
I'm trying to make an "AdminCheck" system which will check if the user is admin and return user's admin level based on information gathered from database

I've did some research and realized my problem is with query being asynchronous, but I couldn't find more

function isAdmin(varr){
    let queryCheck = "SELECT AdminLVL FROM accounts WHERE username = ?"
    pool.query(queryCheck, [varr], (err,results) => {
        console.log(results[0].AdminLVL) // This gives me results
        if(err){
            console.log(err)
        }
        else {
            return results[0].AdminLVL
        }
    })
}

right where I commented "This gives me results" everything works fine, but I wanna be able to use the result, which let's think its "300", somewhere else.

Body:
The problem is that the function calling isAdmin is running asynchronously, and not waiting for results. Change isAdmin to return a promise
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise
Then you can write the rest of your code in isAdmin(varr).then(res => { // your code })
Or you can use async await.

edit to add some code:
Do something along these lines (view the docs to get it to work exactly as you need it to)

  isAdmin(varr) {
    return new Promise((resolve, reject) => {
        let queryCheck = "SELECT AdminLVL FROM accounts WHERE username = ?"
        pool.query(queryCheck, [varr], (err,results) => {
            console.log(results[0].AdminLVL) // This gives me results
            if(err){
                reject(err);
            }
            else {
                resolve(results[0].AdminLVL);
            }
        });
  });


问:
How to get output on label from access batabas query
How to get lable output from access database query?</p>

```<code>con.Open();

  OleDbCommand cmdan = con.CreateCommand();

  cmdan.CommandType = CommandType.Text;

  string na = "SELECT top 1 Priimek_Ime from Dijaki ORDER BY rnd(ID_Dijaki)";

  cmdan.CommandText = na;

  OleDbDataReader n1 = cmdan.ExecuteReader();

  label2.Text = n1["Vprasanja"].ToString();

  n1.Close();

con.Close();
</code>```

答:
You must read the OleDbDataReader

```<code>...
OleDbDataReader n1 = cmdan.ExecuteReader();
n1.Read();
label2.Text = n1["Priimek_Ime"].ToString();
....
</code>```

Do note that Read() function does return a boolean with true if it did read. You could consider checking if you have data in your table.

```<code>if (n1.Read())
{
    label2.Text = n1["Vprasanja"].ToString();
}
else
{
    label2.Text = "No data found";
}
</code>```

Body:
How to get lable output from access database query?

con.Open();

  OleDbCommand cmdan = con.CreateCommand();

  cmdan.CommandType = CommandType.Text;

  string na = "SELECT top 1 Priimek_Ime from Dijaki ORDER BY rnd(ID_Dijaki)";

  cmdan.CommandText = na;

  OleDbDataReader n1 = cmdan.ExecuteReader();

  label2.Text = n1["Vprasanja"].ToString();

  n1.Close();

con.Close();

Body:
You must read the OleDbDataReader

...
OleDbDataReader n1 = cmdan.ExecuteReader();
n1.Read();
label2.Text = n1["Priimek_Ime"].ToString();
....

Do note that Read() function does return a boolean with true if it did read. You could consider checking if you have data in your table.

if (n1.Read())
{
    label2.Text = n1["Vprasanja"].ToString();
}
else
{
    label2.Text = "No data found";
}