问:
PHP: INSERT DATA BY SELECTION TAG HTML WITH PHP
I use this code to insert the data selection from select tag in html but i doesn't work perfectly when i put a value number in text input i would like someone helps me with that. otherwise, when i click in add_btn without value the insertion of data is added in MySQL databases.

HTML->

```<code>  <form id="myForm" action="userInfo.php" method="post">
                    <select name="type" class="add__type" >
                        <option value="inc" selected>+</option>
                        <option value="exp">-</option>
                    </select>
                 <select  name="description" class="add__description" title="h" >
                   <option  value="Food">Food</option>
                   <option  value="Salary">Salary</option>
                   <option  value="Home">Home</option>
                   <option  value="Car">Car</option>
                   <option  value="Education">Education</option>
                   <option  value="Gift">Gift</option>
                   <option  value="Travle"> Travle </option>
                   <option  value="Fun">Fun</option>
                        </select>
                <input name="value" type="number" class="add__value">
           <button class="add__btn"><i class="ion-ios-checkmark-outline"></i></button>
            </form>
     <script src="script/jquery-1.8.1.min.js" type="text/javascript"></script>
    <script src="script/my_script.js" type="text/javascript"></script>
</code>```

PHP-> userinfo.php

```<code>  <?php
        include_once('db.php');

        $type = $_POST['type'];
        $description = $_POST['description'];
        $value = $_POST['value'];

        if(mysql_query("INSERT INTO budget VALUES('$type', '$description' , '$value')"))
          echo "Successfully Inserted";
        else
          echo "Insertion Failed";
?>
</code>```

PHP -> db.php

```<code><?php
      $conn = mysql_connect ('localhost', 'root', '');
      $db   = mysql_select_db ('test');
?>
</code>```

答:
If in your database table have Auto Increment value like id you need to declare inside the values field like this

INSERT INTO budget VALUES('','$type', '$description' , '$value')

If you want to what type of error for inserting in the query you need to check the what is the error. in yours, if condition be like

```<code>if(mysql_query("INSERT INTO budget VALUES('','$type', '$description' , '$value')"))
   echo "Successfully Inserted";
else
   echo "Error: <br>" . mysql_error($conn);
</code>```

And you need to change your default values like value, type this is no issue here but my advice is to avoid default words for define variable.

Final:

Avoid using MySQL because Mysql extension is deprecated as of PHP 5.5.0, and has been removed as of PHP 7.0.0. Instead

Body:
I use this code to insert the data selection from select tag in html but i doesn't work perfectly when i put a value number in text input i would like someone helps me with that. otherwise, when i click in add_btn without value the insertion of data is added in MySQL databases.

HTML->

  <form id="myForm" action="userInfo.php" method="post">
                    <select name="type" class="add__type" >
                        <option value="inc" selected>+</option>
                        <option value="exp">-</option>
                    </select>
                 <select  name="description" class="add__description" title="h" >
                   <option  value="Food">Food</option>
                   <option  value="Salary">Salary</option>
                   <option  value="Home">Home</option>
                   <option  value="Car">Car</option>
                   <option  value="Education">Education</option>
                   <option  value="Gift">Gift</option>
                   <option  value="Travle"> Travle </option>
                   <option  value="Fun">Fun</option>
                        </select>
                <input name="value" type="number" class="add__value">
           <button class="add__btn"></button>
            </form>

PHP-> userinfo.php

  <?php
        include_once('db.php');

        $type = $_POST['type'];
        $description = $_POST['description'];
        $value = $_POST['value'];

        if(mysql_query("INSERT INTO budget VALUES('$type', '$description' , '$value')"))
          echo "Successfully Inserted";
        else
          echo "Insertion Failed";
?>

PHP -> db.php

<?php
      $conn = mysql_connect ('localhost', 'root', '');
      $db   = mysql_select_db ('test');
?>

Body:
If in your database table have Auto Increment value like id you need to declare inside the values field like this

INSERT INTO budget VALUES('','$type', '$description' , '$value')

If you want to what type of error for inserting in the query you need to check the what is the error. in yours, if condition be like

if(mysql_query("INSERT INTO budget VALUES('','$type', '$description' , '$value')"))
   echo "Successfully Inserted";
else
   echo "Error: <br>" . mysql_error($conn);

And you need to change your default values like value, type this is no issue here but my advice is to avoid default words for define variable.

Final:

Avoid using MySQL because Mysql extension is deprecated as of PHP 5.5.0, and has been removed as of PHP 7.0.0. Instead


来源: stackexchange

问:
Advanced transparency in a form
Im looking for a way to create form(s) similar in style to the following two..

Ive played with transparency keys, the windows API, but have not successfully done this in Windows Forms.

[broken image]

what im looking for with this post is any references to articles explaining how this can be done, or some code examples. -- but i will accept any kind of input.

I would use Windows Vista/7 Areo glass if it didnt have such horrible alpha-blending issues.

答:
Refer to the link below for an article about how to find a way to show Windows standard controls on layered windows. It provides both Native MFC and WinForms source code.

Cool, Semi-transparent and Shaped Dialogs with Standard Controls for Windows 2000 and Above

Using the Code in WinForms/.NET

First Step:

Copy files in the /Src/. directory to your project.

Second Step

You need an image file to be the dialog background. You'd better
  choose PNG or TIFF which support alpha channel.

Final Step

Replace the dialog base class from Form to ImageDlgBase.

```<code>public partial class Form2 : CoolImageDlg.ImageDlgBase {
    public Form2()
    {
        base.DlgBgImg = ImgDlgSample.Properties.Resources.DemoDlgBg2;
        //......
     }
}
</code>```

See the example code in the article.

ContentLicense: CC BY-SA 4.0

Title: Advanced transparency in a form

Body:
Refer to the link below for an article about how to find a way to show Windows standard controls on layered windows. It provides both Native MFC and WinForms source code.

Cool, Semi-transparent and Shaped Dialogs with Standard Controls for Windows 2000 and Above

Using the Code in WinForms/.NET

First Step:

Copy files in the /Src/. directory to your project.

Second Step

You need an image file to be the dialog background. You'd better
  choose PNG or TIFF which support alpha channel.

Final Step

Replace the dialog base class from Form to ImageDlgBase.

public partial class Form2 : CoolImageDlg.ImageDlgBase {
    public Form2()
    {
        base.DlgBgImg = ImgDlgSample.Properties.Resources.DemoDlgBg2;
        //......
     }
}

See the example code in the article.

ContentLicense: CC BY-SA 3.0


问:
toggle pseudo class :active with css/jquery
i have a little css problem.
There is a div which is only display an image of an help mark. What i try is on clicking on this image the next div on the same level is display:inline-block. On a second click it is display:none again.

The display:inline-block on :active is working but it is not toggle.

There is JQuery:

```<code>(function($) {

// Execute after the page was fully
setTimeout( function(){
if ($('#jsonPayload').length) {
// scope to JSD
var banner = jQuery('<div class="helpmark">'
+ '<img class="emoticon" align="adsmiddle" src="@contextPath/plugins/cute/static/resource/SD-CGM-TT/help_16.gif" />'
+ ' @message'
+   '</div>');
banner.insertBefore('div.description');
}
}, 1)
})(jQuery);
</code>```

And the HTML around the Elements we are looking for

```<code><div class="helpmark">
    <img class="emoticon" src="http://*********/plugins/cute/static/resource/SD-CGM-TT/help_16.gif"> </div>
<div class="description">
    <p>Hier können Sie einen kurzen Betreff einfügen</p>
</div>
</code>```

by clicking on .helpmark .description is displayed

And the CSS i have

```<code>.helpmark {
    cursor: pointer;
    display: inline-block;
    margin-top: 5px;
}

.helpmark:active + .description {
    display: inline-block;
}

.description {
    display: none;
}
</code>```

I hope anybody can help me.

Best regards,
Stephan

答:
It is simple with jquery, Try the below code.

