问:
php session id value to multiple pages
I'm trying to pass the value of a session id to a different page, but only the last product id is passed to the second page no matter if a product with a different id is selected. Ideally what ever product is clicked that id should pass to the second page

```<code><body>
<?php
session_start();
$_SESSION['favcolor'] = 'green';
?>

<!--Some other html code -->

  <?php

      $servername = "localhost";
      $username = "user";
      $password = "pass";
      $dbname = "dbname";

      // Create connection
      $conn = new mysqli($servername, $username, $password, $dbname);
      // Check connection
      if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
      }

      $sql2 = "SELECT * FROM tablename WHERE 1 ORDER BY ProductName ASC";
      $myresult = $conn->query($sql2);

       $x = 1;
       while ($row = $myresult->fetch_assoc()) {
$_SESSION['id'] = $row['ProductID'];
       ?>

       <div class="col-sm-4">
                           <div class="product-image-wrapper">
                               <div class="single-products">
                                   <div class="productinfo text-center">

                                      <a href="page2.php"> <img src="../../images/myImages/<?php echo $row['ProductImage1'];?>_0001_1.jpg" alt="../../images/myImages/<?php echo $row['ProductImage1'];?>_0001_1.jpg" /></a>
                                       <h2><?php echo $row['ProductPrice'];?></h2>

 <!-- when i echo $_SESSION['id'] i get correct values for each product -->
                                       <p><?php echo $_SESSION['id'];?></p>
                                       <p><?php echo $row['ProductName']; ?></p>

 <!-- Other HTML Code -->
</code>```

Second Page after clicking a product and expecting the correct product id to be passed.

```<code><body>
<?php

 session_start();
 echo $_SESSION['favcolor'];
 echo $_SESSION['id'];

?>
</code>```

This results in the last Product ID being passed to the second page no matter what product is clicked

答:
Well because in while loop you override the value each time so at the end you only get last record.

Change your code at two places.

1. Make array of ids

```<code>$x = 1;
$idArray = array(); //define array
while ($row = $myresult->fetch_assoc()) {
    $idArray[] = $row['ProductID']; //push values in array

    //other code..

} // end while
 $_SESSION['id'] = $idArray; //store to session
</code>```

2. Use data from db not session

Replace this

```<code><p><?php echo $_SESSION['id'];?></p>
</code>```

With this

<?php echo $row['ProductID'];?></p>

Title: php session id value to multiple pages

Body:
I'm trying to pass the value of a session id to a different page, but only the last product id is passed to the second page no matter if a product with a different id is selected. Ideally what ever product is clicked that id should pass to the second page

<?php
session_start();
$_SESSION['favcolor'] = 'green';
?>

  <?php

      $servername = "localhost";
      $username = "user";
      $password = "pass";
      $dbname = "dbname";

      // Create connection
      $conn = new mysqli($servername, $username, $password, $dbname);
      // Check connection
      if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
      }

      $sql2 = "SELECT * FROM tablename WHERE 1 ORDER BY ProductName ASC";
      $myresult = $conn->query($sql2);

       $x = 1;
       while ($row = $myresult->fetch_assoc()) {
$_SESSION['id'] = $row['ProductID'];
       ?>

                                       <img src="../../images/myImages/<?php echo $row['ProductImage1'];?>_0001_1.jpg" alt="../../images/myImages/<?php echo $row['ProductImage1'];?>_0001_1.jpg" />

<?php echo $row['ProductPrice'];?>

<?php echo $_SESSION['id'];?>

<?php echo $row['ProductName']; ?>

Second Page after clicking a product and expecting the correct product id to be passed.

<?php

 session_start();
 echo $_SESSION['favcolor'];
 echo $_SESSION['id'];

?>

This results in the last Product ID being passed to the second page no matter what product is clicked

Body:
Well because in while loop you override the value each time so at the end you only get last record.

Change your code at two places.

1. Make array of ids

$x = 1;
$idArray = array(); //define array
while ($row = $myresult->fetch_assoc()) {
    $idArray[] = $row['ProductID']; //push values in array

    //other code..

} // end while
 $_SESSION['id'] = $idArray; //store to session

2. Use data from db not session

Replace this

<p><?php echo $_SESSION['id'];?></p>

With this

<p><?php echo $row['ProductID'];?></p>


来源: stackexchange

问:
How to do subtraction between two fields in a Table using an SQL query
I want to display the subtraction of two values from two different columns to a third column using a SQL query.

This is the table structure:

```<code>------------------------------------
id | subject | Time1 | Time2| Time3
------------------------------------
1  | String1 | 50    |  78  |
2  | String2 | 60    |  99  |
3  |         |       |      |
</code>```

I want to subtract Time2 from Time1 if both Time1 and Time2 has data and store in Time3.

Output should be like as

```<code>------------------------------------
id | subject | Time1 | Time2| Time3
------------------------------------
1  | String1 | 50    |  78  |  28
2  | String2 | 60    |  99  |  39
3  |         |       |      |
</code>```

Thanks!

答:
```<code>`SELECT
     id,
     subject,
     Time1,
     Time2,
     IF( Time1 != '' AND Time2 != '', Time2-Time1, '') as Time3
FROM tbl_time`
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I want to display the subtraction of two values from two different columns to a third column using a SQL query.

This is the table structure:

------------------------------------
id | subject | Time1 | Time2| Time3
------------------------------------
1  | String1 | 50    |  78  |
2  | String2 | 60    |  99  |
3  |         |       |      |

I want to subtract Time2 from Time1 if both Time1 and Time2 has data and store in Time3.

Output should be like as

------------------------------------
id | subject | Time1 | Time2| Time3
------------------------------------
1  | String1 | 50    |  78  |  28
2  | String2 | 60    |  99  |  39
3  |         |       |      |

Thanks!

ContentLicense: CC BY-SA 4.0


问:
checkboxes with datagridview
I have a c# winform application (2008) with datagridview bound to data from sqlserver.
 I need to display checkboxes near each visible row of grid in order to select rows for further work, all the data in datagrid is readonly but is reload from time to time with different number of lines.

I need some advise and how to perform preferable idea:

-or to create programmatically checkboxes - then how should i know their locations (i want to place them once, of course :)), which data rows are displayed and how many?

-or to use checklistbox instead - then how should i create multiple columns bound to data and how to display columns titles?

-or maybe create additional checkbox column in datagrid - then how should i reload data to datagrid each time it's changed?

-or any other idea???

thanks!

答:
You have to create addtional CheckBox column to perform operation .

For getting currently selected row value  try

```<code>string value=DataGridView1.CurrentRow.Cells["cell1"].Value.ToString();
</code>```

OR  try

```<code>private void DataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)

{
    chk = (CheckBox)e.Control;
    chk.CheckedChanged -=new EventHandler(chk_CheckedChanged);
    chk.CheckedChanged +=new EventHandler(chk_CheckedChanged);

}
 private void chk_CheckedChanged(object sender, EventArgs e)
      {

      }
</code>```

And  add this datagridviewCheckBoxColumn whenever you bind DataGridView

ContentLicense: CC BY-SA 2.5

Title: checkboxes with datagridview

Body:
You have to create addtional CheckBox column to perform operation .

For getting currently selected row value  try

string value=DataGridView1.CurrentRow.Cells["cell1"].Value.ToString();

OR  try

private void DataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)

{
    chk = (CheckBox)e.Control;
    chk.CheckedChanged -=new EventHandler(chk_CheckedChanged);
    chk.CheckedChanged +=new EventHandler(chk_CheckedChanged);

}
 private void chk_CheckedChanged(object sender, EventArgs e)
      {

      }

And  add this datagridviewCheckBoxColumn whenever you bind DataGridView


问:
Enumeration is throwing concurrentModification Exception. why?
Enumeration is Fail-safe. Fail-safe iterators will work on the cloning of the original collection. then why it is throwing concurrentModificationException? please clarify.

Please find my code:

```<code>public static void main(String[] args) {

    Vector<String> v=new Vector<String>();
    v.add("Amit");
    v.add("Raj");
    v.add("Pathak");
    v.add("Sumit");
    v.add("Aron");
    v.add("Trek");

    Enumeration en=(Enumeration) Collections.enumeration(v);

    while(en.hasMoreElements())
    {
        String value=(String) en.nextElement();
        System.out.println(value);
        v.remove(value);//modifying the collection

    }

}
</code>```

Find the error message below

```<code>Exception in thread "main" java.util.ConcurrentModificationException
at java.util.Vector$Itr.checkForComodification(Unknown Source)
at java.util.Vector$Itr.next(Unknown Source)
at java.util.Collections$2.nextElement(Unknown Source)
at valar.org.src.EnumerationTest.main(EnumerationTest.java:24)
</code>```

答:
You are using Enumeration  which is not supported removed method.Once you created a Enumeration then it test for checkForComodification .so when you do the remove from vector the modCount increases and expectedModCount not modified.

```<code> final void checkForComodification() {
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
        }
</code>```

please modify your code using iterator

```<code>public static void main(String[] args) {

        Vector<String> v = new Vector<String>();
        v.add("Amit");
        v.add("Raj");
        v.add("Pathak");
        v.add("Sumit");
        v.add("Aron");
        v.add("Trek");

        Iterator<String> it =v.iterator();

        while (it.hasNext()) {
            String value = it.next();
            System.out.println(value);
            it.remove();

        }

    }
</code>```

Body:
Enumeration is Fail-safe. Fail-safe iterators will work on the cloning of the original collection. then why it is throwing concurrentModificationException? please clarify.

Please find my code:

public static void main(String[] args) {

    Vector<String> v=new Vector<String>();
    v.add("Amit");
    v.add("Raj");
    v.add("Pathak");
    v.add("Sumit");
    v.add("Aron");
    v.add("Trek");

    Enumeration en=(Enumeration) Collections.enumeration(v);

    while(en.hasMoreElements())
    {
        String value=(String) en.nextElement();
        System.out.println(value);
        v.remove(value);//modifying the collection

    }

}

Find the error message below

Exception in thread "main" java.util.ConcurrentModificationException
at java.util.Vector$Itr.checkForComodification(Unknown Source)
at java.util.Vector$Itr.next(Unknown Source)
at java.util.Collections$2.nextElement(Unknown Source)
at valar.org.src.EnumerationTest.main(EnumerationTest.java:24)

Body:
You are using Enumeration  which is not supported removed method.Once you created a Enumeration then it test for checkForComodification .so when you do the remove from vector the modCount increases and expectedModCount not modified.

 final void checkForComodification() {
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
        }

please modify your code using iterator

public static void main(String[] args) {

        Vector<String> v = new Vector<String>();
        v.add("Amit");
        v.add("Raj");
        v.add("Pathak");
        v.add("Sumit");
        v.add("Aron");
        v.add("Trek");

        Iterator<String> it =v.iterator();

        while (it.hasNext()) {
            String value = it.next();
            System.out.println(value);
            it.remove();

        }

    }


问:
Saving data with dynamic input name to database?
Allright, before that i'm a beginner in PHP.
So forgive me for this silly question.

Say that id_user '1' have 2 items, so it will create 2 input form for each item.

These are the input forms:

```<code><input value="0" type="text" name="store_<?php echo $id= "I got this value from id.item in database, in this case '5'" ?>" required="required">

