问:
Parse a file 2 lines at a time
Python beginner here. I have a file that looks like that (every field is \t separated):

```<code>chr1_1792868_SNP    Bcin01g04980    NON_SYNONYMOUS  NON_SYNONYMOUS[T](gene:Bcin01g04980|transcript:Bcin01g04980.1|P->S:225) ...
chr1_1792869_SNP    Bcin01g04980    NON_SYNONYMOUS  NON_SYNONYMOUS[T](gene:Bcin01g04980|transcript:Bcin01g04980.1|P->L:225) ...
chr2_19719_SNP  Bcin02g00005    SYNONYMOUS  SYNONYMOUS[A](gene:Bcin02g00005|transcript:Bcin02g00005.1)  ...
chr2_19811_SNP  Bcin02g00005    SYNONYMOUS  SYNONYMOUS[A](gene:Bcin02g00005|transcript:Bcin02g00005.1)  ...
chr2_20024_SNP  Bcin02g00005    NON_SYNONYMOUS  NON_SYNONYMOUS[C](gene:Bcin02g00005|transcript:Bcin02g00005.1|S->A:331)
chr2_20025_SNP  Bcin02g00005    SYNONYMOUS  SYNONYMOUS[A](gene:Bcin02g00005|transcript:Bcin02g00005.1)
</code>```

I would like to parse through the file and compare 2 lines at a time and compare a value between them.

So in this case, I woud like to compare the line 1 and 2, check if there is "SYNONYMOUS" in the 3rd field in each of them. If yes, I would do some thing, if no (this case) I move on to the 3rd and 4th line (where this time the comparison of the two "SYNONYMOUS" values be positive) and I would select the first value of the line to do some more thing (compare with another dictionnary).

I thought about doing something something like that:

```<code>with open ('file.txt') as mutmut_mutants:
    for line1 in mutmut_mutants:
        line2 = next(mutmut_mutants)
        print type(line1)
        print line2+ "line2"
</code>```

But the problem is that I am dealing with lines of string instead of element of list (on line/element in a big list). Dealing with a list seems easier than with strings/regex. I then thought of this:

```<code>with open ('file.txt') as mutmut_mutants:
    for i in csv.reader(mutmut_mutants, delimiter='\t'):
        for k,(l1, l2) in enumerate(zip(i[0::2], i[1::2])):
            print str(zip(i[0::2], i[1::2]))
</code>```

But I can't make it work (and I don't get the zip and the i[0::2] very clearly). What I'm trying to do is : compare lines 2 by 2, and if SYNONYMOUS in both lines get the first strings (chrX_XXXXX_SNP) of each line.

Any thought on how I should proceed?

答:
I think what you are looking for is the split method of the string. Loop through the file as you do in your first code example, and then split each line on tabs with:

```<code>ls = []
with open ('file.txt') as mutmut_mutants:
    for line1 in mutmut_mutants:
        fields = line1.split('\t')
        ls.append(fields)
</code>```

Splitting the strings on the tabs will give you a list of each field that is separated by tabs. You can then append it to a list and process it however you want. So for example to access the third field of the fourth line you would just do ls[3][2]. Hope this helps.

Title: Parse a file 2 lines at a time

Body:
Python beginner here. I have a file that looks like that (every field is \t separated):

chr1_1792868_SNP    Bcin01g04980    NON_SYNONYMOUS  NON_SYNONYMOUS[T](gene:Bcin01g04980|transcript:Bcin01g04980.1|P->S:225) ...
chr1_1792869_SNP    Bcin01g04980    NON_SYNONYMOUS  NON_SYNONYMOUS[T](gene:Bcin01g04980|transcript:Bcin01g04980.1|P->L:225) ...
chr2_19719_SNP  Bcin02g00005    SYNONYMOUS  SYNONYMOUS[A](gene:Bcin02g00005|transcript:Bcin02g00005.1)  ...
chr2_19811_SNP  Bcin02g00005    SYNONYMOUS  SYNONYMOUS[A](gene:Bcin02g00005|transcript:Bcin02g00005.1)  ...
chr2_20024_SNP  Bcin02g00005    NON_SYNONYMOUS  NON_SYNONYMOUS[C](gene:Bcin02g00005|transcript:Bcin02g00005.1|S->A:331)
chr2_20025_SNP  Bcin02g00005    SYNONYMOUS  SYNONYMOUS[A](gene:Bcin02g00005|transcript:Bcin02g00005.1)

I would like to parse through the file and compare 2 lines at a time and compare a value between them.

So in this case, I woud like to compare the line 1 and 2, check if there is "SYNONYMOUS" in the 3rd field in each of them. If yes, I would do some thing, if no (this case) I move on to the 3rd and 4th line (where this time the comparison of the two "SYNONYMOUS" values be positive) and I would select the first value of the line to do some more thing (compare with another dictionnary).

I thought about doing something something like that:

with open ('file.txt') as mutmut_mutants:
    for line1 in mutmut_mutants:
        line2 = next(mutmut_mutants)
        print type(line1)
        print line2+ "line2"

But the problem is that I am dealing with lines of string instead of element of list (on line/element in a big list). Dealing with a list seems easier than with strings/regex. I then thought of this:

with open ('file.txt') as mutmut_mutants:
    for i in csv.reader(mutmut_mutants, delimiter='\t'):
        for k,(l1, l2) in enumerate(zip(i[0::2], i[1::2])):
            print str(zip(i[0::2], i[1::2]))

But I can't make it work (and I don't get the zip and the i[0::2] very clearly). What I'm trying to do is : compare lines 2 by 2, and if SYNONYMOUS in both lines get the first strings (chrX_XXXXX_SNP) of each line.

Any thought on how I should proceed?

Body:
I think what you are looking for is the split method of the string. Loop through the file as you do in your first code example, and then split each line on tabs with:

ls = []
with open ('file.txt') as mutmut_mutants:
    for line1 in mutmut_mutants:
        fields = line1.split('\t')
        ls.append(fields)

Splitting the strings on the tabs will give you a list of each field that is separated by tabs. You can then append it to a list and process it however you want. So for example to access the third field of the fourth line you would just do ls[3][2]. Hope this helps.


来源: stackexchange

问:
Oracle - exchange partitions with a table
I try to create a table2 on Oracle 11g.2.0.3 with:

```<code>CREATE table2
LOGGING TABLESPACE TS_table1_2014 PCTFREE 10 INITRANS 1 STORAGE ( INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS UNLIMITED BUFFER_POOL DEFAULT ) NOCOMPRESS
as (select * from table1 where date_text <= '2015-12-31');
</code>```

and I have received error below when I try to exchange this table2 with a partitioned table3:

```<code>alter table table3 exchange partition partition_name WITH TABLE table2;

    Error report -
    SQL Error: ORA-14097: column type or size mismatch in ALTER TABLE EXCHANGE PARTITION
    14097. 00000 -  "column type or size mismatch in ALTER TABLE EXCHANGE PARTITION"
    *Cause:    The corresponding columns in the tables specified in the
               ALTER TABLE EXCHANGE PARTITION are of different type or size
    *Action:   Ensure that the two tables have the same number of columns
               with the same type and size.
</code>```

I have test diferences with query below:

```<code>Select a.COLUMN_NAME
  , a.DATA_TYPE, b.DATA_TYPE
  , a.data_length, b.data_length
  , a.data_precision, b.data_precision
  , a.data_scale, b.data_scale
  , a.nullable, b.nullable
from ALL_TAB_COLUMNS a
full outer join ALL_TAB_COLUMNS b on a.column_name=b.column_name
 and b.owner=user and b.table_name='&table2'
 where  a.owner=user and a.table_name='&table1'
 and (
    nvl(a.data_type,'#')!=nvl(b.data_type,'#')
    or nvl(a.data_length,-1)!=nvl(b.data_length,-1)
    or nvl(a.data_precision,-100)!=nvl(b.data_precision,-100)
    or nvl(a.data_scale,-100)!=nvl(b.data_scale,-100)
    or nvl(a.nullable,'#')!=nvl(b.nullable,'#')
   )
;
</code>```

Some differences resulted are in a column size. This syntax "create as select" didn't keep order and size for new table created.

How can I create table2 as select from table1 with force keep same size columns as primary table1 source?

Thanks!

答:
You need to use dbms_metadata package or query number of data dictionary views like all_tab_columns and etc to get metadata about existing table so you can construct correct sql for swap-table (used in exchange partition operation). CTAS does not transfer DEFAULT values for example and constraints except NOT NULL checks.
The best practice is to create/re-create/modify this table simultaneously with partitioned table. </p>

ContentLicense: CC BY-SA 3.0

Body:
I try to create a table2 on Oracle 11g.2.0.3 with:

CREATE table2
LOGGING TABLESPACE TS_table1_2014 PCTFREE 10 INITRANS 1 STORAGE ( INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS UNLIMITED BUFFER_POOL DEFAULT ) NOCOMPRESS
as (select * from table1 where date_text <= '2015-12-31');

and I have received error below when I try to exchange this table2 with a partitioned table3:

alter table table3 exchange partition partition_name WITH TABLE table2;

    Error report -
    SQL Error: ORA-14097: column type or size mismatch in ALTER TABLE EXCHANGE PARTITION
    14097. 00000 -  "column type or size mismatch in ALTER TABLE EXCHANGE PARTITION"
    *Cause:    The corresponding columns in the tables specified in the
               ALTER TABLE EXCHANGE PARTITION are of different type or size
    *Action:   Ensure that the two tables have the same number of columns
               with the same type and size.

I have test diferences with query below:

Select a.COLUMN_NAME
  , a.DATA_TYPE, b.DATA_TYPE
  , a.data_length, b.data_length
  , a.data_precision, b.data_precision
  , a.data_scale, b.data_scale
  , a.nullable, b.nullable
from ALL_TAB_COLUMNS a
full outer join ALL_TAB_COLUMNS b on a.column_name=b.column_name
 and b.owner=user and b.table_name='&table2'
 where  a.owner=user and a.table_name='&table1'
 and (
    nvl(a.data_type,'#')!=nvl(b.data_type,'#')
    or nvl(a.data_length,-1)!=nvl(b.data_length,-1)
    or nvl(a.data_precision,-100)!=nvl(b.data_precision,-100)
    or nvl(a.data_scale,-100)!=nvl(b.data_scale,-100)
    or nvl(a.nullable,'#')!=nvl(b.nullable,'#')
   )
;

Some differences resulted are in a column size. This syntax "create as select" didn't keep order and size for new table created.

How can I create table2 as select from table1 with force keep same size columns as primary table1 source?

Thanks!


问:
how to get data from one textbox to another textbox in dynamically generated html table?
below is my code. in that code when i enter 3 in txtbox and click copy.then same table will be generated 3 times. if i enter name and id in txtbox 1 and 2 and click get data then it will be set to txtbox 3 and 4.it works fine only with first table. the problem is it is not working with dynamic tables.help me!!
the code as follows,

function copytbl() {
  var i, j;
  j = document.getElementById("txtbox").value;
  for (i = 0; i < j - 1; i++) {
    var row = document.getElementById("tblbdy"); // find row to copy
    var table = document.getElementById("tbl"); // find table to append to
    var clone = row.cloneNode(true); // copy children too
    clone.id = "newID"; // change id or other attributes/contents
    table.appendChild(clone); // add new row to end of table
  }
}

function getdata() {
  document.getElementById("txtbox3").value = document.getElementById("txtbox1").value;
  document.getElementById("txtbox4").value = document.getElementById("txtbox2").value;
}

