问:
How to add a RGBA color to google line chart?
I am trying to embed google line chart in a client's website, which will be generated on basis of some php variables in run-time. The issue that I am facing is, the chart's parent's background  ( on which the chart is kept) that I am using is in rgba(0,0,0,.7) format, which gives a transparent feel to the background not to the content, and the background that google api gives is a white one, I tried to change the color of the background, but it accepts hex values "#000", which do not provide transparency. Can anyone suggest a way to give a rgba() as color to google chart. Sorry I cannot share the exact code, but the below can be taken as reference.

```<code>  <html>
  <head>
    <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
    <script type="text/javascript">
      google.charts.load('current', {'packages':['corechart']});
      google.charts.setOnLoadCallback(drawChart);

      function drawChart() {
        var data = google.visualization.arrayToDataTable([
          ['Year', 'Sales', 'Expenses'],
          ['2004',  1000,      400],
          ['2005',  1170,      460],
          ['2006',  660,       1120],
          ['2007',  1030,      540]
        ]);

        var options = {
          title: 'Company Performance',
          curveType: 'function',
          legend: { position: 'bottom' },
          backgroundColor:'#000';
        };

        var chart = new google.visualization.LineChart(document.getElementById('curve_chart'));

        chart.draw(data, options);
      }
    </script>
  </head>
  <body>
    <div id="curve_chart" style="width: 900px; height: 500px"></div>
  </body>
</html>
</code>```

I went through this and this but cannot find an answer to my question. Please suggest a simple way out.

答:
```<code><html>
  <head>
    <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
    <script type="text/javascript">
      google.charts.load('current', {'packages':['corechart']});
      google.charts.setOnLoadCallback(drawChart);

      function drawChart() {
        var data = google.visualization.arrayToDataTable([
          ['Year', 'Sales', 'Expenses'],
          ['2004',  1000,      400],
          ['2005',  1170,      460],
          ['2006',  660,       1120],
          ['2007',  1030,      540]
        ]);

        var options = {
          title: 'Company Performance',
          curveType: 'function',
          legend: { position: 'bottom' },
          backgroundColor:'transparent',
        };
        var chart = new google.visualization.LineChart(document.getElementById('curve_chart'));

        chart.draw(data, options);
      }
    </script>
  </head>
  <body>
    <div id="curve_chart" style="width: 900px; height: 500px;background:rgba(0,0,0,0.7)"></div>
  </body>
</html>
</code>```

Body:
I am trying to embed google line chart in a client's website, which will be generated on basis of some php variables in run-time. The issue that I am facing is, the chart's parent's background  ( on which the chart is kept) that I am using is in rgba(0,0,0,.7) format, which gives a transparent feel to the background not to the content, and the background that google api gives is a white one, I tried to change the color of the background, but it accepts hex values "#000", which do not provide transparency. Can anyone suggest a way to give a rgba() as color to google chart. Sorry I cannot share the exact code, but the below can be taken as reference.

I went through this and this but cannot find an answer to my question. Please suggest a simple way out.


来源: stackexchange

问:
R Corpus Is Messing Up My UTF-8 Encoded Text
I am simply trying to create a corpus from Russian, UTF-8 encoded text.  The problem is, the Corpus method from the tm package is not encoding the strings correctly.

Here is a reproducible example of my problem:

Load in the Russian text:

```<code>> data <- c("Renault Logan, 2005","Складское помещение, 345 м²",
          "Су-шеф","3-к квартира, 64 м², 3/5 эт.","Samsung galaxy S4 mini GT-I9190 (чёрный)")
</code>```

Create a VectorSource:

```<code>> vs <- VectorSource(data)
> vs # outputs correctly
</code>```

Then, create the corpus:

```<code>> corp <- Corpus(vs)
> inspect(corp) # output is not encoded properly
</code>```

The output that I get is:

```<code>> inspect(corp)
<<VCorpus (documents: 5, metadata (corpus/indexed): 0/0)>>

[[1]]
<<PlainTextDocument (metadata: 7)>>
Renault Logan, 2005

[[2]]
<<PlainTextDocument (metadata: 7)>>
Ñêëàäñêîå ïîìåùåíèå, 345 ì<U+00B2>

[[3]]
<<PlainTextDocument (metadata: 7)>>
Ñó-øåô

[[4]]
<<PlainTextDocument (metadata: 7)>>
3-ê êâàðòèðà, 64 ì<U+00B2>, 3/5 ýò.

[[5]]
<<PlainTextDocument (metadata: 7)>>
Samsung galaxy S4 mini GT-I9190 (÷¸ðíûé)
</code>```

Why does it output incorrectly?  There doesn't seem to be any option to set the encoding on the Corpus method.  Is there a way to set it after the fact?  I have tried this:

```<code>> title_corpus <- tm_map(title_corpus, enc2utf8)
Error in FUN(X[[1L]], ...) : argumemt is not a character vector
</code>```

But, it errors as shown.

答:
I had a problem with German UTF-8 encoding while importing the texts. For me, the next oneliner helped:

Sys.setlocale("LC_ALL", "de_DE.UTF-8")

Try to run the same with Russian?

Sys.setlocale("LC_ALL", "ru_RU.UTF-8")

Of course, that goes after library(tm) and before creating a corpus.

ContentLicense: CC BY-SA 3.0

Body:
I am simply trying to create a corpus from Russian, UTF-8 encoded text.  The problem is, the Corpus method from the tm package is not encoding the strings correctly.

Here is a reproducible example of my problem:

Load in the Russian text:

> data <- c("Renault Logan, 2005","Складское помещение, 345 м²",
          "Су-шеф","3-к квартира, 64 м², 3/5 эт.","Samsung galaxy S4 mini GT-I9190 (чёрный)")

Create a VectorSource:

> vs <- VectorSource(data)
> vs # outputs correctly

Then, create the corpus:

> corp <- Corpus(vs)
> inspect(corp) # output is not encoded properly

The output that I get is:

> inspect(corp)
<<VCorpus (documents: 5, metadata (corpus/indexed): 0/0)>>

[[1]]
<<PlainTextDocument (metadata: 7)>>
Renault Logan, 2005

[[2]]
<<PlainTextDocument (metadata: 7)>>
Ñêëàäñêîå ïîìåùåíèå, 345 ì

[[3]]
<<PlainTextDocument (metadata: 7)>>
Ñó-øåô

[[4]]
<<PlainTextDocument (metadata: 7)>>
3-ê êâàðòèðà, 64 ì, 3/5 ýò.

[[5]]
<<PlainTextDocument (metadata: 7)>>
Samsung galaxy S4 mini GT-I9190 (÷¸ðíûé)

Why does it output incorrectly?  There doesn't seem to be any option to set the encoding on the Corpus method.  Is there a way to set it after the fact?  I have tried this:

> title_corpus <- tm_map(title_corpus, enc2utf8)
Error in FUN(X[[1L]], ...) : argumemt is not a character vector

But, it errors as shown.


问:
How to pass arguments to an included file?
I'm trying to make the whole  section its own include file. One drawback is the title and description and keyword will be the same; I can't figure out how to pass arguments to the include file.

So here is the code:

index.php

```<code><?php include("header.php?header=aaaaaaaaaaaaaaaaaaaaa"); ?>

<body>
.....
..
.
</code>```

header.php

```<code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<link rel="shortcut icon" href="favicon.ico">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta name="Keywords" content=" <?php $_GET["header"]?> " >
<meta name="Description" content=" <?php $_GET["header"]?> " >
<title> <?php $_GET["header"]?> </title>
<link rel="stylesheet" type="text/css" href="reset.css" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js"></script>
</head>
</code>```

Obviously this doesn't work; how can I pass arguments to an included file?

答: defining a variable as a pseudo-argument/workaround before an include() - as recommended by many - is a bad idea. it introduces a variable in the global scope. define a function in the included file instead to catch the arguments u want to pass.

ContentLicense: CC BY-SA 2.5

Body:
I'm trying to make the whole  section its own include file. One drawback is the title and description and keyword will be the same; I can't figure out how to pass arguments to the include file.

So here is the code:

index.php

<?php include("header.php?header=aaaaaaaaaaaaaaaaaaaaa"); ?>

.....
..
.

header.php

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<link rel="shortcut icon" href="favicon.ico">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta name="Keywords" content=" <?php $_GET["header"]?> " >
<meta name="Description" content=" <?php $_GET["header"]?> " >
<title> <?php $_GET["header"]?> </title>
<link rel="stylesheet" type="text/css" href="reset.css" />

Obviously this doesn't work; how can I pass arguments to an included file?


问:
PrestaShop backend, Fatal error in ajax call
On the backend of a PrestaShop site I'm using this function:

```<code>public function hookAjax($action, $id_product, $id_lang, $title, $descript, $order, $id = NULL)
{

    /* various code*/

    $this->context->smarty->assign(
        array(
            'block_define'  => $this->getFormDesc($id_product)
        )
    );
    return $this->context->smarty->fetch($this->local_path.'views/templates/hook/admin_extra_desc.tpl');
}

public function getFormDesc($id_product) {
    $array = array();

    foreach (Language::getLanguages() as $lang) {
        /*various code*/

        foreach($result as $k=> $r) {
            $files   = array();
            $helper = new HelperImageUploader();
            $helper->setMultiple(false)->setUseAjax(true)->setName('thumbnail_'.$r['id'].'_'.$r['id_lang'])->setFiles($files)->setMaxFiles(3)->setUrl('../modules/module-name/imgAjaxCall.php?');
            $result[$k]['img-form'] = $helper->render();
            $result[$k]['img'] = $result[$k]['img'] ? _PS_BASE_URL_.__PS_BASE_URI__.'modules/module-name/upload/'.$result[$k]['img'] : '';
        }

        $array[$lang["id_lang"]] = array(
            'lang_data'     =>  $lang,
            'count'         =>  count($result),
            'data'          =>  $result
        );
    }

    return $array;

}
</code>```

HookAjax is called by:

```<code><?php
    include(dirname(__FILE__).'/../../config/config.inc.php');

    $context = Context::getContext();
    $addDesc = Module::getInstanceByName('module-name');

    echo $addDesc->hookAjax($_POST['action'],$_POST['id_prodotto'],$_POST['lang'],$_POST['title'], $_POST['text_desc'], NULL, $_POST['row']);

?>
</code>```

But I struggle with this error:

Fatal error: Call to a member function addJs() on a non-object in {my_site}/classes/helper/HelperUploader.php on line 257

答:
You need to include init.php in HookAjax after including config.inc.php so that controller is initialized in context.

```<code>include(dirname(__FILE__).'/../../init.php');
</code>```

Note that this is just bad practice, respect the MVC and use proper controllers for your AJAX calls and data validation/processing in them, not inside main module class.

Body:
On the backend of a PrestaShop site I'm using this function:

public function hookAjax($action, $id_product, $id_lang, $title, $descript, $order, $id = NULL)
{

    /* various code*/

    $this->context->smarty->assign(
        array(
            'block_define'  => $this->getFormDesc($id_product)
        )
    );
    return $this->context->smarty->fetch($this->local_path.'views/templates/hook/admin_extra_desc.tpl');
}

