问:
How many Amazon SQS ReceiveMessageRequest i can perform on single sqs queue using multiple consumer
I have sqs queue "someQueue" and i have implemented multiple 100 consumer for it.
i added wait_time_seconds as 20 seconds.
now i am getting

"com.amazonaws.SdkClientException: Unable to execute HTTP request: Timeout waiting for connection from pool"

Is there any limit for receive message request?
or i am missing something?

答:
AWS default connection pool size is 50 connections, for one client.
when i reduced the connection request to less than 50 it worked for me.</p>


来源: stackexchange

问:
Spring injection with new Window (FXML)
I use AnnotationConfigApplicationContext to load my spring configuration.

```<code>public class Main extends Application {

private AnnotationConfigApplicationContext applicationContext;

@Override
public void init() throws Exception {
    applicationContext = new AnnotationConfigApplicationContext(ApplicationConfig.class);

}

@Override
public void start(Stage primaryStage) throws Exception{
    FXMLLoader loader = new FXMLLoader(getClass().getResource("/org/test/view/main.fxml"));
    loader.setControllerFactory(applicationContext::getBean);
    Parent root = loader.load();
    primaryStage.show();
    primaryStage.setOnHidden(e -> Platform.exit());
}
</code>```

and this is my ApplicationConfig

```<code>@Configuration
@ComponentScan
public class ApplicationConfig {

@Bean
public Executor executor() {
    return Executors.newCachedThreadPool(r -> {
        Thread t = new Thread(r);
        t.setDaemon(true);
        return t ;
    });
}
</code>```

Now I would like to inject this Executor instance into a new Stage (TestController.fxml) via FXMLLoader. How can I achieve that?

```<code>public void showNewWindow()  {
    try {
        FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/org/test/view/TestController.fxml"));
        Parent root1 = fxmlLoader.load();
        Stage stage = new Stage();
        stage.setScene(new Scene(root1));
        stage.show();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
</code>```

All help will be greatly appreciated. Thanks!

答:
You can inject "well-known objects" into spring-managed beans. The application context itself is one such object, so in your main controller you can do:

```<code>public class MainController {

    @Autowired
    private ApplicationContext applicationContext ;

    public void showNewWindow()  {
        try {
            FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/org/test/view/TestController.fxml"));
            fxmlLoader.setControllerFactory(applicationContext::getBean);
            Parent root1 = fxmlLoader.load();
            Stage stage = new Stage();
            stage.setScene(new Scene(root1));
            stage.show();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // ...

}
</code>```

Now the TestController will be spring-managed, so you can simply do

```<code>public class TestController {

    @Autowired
    private Executor executor ;

    // ...

}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Spring injection with new Window (FXML)

Body:
I use AnnotationConfigApplicationContext to load my spring configuration.

public class Main extends Application {

private AnnotationConfigApplicationContext applicationContext;

@Override
public void init() throws Exception {
    applicationContext = new AnnotationConfigApplicationContext(ApplicationConfig.class);

}

@Override
public void start(Stage primaryStage) throws Exception{
    FXMLLoader loader = new FXMLLoader(getClass().getResource("/org/test/view/main.fxml"));
    loader.setControllerFactory(applicationContext::getBean);
    Parent root = loader.load();
    primaryStage.show();
    primaryStage.setOnHidden(e -> Platform.exit());
}

and this is my ApplicationConfig

@Configuration
@ComponentScan
public class ApplicationConfig {

@Bean
public Executor executor() {
    return Executors.newCachedThreadPool(r -> {
        Thread t = new Thread(r);
        t.setDaemon(true);
        return t ;
    });
}

Now I would like to inject this Executor instance into a new Stage (TestController.fxml) via FXMLLoader. How can I achieve that?

public void showNewWindow()  {
    try {
        FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/org/test/view/TestController.fxml"));
        Parent root1 = fxmlLoader.load();
        Stage stage = new Stage();
        stage.setScene(new Scene(root1));
        stage.show();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

All help will be greatly appreciated. Thanks!

Body:
You can inject "well-known objects" into spring-managed beans. The application context itself is one such object, so in your main controller you can do:

public class MainController {

    @Autowired
    private ApplicationContext applicationContext ;

    public void showNewWindow()  {
        try {
            FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/org/test/view/TestController.fxml"));
            fxmlLoader.setControllerFactory(applicationContext::getBean);
            Parent root1 = fxmlLoader.load();
            Stage stage = new Stage();
            stage.setScene(new Scene(root1));
            stage.show();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // ...

}

Now the TestController will be spring-managed, so you can simply do

public class TestController {

    @Autowired
    private Executor executor ;

    // ...

}


问:
jQuery sum of textbox
Below is my HTML

I want a script like this
in one Textbox I want to add all the amount total and display it
and in one more textbox I want it like this

```<code>"name": [{
  "id": 3,
  "qty": 2
}, {
  "id": 4,
  "qty": 5
}]
</code>```

My Updated Question

```<code> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="main">
  <input type="text" name="name">
  <input type="text" name="id">
  <input type="text" name="qty">
  <input type="text" name="amount">
</div>
<div class="main">
  <input type="text" name="name">
  <input type="text" name="id">
  <input type="text" name="qty">
  <input type="text" name="amount">
</div>
<div class="main">
  <input type="text" name="name">
  <input type="text" name="id">
  <input type="text" name="qty">
  <input type="text" name="amount">
</div>
<button>Click Me!!!</button>
</code>```

My Updated code not working in this js core js is working fine

答:
```<code>var s = { 'name' : [] };
var total =  0;
$(".main").each(function(){
     s['name'].push({ 'id': $(this).find("input[name='id'"]).val(),'qty': $(this).find("input[name='qty'"]).val()});

     total = total + parseFloat($(this).find("input[name='total'"]).val());

});
</code>```

<p>//total gives final sum
//object s gives the array of objects.</p>

Title: jQuery sum of textbox

Body:
Below is my HTML

I want a script like this
in one Textbox I want to add all the amount total and display it
and in one more textbox I want it like this

"name": [{
  "id": 3,
  "qty": 2
}, {
  "id": 4,
  "qty": 5
}]

My Updated Question

  <input type="text" name="name">
  <input type="text" name="id">
  <input type="text" name="qty">
  <input type="text" name="amount">

  <input type="text" name="name">
  <input type="text" name="id">
  <input type="text" name="qty">
  <input type="text" name="amount">

  <input type="text" name="name">
  <input type="text" name="id">
  <input type="text" name="qty">
  <input type="text" name="amount">

<button>Click Me!!!</button>

My Updated code not working in this js core js is working fine

Body:
var s = { 'name' : [] };
var total =  0;
$(".main").each(function(){
     s['name'].push({ 'id': $(this).find("input[name='id'"]).val(),'qty': $(this).find("input[name='qty'"]).val()});

     total = total + parseFloat($(this).find("input[name='total'"]).val());

});

//total gives final sum
//object s gives the array of objects.


问:
Can I build openTok(tokbox) hybrid application with ionic framework?
I am building mobile app which having secure video conference. I found Ionic framework which can support corodova. Can I build openTok hybrid app in Ionic framework? If yes can I know what are the pro and cons or limitation over android and iOS?</p>

答:
Brad, thanks for sharing the plugin!

I've moved over the updated Cordova Plugin to the OpenTok GitHub organization as an OpenTok Labs project so please feel free to contribute!

The plugin is currently compatible with OpenTok iOS & Android 2.12.0 SDKs. I've introduced some changes such as OT.initPublisher not requiring the API Key (similar to the OpenTok JS SDK) and have added more publisher properties: https://github.com/opentok/cordova-plugin-opentok/blob/master/docs/ot.md#initPublisher

Here are some resourceful links:

Cordova OpenTok Plugin: https://github.com/opentok/cordova-plugin-opentok

Cordova Samples: https://github.com/opentok/opentok-cordova-samples

Ionic Samples: https://github.com/opentok/opentok-ionic-samples


问:
bootstrap 4 making dropdown scrollable
I have a problem with my drop down menu on smaller devices. i cannot make it scroll able when i tried the solution here (that is overflow:auto/ overflow-y:scroll) it's not working even if i use !important. What i'm able to scroll was my main page even if the drop down is open.

```<code><nav class="navbar navbar-toggleable-sm ">
    <button class="navbar-toggler navbar-toggler-right main-navbar-toggler" type="button" data-toggle="collapse" data-target="#main-nav-collapse" aria-controls="navbarTogglerDemo02" aria-expanded="false" aria-label="Toggle navigation">
        <span class="fa fa-bars"></span>
    </button>
    <a class="navbar-brand animation" data-animation ="fadeInLeft" href="#"><img src="/093017/img/logo-tmi.png" alt="logo"/></a>
    <div class="collapse navbar-collapse" id = "main-nav-collapse" >
        <ul class="nav navbar-nav navbar-main mr-auto mt-2 mt-md-0 animation" data-animation = "fadeInRight">
            <li class="nav-item dropdown">
                <a class="nav-link dropdown-toggle" data-toggle="dropdown" href="#" role="button" aria-haspopup="true" aria-expanded="false">Vehicles</a>
                <div class="dropdown-menu default-menu main-menu sm-main-menu animation" data-animation = "fadeIn">
                    <!-- Nav tabs -->
                    <div class="sm-main-nav" >
                        <a class="dropdown-item" href="#">Cars</a><hr>
                        <a class="dropdown-item" href="#">Vans & Pickup</a><hr>
                        <a class="dropdown-item" href="#">SUVs & Crossover</a><hr>
                        <a class="dropdown-item" href="#">MPVs</a><hr>
                        <a class="dropdown-item" href="#">Hybrid</a><hr>
                        <a class="dropdown-item" href="#">Performance</a>
                    </div>
                </div>
            </li>
            <li class="nav-item">
                <a class="nav-link " href="#">Owners</a>
            </li>
            <li class="nav-item">
                <a class="nav-link" href="#">Shop</a>
            </li>
            <li class="nav-item">
                <a class="nav-link " href="#">Promotions</a>
            </li>
        </ul>
    </div>
</code>```

答:
You can use a custom class for scroll bar for dropdown list.

```<code><div class="sm-main-nav customClassForDropDown" >
                        <a class="dropdown-item" href="#">Cars</a><hr>
                        <a class="dropdown-item" href="#">Vans & Pickup</a><hr>
                        <a class="dropdown-item" href="#">SUVs & Crossover</a><hr>
                        <a class="dropdown-item" href="#">MPVs</a><hr>
                        <a class="dropdown-item" href="#">Hybrid</a><hr>
                        <a class="dropdown-item" href="#">Performance</a>
</div>
</code>```

This is the custom css class.

```<code> .customClassForDropDown
    {
       height: 100px;
       overflow-y: auto;
    }