function isNumber(evt) {
  evt = (evt) ? evt : window.event;
  var charCode = (evt.which) ? evt.which : evt.keyCode;
  if (charCode > 31 && (charCode < 48 || charCode > 57)) {
    return false;
  }
  return true;
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>table,
td {
  border: 1px solid black;
  border-collapse: collapse;
  height: 90px;
  text-align: left;
}

tr.noBorder td {
  border-right-style: hidden;
  border-left-style: hidden;
}</code>```

<input type="text" id="txtbox" name="textbox" onkeypress="return isNumber(event)" />
<input type="reset" value="Reset">
<button type="button" onclick="copytbl()">COPY</button>

      Header

      Name
      Age
      Sex

        Name:

        <input type="text" id="txtbox1" name="textbox" />
 Id:

        <input type="text" id="txtbox2" name="textbox" onkeypress="return isNumber(event)" />

        <input type="reset" value="Reset">

        <input type="radio" name="gender" value="male" checked> Male

        <input type="radio" name="gender" value="female"> Female

      Footer

        <button type="button" onclick="getdata()">GET DATA</button>

 Name:

        <input type="text" id="txtbox3" name="textbox" />
 Id:

        <input type="text" id="txtbox4" name="textbox" />

```

thanks in advance

答:
You need to change the id's you are using into classes. Then parse the new tbody id you generate into the getdata Function

Demo https://jsfiddle.net/kplcode/bt5da5go/2/

```<code>function copytbl() {
  var i, j;
  j = document.getElementById("txtbox").value;
  for (i = 0; i < j - 1; i++) {
    var newId = "newID-"+(document.querySelectorAll('.tblbdy-ele').length+i);
    var row = document.getElementById("tblbdy"); // find row to copy
    var table = document.getElementById("tbl"); // find table to append to
    var clone = row.cloneNode(true); // copy children too
    clone.id = newId; // change id or other attributes/contents
    table.appendChild(clone); // add new row to end of table
    var getDataBtn = document.getElementById(newId).getElementsByClassName("getDataBtn")[0]
    getDataBtn.onclick = function() {
        getdata(newId);
    };
  }
}

function getdata(id) {
    var table = document.getElementById(id);
  document.getElementById(id).getElementsByClassName("txtbox3")[0].value = document.getElementById(id).getElementsByClassName("txtbox1")[0].value;
  document.getElementById(id).getElementsByClassName("txtbox4")[0].value = document.getElementById(id).getElementsByClassName("txtbox2")[0].value;
}

function isNumber(evt) {
  evt = (evt) ? evt : window.event;
  var charCode = (evt.which) ? evt.which : evt.keyCode;
  if (charCode > 31 && (charCode < 48 || charCode > 57)) {
    return false;
  }
  return true;
}
</code>```

Body:
below is my code. in that code when i enter 3 in txtbox and click copy.then same table will be generated 3 times. if i enter name and id in txtbox 1 and 2 and click get data then it will be set to txtbox 3 and 4.it works fine only with first table. the problem is it is not working with dynamic tables.help me!!
the code as follows,

function copytbl() {
  var i, j;
  j = document.getElementById("txtbox").value;
  for (i = 0; i < j - 1; i++) {
    var row = document.getElementById("tblbdy"); // find row to copy
    var table = document.getElementById("tbl"); // find table to append to
    var clone = row.cloneNode(true); // copy children too
    clone.id = "newID"; // change id or other attributes/contents
    table.appendChild(clone); // add new row to end of table
  }
}

function getdata() {
  document.getElementById("txtbox3").value = document.getElementById("txtbox1").value;
  document.getElementById("txtbox4").value = document.getElementById("txtbox2").value;
}

function isNumber(evt) {
  evt = (evt) ? evt : window.event;
  var charCode = (evt.which) ? evt.which : evt.keyCode;
  if (charCode > 31 && (charCode < 48 || charCode > 57)) {
    return false;
  }
  return true;
}

table,
td {
  border: 1px solid black;
  border-collapse: collapse;
  height: 90px;
  text-align: left;
}

tr.noBorder td {
  border-right-style: hidden;
  border-left-style: hidden;
}

<input type="text" id="txtbox" name="textbox" onkeypress="return isNumber(event)" />
<input type="reset" value="Reset">
<button type="button" onclick="copytbl()">COPY</button>

      Header

      Name
      Age
      Sex

        Name:

        <input type="text" id="txtbox1" name="textbox" />
 Id:

        <input type="text" id="txtbox2" name="textbox" onkeypress="return isNumber(event)" />

        <input type="reset" value="Reset">

        <input type="radio" name="gender" value="male" checked> Male

        <input type="radio" name="gender" value="female"> Female

      Footer

        <button type="button" onclick="getdata()">GET DATA</button>

 Name:

        <input type="text" id="txtbox3" name="textbox" />
 Id:

        <input type="text" id="txtbox4" name="textbox" />

thanks in advance

Body:
You need to change the id's you are using into classes. Then parse the new tbody id you generate into the getdata Function

Demo https://jsfiddle.net/kplcode/bt5da5go/2/

function copytbl() {
  var i, j;
  j = document.getElementById("txtbox").value;
  for (i = 0; i < j - 1; i++) {
    var newId = "newID-"+(document.querySelectorAll('.tblbdy-ele').length+i);
    var row = document.getElementById("tblbdy"); // find row to copy
    var table = document.getElementById("tbl"); // find table to append to
    var clone = row.cloneNode(true); // copy children too
    clone.id = newId; // change id or other attributes/contents
    table.appendChild(clone); // add new row to end of table
    var getDataBtn = document.getElementById(newId).getElementsByClassName("getDataBtn")[0]
    getDataBtn.onclick = function() {
        getdata(newId);
    };
  }
}

function getdata(id) {
    var table = document.getElementById(id);
  document.getElementById(id).getElementsByClassName("txtbox3")[0].value = document.getElementById(id).getElementsByClassName("txtbox1")[0].value;
  document.getElementById(id).getElementsByClassName("txtbox4")[0].value = document.getElementById(id).getElementsByClassName("txtbox2")[0].value;
}

function isNumber(evt) {
  evt = (evt) ? evt : window.event;
  var charCode = (evt.which) ? evt.which : evt.keyCode;
  if (charCode > 31 && (charCode < 48 || charCode > 57)) {
    return false;
  }
  return true;
}


问:
Elasticsearch installation : Error missing 'server' JVM at ...jvm.dll
After having downloaded elasticsearch and unzipped it following the steps in this link:

Install Elastic Search on Windows

I am receiving the following error:

```<code>Error: missing 'server' JVM at 'C:\Program Files (x86)\Java\jre1.8.0_131\bin\server\jvm.dll'.
Please install or use the JRE or JDK that contains these missing components.
</code>```

Note: I also had to install the JDK8 as suggested in this resolution

Should I change something in the .config file? Maybe this line?

```<code> # force the server VM (remove on 32-bit client JVMs)
 -server
</code>```

答:
I solved this by installing Java JRE 64-bit.

And then setting the environment variable JAVA_HOME to this version. (In my case C:\Program Files\Java\jre1.8.0_131)

Body:
After having downloaded elasticsearch and unzipped it following the steps in this link:

Install Elastic Search on Windows

I am receiving the following error:

Error: missing 'server' JVM at 'C:\Program Files (x86)\Java\jre1.8.0_131\bin\server\jvm.dll'.
Please install or use the JRE or JDK that contains these missing components.

Note: I also had to install the JDK8 as suggested in this resolution

Should I change something in the .config file? Maybe this line?

 # force the server VM (remove on 32-bit client JVMs)
 -server


问:
Sql Query results to CSV to a specified file path after stored procedure execution
I'm trying to execute a stored procedure (which i know works) in T-SQL that then gets those results into a CSV file and puts that file into a directory.  I'm not sure how to formulate that query, exactly though.  Here's what i've tried thus far to no avail:

```<code>EXECUTE CLR_ExportQueryToCSV @QueryCommand = 'execute databaseName.dbo.StoredProcedureName',
                          @FilePath = 'C:\Directory',
                          @FileName = '\FileToExport.csv',
                          @IncludeHeaders = 1
</code>```

I realize CLR_ExportQueryToCSV doesn't exist.  Is there any system stored procedure that will do what i'm wanting?

答:
Unfortunately there's no generic/supported method in SQL Server to do what you're asking.

If you're simply looking for a way to dump the results of a SQL query to CSV then I'd be more inclined to either write an SSIS package to do the job or a C# console app, either of which can be scheduled.

Here's an example in C#:

```<code>static void Main(string[] args)
{
    WriteQueryResultsToCsv(@"c:\SqlResults.csv",
        "MyDbConnectionStringName",
        "select * from MyTable where x > @x",
        new SqlParameter("@x", SqlDbType.Int) {Value = 1});
}

private static void WriteQueryResultsToCsv(string csvPath, string connectionStringName, string sql, params SqlParameter[] parameters)
{
    // Requires reference to System.Configuration
    var connectionString = ConfigurationManager.ConnectionStrings[connectionStringName].ConnectionString;

    using (var db = new SqlConnection(connectionString))
    using (var cmd = new SqlCommand(sql, db))
    {
        db.Open();
        cmd.Parameters.AddRange(parameters);

        using (var dr = cmd.ExecuteReader())
        using (var dw = new StreamWriter(csvPath))
        using (var csv = new CsvWriter(dw)) // Requires CsvHelper package from NuGet
        {
            // Write column headers
            for (var c = 0; c < dr.FieldCount; c++)
                csv.WriteField(dr.GetName(c));

            // Write data rows
            while (dr.Read())
            {
                csv.NextRecord();
                for (var c = 0; c < dr.FieldCount; c++)
                {
                    csv.WriteField(dr.GetValue(c).ToString());
                }
            }
        }
    }
}
</code>```

Body:
I'm trying to execute a stored procedure (which i know works) in T-SQL that then gets those results into a CSV file and puts that file into a directory.  I'm not sure how to formulate that query, exactly though.  Here's what i've tried thus far to no avail:

EXECUTE CLR_ExportQueryToCSV @QueryCommand = 'execute databaseName.dbo.StoredProcedureName',
                          @FilePath = 'C:\Directory',
                          @FileName = '\FileToExport.csv',
                          @IncludeHeaders = 1

I realize CLR_ExportQueryToCSV doesn't exist.  Is there any system stored procedure that will do what i'm wanting?

Body:
Unfortunately there's no generic/supported method in SQL Server to do what you're asking.

If you're simply looking for a way to dump the results of a SQL query to CSV then I'd be more inclined to either write an SSIS package to do the job or a C# console app, either of which can be scheduled.

Here's an example in C#:

static void Main(string[] args)
{
    WriteQueryResultsToCsv(@"c:\SqlResults.csv",
        "MyDbConnectionStringName",
        "select * from MyTable where x > @x",
        new SqlParameter("@x", SqlDbType.Int) {Value = 1});
}

private static void WriteQueryResultsToCsv(string csvPath, string connectionStringName, string sql, params SqlParameter[] parameters)
{
    // Requires reference to System.Configuration
    var connectionString = ConfigurationManager.ConnectionStrings[connectionStringName].ConnectionString;

    using (var db = new SqlConnection(connectionString))
    using (var cmd = new SqlCommand(sql, db))
    {
        db.Open();
        cmd.Parameters.AddRange(parameters);

        using (var dr = cmd.ExecuteReader())
        using (var dw = new StreamWriter(csvPath))
        using (var csv = new CsvWriter(dw)) // Requires CsvHelper package from NuGet
        {
            // Write column headers
            for (var c = 0; c < dr.FieldCount; c++)
                csv.WriteField(dr.GetName(c));

            // Write data rows
            while (dr.Read())
            {
                csv.NextRecord();
                for (var c = 0; c < dr.FieldCount; c++)
                {
                    csv.WriteField(dr.GetValue(c).ToString());
                }
            }
        }
    }
}


问:
Parsing through dataset
Using the Wordpress function wp_load_alloptions() I get a large array with all my sites option data. I selected a single portion of it that I need to globally get data from.

```<code>$all_options = wp_load_alloptions();
$my_options = array();
foreach( $all_options as $name => $value ) {
   if(stristr($name, 'options')) $my_options[$name] = $value;
}

echo '```';
   print_r($my_options['sl_options_options']);
echo '```';
</code>```

This returns:

```<code>s:15:"popup_form_text";s:0:"";s:14:"popup_form_URL";s:124:"url";s:15:"popup_form_open";s:2:"14";s:16:"popup_form_close";s:2:"23";s:15:"evergage_toggle";s:2:"On";s:12:"optim_toggle";s:2:"On";s:13:"soasta_toggle";s:3:"Off";}
</code>```

Is there a way I can parse through this data set to break out each individual part. Example of individual parts that go together:

```<code>s:12:"optim_toggle";s:2:"On";
</code>```

答:
Using unserialize I was able to get the data to print out like I wanted.

Serialized Array:

```<code>s:15:"popup_form_text";s:0:"";s:14:"popup_form_URL";s:124:"url";s:15:"popup_form_open";s:2:"14";s:16:"popup_form_close";s:2:"23";s:15:"evergage_toggle";s:2:"On";s:12:"optim_toggle";s:2:"On";s:13:"soasta_toggle";s:3:"Off";}
</code>```

using unserialize:

```<code>$unserialized_array = unserialize(s:15:"popup_form_text";s:0:"";s:14:"popup_form_URL";s:124:"url";s:15:"popup_form_open";s:2:"14";s:16:"popup_form_close";s:2:"23";s:15:"evergage_toggle";s:2:"On";s:12:"optim_toggle";s:2:"On";s:13:"soasta_toggle";s:3:"Off";});
</code>```

Display the new array:

```<code>print_r(unserialize($unserialized_array));
</code>```

Array now displays as:

```<code>Array(
   [popup_form_toggle] => On
   [popup_form_postids] => 51819, 36057, 36061, 36044, 44375, 36073, 48713, 17, 34612, 15908, 51054, 41102, 894
   [popup_form_text] =>
   [popup_form_URL] => https://home-c8.incontact.com/inContact/ChatClient/ChatClientPatron.aspx?poc=5ca78194-54ab-4833-8685-934a9d0305cc&bu=4594385
   [popup_form_open] => 14
   [popup_form_close] => 23
   [evergage_toggle] => On
   [optim_toggle] => On
   [soasta_toggle] => Off
)
</code>```

Title: Parsing through dataset

Body:
Using the Wordpress function wp_load_alloptions() I get a large array with all my sites option data. I selected a single portion of it that I need to globally get data from.

$all_options = wp_load_alloptions();
$my_options = array();
foreach( $all_options as $name => $value ) {
   if(stristr($name, 'options')) $my_options[$name] = $value;
}

echo '
';
   print_r($my_options['sl_options_options']);
echo '
';

This returns:

s:15:"popup_form_text";s:0:"";s:14:"popup_form_URL";s:124:"url";s:15:"popup_form_open";s:2:"14";s:16:"popup_form_close";s:2:"23";s:15:"evergage_toggle";s:2:"On";s:12:"optim_toggle";s:2:"On";s:13:"soasta_toggle";s:3:"Off";}

Is there a way I can parse through this data set to break out each individual part. Example of individual parts that go together:

s:12:"optim_toggle";s:2:"On";

Body:
Using unserialize I was able to get the data to print out like I wanted.

Serialized Array:

s:15:"popup_form_text";s:0:"";s:14:"popup_form_URL";s:124:"url";s:15:"popup_form_open";s:2:"14";s:16:"popup_form_close";s:2:"23";s:15:"evergage_toggle";s:2:"On";s:12:"optim_toggle";s:2:"On";s:13:"soasta_toggle";s:3:"Off";}

using unserialize:

$unserialized_array = unserialize(s:15:"popup_form_text";s:0:"";s:14:"popup_form_URL";s:124:"url";s:15:"popup_form_open";s:2:"14";s:16:"popup_form_close";s:2:"23";s:15:"evergage_toggle";s:2:"On";s:12:"optim_toggle";s:2:"On";s:13:"soasta_toggle";s:3:"Off";});

Display the new array:

print_r(unserialize($unserialized_array));

Array now displays as:

Array(
   [popup_form_toggle] => On
   [popup_form_postids] => 51819, 36057, 36061, 36044, 44375, 36073, 48713, 17, 34612, 15908, 51054, 41102, 894
   [popup_form_text] =>
   [popup_form_URL] => https://home-c8.incontact.com/inContact/ChatClient/ChatClientPatron.aspx?poc=5ca78194-54ab-4833-8685-934a9d0305cc&bu=4594385
   [popup_form_open] => 14
   [popup_form_close] => 23
   [evergage_toggle] => On
   [optim_toggle] => On
   [soasta_toggle] => Off
)


问:
Faster way to query Access table
I have two access tables, A and B:

```<code>Table A
Identifier BenefitBase    PlanNav
1        131368.46      131368.46
2        201768.8       201768.79
3        54057.46       54057.46
4        7397.51        7397.51
5        9931.4         9931.4
6        178200         178200
Table B
p      ValidityDate LockInAmount
1      2016-4       3.82
2      2016-4       19.97
3      2016-4       26.85
4      2016-6       34.95
</code>```

I just want to create a query which extracts records from B where the "p" ID is not found in table A.
My current code is:

```<code>SELECT B.p, B.ValidityDate, B.LockInAmount
FROM B
WHERE (((B.p) Not In (select Identifier from A)));
</code>```

Now to me, this code should work fine. However, because the tables are so large (B consists  of 486,000 rows (the "p"'s repeats in this table for different dates) whereas A consists of circa 19,000), whenever I run the query, access fills the query progress bar but freezes when near full.

Is there another way to do this?

Thanks

答:
You could also use a left join to do the same thing Gustav does. It's easier for me to read, and I believe that it will operate with the same execution plan.

```<code>select B.p, B.ValididtyDate, B.LockInAmount
from B
left join A on B.P = A.Identifier
where A.Identifier is null
</code>```

And add to that the indexes recommended by Erik up above. (That said, if P and Identifier are primary keys on your tables then they are already indexed and you don't need to add the indexes)

Title: Faster way to query Access table

Body:
I have two access tables, A and B:

Table A
Identifier BenefitBase    PlanNav
1        131368.46      131368.46
2        201768.8       201768.79
3        54057.46       54057.46
4        7397.51        7397.51
5        9931.4         9931.4
6        178200         178200
Table B
p      ValidityDate LockInAmount
1      2016-4       3.82
2      2016-4       19.97
3      2016-4       26.85
4      2016-6       34.95

I just want to create a query which extracts records from B where the "p" ID is not found in table A.
My current code is:

SELECT B.p, B.ValidityDate, B.LockInAmount
FROM B
WHERE (((B.p) Not In (select Identifier from A)));

Now to me, this code should work fine. However, because the tables are so large (B consists  of 486,000 rows (the "p"'s repeats in this table for different dates) whereas A consists of circa 19,000), whenever I run the query, access fills the query progress bar but freezes when near full.

Is there another way to do this?

Thanks

Body:
You could also use a left join to do the same thing Gustav does. It's easier for me to read, and I believe that it will operate with the same execution plan.

select B.p, B.ValididtyDate, B.LockInAmount
from B
left join A on B.P = A.Identifier
where A.Identifier is null

And add to that the indexes recommended by Erik up above. (That said, if P and Identifier are primary keys on your tables then they are already indexed and you don't need to add the indexes)


问:
Store pkl / binary in MetaData
I am writing a function that is supposed to store a text representation of a custom class object, cl
I have some code that writes to a file and takes the necessary information out of cl.

Now I need to go backwards, read the file and return a new instance of cl.  The problem is, the file doesn't keep all of the important parts of cl because for the purpose of this text document parts of it are unnecessary.
A .jpg file allows you to store meta data like shutter speed and location.   I would like to store the parts of cl that are not supposed to be in the text portion in the meta data of a .txt or .csv file.  Is there a way to explicitly write something to the metadata of a text file in Python?
Additionally, would it be possible to write the byte-code .pkl representation of the entire object in the metadata?

答:
Text files don't have meta data in the same way that a jpg file does.  A jpeg file is specifically designed to have ways of including meta data as extra structured information in the image.  Text files aren't: every character in the text file is generally displayed to the user.
Similarly, every thing in a CSV file is part of one cell in the table represented by the file.

That said, there are some things similar to text file metadata that have existed or exist over the years that might give you some ideas.  I don't think any of these is ideal, but I'll give some examples to give you an idea how complex the area of meta data is and what people have done in similar situations.

Some filesystems have meta data associated with each file that can be extended.  As an example, NTFS has streams; HFS and HFSplus have resource forks or other attributes; Linux has extended attributes on most of its filesystems.  You could potentially store your pickle information in those filesystem metadata.  There are disadvantages.  Some filesystems don't have this meta data.  Some tools for copying and manipulating files will not recognize (or intentionally strip) meta data.

You could have a .txt file and a .pcl file, where the .txt file contains your text representation and the .pkl file contained the other information.

Back in the day, some DOS programs would stop  reading a text file at a DOS EOF (decimal character 26).  I don't think anything behaves like that, but it's an example that there are file formats that  allowed you to end the file and then still have extra data that programs could use.

With a format like HTML or an actual spreadsheet instead of CSV, there are ways you could include things in meta data easily.

Title: Store pkl / binary in MetaData


问:
Swift 3 Attributed text solution
I have long string something like this:
"Q: what day is it?\nA: bla bla\nQ: what time is it?\nA: bla bla\nQ: what day is it?\nA: bla bla\nQ: what time is it?\nA: bla bla\n"

My problem is I need to show this text in textView but the question has to be orange color and answer has to be grey color. I get string from server and don't know what will I get but the format like this. How resolve this problem?

答:
If your string formate is like "Q: what day is it?\nA: bla bla\nQ: what time is it?\nA: bla bla\nQ: what day is it?\nA: bla bla\nQ: what time is it?\nA: bla bla\n" always then you can try below code:

```<code>var str = "Q: what day is it?\nA: bla bla\nQ: what time is it?\nA: bla bla\nQ: what day is it?\nA: bla bla\nQ: what time is it?\nA: bla bla\n"
let textView = UITextView(frame: CGRect(x: 20.0, y: 90.0, width: 250.0, height: 200.0))

    textView.backgroundColor = UIColor.white

    //separate it with \n
    let QuestionsAndAnswersArray = str.components(separatedBy: ["\n"])

    var finalStringArr = NSMutableAttributedString()

    for item in QuestionsAndAnswersArray {

        if item.characters.count > 0 {

            let firstChar = item[item.startIndex]

            //For Questions
            if firstChar == "Q" {

                //For new line after every character
                let QuestionStr = item + "\n"

                var myMutableString = NSMutableAttributedString()
                myMutableString = NSMutableAttributedString(string: QuestionStr)
                myMutableString.setAttributes([NSForegroundColorAttributeName : UIColor.red], range: NSRange(location:0,length:item.characters.count))
                finalStringArr.append(myMutableString)

            } else if firstChar == "A" {   //For Answers

                let answerStr = item + "\n"

                //For new line after every character
                var myMutableString = NSMutableAttributedString()
                myMutableString = NSMutableAttributedString(string: answerStr)
                myMutableString.setAttributes([NSForegroundColorAttributeName : UIColor.gray], range: NSRange(location:0,length:item.characters.count))
                finalStringArr.append(myMutableString)
            }
        }
    }

    textView.attributedText = finalStringArr