public function getFormDesc($id_product) {
    $array = array();

    foreach (Language::getLanguages() as $lang) {
        /*various code*/

        foreach($result as $k=> $r) {
            $files   = array();
            $helper = new HelperImageUploader();
            $helper->setMultiple(false)->setUseAjax(true)->setName('thumbnail_'.$r['id'].'_'.$r['id_lang'])->setFiles($files)->setMaxFiles(3)->setUrl('../modules/module-name/imgAjaxCall.php?');
            $result[$k]['img-form'] = $helper->render();
            $result[$k]['img'] = $result[$k]['img'] ? _PS_BASE_URL_.__PS_BASE_URI__.'modules/module-name/upload/'.$result[$k]['img'] : '';
        }

        $array[$lang["id_lang"]] = array(
            'lang_data'     =>  $lang,
            'count'         =>  count($result),
            'data'          =>  $result
        );
    }

    return $array;

}

HookAjax is called by:

<?php
    include(dirname(__FILE__).'/../../config/config.inc.php');

    $context = Context::getContext();
    $addDesc = Module::getInstanceByName('module-name');

    echo $addDesc->hookAjax($_POST['action'],$_POST['id_prodotto'],$_POST['lang'],$_POST['title'], $_POST['text_desc'], NULL, $_POST['row']);

?>

But I struggle with this error:

Fatal error: Call to a member function addJs() on a non-object in {my_site}/classes/helper/HelperUploader.php on line 257

Body:
You need to include init.php in HookAjax after including config.inc.php so that controller is initialized in context.

include(dirname(__FILE__).'/../../init.php');

Note that this is just bad practice, respect the MVC and use proper controllers for your AJAX calls and data validation/processing in them, not inside main module class.


问:
a simple one with java calassCastException
```<code>package Medium;

import java.util.ArrayList;
import java.util.Scanner;

public class Demo5 {
    public static void main(String[] args) {
        System.out.println("input end when you want to stop:");

        ArrayList<Double> arr = new ArrayList<Double>();
        while(true){
            Scanner in = new Scanner(System.in);
            //String d = in.nextLine();
            double d = in.nextDouble();
            arr.add(d);
            if (d==0) {
                break;
            }
        }
        Double[] array =(Double[]) arr.toArray();   //I hava already change the type to double
        int outter,inner,max;
         for(outter=0;outter<array.length-1;outter++){
             max = outter;
             for(inner=outter+1;inner<array.length;inner++){
                 if (array[inner]>array[max]) {
                    inner = max;
                }
             }
             double temp =array[outter];
             array[outter] =array[inner];
            array[inner]=temp;
         }
         System.out.println(array);
    }
}
</code>```

Description:Find K-th largest element in an array.
I want to input a arrayList and change it into array,then use selectSort.However,prints out ClassCastException on"Double[] array =(Double[]) arr.toArray();",what's wrong?thank you for your time.

Exception:

```<code>Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.Double;
    at Medium.Demo5.main(Demo5.java:31)
</code>```

答:
Another way to do this is:

```<code>Double[] array = Arrays.copyOf(arr.toArray(), arr.size(), Double[].class);
</code>```

Either method, you need to pass the array type Double[] and its length in some way.

Body:
package Medium;

import java.util.ArrayList;
import java.util.Scanner;

public class Demo5 {
    public static void main(String[] args) {
        System.out.println("input end when you want to stop:");

        ArrayList<Double> arr = new ArrayList<Double>();
        while(true){
            Scanner in = new Scanner(System.in);
            //String d = in.nextLine();
            double d = in.nextDouble();
            arr.add(d);
            if (d==0) {
                break;
            }
        }
        Double[] array =(Double[]) arr.toArray();   //I hava already change the type to double
        int outter,inner,max;
         for(outter=0;outter<array.length-1;outter++){
             max = outter;
             for(inner=outter+1;inner<array.length;inner++){
                 if (array[inner]>array[max]) {
                    inner = max;
                }
             }
             double temp =array[outter];
             array[outter] =array[inner];
            array[inner]=temp;
         }
         System.out.println(array);
    }
}

Description:Find K-th largest element in an array.
I want to input a arrayList and change it into array,then use selectSort.However,prints out ClassCastException on"Double[] array =(Double[]) arr.toArray();",what's wrong?thank you for your time.

Exception:

Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.Double;
    at Medium.Demo5.main(Demo5.java:31)

Body:
Another way to do this is:

Double[] array = Arrays.copyOf(arr.toArray(), arr.size(), Double[].class);

Either method, you need to pass the array type Double[] and its length in some way.


问:
Getting last match from multiple matches
I am trying to match and get the last occurrence of a pattern in my file using notepad++.

My text:

```<code>X12

Source =asdjkasjd
 file="x/y1.dun"
       "x/y2.dun"
       "x/y3.dun"

asds12

    X22
       p/q/xy.dun
asda=23

source =asdf

    X44
1000
1001
      file="abc.dun"
</code>```

What I expect using find-and-replace is this:

```<code>X12     x/y3.dun
X22     p/q/xy.dun
X44     abc.dun
</code>```

What I have tried so far:

```<code>(X\d{2}).*?([^"\s]+dun)((?!X\d{2}).)*
</code>```

replace with:

```<code>$1\t\t$2\n
</code>```

But it returns me this:

```<code>X12     x/y1.dun    //Which is the first match
X22     p/q/xy.dun
X44     abc.dun
</code>```

How do I get the last match inside a match? I am looking for a general way for getting the last match.

答:
You may  match and capture what you need to keep and just match what you do not need, and only replace with text when a capture group  is matched:

Find What: (?s)\b(X\d{2})(?:(?!X\d{2}).)*["\s]([^"\s]+\.dun)|(?:(?!X\d{2}).)*

Replace With: (?{1}$1\t\t$2\n)

See the regex pattern demo.

Details:

(?s) - a  DOTALL modifier (you may remove it and check the . matches newline option)

\b - a leading word boundary to match X at the start of a word

(X\d{2}) - Group 1 capturing a X (note that Match Case must be turned on if you do not want to match a lowercase x) and any two digits

(?:(?!X\d{2}).)* - a tempered greedy token matching any char, zero or more repetitions, that is not followed with X and any two digits. Since it is greedy, it will make it up to the location where the next character starts the forbidden sequence and will backtrack to the last "dun" required by the subsequent subpattern.

