问:
Check if at least two elements in an array are greater than zero - JavaScript/Typescript
Is there a smart way to find out if there are at least two values greater than 0 in an array and return true? And false in the opposite case?

(hypothetical and wrong example using some):

```<code>const a = [9, 1, 0];
const b = [0, 0, 0];
const c = [5, 0, 0];

const cond = (el) => el > 0 && somethingElseMaybe;

console.log(a.some(cond)); // print true
console.log(b.some(cond)); // print false
console.log(c.some(cond)); // print false

</code>```

答:
Try this,

console.log(a.filter(s => s > 0).length >= 2); // print true
console.log(b.filter(s => s > 0).length >= 2); // print false
console.log(c.filter(s => s > 0).length >= 2); // print false
```

Body:
Is there a smart way to find out if there are at least two values greater than 0 in an array and return true? And false in the opposite case?

(hypothetical and wrong example using some):

const a = [9, 1, 0];
const b = [0, 0, 0];
const c = [5, 0, 0];

const cond = (el) => el > 0 && somethingElseMaybe;

console.log(a.some(cond)); // print true
console.log(b.some(cond)); // print false
console.log(c.some(cond)); // print false


来源: stackexchange

问:
'RNFirebaseBackgroundMessage' Event not triggered while receiving data notification in React Native Application
I am using react-native-firebase@5.2.3. I had created a headless task to receive the data notification, and my server is sending me a data notification but it is not reflecting in my application although i had created the event for this.
It is working finely in android < v7. But not working in android version > v7.

I'm not getting anything in console, while server has sent me the data-only notification. Once this callback on headless task execute i will code here to show notification but there is no event triggering.

Environment :

```<code>    OS: Ubuntu
        "react": "16.6.3",
        "react-native": "^0.58.6",
        "react-native-firebase": "^5.2.3",
</code>```

My code is given below.

```<code>import {AppRegistry} from 'react-native';
import 'babel-polyfill';
import App from './App';
import {name as appName} from './app.json';
console.disableYellowBox = true;

const bgMessaging = async(messages) => {
    console.log("BgMessaging",messages);
    return Promise.resolve();
};

AppRegistry.registerHeadlessTask('RNFirebaseBackgroundMessage', () => bgMessaging);
AppRegistry.registerComponent(appName, () => App);
</code>```

答:
I got the solution.
When your application is set to use battery in optimised way, then it does not allow to execute the headless task, So, simply i had changed my app's battery setting to normal mode and it started working finely.
My android device was set to use all application in battery optimisation. That's why i had faced this issue.

ContentLicense: CC BY-SA 4.0

Body:
I am using react-native-firebase@5.2.3. I had created a headless task to receive the data notification, and my server is sending me a data notification but it is not reflecting in my application although i had created the event for this.
It is working finely in android < v7. But not working in android version > v7.

I'm not getting anything in console, while server has sent me the data-only notification. Once this callback on headless task execute i will code here to show notification but there is no event triggering.

Environment :

    OS: Ubuntu
        "react": "16.6.3",
        "react-native": "^0.58.6",
        "react-native-firebase": "^5.2.3",

My code is given below.

import {AppRegistry} from 'react-native';
import 'babel-polyfill';
import App from './App';
import {name as appName} from './app.json';
console.disableYellowBox = true;

const bgMessaging = async(messages) => {
    console.log("BgMessaging",messages);
    return Promise.resolve();
};

AppRegistry.registerHeadlessTask('RNFirebaseBackgroundMessage', () => bgMessaging);
AppRegistry.registerComponent(appName, () => App);


问:
Python: concatenate an integer array with 1 empty array
I have one simple one-dimensional array and an empty array in NumPy. I try to concatenate them, but I get an array in float.

```<code>from numpy import *
a = zeros(5,'i')
a += 1
b = []
c = hstack((a,b))
d = concatenate((a, b))
print("a",a)
print("b",b)
print("c",c)
print("d",d)
</code>```

I got:

```<code>a [1 1 1 1 1]

b []

c [1. 1. 1. 1. 1.]

d [1. 1. 1. 1. 1.]
</code>```

But I am looking for an integer array

```<code>[1 1 1 1 1]
</code>```

How? And what is the most efficient way?

答:
Try this way:

numpy array dtype by default is float.So, change it to np.int32

```<code>a = np.zeros(5,dtype=np.int32)
a += 1
b = np.array([],dtype=np.int32)

</code>```

Body:
I have one simple one-dimensional array and an empty array in NumPy. I try to concatenate them, but I get an array in float.

from numpy import *
a = zeros(5,'i')
a += 1
b = []
c = hstack((a,b))
d = concatenate((a, b))
print("a",a)
print("b",b)
print("c",c)
print("d",d)

I got:

a [1 1 1 1 1]

b []

c [1. 1. 1. 1. 1.]

d [1. 1. 1. 1. 1.]

But I am looking for an integer array

[1 1 1 1 1]

How? And what is the most efficient way?

Body:
Try this way:

numpy array dtype by default is float.So, change it to np.int32

a = np.zeros(5,dtype=np.int32)
a += 1
b = np.array([],dtype=np.int32)


答:
You might create b as 0-size np.array of dtype 'i' rather than list, that is:

```<code>import numpy as np
a = np.zeros(5,'i')
a += 1
b = np.array([],'i')
c = np.hstack((a,b))
d = np.concatenate((a, b))
print(d)
</code>```

Output:

```<code>[1 1 1 1 1]
</code>```

Title: Python: concatenate an integer array with 1 empty array

Body:
You might create b as 0-size np.array of dtype 'i' rather than list, that is:

import numpy as np
a = np.zeros(5,'i')
a += 1
b = np.array([],'i')
c = np.hstack((a,b))
d = np.concatenate((a, b))
print(d)

Output:

[1 1 1 1 1]


问:
The string value data member is skipped by compiler
string value is not displaying all though told the computer to display Please help

```<code>import java.util.Scanner;

class Author
{
    private String name;
    private String email;
    private char gender;

    public Author (String name, String email, char gender) {
        this.name=name;
        this.setEmail(email);
        this.gender=gender;
    }

    /**
     * @return the name
     */
    public String getName() {
        return name;
    }

    /**
     * @return the email
     */
    public String getEmail() {
        return email;
    }
    /**
     * @param email the email to set
     */
    public void setEmail(String email) {
        this.email = email;
    }
    /**
     * @return the gender
     */
    public char getGender() {
        return gender;
    }

    @Override
    public String toString() {
        return "Author [name=" + name + ", email=" + email + ", gender=" + gender + "]";
    }

}
class Book
{
    private String Name;
    Author auth;
    private double price;
    private int qty;

    /**
     * @param name
     * @param auth
     * @param price
     */
    public Book(String name, Author auth, double price) {
        super();
        Name = name;
        this.auth = auth;
        this.price = price;
    }

    /**
     * @param name
     * @param auth
     * @param price
     * @param qty
     */
    public Book(String name, Author auth, double price, int qty) {
        super();
        Name = name;
        this.auth = auth;
        this.price = price;
        this.qty = qty;
    }

    public String getName() {
        return Name;
    }

    public Author getAuth() {
        return auth;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    public int getQty() {
        return qty;
    }

    public void setQty(int qty) {
        this.qty = qty;
    }

    @Override
    public String toString() {
        return "Book [Name=" + Name + ", auth=" + auth + ", price=" + price + ", qty=" + qty + "]";
    }

}
class Student
{
    private String Name;
    private int roll;
    date issueDate;
    date returnDate;
    /**
     * @param name
     * @param roll
     * @param issueDate``
     * @param returnDate
     */
    public Student(String name, int roll, date issueDate, date returnDate) {
        super();
        Name = name;
        this.roll = roll;
        this.issueDate = issueDate;
        this.returnDate = returnDate;
    }
    public String getName() {
        return Name;
    }

    public int getRoll() {
        return roll;
    }

    public date getIssueDate() {

        return issueDate;
    }

    public date getReturnDate() {
        return returnDate;
    }
    public void setReturnDate(date returnDate) {
        this.returnDate = returnDate;

    }

}
public class Main {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner sc=new Scanner(System.in);
        Author ahTeck=null;
        System.out.println("How many Book are there in library ?");
        int n=sc.nextInt();
        Book []ob=new Book[n];
        for(int i=0;i<n;++i)
        {   System.out.println("Author's name");
            String s=sc.nextLine();
            sc.nextLine();
            System.out.println("Author's Email Id");
            String s1=sc.nextLine();
            System.out.println("gender:");
            char c = sc.next(".").charAt(0);
            sc.nextLine();
            System.out.println("Book Name:");
            String b=sc.nextLine();
            System.out.println("Book price:");
            double price=sc.nextInt();
            System.out.println("Book quantity");
            int q=sc.nextInt();
            ob[i]=new Book(b, new Author(s, s1, c),price,q);
            System.out.println(ob[i]);
        }

    }

}
</code>```

the question is there in
https://www.ntu.edu.sg/home/ehchua/programming/java/J3f_OOPExercises.html

Output is coming like

Book [Name=g, auth=Author [name=, email=e, gender=m], price=6.0, qty=6]

the displaying of author name is skipped

答:
Ah yes. The ol' Scanneroo.

Right after entering the integer at the top, call sc.nextLine();

```<code>int n = sc.nextInt();
sc.nextLine();
</code>```

Actually, you don't even have to call sc.nextLine() after entering a string or character. The thing is, when you enter a number, you hit the enter key as well. The Scanner class regards it as another token when you use nextInt(), so the number gets stored correctly, but the enter key \n is regarded as another token.

So when you call nextLine() after entering the number, the system sees that there is already a token remaining in the Scanner object, so it takes '\n' as its input. Thus, the name actually stores "\n", which is empty.

Body:
string value is not displaying all though told the computer to display Please help

import java.util.Scanner;

class Author
{
    private String name;
    private String email;
    private char gender;

    public Author (String name, String email, char gender) {
        this.name=name;
        this.setEmail(email);
        this.gender=gender;
    }

    /**
     * @return the name
     */
    public String getName() {
        return name;
    }

    /**
     * @return the email
     */
    public String getEmail() {
        return email;
    }
    /**
     * @param email the email to set
     */
    public void setEmail(String email) {
        this.email = email;
    }
    /**
     * @return the gender
     */
    public char getGender() {
        return gender;
    }

    @Override
    public String toString() {
        return "Author [name=" + name + ", email=" + email + ", gender=" + gender + "]";
    }

}
class Book
{
    private String Name;
    Author auth;
    private double price;
    private int qty;

    /**
     * @param name
     * @param auth
     * @param price
     */
    public Book(String name, Author auth, double price) {
        super();
        Name = name;
        this.auth = auth;
        this.price = price;
    }

    /**
     * @param name
     * @param auth
     * @param price
     * @param qty
     */
    public Book(String name, Author auth, double price, int qty) {
        super();
        Name = name;
        this.auth = auth;
        this.price = price;
        this.qty = qty;
    }

    public String getName() {
        return Name;
    }

    public Author getAuth() {
        return auth;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    public int getQty() {
        return qty;
    }

    public void setQty(int qty) {
        this.qty = qty;
    }

    @Override
    public String toString() {
        return "Book [Name=" + Name + ", auth=" + auth + ", price=" + price + ", qty=" + qty + "]";
    }

}
class Student
{
    private String Name;
    private int roll;
    date issueDate;
    date returnDate;
    /**
     * @param name
     * @param roll
     * @param issueDate``
     * @param returnDate
     */
    public Student(String name, int roll, date issueDate, date returnDate) {
        super();
        Name = name;
        this.roll = roll;
        this.issueDate = issueDate;
        this.returnDate = returnDate;
    }
    public String getName() {
        return Name;
    }

    public int getRoll() {
        return roll;
    }

    public date getIssueDate() {

        return issueDate;
    }

    public date getReturnDate() {
        return returnDate;
    }
    public void setReturnDate(date returnDate) {
        this.returnDate = returnDate;

    }

}
public class Main {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner sc=new Scanner(System.in);
        Author ahTeck=null;
        System.out.println("How many Book are there in library ?");
        int n=sc.nextInt();
        Book []ob=new Book[n];
        for(int i=0;i<n;++i)
        {   System.out.println("Author's name");
            String s=sc.nextLine();
            sc.nextLine();
            System.out.println("Author's Email Id");
            String s1=sc.nextLine();
            System.out.println("gender:");
            char c = sc.next(".").charAt(0);
            sc.nextLine();
            System.out.println("Book Name:");
            String b=sc.nextLine();
            System.out.println("Book price:");
            double price=sc.nextInt();
            System.out.println("Book quantity");
            int q=sc.nextInt();
            ob[i]=new Book(b, new Author(s, s1, c),price,q);
            System.out.println(ob[i]);
        }

    }

}

the question is there in
https://www.ntu.edu.sg/home/ehchua/programming/java/J3f_OOPExercises.html

Output is coming like

Book [Name=g, auth=Author [name=, email=e, gender=m], price=6.0, qty=6]

the displaying of author name is skipped

Body:
Ah yes. The ol' Scanneroo.

Right after entering the integer at the top, call sc.nextLine();

int n = sc.nextInt();
sc.nextLine();

Actually, you don't even have to call sc.nextLine() after entering a string or character. The thing is, when you enter a number, you hit the enter key as well. The Scanner class regards it as another token when you use nextInt(), so the number gets stored correctly, but the enter key \n is regarded as another token.

So when you call nextLine() after entering the number, the system sees that there is already a token remaining in the Scanner object, so it takes '\n' as its input. Thus, the name actually stores "\n", which is empty.


问:
Iterate over a list by setting element as a variable
I would like to create 12 dataframes labelled with month names by using a for loop. So I created a list with the month names list_month. But I am not able to insert the variable i as df_[i] in the for loop.

The operation I am trying to do is to create a new dataframe df_new_month like df_new_feb = df_feb[df_feb['my_feature'] > 20] for each month contained in the list:

Should I follow a different approach?

list_month = ['jan','feb','mar','apr','may','jun','jul','aug','sep','oct','nov','dec']
for i in list_month:
    df_new_[i] = df_[i][df_[i]['my_feature'] > 20]
    print(i, list_month[i])
```