</code>```

And result will be:

Hope this will help.

Title: Swift 3 Attributed text solution

Body:
If your string formate is like "Q: what day is it?\nA: bla bla\nQ: what time is it?\nA: bla bla\nQ: what day is it?\nA: bla bla\nQ: what time is it?\nA: bla bla\n" always then you can try below code:

var str = "Q: what day is it?\nA: bla bla\nQ: what time is it?\nA: bla bla\nQ: what day is it?\nA: bla bla\nQ: what time is it?\nA: bla bla\n"
let textView = UITextView(frame: CGRect(x: 20.0, y: 90.0, width: 250.0, height: 200.0))

    textView.backgroundColor = UIColor.white

    //separate it with \n
    let QuestionsAndAnswersArray = str.components(separatedBy: ["\n"])

    var finalStringArr = NSMutableAttributedString()

    for item in QuestionsAndAnswersArray {

        if item.characters.count > 0 {

            let firstChar = item[item.startIndex]

            //For Questions
            if firstChar == "Q" {

                //For new line after every character
                let QuestionStr = item + "\n"

                var myMutableString = NSMutableAttributedString()
                myMutableString = NSMutableAttributedString(string: QuestionStr)
                myMutableString.setAttributes([NSForegroundColorAttributeName : UIColor.red], range: NSRange(location:0,length:item.characters.count))
                finalStringArr.append(myMutableString)

            } else if firstChar == "A" {   //For Answers

                let answerStr = item + "\n"

                //For new line after every character
                var myMutableString = NSMutableAttributedString()
                myMutableString = NSMutableAttributedString(string: answerStr)
                myMutableString.setAttributes([NSForegroundColorAttributeName : UIColor.gray], range: NSRange(location:0,length:item.characters.count))
                finalStringArr.append(myMutableString)
            }
        }
    }

    textView.attributedText = finalStringArr

And result will be:

Hope this will help.


问:
try to download file from asp.net server and using UpdatePanel, ProgressTemplate.. But not working
I Want to make some actions in my program.
While these actions run I want to tell the client that these actions are on process.
and after this process end, I want to send to the client this file for example Excel file.
I minimize my project to show exactly where the problem is

Now, this is my problem:
Button1 does not work, And Button2 works fine why? and how to fix that?
Maybe have better solution?

this is my aspx clint code :

```<code><form id="form1" runat="server">
    <asp:ScriptManager ID="ScriptManager1" runat="server"> </asp:ScriptManager>

    <asp:UpdatePanel ID="UpdatePanel1" runat="server">
        <ContentTemplate>
            <asp:Button ID="Button1" runat="server" Height="38px" onclick="Button1_Click" Text="Button" Width="167px" />
        </ContentTemplate>
    </asp:UpdatePanel>
    <asp:UpdateProgress ID="UpdateProgress1" runat="server">
        <ProgressTemplate>
            The report is creating please wait...
        </ProgressTemplate>
    </asp:UpdateProgress>

    <asp:Button ID="Button2" runat="server" OnClick="Button2_Click" Text="Button" />
