问:
Mapbox - How to properly use the Tilesets API
I am trying to update my existing tileset with new data.  In postman, I sucessfully send the following;

```<code>https://api.mapbox.com/tilesets/v1/sources/{{usermame}}/testing?access_token={{admin-access-token}}
</code>```

In the body, I have added a new line delimited geojson, as required, with the following key/value pair;

```<code>key:  file
value:  file_nd.geojson
</code>```

As a reply I get the following;

```<code>status: ok

{
    "id": "mapbox://tileset-source/{{username}}/testing",
    "files": 1,
    "source_size": 1131168,
    "file_size": 1131168
}
</code>```

When I go to the tileset tab on the mapbox website, the modified time does not change and the data is not updated.  I did notice though that if I look at tileset sources in postman using the following;

```<code>https://api.mapbox.com/tilesets/v1/sources/{{username}}?access_token={{admin-access-token}}
</code>```

This is returned;

```<code>    {
        "id": "mapbox://tileset-source/{{username}}/testing",
        "size": 1131168,
        "files": 1
    },
</code>```

So I am guessing that it has not yet been converted to a tileset.  I cannot see in the documentation how to trigger the conversion via the API.  Any help appreciated.

Body:
I am trying to update my existing tileset with new data.  In postman, I sucessfully send the following;

https://api.mapbox.com/tilesets/v1/sources/{{usermame}}/testing?access_token={{admin-access-token}}

In the body, I have added a new line delimited geojson, as required, with the following key/value pair;

key:  file
value:  file_nd.geojson

As a reply I get the following;

status: ok

{
    "id": "mapbox://tileset-source/{{username}}/testing",
    "files": 1,
    "source_size": 1131168,
    "file_size": 1131168
}

When I go to the tileset tab on the mapbox website, the modified time does not change and the data is not updated.  I did notice though that if I look at tileset sources in postman using the following;

https://api.mapbox.com/tilesets/v1/sources/{{username}}?access_token={{admin-access-token}}

This is returned;

    {
        "id": "mapbox://tileset-source/{{username}}/testing",
        "size": 1131168,
        "files": 1
    },

So I am guessing that it has not yet been converted to a tileset.  I cannot see in the documentation how to trigger the conversion via the API.  Any help appreciated.


来源: stackexchange

问:
How to configure Multiple smtp in phplist
How to configure multiple smtp and rotate to always send mails with different smtp through phplist.

I want to send mails with different smtp through phplist.

ContentLicense: CC BY-SA 4.0


问:
script malfunctioning when added to character
I have a simple code that kicks the ball in the direction the player is facing, it worked fine when I tested it with a cube as player but,
now when I added the same script to player character it's only kicking the ball when it's all x, y, z rotation is zero
the code:

```<code>if (Input.GetKey(KeyCode.Space))
{
    Vector3 kickDirection=playerfrount.position - playerback.position;

    kickDirection = kickDirection.normalized;
    Debug.Log(kickDirection);
    //Vector3 forwardd = transform.forward;
    carryingBallplayer = false;
    rbb.AddForce(kickDirection  * kickForceplayer, ForceMode.Impulse);
}
</code>```

I am expecting that the player character kicks in the direction it's facing

Body:
I have a simple code that kicks the ball in the direction the player is facing, it worked fine when I tested it with a cube as player but,
now when I added the same script to player character it's only kicking the ball when it's all x, y, z rotation is zero
the code:

if (Input.GetKey(KeyCode.Space))
{
    Vector3 kickDirection=playerfrount.position - playerback.position;

    kickDirection = kickDirection.normalized;
    Debug.Log(kickDirection);
    //Vector3 forwardd = transform.forward;
    carryingBallplayer = false;
    rbb.AddForce(kickDirection  * kickForceplayer, ForceMode.Impulse);
}

I am expecting that the player character kicks in the direction it's facing


问:
How to output only records from Elastic where a value has changed?
I have a records in EL including time, ID and palce. I need to print only records where the place has changed. Original output for ID=1234:

Time
ID
Place

time1
1234
place1

time2
1234
place1

time3
1234
place2

time4
1234
place2

time5
1234
place3

Required output for ID=1234 (display records where place has changed) :

Time
ID
Place

time1
1234
place1

time3
1234
place2

time5
1234
place3

How is it possible to do it? Using EL 7.17.0 and Kibana.

Tried to define new field "place_diff" in index pattern comparing previous and current value (if different than fill "Y"), but do not know how to access previous valued of the "place" field.


