问:
How can i run artisan commands in cpanel
How can i run these artisan commands in my application that is hosted in the net? Is there like a cmd in my cpanel where i can do these commands? Thanks in advance.

php artisan clear:cache

php artisan view:clear

答:
You could create a simple bash script called clear-cache.sh like this:

```<code>#!/bin/sh
PHP=/path/to/your/php-binary
PATH=/path/to/your-artisan-install

cd $PATH
$PHP artisan clear:cache
$PHP artisan view:clear
</code>```

Save the script and make it executable (chmod +x clear-cache.sh). Run it through a cronjob at specific intervals and configure the cron job to email you the output of those 2 commands. This way you'll get an email, every time the cron runs the script (basically the cron will automatically issue your two commands) and the ouput will be emailed to you.

Of course there are other methods as well like creating a php script and invoke it via web

Body:
You could create a simple bash script called clear-cache.sh like this:

#!/bin/sh
PHP=/path/to/your/php-binary
PATH=/path/to/your-artisan-install

cd $PATH
$PHP artisan clear:cache
$PHP artisan view:clear

Save the script and make it executable (chmod +x clear-cache.sh). Run it through a cronjob at specific intervals and configure the cron job to email you the output of those 2 commands. This way you'll get an email, every time the cron runs the script (basically the cron will automatically issue your two commands) and the ouput will be emailed to you.

Of course there are other methods as well like creating a php script and invoke it via web


来源: stackexchange

问:
Use generic class as generic type in Java
When I try to do this:

```<code>public <T> List<T> get(String key, Class<T> classType) {
        List<classType> list = new ArrayList<classType>();
    }
</code>```

Gives me unknown class error

答:
You actually don't need the classType parameter to create a List. Since your method is generic and has a generic parameter T, T is the type you should use!

```<code>List<T> list = new ArrayList<>();
</code>```

ContentLicense: CC BY-SA 3.0

Body:
When I try to do this:

public <T> List<T> get(String key, Class<T> classType) {
        List<classType> list = new ArrayList<classType>();
    }

Gives me unknown class error

Body:
You actually don't need the classType parameter to create a List. Since your method is generic and has a generic parameter T, T is the type you should use!

List<T> list = new ArrayList<>();


问:
how to delete email address from table in phpmyadmin
I wanted to delete the email address of the customer in phpmyadmin, using php and html. The delete button is working, but it doesn't delete the email address at all.

I'm still new in learning php language. So, there might be some parts I might have done wrong.

I made 3 pages; account.php, deleteemail.php and delete.php

This is the php code for account.php

```<code><?php

        mysql_connect("localhost", "root","") or die(mysql_error());
        mysql_select_db("eib_clicks") or die("Cannot connect to database");
        $query = mysql_query("SELECT * FROM customer_ai WHERE username='$user' LIMIT 1");
        while($row = mysql_fetch_array($query))
        {
            Print "<tr>";

                Print '<td align="center">'. $row['username'] . "</td>";
                Print '<td align="center">'. $row['name'] . "</td>";
                Print '<td align="center">'. $row['address'] . "</td>";
                Print '<td align="center">'. $row['secondaddress'] . "</td>";
                Print '<td align="center"><a href="addaddress.php?username='. $row['username'] .'">add</a> </td>';
                Print '<td align="center">'. $row['email'] . "</td>";
                Print '<td align="center"><a href="editemail.php?username='. $row['username'] .'">edit</a> </td>';
                Print '<td align="center"><a href="deleteemail.php?username='. $row['username'] .'">delete</a> </td>';
                Print '<td align="center">'. $row['type'] . "</td>";
                Print '<td align="center">'. $row['public'] . "</td>";
                Print '<td align="center"><a href="editpublic.php?username='. $row['username'] .'">edit</a> </td>';
            Print "</tr>";
        }
    ?>
</code>```

This one works just fine.

Php code for deleteemail.php

```<code><?php
session_start();
if($_SESSION['user']){
}
else{
    header("location:account.php");
}
$user = $_SESSION['user'];
$id_exists = false;
?>
</code>```

Second part of the code;

```<code><?php

                mysql_connect("localhost", "root", "") or die(mysql_error());
                mysql_select_db("eib_clicks") or die("Cannot connect to database");
                $query = mysql_query("Select * from customer_ai Where username='$user'");
                $count = mysql_num_rows($query);
                if($count > 0)
                {
                    while($row = mysql_fetch_array($query))
                    {
                        Print "<tr>";
                            Print '<td align="center">'. $row['email'] . "</td>";

                        Print "</tr>";
                    }
                }

            ?>
</code>```

Third part of the code;

```<code><?php

        Print '
        <a href="delete.php" class="btn btn-sm btn-danger" role="button" onclick="myFunction('.$row['username'] .')">Delete</a>

        ';

        ?>
</code>```

I add script in this page too;

```<code><script>
    function myFunction(username)
    {
    var r=confirm("Are you sure you want to delete this email?");
    if(r==true)
        {
            window.location.assign("deleteemail.php?username=" + username);
        }
    }
</script>
</code>```

Lastly php code for delete.php

```<code><?php
    session_start();
    if($_SESSION['user']){
    }
    else{
        header("location:homepage.php");
    }

    if($_SERVER['REQUEST_METHOD'] == "GET")
    {
        mysql_connect("localhost", "root","") or die(mysql_error());
        mysql_select_db("eib_clicks") or die("Cannot connect to database");

        mysql_query("DELETE FROM account_ai WHERE $email=['email']");

        header("location: account.php");
    }
?>
</code>```

I tried everything on the delete.php but nothing works. The rest of the codes works fine. I used $row['id'] but it deletes the whole row. I only wanted to delete the email address not the whole row. Please help me.

This is how my customer_ai table looks like;

table for customer_ai

答:
DELETE deletes a complete row. Instead use UPDATE and set the column to NULL.

```<code>UPDATE account_ai SET email = NULL WHERE username = $username
</code>```

If the $username is a user-supplied value, be sure to escape it, otherwise you will risk a SQL injection.

Be aware that mysql_connect is deprecated, see http://php.net/manual/en/function.mysql-connect.php. Use MySQLi or PDO instead. Maybe you take a look at this PDO tutorial. Pay attention to the Prepared statements. Protection from SQL injections chapter.

Body:
I wanted to delete the email address of the customer in phpmyadmin, using php and html. The delete button is working, but it doesn't delete the email address at all.

I'm still new in learning php language. So, there might be some parts I might have done wrong.

I made 3 pages; account.php, deleteemail.php and delete.php

This is the php code for account.php

<?php

        mysql_connect("localhost", "root","") or die(mysql_error());
        mysql_select_db("eib_clicks") or die("Cannot connect to database");
        $query = mysql_query("SELECT * FROM customer_ai WHERE username='$user' LIMIT 1");
        while($row = mysql_fetch_array($query))
        {
            Print "
";

                Print ''. $row['username'] . "	";
                Print ''. $row['name'] . "	";
                Print ''. $row['address'] . "	";
                Print ''. $row['secondaddress'] . "	";
                Print 'add 	';
                Print ''. $row['email'] . "	";
                Print 'edit 	';
                Print 'delete 	';
                Print ''. $row['type'] . "	";
                Print ''. $row['public'] . "	";
                Print 'edit 	';
            Print "
";
        }
    ?>

This one works just fine.

Php code for deleteemail.php

<?php
session_start();
if($_SESSION['user']){
}
else{
    header("location:account.php");
}
$user = $_SESSION['user'];
$id_exists = false;
?>

Second part of the code;

<?php

                mysql_connect("localhost", "root", "") or die(mysql_error());
                mysql_select_db("eib_clicks") or die("Cannot connect to database");
                $query = mysql_query("Select * from customer_ai Where username='$user'");
                $count = mysql_num_rows($query);
                if($count > 0)
                {
                    while($row = mysql_fetch_array($query))
                    {
                        Print "
";
                            Print ''. $row['email'] . "	";

                        Print "
";
                    }
                }

            ?>

Third part of the code;

<?php

        Print '
        Delete

        ';

        ?>

I add script in this page too;

Lastly php code for delete.php

<?php
    session_start();
    if($_SESSION['user']){
    }
    else{
        header("location:homepage.php");
    }

    if($_SERVER['REQUEST_METHOD'] == "GET")
    {
        mysql_connect("localhost", "root","") or die(mysql_error());
        mysql_select_db("eib_clicks") or die("Cannot connect to database");

        mysql_query("DELETE FROM account_ai WHERE $email=['email']");

        header("location: account.php");
    }
?>

I tried everything on the delete.php but nothing works. The rest of the codes works fine. I used $row['id'] but it deletes the whole row. I only wanted to delete the email address not the whole row. Please help me.

This is how my customer_ai table looks like;

table for customer_ai

Body:
DELETE deletes a complete row. Instead use UPDATE and set the column to NULL.

UPDATE account_ai SET email = NULL WHERE username = $username

If the $username is a user-supplied value, be sure to escape it, otherwise you will risk a SQL injection.

Be aware that mysql_connect is deprecated, see http://php.net/manual/en/function.mysql-connect.php. Use MySQLi or PDO instead. Maybe you take a look at this PDO tutorial. Pay attention to the Prepared statements. Protection from SQL injections chapter.


问:
I installed Android Studio 3.0.1 and created a blank project. I can't proceed because I receive the following:
Failed to resolve: junit:junit:4.12

I have attempted numerous solutions from the previous time this question was asked but none of them seem to be working. I tried deleting the entire line Failed to resolve: junit:junit:4.12.

my build.gradle top file:

```<code>// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
    repositories {
        // Gradle 4.1 and higher include support for Google's Maven repo using
        // the google() method. And you need to include this repo to download
        // Android plugin 3.0.0 or higher.
        google()
        maven { url "https://maven.google.com" }
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.1'
    }
}
</code>```

my module app build.gradle

```<code>apply plugin: 'com.android.application'

repositories {
    maven { url "https://maven.google.com" }
    google()
}

android {
    compileSdkVersion 26
    buildToolsVersion "26.0.2"
    defaultConfig {
        applicationId "ru.foodrobot.myapplication"
        minSdkVersion 17
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        //google()
        //jcenter()
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:26.1.0'
    implementation 'com.android.support.constraint:constraint-layout:1.0.2'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.1'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
}
</code>```

finally  this is what I have in my build.gradle app file:

```<code>apply plugin: 'com.android.application'

repositories {
    maven { url 'http://repo1.maven.org/maven2' }
    jcenter { url "http://jcenter.bintray.com/" }
}

android {
    compileSdkVersion 26
    buildToolsVersion "26.0.1"

    defaultConfig {
        applicationId "com.example.application"
        minSdkVersion 15
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
    }
    buildTypes {

        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.1.1'
    compile 'com.android.support:design:23.1.1'
}
</code>```

答:
I was able to compile your gradle by this change in your module app build.gradle

```<code>repositories {
    maven { url "https://maven.google.com" }
    google()
    mavenCentral()
}
</code>```

instead of

```<code>repositories {
    maven { url "https://maven.google.com" }
    google()
}
</code>```

Body:
Failed to resolve: junit:junit:4.12

I have attempted numerous solutions from the previous time this question was asked but none of them seem to be working. I tried deleting the entire line Failed to resolve: junit:junit:4.12.

my build.gradle top file:

// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
    repositories {
        // Gradle 4.1 and higher include support for Google's Maven repo using
        // the google() method. And you need to include this repo to download
        // Android plugin 3.0.0 or higher.
        google()
        maven { url "https://maven.google.com" }
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.1'
    }
}

my module app build.gradle

apply plugin: 'com.android.application'

repositories {
    maven { url "https://maven.google.com" }
    google()
}