<p>The Error I get is:</p>

```Traceback (most recent call
  last):File"/Users/annalisa/anaconda3/lib/python3.7/site_
  packages/IPython/core/interactiveshell.py", line 3325, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
  File "<ipython-input-50-c09b1f63eb51>", line 3, in <module>
    df_new_[i] = df_[i][df_[i]['my_feature'] > 20]
NameError: name 'df_' is not defined
```

答:
This is rather hackish but should work, given that I understood you correctly:

```<code>list_month = ['jan','feb','mar','apr','may','jun','jul','aug','sep','oct','nov','dec']
for i in list_month:
    exec("df_new_{month} = df_{month}[df_{month}['my_feature'] > 20]".format(month=i))
</code>```

Basically it will create a string looking the way you would type it in your script and execute it.

But maybe you should re-think and rather put the data into the same DataFrame like

```<code>df_feb['new'] = ...
</code>```

Body:
I would like to create 12 dataframes labelled with month names by using a for loop. So I created a list with the month names list_month. But I am not able to insert the variable i as df_[i] in the for loop.

The operation I am trying to do is to create a new dataframe df_new_month like df_new_feb = df_feb[df_feb['my_feature'] > 20] for each month contained in the list:

Should I follow a different approach?

list_month = ['jan','feb','mar','apr','may','jun','jul','aug','sep','oct','nov','dec']
for i in list_month:
    df_new_[i] = df_[i][df_[i]['my_feature'] > 20]
    print(i, list_month[i])

The Error I get is:

Traceback (most recent call
  last):File"/Users/annalisa/anaconda3/lib/python3.7/site_
  packages/IPython/core/interactiveshell.py", line 3325, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
  File "<ipython-input-50-c09b1f63eb51>", line 3, in <module>
    df_new_[i] = df_[i][df_[i]['my_feature'] > 20]
NameError: name 'df_' is not defined

Body:
This is rather hackish but should work, given that I understood you correctly:

list_month = ['jan','feb','mar','apr','may','jun','jul','aug','sep','oct','nov','dec']
for i in list_month:
    exec("df_new_{month} = df_{month}[df_{month}['my_feature'] > 20]".format(month=i))

Basically it will create a string looking the way you would type it in your script and execute it.

But maybe you should re-think and rather put the data into the same DataFrame like

df_feb['new'] = ...


问:
Set custom error messages in Django 3 ModelForm in default pop-out window
I'm new in Django3 and now I got a task to create custom error-messages text in default pop-out window of ModelForm.
This window:
default pop-out window, when I press submit button

Models.py

```<code>class Application_form_model(models.Model):
user_name = models.CharField(
    max_length=30,
    null=True
)
</code>```

Forms.py

```<code>class ApplicationForm(forms.ModelForm):
    class Meta:
        model = Application_form_model
        fields = (
            'user_name',
        )
        widgets = {
            'user_name': TextInput(
                attrs={
                    'placeholder': 'Введіть ім\'я'
                },
            ),
        }
        error_messages = {
            'user_name': {
                'required': _("Custom error message."),
            },
    }
</code>```

views.py

```<code>def app_form(request):
    formset = ApplicationForm(request.POST)
    if formset.is_valid():
        save_data = Application_form_model(
            user_name=formset.cleaned_data['user_name'],
        )
        save_data.save()
        return HttpResponseRedirect('')
    return render(
        request,
        'application_form/application_form.html',
        {
            'formset': formset
        }
    )
</code>```

答:
Those messages are the default validation message of elements in HTML5. You may override it by calling the method setCustomValidity.

```<code>widgets = {
            'user_name': TextInput(
                attrs={
                    'placeholder': 'Введіть ім\'я'
                    'oninvalid'="setCustomValidity('Show a custom error message')"
                },
            ),
        }
</code>```

Body:
I'm new in Django3 and now I got a task to create custom error-messages text in default pop-out window of ModelForm.
This window:
default pop-out window, when I press submit button

Models.py

class Application_form_model(models.Model):
user_name = models.CharField(
    max_length=30,
    null=True
)

Forms.py

class ApplicationForm(forms.ModelForm):
    class Meta:
        model = Application_form_model
        fields = (
            'user_name',
        )
        widgets = {
            'user_name': TextInput(
                attrs={
                    'placeholder': 'Введіть ім\'я'
                },
            ),
        }
        error_messages = {
            'user_name': {
                'required': _("Custom error message."),
            },
    }

views.py

def app_form(request):
    formset = ApplicationForm(request.POST)
    if formset.is_valid():
        save_data = Application_form_model(
            user_name=formset.cleaned_data['user_name'],
        )
        save_data.save()
        return HttpResponseRedirect('')
    return render(
        request,
        'application_form/application_form.html',
        {
            'formset': formset
        }
    )

Body:
Those messages are the default validation message of elements in HTML5. You may override it by calling the method setCustomValidity.

widgets = {
            'user_name': TextInput(
                attrs={
                    'placeholder': 'Введіть ім\'я'
                    'oninvalid'="setCustomValidity('Show a custom error message')"
                },
            ),
        }


问:
In R: Extract similar trajectory patterns from a data table
I have a data table that contains several patterns for going from a to c. These patterns are assigned to different expeditions. I want to extract similar patterns for the different expedition_id.

```<code>dt<- data.table(departure = c('a', 'a', 'a', 'b', 'a','d','a', 'b'), arrival =
       c('a','a','b','c','d','c','b','c'), expedition_id = c(1,2,1,1,3,3,2,2))

 >dt
departure      arrival    expedition_id
   a              a            1
   a              a            2
   a              b            1
   b              c            1
   a              d            3
   d              c            3
   a              b            2
   b              c            2
</code>```

The results that I am trying to get look like different data tables for each unique pattern.

```<code>>dt1

departure       arrival         expedition_list
   a                a                1,2
   a                b                1,2
   b                c                1,2

>dt2

departure       arrival         expedition_list
   a                d                3
   d                c                3
</code>```

I'd appreciate your help on this one.

答:
You asked for data.table but for others this dplyr version might also be helpful:

```<code>dt %>%
    group_by(departure, arrival) %>%
    summarise(expedition_list = paste(expedition_id, collapse = ","))
</code>```

Body:
I have a data table that contains several patterns for going from a to c. These patterns are assigned to different expeditions. I want to extract similar patterns for the different expedition_id.

dt<- data.table(departure = c('a', 'a', 'a', 'b', 'a','d','a', 'b'), arrival =
       c('a','a','b','c','d','c','b','c'), expedition_id = c(1,2,1,1,3,3,2,2))

 >dt
departure      arrival    expedition_id
   a              a            1
   a              a            2
   a              b            1
   b              c            1
   a              d            3
   d              c            3
   a              b            2
   b              c            2

The results that I am trying to get look like different data tables for each unique pattern.

>dt1

departure       arrival         expedition_list
   a                a                1,2
   a                b                1,2
   b                c                1,2

>dt2

departure       arrival         expedition_list
   a                d                3
   d                c                3

I'd appreciate your help on this one.

Body:
You asked for data.table but for others this dplyr version might also be helpful:

dt %>%
    group_by(departure, arrival) %>%
    summarise(expedition_list = paste(expedition_id, collapse = ","))


问:
Android Google Maps v2 - set zoom level for myLocation
Is it possible to change the zoom level for myLocation with the new Google Maps API v2?

If you set GoogleMap.setEnableMyLocation(true);, you get a button on the map to find your location.

If you click on it, then the map will bring you to your location and zoom it in to some level. Can I change this zoom to be less or more?

答:
Most of the answers above are either deprecated or the zoom works by retaining the current latitude and longitude and does not zoom to the exact location you want it to. Add the following code to your onMapReady() method.

```<code>@Override
public void onMapReady(GoogleMap googleMap) {
    //Set marker on the map
    googleMap.addMarker(new MarkerOptions().position(new LatLng(0.0000, 0.0000)).title("Marker"));
    //Create a CameraUpdate variable to store the intended location and zoom of the camera
    CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(new LatLng(0.0000, 0.0000), 13);
    //Animate the zoom using the animateCamera() method
    googleMap.animateCamera(cameraUpdate);
}
</code>```