问:
Alternative for Angular (javascript) beforeunload event on mobile devices
What are an alternatives to beforeunload event on mobile devices?
According to the docs (https://developer.mozilla.org/en-US/docs/Web/API/Window/beforeunload_event) beforeunload event doesn't work on mobile devices.

Our customer wants a popup message before closing the browser if user don't save the edited form.

On browsers it works fine with 'beforeunload' event.

Angular code:

```<code>  @HostListener('window:beforeunload', ['$event'])
  unloadNotification($event: BeforeUnloadEvent) {
    if (!this.hasFormChanged) return;
    $event.returnValue();
  }
</code>```

Thanks to everyone for your help.

Body:
What are an alternatives to beforeunload event on mobile devices?
According to the docs (https://developer.mozilla.org/en-US/docs/Web/API/Window/beforeunload_event) beforeunload event doesn't work on mobile devices.

Our customer wants a popup message before closing the browser if user don't save the edited form.

On browsers it works fine with 'beforeunload' event.

Angular code:

  @HostListener('window:beforeunload', ['$event'])
  unloadNotification($event: BeforeUnloadEvent) {
    if (!this.hasFormChanged) return;
    $event.returnValue();
  }

Thanks to everyone for your help.


问:
How would I create a div container with three divs in a row where the divs on both sides expand away from the center when an event is triggered?
I want to create a div that has three nested divs touching each other in a row. I want the div at the center of this container to have a constant width. While I want the left div's width to expand to the left(i.e. not pushing the other two divs in the container to the right) on hover and stay expanded on click. I want the same thing to happen to right div's width except it expands to the right. All the nested divs would have content in them some of the content not completely visible until the div expands.

This would be the general idea:

When Neither is Hovered -->
enter image description here

When One Is Hovered -->
enter image description here

When They Are Both Clicked -->
enter image description here

The problem is I haven't been able to figure out a way to do this or find out if there is a tutorial or something that would be helpful in accomplishing this. I have tried googling how to create this, and in all honesty was not to sure exactly what to search up but nothing has really helped me get both divs expanding the way I want. I would appreciate any help in finding a tutorial or any implementation that might work.

So far I have been able to get this far in terms of coding it in HTML and CSS, but have been stuck for a while with no attempt being closer than this. I would need this to be on top of other elements on a page in my webpage hence the z-index, and positioning is so that I could move it to my desired place on the webpage. I am able to get the right div to expand how I want easily as that is the default behavior but when I try to get the left div and right div to both expand I have been stuck. I have gotten the left div to expand at one point but that led to the right div not working. So right now this is the closest I have gotten both expand properly but the left div is under the center div instead of beside it.

I added a bit of a yellow background in the images to give an idea of positioning

Result on Webpage No Hover -->
enter image description here

Result on Webpage On Hover Of Left Div-->
enter image description here

Result on Webpage On Hover Of Right Div-->
enter image description here

HTML-->

```<code><div class="sliding-window">
   <div class="left-wing">
   </div>
   <div class="middle-box">
      <h3>Content</h3>
   </div>
   <div class="right-wing">
   </div>
</div>
</code>```

CSS-->

```<code>.sliding-window{
  display: flex;
  flex-direction: row;
  /* justify-content: center; */
  z-index: 25;
  position: absolute;
  top: 30%;
  left: 35%;
  width: 850px;
}

.middle-box{
  left: 250px;
  border: 1px red solid;
  text-align: center;
  height: 300px;
  width: 250px;
  border-radius: 10%;
  background-color: grey;
}

.left-wing{
  border: 1px violet solid;
  height: 250px;
  /* float: left;  */
  position: relative;
  float: left;
  left:200px;
  margin-top: 25px;
  margin-bottom: 25px;
  width: 50px;
  background-color: grey;
}

.right-wing{
  left:450px;
  border: 1px green solid;
  height: 250px;
  margin-top: 25px;
  margin-bottom: 25px;
  width: 50px;
  background-color: grey;
}

.right-wing:hover{
  width: 200px;
}

.left-wing:hover{
  width: 200px;
  /* margin-left: -200px; */
}
</code>```

Body:
I want to create a div that has three nested divs touching each other in a row. I want the div at the center of this container to have a constant width. While I want the left div's width to expand to the left(i.e. not pushing the other two divs in the container to the right) on hover and stay expanded on click. I want the same thing to happen to right div's width except it expands to the right. All the nested divs would have content in them some of the content not completely visible until the div expands.

This would be the general idea:

When Neither is Hovered -->
enter image description here

When One Is Hovered -->
enter image description here

When They Are Both Clicked -->
enter image description here

The problem is I haven't been able to figure out a way to do this or find out if there is a tutorial or something that would be helpful in accomplishing this. I have tried googling how to create this, and in all honesty was not to sure exactly what to search up but nothing has really helped me get both divs expanding the way I want. I would appreciate any help in finding a tutorial or any implementation that might work.

So far I have been able to get this far in terms of coding it in HTML and CSS, but have been stuck for a while with no attempt being closer than this. I would need this to be on top of other elements on a page in my webpage hence the z-index, and positioning is so that I could move it to my desired place on the webpage. I am able to get the right div to expand how I want easily as that is the default behavior but when I try to get the left div and right div to both expand I have been stuck. I have gotten the left div to expand at one point but that led to the right div not working. So right now this is the closest I have gotten both expand properly but the left div is under the center div instead of beside it.

I added a bit of a yellow background in the images to give an idea of positioning

Result on Webpage No Hover -->
enter image description here

Result on Webpage On Hover Of Left Div-->
enter image description here

Result on Webpage On Hover Of Right Div-->
enter image description here

HTML-->

Content

CSS-->

.sliding-window{
  display: flex;
  flex-direction: row;
  /* justify-content: center; */
  z-index: 25;
  position: absolute;
  top: 30%;
  left: 35%;
  width: 850px;
}

.middle-box{
  left: 250px;
  border: 1px red solid;
  text-align: center;
  height: 300px;
  width: 250px;
  border-radius: 10%;
  background-color: grey;
}

.left-wing{
  border: 1px violet solid;
  height: 250px;
  /* float: left;  */
  position: relative;
  float: left;
  left:200px;
  margin-top: 25px;
  margin-bottom: 25px;
  width: 50px;
  background-color: grey;
}

.right-wing{
  left:450px;
  border: 1px green solid;
  height: 250px;
  margin-top: 25px;
  margin-bottom: 25px;
  width: 50px;
  background-color: grey;
}

.right-wing:hover{
  width: 200px;
}

.left-wing:hover{
  width: 200px;
  /* margin-left: -200px; */
}


问:
How to save stripe webhook response on mysql
I am using flutter as a client-side and using the firebase extension to get the checkout URL for payment purposes.

This is working fine but I want to save the webhook response data on my MySQL db. The stripe webhook sends data on each event and I want to store each event response on my DB by which I will filter the data from there.

I am using node js as the backend but I don't have much knowledge of nodejs.
I followed the stripe nodejs documentation from which I am triggering the events
and this is the documentation code -

```<code>  // server.js
//
// Use this sample code to handle webhook events in your integration.
//
// 1) Paste this code into a new file (server.js)
//
// 2) Install dependencies
//   npm install stripe
//   npm install express
//
// 3) Run the server on http://localhost:4242
//   node server.js

const stripe = require('stripe');
const express = require('express');
const app = express();

// This is your Stripe CLI webhook secret for testing your endpoint locally.
const endpointSecret = "whsec_a86c898114804f99965ae4a14a7a93731a4c0bdffa506fa3d24d73ac89dd56f3";

app.post('/webhook', express.raw({type: 'application/json'}), (request, response) => {
  const sig = request.headers['stripe-signature'];

  let event;

  try {
    event = stripe.webhooks.constructEvent(request.body, sig, endpointSecret);
  } catch (err) {
    response.status(400).send(`Webhook Error: ${err.message}`);
    return;
  }

  // Handle the event
  switch (event.type) {
    case 'checkout.session.async_payment_failed':
      const session = event.data.object;
      // Then define and call a function to handle the event checkout.session.async_payment_failed
      break;
    case 'checkout.session.async_payment_succeeded':
      const session = event.data.object;
      // Then define and call a function to handle the event checkout.session.async_payment_succeeded
      break;
    case 'payment_intent.created':
      const paymentIntent = event.data.object;
      // Then define and call a function to handle the event payment_intent.created
      break;
    case 'payment_intent.processing':
      const paymentIntent = event.data.object;
      // Then define and call a function to handle the event payment_intent.processing
      break;
    // ... handle other event types
    default:
      console.log(`Unhandled event type ${event.type}`);
  }

  // Return a 200 response to acknowledge receipt of the event
  response.send();
});

app.listen(4242, () => console.log('Running on port 4242'));

</code>```

now, how can I connect MySQL on each switch case and save the data on my mysql db.

(note - I dont have pior knowledge of nodejs and mysql I have just read the documentation and following everything)

Body:
I am using flutter as a client-side and using the firebase extension to get the checkout URL for payment purposes.

This is working fine but I want to save the webhook response data on my MySQL db. The stripe webhook sends data on each event and I want to store each event response on my DB by which I will filter the data from there.

I am using node js as the backend but I don't have much knowledge of nodejs.
I followed the stripe nodejs documentation from which I am triggering the events
and this is the documentation code -

  // server.js
//
// Use this sample code to handle webhook events in your integration.
//
// 1) Paste this code into a new file (server.js)
//
// 2) Install dependencies
//   npm install stripe
//   npm install express
//
// 3) Run the server on http://localhost:4242
//   node server.js

const stripe = require('stripe');
const express = require('express');
const app = express();

// This is your Stripe CLI webhook secret for testing your endpoint locally.
const endpointSecret = "whsec_a86c898114804f99965ae4a14a7a93731a4c0bdffa506fa3d24d73ac89dd56f3";

app.post('/webhook', express.raw({type: 'application/json'}), (request, response) => {
  const sig = request.headers['stripe-signature'];

  let event;

  try {
    event = stripe.webhooks.constructEvent(request.body, sig, endpointSecret);
  } catch (err) {
    response.status(400).send(`Webhook Error: ${err.message}`);
    return;
  }

  // Handle the event
  switch (event.type) {
    case 'checkout.session.async_payment_failed':
      const session = event.data.object;
      // Then define and call a function to handle the event checkout.session.async_payment_failed
      break;
    case 'checkout.session.async_payment_succeeded':
      const session = event.data.object;
      // Then define and call a function to handle the event checkout.session.async_payment_succeeded
      break;
    case 'payment_intent.created':
      const paymentIntent = event.data.object;
      // Then define and call a function to handle the event payment_intent.created
      break;
    case 'payment_intent.processing':
      const paymentIntent = event.data.object;
      // Then define and call a function to handle the event payment_intent.processing
      break;
    // ... handle other event types
    default:
      console.log(`Unhandled event type ${event.type}`);
  }

  // Return a 200 response to acknowledge receipt of the event
  response.send();
});

app.listen(4242, () => console.log('Running on port 4242'));

now, how can I connect MySQL on each switch case and save the data on my mysql db.

(note - I dont have pior knowledge of nodejs and mysql I have just read the documentation and following everything)


问:
Clearing Elastic compilation cache
Is there a way to clear script compilation cache?

```<code>GET /_nodes/stats?metric=script&filter_path=nodes.*.script.*
</code>```

returns

```<code>{
  "nodes" : {
    "kFG" : {
      "script" : {
        "compilations" : 68,
        "cache_evictions" : 0,
        "compilation_limit_triggered" : 0
      }
    }
  }
}
</code>```

and I'm trying to figure out how I can clear those cached scripts?

Title: Clearing Elastic compilation cache

Body:
Is there a way to clear script compilation cache?

GET /_nodes/stats?metric=script&filter_path=nodes.*.script.*

returns

{
  "nodes" : {
    "kFG" : {
      "script" : {
        "compilations" : 68,
        "cache_evictions" : 0,
        "compilation_limit_triggered" : 0
      }
    }
  }
}

and I'm trying to figure out how I can clear those cached scripts?


问:
How to combine two matplotlib figures as subfigures without replotting them

What i want

I want to combine two matplotlib figures in one new subplot.
The two figures are returned from visualization functions of libraries i don't want to or can't change myself(rebuild from source etc.). Also it should be not a hack-around but rather be a nice generic matplotlib solution.

The pseudo code looks like the following.

Pseudo code

import matplotlib.pyplot as plt

from library1 import magic_visualization_1
from library2 import magic_visualization_2

# Data of type some_crazy_data_type_of_the_library e.g. no simple x,y coords
data = ...

fig1 = magic_visualization_1(data)    # type is: <class 'matplotlib.figure.Figure'>
fig2 = magic_visualization_2(data)    # type is: <class 'matplotlib.figure.Figure'>

fig, axs = plt.subplots(2, 1, figsize=(10, 5))
# Somehow add fig1
# Somehow add fig2
plt.show()

# or like

fig = plt.figure(figsize=(10, 5))
gridspec = fig.add_gridspec(2, 1, left=0.05, right=0.95, wspace=0.1, hspace=0.15)
# Somehow add fig1
# Somehow add fig2
plt.show()
```

Example images

The two example figures:
fig1,
fig2

Photoshoped result

I should look like this(i made this by hand with gimp/photoshop)
fig1 on top of fig2

What i tried

The best idea i found was deepcopying every figure into the new subfigures but that feels to much like a hack-around.

Also i tried this solution with copying the two figures content.

Result:
vertical concatenation of the two figures

Body:
What i want

I want to combine two matplotlib figures in one new subplot.
The two figures are returned from visualization functions of libraries i don't want to or can't change myself(rebuild from source etc.). Also it should be not a hack-around but rather be a nice generic matplotlib solution.

The pseudo code looks like the following.

Pseudo code

import matplotlib.pyplot as plt

from library1 import magic_visualization_1
from library2 import magic_visualization_2

# Data of type some_crazy_data_type_of_the_library e.g. no simple x,y coords
data = ...

fig1 = magic_visualization_1(data)    # type is: <class 'matplotlib.figure.Figure'>
fig2 = magic_visualization_2(data)    # type is: <class 'matplotlib.figure.Figure'>

fig, axs = plt.subplots(2, 1, figsize=(10, 5))
# Somehow add fig1
# Somehow add fig2
plt.show()

# or like

fig = plt.figure(figsize=(10, 5))
gridspec = fig.add_gridspec(2, 1, left=0.05, right=0.95, wspace=0.1, hspace=0.15)
# Somehow add fig1
# Somehow add fig2
plt.show()

Example images

The two example figures:
fig1,
fig2

Photoshoped result

I should look like this(i made this by hand with gimp/photoshop)
fig1 on top of fig2

What i tried

The best idea i found was deepcopying every figure into the new subfigures but that feels to much like a hack-around.

Also i tried this solution with copying the two figures content.

Result:
vertical concatenation of the two figures


问:
My Sign in button not working, and also I have few unused import statement but it is for firebase
```<code>package com.dataflair.fooddeliveryapp.Activities;

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

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.dataflair.fooddeliveryapp.MainActivity;
import com.dataflair.fooddeliveryapp.R;
import com.google.android.gms.auth.api.signin.GoogleSignIn;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInClient;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.common.SignInButton;
import com.google.android.gms.common.api.ApiException;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthCredential;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.auth.GoogleAuthProvider;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.google.firebase.database.annotations.NotNull;

import java.util.HashMap;

public class LoginActivity extends AppCompatActivity {

    GoogleSignInClient mSignInClient;
    FirebaseAuth firebaseAuth;
    ProgressDialog progressBar;
    Button signInButton;
    EditText phoneNumberEditTxt, addressEditTxt, cityNameEditTxt, pinCodeEdittxt;

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

        //Firebase Authentication
        firebaseAuth = FirebaseAuth.getInstance();

        //Progress bar
        progressBar = new ProgressDialog(this);
        progressBar.setTitle("Please Wait...");
        progressBar.setMessage("We are setting Everything for you...");
        progressBar.setProgressStyle(ProgressDialog.STYLE_SPINNER);

        //Assigning the address of the android materials
        cityNameEditTxt = (EditText) findViewById(R.id.CityEditText);
        phoneNumberEditTxt = (EditText) findViewById(R.id.PhoneNumberEditText);
        pinCodeEdittxt = (EditText) findViewById(R.id.PinCodeExitText);
        addressEditTxt = (EditText) findViewById(R.id.AddressEditText);
        signInButton = (Button) findViewById(R.id.GoogleSignInBtn);

        //Google Signin Options to get gmail and performed gmail login
        GoogleSignInOptions googleSignInOptions = new GoogleSignInOptions
                .Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                .requestIdToken("319466083877-4cdnl01r8q8p84nqgtcp42tv8cn0dq12.apps.googleusercontent.com")
                .requestEmail()
                .build();

        mSignInClient = GoogleSignIn.getClient(getApplicationContext(), googleSignInOptions);

        //Implementing OnClickListener to perform Login action
        signInButton.setOnClickListener(view -> {

            //Getting user details from the edit text
            String phoneNumber = phoneNumberEditTxt.getText().toString();
            String cityName = cityNameEditTxt.getText().toString();
            String pinCode = pinCodeEdittxt.getText().toString();
            String address = addressEditTxt.getText().toString();

            //Checking all the fields are filled or not
            if (phoneNumber.isEmpty() || cityName.isEmpty() || pinCode.isEmpty() || address.isEmpty()) {
                Toast.makeText(getApplicationContext(), "Please,Fill Details", Toast.LENGTH_SHORT).show();
            } else {
                //Showing all Gmails
                Intent intent = mSignInClient.getSignInIntent();
                startActivityForResult(intent, 100);
            }

        });

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == 100) {
            Task<GoogleSignInAccount> googleSignInAccountTask = GoogleSignIn
                    .getSignedInAccountFromIntent(data);

            if (googleSignInAccountTask.isSuccessful()) {
                progressBar.show();
                try {
                    GoogleSignInAccount googleSignInAccount = googleSignInAccountTask.getResult(ApiException.class);

                    if (googleSignInAccount != null) {
                        AuthCredential authCredential = GoogleAuthProvider
                                .getCredential(googleSignInAccount.getIdToken(), null);

                        firebaseAuth.signInWithCredential(authCredential).addOnCompleteListener(this, task -> {
                            if (task.isSuccessful()) {
                                FirebaseDatabase database = FirebaseDatabase.getInstance();
                                DatabaseReference myRef = database.getReference().child("users");

                                //Hashmap to store the userdetails and setting it to fireabse
                                HashMap<String, Object> user_details = new HashMap<>();

                                //Accessing the user details from gmail
                                String id = googleSignInAccount.getId().toString();
                                String name = googleSignInAccount.getDisplayName().toString();
                                String mail = googleSignInAccount.getEmail().toString();
                                String pic = googleSignInAccount.getPhotoUrl().toString();

                                String phoneNumber = phoneNumberEditTxt.getText().toString();
                                String cityName = cityNameEditTxt.getText().toString();
                                String pinCode = pinCodeEdittxt.getText().toString();
                                String address = addressEditTxt.getText().toString();

                                user_details.put("id", id);
                                user_details.put("name", name);
                                user_details.put("mail", mail);
                                user_details.put("profilepic", pic);
                                user_details.put("role", "empty");
                                user_details.put("phoneNumber", phoneNumber);
                                user_details.put("cityName", cityName);
                                user_details.put("pinCode", pinCode);
                                user_details.put("address", address);

                                //updating the user details in firebase
                                myRef.child(id).updateChildren(user_details).addOnCompleteListener(task1 -> {
                                    if (task1.isSuccessful()) {
                                        progressBar.cancel();

                                        //navigating to the main activity after user successfully registers
                                        Intent intent = new Intent(getApplicationContext(), UserRoleActivity.class);
                                        //Clears older activities and tasks
                                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                                        startActivity(intent);
                                    }
                                });

                            }
                        });
                    }

                } catch (ApiException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
</code>```

I am making a food delivery app where user need to login first which is not working. It is showing that few of the imports are unused. I am not sure of how to solve this problem, as My sign in button not working, the whole project is not working. MainActivity, SignInButton import is also gray.  I want to know how to solve this problem.

Body:
package com.dataflair.fooddeliveryapp.Activities;

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

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.dataflair.fooddeliveryapp.MainActivity;
import com.dataflair.fooddeliveryapp.R;
import com.google.android.gms.auth.api.signin.GoogleSignIn;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInClient;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.common.SignInButton;
import com.google.android.gms.common.api.ApiException;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthCredential;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.auth.GoogleAuthProvider;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.google.firebase.database.annotations.NotNull;

import java.util.HashMap;

public class LoginActivity extends AppCompatActivity {

    GoogleSignInClient mSignInClient;
    FirebaseAuth firebaseAuth;
    ProgressDialog progressBar;
    Button signInButton;
    EditText phoneNumberEditTxt, addressEditTxt, cityNameEditTxt, pinCodeEdittxt;

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

        //Firebase Authentication
        firebaseAuth = FirebaseAuth.getInstance();

        //Progress bar
        progressBar = new ProgressDialog(this);
        progressBar.setTitle("Please Wait...");
        progressBar.setMessage("We are setting Everything for you...");
        progressBar.setProgressStyle(ProgressDialog.STYLE_SPINNER);

        //Assigning the address of the android materials
        cityNameEditTxt = (EditText) findViewById(R.id.CityEditText);
        phoneNumberEditTxt = (EditText) findViewById(R.id.PhoneNumberEditText);
        pinCodeEdittxt = (EditText) findViewById(R.id.PinCodeExitText);
        addressEditTxt = (EditText) findViewById(R.id.AddressEditText);
        signInButton = (Button) findViewById(R.id.GoogleSignInBtn);

        //Google Signin Options to get gmail and performed gmail login
        GoogleSignInOptions googleSignInOptions = new GoogleSignInOptions
                .Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                .requestIdToken("319466083877-4cdnl01r8q8p84nqgtcp42tv8cn0dq12.apps.googleusercontent.com")
                .requestEmail()
                .build();

        mSignInClient = GoogleSignIn.getClient(getApplicationContext(), googleSignInOptions);

        //Implementing OnClickListener to perform Login action
        signInButton.setOnClickListener(view -> {

            //Getting user details from the edit text
            String phoneNumber = phoneNumberEditTxt.getText().toString();
            String cityName = cityNameEditTxt.getText().toString();
            String pinCode = pinCodeEdittxt.getText().toString();
            String address = addressEditTxt.getText().toString();

            //Checking all the fields are filled or not
            if (phoneNumber.isEmpty() || cityName.isEmpty() || pinCode.isEmpty() || address.isEmpty()) {
                Toast.makeText(getApplicationContext(), "Please,Fill Details", Toast.LENGTH_SHORT).show();
            } else {
                //Showing all Gmails
                Intent intent = mSignInClient.getSignInIntent();
                startActivityForResult(intent, 100);
            }

        });

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == 100) {
            Task<GoogleSignInAccount> googleSignInAccountTask = GoogleSignIn
                    .getSignedInAccountFromIntent(data);

            if (googleSignInAccountTask.isSuccessful()) {
                progressBar.show();
                try {
                    GoogleSignInAccount googleSignInAccount = googleSignInAccountTask.getResult(ApiException.class);

                    if (googleSignInAccount != null) {
                        AuthCredential authCredential = GoogleAuthProvider
                                .getCredential(googleSignInAccount.getIdToken(), null);

                        firebaseAuth.signInWithCredential(authCredential).addOnCompleteListener(this, task -> {
                            if (task.isSuccessful()) {
                                FirebaseDatabase database = FirebaseDatabase.getInstance();
                                DatabaseReference myRef = database.getReference().child("users");

                                //Hashmap to store the userdetails and setting it to fireabse
                                HashMap<String, Object> user_details = new HashMap<>();

                                //Accessing the user details from gmail
                                String id = googleSignInAccount.getId().toString();
                                String name = googleSignInAccount.getDisplayName().toString();
                                String mail = googleSignInAccount.getEmail().toString();
                                String pic = googleSignInAccount.getPhotoUrl().toString();

                                String phoneNumber = phoneNumberEditTxt.getText().toString();
                                String cityName = cityNameEditTxt.getText().toString();
                                String pinCode = pinCodeEdittxt.getText().toString();
                                String address = addressEditTxt.getText().toString();

                                user_details.put("id", id);
                                user_details.put("name", name);
                                user_details.put("mail", mail);
                                user_details.put("profilepic", pic);
                                user_details.put("role", "empty");
                                user_details.put("phoneNumber", phoneNumber);
                                user_details.put("cityName", cityName);
                                user_details.put("pinCode", pinCode);
                                user_details.put("address", address);

                                //updating the user details in firebase
                                myRef.child(id).updateChildren(user_details).addOnCompleteListener(task1 -> {
                                    if (task1.isSuccessful()) {
                                        progressBar.cancel();

                                        //navigating to the main activity after user successfully registers
                                        Intent intent = new Intent(getApplicationContext(), UserRoleActivity.class);
                                        //Clears older activities and tasks
                                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                                        startActivity(intent);
                                    }
                                });

                            }
                        });
                    }

                } catch (ApiException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

I am making a food delivery app where user need to login first which is not working. It is showing that few of the imports are unused. I am not sure of how to solve this problem, as My sign in button not working, the whole project is not working. MainActivity, SignInButton import is also gray.  I want to know how to solve this problem.


问:
BluetoothDevice Object can not be parsed to Json in Android
I tried to store a BluetoothDevice object in a sharedPreference object, I used a Gson to parse it into JSON first as sharedPreference could not store BluetoothDevice object directly. Still, after I parsed, I got an empty string. After that, I tried to store the BluetoothDevice in a Javabean class that extents serializable, but I still got an empty string after I parsed it. What should I do to store it?

Here is the JavaBean class I used to carry BluetoothDevice; it works well when I use it to store BluetoothDevice in intent extra.

```<code>public class JavaBeanDevice implements Serializable {
    BleDevice bleDevice;
}
</code>```

The BleDevice is a class that stores a BluetoothDevice and other data like int and string, the other data inside could be parsed correctly except the BluetoothDevice, I did try to store the BluetoothDevice in the JavaBean independently as my question described, but the Gson only returns me a empty string

Body:
I tried to store a BluetoothDevice object in a sharedPreference object, I used a Gson to parse it into JSON first as sharedPreference could not store BluetoothDevice object directly. Still, after I parsed, I got an empty string. After that, I tried to store the BluetoothDevice in a Javabean class that extents serializable, but I still got an empty string after I parsed it. What should I do to store it?

Here is the JavaBean class I used to carry BluetoothDevice; it works well when I use it to store BluetoothDevice in intent extra.

public class JavaBeanDevice implements Serializable {
    BleDevice bleDevice;
}

The BleDevice is a class that stores a BluetoothDevice and other data like int and string, the other data inside could be parsed correctly except the BluetoothDevice, I did try to store the BluetoothDevice in the JavaBean independently as my question described, but the Gson only returns me a empty string


问:
Call to undefined function mb_detect_encoding on Ubuntu
Is there anybody who can give me a clue?

I'm using php on ubuntu. What bothers me is the error Call to undefined function mb_detect_encoding() although I've installed mbstring and gd packages and enabled them too. I've also restarted apache2 many times.

```<code>[Tue Jan 03 14:33:29.036891 2023] [php:error] [pid 2005821] [client 192.168.11.12:34446] PHP Fatal error: Uncaught Error: Call to undefined function mb_detect_encoding() in /var/www/html/...
</code>```

Below is the info

```<code>$ cat /etc/issue Ubuntu 22.04.1 LTS \n \l
root@***:/usr/lib/php# find . | grep mbstring
./20220829/mbstring.so
root@***:/usr/lib/php# php -m | grep mbstring
mbstring
root@***:/usr/lib/php# php -m | grep gd
gd
root@***:/usr/lib/php# php -v
PHP 8.2.0 (cli) (built: Dec 10 2022 10:53:01) (NTS) Copyright (c) The PHP Group Zend Engine v4.2.0, Copyright (c) Zend Technologies with Zend OPcache v8.2.0, Copyright (c), by Zend Technologies
</code>```

I've also restarted apache2 many times.

Body:
Is there anybody who can give me a clue?

I'm using php on ubuntu. What bothers me is the error Call to undefined function mb_detect_encoding() although I've installed mbstring and gd packages and enabled them too. I've also restarted apache2 many times.

[Tue Jan 03 14:33:29.036891 2023] [php:error] [pid 2005821] [client 192.168.11.12:34446] PHP Fatal error: Uncaught Error: Call to undefined function mb_detect_encoding() in /var/www/html/...

Below is the info

$ cat /etc/issue Ubuntu 22.04.1 LTS \n \l
root@***:/usr/lib/php# find . | grep mbstring
./20220829/mbstring.so
root@***:/usr/lib/php# php -m | grep mbstring
mbstring
root@***:/usr/lib/php# php -m | grep gd
gd
root@***:/usr/lib/php# php -v
PHP 8.2.0 (cli) (built: Dec 10 2022 10:53:01) (NTS) Copyright (c) The PHP Group Zend Engine v4.2.0, Copyright (c) Zend Technologies with Zend OPcache v8.2.0, Copyright (c), by Zend Technologies

I've also restarted apache2 many times.


问:
After building an App(Android) using Kivy, Reading and writing text file(authorization completed)
```<code></code>```

I am using Filechooser, and checked whether the correct file is loaded using the print function until the data path.

text file name: A.txt

```<code>  self.data_name = str(self.list_data_load.selection[0])
  self.fdata=self.data_name
  check_error= 'Path' + self.fdata
  f=open(self.fdata,"r")
</code>```

/emulated/0/data/A.txt

#F=f.readline()

but, when I try to use readlines, the app crashes and shuts down in Andorid.
I'm not sure if I need to grant additional permissions to read text files in external storage.

I need some help please.

```<code>
</code>```

Body:
I am using Filechooser, and checked whether the correct file is loaded using the print function until the data path.

text file name: A.txt

  self.data_name = str(self.list_data_load.selection[0])
  self.fdata=self.data_name
  check_error= 'Path' + self.fdata
  f=open(self.fdata,"r")

/emulated/0/data/A.txt

#F=f.readline()

but, when I try to use readlines, the app crashes and shuts down in Andorid.
I'm not sure if I need to grant additional permissions to read text files in external storage.

I need some help please.


问:
Run program in cmd mode after building from Sublime Text 4
I'm using Sublime Text 4 with Python as a build system to compile my py programs.
I want to run the program that I've just compiled in a cmd window (not in the Sublime console) What can I do for that? Thank you.</p>


问:
Cypress automation : Session not getting cleared
Once I enter user Name and click on login, it should ask for password but it is directly login into application. If I try manually it is working fine but through automation it is directly login in  and failing as password field is not found. Below is the code for login

```<code>cy.visit("URL");
Cypress.session.clearAllSavedSessions();
cy.clearLocalStorage();
login(username,password).
</code>```

Expected : Each time I launch browser and application, it should ask me password.

Body:
Once I enter user Name and click on login, it should ask for password but it is directly login into application. If I try manually it is working fine but through automation it is directly login in  and failing as password field is not found. Below is the code for login

cy.visit("URL");
Cypress.session.clearAllSavedSessions();
cy.clearLocalStorage();
login(username,password).

Expected : Each time I launch browser and application, it should ask me password.


问:
ipython magic command for global significant figures precision
IPython's %precision magic is quite useful (doc). It automatically rounds every numerical output on your jupyter notebook.

But absolute round is not enough sometimes. I work with values at different scales, so %precision 3 will output some values as 0.234 (good), but some other values as 6501.766 (bad).

Is there an analogous magic for significant figures? I think there is not. If that is the case, how can I implement a magic command and use it? A python function implementing this logic is for example:

def round_sig(x, sig=3):
    # round to sig significant figures
    if x == 0:
        return 0

    return round(x, sig - int(math.floor(math.log10(abs(x)))) - 1)
```

And a second question. How can this formatting spread to pandas.DataFrames and pandas.Series? This is, output dataframes to have this formatting too?

Body:
IPython's %precision magic is quite useful (doc). It automatically rounds every numerical output on your jupyter notebook.

But absolute round is not enough sometimes. I work with values at different scales, so %precision 3 will output some values as 0.234 (good), but some other values as 6501.766 (bad).

Is there an analogous magic for significant figures? I think there is not. If that is the case, how can I implement a magic command and use it? A python function implementing this logic is for example:

def round_sig(x, sig=3):
    # round to sig significant figures
    if x == 0:
        return 0

    return round(x, sig - int(math.floor(math.log10(abs(x)))) - 1)

And a second question. How can this formatting spread to pandas.DataFrames and pandas.Series? This is, output dataframes to have this formatting too?


问:
Handle Firebase client-side token and access to protected pages
I'm using Firebase auth to login with Facebook, Google and email/pass.  Basically, everything runs client-side, I make a call to Firebase and I receive an object containing an access token (that is a JWT ID Token), a customer id and its email. When I get this object, I put it into a persistent store (local storage, I know it's bad) and I perform an API call to one of my sveltekit endpoint that will in turn make another API call to a backend API (written in Go) to get all the user informations: firstname, lastname, phone, address, stats etc. To give a little bit of context, below is a diagram to illustrate what's happening when a user sign-in using Facebook.

Up to now, I just put the Firebase object into a store and just check if the information are there to allow access to a particular page. This check is done in the +layout.svelte page of the directory containing the page to be protected. It looks like something like this:

  onMount(() => {
    // redirect if not authenticated
    if (browser && !$authStore?.uid) goto(`/auth/sign-in`);
  });
```
<p>It's probably not a good thing especially since my store persists in the <code>local storage</code> and therefore is prone to some javascript manipulation.</p>
<p>From my understanding, there's at least 2 things that could be better implemented but I may be wrong:</p>
<ol>
<li>Set the <code>access token</code> in an <code>httponly cookie</code> straight after receiving it from <code>Firebase</code>. This would avoid storing the access token (that is a JWT) in the <code>local storage</code> and It could be used to authorize access or not to some protected pages...</li>
</ol>
<p>I receive the <code>Firebase</code> authentication object on client-side but<code>http only cookie</code> can only be created from server side. I thought about sending the object as a payload to a POST sveltekit endpoint (like <code>/routes/api/auth/token/+server.js</code>) and set the cookie from here but apparently <code>cookies</code> is not available in a sveltekit endpoint.</p>
<p>So, how and where should I set this cookie ? I see that <code>cookies</code> is available in the load function  of a <code>+layout.server.js</code> file, as well as in the <code>handle</code> function of a <code>hooks.server.js</code> file, but I don't see the logic here.</p>
<ol start="2">
<li>Populate <code>locals.user</code>with the authenticated <code>user</code> once I've performed a call to my backend. Well, here, it's not obvious to me because I think point 1) would be enough to manage access to protected pages, but I see that a check of <code>locals.user</code> is something I've seen elsewhere.</li>
</ol>
<p>I tried to set <code>locals.user</code> in the sveltekit endpoint that is making the API call to the backend API:</p>
<pre class="lang-js prettyprint-override"><code>// /routes/api/users/[uid]/+server.js
import { json } from "@sveltejs/kit";
import axios from "axios";
import { GO_API_GATEWAY_BASE_URL } from "$env/static/private";

export async function GET({ request, locals, params }) {
try {
    const config = {
      method: "get",
      baseURL: GO_API_GATEWAY_BASE_URL,
      url: `/users/${params.uid}`,
      headers: {
        Authorization: `Bearer ${uidToken}`, // <-- the Firebase ID Token
      },
      withCredentials: true,
    };
    const res = await axios(config);
    // set locals
    locals.user = json(res.data); // <--- DOESN'T SEEM TO WORK

    return json(res.data);
  } catch (error) {...}
}
</code>```

...but in the +layout.server.js page that I've created I see nothing:

// routes/app/protected_pages/+layout.server.js
import { redirect } from "@sveltejs/kit";

export function load({ locals }) {
  console.log(locals); // <----- contains an empty object: {}
  if (!locals.user) throw redirect(302, "/auth/sign-in");
}
```

Thank you so much for your help

Body:
I'm using Firebase auth to login with Facebook, Google and email/pass.  Basically, everything runs client-side, I make a call to Firebase and I receive an object containing an access token (that is a JWT ID Token), a customer id and its email. When I get this object, I put it into a persistent store (local storage, I know it's bad) and I perform an API call to one of my sveltekit endpoint that will in turn make another API call to a backend API (written in Go) to get all the user informations: firstname, lastname, phone, address, stats etc. To give a little bit of context, below is a diagram to illustrate what's happening when a user sign-in using Facebook.

Up to now, I just put the Firebase object into a store and just check if the information are there to allow access to a particular page. This check is done in the +layout.svelte page of the directory containing the page to be protected. It looks like something like this:

  onMount(() => {
    // redirect if not authenticated
    if (browser && !$authStore?.uid) goto(`/auth/sign-in`);
  });

It's probably not a good thing especially since my store persists in the local storage and therefore is prone to some javascript manipulation.

From my understanding, there's at least 2 things that could be better implemented but I may be wrong:

Set the access token in an httponly cookie straight after receiving it from Firebase. This would avoid storing the access token (that is a JWT) in the local storage and It could be used to authorize access or not to some protected pages...

I receive the Firebase authentication object on client-side buthttp only cookie can only be created from server side. I thought about sending the object as a payload to a POST sveltekit endpoint (like /routes/api/auth/token/+server.js) and set the cookie from here but apparently cookies is not available in a sveltekit endpoint.

So, how and where should I set this cookie ? I see that cookies is available in the load function  of a +layout.server.js file, as well as in the handle function of a hooks.server.js file, but I don't see the logic here.

Populate locals.userwith the authenticated user once I've performed a call to my backend. Well, here, it's not obvious to me because I think point 1) would be enough to manage access to protected pages, but I see that a check of locals.user is something I've seen elsewhere.

I tried to set locals.user in the sveltekit endpoint that is making the API call to the backend API:

// /routes/api/users/[uid]/+server.js
import { json } from "@sveltejs/kit";
import axios from "axios";
import { GO_API_GATEWAY_BASE_URL } from "$env/static/private";

export async function GET({ request, locals, params }) {
try {
    const config = {
      method: "get",
      baseURL: GO_API_GATEWAY_BASE_URL,
      url: `/users/${params.uid}`,
      headers: {
        Authorization: `Bearer ${uidToken}`, // <-- the Firebase ID Token
      },
      withCredentials: true,
    };
    const res = await axios(config);
    // set locals
    locals.user = json(res.data); // <--- DOESN'T SEEM TO WORK

    return json(res.data);
  } catch (error) {...}
}

...but in the +layout.server.js page that I've created I see nothing:

// routes/app/protected_pages/+layout.server.js
import { redirect } from "@sveltejs/kit";

export function load({ locals }) {
  console.log(locals); // <----- contains an empty object: {}
  if (!locals.user) throw redirect(302, "/auth/sign-in");
}

Thank you so much for your help


问:
How to get the value of the dropdown which dropdown options come from the database?
I have two dropdowns in my project. all the options in these two dropdowns come from the database. I want to select them. after I select them I want to bring a data from another table in my database.

In the normal situation the javascript could take the value of these dropdowns and with php code It can go to the database. But here because these dropdowns option come from database I don't have value so I can not take the selected items! I don't know how to do it. My question here is that How can I get the value of these dropdowns??

```<code>    <div class="one">

    <fieldset>
        <legend>Commodity Balance:</legend>
        <?php
        $servername = "localhost";
        $username = "root";
        $password = "";
        $dbname = "dbtest";
        $usertable_commodity = "t_commodity";
        $columnname_commodity = "commodity";
        $usertable_country = "t_country";
        $columnname_country = "country";
        $usertable_mood = "t_mood";
        $columnname_mood = "commodity";

        $mysqli = new mysqli("$servername", "$username", "$password", "$dbname");

        if ($mysqli->connect_errno) {
            echo "Failed to connect to MySQL: " . $mysqli->connect_error;
            exit();
        }

        $sql_commodity = "select * from $usertable_commodity";
        $result_commodity = $mysqli->query($sql_commodity);
        $sql_country = "select * from $usertable_country";
        $result_country = $mysqli->query($sql_country);

        ?>
        <!-- -------------------------------------------------------------------------------- -->
        <label for="Commoditylb">Commodity/Country:</label>
        <select style="border: 2px solid black;border-radius: 2px 2px 2px 2px;" onchange="function1($stname_commodity)">
            <option></option>
            <?php
            if ($result_commodity) {
                while ($row = mysqli_fetch_array($result_commodity)) {
                    $stname_commodity = $row["$columnname_commodity"];
                    echo "<option>$stname_commodity<br></option>";
                }
            }

            ?>
        </select>
        <!-- -------------------------------------------------------------------------------- -->
        <select style="border: 2px solid black;border-radius: 2px 2px 2px 2px;">
            <option></option>
            <?php
            if ($result_country) {
                while ($row = mysqli_fetch_array($result_country)) {
                    $stname_country = $row["$columnname_country"];
                    echo "<option>$stname_country<br></option>";
                }
            }
            ?>
        </select>
        <!-- -------------------------------------------------------------------------------- -->
        <?php
        if (isset($_POST['button1'])) {

            $sql_mood = "select * from $usertable_mood where (country='Malaysia');";
            $result_mood = $mysqli->query($sql_mood);
            if ($result_mood) {
                while ($row = mysqli_fetch_array($result_mood)) {
                    $stname_mood = $row["$columnname_mood"];
                    echo "$stname_mood";
                }
            }
        ?>
            <!-- -------------------------------------------------------------------------------- -->

        <?php
        }
        ?>
        <form method="post">
            <input type="submit" name="button1" value="button1" />
    </fieldset>
    </form>
</div>
</code>```

Body:
I have two dropdowns in my project. all the options in these two dropdowns come from the database. I want to select them. after I select them I want to bring a data from another table in my database.

In the normal situation the javascript could take the value of these dropdowns and with php code It can go to the database. But here because these dropdowns option come from database I don't have value so I can not take the selected items! I don't know how to do it. My question here is that How can I get the value of these dropdowns??

    <fieldset>
        <legend>Commodity Balance:</legend>
        <?php
        $servername = "localhost";
        $username = "root";
        $password = "";
        $dbname = "dbtest";
        $usertable_commodity = "t_commodity";
        $columnname_commodity = "commodity";
        $usertable_country = "t_country";
        $columnname_country = "country";
        $usertable_mood = "t_mood";
        $columnname_mood = "commodity";

        $mysqli = new mysqli("$servername", "$username", "$password", "$dbname");

        if ($mysqli->connect_errno) {
            echo "Failed to connect to MySQL: " . $mysqli->connect_error;
            exit();
        }

        $sql_commodity = "select * from $usertable_commodity";
        $result_commodity = $mysqli->query($sql_commodity);
        $sql_country = "select * from $usertable_country";
        $result_country = $mysqli->query($sql_country);

        ?>

        Commodity/Country:
        <select style="border: 2px solid black;border-radius: 2px 2px 2px 2px;" onchange="function1($stname_commodity)">
            <option></option>
            <?php
            if ($result_commodity) {
                while ($row = mysqli_fetch_array($result_commodity)) {
                    $stname_commodity = $row["$columnname_commodity"];
                    echo "<option>$stname_commodity
</option>";
                }
            }

            ?>
        </select>

        <select style="border: 2px solid black;border-radius: 2px 2px 2px 2px;">
            <option></option>
            <?php
            if ($result_country) {
                while ($row = mysqli_fetch_array($result_country)) {
                    $stname_country = $row["$columnname_country"];
                    echo "<option>$stname_country
</option>";
                }
            }
            ?>
        </select>

        <?php
        if (isset($_POST['button1'])) {

            $sql_mood = "select * from $usertable_mood where (country='Malaysia');";
            $result_mood = $mysqli->query($sql_mood);
            if ($result_mood) {
                while ($row = mysqli_fetch_array($result_mood)) {
                    $stname_mood = $row["$columnname_mood"];
                    echo "$stname_mood";
                }
            }
        ?>

        <?php
        }
        ?>
        <form method="post">
            <input type="submit" name="button1" value="button1" />
    </fieldset>
    </form>


问:
Error when creating beans after obfucation with proguard
```<code>   <jaxrs:server id="adtsResource" address="/rs">
        <jaxrs:serviceBeans>
            <ref bean="authenticationResource"/>
            <ref bean="apiKeyResource"/>
            <ref bean="authorityResource"/>
            <ref bean="userResource"/>
            <ref bean="ruleEditorResource"/>
            <ref bean="beResource"/>
            <ref bean="beConfigResource"/>
            <ref bean="eventStreamResource"/>
            <ref bean="ruleBookResource"/>
            <ref bean="ruleResource"/>
            <ref bean="txnDataResource"/>
            <ref bean="generalDataResource"/>
            <ref bean="strListResource"/>
            <ref bean="converterResource"/>
            <ref bean="customActionResource"/>
            <ref bean="taskResource"/>
            <ref bean="activeDirectoryResource"/>
            <ref bean="appFraudResource"/>
            <ref bean="airSystemResource"/>
            <ref bean="auditLogResource"/>
            <ref bean="checkerSettingsResource"/>
            <ref bean="ruleBookWorkspaceResource"/>
        </jaxrs:serviceBeans>
</code>```

I’m using jaxrs:serviceBeans for my resource classes when i try to deploy project after obfucation i got errors like second screenshot.I think this error about class names but i don’t know hot to fix this problem.

Body:
   <jaxrs:server id="adtsResource" address="/rs">
        <jaxrs:serviceBeans>
            <ref bean="authenticationResource"/>
            <ref bean="apiKeyResource"/>
            <ref bean="authorityResource"/>
            <ref bean="userResource"/>
            <ref bean="ruleEditorResource"/>
            <ref bean="beResource"/>
            <ref bean="beConfigResource"/>
            <ref bean="eventStreamResource"/>
            <ref bean="ruleBookResource"/>
            <ref bean="ruleResource"/>
            <ref bean="txnDataResource"/>
            <ref bean="generalDataResource"/>
            <ref bean="strListResource"/>
            <ref bean="converterResource"/>
            <ref bean="customActionResource"/>
            <ref bean="taskResource"/>
            <ref bean="activeDirectoryResource"/>
            <ref bean="appFraudResource"/>
            <ref bean="airSystemResource"/>
            <ref bean="auditLogResource"/>
            <ref bean="checkerSettingsResource"/>
            <ref bean="ruleBookWorkspaceResource"/>
        </jaxrs:serviceBeans>

I’m using jaxrs:serviceBeans for my resource classes when i try to deploy project after obfucation i got errors like second screenshot.I think this error about class names but i don’t know hot to fix this problem.


问:
How to configure report user credential to pass-through to SQL data source?
I am using direct query based Power BI report. The model fetches data from a SQL server database.

How to configure report user credential to pass-through to SQL data source? Does this require any special setup like kerberos?


问:
Code Splitting causes chunks to not reload
I have a core component used in various parts of our project. The component is exported as default based on a condition.

```<code>export default isLightWeightPdfGlobal || isSchedulingDisabled() ? CSSModules(GraphTableModule, Styles, { allowMultiple: true }) : connect(mapStateToProps)(CSSModules(GraphTableModule, Styles, { allowMultiple: true }));
</code>```

This module is being used on the homepage; once it gets loaded, it doesn't reload when I go to other modules.
I want the else part of the export to be executed.

webpack split chunk config:

```<code>optimization: {
        splitChunks: {
            chunks: "all",
            maxInitialRequests: Infinity,
            minSize: 0,
            cacheGroups: {
                commons: {
                    chunks: "all",
                    minChunks: 2,
                    maxInitialRequests: 5,
                    minSize: 0
                },
                vendor: {
                    test: /node_modules/,
                    chunks: "initial",
                    priority: 10,
                    enforce: true
                }
            }
        }
    }
</code>```

Body:
I have a core component used in various parts of our project. The component is exported as default based on a condition.

export default isLightWeightPdfGlobal || isSchedulingDisabled() ? CSSModules(GraphTableModule, Styles, { allowMultiple: true }) : connect(mapStateToProps)(CSSModules(GraphTableModule, Styles, { allowMultiple: true }));

This module is being used on the homepage; once it gets loaded, it doesn't reload when I go to other modules.
I want the else part of the export to be executed.

webpack split chunk config:

optimization: {
        splitChunks: {
            chunks: "all",
            maxInitialRequests: Infinity,
            minSize: 0,
            cacheGroups: {
                commons: {
                    chunks: "all",
                    minChunks: 2,
                    maxInitialRequests: 5,
                    minSize: 0
                },
                vendor: {
                    test: /node_modules/,
                    chunks: "initial",
                    priority: 10,
                    enforce: true
                }
            }
        }
    }


问:
ALAssetPropertyLocation always invalid
I am trying to get location information from photos and videos that an user selects from iPhone's library. I am using a custom image picker that uses ALAssetsLibrary to read the photos and videos.

I am trying to get the location information using ALAssetPropertyLocation like this:

```<code>CLLocation *location = [myAsset valueForProperty:ALAssetPropertyLocation];
</code>```

but location always comes up in the logs as

```<code><nan, nan> +/- 0.00m (speed -1.00 mps / course -1.00) @ 9/21/11 1:37:56 PM Central European Summer Time
</code>```

I've tried looking at myAsset.defaultRepresentation.metadata property and GPS location IS there but only for photos. For videos myAsset.defaultRepresentation.metadata is nil.

Any help would be great appreciated!

UPDATE

It looks like this guy here had a similar problem. But it only happened for him on a 3GS while having no problems on the iPhone 4. I am currently testing on an iPhone 4 and still getting the invalid location information.

ContentLicense: CC BY-SA 3.0

Title: ALAssetPropertyLocation always invalid

Body:
I am trying to get location information from photos and videos that an user selects from iPhone's library. I am using a custom image picker that uses ALAssetsLibrary to read the photos and videos.

I am trying to get the location information using ALAssetPropertyLocation like this:

CLLocation *location = [myAsset valueForProperty:ALAssetPropertyLocation];

but location always comes up in the logs as

<nan, nan> +/- 0.00m (speed -1.00 mps / course -1.00) @ 9/21/11 1:37:56 PM Central European Summer Time

I've tried looking at myAsset.defaultRepresentation.metadata property and GPS location IS there but only for photos. For videos myAsset.defaultRepresentation.metadata is nil.

Any help would be great appreciated!

UPDATE

It looks like this guy here had a similar problem. But it only happened for him on a 3GS while having no problems on the iPhone 4. I am currently testing on an iPhone 4 and still getting the invalid location information.


问:
Can we use my own crate repository url in Cargo.toml to download the dependencies
I have my own repository, where I have list of rust crates. When I run the command "cargo run", i want cargo to download all the dependencies from my crate repository url instead of crates.io. To achieve this what configuration need to be done

Looking for some suggestion or code snippet for the same


问:
Is it possible to send ziped serialized (xml) files to the S3 bucket using stream (UploadAsync)
```<code> public void UploadXml(params objects[] objects)
    {
        foreach (var object in objects)
        {
            var fileName = $"{someFileName}.xml";

            var xmlSerializer = new XmlSerializer();
            var textView = xmlSerializer.Serialize(pnrObject);

            var stream = new MemoryStream(Encoding.UTF8.GetBytes(textView));
            _awsS3Helper.UploadStreamAsync(stream, fileName);
        }
    }

private async Task UploadStreamAsync(Stream streamFile, string key)
    {
        try
        {
            var fileTransferUtility = new TransferUtility(Client);
            await fileTransferUtility.UploadAsync(streamFile, $"{_bucket}/{_folder}", key);

        }
    }
</code>```

To send a serialized stream of a xml file, I used this example. This works great. The current task is that I need to archive the objects (zip, without saving the archive locally) and send them by stream to S3 bucket. How this can be implemented?

I heard that you can use "GZipStream" to archive an object. But what to use in my case, I have not found a solution yet

Body:
 public void UploadXml(params objects[] objects)
    {
        foreach (var object in objects)
        {
            var fileName = $"{someFileName}.xml";

            var xmlSerializer = new XmlSerializer();
            var textView = xmlSerializer.Serialize(pnrObject);

            var stream = new MemoryStream(Encoding.UTF8.GetBytes(textView));
            _awsS3Helper.UploadStreamAsync(stream, fileName);
        }
    }

private async Task UploadStreamAsync(Stream streamFile, string key)
    {
        try
        {
            var fileTransferUtility = new TransferUtility(Client);
            await fileTransferUtility.UploadAsync(streamFile, $"{_bucket}/{_folder}", key);

        }
    }

To send a serialized stream of a xml file, I used this example. This works great. The current task is that I need to archive the objects (zip, without saving the archive locally) and send them by stream to S3 bucket. How this can be implemented?

I heard that you can use "GZipStream" to archive an object. But what to use in my case, I have not found a solution yet


问:
How to create multi select CheckboxListTile perfectly in flutter?
I have a Bottom sheet which shows the list of Cities from which I have to select multiple Cities and if I open the bottomSheet second time previous selected cities should be pre selected but only if user press the save button after selecting Cities and if bottomSheet is dismissed then dont include the new selected cities. I am able to select the multiple cities and show previous selected cities in second time. also I am getting null as returned value if bottomSheet is dismissed. but also I am getting upated data in case of dismiss I dont know how it is gettting initialized with new selected values.

below is my code.

This is my bottom sheet.

```<code>import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

import '../../../../business_logic/app/app_event_and_state.dart';
import '../bloc/city_bloc.dart';
import '../bloc/city_event.dart';
import '../bloc/city_state.dart';
import '../model/city_model.dart';

class MultiSelectCity extends StatefulWidget {
  const MultiSelectCity({Key? key, this.selectedCitiesList}) : super(key: key);
  final List<City>? selectedCitiesList;
  @override
  State<MultiSelectCity> createState() => _MultiSelectCityState();
}

class _MultiSelectCityState extends State<MultiSelectCity> {
  bool _isInit = true;
  List<City>? selectedCities = [];
  List<City> filteredCities = [];
  @override
  void didChangeDependencies() {
    print('didChangeDependencies');
    if (_isInit) {
      BlocProvider.of<CityBloc>(context)
          .add(const AppEventLoadCitiesWithFilter(isActive: true));
    }
    _isInit = false;
    selectedCities = widget.selectedCitiesList;
    super.didChangeDependencies();
  }

  @override
  Widget build(BuildContext context) {
    return BlocConsumer<CityBloc, AppState>(
      builder: (context, state) {
        return DraggableScrollableSheet(
          initialChildSize: 0.6,
          minChildSize: 0.4,
          maxChildSize: 0.75,
          expand: false,
          builder: (context, scrollController) => Container(
            color: Colors.white,
            child: Column(children: [
              Container(
                color: Theme.of(context).colorScheme.background,
                padding: EdgeInsets.symmetric(vertical: 25.h, horizontal: 45.w),
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Container(
                      height: 15.h,
                      width: 140.w,
                      decoration: BoxDecoration(
                        shape: BoxShape.rectangle,
                        borderRadius: BorderRadius.circular(25.r),
                        color: Colors.grey.shade400,
                      ),
                    ),
                    Padding(
                      padding:
                      EdgeInsets.only(top: 20.h, left: 10.w, bottom: 2.h),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          SizedBox(height: 25.h),
                          Text('Select City',
                              style: TextStyle(
                                  fontWeight: FontWeight.w900,
                                  fontSize: 65.sp)),
                        ],
                      ),
                    ),
                  ],
                ),
              ),
              Expanded(
                child: state.isLoading
                    ? const Center(
                  child: CircularProgressIndicator(),
                )
                    : filteredCities.isNotEmpty
                    ? ListView.builder(
                  controller: scrollController,
                  itemBuilder: (context, index) {
                    return CheckboxListTile(
                      title: Text(
                        '${filteredCities[index].cityName},'
                            ' ${filteredCities[index].stateCode}, '
                            '${filteredCities[index].countryName}',
                        style:
                        Theme.of(context).textTheme.bodyLarge,
                      ),
                      value: selectedCities?.contains(
                          filteredCities[index]) ,
                      onChanged: (bool? value) {
                        setState(() {
                          if (selectedCities?.contains(
                              filteredCities[index]) ==
                              true) {
                            selectedCities?.removeWhere((element) =>
                            element ==
                                filteredCities[index]);
                          } else {
                            selectedCities
                                ?.add(filteredCities[index]);
                          }
                          print(value);
                        });
                      },
                    );
                  },
                  itemCount: filteredCities.length,
                )
                    : const Center(
                  child: Text("No cities found"),
                ),),
              Container(
                width: double.infinity,
                height: 50,
                margin: EdgeInsets.all(20),
                child: ElevatedButton(
                    onPressed: () {
                      return Navigator.of(context).pop(selectedCities); // if save pressed then pass selected cities else if bottomsheet is dismissed it returns null.
                    },

                    child: Text(
                      'Save',
                      style: TextStyle(
                          fontWeight: FontWeight.w700, fontSize: 45.sp),
                    )),
              )
            ]),
          ),
        );
      },
      listener: (context, state) {
        if (state is AppStateActiveCities) {
          print(state.activeCities.length.toString());
          filteredCities = state.activeCities;
        }
      },
    );
  }
}