android {
    compileSdkVersion 26
    buildToolsVersion "26.0.2"
    defaultConfig {
        applicationId "ru.foodrobot.myapplication"
        minSdkVersion 17
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        //google()
        //jcenter()
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:26.1.0'
    implementation 'com.android.support.constraint:constraint-layout:1.0.2'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.1'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
}

finally  this is what I have in my build.gradle app file:

apply plugin: 'com.android.application'

repositories {
    maven { url 'http://repo1.maven.org/maven2' }
    jcenter { url "http://jcenter.bintray.com/" }
}

android {
    compileSdkVersion 26
    buildToolsVersion "26.0.1"

    defaultConfig {
        applicationId "com.example.application"
        minSdkVersion 15
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
    }
    buildTypes {

        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.1.1'
    compile 'com.android.support:design:23.1.1'
}

Body:
I was able to compile your gradle by this change in your module app build.gradle

repositories {
    maven { url "https://maven.google.com" }
    google()
    mavenCentral()
}

instead of

repositories {
    maven { url "https://maven.google.com" }
    google()
}


问:
How can i remove currency sign on amount before uploading to database?
Before it get's inserted to sql database the currency sign on amount is already removed.</p>

答:
you can get your string replaced by using str_replace()

```<code>$string = str_replace( $search_for_sign, $replace_the_sign_with_nothing, $in_your_string );
</code>```

For Example:

```<code>$string_with_target_sign = "$ value";
$formatted_string = str_replace("$" , "" , $string_with_target_sign);
</code>```

Body:
you can get your string replaced by using str_replace()

$string = str_replace( $search_for_sign, $replace_the_sign_with_nothing, $in_your_string );

For Example:

$string_with_target_sign = "$ value";
$formatted_string = str_replace("$" , "" , $string_with_target_sign);


问:
How to achieve a responsive layout for small and big screen sizes?
I have a problem with proper scaling the layout.

Here is my layout:

```<code><FrameLayout
    android:id="@+id/content_frame"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="1"
    android:layout_marginTop="@dimen/margin_large"
    android:layout_marginLeft="@dimen/margin_xlarge"
    android:layout_marginRight="@dimen/margin_xlarge">

    <include
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        layout="@layout/commissioning_progress_component" />
    <com.app.widget.StepProgressArrow
        android:id="@+id/progress_arrow_asset_to_sync"

        android:layout_width="match_parent"
        android:layout_height="@dimen/progress_arrow_size"

        app:startColor="@color/circular_progress_middle_color"
        app:endColor="@color/circular_progress_end_color"
        android:gravity="right"/>

    <com.app.widget.StepProgressArrow
        android:id="@+id/progress_arrow_sync_to_params"

        android:layout_width="@dimen/progress_arrow_size"
        android:layout_height="match_parent"

        app:startColor="@color/circular_progress_middle_color"
        app:endColor="@color/circular_progress_end_color"
        android:gravity="bottom"  />

    <com.app.widget.StepProgressArrow
        android:id="@+id/progress_arrow_params_to_completed"
        android:layout_width="match_parent"
        android:layout_height="@dimen/progress_arrow_size"

        app:startColor="@color/circular_progress_middle_color"
        app:endColor="@color/circular_progress_end_color"
        android:gravity="left" />

    <TextView
        android:id="@+id/progress_text_stage_params"

        android:layout_width="wrap_content"
        android:layout_height="wrap_content"

        style="@style/AppWidget.Text.Emphasized"
        android:gravity="center"
        android:textColor="@color/circular_progress_middle_color"
        android:text="@string/msg_in_store_commissioning_stage_params" />

</FrameLayout>

<FrameLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <TextView
            android:id="@+id/commissioning_upload_info"

            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="@dimen/margin_normal"
            android:layout_marginRight="@dimen/margin_normal"
            android:layout_marginTop="@dimen/margin_normal"

            android:gravity="center"
            style="@style/AppWidget.Text.Gray.XSmall"
            android:text="@string/msg_commissioning_cloud_upload_info"
            android:visibility="gone"
            tools:visibility="visible" />

        <Button
            android:id="@+id/button_back_to_device_list"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="@dimen/margin_normal"
            android:layout_marginRight="@dimen/margin_normal"
            android:layout_marginTop="@dimen/margin_small"
            android:layout_marginBottom="@dimen/margin_small"

            android:text="@string/button_back_to_device_list"
            android:visibility="gone"
            tools:visibility="visible"
            style="@style/AppWidget.Button"/>

        <TextView
            android:id="@+id/cloning_finished_info"

            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="@dimen/margin_normal"
            android:layout_marginRight="@dimen/margin_normal"
            android:layout_marginTop="@dimen/margin_normal"

            style="@style/AppWidget.Text.Gray.Medium"
            android:text="@string/new_controller_installed"
            android:visibility="gone"
            tools:visibility="visible" />

        <Button
            android:id="@+id/button_continue"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="@dimen/margin_normal"
            android:layout_marginRight="@dimen/margin_normal"
            android:layout_marginTop="@dimen/margin_small"
            android:layout_marginBottom="@dimen/margin_small"
            android:layout_gravity="right"

            android:paddingLeft="@dimen/margin_normal"
            android:paddingRight="@dimen/margin_normal"
            android:text="@string/button_continue"
            android:visibility="gone"
            tools:visibility="visible"
            style="@style/AppWidget.Button.Green"/>

    </LinearLayout>

    <TextView
        android:id="@+id/sync_time_left_text"

        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_margin="@dimen/margin_small"

        style="@style/AppWidget.Text.Gray.Medium"
        android:gravity="center"
        android:visibility="gone"
        android:padding="@dimen/margin_small"
        android:background="@drawable/box"

        tools:visibility="visible"
        tools:text="Time left 5s"/>

</FrameLayout>
</code>```

And here is the layout that i am including:

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">

<com.app.widget.CircularColorProgressView
    android:id="@+id/progress_stage_asset"
    android:layout_width="@dimen/circular_color_progress_size_small"
    android:layout_height="@dimen/circular_color_progress_size_small"
    android:layout_marginStart="24dp"
    app:hideText="true"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:skipStartColor="true" />

<TextView
    android:id="@+id/progress_text_stage_asset"

    style="@style/AppWidget.Text.Emphasized"
    android:layout_width="wrap_content"

    android:layout_height="wrap_content"
    android:layout_marginStart="22dp"
    android:layout_marginTop="12dp"

    android:gravity="center"
    android:text="@string/msg_in_store_commissioning_stage_asset"
    android:textColor="@color/circular_progress_middle_color"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/progress_stage_asset"
    app:layout_gravity="center_horizontal"
    />

<com.app.widget.CircularColorProgressView
    android:id="@+id/progress_stage_sync"
    android:layout_width="@dimen/circular_color_progress_size_small"
    android:layout_height="@dimen/circular_color_progress_size_small"
    android:layout_marginEnd="10dp"

    app:hideText="true"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:skipStartColor="true" />

<TextView
    android:id="@+id/progress_text_stage_sync"
    style="@style/AppWidget.Text.Emphasized"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="@dimen/margin_small"
    android:gravity="center"
    android:text="@string/msg_in_store_commissioning_stage_sync"
    android:textColor="@color/circular_progress_middle_color"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/progress_stage_sync"
    app:layout_gravity="center_horizontal" />

<com.app.widget.CircularColorProgressView
    android:id="@+id/progress_stage_completed"

    android:layout_width="@dimen/circular_color_progress_size_medium"
    android:layout_height="@dimen/circular_color_progress_size_medium"

    android:layout_marginBottom="48dp"

    app:hideText="true"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_gravity="center_horizontal"
    app:skipStartColor="true" />

<TextView
    android:id="@+id/progress_text_stage_completed"

    style="@style/AppWidget.Text.Emphasized"
    android:layout_width="wrap_content"

    android:layout_height="wrap_content"

    android:layout_marginStart="3dp"
    android:layout_marginTop="@dimen/margin_small"
    android:gravity="center"
    android:text="@string/msg_in_store_commissioning_stage_completed"
    android:textColor="@color/circular_progress_middle_color"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/progress_stage_completed"
    app:layout_gravity="center_horizontal" />

<com.app.widget.CircularColorProgressView
    android:id="@+id/progress_stage_params"
    android:layout_width="@dimen/circular_color_progress_size_small"
    android:layout_height="@dimen/circular_color_progress_size_small"
    android:layout_marginBottom="72dp"
    android:layout_marginEnd="10dp"
    app:hideText="true"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:skipStartColor="true" />
</code>```

So here is what that include layout looks like, it scales fine for every screen(from 3.7 to 6.0):

And here is the problem with scaling the wholelayout.
This is how it looks for screen 6.0:

And here is the issue with screen 3.7

So how to properly scale my layout for this case?

答: have you tried using relative layouts to position each item relative to another.Maybe thatll help.Enclose all your layouts in a relative layout and use aspects such as to_right of etc.Always works for me</p>

Body:
I have a problem with proper scaling the layout.

Here is my layout:

<FrameLayout
    android:id="@+id/content_frame"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="1"
    android:layout_marginTop="@dimen/margin_large"
    android:layout_marginLeft="@dimen/margin_xlarge"
    android:layout_marginRight="@dimen/margin_xlarge">

    <include
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        layout="@layout/commissioning_progress_component" />
    <com.app.widget.StepProgressArrow
        android:id="@+id/progress_arrow_asset_to_sync"

        android:layout_width="match_parent"
        android:layout_height="@dimen/progress_arrow_size"

        app:startColor="@color/circular_progress_middle_color"
        app:endColor="@color/circular_progress_end_color"
        android:gravity="right"/>

    <com.app.widget.StepProgressArrow
        android:id="@+id/progress_arrow_sync_to_params"

        android:layout_width="@dimen/progress_arrow_size"
        android:layout_height="match_parent"

        app:startColor="@color/circular_progress_middle_color"
        app:endColor="@color/circular_progress_end_color"
        android:gravity="bottom"  />

    <com.app.widget.StepProgressArrow
        android:id="@+id/progress_arrow_params_to_completed"
        android:layout_width="match_parent"
        android:layout_height="@dimen/progress_arrow_size"

        app:startColor="@color/circular_progress_middle_color"
        app:endColor="@color/circular_progress_end_color"
        android:gravity="left" />

    <TextView
        android:id="@+id/progress_text_stage_params"

        android:layout_width="wrap_content"
        android:layout_height="wrap_content"

        style="@style/AppWidget.Text.Emphasized"
        android:gravity="center"
        android:textColor="@color/circular_progress_middle_color"
        android:text="@string/msg_in_store_commissioning_stage_params" />

</FrameLayout>

<FrameLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <TextView
            android:id="@+id/commissioning_upload_info"

            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="@dimen/margin_normal"
            android:layout_marginRight="@dimen/margin_normal"
            android:layout_marginTop="@dimen/margin_normal"

            android:gravity="center"
            style="@style/AppWidget.Text.Gray.XSmall"
            android:text="@string/msg_commissioning_cloud_upload_info"
            android:visibility="gone"
            tools:visibility="visible" />

        <Button
            android:id="@+id/button_back_to_device_list"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="@dimen/margin_normal"
            android:layout_marginRight="@dimen/margin_normal"
            android:layout_marginTop="@dimen/margin_small"
            android:layout_marginBottom="@dimen/margin_small"

            android:text="@string/button_back_to_device_list"
            android:visibility="gone"
            tools:visibility="visible"
            style="@style/AppWidget.Button"/>

        <TextView
            android:id="@+id/cloning_finished_info"

            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="@dimen/margin_normal"
            android:layout_marginRight="@dimen/margin_normal"
            android:layout_marginTop="@dimen/margin_normal"

            style="@style/AppWidget.Text.Gray.Medium"
            android:text="@string/new_controller_installed"
            android:visibility="gone"
            tools:visibility="visible" />

        <Button
            android:id="@+id/button_continue"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="@dimen/margin_normal"
            android:layout_marginRight="@dimen/margin_normal"
            android:layout_marginTop="@dimen/margin_small"
            android:layout_marginBottom="@dimen/margin_small"
            android:layout_gravity="right"

            android:paddingLeft="@dimen/margin_normal"
            android:paddingRight="@dimen/margin_normal"
            android:text="@string/button_continue"
            android:visibility="gone"
            tools:visibility="visible"
            style="@style/AppWidget.Button.Green"/>

    </LinearLayout>

    <TextView
        android:id="@+id/sync_time_left_text"

        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_margin="@dimen/margin_small"

        style="@style/AppWidget.Text.Gray.Medium"
        android:gravity="center"
        android:visibility="gone"
        android:padding="@dimen/margin_small"
        android:background="@drawable/box"

        tools:visibility="visible"
        tools:text="Time left 5s"/>

</FrameLayout>

And here is the layout that i am including:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">

<com.app.widget.CircularColorProgressView
    android:id="@+id/progress_stage_asset"
    android:layout_width="@dimen/circular_color_progress_size_small"
    android:layout_height="@dimen/circular_color_progress_size_small"
    android:layout_marginStart="24dp"
    app:hideText="true"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:skipStartColor="true" />

<TextView
    android:id="@+id/progress_text_stage_asset"

    style="@style/AppWidget.Text.Emphasized"
    android:layout_width="wrap_content"

    android:layout_height="wrap_content"
    android:layout_marginStart="22dp"
    android:layout_marginTop="12dp"

    android:gravity="center"
    android:text="@string/msg_in_store_commissioning_stage_asset"
    android:textColor="@color/circular_progress_middle_color"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/progress_stage_asset"
    app:layout_gravity="center_horizontal"
    />

<com.app.widget.CircularColorProgressView
    android:id="@+id/progress_stage_sync"
    android:layout_width="@dimen/circular_color_progress_size_small"
    android:layout_height="@dimen/circular_color_progress_size_small"
    android:layout_marginEnd="10dp"

    app:hideText="true"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:skipStartColor="true" />

<TextView
    android:id="@+id/progress_text_stage_sync"
    style="@style/AppWidget.Text.Emphasized"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="@dimen/margin_small"
    android:gravity="center"
    android:text="@string/msg_in_store_commissioning_stage_sync"
    android:textColor="@color/circular_progress_middle_color"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/progress_stage_sync"
    app:layout_gravity="center_horizontal" />

<com.app.widget.CircularColorProgressView
    android:id="@+id/progress_stage_completed"

    android:layout_width="@dimen/circular_color_progress_size_medium"
    android:layout_height="@dimen/circular_color_progress_size_medium"

    android:layout_marginBottom="48dp"

    app:hideText="true"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_gravity="center_horizontal"
    app:skipStartColor="true" />

<TextView
    android:id="@+id/progress_text_stage_completed"

    style="@style/AppWidget.Text.Emphasized"
    android:layout_width="wrap_content"

    android:layout_height="wrap_content"

    android:layout_marginStart="3dp"
    android:layout_marginTop="@dimen/margin_small"
    android:gravity="center"
    android:text="@string/msg_in_store_commissioning_stage_completed"
    android:textColor="@color/circular_progress_middle_color"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/progress_stage_completed"
    app:layout_gravity="center_horizontal" />

<com.app.widget.CircularColorProgressView
    android:id="@+id/progress_stage_params"
    android:layout_width="@dimen/circular_color_progress_size_small"
    android:layout_height="@dimen/circular_color_progress_size_small"
    android:layout_marginBottom="72dp"
    android:layout_marginEnd="10dp"
    app:hideText="true"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:skipStartColor="true" />

So here is what that include layout looks like, it scales fine for every screen(from 3.7 to 6.0):

And here is the problem with scaling the wholelayout.
This is how it looks for screen 6.0:

And here is the issue with screen 3.7

So how to properly scale my layout for this case?


问:
Why seekbar tick marker shown in front of thumb?
My seekBar style is android Widget.AppCompat.SeekBar.Discrete.
I have my own tickMarker but as you can see it shown in front of thumb marker, but I don want to see ticks behind of thumb.

what I want:

and what I have :

my XML:

```<code> <android.support.v7.widget.AppCompatSeekBar
    style="@style/seekbarStyle"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:max="4"
    android:padding="4dp"
    android:progress="0"/>
</code>```

my style:

```<code><style name="seekbarStyle" parent="Widget.AppCompat.SeekBar.Discrete">
    <item name="tickMark">@drawable/seekbar_tickmark</item>
    <item name="android:thumb">@drawable/circle</item>
</style>
</code>```

答:
This is a bug of AppCompatSeekBar.
I resolved this problem with a custom Class that extends AppCompatSeekBar:

```<code>public class CustomSeekBar extends AppCompatSeekBar {

    private Drawable mTickMark;

    public CustomSeekBar(Context context) {
        this(context, null);
    }

    public CustomSeekBar(Context context, AttributeSet attrs) {
        this(context, attrs, android.support.v7.appcompat.R.attr.seekBarStyle);
    }

    public CustomSeekBar(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        applyAttributes(attrs, defStyleAttr);
    }

    private void applyAttributes(AttributeSet rawAttrs, int defStyleAttr)
    {
        TypedArray attrs = getContext().obtainStyledAttributes(rawAttrs, R.styleable.CustomSeekBar, defStyleAttr, 0);
        try {
            mTickMark = attrs.getDrawable(R.styleable.CustomSeekBar_tickMarkFixed);
        } finally {
            attrs.recycle();
        }
    }

    @Override
    protected synchronized void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        drawTickMarks(canvas);
    }

    @Override
    public int getThumbOffset() {
        return super.getThumbOffset();
    }

    void drawTickMarks(Canvas canvas) {
        if (mTickMark != null) {
            final int count = getMax();
            if (count > 1) {
                final int w = mTickMark.getIntrinsicWidth();
                final int h = mTickMark.getIntrinsicHeight();
                final int halfThumbW = getThumb().getIntrinsicWidth() / 2;
                final int halfW = w >= 0 ? w / 2 : 1;
                final int halfH = h >= 0 ? h / 2 : 1;
                mTickMark.setBounds(-halfW, -halfH, halfW, halfH);
                final float spacing = (getWidth() - getPaddingLeft() - getPaddingRight() + getThumbOffset() * 2 - halfThumbW * 2) / (float) count;
                final int saveCount = canvas.save();
                canvas.translate(getPaddingLeft() - getThumbOffset() + halfThumbW, getHeight() / 2);
                for (int i = 0; i <= count; i++) {
                    if(i!=getProgress())
                        mTickMark.draw(canvas);
                    canvas.translate(spacing, 0);
                }
                canvas.restoreToCount(saveCount);
            }
        }
    }
}
</code>```

with the attrs.xml:

```<code><resources>
    <declare-styleable name="CustomSeekBar">
        <attr name="tickMarkFixed" format="reference"/>
    </declare-styleable>
</resources>
</code>```

and in layout you must use tickMarkFixed instead of tickMark.

Body:
My seekBar style is android Widget.AppCompat.SeekBar.Discrete.
I have my own tickMarker but as you can see it shown in front of thumb marker, but I don want to see ticks behind of thumb.

what I want:

and what I have :

my XML:

 <android.support.v7.widget.AppCompatSeekBar
    style="@style/seekbarStyle"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:max="4"
    android:padding="4dp"
    android:progress="0"/>

my style:

Body:
This is a bug of AppCompatSeekBar.
I resolved this problem with a custom Class that extends AppCompatSeekBar:

public class CustomSeekBar extends AppCompatSeekBar {

    private Drawable mTickMark;

    public CustomSeekBar(Context context) {
        this(context, null);
    }

    public CustomSeekBar(Context context, AttributeSet attrs) {
        this(context, attrs, android.support.v7.appcompat.R.attr.seekBarStyle);
    }

    public CustomSeekBar(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        applyAttributes(attrs, defStyleAttr);
    }

    private void applyAttributes(AttributeSet rawAttrs, int defStyleAttr)
    {
        TypedArray attrs = getContext().obtainStyledAttributes(rawAttrs, R.styleable.CustomSeekBar, defStyleAttr, 0);
        try {
            mTickMark = attrs.getDrawable(R.styleable.CustomSeekBar_tickMarkFixed);
        } finally {
            attrs.recycle();
        }
    }

    @Override
    protected synchronized void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        drawTickMarks(canvas);
    }

    @Override
    public int getThumbOffset() {
        return super.getThumbOffset();
    }

    void drawTickMarks(Canvas canvas) {
        if (mTickMark != null) {
            final int count = getMax();
            if (count > 1) {
                final int w = mTickMark.getIntrinsicWidth();
                final int h = mTickMark.getIntrinsicHeight();
                final int halfThumbW = getThumb().getIntrinsicWidth() / 2;
                final int halfW = w >= 0 ? w / 2 : 1;
                final int halfH = h >= 0 ? h / 2 : 1;
                mTickMark.setBounds(-halfW, -halfH, halfW, halfH);
                final float spacing = (getWidth() - getPaddingLeft() - getPaddingRight() + getThumbOffset() * 2 - halfThumbW * 2) / (float) count;
                final int saveCount = canvas.save();
                canvas.translate(getPaddingLeft() - getThumbOffset() + halfThumbW, getHeight() / 2);
                for (int i = 0; i <= count; i++) {
                    if(i!=getProgress())
                        mTickMark.draw(canvas);
                    canvas.translate(spacing, 0);
                }
                canvas.restoreToCount(saveCount);
            }
        }
    }
}

with the attrs.xml:

<resources>
    <declare-styleable name="CustomSeekBar">
        <attr name="tickMarkFixed" format="reference"/>
    </declare-styleable>
</resources>

and in layout you must use tickMarkFixed instead of tickMark.


问:
example of closure with setTimeOut()

Can someone explain to me why the code does not act as expected?

WHy would this happen? I know it is due to "scoping", but I don't know the exact mechanism.

"Considering the above code, the console will display four identical messages "The value undefined is at index: 4". "

```<code>const arr = [10, 12, 15, 21];
for (var i = 0; i < arr.length; i++) {
      setTimeout(function() {
           console.log(`The value ${arr[i]} is at index: ${i}`);
      }, (i+1) * 1000);
}
</code>```

declare i using 'let' solves the problem;

putting setTimeOut() into IIFE also solves the problem, but I could not understand why.

答: let allows you to declare variables that are limited in scope to the block, statement, or expression on which it is used. This is unlike the var keyword, which defines a variable globally, or locally to an entire function regardless of block scope.

Title: example of closure with setTimeOut()

Body:
Can someone explain to me why the code does not act as expected?

WHy would this happen? I know it is due to "scoping", but I don't know the exact mechanism.

"Considering the above code, the console will display four identical messages "The value undefined is at index: 4". "

const arr = [10, 12, 15, 21];
for (var i = 0; i < arr.length; i++) {
      setTimeout(function() {
           console.log(`The value ${arr[i]} is at index: ${i}`);
      }, (i+1) * 1000);
}

declare i using 'let' solves the problem;

putting setTimeOut() into IIFE also solves the problem, but I could not understand why.


问:
Forwarding references for non-reference types
```<code> template<typename T>
 void F(T&& x) {}
</code>```

If we call it with argument of type int& everything is clear - reference collapsing takes place and we still have lvalue-reference. But what happens if we call it with, for example, int argument. My thoughts: we have deduced type T=int, decorate it with rvalue-reference, so F takes int&& argument and calling it with int type will result in error. But in real F takes such argument as lvalue-reference. Where does lvalue-reference come from? What rules did compiler apply to get int& from int?

答:
Forwarding references deduce lvalue reference for lvalues and rvalue reference for rvalues. For example, even for lvalue of type int&& it will still deduce int& (as it would for lvalue of type int), likewise, for rvalues of type int or int&& it will deduce int&&:

```<code>template<typename T>
class show;

template<typename T>
void F(T&& x)
{ show<decltype(x)>();}

int main() {
    int&& x = 5;
    F(x);
}
</code>```

```<code>main.cpp:6:3: error: implicit instantiation of undefined template 'show<int &>'
</code>```

```<code>int main() {
    F(5);
}
</code>```

```<code>main.cpp:6:3: error: implicit instantiation of undefined template 'show<int &&>'
</code>```

```<code>int main() {
    int x = 5;
    F(x);
}
</code>```

```<code>main.cpp:6:3: error: implicit instantiation of undefined template 'show<int &>'
</code>```

```<code>int main() {
    F([]()->int{return 5;}());
}
</code>```

```<code>main.cpp:6:3: error: implicit instantiation of undefined template 'show<int &&>'
</code>```

Body:
 template<typename T>
 void F(T&& x) {}

If we call it with argument of type int& everything is clear - reference collapsing takes place and we still have lvalue-reference. But what happens if we call it with, for example, int argument. My thoughts: we have deduced type T=int, decorate it with rvalue-reference, so F takes int&& argument and calling it with int type will result in error. But in real F takes such argument as lvalue-reference. Where does lvalue-reference come from? What rules did compiler apply to get int& from int?

Body:
Forwarding references deduce lvalue reference for lvalues and rvalue reference for rvalues. For example, even for lvalue of type int&& it will still deduce int& (as it would for lvalue of type int), likewise, for rvalues of type int or int&& it will deduce int&&:

template<typename T>
class show;

template<typename T>
void F(T&& x)
{ show<decltype(x)>();}

int main() {
    int&& x = 5;
    F(x);
}

main.cpp:6:3: error: implicit instantiation of undefined template 'show<int &>'

int main() {
    F(5);
}

main.cpp:6:3: error: implicit instantiation of undefined template 'show<int &&>'

int main() {
    int x = 5;
    F(x);
}

main.cpp:6:3: error: implicit instantiation of undefined template 'show<int &>'

int main() {
    F([]()->int{return 5;}());
}

main.cpp:6:3: error: implicit instantiation of undefined template 'show<int &&>'


问:
How to properly add apostrophes into a mySQL INSERT command
I am trying to add some data into a MySQL database using a text area. However, when someone adds in an apostrophe it breaks the INSERT command because it acts as a single quote. How can this be fixed?

Here is what the command would look like if you stipped out all the variables that I am using.

```<code>INSERT INTO skills09 (name, birthday, skills) VALUES ('Tom Haverford', '31_02_1987', 'Being Awesome, Announcing cool things, Treatin' Yo Self, Failing');
</code>```

As I was looking at this I had a thought.

Is it as simple as using double quotes around my variable names rather than single quotes? This seems like an easy fix but I have always used single quotes in MySQL.

答:
PHP How to replace customers text area apostrophes with a escape character</p>

```<code>$lastname  = "O'Reilly";
$_lastname = mysqli_real_escape_string($lastname);

$query = "SELECT * FROM actors WHERE last_name = '$_lastname'";
</code>```

Body:
I am trying to add some data into a MySQL database using a text area. However, when someone adds in an apostrophe it breaks the INSERT command because it acts as a single quote. How can this be fixed?

Here is what the command would look like if you stipped out all the variables that I am using.

INSERT INTO skills09 (name, birthday, skills) VALUES ('Tom Haverford', '31_02_1987', 'Being Awesome, Announcing cool things, Treatin' Yo Self, Failing');

As I was looking at this I had a thought.

Is it as simple as using double quotes around my variable names rather than single quotes? This seems like an easy fix but I have always used single quotes in MySQL.

Body:
PHP How to replace customers text area apostrophes with a escape character

$lastname  = "O'Reilly";
$_lastname = mysqli_real_escape_string($lastname);

$query = "SELECT * FROM actors WHERE last_name = '$_lastname'";


问:
PHP sleep accuracy
I use the following code to see how long a user is on a particular page. I use a hidden image with a src attribute to this script:

```<code>$timer_seconds = 1;

while(!connection_aborted()) {
   echo "\n";
   flush();
   sleep(1);
   $timer_seconds++;
}
</code>```

I sometimes find this can be off by 5-10 seconds! I am guessing its the load of the server that effects the timing??

Is there anyway I can make this accurate?

Thanks all for any help.

答:
You've got some nice tools (in javascript) to do that.

http://chartbeat.com

http://analytics.google.com

these are some of used on the company i work.

ContentLicense: CC BY-SA 2.5

Title: PHP sleep accuracy

Body:
I use the following code to see how long a user is on a particular page. I use a hidden image with a src attribute to this script:

$timer_seconds = 1;

while(!connection_aborted()) {
   echo "\n";
   flush();
   sleep(1);
   $timer_seconds++;
}

I sometimes find this can be off by 5-10 seconds! I am guessing its the load of the server that effects the timing??

Is there anyway I can make this accurate?

Thanks all for any help.


问:
Function gets executed multiple times, while called once
I'm currently working on a school project, we have to make a game in c++ console Application. And I'm currently having some issues with the AI moving. So once the players moves the bot can make his move. But for some reason the function gets executed multiple times.

The Function where the bot get his move (monsterMove):

```<code>void playerMove() {
COORD playerCord = { playerX,playerY };
memset(map3, 0, sizeof(map3));
int c = 0;
switch ((c = _getch())) {
case KEY_UP:
    if (map[playerY-1][playerX] == ' ')
    {
        SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), playerCord);
        cout << " ";
        map[playerY][playerX] = ' ';
        playerY--;
    }
    break;
case KEY_DOWN:
    if (map[playerY + 1][playerX] == ' ')
    {
        SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), playerCord);
        cout << " ";
        map[playerY][playerX] = ' ';
        playerY++;
    }

    break;