Body:
Most of the answers above are either deprecated or the zoom works by retaining the current latitude and longitude and does not zoom to the exact location you want it to. Add the following code to your onMapReady() method.

@Override
public void onMapReady(GoogleMap googleMap) {
    //Set marker on the map
    googleMap.addMarker(new MarkerOptions().position(new LatLng(0.0000, 0.0000)).title("Marker"));
    //Create a CameraUpdate variable to store the intended location and zoom of the camera
    CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(new LatLng(0.0000, 0.0000), 13);
    //Animate the zoom using the animateCamera() method
    googleMap.animateCamera(cameraUpdate);
}


问:
App crashes when send data to a OBD-ii device via Bluetooth (Android-Studio)
i'm developing an application to request information to a car diagnostic scanner (like a ELM327) via Bluetooth. So, i'm using a obd-java-api (https://github.com/eltonvs/java-obd-api) for the request commands, but something goes wrong and the app crash.
I'm pretty new at java and bluetooth service, so i don't understand at all what is the problem.

Everything goes well until i use the OBD commands. I mean, it works when i connect to the socket, but don't when i use de commands.

Someone have an idea?

I'm already verified if my OBD device works using Bluetooth AT Commands with a ELM327 Terminal an goes well. I though it was a problem with the Echo function but ...i was wrong.

I tried too with the original obd java api(https://github.com/pires/obd-java-api) and had the same results.

```<code>package com.example.obd2_bluetooth_communication;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.ParcelUuid;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Set;
import java.util.UUID;

import br.ufrn.imd.obd.commands.ObdCommandGroup;
import br.ufrn.imd.obd.commands.engine.RPMCommand;
import br.ufrn.imd.obd.commands.protocol.EchoOffCommand;
import br.ufrn.imd.obd.commands.protocol.LineFeedOffCommand;
import br.ufrn.imd.obd.commands.protocol.SelectProtocolCommand;
import br.ufrn.imd.obd.commands.protocol.TimeoutCommand;
import br.ufrn.imd.obd.enums.ObdProtocols;

import static android.graphics.Color.RED;

public class MainActivity extends AppCompatActivity implements AdapterView.OnItemClickListener{

    TextView tvEstadoBT, tvRPM;
    ImageView ivEstadoBT;
    Button btnOnOff, btnPaired, btnEnviar;

    BluetoothAdapter mBlueAdapter;
    Set<BluetoothDevice> paired_devices;
    String plist[];
    ListView lvPairedDevices;
    ArrayAdapter<String> mAdapter;
    ArrayList<BluetoothDevice> mBTDevices = new ArrayList<>();

    private static UUID myuuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
    BluetoothSocket socket;
    //UUID theuuid;

    RPMCommand rpmCommand = new RPMCommand();

    static final int STATE_CONFIG = 1;
    static final int STATE_CONNECTED = 2;
    static final int STATE_CONNECTION_FAILED = 3;
    static final int STATE_ERROR = 4;
    static final int STATE_INTERRUPT = 5;
    static final int STATE_DATO_ENVIADO = 6;

    private final BroadcastReceiver mBroadcastReceiver1 = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            // When discovery finds a device
            if (action.equals(mBlueAdapter.ACTION_STATE_CHANGED)) {
                final int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, mBlueAdapter.ERROR);

                switch (state){
                    case BluetoothAdapter.STATE_OFF:
                        showToast("Bluetooth apagado");
                        btnOnOff.setText("Encender Bluetooth");
                        tvEstadoBT.setText("Bluetooth apagado");
                        tvEstadoBT.setTextColor(RED);
                        ivEstadoBT.setImageResource(R.drawable.ic_action_off);
                        btnEnviar.setEnabled(false);

                        break;

                    case BluetoothAdapter.STATE_TURNING_OFF:
                        showToast("Apagando...");
                        break;

                    case BluetoothAdapter.STATE_ON:
                        showToast("Bluetooth encendido");
                        btnOnOff.setText("Apagar Bluetooth");
                        tvEstadoBT.setText("Bluetooth encendido");
                        tvEstadoBT.setTextColor(Color.GREEN);
                        ivEstadoBT.setImageResource(R.drawable.ic_action_on);

                        break;

                    case BluetoothAdapter.STATE_TURNING_ON:
                        showToast("Encendiendo...");
                        break;

                }
            }
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mBroadcastReceiver1);
    }

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

        tvEstadoBT       = findViewById(R.id.tvEstadoBT);
        ivEstadoBT       = findViewById(R.id.ivEstadoBT);
        btnOnOff         = findViewById(R.id.btnOnOff);
        btnPaired        = findViewById(R.id.btnPaired);
        lvPairedDevices  = findViewById(R.id.lvPairedDevices);
        btnEnviar        = findViewById(R.id.btnSend);
        tvRPM            = findViewById(R.id.tvRPM);

        mBlueAdapter = BluetoothAdapter.getDefaultAdapter();

        //Verificar si el dispositivo posee Bluetooth
        if (mBlueAdapter == null) {

            showToast("Tu dispositivo no soporta la opción de Bluetooth");
        }

        //Condiciones iniciales para el botón de encendido/apagado
        if (!mBlueAdapter.isEnabled()) {
            btnOnOff.setText("Encender Bluetooth");
            tvEstadoBT.setText("Bluetooth apagado");
            tvEstadoBT.setTextColor(RED);
            ivEstadoBT.setImageResource(R.drawable.ic_action_off);
        }
        if (mBlueAdapter.isEnabled()) {
            btnOnOff.setText("Apagar Bluetooth");
            tvEstadoBT.setText("Bluetooth encendido");
            tvEstadoBT.setTextColor(Color.GREEN);
            ivEstadoBT.setImageResource(R.drawable.ic_action_on);

            }

        }

    Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull Message msg) {

            switch(msg.what)
            {
                case STATE_CONFIG:
                    showToast("Configurado");
                    btnEnviar.setEnabled(true);
                    finish();
                    break;

                case STATE_CONNECTED:
                    showToast("Conectado");
                    btnEnviar.setEnabled(true);
                    finish();
                    break;

                case STATE_CONNECTION_FAILED:
                    showToast("Conexión falló");
                    finish();
                    break;

                case STATE_ERROR:
                    showToast("Ocurrió un error");
                    ;
                    break;

                case STATE_INTERRUPT:
                    showToast("Función interrumpida");

                    break;

                case STATE_DATO_ENVIADO:

                    tvRPM.setText(rpmCommand.getFormattedResult() + " rpm");

                    break;

            }
            return false;
        }
    });

    private void showToast(String msg){

        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }

    public void OnOffCLICK(View view) {

        if(!mBlueAdapter.isEnabled()){
            //showToast("Activando Bluetooth...");
            Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivity(enableIntent);
            IntentFilter BTIntent = new IntentFilter((BluetoothAdapter.ACTION_STATE_CHANGED));
            registerReceiver(mBroadcastReceiver1, BTIntent);
        }
        if(mBlueAdapter.isEnabled()){
            mBlueAdapter.disable();

            IntentFilter BTIntent = new IntentFilter((BluetoothAdapter.ACTION_STATE_CHANGED));
            registerReceiver(mBroadcastReceiver1, BTIntent);
        }
    }

    public void PairedDevicesCLICK(View view) {

        if(!mBlueAdapter.isEnabled()){

            showToast("La función no está disponible porque el Bluettoth está apagado");
        }
        else{

            paired_devices = mBlueAdapter.getBondedDevices();
            mBTDevices = new ArrayList<>();
            int count = paired_devices.size();
            plist = new String[count];
            int j = 0;
            for(BluetoothDevice device : paired_devices)
            {
                mBTDevices.add(device);
                plist[j] = device.getName();
                j++;
            }

            mAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,plist);
            lvPairedDevices.setAdapter(mAdapter);
            lvPairedDevices.setOnItemClickListener(MainActivity.this);

        }
    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

        /*String deviceName = mBTDevices.get(i).getName();
        String deviceAddress = mBTDevices.get(i).getAddress();

        showToast("Connecting to: " + deviceName);*/
        /*ParcelUuid[] uuids = mBTDevices.get(i).getUuids();
        theuuid = UUID.fromString(uuids[0].toString());
        showToast(theuuid.toString());*/
        ClientClass cliente = new ClientClass(mBTDevices.get(i));
        cliente.start();

    }

    public void EnviarCLICK(View view) {

        ObdCommandGroup obdCommands = new ObdCommandGroup();

        obdCommands.add(new EchoOffCommand());
        obdCommands.add(new LineFeedOffCommand());
        obdCommands.add(new TimeoutCommand(255));
        obdCommands.add(new SelectProtocolCommand(ObdProtocols.AUTO));
        //obdCommands.add(new RPMCommand());
        obdCommands.add(rpmCommand);

        try {
            obdCommands.run(socket.getInputStream(), socket.getOutputStream());
            Message message = Message.obtain();
            message.what = STATE_DATO_ENVIADO;
            handler.sendMessage(message);

        } catch (IOException e) {
            e.printStackTrace();
            Message message = Message.obtain();
            message.what = STATE_ERROR;
            handler.sendMessage(message);
        } catch (InterruptedException e) {
            e.printStackTrace();
            Message message = Message.obtain();
            message.what = STATE_INTERRUPT;
            handler.sendMessage(message);
        }
    }

    private class ClientClass extends Thread{

        private BluetoothDevice OBD2;
        private BluetoothSocket socket;

        public ClientClass (BluetoothDevice device1)
        {
            OBD2 = device1;
            /*ParcelUuid[] uuids = OBD2.getUuids();

            if (uuids != null)
            {
                theuuid = UUID.fromString(uuids[0].toString());
                //showToast(theuuid.toString());
            }*/

            try {
                //socket = OBD2.createInsecureRfcommSocketToServiceRecord(theuuid);
                socket = OBD2.createInsecureRfcommSocketToServiceRecord(myuuid);
            } catch (IOException e) {
                e.printStackTrace();
                Message message = Message.obtain();
                message.what = STATE_ERROR;
                handler.sendMessage(message);
            }
        }

        public void run()
        {
            mBlueAdapter.cancelDiscovery();
            try {
                socket.connect();
                Message message = Message.obtain();
                message.what = STATE_CONNECTED;
                handler.sendMessage(message);

            } catch (IOException e) {
                e.printStackTrace();
                try {
                    socket.close();
                    Message message = Message.obtain();
                    message.what = STATE_CONNECTION_FAILED;
                    handler.sendMessage(message);
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
                return;

            }
        }
    }
}
</code>```

I expect RPMcommand result, but app crashes when i request that.

答:
I'm the creator of the library you're using. First of all, thanks for using my project!

Reading your error log, I saw that you're having a problem with your broadcast receiver, and not with the OBD api. I think you forgot to register the receiver in the onCreate method (since you're trying to unregister in the onDestroy).

Body:
i'm developing an application to request information to a car diagnostic scanner (like a ELM327) via Bluetooth. So, i'm using a obd-java-api (https://github.com/eltonvs/java-obd-api) for the request commands, but something goes wrong and the app crash.
I'm pretty new at java and bluetooth service, so i don't understand at all what is the problem.

Everything goes well until i use the OBD commands. I mean, it works when i connect to the socket, but don't when i use de commands.

Someone have an idea?

I'm already verified if my OBD device works using Bluetooth AT Commands with a ELM327 Terminal an goes well. I though it was a problem with the Echo function but ...i was wrong.

I tried too with the original obd java api(https://github.com/pires/obd-java-api) and had the same results.

package com.example.obd2_bluetooth_communication;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.ParcelUuid;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Set;
import java.util.UUID;

import br.ufrn.imd.obd.commands.ObdCommandGroup;
import br.ufrn.imd.obd.commands.engine.RPMCommand;
import br.ufrn.imd.obd.commands.protocol.EchoOffCommand;
import br.ufrn.imd.obd.commands.protocol.LineFeedOffCommand;
import br.ufrn.imd.obd.commands.protocol.SelectProtocolCommand;
import br.ufrn.imd.obd.commands.protocol.TimeoutCommand;
import br.ufrn.imd.obd.enums.ObdProtocols;

import static android.graphics.Color.RED;

public class MainActivity extends AppCompatActivity implements AdapterView.OnItemClickListener{

    TextView tvEstadoBT, tvRPM;
    ImageView ivEstadoBT;
    Button btnOnOff, btnPaired, btnEnviar;

    BluetoothAdapter mBlueAdapter;
    Set<BluetoothDevice> paired_devices;
    String plist[];
    ListView lvPairedDevices;
    ArrayAdapter<String> mAdapter;
    ArrayList<BluetoothDevice> mBTDevices = new ArrayList<>();

    private static UUID myuuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
    BluetoothSocket socket;
    //UUID theuuid;

    RPMCommand rpmCommand = new RPMCommand();

    static final int STATE_CONFIG = 1;
    static final int STATE_CONNECTED = 2;
    static final int STATE_CONNECTION_FAILED = 3;
    static final int STATE_ERROR = 4;
    static final int STATE_INTERRUPT = 5;
    static final int STATE_DATO_ENVIADO = 6;

    private final BroadcastReceiver mBroadcastReceiver1 = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            // When discovery finds a device
            if (action.equals(mBlueAdapter.ACTION_STATE_CHANGED)) {
                final int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, mBlueAdapter.ERROR);

                switch (state){
                    case BluetoothAdapter.STATE_OFF:
                        showToast("Bluetooth apagado");
                        btnOnOff.setText("Encender Bluetooth");
                        tvEstadoBT.setText("Bluetooth apagado");
                        tvEstadoBT.setTextColor(RED);
                        ivEstadoBT.setImageResource(R.drawable.ic_action_off);
                        btnEnviar.setEnabled(false);

                        break;

                    case BluetoothAdapter.STATE_TURNING_OFF:
                        showToast("Apagando...");
                        break;

                    case BluetoothAdapter.STATE_ON:
                        showToast("Bluetooth encendido");
                        btnOnOff.setText("Apagar Bluetooth");
                        tvEstadoBT.setText("Bluetooth encendido");
                        tvEstadoBT.setTextColor(Color.GREEN);
                        ivEstadoBT.setImageResource(R.drawable.ic_action_on);

                        break;

                    case BluetoothAdapter.STATE_TURNING_ON:
                        showToast("Encendiendo...");
                        break;

                }
            }
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mBroadcastReceiver1);
    }

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

        tvEstadoBT       = findViewById(R.id.tvEstadoBT);
        ivEstadoBT       = findViewById(R.id.ivEstadoBT);
        btnOnOff         = findViewById(R.id.btnOnOff);
        btnPaired        = findViewById(R.id.btnPaired);
        lvPairedDevices  = findViewById(R.id.lvPairedDevices);
        btnEnviar        = findViewById(R.id.btnSend);
        tvRPM            = findViewById(R.id.tvRPM);

        mBlueAdapter = BluetoothAdapter.getDefaultAdapter();

        //Verificar si el dispositivo posee Bluetooth
        if (mBlueAdapter == null) {

            showToast("Tu dispositivo no soporta la opción de Bluetooth");
        }

        //Condiciones iniciales para el botón de encendido/apagado
        if (!mBlueAdapter.isEnabled()) {
            btnOnOff.setText("Encender Bluetooth");
            tvEstadoBT.setText("Bluetooth apagado");
            tvEstadoBT.setTextColor(RED);
            ivEstadoBT.setImageResource(R.drawable.ic_action_off);
        }
        if (mBlueAdapter.isEnabled()) {
            btnOnOff.setText("Apagar Bluetooth");
            tvEstadoBT.setText("Bluetooth encendido");
            tvEstadoBT.setTextColor(Color.GREEN);
            ivEstadoBT.setImageResource(R.drawable.ic_action_on);

            }

        }

    Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull Message msg) {

            switch(msg.what)
            {
                case STATE_CONFIG:
                    showToast("Configurado");
                    btnEnviar.setEnabled(true);
                    finish();
                    break;

                case STATE_CONNECTED:
                    showToast("Conectado");
                    btnEnviar.setEnabled(true);
                    finish();
                    break;

                case STATE_CONNECTION_FAILED:
                    showToast("Conexión falló");
                    finish();
                    break;

                case STATE_ERROR:
                    showToast("Ocurrió un error");
                    ;
                    break;

                case STATE_INTERRUPT:
                    showToast("Función interrumpida");

                    break;

                case STATE_DATO_ENVIADO:

                    tvRPM.setText(rpmCommand.getFormattedResult() + " rpm");

                    break;

            }
            return false;
        }
    });

    private void showToast(String msg){

        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }

    public void OnOffCLICK(View view) {

        if(!mBlueAdapter.isEnabled()){
            //showToast("Activando Bluetooth...");
            Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivity(enableIntent);
            IntentFilter BTIntent = new IntentFilter((BluetoothAdapter.ACTION_STATE_CHANGED));
            registerReceiver(mBroadcastReceiver1, BTIntent);
        }
        if(mBlueAdapter.isEnabled()){
            mBlueAdapter.disable();

            IntentFilter BTIntent = new IntentFilter((BluetoothAdapter.ACTION_STATE_CHANGED));
            registerReceiver(mBroadcastReceiver1, BTIntent);
        }
    }

    public void PairedDevicesCLICK(View view) {

        if(!mBlueAdapter.isEnabled()){

            showToast("La función no está disponible porque el Bluettoth está apagado");
        }
        else{

            paired_devices = mBlueAdapter.getBondedDevices();
            mBTDevices = new ArrayList<>();
            int count = paired_devices.size();
            plist = new String[count];
            int j = 0;
            for(BluetoothDevice device : paired_devices)
            {
                mBTDevices.add(device);
                plist[j] = device.getName();
                j++;
            }

            mAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,plist);
            lvPairedDevices.setAdapter(mAdapter);
            lvPairedDevices.setOnItemClickListener(MainActivity.this);

        }
    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

        /*String deviceName = mBTDevices.get(i).getName();
        String deviceAddress = mBTDevices.get(i).getAddress();

        showToast("Connecting to: " + deviceName);*/
        /*ParcelUuid[] uuids = mBTDevices.get(i).getUuids();
        theuuid = UUID.fromString(uuids[0].toString());
        showToast(theuuid.toString());*/
        ClientClass cliente = new ClientClass(mBTDevices.get(i));
        cliente.start();

    }

    public void EnviarCLICK(View view) {

        ObdCommandGroup obdCommands = new ObdCommandGroup();

        obdCommands.add(new EchoOffCommand());
        obdCommands.add(new LineFeedOffCommand());
        obdCommands.add(new TimeoutCommand(255));
        obdCommands.add(new SelectProtocolCommand(ObdProtocols.AUTO));
        //obdCommands.add(new RPMCommand());
        obdCommands.add(rpmCommand);

        try {
            obdCommands.run(socket.getInputStream(), socket.getOutputStream());
            Message message = Message.obtain();
            message.what = STATE_DATO_ENVIADO;
            handler.sendMessage(message);

        } catch (IOException e) {
            e.printStackTrace();
            Message message = Message.obtain();
            message.what = STATE_ERROR;
            handler.sendMessage(message);
        } catch (InterruptedException e) {
            e.printStackTrace();
            Message message = Message.obtain();
            message.what = STATE_INTERRUPT;
            handler.sendMessage(message);
        }
    }

    private class ClientClass extends Thread{

        private BluetoothDevice OBD2;
        private BluetoothSocket socket;

        public ClientClass (BluetoothDevice device1)
        {
            OBD2 = device1;
            /*ParcelUuid[] uuids = OBD2.getUuids();

            if (uuids != null)
            {
                theuuid = UUID.fromString(uuids[0].toString());
                //showToast(theuuid.toString());
            }*/

            try {
                //socket = OBD2.createInsecureRfcommSocketToServiceRecord(theuuid);
                socket = OBD2.createInsecureRfcommSocketToServiceRecord(myuuid);
            } catch (IOException e) {
                e.printStackTrace();
                Message message = Message.obtain();
                message.what = STATE_ERROR;
                handler.sendMessage(message);
            }
        }

        public void run()
        {
            mBlueAdapter.cancelDiscovery();
            try {
                socket.connect();
                Message message = Message.obtain();
                message.what = STATE_CONNECTED;
                handler.sendMessage(message);

            } catch (IOException e) {
                e.printStackTrace();
                try {
                    socket.close();
                    Message message = Message.obtain();
                    message.what = STATE_CONNECTION_FAILED;
                    handler.sendMessage(message);
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
                return;

            }
        }
    }
}