</code>```

check this JSFIDDLE

Title: bootstrap 4 making dropdown scrollable

Body:
I have a problem with my drop down menu on smaller devices. i cannot make it scroll able when i tried the solution here (that is overflow:auto/ overflow-y:scroll) it's not working even if i use !important. What i'm able to scroll was my main page even if the drop down is open.

    <button class="navbar-toggler navbar-toggler-right main-navbar-toggler" type="button" data-toggle="collapse" data-target="#main-nav-collapse" aria-controls="navbarTogglerDemo02" aria-expanded="false" aria-label="Toggle navigation">

    </button>

                Vehicles

                        Cars

                        Vans & Pickup

                        SUVs & Crossover

                        MPVs

                        Hybrid

                        Performance

                Owners

                Shop

                Promotions

Body:
You can use a custom class for scroll bar for dropdown list.

<div class="sm-main-nav customClassForDropDown" >
                        <a class="dropdown-item" href="#">Cars</a><hr>
                        <a class="dropdown-item" href="#">Vans & Pickup</a><hr>
                        <a class="dropdown-item" href="#">SUVs & Crossover</a><hr>
                        <a class="dropdown-item" href="#">MPVs</a><hr>
                        <a class="dropdown-item" href="#">Hybrid</a><hr>
                        <a class="dropdown-item" href="#">Performance</a>
</div>

This is the custom css class.

 .customClassForDropDown
    {
       height: 100px;
       overflow-y: auto;
    }

check this JSFIDDLE


问:
Please show me what's going wrong with this delete row function for SQL in C#
I am trying to learn the basics of making databases in Visual C#, and I am building a basic application.  In the application there is a delete button that will delete the record that is currently shown in the textboxes.  The code I have at the moment is this:

```<code>private void btnDelete_Click(object sender, EventArgs e)
{
    currentRow.Delete();
    dAdapter.Update(dataset, "Contacts");
    clearTextBoxes();
}
</code>```

currentRow is the DataRow I want to delete and that which is shown in the textboxes.  dataset is the Dataset.  dAdapter is the DataAdapter, and "Contacts" is the table name or w/e.  However this is generating an error sometimes.  What's wrong here?  Thanks!

答: Have you set the dAdapter.DeleteCommand property?  Based on the error message, it sounds like this property might not be set or may be invalid.

ContentLicense: CC BY-SA 2.5

Body:
I am trying to learn the basics of making databases in Visual C#, and I am building a basic application.  In the application there is a delete button that will delete the record that is currently shown in the textboxes.  The code I have at the moment is this:

private void btnDelete_Click(object sender, EventArgs e)
{
    currentRow.Delete();
    dAdapter.Update(dataset, "Contacts");
    clearTextBoxes();
}

currentRow is the DataRow I want to delete and that which is shown in the textboxes.  dataset is the Dataset.  dAdapter is the DataAdapter, and "Contacts" is the table name or w/e.  However this is generating an error sometimes.  What's wrong here?  Thanks!


问:
How to save image bitmap after rotation?
I develop app that save images to sd Card and all the pictures are upside i want to rotate them and save them in the rotate position i choose .
i know how to rotate on my code but the image is not saved permanently.
here is my code :
//Rotate the picture

```<code>public static Bitmap rotate(Bitmap source, float angle) {
    Matrix matrix = new Matrix();
    matrix.postRotate(angle);

    return Bitmap.createBitmap(source, 0, 0, source.getWidth(),source.getHeight(), matrix, false);
}
</code>```

//Resize image

```<code>public void resizeImage(String path , int Wdist,int Hdist){
    try
    {
        int inWidth = 0;
        int inHeight = 0;

        InputStream in = new FileInputStream(path);

        // decode image size (decode metadata only, not the whole image)
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeStream(in, null, options);
        in.close();
        in = null;

        // save width and height
        inWidth = options.outWidth;
        inHeight = options.outHeight;

        // decode full image pre-resized
        in = new FileInputStream(path);
        options = new BitmapFactory.Options();
        // calc rought re-size (this is no exact resize)
        options.inSampleSize = Math.max(inWidth/Wdist, inHeight/Hdist);
        // decode full image
        Bitmap roughBitmap = BitmapFactory.decodeStream(in, null, options);

        // calc exact destination size
        Matrix m = new Matrix();

        RectF inRect = new RectF(0, 0, roughBitmap.getWidth(), roughBitmap.getHeight());
        RectF outRect = new RectF(0, 0, Wdist, Hdist);
        m.setRectToRect(inRect, outRect, Matrix.ScaleToFit.CENTER);
        float[] values = new float[9];
        m.getValues(values);

        // resize bitmap
        Bitmap resizedBitmap = Bitmap.createScaledBitmap(roughBitmap, (int) (roughBitmap.getWidth() * values[0]), (int) (roughBitmap.getHeight() * values[4]), true);

        // save image
        try
        {
            FileOutputStream out = new FileOutputStream(path);
            resizedBitmap.compress(Bitmap.CompressFormat.JPEG, 80, out);
        }
        catch (Exception e)
        {
            Log.e("Image", e.getMessage(), e);
        }
    }
    catch (IOException e)
    {
        Log.e("Image", e.getMessage(), e);
    }
}
</code>```

thanks for the helpers :)

答:
The following code can help you compress and resize the bitmap.

Note:
Create a String type variable with name of photoPath and store the photo url in it.

```<code>public void compressImage(){
    Log.i("compressPhoto", "Compress and resize photo started.");

    // Getting Image
    InputStream in = null;
    try {
        in = new FileInputStream(photoPath);
    } catch (FileNotFoundException e) {
        Log.e("TAG","originalFilePath is not valid", e);
    }

    BitmapFactory.Options options = new BitmapFactory.Options();
    Bitmap bitmap = BitmapFactory.decodeStream(in, null, options);
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    bitmap = bitmap.createScaledBitmap(bitmap,(int)(bitmap.getWidth()*0.2), (int)(bitmap.getHeight()*0.2), true);
    bitmap.compress(Bitmap.CompressFormat.JPEG, 50, stream);

    byte[] byteArray = stream.toByteArray();

    // Storing Back
    FileOutputStream outStream = null;
    try {
        outStream = new FileOutputStream(photoPath);
        outStream.write(byteArray);
        outStream.close();
    } catch (Exception e) {
        Log.e("TAG","could not save", e);
    }

}
</code>```

Body:
I develop app that save images to sd Card and all the pictures are upside i want to rotate them and save them in the rotate position i choose .
i know how to rotate on my code but the image is not saved permanently.
here is my code :
//Rotate the picture

public static Bitmap rotate(Bitmap source, float angle) {
    Matrix matrix = new Matrix();
    matrix.postRotate(angle);

    return Bitmap.createBitmap(source, 0, 0, source.getWidth(),source.getHeight(), matrix, false);
}

//Resize image

public void resizeImage(String path , int Wdist,int Hdist){
    try
    {
        int inWidth = 0;
        int inHeight = 0;

        InputStream in = new FileInputStream(path);

        // decode image size (decode metadata only, not the whole image)
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeStream(in, null, options);
        in.close();
        in = null;

        // save width and height
        inWidth = options.outWidth;
        inHeight = options.outHeight;

        // decode full image pre-resized
        in = new FileInputStream(path);
        options = new BitmapFactory.Options();
        // calc rought re-size (this is no exact resize)
        options.inSampleSize = Math.max(inWidth/Wdist, inHeight/Hdist);
        // decode full image
        Bitmap roughBitmap = BitmapFactory.decodeStream(in, null, options);

        // calc exact destination size
        Matrix m = new Matrix();

        RectF inRect = new RectF(0, 0, roughBitmap.getWidth(), roughBitmap.getHeight());
        RectF outRect = new RectF(0, 0, Wdist, Hdist);
        m.setRectToRect(inRect, outRect, Matrix.ScaleToFit.CENTER);
        float[] values = new float[9];
        m.getValues(values);

        // resize bitmap
        Bitmap resizedBitmap = Bitmap.createScaledBitmap(roughBitmap, (int) (roughBitmap.getWidth() * values[0]), (int) (roughBitmap.getHeight() * values[4]), true);

        // save image
        try
        {
            FileOutputStream out = new FileOutputStream(path);
            resizedBitmap.compress(Bitmap.CompressFormat.JPEG, 80, out);
        }
        catch (Exception e)
        {
            Log.e("Image", e.getMessage(), e);
        }
    }
    catch (IOException e)
    {
        Log.e("Image", e.getMessage(), e);
    }
}

thanks for the helpers :)

Body:
The following code can help you compress and resize the bitmap.

Note:
Create a String type variable with name of photoPath and store the photo url in it.

public void compressImage(){
    Log.i("compressPhoto", "Compress and resize photo started.");

    // Getting Image
    InputStream in = null;
    try {
        in = new FileInputStream(photoPath);
    } catch (FileNotFoundException e) {
        Log.e("TAG","originalFilePath is not valid", e);
    }

    BitmapFactory.Options options = new BitmapFactory.Options();
    Bitmap bitmap = BitmapFactory.decodeStream(in, null, options);
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    bitmap = bitmap.createScaledBitmap(bitmap,(int)(bitmap.getWidth()*0.2), (int)(bitmap.getHeight()*0.2), true);
    bitmap.compress(Bitmap.CompressFormat.JPEG, 50, stream);

    byte[] byteArray = stream.toByteArray();

    // Storing Back
    FileOutputStream outStream = null;
    try {
        outStream = new FileOutputStream(photoPath);
        outStream.write(byteArray);
        outStream.close();
    } catch (Exception e) {
        Log.e("TAG","could not save", e);
    }

}


问:
Update database using MySQL and PHP
There are no errors shown when I click the register button to register new users, but the data isn't inserted in the database.</p>

```<code><?php
    session_start();
     if(isset($_POST['name'])&&isset($_POST['password'])){
    $name=$_POST['name'];
    $password=$_POST['password'];

    $link=mysqli_connect("localhost","root","");
    $select=mysqli_select_db($link,'first_db');
    $name=mysqli_real_escape_string($link,$name);
    $password=mysqli_real_escape_string($link,$password);
    $query="SELECT * FROM users WHERE name='$name'";
    $run=mysqli_query($link,$query);
    $count = mysqli_num_rows($run);

    if ($count>0) {
    echo 'Sorry! This Username already exists!';
    } else {
        $name = $_POST['name'];
        $password=$_POST['password'];
        $sql = "INSERT INTO users (name, password)
                VALUES
                ('$_POST[name]','$_POST[password]')";
    }
     }
    else{
        echo"Cannot be blank";
    }
?>
</code>```

答:
Just need to execute the query string like you did to check whether the user already exists or not.</p>

```<code>$sql = "INSERT INTO users (name, password)
            VALUES
            ('$_POST[name]','$_POST[password]')";
$run=mysqli_query($link,$sql);    // Executing the query here.
</code>```

Title: Update database using MySQL and PHP

Body:
There are no errors shown when I click the register button to register new users, but the data isn't inserted in the database.

<?php
    session_start();
     if(isset($_POST['name'])&&isset($_POST['password'])){
    $name=$_POST['name'];
    $password=$_POST['password'];

    $link=mysqli_connect("localhost","root","");
    $select=mysqli_select_db($link,'first_db');
    $name=mysqli_real_escape_string($link,$name);
    $password=mysqli_real_escape_string($link,$password);
    $query="SELECT * FROM users WHERE name='$name'";
    $run=mysqli_query($link,$query);
    $count = mysqli_num_rows($run);

    if ($count>0) {
    echo 'Sorry! This Username already exists!';
    } else {
        $name = $_POST['name'];
        $password=$_POST['password'];
        $sql = "INSERT INTO users (name, password)
                VALUES
                ('$_POST[name]','$_POST[password]')";
    }
     }
    else{
        echo"Cannot be blank";
    }
?>

Body:
Just need to execute the query string like you did to check whether the user already exists or not.

$sql = "INSERT INTO users (name, password)
            VALUES
            ('$_POST[name]','$_POST[password]')";
$run=mysqli_query($link,$sql);    // Executing the query here.


问:
search data frame 1 values in data frame 2 and count the occurrence
I have two data frames as below:
data frame df1 (with one column):

```<code>names
alpha beta
test1 test2
abc def
</code>```

and data frame df2 (also with one column):

```<code>names
alpha beta (abc)
abc def d
abc def (xyz)
test1 test2
test1 test2 (a)
alpha beta d
alpha beta (1)
alpha beta (2)
</code>```

I want output such that code will search df1 values in df2 and count the occurrence of those values to show the output as below.

Desired output data frame (two columns):

```<code>names          occurrence
alpha beta         4
test1 test2        2
abc def            2
</code>```

答:
Using replace twice and value_counts

```<code>df1['name'].replace(df['names'].reset_index().set_index('names')['index'].to_dict(),regex=True).replace(df['names'].to_dict()).value_counts()
Out[268]:
alpha beta     4
abc def        2
test1 test2    2
Name: name, dtype: int64
</code>```

Data input

```<code>df = pd.DataFrame({'names':['alpha beta','test1 test2','abc def']})

