问:
Why Hero doesn't work with Multiprovider?
I have a list of cards.
When I tap a card, the BoxViewPage opens.

If I use Hero and Multiprovider together, I get an error,

but,

if I use Hero and MultiProvider individually everything works correctly

Why?

List of Cards:

```<code>    return Hero(
      tag: box.ID,
      child: InkWell(
        child: selectBoxSize(viewType),
        onTap: () async {
          Navigator.of(context).push(
            MaterialPageRoute(
              builder: (BuildContext context) => MultiProvider(
                providers: [
                  ChangeNotifierProvider<Archive>.value(value: archive),
                  ChangeNotifierProvider<Box>.value(value: box),
                ],
                builder: (context, child) => BoxViewPage(),
              ),
            ),
</code>```

Inside BoxViewPage:

```<code>class BoxCardView extends StatefulWidget {
  const BoxCardView({Key key}) : super(key: key);
  @override
  _BoxCardViewState createState() => _BoxCardViewState();
}

class _BoxCardViewState extends State<BoxCardView> {
  @override
  Widget build(BuildContext context) {
    final box = Provider.of<Box>(context);
    return Hero(
      tag: box.ID,
      child: Card(
        clipBehavior: Clip.antiAlias,
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(12.0),
        ),
        margin: EdgeInsets.all(12),
        child: Column(
          children: <Widget>[
            Expanded(child: WidgetEditPhotosScrollHoriz()),
            WidgetNameDescrTagsEdit(),
          ],
        ),
      ),
    );
  }
}
</code>```

Error:

Si è verificata un'eccezione
ProviderNotFoundException (Error: Could not find the correct Provider above this WidgetEditPhotosScrollHoriz Widget

This happens because you used a BuildContext that does not include the provider
of your choice. There are a few common scenarios:

You added a new provider in your main.dart and performed a hot-reload.
To fix, perform a hot-restart.

The provider you are trying to read is in a different route.

Providers are "scoped". So if you insert of provider inside a route, then
other routes will not be able to access that provider.

You used a BuildContext that is an ancestor of the provider you are trying to read.

Make sure that WidgetEditPhotosScrollHoriz is under your MultiProvider/Provider.
This usually happens when you are creating a provider and trying to read it immediately.

For example, instead of:

```<code>Widget build(BuildContext context) {
  return Provider<Example>(
    create: (_) => Example(),
    // Will throw a ProviderNotFoundError, because `context` is associated
    // to the widget that is the parent of `Provider<Example>`
    child: Text(context.watch<Example>()),
  ),
}
</code>```

consider using builder like so:

```<code>Widget build(BuildContext context) {
  return Provider<Example>(
    create: (_) => Example(),
    // we use `builder` to obtain a new `BuildContext` that has access to the provider
    builder: (context) {
      // No longer throws
      return Text(context.watch<Example>()),
    }
  ),
}
</code>```

If none of these solutions work, consider asking for help on StackOverflow:
https://stackoverflow.com/questions/tagged/flutter
)

答:
As much as I understand I think your problem is also one of the typical ones while using providers.

I always recommend using provider at the root of your application (above MaterialApp), that is mainly the best way to use it without running into errors.

You see actually what is happening here, that providers work based on hierarchy (They provide a specific value to all widgets and sub-widgets you can say) and I'm sure you were also expecting this, But when we use a navigator instead of this parent child relation between widgets  it is more of a Sibling-relation between pages. Note down I used the word pages here, Your provider for your case is only providing the value to the sub-widgets of that specific page where you used it, when you navigate to the new page that is now on the top of the navigation stack is not a sub-widget, rather it is sort of sibling relation and hence you cannot access the provider here.

If you do not understand this, do not worry simplest solution and visualization for this is just to open up dart dev tools on browser and in the Widgets Inspector, Check out the widget Hierarchy, you will observe that the widget where you want to use the value provided by the provider is not under that hierarchy, Now you only need to figure out what you should do to make it happen.

One solution I can give is just to Use the provider at the root of application (Above MaterialApp).

Body:
I have a list of cards.
When I tap a card, the BoxViewPage opens.

If I use Hero and Multiprovider together, I get an error,

but,

if I use Hero and MultiProvider individually everything works correctly

Why?