<input value="0" type="text" name="take_<?php echo $id= "I got this value from id.item in database, in this case '5'" ?>" required="required">

<input value="0" type="text" name="store_<?php echo $id= "I got this value from id.item in database, in this case '6'" ?>" required="required">

<input value="0" type="text" name="take_<?php echo $id= "I got this value from id.item in database, in this case '6'" ?>" required="required">
</code>```

Note : value take_{id} and store_{id} are retrieved from table 'item' coloumn 'id_item' in database.

The user input these values :

```<code>*value 'store' for id_item 5 is 3
*value 'take' for id_item 5 is 2
*value 'store' for id_item 6 is 1
*value 'take' for id_item 6 is 1
</code>```

How do i save value 'store' and 'take' from user input to database with their associated id?
Considering 1 user can have multiple item.

This is table item.

```<code>    ->id_user (referencing id_user from user's table)
    ->id_item # this primary key
    ->Take
    ->Store
</code>```

So the final result will be like this:

```<code>id_user : 1
id_item : 5
Store : 3
Take : 2
</code>```

And like this

```<code>id_user : 1
id_item : 6
Store : 1
Take : 1
</code>```

I've been googled all day, and i think regex with pattern 'store_' and 'take_' should do it? or there is another way to accomplish this?

Thankyou :)

答:
```<code>Set You input like this
<input value="0" type="text" name="store[]" required="required">

<input value="0" type="text" name="take[]" required="required">

<input value="0" type="text" name="store[]" required="required">

<input value="0" type="text" name="take[]" required="required">

  and get this value on backside like this
  $postdata=$_POST;
  $count= $postdata['store'];
  for($i=0;$i<$count;$i++){
       echo $postdata['store'][$i];
       echo $postdata['take'][$i];
  }
 die();
 see your store and take value
</code>```

Body:
Allright, before that i'm a beginner in PHP.
So forgive me for this silly question.

Say that id_user '1' have 2 items, so it will create 2 input form for each item.

These are the input forms:

<input value="0" type="text" name="store_<?php echo $id= "I got this value from id.item in database, in this case '5'" ?>" required="required">

<input value="0" type="text" name="take_<?php echo $id= "I got this value from id.item in database, in this case '5'" ?>" required="required">

<input value="0" type="text" name="store_<?php echo $id= "I got this value from id.item in database, in this case '6'" ?>" required="required">

<input value="0" type="text" name="take_<?php echo $id= "I got this value from id.item in database, in this case '6'" ?>" required="required">

Note : value take_{id} and store_{id} are retrieved from table 'item' coloumn 'id_item' in database.

The user input these values :

*value 'store' for id_item 5 is 3
*value 'take' for id_item 5 is 2
*value 'store' for id_item 6 is 1
*value 'take' for id_item 6 is 1

How do i save value 'store' and 'take' from user input to database with their associated id?
Considering 1 user can have multiple item.

This is table item.

    ->id_user (referencing id_user from user's table)
    ->id_item # this primary key
    ->Take
    ->Store

So the final result will be like this:

id_user : 1
id_item : 5
Store : 3
Take : 2

And like this

id_user : 1
id_item : 6
Store : 1
Take : 1

I've been googled all day, and i think regex with pattern 'store_' and 'take_' should do it? or there is another way to accomplish this?

Thankyou :)


问:
INVALID_ARGUMENT: Application credential header not valid. Please fix the client to pass a valid application credential header
When attempting to run a simple Android Instant App, I receive this error in the console and the app does not open. What does this error mean and how do I pass in a valid credential header?</p>

答: Clean build the project and try again. I did get the same error but got rid of it after clean build.</p>


问:
Debugging a native application with GDB on Android
I have a native C++ app which is supposed to run on an Android device. The application crashes at the startup, most likely when calling a function from a linked library. I am trying to debug it with gdb, but I can't succeed.

I am starting gdbserver on the Android device on some arbitrarily picked port (2000):

```<code>shell@msm8996: gdbserver :2000 my_app
Process my_app created; pid = 3420
Listening on port 2000
</code>```

Now I am trying to attach to this process on my Host system (Windows 7) with gdb that was provided in Android-NDK.

```<code>C:\> gdb
(gdb) attach 3420
Can't attach to process.
(gdb) target remote :2000
:2000: The system tried to join a drive to a directory on a joined drive.
</code>```

What is the problem?

EDIT:
Prior to running gdb I forwarded the port 2000 using adb:

```<code>adb forward tcp:2000 tcp:2000
</code>```

This at least helped me to establish some communication, but:

```<code>(gdb) target remote :2000
Remote debugging using :2000
warning: Architecture rejected target-supplied description
Remote 'g' packet reply is too long: 00000000000000000000000000000...
</code>```

On the device side:

```<code>Listening on port 2000
Remote debugging from host 127.0.0.1
readchar: Got EOF
Remote side has terminated connection.  GDBserver will reopen the connection.
Listening on port 2000
</code>```

答:
You are most probably using different architecture / version of gdb. When you start the gdb, it displays a line like (I am showing what my GDB shows):

This GDB was configured as "--host=x86_64-linux-gnu
  --target=arm-Linux-android"

Check if this matches with your phone's architecture.

Downloading the correct GDB version may solve your problem.

Body:
I have a native C++ app which is supposed to run on an Android device. The application crashes at the startup, most likely when calling a function from a linked library. I am trying to debug it with gdb, but I can't succeed.

I am starting gdbserver on the Android device on some arbitrarily picked port (2000):

shell@msm8996: gdbserver :2000 my_app
Process my_app created; pid = 3420
Listening on port 2000

Now I am trying to attach to this process on my Host system (Windows 7) with gdb that was provided in Android-NDK.

C:\> gdb
(gdb) attach 3420
Can't attach to process.
(gdb) target remote :2000
:2000: The system tried to join a drive to a directory on a joined drive.

What is the problem?

EDIT:
Prior to running gdb I forwarded the port 2000 using adb:

adb forward tcp:2000 tcp:2000

This at least helped me to establish some communication, but:

(gdb) target remote :2000
Remote debugging using :2000
warning: Architecture rejected target-supplied description
Remote 'g' packet reply is too long: 00000000000000000000000000000...

On the device side:

Listening on port 2000
Remote debugging from host 127.0.0.1
readchar: Got EOF
Remote side has terminated connection.  GDBserver will reopen the connection.
Listening on port 2000


问:
Cutting value in vector by determine positions
Is there a function in R that I can cut a value in vector.

for example i got this vec:

```<code>40754831597
64278107602
64212163451
</code>```

and each vale in the vec i want to cut so from the number pos 3 to 6 for example and get a new vector look like this

```<code>7548
2781
2121
</code>```

and so on

Body:
Is there a function in R that I can cut a value in vector.

for example i got this vec:

40754831597
64278107602
64212163451

and each vale in the vec i want to cut so from the number pos 3 to 6 for example and get a new vector look like this

7548
2781
2121

and so on

Body:
We can use sub

sub(".{2}(.{4}).*", "\\1", v1)
#[1] "7548" "2781" "2121"

data

v1 <- c(40754831597, 64278107602, 64212163451)


问:
Pass additional parameters to method
I am using Devexpress file upload control. I am making using of the following overload in the UploadControlExtension class:

```<code>public static UploadedFile[] GetUploadedFiles(string name, UploadControlValidationSettings validationSettings, EventHandler<FileUploadCompleteEventArgs> fileUploadCompleteDelegate);
</code>```

My complete event method signature looks like:

```<code>public static void AttachmentUploadedCompleteEvent(object sender, FileUploadCompleteEventArgs e)
</code>```

What I am trying to do is pass in additional parameter to my AttachmentUploadedCompleteEvent() method. So I want the signature to change to

```<code>public static void AttachmentUploadedCompleteEvent(object sender, FileUploadCompleteEventArgs e, bool isAdmin)
</code>```

But of course if I change to the above then I get an error:

cannot convert from 'method group' to 'out string[]'

My knowledge on Delegates is not the best so I was hoping someone could point me to the right direction on how to achieve this.

Thanks in advance for your help.

答:
you need to change Delegate declaration like

public delegate void AttachmentUploadedCompleteEventHandler(object sender, FileUploadCompleteEventArgs e, bool isAdmin)

Title: Pass additional parameters to method

Body:
I am using Devexpress file upload control. I am making using of the following overload in the UploadControlExtension class:

public static UploadedFile[] GetUploadedFiles(string name, UploadControlValidationSettings validationSettings, EventHandler<FileUploadCompleteEventArgs> fileUploadCompleteDelegate);

My complete event method signature looks like:

public static void AttachmentUploadedCompleteEvent(object sender, FileUploadCompleteEventArgs e)

What I am trying to do is pass in additional parameter to my AttachmentUploadedCompleteEvent() method. So I want the signature to change to

public static void AttachmentUploadedCompleteEvent(object sender, FileUploadCompleteEventArgs e, bool isAdmin)

But of course if I change to the above then I get an error:

cannot convert from 'method group' to 'out string[]'

My knowledge on Delegates is not the best so I was hoping someone could point me to the right direction on how to achieve this.

Thanks in advance for your help.


问:
Python - Best way to append a sequence of numbers to a text file?
Let's say that I have textfile of a series of numbers that looks like this:

```<code>18,18,19,19,16,20,19,20,18,20,21
</code>```

That's only a preview of hundreds of numbers separated by commas. I want to be able to manipulate the data in python in a [list]. So I have a variable src that I want to append the integer values to from the text file.

Like so:

```<code>text_file = open("sequence.txt","r")
src = []

for entry in text_file.read():
    if(entry != ','):
        src.append(int(entry))
</code>```

Obviously this get's rid of the ',' between each entry in my textfile however values like 20 in the textfile will be appended to the list as two separate entries [2,0].

What's the best way to append these values ?
Thanks !

答:
You can iterate over the text file line by line; each line is read as a string.  You can use that string's .split() method to separate it into a list of strings (on the commas) and you can use the int() function to interpret each of those resulting strings as an integer.

All of that looks like this:

```<code>src = list()
with open("sequence.txt","r") as text_file:
    for line in text_file:
        src.append([int(x) for x in line.split(',')])
</code>```

... though this does not gracefully handle any corrupt input.

(Exception handling with your own wrapper around the int() function or in other ways is left as an exercise).

Incidentally the details of this question (and my answer) are about how to read integers in from a file; one in which the values are separated by commas but which generally is not conforming to the conventional "CSV" (comma separated values) file format.

To append more values to the file one would simply open the file in append mode and write the new values to it (adding the new values as a new line by default).  Text files which fail to terminate with a newline character are problematic for many common utilities and programming techniques.  (Effectively, it's necessary to treat that last line as a special case, as though it were from a binary file rather than as regular text).

The code for writing to of these comma separated text/integers file would look something like:

```<code>with open('sequence.txt','a') as output:
    output.write(', '.join(src))
    output.write('\n')
</code>```

... and that should be sufficient unless I'm not fully understanding your requirements.

Body:
Let's say that I have textfile of a series of numbers that looks like this:

18,18,19,19,16,20,19,20,18,20,21

That's only a preview of hundreds of numbers separated by commas. I want to be able to manipulate the data in python in a [list]. So I have a variable src that I want to append the integer values to from the text file.

Like so:

text_file = open("sequence.txt","r")
src = []

for entry in text_file.read():
    if(entry != ','):
        src.append(int(entry))

Obviously this get's rid of the ',' between each entry in my textfile however values like 20 in the textfile will be appended to the list as two separate entries [2,0].

What's the best way to append these values ?
Thanks !

Body:
You can iterate over the text file line by line; each line is read as a string.  You can use that string's .split() method to separate it into a list of strings (on the commas) and you can use the int() function to interpret each of those resulting strings as an integer.

All of that looks like this:

src = list()
with open("sequence.txt","r") as text_file:
    for line in text_file:
        src.append([int(x) for x in line.split(',')])

... though this does not gracefully handle any corrupt input.

(Exception handling with your own wrapper around the int() function or in other ways is left as an exercise).

Incidentally the details of this question (and my answer) are about how to read integers in from a file; one in which the values are separated by commas but which generally is not conforming to the conventional "CSV" (comma separated values) file format.

To append more values to the file one would simply open the file in append mode and write the new values to it (adding the new values as a new line by default).  Text files which fail to terminate with a newline character are problematic for many common utilities and programming techniques.  (Effectively, it's necessary to treat that last line as a special case, as though it were from a binary file rather than as regular text).

The code for writing to of these comma separated text/integers file would look something like:

with open('sequence.txt','a') as output:
    output.write(', '.join(src))
    output.write('\n')

... and that should be sufficient unless I'm not fully understanding your requirements.


问:
MultiTenantConnectionProvider implementation has null autowired datasource
I'm trying to support a multi-tenant by schema in my spring boot (1.4) application. I have the following in my config:

```<code>hibernate:
        format_sql: true
        default_schema: corrto
        multiTenancy: SCHEMA
        tenant_identifier_resolver: com.config.HeaderTenantIdentifierResolver
        multi_tenant_connection_provider: com.config.SchemaPerTenantConnectionProvider
</code>```

My MultiTenantConnectionProvider implementation is as follows:

```<code>public class SchemaPerTenantConnectionProvider implements MultiTenantConnectionProvider {

    @Autowired
    private DataSource dataSource;

    @Override
    public Connection getAnyConnection() throws SQLException {
        return this.dataSource.getConnection();
    }

    @Override
    public void releaseAnyConnection(Connection connection) throws SQLException {
        connection.close();
    }

    @Override
    public Connection getConnection(String tenantIdentifier) throws SQLException {
        final Connection connection = this.getAnyConnection();
        // need to do stuff here
        return connection;
    }

    @Override
    public void releaseConnection(String tenantIdentifier, Connection connection) throws SQLException {

    }

    @Override
    public boolean supportsAggressiveRelease() {
        return true;
    }

    @Override
    public boolean isUnwrappableAs(Class unwrapType) {
        return false;
    }

    @Override
    public <T> T unwrap(Class<T> unwrapType) {
        return null;
    }
}
</code>```

It is failing because dataSource is null. I'm assuming it hasn't been created yet but I'm having a hard time finding solutions via Google.

答: I met the same problem.It seems that in the yml ,HeaderTenantIdentifierResolver and SchemaPerTenantConnectionProvider is managed by hibernate.See here.

Body:
I'm trying to support a multi-tenant by schema in my spring boot (1.4) application. I have the following in my config:

hibernate:
        format_sql: true
        default_schema: corrto
        multiTenancy: SCHEMA
        tenant_identifier_resolver: com.config.HeaderTenantIdentifierResolver
        multi_tenant_connection_provider: com.config.SchemaPerTenantConnectionProvider

My MultiTenantConnectionProvider implementation is as follows:

public class SchemaPerTenantConnectionProvider implements MultiTenantConnectionProvider {

    @Autowired
    private DataSource dataSource;

    @Override
    public Connection getAnyConnection() throws SQLException {
        return this.dataSource.getConnection();
    }

    @Override
    public void releaseAnyConnection(Connection connection) throws SQLException {
        connection.close();
    }

    @Override
    public Connection getConnection(String tenantIdentifier) throws SQLException {
        final Connection connection = this.getAnyConnection();
        // need to do stuff here
        return connection;
    }

    @Override
    public void releaseConnection(String tenantIdentifier, Connection connection) throws SQLException {

    }

    @Override
    public boolean supportsAggressiveRelease() {
        return true;
    }

    @Override
    public boolean isUnwrappableAs(Class unwrapType) {
        return false;
    }

    @Override
    public <T> T unwrap(Class<T> unwrapType) {
        return null;
    }
}

It is failing because dataSource is null. I'm assuming it hasn't been created yet but I'm having a hard time finding solutions via Google.


问:
How can I search within a table of comma-separated values?
I have a MySQL table which contains comma-separated values like this:

```<code>first row=(3,56,78,12)
second row=(6,44,2,3)
third row=(67,4,2,7,1)
fourth row=(88,55,22,33)
fifth row=(88,55,3,1,5)
</code>```

I want to select the rows which have 3 in their set. How can I do this?

答:
you can use IN statement in your query.Please try this.

```<code>SELECT *
FROM Table
WHERE Field IN ($first_row)
OR Field IN ($second_row)
OR Field IN ($third_row)
OR Field IN ($fourth_row);
</code>```

Body:
I have a MySQL table which contains comma-separated values like this:

first row=(3,56,78,12)
second row=(6,44,2,3)
third row=(67,4,2,7,1)
fourth row=(88,55,22,33)
fifth row=(88,55,3,1,5)

I want to select the rows which have 3 in their set. How can I do this?

Body:
you can use IN statement in your query.Please try this.

SELECT *
FROM Table
WHERE Field IN ($first_row)
OR Field IN ($second_row)
OR Field IN ($third_row)
OR Field IN ($fourth_row);


问:
getsockopt: connection timed out
I rewrite my project from python tornado to go(use iris framework). The basic function tested ok. When I test under high concurrence.the app always stops a while and then comes out the errors:

```<code>(dial tcp 192.168.1.229:6543: getsockopt: connection timed out)
</code>```

the 6543 port is the postgresql port used with pgbouncer...the pgbouncer and postgresl process runs Ok.

Also, I find that the memcache connect time out sometimes(the memcache process is still working).

Does this happen because too many connections? Or some connections not
closed on time?
How can I avoid this problem?

答: Check your PgBouncer config. Try to increase max_client_conn option. Then experiment with concurrency level and requests count during stress test. Another possible issue can be that you don't return connections to pool.

Title: getsockopt: connection timed out

Body:
I rewrite my project from python tornado to go(use iris framework). The basic function tested ok. When I test under high concurrence.the app always stops a while and then comes out the errors:

(dial tcp 192.168.1.229:6543: getsockopt: connection timed out)

the 6543 port is the postgresql port used with pgbouncer...the pgbouncer and postgresl process runs Ok.

Also, I find that the memcache connect time out sometimes(the memcache process is still working).

Does this happen because too many connections? Or some connections not
closed on time?
How can I avoid this problem?


问:
How to call a function to execute on the url
I wrote a code which is working fine but now I want it to be in a function so as to call it on the url. I will really appreciate if you guys can help.

Here is my code.

```<code>$conn = mysqli_connect("localhost","root","","db");
if(mysqli_connect_errno()){
    echo "Unable to connect".mysqli_connect_error();
}

function day(){
$sql = "SELECT *, DATE_FORMAT(user_registerdate, '%m/%d/%Y') FROM ts_user
        WHERE DATE(user_registerdate) = CURDATE() - INTERVAL 5 DAY";
    if($result = mysqli_query($conn,$sql)){
        while($row = mysqli_fetch_assoc($result)){
            echo $row['user_uname']."<br />";
        }
    }
}
</code>```

And am calling it on the url as
http://localhost/test/index.php/day

Please telling me what am doing wrong. am I calling it wrongly on the url?

答:
You can not call function like this in core php

You have to call like this:

First Way:
http://localhost/test/index.php

```<code>$conn = mysqli_connect("localhost","root","","testing");
    if(mysqli_connect_errno()){
    echo "Unable to connect".mysqli_connect_error();
    } else {
        day($conn);
    }
</code>```

Second Way:
http://localhost/test/index.php?day=yes

```<code>$conn = mysqli_connect("localhost","root","","testing");
if(mysqli_connect_errno()){
echo "Unable to connect".mysqli_connect_error();
} else {
echo "connection successfull";
}

if($_GET['day']) {
    day($conn);
}
</code>```

Declare function :

```<code>function day($conn){
}
</code>```

====================================

Directly call function from url

test.php

```<code>class Test
{
    const DB_SERVER = "localhost";
    const DB_USER = "root";
    const DB_PASSWORD = "";
    const DB = "testing";

    public function processApi(){
        $func = strtolower(trim(str_replace("/","",$_REQUEST['func'])));
        if((int)method_exists($this,$func) > 0)
            $this->$func();
        else
            echo "Method not exist";
    }

    private function get_data() {
        $conn = mysqli_connect("localhost","root","","testing");
        if(mysqli_connect_errno()){
            echo "Unable to connect".mysqli_connect_error();
        } else {
            //replace your query here
            $sql = "SELECT * FROM tbl_employee";
            if($result = mysqli_query($conn,$sql)){
                while($row = mysqli_fetch_assoc($result)){
                    echo $row['name']."<br />";
                }
            }
        }
    }
}
$test = new Test;
$test->processApi();

 ?>
</code>```

Define routing in .htaccess file

```<code><IfModule mod_rewrite.c>
    RewriteEngine On

    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-s
    RewriteRule ^(.*)$ test.php?func=$1 [QSA,NC,L]

    RewriteCond %{REQUEST_FILENAME} -d
    RewriteRule ^(.*)$ test.php [QSA,NC,L]

    RewriteCond %{REQUEST_FILENAME} -s
    RewriteRule ^(.*)$ test.php [QSA,NC,L]
</IfModule>
</code>```

You can run this example like :
http://localhost/core_route/get_data

For more help visit this

Body:
I wrote a code which is working fine but now I want it to be in a function so as to call it on the url. I will really appreciate if you guys can help.

Here is my code.

$conn = mysqli_connect("localhost","root","","db");
if(mysqli_connect_errno()){
    echo "Unable to connect".mysqli_connect_error();
}

function day(){
$sql = "SELECT *, DATE_FORMAT(user_registerdate, '%m/%d/%Y') FROM ts_user
        WHERE DATE(user_registerdate) = CURDATE() - INTERVAL 5 DAY";
    if($result = mysqli_query($conn,$sql)){
        while($row = mysqli_fetch_assoc($result)){
            echo $row['user_uname']."
";
        }
    }
}

And am calling it on the url as
http://localhost/test/index.php/day

Please telling me what am doing wrong. am I calling it wrongly on the url?

Body:
You can not call function like this in core php

You have to call like this:

First Way:
http://localhost/test/index.php

$conn = mysqli_connect("localhost","root","","testing");
    if(mysqli_connect_errno()){
    echo "Unable to connect".mysqli_connect_error();
    } else {
        day($conn);
    }

Second Way:
http://localhost/test/index.php?day=yes

$conn = mysqli_connect("localhost","root","","testing");
if(mysqli_connect_errno()){
echo "Unable to connect".mysqli_connect_error();
} else {
echo "connection successfull";
}

if($_GET['day']) {
    day($conn);
}

Declare function :

function day($conn){
}

====================================

Directly call function from url

test.php

class Test
{
    const DB_SERVER = "localhost";
    const DB_USER = "root";
    const DB_PASSWORD = "";
    const DB = "testing";

    public function processApi(){
        $func = strtolower(trim(str_replace("/","",$_REQUEST['func'])));
        if((int)method_exists($this,$func) > 0)
            $this->$func();
        else
            echo "Method not exist";
    }

    private function get_data() {
        $conn = mysqli_connect("localhost","root","","testing");
        if(mysqli_connect_errno()){
            echo "Unable to connect".mysqli_connect_error();
        } else {
            //replace your query here
            $sql = "SELECT * FROM tbl_employee";
            if($result = mysqli_query($conn,$sql)){
                while($row = mysqli_fetch_assoc($result)){
                    echo $row['name']."<br />";
                }
            }
        }
    }
}
$test = new Test;
$test->processApi();

 ?>

Define routing in .htaccess file

<IfModule mod_rewrite.c>
    RewriteEngine On

    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-s
    RewriteRule ^(.*)$ test.php?func=$1 [QSA,NC,L]

    RewriteCond %{REQUEST_FILENAME} -d
    RewriteRule ^(.*)$ test.php [QSA,NC,L]

    RewriteCond %{REQUEST_FILENAME} -s
    RewriteRule ^(.*)$ test.php [QSA,NC,L]
</IfModule>

You can run this example like :
http://localhost/core_route/get_data

For more help visit this


问:
"%%" and "%/%" for the remainder and the quotient
I am wondering how and why the operator %% and %/% are for the remainder and the quotient.

Is there any reason or history that R developer had given them the meaning they have?

```<code> > 0 %/% 10
[1] 0
> 30 %% 10
[1] 0
> 35 %/% 10
[1] 3
> 35 %% 10
[1] 5
</code>```

答:
Have a look at the examples below for a clearer understanding of the differences between the different operators:</p>

```<code>> # Floating Division:
> 5/2
[1] 2.5
>
> # Integer Division:
> 5%/%2
[1] 2
>
> # Remainder:
> 5%%2
[1] 1
</code>```

OwnerDisplayName: KH Kim

Body:
I am wondering how and why the operator %% and %/% are for the remainder and the quotient.

Is there any reason or history that R developer had given them the meaning they have?

 > 0 %/% 10
[1] 0
> 30 %% 10
[1] 0
> 35 %/% 10
[1] 3
> 35 %% 10
[1] 5

Body:
Have a look at the examples below for a clearer understanding of the differences between the different operators:

> # Floating Division:
> 5/2
[1] 2.5
>
> # Integer Division:
> 5%/%2
[1] 2
>
> # Remainder:
> 5%%2
[1] 1


问:
How can I show GET parameters as a new directory?
I am currently working on a website where pupils can create articles that can be commented by others.

I have a already developed a script that creates them and stores them in a mysql db.

Every one of these articles should be available under www.mydomain/articles/xyz/

but I don't want to create a new directory for everyone. So is it possible to pass the parameter article=xyz (www.maydomain/articles/articles.php&articles=xyz) to be shown as before mentioned?

I am sorry if my problem is too complex. If you have a question regarding it, do not hesitate to contact me! :)

答:
it can be achieved using htaccess,See this Tutorial for htaccess, this will guide you

https://codex.wordpress.org/htaccess

https://www.sitepoint.com/htaccess-for-all/


问:
Preview code in IDE
I usualy use Netbeans. But n.b. don't have preview code window like this screen.
(Right part of screen - mini-column) Plugins disabled for this theme.

I want those window!

Thank you all.

答: Netbeans has this feature now. E.g. Netbeans 8.2 View -> Show Outline will give you this:

Title: Preview code in IDE


问:
Chef: mmake sure a service is listennig on network
I'm using this mongodb3 cookbook in order to install a mongodb instance.

I'm trying to perform an script when service starts:

```<code>execute "Add Mongo Users" do
  command "mongo #{host}:#{port} /tmp/mongo.setup.users.js"
  subscribes :run, 'service[mongod]', :delayed
end
</code>```

I'm getting this error:

```<code>==> Expected process to exit with [0], but received '1'
==> ---- Begin output of mongo localhost:30158 /tmp/mongo.setup.users.js ----
==> STDOUT: MongoDB shell version v3.4.2
==> connecting to: localhost:30158
==> 2017-06-05T07:39:48.136+0000 W NETWORK  [thread1] Failed to connect to 127.0.0.1:30158, in(checking soc
ket for error after poll), reason: Connection refused
==> 2017-06-05T07:39:48.136+0000 E QUERY    [thread1] Error: couldn't connect to server localhost:30158, co
nnection attempt failed :
</code>```

So, as you can see, service is not running yet when command is performed (I'm getting a network error).

I've took a look on cookbook repository code. According to this peace of code, the service is started...

Any ideas?

答:
As triggering the start of a service does not mean that it's immediately ready to accept connections, you need to wait for a bit of time.

A common approach is to add an additional, hardcoded delay, e.g.

command "sleep 3; mongo.."
```

<p>Downside: 3 seconds might be enough on machine A, but not on machine B. (So put 20sec and you've solved it for 99.9% of the cases - but didn't become a better programmer ;-)).</p></li>
<li><p>A better approach can be e.g. seen in the <em>jenkins</em> cookbook's helper library:</p>