df1=pd.DataFrame({'name':['alpha beta (abc)','abc def d','abc def (xyz)','test1 test2','test1 test2 (a)','alpha beta d','alpha beta (1)','alpha beta (2)']})
</code>```

Body:
I have two data frames as below:
data frame df1 (with one column):

names
alpha beta
test1 test2
abc def

and data frame df2 (also with one column):

names
alpha beta (abc)
abc def d
abc def (xyz)
test1 test2
test1 test2 (a)
alpha beta d
alpha beta (1)
alpha beta (2)

I want output such that code will search df1 values in df2 and count the occurrence of those values to show the output as below.

Desired output data frame (two columns):

names          occurrence
alpha beta         4
test1 test2        2
abc def            2

Body:
Using replace twice and value_counts

df1['name'].replace(df['names'].reset_index().set_index('names')['index'].to_dict(),regex=True).replace(df['names'].to_dict()).value_counts()
Out[268]:
alpha beta     4
abc def        2
test1 test2    2
Name: name, dtype: int64

Data input

df = pd.DataFrame({'names':['alpha beta','test1 test2','abc def']})

df1=pd.DataFrame({'name':['alpha beta (abc)','abc def d','abc def (xyz)','test1 test2','test1 test2 (a)','alpha beta d','alpha beta (1)','alpha beta (2)']})


问:
why if condition is working in a weird way
I am just trying to search the key in a binary search Tree.
Here is what I did.

```<code>int searchBST(int key,node *root){

    if(root->data == key){
        printf("The key %d is in the tree.\n",key);
        return 1;
    }
    if(root->left != NULL){
        searchBST(key,root->left);
        return 0;
    }
    if(root->right != NULL){
        searchBST(key,root->right);
        return 0;
    }
}
</code>```

In the main function,check if function return 1, if it does, the key is in the tree.

```<code>printf("Please enter the key value you wish to search for: ");
scanf("%d",&key);
if((searchBST(key,root)) != 1)
    printf("The key %d is not in the tree.\n",key);
</code>```

if the key is not in the tree it will print :

```<code>The key %d is not in the tree.
</code>```

which is correct. So here comes the weird part, if the key is in the tree, sometime system will print out :

```<code>The key %d is in the tree.
</code>```

and other time system will print both:

```<code>The key %d is in the tree.
The key %d is not in the tree.
</code>```

So what can I do to fix it?

Here is my entire code

```<code>#include<stdio.h>
#include<malloc.h>
// This program will create a binary search tree or a max-heap, as chosen from a menu.
typedef struct BSTNode{
int data;
struct Node *left;
struct Node *right;
}node;
node* getNewNode(int data){
    node *new = (node*)malloc(sizeof(node));
    new->data = data;
    new->left = new->right = NULL;
    return new;
}
void heapPreOrder(int heapRootIndex,int array[],int numOfNodes){
int i = heapRootIndex;
printf("%d\t",array[i]);
if( 2*i+1<numOfNodes)
    heapPreOrder(2*i+1,array,numOfNodes);
if(2*i+2<numOfNodes)
    heapPreOrder(2*i+2,array,numOfNodes);
}
void disLevelOrder(int array[],int numOfNodes){
int i;
for(i = 0;i < numOfNodes;i++){
    printf("%d\t",array[i]);
}
printf("\n");
}
node* insertBST(int data,node *root){
if(root == NULL){
    root = getNewNode(data);
}
else{
    if(data <= root->data){
        root->left = insertBST(data,root->left);
    }
        else if(data >= root->data)
        root->right= insertBST(data,root->right);
    }
    return root;

}