List of Cards:

    return Hero(
      tag: box.ID,
      child: InkWell(
        child: selectBoxSize(viewType),
        onTap: () async {
          Navigator.of(context).push(
            MaterialPageRoute(
              builder: (BuildContext context) => MultiProvider(
                providers: [
                  ChangeNotifierProvider<Archive>.value(value: archive),
                  ChangeNotifierProvider<Box>.value(value: box),
                ],
                builder: (context, child) => BoxViewPage(),
              ),
            ),

Inside BoxViewPage:

class BoxCardView extends StatefulWidget {
  const BoxCardView({Key key}) : super(key: key);
  @override
  _BoxCardViewState createState() => _BoxCardViewState();
}

class _BoxCardViewState extends State<BoxCardView> {
  @override
  Widget build(BuildContext context) {
    final box = Provider.of<Box>(context);
    return Hero(
      tag: box.ID,
      child: Card(
        clipBehavior: Clip.antiAlias,
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(12.0),
        ),
        margin: EdgeInsets.all(12),
        child: Column(
          children: <Widget>[
            Expanded(child: WidgetEditPhotosScrollHoriz()),
            WidgetNameDescrTagsEdit(),
          ],
        ),
      ),
    );
  }
}

Error:

Si è verificata un'eccezione
ProviderNotFoundException (Error: Could not find the correct Provider above this WidgetEditPhotosScrollHoriz Widget

This happens because you used a BuildContext that does not include the provider
of your choice. There are a few common scenarios:

You added a new provider in your main.dart and performed a hot-reload.
To fix, perform a hot-restart.

The provider you are trying to read is in a different route.

Providers are "scoped". So if you insert of provider inside a route, then
other routes will not be able to access that provider.

You used a BuildContext that is an ancestor of the provider you are trying to read.

Make sure that WidgetEditPhotosScrollHoriz is under your MultiProvider/Provider.
This usually happens when you are creating a provider and trying to read it immediately.

For example, instead of:

Widget build(BuildContext context) {
  return Provider<Example>(
    create: (_) => Example(),
    // Will throw a ProviderNotFoundError, because `context` is associated
    // to the widget that is the parent of `Provider<Example>`
    child: Text(context.watch<Example>()),
  ),
}

consider using builder like so:

Widget build(BuildContext context) {
  return Provider<Example>(
    create: (_) => Example(),
    // we use `builder` to obtain a new `BuildContext` that has access to the provider
    builder: (context) {
      // No longer throws
      return Text(context.watch<Example>()),
    }
  ),
}

If none of these solutions work, consider asking for help on StackOverflow:
https://stackoverflow.com/questions/tagged/flutter
)


来源: stackexchange

问:
Excel not detecting alternating duplicates in three columns
I have a spreadsheet with three columns: year, name1, name2. Each entry represents a pair. I've noticed that there are duplicates in the data that Excel does not detect, namely:

So the only pair in year 1986 is ABW-AIA. However, in the data I've got two entries: ABW-AIA and AIA-ABW. I would like to remove either ABW-AIA or AIA-ABW, so I am only left with one entry. I would like to repeat the same process with many other pairs. How can I do this?

I'll greatly appreciate any help!

答:
Remove Alernating Duplicates

Option Explicit

Sub RemoveAlternatingDuplicates()

    Const Delim As String = "@@"
    Const cCount As Long = 3

    Dim ws As Worksheet: Set ws = ActiveSheet ' improve!

    ' Copy the range data to the array.

    Dim rg As Range
    Dim rCount As Long
    With ws.Range("A1").CurrentRegion.Resize(, cCount)
        rCount = .Rows.Count - 1
        Set rg = .Resize(rCount).Offset(1)
    End With
    Dim Data As Variant: Data = rg.Value

    ' Copy the 'unique' data from the array to a dictionary.

    Dim dict As Object: Set dict = CreateObject("Scripting.Dictionary")
    dict.CompareMode = vbTextCompare

    Dim r As Long
    Dim sString1 As String
    Dim sString2 As String

    For r = 1 To rCount
        sString1 = Data(r, 1) & Delim & Data(r, 2) & Delim & Data(r, 3)
        sString2 = Data(r, 1) & Delim & Data(r, 3) & Delim & Data(r, 2)
        If Not dict.Exists(sString1) Then
            If Not dict.Exists(sString2) Then
                dict(sString1) = Empty
            End If
        End If
    Next r

    ' Copy from the dictionary to the array.

    r = 0

    Dim Arr() As String
    Dim Key As Variant
    Dim c As Long

    For Each Key In dict.Keys
        Arr = Split(Key, Delim)
        r = r + 1
        For c = 1 To cCount
            Data(r, c) = Arr(c - 1)
        Next c
    Next Key

    ' Copy from the array to the range.

    With rg.Resize(, cCount)
        .Resize(r).Value = Data
        .Resize(ws.Rows.Count - .Row - r + 1).Offset(r).Clear
    End With

    MsgBox "Alternating duplicates removed.", vbInformation

End Sub
```

ContentLicense: CC BY-SA 4.0


问:
MySQL CLI: unknown option: enable-cleartext-plugin
This question has been asked a couple of times out here, but I'm not able to enable cleartext plugin. I'm using mySQL CLI to access an RDS(Engine version: 5.7.26) instance using the command

mysql -h $RDSHOST -u <Username> --password=$TOKEN --enable-cleartext-plugin --port=3306 --ssl-ca=<path to pem file>

I get the following error:

mysql: unknown option '--enable-cleartext-plugin'

I installed mySQL by running yum install curl mysql -y. But in the logs I see maria-db being installed, is there something wrong out here. Thanks in advance.

答:
Note: If you're using a MariaDB client, the --enable-cleartext-plugin option isn't required.

According to the article found here: https://aws.amazon.com/premiumsupport/knowledge-center/users-connect-rds-iam/


问:
Why does the printf prints nothing but an empty blank
I've been trying to figure the problem but after 3 hours I quit, anyone have any suggestion how this problem might occur. Any help would be appreciated!
Currently using codeblock 20.23. img of the empty blank</p>
```<code>#include <stdio.h>
#include <stdbool.h>
int main()
{
    int dd, mm, yy, temp = 0;
    bool isLeapYear = temp;
    printf("Enter the year: ");
    scanf("%d", &yy);
        if(yy < 0)
        {
        printf("Year number cannot be smaller than 0!");
        return 0;
        } else
        {
            if(yy%4==0 && yy%400==0 || yy%4==0)
            temp = 1;
        }
    printf("Enter the month: ");
    scanf("%d", &mm);
        if(mm > 12 || mm < 0)
        {
        printf("Month number cannot be smaller than 0 or bigger than 12!");
        return 0;
        }
    printf("Enter the date: ");
    scanf("%d", &dd);
        if(dd > 30 || dd < 0)
        {
        printf("Date number cannot be smaller than 0 or bigger than 30!");
        return 0;
        } else
        {
            if(dd == 29 && mm == 2 && temp == 0)
            printf("Since given year is not a leap year therefore your input date is invalid.");
            return 0;
        }
    printf("dd/mm/yy of your given number: %02d/%02d/%04d", dd, mm, yy);
    return 0;

}
</code>```

答:
Did you forget to block correctly ?

```<code>if(dd == 29 && mm == 2 && temp == 0){
  printf("Since given year is not a leap year therefore your input date is invalid.");
  return 0;
}
</code>```

instead of

```<code>if(dd == 29 && mm == 2 && temp == 0)
  printf("Since given year is not a leap year therefore your input date is invalid.");
  return 0;
</code>```

Body:
I've been trying to figure the problem but after 3 hours I quit, anyone have any suggestion how this problem might occur. Any help would be appreciated!
Currently using codeblock 20.23. img of the empty blank

#include <stdio.h>
#include <stdbool.h>
int main()
{
    int dd, mm, yy, temp = 0;
    bool isLeapYear = temp;
    printf("Enter the year: ");
    scanf("%d", &yy);
        if(yy < 0)
        {
        printf("Year number cannot be smaller than 0!");
        return 0;
        } else
        {
            if(yy%4==0 && yy%400==0 || yy%4==0)
            temp = 1;
        }
    printf("Enter the month: ");
    scanf("%d", &mm);
        if(mm > 12 || mm < 0)
        {
        printf("Month number cannot be smaller than 0 or bigger than 12!");
        return 0;
        }
    printf("Enter the date: ");
    scanf("%d", &dd);
        if(dd > 30 || dd < 0)
        {
        printf("Date number cannot be smaller than 0 or bigger than 30!");
        return 0;
        } else
        {
            if(dd == 29 && mm == 2 && temp == 0)
            printf("Since given year is not a leap year therefore your input date is invalid.");
            return 0;
        }
    printf("dd/mm/yy of your given number: %02d/%02d/%04d", dd, mm, yy);
    return 0;

}

Body:
Did you forget to block correctly ?

if(dd == 29 && mm == 2 && temp == 0){
  printf("Since given year is not a leap year therefore your input date is invalid.");
  return 0;
}

instead of

if(dd == 29 && mm == 2 && temp == 0)
  printf("Since given year is not a leap year therefore your input date is invalid.");
  return 0;


问:
preg_replace problems
I have a string The Incredible Hulk (2008) and use pattern

```<code>/^\([0-9]{1,4}\)$/
</code>```

to remove (2008). PHP code looks like this:

```<code>$x = trim(preg_replace("/^\([0-9]{1,4}\)$/", "", "The Incredible Hulk (2008)"));
</code>```

And the result is:

```<code>The Incredible Hulk (2008)
</code>```

What am I doing wrong?

答:
You're using the ^ character that matches start of line. Remove that and it should work.

If you also want to get rid of the whitespace before the ( the regex becomes /\s*\([0-9]{1,4}\)$/

ContentLicense: CC BY-SA 3.0

Title: preg_replace problems

Body:
I have a string The Incredible Hulk (2008) and use pattern

/^\([0-9]{1,4}\)$/

to remove (2008). PHP code looks like this:

$x = trim(preg_replace("/^\([0-9]{1,4}\)$/", "", "The Incredible Hulk (2008)"));

And the result is:

The Incredible Hulk (2008)

What am I doing wrong?


问:
How do you do Numpy.eye in JavaScript?
How to create the np.eye function in JavaScript? Or what would be the numpy.eye equivalent in JavaScript?

I would like a function that creates the "Identity matrix" in 2d dimensions, and you can change the number of rows, columns and the index of the diagonal.
https://numpy.org/devdocs/reference/generated/numpy.eye.html

This doesn't take care of M,N,k
@Andy

```<code>function eye(n){
var t=[];
for(var i=0;i<n;i++){
var p=[]
for(var j=0;j<n;j++){
p.push(j==i?1:0)
}
t.push(p)
}}
</code>```

答:
This doesn't take care of M,N,k

You are almost there, just have to put the extra parameters there, like the outer loop (rows) runs to N, the inner loop (columns) runs to M, and the comparison would be j-i===k:

function eye(N,M,k) {
  var t = [];
  for (var i = 0; i < N; i++) {
    var p = []
    for (var j = 0; j < M; j++) {
      p.push(j - i === k ? 1 : 0)
    }
    t.push(p)
  }
  return t;
}

let NMk=prompt("N,M,k").split(",").map(x=>parseInt(x));
console.log(eye(...NMk).map(x=>x.join()));```

Try entering something like 3,3,0 ("classic") or 2,3,1 (a "fancy" one) when asked.

(And don't worry about the snippet printing strings, that's just the join() , to keep output small, and without much coding).

Title: How do you do Numpy.eye in JavaScript?

Body:
How to create the np.eye function in JavaScript? Or what would be the numpy.eye equivalent in JavaScript?

I would like a function that creates the "Identity matrix" in 2d dimensions, and you can change the number of rows, columns and the index of the diagonal.
https://numpy.org/devdocs/reference/generated/numpy.eye.html

This doesn't take care of M,N,k
@Andy

function eye(n){
var t=[];
for(var i=0;i<n;i++){
var p=[]
for(var j=0;j<n;j++){
p.push(j==i?1:0)
}
t.push(p)
}}

Body:
This doesn't take care of M,N,k

You are almost there, just have to put the extra parameters there, like the outer loop (rows) runs to N, the inner loop (columns) runs to M, and the comparison would be j-i===k:

function eye(N,M,k) {
  var t = [];
  for (var i = 0; i < N; i++) {
    var p = []
    for (var j = 0; j < M; j++) {
      p.push(j - i === k ? 1 : 0)
    }
    t.push(p)
  }
  return t;
}

let NMk=prompt("N,M,k").split(",").map(x=>parseInt(x));
console.log(eye(...NMk).map(x=>x.join()));

Try entering something like 3,3,0 ("classic") or 2,3,1 (a "fancy" one) when asked.

(And don't worry about the snippet printing strings, that's just the join() , to keep output small, and without much coding).


问:
Setting a relative frequency in a matplotlib histogram
I have data as a list of floats and I want to plot it as a histogram. Hist() function does the job perfectly for plotting the absolute histogram. However, I cannot figure out how to represent it in a relative frequency format - I would like to have it as a fraction or ideally as a percentage on the y-axis.

Here is the code:

```<code>fig = plt.figure()
ax = fig.add_subplot(111)
n, bins, patches = ax.hist(mydata, bins=100, normed=1, cumulative=0)
ax.set_xlabel('Bins', size=20)
ax.set_ylabel('Frequency', size=20)
ax.legend

plt.show()
</code>```

I thought normed=1 argument would do it, but it gives fractions that are too high and sometimes are greater than 1. They also seem to depend on the bin size, as if they are not normalized by the bin size or something. Nevertheless, when I set cumulative=1, it nicely sums up to 1. So, where is the catch? By the way, when I feed the same data into Origin and plot it, it gives me perfectly correct fractions. Thank you!

答:
You can use numpy.histogram to get the histogram value and bins, and then calculate frequency by yourself. Finally, use bar plot to get the frequency histogram.

hist, edges = np.histogram(p_hat)
freq = hist / float(hist.sum())
width = np.diff(edges) # edges is bins
plt.bar(edges[1:], freq, width=width, align="edge", ec="k")
plt.set(xlabel='x', ylabel='frequency')
```

Body:
I have data as a list of floats and I want to plot it as a histogram. Hist() function does the job perfectly for plotting the absolute histogram. However, I cannot figure out how to represent it in a relative frequency format - I would like to have it as a fraction or ideally as a percentage on the y-axis.

Here is the code:

fig = plt.figure()
ax = fig.add_subplot(111)
n, bins, patches = ax.hist(mydata, bins=100, normed=1, cumulative=0)
ax.set_xlabel('Bins', size=20)
ax.set_ylabel('Frequency', size=20)
ax.legend

plt.show()

I thought normed=1 argument would do it, but it gives fractions that are too high and sometimes are greater than 1. They also seem to depend on the bin size, as if they are not normalized by the bin size or something. Nevertheless, when I set cumulative=1, it nicely sums up to 1. So, where is the catch? By the way, when I feed the same data into Origin and plot it, it gives me perfectly correct fractions. Thank you!


答:
If we indent the code properly we see that the last if-statement looks like this:

```<code>if (dd > 30 || dd < 0) {
    printf("Date number cannot be smaller than 0 or bigger than 30!");
    return 0;
} else {
    if (dd == 29 && mm == 2 && temp == 0)
        printf("Since given year is not a leap year therefore your input date is invalid.");
    return 0;
}
</code>```

This means that the return statement in the else-clause is always executed for a valid day and hence the final print statement is never executed. You should also print to the standard error stream (with a newline) and return an error code (instead of zero which means success):

```<code>fprintf(stderr, "...\n");
return 1;
</code>```

Title: Why does the printf prints nothing but an empty blank

Body:
If we indent the code properly we see that the last if-statement looks like this:

if (dd > 30 || dd < 0) {
    printf("Date number cannot be smaller than 0 or bigger than 30!");
    return 0;
} else {
    if (dd == 29 && mm == 2 && temp == 0)
        printf("Since given year is not a leap year therefore your input date is invalid.");
    return 0;
}

This means that the return statement in the else-clause is always executed for a valid day and hence the final print statement is never executed. You should also print to the standard error stream (with a newline) and return an error code (instead of zero which means success):

fprintf(stderr, "...\n");
return 1;


问:
Not getting Latitude and Longitude from LocationListener class
I am having problem with LocationListener. Why is my code not getting the latitude and longitude coordinates in onLocationChange() method? It is passing the coordinates of latitude and longitude to be 0. Can any one point out the error in this code and the changes that needs to be done?

```<code>public class Login extends AppCompatActivity implements LocationListener {
    private EditText e_mail, pass_word;
    FirebaseAuth mAuth;
    FirebaseFirestore fStore;
    String userID;
    public static final String TAG = "TAG";

    protected LocationManager locationManager;
    protected LocationListener locationListener;
    protected Context context;

    private double lat;
    private double lng;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        e_mail = findViewById(R.id.emailLogin);
        pass_word = findViewById(R.id.password);
        Button btn_login = findViewById(R.id.btn_login);
        Button btn_sign = findViewById(R.id.btn_signup);

        fStore = FirebaseFirestore.getInstance();
        mAuth = FirebaseAuth.getInstance();

        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);

        btn_login.setOnClickListener(v -> {
            String email= e_mail.getText().toString().trim();
            String password=pass_word.getText().toString().trim();

            if(email.isEmpty())
            {
                e_mail.setError("Email is empty");
                e_mail.requestFocus();
                return;
            }
            if(!Patterns.EMAIL_ADDRESS.matcher(email).matches())
            {
                e_mail.setError("Enter the valid email");
                e_mail.requestFocus();
                return;
            }
            if(password.isEmpty())
            {
                pass_word.setError("Password is empty");
                pass_word.requestFocus();
                return;
            }
            if(password.length()<6)
            {
                pass_word.setError("Length of password is more than 6");
                pass_word.requestFocus();
                return;
            }
            mAuth.signInWithEmailAndPassword(email,password).addOnCompleteListener(task -> {

                if(task.isSuccessful())
                {
                    AlertDialog.Builder builder = new AlertDialog.Builder(Login.this);
                    builder.setTitle("Registration")
                            .setMessage("What do you want to register as ? ")
                            .setCancelable(false)
                            .setPositiveButton("Organization", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    Intent organization = new Intent(Login.this,OrganizationPage.class);
                                    startActivity(organization);
                                    Login.this.finish();
                                }
                            })
                            .setNegativeButton("Volunteer", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {

                                    uploadData();
                                    Intent volunteer = new Intent(Login.this,VolunteerPage.class);
                                    startActivity(volunteer);
                                    Login.this.finish();}
                            });
                    //Creating dialog box
                    AlertDialog dialog  = builder.create();
                    dialog.show();

                }
                else
                {
                    Toast.makeText(Login.this,
                            "Please Check Your login Credentials",
                            Toast.LENGTH_SHORT).show();
                }

            });

        });
        btn_sign.setOnClickListener(v -> {
            startActivity(new Intent(Login.this, Register.class));
        });
    }

    @Override
    public void onLocationChanged(@NonNull Location location) {
        lat =location.getLatitude();
        lng = location.getLongitude();
        Log.v("Activity location ", String.valueOf(lat)+"latitude of volunteer");
        Toast.makeText(this,lat+" Works "+lng,Toast.LENGTH_SHORT).show();
    }
    public void uploadData(){
        String name = username;

        double latitude = lat;
        double longitude = lng;

        Log.v("Activity location ", String.valueOf(latitude));

        userID = mAuth.getCurrentUser().getUid();
        CollectionReference collectionReference = fStore.collection("Volunteer data");
        Map<String,Object> user = new HashMap<>();
        user.put("timestamp", FieldValue.serverTimestamp());
        user.put("name",name);
        user.put("volunteerLatitude",latitude);
        user.put("volunteerLongitude",longitude);
        user.put("userid",userID);
        collectionReference.add(user)
                .addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
                    @Override
                    public void onSuccess(DocumentReference documentReference) {
                        Toast.makeText(getApplicationContext(),"Successfully Registered as Volunteer",Toast.LENGTH_SHORT).show();
                    }
                })
                .addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception e) {
                        Toast.makeText(getApplicationContext(),"Error!",Toast.LENGTH_SHORT).show();
                    }
                });
    }
}
</code>```

答:
You need to add location in your manifest.xml like this:</p>
```<code><manifest ... >
  <!-- Always include this permission -->
  <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

  <!-- Include only if your app benefits from precise location access. -->
  <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