<pre class="lang-rb prettyprint-override"><code>def wait_until_ready!
  Timeout.timeout(timeout, JenkinsTimeout) do
    begin
      open(endpoint)
    rescue SocketError,
      Errno::ECONNREFUSED,
      Errno::ECONNRESET,
      Errno::ENETUNREACH,
      Timeout::Error,
      OpenURI::HTTPError => e
      # If authentication has been enabled, the server will return an HTTP
      # 403. This is "OK", since it means that the server is actually
      # ready to accept requests.
      return if e.message =~ /^403/

      Chef::Log.debug("Jenkins is not accepting requests - #{e.message}")
      sleep(0.5)
      retry
    end
  end
rescue JenkinsTimeout
  raise JenkinsNotReady.new(endpoint, timeout)
end
</code>```

This code repeatedly tries to connect to Jenkins, until it either works or a timeout is reached. You should be able to adapt this to mongo (you could call the command and check if it succeeds, or directly connect to the TCP port as the Jenkins code does.

A way in between would be to use Chef's retry parameter:

execute "Add Mongo Users" do
  command "mongo #{host}:#{port} /tmp/mongo.setup.users.js"
  retry 10
  subscribes :run, 'service[mongod]', :delayed
end
```

I'm not entirely sure, if it will work, as the mongo command probably returns the failure pretty quickly, leaving little time up to the service to start (so combine with the all-mighty sleep?). Further, depending on the command that you execute, make sure that you won't cause negative side-effects (when it can connect to the service, but fails in a later step - and the result of this is that it runs once again. Think of data corruption and friends here).