int searchBST(int key,node *root){

 if (!root) return 0;
if (root->data == key) return 1;
if (root->data > key) return searchBST(root->left, key);
return searchBST(root->right, key);
}
void levelOrder(node* root, int level){
if (root == NULL)
    return;
if (level == 1)
    printf("%d\t", root->data);
else if (level > 1)
{
    levelOrder(root->left, level-1);
    levelOrder(root->right, level-1);
}
}
int findHeight(node* root)
{
if (root==NULL)
    return 0;
else
{
    int leftHeight = findHeight(root->left);
    int rightHeight = findHeight(root->right);

    if(leftHeight >= rightHeight)
        return leftHeight+1;
    else
        return rightHeight+1;
}

}
void insertHeap(int key,int numOfNodes,int array[]){
int i,j;
i = numOfNodes-1;
if(i%2 == 1 && array[i] > array[(i-1)/2]){  //if left child is greater than parent
            swap(&array[i],&array[(i-1)/2]);
            for(j = (i-1)/2;j > 0,array[j]>array[(j- 1)/2]; j = (j- 1)/2){
                swap(&array[j],&array[(j-1)/2]);
            }
        }
        if(i%2 == 0 && array[i] > array[(i-2)/2]){//if right child is greater than parent
            swap(&array[i],&array[(i-2)/2]);
            for(j = (i-1)/2;j > 0,array[j]>array[(j- 1)/2]; j = (j- 1)/2){
                swap(&array[j],&array[(j-1)/2]);
            }
        }
}
void searchHeap(int key,int array[],int numOfNodes){
int i;
for(i = 0;i < numOfNodes;i++){
    if(key == array[i]){
        printf("The key %d is in the heap.\n",key);
        return;
    }
}
printf("The key %d is not in the heap.\n",key);
}
void preorder(node *root){
if(root!=NULL){
    printf("%d\t",root->data);
    preorder(root->left);
    preorder(root->right);
}
}
void swap(int *a,int *b){
int temp;
temp = *a;
*a = *b;
*b = temp;

}
int main(){
int i,j,numOfNodes,key,height;
char choice,option;
node *root = (node*)malloc(sizeof(node));       //initialize root;
root = NULL;
printf("Enter the number of nodes in the linked list to be initially created: ");
scanf("%d",&numOfNodes);
int array[numOfNodes];           //store all the data in the array first
printf("Enter the data value to be placed in the node: ");
scanf("%d",&array[0]);
root = insertBST(array[0],root);           //create the root
//root->left = getNewNode(array[0]);
for(i = 1;i < numOfNodes;i++){
    printf("Enter the data value to be placed in the node: ");                 //put each data into array, leave the index 0 empty
    scanf("%d",&array[i]);
}
printf("What do you wish to create a Binary search Tree (B) or a Max-Heap (H)?: ");
scanf(" %c",&choice);
if(choice == 'B' || choice == 'b'){         //if user wants to build a Binary search Tree
    for(i = 1;i<numOfNodes;i++){
        insertBST(array[i],root);
    }
        printf("Binary search tree build successfully.\n");
}

if(choice == 'H'|| choice == 'h'){         //if user wants to build a Max-Heap
        for(i = 1;i<numOfNodes;i++){          //build the max heap
        if(i%2 == 1 && array[i] > array[(i-1)/2]){  //if left child is greater than parent
            swap(&array[i],&array[(i-1)/2]);
            for(j = (i-1)/2;j > 0,array[j]>array[(j- 1)/2]; j = (j- 1)/2){
                swap(&array[j],&array[(j-1)/2]);
            }
        }
        if(i%2 == 0 && array[i] > array[(i-2)/2]){  //if right child is greater than parent
            swap(&array[i],&array[(i-2)/2]);
            for(j = (i-1)/2;j > 0,array[j]>array[(j- 1)/2]; j = (j- 1)/2){
                swap(&array[j],&array[(j-1)/2]);
            }
        }
    }
        printf("Heap successfully created.\n");
    }
while(choice == 'B'||choice == 'b'){
    printf("What do you wish to do?\n");
    printf("Show Preorder Traversal(P)\tShow Level order Traversal(L)\tSearch(S)\tInsert(I)\tQuit(Q)\n");
    printf("Please enter a choice: ");
    scanf(" %c",&option);
        if(option == 'p'||option == 'P'){
        preorder(root);
        printf("\n");
    }
    if(option == 'L'||option == 'l'){
        height = findHeight(root);
        for(i = 1;i <= height;i++){
            levelOrder(root,i);
        }
        printf("\n");
    }
    if(option == 'S'||option == 's'){     //This is the part I have trouble with
        printf("Please enter the key value you wish to search for: ");
        scanf("%d",&key);
        if((searchBST(key,root)) != 1)
        printf("The key %d is not in the tree.\n",key);
    }
    if(option == 'I'||option == 'i'){       //if user wants to insert a number
        printf("please enter the key value you wish to insert: ");
        scanf("%d",&key);
        insertBST(key,root);
        printf("The key value %d was successfully inserted.\n",key);
    }
    if(option == 'q'||option == 'Q'){
        printf("Thanks for using my program, please rate 100 as feedback! Have a wonderful day :)");
        return 0;
    }
    printf("\n");
}
while(choice == 'H'|| choice == 'h'){
    printf("What do you wish to do?\n");
    printf("Show Preorder Traversal(P)\tShow Level order Traversal(L)\tSearch(S)\tInsert(I)\tQuit(Q)\n");
    printf("Please enter a choice: ");
    scanf(" %c",&option);
    if(option == 'p'||option == 'P'){
        heapPreOrder(0,array,numOfNodes);
        printf("\n");
    }
    if(option == 'L'||option == 'l'){
        disLevelOrder(array,numOfNodes);
        printf("\n");
    }
    if(option == 'S'||option == 's'){
        printf("Please enter the key value you wish to search for: ");
        scanf("%d",&key);
        searchHeap(key,array,numOfNodes);
    }
    if(option == 'I'||option == 'i'){       //if user wants to insert a number
        printf("please enter the key value you wish to insert: ");
        scanf("%d",&key);
        numOfNodes++;
        array[numOfNodes-1] = key;
        insertHeap(key,numOfNodes,array);
        printf("The key value %d was successfully inserted.\n",key);
    }
    if(option == 'q'||option == 'Q'){
        printf("Thanks for using my program, please rate 100 as feedback! Have a wonderful day :)");
        return 0;
    }
    printf("\n");
}
</code>```

}

答:
Try this:</p>

```<code>int searchBST(int key,node *root){
    if (!root){
        return 0;
    }
    if(root->data == key){
        printf("The key %d is in the tree.\n",key);
        return 1;
    }
    if(root->left != NULL){
        return searchBST(key,root->left);
        //return 0;
    }
    if(root->right != NULL){
        return searchBST(key,root->right);
        //return 0;
    }
}
</code>```

Body:
I am just trying to search the key in a binary search Tree.
Here is what I did.

int searchBST(int key,node *root){

    if(root->data == key){
        printf("The key %d is in the tree.\n",key);
        return 1;
    }
    if(root->left != NULL){
        searchBST(key,root->left);
        return 0;
    }
    if(root->right != NULL){
        searchBST(key,root->right);
        return 0;
    }
}

In the main function,check if function return 1, if it does, the key is in the tree.

printf("Please enter the key value you wish to search for: ");
scanf("%d",&key);
if((searchBST(key,root)) != 1)
    printf("The key %d is not in the tree.\n",key);

if the key is not in the tree it will print :

The key %d is not in the tree.

which is correct. So here comes the weird part, if the key is in the tree, sometime system will print out :

The key %d is in the tree.

and other time system will print both:

The key %d is in the tree.
The key %d is not in the tree.

So what can I do to fix it?

Here is my entire code

#include<stdio.h>
#include<malloc.h>
// This program will create a binary search tree or a max-heap, as chosen from a menu.
typedef struct BSTNode{
int data;
struct Node *left;
struct Node *right;
}node;
node* getNewNode(int data){
    node *new = (node*)malloc(sizeof(node));
    new->data = data;
    new->left = new->right = NULL;
    return new;
}
void heapPreOrder(int heapRootIndex,int array[],int numOfNodes){
int i = heapRootIndex;
printf("%d\t",array[i]);
if( 2*i+1<numOfNodes)
    heapPreOrder(2*i+1,array,numOfNodes);
if(2*i+2<numOfNodes)
    heapPreOrder(2*i+2,array,numOfNodes);
}
void disLevelOrder(int array[],int numOfNodes){
int i;
for(i = 0;i < numOfNodes;i++){
    printf("%d\t",array[i]);
}
printf("\n");
}
node* insertBST(int data,node *root){
if(root == NULL){
    root = getNewNode(data);
}
else{
    if(data <= root->data){
        root->left = insertBST(data,root->left);
    }
        else if(data >= root->data)
        root->right= insertBST(data,root->right);
    }
    return root;

}

int searchBST(int key,node *root){

 if (!root) return 0;
if (root->data == key) return 1;
if (root->data > key) return searchBST(root->left, key);
return searchBST(root->right, key);
}
void levelOrder(node* root, int level){
if (root == NULL)
    return;
if (level == 1)
    printf("%d\t", root->data);
else if (level > 1)
{
    levelOrder(root->left, level-1);
    levelOrder(root->right, level-1);
}
}
int findHeight(node* root)
{
if (root==NULL)
    return 0;
else
{
    int leftHeight = findHeight(root->left);
    int rightHeight = findHeight(root->right);

    if(leftHeight >= rightHeight)
        return leftHeight+1;
    else
        return rightHeight+1;
}

}
void insertHeap(int key,int numOfNodes,int array[]){
int i,j;
i = numOfNodes-1;
if(i%2 == 1 && array[i] > array[(i-1)/2]){  //if left child is greater than parent
            swap(&array[i],&array[(i-1)/2]);
            for(j = (i-1)/2;j > 0,array[j]>array[(j- 1)/2]; j = (j- 1)/2){
                swap(&array[j],&array[(j-1)/2]);
            }
        }
        if(i%2 == 0 && array[i] > array[(i-2)/2]){//if right child is greater than parent
            swap(&array[i],&array[(i-2)/2]);
            for(j = (i-1)/2;j > 0,array[j]>array[(j- 1)/2]; j = (j- 1)/2){
                swap(&array[j],&array[(j-1)/2]);
            }
        }
}
void searchHeap(int key,int array[],int numOfNodes){
int i;
for(i = 0;i < numOfNodes;i++){
    if(key == array[i]){
        printf("The key %d is in the heap.\n",key);
        return;
    }
}
printf("The key %d is not in the heap.\n",key);
}
void preorder(node *root){
if(root!=NULL){
    printf("%d\t",root->data);
    preorder(root->left);
    preorder(root->right);
}
}
void swap(int *a,int *b){
int temp;
temp = *a;
*a = *b;
*b = temp;

}
int main(){
int i,j,numOfNodes,key,height;
char choice,option;
node *root = (node*)malloc(sizeof(node));       //initialize root;
root = NULL;
printf("Enter the number of nodes in the linked list to be initially created: ");
scanf("%d",&numOfNodes);
int array[numOfNodes];           //store all the data in the array first
printf("Enter the data value to be placed in the node: ");
scanf("%d",&array[0]);
root = insertBST(array[0],root);           //create the root
//root->left = getNewNode(array[0]);
for(i = 1;i < numOfNodes;i++){
    printf("Enter the data value to be placed in the node: ");                 //put each data into array, leave the index 0 empty
    scanf("%d",&array[i]);
}
printf("What do you wish to create a Binary search Tree (B) or a Max-Heap (H)?: ");
scanf(" %c",&choice);
if(choice == 'B' || choice == 'b'){         //if user wants to build a Binary search Tree
    for(i = 1;i<numOfNodes;i++){
        insertBST(array[i],root);
    }
        printf("Binary search tree build successfully.\n");
}

if(choice == 'H'|| choice == 'h'){         //if user wants to build a Max-Heap
        for(i = 1;i<numOfNodes;i++){          //build the max heap
        if(i%2 == 1 && array[i] > array[(i-1)/2]){  //if left child is greater than parent
            swap(&array[i],&array[(i-1)/2]);
            for(j = (i-1)/2;j > 0,array[j]>array[(j- 1)/2]; j = (j- 1)/2){
                swap(&array[j],&array[(j-1)/2]);
            }
        }
        if(i%2 == 0 && array[i] > array[(i-2)/2]){  //if right child is greater than parent
            swap(&array[i],&array[(i-2)/2]);
            for(j = (i-1)/2;j > 0,array[j]>array[(j- 1)/2]; j = (j- 1)/2){
                swap(&array[j],&array[(j-1)/2]);
            }
        }
    }
        printf("Heap successfully created.\n");
    }
while(choice == 'B'||choice == 'b'){
    printf("What do you wish to do?\n");
    printf("Show Preorder Traversal(P)\tShow Level order Traversal(L)\tSearch(S)\tInsert(I)\tQuit(Q)\n");
    printf("Please enter a choice: ");
    scanf(" %c",&option);
        if(option == 'p'||option == 'P'){
        preorder(root);
        printf("\n");
    }
    if(option == 'L'||option == 'l'){
        height = findHeight(root);
        for(i = 1;i <= height;i++){
            levelOrder(root,i);
        }
        printf("\n");
    }
    if(option == 'S'||option == 's'){     //This is the part I have trouble with
        printf("Please enter the key value you wish to search for: ");
        scanf("%d",&key);
        if((searchBST(key,root)) != 1)
        printf("The key %d is not in the tree.\n",key);
    }
    if(option == 'I'||option == 'i'){       //if user wants to insert a number
        printf("please enter the key value you wish to insert: ");
        scanf("%d",&key);
        insertBST(key,root);
        printf("The key value %d was successfully inserted.\n",key);
    }
    if(option == 'q'||option == 'Q'){
        printf("Thanks for using my program, please rate 100 as feedback! Have a wonderful day :)");
        return 0;
    }
    printf("\n");
}
while(choice == 'H'|| choice == 'h'){
    printf("What do you wish to do?\n");
    printf("Show Preorder Traversal(P)\tShow Level order Traversal(L)\tSearch(S)\tInsert(I)\tQuit(Q)\n");
    printf("Please enter a choice: ");
    scanf(" %c",&option);
    if(option == 'p'||option == 'P'){
        heapPreOrder(0,array,numOfNodes);
        printf("\n");
    }
    if(option == 'L'||option == 'l'){
        disLevelOrder(array,numOfNodes);
        printf("\n");
    }
    if(option == 'S'||option == 's'){
        printf("Please enter the key value you wish to search for: ");
        scanf("%d",&key);
        searchHeap(key,array,numOfNodes);
    }
    if(option == 'I'||option == 'i'){       //if user wants to insert a number
        printf("please enter the key value you wish to insert: ");
        scanf("%d",&key);
        numOfNodes++;
        array[numOfNodes-1] = key;
        insertHeap(key,numOfNodes,array);
        printf("The key value %d was successfully inserted.\n",key);
    }
    if(option == 'q'||option == 'Q'){
        printf("Thanks for using my program, please rate 100 as feedback! Have a wonderful day :)");
        return 0;
    }
    printf("\n");
}

}

Body:
Try this:

int searchBST(int key,node *root){
    if (!root){
        return 0;
    }
    if(root->data == key){
        printf("The key %d is in the tree.\n",key);
        return 1;
    }
    if(root->left != NULL){
        return searchBST(key,root->left);
        //return 0;
    }
    if(root->right != NULL){
        return searchBST(key,root->right);
        //return 0;
    }
}


问:
Search username with same username in phpmyadmin
Is it able to do search username which exactly same username in phpmyadmin? I mean for example, my database has two cindy, one is cindy, another one is cindy sam. When I search cindy, it only will display cindy, to display cindy sam, i need to search in the text box with cindy sam. Same as alphabet, when key in a, it will not display any data, mean if i want search username, i need to insert complete username stored in database. Hope can understand my question, thank you. And also hope feedback.

PHP:

```<code><?php

if(isset($_POST['search']))
{
$valueToSearch = $_POST['valueToSearch'];
// search in all table columns
// using concat mysql function
$query = "SELECT * FROM `table1` WHERE CONCAT(`username`)
LIKE '%".$valueToSearch."%'";
$search_result = filterTable($query);

 }
 else {
 $query = "SELECT * FROM `table1` LIMIT 0";
 $search_result = filterTable($query);
 }

 // function to connect and execute the query
function filterTable($query)
{
$connect = mysqli_connect("localhost", "root", "", "wp");
$filter_Result = mysqli_query($connect, $query);
return $filter_Result;
}

?>
</code>```

答:
Hopes it Work:</p>

```<code>   <?php

      // function to connect and execute the query
        function filterTable($query)
        {
        $connect = mysqli_connect("localhost", "root", "", "wp");
        $filter_Result = mysqli_query($connect, $query);
        return $filter_Result;
        }

    if(isset($_POST['search']))
    {
        $valueToSearch = $_POST['valueToSearch'];

     $query = "select * from table1 where CONCAT(username) like '%$valueToSearch%' LIMIT 0,500";
                    $search_result = filterTable($query);
    }
    else
     {
     $query = "SELECT * FROM table1 LIMIT 0";
     $search_result = filterTable($query);
     }

    ?>
</code>```

Body:
Is it able to do search username which exactly same username in phpmyadmin? I mean for example, my database has two cindy, one is cindy, another one is cindy sam. When I search cindy, it only will display cindy, to display cindy sam, i need to search in the text box with cindy sam. Same as alphabet, when key in a, it will not display any data, mean if i want search username, i need to insert complete username stored in database. Hope can understand my question, thank you. And also hope feedback.

PHP:

<?php

if(isset($_POST['search']))
{
$valueToSearch = $_POST['valueToSearch'];
// search in all table columns
// using concat mysql function
$query = "SELECT * FROM `table1` WHERE CONCAT(`username`)
LIKE '%".$valueToSearch."%'";
$search_result = filterTable($query);

 }
 else {
 $query = "SELECT * FROM `table1` LIMIT 0";
 $search_result = filterTable($query);
 }

 // function to connect and execute the query
function filterTable($query)
{
$connect = mysqli_connect("localhost", "root", "", "wp");
$filter_Result = mysqli_query($connect, $query);
return $filter_Result;
}

?>

Body:
Hopes it Work:

   <?php

      // function to connect and execute the query
        function filterTable($query)
        {
        $connect = mysqli_connect("localhost", "root", "", "wp");
        $filter_Result = mysqli_query($connect, $query);
        return $filter_Result;
        }

    if(isset($_POST['search']))
    {
        $valueToSearch = $_POST['valueToSearch'];

     $query = "select * from table1 where CONCAT(username) like '%$valueToSearch%' LIMIT 0,500";
                    $search_result = filterTable($query);
    }
    else
     {
     $query = "SELECT * FROM table1 LIMIT 0";
     $search_result = filterTable($query);
     }

    ?>


问:
Retrieve JSON array from Firebase in Android
I have a JSON array where I store a few items I want to display on my app's main menu. It looks like this:

I'd like to retrieve this list but for some reason I ignore the code below doesn't work:

```<code>DatabaseReference mRootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference mMainMenuRef = mRootRef.child("main_menu");

    @Override
protected void onStart() {
    super.onStart();
    mAuth.addAuthStateListener(mAuthListener);

    mMainMenuRef.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {

            for (DataSnapshot ds : dataSnapshot.getChildren()) {
                String stringValue = ds.getValue(String.class);
                Log.i("Firebase", stringValue);
            }
        }

        ...

    });