I expect RPMcommand result, but app crashes when i request that.


问:
Flutter positioning widgets in Column

I am trying to set an image in the center of Column, and the Text at the bottom of the image, by wrapping Image and Text in the Column widget and placing it in the Center widget.

Unfortunately, it centers the Column and makes Image to be above the center of the screen.

How can I solve it?

My current code:

```<code>  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: BoxDecoration(color: Theme.of(context).primaryColor),
      child: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Image.asset(ImagePaths.newLogoLogin),
            Text(Strings.beALocal)
          ],
        ),
      ),
    );
  }
</code>```

答:
This can be achieved using the Expanded widget:

```<code>@override
Widget build(BuildContext context) {
  return Container(
    decoration: BoxDecoration(color: Theme.of(context).primaryColor),
    child: Column(
      children: [
        Spacer(),
        Image.asset(ImagePaths.newLogoLogin),
        Expanded(
          Column(
             children: [ Text(Strings.beALocal) ],
             mainAxisAlignment: MainAxisAlignment.start
          )
        )
      ],
    ),
  );
}
</code>```

Title: Flutter positioning widgets in Column

Body:
I am trying to set an image in the center of Column, and the Text at the bottom of the image, by wrapping Image and Text in the Column widget and placing it in the Center widget.

Unfortunately, it centers the Column and makes Image to be above the center of the screen.

How can I solve it?

My current code:

  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: BoxDecoration(color: Theme.of(context).primaryColor),
      child: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Image.asset(ImagePaths.newLogoLogin),
            Text(Strings.beALocal)
          ],
        ),
      ),
    );
  }