</manifest>
</code>```

Body:
I am having problem with LocationListener. Why is my code not getting the latitude and longitude coordinates in onLocationChange() method? It is passing the coordinates of latitude and longitude to be 0. Can any one point out the error in this code and the changes that needs to be done?

public class Login extends AppCompatActivity implements LocationListener {
    private EditText e_mail, pass_word;
    FirebaseAuth mAuth;
    FirebaseFirestore fStore;
    String userID;
    public static final String TAG = "TAG";

    protected LocationManager locationManager;
    protected LocationListener locationListener;
    protected Context context;

    private double lat;
    private double lng;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        e_mail = findViewById(R.id.emailLogin);
        pass_word = findViewById(R.id.password);
        Button btn_login = findViewById(R.id.btn_login);
        Button btn_sign = findViewById(R.id.btn_signup);

        fStore = FirebaseFirestore.getInstance();
        mAuth = FirebaseAuth.getInstance();

        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);

        btn_login.setOnClickListener(v -> {
            String email= e_mail.getText().toString().trim();
            String password=pass_word.getText().toString().trim();

            if(email.isEmpty())
            {
                e_mail.setError("Email is empty");
                e_mail.requestFocus();
                return;
            }
            if(!Patterns.EMAIL_ADDRESS.matcher(email).matches())
            {
                e_mail.setError("Enter the valid email");
                e_mail.requestFocus();
                return;
            }
            if(password.isEmpty())
            {
                pass_word.setError("Password is empty");
                pass_word.requestFocus();
                return;
            }
            if(password.length()<6)
            {
                pass_word.setError("Length of password is more than 6");
                pass_word.requestFocus();
                return;
            }
            mAuth.signInWithEmailAndPassword(email,password).addOnCompleteListener(task -> {

                if(task.isSuccessful())
                {
                    AlertDialog.Builder builder = new AlertDialog.Builder(Login.this);
                    builder.setTitle("Registration")
                            .setMessage("What do you want to register as ? ")
                            .setCancelable(false)
                            .setPositiveButton("Organization", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    Intent organization = new Intent(Login.this,OrganizationPage.class);
                                    startActivity(organization);
                                    Login.this.finish();
                                }
                            })
                            .setNegativeButton("Volunteer", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {

                                    uploadData();
                                    Intent volunteer = new Intent(Login.this,VolunteerPage.class);
                                    startActivity(volunteer);
                                    Login.this.finish();}
                            });
                    //Creating dialog box
                    AlertDialog dialog  = builder.create();
                    dialog.show();

                }
                else
                {
                    Toast.makeText(Login.this,
                            "Please Check Your login Credentials",
                            Toast.LENGTH_SHORT).show();
                }

            });

        });
        btn_sign.setOnClickListener(v -> {
            startActivity(new Intent(Login.this, Register.class));
        });
    }

    @Override
    public void onLocationChanged(@NonNull Location location) {
        lat =location.getLatitude();
        lng = location.getLongitude();
        Log.v("Activity location ", String.valueOf(lat)+"latitude of volunteer");
        Toast.makeText(this,lat+" Works "+lng,Toast.LENGTH_SHORT).show();
    }
    public void uploadData(){
        String name = username;

        double latitude = lat;
        double longitude = lng;

        Log.v("Activity location ", String.valueOf(latitude));

        userID = mAuth.getCurrentUser().getUid();
        CollectionReference collectionReference = fStore.collection("Volunteer data");
        Map<String,Object> user = new HashMap<>();
        user.put("timestamp", FieldValue.serverTimestamp());
        user.put("name",name);
        user.put("volunteerLatitude",latitude);
        user.put("volunteerLongitude",longitude);
        user.put("userid",userID);
        collectionReference.add(user)
                .addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
                    @Override
                    public void onSuccess(DocumentReference documentReference) {
                        Toast.makeText(getApplicationContext(),"Successfully Registered as Volunteer",Toast.LENGTH_SHORT).show();
                    }
                })
                .addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception e) {
                        Toast.makeText(getApplicationContext(),"Error!",Toast.LENGTH_SHORT).show();
                    }
                });
    }
}

Body:
You need to add location in your manifest.xml like this:

<manifest ... >
  <!-- Always include this permission -->
  <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

  <!-- Include only if your app benefits from precise location access. -->
  <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
</manifest>


问:
Trouble finding the correct SQL subqueries
I have a database table with employees (emp). I am trying to write a query to find employees (name) in department 1 (deptno=1) with the same jobs (job) as employees i department 2 (deptno=2). In other words, the results should be the name of employees in department 1 who has a job than can be found amongst one or more of the employees in department 2.

I tried the following code, but it did not work. Any ideas?

```<code>select name from emp where deptno=1 and job=(select job from emp where deptno=3)
</code>```

答:
If there is any possibilities of having multiple job under single department then you can use IN  :

```<code>select name from emp where deptno=1
and job in (select job from emp where deptno=2)
</code>```

Body:
I have a database table with employees (emp). I am trying to write a query to find employees (name) in department 1 (deptno=1) with the same jobs (job) as employees i department 2 (deptno=2). In other words, the results should be the name of employees in department 1 who has a job than can be found amongst one or more of the employees in department 2.

I tried the following code, but it did not work. Any ideas?

select name from emp where deptno=1 and job=(select job from emp where deptno=3)

Body:
If there is any possibilities of having multiple job under single department then you can use IN  :

select name from emp where deptno=1
and job in (select job from emp where deptno=2)


问:
How To Launch Git Bash from Windows Command Line?
I've got what I'm hoping is a simple question, but I haven't been able to find the answer yet.  I would like to launch Git Bash from a Windows batch file.  Here is what I tried so far:

Launched Git Bash from Win 7 Start button

Used CTRL+ALT+DEL to identify the process as "sh.exe"

Launched sh.exe from batch file using start command

```<code> start sh.exe
</code>```

However, this does not launch the full Git Bash environment.  Git Bash usually has "MINGW32" in the title bar, but sh.exe has a full path to ... Git\bin\sh.exe.  It feels to me like there are some overlays or dependencies that I'm not aware of possibly, that also need to be loaded (pulled in? imported?).

This was one of the top results I found through searching the web, but it doesn't make complete sense to me and I'm not sure if it applies exactly to my situation:

Running git from Windows Cmd line: Where are key files?

I'm a beginner in the world of Windows batch scripting.

答:
Windows

Git bash  default location C:\Program Files\Git\bin

So copy this folder path and paste it inside environment variables setting under system variables.

start -> Environment Variables

select Environment variable

Create a new environment variable like this

Add environment variable gtbash %gtbash% in the path variable

Now check by taking a new command prompt and typing sh (close already opened terminal or cmd)

Now live

something like this(GIF):

Body:
I've got what I'm hoping is a simple question, but I haven't been able to find the answer yet.  I would like to launch Git Bash from a Windows batch file.  Here is what I tried so far:

Launched Git Bash from Win 7 Start button

Used CTRL+ALT+DEL to identify the process as "sh.exe"

Launched sh.exe from batch file using start command

 start sh.exe

However, this does not launch the full Git Bash environment.  Git Bash usually has "MINGW32" in the title bar, but sh.exe has a full path to ... Git\bin\sh.exe.  It feels to me like there are some overlays or dependencies that I'm not aware of possibly, that also need to be loaded (pulled in? imported?).

This was one of the top results I found through searching the web, but it doesn't make complete sense to me and I'm not sure if it applies exactly to my situation:

Running git from Windows Cmd line: Where are key files?

I'm a beginner in the world of Windows batch scripting.


问:
How to generate multiple combinations from tables using SQL?
I have few combinations of records in my table but i want to generate Multiple combinations from original table.

Records in table

codeset
codevalue
column
system

test1
1
null
sys1

test2
2
col2
sys1

test3
3
col3
sys1

test3
4
col4
sys1

test3
5
col5
sys1

test4
null
col6
sys1

test5
6
col7
sys2

test5
7
col8
sys2

After applied below logic and would like to get expected output.

Group by 'codeset'

system name should be 'sys1'

'codevalue' and 'column' should be more than 1 row

'codevalue' and 'column' equal rows

Expected Output

codeset
codevalue
column
system

test1
1
null
sys1

test2
2
col2
sys1

test3
3
col3
sys1

test3
3
col4
sys1

test3
3
col5
sys1

test3
4
col3
sys1

test3
4
col4
sys1

test3
4
col5
sys1

test3
5
col3
sys1

test3
5
col4
sys1

test3
5
col5
sys1

test4
null
col6
sys1

test5
6
col7
sys2

test5
7
col8
sys2

答:
You want to self join all test3 rows. One way:

```<code>select codeset, codevalue, column, system
from mytable
where codeset <> 'test3'
union all
select t1.codeset, t1.codevalue, t2.column, t2.system
from (select * from mytable where codeset = 'test3') t1
cross join (select * from mytable where codeset = 'test3') t2
order by codeset, column;
</code>```

(It is not clear from your explanation and sample data whether you want to show the system belonging to the codeset/codevalue or to the column. I took it from the column row. If you want it elsewise, change the qualifier from t2 to t1.)

Here is another, shorter approach, that you may or may nt like better:

```<code>select t1.codeset, t1.codevalue, t2.column, t2.system
from mytable t1
join mytable t2 on t2.rowid = t1.rowid or (t2.codeset = 'test3' and t1.codeset = 'test3')
order by t1.codeset, t2.column;
</code>```

Body:
You want to self join all test3 rows. One way:

select codeset, codevalue, column, system
from mytable
where codeset <> 'test3'
union all
select t1.codeset, t1.codevalue, t2.column, t2.system
from (select * from mytable where codeset = 'test3') t1
cross join (select * from mytable where codeset = 'test3') t2
order by codeset, column;

(It is not clear from your explanation and sample data whether you want to show the system belonging to the codeset/codevalue or to the column. I took it from the column row. If you want it elsewise, change the qualifier from t2 to t1.)

Here is another, shorter approach, that you may or may nt like better:

select t1.codeset, t1.codevalue, t2.column, t2.system
from mytable t1
join mytable t2 on t2.rowid = t1.rowid or (t2.codeset = 'test3' and t1.codeset = 'test3')
order by t1.codeset, t2.column;


问:
How to make a github workflow error message show up in log and annotations?
I have a workflow step that runs this last stage of a shell command in a loop:

    || echo "::error Filename $filename doesn't match possible files" && exit 1 ; done

The exit is triggered appropriately, but the only annotation I see is:

Error: Process completed with exit code 1.

The log shows the entire shell command pipeline and also that same error message, but not my echo'd error.

How do I get my output, including the $filename variable, included?

答:
You have wrong syntax:

echo "::error::Filename $filename doesn't match possible files"

You need to postfix error with ::

Here is a working example of workflow using my suggestion:
https://github.com/grzegorzkrukowski/stackoverflow_tests/actions/runs/1835152772

There must be something else wrong with your workflow if it doesn't work - other command is exiting with code 1 before it has a chance to execute.


问:
C# Windows Forms - read XML into checkedlistbox
I'm creating a Windows Forms application in VisualStudio an C#.

I have a XML file like this:

```<code><?xml version="1.0" encoding="utf-8"?>
<Team>
<TeamMember>
    <Name>Jack John</Name>
    <MailAddress>Jack@test.com</MailAddress>
    <SearchName>John, Jack</SearchName>
    <AltSearchName>Jack John 123</AltSearchName>