</code>```

答:
Here is your modified code of yours, as per your requirement:</p>

```<code>DatabaseReference mRootRef =
FirebaseDatabase.getInstance().getReference();
DatabaseReference mMainMenuRef = mRootRef.child("main_menu");

@Override
protected void onStart() {
   super.onStart();
   mAuth.addAuthStateListener(mAuthListener);

   mMainMenuRef.addValueEventListener(new ValueEventListener() {
       @Override
       public void onDataChange(DataSnapshot dataSnapshot) {

          for(DataSnapshot dataSnapshot1 :dataSnapshot.getChildren())
            {

                for (DataSnapshot property :dataSnapshot1.getChildren()) {
                    String value = property.getValue(String.class);
                    Log.i("Firebase", value);
                }
            }
       }

    ...

});
</code>```

Body:
I have a JSON array where I store a few items I want to display on my app's main menu. It looks like this:

I'd like to retrieve this list but for some reason I ignore the code below doesn't work:

DatabaseReference mRootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference mMainMenuRef = mRootRef.child("main_menu");

    @Override
protected void onStart() {
    super.onStart();
    mAuth.addAuthStateListener(mAuthListener);

    mMainMenuRef.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {

            for (DataSnapshot ds : dataSnapshot.getChildren()) {
                String stringValue = ds.getValue(String.class);
                Log.i("Firebase", stringValue);
            }
        }

        ...

    });

Body:
Here is your modified code of yours, as per your requirement:

DatabaseReference mRootRef =
FirebaseDatabase.getInstance().getReference();
DatabaseReference mMainMenuRef = mRootRef.child("main_menu");

@Override
protected void onStart() {
   super.onStart();
   mAuth.addAuthStateListener(mAuthListener);

   mMainMenuRef.addValueEventListener(new ValueEventListener() {
       @Override
       public void onDataChange(DataSnapshot dataSnapshot) {

          for(DataSnapshot dataSnapshot1 :dataSnapshot.getChildren())
            {

                for (DataSnapshot property :dataSnapshot1.getChildren()) {
                    String value = property.getValue(String.class);
                    Log.i("Firebase", value);
                }
            }
       }

    ...

});

ContentLicense: CC BY-SA 4.0


问:
Advanced numpy indexing
Here is what I want to do with numpy arrays:

```<code>import numpy as np

x = np.random.random((10,321,321))
y = np.random.rand((10,21,321,321))
z = np.random.randint(0,21,size=(10,321,321))

for i in range(10):
    for j in range(321):
        for k in range(321):
            if x[i][j][k] <= 0.5:
               for l in range(21):
                   if l == z[i][j][k]:
                       y[i][l][j][k] = 1
                   else:
                       y[i][l][j][k] = 0
</code>```

What would be the better way of doing this?

答:
One way would be to use np.identity to create a complete set of one-hot vectors and select the appropriate ones using advanced indexing:

```<code>import numpy as np

x = np.random.random((10,321,321))
y = np.random.rand(10,21,321,321)
z = np.random.randint(0,21,size=(10,321,321))

yc = y.copy()
yct= yc.transpose(0, 2, 3, 1)
yct[x <= 0.5] = np.identity(21, dtype=yc.dtype)[z[x <= 0.5]]

for i in range(10):
    for j in range(321):
        for k in range(321):
            if x[i][j][k] <= 0.5:
               for l in range(21):
                   if l == z[i][j][k]:
                       y[i][l][j][k] = 1
                   else:
                       y[i][l][j][k] = 0

print(np.all(yc == y))
# True
</code>```

Title: Advanced numpy indexing

Body:
Here is what I want to do with numpy arrays:

import numpy as np

x = np.random.random((10,321,321))
y = np.random.rand((10,21,321,321))
z = np.random.randint(0,21,size=(10,321,321))

for i in range(10):
    for j in range(321):
        for k in range(321):
            if x[i][j][k] <= 0.5:
               for l in range(21):
                   if l == z[i][j][k]:
                       y[i][l][j][k] = 1
                   else:
                       y[i][l][j][k] = 0

What would be the better way of doing this?

Body:
One way would be to use np.identity to create a complete set of one-hot vectors and select the appropriate ones using advanced indexing:

import numpy as np

x = np.random.random((10,321,321))
y = np.random.rand(10,21,321,321)
z = np.random.randint(0,21,size=(10,321,321))

yc = y.copy()
yct= yc.transpose(0, 2, 3, 1)
yct[x <= 0.5] = np.identity(21, dtype=yc.dtype)[z[x <= 0.5]]

for i in range(10):
    for j in range(321):
        for k in range(321):
            if x[i][j][k] <= 0.5:
               for l in range(21):
                   if l == z[i][j][k]:
                       y[i][l][j][k] = 1
                   else:
                       y[i][l][j][k] = 0

print(np.all(yc == y))
# True


问:
Custom theme for Payment Request Button [Stripe]
Usually, we use a theme which was provided stripe like the following.

```<code>style: {
  paymentRequestButton: {
    theme: "light-outline"
  }
}
</code>```

They have also provided some theme's like 'dark' | 'light' | 'light-outline'

My question is can we create a custom theme for this button.? eg: a blue colour theme

Or is there any workaround or script hack for changing the color of the button.?

答:
Reading Step 3 of Payment Request Button implementation steps, it is obvious the element has id: #payment-request-button.

Haven't worked with Stripe and I don't know if it's a <button> or a more complex HTML markup structure and I also read somewhere in their docs they do not guarantee maintaining the HTML structure of their elements.

Anyway, here are a few things to keep in mind when aiming this type of intervention: most importantly, develop in steps:

Find a solution that works for the time being. Ideally, it should be something that degrades/fails gracefully and silently (no public facing errors)

Maximize ability to withstand minor modifications in markup from Stripe

Also, keep your source files so you can easily adapt your solution to any markup breaking changes from Stripe so you can provide a fix when it stops working.

If you rely on CSS (recommended), you should inspect the currently rendered markup and find out what are the currently applying selectors. Simply writing stronger selectors should be enough. If styles are being applied via JavaScript by Stripe, chances are you will need to use !important in your CSS. Of course, you should avoid it as much as possible, or at least thoroughly test on as many devices as you can get your hands on.

As a rule of thumb, !important is quite bad in CSS. It's a very powerful hammer and most times it breaks delicate things (i.e.: responsiveness on touch devices).

Alternatively, if you rely on JavaScript to do the styling, you might want to play around with setTimeout() and determine the proper amount of miliseconds to wait before triggering your changes after the prButton.mount() method was called. Test on multiple devices. I advise against this method as it's more error prone and more difficult to control: you want to time your changes just after the element was built but (ideally) before it gets rendered. Of course, there are workarounds, such as hide or fade it until your changes are applied.

Note: This is not an easy task and nobody (except Stripe themselves, by providing a proper method) can guarantee you a bullet-proof solution so I thought laying out the principles on how to approach it might have more value on short and long term than trying to get Stripe working on a test/dev account and provide a particular solution which might stop working the next day, when Stripe change their markup.

Body:
Usually, we use a theme which was provided stripe like the following.

style: {
  paymentRequestButton: {
    theme: "light-outline"
  }
}

They have also provided some theme's like 'dark' | 'light' | 'light-outline'

My question is can we create a custom theme for this button.? eg: a blue colour theme

Or is there any workaround or script hack for changing the color of the button.?


问:
deploy spring boot war into tomcat
i am using spring boot and i want to deploy a rest API war file into tomcat server.
There is no errors in the tomcat server logs but when i call any endpoint i got 404 "not found" and i got the same from the tomcat server .

java version : 8.
tomcat version : 9.

maybe i miss something , here are my code samples :

Pom :

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.test</groupId>
<artifactId>test</artifactId>
<version>1.1</version>
<packaging>war</packaging>

<name>test</name>
<description>test API</description>

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.1.RELEASE</version>
    <relativePath /> <!-- lookup parent from repository -->
</parent>

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-
8</project.reporting.outputEncoding>
    <java.version>1.8</java.version>
</properties>

<dependencies>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-tomcat</artifactId>
        <scope>provided</scope>
    </dependency>

        <!-- tag::security[] -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-security</artifactId>
    </dependency>
    <!-- end::security[] -->

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-jdbc</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
</dependencies>

<build>
    <defaultGoal>install</defaultGoal>

    <pluginManagement>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-assembly-plugin</artifactId>
                <version>3.0.0</version>
            </plugin>

        </plugins>
    </pluginManagement>
    <!-- To use the plugin goals in your POM or parent POM -->
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-assembly-plugin</artifactId>
        </plugin>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <configuration>
                <source>1.8</source>
                <target>1.8</target>
            </configuration>
        </plugin>
    </plugins>
 </build>
 </project>
</code>```

2.Application.java

```<code>@SpringBootApplication
public class TestApplication extends SpringBootServletInitializer {

@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder
application) {
    return application.sources(TestApplication.class);
    }

public static void main(String[] args) {
SpringApplication.run(TestApplication.class, args);
}

}
</code>```

答:
Yes I had the similar error, in my case  I autowire the object of Spring security session so it shows circular reference error.
I added @Lay annotation on top of the autowired object. For more details pls check the link.

https://www.quora.com/How-can-you-fix-Requested-bean-is-currently-in-creation-Is-there-an-unresolvable-circular-reference-while-deploying-a-Spring-Security-application-in-Tomcat

Title: deploy spring boot war into tomcat

Body:
i am using spring boot and i want to deploy a rest API war file into tomcat server.
There is no errors in the tomcat server logs but when i call any endpoint i got 404 "not found" and i got the same from the tomcat server .

java version : 8.
tomcat version : 9.

maybe i miss something , here are my code samples :

Pom :

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.test</groupId>
<artifactId>test</artifactId>
<version>1.1</version>
<packaging>war</packaging>

<name>test</name>
<description>test API</description>

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.1.RELEASE</version>
    <relativePath />
</parent>

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-
8</project.reporting.outputEncoding>
    <java.version>1.8</java.version>
</properties>

<dependencies>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-tomcat</artifactId>
        <scope>provided</scope>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-security</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-jdbc</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
</dependencies>

<build>
    <defaultGoal>install</defaultGoal>

    <pluginManagement>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-assembly-plugin</artifactId>
                <version>3.0.0</version>
            </plugin>

        </plugins>
    </pluginManagement>

    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-assembly-plugin</artifactId>
        </plugin>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <configuration>
                <source>1.8</source>
                <target>1.8</target>
            </configuration>
        </plugin>
    </plugins>
 </build>
 </project>

2.Application.java

@SpringBootApplication
public class TestApplication extends SpringBootServletInitializer {

@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder
application) {
    return application.sources(TestApplication.class);
    }

public static void main(String[] args) {
SpringApplication.run(TestApplication.class, args);
}

}


