问:
How correctly generate html select option with php?
yesterday, I was designing a platform to enter products and their quantities using drop-down lists, but I had to generate them using a button, so I had to use javascript. It worked, but at the moment of sending the data by post only takes the last Select generated, then the code and the result.

```<code>    <form id="pedido" name="pedido" action="funciones/pedido.php" method="post" >

<table name="pedidos" class="table table-bordered table-hover" id="myTable">
                                 <thead>
                                    <tr>
                                        <th>Producto</th>
                                        <th>Cantidad</th>
                                    </tr>
                                </thead>

</table>
<br>

</form>
<center>
<button class="btn btn-sm btn-primary"  onclick="myCreateFunction()">Agregar Producto</button>
<button class="btn btn-sm btn-danger" onclick="myDeleteFunction()">Eliminar Producto</button>
<button class="btn btn-sm btn-success"  form="pedido" type="submit">Guardar</button></center>
<br>
</code>```

and the Javascript

```<code><script>
function myCreateFunction() {
    var table = document.getElementById("myTable");
    var row = table.insertRow(1);
    var cell = row.insertCell(0);

    <? $sql="select * from productodist where  rut_dist='".$_GET['id']."';";
$resultado=mysql_query($sql);
$x=0;?>
    var element = document.createElement("select");
 <? while($datos=mysql_fetch_array($resultado)){
     $x++?>
    var option<? echo $x; ?> = document.createElement("option");
    option<? echo $x; ?> .innerHTML = "<? echo  $datos['Descripcion'] ?>";
    option<? echo $x; ?>.value = "<? echo  $datos['CodArticulo'] ?>";
    element.add(option<? echo $x; ?>, null);
    element.name = "producto<? echo $x; ?>";

    <?
 }
    ?>
    cell.appendChild(element);

    var cell2 = row.insertCell(1);
    var element2 = document.createElement("select");
    //element2.type = "select"

    <?  for ($y=1;$y<=100;$y++){
        ?>    var option<? echo $y; ?> = document.createElement("option");
    option<? echo $y; ?>.innerHTML = "<? echo $y; ?>";
    option<? echo $y; ?>.value = "<? echo $y; ?>";
    element2.add(option<? echo $y; ?>, null);
    element2.name = "cantidad<? echo $x; ?>";
    <?  }?>
    cell2.appendChild(element2);
}

function myDeleteFunction() {
    document.getElementById("myTable").deleteRow(1);
}
</script>
</code>```

And then when I send it, the post array anwer me this.

```<code>Array ( [producto30] => 20008 [cantidad30] => 1 )
</code>```

What I'm doing wrong? Thanks you in advance!

答:
you need to set attribute of option is selected, so form can read what value have to send. if you want to send more that one value , you have to set attribute select to multiple, and mark option value that you want to send value as selected.

/* mark your option to selected*/

```<code>option.setAttribute('selected', true);
</code>```

/add attr multiple to make select can be select more than one value./

```<code>element2.setAttribute(multiple, "multiple");
</code>```

i hope this help.

the name of your select is same, so form will replace all and get the last select.
you can see in here
name of select same

so, you need to add class in select to make it simple to count.

```<code>/*we add attr class*/
element.setAttribute(class, "element");
element2.setAttribute(class, "element2");

/*here we count created select*/
    var x = $(".element").length;
</code>```

because element 1 and 2 is same length we don't need to count element 2
and just set the name of element like.

```<code>  element.name = "producto"+x;
  element2.name = "cantidad"+x;
</code>```

this the final function.

```<code>function myCreateFunction() {
    var table = document.getElementById("myTable");
    var row = table.insertRow(1);
    var cell = row.insertCell(0);
    var x = parseFloat($(".element").length); /*this  for count length of class element*/

    <? $sql="select * from productodist where  rut_dist='".$_GET['id']."';";
        $resultado=mysql_query($sql);
        $x=0;
    ?>
    var element = document.createElement("select");
    element.setAttribute("Class","element"); /*this will be add class element into input select1 */
    <?
        while($datos=mysql_fetch_array($resultado)){
        $x++;
     ?>

        var option<? echo $x; ?>        = document.createElement("option");
        option<? echo $x; ?> .innerHTML = "<? echo  $datos['Descripcion'] ?>";
        option<? echo $x; ?>.value      = "<? echo  $datos['CodArticulo'] ?>";
        element.add(option<? echo $x; ?>, null);
    <?
        }
    ?>

    element.name                    = "producto"+(x+1); /*i move outside looping so it's just set once and set name element +length of select has been create + 1*/
    cell.appendChild(element);

    var cell2 = row.insertCell(1);
    var element2 = document.createElement("select");
    element2.setAttribute("Class","element"); /*this will be add class element into input select2 */
    //element2.type = "select"

    <?
    for ($y=1;$y<=100;$y++){
    ?>
        var option<? echo $y; ?>       = document.createElement("option");
        option<? echo $y; ?>.innerHTML = "<? echo $y; ?>";
        option<? echo $y; ?>.value     = "<? echo $y; ?>";
        element2.add(option<? echo $y; ?>, null);

    <?
    }
    ?>

    element2.name                  = "cantidad"+(x+1);
    element.name                    = "producto"+(x+1); /*i move outside looping so it's just set once and set name element2 + length of select has been create + 1*/
    cell2.appendChild(element2);
}
</code>```

let me know it's working or not.

Body:
yesterday, I was designing a platform to enter products and their quantities using drop-down lists, but I had to generate them using a button, so I had to use javascript. It worked, but at the moment of sending the data by post only takes the last Select generated, then the code and the result.

    <form id="pedido" name="pedido" action="funciones/pedido.php" method="post" >

                                        Producto
                                        Cantidad

</form>

<button class="btn btn-sm btn-primary"  onclick="myCreateFunction()">Agregar Producto</button>
<button class="btn btn-sm btn-danger" onclick="myDeleteFunction()">Eliminar Producto</button>
<button class="btn btn-sm btn-success"  form="pedido" type="submit">Guardar</button>

and the Javascript

And then when I send it, the post array anwer me this.

Array ( [producto30] => 20008 [cantidad30] => 1 )

What I'm doing wrong? Thanks you in advance!

Body:
you need to set attribute of option is selected, so form can read what value have to send. if you want to send more that one value , you have to set attribute select to multiple, and mark option value that you want to send value as selected.

/* mark your option to selected*/

option.setAttribute('selected', true);

/add attr multiple to make select can be select more than one value./

element2.setAttribute(multiple, "multiple");

i hope this help.

the name of your select is same, so form will replace all and get the last select.
you can see in here
name of select same

so, you need to add class in select to make it simple to count.

/*we add attr class*/
element.setAttribute(class, "element");
element2.setAttribute(class, "element2");

/*here we count created select*/
    var x = $(".element").length;

because element 1 and 2 is same length we don't need to count element 2
and just set the name of element like.

  element.name = "producto"+x;
  element2.name = "cantidad"+x;

this the final function.

function myCreateFunction() {
    var table = document.getElementById("myTable");
    var row = table.insertRow(1);
    var cell = row.insertCell(0);
    var x = parseFloat($(".element").length); /*this  for count length of class element*/

    <? $sql="select * from productodist where  rut_dist='".$_GET['id']."';";
        $resultado=mysql_query($sql);
        $x=0;
    ?>
    var element = document.createElement("select");
    element.setAttribute("Class","element"); /*this will be add class element into input select1 */
    <?
        while($datos=mysql_fetch_array($resultado)){
        $x++;
     ?>

        var option<? echo $x; ?>        = document.createElement("option");
        option<? echo $x; ?> .innerHTML = "<? echo  $datos['Descripcion'] ?>";
        option<? echo $x; ?>.value      = "<? echo  $datos['CodArticulo'] ?>";
        element.add(option<? echo $x; ?>, null);
    <?
        }
    ?>

    element.name                    = "producto"+(x+1); /*i move outside looping so it's just set once and set name element +length of select has been create + 1*/
    cell.appendChild(element);

    var cell2 = row.insertCell(1);
    var element2 = document.createElement("select");
    element2.setAttribute("Class","element"); /*this will be add class element into input select2 */
    //element2.type = "select"

    <?
    for ($y=1;$y<=100;$y++){
    ?>
        var option<? echo $y; ?>       = document.createElement("option");
        option<? echo $y; ?>.innerHTML = "<? echo $y; ?>";
        option<? echo $y; ?>.value     = "<? echo $y; ?>";
        element2.add(option<? echo $y; ?>, null);

    <?
    }
    ?>

    element2.name                  = "cantidad"+(x+1);
    element.name                    = "producto"+(x+1); /*i move outside looping so it's just set once and set name element2 + length of select has been create + 1*/
    cell2.appendChild(element2);
}

let me know it's working or not.


来源: stackexchange

问:
Upload file onto AWS S3 with specific path in NodeJS
I've been taking a crack at uploading files onto S3 via NodeJS, but with a specific path where they have to be stored.

```<code>return s3fsImpl.writeFile(file_name.originalFilename,stream).then(function() {
     fs.unlink(file_name.path, function(err) {
         if (err) {
                console.error(err);
         } else {  /** sucessess **/  }
</code>```

I'm not sure how do I give a path like /project_name/file_name.
I have been following this tutorial

答: In this scenario your are using a stream as the target. When you created that stream you should have specified the path at that point.</p>

ContentLicense: CC BY-SA 3.0

Body:
I've been taking a crack at uploading files onto S3 via NodeJS, but with a specific path where they have to be stored.