</form>
</code>```

And next is my code behind

```<code>public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {}

        protected void Button1_Click(object sender, EventArgs e)
        {
            Thread.Sleep(5000);
            sendBackToUser();
        }

        protected void Button2_Click(object sender, EventArgs e)
        {
            sendBackToUser();
        }

        private void sendBackToUser()
        {
            FileInfo file = new FileInfo(@"C:\F\f.xlsx");
            if (file.Exists)
            {
                Response.Clear();
                Response.ClearHeaders();
                Response.ClearContent();
                Response.AddHeader("content-disposition", "attachment; filename=" + @"C:\F\f.xlsx");
                Response.AddHeader("Content-Type", "application/Excel");
                Response.ContentType = "application/vnd.xlsx";
                Response.AddHeader("Content-Length", file.Length.ToString());
                Response.WriteFile(file.FullName);
                Response.End();
            }
            else
            {
                Response.Write("This file does not exist.");
            }
        }
    }
</code>```

答:
While the UpdatePanel is a perfectly suitable solution to your previous question, you neglected to mention that you were trying to initiate a file download as well (you did say something about it in comments, but I didn't understand you clearly).

The problem with Button1 is because the UpdatePanel doesn't trigger a full PostBack of the page - it only posts back the content of the UpdatePanel.

As per this answer regarding UpdatePanels and downloads, you need to trigger a full PostBack:

Change your UpdatePanel like this:

```<code><asp:UpdatePanel runat="server" id="UpdatePanel1">
    <Triggers>
        <asp:PostBackTrigger ControlID="Button1" />
    </Triggers>
    <ContentTemplate>
    ...
    </ContentTemplate>
</asp:UpdatePanel>
</code>```

Body:
I Want to make some actions in my program.
While these actions run I want to tell the client that these actions are on process.
and after this process end, I want to send to the client this file for example Excel file.
I minimize my project to show exactly where the problem is

Now, this is my problem:
Button1 does not work, And Button2 works fine why? and how to fix that?
Maybe have better solution?

this is my aspx clint code :

<form id="form1" runat="server">
    <asp:ScriptManager ID="ScriptManager1" runat="server"> </asp:ScriptManager>

    <asp:UpdatePanel ID="UpdatePanel1" runat="server">
        <ContentTemplate>
            <asp:Button ID="Button1" runat="server" Height="38px" onclick="Button1_Click" Text="Button" Width="167px" />
        </ContentTemplate>
    </asp:UpdatePanel>
    <asp:UpdateProgress ID="UpdateProgress1" runat="server">
        <ProgressTemplate>
            The report is creating please wait...
        </ProgressTemplate>
    </asp:UpdateProgress>

    <asp:Button ID="Button2" runat="server" OnClick="Button2_Click" Text="Button" />
</form>

And next is my code behind

public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {}

        protected void Button1_Click(object sender, EventArgs e)
        {
            Thread.Sleep(5000);
            sendBackToUser();
        }

        protected void Button2_Click(object sender, EventArgs e)
        {
            sendBackToUser();
        }

        private void sendBackToUser()
        {
            FileInfo file = new FileInfo(@"C:\F\f.xlsx");
            if (file.Exists)
            {
                Response.Clear();
                Response.ClearHeaders();
                Response.ClearContent();
                Response.AddHeader("content-disposition", "attachment; filename=" + @"C:\F\f.xlsx");
                Response.AddHeader("Content-Type", "application/Excel");
                Response.ContentType = "application/vnd.xlsx";
                Response.AddHeader("Content-Length", file.Length.ToString());
                Response.WriteFile(file.FullName);
                Response.End();
            }
            else
            {
                Response.Write("This file does not exist.");
            }
        }
    }

Body:
While the UpdatePanel is a perfectly suitable solution to your previous question, you neglected to mention that you were trying to initiate a file download as well (you did say something about it in comments, but I didn't understand you clearly).

The problem with Button1 is because the UpdatePanel doesn't trigger a full PostBack of the page - it only posts back the content of the UpdatePanel.

As per this answer regarding UpdatePanels and downloads, you need to trigger a full PostBack:

Change your UpdatePanel like this:

<asp:UpdatePanel runat="server" id="UpdatePanel1">
    <Triggers>
        <asp:PostBackTrigger ControlID="Button1" />
    </Triggers>
    <ContentTemplate>
    ...
    </ContentTemplate>
</asp:UpdatePanel>


问:
SSIS: data types just don't get converted from string
That's my first experience in SSIS and I'm just going nuts: NOTHING WORKS.

(Don't be afraid of big post: most is just errors output.)

I've got two MS SQL DBs with same fields and I have to transfer from first one, where everything is in nvarchar(32) aka DT_WSTR, into second one, where types are different.

Data and its examples:

"Timestamp" is "datetime2(7)" in destination, and source looks like ISO 8601: 2013-12-19T00:00:00.000

"Value" is "real" numbers with scientific notation, test examples are: 17e+10, 17.14, 17.14e+5, 1715E+4, 1714

And four columns with just different ints (bigint, bigint, tinyint, int).

Now for what I've tried (warning for lots of quotations):

Derived Column. I used casts like "(DT_DBTIMESTAMP2,7)time" and "(DT_R4)value". Perhaps I'm using wrong types, but I strongly doubt: I googled it like a lot and most articles (like this) tells that I'm right.

Error: 0xC0049064 at Import from ODS to DWH, Derived Column [2]: An error occurred while attempting to perform a type cast.

Error: 0xC0209029 at Import from ODS to DWH, Derived Column [2]: SSIS Error Code DTS_E_INDUCEDTRANSFORMFAILUREONERROR.  The "Derived Column" failed because error code 0xC0049064 occurred, and the error row disposition on "Derived Column.Outputs[Derived Column Output].Columns[timestamp]" specifies failure on error. An error occurred on the specified object of the specified component.  There may be error messages posted before this with more information about the failure.

Error: 0xC0047022 at Import from ODS to DWH, SSIS.Pipeline: SSIS Error Code DTS_E_PROCESSINPUTFAILED.  The ProcessInput method on component "Derived Column" (2) failed with error code 0xC0209029 while processing input "Derived Column Input" (3). The identified component returned an error from the ProcessInput method. The error is specific to the component, but the error is fatal and will cause the Data Flow task to stop running.  There may be error messages posted before this with more information about the failure.
Error: 0xC02020C4 at Import from ODS to DWH, OLE DB Source [62]: The attempt to add a row to the Data Flow task buffer failed with error code 0xC0047020.

Error: 0xC0047038 at Import from ODS to DWH, SSIS.Pipeline: SSIS Error Code DTS_E_PRIMEOUTPUTFAILED.  The PrimeOutput method on OLE DB Source returned error code 0xC02020C4.  The component returned a failure code when the pipeline engine called PrimeOutput(). The meaning of the failure code is defined by the component, but the error is fatal and the pipeline stopped executing.  There may be error messages posted before this with more information about the failure.

Explicitly changing types in source (so they match destination) and connecting directly to destination.

Error: 0xC020901C at Direct, OLE DB Source [32]: There was an error with OLE DB Source.Outputs[OLE DB Source Output].Columns[time] on OLE DB Source.Outputs[OLE DB Source Output]. The column status returned was: "The value could not be converted because of a potential loss of data.".

Error: 0xC0209029 at Direct, OLE DB Source [32]: SSIS Error Code DTS_E_INDUCEDTRANSFORMFAILUREONERROR.  The "OLE DB Source.Outputs[OLE DB Source Output].Columns[time]" failed because error code 0xC0209072 occurred, and the error row disposition on "OLE DB Source.Outputs[OLE DB Source Output].Columns[time]" specifies failure on error. An error occurred on the specified object of the specified component.  There may be error messages posted before this with more information about the failure.

Error: 0xC0047038 at Direct, SSIS.Pipeline: SSIS Error Code DTS_E_PRIMEOUTPUTFAILED.  The PrimeOutput method on OLE DB Source returned error code 0xC0209029.  The component returned a failure code when the pipeline engine called PrimeOutput(). The meaning of the failure code is defined by the component, but the error is fatal and the pipeline stopped executing.  There may be error messages posted before this with more information about the failure.

Data Conversion. Same result: failure.

Error: 0xC02020C5 at Conversion, Data Conversion [2]: Data conversion failed while converting column "time" (74) to column "Copy of time" (11).  The conversion returned status value 2 and status text "The value could not be converted because of a potential loss of data.".

Error: 0xC0209029 at Conversion, Data Conversion [2]: SSIS Error Code DTS_E_INDUCEDTRANSFORMFAILUREONERROR.  The "Data Conversion.Outputs[Data Conversion Output].Columns[Copy of time]" failed because error code 0xC020907F occurred, and the error row disposition on "Data Conversion.Outputs[Data Conversion Output].Columns[Copy of time]" specifies failure on error. An error occurred on the specified object of the specified component.  There may be error messages posted before this with more information about the failure.

Error: 0xC0047022 at Conversion, SSIS.Pipeline: SSIS Error Code DTS_E_PROCESSINPUTFAILED.  The ProcessInput method on component "Data Conversion" (2) failed with error code 0xC0209029 while processing input "Data Conversion Input" (3). The identified component returned an error from the ProcessInput method. The error is specific to the component, but the error is fatal and will cause the Data Flow task to stop running.  There may be error messages posted before this with more information about the failure.

Error: 0xC02020C4 at Conversion, OLE DB Source [62]: The attempt to add a row to the Data Flow task buffer failed with error code 0xC0047020.

Error: 0xC0047038 at Conversion, SSIS.Pipeline: SSIS Error Code DTS_E_PRIMEOUTPUTFAILED.  The PrimeOutput method on OLE DB Source returned error code 0xC02020C4.  The component returned a failure code when the pipeline engine called PrimeOutput(). The meaning of the failure code is defined by the component, but the error is fatal and the pipeline stopped executing.  There may be error messages posted before this with more information about the failure.

So now I just ran out of tools and ideas how to do this: most instructions just say something like "map this to that and it will work". I'm struggling with this so hard and for so long I even created a StackExchange account for that. Any help appreciated. Cheers.

答:
New Answer to an old question -  but I just pulled all of my hair out trying to solve this error. Multiple error paths, data conversion, derived columns, etc. were not working. Two things solved this error:

I noticed that columns with Null Values were causing errors when dealing with Curreny (DT_CY) .
I finally solved this error by checking a little box "Retain null values from source as null values in the data flow" that was within the Flat File Source node. (why is this not selected by deafult!?)

Second, I was having a hard time converting dates to strings - an easy solution would be to do an update statement within a Execute SQL Task within the control flow.

For example: your database column is varchar or nvarchar. Your Source has data coming in a mm/dd/yyyy. No matter how many times you try wrestling with the above error, converting this into a string fails.

I solved this by loading the data (you can use a temp table if you'd like) and then converting this column using a SQL Query. I personally used:

```<code>update MY_TABLE_NAME
set [MY_DATE_COLUMN] = convert(varchar(8),CONVERT (datetime,[MY_DATE_COLUMN] ), 112)
where (FILTER_STATEMENT_TO_UPDATE_ONLY_WHAT_YOU_JUST_LOADED)
</code>```

Hopefully this can assist others who stumble upon this post.

Body:
New Answer to an old question -  but I just pulled all of my hair out trying to solve this error. Multiple error paths, data conversion, derived columns, etc. were not working. Two things solved this error:

I noticed that columns with Null Values were causing errors when dealing with Curreny (DT_CY) .
I finally solved this error by checking a little box "Retain null values from source as null values in the data flow" that was within the Flat File Source node. (why is this not selected by deafult!?)

Second, I was having a hard time converting dates to strings - an easy solution would be to do an update statement within a Execute SQL Task within the control flow.

For example: your database column is varchar or nvarchar. Your Source has data coming in a mm/dd/yyyy. No matter how many times you try wrestling with the above error, converting this into a string fails.

I solved this by loading the data (you can use a temp table if you'd like) and then converting this column using a SQL Query. I personally used:

update MY_TABLE_NAME
set [MY_DATE_COLUMN] = convert(varchar(8),CONVERT (datetime,[MY_DATE_COLUMN] ), 112)
where (FILTER_STATEMENT_TO_UPDATE_ONLY_WHAT_YOU_JUST_LOADED)

Hopefully this can assist others who stumble upon this post.


问:
Android case statement help
I'm trying to make my case statement open up a different class depending on what button is pressed. I got this working fine for one button but am unsure how to proceed for two buttons.

Heres my code so far:

```<code>public void onClick(View v) {
    switch (v.getId()) {
    case R.id.about_button:
        Intent i = new Intent(this, About.class);
        startActivity(i);
        break;
    case R.id.reminderList_button:
        Intent i = new Intent (this, ReminderListActivity.class);
        startActivity(i);
        break;

    }

}
</code>```

This gives an error because I'm reusing the local variable (i) - if anyone could let me know how to do this properly it would be much appreciated.

答:
Scope it.</p>

```<code>public void onClick(View v) {
    switch (v.getId()) {
    case R.id.about_button:
        {
            Intent i = new Intent(this, About.class);
            startActivity(i);
            break;
        }
    case R.id.reminderList_button:
        {
            Intent i = new Intent (this, ReminderListActivity.class);
            startActivity(i);
            break;
        }
    }
}
</code>```

ContentLicense: CC BY-SA 2.5

Title: Android case statement help

Body:
I'm trying to make my case statement open up a different class depending on what button is pressed. I got this working fine for one button but am unsure how to proceed for two buttons.

Heres my code so far:

public void onClick(View v) {
    switch (v.getId()) {
    case R.id.about_button:
        Intent i = new Intent(this, About.class);
        startActivity(i);
        break;
    case R.id.reminderList_button:
        Intent i = new Intent (this, ReminderListActivity.class);
        startActivity(i);
        break;

    }

}

This gives an error because I'm reusing the local variable (i) - if anyone could let me know how to do this properly it would be much appreciated.

Body:
Scope it.

public void onClick(View v) {
    switch (v.getId()) {
    case R.id.about_button:
        {
            Intent i = new Intent(this, About.class);
            startActivity(i);
            break;
        }
    case R.id.reminderList_button:
        {
            Intent i = new Intent (this, ReminderListActivity.class);
            startActivity(i);
            break;
        }
    }
}


问:
JavaScript Regexp between two strings without capturing first string
So I've gone through several examples and this seems like it should be very simple, however nothing seems to be working.

I'm pulling an html file from an email and trying to parse it out using REGEXP. The line that I'm working on currently is this:

```<code><br><br><b>STATUS:</b> Cancel<br><br><b>
</code>```

And throughout the whole document there are a bunch of those tags.

I'm using regexr.com to do my testing.

The closest expression I've been able to come up with is:

```<code>(?:STATUS:<\/b> )(.*?)(?=&lt)
</code>```

When I use that though, it returns:

```<code>STATUS:</b> Cancel
</code>```

I'm just trying to get the "Cancel". I've seen other questions answered with using lookbehind, but that's not supported in JavaScript. Is there a work around for this or am I approaching this the wrong way?

Edit

I'm trying to pull the information via a Google Web App.

What I've learned so far is it depends on how your browser displays the info if you see "<" or the actual "<" so to make it easier to see, I shifted my characters in the REGEXP to:

```<code>(?:<b>STATUS:<\/b>)(.*?)(?=<br>)
</code>```

The line I'm trying to interpret would be:

```<code><b>STATUS:</b> Cancel<br>
</code>```

Here's the code I'm using to run the REGEXP:

```<code>var re = new RegExp('(?:<b>STATUS:<\/b> )(.*?)(?=<br>)');
var status = messages[i].getBody().match(re)[1];
var child = XmlService.createElement('Status').setText(status);
root.addContent(child);
</code>```

When I try to run it, I get the same thing

```<code>match[0] = "<b>STATUS:</b> Cancel"
match[1] = "<b>STATUS:</b> Cancel"
</code>```

答:
Your regex seems to work, just extract match[1] :

let str = "

STATUS: Cancel

"

console.log( str.match(/(?:STATUS:<\/b> )(.*?)(?=&lt)/)[1]) // "Cancel"```