</code>```

This is how I am calling it.

```<code>Future<void> _showMultiSelectCityOptions() async {
  returnedSelectedCities = await showModalBottomSheet<List<City>>(
    isScrollControlled: true,
    isDismissible: false,
    context: context,
    builder: (context) => Padding(
      padding:
          EdgeInsets.only(bottom: MediaQuery.of(context).viewInsets.bottom),
      child: MultiSelectCity(selectedCitiesList: selectedCities),
    ),
  );
  // here i am getting null as expected if bottomSheet is dismissed but also seletedCites are getting updated I dont know how. can some explain it.
  if (returnedSelectedCities != null) {
    setState(() {
      selectedCities = returnedSelectedCities;
    });
  }
}
</code>```

Body:
I have a Bottom sheet which shows the list of Cities from which I have to select multiple Cities and if I open the bottomSheet second time previous selected cities should be pre selected but only if user press the save button after selecting Cities and if bottomSheet is dismissed then dont include the new selected cities. I am able to select the multiple cities and show previous selected cities in second time. also I am getting null as returned value if bottomSheet is dismissed. but also I am getting upated data in case of dismiss I dont know how it is gettting initialized with new selected values.

below is my code.

This is my bottom sheet.

import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

import '../../../../business_logic/app/app_event_and_state.dart';
import '../bloc/city_bloc.dart';
import '../bloc/city_event.dart';
import '../bloc/city_state.dart';
import '../model/city_model.dart';

class MultiSelectCity extends StatefulWidget {
  const MultiSelectCity({Key? key, this.selectedCitiesList}) : super(key: key);
  final List<City>? selectedCitiesList;
  @override
  State<MultiSelectCity> createState() => _MultiSelectCityState();
}

class _MultiSelectCityState extends State<MultiSelectCity> {
  bool _isInit = true;
  List<City>? selectedCities = [];
  List<City> filteredCities = [];
  @override
  void didChangeDependencies() {
    print('didChangeDependencies');
    if (_isInit) {
      BlocProvider.of<CityBloc>(context)
          .add(const AppEventLoadCitiesWithFilter(isActive: true));
    }
    _isInit = false;
    selectedCities = widget.selectedCitiesList;
    super.didChangeDependencies();
  }

  @override
  Widget build(BuildContext context) {
    return BlocConsumer<CityBloc, AppState>(
      builder: (context, state) {
        return DraggableScrollableSheet(
          initialChildSize: 0.6,
          minChildSize: 0.4,
          maxChildSize: 0.75,
          expand: false,
          builder: (context, scrollController) => Container(
            color: Colors.white,
            child: Column(children: [
              Container(
                color: Theme.of(context).colorScheme.background,
                padding: EdgeInsets.symmetric(vertical: 25.h, horizontal: 45.w),
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Container(
                      height: 15.h,
                      width: 140.w,
                      decoration: BoxDecoration(
                        shape: BoxShape.rectangle,
                        borderRadius: BorderRadius.circular(25.r),
                        color: Colors.grey.shade400,
                      ),
                    ),
                    Padding(
                      padding:
                      EdgeInsets.only(top: 20.h, left: 10.w, bottom: 2.h),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          SizedBox(height: 25.h),
                          Text('Select City',
                              style: TextStyle(
                                  fontWeight: FontWeight.w900,
                                  fontSize: 65.sp)),
                        ],
                      ),
                    ),
                  ],
                ),
              ),
              Expanded(
                child: state.isLoading
                    ? const Center(
                  child: CircularProgressIndicator(),
                )
                    : filteredCities.isNotEmpty
                    ? ListView.builder(
                  controller: scrollController,
                  itemBuilder: (context, index) {
                    return CheckboxListTile(
                      title: Text(
                        '${filteredCities[index].cityName},'
                            ' ${filteredCities[index].stateCode}, '
                            '${filteredCities[index].countryName}',
                        style:
                        Theme.of(context).textTheme.bodyLarge,
                      ),
                      value: selectedCities?.contains(
                          filteredCities[index]) ,
                      onChanged: (bool? value) {
                        setState(() {
                          if (selectedCities?.contains(
                              filteredCities[index]) ==
                              true) {
                            selectedCities?.removeWhere((element) =>
                            element ==
                                filteredCities[index]);
                          } else {
                            selectedCities
                                ?.add(filteredCities[index]);
                          }
                          print(value);
                        });
                      },
                    );
                  },
                  itemCount: filteredCities.length,
                )
                    : const Center(
                  child: Text("No cities found"),
                ),),
              Container(
                width: double.infinity,
                height: 50,
                margin: EdgeInsets.all(20),
                child: ElevatedButton(
                    onPressed: () {
                      return Navigator.of(context).pop(selectedCities); // if save pressed then pass selected cities else if bottomsheet is dismissed it returns null.
                    },

                    child: Text(
                      'Save',
                      style: TextStyle(
                          fontWeight: FontWeight.w700, fontSize: 45.sp),
                    )),
              )
            ]),
          ),
        );
      },
      listener: (context, state) {
        if (state is AppStateActiveCities) {
          print(state.activeCities.length.toString());
          filteredCities = state.activeCities;
        }
      },
    );
  }
}

This is how I am calling it.

Future<void> _showMultiSelectCityOptions() async {
  returnedSelectedCities = await showModalBottomSheet<List<City>>(
    isScrollControlled: true,
    isDismissible: false,
    context: context,
    builder: (context) => Padding(
      padding:
          EdgeInsets.only(bottom: MediaQuery.of(context).viewInsets.bottom),
      child: MultiSelectCity(selectedCitiesList: selectedCities),
    ),
  );
  // here i am getting null as expected if bottomSheet is dismissed but also seletedCites are getting updated I dont know how. can some explain it.
  if (returnedSelectedCities != null) {
    setState(() {
      selectedCities = returnedSelectedCities;
    });
  }
}


问:
Add a job to a Gitlab pipeline if a tools exit code is 0
I would like to add a job to a pipeline in Gitlab, but only if a tool, e.g. Maven, exits with exit code 0.

For example, I would like to run the job for integration tests only if a given profile exists.

Currently I run always the job, but skip the call to Maven if the profile does not exists.  Unfortunately my current approach adds the job to the pipeline and the viewer of the pipeline might think, that the job as been executed.

integration-test-job:
  stage: build
  script:
    - |
      if mvn help:all-profiles | grep "Profile Id: IT" 2>&- 1>&-;
      then
        mvn -P IT clean install
      fi
```