问:
Replacing images in the bundle at run time
Can I replace images in bundle at run time? Basically, I have some images part of my bundle and also I will have them from the server if there is any change in the image. Can I place them in the bundle at run time so that I need not to change my code to pick the image?</p>

答:
You cannot change the bundle on runtime. This will prevent the app from running, as the profile won't be valid anymore. You will find tons of code how to deal with the sandbox folders provided by iOS on stackoverflow.

edit

Useful questions / answers

copying folder from bundle to documents

Downloading image into bundle


问:
Dynamically adding pages to QStackedWidget using a custom widget designed in Qt Creator
So I'm lost ... again. I have a QMainWindow with a empty QStackedWidget. I would like to dynamically populate the QStackedWidget using a custom widget that I created in Qt Creator. I tried following Creating a custom widget in PyQT5 in another thread, but that doesn't really cover importing from a UI file in this case. I keep receiving:

AttributeError: 'QStackedWidget' object has no attribute 'addItemWidget'

Here is the code for the Widget...

```<code># ItemWidget.py

from PyQt5 import uic
from PyQt5.QtWidgets import QWidget

class Widget:

    def __init__(self):
        self.text = None
        self.data = None

class ItemWidget(QWidget):

    def __init_(self, parent = None):
        self.WidgetList = []
        QWidget.__init__(self, parent = parent)
        uic.loadUi(r'interface/ItemWidget.ui', self)

    def addItemWidget(self, index, text):
        widget = Widget()
        widget.text = text
        self.WidgetList.append([])
        self.WidgetList[index].append(widget)

        # TESTING
        print(self.WidgetList)
</code>```

Relevant code from main.py:

```<code>from ItemWidget import *

for key, value in self.ItemIndexList.items():
    self.ItemStackedWidget.addItemWidget(value, key)
</code>```

I understand that I'm getting this error because QStackedWidget has no defined attribute called 'addItemWidget, but I don't know what I need to do to get this to work as intended. When I try overriding the method using 'addWidget', I get an unexpected value error.

Any ideas? I'm fairly new to Python and still learning, so if I'm missing some important information please let me know.

I have a few different revisions of my MainWindow.ui. One just has a QStackedWidget where I want the pages to go, the other is completely laid out how I would imagine the final product to look. The ItemWidget.ui file just contains the elements I want to add to each QStackedWidget page. I have not promoted any of them to a custom class, which I suspect I will need to do.

I'm currently using Python 3.6 and PyQt5

** EDIT TO ADD MVCE **

TestApp.py

```<code>from PyQt5.QtWidgets import QApplication
import TestMain
import sys

class MCVE(QApplication):

    def __init__(self):
        args = sys.argv
        QApplication.__init__(self, args)
        self.application = TestMain.TestMainWindow()

    def initApp(self):
        self.application.show()

if __name__ == '__main__':
    app = MCVE()
    app.initApp()
    sys.exit(app.exec_())
</code>```

TestMain.py

```<code>from PyQt5.Qt import Qt
from PyQt5.QtWidgets import QMainWindow
from TestItemWidget import *

class TestMainWindow(QMainWindow):

    def __init__(self):
        QMainWindow.__init__(self, None, Qt.Window)
        uic.loadUi(r'interface/TestMainWindow.ui', self)

        SlotList = {('Header1', 0),('Header2', 1)}

        for key, value in SlotList:
            self.ItemStackedWidget.addItemWidget(value, key)
</code>```

TestItemWidget.py

```<code>from PyQt5 import uic
from PyQt5.QtWidgets import QWidget

class Widget:

    def __init__(self):
        self.text = None
        self.data = None

class ItemWidget(QWidget):

    def __init_(self, parent = None):
        self.WidgetList = []
        QWidget.__init__(self, parent = parent, flags = None)
        uic.loadUi(r'interface/TestItemWidget.ui', self)

    def addItemWidget(self, index, text):
        widget = Widget()
        widget.text = text
        self.WidgetList.append([])
        self.WidgetList[index].append(widget)
        print(self.WidgetList)

if __name__ == '__main__':
    pass
</code>```

TestItemWidget.ui

```<code><?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
 <class>Form</class>
 <widget class="QWidget" name="Form">
  <property name="geometry">
   <rect>
    <x>0</x>
    <y>0</y>
    <width>400</width>
    <height>300</height>
   </rect>
  </property>
  <property name="windowTitle">
   <string>Form</string>
  </property>
  <layout class="QVBoxLayout" name="verticalLayout">
   <item alignment="Qt::AlignHCenter">
    <widget class="QLabel" name="label">
     <property name="text">
      <string>ItemWidget</string>
     </property>
    </widget>
   </item>
  </layout>
 </widget>
 <resources/>
 <connections/>
</ui>
</code>```

TestMainWindow.ui

```<code><?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
 <class>MainWindow</class>
 <widget class="QMainWindow" name="MainWindow">
  <property name="geometry">
   <rect>
    <x>0</x>
    <y>0</y>
    <width>417</width>
    <height>288</height>
   </rect>
  </property>
  <property name="MainWindowUI" stdset="0">
   <string>MainWindow</string>
  </property>
  <widget class="QWidget" name="widget">
   <layout class="QVBoxLayout">
    <item>
     <widget class="QStackedWidget" name="ItemStackedWidget"/>
    </item>
   </layout>
  </widget>
 </widget>
 <resources/>
 <connections/>
</ui>
</code>```

答:
If you want to interact with a widget you must do it where the widget exists and in your case QStackedWidget exists in TestMain.py so you must use it with your addWidget method, it does not have the addItemWidget method, I also recommend verifying your syntax, for example the init method is placed with 2 underscores on each side, but in your code ItemWidget has only one on the right side: __init_, in conclusion your code should be as follows, add the text to the labels to make it visible:

TestMain.py

```<code>from PyQt5.Qt import Qt
from PyQt5.QtWidgets import QMainWindow, QMenu, QToolBar, QTreeWidgetItem
from TestItemWidget import *

class TestMainWindow(QMainWindow):
    def __init__(self):
        QMainWindow.__init__(self, None, Qt.Window)
        uic.loadUi(r'interface/TestMainWindow.ui', self)

        SlotList = {('Header1', 0),('Header2', 1)}

        for key, value in SlotList:
            w = ItemWidget(self)
            w.label.setText(key)
            self.ItemStackedWidget.insertWidget(value, w)
</code>```

TestItemWidget.py

```<code>from PyQt5 import uic
from PyQt5.QtWidgets import QWidget

class ItemWidget(QWidget):
    def __init__(self, parent = None):
        QWidget.__init__(self, parent = parent)
        uic.loadUi(r'interface/TestItemWidget.ui', self)
</code>```

Body:
So I'm lost ... again. I have a QMainWindow with a empty QStackedWidget. I would like to dynamically populate the QStackedWidget using a custom widget that I created in Qt Creator. I tried following Creating a custom widget in PyQT5 in another thread, but that doesn't really cover importing from a UI file in this case. I keep receiving:

AttributeError: 'QStackedWidget' object has no attribute 'addItemWidget'

Here is the code for the Widget...

# ItemWidget.py

from PyQt5 import uic
from PyQt5.QtWidgets import QWidget

class Widget:

    def __init__(self):
        self.text = None
        self.data = None

class ItemWidget(QWidget):

    def __init_(self, parent = None):
        self.WidgetList = []
        QWidget.__init__(self, parent = parent)
        uic.loadUi(r'interface/ItemWidget.ui', self)

    def addItemWidget(self, index, text):
        widget = Widget()
        widget.text = text
        self.WidgetList.append([])
        self.WidgetList[index].append(widget)

        # TESTING
        print(self.WidgetList)

Relevant code from main.py:

from ItemWidget import *

for key, value in self.ItemIndexList.items():
    self.ItemStackedWidget.addItemWidget(value, key)

I understand that I'm getting this error because QStackedWidget has no defined attribute called 'addItemWidget, but I don't know what I need to do to get this to work as intended. When I try overriding the method using 'addWidget', I get an unexpected value error.

Any ideas? I'm fairly new to Python and still learning, so if I'm missing some important information please let me know.

I have a few different revisions of my MainWindow.ui. One just has a QStackedWidget where I want the pages to go, the other is completely laid out how I would imagine the final product to look. The ItemWidget.ui file just contains the elements I want to add to each QStackedWidget page. I have not promoted any of them to a custom class, which I suspect I will need to do.

I'm currently using Python 3.6 and PyQt5

** EDIT TO ADD MVCE **

TestApp.py

from PyQt5.QtWidgets import QApplication
import TestMain
import sys

class MCVE(QApplication):

    def __init__(self):
        args = sys.argv
        QApplication.__init__(self, args)
        self.application = TestMain.TestMainWindow()

    def initApp(self):
        self.application.show()

if __name__ == '__main__':
    app = MCVE()
    app.initApp()
    sys.exit(app.exec_())

TestMain.py

from PyQt5.Qt import Qt
from PyQt5.QtWidgets import QMainWindow
from TestItemWidget import *

class TestMainWindow(QMainWindow):

    def __init__(self):
        QMainWindow.__init__(self, None, Qt.Window)
        uic.loadUi(r'interface/TestMainWindow.ui', self)

        SlotList = {('Header1', 0),('Header2', 1)}

        for key, value in SlotList:
            self.ItemStackedWidget.addItemWidget(value, key)

TestItemWidget.py

from PyQt5 import uic
from PyQt5.QtWidgets import QWidget

class Widget:

    def __init__(self):
        self.text = None
        self.data = None

class ItemWidget(QWidget):

    def __init_(self, parent = None):
        self.WidgetList = []
        QWidget.__init__(self, parent = parent, flags = None)
        uic.loadUi(r'interface/TestItemWidget.ui', self)

    def addItemWidget(self, index, text):
        widget = Widget()
        widget.text = text
        self.WidgetList.append([])
        self.WidgetList[index].append(widget)
        print(self.WidgetList)

if __name__ == '__main__':
    pass

TestItemWidget.ui

<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
 <class>Form</class>
 <widget class="QWidget" name="Form">
  <property name="geometry">
   <rect>
    <x>0</x>
    <y>0</y>
    <width>400</width>
    <height>300</height>
   </rect>
  </property>
  <property name="windowTitle">
   <string>Form</string>
  </property>
  <layout class="QVBoxLayout" name="verticalLayout">
   <item alignment="Qt::AlignHCenter">
    <widget class="QLabel" name="label">
     <property name="text">
      <string>ItemWidget</string>
     </property>
    </widget>
   </item>
  </layout>
 </widget>
 <resources/>
 <connections/>