</TeamMember>
<TeamMember>
    <Name>Johanna Johnson</Name>
    <MailAddress>Johanna@test.com</MailAddress>
    <SearchName>Johnson, Johanne</SearchName>
    <AltSearchName>Johanna Johnson 123</AltSearchName>
</TeamMember>
<TeamMember>
    <Name>Ron Ma</Name>
    <MailAddress>Ron@test.com</MailAddress>
    <SearchName>Ma, Ron</SearchName>
    <AltSearchName></AltSearchName>
</TeamMember>
</Team>
</code>```

What I want to achieve is to put all the Names (without the other informations of the XML) into one CheckedListBox.
Goal is to create a program in which you can paste a long string of Persons and email adresses and the code searches this string for all TeamMembers which are in the XML. If the long string contains the TeamMembers, it will "check" the box in the CheckedListBox of the coressponding person.

What I have so far:

```<code>using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace TestMailVerteiler
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            DataSet ds = new DataSet();
            string fileNameWithAbsolutePath = "C:/Test/Text.xml";
            ds.ReadXml(fileNameWithAbsolutePath);
            if (ds.Tables.Count > 0)
            {
                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                {
                    for (int j = 0; j < ds.Tables[0].Columns.Count; j++)
                    {
                        checkedListBox1.Items.Add(ds.Tables[0].Rows[i][j].ToString());
                    }
                }
            }

        }
    }
}
</code>```

But his (as expected) will put all information of the XML in the CheckedListBox.

What I'm thinking of:

Create a internal "table/class (?)" from my xml file

Use table column "Name" to fill out CheckedListBox

Use other table columns to later search the input-string and match the "Names", if match was found, after pressing a button, check ListBoxes accordingly.

How can I achieve this?

答:
The simplest thing is:

```<code>ds.ReadXml(fileNameWithAbsolutePath);
if (ds.Tables.Count > 0)
{
    for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
    {
        checkedListBox1.Items.Add(ds.Tables[0].Rows[i][0].ToString());
    }
}
</code>```

However, implementing a class is a good idea. To do this automatically, select your entire XML and copy to the clipboard. In Visual Studio, place the cursor at the point you wish to insert the classes. It should be outside the Form1 but inside the same namespace or on a separate class file. Then go to Edit (menu) and paste special > paste as XML class.

Something like that will come out:

```<code>/// <remarks/>
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "", IsNullable = false)]
public partial class Team
{