case KEY_LEFT:
    if (map[playerY][playerX-1]== ' ')
    {
        SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), playerCord);
        cout << " ";
        map[playerY][playerX] = ' ';
        playerX--;
    }
    break;
case KEY_RIGHT:
    if (map[playerY][playerX + 1] == ' ')

    {
        SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), playerCord);
        cout << " ";
        map[playerY][playerX] = ' ';
        playerX++;
    }
    break;
default:
    break;
}
monsterMove(1);
map[playerY][playerX] = 157;
COORD playerCord2 = { playerX,playerY };

SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), playerCord2);
cout << "I";

playerMove();
}
</code>```

The function itself:

```<code>void monsterMove(int moves) {
map[monsterY][monsterX] = ' ';
int row[] = { -1, 0, 0, 1 };
int col[] = { 0, -1, 1, 0 };
int toMove =BFS(map, playerX, playerY, monsterX, monsterY)-moves;

COORD monsterCoord2 = { monsterX,monsterY};
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), monsterCoord2);
cout << ' ';
while (map3[monsterY][monsterX] != toMove)
{
    for (int k = 0; k < 4; k++)
    {
        if ((map3[monsterY + col[k]][monsterX + row[k]] == map3[monsterY][monsterX] -1) && !( map3[monsterY][monsterX] == toMove))
        {
            monsterX = monsterX+ row[k];
            monsterY =monsterY+ col[k];
        }
    }
}
COORD monsterCoord = { monsterX,monsterY };
map[monsterY][monsterX] = 157;
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), monsterCoord);
cout << 'M';
}
</code>```

I've put breakpoints to see what exactly happens , and the line 'monsterMove();' gets executed multiple times. I really don't get what I'm doing wrong.

答: An obvious issue with your code is that you are calling playerMove() inside playerMove(), and as I can see so far from the code you pasted there is nothing to stop the recursion. Also I don't find the line MonsterMove(); mentioned by you at all in the code and even if such a line does exist, you are missing a argument and it won't even compile.

Body:
I'm currently working on a school project, we have to make a game in c++ console Application. And I'm currently having some issues with the AI moving. So once the players moves the bot can make his move. But for some reason the function gets executed multiple times.

The Function where the bot get his move (monsterMove):

void playerMove() {
COORD playerCord = { playerX,playerY };
memset(map3, 0, sizeof(map3));
int c = 0;
switch ((c = _getch())) {
case KEY_UP:
    if (map[playerY-1][playerX] == ' ')
    {
        SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), playerCord);
        cout << " ";
        map[playerY][playerX] = ' ';
        playerY--;
    }
    break;
case KEY_DOWN:
    if (map[playerY + 1][playerX] == ' ')
    {
        SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), playerCord);
        cout << " ";
        map[playerY][playerX] = ' ';
        playerY++;
    }

    break;
case KEY_LEFT:
    if (map[playerY][playerX-1]== ' ')
    {
        SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), playerCord);
        cout << " ";
        map[playerY][playerX] = ' ';
        playerX--;
    }
    break;
case KEY_RIGHT:
    if (map[playerY][playerX + 1] == ' ')

    {
        SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), playerCord);
        cout << " ";
        map[playerY][playerX] = ' ';
        playerX++;
    }
    break;
default:
    break;
}
monsterMove(1);
map[playerY][playerX] = 157;
COORD playerCord2 = { playerX,playerY };

SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), playerCord2);
cout << "I";

playerMove();
}

The function itself:

void monsterMove(int moves) {
map[monsterY][monsterX] = ' ';
int row[] = { -1, 0, 0, 1 };
int col[] = { 0, -1, 1, 0 };
int toMove =BFS(map, playerX, playerY, monsterX, monsterY)-moves;

COORD monsterCoord2 = { monsterX,monsterY};
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), monsterCoord2);
cout << ' ';
while (map3[monsterY][monsterX] != toMove)
{
    for (int k = 0; k < 4; k++)
    {
        if ((map3[monsterY + col[k]][monsterX + row[k]] == map3[monsterY][monsterX] -1) && !( map3[monsterY][monsterX] == toMove))
        {
            monsterX = monsterX+ row[k];
            monsterY =monsterY+ col[k];
        }
    }
}
COORD monsterCoord = { monsterX,monsterY };
map[monsterY][monsterX] = 157;
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), monsterCoord);
cout << 'M';
}

I've put breakpoints to see what exactly happens , and the line 'monsterMove();' gets executed multiple times. I really don't get what I'm doing wrong.


问:
Can disabling autowiring and using annotation instead for services in Symfony 3?
In the DI there is Autowiring, annotation definition and PHP definition.

In Symfony 3.3 the autowiring is enabled by default. So if I disable the autowiring, can I use the annotation to define a service?

```<code>class Foo
{
    /**
     * @Inject({"my.specific.service"})
     */
    public function __construct(Bar $param1)
    {
    }
}
</code>```

Update : Use JMSDiExtraBundle

```<code>namespace MediaBundle\Net;