Body:
I'm using this mongodb3 cookbook in order to install a mongodb instance.

I'm trying to perform an script when service starts:

execute "Add Mongo Users" do
  command "mongo #{host}:#{port} /tmp/mongo.setup.users.js"
  subscribes :run, 'service[mongod]', :delayed
end

I'm getting this error:

==> Expected process to exit with [0], but received '1'
==> ---- Begin output of mongo localhost:30158 /tmp/mongo.setup.users.js ----
==> STDOUT: MongoDB shell version v3.4.2
==> connecting to: localhost:30158
==> 2017-06-05T07:39:48.136+0000 W NETWORK  [thread1] Failed to connect to 127.0.0.1:30158, in(checking soc
ket for error after poll), reason: Connection refused
==> 2017-06-05T07:39:48.136+0000 E QUERY    [thread1] Error: couldn't connect to server localhost:30158, co
nnection attempt failed :

So, as you can see, service is not running yet when command is performed (I'm getting a network error).

I've took a look on cookbook repository code. According to this peace of code, the service is started...

Any ideas?

Body:
As triggering the start of a service does not mean that it's immediately ready to accept connections, you need to wait for a bit of time.

A common approach is to add an additional, hardcoded delay, e.g.

command "sleep 3; mongo.."

Downside: 3 seconds might be enough on machine A, but not on machine B. (So put 20sec and you've solved it for 99.9% of the cases - but didn't become a better programmer ;-)).

A better approach can be e.g. seen in the jenkins cookbook's helper library:

def wait_until_ready!
  Timeout.timeout(timeout, JenkinsTimeout) do
    begin
      open(endpoint)
    rescue SocketError,
      Errno::ECONNREFUSED,
      Errno::ECONNRESET,
      Errno::ENETUNREACH,
      Timeout::Error,
      OpenURI::HTTPError => e
      # If authentication has been enabled, the server will return an HTTP
      # 403. This is "OK", since it means that the server is actually
      # ready to accept requests.
      return if e.message =~ /^403/

      Chef::Log.debug("Jenkins is not accepting requests - #{e.message}")
      sleep(0.5)
      retry
    end
  end
rescue JenkinsTimeout
  raise JenkinsNotReady.new(endpoint, timeout)
end

This code repeatedly tries to connect to Jenkins, until it either works or a timeout is reached. You should be able to adapt this to mongo (you could call the command and check if it succeeds, or directly connect to the TCP port as the Jenkins code does.

A way in between would be to use Chef's retry parameter:

execute "Add Mongo Users" do
  command "mongo #{host}:#{port} /tmp/mongo.setup.users.js"
  retry 10
  subscribes :run, 'service[mongod]', :delayed
end

I'm not entirely sure, if it will work, as the mongo command probably returns the failure pretty quickly, leaving little time up to the service to start (so combine with the all-mighty sleep?). Further, depending on the command that you execute, make sure that you won't cause negative side-effects (when it can connect to the service, but fails in a later step - and the result of this is that it runs once again. Think of data corruption and friends here).


问:
Using dummy variables for Machine Learning with more than one categorical variable
I am looking to do either a multivariate Linear Regression or a Logistic Regression using Python on some data that has a large number of categorical variables. I understand that with one Categorical variable I would need to translate this into a dummy and then remove one type of dummy so as to avoid colinearity however is anyone familiar with what the approach should be when dealing with more than one type of categorical variable?

Do I do the same thing for each? e.g translate each type of record into a dummy variable and then for each remove one dummy variable so as to avoid colinearity?

答:
In a case where there is more than one categorical variable that needs to be replaced for a dummy. The approach should be to encode each of the variables for a dummy (as in the case for a single categorical variable) and then remove one instance of each dummy that exists for each variable in order to avoid colinearity.

Basically, each categorical variable should be treated the same as a single individual one.


问:
Pass multiple values to query dynamically in java
I am trying to pass multiple values in a SELECT QUERY consisting of two IN clauses. I would like to execute the following query:

```<code>String sql = "select ADDRESS from CDR where APARTY in(?,?,?) intersect select ADDRESS from CDR where BPARTY in (?,?) and USAGETYPE='SMSMT'";
</code>```

How can I pass value using preparedStatement.setString() ?.Thanks in advance.

答:
To build your query you can use for example StringBuilder for example :

Consider you have a two lists like this :

```<code>List<String> values1 = new ArrayList<>();
values1.add("val1_1");
values1.add("val1_2");
values1.add("val1_3");
List<String> values2 = new ArrayList<>();
values2.add("val2_1");
values2.add("val2_2");
</code>```

Now we will build the query :

```<code>StringBuilder sql = new StringBuilder("select ADDRESS from CDR where APARTY IN(");

for (int i = 0; i < values1.size(); i++) {
    sql.append(i == values1.size() - 1 ? "?" : "?,");
}
sql.append(") intersect select ADDRESS from CDR where BPARTY IN (");
for (int i = 0; i < values2.size(); i++) {
    sql.append(i == values2.size() - 1 ? "?" : "?,");
}
sql.append(") and USAGETYPE='SMSMT'");
System.out.println(sql);
</code>```

Until now this can gives you :

```<code>select ADDRESS from CDR where APARTY IN(?,?,?) intersect select ADDRESS from CDR where BPARTY IN (?,?) and USAGETYPE='SMSMT'
</code>```

Now you have to use this query in the PreparedStatement :

```<code>try (PreparedStatement pstm = connection.prepareStatement(sql)) {
    int i = 1;
    for (String s : values1) {
        pstm.setString(i++, s);
    }

    for (String s : values2) {
        pstm.setString(i++, s);
    }
    //...execute the statement and retrieve the results
}
</code>```

Body:
I am trying to pass multiple values in a SELECT QUERY consisting of two IN clauses. I would like to execute the following query:

String sql = "select ADDRESS from CDR where APARTY in(?,?,?) intersect select ADDRESS from CDR where BPARTY in (?,?) and USAGETYPE='SMSMT'";

How can I pass value using preparedStatement.setString() ?.Thanks in advance.

Body:
To build your query you can use for example StringBuilder for example :

Consider you have a two lists like this :

List<String> values1 = new ArrayList<>();
values1.add("val1_1");
values1.add("val1_2");
values1.add("val1_3");
List<String> values2 = new ArrayList<>();
values2.add("val2_1");
values2.add("val2_2");

Now we will build the query :

StringBuilder sql = new StringBuilder("select ADDRESS from CDR where APARTY IN(");

for (int i = 0; i < values1.size(); i++) {
    sql.append(i == values1.size() - 1 ? "?" : "?,");
}
sql.append(") intersect select ADDRESS from CDR where BPARTY IN (");
for (int i = 0; i < values2.size(); i++) {
    sql.append(i == values2.size() - 1 ? "?" : "?,");
}
sql.append(") and USAGETYPE='SMSMT'");
System.out.println(sql);

Until now this can gives you :

select ADDRESS from CDR where APARTY IN(?,?,?) intersect select ADDRESS from CDR where BPARTY IN (?,?) and USAGETYPE='SMSMT'

Now you have to use this query in the PreparedStatement :

try (PreparedStatement pstm = connection.prepareStatement(sql)) {
    int i = 1;
    for (String s : values1) {
        pstm.setString(i++, s);
    }

    for (String s : values2) {
        pstm.setString(i++, s);
    }
    //...execute the statement and retrieve the results
}


问:
Flying Saucer does not render background color and strikethrough
Flying Saucer does not render the strikethrough for the following HTML sample:

```<code><s><span style="color: rgb(255, 0, 0);"><span style="background-color: rgb(255, 255, 0);">This is a test </span></span>
</s>
</code>```

Only the background color and the colored text is shown on the generated PDF:

However, the strikethrough is properly rendered when not using a background color.

How can I get Flying Saucer to render the strikethrough when combined with a background color?

Update June 6

If I move the strike tag <s> inside of the span tags, then it works:

```<code><span style="color: rgb(255, 0, 0);"><span style="background-color: rgb(255, 255, 0);"><s>This is a test</s></span></span>
</code>```

答:
There may be a problem in your CSS.

Here is an example which shows strikethrough working with flying-saucer (9.1.1):

```<code><html>
<head>
    <style>
        span {
            color: rgb(255, 0, 0);
            background-color: rgb(255, 255, 0);
        }
        span.decorated {    text-decoration: line-through;}
    </style>
</head>
<body>
    <span>Without strikethrough</span>
    <span class="decorated">With strikethrough</span>
</body>
</html>
</code>```

The result:

Body:
Flying Saucer does not render the strikethrough for the following HTML sample:

<s>This is a test
</s>

Only the background color and the colored text is shown on the generated PDF:

However, the strikethrough is properly rendered when not using a background color.

How can I get Flying Saucer to render the strikethrough when combined with a background color?

Update June 6

If I move the strike tag <s> inside of the span tags, then it works:

<s>This is a test</s>

Body:
There may be a problem in your CSS.

Here is an example which shows strikethrough working with flying-saucer (9.1.1):

<html>
<head>
    <style>
        span {
            color: rgb(255, 0, 0);
            background-color: rgb(255, 255, 0);
        }
        span.decorated {    text-decoration: line-through;}
    </style>
</head>
<body>
    <span>Without strikethrough</span>
    <span class="decorated">With strikethrough</span>
</body>
</html>

The result:


问:
getting confusion on this explain this loop result in java
```<code>int a = 0, b = 0;

for (int i = 0; i < 5; i++) {
    if (++a > 2 || ++b > 2) {
        a++;
    }
}

System.out.println("a= " + a + " b=" + b);
</code>```

can you explain the logic please?

答:
These are the five iteration and result of a & b finally. Every row is the result of every single iteration in loop.</p>

```<code>a     b
--------
1     1
2     2
4     2
6     2
8     2

++a > 2    means   increment a (by 1) first than compare with 2
++b > 2    means   increment b (by 1) first than compare with 2
a++        means   a=a+1;  means increment a by 1.
</code>```

Body:
int a = 0, b = 0;

for (int i = 0; i < 5; i++) {
    if (++a > 2 || ++b > 2) {
        a++;
    }
}

System.out.println("a= " + a + " b=" + b);

can you explain the logic please?

Body:
These are the five iteration and result of a & b finally. Every row is the result of every single iteration in loop.

a     b
--------
1     1
2     2
4     2
6     2
8     2

++a > 2    means   increment a (by 1) first than compare with 2
++b > 2    means   increment b (by 1) first than compare with 2
a++        means   a=a+1;  means increment a by 1.


问:
Python create sorted list based on attribute
I need to create a list of dictionary values, sorted based on whether or not the value is empty, my attempt gets the desired output but has to iterate twice over the dictionary, I was wondering if there was a way to do this only iterating once? My actual dictionary contains like 50,000 values and just iterating once would save some time when doing it repeatedly

```<code>d = {'id1':[],
     'id2':[1],
     'id3':[1]}
l = [v for v in d.values() if v]+[v for v in d.values() if not v]
print (l)
</code>```

this is my desired output:

```<code>[[1], [1], []]
</code>```

答:
I suggest SortedContainers : Fast, pure-Python implementation of SortedList, SortedDict, and SortedSet types.</p>

```<code>from sortedcontainers import SortedList
d = {'id1':[],
     'id2':[1],
     'id3':[1]}

res=SortedList(d.values())
</code>```

Body:
I need to create a list of dictionary values, sorted based on whether or not the value is empty, my attempt gets the desired output but has to iterate twice over the dictionary, I was wondering if there was a way to do this only iterating once? My actual dictionary contains like 50,000 values and just iterating once would save some time when doing it repeatedly

d = {'id1':[],
     'id2':[1],
     'id3':[1]}
l = [v for v in d.values() if v]+[v for v in d.values() if not v]
print (l)

this is my desired output:

[[1], [1], []]

Body:
I suggest SortedContainers : Fast, pure-Python implementation of SortedList, SortedDict, and SortedSet types.

from sortedcontainers import SortedList
d = {'id1':[],
     'id2':[1],
     'id3':[1]}

res=SortedList(d.values())


问:
Why is goto poor practise?

This question is a duplicate of  Goto Still Considered Harmful. If you wish to discuss this further please use the original question.

Why exactly is GOTO poor programming practise? It makes sense on some occasions to use it.

答: GOTO short circuits your control flow, thereby undermining your design and opening the door to debug and maintenance nightmares. </p>

Title: Why is goto poor practise?

LastEditorDisplayName: Rich B

OwnerDisplayName: cmsjr


问:
Devexpress AspxScheduler displays the current time line across calendar (colour amber-ish)
How can I get rid of it?</p>

答: Set the OptionsBehavior.ShowTimeMarker property to False to hide this line..</p>

Body: How can I get rid of it?


问:
Custom dialog too small
I have an android activity that implements a custom dialog.The application is running ok but the dialog is too small,i want to display a bigger dialog.How can i achieve this?
Here is my layout xml

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/white"
android:orientation="vertical" >

         <LinearLayout
         android:layout_width="match_parent"
         android:layout_height="wrap_content"
         android:orientation="vertical"
         android:background="@drawable/view_more_borders">

         <LinearLayout
             android:layout_width="match_parent"
             android:layout_height="match_parent"
             android:layout_weight="1"
             android:orientation="horizontal"
             android:layout_marginTop="4dp"
             android:gravity="center_vertical">

             <TextView
                 android:id="@+id/share_amount"
                 android:layout_width="0dp"
                 android:layout_height="wrap_content"
                 android:layout_weight="1"
                 android:text="Company Name:"
                 android:textAppearance="?android:attr/textAppearanceSmall"
                 android:textColor="@color/nice_blue"
                 android:typeface="sans" />

            <TextView
                android:id="@+id/textViewCompanyName"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1.80"
                android:text=" "
                android:textAppearance="?android:attr/textAppearanceSmall" />

         </LinearLayout>

         <LinearLayout
             android:layout_width="match_parent"
             android:layout_height="match_parent"
             android:layout_weight="1"
             android:layout_marginTop="4dp"
             android:gravity="center_vertical">

             <TextView
                android:id="@+id/textView5"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="Price per share:"

                android:textAppearance="?android:attr/textAppearanceSmall"
                android:textColor="@color/nice_blue" />

            <TextView
                android:id="@+id/textViewprice_pershare"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="2"
                android:layout_alignBaseline="@+id/Yesterday"
                android:layout_alignBottom="@+id/Yesterday"
                android:layout_marginLeft="38dp"
                android:fontFamily="sans-serif"
                android:layout_toRightOf="@+id/company"
                android:text=" "
                android:textAppearance="?android:attr/textAppearanceSmall" />
         </LinearLayout>

         <LinearLayout
             android:layout_width="match_parent"
             android:layout_height="match_parent"
             android:layout_weight="1"
             android:layout_marginTop="4dp"
             android:gravity="center_vertical">

              <TextView
                    android:id="@+id/textView4"
                  android:layout_width="0dp"
                  android:layout_height="wrap_content"
                  android:layout_weight="1"
                  android:text="Total cost:"

                  android:textAppearance="?android:attr/textAppearanceSmall"
                  android:textColor="@color/nice_blue" />

            <TextView
                android:id="@+id/textview_totalcost"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="2"
                android:layout_alignBaseline="@+id/Yesterday"
                android:layout_alignBottom="@+id/Yesterday"
                android:layout_marginLeft="38dp"
                android:fontFamily="sans-serif"
                android:layout_toRightOf="@+id/company"
                android:text=" "
                android:textAppearance="?android:attr/textAppearanceSmall" />
         </LinearLayout>

         <LinearLayout
             android:layout_width="match_parent"
             android:layout_height="match_parent"
             android:layout_weight="1"
             android:layout_marginTop="4dp"
             android:gravity="center_vertical">

                 <TextView
            android:id="@+id/textView3"
                     android:layout_width="0dp"
                     android:layout_height="wrap_content"
                     android:layout_weight="1"
                     android:text="Number of shares:"

                     android:textAppearance="?android:attr/textAppearanceSmall"
                     android:textColor="@color/nice_blue" />

            <EditText
                android:id="@+id/shareNumber"
                android:layout_width="0dp"
                android:layout_weight="2"
                android:layout_height="wrap_content"
                android:inputType="number"
                android:fontFamily="sans-serif"
                android:textSize="12sp"
                 >

            <requestFocus />
            </EditText>
         </LinearLayout>

         <LinearLayout
             android:layout_width="match_parent"
             android:layout_height="match_parent"
             android:layout_weight="1"
             android:layout_marginTop="4dp"
             android:gravity="center_vertical">

              <TextView
        android:id="@+id/textView2"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="Payment method:"

                android:textAppearance="?android:attr/textAppearanceSmall"
                android:textColor="@color/nice_blue" />

             <Spinner
                 android:id="@+id/spinner_paymentmode"
                 android:layout_width="0dp"
                 android:layout_height="wrap_content"
                 android:layout_weight="2" />

         </LinearLayout>
     </LinearLayout>
     <Button
    android:id="@+id/button_buy_shares"
    style="@style/ButtonText"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/blue_button"
    android:text="Buy" />
</code>```

And here is my output.I want to increase the width and height of the dialog.

And my java file

```<code>public class MyDialogFragment extends DialogFragment {

public MyDialogFragment() {

}

private EditText mEditText;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.dialogfragment, container);
    // mEditText = (EditText) view.findViewById(R.id.txt_your_name);
    // getDialog().setTitle("Hello");
    getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE);

    return view;
}
}
</code>```

答:
put below line in onCreate

```<code>setStyle(DialogFragment.STYLE_NO_TITLE, android.R.style.Theme_Holo_Light_Dialog_NoActionBar_MinWidth);
</code>```

original answer

Title: Custom dialog too small

Body:
I have an android activity that implements a custom dialog.The application is running ok but the dialog is too small,i want to display a bigger dialog.How can i achieve this?
Here is my layout xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/white"
android:orientation="vertical" >

         <LinearLayout
         android:layout_width="match_parent"
         android:layout_height="wrap_content"
         android:orientation="vertical"
         android:background="@drawable/view_more_borders">

         <LinearLayout
             android:layout_width="match_parent"
             android:layout_height="match_parent"
             android:layout_weight="1"
             android:orientation="horizontal"
             android:layout_marginTop="4dp"
             android:gravity="center_vertical">

             <TextView
                 android:id="@+id/share_amount"
                 android:layout_width="0dp"
                 android:layout_height="wrap_content"
                 android:layout_weight="1"
                 android:text="Company Name:"
                 android:textAppearance="?android:attr/textAppearanceSmall"
                 android:textColor="@color/nice_blue"
                 android:typeface="sans" />

            <TextView
                android:id="@+id/textViewCompanyName"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1.80"
                android:text=" "
                android:textAppearance="?android:attr/textAppearanceSmall" />

         </LinearLayout>

         <LinearLayout
             android:layout_width="match_parent"
             android:layout_height="match_parent"
             android:layout_weight="1"
             android:layout_marginTop="4dp"
             android:gravity="center_vertical">

             <TextView
                android:id="@+id/textView5"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="Price per share:"

                android:textAppearance="?android:attr/textAppearanceSmall"
                android:textColor="@color/nice_blue" />

            <TextView
                android:id="@+id/textViewprice_pershare"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="2"
                android:layout_alignBaseline="@+id/Yesterday"
                android:layout_alignBottom="@+id/Yesterday"
                android:layout_marginLeft="38dp"
                android:fontFamily="sans-serif"
                android:layout_toRightOf="@+id/company"
                android:text=" "
                android:textAppearance="?android:attr/textAppearanceSmall" />
         </LinearLayout>

         <LinearLayout
             android:layout_width="match_parent"
             android:layout_height="match_parent"
             android:layout_weight="1"
             android:layout_marginTop="4dp"
             android:gravity="center_vertical">

              <TextView
                    android:id="@+id/textView4"
                  android:layout_width="0dp"
                  android:layout_height="wrap_content"
                  android:layout_weight="1"
                  android:text="Total cost:"

                  android:textAppearance="?android:attr/textAppearanceSmall"
                  android:textColor="@color/nice_blue" />

            <TextView
                android:id="@+id/textview_totalcost"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="2"
                android:layout_alignBaseline="@+id/Yesterday"
                android:layout_alignBottom="@+id/Yesterday"
                android:layout_marginLeft="38dp"
                android:fontFamily="sans-serif"
                android:layout_toRightOf="@+id/company"
                android:text=" "
                android:textAppearance="?android:attr/textAppearanceSmall" />
         </LinearLayout>

         <LinearLayout
             android:layout_width="match_parent"
             android:layout_height="match_parent"
             android:layout_weight="1"
             android:layout_marginTop="4dp"
             android:gravity="center_vertical">

                 <TextView
            android:id="@+id/textView3"
                     android:layout_width="0dp"
                     android:layout_height="wrap_content"
                     android:layout_weight="1"
                     android:text="Number of shares:"

                     android:textAppearance="?android:attr/textAppearanceSmall"
                     android:textColor="@color/nice_blue" />

            <EditText
                android:id="@+id/shareNumber"
                android:layout_width="0dp"
                android:layout_weight="2"
                android:layout_height="wrap_content"
                android:inputType="number"
                android:fontFamily="sans-serif"
                android:textSize="12sp"
                 >

            <requestFocus />
            </EditText>
         </LinearLayout>

         <LinearLayout
             android:layout_width="match_parent"
             android:layout_height="match_parent"
             android:layout_weight="1"
             android:layout_marginTop="4dp"
             android:gravity="center_vertical">

              <TextView
        android:id="@+id/textView2"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="Payment method:"

                android:textAppearance="?android:attr/textAppearanceSmall"
                android:textColor="@color/nice_blue" />

             <Spinner
                 android:id="@+id/spinner_paymentmode"
                 android:layout_width="0dp"
                 android:layout_height="wrap_content"
                 android:layout_weight="2" />

         </LinearLayout>
     </LinearLayout>
     <Button
    android:id="@+id/button_buy_shares"
    style="@style/ButtonText"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/blue_button"
    android:text="Buy" />

And here is my output.I want to increase the width and height of the dialog.

And my java file

public class MyDialogFragment extends DialogFragment {

public MyDialogFragment() {

}

private EditText mEditText;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.dialogfragment, container);
    // mEditText = (EditText) view.findViewById(R.id.txt_your_name);
    // getDialog().setTitle("Hello");
    getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE);

    return view;
}
}

Body:
put below line in onCreate

setStyle(DialogFragment.STYLE_NO_TITLE, android.R.style.Theme_Holo_Light_Dialog_NoActionBar_MinWidth);

original answer


问:
JSON Data to Table View is too slow
I am showing JSON data in TableView but the application is slow. It is waiting 5-10 seconds before display.
I am getting this error in Xcode output:

2017-06-05 12:49:47.505 Ekstraders[1167:137558] This application is
  modifying the autolayout engine from a background thread after the
  engine was accessed from the main thread. This can lead to engine
  corruption and weird crashes.

```<code> Stack:(
    0   CoreFoundation                      0x000000010ad78b0b __exceptionPreprocess + 171
    1   libobjc.A.dylib                     0x0000000108020141 objc_exception_throw + 48
    2   CoreFoundation                      0x000000010ade1625 +[NSException raise:format:] + 197
    3   Foundation                          0x0000000107d1917b _AssertAutolayoutOnAllowedThreadsOnly + 105
    4   Foundation                          0x0000000107d18f0f -[NSISEngine _optimizeWithoutRebuilding] + 61
    5   Foundation                          0x0000000107b487e6 -[NSISEngine optimize] + 108
    6   Foundation                          0x0000000107d16ef4 -[NSISEngine performPendingChangeNotifications] + 84
    7   UIKit                               0x00000001085b5412 -[UIView(CALayerDelegate) layoutSublayersOfLayer:] + 1787
    8   QuartzCore                          0x000000010dce6904 -[CALayer layoutSublayers] + 146
    9   QuartzCore                          0x000000010dcda526 _ZN2CA5Layer16layout_if_neededEPNS_11TransactionE + 370
    10  QuartzCore                          0x000000010dcda3a0 _ZN2CA5Layer28layout_and_display_if_neededEPNS_11TransactionE + 24
    11  QuartzCore                          0x000000010dc69e92 _ZN2CA7Context18commit_transactionEPNS_11TransactionE + 294
    12  QuartzCore                          0x000000010dc96130 _ZN2CA11Transaction6commitEv + 468
    13  QuartzCore                          0x000000010dc9642c _ZN2CA11Transaction14release_threadEPv + 214
    14  libsystem_pthread.dylib             0x000000010c065413 _pthread_tsd_cleanup + 544
    15  libsystem_pthread.dylib             0x000000010c06514d _pthread_exit + 152
    16  libsystem_pthread.dylib             0x000000010c0636d1 pthread_attr_getschedpolicy + 0
    17  libsystem_pthread.dylib             0x000000010c0630f1 start_wqthread + 13
)
</code>```

ViewController.swift:

```<code>import UIKit