Body:
This can be achieved using the Expanded widget:

@override
Widget build(BuildContext context) {
  return Container(
    decoration: BoxDecoration(color: Theme.of(context).primaryColor),
    child: Column(
      children: [
        Spacer(),
        Image.asset(ImagePaths.newLogoLogin),
        Expanded(
          Column(
             children: [ Text(Strings.beALocal) ],
             mainAxisAlignment: MainAxisAlignment.start
          )
        )
      ],
    ),
  );
}


问:
req.cookies returns undefined but cookies are set
I am using cookie-parser in my express app. When the root page is requested I set a random number on the cookie using res.cookie(name, value) and it sets it fine (I checked on my browser console). But when I try to log req.cookie it always returns undefined.

Here's my code:

routes.js

```<code>var express = require('express')
var router = express.Router()

var movieTrailer = require('movie-trailer');

var Promise = require('bluebird');
var logs = require('log-switch');
var fs = require('fs');
//var cookieParser = require('cookie-parser');

//Setup x-ray for scraping
var Xray = require('x-ray');
var x = Xray();

var debug = false;

router.get('/', (req, res) => {
  console.log('Page requested!');
  console.log('Cookies: ', req.headers.cookies); // For some reason this returns undefined

  var scrapeMovies = function(){
    return new Promise((resolve, reject) =>{
      fs.readFile('moviesRT.json', (err,data) =>{
        var movies = JSON.parse(data);
        resolve(movies);
      });
    });
  };

scrapeMovies().then(
    movies => {
      var randomInt = Math.floor(Math.random() * movies.length);
      res.cookie('randomInt', randomInt);
      var randomMovie = movies[randomInt];
      movieTrailer(randomMovie.title, (err, url) =>{
        console.log('Requesting trailer: ', randomMovie.title);
        if(err) throw err;
        var embedUrl = url.replace('watch?v=','embed/');
        console.log('Video ID: ', url.slice(32,url.length));
        randomMovie.trailerURL = embedUrl; //Add the embed URL to the randomMovie object before rendering it
        res.render('main',randomMovie,
        (err, html) =>
        {
          if(err) throw err;
          console.log('Rendering...');
          res.send(html);
          console.log("Done!");
        });
      });
    });

});

module.exports = router;
</code>```

app.js

```<code>const express = require('express');

//Define app and settings
const app = express();
const exphbs = require('express-handlebars');
var cookieParser = require('cookie-parser');
const port = 3000;

var routes = require('./routes');

var debug = true;

app.use('/', routes);
app.use(express.static('public'));
app.use(cookieParser());
//app.use(cookieParser());

//View engine
app.engine('handlebars', exphbs({defaultLayout: 'main'}));
app.set('view engine', 'handlebars');

app.listen(port, function () {
  console.log(`Server Starts on ${port}`);
  if(!debug) logs.disable(); //Disable logging if debug variable is false
});
</code>```

答:
This happened to me, when I sent a PUT request from the client-side (Angular) without passing the body object.

I was doing this (second argument missing):

```<code>requestBranchEditPermission() {
  return this.http.put<IPutProfile>(`${this.api}/some-endpoint`, this.options).toPromise();
}
</code>```

instead of this:

```<code>requestBranchEditPermission() {
  return this.http.put<IPutProfile>(`${this.api}/some-endpoint`, {}, this.options).toPromise();
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am using cookie-parser in my express app. When the root page is requested I set a random number on the cookie using res.cookie(name, value) and it sets it fine (I checked on my browser console). But when I try to log req.cookie it always returns undefined.

Here's my code:

routes.js

var express = require('express')
var router = express.Router()

var movieTrailer = require('movie-trailer');

var Promise = require('bluebird');
var logs = require('log-switch');
var fs = require('fs');
//var cookieParser = require('cookie-parser');

//Setup x-ray for scraping
var Xray = require('x-ray');
var x = Xray();

var debug = false;

router.get('/', (req, res) => {
  console.log('Page requested!');
  console.log('Cookies: ', req.headers.cookies); // For some reason this returns undefined

  var scrapeMovies = function(){
    return new Promise((resolve, reject) =>{
      fs.readFile('moviesRT.json', (err,data) =>{
        var movies = JSON.parse(data);
        resolve(movies);
      });
    });
  };

scrapeMovies().then(
    movies => {
      var randomInt = Math.floor(Math.random() * movies.length);
      res.cookie('randomInt', randomInt);
      var randomMovie = movies[randomInt];
      movieTrailer(randomMovie.title, (err, url) =>{
        console.log('Requesting trailer: ', randomMovie.title);
        if(err) throw err;
        var embedUrl = url.replace('watch?v=','embed/');
        console.log('Video ID: ', url.slice(32,url.length));
        randomMovie.trailerURL = embedUrl; //Add the embed URL to the randomMovie object before rendering it
        res.render('main',randomMovie,
        (err, html) =>
        {
          if(err) throw err;
          console.log('Rendering...');
          res.send(html);
          console.log("Done!");
        });
      });
    });

});

module.exports = router;

app.js

const express = require('express');

//Define app and settings
const app = express();
const exphbs = require('express-handlebars');
var cookieParser = require('cookie-parser');
const port = 3000;

var routes = require('./routes');

var debug = true;

app.use('/', routes);
app.use(express.static('public'));
app.use(cookieParser());
//app.use(cookieParser());

//View engine
app.engine('handlebars', exphbs({defaultLayout: 'main'}));
app.set('view engine', 'handlebars');

app.listen(port, function () {
  console.log(`Server Starts on ${port}`);
  if(!debug) logs.disable(); //Disable logging if debug variable is false
});

Body:
This happened to me, when I sent a PUT request from the client-side (Angular) without passing the body object.

I was doing this (second argument missing):

requestBranchEditPermission() {
  return this.http.put<IPutProfile>(`${this.api}/some-endpoint`, this.options).toPromise();
}

instead of this:

requestBranchEditPermission() {
  return this.http.put<IPutProfile>(`${this.api}/some-endpoint`, {}, this.options).toPromise();
}


问:
compare list values withina python dictionary
I think it is very basic, but I struggle to find a way to solve this.
In a python dictionary like below (where values are lists), how can I conveniently compare values of each key-value pair?
For example, how can I retrieve the key-value pairs where:

Elements of values are not repeated in values of other key-value pairs,

If the first element of the value present in other values, select the pair where the second element of the value in larger.

In other words, I need to get

```<code>"a": ["bc", "5", "0"]
"b": ["nc", "8", "5"]
</code>```

```<code>test_dict = {"a": ["bc", "5", "0"], "b": ["nc", "8", "5"], "c": ["bc", "3", "0"]}
</code>```

Any hint is appreciated.

答:
I would use an auxilliary mapping indexed by first element of the value:</p>

```<code>aux = {}
for k, v in test_dict.items():
    if v[0] in aux:
        if v[1] > aux[v[0]][1][1]:
            aux[v[0]] = (k, v)
    else: aux[v[0]] = (k, v)
resul = {k: v for k,v in aux.values()}
</code>```

Body:
I think it is very basic, but I struggle to find a way to solve this.
In a python dictionary like below (where values are lists), how can I conveniently compare values of each key-value pair?
For example, how can I retrieve the key-value pairs where:

Elements of values are not repeated in values of other key-value pairs,

If the first element of the value present in other values, select the pair where the second element of the value in larger.

In other words, I need to get

"a": ["bc", "5", "0"]
"b": ["nc", "8", "5"]

test_dict = {"a": ["bc", "5", "0"], "b": ["nc", "8", "5"], "c": ["bc", "3", "0"]}

Any hint is appreciated.

Body:
I would use an auxilliary mapping indexed by first element of the value:

aux = {}
for k, v in test_dict.items():
    if v[0] in aux:
        if v[1] > aux[v[0]][1][1]:
            aux[v[0]] = (k, v)
    else: aux[v[0]] = (k, v)
resul = {k: v for k,v in aux.values()}


问:
Select rows where elements of two arrays don't match a pattern
I try to write a query where I select rows based one a LIKE pattern that has to match none of the entries of an array. What I have is the current one

```<code>SELECT * FROM mytable WHERE
NOT (EXISTS (SELECT * from unnest(a) WHERE  unnest LIKE '%XYZ%' )))
</code>```

Actually what I want is pairs - so it is more like

```<code>SELECT * FROM mytable WHERE
NOT (
  (EXISTS (select * from unnest(a) as A, unnest(b) as B  WHERE  A||B LIKE '%xyz%abc%' )) OR
  (EXISTS (select * from unnest(a) as A, unnest(b) as B  WHERE  A||B LIKE '%abc%xyz%' ))
)
</code>```

This works for me but looks rather unwieldy. Is there prettier/more efficient solution to this? What I am find the most irksome is the SELECT as part of the WHERE clause to unroll arrays.

some points:

In my case xyz and abc will not appear together as substrings in a single array entry (e.g. nothing like xyzblaabcexists)

Both arrays have exactly the same number of elements (they are actually derived from another query)

no null elements (but even if that would still work as then I don't have a pair of abc and xyz)

Edit:

Clarification: a row contains A as {rxyz,foo, bar} and B as {other, abc, this} should not be returned as it contains the rxyz in one array and abc in the other

Example:

```<code>SELECT * FROM(
 SELECT *
    FROM   (select 1 as ID, '{rxyz,foo,bar}'::varchar[] as a, '{abc,other,this}'::varchar[] as b) row1  UNION
 SELECT *
    FROM   (select 2 as ID, '{rxyz,foo,bar}'::varchar[] as a, '{other,rabc,this}'::varchar[] as b) row1  UNION
 SELECT *
    FROM   (select 3 as ID, '{else,foo,bar}'::varchar[] as a, '{abc,other,this}'::varchar[] as b) row2

    ) mytable
WHERE
NOT (
  (EXISTS (select * from unnest(a) as A, unnest(b) as B  WHERE  A||'-|-'||B LIKE '%xyz%-|-%abc%' OR B||'-|-'||A LIKE '%xyz%-|-%abc%' )))
</code>```

returns only row3. In my use case I can guaranty that -|- is not part of either list making it possible to separate these.

答:
The updated task description is:

Eliminate rows where any element of text array a contains one of ('abc', 'xyz') and any element of text array b contains the other.

Your second query achieves that, but at terrible cost. unnest(a) as A, unnest(b) combines every element of array a with every element of array b - a Cartesian product, O(N²), makes performance deteriorate quickly with longer arrays.

Try one of these instead:

Test against concatenated strings with CROSS JOIN:

```<code>SELECT t.*
FROM   tbl t, array_to_string(a, '|') AS a_string, array_to_string(b, '|') AS b_string
WHERE (a_string LIKE '%abc%' AND b_string LIKE '%xyz%'
   OR  a_string LIKE '%xyz%' AND b_string LIKE '%abc%') IS NOT TRUE;