use JMS\DiExtraBundle\Annotation\Inject;
use JMS\DiExtraBundle\Annotation\InjectParams;
use JMS\DiExtraBundle\Annotation\Service;

/**
 * @Service("some.service.id", public=false, environments = {"prod", "test", "dev"})
 */
class Foo
{
    private $em;
    private $session;

    /**
     * @InjectParams({
     *     "em" = @Inject("doctrine.orm.entity_manager"),
     *     "session" = @Inject("session")
     * })
     */
    public function __construct($em, $session)
    {
        $this->em = $em;
        $this->session = $session;
    }
}
</code>```

Calling the service in the controller:

```<code>namespace MediaBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;

class DefaultController extends Controller
{
    /**
     * @Route("/media")
     */
    public function indexAction()
    {
        $someService = $this->get('some.service.id');

        return $this->render('MediaBundle:Default:index.html.twig');
    }
}
</code>```

Result : You have requested a non-existent service "some.service.id".

答: Is your service injected somewhere? If not, it will be dropped from the container due to public=false, see http://symfony.com/blog/new-in-symfony-3-2-improved-private-services

Body:
In the DI there is Autowiring, annotation definition and PHP definition.

In Symfony 3.3 the autowiring is enabled by default. So if I disable the autowiring, can I use the annotation to define a service?

class Foo
{
    /**
     * @Inject({"my.specific.service"})
     */
    public function __construct(Bar $param1)
    {
    }
}

Update : Use JMSDiExtraBundle

namespace MediaBundle\Net;

use JMS\DiExtraBundle\Annotation\Inject;
use JMS\DiExtraBundle\Annotation\InjectParams;
use JMS\DiExtraBundle\Annotation\Service;

/**
 * @Service("some.service.id", public=false, environments = {"prod", "test", "dev"})
 */
class Foo
{
    private $em;
    private $session;

    /**
     * @InjectParams({
     *     "em" = @Inject("doctrine.orm.entity_manager"),
     *     "session" = @Inject("session")
     * })
     */
    public function __construct($em, $session)
    {
        $this->em = $em;
        $this->session = $session;
    }
}

Calling the service in the controller:

namespace MediaBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;

class DefaultController extends Controller
{
    /**
     * @Route("/media")
     */
    public function indexAction()
    {
        $someService = $this->get('some.service.id');

        return $this->render('MediaBundle:Default:index.html.twig');
    }
}

Result : You have requested a non-existent service "some.service.id".


问:
How can I use data members on a reference without creating an object with new keyword?
```<code>class player{
   public:
      int a;
}
int main(){
   player p1;
   p1.a=10;
}
</code>```

I created a reference variable p1 of player but not the actual object on heap since I haven't used the new keyword on p1. But, c++ compiler allows me to assign value 10 to data member 'a' of p1. How is this possible without having an object on heap?

答:
You are confusing C++ with Java. p1 is not a reference, it's just an object with automatic storage duration. It's created when the variable's scope begins, and it's destroyed when the variable's scope ends.

In C++, you normally only use the "heap" (the correct word would be: the free store) if you need more complex control over an object's lifetime.

If you don't need this special control, then an object in C++ works just like, say, an int or a double. You wouldn't feel it's necessary to write new int or new double, would you? Well, in C++, your player acts like an int or a double in this regard. It's a major difference to almost all other popular programming languages.

Body:
class player{
   public:
      int a;
}
int main(){
   player p1;
   p1.a=10;
}

I created a reference variable p1 of player but not the actual object on heap since I haven't used the new keyword on p1. But, c++ compiler allows me to assign value 10 to data member 'a' of p1. How is this possible without having an object on heap?


问:
Checkbox issue oncheck function
Please see the following code at first.
I want the particular checkbox (with id cfc1) to not be shown ticked whenever clicking on it.
I have used the onCheck function there. I'm not finding any way to the particular element be shown unchecked whenever clicked on it. I'm trying using the code -

```<code>if(e.currentTarget.id === 'cfc1') {
    document.getElementById(e.currentTarget.id).checked = false;
}
</code>```

but it's not working.

How to do it using the onCheck function?

```<code>import React, {Component} from 'react';
import Checkbox from 'material-ui/Checkbox';

class Checkboxes extends Component {
  constructor() {
     super();
     this.state = {
        checkids:['cfc0', 'cfc1', 'cfc2', 'cfc3']
     };
     this.handleCheck = this.handleCheck.bind(this);
     this.getElements = this.getElements.bind(this);
  }
  getElements() {
     let arr = [];
     this.state.checkids.forEach(function(element) {
        arr.push(
          <Checkbox
             id={element}
             onCheck={this.handleCheck}
          />
        );
     }, this)
     return arr;
  }
  handleCheck(e) {
     console.log(e.currentTarget.id);
     console.log(e.currentTarget.checked);
  }
  render() {
     return(
       <div>
          {this.getElements()}
       </div>
     );
  }
}
export default Checkboxes
</code>```

答:
You can use this.checked = false via javascript

document.getElementById('cfc1').onclick = function() {
  this.checked = false;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><label><input type="checkbox" id="cfc1">Click</label></code>```

Title: Checkbox issue oncheck function

Body:
Please see the following code at first.
I want the particular checkbox (with id cfc1) to not be shown ticked whenever clicking on it.
I have used the onCheck function there. I'm not finding any way to the particular element be shown unchecked whenever clicked on it. I'm trying using the code -

if(e.currentTarget.id === 'cfc1') {
    document.getElementById(e.currentTarget.id).checked = false;
}

but it's not working.

How to do it using the onCheck function?

import React, {Component} from 'react';
import Checkbox from 'material-ui/Checkbox';

class Checkboxes extends Component {
  constructor() {
     super();
     this.state = {
        checkids:['cfc0', 'cfc1', 'cfc2', 'cfc3']
     };
     this.handleCheck = this.handleCheck.bind(this);
     this.getElements = this.getElements.bind(this);
  }
  getElements() {
     let arr = [];
     this.state.checkids.forEach(function(element) {
        arr.push(
          <Checkbox
             id={element}
             onCheck={this.handleCheck}
          />
        );
     }, this)
     return arr;
  }
  handleCheck(e) {
     console.log(e.currentTarget.id);
     console.log(e.currentTarget.checked);
  }
  render() {
     return(

          {this.getElements()}

     );
  }
}
export default Checkboxes