class FirstViewController: UIViewController,UITableViewDataSource,UITableViewDelegate {

    @IBOutlet weak var tableView: UITableView!

    var tbCount = 0

    var myMp3s = [Mp3]()

    override func viewDidLoad() {
        super.viewDidLoad()

        tableView.dataSource = self
        tableView.delegate = self

        let url = URL(string: "example.php")

         DispatchQueue.main.async() { //JSON to Mp3 object.

        URLSession.shared.dataTask(with:url!, completionHandler: {(data, response, error) in
            guard let data = data, error == nil else { return }

            do {
                let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as! [String:Any]
                let posts = json["server_response"] as? [[String: Any]] ?? []

                for i in posts {

                    print(i["id"]!)

                    let mp3 = Mp3(id: i["id"] as! String, category: i["kategori"] as! String)

                    self.myMp3s.append(mp3)

                }

                self.tableView.reloadData()
                self.tableView.tableFooterView = UIView(frame: .zero)

                print("counte", self.myMp3s.count)

            } catch let error as NSError {
                print(error)
            }
        }).resume()

        }

    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return myMp3s.count

    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {

        var height:CGFloat = CGFloat()

        height = 100
        return height
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell  = UITableViewCell()
        cell.backgroundColor =  UIColor.darkGray

        //Design
        cell.textLabel?.text = self.myMp3s[indexPath.row].category

        cell.textLabel?.backgroundColor = .red
        cell.textLabel?.layer.borderWidth = 3
        cell.textLabel?.layer.borderColor = UIColor.lightGray.cgColor
        cell.textLabel?.heightAnchor.constraint(equalToConstant: 50).isActive = true
        cell.textLabel?.widthAnchor.constraint(equalToConstant: 200).isActive = true

        cell.textLabel?.layer.cornerRadius = 10
        cell.textLabel?.clipsToBounds = true
        cell.textLabel?.centerYAnchor.constraint(equalTo: cell.centerYAnchor).isActive = true
        cell.textLabel?.centerXAnchor.constraint(equalTo: cell.centerXAnchor).isActive = true

        cell.textLabel?.textAlignment = .center
        cell.textLabel?.textColor = .white
        cell.textLabel?.font = UIFont.boldSystemFont(ofSize: 16.0)

        return cell

    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        print(myMp3s[indexPath.row].category)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}
</code>```

I can show JSON data in tableview, no problem but the problem is that it is too slow. It is waiting before display.
How can I solve this problem? Where am I wrong?

答:
The data you are receiving is big, or if it is small you might be experiencing network problems.To check the amount of data and average time, fetch that data using a REST client. You can use Postman or ARC to know the data.

As everyone else mentioned, you are getting that error, (Not crash) I believe, as you are making UI changes from a background thread. Now the network call you are making is an asynchronous call, meaning it is getting called in the background thread, once it is initiated. You should always make UI changes from the main thread.

```<code>DispatchQueue.main.async {
   self.tableView.reloadData()
   self.tableView.tableFooterView = UIView(frame: .zero)
}
</code>```

Title: JSON Data to Table View is too slow

Body:
I am showing JSON data in TableView but the application is slow. It is waiting 5-10 seconds before display.
I am getting this error in Xcode output:

2017-06-05 12:49:47.505 Ekstraders[1167:137558] This application is
  modifying the autolayout engine from a background thread after the
  engine was accessed from the main thread. This can lead to engine
  corruption and weird crashes.

 Stack:(
    0   CoreFoundation                      0x000000010ad78b0b __exceptionPreprocess + 171
    1   libobjc.A.dylib                     0x0000000108020141 objc_exception_throw + 48
    2   CoreFoundation                      0x000000010ade1625 +[NSException raise:format:] + 197
    3   Foundation                          0x0000000107d1917b _AssertAutolayoutOnAllowedThreadsOnly + 105
    4   Foundation                          0x0000000107d18f0f -[NSISEngine _optimizeWithoutRebuilding] + 61
    5   Foundation                          0x0000000107b487e6 -[NSISEngine optimize] + 108
    6   Foundation                          0x0000000107d16ef4 -[NSISEngine performPendingChangeNotifications] + 84
    7   UIKit                               0x00000001085b5412 -[UIView(CALayerDelegate) layoutSublayersOfLayer:] + 1787
    8   QuartzCore                          0x000000010dce6904 -[CALayer layoutSublayers] + 146
    9   QuartzCore                          0x000000010dcda526 _ZN2CA5Layer16layout_if_neededEPNS_11TransactionE + 370
    10  QuartzCore                          0x000000010dcda3a0 _ZN2CA5Layer28layout_and_display_if_neededEPNS_11TransactionE + 24
    11  QuartzCore                          0x000000010dc69e92 _ZN2CA7Context18commit_transactionEPNS_11TransactionE + 294
    12  QuartzCore                          0x000000010dc96130 _ZN2CA11Transaction6commitEv + 468
    13  QuartzCore                          0x000000010dc9642c _ZN2CA11Transaction14release_threadEPv + 214
    14  libsystem_pthread.dylib             0x000000010c065413 _pthread_tsd_cleanup + 544
    15  libsystem_pthread.dylib             0x000000010c06514d _pthread_exit + 152
    16  libsystem_pthread.dylib             0x000000010c0636d1 pthread_attr_getschedpolicy + 0
    17  libsystem_pthread.dylib             0x000000010c0630f1 start_wqthread + 13
)

ViewController.swift:

import UIKit

class FirstViewController: UIViewController,UITableViewDataSource,UITableViewDelegate {

    @IBOutlet weak var tableView: UITableView!

    var tbCount = 0

    var myMp3s = [Mp3]()

    override func viewDidLoad() {
        super.viewDidLoad()

        tableView.dataSource = self
        tableView.delegate = self

        let url = URL(string: "example.php")

         DispatchQueue.main.async() { //JSON to Mp3 object.

        URLSession.shared.dataTask(with:url!, completionHandler: {(data, response, error) in
            guard let data = data, error == nil else { return }

            do {
                let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as! [String:Any]
                let posts = json["server_response"] as? [[String: Any]] ?? []

                for i in posts {

                    print(i["id"]!)

                    let mp3 = Mp3(id: i["id"] as! String, category: i["kategori"] as! String)

                    self.myMp3s.append(mp3)

                }

                self.tableView.reloadData()
                self.tableView.tableFooterView = UIView(frame: .zero)

                print("counte", self.myMp3s.count)

            } catch let error as NSError {
                print(error)
            }
        }).resume()

        }

    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return myMp3s.count

    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {

        var height:CGFloat = CGFloat()

        height = 100
        return height
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell  = UITableViewCell()
        cell.backgroundColor =  UIColor.darkGray

        //Design
        cell.textLabel?.text = self.myMp3s[indexPath.row].category

        cell.textLabel?.backgroundColor = .red
        cell.textLabel?.layer.borderWidth = 3
        cell.textLabel?.layer.borderColor = UIColor.lightGray.cgColor
        cell.textLabel?.heightAnchor.constraint(equalToConstant: 50).isActive = true
        cell.textLabel?.widthAnchor.constraint(equalToConstant: 200).isActive = true

        cell.textLabel?.layer.cornerRadius = 10
        cell.textLabel?.clipsToBounds = true
        cell.textLabel?.centerYAnchor.constraint(equalTo: cell.centerYAnchor).isActive = true
        cell.textLabel?.centerXAnchor.constraint(equalTo: cell.centerXAnchor).isActive = true

        cell.textLabel?.textAlignment = .center
        cell.textLabel?.textColor = .white
        cell.textLabel?.font = UIFont.boldSystemFont(ofSize: 16.0)

        return cell

    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        print(myMp3s[indexPath.row].category)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}

I can show JSON data in tableview, no problem but the problem is that it is too slow. It is waiting before display.
How can I solve this problem? Where am I wrong?

Body:
The data you are receiving is big, or if it is small you might be experiencing network problems.To check the amount of data and average time, fetch that data using a REST client. You can use Postman or ARC to know the data.

As everyone else mentioned, you are getting that error, (Not crash) I believe, as you are making UI changes from a background thread. Now the network call you are making is an asynchronous call, meaning it is getting called in the background thread, once it is initiated. You should always make UI changes from the main thread.

DispatchQueue.main.async {
   self.tableView.reloadData()
   self.tableView.tableFooterView = UIView(frame: .zero)
}


问:
remove extra + from text SQL
this refers to a question asked by someone else previously
previous question

my question is how do I adapt this solution so that before any function/script is ran the name and value fields are stripped of any additional + and updated so no additional + remain.

For e.g.

```<code>Name     Value
A+B+C+   1+2+3+
A++B     1++2
</code>```

this should be updated to

```<code>   Name     Value
    A+B+C   1+2+3
    A+B     1+2
</code>```

once this update has taken place, I can run the solution provided in the previous question.

Thanks

答:
You can use the below:

```<code>LTRIM(RTRIM (REGEXP_REPLACE (column_name, '\+{2,}', '+'), '+'),'+')
</code>```

Eg:

```<code>    SELECT LTRIM(RTRIM (REGEXP_REPLACE ('+A+++B+C+++D++', '\+{2,}', '+'), '+'),'+') VALUE
  FROM DUAL;
</code>```

returns output: A+B+C+D

Title: remove extra + from text SQL

Body:
this refers to a question asked by someone else previously
previous question

my question is how do I adapt this solution so that before any function/script is ran the name and value fields are stripped of any additional + and updated so no additional + remain.

For e.g.

Name     Value
A+B+C+   1+2+3+
A++B     1++2

this should be updated to

   Name     Value
    A+B+C   1+2+3
    A+B     1+2

once this update has taken place, I can run the solution provided in the previous question.

Thanks

Body:
You can use the below:

LTRIM(RTRIM (REGEXP_REPLACE (column_name, '\+{2,}', '+'), '+'),'+')

Eg:

    SELECT LTRIM(RTRIM (REGEXP_REPLACE ('+A+++B+C+++D++', '\+{2,}', '+'), '+'),'+') VALUE
  FROM DUAL;

returns output: A+B+C+D


问:
Which is the best way to display combobox on a cell if a condition is verified?
So here is my problem: I have to build a grid on my view (it can be a datagrid or a gridview, i have no particular preference). I know the number of columns, but i have to build the row dinamically. The problem is that there are some rows that must display a combobox on the third column if the datatype of the data inside the first column is different from "string", otherways they have a simple textbox. I know that there is a control named "template selector" which can do stuff like this, but since i never used it, i wonder if this is the best way to approach my problem. </p>

答:
Without knowing any details about what you are trying to do, you could for example use a DataGridTemplateColumn with a CellTemplateSelector/CellEditingTemplateSelector.

The following sample code should give you the idea:

```<code><DataGrid x:Name="dg">
    <DataGrid.Resources>
        <DataTemplate x:Key="dtA">...</DataTemplate>
        <DataTemplate x:Key="dtB">...</DataTemplate>
        <local:Selector x:Key="selector" TemplateA="{StaticResource dtA}" TemplateB="{StaticResource dtA}" />
    </DataGrid.Resources>
    <DataGrid.Columns>
        <DataGridTextColumn Binding="{Binding A}" />
        <DataGridTextColumn Binding="{Binding B}" />
        <DataGridTemplateColumn CellEditingTemplateSelector="{StaticResource selector}">
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <TextBlock Text="{Binding C}" />
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>
    </DataGrid.Columns>
</DataGrid>
</code>```

```<code>public class Selector : DataTemplateSelector
{
    public DataTemplate TemplateA { get; set; }
    public DataTemplate TemplateB { get; set; }

    public override DataTemplate SelectTemplate(object item, DependencyObject container)
    {
        System.Data.DataRowView dr = item as DataRowView;
        //return TemplateA or TemplateB based on your logic

        return base.SelectTemplate(item, container);
    }
}
</code>```

Body:
Without knowing any details about what you are trying to do, you could for example use a DataGridTemplateColumn with a CellTemplateSelector/CellEditingTemplateSelector.

The following sample code should give you the idea:

<DataGrid x:Name="dg">
    <DataGrid.Resources>
        <DataTemplate x:Key="dtA">...</DataTemplate>
        <DataTemplate x:Key="dtB">...</DataTemplate>
        <local:Selector x:Key="selector" TemplateA="{StaticResource dtA}" TemplateB="{StaticResource dtA}" />
    </DataGrid.Resources>
    <DataGrid.Columns>
        <DataGridTextColumn Binding="{Binding A}" />
        <DataGridTextColumn Binding="{Binding B}" />
        <DataGridTemplateColumn CellEditingTemplateSelector="{StaticResource selector}">
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <TextBlock Text="{Binding C}" />
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>
    </DataGrid.Columns>
</DataGrid>

public class Selector : DataTemplateSelector
{
    public DataTemplate TemplateA { get; set; }
    public DataTemplate TemplateB { get; set; }

    public override DataTemplate SelectTemplate(object item, DependencyObject container)
    {
        System.Data.DataRowView dr = item as DataRowView;
        //return TemplateA or TemplateB based on your logic

        return base.SelectTemplate(item, container);
    }
}


答:
Following up on the comment, if you are willing to use ItemsControl in place of your grid, one way to achieve the behavior in question is as follows:

View:

```<code><Window.Resources>
    <BooleanToVisibilityConverter x:Key="BoolToVis"/>
</Window.Resources>
<StackPanel>
    <ItemsControl ItemsSource="{Binding MyItems, Mode=OneWay}">
        <ItemsControl.ItemTemplate>
            <DataTemplate>
                <StackPanel Orientation="Horizontal">
                    <Label Width="150" Content="{Binding FirstProperty}"/>
                    <ComboBox Width="150"
                              Visibility="{Binding HasCombobox, Converter={StaticResource BoolToVis}}"/>
                </StackPanel>
            </DataTemplate>
        </ItemsControl.ItemTemplate>
    </ItemsControl>
</StackPanel>
</code>```

Code-behind + view-model:

```<code>public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        DataContext = new MainWindowViewModel();
    }
}