    private TeamTeamMember[] teamMemberField;

    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute("TeamMember")]
    public TeamTeamMember[] TeamMember
    {
        get
        {
            return this.teamMemberField;
        }
        set
        {
            this.teamMemberField = value;
        }
    }
}

/// <remarks/>
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
public partial class TeamTeamMember
{

    private string nameField;

    private string mailAddressField;

    private string searchNameField;

    private string altSearchNameField;

    /// <remarks/>
    public string Name
    {
        get
        {
            return this.nameField;
        }
        set
        {
            this.nameField = value;
        }
    }

    /// <remarks/>
    public string MailAddress
    {
        get
        {
            return this.mailAddressField;
        }
        set
        {
            this.mailAddressField = value;
        }
    }

    /// <remarks/>
    public string SearchName
    {
        get
        {
            return this.searchNameField;
        }
        set
        {
            this.searchNameField = value;
        }
    }

    /// <remarks/>
    public string AltSearchName
    {
        get
        {
            return this.altSearchNameField;
        }
        set
        {
            this.altSearchNameField = value;
        }
    }
}
</code>```

Now, here is a code to deserialize your xml and extract only the names in your checkedListbox:

```<code>            XmlSerializer xs = new XmlSerializer(typeof(Team));
            using (StreamReader rd = new StreamReader(MyXmlFile))
            {
                Team team = xs.Deserialize(rd) as Team;
                int n = team.TeamMember.Length;
                for (int i = 0; i < n; i++)
                {
                    checkedListBox1.Items.Add(team.TeamMember[i].Name);
                }
            }
</code>```

You will have to insert the following references at the beggining:

```<code>using System.Xml.Serialization;
using System.IO;
</code>```

Body:
I'm creating a Windows Forms application in VisualStudio an C#.

I have a XML file like this:

<?xml version="1.0" encoding="utf-8"?>
<Team>
<TeamMember>
    <Name>Jack John</Name>
    <MailAddress>Jack@test.com</MailAddress>
    <SearchName>John, Jack</SearchName>
    <AltSearchName>Jack John 123</AltSearchName>
</TeamMember>
<TeamMember>
    <Name>Johanna Johnson</Name>
    <MailAddress>Johanna@test.com</MailAddress>
    <SearchName>Johnson, Johanne</SearchName>
    <AltSearchName>Johanna Johnson 123</AltSearchName>
</TeamMember>
<TeamMember>
    <Name>Ron Ma</Name>
    <MailAddress>Ron@test.com</MailAddress>
    <SearchName>Ma, Ron</SearchName>
    <AltSearchName></AltSearchName>
</TeamMember>
</Team>

What I want to achieve is to put all the Names (without the other informations of the XML) into one CheckedListBox.
Goal is to create a program in which you can paste a long string of Persons and email adresses and the code searches this string for all TeamMembers which are in the XML. If the long string contains the TeamMembers, it will "check" the box in the CheckedListBox of the coressponding person.

What I have so far:

using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace TestMailVerteiler
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            DataSet ds = new DataSet();
            string fileNameWithAbsolutePath = "C:/Test/Text.xml";
            ds.ReadXml(fileNameWithAbsolutePath);
            if (ds.Tables.Count > 0)
            {
                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                {
                    for (int j = 0; j < ds.Tables[0].Columns.Count; j++)
                    {
                        checkedListBox1.Items.Add(ds.Tables[0].Rows[i][j].ToString());
                    }
                }
            }

        }
    }
}

But his (as expected) will put all information of the XML in the CheckedListBox.

What I'm thinking of:

Create a internal "table/class (?)" from my xml file

Use table column "Name" to fill out CheckedListBox

Use other table columns to later search the input-string and match the "Names", if match was found, after pressing a button, check ListBoxes accordingly.

How can I achieve this?

Body:
The simplest thing is:

ds.ReadXml(fileNameWithAbsolutePath);
if (ds.Tables.Count > 0)
{
    for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
    {
        checkedListBox1.Items.Add(ds.Tables[0].Rows[i][0].ToString());
    }
}

However, implementing a class is a good idea. To do this automatically, select your entire XML and copy to the clipboard. In Visual Studio, place the cursor at the point you wish to insert the classes. It should be outside the Form1 but inside the same namespace or on a separate class file. Then go to Edit (menu) and paste special > paste as XML class.

Something like that will come out:

/// <remarks/>
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "", IsNullable = false)]
public partial class Team
{

    private TeamTeamMember[] teamMemberField;

    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute("TeamMember")]
    public TeamTeamMember[] TeamMember
    {
        get
        {
            return this.teamMemberField;
        }
        set
        {
            this.teamMemberField = value;
        }
    }
}

/// <remarks/>
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
public partial class TeamTeamMember
{

    private string nameField;

    private string mailAddressField;

    private string searchNameField;

    private string altSearchNameField;

    /// <remarks/>
    public string Name
    {
        get
        {
            return this.nameField;
        }
        set
        {
            this.nameField = value;
        }
    }

    /// <remarks/>
    public string MailAddress
    {
        get
        {
            return this.mailAddressField;
        }
        set
        {
            this.mailAddressField = value;
        }
    }

    /// <remarks/>
    public string SearchName
    {
        get
        {
            return this.searchNameField;
        }
        set
        {
            this.searchNameField = value;
        }
    }

    /// <remarks/>
    public string AltSearchName
    {
        get
        {
            return this.altSearchNameField;
        }
        set
        {
            this.altSearchNameField = value;
        }
    }
}

Now, here is a code to deserialize your xml and extract only the names in your checkedListbox:

            XmlSerializer xs = new XmlSerializer(typeof(Team));
            using (StreamReader rd = new StreamReader(MyXmlFile))
            {
                Team team = xs.Deserialize(rd) as Team;
                int n = team.TeamMember.Length;
                for (int i = 0; i < n; i++)
                {
                    checkedListBox1.Items.Add(team.TeamMember[i].Name);
                }
            }

You will have to insert the following references at the beggining:

using System.Xml.Serialization;
using System.IO;


问:
Amcharts 4 : Disable single legend item programmatically
I just need to know how to disable a single legend item programmatically on chart reload (disable means: legend is shown greyed out and its linked curve is hidden), as I need to reload a chart with some new data using some back and forward arrows, but still need to remember the user preference or the state of legend items (on/off)

答:
Thanks @xorspark that's really it, it's about controlling the series not legend.

It happened to work specifically with the appeared or inited events, not shown event as it seemed to be, like this:

```<code>series.events.on("inited", () => {
  reactState ? series.show() : series.hide();
});
</code>```

inited event even works better, as disabled legends will not show a glimpse of their color on the curve when using appeared.

Body:
Thanks @xorspark that's really it, it's about controlling the series not legend.

It happened to work specifically with the appeared or inited events, not shown event as it seemed to be, like this:

series.events.on("inited", () => {
  reactState ? series.show() : series.hide();
});

inited event even works better, as disabled legends will not show a glimpse of their color on the curve when using appeared.


问:
Open Refine / Google Refine - Remove blank cells in a column
The task is simple to understand, I have a table like this:

And I would like to edit the column "L1_latitud" to collapse (or remove) all the blank cells:

It looks like a simple task but I can't find out a way to deal with it.

答:
Create "Facet" -> "Customized facets" -> "Facet by null"

then simply exclude True choice in facet


问:
Why trigger in SQlite3 is not waiting for commit?
I have problem with calling python function after sqlite3 insert.

I found example there, but is not passing my conditions. Link: Launch a Python Script from a sqlite3 Trigger

My code is similar, but inside function I want to select all inserted values.

```<code>import sqlite3