Body:
You can use this.checked = false via javascript

document.getElementById('cfc1').onclick = function() {
  this.checked = false;
}

<label><input type="checkbox" id="cfc1">Click</label>


问:
scanf prematurely terminating while loop (I think)
I am making a simple program to calculate the required exam mark based on your current mark, the % total worth of the exam on the course, and your desired mark. I was having no problems with it until I wanted a simple while loop to redo the proses if the user wanted to do so. The problem that arose was that when I have the scanf to get a char response from the user, it terminates the while loop and then the program. When I comment out the scanf line and leave the code as is (an infinite while loop) it works properly looping forever but with it, it will terminate with no errors. Any thoughts?</p>

```<code>    #include <stdio.h>

    #define TRUE 1
    #define FALSE 0

    int main()
    {
        int continueProgram = TRUE;
        float currentMark = 0.0, examPercent = 0.0, desiredMark = 0.0, requiredMark = 0.0;
        char response  = 'y';

        while (continueProgram == TRUE)
        {
            printf("What is your current mark in your class: ");
            scanf("%f", &currentMark);
            printf("How much is you exam worth: ");
            scanf("%f", &examPercent);
            examPercent /= 100.0;
            printf("What is your desiered mark: ");
            scanf("%f", &desiredMark);

            // Simple math to get mark
            requiredMark = (desiredMark - currentMark * examPercent) / examPercent;

            if (requiredMark > 100.0)
            {
                printf("\nI'm sorry but you need above 100%% to get to your required mark\nHere is a list of all the marks you can get:\n\n");

                for (requiredMark = 0.0; requiredMark <= 100.0; requiredMark += 5.0)
                {
                    desiredMark = currentMark * examPercent + requiredMark * examPercent;
                    printf("Exam Mark: %.2f, Final Mark: %.2f\n", requiredMark, desiredMark);
                }
            }
            else
            {
                printf("\nThe mark that you need to get on the exam is: %.2f\nHere is a list of all the marks you can get:\n\n", requiredMark);

                for (requiredMark = 0.0; requiredMark <= 100.0; requiredMark += 5.0)
                {
                    desiredMark = currentMark * examPercent + requiredMark * examPercent;
                    printf("Exam Mark: %.2f, Final Mark: %.2f\n", requiredMark, desiredMark);
                }
            }

            printf("\nDid you want to continue with a new grade (y or n): ");

            // THIS IS WHERE I AM HAVING THE ISSUE
            scanf("%c", &response );

            if (response  == 'y')
            {
                printf("\n\nResetting  terminal...\n\n");
                currentMark = 0.0;
                examPercent = 0.0;
                desiredMark = 0.0;
                requiredMark = 0.0;
            }
            else
                continueProgram = FALSE;
        }
    }
</code>```

答:
before this

```<code>scanf("%c", &response );
</code>```

need to clear out stdin, perhaps by:

```<code>int ch;
while( (ch = getchar()) != EOF && '\n' != ch );
</code>```

because the prior call to scanf() left the newline char in the input stream.

Body:
I am making a simple program to calculate the required exam mark based on your current mark, the % total worth of the exam on the course, and your desired mark. I was having no problems with it until I wanted a simple while loop to redo the proses if the user wanted to do so. The problem that arose was that when I have the scanf to get a char response from the user, it terminates the while loop and then the program. When I comment out the scanf line and leave the code as is (an infinite while loop) it works properly looping forever but with it, it will terminate with no errors. Any thoughts?

    #include <stdio.h>

    #define TRUE 1
    #define FALSE 0

    int main()
    {
        int continueProgram = TRUE;
        float currentMark = 0.0, examPercent = 0.0, desiredMark = 0.0, requiredMark = 0.0;
        char response  = 'y';

        while (continueProgram == TRUE)
        {
            printf("What is your current mark in your class: ");
            scanf("%f", &currentMark);
            printf("How much is you exam worth: ");
            scanf("%f", &examPercent);
            examPercent /= 100.0;
            printf("What is your desiered mark: ");
            scanf("%f", &desiredMark);

            // Simple math to get mark
            requiredMark = (desiredMark - currentMark * examPercent) / examPercent;

            if (requiredMark > 100.0)
            {
                printf("\nI'm sorry but you need above 100%% to get to your required mark\nHere is a list of all the marks you can get:\n\n");

                for (requiredMark = 0.0; requiredMark <= 100.0; requiredMark += 5.0)
                {
                    desiredMark = currentMark * examPercent + requiredMark * examPercent;
                    printf("Exam Mark: %.2f, Final Mark: %.2f\n", requiredMark, desiredMark);
                }
            }
            else
            {
                printf("\nThe mark that you need to get on the exam is: %.2f\nHere is a list of all the marks you can get:\n\n", requiredMark);

                for (requiredMark = 0.0; requiredMark <= 100.0; requiredMark += 5.0)
                {
                    desiredMark = currentMark * examPercent + requiredMark * examPercent;
                    printf("Exam Mark: %.2f, Final Mark: %.2f\n", requiredMark, desiredMark);
                }
            }

            printf("\nDid you want to continue with a new grade (y or n): ");

            // THIS IS WHERE I AM HAVING THE ISSUE
            scanf("%c", &response );

            if (response  == 'y')
            {
                printf("\n\nResetting  terminal...\n\n");
                currentMark = 0.0;
                examPercent = 0.0;
                desiredMark = 0.0;
                requiredMark = 0.0;
            }
            else
                continueProgram = FALSE;
        }
    }

Body:
before this

scanf("%c", &response );

need to clear out stdin, perhaps by:

int ch;
while( (ch = getchar()) != EOF && '\n' != ch );

because the prior call to scanf() left the newline char in the input stream.


问:
my add form is not showing
I am developing Zend Framework App.

In my indexcontroller view views/scripts/index/index.phtml

```<code><p><a href="<?php echo $this->url(array('controller'=>'index',
'action'=>'add'));?>">Add new album</a></p>
</code>```

in my browser is is outputting me only url path so it is not going to the add action.
Here it is my add action in IndexController.php

```<code> public function addAction()
    {
        // action body
        $form = new Application_Form_User();
        $form->submit->setLabel('Add');
        $this->view->form = $form;
        if ($this->getRequest()->isPost()) {
            $formData = $this->getRequest()->getPost();
            if ($form->isValid($formData)) {
                $artist = $form->getValue('artist');
                $title = $form->getValue('title');
                $albums = new Application_Model_DbTable_Albums();
                $albums->addUser($artist, $title);
                $this->_helper->redirector('index');
            } else {
                $form->populate($formData);
            }
        }
    }
</code>```

and my add.phtml is

```<code><?php
$this->title = "Add new album";
$this->headTitle($this->title);
echo $this->form ;
?>
</code>```

why it is not going to add action. please suggest
Edit More Info

and i am using this pdf to build the app http://akrabat.com/wp-content/uploads/Getting-Started-with-Zend-Framework.pdf

In page No. 9
I am not getting where to put this line and is these lines are necessary or not ?

```<code>$view = new Zend_View();
$view->setScriptPath('/path/to/scripts');
echo $view->render('script.php');
</code>```

and i haven't set the layout and CSS .but my listing from Database is coming but my add Dction is not working ? Please suggest why

答:
I had added the  following lines in the Bootstrap.php
Because before i was trying to build REST API .</p>

```<code>#$restRoute = new Zend_Rest_Route($frontController);
        # $frontController->getRouter()->addRoute('default', $restRoute);
</code>```

Title: my add form is not showing

Body:
I am developing Zend Framework App.

In my indexcontroller view views/scripts/index/index.phtml

<a href="<?php echo $this->url(array('controller'=>'index',
'action'=>'add'));?>">Add new album

in my browser is is outputting me only url path so it is not going to the add action.
Here it is my add action in IndexController.php

 public function addAction()
    {
        // action body
        $form = new Application_Form_User();
        $form->submit->setLabel('Add');
        $this->view->form = $form;
        if ($this->getRequest()->isPost()) {
            $formData = $this->getRequest()->getPost();
            if ($form->isValid($formData)) {
                $artist = $form->getValue('artist');
                $title = $form->getValue('title');
                $albums = new Application_Model_DbTable_Albums();
                $albums->addUser($artist, $title);
                $this->_helper->redirector('index');
            } else {
                $form->populate($formData);
            }
        }
    }

and my add.phtml is

<?php
$this->title = "Add new album";
$this->headTitle($this->title);
echo $this->form ;
?>

why it is not going to add action. please suggest
Edit More Info

and i am using this pdf to build the app http://akrabat.com/wp-content/uploads/Getting-Started-with-Zend-Framework.pdf

In page No. 9
I am not getting where to put this line and is these lines are necessary or not ?

$view = new Zend_View();
$view->setScriptPath('/path/to/scripts');
echo $view->render('script.php');

and i haven't set the layout and CSS .but my listing from Database is coming but my add Dction is not working ? Please suggest why

Body:
I had added the  following lines in the Bootstrap.php
Because before i was trying to build REST API .

#$restRoute = new Zend_Rest_Route($frontController);
        # $frontController->getRouter()->addRoute('default', $restRoute);


问:
ratingbar not working (not clickable) when using ratingBarStyleSmall style
ratingbar didn't change when the user click on it ?

her is my xml code

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.soulhis.testmaterialdesign.Test">
<RatingBar
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/ratingBar4"
    android:layout_centerVertical="true"
    style="?android:attr/ratingBarStyleSmall"
     android:layout_centerHorizontal="true" />
 </RelativeLayout>
</code>```

the problem occur just when using ratingBarStyleSmall
tested on android jellybean api level 17

答:
so I had the same issue and I put android:isIndicator="false" to my RatingBar tag and it solved the problem for me now my full rate bar tag looks like this:

```<code><RatingBar
    android:id="@+id/ratingReview"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:numStars="5"
    android:isIndicator="false"
    style="@style/Base.Widget.AppCompat.RatingBar"/>