</code>```

Make sure to choose a separator that cannot produce false matches. '|' in the example.

Test against concatenated strings with NOT EXISTS:

```<code>SELECT *
FROM   tbl t
WHERE  NOT EXISTS (
   SELECT FROM array_to_string(a, '|') a_string
             , array_to_string(b, '|') b_string
   WHERE  a_string LIKE '%abc%' AND b_string LIKE '%xyz%'
      OR  a_string LIKE '%xyz%' AND b_string LIKE '%abc%'
   );
</code>```

Test unnested elements with LATERAL subquery;

```<code>SELECT t.*
FROM   tbl t
JOIN   LATERAL (
   SELECT bool_or(a_elem LIKE '%abc%') AND bool_or(b_elem LIKE '%xyz%')
       OR bool_or(a_elem LIKE '%xyz%') AND bool_or(b_elem LIKE '%abc%') AS exclude
   FROM   unnest(t.a,t.b) e(a_elem, b_elem)
   ) x ON exclude IS NOT TRUE;
</code>```

Test unnested elements with NOT EXISTS

```<code>SELECT *
FROM   tbl t
WHERE  NOT EXISTS (
   SELECT FROM unnest(t.a,t.b) AS e(a_elem, b_elem)
   HAVING bool_or(a_elem LIKE '%abc%') AND bool_or(b_elem LIKE '%xyz%')
       OR bool_or(a_elem LIKE '%xyz%') AND bool_or(b_elem LIKE '%abc%')
   );
</code>```

db<>fiddle here

The last one is my favorite. NNot sure which one performs best. All of them should perform substantially faster than what you have now.

About unnest(a,b):

Unnest multiple arrays in parallel

Some comments on your points

In my case xyz and abc will not appear together as substrings in a single array entry (e.g. nothing like xyzblaabcexists).

That's a big assumption. There may be good reasons for it, but are you sure there are no corner cases, not now, not ever? Else your code will break silently later and it will be extremely hard to determine the cause.

Both arrays have exactly the same number of elements (they are actually derived from another query)

The most efficient query would then typically be to apply the filter at the source, in that other query - if at all possible. Might even use an appropriate index. Like, a trigram index:

PostgreSQL LIKE query performance variations

no null elements (but even if that would still work as then I don't have a pair of abc and xyz)

Fair enough. But be wary of NULL values doing what you want if there are some.

Body:
I try to write a query where I select rows based one a LIKE pattern that has to match none of the entries of an array. What I have is the current one

SELECT * FROM mytable WHERE
NOT (EXISTS (SELECT * from unnest(a) WHERE  unnest LIKE '%XYZ%' )))

Actually what I want is pairs - so it is more like

SELECT * FROM mytable WHERE
NOT (
  (EXISTS (select * from unnest(a) as A, unnest(b) as B  WHERE  A||B LIKE '%xyz%abc%' )) OR
  (EXISTS (select * from unnest(a) as A, unnest(b) as B  WHERE  A||B LIKE '%abc%xyz%' ))
)

This works for me but looks rather unwieldy. Is there prettier/more efficient solution to this? What I am find the most irksome is the SELECT as part of the WHERE clause to unroll arrays.

some points:

In my case xyz and abc will not appear together as substrings in a single array entry (e.g. nothing like xyzblaabcexists)

Both arrays have exactly the same number of elements (they are actually derived from another query)

no null elements (but even if that would still work as then I don't have a pair of abc and xyz)

Edit:

Clarification: a row contains A as {rxyz,foo, bar} and B as {other, abc, this} should not be returned as it contains the rxyz in one array and abc in the other

Example:

SELECT * FROM(
 SELECT *
    FROM   (select 1 as ID, '{rxyz,foo,bar}'::varchar[] as a, '{abc,other,this}'::varchar[] as b) row1  UNION
 SELECT *
    FROM   (select 2 as ID, '{rxyz,foo,bar}'::varchar[] as a, '{other,rabc,this}'::varchar[] as b) row1  UNION
 SELECT *
    FROM   (select 3 as ID, '{else,foo,bar}'::varchar[] as a, '{abc,other,this}'::varchar[] as b) row2

    ) mytable
WHERE
NOT (
  (EXISTS (select * from unnest(a) as A, unnest(b) as B  WHERE  A||'-|-'||B LIKE '%xyz%-|-%abc%' OR B||'-|-'||A LIKE '%xyz%-|-%abc%' )))

returns only row3. In my use case I can guaranty that -|- is not part of either list making it possible to separate these.

Body:
The updated task description is:

Eliminate rows where any element of text array a contains one of ('abc', 'xyz') and any element of text array b contains the other.

Your second query achieves that, but at terrible cost. unnest(a) as A, unnest(b) combines every element of array a with every element of array b - a Cartesian product, O(N²), makes performance deteriorate quickly with longer arrays.

Try one of these instead:

Test against concatenated strings with CROSS JOIN:

SELECT t.*
FROM   tbl t, array_to_string(a, '|') AS a_string, array_to_string(b, '|') AS b_string
WHERE (a_string LIKE '%abc%' AND b_string LIKE '%xyz%'
   OR  a_string LIKE '%xyz%' AND b_string LIKE '%abc%') IS NOT TRUE;

Make sure to choose a separator that cannot produce false matches. '|' in the example.

Test against concatenated strings with NOT EXISTS:

SELECT *
FROM   tbl t
WHERE  NOT EXISTS (
   SELECT FROM array_to_string(a, '|') a_string
             , array_to_string(b, '|') b_string
   WHERE  a_string LIKE '%abc%' AND b_string LIKE '%xyz%'
      OR  a_string LIKE '%xyz%' AND b_string LIKE '%abc%'
   );

Test unnested elements with LATERAL subquery;

SELECT t.*
FROM   tbl t
JOIN   LATERAL (
   SELECT bool_or(a_elem LIKE '%abc%') AND bool_or(b_elem LIKE '%xyz%')
       OR bool_or(a_elem LIKE '%xyz%') AND bool_or(b_elem LIKE '%abc%') AS exclude
   FROM   unnest(t.a,t.b) e(a_elem, b_elem)
   ) x ON exclude IS NOT TRUE;

Test unnested elements with NOT EXISTS

SELECT *
FROM   tbl t
WHERE  NOT EXISTS (
   SELECT FROM unnest(t.a,t.b) AS e(a_elem, b_elem)
   HAVING bool_or(a_elem LIKE '%abc%') AND bool_or(b_elem LIKE '%xyz%')
       OR bool_or(a_elem LIKE '%xyz%') AND bool_or(b_elem LIKE '%abc%')
   );

db<>fiddle here

The last one is my favorite. NNot sure which one performs best. All of them should perform substantially faster than what you have now.

About unnest(a,b):

Unnest multiple arrays in parallel

Some comments on your points

In my case xyz and abc will not appear together as substrings in a single array entry (e.g. nothing like xyzblaabcexists).

That's a big assumption. There may be good reasons for it, but are you sure there are no corner cases, not now, not ever? Else your code will break silently later and it will be extremely hard to determine the cause.

Both arrays have exactly the same number of elements (they are actually derived from another query)

The most efficient query would then typically be to apply the filter at the source, in that other query - if at all possible. Might even use an appropriate index. Like, a trigram index:

PostgreSQL LIKE query performance variations

no null elements (but even if that would still work as then I don't have a pair of abc and xyz)

Fair enough. But be wary of NULL values doing what you want if there are some.


问:
Test where ID not in (n, n1, n2)
Given a value, #some_id = x, what's the proper syntax or method to test that the id does not exist in a collection of id's?

For example...

```<code>if($some_id not in array(3, 5, 9)){
  //do something
}
</code>```

答:
in_array
  too slow

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

if(!isset($array[$some_id])){ // do something }
</code>```

Title: Test where ID not in (n, n1, n2)

Body:
Given a value, #some_id = x, what's the proper syntax or method to test that the id does not exist in a collection of id's?

For example...

if($some_id not in array(3, 5, 9)){
  //do something
}

Body:
in_array
  too slow

$array = array_flip($array);