public class MainWindowViewModel
{
    public MainWindowViewModel()
    {
        MyItems = new List<DisplayableItem>
        {
            new DisplayableItem { FirstProperty = "Some string" },
            new DisplayableItem { FirstProperty = 60 },
            new DisplayableItem { FirstProperty = "Also a string" },
        };
    }

    public IEnumerable<DisplayableItem> MyItems { get; }
}

public class DisplayableItem
{
    public object FirstProperty { get; set; }
    public bool HasCombobox => !(FirstProperty is string);
}
</code>```

Title: Which is the best way to display combobox on a cell if a condition is verified?

Body: So here is my problem: I have to build a grid on my view (it can be a datagrid or a gridview, i have no particular preference). I know the number of columns, but i have to build the row dinamically. The problem is that there are some rows that must display a combobox on the third column if the datatype of the data inside the first column is different from "string", otherways they have a simple textbox. I know that there is a control named "template selector" which can do stuff like this, but since i never used it, i wonder if this is the best way to approach my problem.

Body:
Following up on the comment, if you are willing to use ItemsControl in place of your grid, one way to achieve the behavior in question is as follows:

View:

<Window.Resources>
    <BooleanToVisibilityConverter x:Key="BoolToVis"/>
</Window.Resources>
<StackPanel>
    <ItemsControl ItemsSource="{Binding MyItems, Mode=OneWay}">
        <ItemsControl.ItemTemplate>
            <DataTemplate>
                <StackPanel Orientation="Horizontal">
                    <Label Width="150" Content="{Binding FirstProperty}"/>
                    <ComboBox Width="150"
                              Visibility="{Binding HasCombobox, Converter={StaticResource BoolToVis}}"/>
                </StackPanel>
            </DataTemplate>
        </ItemsControl.ItemTemplate>
    </ItemsControl>
</StackPanel>

Code-behind + view-model:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        DataContext = new MainWindowViewModel();
    }
}

public class MainWindowViewModel
{
    public MainWindowViewModel()
    {
        MyItems = new List<DisplayableItem>
        {
            new DisplayableItem { FirstProperty = "Some string" },
            new DisplayableItem { FirstProperty = 60 },
            new DisplayableItem { FirstProperty = "Also a string" },
        };
    }

    public IEnumerable<DisplayableItem> MyItems { get; }
}

public class DisplayableItem
{
    public object FirstProperty { get; set; }
    public bool HasCombobox => !(FirstProperty is string);
}


问:
Could not open modal window dynamically using Angular.js/Jquery
I have an issue. I am trying to open one pop-up window dynamically using Angular.js and Jquery but its not opening. I am explaining my code below.

```<code><input type='button' class='btn btn-xs btn-green' value='View' data-toggle="modal" data-target="#" ng-click="viewSearchDetails(133);">
<div class="modal fade" id="viewdetailssec" tabindex="-1" role="dialog" aria-labelledby="viewexamplelabel" aria-hidden="true" ng-repeat="ind in indUserDetails" ng-if="indUserDetails.length >0">
 <div class="modal-dialog fyndspacemodalsec" role="document">