</code>```

hope this helps.
for more info you can refer to this answer too.

Body:
ratingbar didn't change when the user click on it ?

her is my xml code

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.soulhis.testmaterialdesign.Test">
<RatingBar
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/ratingBar4"
    android:layout_centerVertical="true"
    style="?android:attr/ratingBarStyleSmall"
     android:layout_centerHorizontal="true" />
 </RelativeLayout>

the problem occur just when using ratingBarStyleSmall
tested on android jellybean api level 17

Body:
so I had the same issue and I put android:isIndicator="false" to my RatingBar tag and it solved the problem for me now my full rate bar tag looks like this:

<RatingBar
    android:id="@+id/ratingReview"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:numStars="5"
    android:isIndicator="false"
    style="@style/Base.Widget.AppCompat.RatingBar"/>

hope this helps.
for more info you can refer to this answer too.


问:
How to print diamond shape w/ c++
I need help, I created a short little program a while ago where it would print a simple pyramid with "*" like this:

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

but I decided to challenge myself and see if I could create a simple diamond shape like this:

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

Here is my code so far.
I should also add that the value you input, for example 5, determines how big the diamond is.

```<code>#include <iostream>
#include <sstream>
using namespace std;

int main() {

int value = 0;
cout << "Please enter in a value: ";
cin >> value;
cout << endl;

for (int i = 0; i < value; i++) {
    //print spaces v v v
    for (int x = 0; x < (value - i - 1); x++) {
        cout << " ";
    }
    //print * v v v
    for (int y = 0; y < (2 * i + 1); y++) {
        cout << "*";
    }
    cout << endl;
}

for (int i = 0; i < value; i++) {
    int number = 0;
    number+= 2;
    //print spaces v v v
    for (int x = 0; x < (value - value + i + 1); x++) {
        cout << " ";
    }
    //print * v v v
    for (int y = 0; y < (/*ATTENTION: What do I do here? Plz help*/); y++) {
        cout << "*";
    }
    cout << endl;
}

return 0;
}
</code>```

What I've been trying to do is figure out what to put inside the parenthesis where it says (//ATTENTION). I've been working for at least an hour trying to do random things, and one time it worked when I input 4, but not for 5, and it's just been very hard. This is key to building the diamond, try putting in just value and compile to see what happens. I need it to be symmetrical.

I need to know what to put inside the parenthesis please. I'm sorry this is very long but the help would be appreciated thanks.

I also apologize if my code is messy and hard to read.

答:
int number = 0; and number+= 2;

value - value inside for (int x = 0; x < (value - value + i + 1); x++) {

are not required.

Inside the parenthesis, you can use

```<code>2*(value-i-1)-1
</code>```

However, I would suggest you to first analyze the problem and then try to solve it instead of trying random things. For instance, let's consider the cases of even and odd inputs i.e., 2 and 3.

Even Case (2)

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

The Analysis

```<code>Row Index    Number of Spaces    Number of Stars
0            1                   1
1            0                   3
2            0                   3
3            1                   1
</code>```

For row index < value

Number of Spaces = value - row index - 1

Number of Stars = 2 * row index + 1

For row index >=value
The number of spaces and stars are simply reversed. In the odd cases, the situation is similar too with a small exception.

Odd Case (3)

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

The Analysis

```<code>Row Index    Number of Spaces    Number of Stars
0            2                   1
1            1                   3
2            0                   5
3            1                   3
4            2                   1
</code>```

The small exception is that while reversing, we have to ignore the row index = value.

Now, if we put the above analysis in code we get the solution

```<code>//Define the Print Function
void PrintDiamond(int rowIndex, int value)
{
    //print spaces v v v
    for (int x = 0; x < value - rowIndex -1; x++) {
        cout << " ";
    }
    //print * v v v
    for (int y = 0; y < 2 * rowIndex + 1; y++) {
        cout << "*";
    }
    cout << endl;
}
</code>```

And then inside main

```<code>//Row index < value
for (int i = 0; i < value; i++) {
    PrintDiamond(i,value);
}

//For row index >= value reversing the above case
//value-(value%2)-1 subtracts 1 for even and 2 for odd cases
//ignore the row index = value in odd cases
for (int i = value-(value%2)-1; i >=0; i--) {
    PrintDiamond(i,value);
}
</code>```

Title: How to print diamond shape w/ c++

Body:
I need help, I created a short little program a while ago where it would print a simple pyramid with "*" like this:

  *
 ***
*****

but I decided to challenge myself and see if I could create a simple diamond shape like this:

  *
 ***
*****
 ***
  *

Here is my code so far.
I should also add that the value you input, for example 5, determines how big the diamond is.

#include <iostream>
#include <sstream>
using namespace std;

int main() {

int value = 0;
cout << "Please enter in a value: ";
cin >> value;
cout << endl;

for (int i = 0; i < value; i++) {
    //print spaces v v v
    for (int x = 0; x < (value - i - 1); x++) {
        cout << " ";
    }
    //print * v v v
    for (int y = 0; y < (2 * i + 1); y++) {
        cout << "*";
    }
    cout << endl;
}

for (int i = 0; i < value; i++) {
    int number = 0;
    number+= 2;
    //print spaces v v v
    for (int x = 0; x < (value - value + i + 1); x++) {
        cout << " ";
    }
    //print * v v v
    for (int y = 0; y < (/*ATTENTION: What do I do here? Plz help*/); y++) {
        cout << "*";
    }
    cout << endl;
}

return 0;
}

What I've been trying to do is figure out what to put inside the parenthesis where it says (//ATTENTION). I've been working for at least an hour trying to do random things, and one time it worked when I input 4, but not for 5, and it's just been very hard. This is key to building the diamond, try putting in just value and compile to see what happens. I need it to be symmetrical.

I need to know what to put inside the parenthesis please. I'm sorry this is very long but the help would be appreciated thanks.

I also apologize if my code is messy and hard to read.

Body:
int number = 0; and number+= 2;

value - value inside for (int x = 0; x < (value - value + i + 1); x++) {

are not required.

Inside the parenthesis, you can use

2*(value-i-1)-1

However, I would suggest you to first analyze the problem and then try to solve it instead of trying random things. For instance, let's consider the cases of even and odd inputs i.e., 2 and 3.

Even Case (2)

 *
***
***
 *

The Analysis

Row Index    Number of Spaces    Number of Stars
0            1                   1
1            0                   3
2            0                   3
3            1                   1

For row index < value

Number of Spaces = value - row index - 1

Number of Stars = 2 * row index + 1

For row index >=value
The number of spaces and stars are simply reversed. In the odd cases, the situation is similar too with a small exception.

Odd Case (3)

  *
 ***
*****
 ***
  *

The Analysis

Row Index    Number of Spaces    Number of Stars
0            2                   1
1            1                   3
2            0                   5
3            1                   3
4            2                   1

The small exception is that while reversing, we have to ignore the row index = value.

Now, if we put the above analysis in code we get the solution

//Define the Print Function
void PrintDiamond(int rowIndex, int value)
{
    //print spaces v v v
    for (int x = 0; x < value - rowIndex -1; x++) {
        cout << " ";
    }
    //print * v v v
    for (int y = 0; y < 2 * rowIndex + 1; y++) {
        cout << "*";
    }
    cout << endl;
}

And then inside main

//Row index < value
for (int i = 0; i < value; i++) {
    PrintDiamond(i,value);
}

//For row index >= value reversing the above case
//value-(value%2)-1 subtracts 1 for even and 2 for odd cases
//ignore the row index = value in odd cases
for (int i = value-(value%2)-1; i >=0; i--) {
    PrintDiamond(i,value);
}


问:
how to prevent from exiting or jump out elements from page?
I use several buttons to create motion, now i have a problem when i use marginLeft for move the element to left and right div#ball, it doesn't fit in the page and  jumps out and exit form both left and right side. how i can set a limitation and avoid element from exiting ?

$(document).ready(function() {
  $('#fastleft').click(function() {
    $('#ball').toggleClass('rotated');
    $('#ball').animate({
      'marginLeft': "-=300px"
    });
  });

  $('#moveleft').click(function() {
    $('#ball').toggleClass('rotated');
    $('#ball').animate({
      'marginLeft': "-=20px"
    });
  });

  $('#moveright').click(function() {
    $('#ball').toggleClass('rotated');
    $('#ball').animate({
      'marginLeft': "+=20px"
    });
  });

  $('#fastright').click(function() {
    $('#ball').toggleClass('rotated');
    $('#ball').animate({
      'marginLeft': "+=300px"
    });
  });

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#ball {
  width: 50px;
  height: 50px;
  display: inline-block;
  /*background-image: url(./boll.png);*/
  background-color:red;
  background-size: contain;
  background-repeat: no-repeat;
  background-position: center;
  position: relative;
}

.rotated {
  animation-duration: 0.5s;
  animation-name: ball;
}

@keyframes ball {
  0% {
    transform: rotate(100deg)
  }
  25% {
    transform: rotate(200deg)
  }
  50% {
    transform: rotate(300deg)
  }
  100% {
    transform: rotate(360deg)
  }
}</code>```

    <button id="fastleft" type="button">FastLeft</button></button>
    <button id="moveleft" type="button">Left</button>
    <button id="moveright" type="button">Right</button>
    <button id="fastright" type="button">FastRight</button>

```

答:
Here's a more optimized version of your code using function and data attribute. Examine it and let me know if you have any questions understanding it.

var ball = $('#ball');
var position = 0;
var bw = ball.width();
var ww = $('body').width();

$('button').click(function() {
  var speed = $(this).data('speed');
  moveBall(speed);
});

function moveBall(px){
  position+= px;
  position = Math.min(position,ww-bw);
  position = Math.max(position,0);

  console.log(position);

  ball.toggleClass('rotated').animate({
      'marginLeft': position+"px"
  });
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>    #ball {
      width: 50px;
      height: 50px;
      display: inline-block;
      /*background-image: url(./boll.png);*/
      background-color:red;
      background-size: contain;
      background-repeat: no-repeat;
      background-position: center;
      position: relative;
    }

    .rotated {
      animation-duration: 0.5s;
      animation-name: ball;
    }

    @keyframes ball {
      0% {
        transform: rotate(100deg)
      }
      25% {
        transform: rotate(200deg)
      }
      50% {
        transform: rotate(300deg)
      }
      100% {
        transform: rotate(360deg)
      }
    }</code>```

        <button data-speed="-300" id="fastleft" type="button">FastLeft</button>
        <button data-speed="-20" id="moveleft" type="button">Left</button>
        <button data-speed="20" id="moveright" type="button">Right</button>
        <button data-speed="300" id="fastright" type="button">FastRight</button>