$('.helpmark').click(function(){
  $('.description').toggle();
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.helpmark{
  width: 30px;
  height: 30px;
  background: red;
}
.description{
  display: none;
}</code>```

Hier können Sie einen kurzen Betreff einfügen

```

Body:
i have a little css problem.
There is a div which is only display an image of an help mark. What i try is on clicking on this image the next div on the same level is display:inline-block. On a second click it is display:none again.

The display:inline-block on :active is working but it is not toggle.

There is JQuery:

(function($) {

// Execute after the page was fully
setTimeout( function(){
if ($('#jsonPayload').length) {
// scope to JSD
var banner = jQuery('
'
+ ''
+ ' @message'
+   '
');
banner.insertBefore('div.description');
}
}, 1)
})(jQuery);

And the HTML around the Elements we are looking for

Hier können Sie einen kurzen Betreff einfügen

by clicking on .helpmark .description is displayed

And the CSS i have

.helpmark {
    cursor: pointer;
    display: inline-block;
    margin-top: 5px;
}

.helpmark:active + .description {
    display: inline-block;
}

.description {
    display: none;
}

I hope anybody can help me.

Best regards,
Stephan

Body:
It is simple with jquery, Try the below code.

$('.helpmark').click(function(){
  $('.description').toggle();
});

.helpmark{
  width: 30px;
  height: 30px;
  background: red;
}
.description{
  display: none;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="helpmark"> </div>
<div class="description">
    <p>Hier können Sie einen kurzen Betreff einfügen</p>
</div>


问:
axios post request to send form data
axios POST request is hitting the url on the controller but setting null values to my POJO class, when I go through developer tools in chrome, the payload contains data. What am I doing wrong?

Axios POST Request:

```<code>var body = {
    userName: 'Fred',
    userEmail: 'Flintstone@gmail.com'
}

axios({
    method: 'post',
    url: '/addUser',
    data: body
})
.then(function (response) {
    console.log(response);
})
.catch(function (error) {
    console.log(error);
});
</code>```

Browser Response:

If I set headers as:

```<code>headers:{
  Content-Type:'multipart/form-data'
}
</code>```

The request throws the error

Error in posting multipart/form-data. Content-Type header is missing boundary

If I make the same request in postman it's working fine and sets values to my POJO class.

Can anyone explain how to set boundary or how can I send form data using axios.

答:
You can post axios data by using FormData() like:

var bodyFormData = new FormData();
```
<p>And then add the fields to the form you want to send:</p>
<pre class="lang-js prettyprint-override"><code>bodyFormData.append('userName', 'Fred');
</code>```

If you are uploading images, you may want to use .append

bodyFormData.append('image', imageFile);
```
<p>And then you can use axios post method (You can amend it accordingly)</p>
<pre class="lang-js prettyprint-override"><code>axios({
  method: "post",
  url: "myurl",
  data: bodyFormData,
  headers: { "Content-Type": "multipart/form-data" },
})
  .then(function (response) {
    //handle success
    console.log(response);
  })
  .catch(function (response) {
    //handle error
    console.log(response);
  });
</code>```

Related GitHub issue:

Can't get a .post with 'Content-Type': 'multipart/form-data' to work @ axios/axios

Title: axios post request to send form data

Body:
axios POST request is hitting the url on the controller but setting null values to my POJO class, when I go through developer tools in chrome, the payload contains data. What am I doing wrong?

Axios POST Request:

var body = {
    userName: 'Fred',
    userEmail: 'Flintstone@gmail.com'
}

axios({
    method: 'post',
    url: '/addUser',
    data: body
})
.then(function (response) {
    console.log(response);
})
.catch(function (error) {
    console.log(error);
});

Browser Response:

If I set headers as:

headers:{
  Content-Type:'multipart/form-data'
}

The request throws the error

Error in posting multipart/form-data. Content-Type header is missing boundary

If I make the same request in postman it's working fine and sets values to my POJO class.

Can anyone explain how to set boundary or how can I send form data using axios.

Body:
You can post axios data by using FormData() like:

var bodyFormData = new FormData();

And then add the fields to the form you want to send:

bodyFormData.append('userName', 'Fred');

If you are uploading images, you may want to use .append

bodyFormData.append('image', imageFile);

And then you can use axios post method (You can amend it accordingly)

axios({
  method: "post",
  url: "myurl",
  data: bodyFormData,
  headers: { "Content-Type": "multipart/form-data" },
})
  .then(function (response) {
    //handle success
    console.log(response);
  })
  .catch(function (response) {
    //handle error
    console.log(response);
  });

Related GitHub issue:

Can't get a .post with 'Content-Type': 'multipart/form-data' to work @ axios/axios


问:
JUnit Servlets testing with jndi lookup for the datasource
How to make unit test of servlets which uses jndi for lookup of datasource (JDBC) ?</p>

答:
I run the following code in the before class method.

```<code>    try {

        // Create initial context
        System.setProperty(Context.INITIAL_CONTEXT_FACTORY,
            "org.apache.naming.java.javaURLContextFactory");
        System.setProperty(Context.URL_PKG_PREFIXES,
            "org.apache.naming");
        InitialContext ic = new InitialContext();

        ic.createSubcontext("java:");
        ic.createSubcontext("java:/comp");
        ic.createSubcontext("java:/comp/env");
        ic.createSubcontext("java:/comp/env/jdbc");

        // Construct DataSource
        OracleConnectionPoolDataSource ds = new OracleConnectionPoolDataSource();
        ds.setURL(""); // <--insert url to database here
        ds.setUser("username"); //<-- self explanatory
        ds.setPassword("password"); //<-- self explanatory

        ic.bind("java:/comp/env/jdbc/examplename", ds); //<--insert name of binding here
    } catch (NamingException ex) {
        ex.printStackTrace();
    } catch (SQLException ex){
        ex.printStackTrace();
    }
</code>```

I am using Tomcat as my server so I also had to reference the following jar files located in the tomcat\bin directory:

tomcat-juli.jar

bootstrap.jar

commons-daemon.jar

I hope this helps you

ContentLicense: CC BY-SA 2.5

Body:
I run the following code in the before class method.

    try {

        // Create initial context
        System.setProperty(Context.INITIAL_CONTEXT_FACTORY,
            "org.apache.naming.java.javaURLContextFactory");
        System.setProperty(Context.URL_PKG_PREFIXES,
            "org.apache.naming");
        InitialContext ic = new InitialContext();

        ic.createSubcontext("java:");
        ic.createSubcontext("java:/comp");
        ic.createSubcontext("java:/comp/env");
        ic.createSubcontext("java:/comp/env/jdbc");

        // Construct DataSource
        OracleConnectionPoolDataSource ds = new OracleConnectionPoolDataSource();
        ds.setURL(""); // <--insert url to database here
        ds.setUser("username"); //<-- self explanatory
        ds.setPassword("password"); //<-- self explanatory

        ic.bind("java:/comp/env/jdbc/examplename", ds); //<--insert name of binding here
    } catch (NamingException ex) {
        ex.printStackTrace();
    } catch (SQLException ex){
        ex.printStackTrace();
    }

I am using Tomcat as my server so I also had to reference the following jar files located in the tomcat\bin directory:

tomcat-juli.jar

bootstrap.jar

commons-daemon.jar

I hope this helps you


问:
Read multi-line delimited sub-strings to bash array
I'd like to create array containing

```<code>Speed: 10500 Mbps
Size: 122400 MB
Load: 4544 Kg
Distance: 232680 miles
Acceleration: 11200 meters/s2
Deviation: 1100 Wierdos
</code>```

From the following code:

```<code>read -r -d '' TEST_STRING << EOM
Speed: 10500 Mbps; Size: 122400 MB
Load: 4544 Kg; Distance: 232680 miles
Acceleration: 11200 meters/s2; Deviation: 1100 Wierdos
EOM

STRINGS_ARRAY=()
RE_INTRALINEDELIMITER=";"

while IFS=$'\n' read -a LINE; do

    if [[ $LINE =~ $RE_INTRALINEDELIMITER ]]; then
        echo "(intraline): $LINE"
        while IFS=$';' read -a SUBSTR; do
            echo "(substr): $SUBSTR"
        done <<< "$LINE"

    fi

done <<< "$TEST_STRING"
</code>```

(echoes are added for debugging and as an empty operator). Then process lines with some functions and finally to assembly it back to the original string.

But for SUBSTR I get only first sub-string from every string (before semicolon). What I'm doing wrong?

答:
With read -ra you are basically reading into an array SUBSTR but only trying to print it in a string variable's context. Try printing the whole array, which should have the complete line stored.

```<code>echo "(substr): ${SUBSTR[@]}"
</code>```

Also mind the -a usage earlier in the code for LINE where you have the entire line stored as an array.

Also if you have pretty recent versions of bash installed, try using mapfile/readarray to parse multi-line output into an array. Your entire requirement could very well be reduced to

```<code>re_delimiter=';'
mapfile -t stringArray <<<"$TEST_STRING"
</code>```

This stores the entire string in the array, from which you loop over one entry at a time to see if the line has a ; character present. I have initialized wholeArray here to store all the ; delimited strings from all the lines in your input string.

```<code>wholeArray=()
for line in "${stringArray[@]}"; do
    substringArray=()
    if [[ $line =~ $re_delimiter ]]; then
        IFS=';' read -ra substringArray <<<"$line"
        wholeArray+=( "${substringArray[@]}" )
    fi
done
</code>```

and now print the entire array content as

```<code>declare -p wholeArray
declare -a wholeArray='([0]="Speed: 10500 Mbps" [1]=" Size: 122400 MB" [2]="Load: 4544 Kg" [3]=" Distance: 232680 miles" [4]="Acceleration: 11200 meters/s2" [5]=" Deviation: 1100 Wierdos")'
</code>```

(or) print the element one at a time using a proper for-loop

```<code>for entry in "${wholeArray[@]}"; do
    printf '%s\n' "$entry"
done
</code>```

Also always use upper-case variables to store variable names to not confuse with environment variables maintained by the shell.

Body:
I'd like to create array containing

Speed: 10500 Mbps
Size: 122400 MB
Load: 4544 Kg
Distance: 232680 miles
Acceleration: 11200 meters/s2
Deviation: 1100 Wierdos

From the following code:

read -r -d '' TEST_STRING << EOM
Speed: 10500 Mbps; Size: 122400 MB
Load: 4544 Kg; Distance: 232680 miles
Acceleration: 11200 meters/s2; Deviation: 1100 Wierdos
EOM

STRINGS_ARRAY=()
RE_INTRALINEDELIMITER=";"

while IFS=$'\n' read -a LINE; do

    if [[ $LINE =~ $RE_INTRALINEDELIMITER ]]; then
        echo "(intraline): $LINE"
        while IFS=$';' read -a SUBSTR; do
            echo "(substr): $SUBSTR"
        done <<< "$LINE"

    fi

done <<< "$TEST_STRING"

(echoes are added for debugging and as an empty operator). Then process lines with some functions and finally to assembly it back to the original string.

But for SUBSTR I get only first sub-string from every string (before semicolon). What I'm doing wrong?

Body:
With read -ra you are basically reading into an array SUBSTR but only trying to print it in a string variable's context. Try printing the whole array, which should have the complete line stored.

echo "(substr): ${SUBSTR[@]}"

Also mind the -a usage earlier in the code for LINE where you have the entire line stored as an array.

Also if you have pretty recent versions of bash installed, try using mapfile/readarray to parse multi-line output into an array. Your entire requirement could very well be reduced to

re_delimiter=';'
mapfile -t stringArray <<<"$TEST_STRING"

This stores the entire string in the array, from which you loop over one entry at a time to see if the line has a ; character present. I have initialized wholeArray here to store all the ; delimited strings from all the lines in your input string.

wholeArray=()
for line in "${stringArray[@]}"; do
    substringArray=()
    if [[ $line =~ $re_delimiter ]]; then
        IFS=';' read -ra substringArray <<<"$line"
        wholeArray+=( "${substringArray[@]}" )
    fi
done

and now print the entire array content as

declare -p wholeArray
declare -a wholeArray='([0]="Speed: 10500 Mbps" [1]=" Size: 122400 MB" [2]="Load: 4544 Kg" [3]=" Distance: 232680 miles" [4]="Acceleration: 11200 meters/s2" [5]=" Deviation: 1100 Wierdos")'

(or) print the element one at a time using a proper for-loop

for entry in "${wholeArray[@]}"; do
    printf '%s\n' "$entry"
done

Also always use upper-case variables to store variable names to not confuse with environment variables maintained by the shell.


问:
ScrollView's scroll is not working inside bottomsheet?
I've placed an edit text inside a NestedScrollView so that the edit text can be expanded .But the problem is this NestedScrollView is placed inside a BottomSheet that's why the scrollview is not scrolled.
I wonder how to make the NestedScrollView scroll?

My Code :

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
<RelativeLayout
android:id="@+id/relBot"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
app:layout_behavior="@string/bottom_sheet_behavior"
android:background="#fff"
android:orientation="vertical">
<View
    android:id="@+id/hBot"
    android:layout_width="match_parent"
    android:layout_height="44dp"
    android:background="@drawable/shadow"
    />
<TextView
    android:id="@+id/headingBot"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:text="Comments"
    android:textColor="#fff"
    android:layout_marginTop="2dp"
    android:textSize="25sp"
    android:textStyle="bold"
    android:fontFamily="sans-serif-condensed"
    />
<ImageView
    android:id="@+id/back_of_bot"
    android:layout_width="30dp"
    android:layout_height="30dp"
    android:layout_marginTop="5dp"
    android:tint="#fff"
    android:clickable="true"
    android:src="@drawable/ic_arrow_left_black_48dp" />

<android.support.v7.widget.RecyclerView
 android:id="@+id/botRView"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:layout_marginTop="10dp"
 android:layout_below="@+id/hBot"
 android:layout_above="@+id/linLayCommi"/>
<android.support.v4.widget.NestedScrollView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/linLayCommi"
    android:clickable="true"
    android:focusable="true"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    android:layout_alignParentBottom="true">
<android.support.v7.widget.CardView
 android:layout_width="match_parent"
 android:layout_height="50dp"
 app:cardBackgroundColor="#efeeee"
 android:orientation="vertical">
<EditText
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginRight="40dp"
    android:layout_marginEnd="40dp"
    android:imeOptions="actionDone"
    android:hint="Write a Comment..."
    app:backgroundTint="#efeeee"/>
 <LinearLayout
     android:layout_width="40dp"
     android:layout_height="match_parent"
     android:layout_gravity="end"
     android:clickable="true"
     android:gravity="center"
     android:background="#001919">

     <ImageView
         android:layout_width="30dp"
         android:layout_height="25dp"
         android:tint="#fff"
         app:srcCompat="@drawable/emoji_1f58b" />
 </LinearLayout>
</android.support.v7.widget.CardView>
</android.support.v4.widget.NestedScrollView>
</RelativeLayout>
</android.support.design.widget.CoordinatorLayout>
</code>```

答:
After a lot of research I finally solved my issue by placing the scrollview inside a trasperent linear layout as we can't set maxHeight of any view in xml and now it's scrolling .
Ref :https://stackoverflow.com/a/13811461/8953835</p>

Body:
I've placed an edit text inside a NestedScrollView so that the edit text can be expanded .But the problem is this NestedScrollView is placed inside a BottomSheet that's why the scrollview is not scrolled.
I wonder how to make the NestedScrollView scroll?

My Code :

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
<RelativeLayout
android:id="@+id/relBot"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
app:layout_behavior="@string/bottom_sheet_behavior"
android:background="#fff"
android:orientation="vertical">
<View
    android:id="@+id/hBot"
    android:layout_width="match_parent"
    android:layout_height="44dp"
    android:background="@drawable/shadow"
    />
<TextView
    android:id="@+id/headingBot"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:text="Comments"
    android:textColor="#fff"
    android:layout_marginTop="2dp"
    android:textSize="25sp"
    android:textStyle="bold"
    android:fontFamily="sans-serif-condensed"
    />
<ImageView
    android:id="@+id/back_of_bot"
    android:layout_width="30dp"
    android:layout_height="30dp"
    android:layout_marginTop="5dp"
    android:tint="#fff"
    android:clickable="true"
    android:src="@drawable/ic_arrow_left_black_48dp" />

<android.support.v7.widget.RecyclerView
 android:id="@+id/botRView"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:layout_marginTop="10dp"
 android:layout_below="@+id/hBot"
 android:layout_above="@+id/linLayCommi"/>
<android.support.v4.widget.NestedScrollView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/linLayCommi"
    android:clickable="true"
    android:focusable="true"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    android:layout_alignParentBottom="true">
<android.support.v7.widget.CardView
 android:layout_width="match_parent"
 android:layout_height="50dp"
 app:cardBackgroundColor="#efeeee"
 android:orientation="vertical">
<EditText
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginRight="40dp"
    android:layout_marginEnd="40dp"
    android:imeOptions="actionDone"
    android:hint="Write a Comment..."
    app:backgroundTint="#efeeee"/>
 <LinearLayout
     android:layout_width="40dp"
     android:layout_height="match_parent"
     android:layout_gravity="end"
     android:clickable="true"
     android:gravity="center"
     android:background="#001919">

     <ImageView
         android:layout_width="30dp"
         android:layout_height="25dp"
         android:tint="#fff"
         app:srcCompat="@drawable/emoji_1f58b" />
 </LinearLayout>
</android.support.v7.widget.CardView>
</android.support.v4.widget.NestedScrollView>
</RelativeLayout>
</android.support.design.widget.CoordinatorLayout>


问:
HTML Table with curved linked heading

I'm trying to achieve this type of table so that I can have extended labels for columns. But I don't even know what it's called to try and describe it in a search.

Edit
I can find how to round html borders with CSS. But that doesn't help with linking rows to columns. I can rotate the column header text, but again, that isn't what I'm after.

The closest thing I can come up with is a full table with borders or a background colour to highlight the connection, but this would be squared instead of rounded.

I'm wondering if there is a method of achieving this with css. Or alternatively a library which would do the same thing.

答:
??? Use id or number + legend

#1 #2 #3
left mid right
L M R

Or, may be better, if you create image.

But, you can still use border-radius + position in table row. May be its not work cross-browser, as you wish.

http://border-radius.com

(write 40 to black input box on site, for example)

Title: HTML Table with curved linked heading


问:
Powershell replacing string with multiple values
I am new to powershell. Here are some code examples will help me to explain:

The first example gives the correct output I want which is a list of values, two values in this example, under OrganizationalUnitDistinguishedNames

```<code>PS C:\Users\Administrator\Desktop> $test=Get-APSDirectoryConfigList -DirectoryName test.com
PS C:\Users\Administrator\Desktop> $test

CreatedTime          DirectoryName OrganizationalUnitDistinguishedNames ServiceAccountCredentials
-----------          ------------- ------------------------------------ -------------------------
12/4/2017 9:26:50 AM test.com      {OU=t1,DC=acc, OU=t2,DC=test}        Amazon.AppStream.Model.ServiceAccountCredentials

PS C:\Users\Administrator\Desktop> $test.OrganizationalUnitDistinguishedNames
OU=t1,DC=acc
OU=t2,DC=test
</code>```

However, the following command treats two values "OU=t2,DC=test,OU=t1,DC=acc" as a single string. What is the correct syntax to create with two separate values instead of a single string? I have tried different ways (with or without double quotes), they don't work.

```<code>PS C:\Users\Administrator\Desktop> $test=New-APSDirectoryConfig -DirectoryName test.com -OrganizationalUnitDistinguishedName "OU=t2,DC=test,OU=t1,DC=acc" -ServiceAcco
untCredentials_AccountName TEST\serviceaccount -ServiceAccountCredentials_AccountPassword secret_password
PS C:\Users\Administrator\Desktop> $test

CreatedTime          DirectoryName OrganizationalUnitDistinguishedNames ServiceAccountCredentials
-----------          ------------- ------------------------------------ -------------------------
12/4/2017 9:33:25 AM test.com      {OU=t2,DC=test,OU=t1,DC=acc}         Amazon.AppStream.Model.ServiceAccountCredentials

PS C:\Users\Administrator\Desktop> $test.OrganizationalUnitDistinguishedNames
OU=t2,DC=test,OU=t1,DC=acc
</code>```

答:
Try:

```<code>$OUDNArray = @("OU=t2,DC=test","OU=t1,DC=acc")
$test=New-APSDirectoryConfig -DirectoryName test.com -OrganizationalUnitDistinguishedName $OUDNArray -ServiceAccountCredentials_AccountName TEST\serviceaccount -ServiceAccountCredentials_AccountPassword T3st12345
</code>```

According to the AWS Appstream Docs:

Parameters

-OrganizationalUnitDistinguishedName <String[]>
The distinguished names of the organizational units for computer accounts.
  Required? False Position? Named Accept pipeline input?    False

The OrganizationalUnitDistinguishedName accepts an array.

Body:
I am new to powershell. Here are some code examples will help me to explain:

The first example gives the correct output I want which is a list of values, two values in this example, under OrganizationalUnitDistinguishedNames

PS C:\Users\Administrator\Desktop> $test=Get-APSDirectoryConfigList -DirectoryName test.com
PS C:\Users\Administrator\Desktop> $test

CreatedTime          DirectoryName OrganizationalUnitDistinguishedNames ServiceAccountCredentials
-----------          ------------- ------------------------------------ -------------------------
12/4/2017 9:26:50 AM test.com      {OU=t1,DC=acc, OU=t2,DC=test}        Amazon.AppStream.Model.ServiceAccountCredentials

PS C:\Users\Administrator\Desktop> $test.OrganizationalUnitDistinguishedNames
OU=t1,DC=acc
OU=t2,DC=test

However, the following command treats two values "OU=t2,DC=test,OU=t1,DC=acc" as a single string. What is the correct syntax to create with two separate values instead of a single string? I have tried different ways (with or without double quotes), they don't work.

PS C:\Users\Administrator\Desktop> $test=New-APSDirectoryConfig -DirectoryName test.com -OrganizationalUnitDistinguishedName "OU=t2,DC=test,OU=t1,DC=acc" -ServiceAcco
untCredentials_AccountName TEST\serviceaccount -ServiceAccountCredentials_AccountPassword secret_password
PS C:\Users\Administrator\Desktop> $test

CreatedTime          DirectoryName OrganizationalUnitDistinguishedNames ServiceAccountCredentials
-----------          ------------- ------------------------------------ -------------------------
12/4/2017 9:33:25 AM test.com      {OU=t2,DC=test,OU=t1,DC=acc}         Amazon.AppStream.Model.ServiceAccountCredentials

PS C:\Users\Administrator\Desktop> $test.OrganizationalUnitDistinguishedNames
OU=t2,DC=test,OU=t1,DC=acc

Body:
Try:

$OUDNArray = @("OU=t2,DC=test","OU=t1,DC=acc")
$test=New-APSDirectoryConfig -DirectoryName test.com -OrganizationalUnitDistinguishedName $OUDNArray -ServiceAccountCredentials_AccountName TEST\serviceaccount -ServiceAccountCredentials_AccountPassword T3st12345

According to the AWS Appstream Docs:

Parameters

-OrganizationalUnitDistinguishedName <String[]>
The distinguished names of the organizational units for computer accounts.
  Required? False Position? Named Accept pipeline input?    False

The OrganizationalUnitDistinguishedName accepts an array.


问:
Google Places API for iOS not letting me cancel or select
I have followed the Places API tutorial on Google's website, and I have double checked that the Places API for iOS is enabled and that my API key is in my AppDelegate. I have definitely implemented GMSPlacePickerViewControllerDelegate in my class. The Places Picker will open, I can view places, and I can tap on them, and I can search. I cannot get out of this screen, I cannot cancel, I cannot actually select anything or return a location. This is the same on a physical device and on the simulator. Why doesn't it work, and how can I make it work?</p>

```<code>@IBAction func selectLocationPressed(_ sender: Any) {
    let config = GMSPlacePickerConfig(viewport: nil)
    let placePicker = GMSPlacePickerViewController(config: config)
    present(placePicker, animated: true, completion: nil)
}

// To receive the results from the place picker 'self' will need to conform to
// GMSPlacePickerViewControllerDelegate and implement this code.
func placePicker(_ viewController: GMSPlacePickerViewController,
didPick place: GMSPlace) {
// Dismiss the place picker, as it cannot dismiss itself.
viewController.dismiss(animated: true, completion: nil)

print("Place name \(place.name)")
print("Place address \(place.formattedAddress)")
print("Place attributions \(place.attributions)")
}

func placePickerDidCancel(_ viewController:
GMSPlacePickerViewController) {
// Dismiss the place picker, as it cannot dismiss itself.
viewController.dismiss(animated: true, completion: nil)

print("No place selected")
}
</code>```

答: Implement GMSPlacePickerViewControllerDelegate protocol in your class and set placePicker.delegate = self

Body:
I have followed the Places API tutorial on Google's website, and I have double checked that the Places API for iOS is enabled and that my API key is in my AppDelegate. I have definitely implemented GMSPlacePickerViewControllerDelegate in my class. The Places Picker will open, I can view places, and I can tap on them, and I can search. I cannot get out of this screen, I cannot cancel, I cannot actually select anything or return a location. This is the same on a physical device and on the simulator. Why doesn't it work, and how can I make it work?

@IBAction func selectLocationPressed(_ sender: Any) {
    let config = GMSPlacePickerConfig(viewport: nil)
    let placePicker = GMSPlacePickerViewController(config: config)
    present(placePicker, animated: true, completion: nil)
}

// To receive the results from the place picker 'self' will need to conform to
// GMSPlacePickerViewControllerDelegate and implement this code.
func placePicker(_ viewController: GMSPlacePickerViewController,
didPick place: GMSPlace) {
// Dismiss the place picker, as it cannot dismiss itself.
viewController.dismiss(animated: true, completion: nil)

print("Place name \(place.name)")
print("Place address \(place.formattedAddress)")
print("Place attributions \(place.attributions)")
}

func placePickerDidCancel(_ viewController:
GMSPlacePickerViewController) {
// Dismiss the place picker, as it cannot dismiss itself.
viewController.dismiss(animated: true, completion: nil)

print("No place selected")
}


问:
Collection View Header not showing
I am currently implementing infinite scrolling using collectionView by following this link. But I got stuck when I have to add collectionView sectionheader. The header doesn't shows up when I am implemeting the above link custom flow layout, but if I use default UICollectionViewLayout it's been displayed.

Implemented the method : -

```<code>func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize
</code>```

答:
```<code>func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize
</code>```

<p>This function is important for giving the size for collection view section header , and if you using the UICollectionViewLayout functions and pass the attribute layout then "referenceSizeForHeaderInSection"  method is not need to implement </p>

```<code>layoutAttributesForElements(in rect:)
</code>```

Title: Collection View Header not showing

Body:
I am currently implementing infinite scrolling using collectionView by following this link. But I got stuck when I have to add collectionView sectionheader. The header doesn't shows up when I am implemeting the above link custom flow layout, but if I use default UICollectionViewLayout it's been displayed.

Implemented the method : -

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize

Body:
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize

This function is important for giving the size for collection view section header , and if you using the UICollectionViewLayout functions and pass the attribute layout then "referenceSizeForHeaderInSection"  method is not need to implement

layoutAttributesForElements(in rect:)


问:
Install4j - macOS single bundle
I have native macOS application and I need to wrap it to Install4j.
I'm able to make media: macOS folder only. I'm trying to change media type to macOS single bundle, but launcher is required for this bundle. I need to use 'macOS single bundle' because 'macOS folder' media automatically creates folder for application and customer doesn't want it.

I found that macOS single bundle accept only 'Generated launcher' not 'External launcher'. But 'Generated launcher' is for java application only, isn't it?
So is there any way how to make 'macOS single bundle' media for native macOS application?
Thanks.

答: As of install4j 7.0, using a native executable for the single bundle media file on macOS is not supported.</p>

Title: Install4j - macOS single bundle


问:
In Java, can the this/super keywords represent anything other than classes/enums?
I've noticed that:

```<code>class A {
    ClassB b = new ClassB() { // anonymous class
        /* some expression using this */
    }
}
</code>```

Whenever I use the this keyword inside an anonymous class, the this refers to the enclosing outer class/enum and not to the anonymous class.

Does this mean this can never represent an anonymous class? Just "normal" classes and enums?

Also, can this or super represent an interface?

答:
Your statement about using this is incorrect.  When you use this inside an anonymous class, it always refers to the anonymous class.  It never refers to the enclosing outer class unless you use OuterClassName.this.

this or super can never represent an interface, since an interface cannot have defined methods.

Body:
I've noticed that:

class A {
    ClassB b = new ClassB() { // anonymous class
        /* some expression using this */
    }
}

Whenever I use the this keyword inside an anonymous class, the this refers to the enclosing outer class/enum and not to the anonymous class.

Does this mean this can never represent an anonymous class? Just "normal" classes and enums?

Also, can this or super represent an interface?


问:
How to use iOS 11.1 device with Xcode 8 or earlier?
I want to install my app on iOS 11 device using xcode8. I don't wan't to update xcode.</p>

答: You can update it to test flight. Once you did that, you can download it on your iOS 11 device. Of course you need an official development account from Apple.(Paying the 99 euros). But that's the only way.</p>


问:
PHP MYSQL: two while echo from two table to create an ajax live search
My project involves the creation of an Ajax live search which will display the cities and hotels, taken from two separate tables, based on the text entered in the input field.

The code works regularly if I set a single while, but the cities and hotels are displayed alternately. Instead, I would like the results to be divided; that is, first the hotels, then the cities.

I created the following code:

```<code>if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}

$term = mysqli_real_escape_string($link, $_REQUEST['term']);
if(isset($term)){
$sql = "select * FROM pt_locations WHERE location LIKE '" . $term . "%' LIMIT 3";

if($result = mysqli_query($link, $sql)){
    if(mysqli_num_rows($result) > 0){
        while($row = mysqli_fetch_array($result)){
            $ID_city = $row['ID'];

            $sql2 = "select hotel_title FROM pt_hotels WHERE hotel_code LIKE '" . $ID_city . "%' LIMIT 3";
                if($result = mysqli_query($link, $sql2)){
                    if(mysqli_num_rows($result2) > 0){
                        while($row2 = mysqli_fetch_array($result2)){
                        echo "<div id='wrap_search'><div id='left_col'><img src='images/hotel.png' alt='icon search hotel'></div>";
                        echo "<div id='right_col'><p>" . substr($row2['hotel_title'], 0, 25) . " ... "."</p></div></div>";

                        }

                    }

                }

            echo "<div id='wrap_search'><div id='left_col'><img src='images/background-world-map.png' alt='icon search city'></div>";
            echo "<div id='right_col'><p>" . $row['location'] . ' - ' . $row['country'] . "</p></div></div>";
        }
        // Close result set
        mysqli_free_result($result);
    } else{
        echo "<p>Nessun risultato</p>";
    }
} else{
    echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
}

mysqli_close($link);
</code>```

but returns the error:

```<code>Parse error: syntax error, unexpected '$sql2' (T_VARIABLE) in /var/www/vhosts/allrentis.com/car.allrentis.com/definitivo/backend-search.php on line 25
</code>```

答:
you missed the semicolon (;) in the end of following line

```<code>$ID_city = $row['ID'];
</code>```

Body:
My project involves the creation of an Ajax live search which will display the cities and hotels, taken from two separate tables, based on the text entered in the input field.

The code works regularly if I set a single while, but the cities and hotels are displayed alternately. Instead, I would like the results to be divided; that is, first the hotels, then the cities.

I created the following code:

if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}

$term = mysqli_real_escape_string($link, $_REQUEST['term']);
if(isset($term)){
$sql = "select * FROM pt_locations WHERE location LIKE '" . $term . "%' LIMIT 3";

if($result = mysqli_query($link, $sql)){
    if(mysqli_num_rows($result) > 0){
        while($row = mysqli_fetch_array($result)){
            $ID_city = $row['ID'];

            $sql2 = "select hotel_title FROM pt_hotels WHERE hotel_code LIKE '" . $ID_city . "%' LIMIT 3";
                if($result = mysqli_query($link, $sql2)){
                    if(mysqli_num_rows($result2) > 0){
                        while($row2 = mysqli_fetch_array($result2)){
                        echo "

";
                        echo "

" . substr($row2['hotel_title'], 0, 25) . " ... "."

";

                        }

                    }

                }

            echo "

";
            echo "

" . $row['location'] . ' - ' . $row['country'] . "

";
        }
        // Close result set
        mysqli_free_result($result);
    } else{
        echo "
Nessun risultato
";
    }
} else{
    echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
}

mysqli_close($link);

but returns the error:

Parse error: syntax error, unexpected '$sql2' (T_VARIABLE) in /var/www/vhosts/allrentis.com/car.allrentis.com/definitivo/backend-search.php on line 25

Body:
you missed the semicolon (;) in the end of following line

$ID_city = $row['ID'];


问:
How to count the number of letters in a string without the spaces?
This is my solution resulting in an error. Returns 0

PS: I'd still love a fix to my code :)

```<code>from collections import Counter
import string

def count_letters(word):
    global count
    wordsList = string.split(word)
    count = Counter()
    for words in wordsList:
        for letters in set(words):
            return count[letters]

word = "The grey old fox is an idiot"
print count_letters(word)
</code>```

答:
```<code>word_display = ""
for letter in word:
    if letter in known:
        word_display = "%s%s " % (word_display, letter)
    else:
        word_display = "%s_ " % word_display
return word_display
</code>```

Body:
This is my solution resulting in an error. Returns 0

PS: I'd still love a fix to my code :)

from collections import Counter
import string

def count_letters(word):
    global count
    wordsList = string.split(word)
    count = Counter()
    for words in wordsList:
        for letters in set(words):
            return count[letters]

word = "The grey old fox is an idiot"
print count_letters(word)


问:
Android getting an image from gallery comes rotated
I am trying to let users select a profile picture from gallery. My issue is that some pictures come as rotated to the right.

I start the image picker like so:

```<code>Intent photoPickerIntent = new Intent();
photoPickerIntent.setType("image/*");
photoPickerIntent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(photoPickerIntent, "Select profile picture"), Global.CODE_SELECT_PICTURE);
</code>```

I get the image from onActivityResult like so:

```<code>Uri selectedPicture = data.getData();
profilePic = MediaStore.Images.Media.getBitmap(activity.getContentResolver(), selectedPicture);
</code>```

How can i make have images not to be rotated?

UPDATE:

Following some of the helpful answers i have received, i managed to come up with the following working solution (It's just a working code, not well written). I would love to get your feedback on how i can improve it!

```<code>public void onActivityResult(int requestCode, int resultCode, Intent data) {

    if (resultCode == Activity.RESULT_OK && requestCode == Global.CODE_SELECT_PICTURE) {

        // Get selected gallery image
        Uri selectedPicture = data.getData();
        // Get and resize profile image
        String[] filePathColumn = {MediaStore.Images.Media.DATA};
        Cursor cursor = activity.getContentResolver().query(selectedPicture, filePathColumn, null, null, null);
        cursor.moveToFirst();

        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
        String picturePath = cursor.getString(columnIndex);
        cursor.close();

        Bitmap loadedBitmap = BitmapFactory.decodeFile(picturePath);

        ExifInterface exif = null;
        try {
            File pictureFile = new File(picturePath);
            exif = new ExifInterface(pictureFile.getAbsolutePath());
        } catch (IOException e) {
            e.printStackTrace();
        }

        int orientation = ExifInterface.ORIENTATION_NORMAL;

        if (exif != null)
            orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);

        switch (orientation) {
            case ExifInterface.ORIENTATION_ROTATE_90:
                loadedBitmap = rotateBitmap(loadedBitmap, 90);
                break;
            case ExifInterface.ORIENTATION_ROTATE_180:
                loadedBitmap = rotateBitmap(loadedBitmap, 180);
                break;

            case ExifInterface.ORIENTATION_ROTATE_270:
                loadedBitmap = rotateBitmap(loadedBitmap, 270);
                break;
        }
    }
}

public static Bitmap rotateBitmap(Bitmap bitmap, int degrees) {
    Matrix matrix = new Matrix();
    matrix.postRotate(degrees);
    return Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
}
</code>```

答:
2 One line solutions using Picasso and glide library

After spending a lot of time with a lot of solutions for image rotation problem I finally found two simple solutions. We don't need to do any additional works.

Using Picasso library https://github.com/square/picasso

```<code>Picasso.with(context).load("http url or sdcard url").into(imageView);
</code>```

Using glide library  https://github.com/bumptech/glide

```<code>Glide.with(this).load("http url or sdcard url").into(imgageView);
</code>```

Picasso and Glide are a very powerful library for handling images in your app includes. It will read image EXIF data and auto-rotates the images.

Body:
I am trying to let users select a profile picture from gallery. My issue is that some pictures come as rotated to the right.

I start the image picker like so:

Intent photoPickerIntent = new Intent();
photoPickerIntent.setType("image/*");
photoPickerIntent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(photoPickerIntent, "Select profile picture"), Global.CODE_SELECT_PICTURE);

I get the image from onActivityResult like so:

Uri selectedPicture = data.getData();
profilePic = MediaStore.Images.Media.getBitmap(activity.getContentResolver(), selectedPicture);

How can i make have images not to be rotated?

UPDATE:

Following some of the helpful answers i have received, i managed to come up with the following working solution (It's just a working code, not well written). I would love to get your feedback on how i can improve it!

public void onActivityResult(int requestCode, int resultCode, Intent data) {

    if (resultCode == Activity.RESULT_OK && requestCode == Global.CODE_SELECT_PICTURE) {

        // Get selected gallery image
        Uri selectedPicture = data.getData();
        // Get and resize profile image
        String[] filePathColumn = {MediaStore.Images.Media.DATA};
        Cursor cursor = activity.getContentResolver().query(selectedPicture, filePathColumn, null, null, null);
        cursor.moveToFirst();

        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
        String picturePath = cursor.getString(columnIndex);
        cursor.close();

        Bitmap loadedBitmap = BitmapFactory.decodeFile(picturePath);

        ExifInterface exif = null;
        try {
            File pictureFile = new File(picturePath);
            exif = new ExifInterface(pictureFile.getAbsolutePath());
        } catch (IOException e) {
            e.printStackTrace();
        }

        int orientation = ExifInterface.ORIENTATION_NORMAL;

        if (exif != null)
            orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);

        switch (orientation) {
            case ExifInterface.ORIENTATION_ROTATE_90:
                loadedBitmap = rotateBitmap(loadedBitmap, 90);
                break;
            case ExifInterface.ORIENTATION_ROTATE_180:
                loadedBitmap = rotateBitmap(loadedBitmap, 180);
                break;

            case ExifInterface.ORIENTATION_ROTATE_270:
                loadedBitmap = rotateBitmap(loadedBitmap, 270);
                break;
        }
    }
}

public static Bitmap rotateBitmap(Bitmap bitmap, int degrees) {
    Matrix matrix = new Matrix();
    matrix.postRotate(degrees);
    return Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
}

Body:
2 One line solutions using Picasso and glide library

After spending a lot of time with a lot of solutions for image rotation problem I finally found two simple solutions. We don't need to do any additional works.

Using Picasso library https://github.com/square/picasso

Picasso.with(context).load("http url or sdcard url").into(imageView);

Using glide library  https://github.com/bumptech/glide

Glide.with(this).load("http url or sdcard url").into(imgageView);

Picasso and Glide are a very powerful library for handling images in your app includes. It will read image EXIF data and auto-rotates the images.


问:
pydevd trigger CMD_ADD_EXCEPTION_BREAK from runtime code
Using pydevd, is there a way that I can turn on & off suspending code on uncaught exceptions directly from the runtime code (rather than from the debug server), similar to how adding pydevd.settrace() behaves as a breakpoint?

Basically, I have a large application that uses generators and threading to process and manipulate lots of data. Because of this, manually setting breakpoints can be quite cumbersome. Currently I'll inspect the stack trace, inspect the code, and try to construct a conditional pydevd.settrace() that will hopefully only trigger when the offending scenario is hit. This takes a good bit of trial and error.

What I'd love to do is make (or use) a context manager and wrap the offending code like this

```<code>with pydevd.suspend_on_exception():
    ... code causing eventual exception ...
</code>```

I've dug around the pydevd code, and tried (with no luck) various incantations to try to simulate what I think the remote debugger is doing. I thought the following would get me close, but no dice.

```<code>debugger = pydevd.get_global_debugger()
ex = debugger.add_break_on_exception('Exception', True, True, False, True)
debugger.update_after_exceptions_added([ex])
debugger.enable_tracing_in_frames_while_running_if_frame_eval()
</code>```

(roughly based on https://github.com/fabioz/PyDev.Debugger/blob/master/_pydevd_bundle/pydevd_process_net_command.py#L496)

I'm using pydevd to connect to a PyCharm remote debugging server, in case that makes a difference in the solution.

答:
That code seems correct for me...

i.e.: Running the code:

```<code>if __name__ == '__main__':
    import pydevd
    debugger = pydevd.get_global_debugger()
    ex = debugger.add_break_on_exception('Exception', True, True, False, True)
    debugger.update_after_exceptions_added([ex])
    debugger.enable_tracing_in_frames_while_running_if_frame_eval()

    def foo():
        raise Exception()

    foo()
</code>```

does stop in the proper exception here.

Note: this is actually tested on the latest PyDev, not on PyCharm, but the behavior should be the same.

Body:
Using pydevd, is there a way that I can turn on & off suspending code on uncaught exceptions directly from the runtime code (rather than from the debug server), similar to how adding pydevd.settrace() behaves as a breakpoint?

Basically, I have a large application that uses generators and threading to process and manipulate lots of data. Because of this, manually setting breakpoints can be quite cumbersome. Currently I'll inspect the stack trace, inspect the code, and try to construct a conditional pydevd.settrace() that will hopefully only trigger when the offending scenario is hit. This takes a good bit of trial and error.

What I'd love to do is make (or use) a context manager and wrap the offending code like this

with pydevd.suspend_on_exception():
    ... code causing eventual exception ...

I've dug around the pydevd code, and tried (with no luck) various incantations to try to simulate what I think the remote debugger is doing. I thought the following would get me close, but no dice.

debugger = pydevd.get_global_debugger()
ex = debugger.add_break_on_exception('Exception', True, True, False, True)
debugger.update_after_exceptions_added([ex])
debugger.enable_tracing_in_frames_while_running_if_frame_eval()

(roughly based on https://github.com/fabioz/PyDev.Debugger/blob/master/_pydevd_bundle/pydevd_process_net_command.py#L496)

I'm using pydevd to connect to a PyCharm remote debugging server, in case that makes a difference in the solution.

Body:
That code seems correct for me...

i.e.: Running the code:

if __name__ == '__main__':
    import pydevd
    debugger = pydevd.get_global_debugger()
    ex = debugger.add_break_on_exception('Exception', True, True, False, True)
    debugger.update_after_exceptions_added([ex])
    debugger.enable_tracing_in_frames_while_running_if_frame_eval()

    def foo():
        raise Exception()

    foo()

does stop in the proper exception here.

Note: this is actually tested on the latest PyDev, not on PyCharm, but the behavior should be the same.


问:
Set service Startup type in WiX installer
I am trying to set a pre-installed service's startup type to Automatic, using WiX. Another task was to start the service on install, which I achieved with:

```<code><ServiceControl
    Id="ServiceRunningState"
    Name="[Service Name]"
    Start="install"
    Stop="install"
    Wait="yes" />
</code>```

Now I would also like to set the startup type. I have tried the following (see answer):

```<code><ServiceConfig
    Id="ServiceStartup"
    ServiceName="[Service Name]"
    DelayedAutoStart="yes"
    OnInstall="yes"
    OnReinstall="yes" />
</code>```

But this didn't change the startup type of the service (tested from Manual startup type). And besides, I want the startup type to be Automatic, not Automatic (Delayed Start).

Please note that I am trying to modify an existing service, so there is no ServiceInstall element.

The two elements (ServiceControl and ServiceConfig) are children within a Component parent element.

Any help is appreciated :)

答: Set the "DelayedAutoStart" parameter to "no", rather than "yes".</p>

Body:
I am trying to set a pre-installed service's startup type to Automatic, using WiX. Another task was to start the service on install, which I achieved with:

<ServiceControl
    Id="ServiceRunningState"
    Name="[Service Name]"
    Start="install"
    Stop="install"
    Wait="yes" />

Now I would also like to set the startup type. I have tried the following (see answer):

<ServiceConfig
    Id="ServiceStartup"
    ServiceName="[Service Name]"
    DelayedAutoStart="yes"
    OnInstall="yes"
    OnReinstall="yes" />

But this didn't change the startup type of the service (tested from Manual startup type). And besides, I want the startup type to be Automatic, not Automatic (Delayed Start).

Please note that I am trying to modify an existing service, so there is no ServiceInstall element.

The two elements (ServiceControl and ServiceConfig) are children within a Component parent element.

Any help is appreciated :)


问:
How to reset Sqlite primary Id
Let's say I have Sqlite table with a column which its datatype is INTEGER PRIMARY KEY AUTOINCREMENT
If I add a row into it I get a row with id of 1, then if I delete that row and add another row its id will be 2 instead of 1

How can I decrement the id whenever I delete a row?

Thank you

答:
You cannot tweak an auto-incremented id manually as you edit the table, because it's meant to work that way. If it could go back and forth, you wouldn't be able to assert that the ID would be unique.

The best options you currently have are:

Use a GUID instead, which solves your uniqueness issue for 99.999% of your cases.

Add a manually-filled order field. You can use this field separately to calculate the number you want to use.

Truncate the table. If you do this, you'll reset the table's ID, but you'll lose the data.

Title: How to reset Sqlite primary Id


问:
Sending byte array to printer directly
My service converts report into a byte array and passes to client(wpf app) using the following code:

```<code>byte[] bytes = renderer.ServerReport.Render("PDF", deviceInfo, out mimeType, out encoding, out extension, out streamids, out warnings);
</code>```

where renderer is an instance of Microsoft.Reporting.Webforms.ReportViewer. There is a problem here: encoding output parameter is returning null, so couldn't findout information about encoding.

The UI has to print this byte array silently to printer. Can this byte array be sent directly to printer instead of converting it back to PDF file in UI and then printing?

I actually tried something like below after looking at a msdn link, but this is printing wierd symbols over so many pages when the actual report is just a one or two page one. There is less information about the winspool dll's functions online, so not sure where I am going wrong.

Any ideas highly appreciated.

```<code>public class RawPrintHelper
{
     //Structure and API declarions:
    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
    public class DOCINFOA
    {
        [MarshalAs(UnmanagedType.LPStr)]
        public string pDocName;
        [MarshalAs(UnmanagedType.LPStr)]
        public string pOutputFile;
        [MarshalAs(UnmanagedType.LPStr)]
        public string pDataType;
    }
    [DllImport("winspool.Drv", EntryPoint = "OpenPrinter", SetLastError = true, CharSet = CharSet.Auto, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
    public static extern bool OpenPrinter([MarshalAs(UnmanagedType.LPStr)] string szPrinter, out IntPtr hPrinter, IntPtr pd);

    [DllImport("winspool.Drv", EntryPoint = "ClosePrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
    public static extern bool ClosePrinter(IntPtr hPrinter);

    [DllImport("winspool.Drv", EntryPoint = "StartDocPrinter", SetLastError = true, CharSet = CharSet.Auto, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
    public static extern bool StartDocPrinter(IntPtr hPrinter, Int32 level, [In, MarshalAs(UnmanagedType.LPStruct)] DOCINFOA di);

    [DllImport("winspool.Drv", EntryPoint = "EndDocPrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
    public static extern bool EndDocPrinter(IntPtr hPrinter);

    [DllImport("winspool.Drv", EntryPoint = "StartPagePrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
    public static extern bool StartPagePrinter(IntPtr hPrinter);

    [DllImport("winspool.Drv", EntryPoint = "EndPagePrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
    public static extern bool EndPagePrinter(IntPtr hPrinter);

    [DllImport("winspool.Drv", EntryPoint = "WritePrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
    public static extern bool WritePrinter(IntPtr hPrinter, IntPtr pBytes, Int32 dwCount, out Int32 dwWritten);

    // SendBytesToPrinter()
    // When the function is given a printer name and an unmanaged array
    // of bytes, the function sends those bytes to the print queue.
    // Returns true on success, false on failure.
    public static bool SendBytesToPrinter(string szPrinterName, IntPtr pBytes, Int32 dwCount)
    {
        Int32 dwError = 0, dwWritten = 0;
        IntPtr hPrinter = new IntPtr(0);
        DOCINFOA di = new DOCINFOA();
        bool bSuccess = false; // Assume failure unless you specifically succeed.

        di.pDocName = "My C#.NET RAW Document";
        di.pDataType = "RAW";

        // Open the printer.
        if (OpenPrinter(szPrinterName.Normalize(), out hPrinter, IntPtr.Zero))
        {
            // Start a document.
            if (StartDocPrinter(hPrinter, 1, di))
            {
                // Start a page.
                if (StartPagePrinter(hPrinter))
                {
                    // Write your bytes.
                    bSuccess = WritePrinter(hPrinter, pBytes, dwCount, out dwWritten);
                    EndPagePrinter(hPrinter);
                }
                EndDocPrinter(hPrinter);
            }
            ClosePrinter(hPrinter);
        }
        // If you did not succeed, GetLastError may give more information
        // about why not.
        if (bSuccess == false)
        {
            dwError = Marshal.GetLastWin32Error();
        }
        return bSuccess;
    }
</code>```

}

答: I kept my initial implementation where I sent PDF file to printer as sending bytes directly to printer didnot work.</p>

Title: Sending byte array to printer directly

Body:
My service converts report into a byte array and passes to client(wpf app) using the following code:

byte[] bytes = renderer.ServerReport.Render("PDF", deviceInfo, out mimeType, out encoding, out extension, out streamids, out warnings);

where renderer is an instance of Microsoft.Reporting.Webforms.ReportViewer. There is a problem here: encoding output parameter is returning null, so couldn't findout information about encoding.

The UI has to print this byte array silently to printer. Can this byte array be sent directly to printer instead of converting it back to PDF file in UI and then printing?

I actually tried something like below after looking at a msdn link, but this is printing wierd symbols over so many pages when the actual report is just a one or two page one. There is less information about the winspool dll's functions online, so not sure where I am going wrong.

Any ideas highly appreciated.

public class RawPrintHelper
{
     //Structure and API declarions:
    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
    public class DOCINFOA
    {
        [MarshalAs(UnmanagedType.LPStr)]
        public string pDocName;
        [MarshalAs(UnmanagedType.LPStr)]
        public string pOutputFile;
        [MarshalAs(UnmanagedType.LPStr)]
        public string pDataType;
    }
    [DllImport("winspool.Drv", EntryPoint = "OpenPrinter", SetLastError = true, CharSet = CharSet.Auto, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
    public static extern bool OpenPrinter([MarshalAs(UnmanagedType.LPStr)] string szPrinter, out IntPtr hPrinter, IntPtr pd);

    [DllImport("winspool.Drv", EntryPoint = "ClosePrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
    public static extern bool ClosePrinter(IntPtr hPrinter);

    [DllImport("winspool.Drv", EntryPoint = "StartDocPrinter", SetLastError = true, CharSet = CharSet.Auto, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
    public static extern bool StartDocPrinter(IntPtr hPrinter, Int32 level, [In, MarshalAs(UnmanagedType.LPStruct)] DOCINFOA di);

    [DllImport("winspool.Drv", EntryPoint = "EndDocPrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
    public static extern bool EndDocPrinter(IntPtr hPrinter);

    [DllImport("winspool.Drv", EntryPoint = "StartPagePrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
    public static extern bool StartPagePrinter(IntPtr hPrinter);

    [DllImport("winspool.Drv", EntryPoint = "EndPagePrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
    public static extern bool EndPagePrinter(IntPtr hPrinter);

    [DllImport("winspool.Drv", EntryPoint = "WritePrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
    public static extern bool WritePrinter(IntPtr hPrinter, IntPtr pBytes, Int32 dwCount, out Int32 dwWritten);

    // SendBytesToPrinter()
    // When the function is given a printer name and an unmanaged array
    // of bytes, the function sends those bytes to the print queue.
    // Returns true on success, false on failure.
    public static bool SendBytesToPrinter(string szPrinterName, IntPtr pBytes, Int32 dwCount)
    {
        Int32 dwError = 0, dwWritten = 0;
        IntPtr hPrinter = new IntPtr(0);
        DOCINFOA di = new DOCINFOA();
        bool bSuccess = false; // Assume failure unless you specifically succeed.

        di.pDocName = "My C#.NET RAW Document";
        di.pDataType = "RAW";

        // Open the printer.
        if (OpenPrinter(szPrinterName.Normalize(), out hPrinter, IntPtr.Zero))
        {
            // Start a document.
            if (StartDocPrinter(hPrinter, 1, di))
            {
                // Start a page.
                if (StartPagePrinter(hPrinter))
                {
                    // Write your bytes.
                    bSuccess = WritePrinter(hPrinter, pBytes, dwCount, out dwWritten);
                    EndPagePrinter(hPrinter);
                }
                EndDocPrinter(hPrinter);
            }
            ClosePrinter(hPrinter);
        }
        // If you did not succeed, GetLastError may give more information
        // about why not.
        if (bSuccess == false)
        {
            dwError = Marshal.GetLastWin32Error();
        }
        return bSuccess;
    }

}


问:
ModelAttribute adds only 1st value into List
On my view, I generate input "username", select with attribute multiple=multiple, which has name "rolesss".

My issue is, that if I send such form via post, my controller should convert roles to list, but i get only list containing single element.

For example:
I send post, with values:

```<code>username:MyUser
_csrf:aef50238-92cf-48df-86a4-cb6e2b8f62c9
rolesss:USER
rolesss:ADMIN
</code>```

In debug mode in my controller I see values:
roless: "USER"
username: "MyUser"

"ADMIN" did just disappear.

My controller looks like:

```<code>@Controller
@RequestMapping("/user-management")
public class UserManagementController {

    @RequestMapping("")
    public ModelAndView home() {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("pages/user-management");

        return modelAndView;
    }

    @RequestMapping(value = "", method = RequestMethod.POST)
    public ModelAndView changeRoles(@ModelAttribute("username") String username,@ModelAttribute("rolesss") List<String> rolesss) {

        return null;
    }

}
</code>```

My view I merged 2 thymeleaf fragments into 1, in my code #user-roles-form is in separate fragment, but I think that it should not change anything:

```<code><th:block layout:fragment="main-content">
    <section>
        <h2 class="section-title no-margin-top">Role Management</h2>
        <div class="form-group">
            <div class="panel panel-primary">
                <div class="panel-heading">Změna rolí uživatele</div>
                <div class="panel-body">
                    <form class="form-horizontal" role="form" action="/user-management" method="post">
                        <div class="form-group">
                            <label for="user-name" class="col-sm-2 control-label">Uživatel</label>
                            <div class="col-sm-10">
                                <input id="user-name" class="autocomplete form-control" type="text"
                                       placeholder="Jméno uživatele" name="username"/>
                            </div>
                            <input type="hidden"
                                   th:name="${_csrf.parameterName}"
                                   th:value="${_csrf.token}"/>
                        </div>
                        <div id="user-roles-form" th:fragment="roles(roles)" xmlns:th="http://www.thymeleaf.org">
                            <div class="form-group">
                                <label for="user-roles" class="col-sm-2 control-label">Uživatelovy role</label>
                                <div class="col-sm-10">
                                    <select multiple="multiple" class="form-control" id="user-roles" name="rolesss">
                                        <th:block th:each="role : ${roles}">
                                            <option th:value="${role.userRole.role}" th:text="${role.userRole.role}" th:selected="${role.selected}"></option>
                                        </th:block>
                                    </select>
                                </div>
                            </div>
                            <div class="form-group">
                                <div class="col-sm-offset-2 col-sm-10">
                                    <button type="submit" class="btn btn-ar btn-primary">Uložit</button>
                                </div>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </section>
</th:block>
</code>```

答:
try using  like below in your controller

in your HTML or JSP

```<code> <form modelAttribute="your_model_name"></form>
</code>```

if you are using model attribute then use @ModelAttribute

otherwise, use @RequestParam("username")

In your case

```<code>@RequestMapping(value = "", method = RequestMethod.POST)
public ModelAndView changeRoles(@RequestParam("username") String username,@RequestParam("rolesss") List<String> rolesss) {
     ..........
     .........
    return null;
}
</code>```

Body:
On my view, I generate input "username", select with attribute multiple=multiple, which has name "rolesss".

My issue is, that if I send such form via post, my controller should convert roles to list, but i get only list containing single element.

For example:
I send post, with values:

username:MyUser
_csrf:aef50238-92cf-48df-86a4-cb6e2b8f62c9
rolesss:USER
rolesss:ADMIN

In debug mode in my controller I see values:
roless: "USER"
username: "MyUser"

"ADMIN" did just disappear.

My controller looks like:

@Controller
@RequestMapping("/user-management")
public class UserManagementController {

    @RequestMapping("")
    public ModelAndView home() {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("pages/user-management");

        return modelAndView;
    }

    @RequestMapping(value = "", method = RequestMethod.POST)
    public ModelAndView changeRoles(@ModelAttribute("username") String username,@ModelAttribute("rolesss") List<String> rolesss) {

        return null;
    }

}

My view I merged 2 thymeleaf fragments into 1, in my code #user-roles-form is in separate fragment, but I think that it should not change anything:

Role Management

Změna rolí uživatele

                    <form class="form-horizontal" role="form" action="/user-management" method="post">

                            Uživatel

                                <input id="user-name" class="autocomplete form-control" type="text"
                                       placeholder="Jméno uživatele" name="username"/>

                            <input type="hidden"
                                   th:name="${_csrf.parameterName}"
                                   th:value="${_csrf.token}"/>

                                Uživatelovy role

                                    <select multiple="multiple" class="form-control" id="user-roles" name="rolesss">

                                            <option th:value="${role.userRole.role}" th:text="${role.userRole.role}" th:selected="${role.selected}"></option>

                                    </select>

                                    <button type="submit" class="btn btn-ar btn-primary">Uložit</button>

                    </form>

Body:
try using  like below in your controller

in your HTML or JSP

 <form modelAttribute="your_model_name"></form>

if you are using model attribute then use @ModelAttribute

otherwise, use @RequestParam("username")

In your case

@RequestMapping(value = "", method = RequestMethod.POST)
public ModelAndView changeRoles(@RequestParam("username") String username,@RequestParam("rolesss") List<String> rolesss) {
     ..........
     .........
    return null;
}


问:
SQL Server parse a column's XML value into a table (for each row)
Sorry if the topic isn't very clear, but here is what I need to accomplish. I have a table like so:

```<code> user_id   | friends
==============================
75          | <friend name="bob" /><friend name="joe" />
76          | <friend name="bill" /><friend name="bob" />
77          | <friend name="sam" /><friend name="gary" /><friend name="john" />
</code>```

I need to get the number of friends (ie, number of XML nodes) for each user.
The resulting table should look like this:

```<code> user_id   | number_of_friends
==============================
75         | 2
76         | 2
77         | 3
</code>```

The following SQL can do it for one column at a time, but I'm not sure how to do it for all columns in one go.

```<code>DECLARE @x XML;

SELECT @x = pval
FROM [mytable]
WHERE uid=75 AND pkey='roster';

SELECT COUNT(t.c.value('@name', 'NVARCHAR(MAX)')) AS number_of_friends
FROM @x.nodes('//friend') t(c);
</code>```

This results in the table:

```<code>number_of_friends
=================
2
</code>```

答:
You can try this trick: Remove (replace) what you are searching for and compare the difference in string length:

```<code>SELECT
    user_id,
    ROUND (
        (
            LENGTH(friends)
            - LENGTH( REPLACE ( friends, "<friend", "") )
        ) / LENGTH("<friend")
    ) AS count
FROM friendtable
</code>```

Running fiddle

Count the number of occurrences of a string in a VARCHAR field?

Body:
Sorry if the topic isn't very clear, but here is what I need to accomplish. I have a table like so:

 user_id   | friends
==============================
75          | <friend name="bob" /><friend name="joe" />
76          | <friend name="bill" /><friend name="bob" />
77          | <friend name="sam" /><friend name="gary" /><friend name="john" />

I need to get the number of friends (ie, number of XML nodes) for each user.
The resulting table should look like this:

 user_id   | number_of_friends
==============================
75         | 2
76         | 2
77         | 3

The following SQL can do it for one column at a time, but I'm not sure how to do it for all columns in one go.

DECLARE @x XML;

SELECT @x = pval
FROM [mytable]
WHERE uid=75 AND pkey='roster';

SELECT COUNT(t.c.value('@name', 'NVARCHAR(MAX)')) AS number_of_friends
FROM @x.nodes('//friend') t(c);

This results in the table:

number_of_friends
=================
2

Body:
You can try this trick: Remove (replace) what you are searching for and compare the difference in string length:

SELECT
    user_id,
    ROUND (
        (
            LENGTH(friends)
            - LENGTH( REPLACE ( friends, "<friend", "") )
        ) / LENGTH("<friend")
    ) AS count
FROM friendtable

Running fiddle

Count the number of occurrences of a string in a VARCHAR field?


问:
APK not valid Google Play Developers Console
I'm trying to upload my first app to the Google Play Developer Console, but I'm getting the error; "Upload failed, you need to upload a valid .apk file".

I followed the instructions to get a signed apk file from Android Studio and I was able to generate the apk file with no issues. The Developer Console isn't giving me any information to figure out why it is invalid! Any ideas?

答:
Problem is related with some cookie problem.
Log out from Google Developer Console and log in again. Also you can use browser incognito mode. </p>


答: Are you missing a ; after $ID_city = $row['ID']</p>

Title: PHP MYSQL: two while echo from two table to create an ajax live search


问:
AudioKit ios AKSamplerMetronome
I'm currently using AudioKit's AKSamplerMetronome to generate and play Metronome sounds , now I need implement an callback to get current beat suppose If I'm having 5 beats I need to get current beat that is being played so that I can add some more functions based on the beat count , is there any callback available to achieve It ??

This is my current code

```<code> // using AKSamplerMetronome
var metronome1 = AKSamplerMetronome()
var mixer = AKMixer()
// first sound called
let beatstart = Bundle.main.url(forResource: "mybeat", withExtension: "wav")
 // other sounds based on beat count
let beaten = Bundle.main.url(forResource: "others", withExtension: "wav")
// setting first sound and other beat sounds
metronome1.sound = McountSoundUrl
metronome1.downBeatSound = MoneSoundUrl
metronome1 >>> mixer
AudioKit.output = mixer
AudioKit.start()
</code>```

答:
You could do this easily enough with AKSequencer (I did something similar). I assigned one track of the sequencer to an AKMIDISampler, generating the metronome sound, and a second track that went to an AKCallbackInstrument.

In the track being sent to the AKCallbackInstrument, I encoded the beat information arbitrarily in the MIDI data, so for example, the MIDI data for the first beat has a MIDINote of 1, the second, MIDINote 2 (you could do this with the velocity).  Then the callback function could would just look at all of the noteOn messages and get the current beat from the MIDI Note number, and respond accordingly.  It's a little indirect, but it works.

```<code>// create the sequencer before hand (e.g., at init); calling play() immediately after creating it causes some odd behaviour
    let sequencer = AKSequencer()

    // set up the sampler and callbackInst
    let sampler = AKSynthSnare()
    // or for your own sample:
    // let sampler = AKMIDISampler()
    // sampler.loadWav("myMetronomeSound)
    let callbackInst = AKCallbackInstrument()
    AudioKit.output = sampler
    AudioKit.start()

    // create two tracks for the sequencer
    let metronomeTrack = sequencer.newTrack()
    metronomeTrack?.setMIDIOutput(sampler.midiIn)
    let callbackTrack = sequencer.newTrack()
    callbackTrack?.setMIDIOutput(callbackInst.midiIn)

    // create the MIDI data
    for i in 0 ..< 4 {
        // this will trigger the sampler on the four down beats
        metronomeTrack?.add(noteNumber: 60, velocity: 100, position: AKDuration(beats: Double(i)), duration: AKDuration(beats: 0.5))

        // set the midiNote number to the current beat number
        callbackTrack?.add(noteNumber: MIDINoteNumber(i), velocity: 100, position: AKDuration(beats: Double(i)), duration: AKDuration(beats: 0.5))
    }

    // set the callback
    callbackInst.callback = {status, noteNumber, velocity in
        guard status == .noteOn else { return }
        print("beat number: \(noteNumber + 1)")
        // e.g., resondToBeat(beatNum: noteNumber)
    }

    // get the sequencer ready
    sequencer.enableLooping(AKDuration(beats: 4))
    sequencer.setTempo(60)
    sequencer.play()
</code>```

Title: AudioKit ios AKSamplerMetronome

Body:
I'm currently using AudioKit's AKSamplerMetronome to generate and play Metronome sounds , now I need implement an callback to get current beat suppose If I'm having 5 beats I need to get current beat that is being played so that I can add some more functions based on the beat count , is there any callback available to achieve It ??

This is my current code

 // using AKSamplerMetronome
var metronome1 = AKSamplerMetronome()
var mixer = AKMixer()
// first sound called
let beatstart = Bundle.main.url(forResource: "mybeat", withExtension: "wav")
 // other sounds based on beat count
let beaten = Bundle.main.url(forResource: "others", withExtension: "wav")
// setting first sound and other beat sounds
metronome1.sound = McountSoundUrl
metronome1.downBeatSound = MoneSoundUrl
metronome1 >>> mixer
AudioKit.output = mixer
AudioKit.start()

Body:
You could do this easily enough with AKSequencer (I did something similar). I assigned one track of the sequencer to an AKMIDISampler, generating the metronome sound, and a second track that went to an AKCallbackInstrument.

In the track being sent to the AKCallbackInstrument, I encoded the beat information arbitrarily in the MIDI data, so for example, the MIDI data for the first beat has a MIDINote of 1, the second, MIDINote 2 (you could do this with the velocity).  Then the callback function could would just look at all of the noteOn messages and get the current beat from the MIDI Note number, and respond accordingly.  It's a little indirect, but it works.

// create the sequencer before hand (e.g., at init); calling play() immediately after creating it causes some odd behaviour
    let sequencer = AKSequencer()

    // set up the sampler and callbackInst
    let sampler = AKSynthSnare()
    // or for your own sample:
    // let sampler = AKMIDISampler()
    // sampler.loadWav("myMetronomeSound)
    let callbackInst = AKCallbackInstrument()
    AudioKit.output = sampler
    AudioKit.start()

    // create two tracks for the sequencer
    let metronomeTrack = sequencer.newTrack()
    metronomeTrack?.setMIDIOutput(sampler.midiIn)
    let callbackTrack = sequencer.newTrack()
    callbackTrack?.setMIDIOutput(callbackInst.midiIn)

    // create the MIDI data
    for i in 0 ..< 4 {
        // this will trigger the sampler on the four down beats
        metronomeTrack?.add(noteNumber: 60, velocity: 100, position: AKDuration(beats: Double(i)), duration: AKDuration(beats: 0.5))

        // set the midiNote number to the current beat number
        callbackTrack?.add(noteNumber: MIDINoteNumber(i), velocity: 100, position: AKDuration(beats: Double(i)), duration: AKDuration(beats: 0.5))
    }

    // set the callback
    callbackInst.callback = {status, noteNumber, velocity in
        guard status == .noteOn else { return }
        print("beat number: \(noteNumber + 1)")
        // e.g., resondToBeat(beatNum: noteNumber)
    }

    // get the sequencer ready
    sequencer.enableLooping(AKDuration(beats: 4))
    sequencer.setTempo(60)
    sequencer.play()


问:
Trying to come up with python anagram function
What I'm trying to do is if I have a list like:

```<code>["lime", "mile", "liem", "tag", "gat", "goat", "math"]
</code>```

I want to write a function that returns the words in the list that have an anagram, which would look like:

```<code>["lime", "mile", "liem", "tag", "gat",]
</code>```

So far I have this code:

```<code>def anagramprinter(x):

    output = []
    for i in x:
        for n in i:
            if n in x[i]:
</code>```

I can't past this part and would like some help and would also appreciate a thorough explanation as well.

Can anyone please show me a way that doesn't involve importing?
Thanks

Thanks.

答:
Checks two given strings if they're anagrams or not. Those strings may include spaces, numbers or special characters

```<code>#First of all define a function that counts the number of alphabets in a string. It'll be used as a final condition to check for anagrams
def count_alpha(text):
    text = text.lower()
    count = 0
    i = 97    #ASCII code range from 'a' to 'z' is 97 to 122
    while i < 123:
        if chr(i) in text:
            count += text.count(chr(i))
        i += 1
    return count
text1 = input('Enter your First Word: ')
text2 = input('Enter your Second Word: ')
#replace all the spaces with empty strings and make the string lower case
text1 = text1.replace(' ','').lower()
text2 = text2.replace(' ','').lower()
i = 97
while i < 123:
    #check if an alphabet count in both strings is the same.
    if text1.count(chr(i)) == text2.count(chr(i)):
        #replace all the alphabets with spaces
        text1 = text1.replace(chr(i),' ')
        text2 = text2.replace(chr(i),' ')
    i += 1
#since all the alphabets have been replaced by spaces. There's no alphabet left(if they had the same number of particular alphabets)
if count_alpha(text1) == 0 and count_alpha(text2) == 0:
    print('They are anagrams')
else: print('They are not anagrams')
</code>```

So here's your code. Enjoy!

Body:
What I'm trying to do is if I have a list like:

["lime", "mile", "liem", "tag", "gat", "goat", "math"]

I want to write a function that returns the words in the list that have an anagram, which would look like:

["lime", "mile", "liem", "tag", "gat",]

So far I have this code:

def anagramprinter(x):

    output = []
    for i in x:
        for n in i:
            if n in x[i]:

I can't past this part and would like some help and would also appreciate a thorough explanation as well.

Can anyone please show me a way that doesn't involve importing?
Thanks

Thanks.

Body:
Checks two given strings if they're anagrams or not. Those strings may include spaces, numbers or special characters

#First of all define a function that counts the number of alphabets in a string. It'll be used as a final condition to check for anagrams
def count_alpha(text):
    text = text.lower()
    count = 0
    i = 97    #ASCII code range from 'a' to 'z' is 97 to 122
    while i < 123:
        if chr(i) in text:
            count += text.count(chr(i))
        i += 1
    return count
text1 = input('Enter your First Word: ')
text2 = input('Enter your Second Word: ')
#replace all the spaces with empty strings and make the string lower case
text1 = text1.replace(' ','').lower()
text2 = text2.replace(' ','').lower()
i = 97
while i < 123:
    #check if an alphabet count in both strings is the same.
    if text1.count(chr(i)) == text2.count(chr(i)):
        #replace all the alphabets with spaces
        text1 = text1.replace(chr(i),' ')
        text2 = text2.replace(chr(i),' ')
    i += 1
#since all the alphabets have been replaced by spaces. There's no alphabet left(if they had the same number of particular alphabets)
if count_alpha(text1) == 0 and count_alpha(text2) == 0:
    print('They are anagrams')
else: print('They are not anagrams')

So here's your code. Enjoy!


问:
how to mock a method decorated with Python Flask route()
I need to unit test whether a method decorated by a Flask route() gets called or not.

I'd like to do this without modifying the original code under test, if possible, so mocking the method would suite my requirements perfectly.

Hence I am asking this specific question about how to mock a decorated request method (I want to stress this to try to avoid people wasting their time with less specific answers)...

Sample application jflask.py:

```<code>from flask import Flask
app = Flask(__name__)
app.config.from_object(__name__)

@app.route('/hello')           # This method represents the code under test.
def hello():                   # I want to assert that this method gets
    return 'Hello, World'      # called without modifying this code.

if __name__ == "__main__":
    app.run()
</code>```

In the unit test I'm using @patch() to mock the method so I can assert it was called, but the assertion fails. I.e. the mock method doesn't get called, when I expect it to.

Sample unit test test_hello.py:

```<code>import unittest
import jflask
from unittest.mock import patch

class jTest(unittest.TestCase):
    def setUp(self):
        #jflask.app.testing = True
        self.app = jflask.app.test_client()

    @patch('jflask.hello')                # mock the hello() method
    def test_hello(self, mock_method):
        rv = self.app.get('/hello')
        mock_method.assert_called()    # this assertion fails
</code>```

What am I doing wrong ?

Background

Some background information about the actual behaviour I'm trying to test
(since the above is just a condensed test case, and may not seem entirely sane by itself).

In the actual code I am unit testing, there is a before_request() handler
installed for the app. This gets called by Flask before each request is handled, and in
certain situations this handler has been designed to return a response value, which
causes Flask request processing to stop (in this application's case, this feature is used to centrally validate request parameters), so that the usual routed request handler will (deliberately) not get called.

My unit tests need to assert that request processing gets stopped
or continues, appropriately depending on the situation.
Hence, my test needs to mock the real request handler and assert whether
it was called or not.

答:
```<code>from functools import wraps
import logging
from datetime import datetime
logging.basicConfig(filename=datetime.now().strftime('%d_%m_%Y.log'),level=logging.INFO)

def logger_required(f):
    @wraps(f)
    def decorated(*args, **kwargs):
        logging.info(f.__name__  + ' was called')
        return f(*args, **kwargs)
    return decorated

@app.route('/hello')
@logger_required
def hello():                   # I want to assert that this gets called
    return 'Hello, World'
</code>```

Body:
I need to unit test whether a method decorated by a Flask route() gets called or not.

I'd like to do this without modifying the original code under test, if possible, so mocking the method would suite my requirements perfectly.

Hence I am asking this specific question about how to mock a decorated request method (I want to stress this to try to avoid people wasting their time with less specific answers)...

Sample application jflask.py:

from flask import Flask
app = Flask(__name__)
app.config.from_object(__name__)

@app.route('/hello')           # This method represents the code under test.
def hello():                   # I want to assert that this method gets
    return 'Hello, World'      # called without modifying this code.

if __name__ == "__main__":
    app.run()

In the unit test I'm using @patch() to mock the method so I can assert it was called, but the assertion fails. I.e. the mock method doesn't get called, when I expect it to.

Sample unit test test_hello.py:

import unittest
import jflask
from unittest.mock import patch

class jTest(unittest.TestCase):
    def setUp(self):
        #jflask.app.testing = True
        self.app = jflask.app.test_client()

    @patch('jflask.hello')                # mock the hello() method
    def test_hello(self, mock_method):
        rv = self.app.get('/hello')
        mock_method.assert_called()    # this assertion fails

What am I doing wrong ?

Background

Some background information about the actual behaviour I'm trying to test
(since the above is just a condensed test case, and may not seem entirely sane by itself).

In the actual code I am unit testing, there is a before_request() handler
installed for the app. This gets called by Flask before each request is handled, and in
certain situations this handler has been designed to return a response value, which
causes Flask request processing to stop (in this application's case, this feature is used to centrally validate request parameters), so that the usual routed request handler will (deliberately) not get called.

My unit tests need to assert that request processing gets stopped
or continues, appropriately depending on the situation.
Hence, my test needs to mock the real request handler and assert whether
it was called or not.


问:
SQLite - SQL logic error or missing database near "ON": syntax error
The following SQL Query:

```<code>CREATE TABLE IF NOT EXISTS `dsgdsgdsg` (`combo` varchar(255) NOT NULL, `dt` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, PRIMARY KEY (`combo`))
</code>```

Returns:

SQL logic error or missing database near "ON": syntax error

Which seems to be related to "ON UPDATE", why is that? Is On Update not supported by SQLite? if so, is there an alternative (So that when I update using REPLACE INTO, I wont need to supply a new timestamp it just updates).

答:
This is okey for a MySQL. However it's different in SQLite, use a trigger instead.
Someone had the same problem and was solved here on update current_timestamp with SQLite</p>

Body:
The following SQL Query:

CREATE TABLE IF NOT EXISTS `dsgdsgdsg` (`combo` varchar(255) NOT NULL, `dt` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, PRIMARY KEY (`combo`))

Returns:

SQL logic error or missing database near "ON": syntax error

Which seems to be related to "ON UPDATE", why is that? Is On Update not supported by SQLite? if so, is there an alternative (So that when I update using REPLACE INTO, I wont need to supply a new timestamp it just updates).