</ui>

TestMainWindow.ui

<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
 <class>MainWindow</class>
 <widget class="QMainWindow" name="MainWindow">
  <property name="geometry">
   <rect>
    <x>0</x>
    <y>0</y>
    <width>417</width>
    <height>288</height>
   </rect>
  </property>
  <property name="MainWindowUI" stdset="0">
   <string>MainWindow</string>
  </property>
  <widget class="QWidget" name="widget">
   <layout class="QVBoxLayout">
    <item>
     <widget class="QStackedWidget" name="ItemStackedWidget"/>
    </item>
   </layout>
  </widget>
 </widget>
 <resources/>
 <connections/>
</ui>

Body:
If you want to interact with a widget you must do it where the widget exists and in your case QStackedWidget exists in TestMain.py so you must use it with your addWidget method, it does not have the addItemWidget method, I also recommend verifying your syntax, for example the init method is placed with 2 underscores on each side, but in your code ItemWidget has only one on the right side: __init_, in conclusion your code should be as follows, add the text to the labels to make it visible:

TestMain.py

from PyQt5.Qt import Qt
from PyQt5.QtWidgets import QMainWindow, QMenu, QToolBar, QTreeWidgetItem
from TestItemWidget import *

class TestMainWindow(QMainWindow):
    def __init__(self):
        QMainWindow.__init__(self, None, Qt.Window)
        uic.loadUi(r'interface/TestMainWindow.ui', self)

        SlotList = {('Header1', 0),('Header2', 1)}

        for key, value in SlotList:
            w = ItemWidget(self)
            w.label.setText(key)
            self.ItemStackedWidget.insertWidget(value, w)

TestItemWidget.py

from PyQt5 import uic
from PyQt5.QtWidgets import QWidget

class ItemWidget(QWidget):
    def __init__(self, parent = None):
        QWidget.__init__(self, parent = parent)
        uic.loadUi(r'interface/TestItemWidget.ui', self)


答:
You forgot to execute your Insert query like below :

```<code>mysqli_query($link,$sql);
</code>```

But you have to use Prepared Insert Query to make it more secure:

```<code>// prepare and bind User Query
$queryUsers = $conn->prepare("INSERT INTO
users(name,password) VALUES (?, ?)");
$queryUsers->bind_param("ss",$name,$password);

$name = $_POST[name];
$password = $_POST[password];

// execute Users Query
$queryUsers->execute();

// Close Connections
$queryUsers->close();
</code>```

Title: Update database using MySQL and PHP

Body:
You forgot to execute your Insert query like below :

mysqli_query($link,$sql);

But you have to use Prepared Insert Query to make it more secure:

// prepare and bind User Query
$queryUsers = $conn->prepare("INSERT INTO
users(name,password) VALUES (?, ?)");
$queryUsers->bind_param("ss",$name,$password);

$name = $_POST[name];
$password = $_POST[password];

// execute Users Query
$queryUsers->execute();

// Close Connections
$queryUsers->close();


问:
Activity indicator with custom image
I am loading a UIWebView and in the meantime I wan't to show a blank page with this activity indicator spinning (siri activity indicator). From what I have understand you can not change the image, but can't I use that image and create an animation with it rotating 360° and looping? Or will that drain the battery?

something like this?:

```<code>- (void)webViewDidStartLoad:(UIWebView *)webView {
    //set up animation
    [self.view addSubview:self.loadingImage];
    //start animation
}

- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    //stop animation
    [self.loadingImage removeFromSuperview];
}
</code>```

What should I do?

Thanks in advance!

答:
it works in both SWITF 3 and 4

```<code>var activityIndicator = UIActivityIndicatorView()
var myView : UIView = UIView()

func viewDidLoad() {
    spinnerCreation()
}

func spinnerCreation() {

    activityIndicator.activityIndicatorViewStyle =  .whiteLarge

    let label = UILabel.init(frame: CGRect(x: 5, y: 60, width: 90, height: 20))
    label.textColor = UIColor.white
    label.font = UIFont.boldSystemFont(ofSize: 14.0)
    label.textAlignment = NSTextAlignment.center
    label.text = "Please wait...."

    myView.frame = CGRect(x: (UIScreen.main.bounds.size.width - 100)/2, y: (UIScreen.main.bounds.size.height - 100)/2, width: 100, height: 100)

    myView.backgroundColor = UIColor.init(white: 0.0, alpha: 0.7)
    myView.layer.cornerRadius = 5
    activityIndicator.center = CGPoint(x: myView.frame.size.width/2, y:  myView.frame.size.height/2 - 10)
    myView.addSubview(activityIndicator)
    myView.addSubview(label)

    myView.isHidden = true
    self.window?.addSubview(myView)
}

@IBAction func activityIndicatorStart(_ sender: Any) {
    myView.isHidden = false
    self.activityIndicator.startAnimating()
    self.view.isUserInteractionEnabled = false
    self.view.bringSubview(toFront: myView)
}

@IBAction func activityIndicatorStop(_ sender: Any)() {
    myView.isHidden = true
    self.activityIndicator.stopAnimating()
    self.view.isUserInteractionEnabled = true
}
</code>```

Title: Activity indicator with custom image

Body:
I am loading a UIWebView and in the meantime I wan't to show a blank page with this activity indicator spinning (siri activity indicator). From what I have understand you can not change the image, but can't I use that image and create an animation with it rotating 360° and looping? Or will that drain the battery?

something like this?:

- (void)webViewDidStartLoad:(UIWebView *)webView {
    //set up animation
    [self.view addSubview:self.loadingImage];
    //start animation
}

- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    //stop animation
    [self.loadingImage removeFromSuperview];
}

What should I do?

Thanks in advance!

Body:
it works in both SWITF 3 and 4

var activityIndicator = UIActivityIndicatorView()
var myView : UIView = UIView()

func viewDidLoad() {
    spinnerCreation()
}

func spinnerCreation() {

    activityIndicator.activityIndicatorViewStyle =  .whiteLarge

    let label = UILabel.init(frame: CGRect(x: 5, y: 60, width: 90, height: 20))
    label.textColor = UIColor.white
    label.font = UIFont.boldSystemFont(ofSize: 14.0)
    label.textAlignment = NSTextAlignment.center
    label.text = "Please wait...."

    myView.frame = CGRect(x: (UIScreen.main.bounds.size.width - 100)/2, y: (UIScreen.main.bounds.size.height - 100)/2, width: 100, height: 100)

    myView.backgroundColor = UIColor.init(white: 0.0, alpha: 0.7)
    myView.layer.cornerRadius = 5
    activityIndicator.center = CGPoint(x: myView.frame.size.width/2, y:  myView.frame.size.height/2 - 10)
    myView.addSubview(activityIndicator)
    myView.addSubview(label)

    myView.isHidden = true
    self.window?.addSubview(myView)
}

@IBAction func activityIndicatorStart(_ sender: Any) {
    myView.isHidden = false
    self.activityIndicator.startAnimating()
    self.view.isUserInteractionEnabled = false
    self.view.bringSubview(toFront: myView)
}

@IBAction func activityIndicatorStop(_ sender: Any)() {
    myView.isHidden = true
    self.activityIndicator.stopAnimating()
    self.view.isUserInteractionEnabled = true
}


问:
SwiftLint: Exclude file for specific rule
I'm trying to do something like this in my .swiftlint.yml file:

```<code>force_cast:
  severity: warning # explicitly
  excluded:
    - Dog.swift
</code>```

I have this code and I don't like the force_try warning I'm getting for it:

```<code>let cell = tableView.dequeueReusableCellWithIdentifier(Constants.dogViewCellReuseIdentifier,
                                                               forIndexPath: indexPath) as! DogViewCell
</code>```

I want to suppress the warning for this file by excluding this file from the rule.

Is there a way to do that ?

答:
I just get rid with  force_cast

Step 1:

```<code>cd path-to-your-project
</code>```

Step 2:

```<code>touch .swiftlint.yml
</code>```

Step 3:
open  .swiftlint.yml and add the rule

```<code>disabled_rules: # rule identifiers to exclude from running
 - force_cast
</code>```

Reference - https://github.com/realm/SwiftLint#disable-rules-in-code

Body:
I'm trying to do something like this in my .swiftlint.yml file:

force_cast:
  severity: warning # explicitly
  excluded:
    - Dog.swift

I have this code and I don't like the force_try warning I'm getting for it:

let cell = tableView.dequeueReusableCellWithIdentifier(Constants.dogViewCellReuseIdentifier,
                                                               forIndexPath: indexPath) as! DogViewCell

I want to suppress the warning for this file by excluding this file from the rule.

Is there a way to do that ?

Body:
I just get rid with  force_cast

Step 1:

cd path-to-your-project

Step 2:

touch .swiftlint.yml

Step 3:
open  .swiftlint.yml and add the rule

disabled_rules: # rule identifiers to exclude from running
 - force_cast

Reference - https://github.com/realm/SwiftLint#disable-rules-in-code


问:
python - how to reduce repetitive try/catch blocks?
I'm new to python and am writing a CLI wrapper for an internal tool using a python wrapper to a C++ API, and find myself constantly defining functions with identical try/catch blocks inside of them, with the only difference being the single call to the API.

For example...

```<code>px5 = PX5()

try:
  px5.connect()
except PX5Exception:
  for te in px5.errors:
    print(te)

def some_action(some_val):
  try:
    px5.run_method(some_val)
  except PX5Exception:
    for te in px5.errors:
      print(te)
    exit()

def some_other_action(some_val):
  try:
    return px5.run_some_other_method(some_val)
  except PX5Exception:
    for te in px5.errors:
      print(te)
    exit()
</code>```