```

Body:
I use several buttons to create motion, now i have a problem when i use marginLeft for move the element to left and right div#ball, it doesn't fit in the page and  jumps out and exit form both left and right side. how i can set a limitation and avoid element from exiting ?

$(document).ready(function() {
  $('#fastleft').click(function() {
    $('#ball').toggleClass('rotated');
    $('#ball').animate({
      'marginLeft': "-=300px"
    });
  });

  $('#moveleft').click(function() {
    $('#ball').toggleClass('rotated');
    $('#ball').animate({
      'marginLeft': "-=20px"
    });
  });

  $('#moveright').click(function() {
    $('#ball').toggleClass('rotated');
    $('#ball').animate({
      'marginLeft': "+=20px"
    });
  });

  $('#fastright').click(function() {
    $('#ball').toggleClass('rotated');
    $('#ball').animate({
      'marginLeft': "+=300px"
    });
  });

});

#ball {
  width: 50px;
  height: 50px;
  display: inline-block;
  /*background-image: url(./boll.png);*/
  background-color:red;
  background-size: contain;
  background-repeat: no-repeat;
  background-position: center;
  position: relative;
}

.rotated {
  animation-duration: 0.5s;
  animation-name: ball;
}

@keyframes ball {
  0% {
    transform: rotate(100deg)
  }
  25% {
    transform: rotate(200deg)
  }
  50% {
    transform: rotate(300deg)
  }
  100% {
    transform: rotate(360deg)
  }
}

    <button id="fastleft" type="button">FastLeft</button></button>
    <button id="moveleft" type="button">Left</button>
    <button id="moveright" type="button">Right</button>
    <button id="fastright" type="button">FastRight</button>

Body:
Here's a more optimized version of your code using function and data attribute. Examine it and let me know if you have any questions understanding it.

var ball = $('#ball');
var position = 0;
var bw = ball.width();
var ww = $('body').width();

$('button').click(function() {
  var speed = $(this).data('speed');
  moveBall(speed);
});

function moveBall(px){
  position+= px;
  position = Math.min(position,ww-bw);
  position = Math.max(position,0);

  console.log(position);

  ball.toggleClass('rotated').animate({
      'marginLeft': position+"px"
  });
}

    #ball {
      width: 50px;
      height: 50px;
      display: inline-block;
      /*background-image: url(./boll.png);*/
      background-color:red;
      background-size: contain;
      background-repeat: no-repeat;
      background-position: center;
      position: relative;
    }

    .rotated {
      animation-duration: 0.5s;
      animation-name: ball;
    }

    @keyframes ball {
      0% {
        transform: rotate(100deg)
      }
      25% {
        transform: rotate(200deg)
      }
      50% {
        transform: rotate(300deg)
      }
      100% {
        transform: rotate(360deg)
      }
    }

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

    <div class="container">
      <div id="butts">
        <button data-speed="-300" id="fastleft" type="button">FastLeft</button>
        <button data-speed="-20" id="moveleft" type="button">Left</button>
        <button data-speed="20" id="moveright" type="button">Right</button>
        <button data-speed="300" id="fastright" type="button">FastRight</button>
      </div>
      <br>
      <div id="ball"></div>
    </div>


问:
Netbeans as Mercurial Merge Tool
the company I work for have started to use Mercurial as our version control software, with NetBeans becoming the editor of choice for most developers.

Up until now we've been using WinMerge and KDiff3as our Mercurial merge tool, but have decided that we don't like it.

Now one of the things we've noticed about NetBeans is that it has a very nice diff tool built into it, so was hoping that there might be some way of using this as the Mercurial merge tool?

Can anyone let me know if this is possible, and if so, how?

(Or, are there any other windows diff/merge tools that are as good as the NetBeans diff tool?)

Cheers

答:
I am not sure about using the NetBeans diff tool but as for other merge tools that will work well with Mercurial, I would recommend Perforce's Merge tool which I have heard is somewhat similar to the Netbeans one.

Another good one is DiffMerge.

Title: Netbeans as Mercurial Merge Tool


问:
How to get output like this in Javascript/ES6
Let's say you have an array like this:

//Input
[1,2,3,4,5,6,7]

How to write the function which will get us the output of

//Output

```<code> Array1 = [1]
 Array2 = [1,2]
 Array3 = [1,2,3]
 Array4 = [1,2,3,4]
 Array5 = [1,2,3,4,5]
</code>```

And

//Output
1. [1,1,2,1,2,3,1,2,3,4...]

// tried this

```<code>for (i = 0; i < arr.length; i++) {
    arr = new Array(arr[i]);
}
</code>```

答:
You could reduce the array by slicing the wanted part with spread syntax ....

var array = [1, 2, 3, 4, 5, 6, 7],
    result = array.reduce((r, _, i, a) => [...r, ...a.slice(0, i + 1)], []);

console.log(result);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

Body:
Let's say you have an array like this:

//Input
[1,2,3,4,5,6,7]

How to write the function which will get us the output of

//Output

 Array1 = [1]
 Array2 = [1,2]
 Array3 = [1,2,3]
 Array4 = [1,2,3,4]
 Array5 = [1,2,3,4,5]

And

//Output
1. [1,1,2,1,2,3,1,2,3,4...]

// tried this

for (i = 0; i < arr.length; i++) {
    arr = new Array(arr[i]);
}

Body:
You could reduce the array by slicing the wanted part with spread syntax ....

var array = [1, 2, 3, 4, 5, 6, 7],
    result = array.reduce((r, _, i, a) => [...r, ...a.slice(0, i + 1)], []);

console.log(result);

.as-console-wrapper { max-height: 100% !important; top: 0; }


问:
Packets sometimes get concatenated
I'm trying to make a simple server/application in Erlang.

My server initialize a socket with gen_tcp:listen(Port, [list, {active, false}, {keepalive, true}, {nodelay, true}]) and the clients connect with gen_tcp:connect(Server, Port, [list, {active, true}, {keepalive, true}, {nodelay, true}]).
Messages received from the server are tested by guards such as {tcp, _, [115, 58 | Data]}.

Problem is, packets sometimes get concatenated when sent or received and thus cause unexpected behaviors as the guards consider the next packet as part of the variable.

Is there a way to make sure every packet is sent as a single message to the receiving process?

答:
You need to implement a delimiter for your packets.
One solution is to use a special character ; or something similar.

The other solution is to send the size of the packet first.
PacketSizeInBytes:Body

Then read the provided amount of bytes from your message. When you're at the end you got your whole packet.

Nobody mentions that TCP may also split your message into multiple pieces (split your packet into two messages).

So the second solution is the best of all. But a little hard. While the first one is still good but limits your ability to send packets with special characters. But the easiest to implement. Ofc theres a workaround for all of this. I hope it helps.

Title: Packets sometimes get concatenated


问:
XmlWriter including namespace\schema for each tag
I need to create a file in XML using XmlWriter including for each tag the namespace\schema.
First I have a class produced by xsd schema file, I create the class with all objects and finally I serialize the class writing xml:

```<code>myclass root = new myclass();
root.val1 = "temp1";
root.val2 = "temp2";

[...]

using (XmlWriter writer = XmlWriter.Create(Path.Combine("myfile.xml"), s))
{
    serializer.Serialize(writer, root);
</code>```

the problem is that it creates the tags like that:

```<code><Message>
    <val1> temp1 </val1>
    <val2> temp2 </val2>
<Message>
</code>```

I want to write the tags as:

```<code><temp:Message>
    <temp:val1> temp1 </val1>
    <temp:val2> temp2 </val2>
<temp:Message>
</code>```

can I use some attribute in my class to add temp: starting tags?

I need also to add to my root tag some namespace:

```<code><temp:Message
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="myxml.xsd"
    xmlns:stf="urn:oecd:ties:stf:v4"
    xmlns:mesage="urn:oecd:ties:cbc:v1"
    xmlns:iso="urn:oecd:ties:isocbctypes:v1"
    version="1.0">
</code>```

so I need to add to root class:

```<code>1) xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
2) xsi:schemaLocation="myxml.xsd"
3) xmlns:mesage="urn:oecd:ties:cbc:v1"
4) etc...
</code>```

how can I do that?

答:
you can attache temp by doing as below , attach namespace with you xml

```<code>var xsn = new XmlSerializerNamespaces();
xsn.Add("temp", "http://namespaceforxml");
XmlSerializer s = new XmlSerializer(typeof(Message));
Message msg = new Message();
// Writing a file requires a TextWriter.
TextWriter t = new StreamWriter(filename);
s.Serialize(t,msg,ns);
t.Close();
</code>```

decorate calss as below

```<code>[XmlRoot(ElementName = "Message", Namespace = "//namespaceforxml")]
public class Message
{
    [XmlElement(ElementName = "val1")]
    public string val1{ get; set; }
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I need to create a file in XML using XmlWriter including for each tag the namespace\schema.
First I have a class produced by xsd schema file, I create the class with all objects and finally I serialize the class writing xml:

myclass root = new myclass();
root.val1 = "temp1";
root.val2 = "temp2";

[...]

using (XmlWriter writer = XmlWriter.Create(Path.Combine("myfile.xml"), s))
{
    serializer.Serialize(writer, root);

the problem is that it creates the tags like that:

<Message>
    <val1> temp1 </val1>
    <val2> temp2 </val2>
<Message>

I want to write the tags as:

<temp:Message>
    <temp:val1> temp1 </val1>
    <temp:val2> temp2 </val2>
<temp:Message>

can I use some attribute in my class to add temp: starting tags?

I need also to add to my root tag some namespace:

<temp:Message
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="myxml.xsd"
    xmlns:stf="urn:oecd:ties:stf:v4"
    xmlns:mesage="urn:oecd:ties:cbc:v1"
    xmlns:iso="urn:oecd:ties:isocbctypes:v1"
    version="1.0">

so I need to add to root class:

1) xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
2) xsi:schemaLocation="myxml.xsd"
3) xmlns:mesage="urn:oecd:ties:cbc:v1"
4) etc...

how can I do that?

Body:
you can attache temp by doing as below , attach namespace with you xml

var xsn = new XmlSerializerNamespaces();
xsn.Add("temp", "http://namespaceforxml");
XmlSerializer s = new XmlSerializer(typeof(Message));
Message msg = new Message();
// Writing a file requires a TextWriter.
TextWriter t = new StreamWriter(filename);
s.Serialize(t,msg,ns);
t.Close();

decorate calss as below

[XmlRoot(ElementName = "Message", Namespace = "//namespaceforxml")]
public class Message
{
    [XmlElement(ElementName = "val1")]
    public string val1{ get; set; }
}