["\s] - a whitespace or a double quote

([^"\s]+\.dun) - Group 2 capturing one or more chars other than whitespace and double quote, then a dot and a dun substring

| - or

(?:(?!X\d{2}).)* - the same tempered greedy token as above.

Replacement details:

(?{1} - if Group 1 matched....

$1\t\t$2\n - replace with the first group value, two tabs, the second group value and a newline

) - else replace with an empty  string.

Body:
I am trying to match and get the last occurrence of a pattern in my file using notepad++.

My text:

X12

Source =asdjkasjd
 file="x/y1.dun"
       "x/y2.dun"
       "x/y3.dun"

asds12

    X22
       p/q/xy.dun
asda=23

source =asdf

    X44
1000
1001
      file="abc.dun"

What I expect using find-and-replace is this:

X12     x/y3.dun
X22     p/q/xy.dun
X44     abc.dun

What I have tried so far:

(X\d{2}).*?([^"\s]+dun)((?!X\d{2}).)*

replace with:

$1\t\t$2\n

But it returns me this:

X12     x/y1.dun    //Which is the first match
X22     p/q/xy.dun
X44     abc.dun

How do I get the last match inside a match? I am looking for a general way for getting the last match.


问:
Implement a method in java mysql database connection class to use preparedStatements
I have created a database connection class in my project to create and share database instance across the all class in the project.

Database connection obtained using this code

```<code>void createConnection(){
    try{
        connection = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/testdb", "root", "");
        System.out.println("Connected");
    }catch(Exception e) {
        System.out.println("Connection Failed");
        System.out.println(e);
    }

}
</code>```

Then I created a method to insert values to database using prepared statements as follows

```<code>public boolean execAction(String query){
    try {
        pstatement = (PreparedStatement) connection.prepareStatement(query);
        pstatement.execute(query);
        System.out.println("Values inserted");
        return true;
    } catch (SQLException ex) {
        Logger.getLogger(databaseHandler.class.getName()).log(Level.SEVERE, null, ex);
        System.out.println("Values insertion failed");
        return false;
    } finally {

    }
</code>```

I want to find a way to pass preparedstatement variable values to this method.

答:
If you are looking for execAction(String query) to handle for any database table, then you need to write quite complex logic to check which datatype (i.e., blob, int, string, etc..) and it is not a good idea to reinvent something again. It can be nicely and easily handled if you use any of the ORM (Object to Relational Mapping) tools like Hibernate, etc.

The ORM concept is that you need to map each Model (Entity) class to a table in the database and the framework will handle all boilerplate code (i.e., adding preparedstatement.setString(), setInt(), etc..).

Is there a way to get connection object in another class if I share a
  database class instance through the overall project?

It is not a good practice to share a single connection object across the whole application, rather return different connection objects as shown below, Also, ensure that you need to close the connection by calling close().

One more point is that you might need to setup connection-pool otherwise, you will end up with errors.

```<code>public class DBUtil {

  public static Connection createConnection(){
    try{
       Connection connection = (Connection) DriverManager.
               getConnection("jdbc:mysql://localhost:3306/testdb",
                    "root", "");
        System.out.println("Connected");
        return connection;
    }catch(Exception e) {
        System.out.println("Connection Failed");
        System.out.println(e);
    }
}

  public static void closeConnection(Connection conn) {
        conn.close();
  }
}
</code>```

Body:
I have created a database connection class in my project to create and share database instance across the all class in the project.

Database connection obtained using this code

void createConnection(){
    try{
        connection = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/testdb", "root", "");
        System.out.println("Connected");
    }catch(Exception e) {
        System.out.println("Connection Failed");
        System.out.println(e);
    }

}

Then I created a method to insert values to database using prepared statements as follows

public boolean execAction(String query){
    try {
        pstatement = (PreparedStatement) connection.prepareStatement(query);
        pstatement.execute(query);
        System.out.println("Values inserted");
        return true;
    } catch (SQLException ex) {
        Logger.getLogger(databaseHandler.class.getName()).log(Level.SEVERE, null, ex);
        System.out.println("Values insertion failed");
        return false;
    } finally {

    }

I want to find a way to pass preparedstatement variable values to this method.

Body:
If you are looking for execAction(String query) to handle for any database table, then you need to write quite complex logic to check which datatype (i.e., blob, int, string, etc..) and it is not a good idea to reinvent something again. It can be nicely and easily handled if you use any of the ORM (Object to Relational Mapping) tools like Hibernate, etc.

The ORM concept is that you need to map each Model (Entity) class to a table in the database and the framework will handle all boilerplate code (i.e., adding preparedstatement.setString(), setInt(), etc..).

Is there a way to get connection object in another class if I share a
  database class instance through the overall project?

It is not a good practice to share a single connection object across the whole application, rather return different connection objects as shown below, Also, ensure that you need to close the connection by calling close().

One more point is that you might need to setup connection-pool otherwise, you will end up with errors.

public class DBUtil {

  public static Connection createConnection(){
    try{
       Connection connection = (Connection) DriverManager.
               getConnection("jdbc:mysql://localhost:3306/testdb",
                    "root", "");
        System.out.println("Connected");
        return connection;
    }catch(Exception e) {
        System.out.println("Connection Failed");
        System.out.println(e);
    }
}

  public static void closeConnection(Connection conn) {
        conn.close();
  }
}


问:
Can I use html5 in my mobile website?
I must create a web site optimised for mobile devices, can I use html5 and css3?
What are the main limitations?
Which devices are compatible? (IOS, Android...)

Regards

答: Yes you can! and about compatibity... it depends on the browser... the new versions of safari that run on the iOs 4++ support html 5...</p>

Title: Can I use html5 in my mobile website?


问:
Launcher activity not starting
My launcher activity not starting can any body tell me whats the problem.

I also have a service in it.
Any help is appreciated Please help i am stuck and don't know what to do.

Here is  the code of Manifest

```<code> <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="pelicans.abc.abc">
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.CALL_PHONE" />
<uses-permission android:name="android.permission.SEND_SMS" />
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>

<uses-feature android:name="android.hardware.camera" />

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">

    <activity android:name=".Permiss"
        android:screenOrientation="portrait">
        <intent-filter>
            <action android:name="android.intent.action.MAIN"/>
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <activity android:name=".MainActivity"
        android:screenOrientation="portrait">
        <meta-data
            android:name="android.app.searchable"
            android:resource="@xml/searchable">
        </meta-data>
    </activity>

    <service
        android:name=".Service.FeatureService"
        android:enabled="true">
    </service>

    <receiver android:name=".Receiver.RestartService"
        android:enabled="true"
        android:exported="true"
        android:label="RestartServiceWhenStopped">

        <intent-filter>
            <action android:name="Restart_Service"></action>
        </intent-filter>
    </receiver>
</application>
</manifest>
</code>```

Launcher activity is not called in any version of android.

答:
really no log?..try more times,try to Log at application onCreate() and activity onCreate()

delete sth,like your MainActivity or RestartService,and try again

Title: Launcher activity not starting

Body:
My launcher activity not starting can any body tell me whats the problem.

I also have a service in it.
Any help is appreciated Please help i am stuck and don't know what to do.

Here is  the code of Manifest

 <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="pelicans.abc.abc">
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.CALL_PHONE" />
<uses-permission android:name="android.permission.SEND_SMS" />
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>

<uses-feature android:name="android.hardware.camera" />

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">

    <activity android:name=".Permiss"
        android:screenOrientation="portrait">
        <intent-filter>
            <action android:name="android.intent.action.MAIN"/>
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <activity android:name=".MainActivity"
        android:screenOrientation="portrait">
        <meta-data
            android:name="android.app.searchable"
            android:resource="@xml/searchable">
        </meta-data>
    </activity>

    <service
        android:name=".Service.FeatureService"
        android:enabled="true">
    </service>

    <receiver android:name=".Receiver.RestartService"
        android:enabled="true"
        android:exported="true"
        android:label="RestartServiceWhenStopped">

        <intent-filter>
            <action android:name="Restart_Service"></action>
        </intent-filter>
    </receiver>
</application>
</manifest>

Launcher activity is not called in any version of android.


问:
Hiding certain methods from other packages
I have two packages in my project: odp.proj and odp.proj.test. There are certain methods that I want to be visible only to the classes in these two packages. How can I do this?

If there is no concept of a subpackage in Java, is there any way around this? I have certain methods that I want to be available only to testers and other members of that package. Should I just throw everything into the same package? Use extensive reflection?

答:
With the PackageVisibleHelper class, and keep it private before PackageVisibleHelperFactory  frozen, we can invoke  the launchA(by PackageVisibleHelper )  method in anywhere:)</p>

```<code>package odp.proj;
public class A
 {
    void launchA() { }
}

public class PackageVisibleHelper {

    private final PackageVisibleHelperFactory factory;

    public PackageVisibleHelper(PackageVisibleHelperFactory factory) {
        super();
        this.factory = factory;
    }

    public void launchA(A a) {
        if (factory == PackageVisibleHelperFactory.INSTNACNE && !factory.isSampleHelper(this)) {
            throw new IllegalAccessError("wrong PackageVisibleHelper ");
        }
        a.launchA();
    }
}

public class PackageVisibleHelperFactory {

    public static final PackageVisibleHelperFactory INSTNACNE = new PackageVisibleHelperFactory();

    private static final PackageVisibleHelper HELPER = new PackageVisibleHelper(INSTNACNE);

    private PackageVisibleHelperFactory() {
        super();
    }

    private boolean frozened;

    public PackageVisibleHelper getHelperBeforeFrozen() {
        if (frozened) {
            throw new IllegalAccessError("please invoke before frozen!");
        }
        return HELPER;
    }

    public void frozen() {
        frozened = true;
    }

    public boolean isSampleHelper(PackageVisibleHelper helper) {
        return HELPER.equals(helper);
    }
}
package odp.proj.test;

import odp.proj.A;
import odp.proj.PackageVisibleHelper;
import odp.proj.PackageVisibleHelperFactory;

public class Test {

    public static void main(String[] args) {

        final PackageVisibleHelper helper = PackageVisibleHelperFactory.INSTNACNE.getHelperBeforeFrozen();
        PackageVisibleHelperFactory.INSTNACNE.frozen();

        A a = new A();
        helper.launchA(a);

        // illegal access
        new PackageVisibleHelper(PackageVisibleHelperFactory.INSTNACNE).launchA(a);
    }
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
With the PackageVisibleHelper class, and keep it private before PackageVisibleHelperFactory  frozen, we can invoke  the launchA(by PackageVisibleHelper )  method in anywhere:)

package odp.proj;
public class A
 {
    void launchA() { }
}

public class PackageVisibleHelper {

    private final PackageVisibleHelperFactory factory;

    public PackageVisibleHelper(PackageVisibleHelperFactory factory) {
        super();
        this.factory = factory;
    }

    public void launchA(A a) {
        if (factory == PackageVisibleHelperFactory.INSTNACNE && !factory.isSampleHelper(this)) {
            throw new IllegalAccessError("wrong PackageVisibleHelper ");
        }
        a.launchA();
    }
}

public class PackageVisibleHelperFactory {

    public static final PackageVisibleHelperFactory INSTNACNE = new PackageVisibleHelperFactory();

    private static final PackageVisibleHelper HELPER = new PackageVisibleHelper(INSTNACNE);

    private PackageVisibleHelperFactory() {
        super();
    }

    private boolean frozened;

    public PackageVisibleHelper getHelperBeforeFrozen() {
        if (frozened) {
            throw new IllegalAccessError("please invoke before frozen!");
        }
        return HELPER;
    }

    public void frozen() {
        frozened = true;
    }

    public boolean isSampleHelper(PackageVisibleHelper helper) {
        return HELPER.equals(helper);
    }
}
package odp.proj.test;

import odp.proj.A;
import odp.proj.PackageVisibleHelper;
import odp.proj.PackageVisibleHelperFactory;

public class Test {

    public static void main(String[] args) {

        final PackageVisibleHelper helper = PackageVisibleHelperFactory.INSTNACNE.getHelperBeforeFrozen();
        PackageVisibleHelperFactory.INSTNACNE.frozen();

        A a = new A();
        helper.launchA(a);

        // illegal access
        new PackageVisibleHelper(PackageVisibleHelperFactory.INSTNACNE).launchA(a);
    }
}


问:
delete_all does not work while each do delete does
Intended functionality - delete all linked asset_items when an asset_line_item is deleted. (without using destroy, destroy_all). I am using postgres

With the following model:

```<code>class AssetLineItem < PurchaseLineItem

  has_many :asset_items
  ...

  after_destroy :destroy_cleanup

  private

  def destroy_cleanup
    asset_items.delete_all
  end
end
</code>```

This results in the asset_items remaining, however all of their asset_line_item columns are set to null.

```<code>  def destroy_cleanup
    asset_items.each do |asset_item|
      asset_item.delete
    end
  end
</code>```

replacing delete_all with the loop above however has the intended result of delete all associated asset_items.

Although I have working code, I'm curious what could cause delete_all to act in this way?

答: use has_many :asset_items dependent: :destroy

Body:
Intended functionality - delete all linked asset_items when an asset_line_item is deleted. (without using destroy, destroy_all). I am using postgres

With the following model:

class AssetLineItem < PurchaseLineItem

  has_many :asset_items
  ...

  after_destroy :destroy_cleanup

  private

  def destroy_cleanup
    asset_items.delete_all
  end
end

This results in the asset_items remaining, however all of their asset_line_item columns are set to null.

  def destroy_cleanup
    asset_items.each do |asset_item|
      asset_item.delete
    end
  end

replacing delete_all with the loop above however has the intended result of delete all associated asset_items.

Although I have working code, I'm curious what could cause delete_all to act in this way?


问:
How to use substring when using powershell select-object
I'm wondering if there is a way to use do a substring when using powershell's select-object cmdlet

Here is an example of what i'm trying to do

```<code>$sapFile = "C:\MyFile*.XML"

# Get the newest xml file
$newestFile = Get-ChildItem -Path $sapFile | Sort CreationTime | Select -Last 1

# get the contents of the xml file
[XML]$sapContent = Get-Content -Path $newestFile.FullName

$sapContent.DATA.CP | Select -Property CP_NO,MEN.Substring(0,4)
</code>```

This however doesn't work.

Thanks

答:
other method :</p>

```<code>$sapContent.DATA.CP | foreach {
       [pscustomobject]@{
        CP_NO=$_.CP_NO
        PartOfMen=MEN.Substring(0,4)
       }
      }
</code>```

Body:
I'm wondering if there is a way to use do a substring when using powershell's select-object cmdlet

Here is an example of what i'm trying to do

$sapFile = "C:\MyFile*.XML"

# Get the newest xml file
$newestFile = Get-ChildItem -Path $sapFile | Sort CreationTime | Select -Last 1

# get the contents of the xml file
[XML]$sapContent = Get-Content -Path $newestFile.FullName

$sapContent.DATA.CP | Select -Property CP_NO,MEN.Substring(0,4)

This however doesn't work.

Thanks

Body:
other method :

$sapContent.DATA.CP | foreach {
       [pscustomobject]@{
        CP_NO=$_.CP_NO
        PartOfMen=MEN.Substring(0,4)
       }
      }


问:
Android Studio stacktrace is unclickable
Using : Android Studio (IntellIJ IDEA) running an Emulator

I want to be able to click on the stack-trace/error of the DDMS (Android Monitor) as shown here, to move to the file/line that caused this error.

Unclickable stack trace

Because of my last two unrelated questions I got banned for some years... So I hope that I respect every rules this time. Thank you.

Edit : apparently the Android Studio's Android Monitor is clickable, but not Android Studio's DDMS. Weird... Maybe because DDMS was made for Eclipse, not intellij idea.

Android's DDMS is clickable

答:
You can do this using the 'Analyze Stacktrace` function.  This can be found on the menu:

Analyze -> Analyze Stacktrace

Just paste your stacktrace from DDMS into the dialog, click OK and it will give you one with clickable links (if it can find them).


问:
DevExpress modify label in templateitem
I am working with DevExpress platform.
I have a axGridview that contains an ItemTemplate with a Label, i need just modify in every row with value.
With asp.net and GridView i used to manage FindControl in RowDataboundEvent, but here i really need help. The FindCellTemplate function always returns NULL.
here my code:

```<code>        <dx:ASPxGridView ID="gvRecapiti" ClientIDMode="Static" ClientInstanceName="gvRecapiti" Width="100%"  runat="server" AutoGenerateColumns="False"
            OnHtmlRowCreated="gvRecapiti_HtmlRowCreated"  >
            <Columns>
                        <dx:GridViewDataColumn  Caption="RecapitoTipo" >
                        <SettingsHeaderFilter>
                        <DateRangePickerSettings EditFormatString=""></DateRangePickerSettings>
                        </SettingsHeaderFilter>
                        </dx:GridViewDataColumn>

                    <dx:GridViewDataTextColumn FieldName="DescRecapito" >
                        <DataItemTemplate>
                                <dx:ASPxLabel  ID="lblRecapito" ClientIDMode="Static" runat="server" ClientInstanceName="lblRecapito" Text='<%# Eval("DescRecapito") %>' ></dx:ASPxLabel>
                            </DataItemTemplate>
                    </dx:GridViewDataTextColumn>
            </Columns>

            </dx:ASPxGridView>

using DevExpress.Web;

namespace ProvaGridItem
{
    public partial class Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Page.IsPostBack != false)
            {
                BindGrid();
            }
        }
        private void BindGrid()
        {
            List<Recapito> R = new List<Recapito>();

            for (int i=0;i<5;i++)
            {
                Recapito Recapito = new Recapito();
                Recapito.DescRecapito = "Recapito: " + i;
                Recapito.RecapitoTipo="RecapitoTipo: "+i;
                R.Add(Recapito);
            }

            gvRecapiti.DataSource = R;
            gvRecapiti.DataBind();
        }

        protected void gvRecapiti_HtmlRowCreated(object sender, DevExpress.Web.ASPxGridViewTableRowEventArgs e)
        {
            if (e.RowType != DevExpress.Web.GridViewRowType.Data) return;
            ASPxLabel lblRecapitoTipo = (ASPxLabel)gvRecapiti.FindRowCellTemplateControl(e.VisibleIndex, null, "lblRecapitoTipo");
            lblRecapitoTipo.Text = "Label Updated by code!!";
        }

      internal  class Recapito
        {
            public string RecapitoTipo { get; set; }
            public string DescRecapito { get; set; }
        }
    }
}
</code>```

答:
```<code>  (ASPxLabel)gvRecapiti.FindRowCellTemplateControl(e.VisibleIndex, null, "lblRecapitoTipo");
</code>```

This should have column to find control. so that first get column in a variable and then find template control of that column.Please go through with below code.

```<code> GridViewDataTextColumn col = gvRecapiti.Columns["lblRecapito"] as GridViewDataTextColumn;
   ASPxLabel lblRecapitoTipo =  gvRecapiti.FindRowCellTemplateControl(e.VisibleIndex, col , "lblRecapitoTipo") as ASPxLabel;
</code>```

and then you can change lblRecapitoTipo label properties as you want.In your case it is

```<code>lblRecapitoTipo.Text = "Label Updated by code!!";
</code>```

Title: DevExpress modify label in templateitem

Body:
I am working with DevExpress platform.
I have a axGridview that contains an ItemTemplate with a Label, i need just modify in every row with value.
With asp.net and GridView i used to manage FindControl in RowDataboundEvent, but here i really need help. The FindCellTemplate function always returns NULL.
here my code:

        <dx:ASPxGridView ID="gvRecapiti" ClientIDMode="Static" ClientInstanceName="gvRecapiti" Width="100%"  runat="server" AutoGenerateColumns="False"
            OnHtmlRowCreated="gvRecapiti_HtmlRowCreated"  >
            <Columns>
                        <dx:GridViewDataColumn  Caption="RecapitoTipo" >
                        <SettingsHeaderFilter>
                        <DateRangePickerSettings EditFormatString=""></DateRangePickerSettings>
                        </SettingsHeaderFilter>
                        </dx:GridViewDataColumn>

                    <dx:GridViewDataTextColumn FieldName="DescRecapito" >
                        <DataItemTemplate>
                                <dx:ASPxLabel  ID="lblRecapito" ClientIDMode="Static" runat="server" ClientInstanceName="lblRecapito" Text='<%# Eval("DescRecapito") %>' ></dx:ASPxLabel>
                            </DataItemTemplate>
                    </dx:GridViewDataTextColumn>
            </Columns>

            </dx:ASPxGridView>

using DevExpress.Web;

namespace ProvaGridItem
{
    public partial class Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Page.IsPostBack != false)
            {
                BindGrid();
            }
        }
        private void BindGrid()
        {
            List<Recapito> R = new List<Recapito>();

            for (int i=0;i<5;i++)
            {
                Recapito Recapito = new Recapito();
                Recapito.DescRecapito = "Recapito: " + i;
                Recapito.RecapitoTipo="RecapitoTipo: "+i;
                R.Add(Recapito);
            }

            gvRecapiti.DataSource = R;
            gvRecapiti.DataBind();
        }

        protected void gvRecapiti_HtmlRowCreated(object sender, DevExpress.Web.ASPxGridViewTableRowEventArgs e)
        {
            if (e.RowType != DevExpress.Web.GridViewRowType.Data) return;
            ASPxLabel lblRecapitoTipo = (ASPxLabel)gvRecapiti.FindRowCellTemplateControl(e.VisibleIndex, null, "lblRecapitoTipo");
            lblRecapitoTipo.Text = "Label Updated by code!!";
        }

      internal  class Recapito
        {
            public string RecapitoTipo { get; set; }
            public string DescRecapito { get; set; }
        }
    }
}

Body:
  (ASPxLabel)gvRecapiti.FindRowCellTemplateControl(e.VisibleIndex, null, "lblRecapitoTipo");

This should have column to find control. so that first get column in a variable and then find template control of that column.Please go through with below code.

 GridViewDataTextColumn col = gvRecapiti.Columns["lblRecapito"] as GridViewDataTextColumn;
   ASPxLabel lblRecapitoTipo =  gvRecapiti.FindRowCellTemplateControl(e.VisibleIndex, col , "lblRecapitoTipo") as ASPxLabel;

and then you can change lblRecapitoTipo label properties as you want.In your case it is

lblRecapitoTipo.Text = "Label Updated by code!!";


问:
Pattern Replacing in string with escaped characters failing with replaceAll
I have a use case where I want to replace some values in html string, so I need to do replaceAll for that, but that is not working, although replace is working fine, here is my code:

```<code>    String str  = "<style type=\"text/css\">#include(\"Invoice_Service_Tax.css\")</style>";
    String pattern = "#include(\"Invoice_Service_Tax.css\")";
    System.out.println(str.replace(pattern, "some-value"));
    System.out.println(str.replaceAll(pattern, "some-value"));
</code>```

output is :

```<code><style type="text/css">some-value</style>
<style type="text/css">#include("Invoice_Service_Tax.css")</style>
</code>```

For my use case I need to do replaceAll only, I tried with below patterns also but no help:

```<code>"#include(\\\"Invoice_Service_Tax.css\\\")"
"#include(Invoice_Service_Tax.css)"
</code>```

答:
Replace doesn't look for special chars, just a literal replace while replaceAll uses regexes so there are some special characters.

The problem with the regex is that ( is a special character for grouping so you need to escape it.

#include\\(\"Invoice_Service_Tax.css\"\\) should work with your replaceAll

Body:
I have a use case where I want to replace some values in html string, so I need to do replaceAll for that, but that is not working, although replace is working fine, here is my code:

    String str  = "";
    String pattern = "#include(\"Invoice_Service_Tax.css\")";
    System.out.println(str.replace(pattern, "some-value"));
    System.out.println(str.replaceAll(pattern, "some-value"));

output is :

For my use case I need to do replaceAll only, I tried with below patterns also but no help:

"#include(\\\"Invoice_Service_Tax.css\\\")"
"#include(Invoice_Service_Tax.css)"


问:
After submit a form, stay same page, show a word in the page

After clicking "submit", stay on the page.

Input data, like "computer number" and "profit", stay inside those blank square.

A word "Submitted", appear in the center of this page.

The following is my code, Please help, thank you!

<title></title>

  <form name="form"
onsubmit="return validateForm()">

    Computer Number:

    <input type="text" name="Computer" required>

How much is your profit?

<input id="id1" name = "id1" required>
  <button  type = "button" onclick="myFunction()">My Answer</button>
    <button type="button" id="btn1" onclick="Solution()" style="display:none;">Solution</button>

  <input type="submit" value="Submit">

</form>

```

答:
Firstly, you were having document.forms["my form"] which was invalid since your form name was form so I changed it to document.forms["form"].

And, on submit, I added return false at the bottom of the function to stay on the page. Also, before that, added "Submitted" text in the center of the page as shown below.

Here's working code snippet!

Hope that helps!

var errosCount = 0;

function myFunction() {
  var x, text;
  x = document.getElementById("id1").value;

  if (isNaN(x) || x != 100) {
    text = "Incorrect";
    document.getElementById("Q1").style.color = "red";
    errosCount++;
  } else {
    text = "Correct";
    document.getElementById("Q1").style.color = "green";
  }
  document.getElementById("Q1").innerHTML = text;
  if (errosCount === 3) {
    errosCount = 0;
    document.getElementById('btn1').style.display = 'block';
    document.getElementById("Q1").innerHTML = '';
  } else {
    document.getElementById('btn1').style.display = 'none';
  }
}

function Solution() {
  text = "(P - w) * qo - I = (53 - 43) * 30 - 200 = 100";
  document.getElementById("Q1").style.color = "red";
  document.getElementById("Q1").innerHTML = text;
}

function validateForm() {
  var q = document.forms["form"]["Computer"].value;
  if (q == "") {
    alert("Computer Number is Missing!");
    return false;
  }
  var w = document.forms["form"]["id1"].value;
  if (w != "100") {
    alert("Question 1 is Incorrect!");
    return false;
  }
  document.getElementById("submitted").innerHTML = "Submitted"
  return false;
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#submitted {
  text-align: center
}</code>```

<form name="form" onsubmit="return validateForm()">

  Computer Number:

  <input type="text" name="Computer">

How much is your profit?

    <input id="id1" name="id1" required>
    <button type="button" onclick="myFunction()">My Answer</button>
    <button type="button" id="btn1" onclick="Solution()" style="display:none;">Solution</button>

  <input type="submit" value="Submit">

</form>

```

Body:
Firstly, you were having document.forms["my form"] which was invalid since your form name was form so I changed it to document.forms["form"].

And, on submit, I added return false at the bottom of the function to stay on the page. Also, before that, added "Submitted" text in the center of the page as shown below.

Here's working code snippet!

Hope that helps!

var errosCount = 0;

function myFunction() {
  var x, text;
  x = document.getElementById("id1").value;

  if (isNaN(x) || x != 100) {
    text = "Incorrect";
    document.getElementById("Q1").style.color = "red";
    errosCount++;
  } else {
    text = "Correct";
    document.getElementById("Q1").style.color = "green";
  }
  document.getElementById("Q1").innerHTML = text;
  if (errosCount === 3) {
    errosCount = 0;
    document.getElementById('btn1').style.display = 'block';
    document.getElementById("Q1").innerHTML = '';
  } else {
    document.getElementById('btn1').style.display = 'none';
  }
}

function Solution() {
  text = "(P - w) * q<sub>o</sub> - I = (53 - 43) * 30 - 200 = 100";
  document.getElementById("Q1").style.color = "red";
  document.getElementById("Q1").innerHTML = text;
}

function validateForm() {
  var q = document.forms["form"]["Computer"].value;
  if (q == "") {
    alert("Computer Number is Missing!");
    return false;
  }
  var w = document.forms["form"]["id1"].value;
  if (w != "100") {
    alert("Question 1 is Incorrect!");
    return false;
  }
  document.getElementById("submitted").innerHTML = "Submitted"
  return false;
}

#submitted {
  text-align: center
}

<form name="form" onsubmit="return validateForm()">

  Computer Number:<br>
  <input type="text" name="Computer"><br>

  <p>How much is your profit?

    <input id="id1" name="id1" required>
    <button type="button" onclick="myFunction()">My Answer</button>
    <button type="button" id="btn1" onclick="Solution()" style="display:none;">Solution</button>
  </p>

  <p id="Q1"></p>

  <input type="submit" value="Submit">

</form>
<br/>
<div id="submitted">

</div>


问:
Is it safe to enable ”Access-Control-Allow-Origin: *“ (wildcard) for a public and readonly webservice?
Enabling CORS has several security issues:

CSRF

exposure of protected data

But are there any issues for a public and readonly webservice to enable global CORS?

```<code>Access-Control-Allow-Origin: *
</code>```

My assumptions:

CSRF is not relevant, because webservice is readonly.

stealing of protected data is not relevant, because webservice is public.

答:
Here’s something relevant from the Fetch spec (which defines CORS):

Basic safe CORS protocol setup

For resources where data is protected through IP authentication or a firewall (unfortunately relatively common still), using the CORS protocol is unsafe. (This is the reason why the CORS protocol had to be invented.)

However, otherwise using the following header is safe:

```<code>Access-Control-Allow-Origin: *
</code>```

Even if a resource exposes additional information based on cookie or HTTP authentication, using the above header will not reveal it. It will share the resource with APIs such as XMLHttpRequest, much like it is already shared with curl and wget.

Thus in other words, if a resource cannot be accessed from a random device connected to the web using curl and wget the aforementioned header is not to be included. If it can be accessed however, it is perfectly fine to do so.

And the author of the Fetch/CORS spec goes into a bit more detail in a related blog posting:

It is completely safe to augment any resource with Access-Control-Allow-Origin: * as long as the resource is not part of an intranet (behind a firewall). In other words, a URL you can fetch from a server on the internet using wget or curl. For your basic web site this encompasses all resources on the site. The Access-Control-Allow-Origin header (part of CORS) tells the browser the resource can be shared.

Even if the resource includes confidential information based on cookies or HTTP authentication data in the request, including the header and sharing the resource is still safe, since the browser will make the request without any cookies or HTTP authentication data. And if the browser did make the request with cookies or HTTP authentication data, it would never share the resource because that would require an additional header, Access-Control-Allow-Credentials, and a different value for the aforementioned header.

So go ahead and safely share your public data with other applications!

Body:
Enabling CORS has several security issues:

CSRF

exposure of protected data

But are there any issues for a public and readonly webservice to enable global CORS?

Access-Control-Allow-Origin: *

My assumptions:

CSRF is not relevant, because webservice is readonly.

stealing of protected data is not relevant, because webservice is public.

Body:
Here’s something relevant from the Fetch spec (which defines CORS):

Basic safe CORS protocol setup

For resources where data is protected through IP authentication or a firewall (unfortunately relatively common still), using the CORS protocol is unsafe. (This is the reason why the CORS protocol had to be invented.)

However, otherwise using the following header is safe:

Access-Control-Allow-Origin: *

Even if a resource exposes additional information based on cookie or HTTP authentication, using the above header will not reveal it. It will share the resource with APIs such as XMLHttpRequest, much like it is already shared with curl and wget.

Thus in other words, if a resource cannot be accessed from a random device connected to the web using curl and wget the aforementioned header is not to be included. If it can be accessed however, it is perfectly fine to do so.

And the author of the Fetch/CORS spec goes into a bit more detail in a related blog posting:

It is completely safe to augment any resource with Access-Control-Allow-Origin: * as long as the resource is not part of an intranet (behind a firewall). In other words, a URL you can fetch from a server on the internet using wget or curl. For your basic web site this encompasses all resources on the site. The Access-Control-Allow-Origin header (part of CORS) tells the browser the resource can be shared.

Even if the resource includes confidential information based on cookies or HTTP authentication data in the request, including the header and sharing the resource is still safe, since the browser will make the request without any cookies or HTTP authentication data. And if the browser did make the request with cookies or HTTP authentication data, it would never share the resource because that would require an additional header, Access-Control-Allow-Credentials, and a different value for the aforementioned header.

So go ahead and safely share your public data with other applications!


问:
Images are not shown in React although the path is right
I have created a little test in react with dynamic content. Within a sidebar there is something like bootstrap collapses, containing lists with icons and names. The problem is that some images within "Natürlich" are not shown. These images are stored together with all the working ones and if I follow the link from the inspector the right images is at the right place.

I have some code going on to take the name of the list item and first remove the umlauts and then put it in between the link of the image as you can see here. This seems to work for all other images except the 3 missing within "Natürlich"

```<code>correctNames: function(warning) {
  if (warning) {
    var warningCorrected = warning.toLowerCase().replace(/\u00f6/g, 'oe').replace(/\u00e4/g, 'ae').replace(/\u00fc/g, 'ue').replace(/\u00df/g, 'ss');
    return warningCorrected
  }
},

render: function() {
    var warnings = this.props.warningName;
    var isActive = this.state.warningState ? 'warning-active' : 'warning-inactive';
    return (
    <li className={'transition ' + isActive} onClick={this.activateWarning}>
    {this.correctNames()}
    <img src={'img/warning/' + this.correctNames(warnings) + '-active.png'} alt="" />
    <p>{warnings + " " + this.correctNames(warnings)}</p>
    </li>
    );
}
</code>```

You can find the page here

UPDATE!
It seems to be a problem with UTF-8 or something. While in my inspector the path is shown right, the error message is
kon%E2%80%8Bser%E2%80%8Bvie%E2%80%8Brungs%E2%80%8Bstoffe-active.png

How can I get rid of these errors?

答:
If your are using webpack you may need to use require  in your image source

```<code>render: function() {
    var warnings = this.props.warningName;
    var isActive = this.state.warningState ? 'warning-active' : 'warning-inactive';
    return (
    <li className={'transition ' + isActive} onClick={this.activateWarning}>
    {this.correctNames()}
    <img src={require(`'./img/warning/${this.correctNames(warnings)}-active.png'`)} alt="" />
    <p>{warnings + " " + this.correctNames(warnings)}</p>
    </li>
    );
}
</code>```

Body:
I have created a little test in react with dynamic content. Within a sidebar there is something like bootstrap collapses, containing lists with icons and names. The problem is that some images within "Natürlich" are not shown. These images are stored together with all the working ones and if I follow the link from the inspector the right images is at the right place.

I have some code going on to take the name of the list item and first remove the umlauts and then put it in between the link of the image as you can see here. This seems to work for all other images except the 3 missing within "Natürlich"

correctNames: function(warning) {
  if (warning) {
    var warningCorrected = warning.toLowerCase().replace(/\u00f6/g, 'oe').replace(/\u00e4/g, 'ae').replace(/\u00fc/g, 'ue').replace(/\u00df/g, 'ss');
    return warningCorrected
  }
},

render: function() {
    var warnings = this.props.warningName;
    var isActive = this.state.warningState ? 'warning-active' : 'warning-inactive';
    return (

    {this.correctNames()}

{warnings + " " + this.correctNames(warnings)}

    );
}

You can find the page here

UPDATE!
It seems to be a problem with UTF-8 or something. While in my inspector the path is shown right, the error message is
kon%E2%80%8Bser%E2%80%8Bvie%E2%80%8Brungs%E2%80%8Bstoffe-active.png

How can I get rid of these errors?

Body:
If your are using webpack you may need to use require  in your image source

render: function() {
    var warnings = this.props.warningName;
    var isActive = this.state.warningState ? 'warning-active' : 'warning-inactive';
    return (
    <li className={'transition ' + isActive} onClick={this.activateWarning}>
    {this.correctNames()}
    <img src={require(`'./img/warning/${this.correctNames(warnings)}-active.png'`)} alt="" />
    <p>{warnings + " " + this.correctNames(warnings)}</p>
    </li>
    );
}


答:
Back in April, sources announced that LG would be the first company to launch an HTML5 compatible browser.

Where this was over 6 months ago, I haven't been able to find any other sources that woukd indicate whether any phone browsers would support it.

The best thing to do would to point your mobile device (or emulate one) to a site made with HTML5.

After a little more research I found this quote from the apple.com site.

"Every new Apple mobile device and every new Mac — along with the latest version of Apple’s >Safari web browser — supports web standards including HTML5, CSS3, and JavaScript."

Also for Android, check this page.

Title: Can I use html5 in my mobile website?

Body:
I must create a web site optimised for mobile devices, can I use html5 and css3?
What are the main limitations?
Which devices are compatible? (IOS, Android...)

Regards


答:
I want to find a way to pass preparedstatement variable values to this method.

In general, you can pass a variable to another method as parameter or you can access variable if it is declared at class level.

I do not know the exact details of the query and its supplying parameters. See an example which explains the use of Prepared Statement.

Example: See more details in the link

```<code>    private static void insertRecordIntoTable() throws SQLException {

    Connection dbConnection = null;
    PreparedStatement preparedStatement = null;

    String insertTableSQL = "INSERT INTO DBUSER"
            + "(USER_ID, USERNAME, CREATED_BY, CREATED_DATE) VALUES"
            + "(?,?,?,?)";

    try {
        dbConnection = getDBConnection();
        preparedStatement = dbConnection.prepareStatement(insertTableSQL);

        preparedStatement.setInt(1, 11);
        preparedStatement.setString(2, "mkyong");
        preparedStatement.setString(3, "system");
        preparedStatement.setTimestamp(4, getCurrentTimeStamp());

        // execute insert SQL stetement
        preparedStatement.executeUpdate();

        System.out.println("Record is inserted into DBUSER table!");

    } catch (SQLException e) {

        System.out.println(e.getMessage());

    } finally {

        if (preparedStatement != null) {
            preparedStatement.close();
        }

        if (dbConnection != null) {
            dbConnection.close();
        }

    }

}
</code>```

Is there a way to get connection object in another class if I share a database class instance through the overall project?

If you want to share connection among different classes or project level, you can create connection object using singleton pattern which will give the flexibility to share one connection for all the classes.

Title: Implement a method in java mysql database connection class to use preparedStatements

Body:
I want to find a way to pass preparedstatement variable values to this method.

In general, you can pass a variable to another method as parameter or you can access variable if it is declared at class level.

I do not know the exact details of the query and its supplying parameters. See an example which explains the use of Prepared Statement.

Example: See more details in the link

    private static void insertRecordIntoTable() throws SQLException {

    Connection dbConnection = null;
    PreparedStatement preparedStatement = null;

    String insertTableSQL = "INSERT INTO DBUSER"
            + "(USER_ID, USERNAME, CREATED_BY, CREATED_DATE) VALUES"
            + "(?,?,?,?)";

    try {
        dbConnection = getDBConnection();
        preparedStatement = dbConnection.prepareStatement(insertTableSQL);

        preparedStatement.setInt(1, 11);
        preparedStatement.setString(2, "mkyong");
        preparedStatement.setString(3, "system");
        preparedStatement.setTimestamp(4, getCurrentTimeStamp());

        // execute insert SQL stetement
        preparedStatement.executeUpdate();

        System.out.println("Record is inserted into DBUSER table!");

    } catch (SQLException e) {

        System.out.println(e.getMessage());

    } finally {

        if (preparedStatement != null) {
            preparedStatement.close();
        }

        if (dbConnection != null) {
            dbConnection.close();
        }

    }

}

Is there a way to get connection object in another class if I share a database class instance through the overall project?

If you want to share connection among different classes or project level, you can create connection object using singleton pattern which will give the flexibility to share one connection for all the classes.


问:
Creating a list of lists from round robin not using a recipe
I am new to python and trying to learn how to round robin of a list into a list of lists. I saw posts with answers pointing to a standard round robin recipe, but I don't understand some of the concepts in it and would prefer a simpler solution.

I want to achieve something like this using a function, but I haven't been able to come close:

```<code>MYLIST = ['apples', 'oranges', 'bananas', 'grapes', 'strawberries', 'pears']
>>>myfunc(MYLIST)
[['apples', 'grapes'], ['oranges', 'strawberries'], ['bananas', 'pears']]
</code>```

I'm very confused after attempting to solve this problem using a combination of for loops, while loops and if statements. Nothing I did worked.

I don't have any code that works or comes close to working. Any help would be appreciated. Thanks.

答:
Solution: This behavior is implemented in more_itertools.distribute see documentation for details.  Simply pip install more-itertools and code the following:

```<code>import more_itertools

list_ = ['apples', 'oranges', 'bananas', 'grapes', 'strawberries', 'pears']
[list(c) for c in list(more_itertools.distribute(3, list_))]
# [['apples', 'grapes'], ['oranges', 'strawberries'], ['bananas', 'pears']]
</code>```

Explanation: The latter redistributes an iterable across n containers.

Note, this is not what the roundrobin recipe does, which yields interleaved elements from n iterables, e.g. roundrobin('ABC', 'D', 'EF') --> A D E B F C.  This creates a single stream of elements that are not divided among separate containers, as you require.

Body:
I am new to python and trying to learn how to round robin of a list into a list of lists. I saw posts with answers pointing to a standard round robin recipe, but I don't understand some of the concepts in it and would prefer a simpler solution.

I want to achieve something like this using a function, but I haven't been able to come close:

MYLIST = ['apples', 'oranges', 'bananas', 'grapes', 'strawberries', 'pears']
>>>myfunc(MYLIST)
[['apples', 'grapes'], ['oranges', 'strawberries'], ['bananas', 'pears']]

I'm very confused after attempting to solve this problem using a combination of for loops, while loops and if statements. Nothing I did worked.

I don't have any code that works or comes close to working. Any help would be appreciated. Thanks.

Body:
Solution: This behavior is implemented in more_itertools.distribute see documentation for details.  Simply pip install more-itertools and code the following:

import more_itertools

list_ = ['apples', 'oranges', 'bananas', 'grapes', 'strawberries', 'pears']
[list(c) for c in list(more_itertools.distribute(3, list_))]
# [['apples', 'grapes'], ['oranges', 'strawberries'], ['bananas', 'pears']]

Explanation: The latter redistributes an iterable across n containers.

Note, this is not what the roundrobin recipe does, which yields interleaved elements from n iterables, e.g. roundrobin('ABC', 'D', 'EF') --> A D E B F C.  This creates a single stream of elements that are not divided among separate containers, as you require.


问:
bind json data to input select
I am using one input select where i have to bind json data to this control.

Below is the input select used:

<select id="ms" multiple="multiple" name="selector">

</select>```
</div>
</div>

Below is jquery used for bind data on page load:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>$(document).ready(function () {

        $('#ms').multipleSelect({
            width: '100%'
        });
        BindCategory();
  });
   function BindCategory()
    {
        $.ajax({
            url: "/Article/BindCategory",
            type: "GET",
            contentType: 'application/json; charset=utf-8',
            success: function (response) {
                var sel = $('#ms');
                $.each(response.Categories, function (i, value) {
                    j=1;
                    sel.append('<option value="' + value + '">' + i + '</option>');

                    j++;
                });
            },
            error: function (er) {
                alert(er);
            }
        });
    }</code>```

in this bindcategory function i am running one loop to get value one by one and putting in html select control but after complete this process data is not binding in this control.

I added now screen shot of response for your reference in below:

答:
Here is working code,

```<code><select id="ms" multiple="multiple" name="selector"></select>
</code>```

Below is the modified JS code.

```<code>function BindCategory(){
    $.ajax({
        url: "https://restcountries.eu/rest/v2/all",
        type: "GET",
        success: function (response) {
            var sel = $('#ms');
            $.each(response, function (i, value) {
                sel.append('<option value="' + value.name + '">' + value.name + '</option>');
            });
            sel.multipleSelect('refresh');
        },
        error: function (er) {
            console.log(er);
        }
    });
}

$(document).ready(function () {
    $('#ms').multipleSelect({
        width: '100%'
    });

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

Just change the ajax url to your url and sel.append('<option value="' + value.name + '">' + value.name + '</option>'); and this part of code as per your need. Let me know if its works for you. Below is the working fiddle if you want to test it. Working fiddle. try it

Title: bind json data to input select

Body:
I am using one input select where i have to bind json data to this control.

Below is the input select used:

<select id="ms" multiple="multiple" name="selector">

</select>

Below is jquery used for bind data on page load:

$(document).ready(function () {

        $('#ms').multipleSelect({
            width: '100%'
        });
        BindCategory();
  });
   function BindCategory()
    {
        $.ajax({
            url: "/Article/BindCategory",
            type: "GET",
            contentType: 'application/json; charset=utf-8',
            success: function (response) {
                var sel = $('#ms');
                $.each(response.Categories, function (i, value) {
                    j=1;
                    sel.append('<option value="' + value + '">' + i + '</option>');

                    j++;
                });
            },
            error: function (er) {
                alert(er);
            }
        });
    }

in this bindcategory function i am running one loop to get value one by one and putting in html select control but after complete this process data is not binding in this control.

I added now screen shot of response for your reference in below:

Body:
Here is working code,

<select id="ms" multiple="multiple" name="selector"></select>

Below is the modified JS code.

function BindCategory(){
    $.ajax({
        url: "https://restcountries.eu/rest/v2/all",
        type: "GET",
        success: function (response) {
            var sel = $('#ms');
            $.each(response, function (i, value) {
                sel.append('<option value="' + value.name + '">' + value.name + '</option>');
            });
            sel.multipleSelect('refresh');
        },
        error: function (er) {
            console.log(er);
        }
    });
}

$(document).ready(function () {
    $('#ms').multipleSelect({
        width: '100%'
    });

    BindCategory();
});

Just change the ajax url to your url and sel.append('<option value="' + value.name + '">' + value.name + '</option>'); and this part of code as per your need. Let me know if its works for you. Below is the working fiddle if you want to test it. Working fiddle. try it


问:
Extracting array data from javascript
I'm trying to get the data in an array in javascript.

here's my arrayProgram in javascript:

```<code>    [0] => Array (
    [Program] => Array (
        [event_name] => Event Daily
        [keyword] => KVIP SHOWTIME
        [start_date] => 2017-04-07 12:00:00
        [end_date] => 2017-04-03 15:00:00
        [location] => Studio 1
        [slots] => 10
        [event_color] => #9a9aff
        [is_allday] => 1
        [repeat_program] => daily-weekly
        [repeat_every] => 1
        [repeat_days] => ,1,2,3,4,5,6
        [repeat_yearly] => 0
        [is_end] => 0
        )
    )
[1] => Array (
    [Program] => Array (
        [event_name] => NEWS
        [keyword] => KVIP NEWS
        [start_date] => 2017-04-30 05:30:00
        [end_date] => 2017-04-01 19:00:00
        [location] => Studio 4
        [slots] => 05
        [event_color] => #fb8979
        [is_allday] => 1
        [repeat_program] => monthly
        [repeat_every] => 0
        [repeat_days] =>
        )
    )
[2] => Array (
    [Program] => Array (
        [event_name] => ASAP
        [keyword] => KVIP ASAP
        [start_date] => 2017-12-31 12:00:00
        [end_date] => 2017-04-01 15:00:00
        [location] => Studio 10
        [slots] => 16
        [event_color] => #9a9aff
        [is_allday] => 1
        [repeat_program] => yearly
        [repeat_every] => 0
        [repeat_days] =>
        )
    )
</code>```

how can I extract the data using a for loop? I tried using $.each but it doesn't work for me. Can someone please help me?

答:
You can loop by using for statement:

```<code>var arr = [/* your array data here*/];

for (var i = 0; i < arr.length; i++)
{
    console.log( arr[i]['Program']['event_name'] );
    console.log( arr[i]['Program']['keyword'] );
    // ... use arr[i]['Program'][...] to access other attribute
}
</code>```

Title: Extracting array data from javascript

Body:
I'm trying to get the data in an array in javascript.

here's my arrayProgram in javascript:

    [0] => Array (
    [Program] => Array (
        [event_name] => Event Daily
        [keyword] => KVIP SHOWTIME
        [start_date] => 2017-04-07 12:00:00
        [end_date] => 2017-04-03 15:00:00
        [location] => Studio 1
        [slots] => 10
        [event_color] => #9a9aff
        [is_allday] => 1
        [repeat_program] => daily-weekly
        [repeat_every] => 1
        [repeat_days] => ,1,2,3,4,5,6
        [repeat_yearly] => 0
        [is_end] => 0
        )
    )
[1] => Array (
    [Program] => Array (
        [event_name] => NEWS
        [keyword] => KVIP NEWS
        [start_date] => 2017-04-30 05:30:00
        [end_date] => 2017-04-01 19:00:00
        [location] => Studio 4
        [slots] => 05
        [event_color] => #fb8979
        [is_allday] => 1
        [repeat_program] => monthly
        [repeat_every] => 0
        [repeat_days] =>
        )
    )
[2] => Array (
    [Program] => Array (
        [event_name] => ASAP
        [keyword] => KVIP ASAP
        [start_date] => 2017-12-31 12:00:00
        [end_date] => 2017-04-01 15:00:00
        [location] => Studio 10
        [slots] => 16
        [event_color] => #9a9aff
        [is_allday] => 1
        [repeat_program] => yearly
        [repeat_every] => 0
        [repeat_days] =>
        )
    )

how can I extract the data using a for loop? I tried using $.each but it doesn't work for me. Can someone please help me?

Body:
You can loop by using for statement:

var arr = [/* your array data here*/];

for (var i = 0; i < arr.length; i++)
{
    console.log( arr[i]['Program']['event_name'] );
    console.log( arr[i]['Program']['keyword'] );
    // ... use arr[i]['Program'][...] to access other attribute
}


问:
How to encrypt and decrypt sound files in Java?
Is there a way to encrypt and decrypt sound files such as *.wav , *.au or *.snd files in Java ?

Edit :
I knew how to encrypt and decrypt text files, just curious if a sound file could be encrypted and decrypted, now it seems I can use the same methods.

答:
Yes there is a way. It is effectively the same as encrypting/decrypting text as the API requests or returns byte arrays.

Here is a very basic example: Basic symmetric encryption example


问:
htmlunit : checkbox not getting checked
I am using HtmlUnit for setting a checkbox in a page. Html code for checkbox is :

```<code><input id="Checkbox" type="checkbox"  name="Checkbox" style="color:Black;"/>
</code>```

My java code to set checkbox is :

```<code>HtmlCheckBoxInput checkBox = page.getHtmlElementById("Checkbox");
checkBox.setChecked(true);

FileUtils.writeStringToFile(new File("src/test/page-dumps/page-3.html"),page.asXml(),"UTF-8");
</code>```

When I open page-3.html in my browse, ckeckbox is unchecked. Why is it not checked?

答: Can you try adding the checked attribute to the <input> element?

Title: htmlunit : checkbox not getting checked

Body:
I am using HtmlUnit for setting a checkbox in a page. Html code for checkbox is :

<input id="Checkbox" type="checkbox"  name="Checkbox" style="color:Black;"/>

My java code to set checkbox is :

HtmlCheckBoxInput checkBox = page.getHtmlElementById("Checkbox");
checkBox.setChecked(true);

FileUtils.writeStringToFile(new File("src/test/page-dumps/page-3.html"),page.asXml(),"UTF-8");

When I open page-3.html in my browse, ckeckbox is unchecked. Why is it not checked?


问:
iterate over the hostname stored in var_files
I have two type of server host names added in the ansible main.yml var file:

main.yml file:

```<code>foo_server1: 10.10.1.1
foo_server2: 10.10.1.2

bar_server1: 192.168.1.3
bar_server2: 192.168.1.4
bar_server3: 192.168.1.5
</code>```

I am having an ansible playbook which essentially runs on foo_server1 and initializes/formats all other servers in the list one at a time - starting with foo_server2 then bar_server1, bar_server2 and so on...

```<code>---
- name: Reading variables from var files
  hosts: localhost
  connection: local
  vars_files:
    - main.yml
  tasks:
    - name: Initialize foo server2
      command: initialize --host1 {{foo_server1}} to --host2 {{foo_server2}}
    - name: Initialize bar server1
      command: initialize --host1 {{foo_server1}} to --host2 {{bar_server1}}
    - name: Initialize bar server2
      command:  initialize --host1 {{foo_server1}} to --host2 {{bar_server2}}
    - name: Initialize bar server3
      command:  initialize --host1 {{foo_server1}} to --host2 {{bar_server3}}
</code>```

I dont want to add multiple lines in the playbook for each server rather wants to loop over the host names from the variable file. I am not sure how i would get this done..i am trying to loop over the hostname.. tried something below but no luck as i am getting undefined variable name..

```<code>---
server_list:
    foo_server1: 10.10.1.1
    foo_server2: 10.10.1.2

    bar_server1: 192.168.1.3
    bar_server2: 192.168.1.4
    bar_server3: 192.168.1.5
</code>```

Ansible playbook...

```<code>---
- hosts: localhost
  gather_facts: no
  vars_files:
  - input.yml
  tasks:
  - name: Enable replication
    local_action: shell initialize --host1 {{item.foo_server1}} --host2 {{item.foo_server2}}
    with_items:
     - "{{ server_list }}"
</code>```

Can some one please suggest how can i run the same command on multiple servers. Would appreciate any help offered..

答:
Here is an example for you:</p>

```<code>---
- hosts: localhost
  gather_facts: no
  vars:
    servers:
      foo_server1: 10.10.1.1
      foo_server2: 10.10.1.2
      bar_server1: 192.168.1.3
      bar_server2: 192.168.1.4
      bar_server3: 192.168.1.5
  tasks:
    - debug:
        msg: shell initialize --host1 {{ servers.foo_server1 }} --host2 {{ item.value }}
      when: item.key != 'foo_server1'
      with_dict: "{{ servers }}"
</code>```

Body:
I have two type of server host names added in the ansible main.yml var file:

main.yml file:

foo_server1: 10.10.1.1
foo_server2: 10.10.1.2

bar_server1: 192.168.1.3
bar_server2: 192.168.1.4
bar_server3: 192.168.1.5

I am having an ansible playbook which essentially runs on foo_server1 and initializes/formats all other servers in the list one at a time - starting with foo_server2 then bar_server1, bar_server2 and so on...

---
- name: Reading variables from var files
  hosts: localhost
  connection: local
  vars_files:
    - main.yml
  tasks:
    - name: Initialize foo server2
      command: initialize --host1 {{foo_server1}} to --host2 {{foo_server2}}
    - name: Initialize bar server1
      command: initialize --host1 {{foo_server1}} to --host2 {{bar_server1}}
    - name: Initialize bar server2
      command:  initialize --host1 {{foo_server1}} to --host2 {{bar_server2}}
    - name: Initialize bar server3
      command:  initialize --host1 {{foo_server1}} to --host2 {{bar_server3}}

I dont want to add multiple lines in the playbook for each server rather wants to loop over the host names from the variable file. I am not sure how i would get this done..i am trying to loop over the hostname.. tried something below but no luck as i am getting undefined variable name..

---
server_list:
    foo_server1: 10.10.1.1
    foo_server2: 10.10.1.2

    bar_server1: 192.168.1.3
    bar_server2: 192.168.1.4
    bar_server3: 192.168.1.5

Ansible playbook...

---
- hosts: localhost
  gather_facts: no
  vars_files:
  - input.yml
  tasks:
  - name: Enable replication
    local_action: shell initialize --host1 {{item.foo_server1}} --host2 {{item.foo_server2}}
    with_items:
     - "{{ server_list }}"

Can some one please suggest how can i run the same command on multiple servers. Would appreciate any help offered..

Body:
Here is an example for you:

---
- hosts: localhost
  gather_facts: no
  vars:
    servers:
      foo_server1: 10.10.1.1
      foo_server2: 10.10.1.2
      bar_server1: 192.168.1.3
      bar_server2: 192.168.1.4
      bar_server3: 192.168.1.5
  tasks:
    - debug:
        msg: shell initialize --host1 {{ servers.foo_server1 }} --host2 {{ item.value }}
      when: item.key != 'foo_server1'
      with_dict: "{{ servers }}"


问:
What is the best way to reuse functions in Flex MVC environment?
I am using a Cairngorm MVC architecture for my current project.

I have several commands which use the same type of function that returns a value. I would like to have this function in one place, and reuse it, rather than duplicate the code in each command. What is the best way to do this?

答: Create an abstract base class for your commands and add your function in the protected scope.  If you need to reuse it anywhere else, refactor it into a public static method on a utility class.</p>

OwnerDisplayName: Eric Belair


问:
Can I use html5 in my mobile website?
I must create a web site optimised for mobile devices, can I use html5 and css3?
What are the main limitations?
Which devices are compatible? (IOS, Android...)

Regards

答: iOS and Android will both support HTML5 and CSS3 (and well). You'll run into some problems with windows mobile (which runs a modified version of ie7)</p>

Title: Can I use html5 in my mobile website?


问:
Why divs are not centered well?
I have such code https://jsfiddle.net/96Lnxr38/3/ but as you can see - divs with class d1 are not aligned properly. If I add more spaces between

 elements - alignment will work fine. Is it a browser bug or my mistake? I have found that FF works fine and Chome/Safari show me this bug.

答:
If you are using a pixel width, the best solution is margin:auto;

```<code>.cont {
  text-align: center;
  width: 500px;
  margin:auto;
}

.d1 {
  width: 300px;
  height: 500px;
  margin-top: 10px;
  background-color: red;
  display: inline-block;
  margin:auto;
}
</code>```

follow this link : https://jsfiddle.net/96Lnxr38/6/

Title: Why divs are not centered well?

Body:
If you are using a pixel width, the best solution is margin:auto;

.cont {
  text-align: center;
  width: 500px;
  margin:auto;
}

.d1 {
  width: 300px;
  height: 500px;
  margin-top: 10px;
  background-color: red;
  display: inline-block;
  margin:auto;
}

follow this link : https://jsfiddle.net/96Lnxr38/6/


问:
ExecuteNonQuery: CommandText property has not been initialized in c#
I am trying to insert data from dynamically generated textbox of gridview in the database. however, I am getting the exception of the CommandText property has not been initialized cmd.executeNonQuery();

```<code>private void InsertRecords(StringCollection sc)
{
    StringBuilder sb = new StringBuilder(string.Empty);
    string[] splitItems = null;
    const string sqlStatement = "INSERT INTO Ingredients_List (Ingredients1) VALUES";
    foreach (string item in sc)
    {
        if (item.Contains(","))
        {
            splitItems = item.Split(",".ToCharArray());
            sb.AppendFormat("{0}('{1}'); ", sqlStatement, splitItems[0]);
        }

    }
    //  conn.Open();
    using (SqlConnection connn = new SqlConnection(GetConnectionString()))

    {
        using (SqlCommand cmd = new SqlCommand(sb.ToString(), connn))
        {
            connn.Open();
            //      cmd.CommandType = CommandType.Text;
            cmd.ExecuteNonQuery();
            connn.Close();
        }
        // Page.ClientScript.RegisterClientScriptBlock(typeof(Page), "Script", "alert('Records Successfuly Saved!');", true);
    }
}
</code>```

答:
Your problem is caused by the fact that you don't check if, after the loop, you have inserted anything in the StringBuilder. In case of no string with commas, then, the internal condition into the foreach statement, leaves the stringbuilder empty and the command will never have a proper command text.

The workaround should be simple like adding a test to see if there is some text inside the StringBuilder but I prefer to suggest you a different approach using a List<SqlParameter>

```<code>StringBuilder sb = new StringBuilder(string.Empty);
List<SqlParameter> prms = new List<SqlParameter>();
string[] splitItems = null;

// Base string for creating parameter placeholders dynamically
string sqlStatement = "INSERT INTO Ingredients_List (Ingredients1) VALUES (@p{0});";

int count = 1;
foreach (string item in sc)
{
    if (item.Contains(","))
    {
        splitItems = item.Split(',');

        // Parameter name created dynamically
        prms.Add(new SqlParameter($"@p{count}", SqlDbType.NVarChar) {Value=splitItems[0]});

        // Create the placeholder for the nth parameter
        sb.AppendFormat(sqlStatement, count);
    }
}

// Don't execute anything if there are no parameters (or stringbuilder empty)
if(prms.Count > 0)
{
    using (SqlConnection connn = new SqlConnection(GetConnectionString()))
    using (SqlCommand cmd = new SqlCommand(sb.ToString(), connn))
    {
        connn.Open();

        // Add all parameters together
        cmd.Parameters.AddRange(prms);
        cmd.ExecuteNonQuery();
    }
}
</code>```

Body:
I am trying to insert data from dynamically generated textbox of gridview in the database. however, I am getting the exception of the CommandText property has not been initialized cmd.executeNonQuery();

private void InsertRecords(StringCollection sc)
{
    StringBuilder sb = new StringBuilder(string.Empty);
    string[] splitItems = null;
    const string sqlStatement = "INSERT INTO Ingredients_List (Ingredients1) VALUES";
    foreach (string item in sc)
    {
        if (item.Contains(","))
        {
            splitItems = item.Split(",".ToCharArray());
            sb.AppendFormat("{0}('{1}'); ", sqlStatement, splitItems[0]);
        }

    }
    //  conn.Open();
    using (SqlConnection connn = new SqlConnection(GetConnectionString()))

    {
        using (SqlCommand cmd = new SqlCommand(sb.ToString(), connn))
        {
            connn.Open();
            //      cmd.CommandType = CommandType.Text;
            cmd.ExecuteNonQuery();
            connn.Close();
        }
        // Page.ClientScript.RegisterClientScriptBlock(typeof(Page), "Script", "alert('Records Successfuly Saved!');", true);
    }
}

Body:
Your problem is caused by the fact that you don't check if, after the loop, you have inserted anything in the StringBuilder. In case of no string with commas, then, the internal condition into the foreach statement, leaves the stringbuilder empty and the command will never have a proper command text.

The workaround should be simple like adding a test to see if there is some text inside the StringBuilder but I prefer to suggest you a different approach using a List<SqlParameter>

StringBuilder sb = new StringBuilder(string.Empty);
List<SqlParameter> prms = new List<SqlParameter>();
string[] splitItems = null;

// Base string for creating parameter placeholders dynamically
string sqlStatement = "INSERT INTO Ingredients_List (Ingredients1) VALUES (@p{0});";

int count = 1;
foreach (string item in sc)
{
    if (item.Contains(","))
    {
        splitItems = item.Split(',');

        // Parameter name created dynamically
        prms.Add(new SqlParameter($"@p{count}", SqlDbType.NVarChar) {Value=splitItems[0]});

        // Create the placeholder for the nth parameter
        sb.AppendFormat(sqlStatement, count);
    }
}

// Don't execute anything if there are no parameters (or stringbuilder empty)
if(prms.Count > 0)
{
    using (SqlConnection connn = new SqlConnection(GetConnectionString()))
    using (SqlCommand cmd = new SqlCommand(sb.ToString(), connn))
    {
        connn.Open();

        // Add all parameters together
        cmd.Parameters.AddRange(prms);
        cmd.ExecuteNonQuery();
    }
}


问:
Column Alignment using C++
I'm struggling getting my columns to align on an assignment I have for school. The directions are to ensure that each column heading aligns correctly with its respective column. I've tried everything I've found online so far, including the cout.width() and the setw(), neither of which has worked. I'm hoping it's not due to me implementing these methods incorrectly, though I can't think of any other reason why they wouldn't work. The assignment specifically has 2 student names to use as an example. Jones, Bob and Washington, George. Due to the major difference in the number of characters between one student and the next, the columns just won't align. I know that setting a column width should fix that, but in my case it isn't. Then code I'm supplying is using the setw() method, but I can supply how I tried using the cout.width() if needed. Any help is GREATLY appreciated.

```<code>#include <iostream>
#include <iomanip>
#include <string>
#include <cstdlib>

using std::cout;
using std::cin;
using namespace std;

const int ARRAYSIZE = 2;

struct studentData{
    string lastName;
    string firstName;
    float studentGpa;
}studentArray[ARRAYSIZE];

void displayData(int a);

int main()
{
    int counter = 0;

    for (int a = 0; a < ARRAYSIZE; a++)
    {
        cout << "Enter last name: " << endl;
        cin >> studentArray[a].lastName;

        cout << "Enter first name: " << endl;
        cin >> studentArray[a].firstName;

        cout << "Enter GPA: "<< endl;
        cin >> studentArray[a].studentGpa;

        counter++;
    }
    cout << "\n\n";
    displayData(counter);

return 0;
}

void displayData(int a)
{
    int newSize = a;

    cout << left << setw(20) <<"\nName(Last, First)";
    cout << right << setw(20) << "GPA\n";

    for (int z = 0; z < newSize; z++)
    {
        cout << studentArray[z].lastName << ", " << studentArray[z].firstName;
        cout << right << setw(20) << fixed << setprecision(2) <<studentArray[z].studentGpa << endl;
    }
}
</code>```

And my console input/output:

```<code>Enter last name:
Jones
Enter first name:
Bob
Enter GPA:
3.0
Enter last name:
Washington
Enter first name:
George
Enter GPA:
4.0

Name(Last, First)                  GPA
Jones, Bob                3.00
Washington, George                4.00
</code>```

答:
You are along the right lines, but std::setw only applies to the next output operation. If you turn printing the name into one operation, instead of 3 (last, comma, first) then you can pad the width of that more easily:

```<code>void displayData(std::size_t a)
{
    std::cout << std::left
              << std::setw(20)
              << "Name(Last, First)"
              << "GPA\n";

    for (std::size_t z = 0; z < a; ++z)
    {
        std::cout << std::left
                  << std::setw(20)
                  << (studentArray[z].lastName + ", " + studentArray[z].firstName)
                  << std::fixed << std::setprecision(2)
                  << studentArray[z].studentGpa
                  << '\n';
    }
}
</code>```

Output:

```<code>Name(Last, First)   GPA
Jones, Bob          3.00
Washington, George  4.00
</code>```

Here, both for printing the column headings, and for the student names, I use std::left to say that the content should be at the left of the padded total, and std::setw to pad this output operation to 20 characters total (by default it will pad with spaces).

In both cases, this is the 1st column in the output, so I don't need to do anything with the 2nd column. If you had a 3rd column, you would need to pad the 2nd as well.

I also replaced your ints with size_ts for array indexing. It's a little point, but you shouldn't really use a signed type for indexing into a container where accessing a negative index would be Undefined Behaviour.

Also, please reconsider your use of what are often considered bad practices: using namespace std; and endl (those are links to explanations).

Title: Column Alignment using C++

Body:
I'm struggling getting my columns to align on an assignment I have for school. The directions are to ensure that each column heading aligns correctly with its respective column. I've tried everything I've found online so far, including the cout.width() and the setw(), neither of which has worked. I'm hoping it's not due to me implementing these methods incorrectly, though I can't think of any other reason why they wouldn't work. The assignment specifically has 2 student names to use as an example. Jones, Bob and Washington, George. Due to the major difference in the number of characters between one student and the next, the columns just won't align. I know that setting a column width should fix that, but in my case it isn't. Then code I'm supplying is using the setw() method, but I can supply how I tried using the cout.width() if needed. Any help is GREATLY appreciated.

#include <iostream>
#include <iomanip>
#include <string>
#include <cstdlib>

using std::cout;
using std::cin;
using namespace std;

const int ARRAYSIZE = 2;

struct studentData{
    string lastName;
    string firstName;
    float studentGpa;
}studentArray[ARRAYSIZE];

void displayData(int a);

int main()
{
    int counter = 0;

    for (int a = 0; a < ARRAYSIZE; a++)
    {
        cout << "Enter last name: " << endl;
        cin >> studentArray[a].lastName;

        cout << "Enter first name: " << endl;
        cin >> studentArray[a].firstName;

        cout << "Enter GPA: "<< endl;
        cin >> studentArray[a].studentGpa;

        counter++;
    }
    cout << "\n\n";
    displayData(counter);

return 0;
}

void displayData(int a)
{
    int newSize = a;

    cout << left << setw(20) <<"\nName(Last, First)";
    cout << right << setw(20) << "GPA\n";

    for (int z = 0; z < newSize; z++)
    {
        cout << studentArray[z].lastName << ", " << studentArray[z].firstName;
        cout << right << setw(20) << fixed << setprecision(2) <<studentArray[z].studentGpa << endl;
    }
}

And my console input/output:

Enter last name:
Jones
Enter first name:
Bob
Enter GPA:
3.0
Enter last name:
Washington
Enter first name:
George
Enter GPA:
4.0

Name(Last, First)                  GPA
Jones, Bob                3.00
Washington, George                4.00

Body:
You are along the right lines, but std::setw only applies to the next output operation. If you turn printing the name into one operation, instead of 3 (last, comma, first) then you can pad the width of that more easily:

void displayData(std::size_t a)
{
    std::cout << std::left
              << std::setw(20)
              << "Name(Last, First)"
              << "GPA\n";

    for (std::size_t z = 0; z < a; ++z)
    {
        std::cout << std::left
                  << std::setw(20)
                  << (studentArray[z].lastName + ", " + studentArray[z].firstName)
                  << std::fixed << std::setprecision(2)
                  << studentArray[z].studentGpa
                  << '\n';
    }
}

Output:

Name(Last, First)   GPA
Jones, Bob          3.00
Washington, George  4.00

Here, both for printing the column headings, and for the student names, I use std::left to say that the content should be at the left of the padded total, and std::setw to pad this output operation to 20 characters total (by default it will pad with spaces).

In both cases, this is the 1st column in the output, so I don't need to do anything with the 2nd column. If you had a 3rd column, you would need to pad the 2nd as well.

I also replaced your ints with size_ts for array indexing. It's a little point, but you shouldn't really use a signed type for indexing into a container where accessing a negative index would be Undefined Behaviour.

Also, please reconsider your use of what are often considered bad practices: using namespace std; and endl (those are links to explanations).