Am I just way overdoing it with the try/catch blocks? Each individual command I need to run can easily have exceptions that I want to catch and display in a friendly manner vs. displaying the entire exception (basically, as the tool itself would display them if you weren't going through the API and using the CLI directly).

答:
One option would be to make a wrapper method:

```<code>def print_errors(func, *args, **kwargs):
    try:
        return func(*args, **kwargs)
    except PX5Exception:
        for te in px5.errors:
            print(te)
</code>```

Then instead of a try/except block each time, you'd just wrap:

```<code>print_errors(px5.run_some_other_method, some_val)
</code>```

Body:
I'm new to python and am writing a CLI wrapper for an internal tool using a python wrapper to a C++ API, and find myself constantly defining functions with identical try/catch blocks inside of them, with the only difference being the single call to the API.

For example...

px5 = PX5()

try:
  px5.connect()
except PX5Exception:
  for te in px5.errors:
    print(te)

def some_action(some_val):
  try:
    px5.run_method(some_val)
  except PX5Exception:
    for te in px5.errors:
      print(te)
    exit()

def some_other_action(some_val):
  try:
    return px5.run_some_other_method(some_val)
  except PX5Exception:
    for te in px5.errors:
      print(te)
    exit()

Am I just way overdoing it with the try/catch blocks? Each individual command I need to run can easily have exceptions that I want to catch and display in a friendly manner vs. displaying the entire exception (basically, as the tool itself would display them if you weren't going through the API and using the CLI directly).

Body:
One option would be to make a wrapper method:

def print_errors(func, *args, **kwargs):
    try:
        return func(*args, **kwargs)
    except PX5Exception:
        for te in px5.errors:
            print(te)

Then instead of a try/except block each time, you'd just wrap:

print_errors(px5.run_some_other_method, some_val)


问:
How to use multiple belongsTo in bookshelfjs?
i have one Table with name "class" and it has two foreign key attendance_id and syllabus_id, but using JOIN i can get only one foreign key value, here is my Model,

```<code>var AttendanceType = bookshelf.Model.extend({
   tableName: 'attendance_type',
});
var SyllabusName = bookshelf.Model.extend({
   tableName: 'syllabus_name',});
var Class = bookshelf.Model.extend({
   tableName: 'class',
AttendanceRef: function() {
   return this.belongsTo(AttendanceType);
},
SyllabusRef: function() {
   return this.belongsTo(SyllabusName);
}
});
module.exports = Class;
</code>```

HERE is my controller,

```<code>.fetchAll({ withRelated: ['AttendanceRef','SyllabusRef']})
</code>```

but i get only data from "attendance_type" Table.

答:
```<code>var AttendanceType = bookshelf.Model.extend({
   tableName: 'attendance_type',
});

var syllabusName = bookshelf.Model.extend({
   tableName: 'syllabus_name',
});

var Class = bookshelf.Model.extend({
   tableName: 'class',
   AttendanceRef: function() {
      return this.belongsTo(AttendanceType,'attendance_type_id');
   },
   SyllabusNameRef: function() {
      return this.belongsTo(syllabusName,'syllabus_id');
   }
});
module.exports = Class;
</code>```

here is my Controller.

```<code>.fetchAll({ withRelated: ['AttendanceRef','SyllabusNameRef']})
</code>```

Body:
i have one Table with name "class" and it has two foreign key attendance_id and syllabus_id, but using JOIN i can get only one foreign key value, here is my Model,

var AttendanceType = bookshelf.Model.extend({
   tableName: 'attendance_type',
});
var SyllabusName = bookshelf.Model.extend({
   tableName: 'syllabus_name',});
var Class = bookshelf.Model.extend({
   tableName: 'class',
AttendanceRef: function() {
   return this.belongsTo(AttendanceType);
},
SyllabusRef: function() {
   return this.belongsTo(SyllabusName);
}
});
module.exports = Class;

HERE is my controller,

.fetchAll({ withRelated: ['AttendanceRef','SyllabusRef']})

but i get only data from "attendance_type" Table.

Body:
var AttendanceType = bookshelf.Model.extend({
   tableName: 'attendance_type',
});

var syllabusName = bookshelf.Model.extend({
   tableName: 'syllabus_name',
});

var Class = bookshelf.Model.extend({
   tableName: 'class',
   AttendanceRef: function() {
      return this.belongsTo(AttendanceType,'attendance_type_id');
   },
   SyllabusNameRef: function() {
      return this.belongsTo(syllabusName,'syllabus_id');
   }
});
module.exports = Class;

here is my Controller.

.fetchAll({ withRelated: ['AttendanceRef','SyllabusNameRef']})


问:
What case is to be made when the Dividend and the Divisor have a value of zero?
I am getting a divided by zero error on my Query even after adding a case to make the values null. I think it may be because a.grosspcs is also a value of zero at the first of the month. However, I tried this case every which way for the last 2 hours and it keeps coming up. Am I missing something? Do I need the case in the CTE select statements also? If a.grosspcs is also a value of zero do I make 2 cases?I am still new to SQL so thanks in advance for any help. </p>

```<code>SELECT datename(MM,a.MonthDate) as Month

,Sum(a.ScrapPcs) / (Sum(a.GrossPcs)*1.00) As ScrapPct

,0.005 As ScrapTarget

,CASE
 WHEN Sum(a.ScrapPcs) / (Sum(a.GrossPcs)*1.00) <= 0.005 THEN 1
 WHEN Sum(a.ScrapPcs) / (Sum(a.GrossPcs)*1.00) >= 0.9*.005 THEN -1
 ELSE 0
 END
 AS Status

,Case
  when a.ScrapPcs=0 then null
Else a.GrossPcs / a.ScrapPcs
 end

FROM
(
SELECT DATEADD(month, DATEDIFF(month, 0, b.CreationProdDate), 0) As MonthDate
      ,Count(b.BOOKING_ID) As ScrapPcs
      , 0 As GrossPcs

FROM dbo.CPC_BOOKING b

WHERE b.CreationProdDate Between DATEADD(yy, DATEDIFF(yy, 0, GetDate()), 0) AND DateAdd("d", -1, GetDate())
AND CPC_Level_ID = 37

GROUP BY DATEADD(month, DATEDIFF(month, 0, b.CreationProdDate), 0)

UNION ALL

SELECT DATEADD(month, DATEDIFF(month, 0, n.date), 0) As MonthDate
      ,0 As ScrapPcs
      ,Sum(n.Processed) As GrossPcs

 FROM [NORIS].[dbo].[USC_CustomerCounts] n

WHERE n.date Between DATEADD(yy, DATEDIFF(yy, 0, GetDate()), 0) AND DateAdd("d", -1, GetDate())
and n.Customer = 'SGM'

GROUP BY DATEADD(month, DATEDIFF(month, 0, n.Date), 0)
) a

group by a.MonthDate,a.GrossPcs, a.ScrapPcs
</code>```

答:
wrap the divisors in a NULLIF() function

```<code>  SELECT 100 / NULLIF( val ,0)  AS foo
--             ^^^^^^^     ^^^
</code>```

In the first SELECT, I see four division operations

The fourth one, inside the CASE statement...  I don't think there's any guarantee that SQL Server won't evaluate the contents of the ELSE before it evaluates the condition in the WHEN.

change this, where the order of operations is not guaranteed:

```<code>  , Case
    when a.ScrapPcs=0 then null
    Else a.GrossPcs / a.ScrapPcs
    end
</code>```

to this

```<code>  , a.GrossPcs / NULLIF( a.ScrapPcs ,0)
    --           ^^^^^^^            ^^^
</code>```

so the NULLIF function is guaranteed to be evaluated before the division. (The division can't be performed before the value to divide by is known.)

Also, if there's no guarantee that Sum(a.GrossPcs) won't ever be zero, then
wrap that expression in a NULLIF where it's used as a divisor. (Or, wrap the whole divisor in a NULLIF.) I see three occurrences of that expression in the SELECT list which would have a "divide by zero".

```<code>    foo  / ( NULLIF( SUM(a.GrossPcs) ,0)*1.00 )
         --  ^^^^^^^                 ^^^
</code>```

Body:
I am getting a divided by zero error on my Query even after adding a case to make the values null. I think it may be because a.grosspcs is also a value of zero at the first of the month. However, I tried this case every which way for the last 2 hours and it keeps coming up. Am I missing something? Do I need the case in the CTE select statements also? If a.grosspcs is also a value of zero do I make 2 cases?I am still new to SQL so thanks in advance for any help.

SELECT datename(MM,a.MonthDate) as Month

,Sum(a.ScrapPcs) / (Sum(a.GrossPcs)*1.00) As ScrapPct

,0.005 As ScrapTarget

,CASE
 WHEN Sum(a.ScrapPcs) / (Sum(a.GrossPcs)*1.00) <= 0.005 THEN 1
 WHEN Sum(a.ScrapPcs) / (Sum(a.GrossPcs)*1.00) >= 0.9*.005 THEN -1
 ELSE 0
 END
 AS Status

,Case
  when a.ScrapPcs=0 then null
Else a.GrossPcs / a.ScrapPcs
 end

FROM
(
SELECT DATEADD(month, DATEDIFF(month, 0, b.CreationProdDate), 0) As MonthDate
      ,Count(b.BOOKING_ID) As ScrapPcs
      , 0 As GrossPcs

FROM dbo.CPC_BOOKING b

WHERE b.CreationProdDate Between DATEADD(yy, DATEDIFF(yy, 0, GetDate()), 0) AND DateAdd("d", -1, GetDate())
AND CPC_Level_ID = 37

GROUP BY DATEADD(month, DATEDIFF(month, 0, b.CreationProdDate), 0)

UNION ALL

SELECT DATEADD(month, DATEDIFF(month, 0, n.date), 0) As MonthDate
      ,0 As ScrapPcs
      ,Sum(n.Processed) As GrossPcs

 FROM [NORIS].[dbo].[USC_CustomerCounts] n

WHERE n.date Between DATEADD(yy, DATEDIFF(yy, 0, GetDate()), 0) AND DateAdd("d", -1, GetDate())
and n.Customer = 'SGM'

GROUP BY DATEADD(month, DATEDIFF(month, 0, n.Date), 0)
) a

group by a.MonthDate,a.GrossPcs, a.ScrapPcs

Body:
wrap the divisors in a NULLIF() function

  SELECT 100 / NULLIF( val ,0)  AS foo
--             ^^^^^^^     ^^^

In the first SELECT, I see four division operations

The fourth one, inside the CASE statement...  I don't think there's any guarantee that SQL Server won't evaluate the contents of the ELSE before it evaluates the condition in the WHEN.

change this, where the order of operations is not guaranteed:

  , Case
    when a.ScrapPcs=0 then null
    Else a.GrossPcs / a.ScrapPcs
    end

to this

  , a.GrossPcs / NULLIF( a.ScrapPcs ,0)
    --           ^^^^^^^            ^^^

so the NULLIF function is guaranteed to be evaluated before the division. (The division can't be performed before the value to divide by is known.)

Also, if there's no guarantee that Sum(a.GrossPcs) won't ever be zero, then
wrap that expression in a NULLIF where it's used as a divisor. (Or, wrap the whole divisor in a NULLIF.) I see three occurrences of that expression in the SELECT list which would have a "divide by zero".

    foo  / ( NULLIF( SUM(a.GrossPcs) ,0)*1.00 )
         --  ^^^^^^^                 ^^^


问:
How does a UInt128, relate to the 2 UInt64s it's comprised of?
If I have the following struct:

```<code>public struct UInt128 {
    internal var value: (upperBits: UInt64, lowerBits: UInt64)
}
</code>```

Imagine an initializer that creates a random number that fits into UInt128 and that number is sufficiently large such that it exceeds the value of one of the UInt64

Do the upper bits and the lower bits sum to be the total of the UInt128 or the memory managed in another way?

For the sake of working with small numbers, if the capacity of each UInt64 is 20, If the value of the UInt128 was 24, would the upper bits value be 20 and the lower bits value be 4?

答:
I think any answer you’re going to get is going to be a vast oversimplification given the question, but here’s my take:

The lower bits would represent the numbers 0 to 2^64-1 and the upper bits would represent the numbers 2^64 to 2^128-1

If you had two 64 bit numbers and wanted to add them together, you would shift the higher bits 64 bits to the left.

Does that help your understanding?

Body:
If I have the following struct:

public struct UInt128 {
    internal var value: (upperBits: UInt64, lowerBits: UInt64)
}

Imagine an initializer that creates a random number that fits into UInt128 and that number is sufficiently large such that it exceeds the value of one of the UInt64

Do the upper bits and the lower bits sum to be the total of the UInt128 or the memory managed in another way?

For the sake of working with small numbers, if the capacity of each UInt64 is 20, If the value of the UInt128 was 24, would the upper bits value be 20 and the lower bits value be 4?