if(!isset($array[$some_id])){ // do something }


问:
C# Label Printing Nothing
Currently trying to make a few labels dynamically via c# & winforms. Basically want to add a part number and if it exists a lot number to a new label.

I wrote this code which works as expected:

```<code>string[] item_list = { "PN=12345678", "PN=1234-5678-0001", "PN=1234-4321-0001;LOT=xyz" };
string PN_EQ = "";
string LOT_EQ = "";
string final_form = "";

foreach (string item in item_list)
{
    LOT_EQ = ""; // Clear BK_EQ after every iteration
    string[] split = item.Split(';');
    PN_EQ = split[0].Substring(3, split[0].Length - 3); // Removing PN=, will always exists
    final_form = string.Format("PN_EQ:{0}", PN_EQ);
    if(split.Length == 2)
    {
        LOT_EQ = split[1].Substring(4, split[1].Length - 4); // Removing LOT= if it exists
        final_form = final_form + string.Format(" LOT_EQ: {0}", LOT_EQ);
    }
    Console.WriteLine(final_form);
}
</code>```

Outputs, as expected:

```<code>PN_EQ: 12345678
PN_EQ: 1234-5678-0001
PN_EQ: 1234-4321-0001 LOT_EQ: xyz
</code>```

So I took this logic to the world of labels

```<code>string[] item_list = { "PN=12345678", "PN=1234-5678-0001", "PN=1234-4321-0001;LOT=xyz" };
string PN_EQ = "";
string LOT_EQ = "";
List<Label> labels = new List<Label>();
foreach (string item in item_list)
{
    Label lbl = new Label(); // create new label for each thing
    LOT_EQ = ""; // Clear BK_EQ after every iteration
    string[] split = item.Split(';');
    PN_EQ = split[0].Substring(3, split[0].Length - 3); // Removing PN=, will always exists
    lbl.Name = PN_EQ // Unique Names for each label
    lbl.Text = string.Format("PN_EQ:{0}", PN_EQ);
    if(split.Length == 2)
    {
        LOT_EQ = split[1].Substring(4, split[1].Length - 4); // Removing LOT= if it exists
        lbl.Text = lbl.Text + string.Format(" LOT_EQ: {0}", LOT_EQ);
    }
    labels.Add(lbl);
    this.Controls.Add(lbl);
}
</code>```

Then outputs when prompted:

```<code>PN_EQ: 12345678
PN_EQ: // Should be output
PN_EQ: // Should be output
</code>```

But they are not! Wondering if anyone knows why

答:
Let's extract method:

```<code>private static string FormatMe(string value) {
  if (string.IsNullOrEmpty(value))
    return value;
  else if (!value.StartsWith("PN="))
    return value;

  int lot = value.IndexOf(";LOT=", 3);

  if (lot >= 0)
    return $"PN_EQ: {value.Substring(3, lot - 3)} LOT_EQ: {value.Substring(lot + 5)}";
  else
    return $"PN_EQ: {value.Substring(3)}";
}
</code>```

Let's have a look:

```<code>  string[] item_list = {
    "PN=12345678",
    "PN=1234-5678-0001",
    "PN=1234-4321-0001;LOT=xyz"
  };

  string report = string.Join(Environment.NewLine, item_list
    .Select(item => FormatMe(item)));

  Console.Write(report);
</code>```

Outcome:

```<code>PN_EQ: 12345678
PN_EQ: 1234-5678-0001
PN_EQ: 1234-4321-0001 LOT_EQ: xyz
</code>```

Time to create Labels (assuming WinForms):

```<code> using System.Linq;

  ...

  string[] item_list = {
    "PN=12345678",
    "PN=1234-5678-0001",
    "PN=1234-4321-0001;LOT=xyz"
  };

  // let's query item_list:
  //   for each item within item_list
  //   we create a Label
  //   all the labels we materialize in a List
  List<Label> labels = item_list
    .Select((item, index) => new Label() {
      Text     = FormatMe(item),
      Location = new Point(10, 50 + 40 * index), //TODO: put the right locations here
      AutoSize = true,
      Parent   = this, // Instead of this.Controls.Add(...);
     })
    .ToList();
</code>```

Edit: Alternative no Linq but loop solution:

```<code>    List<Label> labels = new List<Label>(item_list.Length);

    for (int index = 0; index < item_list.Length; ++index)
      labels.Add(new Label() {
        Text     = FormatMe(item_list[index]),
        Location = new Point(10, 50 + 40 * index), //TODO: put the right locations here
        AutoSize = true,
        Parent   = this, // Instead of this.Controls.Add(...);
     });
</code>```

Title: C# Label Printing Nothing

Body:
Currently trying to make a few labels dynamically via c# & winforms. Basically want to add a part number and if it exists a lot number to a new label.

I wrote this code which works as expected:

string[] item_list = { "PN=12345678", "PN=1234-5678-0001", "PN=1234-4321-0001;LOT=xyz" };
string PN_EQ = "";
string LOT_EQ = "";
string final_form = "";

foreach (string item in item_list)
{
    LOT_EQ = ""; // Clear BK_EQ after every iteration
    string[] split = item.Split(';');
    PN_EQ = split[0].Substring(3, split[0].Length - 3); // Removing PN=, will always exists
    final_form = string.Format("PN_EQ:{0}", PN_EQ);
    if(split.Length == 2)
    {
        LOT_EQ = split[1].Substring(4, split[1].Length - 4); // Removing LOT= if it exists
        final_form = final_form + string.Format(" LOT_EQ: {0}", LOT_EQ);
    }
    Console.WriteLine(final_form);
}

Outputs, as expected:

PN_EQ: 12345678
PN_EQ: 1234-5678-0001
PN_EQ: 1234-4321-0001 LOT_EQ: xyz

So I took this logic to the world of labels

string[] item_list = { "PN=12345678", "PN=1234-5678-0001", "PN=1234-4321-0001;LOT=xyz" };
string PN_EQ = "";
string LOT_EQ = "";
List labels = new List();
foreach (string item in item_list)
{
    Label lbl = new Label(); // create new label for each thing
    LOT_EQ = ""; // Clear BK_EQ after every iteration
    string[] split = item.Split(';');
    PN_EQ = split[0].Substring(3, split[0].Length - 3); // Removing PN=, will always exists
    lbl.Name = PN_EQ // Unique Names for each label
    lbl.Text = string.Format("PN_EQ:{0}", PN_EQ);
    if(split.Length == 2)
    {
        LOT_EQ = split[1].Substring(4, split[1].Length - 4); // Removing LOT= if it exists
        lbl.Text = lbl.Text + string.Format(" LOT_EQ: {0}", LOT_EQ);
    }
    labels.Add(lbl);
    this.Controls.Add(lbl);
}

Then outputs when prompted:

PN_EQ: 12345678
PN_EQ: // Should be output
PN_EQ: // Should be output

But they are not! Wondering if anyone knows why

Body:
Let's extract method:

private static string FormatMe(string value) {
  if (string.IsNullOrEmpty(value))
    return value;
  else if (!value.StartsWith("PN="))
    return value;

  int lot = value.IndexOf(";LOT=", 3);

  if (lot >= 0)
    return $"PN_EQ: {value.Substring(3, lot - 3)} LOT_EQ: {value.Substring(lot + 5)}";
  else
    return $"PN_EQ: {value.Substring(3)}";
}

Let's have a look:

  string[] item_list = {
    "PN=12345678",
    "PN=1234-5678-0001",
    "PN=1234-4321-0001;LOT=xyz"
  };

  string report = string.Join(Environment.NewLine, item_list
    .Select(item => FormatMe(item)));

  Console.Write(report);

Outcome:

PN_EQ: 12345678
PN_EQ: 1234-5678-0001
PN_EQ: 1234-4321-0001 LOT_EQ: xyz

Time to create Labels (assuming WinForms):

 using System.Linq;

  ...

  string[] item_list = {
    "PN=12345678",
    "PN=1234-5678-0001",
    "PN=1234-4321-0001;LOT=xyz"
  };

  // let's query item_list:
  //   for each item within item_list
  //   we create a Label
  //   all the labels we materialize in a List
  List<Label> labels = item_list
    .Select((item, index) => new Label() {
      Text     = FormatMe(item),
      Location = new Point(10, 50 + 40 * index), //TODO: put the right locations here
      AutoSize = true,
      Parent   = this, // Instead of this.Controls.Add(...);
     })
    .ToList();

Edit: Alternative no Linq but loop solution:

    List<Label> labels = new List<Label>(item_list.Length);

    for (int index = 0; index < item_list.Length; ++index)
      labels.Add(new Label() {
        Text     = FormatMe(item_list[index]),
        Location = new Point(10, 50 + 40 * index), //TODO: put the right locations here
        AutoSize = true,
        Parent   = this, // Instead of this.Controls.Add(...);
     });


问:
Heroku: How to add variable that was in .env file prior to deployment?
I deployed a React app on Heroku which had an API key in an .env file. Now that the app is deployed I don't know how to reinstate that variable.

```<code>REACT_APP_API_KEY = blahblahblah
</code>```

In Heroku I thought would just add the same variable in 'Config Vars' but it's not working. In my app the .env file is located in the same directory as the src/ directory. The file that uses that API key is located in the src/ directory.

答:
In Heroku I thought would just add the same variable in 'Config Vars' but it's not working

For back-end code, this is the right approach.

But front-end code isn't running in that environment and therefore has no access to those environment variables. It runs in your users' browsers.

Compile that value into your application at build time. Depending on your toolchain this might already be happening, but if you set the config var after build it won't have been included. Rebuild your application and see if that works.

If it doesn't, please edit your question and add information about how you are building your application.

Body:
I deployed a React app on Heroku which had an API key in an .env file. Now that the app is deployed I don't know how to reinstate that variable.

REACT_APP_API_KEY = blahblahblah

In Heroku I thought would just add the same variable in 'Config Vars' but it's not working. In my app the .env file is located in the same directory as the src/ directory. The file that uses that API key is located in the src/ directory.


答:
This is what i want
result as image given in question</p>

```<code>    $data = json_decode($data , true);
$k = 1;
$l=1;
$html .='<table class="table table-striped table-bordered" border="1">';
foreach($data as $combine){
    if($combine['RowIndex']==$k){
         $html .='<tr>';
         foreach($data as $com){
             if($com['RowIndex']==$l){
                $html .='<td>'.$com['Line'].'</td>';
             }
         }
    $html .='</tr>';
    //$k=$combine['RowIndex'];
    $k++;
    $l++;
    }
}
$html .='</table>';
print_r($html);
die;
</code>```

Title: How to print a table by given row index and column index put the Line value in table Column value in json data in php

Body:
i am trying to print a table from json data which contain row index and column index my array is given below

[{"ID":["64103487-ab83-4ce2-ba22-e4c83184eeda"],"RowIndex":1,"ColumnIndex":1,"Line":""},{"ID":["a38cb3ca-9565-463c-830d-f686cb2a965e"],"RowIndex":1,"ColumnIndex":2,"Line":""},{"ID":["73863297-6182-4c24-a5cc-13a20f8b9b97"],"RowIndex":1,"ColumnIndex":3,"Line":"Department"},{"ID":["6c87f8d1-e7b5-49e6-8d45-049532177b0e"],"RowIndex":2,"ColumnIndex":1,"Line":""},{"ID":["ef36343e-e89a-4671-9672-310fdd451111","5e210db5-979e-4b88-9ac1-8d7d3776569c"],"RowIndex":2,"ColumnIndex":2,"Line":""},{"ID":["301021a5-9a2b-4147-85f1-def1b91c0543"],"RowIndex":2,"ColumnIndex":3,"Line":"Sales"},{"ID":["503339ef-2892-460d-9638-d08a6ebeaf5a"],"RowIndex":3,"ColumnIndex":1,"Line":"3"},{"ID":["8fff1706-8091-4ee4-9515-627e68758109","98d44dc1-a620-4de9-9eb0-4af878a46b6f"],"RowIndex":3,"ColumnIndex":2,"Line":"Justin Shore"},{"ID":["07172dfe-2037-4355-87c8-03fef616634c"],"RowIndex":3,"ColumnIndex":3,"Line":"Marketing"},{"ID":["c88a583d-f5c8-48fb-aaa8-8a1bda6bf1d5"],"RowIndex":4,"ColumnIndex":1,"Line":"4"},{"ID":["30696ecb-aabc-4735-bdf8-47f864260e26","4179cd2e-8132-4baa-afec-41d4b33870a3"],"RowIndex":4,"ColumnIndex":2,"Line":"Lexi Barringer"},{"ID":["a67c9508-7731-4953-b88e-df7dd58c6c34"],"RowIndex":4,"ColumnIndex":3,"Line":"Finance"},{"ID":["153f68af-a9aa-49a9-ab26-ad9f89e21ecc"],"RowIndex":5,"ColumnIndex":1,"Line":"5"},{"ID":["0916eb3e-e8e0-43fd-a424-bada4c95080b","66dd35de-f4d7-48e3-bb4a-a42e158c28c7"],"RowIndex":5,"ColumnIndex":2,"Line":"Safa thsan"},{"ID":["2aa280ff-b527-4b4b-9ca5-3538a3fcbb98"],"RowIndex":5,"ColumnIndex":3,"Line":"Sales"},{"ID":["3d9af0ca-e0e8-4747-bfc7-85273a053a0f"],"RowIndex":6,"ColumnIndex":1,"Line":"6"},{"ID":["99314a19-0377-416d-bc25-6efcf4943abb","d001dfb2-d51c-460d-bbd7-d2340695dddb"],"RowIndex":6,"ColumnIndex":2,"Line":"Roy Flint"},{"ID":["66201bf3-aa64-4761-a291-040310b1b5cb"],"RowIndex":6,"ColumnIndex":3,"Line":"Finance"}]

and i want to ouput like the image given below

enter image description here

Body:
This is what i want
result as image given in question

    $data = json_decode($data , true);
$k = 1;
$l=1;
$html .='<table class="table table-striped table-bordered" border="1">';
foreach($data as $combine){
    if($combine['RowIndex']==$k){
         $html .='<tr>';
         foreach($data as $com){
             if($com['RowIndex']==$l){
                $html .='<td>'.$com['Line'].'</td>';
             }
         }
    $html .='</tr>';
    //$k=$combine['RowIndex'];
    $k++;
    $l++;
    }
}
$html .='</table>';
print_r($html);
die;


问:
'Chalet' Family fonts doesn't work in React Native iOS app
I have used to 'chalet' fonts in react-native app. This font doesn't work in 'iOS build', but it works fine in Android build. I have tried with other fonts , but it's works fine in both the builds iOS and android.

Can you please check this link for Font-family .ttf files.

If you guys found any solution, please help me !!

答:
Usually font name is different for iOS and android,

Please follow below link to know the name of font for iOS,

https://medium.com/react-native-training/adding-custom-fonts-to-react-native-b266b41bff7f

and apply font according to platform name


问:
Dynamically change background of body in html
In our application, I've to write JSP which I upload to an application and as per JSP UI is reflected.

In this I make API call and get value of Rating which is A, B, C, D or E. I've some code to achieve that and store in variable -

```<code>String reliabilityRating = getRating();
</code>```

Based on rating, I want to change background of the page. CSS are like follows -

```<code>.rating-A {
    line-height: 23px;
    background-color: #00aa00;
}
.rating-B {
    background-color: #b0d513;
}

.rating-C {
    background-color: #eabe06;
}
</code>```

To change background based on rating, I can have html like -

```<code><body class="rating-A">
</code>```

But this is fixed. I want to make it dynamic like rating-X where X can be A, B, C, D or E. Hence I tried calling method which returns rating like

```<code><body class="rating-" + getRating()>
</code>```

But this is not helping to achieve what I want. Could you please suggest how I can change background of page based on value of specific variable?

答:
Judging from this tutorial, if you want to output the content of a Java expression you need to wrap it in ${ and }.

Therefore:

```<code><body class="rating-${getRating()}">
</code>```

Body:
In our application, I've to write JSP which I upload to an application and as per JSP UI is reflected.

In this I make API call and get value of Rating which is A, B, C, D or E. I've some code to achieve that and store in variable -

String reliabilityRating = getRating();

Based on rating, I want to change background of the page. CSS are like follows -

.rating-A {
    line-height: 23px;
    background-color: #00aa00;
}
.rating-B {
    background-color: #b0d513;
}

.rating-C {
    background-color: #eabe06;
}

To change background based on rating, I can have html like -

But this is fixed. I want to make it dynamic like rating-X where X can be A, B, C, D or E. Hence I tried calling method which returns rating like

But this is not helping to achieve what I want. Could you please suggest how I can change background of page based on value of specific variable?

Body:
Judging from this tutorial, if you want to output the content of a Java expression you need to wrap it in ${ and }.

Therefore:

<body class="rating-${getRating()}">


问:
Functional Search Bar in TypeScript
I have created a Material UI search bar front-end but for now I am unable to type anything into it. How could I fix this?

```<code>export default class userSearchPage extends Component <{}, { searchItem: string}>{
  constructor(props: Readonly<{}>) {
    super(props);
    this.state = {
      searchItem: 'ha'
    };
  }

  render() {
    return (
  <div>
    <PermanentDrawerLeft></PermanentDrawerLeft>
    <div className='main-content'>
      {/* <Typography>{this.state.searchItem}</Typography> */}
      <SearchBar

        onChange={e => {
          this.setState({searchItem: e.target.value})
        }}

        onRequestSearch={() => console.log('onRequestSearch')}
        style={{
          margin: '0 auto',
          maxWidth: 800
        }}
      />
    </div>
  </div>
  );
}
}
</code>```

The onChange method doesn't work and gives an error.

I feel that this method in general is not the ideal way. How else could I make the search bar functional in Typescript so it could read and store what the user types in?

答:
Try this one</p>

```<code><form onSubmit={props.onRequestChange}>
  <input id="searchbartext" onChange={props.onChange} />
</form>
</code>```

Title: Functional Search Bar in TypeScript

Body:
I have created a Material UI search bar front-end but for now I am unable to type anything into it. How could I fix this?

export default class userSearchPage extends Component <{}, { searchItem: string}>{
  constructor(props: Readonly<{}>) {
    super(props);
    this.state = {
      searchItem: 'ha'
    };
  }

  render() {
    return (

    <PermanentDrawerLeft></PermanentDrawerLeft>

      {/* <Typography>{this.state.searchItem}</Typography> */}
      <SearchBar

        onChange={e => {
          this.setState({searchItem: e.target.value})
        }}

        onRequestSearch={() => console.log('onRequestSearch')}
        style={{
          margin: '0 auto',
          maxWidth: 800
        }}
      />

  );
}
}

The onChange method doesn't work and gives an error.

I feel that this method in general is not the ideal way. How else could I make the search bar functional in Typescript so it could read and store what the user types in?

Body:
Try this one

<form onSubmit={props.onRequestChange}>
  <input id="searchbartext" onChange={props.onChange} />
</form>


问:
Exchange data.table columns with most prevalent value of columns
I have data

```<code>test = data.table(
  a = c(1,1,3,4,5,6),
  b = c("a", "be", "a", "c", "d", "c"),
  c = rep(1, 6)
)
</code>```

I wish to take the unique values of column a, store it in another data.table, and afterwards fill in the remaining columns with the most prevalent values of those remaining columns, such that my resulting data.table would be:

```<code>test2 = data.table(a = c(1,3,4,5,6), b = "a", c = 1)
</code>```

Column be has equal amounts of "a" and "c", but it doesn't matter which is chosen in those cases.

Attempt so far:

```<code>test2 = unique(test, by = "a")
test2[, c("b", "c") := lapply(.SD, FUN = function(x){test2[, .N, by = x][order(-N)][1,1]}), .SDcols = c("b", "c")]
</code>```

EDIT: I would preferrably like a generic solution that is compatible with a function where I specify the column to be "uniqued", and the rest of the columns are with the single most prevalent value. Hence my use of lapply and .SD =)