Body:
So I've gone through several examples and this seems like it should be very simple, however nothing seems to be working.

I'm pulling an html file from an email and trying to parse it out using REGEXP. The line that I'm working on currently is this:

STATUS: Cancel

And throughout the whole document there are a bunch of those tags.

I'm using regexr.com to do my testing.

The closest expression I've been able to come up with is:

(?:STATUS:<\/b> )(.*?)(?=&lt)

When I use that though, it returns:

STATUS: Cancel

I'm just trying to get the "Cancel". I've seen other questions answered with using lookbehind, but that's not supported in JavaScript. Is there a work around for this or am I approaching this the wrong way?

Edit

I'm trying to pull the information via a Google Web App.

What I've learned so far is it depends on how your browser displays the info if you see "<" or the actual "<" so to make it easier to see, I shifted my characters in the REGEXP to:

(?:STATUS:<\/b>)(.*?)(?=
)

The line I'm trying to interpret would be:

STATUS: Cancel

Here's the code I'm using to run the REGEXP:

var re = new RegExp('(?:STATUS:<\/b> )(.*?)(?=
)');
var status = messages[i].getBody().match(re)[1];
var child = XmlService.createElement('Status').setText(status);
root.addContent(child);

When I try to run it, I get the same thing

match[0] = "STATUS: Cancel"
match[1] = "STATUS: Cancel"

Body:
Your regex seems to work, just extract match[1] :

let str = "&lt;br&gt;&lt;br&gt;&lt;b&gt;STATUS:&lt;/b&gt; Cancel&lt;br&gt;&lt;br&gt;&lt;b&gt;"

console.log( str.match(/(?:STATUS:&lt;\/b&gt; )(.*?)(?=&lt)/)[1]) // "Cancel"


问:
Hbase Long Comparison Filter using Java Api
I am unable to compare a Long value in one of the column values of my HBase table. I am using java api. Below is the code snippet.I clearly have a value in the table which satisfies the filter.

I would also like to know what is lexicographical comparison and how would I perform long comparison.

Any direction on this greatly helpful.

Thanks in advance

```<code>FilterList list = new FilterList(FilterList.Operator.MUST_PASS_ALL);
SingleColumnValueFilter fil = new SingleColumnValueFilter(CF1_BYTE, VALUE_BYTE, CompareOp.LESS,new BinaryComparator(Bytes.toBytes(50)));
 Scan scan = new Scan();
 scan.addColumn(Bytes.toBytes("C1"),Bytes.toBytes("VALUE"));
    list.addFilter(fil);
    scan.setFilter(list);
    try {
        ResultScanner scanner = table.getScanner(scan);

        for(Result r : scanner){
            String VAL = Bytes.toString(r.getValue(Bytes.toBytes("C1"),Bytes.toBytes("VALUE")));
            count ++;
            if(count == 1000){
                break;
            }
            System.out.println(count +"  "+Bytes.toString(r.getRow()) + "        "+VAL );
        }
        scanner.close();

    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    try {
        table.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
</code>```

答:
According to  doc, you have to provide your own comparator which will deserialize Long values from Byte arrays. As I know default comparison is lexicographical. Regarding lexicographical comparison, you can find this post useful. And this post provide a clue how you can write the corresponding comparator.

Update:

```<code>import java.util.Comparator
import org.apache.hadoop.hbase.util.Bytes

class LongComparator implements Comparator<byte[]> {
    public int compare(byte[] left, byte[] right) {
        long leftLong = Bytes.toLong(left);
        long rightLong = Bytes.toLong(right);
        return Long.compare(leftLong, rightLong);
    }
}
</code>```

I suggest using HBase utils instead of guava since it may conflict with HBase guava dependencies.

Body:
I am unable to compare a Long value in one of the column values of my HBase table. I am using java api. Below is the code snippet.I clearly have a value in the table which satisfies the filter.

I would also like to know what is lexicographical comparison and how would I perform long comparison.

Any direction on this greatly helpful.

Thanks in advance