Does someone have a better solution?

Body:
I would like to add a job to a pipeline in Gitlab, but only if a tool, e.g. Maven, exits with exit code 0.

For example, I would like to run the job for integration tests only if a given profile exists.

Currently I run always the job, but skip the call to Maven if the profile does not exists.  Unfortunately my current approach adds the job to the pipeline and the viewer of the pipeline might think, that the job as been executed.

integration-test-job:
  stage: build
  script:
    - |
      if mvn help:all-profiles | grep "Profile Id: IT" 2>&- 1>&-;
      then
        mvn -P IT clean install
      fi

Does someone have a better solution?


问:
Make a list of the elements removing numbers and alphabets after numbers
```<code>List=['hello-67.33-yo', 'bye-67-27.34-jk', 'hi56']
g = "".join(List)
S = g.split('-67')[:-1]
</code>```

Expected output

```<code>['hello','bye', 'hi']
</code>```

This logic works fine for 2 of the elements in the list but I want a solution for all the elements.

Body:
List=['hello-67.33-yo', 'bye-67-27.34-jk', 'hi56']
g = "".join(List)
S = g.split('-67')[:-1]

Expected output

['hello','bye', 'hi']

This logic works fine for 2 of the elements in the list but I want a solution for all the elements.


问:
Ubuntu 22.04 cannot install chrome vue devtools
OS: Ubuntu 22.04
Chrome: Version 108.0.5359.71 (Offizieller Build) (64-Bit)