def hello():
    print ("Hello is executing")
    try:
        con = sqlite3.connect('test1.db')
        sql = "SELECT x FROM t WHERE 1==1"
        cur = con.cursor()
        for row in  cur.execute(sql):
            print(row)
    except Exception as e:
        print('ttt')
        print(e)

con = sqlite3.connect('test1.db')
con.create_function("hello",0, hello)
cur = con.cursor()
cur.execute("CREATE TABLE IF NOT EXISTS t(x)")
cur.execute("CREATE TRIGGER IF NOT EXISTS tt  AFTER INSERT ON t BEGIN SELECT hello(); END;")
cur.execute("INSERT INTO t VALUES(2)")
con.commit()
con.close()
</code>```

Problem is that when I first time execute a script I do not see inserted value in hello() function. Program is printing only:

```<code>Hello is executing
</code>```

It is looking like trigger is executing a job before commit instruction.

Is that bug on SQlite3 or is other way to see inserted value in python function?

Can you help me?

答: The bug is not in SQLite3; it is in the program.  "trigger is executing a job before commit instruction" is true. The proximate cause is because a new connection to the database is created in the function, the trigger executes before the commit, therefore the SELECT in the function does not "know" the new row. Do not create a new connection in the function.

Body:
I have problem with calling python function after sqlite3 insert.

I found example there, but is not passing my conditions. Link: Launch a Python Script from a sqlite3 Trigger

My code is similar, but inside function I want to select all inserted values.

import sqlite3

def hello():
    print ("Hello is executing")
    try:
        con = sqlite3.connect('test1.db')
        sql = "SELECT x FROM t WHERE 1==1"
        cur = con.cursor()
        for row in  cur.execute(sql):
            print(row)
    except Exception as e:
        print('ttt')
        print(e)

con = sqlite3.connect('test1.db')
con.create_function("hello",0, hello)
cur = con.cursor()
cur.execute("CREATE TABLE IF NOT EXISTS t(x)")
cur.execute("CREATE TRIGGER IF NOT EXISTS tt  AFTER INSERT ON t BEGIN SELECT hello(); END;")
cur.execute("INSERT INTO t VALUES(2)")
con.commit()
con.close()

Problem is that when I first time execute a script I do not see inserted value in hello() function. Program is printing only:

Hello is executing

It is looking like trigger is executing a job before commit instruction.

Is that bug on SQlite3 or is other way to see inserted value in python function?

Can you help me?


问:
Adjust the setting guides indentation to keep it to the UI guides of Flutter on the VS Code
How can i set the guides indentation like this?

I just want to keep it to the Flutter UI Guides.

答:
In Andriod Studio

to enable flutter UI guides goto

Files -> Settings -> Languages & Frameworks -> Flutter

and in editor enable(tick) the Show UI guides for build methods

In VScode

goto settings search for flutter UI and enable preview flutter UI guides

or

goto settings.json and add
"dart.previewFlutterUiGuides": true, "dart.previewFlutterUiGuidesCustomTracking": true, & restart the vscode


问:
How to read user input directly in Node.js
From the following code I can read and console.log the line

```<code>const readline = require('readline');
const { stdin: input, stdout: output } = require('process');

const rl = readline.createInterface({ input, output });