FilterList list = new FilterList(FilterList.Operator.MUST_PASS_ALL);
SingleColumnValueFilter fil = new SingleColumnValueFilter(CF1_BYTE, VALUE_BYTE, CompareOp.LESS,new BinaryComparator(Bytes.toBytes(50)));
 Scan scan = new Scan();
 scan.addColumn(Bytes.toBytes("C1"),Bytes.toBytes("VALUE"));
    list.addFilter(fil);
    scan.setFilter(list);
    try {
        ResultScanner scanner = table.getScanner(scan);

        for(Result r : scanner){
            String VAL = Bytes.toString(r.getValue(Bytes.toBytes("C1"),Bytes.toBytes("VALUE")));
            count ++;
            if(count == 1000){
                break;
            }
            System.out.println(count +"  "+Bytes.toString(r.getRow()) + "        "+VAL );
        }
        scanner.close();

    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    try {
        table.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

Body:
According to  doc, you have to provide your own comparator which will deserialize Long values from Byte arrays. As I know default comparison is lexicographical. Regarding lexicographical comparison, you can find this post useful. And this post provide a clue how you can write the corresponding comparator.

Update:

import java.util.Comparator
import org.apache.hadoop.hbase.util.Bytes

class LongComparator implements Comparator<byte[]> {
    public int compare(byte[] left, byte[] right) {
        long leftLong = Bytes.toLong(left);
        long rightLong = Bytes.toLong(right);
        return Long.compare(leftLong, rightLong);
    }
}

I suggest using HBase utils instead of guava since it may conflict with HBase guava dependencies.


问:
Selenium driver cannot be found in environment variables
I have been using selenium and everything has been working fine.

I have been including the chromedriver and others in my bin directory so that they can be picked up.

If I move them outside this location then I get the below error message.

Result Message:   OneTimeSetUp:
  OpenQA.Selenium.DriverServiceNotFoundException : The chromedriver.exe
  file does not exist in the current directory or in a directory on the
  PATH environment variable. The driver can be downloaded at
  http://chromedriver.storage.googleapis.com/index.html.

I understand this is due to it not finding the driver exe so the location is needed to be referenced.

If i put it in the code everything works fine

```<code>Instance = new ChromeDriver("C:\\drivers");
</code>```

The issue I have is that hard coded locations are bad practice and I don't want to do this as I am making a reusable component for others who may wish to store drivers on a 2nd HD.

I have added the location in to my path environment variables as the error above suggests however my code then cannot pick up the driver exe

Is there a step I am missing?

答: You could add the path to the web driver to your computer's PATH variable or have the path in a config file that you read from and where the path is set during installation. Oracle has a guide to adding to the PATH variable for java but if you replace java.exe with chromedriver.exe it should work out the same.</p>

Body:
I have been using selenium and everything has been working fine.

I have been including the chromedriver and others in my bin directory so that they can be picked up.

If I move them outside this location then I get the below error message.

Result Message:   OneTimeSetUp:
  OpenQA.Selenium.DriverServiceNotFoundException : The chromedriver.exe
  file does not exist in the current directory or in a directory on the
  PATH environment variable. The driver can be downloaded at
  http://chromedriver.storage.googleapis.com/index.html.

I understand this is due to it not finding the driver exe so the location is needed to be referenced.

If i put it in the code everything works fine

Instance = new ChromeDriver("C:\\drivers");

The issue I have is that hard coded locations are bad practice and I don't want to do this as I am making a reusable component for others who may wish to store drivers on a 2nd HD.

I have added the location in to my path environment variables as the error above suggests however my code then cannot pick up the driver exe

Is there a step I am missing?


答:
It will probably depend on the weight of your text file (you can have a really big number of SNPs ...).

If you can load the whole file in one variable:

```<code># Store everything in one variable - readlines() to have a list of lines
mutmut_mutants = open('file.txt', "r").readlines()

# The number of lines
n = len(mutmut_mutants)

# Loop two by two (end at n-1 or n-2)
for i in range(0, n-1, 2):
    first_line = mutmut_mutants[i]
    second_line = mutmut_mutants[i+1]

    # Split those lines (the separator is \t ?) and compare what's
    # inside, for example
    syn1 = first_line.split("\t")[2]
    syn2 = second_line.split("\t")[2]
    if syn1 == syn2 and syn1 == "SYNONYMOUS":
        # Do stuff
</code>```

If you can't load everything in one variable. Hum. I probably can't suggest something even remotely beautiful. Hope this helps.

Title: Parse a file 2 lines at a time

Body:
Python beginner here. I have a file that looks like that (every field is \t separated):

chr1_1792868_SNP    Bcin01g04980    NON_SYNONYMOUS  NON_SYNONYMOUS[T](gene:Bcin01g04980|transcript:Bcin01g04980.1|P->S:225) ...
chr1_1792869_SNP    Bcin01g04980    NON_SYNONYMOUS  NON_SYNONYMOUS[T](gene:Bcin01g04980|transcript:Bcin01g04980.1|P->L:225) ...
chr2_19719_SNP  Bcin02g00005    SYNONYMOUS  SYNONYMOUS[A](gene:Bcin02g00005|transcript:Bcin02g00005.1)  ...
chr2_19811_SNP  Bcin02g00005    SYNONYMOUS  SYNONYMOUS[A](gene:Bcin02g00005|transcript:Bcin02g00005.1)  ...
chr2_20024_SNP  Bcin02g00005    NON_SYNONYMOUS  NON_SYNONYMOUS[C](gene:Bcin02g00005|transcript:Bcin02g00005.1|S->A:331)
chr2_20025_SNP  Bcin02g00005    SYNONYMOUS  SYNONYMOUS[A](gene:Bcin02g00005|transcript:Bcin02g00005.1)

I would like to parse through the file and compare 2 lines at a time and compare a value between them.

So in this case, I woud like to compare the line 1 and 2, check if there is "SYNONYMOUS" in the 3rd field in each of them. If yes, I would do some thing, if no (this case) I move on to the 3rd and 4th line (where this time the comparison of the two "SYNONYMOUS" values be positive) and I would select the first value of the line to do some more thing (compare with another dictionnary).

I thought about doing something something like that:

with open ('file.txt') as mutmut_mutants:
    for line1 in mutmut_mutants:
        line2 = next(mutmut_mutants)
        print type(line1)
        print line2+ "line2"

But the problem is that I am dealing with lines of string instead of element of list (on line/element in a big list). Dealing with a list seems easier than with strings/regex. I then thought of this:

with open ('file.txt') as mutmut_mutants:
    for i in csv.reader(mutmut_mutants, delimiter='\t'):
        for k,(l1, l2) in enumerate(zip(i[0::2], i[1::2])):
            print str(zip(i[0::2], i[1::2]))

But I can't make it work (and I don't get the zip and the i[0::2] very clearly). What I'm trying to do is : compare lines 2 by 2, and if SYNONYMOUS in both lines get the first strings (chrX_XXXXX_SNP) of each line.

Any thought on how I should proceed?

Body:
It will probably depend on the weight of your text file (you can have a really big number of SNPs ...).

If you can load the whole file in one variable:

# Store everything in one variable - readlines() to have a list of lines
mutmut_mutants = open('file.txt', "r").readlines()

# The number of lines
n = len(mutmut_mutants)

# Loop two by two (end at n-1 or n-2)
for i in range(0, n-1, 2):
    first_line = mutmut_mutants[i]
    second_line = mutmut_mutants[i+1]

    # Split those lines (the separator is \t ?) and compare what's
    # inside, for example
    syn1 = first_line.split("\t")[2]
    syn2 = second_line.split("\t")[2]
    if syn1 == syn2 and syn1 == "SYNONYMOUS":
        # Do stuff

If you can't load everything in one variable. Hum. I probably can't suggest something even remotely beautiful. Hope this helps.


问:
ScriptManager is not declared - err msg

I've this class and it gave me an error name 'ScriptManager is not declared'

```<code>Public NotInheritable Class ResponseHelper
Private Sub New()
End Sub
Public Shared Sub Redirect(ByVal response As HttpResponse, ByVal url As String, ByVal target As String, ByVal windowFeatures As String)
    If ([String].IsNullOrEmpty(target) OrElse target.Equals("_self", StringComparison.OrdinalIgnoreCase)) AndAlso [String].IsNullOrEmpty(windowFeatures) Then
        response.Redirect(url)
    Else
        Dim page As Page = DirectCast(HttpContext.Current.Handler, Page)
        If page Is Nothing Then
            Throw New InvalidOperationException("Cannot redirect to new window outside Page context.")
        End If
        url = page.ResolveClientUrl(url)
        Dim script As String
        If Not [String].IsNullOrEmpty(windowFeatures) Then
            script = "window.open(""{0}"", ""{1}"", ""{2}"");"
        Else
            script = "window.open(""{0}"", ""{1}"");"
        End If
        script = [String].Format(script, url, target, windowFeatures)
        ScriptManager.RegisterStartupScript(page, GetType(Page), "Redirect", script, True)
    End If
End Sub
</code>```

End Class

This code from this link:

http://weblogs.asp.net/infinitiesloop/archive/2007/09/25/response-redirect-into-a-new-window-with-extension-methods.aspx

I've been 8 hours trying to figure out how to open a new page and send parameters to it. And found this code , and 6 hours trying to apply it but nothing.

Thanks.

答:
You need Ajax to be installed to access the Scriptmanager.
Use Page.ClientScript.RegisterStartupScript instead.
If you want a solution that works whether AJAX is available or not, have a look at this link. </p>

Title: ScriptManager is not declared - err msg

Body:
I've this class and it gave me an error name 'ScriptManager is not declared'

Public NotInheritable Class ResponseHelper
Private Sub New()
End Sub
Public Shared Sub Redirect(ByVal response As HttpResponse, ByVal url As String, ByVal target As String, ByVal windowFeatures As String)
    If ([String].IsNullOrEmpty(target) OrElse target.Equals("_self", StringComparison.OrdinalIgnoreCase)) AndAlso [String].IsNullOrEmpty(windowFeatures) Then
        response.Redirect(url)
    Else
        Dim page As Page = DirectCast(HttpContext.Current.Handler, Page)
        If page Is Nothing Then
            Throw New InvalidOperationException("Cannot redirect to new window outside Page context.")
        End If
        url = page.ResolveClientUrl(url)
        Dim script As String
        If Not [String].IsNullOrEmpty(windowFeatures) Then
            script = "window.open(""{0}"", ""{1}"", ""{2}"");"
        Else
            script = "window.open(""{0}"", ""{1}"");"
        End If
        script = [String].Format(script, url, target, windowFeatures)
        ScriptManager.RegisterStartupScript(page, GetType(Page), "Redirect", script, True)
    End If
End Sub

End Class

This code from this link:

http://weblogs.asp.net/infinitiesloop/archive/2007/09/25/response-redirect-into-a-new-window-with-extension-methods.aspx

I've been 8 hours trying to figure out how to open a new page and send parameters to it. And found this code , and 6 hours trying to apply it but nothing.

Thanks.


问:
Spring Integration, how to better describe validation component
My flow is defined like

```<code>return IntegrationFlows.from(
(MessageSourceSpec<?, ? extends MessageSource<?>>) Files.inboundAdapter(directory)
           .autoCreateDirectory(false)
           .patternFilter("*.xml"),
  e -> e.poller(Pollers.fixedDelay(1000)) ))
  .transform(new TransformXmlToMyDocument())
  .transform(new DataValidator())  // VALIDATOR
  .transform(new TransformMyDocumentToRabbitDomain())
  .channel(pubSubRabbitOutput)
  .get();
</code>```

Question is about the validator. Currently the validator I made as a "transparent" transformer that throws if data inside message are not valid. The whole flow will be wrapped in pseudo-transaction to handle error as suggested in "how to move processed file to another directory using Spring integration ftp inbound adapter".

But what would be the best way to include a logical validator in the Flow? Should it be transfomer or other kind of flow component?

答:
There is Filter EIP. And of course Spring Integration provides one on the matter.

You DataValidator must return true/false for the condition and there is throw-exception-on-rejection option for your discard logic:

```<code> .filter(new DataValidator(), "validate", e -> e.throwExceptionOnRejection(true))
</code>```

Body:
My flow is defined like

return IntegrationFlows.from(
(MessageSourceSpec<?, ? extends MessageSource<?>>) Files.inboundAdapter(directory)
           .autoCreateDirectory(false)
           .patternFilter("*.xml"),
  e -> e.poller(Pollers.fixedDelay(1000)) ))
  .transform(new TransformXmlToMyDocument())
  .transform(new DataValidator())  // VALIDATOR
  .transform(new TransformMyDocumentToRabbitDomain())
  .channel(pubSubRabbitOutput)
  .get();