Using the link, recommend by devtools.vue.js, the provided resource does not offer any install button/link.

Question:

How to install on ubuntu 22.04 vue devtools for chrome browser?


问:
My C Code exe only runs on my PC. How do I Include VCRuntime140.dll in my C code exe
I have recently been getting in C code.

I would like to create a stand alone .exe that can run on a windows PC.
The exe runs on my pc, of course because of the installation. However, on another PC I get an error

> code execution cannot proceed because vcruntime140d.dll was not found

How do I include this dll so that it will run on any PC

Any assistance will be fantastic.

Its a very simple code, see below

```<code>#define _CRT_SECURE_NO_DEPRECATE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>

int main(int argc, char* argv[])
{
    printf("\n\nHi there.\n\nThis is a .exe test.\n\n If you are seeing this, it is successful.\n\n");
    system("pause");
}
</code>```

I have googled this for a couple of days now, there has not been a real answer to my question.

EDIT after last comment
Here are the settings I have adjusted
I did select x64

Body:
I have recently been getting in C code.

I would like to create a stand alone .exe that can run on a windows PC.
The exe runs on my pc, of course because of the installation. However, on another PC I get an error

> code execution cannot proceed because vcruntime140d.dll was not found

How do I include this dll so that it will run on any PC

Any assistance will be fantastic.