EDIT2: as @MichaelChirico points out, how do we keep the class. With the following data.table some of the solutions does not work, although solution of @chinsoon12 does work:

```<code>test = data.table(a = c(1,1,3,4,5,6),
                  b = c("a", "be", "a", "c", "d", "c"),
                  c = rep(1, 6),
                  d = as.Date("2019-01-01"))
</code>```

答:
Here's another variant which one might find less sophisticated, yet more readable. It's essentially chinsoon12's rowid approach generalized for any number of columns. Also the classes are kept.

```<code>test = data.table(a = c(1,1,3,4,5,6),
                  b = c("a", "be", "a", "c", "d", "c"),
                  c = rep(1, 6),
                  d = as.Date("2019-01-01"))
test2 = unique(test, by = "a")
for (col in setdiff(names(test2), "a")) test2[[col]] = test2[[col]][which.max(rowid(test2[[col]]))]
</code>```

Body:
I have data

test = data.table(
  a = c(1,1,3,4,5,6),
  b = c("a", "be", "a", "c", "d", "c"),
  c = rep(1, 6)
)

I wish to take the unique values of column a, store it in another data.table, and afterwards fill in the remaining columns with the most prevalent values of those remaining columns, such that my resulting data.table would be:

test2 = data.table(a = c(1,3,4,5,6), b = "a", c = 1)

Column be has equal amounts of "a" and "c", but it doesn't matter which is chosen in those cases.

Attempt so far:

test2 = unique(test, by = "a")
test2[, c("b", "c") := lapply(.SD, FUN = function(x){test2[, .N, by = x][order(-N)][1,1]}), .SDcols = c("b", "c")]

EDIT: I would preferrably like a generic solution that is compatible with a function where I specify the column to be "uniqued", and the rest of the columns are with the single most prevalent value. Hence my use of lapply and .SD =)

EDIT2: as @MichaelChirico points out, how do we keep the class. With the following data.table some of the solutions does not work, although solution of @chinsoon12 does work:

test = data.table(a = c(1,1,3,4,5,6),
                  b = c("a", "be", "a", "c", "d", "c"),
                  c = rep(1, 6),
                  d = as.Date("2019-01-01"))

Body:
Here's another variant which one might find less sophisticated, yet more readable. It's essentially chinsoon12's rowid approach generalized for any number of columns. Also the classes are kept.

test = data.table(a = c(1,1,3,4,5,6),
                  b = c("a", "be", "a", "c", "d", "c"),
                  c = rep(1, 6),
                  d = as.Date("2019-01-01"))
test2 = unique(test, by = "a")
for (col in setdiff(names(test2), "a")) test2[[col]] = test2[[col]][which.max(rowid(test2[[col]]))]


问:
Difference between case class with parentheses and without
I have a case class case class FOO. And would like to test a method myMethod that returns FOO() given parameter value value1.

I have a test like : myMethod(value1) should equal FOO.

The test failed with FOO did not equal FOO().

What is the difference between FOO and FOO() ?

答:
A case class Foo() desugars into something equivalent to

```<code>class Foo() extends Product with Serializable {
  // some methods
}

object Foo extends (() => Foo) with Serializable {
  // some methods
}
</code>```

So Foo() creates an instance of the Foo class while Foo is a reference to the Foo companion object.

However if your case class Foo has no parameters you should consider making it a case object instead. If you are not abusing your case class with internal mutable state[1] all Foo() instances should be indistinguishable anyway.

[1] If you are, consider using a regular class instead.

Body:
A case class Foo() desugars into something equivalent to

class Foo() extends Product with Serializable {
  // some methods
}

object Foo extends (() => Foo) with Serializable {
  // some methods
}

So Foo() creates an instance of the Foo class while Foo is a reference to the Foo companion object.

However if your case class Foo has no parameters you should consider making it a case object instead. If you are not abusing your case class with internal mutable state[1] all Foo() instances should be indistinguishable anyway.

[1] If you are, consider using a regular class instead.


问:
laravel show multiple data in datatables
I work with laravel spatie permission package and need to show user role for each user in datatables lists. now I  add datatables addColumn method:

```<code>$items = Admin::orderBy('id','DESC');

return DataTables::of($items)
    ->addColumn('role',function(Admin $admin){

        foreach($admin->getRoleNames() as $v){
            return $v;
        }

    })
    ->toJson();
</code>```

this code work and show role name for each user but If user have a two role name(multiple roles) My code not work and show only first role name. ie: for user test I have two roles name: moderator and editor But i see only moderator.

How to can i show multiple roles name for each user in datatables list?!

答:
I found this and work true:</p>

```<code>return DataTables::of($items)
    ->addColumn('roles',function(Admin $admin){

        return $admin->roles->pluck('name')->toArray();
    })
    ->toJson();
</code>```

Body:
I work with laravel spatie permission package and need to show user role for each user in datatables lists. now I  add datatables addColumn method:

$items = Admin::orderBy('id','DESC');

return DataTables::of($items)
    ->addColumn('role',function(Admin $admin){

        foreach($admin->getRoleNames() as $v){
            return $v;
        }

    })
    ->toJson();

this code work and show role name for each user but If user have a two role name(multiple roles) My code not work and show only first role name. ie: for user test I have two roles name: moderator and editor But i see only moderator.

How to can i show multiple roles name for each user in datatables list?!

Body:
I found this and work true:

return DataTables::of($items)
    ->addColumn('roles',function(Admin $admin){

        return $admin->roles->pluck('name')->toArray();
    })
    ->toJson();