Question is about the validator. Currently the validator I made as a "transparent" transformer that throws if data inside message are not valid. The whole flow will be wrapped in pseudo-transaction to handle error as suggested in "how to move processed file to another directory using Spring integration ftp inbound adapter".

But what would be the best way to include a logical validator in the Flow? Should it be transfomer or other kind of flow component?

Body:
There is Filter EIP. And of course Spring Integration provides one on the matter.

You DataValidator must return true/false for the condition and there is throw-exception-on-rejection option for your discard logic:

 .filter(new DataValidator(), "validate", e -> e.throwExceptionOnRejection(true))


问:
macro variable in data frame name using r
I would like to use the concept of macro variable from SAS in r but cannot seem to find the right code.
It would normally look like this in SAS where I change the name once and it replicates many places.

```<code>%LET CITY=NewYork;
Query_&NAME_V01 <- &NAME[,1:3]
Query_&NAME_V01 <- &NAME[1:10,]
</code>```

I tried using the quote and noquote function but I always end up with the this error message: target of assignment expands to non-language object.

答:
I recently had to learn some SAS and trust me I cannot think to something like SAS macros in R. At least not something that it is as easy to use.
But trust me, R is much more powerful, you have just to think like R (and most of programming languages nowadays) and not like SAS.

Put your data in a list and use a for loop here an example that print the colnames  of dataframe(cat is just the print function)

```<code>example<-list(airquality,iris,mtcars)
for(i in 1:length(example)){
  cat(colnames(example[[i]]),"\n")
}
</code>```

You could use non standard evaluation to imitate SAS behaviour, here a reference http://adv-r.had.co.nz/Computing-on-the-language.html but trust me It is something that it does not fit to a newbie. Even R experienced users struggle with this.

Body:
I would like to use the concept of macro variable from SAS in r but cannot seem to find the right code.
It would normally look like this in SAS where I change the name once and it replicates many places.

%LET CITY=NewYork;
Query_&NAME_V01 <- &NAME[,1:3]
Query_&NAME_V01 <- &NAME[1:10,]

I tried using the quote and noquote function but I always end up with the this error message: target of assignment expands to non-language object.

Body:
I recently had to learn some SAS and trust me I cannot think to something like SAS macros in R. At least not something that it is as easy to use.
But trust me, R is much more powerful, you have just to think like R (and most of programming languages nowadays) and not like SAS.

Put your data in a list and use a for loop here an example that print the colnames  of dataframe(cat is just the print function)

example<-list(airquality,iris,mtcars)
for(i in 1:length(example)){
  cat(colnames(example[[i]]),"\n")
}

You could use non standard evaluation to imitate SAS behaviour, here a reference http://adv-r.had.co.nz/Computing-on-the-language.html but trust me It is something that it does not fit to a newbie. Even R experienced users struggle with this.


问:
Cannot Index on array of int RavenDB
I'm trying to query on a property of type IEnumerable int to find all documents in the collection that contain an integer value in this property.

I've tried to accomplish this with an index on the property to return a list of id's which satisfy the query. I am projecting the id's in the query however I'm getting a list of id 0's.

Index

```<code>public class Merchants_CategoryId : AbstractIndexCreationTask<Merchant>
{
    public class Result
    {
        public int MerchantId { get; set; }
        public IEnumerable<int> CategoryIds { get; set; }
    }

    public Merchants_CategoryId()
    {
        Map = merchants => merchants.Select(merchant => new
        {
            CategoryIds = merchant.Header.CategoryIds,
            MerchantId = merchant.Header.Id
        });
    }
}
</code>```

Query

```<code>return await session
                .Query<Merchants_CategoryId.Result, Merchants_CategoryId>()
                .Where(x => x.CategoryIds.Any(c => c == categoryId))
                .Select(x => x.MerchantId)
                .ToListAsync();
</code>```

答:
Index:

```<code>public class Merchants_CategoryId : AbstractIndexCreationTask<Merchant>
{
      public class Result
      {
          public int MerchantId { get; set; }
          public int CategoryId { get; set; }
      }

      Map = merchants => from merchant in merchants
                         from categoryId in merchant.Header.CategoryIds
                         select new
                         {
                             MerchantId = merchant.Header.Id,
                             CategoryId = categoryId
                         };

      Index(x => x.CategoryId, FieldIndexing.Yes);
      Store(x => x.MerchantId, FieldStorage.Yes);
}
</code>```

Query:

```<code>return await session
            .Query<Merchants_CategoryId.Result, Merchants_CategoryId>()
            .Where(x => x.CategoryId == categoryId)
            .Select(x => x.MerchantId)
            .ToListAsync();
</code>```

Title: Cannot Index on array of int RavenDB

Body:
I'm trying to query on a property of type IEnumerable int to find all documents in the collection that contain an integer value in this property.

I've tried to accomplish this with an index on the property to return a list of id's which satisfy the query. I am projecting the id's in the query however I'm getting a list of id 0's.

Index

public class Merchants_CategoryId : AbstractIndexCreationTask<Merchant>
{
    public class Result
    {
        public int MerchantId { get; set; }
        public IEnumerable<int> CategoryIds { get; set; }
    }

    public Merchants_CategoryId()
    {
        Map = merchants => merchants.Select(merchant => new
        {
            CategoryIds = merchant.Header.CategoryIds,
            MerchantId = merchant.Header.Id
        });
    }
}

Query

return await session
                .Query<Merchants_CategoryId.Result, Merchants_CategoryId>()
                .Where(x => x.CategoryIds.Any(c => c == categoryId))
                .Select(x => x.MerchantId)
                .ToListAsync();

Body:
Index:

public class Merchants_CategoryId : AbstractIndexCreationTask<Merchant>
{
      public class Result
      {
          public int MerchantId { get; set; }
          public int CategoryId { get; set; }
      }

      Map = merchants => from merchant in merchants
                         from categoryId in merchant.Header.CategoryIds
                         select new
                         {
                             MerchantId = merchant.Header.Id,
                             CategoryId = categoryId
                         };

      Index(x => x.CategoryId, FieldIndexing.Yes);
      Store(x => x.MerchantId, FieldStorage.Yes);
}

Query:

return await session
            .Query<Merchants_CategoryId.Result, Merchants_CategoryId>()
            .Where(x => x.CategoryId == categoryId)
            .Select(x => x.MerchantId)
            .ToListAsync();


问:
How does AWS Athena react to schema changes in S3 files?
What happens when after creating the table in AWS Athena for files on S3, the structure of the files on S3 change?

For eg:

If the files previously had 5 columns when the table was created and later the new files started getting 1 more column:
a) at the end?
b) in between?

What happens when some columns are not available in new files?

What happens when the columns remain the same but the column order changes?

Can we alter Athena tables to adjust to these changes?

答:
1 - Athena is not a NoSQL solution. It is not dynamic schema either. If you change the schema, all your files in a particular folder should reflect that change. Athena wont magically update to have it included.

2 - Then it'll be a problem and it'll break. You should include NULL or ,, to force it to be okay.

3 - Athena picks it up by column order. Not by name, really. If your column orders change, it'll probably break (different types).

4 - Yes. You can always easily recreate Athena tables by dropping it and creating a new one.

If you have variable length files, then you should insert them into different folders so that each folder represents one consistent schema. You can then unify this later on in Athena with a union or similar to create a condensed, simplified table that you can apply the consistent schema to.


问:
Redux-Saga takeEvery not calling saga
Okay, so working my way up from the Hello World tutorial at https://redux-saga.js.org/docs/introduction/BeginnerTutorial.html, I'm trying to build a very simple fetch call... only that my generator function never gets executed.

The relevant code looks as follows, for now just console logging for testing purposes:

```<code>export function* fetchData() {
  debugger;
  console.log('Fetching data');
}

export function* fetchDataWatcher() {
  console.log("watching");
  yield takeEvery('FETCH_REQUESTED', fetchData);
}

// single entry point to start all Sagas at once
export default function* rootSaga() {
  yield all([
    fetchDataWatcher()
  ]);
}
</code>```

Of course I implemented the boilerplate in my index.js:

```<code>import rootSaga from './sagas';
...

const sagaMiddleware = createSagaMiddleware();
...
const enhancers =
  compose(
    window.devToolsExtension ? window.devToolsExtension() : f => f,
    applyMiddleware(sagaMiddleware)
  );

const store = createStore(
  combineReducers({
   ...
  }),
  defaultState,
  enhancers
);

sagaMiddleware.run(rootSaga);
</code>```

In the browser console, I see a single 'watching', but when I dispatch an action

```<code>{
type: 'FETCH_REQUESTED'
}
</code>```

via Redux's devtools, I'd expect the debugger to stop my code and step me through the fetchData function... but nothing happens.

I'm sure I'm missing something very simple here - can you help me out?

EDIT:

Turns out, if I move the devTools enhancer to the end of compose, everything works fine.

```<code>const enhancers =
  compose(
    applyMiddleware(sagaMiddleware),
    window.devToolsExtension ? window.devToolsExtension() : f => f
  )
</code>```

Now I know that the resulting signature of compose depends on the last function submitted to it, still this is somewhat unclear to me... Can somebody clarify what is going on?

答:
Try to create your rootSaga in this way

```<code>export default function * root () {
  yield [
    fetchDataWatcher()
  ]
}
</code>```

Title: Redux-Saga takeEvery not calling saga

Body:
Okay, so working my way up from the Hello World tutorial at https://redux-saga.js.org/docs/introduction/BeginnerTutorial.html, I'm trying to build a very simple fetch call... only that my generator function never gets executed.

The relevant code looks as follows, for now just console logging for testing purposes:

export function* fetchData() {
  debugger;
  console.log('Fetching data');
}

export function* fetchDataWatcher() {
  console.log("watching");
  yield takeEvery('FETCH_REQUESTED', fetchData);
}

// single entry point to start all Sagas at once
export default function* rootSaga() {
  yield all([
    fetchDataWatcher()
  ]);
}

Of course I implemented the boilerplate in my index.js:

import rootSaga from './sagas';
...

const sagaMiddleware = createSagaMiddleware();
...
const enhancers =
  compose(
    window.devToolsExtension ? window.devToolsExtension() : f => f,
    applyMiddleware(sagaMiddleware)
  );

const store = createStore(
  combineReducers({
   ...
  }),
  defaultState,
  enhancers
);

sagaMiddleware.run(rootSaga);

In the browser console, I see a single 'watching', but when I dispatch an action

{
type: 'FETCH_REQUESTED'
}

via Redux's devtools, I'd expect the debugger to stop my code and step me through the fetchData function... but nothing happens.

I'm sure I'm missing something very simple here - can you help me out?

EDIT:

Turns out, if I move the devTools enhancer to the end of compose, everything works fine.

const enhancers =
  compose(
    applyMiddleware(sagaMiddleware),
    window.devToolsExtension ? window.devToolsExtension() : f => f
  )

Now I know that the resulting signature of compose depends on the last function submitted to it, still this is somewhat unclear to me... Can somebody clarify what is going on?

Body:
Try to create your rootSaga in this way

export default function * root () {
  yield [
    fetchDataWatcher()
  ]
}


问:
angular-cli what is the difference between version of package.json and ng -v
I have in my package.json this versions of dependencies

```<code>"dependencies": {
  "@angular/animations": "^4.1.3",
  "@angular/common": "^4.0.0",
  "@angular/compiler": "^4.0.0",
  "@angular/core": "^4.0.0",
  "@angular/forms": "^4.0.0",
  "@angular/http": "^4.0.0",
  "@angular/platform-browser": "^4.0.0",
  "@angular/platform-browser-dynamic": "^4.0.0",
  "@angular/router": "^4.0.0",

"devDependencies": {
   "@angular/cli": "1.0.6",
   "@angular/compiler-cli": "^4.0.0",
</code>```