Its a very simple code, see below

#define _CRT_SECURE_NO_DEPRECATE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>

int main(int argc, char* argv[])
{
    printf("\n\nHi there.\n\nThis is a .exe test.\n\n If you are seeing this, it is successful.\n\n");
    system("pause");
}

I have googled this for a couple of days now, there has not been a real answer to my question.

EDIT after last comment
Here are the settings I have adjusted
I did select x64


问:
Send data by TCP connected to server by VPN
I'm trying to send a packet by TCP to a server from VPN if I'm not connected to the local network, if I'm on the same local network I'm putting its IP if it's sent, but if I'm not and I'm passing the server's remote IP It gives an error.

This code works for me if I'm in the same local network as the server:

```<code>//Crear socket
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//Definir Ip de destino y puerto
IPAddress ip = IPAddress.Parse("192.168.1.50");
int puerto = 8888;
//Apuntar a donde se enviara el mensaje
IPEndPoint destino = new IPEndPoint(ip, puerto);

try
{
    //Realizar conexion
    socket.Connect(destino);

    //Crear mensaje
    byte[] mensaje = Encoding.ASCII.GetBytes("shutdown");

    //Enviar mensaje
    var result = socket.Send(mensaje);
}
catch (Exception ex)
{
    throw ex;
}
finally
{
    socket.Close();
}
</code>```