<div class="modal-content">
 <div class="modal-header">
<h5 class="modal-title pull-left" id="viewexamplelabel">View Details</h5>
</div>
</div>
</div>
</div>
</code>```

My controller side code is given below.

```<code>$scope.viewSearchDetails=function(userid){
    $scope.indUserDetails=[];
    angular.forEach($scope.allUserInfo,function(obj){
      if(obj.user_id==userid){
        $scope.indUserDetails=obj;
        $("#viewdetailssec").modal();
      }
    })
  }
</code>```

Here I need to open the pop up window while if statement will execute but its not opening at all. Please help me to resolve this issue.

答:
try this one</p>

```<code> $("#viewdetailssec").modal("show");
</code>```

Body:
I have an issue. I am trying to open one pop-up window dynamically using Angular.js and Jquery but its not opening. I am explaining my code below.

<input type='button' class='btn btn-xs btn-green' value='View' data-toggle="modal" data-target="#" ng-click="viewSearchDetails(133);">

0">

View Details

My controller side code is given below.

$scope.viewSearchDetails=function(userid){
    $scope.indUserDetails=[];
    angular.forEach($scope.allUserInfo,function(obj){
      if(obj.user_id==userid){
        $scope.indUserDetails=obj;
        $("#viewdetailssec").modal();
      }
    })
  }

Here I need to open the pop up window while if statement will execute but its not opening at all. Please help me to resolve this issue.

Body:
try this one

 $("#viewdetailssec").modal("show");