return s3fsImpl.writeFile(file_name.originalFilename,stream).then(function() {
     fs.unlink(file_name.path, function(err) {
         if (err) {
                console.error(err);
         } else {  /** sucessess **/  }

I'm not sure how do I give a path like /project_name/file_name.
I have been following this tutorial


问:
Retrieving IBM Cloud Object Storage S3 pricing via API
Is there any way that I can retrieve "IBM Cloud Object Storage - S3" pricing figures through some API calls?

The pricing figures that I am looking to retrieve through API are highlighted in this screenshot.

答:
You need to use this request using REST ful:

```<code>https://$USERID:$APIKEY8@api.softlayer.com/rest/v3/SoftLayer_Product_Package/206/getObjectStorageDatacenters
</code>```

Then you need to look for all the items whose long description proiperty contains "Cleversafe"

e.g.

this is the value for this attribute that you are going to get using the request above:

```<code> {
                "currentPriceFlag": null,
                "hourlyRecurringFee": "0",
                "id": 177743,
                "itemId": 8179,
                "laborFee": "0",
                "locationGroupId": null,
                "onSaleFlag": null,
                "oneTimeFee": "0",
                "quantity": null,
                "recurringFee": "0",
                "setupFee": "0",
                "sort": 0,
                "usageRate": ".03",
                "item": {
                    "capacity": "0",
                    "description": "Standard Cross Region",
                    "id": 8179,
                    "itemTaxCategoryId": 166,
                    "keyName": "STANDARD_CROSS_REGION",
                    "longDescription": "Standard Cross Region - CLEVERSAFE",
                    "softwareDescriptionId": null,
                    "units": "GIGABYTE",
                    "upgradeItemId": null,
                    "itemCategory": {
                        "categoryCode": "object_storage_service",
                        "id": 812,
                        "name": "Object Storage Service",
                        "quantityLimit": 0
                    }
                }
            },
</code>```

As you can see in the description it says "Standard Cross Region" the usageRate says ".03" and the units say "GYGABYTE" . You just need to look for the other vaules in the response

Regards

Body:
You need to use this request using REST ful:

https://$USERID:$APIKEY8@api.softlayer.com/rest/v3/SoftLayer_Product_Package/206/getObjectStorageDatacenters

Then you need to look for all the items whose long description proiperty contains "Cleversafe"

e.g.

this is the value for this attribute that you are going to get using the request above:

 {
                "currentPriceFlag": null,
                "hourlyRecurringFee": "0",
                "id": 177743,
                "itemId": 8179,
                "laborFee": "0",
                "locationGroupId": null,
                "onSaleFlag": null,
                "oneTimeFee": "0",
                "quantity": null,
                "recurringFee": "0",
                "setupFee": "0",
                "sort": 0,
                "usageRate": ".03",
                "item": {
                    "capacity": "0",
                    "description": "Standard Cross Region",
                    "id": 8179,
                    "itemTaxCategoryId": 166,
                    "keyName": "STANDARD_CROSS_REGION",
                    "longDescription": "Standard Cross Region - CLEVERSAFE",
                    "softwareDescriptionId": null,
                    "units": "GIGABYTE",
                    "upgradeItemId": null,
                    "itemCategory": {
                        "categoryCode": "object_storage_service",
                        "id": 812,
                        "name": "Object Storage Service",
                        "quantityLimit": 0
                    }
                }
            },

As you can see in the description it says "Standard Cross Region" the usageRate says ".03" and the units say "GYGABYTE" . You just need to look for the other vaules in the response

Regards


问:
resizing multidimensional vector
How to resize multidimensional vector such as:

```<code>  vector <vector <vector <custom_type> > > array;
</code>```

For example, I need array[3][5][10]?

答: You should resize all the nested vectors one by one.  Use nested for loops or recursion.

ContentLicense: CC BY-SA 2.5

Title: resizing multidimensional vector

Body:
How to resize multidimensional vector such as:

  vector <vector <vector <custom_type> > > array;

For example, I need array[3][5][10]?


问:
What is the default default value of a dependency property?
A WPF dependency property can be given a default value by passing a PropertyMetadata with the default value to the Register function:

```<code> public static readonly DependencyProperty MyPropertyProperty =
        DependencyProperty.Register("MyProperty", typeof(double), typeof(MyControl),
        new PropertyMetadata(0.0));
</code>```

What is the default value for the dependency property if no default value is specified, either by not passing a PropertyMetadata or by using a PropertyMetadata constructor which doesn't specify a default value?

This page says

(For cases where a property registration does not specify metadata, a default PropertyMetadata is created with default values for that class.)

but I haven't found anywhere that describes what these default values are.

答:
The reference code below is what is called by the DependencyProperty when no default value was given by the PropertyMetadata.

It uses the standard default values in most cases (null for reference types, zeroed for value types), but for enums it uses the first enumerator instead of the enumerator with the value 0 (if they are different).

referencesource.microsoft.com

```<code>private static object GetDefaultValue(string name, System.Type propertyType, System.Type ownerType)
{
     if (name == null)
          throw new ArgumentNullException("name");
      if (name.Length == 0)
          throw new ArgumentException(SR.GetString(SR.Error_EmptyArgument), "name");
      if (propertyType == null)
          throw new ArgumentNullException("propertyType");
      if (ownerType == null)
           throw new ArgumentNullException("ownerType");

     object defaultValue = null;
     if (propertyType.IsValueType)
     {
         try
         {
             if (propertyType.IsEnum)
             {
                 Array values = Enum.GetValues(propertyType);
                 if (values.Length > 0)
                     defaultValue = values.GetValue(0);
                 else
                     defaultValue = Activator.CreateInstance(propertyType);
             }
             else
                 defaultValue = Activator.CreateInstance(propertyType);
         }
         catch
         {
         }
     }
     return defaultValue;
 }
</code>```

Body:
A WPF dependency property can be given a default value by passing a PropertyMetadata with the default value to the Register function:

 public static readonly DependencyProperty MyPropertyProperty =
        DependencyProperty.Register("MyProperty", typeof(double), typeof(MyControl),
        new PropertyMetadata(0.0));

What is the default value for the dependency property if no default value is specified, either by not passing a PropertyMetadata or by using a PropertyMetadata constructor which doesn't specify a default value?

This page says

(For cases where a property registration does not specify metadata, a default PropertyMetadata is created with default values for that class.)

but I haven't found anywhere that describes what these default values are.

Body:
The reference code below is what is called by the DependencyProperty when no default value was given by the PropertyMetadata.

It uses the standard default values in most cases (null for reference types, zeroed for value types), but for enums it uses the first enumerator instead of the enumerator with the value 0 (if they are different).

referencesource.microsoft.com

private static object GetDefaultValue(string name, System.Type propertyType, System.Type ownerType)
{
     if (name == null)
          throw new ArgumentNullException("name");
      if (name.Length == 0)
          throw new ArgumentException(SR.GetString(SR.Error_EmptyArgument), "name");
      if (propertyType == null)
          throw new ArgumentNullException("propertyType");
      if (ownerType == null)
           throw new ArgumentNullException("ownerType");

     object defaultValue = null;
     if (propertyType.IsValueType)
     {
         try
         {
             if (propertyType.IsEnum)
             {
                 Array values = Enum.GetValues(propertyType);
                 if (values.Length > 0)
                     defaultValue = values.GetValue(0);
                 else
                     defaultValue = Activator.CreateInstance(propertyType);
             }
             else
                 defaultValue = Activator.CreateInstance(propertyType);
         }
         catch
         {
         }
     }
     return defaultValue;
 }


问:
Run time error 1004 excel cannot find the text file to refresh this external range
I'm trying to convert tsv files in a folder to xlsx format by importing them as text file using Data=>From Text option via VBA.

During that encountered this error

Code:

Sub convert()

Dim CSVfolder As String, XlsFolder As String, fname As String, wBook As Workbook

CSVfolder = ActiveSheet.Range("B2").Value & "\"

fname = Dir(CSVfolder & "*.tsv")

Do While fname <> ""
    Workbooks.Add

    Set wBook = ActiveWorkbook

       With ActiveSheet.QueryTables.Add(Connection:="TEXT;" & fname, Destination:=Range("$A$1"))
        .Name = fname
        .FieldNames = True
        .RowNumbers = False
        .FillAdjacentFormulas = False
        .PreserveFormatting = True
        .RefreshOnFileOpen = False
        .RefreshStyle = xlInsertDeleteCells
        .SavePassword = False
        .SaveData = True
        .AdjustColumnWidth = True
        .RefreshPeriod = 0
        .TextFilePromptOnRefresh = False
        .TextFilePlatform = 65001
        .TextFileStartRow = 1
        .TextFileParseType = xlDelimited
        .TextFileTextQualifier = xlTextQualifierNone
        .TextFileConsecutiveDelimiter = False
        .TextFileTabDelimiter = True
        .TextFileSemicolonDelimiter = False
        .TextFileCommaDelimiter = False
        .TextFileSpaceDelimiter = False
        .TextFileColumnDataTypes = Array(1, 1, 1, 1, 1, 1, 1, 1, 1)
        .TextFileTrailingMinusNumbers = True
        .Refresh BackgroundQuery:=False
    End With

    wBook.Close False
    fname = Dir

 Loop
End Sub```

End Sub

Why i'm getting the error in .Refresh BackgroundQuery:=False ?

答:
The error is happening there as it's at the Refresh stage that it looks for the file.

The issue is that Fname won't contain the path.

Change your connection to:

```<code>With ActiveSheet.QueryTables.Add(Connection:="TEXT;" & CSVfolder & fname, Destination....
</code>```

Body:
I'm trying to convert tsv files in a folder to xlsx format by importing them as text file using Data=>From Text option via VBA.

During that encountered this error

Code:

Sub convert()

Dim CSVfolder As String, XlsFolder As String, fname As String, wBook As Workbook

CSVfolder = ActiveSheet.Range("B2").Value & "\"

fname = Dir(CSVfolder & "*.tsv")

Do While fname <> ""
    Workbooks.Add

    Set wBook = ActiveWorkbook

       With ActiveSheet.QueryTables.Add(Connection:="TEXT;" & fname, Destination:=Range("$A$1"))
        .Name = fname
        .FieldNames = True
        .RowNumbers = False
        .FillAdjacentFormulas = False
        .PreserveFormatting = True
        .RefreshOnFileOpen = False
        .RefreshStyle = xlInsertDeleteCells
        .SavePassword = False
        .SaveData = True
        .AdjustColumnWidth = True
        .RefreshPeriod = 0
        .TextFilePromptOnRefresh = False
        .TextFilePlatform = 65001
        .TextFileStartRow = 1
        .TextFileParseType = xlDelimited
        .TextFileTextQualifier = xlTextQualifierNone
        .TextFileConsecutiveDelimiter = False
        .TextFileTabDelimiter = True
        .TextFileSemicolonDelimiter = False
        .TextFileCommaDelimiter = False
        .TextFileSpaceDelimiter = False
        .TextFileColumnDataTypes = Array(1, 1, 1, 1, 1, 1, 1, 1, 1)
        .TextFileTrailingMinusNumbers = True
        .Refresh BackgroundQuery:=False
    End With

    wBook.Close False
    fname = Dir

 Loop
End Sub

End Sub

Why i'm getting the error in .Refresh BackgroundQuery:=False ?

Body:
The error is happening there as it's at the Refresh stage that it looks for the file.

The issue is that Fname won't contain the path.

Change your connection to:

With ActiveSheet.QueryTables.Add(Connection:="TEXT;" & CSVfolder & fname, Destination....


问:
How to send values to another method
I have these strings latRepr and LngRepr and I want to send them to the getDirecoes method. The GetDirecoes class is a AsyncTask.

This is how I start the method:

new GetDirecoes().execute();

So, how do I send those strings to here:

```<code>private class GetDirecoes extends AsyncTask<Void, Void, Void> implements Serializable {
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected Void doInBackground(Void... params) {}
</code>```

答:
```<code>new GetDirecoes().execute(latRepr,LngRepr);
</code>```

<p>this is how you can pass. </p>

```<code>private class GetDirecoes extends AsyncTask<String, Void, Void> implements Serializable {

@Override
protected void onPreExecute() {
    super.onPreExecute();
}

@Override
protected Void doInBackground(String... params) {
  String latRepr=params[0];
  String LngRepr=params[1];
 }
 }
</code>```

Title: How to send values to another method

Body:
I have these strings latRepr and LngRepr and I want to send them to the getDirecoes method. The GetDirecoes class is a AsyncTask.

This is how I start the method:

new GetDirecoes().execute();

So, how do I send those strings to here:

private class GetDirecoes extends AsyncTask<Void, Void, Void> implements Serializable {
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected Void doInBackground(Void... params) {}

Body:
new GetDirecoes().execute(latRepr,LngRepr);

this is how you can pass.

private class GetDirecoes extends AsyncTask<String, Void, Void> implements Serializable {

@Override
protected void onPreExecute() {
    super.onPreExecute();
}

@Override
protected Void doInBackground(String... params) {
  String latRepr=params[0];
  String LngRepr=params[1];
 }
 }


问:
How to use the native android widgets type definitions in nativescript?
I installed the platform definitions by adding "tns-platform-declarations": "^2.5.2"However, when I use the definitions in tns-platform-declarations/android.d.ts I can't access certain parts of the API. For instance, I can't access android.support.design.widget.Snackbar

```<code>  private snackbar: android.support.design.widget.Snackbar;
</code>```

because 'android.support' has no exported member 'design' what am I missing? When I go to code complete, I get only 'android.v4' and v4 does not contain a "design" module.

I also tried to import directly using the 'app' object as somebody suggested:

```<code>  import * as app from 'application';
  private snackbar = app.android.support.design.widget.Snackbar;
  // error: 'application' has no member 'android'
</code>```

With the above, I get code completion, but a red squiggly under android and tsc won't compile.

The only alternative I have found, is similar to this solution which isn't really a solution, as I can cheat like this, too:

```<code>declare var android:any;
</code>```

How do I actually use the TS definitions to compile and get code completion?

答:
There's an experimental type definitions generating tool for the android sdk, and android support libraries used in the project. Do a build/run with the --androidTypings flag to have d.ts' generated for you.

Those should contain the classes that you can't find in the platform-declarations, as they are generated against the versions used in your project.

tns build android --androidTypings

Body:
I installed the platform definitions by adding "tns-platform-declarations": "^2.5.2"However, when I use the definitions in tns-platform-declarations/android.d.ts I can't access certain parts of the API. For instance, I can't access android.support.design.widget.Snackbar

  private snackbar: android.support.design.widget.Snackbar;

because 'android.support' has no exported member 'design' what am I missing? When I go to code complete, I get only 'android.v4' and v4 does not contain a "design" module.

I also tried to import directly using the 'app' object as somebody suggested:

  import * as app from 'application';
  private snackbar = app.android.support.design.widget.Snackbar;
  // error: 'application' has no member 'android'

With the above, I get code completion, but a red squiggly under android and tsc won't compile.

The only alternative I have found, is similar to this solution which isn't really a solution, as I can cheat like this, too:

declare var android:any;

How do I actually use the TS definitions to compile and get code completion?


问:
Strange behaviour of preg_replace and sql select
```<code>      preg_match_all('#\<td id=\"(.*)\"  class=\"(.*)column(.*)\>(.*)\<\/td\>#i', $htmlcontent, $matches);
  $output = $htmlcontent;
  foreach ($matches[1] as $match) {
    echo $match.",";
    $ressql = "SELECT * FROM var WHERE varimportedindex = '".$match."' AND projectid = '".$pid."' AND sheetName = '".$sheetName."'";
    $result2 = $db->query("SELECT * FROM var WHERE varimportedindex = '".$match."' AND projectid = '".$pid."' AND sheetName = '".$sheetName."'");
    $rowoperation = $result2->fetch_assoc(); //<-- HERE
    #echo $rowvalue = $rowoperation['varvalue'];
    $output = preg_replace("#\<td id=\"(.*)\"  class=\"(.*)column(.*)\>(.*)\<\/td\>#i", "<td id='\\1'  class=\"\\2column\\3\"><input type='input' id='\\1' name='\\1' value='".$rowvalue."'>\\4</td>", $output);
  }
  echo $output;
</code>```

Ok, i can not find PROBLEM there, but if i deactivate replacement row HERE everything works fine. But when i activate it, replacement is not working anymore.

Can someone find the problem with these lines?

Thank you so much.

Regards,
Olaf

答:
```<code>// Olaf, please edit your question to display a sample input value for $htmlcontent
if(!preg_match_all('#\<td id=\"(.*)\"  class=\"(.*)column(.*)\>(.*)\<\/td\>#i',$htmlcontent,$matches)){
    echo "<div>No match</div>";
}else{
    $where_ext=implode("' OR `varimportedindex`='",$matches[1]);
    $query="SELECT * FROM `var` WHERE projectid='{$pid}' AND `sheetName`='{$sheetName}' AND (`varimportedindex`='{$where_ext}') ORDER BY varimportedindex;";  // only run one query
    if($result=$db->query($query)){
        $pattern="#\<td id=\"(.*)\"  class=\"(.*)column(.*)\>(.*)\<\/td\>#i";
        while($row=$result->fetch_assoc()){
            echo "<div>vii={$varimportedindex} & vv={$row["varvalue"]}</div>";
            // Olaf, please state what $varvalue's value might be
            $replace="<td id='\\1' class=\"\\2column\\3\"><input type='input' id='\\1' name='\\1' value='{$row["varvalue"]}'>\\4</td>";
            $output=preg_replace($pattern,$replace,$output);
        }
        echo "<div>{$output}</div>";
        // Olaf, please edit your question to display your expected result based on your sample $htmlcontent
    }else{
        echo "<div>{$db->error}</div>";
    }
}
</code>```

Body:
      preg_match_all('#\(.*)\<\/td\>#i', $htmlcontent, $matches);
  $output = $htmlcontent;
  foreach ($matches[1] as $match) {
    echo $match.",";
    $ressql = "SELECT * FROM var WHERE varimportedindex = '".$match."' AND projectid = '".$pid."' AND sheetName = '".$sheetName."'";
    $result2 = $db->query("SELECT * FROM var WHERE varimportedindex = '".$match."' AND projectid = '".$pid."' AND sheetName = '".$sheetName."'");
    $rowoperation = $result2->fetch_assoc(); //<-- HERE
    #echo $rowvalue = $rowoperation['varvalue'];
    $output = preg_replace("#\(.*)\<\/td\>#i", "<input type='input' id='\\1' name='\\1' value='".$rowvalue."'>\\4	", $output);
  }
  echo $output;

Ok, i can not find PROBLEM there, but if i deactivate replacement row HERE everything works fine. But when i activate it, replacement is not working anymore.

Can someone find the problem with these lines?

Thank you so much.

Regards,
Olaf


问:
Python cartesian product in nested dict
I know that in order to get the combination of an list of list the cartesian product must be used, but in my case I need the result to be a dictionary where combination subgroups are nested inside so I can use the result as a JSON for a recursive angular directive that shows elements nested in N depth levels.

Here is a data input example:

```<code>[
    [{"cluster_id":1,"id":1,"name":"A"}, {"cluster_id":1,"id":2,"name":"B"}, {"cluster_id":1,"id":3,"name":"C"}],
    [{"cluster_id":2,"id":1,"name":"D"}, {"cluster_id":2,"id":2,"name":"E"}, {"cluster_id":2,"id":3,"name":"F"}],
    [{"cluster_id":3,"id":1,"name":"G"}, {"cluster_id":3,"id":2,"name":"H"}, {"cluster_id":3,"id":3,"name":"I"}]
]
</code>```

That should result like this:

```<code>[{"cluster_id":1,"id":1,"name":"A", "subcluster": [
        {"cluster_id":2,"id":1,"name":"D", "subcluster": [
                {"cluster_id":3,"id":1,"name":"G"},
                {"cluster_id":3,"id":2,"name":"H"},
                {"cluster_id":3,"id":3,"name":"I"},
            ]
        },
        {"cluster_id":2,"id":2,"name":"E", "subcluster": [
                {"cluster_id":3,"id":1,"name":"G"},
                {"cluster_id":3,"id":2,"name":"H"},
                {"cluster_id":3,"id":3,"name":"I"},
            ]
        },
        {"cluster_id":2,"id":3,"name":"F", "subcluster": [
                {"cluster_id":3,"id":1,"name":"G"},
                {"cluster_id":3,"id":2,"name":"H"},
                {"cluster_id":3,"id":3,"name":"I"},
            ]
        }
    ]
},
{"cluster_id":1,"id":2,"name":"B", "subcluster": [
        {"cluster_id":2,"id":1,"name":"D", "subcluster": [
                {"cluster_id":3,"id":1,"name":"G"},
                {"cluster_id":3,"id":2,"name":"H"},
                {"cluster_id":3,"id":3,"name":"I"},
            ]
        },
        {"cluster_id":2,"id":2,"name":"E", "subcluster": [
                {"cluster_id":3,"id":1,"name":"G"},
                {"cluster_id":3,"id":2,"name":"H"},
                {"cluster_id":3,"id":3,"name":"I"},
            ]
        },
        {"cluster_id":2,"id":3,"name":"F", "subcluster": [
                {"cluster_id":3,"id":1,"name":"G"},
                {"cluster_id":3,"id":2,"name":"H"},
                {"cluster_id":3,"id":3,"name":"I"},
            ]
        }
    ]
},
{"cluster_id":1,"id":3,"name":"C", "subcluster": [
        {"cluster_id":2,"id":1,"name":"D", "subcluster": [
                {"cluster_id":3,"id":1,"name":"G"},
                {"cluster_id":3,"id":2,"name":"H"},
                {"cluster_id":3,"id":3,"name":"I"},
            ]
        },
        {"cluster_id":2,"id":2,"name":"E", "subcluster": [
                {"cluster_id":3,"id":1,"name":"G"},
                {"cluster_id":3,"id":2,"name":"H"},
                {"cluster_id":3,"id":3,"name":"I"},
            ]
        },
        {"cluster_id":2,"id":3,"name":"F", "subcluster": [
                {"cluster_id":3,"id":1,"name":"G"},
                {"cluster_id":3,"id":2,"name":"H"},
                {"cluster_id":3,"id":3,"name":"I"},
            ]
        }
    ]
}]
</code>```

I would like to know how to generate this output using Pyhton if possible, but any help is welcome.

答:
I was finally able to solve it with the following recursive function:</p>

```<code>def generate_tree(filters, depth):
    if depth == len(filters)-1:
        return filters[depth]
    else:
        return [{'name': i['name'], 'id': i['id'], 'cycle_cluster_id': i['cycle_cluster_id'], 'subcluster': generate_tree(filters, depth+1)} for i in filters[depth]]
</code>```

Title: Python cartesian product in nested dict

Body:
I know that in order to get the combination of an list of list the cartesian product must be used, but in my case I need the result to be a dictionary where combination subgroups are nested inside so I can use the result as a JSON for a recursive angular directive that shows elements nested in N depth levels.

Here is a data input example:

[
    [{"cluster_id":1,"id":1,"name":"A"}, {"cluster_id":1,"id":2,"name":"B"}, {"cluster_id":1,"id":3,"name":"C"}],
    [{"cluster_id":2,"id":1,"name":"D"}, {"cluster_id":2,"id":2,"name":"E"}, {"cluster_id":2,"id":3,"name":"F"}],
    [{"cluster_id":3,"id":1,"name":"G"}, {"cluster_id":3,"id":2,"name":"H"}, {"cluster_id":3,"id":3,"name":"I"}]
]

That should result like this:

[{"cluster_id":1,"id":1,"name":"A", "subcluster": [
        {"cluster_id":2,"id":1,"name":"D", "subcluster": [
                {"cluster_id":3,"id":1,"name":"G"},
                {"cluster_id":3,"id":2,"name":"H"},
                {"cluster_id":3,"id":3,"name":"I"},
            ]
        },
        {"cluster_id":2,"id":2,"name":"E", "subcluster": [
                {"cluster_id":3,"id":1,"name":"G"},
                {"cluster_id":3,"id":2,"name":"H"},
                {"cluster_id":3,"id":3,"name":"I"},
            ]
        },
        {"cluster_id":2,"id":3,"name":"F", "subcluster": [
                {"cluster_id":3,"id":1,"name":"G"},
                {"cluster_id":3,"id":2,"name":"H"},
                {"cluster_id":3,"id":3,"name":"I"},
            ]
        }
    ]
},
{"cluster_id":1,"id":2,"name":"B", "subcluster": [
        {"cluster_id":2,"id":1,"name":"D", "subcluster": [
                {"cluster_id":3,"id":1,"name":"G"},
                {"cluster_id":3,"id":2,"name":"H"},
                {"cluster_id":3,"id":3,"name":"I"},
            ]
        },
        {"cluster_id":2,"id":2,"name":"E", "subcluster": [
                {"cluster_id":3,"id":1,"name":"G"},
                {"cluster_id":3,"id":2,"name":"H"},
                {"cluster_id":3,"id":3,"name":"I"},
            ]
        },
        {"cluster_id":2,"id":3,"name":"F", "subcluster": [
                {"cluster_id":3,"id":1,"name":"G"},
                {"cluster_id":3,"id":2,"name":"H"},
                {"cluster_id":3,"id":3,"name":"I"},
            ]
        }
    ]
},
{"cluster_id":1,"id":3,"name":"C", "subcluster": [
        {"cluster_id":2,"id":1,"name":"D", "subcluster": [
                {"cluster_id":3,"id":1,"name":"G"},
                {"cluster_id":3,"id":2,"name":"H"},
                {"cluster_id":3,"id":3,"name":"I"},
            ]
        },
        {"cluster_id":2,"id":2,"name":"E", "subcluster": [
                {"cluster_id":3,"id":1,"name":"G"},
                {"cluster_id":3,"id":2,"name":"H"},
                {"cluster_id":3,"id":3,"name":"I"},
            ]
        },
        {"cluster_id":2,"id":3,"name":"F", "subcluster": [
                {"cluster_id":3,"id":1,"name":"G"},
                {"cluster_id":3,"id":2,"name":"H"},
                {"cluster_id":3,"id":3,"name":"I"},
            ]
        }
    ]
}]

I would like to know how to generate this output using Pyhton if possible, but any help is welcome.

Body:
I was finally able to solve it with the following recursive function:

def generate_tree(filters, depth):
    if depth == len(filters)-1:
        return filters[depth]
    else:
        return [{'name': i['name'], 'id': i['id'], 'cycle_cluster_id': i['cycle_cluster_id'], 'subcluster': generate_tree(filters, depth+1)} for i in filters[depth]]


问:
GWT replacement for java.net.URL
I have to replace the protocol part of a already existing url in GWT. The java.net package has a class which was build for exactly that purpose: URL. Sadly GWT does not emulate the java.net package.

How can I reassemble a url in GWT without creating my own parser? (I know about UrlBuilder, but UrlBuilder won't take an existing URL)

Example: I have a url in a string "http://myserver.com/somepath/file.html?param" and I want to replace the protocol part with "https".

答: Does Window.Location help you at all? You can read out the URL there, mod it and .assign() it back.

Title: GWT replacement for java.net.URL


答:
your first Void represent the type of params in doInBackground method.

So you can construct your AsyncTask as this :

```<code>private class GetDirecoes extends AsyncTask<String, Void, Void> implements Serializable {
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected Void doInBackground(String... params) {
        String lat = params[0];
        String lng = params[1];
        ...
    }
</code>```

and then call your AsyncTask like this :

```<code>new GetDirecoes().execute(latRepr, lngRepr);
</code>```

You will find more info there : https://developer.android.com/reference/android/os/AsyncTask.html

Title: How to send values to another method

Body:
your first Void represent the type of params in doInBackground method.

So you can construct your AsyncTask as this :

private class GetDirecoes extends AsyncTask<String, Void, Void> implements Serializable {
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected Void doInBackground(String... params) {
        String lat = params[0];
        String lng = params[1];
        ...
    }

and then call your AsyncTask like this :

new GetDirecoes().execute(latRepr, lngRepr);

You will find more info there : https://developer.android.com/reference/android/os/AsyncTask.html


问:
What is the proper annotation since @SpringApplicationConfiguration, @WebIntegration, is deprecated in Spring Boot Framework?
What is the proper annotation since @SpringApplicationConfiguration and @WebIntegration are deprecated as of Spring Boot Framework 1.4?  I'm trying to play around with unit testing.

答:
You should use this annotation: </p>

```<code>@ContextConfiguration(classes = main_class)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
You should use this annotation:

@ContextConfiguration(classes = main_class)


问:
Get Element ID - JavaScript
I know the data-id from the li element, but now i want the id value of the li element. How can I get this? Tried:

```<code> var id = $('li[data-id="KnSubject[StId]"]').id;
 console.log(id); // UNDEFINED
</code>```

Html Code:

```<code><li role="treeitem" data-jstree="{"icon" : "glyphicon glyphicon-pencil"}" data-id="KnSubject[StId]" data-values="null" aria-selected="true" aria-level="3" aria-labelledby="j1_4_anchor" id="j1_4" class="jstree-node  jstree-leaf"><i class="jstree-icon jstree-ocl" role="presentation"></i><a class="jstree-anchor jstree-clicked" href="#" tabindex="-1" id="j1_4_anchor"><i class="jstree-icon jstree-themeicon glyphicon glyphicon-pencil jstree-themeicon-custom" role="presentation"></i>Type dossieritem (StId)</a></li>
</code>```

答:
Just for completeness reasons:

```<code>$('li[data-id="KnSubject[StId]"]').get(0).id
</code>```

.get(0) retrieves the raw JS DOM Element.

Title: Get Element ID - JavaScript

Body:
I know the data-id from the li element, but now i want the id value of the li element. How can I get this? Tried:

 var id = $('li[data-id="KnSubject[StId]"]').id;
 console.log(id); // UNDEFINED

Html Code:

Type dossieritem (StId)

Body:
Just for completeness reasons:

$('li[data-id="KnSubject[StId]"]').get(0).id

.get(0) retrieves the raw JS DOM Element.


问:
Why doesn't clojure.test/run-all-tests find tests when run from a leiningen plugin?
I have a leiningen plugin consisting of the following function:

```<code>(defn vscode-test
  "Simple test run"
  [project & args]
  (leiningen.core.eval/eval-in-project project `(clojure.test/run-all-tests)))
</code>```

When I run this with lein vscode-test inside a Clojure project with a project.clj file clojure.test/run-all-tests runs, but it doesn't find any of the tests in the project. Note that lein test does run all the tests.

My project.clj is

```<code>(defproject repl_test "0.1.0-SNAPSHOT"
  :description "FIXME: write description"
  :url "http://example.com/FIXME"
  :license {:name "Eclipse Public License"
            :url "http://www.eclipse.org/legal/epl-v10.html"}
  :source-paths ["src" "test" "dev"]
  :plugins [[vscode-test "0.1.0-SNAPSHOT"]]
  :dependencies [[org.clojure/clojure "1.8.0"]
                 [org.clojure/core.async "0.3.442"]
                 [org.clojure/tools.namespace "0.2.11"]])
</code>```

Why doesn't the plugin see the tests?

答:
clojure.test/run-all-tests runs all currently defined tests. lein test first loads the test definitions in the test directory and then calls the clojure.test code.

In other words; you're not running any tests because the code you've provided doesn't load / require the namespaces containing your tests.

Body:
I have a leiningen plugin consisting of the following function:

(defn vscode-test
  "Simple test run"
  [project & args]
  (leiningen.core.eval/eval-in-project project `(clojure.test/run-all-tests)))

When I run this with lein vscode-test inside a Clojure project with a project.clj file clojure.test/run-all-tests runs, but it doesn't find any of the tests in the project. Note that lein test does run all the tests.

My project.clj is

(defproject repl_test "0.1.0-SNAPSHOT"
  :description "FIXME: write description"
  :url "http://example.com/FIXME"
  :license {:name "Eclipse Public License"
            :url "http://www.eclipse.org/legal/epl-v10.html"}
  :source-paths ["src" "test" "dev"]
  :plugins [[vscode-test "0.1.0-SNAPSHOT"]]
  :dependencies [[org.clojure/clojure "1.8.0"]
                 [org.clojure/core.async "0.3.442"]
                 [org.clojure/tools.namespace "0.2.11"]])

Why doesn't the plugin see the tests?


问:
odoo v9 enterprice saas connecting with xml-rpc
I was trying to access my saas online server via xml-rpc but i keep getting the following error:

File "/usr/lib/python2.7/ssl.py", line 405, in do_handshake    self._sslobj.do_handshake()ssl.SSLError: [Errno 1] _ssl.c:510: error:14077438:SSL routines:SSL23_GET_SERVER_HELLO:tlsv1 alert internal error

My simple xml-rpc script:

```<code>import xmlrpclib
url = 'https://myodoo.com'
db = 'myodoo'
username = 'admin'
password = 'admin'
common = xmlrpclib.ServerProxy('{}/xmlrpc/2/common'.format(url))
print common.version()
</code>```

And the interesting part is that if i use my saas online test-myodoo.odoo.com instance it works but on the main (myodoo.com) one i got the error above.

Do you guys have any idea what could be the cause of the error above?

Any help and suggestion would be highly appreciated.

Kind Regards,
Teewux

答:
This is possibly OPENSSL related issue i guess.
Upgrade your openssl to version: 1.0.1
Then your script should work :)

tried with installed openssl version=1.0.1 on system and yeahh it is working!

Body:
I was trying to access my saas online server via xml-rpc but i keep getting the following error:

File "/usr/lib/python2.7/ssl.py", line 405, in do_handshake    self._sslobj.do_handshake()ssl.SSLError: [Errno 1] _ssl.c:510: error:14077438:SSL routines:SSL23_GET_SERVER_HELLO:tlsv1 alert internal error

My simple xml-rpc script:

import xmlrpclib
url = 'https://myodoo.com'
db = 'myodoo'
username = 'admin'
password = 'admin'
common = xmlrpclib.ServerProxy('{}/xmlrpc/2/common'.format(url))
print common.version()

And the interesting part is that if i use my saas online test-myodoo.odoo.com instance it works but on the main (myodoo.com) one i got the error above.

Do you guys have any idea what could be the cause of the error above?

Any help and suggestion would be highly appreciated.

Kind Regards,
Teewux


问:
Console error Meteor server side
I started Meteor and Angular2.
On my server side (Meteor) I have a method file where I put some methods that I call in my client.
Obviously I need some meteor library so I import them like that :

```<code>import {Meteor} from 'meteor/meteor';
import {check, Match} from 'meteor/check';
</code>```

The thing is, in my console output I have the messages :

server/imports/methods/methods.ts (4, 22): Cannot find module 'meteor/meteor'.
server/imports/methods/methods.ts (8, 28): Cannot find module 'meteor/check'.

The line matches with the import.
Anyone has an idea to know where is this coming from ?

答:
This is just a TypeScript warning, it actually does not prevent your app from working, since Meteor still loads global variables anyway as of today.

To avoid these messages, you have to provide your TypeScript compiler with proper meteor typings, using a version that specifies the mentioned namespaces.

E.g. get @types/meteor@>=1.4.0, and make sure to tell TypeScript to use it.

```<code>$ meteor npm i --save-dev @types/meteor
</code>```

In your tsconfig.json:

{
    "compilerOptions": {
        "types": [
            "@types/meteor"
        ]
    }
}
```

<p>Or in <code>*.d.ts</code> file:</p>

<pre class="lang-ts prettyprint-override"><code>/// <reference types="@types/meteor" />
</code>```

Title: Console error Meteor server side

Body:
I started Meteor and Angular2.
On my server side (Meteor) I have a method file where I put some methods that I call in my client.
Obviously I need some meteor library so I import them like that :

import {Meteor} from 'meteor/meteor';
import {check, Match} from 'meteor/check';

The thing is, in my console output I have the messages :

server/imports/methods/methods.ts (4, 22): Cannot find module 'meteor/meteor'.
server/imports/methods/methods.ts (8, 28): Cannot find module 'meteor/check'.

The line matches with the import.
Anyone has an idea to know where is this coming from ?

Body:
This is just a TypeScript warning, it actually does not prevent your app from working, since Meteor still loads global variables anyway as of today.

To avoid these messages, you have to provide your TypeScript compiler with proper meteor typings, using a version that specifies the mentioned namespaces.

E.g. get @types/meteor@>=1.4.0, and make sure to tell TypeScript to use it.

$ meteor npm i --save-dev @types/meteor

In your tsconfig.json:

{
    "compilerOptions": {
        "types": [
            "@types/meteor"
        ]
    }
}

Or in *.d.ts file:

/// <reference types="@types/meteor" />


问:
Why does ref in C++0x not behave as expected?
I'm very sorry for my previous miswording. So I rephrased this question as follows:

The simplest C++0x code below should be not valid:

```<code>#include <functional>

template<class T_>
void f(T_ obj)
{
    Obj++; // OK that is as expected.
    static_cast<int&>(obj) = 2; // Though ugly, this is still OK.

    obj = 2; // However, this line will generate a compiler error
}

int main()
{
    int i = 1;
    f(std::tr1::ref(i));
}
</code>```

Who can tell me the exact semantics of ref?

答:
The cause of the error is that there is no suitable assignment operator to apply. The only candidate is this:

```<code>reference_wrapper& operator=(const reference_wrapper<T>& x);
</code>```

A reference_wrapper acts as a reference with the help of implicit conversion operators:

```<code>operator T& () const;
</code>```

However, an implicit conversion will not happen on the left side of the assignment operator.

If you are expecting this template to support reference_wrapper, perhaps you can work around in ways like this:

```<code>#include <functional>
#include <iostream>

template <class T>
T& get(T& value)
{
    return value;
}

template <class T>
T& get(std::reference_wrapper<T>& w)
{
    return w.get();
}

template<class T_>
void f(T_ obj)
{
    //obj = 2;
    get(obj) = 2;
}

int main()
{
    int i = 1;
    f(std::ref(i));
    std::cout << i << '\n';
    f(3.14); //at the same time, we want this also to work
}
</code>```

As to why reference_wrapper doesn't have an assignment operator for stored type, not sure. Boost's version doesn't have either, and they simply say that this class "usually allows the function templates to work on references unmodified". Guess this is just not one of those cases.

Body:
I'm very sorry for my previous miswording. So I rephrased this question as follows:

The simplest C++0x code below should be not valid:

#include <functional>

template<class T_>
void f(T_ obj)
{
    Obj++; // OK that is as expected.
    static_cast<int&>(obj) = 2; // Though ugly, this is still OK.

    obj = 2; // However, this line will generate a compiler error
}

int main()
{
    int i = 1;
    f(std::tr1::ref(i));
}

Who can tell me the exact semantics of ref?

Body:
The cause of the error is that there is no suitable assignment operator to apply. The only candidate is this:

reference_wrapper& operator=(const reference_wrapper<T>& x);

A reference_wrapper acts as a reference with the help of implicit conversion operators:

operator T& () const;

However, an implicit conversion will not happen on the left side of the assignment operator.

If you are expecting this template to support reference_wrapper, perhaps you can work around in ways like this:

#include <functional>
#include <iostream>

template <class T>
T& get(T& value)
{
    return value;
}

template <class T>
T& get(std::reference_wrapper<T>& w)
{
    return w.get();
}

template<class T_>
void f(T_ obj)
{
    //obj = 2;
    get(obj) = 2;
}

int main()
{
    int i = 1;
    f(std::ref(i));
    std::cout << i << '\n';
    f(3.14); //at the same time, we want this also to work
}

As to why reference_wrapper doesn't have an assignment operator for stored type, not sure. Boost's version doesn't have either, and they simply say that this class "usually allows the function templates to work on references unmodified". Guess this is just not one of those cases.


问:
set checkbox event checked periodic
I have checkbox and I want when it
 checked work periodically every 10 sec.  </p>

```<code>$("#cctv_ch").change(function () {
      if (this.checked) {
          alert("checked");
      }
});
</code>```

答:
use setInterval() and jquery is(':checked') its check every 10s is checked or not

setInterval(function(){
    var res = $("#cctv_ch").is(':checked');
if(res){
alert('checked')
}
else{

}

    },10000)```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" id="cctv_ch"></code>```

Title: set checkbox event checked periodic

Body:
I have checkbox and I want when it
 checked work periodically every 10 sec.

$("#cctv_ch").change(function () {
      if (this.checked) {
          alert("checked");
      }
});

Body:
use setInterval() and jquery is(':checked') its check every 10s is checked or not

setInterval(function(){
    var res = $("#cctv_ch").is(':checked');
if(res){
alert('checked')
}
else{

}

    },10000)

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" id="cctv_ch">


问:
Ruby - converting a string into hash with each character as key and index as value?
I am trying to transform a given string into a hash with each its character = key and index = value.

For example, if I have str = "hello", I would like it to transform into {"h"=>0, "e"=>1, "l"=>2, "l"=>3, "o"=>4}.

I created a method as such:

```<code>def map_indices(arr)
  arr.map.with_index {|el, index| [el, index]}.to_h
end
#=> map_indices('hello'.split(''))
#=> {"h"=>0, "e"=>1, "l"=>3, "o"=>4}
</code>```

The problem is it skips the first l. If I reverse the order of el and index:   arr.map.with_index {|el, index| [index, el]}.to_h, I get all the letters spelled out: {0=>"h", 1=>"e", 2=>"l", 3=>"l", 4=>"o"}

But when I invert it, I get the same hash that skips one of the l's.

```<code>map_indices('hello'.split('')).invert
#=> {"h"=>0, "e"=>1, "l"=>3, "o"=>4}
</code>```

Why is this behaving like such? How can I get it to print {"h"=>0, "e"=>1, "l"=>2, "l"=>3, "o"=>4}?

答:
I am new to Ruby and I am sure this can be refactored, but another alternative might be:

```<code>arr1 = "Hello".split(%r{\s*})

arr2 = []

for i in 0..arr1.size - 1
  arr2 << i
end

o = arr1.zip(arr2)

a_h = []

o.each do |i|
  a_h << Hash[*i]
end

p a_h.each_with_object({}) { |k, v| k.each { |kk,vv| (v[kk] ||= []) << vv } }
</code>```

=> {"H"=>[0], "e"=>[1], "l"=>[2, 3], "o"=>[4]}

Body:
I am trying to transform a given string into a hash with each its character = key and index = value.

For example, if I have str = "hello", I would like it to transform into {"h"=>0, "e"=>1, "l"=>2, "l"=>3, "o"=>4}.

I created a method as such:

def map_indices(arr)
  arr.map.with_index {|el, index| [el, index]}.to_h
end
#=> map_indices('hello'.split(''))
#=> {"h"=>0, "e"=>1, "l"=>3, "o"=>4}

The problem is it skips the first l. If I reverse the order of el and index:   arr.map.with_index {|el, index| [index, el]}.to_h, I get all the letters spelled out: {0=>"h", 1=>"e", 2=>"l", 3=>"l", 4=>"o"}

But when I invert it, I get the same hash that skips one of the l's.

map_indices('hello'.split('')).invert
#=> {"h"=>0, "e"=>1, "l"=>3, "o"=>4}

Why is this behaving like such? How can I get it to print {"h"=>0, "e"=>1, "l"=>2, "l"=>3, "o"=>4}?

Body:
I am new to Ruby and I am sure this can be refactored, but another alternative might be:

arr1 = "Hello".split(%r{\s*})

arr2 = []

for i in 0..arr1.size - 1
  arr2 << i
end

o = arr1.zip(arr2)

a_h = []

o.each do |i|
  a_h << Hash[*i]
end

p a_h.each_with_object({}) { |k, v| k.each { |kk,vv| (v[kk] ||= []) << vv } }

=> {"H"=>[0], "e"=>[1], "l"=>[2, 3], "o"=>[4]}


问:
sed and awk: how to replace a section of file to another content?
File a.html:

```<code><!--TEMPLATE: banner-->
blahblah
<!--TEMPLATE-END: banner-->
</code>```

I want to replace the middle text to some other text, how to achieve that using sed/awk/other tools?

答:
```<code>sed -r 'N;s/(<!--TEMPLATE: banner-->\n).*/\1lalala/'
</code>```

Input

```<code>$ cat sedbanner
<!--TEMPLATE: banner-->
blahblah
<!--TEMPLATE-END: banner-->
</code>```

Output

```<code>$ sed -r 'N;s/(<!--TEMPLATE: banner-->\n).*/\1lalala/' ./sedbanner
<!--TEMPLATE: banner-->
lalala
<!--TEMPLATE-END: banner-->
</code>```

If you like the output then replace sed -r with sed -ri to make it an in-place edit

Body:
File a.html:

blahblah

I want to replace the middle text to some other text, how to achieve that using sed/awk/other tools?

Body:
sed -r 'N;s/(<!--TEMPLATE: banner-->\n).*/\1lalala/'

Input

$ cat sedbanner
<!--TEMPLATE: banner-->
blahblah
<!--TEMPLATE-END: banner-->

Output

$ sed -r 'N;s/(<!--TEMPLATE: banner-->\n).*/\1lalala/' ./sedbanner
<!--TEMPLATE: banner-->
lalala
<!--TEMPLATE-END: banner-->

If you like the output then replace sed -r with sed -ri to make it an in-place edit


问:
How do I change the distance between text and underline in TimePicker?
There is currently 12 pixels between the text and underline for timepicker and I want to set it to 7 pixels.

```<code><materialDesign:TimePicker  SelectedTime="{Binding LabCase.AptTime}" />
</code>```

In resource dictionary I have made these changes to style:

```<code><Style TargetType="materialDesign:TimePicker" BasedOn="{StaticResource {x:Type materialDesign:TimePicker}}">
     <Setter Property="HorizontalAlignment" Value="Left" />
     <Setter Property="MinWidth" Value="200" />
     <Setter Property="materialDesign:HintAssist.Hint" Value="" />
     <Setter Property="Margin" Value="0,-3,0,0" />
</Style>
</code>```

Padding didn't work

```<code><Setter Property="Padding" Value="0,7,0,0"/>
</code>```

https://github.com/ButchersBoy/MaterialDesignInXamlToolkit/blob/master/MaterialDesignThemes.Wpf/Themes/MaterialDesignTheme.TimePicker.xaml

It seems like margin is the problem but I can't see to override it when I can override everything else

答:
Finished answer =</p>

```<code><Style x:Key="TimePicker" TargetType="{x:Type materialDesign:TimePicker}">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type materialDesign:TimePicker}">
                <ControlTemplate.Resources>
                    <ControlTemplate x:Key="TextBoxTemplate" TargetType="{x:Type TextBox}">
                        <Grid>
                            <ScrollViewer x:Name="PART_ContentHost" Focusable="false" HorizontalScrollBarVisibility="Hidden" VerticalScrollBarVisibility="Hidden" />
                            <materialDesign:SmartHint x:Name="Hint"
                                           FontSize="{TemplateBinding FontSize}"
                                           UseFloating="{Binding Path=(materialDesign:HintAssist.IsFloating), RelativeSource={RelativeSource TemplatedParent}}"
                                           Hint="{Binding Path=(materialDesign:HintAssist.Hint), RelativeSource={RelativeSource TemplatedParent}}"
                                           HintProxy="{Binding RelativeSource={RelativeSource TemplatedParent}, Converter={x:Static converters:HintProxyFabricConverter.Instance}}"
                                           HintOpacity="{Binding Path=(materialDesign:HintAssist.HintOpacity), RelativeSource={RelativeSource TemplatedParent}}"/>
                        </Grid>
                        <ControlTemplate.Triggers>
                            <MultiTrigger>
                                <MultiTrigger.Conditions>
                                    <Condition SourceName="Hint" Property="IsContentNullOrEmpty" Value="False" />
                                    <Condition Property="IsKeyboardFocused" Value="True" />
                                </MultiTrigger.Conditions>
                                <Setter TargetName="Hint" Property="Foreground" Value="{DynamicResource PrimaryHueMidBrush}" />
                                <Setter TargetName="Hint" Property="HintOpacity" Value="1" />
                            </MultiTrigger>
                        </ControlTemplate.Triggers>
                    </ControlTemplate>
                    <ControlTemplate x:Key="DropDownButtonTemplate" TargetType="{x:Type Button}">
                        <Grid Background="Transparent">
                            <VisualStateManager.VisualStateGroups>
                                <VisualStateGroup x:Name="CommonStates">
                                    <VisualStateGroup.Transitions>
                                        <VisualTransition GeneratedDuration="0"/>
                                        <VisualTransition GeneratedDuration="0:0:0.1" To="MouseOver"/>
                                        <VisualTransition GeneratedDuration="0:0:0.1" To="Pressed"/>
                                    </VisualStateGroup.Transitions>
                                    <VisualState x:Name="Normal"/>
                                    <VisualState x:Name="MouseOver"/>
                                    <VisualState x:Name="Pressed"/>
                                    <VisualState x:Name="Disabled"/>
                                </VisualStateGroup>
                            </VisualStateManager.VisualStateGroups>
                            <Viewbox>
                                <Canvas Width="24" Height="24">
                                    <Path Data="M12,20A8,8 0 0,0 20,12A8,8 0 0,0 12,4A8,8 0 0,0 4,12A8,8 0 0,0 12,20M12,2A10,10 0 0,1 22,12A10,10 0 0,1 12,22C6.47,22 2,17.5 2,12A10,10 0 0,1 12,2M12.5,7V12.25L17,14.92L16.25,16.15L11,13V7H12.5Z" Fill="{TemplateBinding Foreground}" />
                                </Canvas>
                            </Viewbox>
                        </Grid>
                    </ControlTemplate>
                </ControlTemplate.Resources>
                <Grid x:Name="TemplateRoot">
                    <Border BorderBrush="{TemplateBinding BorderBrush}"
                            BorderThickness="{TemplateBinding BorderThickness}"
                            Background="{TemplateBinding Background}"
                            Padding="0"
                            SnapsToDevicePixels="True">
                        <Grid>
                            <Grid.ColumnDefinitions>
                                <ColumnDefinition Width="*" />
                                <ColumnDefinition Width="Auto" />
                            </Grid.ColumnDefinitions>
                            <TextBox BorderThickness="0" x:Name="PART_TextBox"
                                     materialDesign:TextFieldAssist.TextBoxViewMargin=".5 0 0 0"
                                     Margin="0"
                                     Template="{StaticResource TextBoxTemplate}"
                                     />
                            <Button Grid.Column="1" Foreground="{TemplateBinding BorderBrush}" Focusable="False" HorizontalAlignment="Right" Margin="4 0 0 -3" Grid.Row="0" Padding="0"
                                    x:Name="PART_Button"
                                    Height="17"
                                    Template="{StaticResource DropDownButtonTemplate}" />
                            <Popup x:Name="PART_Popup" AllowsTransparency="True"
                                   Placement="Custom"
                                   CustomPopupPlacementCallback="{x:Static materialDesign:CustomPopupPlacementCallbackHelper.LargePopupCallback}"
                                   PlacementTarget="{Binding ElementName=PART_TextBox}" StaysOpen="False"
                                   PopupAnimation="Fade"/>
                        </Grid>
                    </Border>
                    <materialDesign:Underline x:Name="Underline" Visibility="{Binding Path=(materialDesign:TextFieldAssist.DecorationVisibility), RelativeSource={RelativeSource TemplatedParent}}"/>
                </Grid>
                <ControlTemplate.Triggers>
                    <Trigger Property="IsEnabled" Value="False">
                        <Setter Property="Opacity" TargetName="TemplateRoot" Value="0.56"/>
                    </Trigger>
                    <Trigger Property="IsMouseOver" Value="true">
                        <Setter Property="BorderBrush" Value="{DynamicResource PrimaryHueMidBrush}"/>
                    </Trigger>
                    <Trigger Property="IsKeyboardFocusWithin" Value="true">
                        <Setter Property="IsActive" TargetName="Underline" Value="True"/>
                        <Setter Property="BorderBrush"  Value="{DynamicResource PrimaryHueMidBrush}"/>
                    </Trigger>
                    <Trigger Property="Validation.HasError" Value="true">
                        <Setter Property="BorderBrush" Value="{DynamicResource ValidationErrorBrush}"/>
                        <Setter TargetName="Underline" Property="Background" Value="{DynamicResource ValidationErrorBrush}"/>
                    </Trigger>
                </ControlTemplate.Triggers>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>
</code>```

Body:
There is currently 12 pixels between the text and underline for timepicker and I want to set it to 7 pixels.

<materialDesign:TimePicker  SelectedTime="{Binding LabCase.AptTime}" />

In resource dictionary I have made these changes to style:

Padding didn't work

<Setter Property="Padding" Value="0,7,0,0"/>

https://github.com/ButchersBoy/MaterialDesignInXamlToolkit/blob/master/MaterialDesignThemes.Wpf/Themes/MaterialDesignTheme.TimePicker.xaml

It seems like margin is the problem but I can't see to override it when I can override everything else

Body:
Finished answer =

<Style x:Key="TimePicker" TargetType="{x:Type materialDesign:TimePicker}">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type materialDesign:TimePicker}">
                <ControlTemplate.Resources>
                    <ControlTemplate x:Key="TextBoxTemplate" TargetType="{x:Type TextBox}">
                        <Grid>
                            <ScrollViewer x:Name="PART_ContentHost" Focusable="false" HorizontalScrollBarVisibility="Hidden" VerticalScrollBarVisibility="Hidden" />
                            <materialDesign:SmartHint x:Name="Hint"
                                           FontSize="{TemplateBinding FontSize}"
                                           UseFloating="{Binding Path=(materialDesign:HintAssist.IsFloating), RelativeSource={RelativeSource TemplatedParent}}"
                                           Hint="{Binding Path=(materialDesign:HintAssist.Hint), RelativeSource={RelativeSource TemplatedParent}}"
                                           HintProxy="{Binding RelativeSource={RelativeSource TemplatedParent}, Converter={x:Static converters:HintProxyFabricConverter.Instance}}"
                                           HintOpacity="{Binding Path=(materialDesign:HintAssist.HintOpacity), RelativeSource={RelativeSource TemplatedParent}}"/>
                        </Grid>
                        <ControlTemplate.Triggers>
                            <MultiTrigger>
                                <MultiTrigger.Conditions>
                                    <Condition SourceName="Hint" Property="IsContentNullOrEmpty" Value="False" />
                                    <Condition Property="IsKeyboardFocused" Value="True" />
                                </MultiTrigger.Conditions>
                                <Setter TargetName="Hint" Property="Foreground" Value="{DynamicResource PrimaryHueMidBrush}" />
                                <Setter TargetName="Hint" Property="HintOpacity" Value="1" />
                            </MultiTrigger>
                        </ControlTemplate.Triggers>
                    </ControlTemplate>
                    <ControlTemplate x:Key="DropDownButtonTemplate" TargetType="{x:Type Button}">
                        <Grid Background="Transparent">
                            <VisualStateManager.VisualStateGroups>
                                <VisualStateGroup x:Name="CommonStates">
                                    <VisualStateGroup.Transitions>
                                        <VisualTransition GeneratedDuration="0"/>
                                        <VisualTransition GeneratedDuration="0:0:0.1" To="MouseOver"/>
                                        <VisualTransition GeneratedDuration="0:0:0.1" To="Pressed"/>
                                    </VisualStateGroup.Transitions>
                                    <VisualState x:Name="Normal"/>
                                    <VisualState x:Name="MouseOver"/>
                                    <VisualState x:Name="Pressed"/>
                                    <VisualState x:Name="Disabled"/>
                                </VisualStateGroup>
                            </VisualStateManager.VisualStateGroups>
                            <Viewbox>
                                <Canvas Width="24" Height="24">
                                    <Path Data="M12,20A8,8 0 0,0 20,12A8,8 0 0,0 12,4A8,8 0 0,0 4,12A8,8 0 0,0 12,20M12,2A10,10 0 0,1 22,12A10,10 0 0,1 12,22C6.47,22 2,17.5 2,12A10,10 0 0,1 12,2M12.5,7V12.25L17,14.92L16.25,16.15L11,13V7H12.5Z" Fill="{TemplateBinding Foreground}" />
                                </Canvas>
                            </Viewbox>
                        </Grid>
                    </ControlTemplate>
                </ControlTemplate.Resources>
                <Grid x:Name="TemplateRoot">
                    <Border BorderBrush="{TemplateBinding BorderBrush}"
                            BorderThickness="{TemplateBinding BorderThickness}"
                            Background="{TemplateBinding Background}"
                            Padding="0"
                            SnapsToDevicePixels="True">
                        <Grid>
                            <Grid.ColumnDefinitions>
                                <ColumnDefinition Width="*" />
                                <ColumnDefinition Width="Auto" />
                            </Grid.ColumnDefinitions>
                            <TextBox BorderThickness="0" x:Name="PART_TextBox"
                                     materialDesign:TextFieldAssist.TextBoxViewMargin=".5 0 0 0"
                                     Margin="0"
                                     Template="{StaticResource TextBoxTemplate}"
                                     />
                            <Button Grid.Column="1" Foreground="{TemplateBinding BorderBrush}" Focusable="False" HorizontalAlignment="Right" Margin="4 0 0 -3" Grid.Row="0" Padding="0"
                                    x:Name="PART_Button"
                                    Height="17"
                                    Template="{StaticResource DropDownButtonTemplate}" />
                            <Popup x:Name="PART_Popup" AllowsTransparency="True"
                                   Placement="Custom"
                                   CustomPopupPlacementCallback="{x:Static materialDesign:CustomPopupPlacementCallbackHelper.LargePopupCallback}"
                                   PlacementTarget="{Binding ElementName=PART_TextBox}" StaysOpen="False"
                                   PopupAnimation="Fade"/>
                        </Grid>
                    </Border>
                    <materialDesign:Underline x:Name="Underline" Visibility="{Binding Path=(materialDesign:TextFieldAssist.DecorationVisibility), RelativeSource={RelativeSource TemplatedParent}}"/>
                </Grid>
                <ControlTemplate.Triggers>
                    <Trigger Property="IsEnabled" Value="False">
                        <Setter Property="Opacity" TargetName="TemplateRoot" Value="0.56"/>
                    </Trigger>
                    <Trigger Property="IsMouseOver" Value="true">
                        <Setter Property="BorderBrush" Value="{DynamicResource PrimaryHueMidBrush}"/>
                    </Trigger>
                    <Trigger Property="IsKeyboardFocusWithin" Value="true">
                        <Setter Property="IsActive" TargetName="Underline" Value="True"/>
                        <Setter Property="BorderBrush"  Value="{DynamicResource PrimaryHueMidBrush}"/>
                    </Trigger>
                    <Trigger Property="Validation.HasError" Value="true">
                        <Setter Property="BorderBrush" Value="{DynamicResource ValidationErrorBrush}"/>
                        <Setter TargetName="Underline" Property="Background" Value="{DynamicResource ValidationErrorBrush}"/>
                    </Trigger>
                </ControlTemplate.Triggers>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>


问:
Showing all session data at once?
I have tried the following but it is giving me errors:

```<code>print_r($this->session->userdata());
</code>```

How can I show all session data in CodeIgniter?

答:
here is code:</p>

```<code><?php echo '```' . print_r($_SESSION, TRUE) . '```'; ?>
</code>```

Title: Showing all session data at once?

Body:
I have tried the following but it is giving me errors:

print_r($this->session->userdata());

How can I show all session data in CodeIgniter?

Body:
here is code:

<?php echo '<pre>' . print_r($_SESSION, TRUE) . '</pre>'; ?>


问:
Exception connecting Azure Sql Server and Spring Boot
I'm trying configure a app in Spring Boot to connect with Azure DataBase using com.microsoft.sqlserver.jdbc.SQLServerDriver driver.

This is my configuration:

```<code>spring.datasource.driverClassName=com.microsoft.sqlserver.jdbc.SQLServerDriver
spring.datasource.url=jdbc:sqlserver://hdonrns815.database.windows.net:1433;databaseName=code_dev
spring.datasource.username=user
spring.datasource.password=password
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.SQLServerDialect
spring.jpa.show-sql=true
</code>```

this is my SQL Server pom.xml configuration:

```<code><dependency>
   <groupId>com.microsoft.sqlserver</groupId>
   <artifactId>mssql-jdbc</artifactId>
</dependency>
</code>```

And this is the error:

```<code>com.microsoft.sqlserver.jdbc.SQLServerException: SQL Server did not return a response. The connection has been closed. ClientConnectionId:d7304f30-4c29-4258-ac9f-4409dee20fdd
</code>```

I can connect to the DB from Sql Server management.

I don't know what happend.

Thanks.

答:
Allow Azure Services to access Azure SQL.

Reference: https://learn.microsoft.com/en-us/azure/sql-database/sql-database-firewall-configure#connecting-from-azure

Body:
I'm trying configure a app in Spring Boot to connect with Azure DataBase using com.microsoft.sqlserver.jdbc.SQLServerDriver driver.

This is my configuration:

spring.datasource.driverClassName=com.microsoft.sqlserver.jdbc.SQLServerDriver
spring.datasource.url=jdbc:sqlserver://hdonrns815.database.windows.net:1433;databaseName=code_dev
spring.datasource.username=user
spring.datasource.password=password
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.SQLServerDialect
spring.jpa.show-sql=true

this is my SQL Server pom.xml configuration:

<dependency>
   <groupId>com.microsoft.sqlserver</groupId>
   <artifactId>mssql-jdbc</artifactId>
</dependency>

And this is the error:

com.microsoft.sqlserver.jdbc.SQLServerException: SQL Server did not return a response. The connection has been closed. ClientConnectionId:d7304f30-4c29-4258-ac9f-4409dee20fdd

I can connect to the DB from Sql Server management.

I don't know what happend.

Thanks.


问:
How to send values to another method
I have these strings latRepr and LngRepr and I want to send them to the getDirecoes method. The GetDirecoes class is a AsyncTask.

This is how I start the method:

new GetDirecoes().execute();

So, how do I send those strings to here:

```<code>private class GetDirecoes extends AsyncTask<Void, Void, Void> implements Serializable {
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected Void doInBackground(Void... params) {}
</code>```

答:
Your GetDirecoes is a class, not a method.

What you can do is create a constructor that takes in two String parameters, and store the variables as fields of that GetDircoes.

```<code>private class GetDirecoes {
    private String latRepr;
    private String LngRepr;
    public GetDirecoes(String latRepr, String LngRepr) {
          this.latRepr = latRepr;
          this.LngRepr = LngRepr;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected Void doInBackground(Void... params) {}
}
</code>```

Then you should be able to call new GetDirecoes(latRepr,LngRepr).execute();

Title: How to send values to another method

Body:
I have these strings latRepr and LngRepr and I want to send them to the getDirecoes method. The GetDirecoes class is a AsyncTask.

This is how I start the method:

new GetDirecoes().execute();

So, how do I send those strings to here:

private class GetDirecoes extends AsyncTask<Void, Void, Void> implements Serializable {
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected Void doInBackground(Void... params) {}

Body:
Your GetDirecoes is a class, not a method.

What you can do is create a constructor that takes in two String parameters, and store the variables as fields of that GetDircoes.

private class GetDirecoes {
    private String latRepr;
    private String LngRepr;
    public GetDirecoes(String latRepr, String LngRepr) {
          this.latRepr = latRepr;
          this.LngRepr = LngRepr;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected Void doInBackground(Void... params) {}
}

Then you should be able to call new GetDirecoes(latRepr,LngRepr).execute();


问:
Responsive templates and search bar
I am working on a pretty basic website and I have the search bar exactly how I want it to look. The problem is that I cannot get the search button to be responsive to different devices. On my iPhone 6, the button moves below the search bar and doesn't look right. Any thoughts on how I can get this better looking? I am new to responsive templates!

答:
Try clear fix:</p>

```<code><div class="bg-info clearfix">
      <button class="btn btn-secondary float-left">Example Button floated left</button>
      <button class="btn btn-secondary float-right">Example Button floated right</button>
    </div>
</code>```

Title: Responsive templates and search bar

Body:
Try clear fix:

<div class="bg-info clearfix">
      <button class="btn btn-secondary float-left">Example Button floated left</button>
      <button class="btn btn-secondary float-right">Example Button floated right</button>
    </div>


问:
How to prevent jquery event firing on a drop down list given an event is attached
I have a drop down list on my webpage with a jquery event attached to the change event. On change I use ajax to load a partial view in a popup window.

When the user uses the keyboard to navigate through the list of items but then clicks a link on another part of the page I momentarily see my popup window. This is obviously happening as when the user clicks a link elsewhere on the page, the change event is triggered on the drop down first.

Are there any neat solutions to solve this problem? A simple solution would be to fire the event on keyup but I don't want this functionality to happen.

Here's the change event snippet of code

```<code>$('#lookup').change(function()
{
    $.get(..//load template
</code>```

答: Did not find a solution that I liked or worked clean with my style so decided to catch trigger on both the 'change' and 'keyup' events so as to avoid this scenario.</p>

Body:
I have a drop down list on my webpage with a jquery event attached to the change event. On change I use ajax to load a partial view in a popup window.

When the user uses the keyboard to navigate through the list of items but then clicks a link on another part of the page I momentarily see my popup window. This is obviously happening as when the user clicks a link elsewhere on the page, the change event is triggered on the drop down first.

Are there any neat solutions to solve this problem? A simple solution would be to fire the event on keyup but I don't want this functionality to happen.

Here's the change event snippet of code

$('#lookup').change(function()
{
    $.get(..//load template


问:
django: access elements from another template
```<code>project/
|----app1/
     |----templates/
                   app1/
                   |----home.html
                   |----exchange.html
</code>```

I need to perform calculations on the home.html using javascript, but some data is stored in the table inside exchange.html, and I don't want to put them together under one page. how would I go about that. I am very new to python and django.

```<code>{% include "exchange.html" %}
</code>```

I tried this on home.html but it loads all the content which i don't need. can anybody help please.

```<code><table class="table table-hover">
        <caption>Exchange rate</caption>
        <thead>
            <tr>
                <th></th>
                <th>GBP</th>
                <th>EUR</th>
                <th>USD</th>
                <th>CAD</th>
                <th>AUD</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td>GBP</td>
                <td><input type="number" value="1" readonly></td>
                <td><input class="rate" type="number"></td>
                <td><input class="rate" type="number"></td>
                <td><input class="rate" type="number"></td>
                <td><input class="rate" type="number"></td>
            </tr>
            <tr>
                <td>EUR</td>
                <td><input class="rate" type="number"></td>
                <td><input type="number" value="1" readonly></td>
                <td><input class="rate" type="number"></td>
                <td><input class="rate" type="number"></td>
                <td><input class="rate" type="number"></td>
            </tr>
                <td>USD</td>
                <td><input class="rate" type="number"></td>
                <td><input class="rate" type="number"></td>
                <td><input type="number" value="1" readonly></td>
                <td><input class="rate" type="number"></td>
                <td><input class="rate" type="number"></td>
            <tr>
                <td>CAD</td>
                <td><input class="rate" type="number"></td>
                <td><input class="rate" type="number"></td>
                <td><input class="rate" type="number"></td>
                <td><input type="number" value="1" readonly></td>
                <td><input class="rate" type="number"></td>
            </tr>
            <tr>
                <td>AUD</td>
                <td><input class="rate" type="number"></td>
                <td><input class="rate" type="number"></td>
                <td><input class="rate" type="number"></td>
                <td><input class="rate" type="number"></td>
                <td><input type="number" value="1" readonly></td>
            </tr>
        </tbody>
    </table>
</code>```

I have this table in exchage.html where users can input the exchange rate, and I need to to do some calculation on home.html using the relevant rate.

答:
You want to create a small piece of html that contains only the information that you need, and put it in another file, calculations.html for example. You don't put all of the code from exchange.html in there, only the duplicated part.

Then use the include tag to add that HTML from both the exchange.html and home.html.

```<code>{% include calculations.html %}
</code>```

Body:
project/
|----app1/
     |----templates/
                   app1/
                   |----home.html
                   |----exchange.html

I need to perform calculations on the home.html using javascript, but some data is stored in the table inside exchange.html, and I don't want to put them together under one page. how would I go about that. I am very new to python and django.

{% include "exchange.html" %}

I tried this on home.html but it loads all the content which i don't need. can anybody help please.

Exchange rate

                GBP
                EUR
                USD
                CAD
                AUD

                GBP
                <input type="number" value="1" readonly>
                <input class="rate" type="number">
                <input class="rate" type="number">
                <input class="rate" type="number">
                <input class="rate" type="number">

                EUR
                <input class="rate" type="number">
                <input type="number" value="1" readonly>
                <input class="rate" type="number">
                <input class="rate" type="number">
                <input class="rate" type="number">

                USD
                <input class="rate" type="number">
                <input class="rate" type="number">
                <input type="number" value="1" readonly>
                <input class="rate" type="number">
                <input class="rate" type="number">

                CAD
                <input class="rate" type="number">
                <input class="rate" type="number">
                <input class="rate" type="number">
                <input type="number" value="1" readonly>
                <input class="rate" type="number">

                AUD
                <input class="rate" type="number">
                <input class="rate" type="number">
                <input class="rate" type="number">
                <input class="rate" type="number">
                <input type="number" value="1" readonly>

I have this table in exchage.html where users can input the exchange rate, and I need to to do some calculation on home.html using the relevant rate.

Body:
You want to create a small piece of html that contains only the information that you need, and put it in another file, calculations.html for example. You don't put all of the code from exchange.html in there, only the duplicated part.

Then use the include tag to add that HTML from both the exchange.html and home.html.

{% include calculations.html %}


问:
Singular Value Decomposition with LAPACK: problems with big matrices
I am using the C interface of LAPACK to compute the Singular Value Decomposition (SVD) of a matrix. To do so, I am using the routine dgesvd_.

I have created a simple C++ script which creates a random matrix (with M rows and N columns), and that computes its SVD. The code of this script is the following:

```<code>#include <iostream>
#include <random>
#include "lapacke.h"

#define M 150
#define N 3
#define MEAN 0
#define STD 0.25

int main(int argc, char *argv[])
{

    std::default_random_engine generator;
    std::normal_distribution<double> distribution(MEAN, STD);

    int m = M, n = N, lda = M, ldu = M, ldvt = N, info, lwork;
    double wkopt;
    double* work;
    double s[n], u[ldu * m], vt[ldvt * n], a[lda * n];

    for(unsigned int k = 0; k < (lda * n); k++){
        a[k] = distribution(generator);
    }

    lwork = -1;
    dgesvd_("All", "All", &m, &n, a, &lda, s, u, &ldu, vt, &ldvt, &wkopt, &lwork, &info);
    lwork = (int)wkopt;
    work = (double*) malloc(lwork * sizeof(double));
    dgesvd_("All", "All", &m, &n, a, &lda, s, u, &ldu, vt, &ldvt, work, &lwork, &info);

    if(info > 0){
        std::cerr<< "The algorithm computing SVD failed to converge\n"     ;
        exit(1);
    }

    free(work);

    std::cout<<"Singular values:\n";
    for(unsigned int k = 0; k < n; k++){
        std::cout<<s[k]<<" ";
    }
    std::cout<<"\n";
    return(0);
}
</code>```

A matrix with 150 rows and 3 columns seems to compute the SVD correctly. However, when the matrix has a bigger number of rows (for example, a matrix with 1500 rows and 3 columns), the execution of the compiled script raises this error: Segmentation fault (core dumped).

I tried to do something similar in a Python script:

```<code>import numpy as np
M = 1500
N = 3
MEAN = np.zeros(3)
STD = 0.25
result = np.linalg.svd(points)
</code>```

When I use Python, the singular values seems to be computed correctly whithout any error, although the NumPy method that I used is performed using the LAPACK routine dgesdd_ (I tried this and the same error is raised).

Does anyone know why is this error happening? Any help to solve the issue would be appreciated. Thanks.

Pd: I am using version 3.6.0 of lapacke, and Ubuntu 16.04 LTS.

答:
Allocating the matrices on the heap like this solves the problem:</p>

```<code>double* s = new double[n];
double* u = new double[ldu * m];
double* vt = new double[ldvt * n];
double* a = new double[lda * n];
</code>```

Body:
I am using the C interface of LAPACK to compute the Singular Value Decomposition (SVD) of a matrix. To do so, I am using the routine dgesvd_.

I have created a simple C++ script which creates a random matrix (with M rows and N columns), and that computes its SVD. The code of this script is the following:

#include <iostream>
#include <random>
#include "lapacke.h"

#define M 150
#define N 3
#define MEAN 0
#define STD 0.25

int main(int argc, char *argv[])
{

    std::default_random_engine generator;
    std::normal_distribution<double> distribution(MEAN, STD);

    int m = M, n = N, lda = M, ldu = M, ldvt = N, info, lwork;
    double wkopt;
    double* work;
    double s[n], u[ldu * m], vt[ldvt * n], a[lda * n];

    for(unsigned int k = 0; k < (lda * n); k++){
        a[k] = distribution(generator);
    }

    lwork = -1;
    dgesvd_("All", "All", &m, &n, a, &lda, s, u, &ldu, vt, &ldvt, &wkopt, &lwork, &info);
    lwork = (int)wkopt;
    work = (double*) malloc(lwork * sizeof(double));
    dgesvd_("All", "All", &m, &n, a, &lda, s, u, &ldu, vt, &ldvt, work, &lwork, &info);

    if(info > 0){
        std::cerr<< "The algorithm computing SVD failed to converge\n"     ;
        exit(1);
    }

    free(work);

    std::cout<<"Singular values:\n";
    for(unsigned int k = 0; k < n; k++){
        std::cout<<s[k]<<" ";
    }
    std::cout<<"\n";
    return(0);
}

A matrix with 150 rows and 3 columns seems to compute the SVD correctly. However, when the matrix has a bigger number of rows (for example, a matrix with 1500 rows and 3 columns), the execution of the compiled script raises this error: Segmentation fault (core dumped).

I tried to do something similar in a Python script:

import numpy as np
M = 1500
N = 3
MEAN = np.zeros(3)
STD = 0.25
result = np.linalg.svd(points)

When I use Python, the singular values seems to be computed correctly whithout any error, although the NumPy method that I used is performed using the LAPACK routine dgesdd_ (I tried this and the same error is raised).

Does anyone know why is this error happening? Any help to solve the issue would be appreciated. Thanks.

Pd: I am using version 3.6.0 of lapacke, and Ubuntu 16.04 LTS.

Body:
Allocating the matrices on the heap like this solves the problem:

double* s = new double[n];
double* u = new double[ldu * m];
double* vt = new double[ldvt * n];
double* a = new double[lda * n];


问:
Date to Correct Format (Ex. 01-MAR-2017 00:00:00)
Every time I've tried to change my date to a specific format, excel automatically autoformats to "3/1/2017 0:00" instead of 01-MAR-2017 00:00:00.

My code is the following:

```<code>objMasterDefectLog.Sheets(1).Range(strFrozenCustReqDateLoc).Offset(iCounter, 0).Value = Format(tempString, "dd-mmm-yyyy hh:mm:ss")
</code>```

Even if I convert tempString into a date, it still does not format correctly. I would rather not parse everything out if I don't have to.

答:
You need also to define the format of the cell after you set the value. Setting a .Value only sets a value of a cell but not the format. So you additionally need to format the cell:

```<code>objMasterDefectLog.Sheets(1).Range(strFrozenCustReqDateLoc).Offset(iCounter, 0).NumberFormat = "dd-mmm-yyyy hh:mm:ss"
</code>```

See also: Range.NumberFormat Property (Excel)

Body:
Every time I've tried to change my date to a specific format, excel automatically autoformats to "3/1/2017 0:00" instead of 01-MAR-2017 00:00:00.

My code is the following:

objMasterDefectLog.Sheets(1).Range(strFrozenCustReqDateLoc).Offset(iCounter, 0).Value = Format(tempString, "dd-mmm-yyyy hh:mm:ss")

Even if I convert tempString into a date, it still does not format correctly. I would rather not parse everything out if I don't have to.

Body:
You need also to define the format of the cell after you set the value. Setting a .Value only sets a value of a cell but not the format. So you additionally need to format the cell:

objMasterDefectLog.Sheets(1).Range(strFrozenCustReqDateLoc).Offset(iCounter, 0).NumberFormat = "dd-mmm-yyyy hh:mm:ss"

See also: Range.NumberFormat Property (Excel)


问:
ANTLR on a noisy data stream
I'm very new in the ANTLR world and I'm trying to figure out how can I use this parsing tool to interpret a set of "noisy" string. What I would like to achieve is the following.

let's take for example this phrase : It's 10PM and the Lazy CAT is currently SLEEPING heavily on the SOFA in front of the TV

What I would like to extract is CAT, SLEEPING and SOFA and have a grammar that match easily the following pattern : SUBJECT - VERB - INDIRECT OBJECT... where I could define

VERB : 'SLEEPING' | 'WALKING';

SUBJECT : 'CAT'|'DOG'|'BIRD';

INDIRECT_OBJECT : 'CAR'| 'SOFA';

etc.. I don't want to ends up with a permanent "NoViableException" as I can't describe all the possibilities around the language structure. I just want to tear apart useless words and just keep the one that are interesting.

 It's more like if I had a tokeniser and asked the parser "Ok, read the stream until you find a SUBJECT, then ignore the rest until you find a VERB, etc.."

I need to extract an organized structure in an un-organized set... For example, I would like to be able to interpret (I'm not judging the pertinence of this utterly basic and incorrect view of 'english grammar')

SUBJECT - VERB - INDIRECT OBJECT

INDIRECT OBJECT - SUBJECT - VERB

so I will parse sentences like

It's 10PM and the Lazy CAT is currently SLEEPING heavily on the SOFA in front of the TV

or

 It's 10PM and, on the SOFA in front of the TV,  the Lazy CAT is currently SLEEPING heavily

答:
You could create only a couple of lexer rules (the ones you posted, for example), and as a last lexer rule, you could match any character and skip() it:

```<code>VERB            : 'SLEEPING' | 'WALKING';
SUBJECT         : 'CAT'|'DOG'|'BIRD';
INDIRECT_OBJECT : 'CAR'| 'SOFA';
ANY             : . {skip();};
</code>```

The order is important here: the lexer tries to match tokens from top to bottom, so if it can't match any of the tokens VERB, SUBJECT or INDIRECT_OBJECT, it "falls through" to the ANY rule and skips this token. You can then use these parser rules to filter your input stream:

```<code>parse
  :  sentenceParts+ EOF
  ;

sentenceParts
  :  SUBJECT VERB INDIRECT_OBJECT
  ;
</code>```

which will parse the input text:

It's 10PM and the Lazy CAT is currently SLEEPING
  heavily on the SOFA in front of the TV. The DOG
  is WALKING on the SOFA.

as follows:

Title: ANTLR on a noisy data stream

Body:
You could create only a couple of lexer rules (the ones you posted, for example), and as a last lexer rule, you could match any character and skip() it:

VERB            : 'SLEEPING' | 'WALKING';
SUBJECT         : 'CAT'|'DOG'|'BIRD';
INDIRECT_OBJECT : 'CAR'| 'SOFA';
ANY             : . {skip();};

The order is important here: the lexer tries to match tokens from top to bottom, so if it can't match any of the tokens VERB, SUBJECT or INDIRECT_OBJECT, it "falls through" to the ANY rule and skips this token. You can then use these parser rules to filter your input stream:

parse
  :  sentenceParts+ EOF
  ;

sentenceParts
  :  SUBJECT VERB INDIRECT_OBJECT
  ;

which will parse the input text:

It's 10PM and the Lazy CAT is currently SLEEPING
  heavily on the SOFA in front of the TV. The DOG
  is WALKING on the SOFA.

as follows:


问:
Jekyll select current page url and change its class
I've been using Jekyll for a static site (so that its easy to maintain), and have been stuck at the following feature :

This is my link bar :

```<code><ul id="links">
    <li class="first"><a class="active" href="/">Home</a></li>
    <li><a href="./associate.html">Associate With Us</a></li>
    <li><a href="./media.html">Media</a></li>
    <li><a href="./clients.html">Clients</a></li>
    <li class="last"><a  href="./contact.html">Contact Us</a></li>
</ul>
</code>```

The active class handles the coloring. What I want is this class be applied by jekyll depending on some variable set using liquid/YAML.

Is there some easy way to go about this?

Since the bar is common to all the pages, it is now in the default layout. I could go around by using Javascript to detect the url, and do the highlighting but was wondering if there was any way of doing this in Jekyll.

答:
With Jekyll 3.4.3, this works :</p>

```<code><ul>
    {% for my_page in site.pages %}
        {% if my_page.title %}
            <li {% if my_page.url == page.url %} class="active" {% endif %}>
                <a href="{{ my_page.url | relative_url }}">{{ my_page.title | escape }}
                </a>
            </li>
        {% endif %} {% endfor %}
</ul>
</code>```

Body:
I've been using Jekyll for a static site (so that its easy to maintain), and have been stuck at the following feature :

This is my link bar :

Home

Associate With Us

Media

Clients

Contact Us

The active class handles the coloring. What I want is this class be applied by jekyll depending on some variable set using liquid/YAML.

Is there some easy way to go about this?

Since the bar is common to all the pages, it is now in the default layout. I could go around by using Javascript to detect the url, and do the highlighting but was wondering if there was any way of doing this in Jekyll.

Body:
With Jekyll 3.4.3, this works :

<ul>
    {% for my_page in site.pages %}
        {% if my_page.title %}
            <li {% if my_page.url == page.url %} class="active" {% endif %}>
                <a href="{{ my_page.url | relative_url }}">{{ my_page.title | escape }}
                </a>
            </li>
        {% endif %} {% endfor %}
</ul>