But to do it from outside the local network connected to the VPN passing as address the ip obtained by DNS does not work for me:

```<code>//Crear socket
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//Definir Ip de destino y puerto
IPAddress ip = Dns.GetHostAddresses("google.com")[0]; //it returns me for example ip 88.23.154.89
int puerto = Convert.ToInt32(ConfigurationManager.AppSettings["PUERTO_SERVIDOR"]);
//Apuntar a donde se enviara el mensaje
IPEndPoint destino = new IPEndPoint(ip, puerto);

try
{
    //Realizar conexion
    socket.Connect(destino);

    //Crear mensaje
    byte[] mensaje = Encoding.ASCII.GetBytes("shutdown");

    //Enviar mensaje
    var result = socket.Send(mensaje);
}
catch (Exception ex)
{
    throw ex;
}
finally
{
    socket.Close();
}

</code>```

The error gives me in socket.Connect(destino);

The connection attempt failed because the connected party did not respond properly after a period of time, or the established connection failed because the connected host was unable to respond 88.23.154.89:1025

Body:
I'm trying to send a packet by TCP to a server from VPN if I'm not connected to the local network, if I'm on the same local network I'm putting its IP if it's sent, but if I'm not and I'm passing the server's remote IP It gives an error.

This code works for me if I'm in the same local network as the server:

//Crear socket
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//Definir Ip de destino y puerto
IPAddress ip = IPAddress.Parse("192.168.1.50");
int puerto = 8888;
//Apuntar a donde se enviara el mensaje
IPEndPoint destino = new IPEndPoint(ip, puerto);

try
{
    //Realizar conexion
    socket.Connect(destino);

    //Crear mensaje
    byte[] mensaje = Encoding.ASCII.GetBytes("shutdown");

    //Enviar mensaje
    var result = socket.Send(mensaje);
}
catch (Exception ex)
{
    throw ex;
}
finally
{
    socket.Close();
}

But to do it from outside the local network connected to the VPN passing as address the ip obtained by DNS does not work for me:

//Crear socket
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//Definir Ip de destino y puerto
IPAddress ip = Dns.GetHostAddresses("google.com")[0]; //it returns me for example ip 88.23.154.89
int puerto = Convert.ToInt32(ConfigurationManager.AppSettings["PUERTO_SERVIDOR"]);
//Apuntar a donde se enviara el mensaje
IPEndPoint destino = new IPEndPoint(ip, puerto);

try
{
    //Realizar conexion
    socket.Connect(destino);

    //Crear mensaje
    byte[] mensaje = Encoding.ASCII.GetBytes("shutdown");

    //Enviar mensaje
    var result = socket.Send(mensaje);
}
catch (Exception ex)
{
    throw ex;
}
finally
{
    socket.Close();
}

The error gives me in socket.Connect(destino);

The connection attempt failed because the connected party did not respond properly after a period of time, or the established connection failed because the connected host was unable to respond 88.23.154.89:1025


问:
Invalid character error while parsing xml in php
<meta_description><![CDATA[Its a frightening sign of these tough economic times: Each Spirit Halloween store in the Bay Area has gotten close to a thousand applications for the 25 to 40 jobs it will have available this year.]]></meta_description>

Hi guys,

I am not able to parse above xml as its giving invalid character error. I am using xml_parser_create of PHP

Any help will be appreciated.

Thanks,

Umesh Kulkarni.


问:
Media Queries with device-pixel ratio aren't working the way I want them to work
I'm currently coding a website. And then I ran into this problem. I'm still pretty much at the beginning of my career. On my 1920x1080 monitor everything was displayed correctly.

Then my dad looked at the website on his laptop and the image was a bit skewed to the bottom right. After that I did some research and found out that laptops with the same resolution make websites appear differently because they usually have 1.25 zoom.

But how do I get my website to then recognize that this person is using a laptop that has a different scaling value.

Here are my media queries in CSS:

```<code>/** Phone **/
media (max-device-width: 31.25rem) {
}
/** Tablet **/
@media (min-device-width: 31.313rem) and (max-device-width: 56.25rem) {
}
/** Bigger Tablets **/
@media only screen and (min-device-width: 56.313rem) and (max-device-width: 75rem) {
}
/** Laptops **/
@media screen and (min-device-width: 75.063rem) and (max-device-width: 90rem) {
}
/** All above **/
@media screen and (min-device-width: 90.063rem) {
}
</code>```

What I tried was using:

```<code>@media screen and (min-width: 90rem) and (-webkit-device-pixel-ratio: 1.25) {
}
</code>```

And then just adjusting the things for making them look good.

Here is how it should look on Laptop

Here is how it's looking on the laptop.

Body:
I'm currently coding a website. And then I ran into this problem. I'm still pretty much at the beginning of my career. On my 1920x1080 monitor everything was displayed correctly.

Then my dad looked at the website on his laptop and the image was a bit skewed to the bottom right. After that I did some research and found out that laptops with the same resolution make websites appear differently because they usually have 1.25 zoom.

But how do I get my website to then recognize that this person is using a laptop that has a different scaling value.

Here are my media queries in CSS:

/** Phone **/
media (max-device-width: 31.25rem) {
}
/** Tablet **/
@media (min-device-width: 31.313rem) and (max-device-width: 56.25rem) {
}
/** Bigger Tablets **/
@media only screen and (min-device-width: 56.313rem) and (max-device-width: 75rem) {
}
/** Laptops **/
@media screen and (min-device-width: 75.063rem) and (max-device-width: 90rem) {
}
/** All above **/
@media screen and (min-device-width: 90.063rem) {
}

What I tried was using:

@media screen and (min-width: 90rem) and (-webkit-device-pixel-ratio: 1.25) {
}

And then just adjusting the things for making them look good.

Here is how it should look on Laptop

Here is how it's looking on the laptop.


问:
How to handle system Dark mode in QML
I'm using QML + Python to create a multi-platform application. Facing a challenge with handling System Dark Mode (not sure if it applies to Windows, but I'm currently using a Mac).

For now I do set Dark / Light mode manually, using property. Is there any way I can detect user's mode and set this value to my property? Or are there any other possible solutions?

```<code>import QtCore
import QtQuick
import QtQuick.Controls
import QtQuick.Dialogs

ApplicationWindow {
    width: 640
    height: 480
    visible: true
    property bool darkMode: false

    Text {
        id: textField
        color: {
            switch (darkMode) {
                case true:
                    "white";
                    break;
                case false:
                    "black";
                    break;
            }
         }
    }
}
</code>```

Title: How to handle system Dark mode in QML

Body:
I'm using QML + Python to create a multi-platform application. Facing a challenge with handling System Dark Mode (not sure if it applies to Windows, but I'm currently using a Mac).

For now I do set Dark / Light mode manually, using property. Is there any way I can detect user's mode and set this value to my property? Or are there any other possible solutions?

import QtCore
import QtQuick
import QtQuick.Controls
import QtQuick.Dialogs

ApplicationWindow {
    width: 640
    height: 480
    visible: true
    property bool darkMode: false

    Text {
        id: textField
        color: {
            switch (darkMode) {
                case true:
                    "white";
                    break;
                case false:
                    "black";
                    break;
            }
         }
    }
}


问:
Is it physical to consider model with number of free parameter higher than data point while model comparison in Ultranest bayesian analysis
I am conducting a model comparison for a limited set of data using the Ultranest nested sampling bayesian analysis. I realized that for a few complex models, the number of data points is less than the free parameters in the model. Is it physical to consider such a complex model during model comparison? The complex model is fitting the data better.

Also, does the evidence value (logz) takes care of the above-mentioned problem.