and in the project when execute ng -v

```<code>$ ng -v
@angular/animations: 4.2.4
@angular/common: 4.2.4
@angular/compiler: 4.2.4
@angular/core: 4.2.4
@angular/forms: 4.2.4
@angular/http: 4.2.4
@angular/platform-browser: 4.2.4
@angular/platform-browser-dynamic: 4.2.4
@angular/router: 4.2.4
@angular/cli: 1.0.6
@angular/compiler-cli: 4.2.4
</code>```

what is the current version of @angular in the project 4.0.0 or 4.2.4?

答: Your previous package.json did not have @angular/cli, If you talk about other packages in general, this will be the explanation:   It is 4.2.4, the ^ says, take a package 4.0.0 or greater than that, while doing a fresh npm install you would have got the latest version. To stick to the same version on all development machines (if working in a team), I would recommend giving exact dependencies in package.json coz new versions might break the code in a fresh install.

Body:
I have in my package.json this versions of dependencies

"dependencies": {
  "@angular/animations": "^4.1.3",
  "@angular/common": "^4.0.0",
  "@angular/compiler": "^4.0.0",
  "@angular/core": "^4.0.0",
  "@angular/forms": "^4.0.0",
  "@angular/http": "^4.0.0",
  "@angular/platform-browser": "^4.0.0",
  "@angular/platform-browser-dynamic": "^4.0.0",
  "@angular/router": "^4.0.0",

"devDependencies": {
   "@angular/cli": "1.0.6",
   "@angular/compiler-cli": "^4.0.0",

and in the project when execute ng -v

$ ng -v
@angular/animations: 4.2.4
@angular/common: 4.2.4
@angular/compiler: 4.2.4
@angular/core: 4.2.4
@angular/forms: 4.2.4
@angular/http: 4.2.4
@angular/platform-browser: 4.2.4
@angular/platform-browser-dynamic: 4.2.4
@angular/router: 4.2.4
@angular/cli: 1.0.6
@angular/compiler-cli: 4.2.4

what is the current version of @angular in the project 4.0.0 or 4.2.4?


问:
How to replace a particular string in js
I have a variable with the following data

Peaks in mesothelioma incidence were expected to take place between 2014 and 2021 in Australia, between 2011 and 2015 in the United Kingdom, between 2015 and 2024 in Italy, in 2010 in the United States, in 2015 in Denmark, in 2017 in the Netherlands, and in 2027 in Japan.

Here I want to replace

```<code><img src="test" />
</code>```

To

```<code><amp-img src="test"></amp-img>
</code>```

But here I am getting the data of 100 records as an example I put

```<code> <img src="test" />
</code>```

But I am not sure what my img tag contains.So I van replace img with

```<code>replace('<img',<amp-img>);
</code>```

But how can I replace the end tag i.e

```<code>  ('/>','></amp-img>').
</code>```

Can any one please suggest me help.Thanks.

答:
If what you have is a string that literally includes:  then you can use:

```<code>string = string.replace(/<img\s+(.*?)\s*\/>/g, '<amp-img $1></amp-img>');
</code>```

or even:

```<code>string = string.replace(/<img\s+([^>]*?)\s*\/>/g, '<amp-img $1></amp-img>');
</code>```

Don't replace the closing tag separately as suggested here:

```<code>string.replace(' />','</amp-img>')
</code>```

because that will break all other markup where you have other tags that you don't want to replace (and in that case it will also not work if you have no space before the slash - which is completely valid and should be expected).

If what you have is a DOM object then you should replace the DOM nodes individually instead of parsing the markup as strings.

Body:
I have a variable with the following data

Peaks in mesothelioma incidence were expected to take place between 2014 and 2021 in Australia, between 2011 and 2015 in the United Kingdom, between 2015 and 2024 in Italy, in 2010 in the United States, in 2015 in Denmark, in 2017 in the Netherlands, and in 2027 in Japan.

Here I want to replace

To

<amp-img src="test"></amp-img>

But here I am getting the data of 100 records as an example I put

But I am not sure what my img tag contains.So I van replace img with

replace('<img',<amp-img>);

But how can I replace the end tag i.e

  ('/>','></amp-img>').

Can any one please suggest me help.Thanks.

Body:
If what you have is a string that literally includes: <img src="test" /> then you can use:

string = string.replace(/<img\s+(.*?)\s*\/>/g, '<amp-img $1></amp-img>');

or even:

string = string.replace(/<img\s+([^>]*?)\s*\/>/g, '<amp-img $1></amp-img>');

Don't replace the closing tag separately as suggested here:

string.replace(' />','</amp-img>')

because that will break all other markup where you have other tags that you don't want to replace (and in that case it will also not work if you have no space before the slash - which is completely valid and should be expected).

If what you have is a DOM object then you should replace the DOM nodes individually instead of parsing the markup as strings.


问:
Excel graph plotting - frequency of low cardinality column vs bins
I've 2 columns and a set of bin values.
Column A contains numeric random values. Column B (contains another property of column A) contains 'True', 'False', and blank cells, i.e 3 distinct values.

I need to plot a single graph as following:

X axis contains the bin values, e.g., 0, 250, 500.

3 curves showing frequency value for three distinct values of column B. B relates to bins through the medium of column A.

I think this type of graph would be a standard type graph. If so, please let me know the name.

Please either provide precise steps to plot it or provide a pointer which could help me plot this graph.

答:
You should probably create a new table with the values you would use to plot the graphics, using COUNTIFS function.
Something like:
Column D for bin values,
Column E for "True": =COUNTIFS(A1:A100; "<0"; B1:B100; "True"),
Columns F, G for "False" and "".
Then just plot it.

Now you can also use references to reduce your work.

You could write "True" to E1, "False" to F1, nothing to G1 and start your bins from the second row:
=COUNTIFS(A1:A100; "<0"; B1:B100; E$1) - that will allow to copy to functions from E to F and G.

There also is a hack to avoid explicitely writing "<100" for each bin: you should instead construct this string by "<" & TEXT($D2).


问:
How to present frequencies and cumulative frequencies side by side (dodge position) in barchart with ggplot
I am trying to present frequencies and cumulative frequencies side by side in a bar chart in ggplot but what I end up is overlapping bars.

For a reproducible example:

```<code>data(mtcars)
setDT(mtcars)

data <- mtcars[, .(Total = .N), by = carb][order(carb)][, .(carb, freq = Total/sum(Total))][
  , .(carb, freq, cumfreq = cumsum(freq))]

ggplot(data, aes(x = carb)) +
  geom_bar(fill = "red", alpha = 0.5, stat = "identity" , aes(y = freq), position = position_dodge()) +
  geom_bar(fill = "blue", alpha = 0.5, stat = "identity" , aes(y = cumfreq), position = position_dodge())
</code>```

Your advice will be appreciated.

答:
I would change a little bit the data you are using, like this (with reshape2 package) :

```<code>library(reshape2)

new_data = melt(data,id = "carb")

ggplot(data = new_data)+aes(x = carb, y = value, fill = variable)+
  geom_bar(alpha = 0.5,stat = "identity", position = position_dodge())+
  scale_fill_manual(values = c("red","blue"))
</code>```

Tell me if it's what you want

Body:
I am trying to present frequencies and cumulative frequencies side by side in a bar chart in ggplot but what I end up is overlapping bars.

For a reproducible example:

data(mtcars)
setDT(mtcars)

data <- mtcars[, .(Total = .N), by = carb][order(carb)][, .(carb, freq = Total/sum(Total))][
  , .(carb, freq, cumfreq = cumsum(freq))]

ggplot(data, aes(x = carb)) +
  geom_bar(fill = "red", alpha = 0.5, stat = "identity" , aes(y = freq), position = position_dodge()) +
  geom_bar(fill = "blue", alpha = 0.5, stat = "identity" , aes(y = cumfreq), position = position_dodge())

Your advice will be appreciated.

Body:
I would change a little bit the data you are using, like this (with reshape2 package) :

library(reshape2)

new_data = melt(data,id = "carb")

ggplot(data = new_data)+aes(x = carb, y = value, fill = variable)+
  geom_bar(alpha = 0.5,stat = "identity", position = position_dodge())+
  scale_fill_manual(values = c("red","blue"))

Tell me if it's what you want


问:
Why does the ToolTip not appear when set to a long string?
I am working in VB.Net 2010 framework 2.0.
I am setting a big string to tooltip object. In this case tooltip is not appearing. If the string is short (say of 10 lines), tooptip is appearing properly.

The following is the code:

```<code>Protected Overrides Sub OnMouseEnter(ByVal e As System.EventArgs)
    If _showToolTip Then
        If Not IsNothing(_tooltipDSPanel) Then
            _tooltipDSPanel.Dispose()
            _tooltipDSPanel = Nothing
        End If
        _tooltipDSPanel = New ToolTip
        _tooltipDSPanel.SetToolTip(Me, PanelText)
    End If
End Sub
</code>```

If the "PanelText" is too long (say 50 lines), it does not appear. Sometimes it shows an empty tooltip.

Where I am going wrong?

Thanks for any reply in advance.

答: The tooltip wasn't designed for large amounts of text. Its performance degrades quickly as the character number increases. It's really only usable up to about 1000 characters in my experience. Anything over this takes several seconds to appear. As such, it may be disappearing before it actually renders. I would try setting the AutoPopDelay to a high number to see if it shows at all.

Body:
I am working in VB.Net 2010 framework 2.0.
I am setting a big string to tooltip object. In this case tooltip is not appearing. If the string is short (say of 10 lines), tooptip is appearing properly.

The following is the code:

Protected Overrides Sub OnMouseEnter(ByVal e As System.EventArgs)
    If _showToolTip Then
        If Not IsNothing(_tooltipDSPanel) Then
            _tooltipDSPanel.Dispose()
            _tooltipDSPanel = Nothing
        End If
        _tooltipDSPanel = New ToolTip
        _tooltipDSPanel.SetToolTip(Me, PanelText)
    End If
End Sub

If the "PanelText" is too long (say 50 lines), it does not appear. Sometimes it shows an empty tooltip.

Where I am going wrong?

Thanks for any reply in advance.


问:
Is it possible to get the string inside the enclosing '<' and '>' of a tag using jquery or plain javascript?
If  my question isn't clear,I don't want the outerhtml which returns all the contents inside a node.I don't want those.For example:

  Hello!

    How are you?Hope you are doing well!

```
</div>
</div>
</p>

<p>Now,outerHTML of 'foo' will give the whole string representation of its DOM structure.I just want </p>

```div id="foo" class="something" style="width:80%; display:inline-block"
```

Is it possible to get this without using regex/string matching?

答:
You can try something like this,

var element = document.getElementById("foo");

var tag = element.tagName;
  $.each(element.attributes, function() {
    tag += " "+ this.name + '"'+ this.value+ '"';
  });
  alert(tag);```
<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>
<div id="foo" class="something" style="width:80%; display:inline-block">
  Hello!
  <div id="bar" class="something_else">
    How are you?Hope you are doing well!
  </div>
</div></code>```

Body:
If  my question isn't clear,I don't want the outerhtml which returns all the contents inside a node.I don't want those.For example:

  Hello!

    How are you?Hope you are doing well!

Now,outerHTML of 'foo' will give the whole string representation of its DOM structure.I just want

div id="foo" class="something" style="width:80%; display:inline-block"

Is it possible to get this without using regex/string matching?

Body:
You can try something like this,

var element = document.getElementById("foo");

var tag = element.tagName;
  $.each(element.attributes, function() {
    tag += " "+ this.name + '"'+ this.value+ '"';
  });
  alert(tag);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="foo" class="something" style="width:80%; display:inline-block">
  Hello!
  <div id="bar" class="something_else">
    How are you?Hope you are doing well!
  </div>
</div>