rl.question('What is your name? ', (answer) => {
  console.log(`Hi ${answer}!`);

  rl.close();
});
</code>```

But I am trying to read user input like this
Input: node app.js John
Ouput: Hi John!

How can I achieve this in node?

答:
To achieve that you can use the following:

```<code>process.argv
</code>```

process.argv is an array containing all arguments that were used when invoking you programm.
Image you called your programm like that: node index.js "John", process.argv would look like this: ["node", "path/to/index.js", "John"].

Body:
From the following code I can read and console.log the line

const readline = require('readline');
const { stdin: input, stdout: output } = require('process');

const rl = readline.createInterface({ input, output });

rl.question('What is your name? ', (answer) => {
  console.log(`Hi ${answer}!`);

  rl.close();
});

But I am trying to read user input like this
Input: node app.js John
Ouput: Hi John!

How can I achieve this in node?

Body:
To achieve that you can use the following:

process.argv

process.argv is an array containing all arguments that were used when invoking you programm.
Image you called your programm like that: node index.js "John", process.argv would look like this: ["node", "path/to/index.js", "John"].


问:
Using DECODE Statement in SQL
I have been trying to learn SQL, and I was learning the DECODE statement:

This is the query I was trying to use:

```<code>SELECT DECODE(FIRST_NAME,'Steven','Name is Steven','Neena','Name is Neena','Some other name') AS "NAME" FROM hr.employees;
</code>```

This query works successfully,but when I try the query:

```<code>SELECT DECODE(FIRST_NAME,'Steven','Name is Steven','Neena','Name is Neena','Some other name') AS "NAME" WHERE FIRST_NAME='Steven' FROM hr.employees;
</code>```

This query gives me the output as:

```<code>ORA-00923: FROM keyword not found where expected
</code>```

Can anyone explain me what's wrong?

答:
Where clause needs to be placed after From clause.

```<code>SELECT DECODE(FIRST_NAME,'Steven','Name is Steven','Neena','Name is Neena','Some other name') AS "NAME"
FROM hr.employees
WHERE FIRST_NAME='Steven';
</code>```

Title: Using DECODE Statement in SQL

Body:
I have been trying to learn SQL, and I was learning the DECODE statement:

This is the query I was trying to use:

SELECT DECODE(FIRST_NAME,'Steven','Name is Steven','Neena','Name is Neena','Some other name') AS "NAME" FROM hr.employees;

This query works successfully,but when I try the query:

SELECT DECODE(FIRST_NAME,'Steven','Name is Steven','Neena','Name is Neena','Some other name') AS "NAME" WHERE FIRST_NAME='Steven' FROM hr.employees;

This query gives me the output as:

ORA-00923: FROM keyword not found where expected

Can anyone explain me what's wrong?

Body:
Where clause needs to be placed after From clause.

SELECT DECODE(FIRST_NAME,'Steven','Name is Steven','Neena','Name is Neena','Some other name') AS "NAME"
FROM hr.employees
WHERE FIRST_NAME='Steven';


问:
Set a drawable as background programmatically
EDIT: Sorry I realise from your comment my question was not clear enough. I will post a new one. Sorry for this and thanks for your answers

I am populating a ListView from a Json file.

With my listadapter, I can easily assign appropriate json data to each row of my list. That works well for text, for example:

```<code>TextView tv = (TextView)ll.findViewById(R.id.descView);
tv.setText(i.desc);
</code>```

With the above code, every row will be correctly populated by the good json data.

However, I don't manage to do the same thing for an image. I have tried to set the right image from my json data using this:

```<code>ImageView iv = (ImageView)ll.findViewById(R.id.imgView);
iv.setBackgroundDrawable(context.getResources().getDrawable(i.img));
</code>```

I guess I am doing something wrong with the type of my parameters: "setBackgroundDrawable" requires a drawable parameter.
"getDrawable" requires an int.
I have set the type of my field img to int, but that doesn't work.

Any idea why?

My list adapter:

```<code>public class adapter extends ArrayAdapter<ListItems> {

int resource;
String response;
Context context;

//Initialize adapter
public ListItemsAdapter(Context context, int resource, List<ListItems> items) {
    super(context, resource, items);
    this.resource=resource;
}

@Override
public View getView(int position, View convertView, ViewGroup parent)
{

    //Get the current object
    ListItems i = getItem(position);

    //Inflate the view
    if(convertView==null)
    {
        ll = new LinearLayout(getContext());
        String inflater = Context.LAYOUT_INFLATER_SERVICE;
        LayoutInflater li;
        li = (LayoutInflater)getContext().getSystemService(inflater);
        li.inflate(resource, ll, true);
    }
    else
    {
        ll = (LinearLayout) convertView;
    }

    //For the message
    TextView tv = (TextView)ll.findViewById(R.id.descView);
    tv.setText(i.desc);

// For the Img
    ImageView iv = (ImageView)ll.findViewById(R.id.imgView);
    iv.setBackgroundDrawable(context.getResources().getDrawable(i.img));

    return ll;
}
</code>```

my item class:

```<code>    public class ListItems{
int id;
int img;
String desc;}
</code>```

And a sample of my json file:

```<code>    [{"id":10001,"img":e1,"desc":"desc1"},
    {"id":10002,"img":e2,"desc":"desc2"},
    {"id":10003,"img":e3,"desc":"desc3"}]
</code>```

答:
If you want to change the ImageView image/src,

In Layout android:src="@drawable/img" or app:srcCompat="@drawable/img"

Programmatically imageview.setImageResource(R.drawable.img);

If you want to change the background of ImageView

In Layout android:background="@drawable/img"

programmatically selectimg.setBackgroundResource(R.drawable.circle_filled);

Here imageview is a ImageView and img is a drawable.

Body:
EDIT: Sorry I realise from your comment my question was not clear enough. I will post a new one. Sorry for this and thanks for your answers

I am populating a ListView from a Json file.

With my listadapter, I can easily assign appropriate json data to each row of my list. That works well for text, for example:

TextView tv = (TextView)ll.findViewById(R.id.descView);
tv.setText(i.desc);

With the above code, every row will be correctly populated by the good json data.

However, I don't manage to do the same thing for an image. I have tried to set the right image from my json data using this:

ImageView iv = (ImageView)ll.findViewById(R.id.imgView);
iv.setBackgroundDrawable(context.getResources().getDrawable(i.img));

I guess I am doing something wrong with the type of my parameters: "setBackgroundDrawable" requires a drawable parameter.
"getDrawable" requires an int.
I have set the type of my field img to int, but that doesn't work.

Any idea why?

My list adapter:

public class adapter extends ArrayAdapter<ListItems> {

int resource;
String response;
Context context;

//Initialize adapter
public ListItemsAdapter(Context context, int resource, List<ListItems> items) {
    super(context, resource, items);
    this.resource=resource;
}

@Override
public View getView(int position, View convertView, ViewGroup parent)
{

    //Get the current object
    ListItems i = getItem(position);

    //Inflate the view
    if(convertView==null)
    {
        ll = new LinearLayout(getContext());
        String inflater = Context.LAYOUT_INFLATER_SERVICE;
        LayoutInflater li;
        li = (LayoutInflater)getContext().getSystemService(inflater);
        li.inflate(resource, ll, true);
    }
    else
    {
        ll = (LinearLayout) convertView;
    }

    //For the message
    TextView tv = (TextView)ll.findViewById(R.id.descView);
    tv.setText(i.desc);

// For the Img
    ImageView iv = (ImageView)ll.findViewById(R.id.imgView);
    iv.setBackgroundDrawable(context.getResources().getDrawable(i.img));

    return ll;
}

my item class:

    public class ListItems{
int id;
int img;
String desc;}

And a sample of my json file:

    [{"id":10001,"img":e1,"desc":"desc1"},
    {"id":10002,"img":e2,"desc":"desc2"},
    {"id":10003,"img":e3,"desc":"desc3"}]


问:
Unable to install wget
My MacBook Air was equipped with macOS Mojave Version 10.14.6.
I cannot install wget even if I have checked brew version.

```<code>brew --version
</code>```

The output is :

```<code>Homebrew 3.3.13
Homebrew/homebrew-core (no Git repository)
Homebrew/homebrew-cask (git revision fb6ec06d8b; last commit 2022-01-31)
</code>```

When I tried to install wget:

```<code>brew install wget
</code>```

This is the result:

```<code>Warning: No available formula with the name "ca-certificates".
==> Searching for similarly named formulae...
Error: No similarly named formulae found.
==> Searching for a previously deleted formula (in the last month)...
Error: No previously deleted formula found.
==> Searching taps on GitHub...
Running `brew update --preinstall`...
Error: No formulae found in taps.
fatal: Could not resolve HEAD to a revision
Warning: No available formula with the name "wget".
==> Searching for similarly named formulae...
Error: No similarly named formulae found.
==> Searching for a previously deleted formula (in the last month)...
Error: No previously deleted formula found.
==> Searching taps on GitHub...
Error: No formulae found in taps.
</code>```

This problem has bothered me for a long while...

答:
Eventually, I solved this problem by running the following code:

```<code>brew update-reset
brew install wget
</code>```

I hoped this may help others.

Title: Unable to install wget

Body:
My MacBook Air was equipped with macOS Mojave Version 10.14.6.
I cannot install wget even if I have checked brew version.

brew --version

The output is :

Homebrew 3.3.13
Homebrew/homebrew-core (no Git repository)
Homebrew/homebrew-cask (git revision fb6ec06d8b; last commit 2022-01-31)

When I tried to install wget:

brew install wget

This is the result:

Warning: No available formula with the name "ca-certificates".
==> Searching for similarly named formulae...
Error: No similarly named formulae found.
==> Searching for a previously deleted formula (in the last month)...
Error: No previously deleted formula found.
==> Searching taps on GitHub...
Running `brew update --preinstall`...
Error: No formulae found in taps.
fatal: Could not resolve HEAD to a revision
Warning: No available formula with the name "wget".
==> Searching for similarly named formulae...
Error: No similarly named formulae found.
==> Searching for a previously deleted formula (in the last month)...
Error: No previously deleted formula found.
==> Searching taps on GitHub...
Error: No formulae found in taps.

This problem has bothered me for a long while...

Body:
Eventually, I solved this problem by running the following code:

brew update-reset
brew install wget

I hoped this may help others.


问:
Opencl/Gcc error vsc "fatal error: CL/cl.hpp: No such file or directory"
I am having trouble compiling a OpenCL code with two .cl kernel files and a .cpp file, I'm new to C++ but I know you need headers so I've downloaded many eg. OCL_SDK_LIGHT, CUDA, vcpkg OPENCL package. All bring up the same error after compiling and only after compiling here is the error. I'm using the mingw64 g++ compiling which doesn't contain the CL/cl.hpp file, I've tried adding it directly into the include file from other directories but that just brings up more errors. I have also tried compiling in and out of vsc with similar results. I have a nvidia gpu and an amd cpu. I have also added the path to the CUDA toolkit in the properties.json file in vsc.

Any help would be amazing!

答:
You have to tell the compiler where the CL/cl.hpp file is located. I usually copy the folder containing the OpenCL headers in the project directory. Then compile with:

```<code>g++ *.cpp -o Test.exe -I./OpenCL/include -L./OpenCL/lib -lOpenCL
</code>```

Once you have the OpenCL headers, there is no need to install any SDK or CUDA. The graphics driver alone is sufficient as it contains the OpenCL Runtime.

For an easy start with OpenCL development, I recomment this OpenCL-Wrapper. It contains a vector addition example. The Wrapper vastly simplifies working OpenCL and entirely eliminates code overhead.

Body:
You have to tell the compiler where the CL/cl.hpp file is located. I usually copy the folder containing the OpenCL headers in the project directory. Then compile with:

g++ *.cpp -o Test.exe -I./OpenCL/include -L./OpenCL/lib -lOpenCL

Once you have the OpenCL headers, there is no need to install any SDK or CUDA. The graphics driver alone is sufficient as it contains the OpenCL Runtime.

For an easy start with OpenCL development, I recomment this OpenCL-Wrapper. It contains a vector addition example. The Wrapper vastly simplifies working OpenCL and entirely eliminates code overhead.


问:
adding records to inmemorydatabase just once
I am trying to write my very first xunit test with Database, instead of mocking the DbContext I used the inMemoryDatabase as I read in articles, so I did like following

public class GetCustomersTest
{
DbContextOptions _context;

```<code>    public GetCustomersTest()
    {
        if (_context==null)
            _context = CreateContextForCustomer();
    }

    [Theory]
    [InlineData(1)]
    [InlineData(2)]
    public void GetCustomerById_ShouldReturnCorrectObject(int id)
    {
        using (var context = new DataBaseContext(_context))
        {
            var customerByIdService = new GetCustomerByIdService(context);

            var customer = customerByIdService.Execute(id);
            var customerActual = context.Customers.Where(x => x.Id == id).SingleOrDefault();
            var customerTmp = new Customer()
            {
                Id = id,
                FirstName = customer.Data.FirstName,
                LastName = customer.Data.LastName,
                Phone = customer.Data.Phone,
                ClientNote = customer.Data.ClientNote
            };
            Assert.Equal(customerTmp.FirstName, customerActual.FirstName);
            Assert.Equal(customerTmp.LastName, customerActual.LastName);
            Assert.Equal(customerTmp.Phone, customerActual.Phone);
            Assert.Equal(customerTmp.ClientNote, customerActual.ClientNote);

        }
    }

    private DbContextOptions<DataBaseContext> CreateContextForCustomer() {

        var options = new DbContextOptionsBuilder<DataBaseContext>()
            .UseInMemoryDatabase(databaseName: "SalonDatabase")
            .Options;

        using (var context = new DataBaseContext(options))
        {
            context.Customers.Add(new Customer
            {
                Id = 1,
                FirstName = "User1",
                LastName = "Surname1",
                Phone = "123",
                ClientNote = ""
            });
            context.Customers.Add(new Customer
            {
                Id = 2,
                FirstName = "User2",
                LastName = "Surname2",
                Phone = "4567",
                ClientNote = "The best"
            });

            context.SaveChanges();
        }
        return options;
    }
}
</code>```

it works find on [InlineData(1)] but when it comes to [InlineData(2)], it seems that it starts to run the constructor again , so as it wants to add the customerdata to table, it says that the record with that Id key exists.what is the best way for doing that?

答:
When building your DB context options, add a GUID to the database name to make it unique:

```<code>var options = new DbContextOptionsBuilder<DataBaseContext>()
    .UseInMemoryDatabase(databaseName: "SalonDatabase" + Guid.NewGuid().ToString())
    .Options;
</code>```

Or if you're using a new enough language version you can use string interpolation instead of concatenation:

```<code>var options = new DbContextOptionsBuilder<DataBaseContext>()
    .UseInMemoryDatabase(databaseName: $"SalonDatabase{Guid.NewGuid()}")
    .Options;
</code>```

If you do this then every test uses a brand new database, unaffected by any previous tests.

As @MicheleMassari says, it's good practice to follow the Arrange Act Assert pattern, so that it's clear which lines are setting things up ready for the test and which are performing the action that you want to test the outcome of.

Arrange inputs and targets. Arrange steps should set up the test case. Does the test require any objects or special settings? Does it need to prep a database? Does it need to log into a web app? Handle all of these operations at the start of the test.

Act on the target behavior. Act steps should cover the main thing to be tested. This could be calling a function or method, calling a REST API, or interacting with a web page. Keep actions focused on the target behavior.

Assert expected outcomes. Act steps should elicit some sort of response. Assert steps verify the goodness or badness of that response. Sometimes, assertions are as simple as checking numeric or string values. Other times, they may require checking multiple facets of a system. Assertions will ultimately determine if the test passes or fails.

The code samples in that page are written in Python rather than C#, but the pattern is valid for unit tests in any language. In the case of your test, structuring the test in this way makes it clear whether you're testing the behaviour of GetCustomerByIdService.Execute or of Entity Framework's Where method.

Body:
I am trying to write my very first xunit test with Database, instead of mocking the DbContext I used the inMemoryDatabase as I read in articles, so I did like following

public class GetCustomersTest
{
DbContextOptions _context;

    public GetCustomersTest()
    {
        if (_context==null)
            _context = CreateContextForCustomer();
    }

    [Theory]
    [InlineData(1)]
    [InlineData(2)]
    public void GetCustomerById_ShouldReturnCorrectObject(int id)
    {
        using (var context = new DataBaseContext(_context))
        {
            var customerByIdService = new GetCustomerByIdService(context);

            var customer = customerByIdService.Execute(id);
            var customerActual = context.Customers.Where(x => x.Id == id).SingleOrDefault();
            var customerTmp = new Customer()
            {
                Id = id,
                FirstName = customer.Data.FirstName,
                LastName = customer.Data.LastName,
                Phone = customer.Data.Phone,
                ClientNote = customer.Data.ClientNote
            };
            Assert.Equal(customerTmp.FirstName, customerActual.FirstName);
            Assert.Equal(customerTmp.LastName, customerActual.LastName);
            Assert.Equal(customerTmp.Phone, customerActual.Phone);
            Assert.Equal(customerTmp.ClientNote, customerActual.ClientNote);

        }
    }

    private DbContextOptions<DataBaseContext> CreateContextForCustomer() {

        var options = new DbContextOptionsBuilder<DataBaseContext>()
            .UseInMemoryDatabase(databaseName: "SalonDatabase")
            .Options;

        using (var context = new DataBaseContext(options))
        {
            context.Customers.Add(new Customer
            {
                Id = 1,
                FirstName = "User1",
                LastName = "Surname1",
                Phone = "123",
                ClientNote = ""
            });
            context.Customers.Add(new Customer
            {
                Id = 2,
                FirstName = "User2",
                LastName = "Surname2",
                Phone = "4567",
                ClientNote = "The best"
            });

            context.SaveChanges();
        }
        return options;
    }
}

it works find on [InlineData(1)] but when it comes to [InlineData(2)], it seems that it starts to run the constructor again , so as it wants to add the customerdata to table, it says that the record with that Id key exists.what is the best way for doing that?

Body:
When building your DB context options, add a GUID to the database name to make it unique:

var options = new DbContextOptionsBuilder<DataBaseContext>()
    .UseInMemoryDatabase(databaseName: "SalonDatabase" + Guid.NewGuid().ToString())
    .Options;

Or if you're using a new enough language version you can use string interpolation instead of concatenation:

var options = new DbContextOptionsBuilder<DataBaseContext>()
    .UseInMemoryDatabase(databaseName: $"SalonDatabase{Guid.NewGuid()}")
    .Options;

If you do this then every test uses a brand new database, unaffected by any previous tests.

As @MicheleMassari says, it's good practice to follow the Arrange Act Assert pattern, so that it's clear which lines are setting things up ready for the test and which are performing the action that you want to test the outcome of.

Arrange inputs and targets. Arrange steps should set up the test case. Does the test require any objects or special settings? Does it need to prep a database? Does it need to log into a web app? Handle all of these operations at the start of the test.

Act on the target behavior. Act steps should cover the main thing to be tested. This could be calling a function or method, calling a REST API, or interacting with a web page. Keep actions focused on the target behavior.

Assert expected outcomes. Act steps should elicit some sort of response. Assert steps verify the goodness or badness of that response. Sometimes, assertions are as simple as checking numeric or string values. Other times, they may require checking multiple facets of a system. Assertions will ultimately determine if the test passes or fails.

The code samples in that page are written in Python rather than C#, but the pattern is valid for unit tests in any language. In the case of your test, structuring the test in this way makes it clear whether you're testing the behaviour of GetCustomerByIdService.Execute or of Entity Framework's Where method.


问:
REST API iOS development
I'm having lots of trouble setting up the RestKit API to my app. I wonder if there is any other good API to make RESTful apps? I've just followed lots of tutorials and the github directory of the RestKit API, but I just can't get it up and running. I've seen that Xcode 4 is having problems importing this API.

This is an old question, Nowadays, after 4 years in iOS development I use AFNetworking: https://github.com/AFNetworking/AFNetworking

It is quite simple to start, and can be installed using cocoapods.

答: I use ASIHTTPRequest for RESTful client stuff in my apps.</p>

Title: REST API iOS development


问:
Android Studio Bumblebee - device manager not opening
I just updated Android Studio to:
Android Studio Bumblebee | 2021.1.1
Build #AI-211.7628.21.2111.8092744, built on January 19, 2022

But now I cannot open the device manager anymore.

If I click on the icon, nothing happens.

答:
If you are still experiencing this issue in the latest version(Android Studio Bumblebee | 2021.1.1 Patch1), click on the search icon in Android Studio and type "virtual device manager".

See attached screenshots.