问:
I have a list of datatable, how can I copy that list into single datatable in c#
```<code>public DataTable LoadPaymentsList()
{
   List< DataTable > lstDts = new List< DataTable >();
   // Copy into  dt
   Datatable dt=new Datatable();
   return dt;
}
</code>```

答:
I don't think there's a better way than simple Row- and Column-Adding:

```<code>DataTable mergedTable = new DataTable();
List<DataTable> tableCollection = new List<DataTable>();
/*---------------------------------*/

bool columnsAdded = false;
foreach (DataTable table in tableCollection)
{
    if (!columnsAdded)
    {
        foreach (DataColumn column in table.Columns)
        {
            mergedTable.Columns.Add(column);
        }
        columnsAdded = true;
    }
    foreach (DataRow row in table.Rows)
    {
        mergedTable.Rows.Add(row);
    }
}
</code>```

Body:
I don't think there's a better way than simple Row- and Column-Adding:

DataTable mergedTable = new DataTable();
List<DataTable> tableCollection = new List<DataTable>();
/*---------------------------------*/

bool columnsAdded = false;
foreach (DataTable table in tableCollection)
{
    if (!columnsAdded)
    {
        foreach (DataColumn column in table.Columns)
        {
            mergedTable.Columns.Add(column);
        }
        columnsAdded = true;
    }
    foreach (DataRow row in table.Rows)
    {
        mergedTable.Rows.Add(row);
    }
}


来源: stackexchange

问:
Stored procedure called from C# executes 6 times longer than from SQL Management studio
I have search stored procedure which is my performance bottleneck.

In order to get control about what is happened, I added logging for all parameters and also execution time in SP.

I noticed, that when I call SP from MIcrosoft SQL server management Studio execution time is 1.3-1.6 seconds, but when i call it from C#, it takes 6-8 secods (!!!)

```<code>Parameters                                                            | Time (ms)
"tb *"TreeType:259Parents:212fL:13;14fV:0;lcid:2057min:0max:10sort:-1 | 6406
"tb *"TreeType:259Parents:212fL:13;14fV:0;lcid:2057min:0max:10sort:-1 | 1346
</code>```

SP is called with LINQ. Login settings are same.
SP uses full text search

What could cause this?

答:
In order to locate such issues, the best tool is SQL Profiler, which records the exact call to database.

For me the difference was with novalue passed by SQL sample, which was substituted by '' and null value passed by C#.

ContentLicense: CC BY-SA 2.5

Body:
I have search stored procedure which is my performance bottleneck.

In order to get control about what is happened, I added logging for all parameters and also execution time in SP.

I noticed, that when I call SP from MIcrosoft SQL server management Studio execution time is 1.3-1.6 seconds, but when i call it from C#, it takes 6-8 secods (!!!)

Parameters                                                            | Time (ms)
"tb *"TreeType:259Parents:212fL:13;14fV:0;lcid:2057min:0max:10sort:-1 | 6406
"tb *"TreeType:259Parents:212fL:13;14fV:0;lcid:2057min:0max:10sort:-1 | 1346

SP is called with LINQ. Login settings are same.
SP uses full text search

What could cause this?


问:
Check if a variable has "moved"
I have a thread wherein the program constantly gets the user's distance from another phone thru bluetooth.

I opted to implement a text-to-speech feature wherein the program will "talk" when the user moves a meter closer/farther. I am already able to get the distance but the problem is I have no idea how to check if the distance has moved atleast 1 meter closer/farther. For example:

```<code>Initial distance: 0.81 meters
</code>```

The TTS feature should activate when the value increases/decreases by roughly 1 meter.

```<code>Should activate TTS when distance becomes: 1.81, 2.85, 3.90
</code>```

Notice that the 2nd value 2.85 is not exactly 1 meter farther from the last distance 1.81 because the distance being obtained "jumps" meaning if you display the distance and start walking away it will look similar to this:

```<code>Distance: 1.01, 1.86, 2.31, 3.29, ...
</code>```

I have tried various ways but I just can't seem to do it. Any help will be appreciated!

答:
Please try this </p>

```<code>int initDist = x;
int newDist = y;

int diff = newDist - initDist;

if(diff >= 1){
    // activate TTS here;
    initDist = newDist;
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Check if a variable has "moved"

Body:
I have a thread wherein the program constantly gets the user's distance from another phone thru bluetooth.

I opted to implement a text-to-speech feature wherein the program will "talk" when the user moves a meter closer/farther. I am already able to get the distance but the problem is I have no idea how to check if the distance has moved atleast 1 meter closer/farther. For example:

Initial distance: 0.81 meters

The TTS feature should activate when the value increases/decreases by roughly 1 meter.

Should activate TTS when distance becomes: 1.81, 2.85, 3.90

Notice that the 2nd value 2.85 is not exactly 1 meter farther from the last distance 1.81 because the distance being obtained "jumps" meaning if you display the distance and start walking away it will look similar to this:

Distance: 1.01, 1.86, 2.31, 3.29, ...

I have tried various ways but I just can't seem to do it. Any help will be appreciated!

Body:
Please try this

int initDist = x;
int newDist = y;

int diff = newDist - initDist;

if(diff >= 1){
    // activate TTS here;
    initDist = newDist;
}


问:
Biopython to extract base calls at a list of positions
I have a list of positions of interest eg:

```<code>10
20
1000
4000000
</code>```

I want to extract the base call at these positions from a fasta file using biopython.

This is what I have tried:

```<code>query_dic ={}
with open(line) as pos_file:
    for x in pos_file:
        for seq_record in SeqIO.parse(query_file, "fasta"):
            nuc = seq_record[x]
            query_dic[x]=nuc
</code>```

The error message says 'invalid index' - what is wrong?

答:
Most likely some of the sequences are not long enough to have that many letters, and thus the larger indexes are invalid.

You might consider modifying the final loop to something like this:

```<code>if len(seq_record) > x:
    nuc = seq_record[x]
else:
    nuc = None
query_dic[x] = nuc
</code>```

Body:
I have a list of positions of interest eg:

10
20
1000
4000000

I want to extract the base call at these positions from a fasta file using biopython.

This is what I have tried:

query_dic ={}
with open(line) as pos_file:
    for x in pos_file:
        for seq_record in SeqIO.parse(query_file, "fasta"):
            nuc = seq_record[x]
            query_dic[x]=nuc

The error message says 'invalid index' - what is wrong?

Body:
Most likely some of the sequences are not long enough to have that many letters, and thus the larger indexes are invalid.

You might consider modifying the final loop to something like this:

if len(seq_record) > x:
    nuc = seq_record[x]
else:
    nuc = None
query_dic[x] = nuc


问:
angularjs push data into ng-repeat object after posting
Below is my code

```<code><select class="form-control" id="prevCountry" name="prevCountry" ng-model="asset.assets.countryID" ng-options="value.ID as value.country for value in technical.country">
  <option value="">Select Country</option>
</select>
</code>```

angularjs code

$scope.technical.assets.push($scope.assets);

I'm posting countryID but I want to push into ng-repeat object the countryName of countryID.

答:
If I understood you right, you need to check the example of ngOptions usage here. Created a Plunker for you. Hope it'll help.</p>

```<code><select name="mySelect" id="mySelect"
  ng-options="option.countryName for option in technical.country"
  ng-model="asset.assets"></select>
</code>```

Body:
Below is my code

<select class="form-control" id="prevCountry" name="prevCountry" ng-model="asset.assets.countryID" ng-options="value.ID as value.country for value in technical.country">
  <option value="">Select Country</option>
</select>

angularjs code

$scope.technical.assets.push($scope.assets);

I'm posting countryID but I want to push into ng-repeat object the countryName of countryID.

Body:
If I understood you right, you need to check the example of ngOptions usage here. Created a Plunker for you. Hope it'll help.

<select name="mySelect" id="mySelect"
  ng-options="option.countryName for option in technical.country"
  ng-model="asset.assets"></select>


问:
Not able to Build Xcode Project using Jenkins & Pods
We are using Jenkins 2.62. When trying to build from Jenkins, I am getting the errors below:

[workspace] $ /bin/bash -l /var/folders/km/33wcncls1874x2xv50nv43480000gn/T/jenkins1804164065511577211.sh
  /Library/Ruby/Site/2.0.0/rubygems/dependency.rb:318:in to_specs': Could not find 'claide' (< 2.0, >= 1.0.0) among 32 total gem(s) (Gem::LoadError)
  Checked in 'GEM_PATH=file:/Users/administrator/.jenkins/plugins/ruby-runtime/WEB-INF/lib/stapler-jruby-1.209.jar!/gem:/Users/administrator/Software/ruby', executegem envfor more information
      from /Library/Ruby/Site/2.0.0/rubygems/specification.rb:1402:inblock in activate_dependencies'
      from /Library/Ruby/Site/2.0.0/rubygems/specification.rb:1391:in each'
      from /Library/Ruby/Site/2.0.0/rubygems/specification.rb:1391:inactivate_dependencies'
      from /Library/Ruby/Site/2.0.0/rubygems/specification.rb:1373:in activate'
      from /Library/Ruby/Site/2.0.0/rubygems/core_ext/kernel_gem.rb:67:inblock in gem'
      from /Library/Ruby/Site/2.0.0/rubygems/core_ext/kernel_gem.rb:66:in synchronize'
      from /Library/Ruby/Site/2.0.0/rubygems/core_ext/kernel_gem.rb:66:ingem'
      from /usr/local/bin/pod:22:in `'

Below is the script we are using in Execute Shell

```<code>**rm -fr *.xcworkspace
rm -fr ~/Library/Caches/CocoaPods/
rm -fr Pods/
rm -rf ~/Library/Developer/Xcode/DerivedData/*
/usr/local/bin/pod install
xcodebuild -workspace Proj.xcworkspace -scheme Proj_test -sdk iphoneos -configuration Release archive -archivePath ${WORKSPACE}/Proj/Build/Release-iphoneos/Proj.xcarchive
xcodebuild -exportArchive -archivePath ${WORKSPACE}/ChannelConnect/Build/Release-iphoneos/Proj.xcarchive -exportOptionsPlist ${WORKSPACE}/exportOptionsPlist.plist -exportPath ${WORKSPACE}/Proj/Build/Release-iphoneos**
</code>```

When we tried "Pod Install" for the same path in the server manually, it worked just fine.

Can we change the Jenkins pods path?

答:
Sounds like Jenkins messes with your PATH. This is very common. You have to explicitly tell Jenkins to add /usr/local/bin to your PATH.

See the current contents under System Information -> Environment Variables to validate this theory.

Adjust the value under Configure System -> Environment Variables by adding PATH="/usr/local/bin:$PATH"

If you have slaves, you'll have to configure it for each of them under Manage Nodes -> Node -> System Info

Body:
We are using Jenkins 2.62. When trying to build from Jenkins, I am getting the errors below:

[workspace] $ /bin/bash -l /var/folders/km/33wcncls1874x2xv50nv43480000gn/T/jenkins1804164065511577211.sh
  /Library/Ruby/Site/2.0.0/rubygems/dependency.rb:318:in to_specs': Could not find 'claide' (< 2.0, >= 1.0.0) among 32 total gem(s) (Gem::LoadError)
  Checked in 'GEM_PATH=file:/Users/administrator/.jenkins/plugins/ruby-runtime/WEB-INF/lib/stapler-jruby-1.209.jar!/gem:/Users/administrator/Software/ruby', executegem envfor more information
      from /Library/Ruby/Site/2.0.0/rubygems/specification.rb:1402:inblock in activate_dependencies'
      from /Library/Ruby/Site/2.0.0/rubygems/specification.rb:1391:in each'
      from /Library/Ruby/Site/2.0.0/rubygems/specification.rb:1391:inactivate_dependencies'
      from /Library/Ruby/Site/2.0.0/rubygems/specification.rb:1373:in activate'
      from /Library/Ruby/Site/2.0.0/rubygems/core_ext/kernel_gem.rb:67:inblock in gem'
      from /Library/Ruby/Site/2.0.0/rubygems/core_ext/kernel_gem.rb:66:in synchronize'
      from /Library/Ruby/Site/2.0.0/rubygems/core_ext/kernel_gem.rb:66:ingem'
      from /usr/local/bin/pod:22:in `'

Below is the script we are using in Execute Shell

**rm -fr *.xcworkspace
rm -fr ~/Library/Caches/CocoaPods/
rm -fr Pods/
rm -rf ~/Library/Developer/Xcode/DerivedData/*
/usr/local/bin/pod install
xcodebuild -workspace Proj.xcworkspace -scheme Proj_test -sdk iphoneos -configuration Release archive -archivePath ${WORKSPACE}/Proj/Build/Release-iphoneos/Proj.xcarchive
xcodebuild -exportArchive -archivePath ${WORKSPACE}/ChannelConnect/Build/Release-iphoneos/Proj.xcarchive -exportOptionsPlist ${WORKSPACE}/exportOptionsPlist.plist -exportPath ${WORKSPACE}/Proj/Build/Release-iphoneos**

When we tried "Pod Install" for the same path in the server manually, it worked just fine.

Can we change the Jenkins pods path?


问:
Selecting phone calls in where date is today
I'm trying to retrieve phone calls from our Avaya database in SQL 2012 and i can't seem to get the dates on my code right.

```<code>cmdCalls = String.Format("SELECT * FROM dbo.tblCallList WHERE CreateDate > cast('" & DateYesterday & "' as date)")
</code>```

This is my query string

```<code>Dim DateYesterday As Date = Date.Today.AddDays(<insert number of days>).ToString("yyyy-MM-dd")
</code>```

I can't seem to pull the data i need from the database, it does subtract the days from the date variable but the problem is its using the days as months on the query and it shows all the records from the month instead of day

The Dates formats on the database are '2017-06-08 12:04::00:000' for example

答:
Use the current date in the database:</p>

```<code>SELECT *
FROM dbo.tblCallList
WHERE CreateDate >= CAST(getdate() as date);
</code>```

Body:
I'm trying to retrieve phone calls from our Avaya database in SQL 2012 and i can't seem to get the dates on my code right.

cmdCalls = String.Format("SELECT * FROM dbo.tblCallList WHERE CreateDate > cast('" & DateYesterday & "' as date)")

This is my query string

Dim DateYesterday As Date = Date.Today.AddDays(<insert number of days>).ToString("yyyy-MM-dd")

I can't seem to pull the data i need from the database, it does subtract the days from the date variable but the problem is its using the days as months on the query and it shows all the records from the month instead of day

The Dates formats on the database are '2017-06-08 12:04::00:000' for example

Body:
Use the current date in the database:

SELECT *
FROM dbo.tblCallList
WHERE CreateDate >= CAST(getdate() as date);


问:
python alternative to the goto command?
I have a python program that is essentailly made up of turtle graphics, and it is basically asking the user how many squares to draw, and then after each square, it adds 1 to a counter using:

```<code>counter=1
<drawing code here>
counter +=1
</code>```

And then after that I wanted to do a check to see if the number of squares is equal to the amount that the user typed in, and if it is, then I wanted to go to the bottom of the script where I would make it say something like done!!. but I dont know how to make it go to a certain part of the script as the goto command that I'm used to in batch isn't supported in python (i know, goto= spaghetti code)

I found an easy workaround is just to download a module that someone made that lets you import the goto command into python and use it just as you would in batch but I would like a native python solution if any!

my current code is:

```<code>from turtle import *
import time
counter=1
color("red", "blue")
down()

user=int(raw_input('how many balls do you want?'))
counter +=1
if user===counter:

# solution goes here!

else:

for step in range(24):
        right(105)
        forward(100)
        right(105)
        forward(100)
        right(105)
        forward(100)
        right(105)
        forward(100)

up()
goto(120,0)
down()

counter +=1
if user==counter:

#solution goes here!

else:

for step in range(24):
        right(105)
        forward(100)
        right(105)
        forward(100)
        right(105)
        forward(100)
        right(105)
        forward(100)

up()
goto(0,-50)
write("Done!")

time.sleep(5)
</code>```

If you have an answer or alternative to this problem it would be greatly appreciated!

答: Don't check the number of squares and then go to the end, just loop the appropriate number of times instead, drawing a square each time.</p>

Title: python alternative to the goto command?

Body:
I have a python program that is essentailly made up of turtle graphics, and it is basically asking the user how many squares to draw, and then after each square, it adds 1 to a counter using:

counter=1
<drawing code here>
counter +=1

And then after that I wanted to do a check to see if the number of squares is equal to the amount that the user typed in, and if it is, then I wanted to go to the bottom of the script where I would make it say something like done!!. but I dont know how to make it go to a certain part of the script as the goto command that I'm used to in batch isn't supported in python (i know, goto= spaghetti code)

I found an easy workaround is just to download a module that someone made that lets you import the goto command into python and use it just as you would in batch but I would like a native python solution if any!

my current code is:

from turtle import *
import time
counter=1
color("red", "blue")
down()

user=int(raw_input('how many balls do you want?'))
counter +=1
if user===counter:

# solution goes here!

else:

for step in range(24):
        right(105)
        forward(100)
        right(105)
        forward(100)
        right(105)
        forward(100)
        right(105)
        forward(100)

up()
goto(120,0)
down()

counter +=1
if user==counter:

#solution goes here!

else:

for step in range(24):
        right(105)
        forward(100)
        right(105)
        forward(100)
        right(105)
        forward(100)
        right(105)
        forward(100)

up()
goto(0,-50)
write("Done!")

time.sleep(5)

If you have an answer or alternative to this problem it would be greatly appreciated!


问:
How to do math operations with the SQL OVER() command on BigQuery
We are trying to do a math operation with the SQL OVER() command.

This is the kind of query we would like to run...

```<code>SELECT SurvivedCount/(SUM(SurvivedCount) OVER()) AS PercentSurvived
</code>```

...but it gives this error:

```<code>Encountered " "OVER" "OVER "" at line 2, column 50. Was expecting: ")" ...
</code>```

Apart from splitting this into a two stage SQL sub-select, is there any way to do math with the OVER() operation on Google BigQuery?

答:
You need to enable standard SQL. Legacy SQL is enabled by default.

```<code>#standardSQL
WITH
  tmp AS (
  SELECT
    10 AS SurvivedCount,
    'foo' AS a
  UNION ALL
  SELECT
    20 AS SurvivedCount,
    'foo' AS b)
SELECT
  SurvivedCount,
  SurvivedCount/(SUM(SurvivedCount) OVER()) AS PercentSurvived
FROM
  tmp
</code>```

https://cloud.google.com/bigquery/docs/reference/standard-sql/enabling-standard-sql

Body:
We are trying to do a math operation with the SQL OVER() command.

This is the kind of query we would like to run...

SELECT SurvivedCount/(SUM(SurvivedCount) OVER()) AS PercentSurvived

...but it gives this error:

Encountered " "OVER" "OVER "" at line 2, column 50. Was expecting: ")" ...

Apart from splitting this into a two stage SQL sub-select, is there any way to do math with the OVER() operation on Google BigQuery?

Body:
You need to enable standard SQL. Legacy SQL is enabled by default.

#standardSQL
WITH
  tmp AS (
  SELECT
    10 AS SurvivedCount,
    'foo' AS a
  UNION ALL
  SELECT
    20 AS SurvivedCount,
    'foo' AS b)
SELECT
  SurvivedCount,
  SurvivedCount/(SUM(SurvivedCount) OVER()) AS PercentSurvived
FROM
  tmp

https://cloud.google.com/bigquery/docs/reference/standard-sql/enabling-standard-sql


问:
Group array of javascript objects based on value into there own sub array of objects
I have an array of Javascript objects like below.

```<code>        [{

            "email": "alex@test.com",
            "fn": "Alex",
            "sn": "McPherson",
            "phone": "01233xxxxx",
            "hours": "40",
            "rate": "20",
            "amount": "200",
            "vat": "60",
            "agency": "test",
            "start": "08/06/2017",
            "end": "10/06/2017"
        },
        {

            "email": "mike@test.com",
            "fn": "Mike",
            "sn": "Mann",
            "phone": "01233xxxxx",
            "hours": "50",
            "rate": "70",
            "amount": "500",
            "vat": "90",
            "agency": "test",
            "start": "08/06/2017",
            "end": "10/06/2017"
        },
        {

            "email": "fred@test.com",
            "fn": "Fred",
            "sn": "Frogg",
            "phone": "01233xxxxx",
            "hours": "80",
            "rate": "90",
            "amount": "800",
            "vat": "100",
            "agency": "test",
            "start": "08/06/2017",
            "end": "10/06/2017"
        },
        {

            "email": "alex@test.com",
            "fn": "Alex",
            "sn": "McPherson",
            "phone": "01233xxxxx",
            "hours": "90",
            "rate": "30",
            "amount": "900",
            "vat": "120",
            "agency": "test",
            "start": "08/06/2017",
            "end": "10/06/2017"
        }]
</code>```

What I ideally want is to group those of the same value (email) into there own sub array of objects i.e if you look at the array above you will see I have 2 entries for the same person Alex McPherson. What I want to do is the below if possible move and combine into a sub array and the same for any other value that exists more than once.

```<code>    [[{

        "email": "alex@test.com",
        "fn": "Alex",
        "sn": "McPherson",
        "phone": "01233xxxxx",
        "hours": "40",
        "rate": "20",
        "amount": "200",
        "vat": "60",
        "agency": "test",
        "start": "08/06/2017",
        "end": "10/06/2017"
    },{

        "email": "alex@test.com",
        "fn": "Alex",
        "sn": "McPherson",
        "phone": "01233xxxxx",
        "hours": "90",
        "rate": "30",
        "amount": "900",
        "vat": "120",
        "agency": "test",
        "start": "08/06/2017",
        "end": "10/06/2017"
    }],
    [{

        "email": "mike@test.com",
        "fn": "Mike",
        "sn": "Mann",
        "phone": "01233xxxxx",
        "hours": "50",
        "rate": "70",
        "amount": "500",
        "vat": "90",
        "agency": "test",
        "start": "08/06/2017",
        "end": "10/06/2017"
    }],
    [{

        "email": "fred@test.com",
        "fn": "Fred",
        "sn": "Frogg",
        "phone": "01233xxxxx",
        "hours": "80",
        "rate": "90",
        "amount": "800",
        "vat": "100",
        "agency": "test",
        "start": "08/06/2017",
        "end": "10/06/2017"
    }]]
</code>```

I can't seem to get my head around resorting the array.

答:
Hard to be more efficient than something like this:

const groupBy = (data, groupingProp) => {
  // Create a dictionnary of groups.
  const map = new Map();
  data.forEach(entry => {
    const groupKey = entry[groupingProp];
    const list = map.get(groupKey);
    if (list == null) {
      map.set(groupKey, [entry]);
    } else {
      list.push(entry);
    }
  });
  // Transform it back into a list of groups.
  return [...map.values()];
}

// The data.
const data = [{
    "email": "alex@test.com",
    "fn": "Alex",
    "sn": "McPherson",
    "phone": "01233xxxxx",
    "hours": "40",
    "rate": "20",
    "amount": "200",
    "vat": "60",
    "agency": "test",
    "start": "08/06/2017",
    "end": "10/06/2017"
  },
  {
    "email": "mike@test.com",
    "fn": "Mike",
    "sn": "Mann",
    "phone": "01233xxxxx",
    "hours": "50",
    "rate": "70",
    "amount": "500",
    "vat": "90",
    "agency": "test",
    "start": "08/06/2017",
    "end": "10/06/2017"
  },
  {
    "email": "fred@test.com",
    "fn": "Fred",
    "sn": "Frogg",
    "phone": "01233xxxxx",
    "hours": "80",
    "rate": "90",
    "amount": "800",
    "vat": "100",
    "agency": "test",
    "start": "08/06/2017",
    "end": "10/06/2017"
  },
  {
    "email": "alex@test.com",
    "fn": "Alex",
    "sn": "McPherson",
    "phone": "01233xxxxx",
    "hours": "90",
    "rate": "30",
    "amount": "900",
    "vat": "120",
    "agency": "test",
    "start": "08/06/2017",
    "end": "10/06/2017"
  }
];

console.log(groupBy(data, 'email'));```

Body:
I have an array of Javascript objects like below.

        [{

            "email": "alex@test.com",
            "fn": "Alex",
            "sn": "McPherson",
            "phone": "01233xxxxx",
            "hours": "40",
            "rate": "20",
            "amount": "200",
            "vat": "60",
            "agency": "test",
            "start": "08/06/2017",
            "end": "10/06/2017"
        },
        {

            "email": "mike@test.com",
            "fn": "Mike",
            "sn": "Mann",
            "phone": "01233xxxxx",
            "hours": "50",
            "rate": "70",
            "amount": "500",
            "vat": "90",
            "agency": "test",
            "start": "08/06/2017",
            "end": "10/06/2017"
        },
        {

            "email": "fred@test.com",
            "fn": "Fred",
            "sn": "Frogg",
            "phone": "01233xxxxx",
            "hours": "80",
            "rate": "90",
            "amount": "800",
            "vat": "100",
            "agency": "test",
            "start": "08/06/2017",
            "end": "10/06/2017"
        },
        {

            "email": "alex@test.com",
            "fn": "Alex",
            "sn": "McPherson",
            "phone": "01233xxxxx",
            "hours": "90",
            "rate": "30",
            "amount": "900",
            "vat": "120",
            "agency": "test",
            "start": "08/06/2017",
            "end": "10/06/2017"
        }]

What I ideally want is to group those of the same value (email) into there own sub array of objects i.e if you look at the array above you will see I have 2 entries for the same person Alex McPherson. What I want to do is the below if possible move and combine into a sub array and the same for any other value that exists more than once.

    [[{

        "email": "alex@test.com",
        "fn": "Alex",
        "sn": "McPherson",
        "phone": "01233xxxxx",
        "hours": "40",
        "rate": "20",
        "amount": "200",
        "vat": "60",
        "agency": "test",
        "start": "08/06/2017",
        "end": "10/06/2017"
    },{

        "email": "alex@test.com",
        "fn": "Alex",
        "sn": "McPherson",
        "phone": "01233xxxxx",
        "hours": "90",
        "rate": "30",
        "amount": "900",
        "vat": "120",
        "agency": "test",
        "start": "08/06/2017",
        "end": "10/06/2017"
    }],
    [{

        "email": "mike@test.com",
        "fn": "Mike",
        "sn": "Mann",
        "phone": "01233xxxxx",
        "hours": "50",
        "rate": "70",
        "amount": "500",
        "vat": "90",
        "agency": "test",
        "start": "08/06/2017",
        "end": "10/06/2017"
    }],
    [{

        "email": "fred@test.com",
        "fn": "Fred",
        "sn": "Frogg",
        "phone": "01233xxxxx",
        "hours": "80",
        "rate": "90",
        "amount": "800",
        "vat": "100",
        "agency": "test",
        "start": "08/06/2017",
        "end": "10/06/2017"
    }]]

I can't seem to get my head around resorting the array.

ContentLicense: CC BY-SA 4.0


问:
c++ grammar, return value type according to this code.
```<code>if(isRoot) isCutVertex[here] = (children>=2);
</code>```

I would like to know whether return value is bool type(1 or 0) or int type(according to the value of children)

答:
the expression

```<code> isCutVertex[here] = (children>=2);
</code>```

infers that  this is valid

```<code> isCutVertex[here] = x;
</code>```

when x results to be either true or false

so you could have

```<code>bool isCutVertex[10];

isCutVertex[0] = true;
isCutVertex[1] = false;
</code>```

or

```<code>std::vector<bool> isCutVertex2;
isCutVertex2[0] = true;
isCutVertex2[1] = false;
</code>```

Body:
if(isRoot) isCutVertex[here] = (children>=2);

I would like to know whether return value is bool type(1 or 0) or int type(according to the value of children)

Body:
the expression

 isCutVertex[here] = (children>=2);

infers that  this is valid

 isCutVertex[here] = x;

when x results to be either true or false

so you could have

bool isCutVertex[10];

isCutVertex[0] = true;
isCutVertex[1] = false;

or

std::vector<bool> isCutVertex2;
isCutVertex2[0] = true;
isCutVertex2[1] = false;


问:
Crystal Report not appearing in Visual Studio 2012/13 Add New Item
I have installed Crystal report 2011 SP4 on my system where VS 2012 and 2013 are already isntalled. I dont see Crystal Report showing up in Add New Item -> Reporting dialog box.

答:
According to this document https://www.tektutorialshub.com/install-crystal-reports-visual-studio/#Visual-Studio-2013-VS-2013 you might need a newer version of CR:

Visual Studio 2012 (VS 2012)

You can install SP 7 or higher.

Visual Studio 2013 (VS 2013)

Any version above the SP 9 is allowed


问:
Find years where 22nd March will be a Tuesday
I need to find out in which years between 2017 and 2100 (both inclusive) will the 22nd March be a Tuesday.

I tried using the datetime module but I couldn't figure out how...

答:
Use the calendar module instead:

```<code>>>> import calendar
>>> [year for year in range(2017, 2101) if calendar.weekday(year, 3, 22) == calendar.TUESDAY]
[2022, 2033, 2039, 2044, 2050, 2061, 2067, 2072, 2078, 2089, 2095]
</code>```

Body:
Use the calendar module instead:

>>> import calendar
>>> [year for year in range(2017, 2101) if calendar.weekday(year, 3, 22) == calendar.TUESDAY]
[2022, 2033, 2039, 2044, 2050, 2061, 2067, 2072, 2078, 2089, 2095]


问:
The "https://packagist.org/packages.json" file could not be downloaded: SSL operation failed
```<code>When I run the following command
</code>```

sudo composer update

```<code>then I am getting following error.
</code>```

The "https://packagist.org/packages.json" file could not be
  downloaded: SSL operation failed      with code 1. OpenSSL Error
  messages:

  error:140770FC:SSL routines:SSL23_GET_SERVER_HELLO:unknown protocol

  Failed to enable crypto

  failed to open stream: operation failed

答:
I've tried these solutions, but none of them worked for me. I know it may sounds like a dummy workaround, but this what I did in case anyone find it useful:

1) temporarily I enabled my mobile as a wifi hotspot.
2) connected my laptop to this wifi. I have my Vagrant VM here, with Laravel/Composer running.
3) I disabled all proxy environment settings (e.g. http_proxy, https_proxy, etc) within my VM.
4) Then, I successfully created my project, by using "composer global require "laravel/installer" and "composer create-project laravel/laravel" commands.
5) disconnected the wifi hotspot, and started to work normally (ethernet).

HTH.
Carlos.

Body:
When I run the following command

sudo composer update

then I am getting following error.

The "https://packagist.org/packages.json" file could not be
  downloaded: SSL operation failed      with code 1. OpenSSL Error
  messages:

  error:140770FC:SSL routines:SSL23_GET_SERVER_HELLO:unknown protocol

  Failed to enable crypto

  failed to open stream: operation failed


问:
Share an Xcode project as a static library for other people to use in emulator. How do you use an AppDelegate from a .a static library file in Xcode?
I want to share my Xcode project as a static library for other people to use in the xcode emulator (giving them as little raw source code as possible).  How do you use an AppDelegate from a .a library file in Xcode or UIBuilder?

I copied the main Window.xib file to a new project and included all of the other source files in a static .a library that I thought I would be able to invoke somehow.  What do I have to do to launch my main product that is compiled into the .a library from a brand new Xcode project that is including that library?

答:
This is a much better solution found in someone else's question:
iOS Question. Can I distribute the Xcode simulator versions of my app?</p>


问:
Oracle TIMESTAMP and Mybatis issue
I'm using mybatis in my web application.

I'm executing the below select query:

```<code><select id="retrieveSearchResultReferrals" resultType="hashmap" parameterType="map">
    select *
    from
        table(xxxx.test_abc_pk.retrieveDA(#{searchString}))
</select>
</code>```

Of the columns in result some are DATE data type and one column is TIMESTAMP data type.

Mybatis is converting DATE column correctly to java.sql.Date BUT for the TIMESTAMP column it is converting it to oracle.sql.TIMESTAMP instead of java.sql.Timestamp.

Any ideas on how can I make mybatis to convert TIMESTAMP to java.sql.Timestamp?

答:
Try setting property oracle.jdbc.J2EE13Compliant=true for your application.

See java.lang.ClassCastException: oracle.sql.TIMESTAMP cannot be cast to java.sql.Timestamp

Title: Oracle TIMESTAMP and Mybatis issue

Body:
I'm using mybatis in my web application.

I'm executing the below select query:

<select id="retrieveSearchResultReferrals" resultType="hashmap" parameterType="map">
    select *
    from
        table(xxxx.test_abc_pk.retrieveDA(#{searchString}))
</select>

Of the columns in result some are DATE data type and one column is TIMESTAMP data type.

Mybatis is converting DATE column correctly to java.sql.Date BUT for the TIMESTAMP column it is converting it to oracle.sql.TIMESTAMP instead of java.sql.Timestamp.

Any ideas on how can I make mybatis to convert TIMESTAMP to java.sql.Timestamp?


问:
Download file, after generating it based on user input
I have a button on my web app which when clicked generates a text file based on user inputs.
For this i use ajax that send parameters to spring backend. This works. What I want is on the same button when clicked generated file to be downloaded on user computer.

Can this be done without storing the file on server and generating link ?

答:
Maybe data-URI can help you for presenting a download link to the user:

```<code><a href="data:text/plain,this is some text" download="some-filename.txt" target="_blank">Download<a>
</code>```

for more information see Mozilla: Data-URI

credits to the original answer

Body:
Maybe data-URI can help you for presenting a download link to the user:

<a href="data:text/plain,this is some text" download="some-filename.txt" target="_blank">Download<a>

for more information see Mozilla: Data-URI

credits to the original answer


问:
Is EF Core Add Migration Supported from .NET Standard Library?
We have been trying to run EF Core Migration in .Net Standard 1.6 class library, but it has been failing. But same passes very well in .Net Core 1.1 class library.

Is EF Migration supported in .NET STANDARD?

答:
The documentation covers this case as know issue/limitation when the DbContext is placed inside an netstandardx.y Class Library.

Workaround 1 - Use an app as the startup project

If you have an existing .NET Core App or .NET Framework App (including an ASP.NET Core Web Application), you can use it as the startup project. If not, you can create a new one just for use with the .NET Command Line Tools.
  Specify a startup project that is a "runnable app."
  Example: console

```<code>dotnet ef migrations list --startup-project ../MyConsoleApp/
</code>```

Workaround 2 - Cross-target a runnable framework

Add an additional target framework to the class library project. This can a version of either .NET Core App or .NET Framework.
  To make the project a .NET Core App, add the "netcoreapp1.0" framework to project like in the sample below:
  XML

```<code><Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <TargetFrameworks>netcoreapp1.0;netstandard1.4</TargetFrameworks>
  </PropertyGroup>
</Project>
</code>```

When targeting .NET Framework, ensure you project targets version 4.5.1 or newer.
  XML

```<code><Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <TargetFrameworks>net46;netstandard1.4</TargetFrameworks>
  </PropertyGroup>
</Project>
</code>```

Body:
The documentation covers this case as know issue/limitation when the DbContext is placed inside an netstandardx.y Class Library.

Workaround 1 - Use an app as the startup project

If you have an existing .NET Core App or .NET Framework App (including an ASP.NET Core Web Application), you can use it as the startup project. If not, you can create a new one just for use with the .NET Command Line Tools.
  Specify a startup project that is a "runnable app."
  Example: console

dotnet ef migrations list --startup-project ../MyConsoleApp/

Workaround 2 - Cross-target a runnable framework

Add an additional target framework to the class library project. This can a version of either .NET Core App or .NET Framework.
  To make the project a .NET Core App, add the "netcoreapp1.0" framework to project like in the sample below:
  XML

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <TargetFrameworks>netcoreapp1.0;netstandard1.4</TargetFrameworks>
  </PropertyGroup>
</Project>

When targeting .NET Framework, ensure you project targets version 4.5.1 or newer.
  XML

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <TargetFrameworks>net46;netstandard1.4</TargetFrameworks>
  </PropertyGroup>
</Project>


问:
How to process data before storing to database in python eve
I'm currently learning python eve framework and mongoDB database for restful API development. In eve, basic CRUD operations are done only by defining the schema in settings.py file. Client can send GET/POST methods and data is automatically stored into mongoDB according to the predefined schema.

What if I want to preprocess my data before inserting it into mongoDB (e.g.: Client only sends product quantity and price, then the server calculates the total amount and stores product, price and amount to the database). And what if I want to process my data before respond to client. Should we use flask controller methods(like this EVE - define custom flask controllers) and manually store the data to database?

答:
You are asking two things here.

First, if you want to manipulate data already stored before responding to GET requests, what you need is on_fetched_resource_<resource_name> and on_fetched_item_<resource_name> database event hooks. You can add there the information you want to the response before it is returned:

When a GET, POST, PATCH, PUT, DELETE method has been executed, both a on_post_ and on_post__ event is raised. You can subscribe to these events with multiple callback functions. Callbacks will receive the resource accessed, original flask.request object and the response payload.

```<code>def post_get_callback(resource, request, payload):
    print('A GET on the "%s" endpoint was just performed!' % resource)

def post_contacts_get_callback(request, payload):
    print('A get on "contacts" was just performed!')

app = Eve()

app.on_post_GET += post_get_callback
app.on_post_GET_contacts += post_contacts_get_callback

app.run()
</code>```

See documentation here: http://python-eve.org/features.html#post-request-event-hooks

But if you want to process POST data before storing in database what you need is a on_insert_<resource_name> database event hook. You can add there the information you want to the resource before it is saved at database:

Database event hooks work like request event hooks. These events are fired before and after a database action. Here is an example of how events are configured:

```<code>def add_sum(items):
    for item in items:
        item['sum'] = item['a'] + item['b']

app = Eve()
app.on_insert_item += add_sum
</code>```

Body:
You are asking two things here.

First, if you want to manipulate data already stored before responding to GET requests, what you need is on_fetched_resource_<resource_name> and on_fetched_item_<resource_name> database event hooks. You can add there the information you want to the response before it is returned:

When a GET, POST, PATCH, PUT, DELETE method has been executed, both a on_post_ and on_post__ event is raised. You can subscribe to these events with multiple callback functions. Callbacks will receive the resource accessed, original flask.request object and the response payload.

def post_get_callback(resource, request, payload):
    print('A GET on the "%s" endpoint was just performed!' % resource)

def post_contacts_get_callback(request, payload):
    print('A get on "contacts" was just performed!')

app = Eve()

app.on_post_GET += post_get_callback
app.on_post_GET_contacts += post_contacts_get_callback

app.run()

See documentation here: http://python-eve.org/features.html#post-request-event-hooks

But if you want to process POST data before storing in database what you need is a on_insert_<resource_name> database event hook. You can add there the information you want to the resource before it is saved at database:

Database event hooks work like request event hooks. These events are fired before and after a database action. Here is an example of how events are configured:

def add_sum(items):
    for item in items:
        item['sum'] = item['a'] + item['b']

app = Eve()
app.on_insert_item += add_sum


问:
Extract integer from a list
I have a list like ['-1', '1,2,3', '2'] and I want to extract all the integers in it.
I don't know the number of integers in each position of the list ie the list can also be ['2,3,4','1,2,3','-1'] but it will never have an empty string.
So I want that the answer should be [2,3,4,1,2,3,-1]

What is the best way to do so in terms of complexity as well as less code.

Thanks...

答:
Not the same. Test gives the truth.
In THIS case, map() is faster than a list comprehension.

```<code>from time import clock
from random import randint

li = [ ', '.join([str(randint(-30,30)) for i in xrange(randint(1,8))])
       for j in xrange(1000) ]

A,B = [],[]

for fois in xrange(20):
    te = clock()
    res1 = map(int, ','.join(li).split(','))
    A.append( clock()-te )

    te = clock()
    new_list = [ int(i) for i in ','.join(li).split(',') ]
    B.append( clock()-te )

print '{:.1%}.'.format(min(B)/min(A))
</code>```

a result: 115.1%.
not a big one, but there is a difference

Title: Extract integer from a list

Body:
Not the same. Test gives the truth.
In THIS case, map() is faster than a list comprehension.

from time import clock
from random import randint

li = [ ', '.join([str(randint(-30,30)) for i in xrange(randint(1,8))])
       for j in xrange(1000) ]

A,B = [],[]

for fois in xrange(20):
    te = clock()
    res1 = map(int, ','.join(li).split(','))
    A.append( clock()-te )

    te = clock()
    new_list = [ int(i) for i in ','.join(li).split(',') ]
    B.append( clock()-te )

print '{:.1%}.'.format(min(B)/min(A))

a result: 115.1%.
not a big one, but there is a difference


问:
Excel VBA - loop over files in folder, copy range, paste in this workbook
I have 500 excel files with data. I would merge all this data into one file.

Task list to achieve this:

I want to loop over all the files in a folder

open the file,

copy this range "B3:I102"

paste it into the 1st sheet of the active workbook

repeat but paste new data underneath

I've done task 1-4 but i need help with task 5, last bit - pasting the data under the existing data and making it dynamic. I've highlighted this bit with '#### in my code.

Here is my code which I've put together from other people's question :)

Any suggestions on how to do this?

```<code>Sub LoopThroughFiles()
Dim MyObj As Object,
MySource As Object,
file As Variant
Dim wbThis                  As Workbook     'workbook where the data is to be pasted, aka Master file
Dim wbTarget                As Workbook     'workbook from where the data is to be copied from, aka Overnights file
Dim LastRow As Long
Dim sht1 As Worksheet
Dim sht2 As Worksheet

'set to the current active workbook (the source book, the Master!)
Set wbThis = ActiveWorkbook
Set sht1 = wbThis.Sheets("Sheet1")

Folder = "\\dne\ldc\research-dept\3 CEEMEA\15. EMB\Turkey\TLC Overnight & Weekly Reports\weekly (majeed)\"
Fname = Dir(Folder)

While (Fname <> "")

  Set wbTarget = Workbooks.Open(Filename:=Folder & Fname)
  wbTarget.Activate
  Range("b3:i102").Copy

  wbThis.Activate

  '################################
  'NEED HELP HERE. I GET A ERROR HERE. NEEDS TO BE MORE DYNAMIC.
  sht1.Range("b1:i100").PasteSpecial

 Fname = Dir

 'close the overnight's file
  wbTarget.Close
 Wend

End Sub
</code>```

答:
How about you define sht1.Range("b1:i102") as variables instead of constants?

Something like:

```<code>Dim x As Long
Dim y As Long
x = 1
y = 1
Dim rng As Range
Set rng = Range("b"&x ,"i"&y)
</code>```

And then use:

```<code>sht1.rng
</code>```

Just remember to add x = x+100 and y = y +100 at the end of your while statement (so it will update new values between each paste.)

Body:
I have 500 excel files with data. I would merge all this data into one file.

Task list to achieve this:

I want to loop over all the files in a folder

open the file,

copy this range "B3:I102"

paste it into the 1st sheet of the active workbook

repeat but paste new data underneath

I've done task 1-4 but i need help with task 5, last bit - pasting the data under the existing data and making it dynamic. I've highlighted this bit with '#### in my code.

Here is my code which I've put together from other people's question :)

Any suggestions on how to do this?

Sub LoopThroughFiles()
Dim MyObj As Object,
MySource As Object,
file As Variant
Dim wbThis                  As Workbook     'workbook where the data is to be pasted, aka Master file
Dim wbTarget                As Workbook     'workbook from where the data is to be copied from, aka Overnights file
Dim LastRow As Long
Dim sht1 As Worksheet
Dim sht2 As Worksheet

'set to the current active workbook (the source book, the Master!)
Set wbThis = ActiveWorkbook
Set sht1 = wbThis.Sheets("Sheet1")

Folder = "\\dne\ldc\research-dept\3 CEEMEA\15. EMB\Turkey\TLC Overnight & Weekly Reports\weekly (majeed)\"
Fname = Dir(Folder)

While (Fname <> "")

  Set wbTarget = Workbooks.Open(Filename:=Folder & Fname)
  wbTarget.Activate
  Range("b3:i102").Copy

  wbThis.Activate

  '################################
  'NEED HELP HERE. I GET A ERROR HERE. NEEDS TO BE MORE DYNAMIC.
  sht1.Range("b1:i100").PasteSpecial

 Fname = Dir

 'close the overnight's file
  wbTarget.Close
 Wend

End Sub

Body:
How about you define sht1.Range("b1:i102") as variables instead of constants?

Something like:

Dim x As Long
Dim y As Long
x = 1
y = 1
Dim rng As Range
Set rng = Range("b"&x ,"i"&y)

And then use:

sht1.rng

Just remember to add x = x+100 and y = y +100 at the end of your while statement (so it will update new values between each paste.)


问:
Form control with angular.js
I have been playing about with angular and forms but I am having some trouble with the code below. I thought that it should add forenames to the ones already displayed by the ng-repeat whenever the form is submitted but the submit button appears to do nothing.

HTML:

```<code><!DOCTYPE html>
    <html lang="en" ng-app="file">
    <head>
        <meta charset="UTF-8">
        <link rel="stylesheet" type="text/css" href="bootstrap.min.css" />
        <script types="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
        <script types=text/javascript" src="formLoops.js"></script>
        <title>Title</title>
    </head>
    <body ng-controller="PersonalDetailsController as person">
        <p ng-repeat="info in person.details">{{info.forename}}</p>

    <form name="PersonalDetailsForm" ng-controller="DataEntryController as dataCtrl" ng-submit="addPerson(person)">
        <blockquote>
            <p>{{dataCtrl.person.forename}}</p>
            <p>{{dataCtrl.person.surname}}</p>
        </blockquote>

        <label>Forename:</label>
        <input ng-model="dataCtrl.person.forename"/>
        <label>Surname:</label>
        <input ng-model="dataCtrl.person.surname"/>
        <input type="submit" value="submit"/>

    </form>

    </body>
    </html>
</code>```

JS:

```<code>var app = angular.module("file", []);

app.controller("PersonalDetailsController", function() {
  this.details = personalDetails;
});

app.controller("DataEntryController", function() {
  this.person = {};
  this.addPerson = function(person) {
    person.personalDetails.push(this.person);
  };
});

var personalDetails = [{
    forename: "John",
    surname: "Doe"
  },
  {
    forename: "John",
    surname: "Smith"
  }
];
</code>```

答:
You need to do two changes to the code

1) In HTML you need to add the ng-submit="dataCtrl.addPerson(person)"
   since you are using the controller as syntax
2) You need to change your js code as follows person.personalDetails.push(this.person); to person.details.push(this.person);

This is because your repeat is working with the details array so you need to push the new data to the details array itself. You are trying to push the data inside the global array that is why it is not worked

Thanks

Title: Form control with angular.js

Body:
I have been playing about with angular and forms but I am having some trouble with the code below. I thought that it should add forenames to the ones already displayed by the ng-repeat whenever the form is submitted but the submit button appears to do nothing.

HTML:

<!DOCTYPE html>

        <meta charset="UTF-8">
        <link rel="stylesheet" type="text/css" href="bootstrap.min.css" />

        <title>Title</title>

{{info.forename}}

    <form name="PersonalDetailsForm" ng-controller="DataEntryController as dataCtrl" ng-submit="addPerson(person)">

{{dataCtrl.person.forename}}

{{dataCtrl.person.surname}}

        Forename:
        <input ng-model="dataCtrl.person.forename"/>
        Surname:
        <input ng-model="dataCtrl.person.surname"/>
        <input type="submit" value="submit"/>

    </form>

JS:

var app = angular.module("file", []);

app.controller("PersonalDetailsController", function() {
  this.details = personalDetails;
});

app.controller("DataEntryController", function() {
  this.person = {};
  this.addPerson = function(person) {
    person.personalDetails.push(this.person);
  };
});

var personalDetails = [{
    forename: "John",
    surname: "Doe"
  },
  {
    forename: "John",
    surname: "Smith"
  }
];


问:
Hibernate Search, Infinispan and clustering with JGroups
We are attempting to use Hibernate Search in our project together with Infinispan. We have looked in the documentation and tried the easiest configuration, just to define Infinispan as provider. When starting the application (deployed in Tomcat) on two machines on the network, the index on both machines are updated individually but there is no communication between the machines.

This is my configuration.
We are using default tcp communication. What could be wrong?

```<code><?xml version="1.0" encoding="UTF-8"?>
<infinispan
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="urn:infinispan:config:7.0 http://www.infinispan.org/schemas/infinispan-config-7.0.xsd
                    urn:infinispan:config:store:jdbc:7.0 http://www.infinispan.org/schemas/infinispan-cachestore-jdbc-config-7.0.xsd"
xmlns="urn:infinispan:config:7.0"
xmlns:jdbc="urn:infinispan:config:store:jdbc:7.0">

<!-- *************************** -->
<!-- System-wide global settings -->
<!-- *************************** -->
<jgroups>
    <!-- Note that the JGroups transport uses sensible defaults if no configuration
        property is defined. See the JGroupsTransport javadocs for more flags.
        jgroups-udp.xml is the default stack bundled in the Infinispan core jar: integration
        and tuning are tested by Infinispan. -->
  <stack-file name="default-jgroups-tcp" path="default-configs/default-jgroups-tcp.xml" />
</jgroups>

<cache-container name="HibernateSearch" default-cache="default" statistics="false" shutdown-hook="DONT_REGISTER">

    <transport stack="default-jgroups-tcp" cluster="venkatcluster"/>

    <!-- Duplicate domains are allowed so that multiple deployments with default configuration
        of Hibernate Search applications work - if possible it would be better to use JNDI to share
        the CacheManager across applications -->
    <jmx duplicate-domains="true" />

     <!-- *************************************** -->
     <!--  Cache to store Lucene's file metadata  -->
     <!-- *************************************** -->
     <replicated-cache name="LuceneIndexesMetadata" mode="SYNC" remote-timeout="25000">
        <transaction mode="NONE"/>
        <state-transfer enabled="true" timeout="480000" await-initial-transfer="true" />
        <indexing index="NONE" />
        <locking striping="false" acquire-timeout="10000" concurrency-level="500" write-skew="false" />
        <eviction max-entries="-1" strategy="NONE"/>
        <expiration max-idle="-1"/>
        <persistence passivation="false">
            <jdbc:string-keyed-jdbc-store preload="true" fetch-state="true" read-only="false" purge="false">
                <property name="key2StringMapper">org.infinispan.lucene.LuceneKey2StringMapper</property>
                <jdbc:connection-pool connection-url="jdbc:mysql://192.168.2.15:3306/entityindex" driver="com.mysql.jdbc.Driver" password="pf_user1!" username="pf_user"></jdbc:connection-pool>
                <jdbc:string-keyed-table drop-on-exit="false" create-on-start="true" prefix="ISPN_STRING_TABLE">
                    <jdbc:id-column name="ID" type="VARCHAR(255)"/>
                    <jdbc:data-column name="DATA" type="BLOB"/>
                    <jdbc:timestamp-column name="TIMESTAMP" type="BIGINT"/>
                </jdbc:string-keyed-table>
            </jdbc:string-keyed-jdbc-store>
        </persistence>
     </replicated-cache>

     <!-- **************************** -->
     <!--  Cache to store Lucene data  -->
     <!-- **************************** -->
     <distributed-cache name="LuceneIndexesData" mode="SYNC" remote-timeout="25000">
        <transaction mode="NONE"/>
        <state-transfer enabled="true" timeout="480000" await-initial-transfer="true" />
        <indexing index="NONE" />
        <locking striping="false" acquire-timeout="10000" concurrency-level="500" write-skew="false" />
        <eviction max-entries="-1" strategy="NONE"/>
        <expiration max-idle="-1"/>
        <persistence passivation="false">
            <jdbc:string-keyed-jdbc-store preload="true" fetch-state="true" read-only="false" purge="false">
                <property name="key2StringMapper">org.infinispan.lucene.LuceneKey2StringMapper</property>
                <jdbc:connection-pool connection-url="jdbc:mysql://192.168.2.15:3306/entityindex" driver="com.mysql.jdbc.Driver" password="pf_user1!" username="pf_user"></jdbc:connection-pool>
                <jdbc:string-keyed-table drop-on-exit="false" create-on-start="true" prefix="ISPN_STRING_TABLE">
                    <jdbc:id-column name="ID" type="VARCHAR(255)"/>
                    <jdbc:data-column name="DATA" type="BLOB"/>
                    <jdbc:timestamp-column name="TIMESTAMP" type="BIGINT"/>
                </jdbc:string-keyed-table>
            </jdbc:string-keyed-jdbc-store>
        </persistence>
     </distributed-cache>

     <!-- ***************************** -->
     <!--  Cache to store Lucene locks  -->
     <!-- ***************************** -->
    <replicated-cache name="LuceneIndexesLocking" mode="SYNC" remote-timeout="25000">
        <transaction mode="NONE"/>
        <state-transfer enabled="true" timeout="480000" await-initial-transfer="true" />
        <indexing index="NONE" />
        <locking striping="false" acquire-timeout="10000" concurrency-level="500" write-skew="false" />
        <eviction max-entries="-1" strategy="NONE"/>
        <expiration max-idle="-1"/>
        <persistence passivation="false">
            <jdbc:string-keyed-jdbc-store preload="true" fetch-state="true" read-only="false" purge="false">
                <property name="key2StringMapper">org.infinispan.lucene.LuceneKey2StringMapper</property>
                <jdbc:connection-pool connection-url="jdbc:mysql://192.168.2.15:3306/entityindex" driver="com.mysql.jdbc.Driver" password="pf_user1!" username="pf_user"></jdbc:connection-pool>
                <jdbc:string-keyed-table drop-on-exit="false" create-on-start="true" prefix="ISPN_STRING_TABLE">
                    <jdbc:id-column name="ID" type="VARCHAR(255)"/>
                    <jdbc:data-column name="DATA" type="BLOB"/>
                    <jdbc:timestamp-column name="TIMESTAMP" type="BIGINT"/>
                </jdbc:string-keyed-table>
            </jdbc:string-keyed-jdbc-store>
        </persistence>
    </replicated-cache>

</cache-container>
</code>```

答:
You likely need to make some adjustments either to your local network configuration or to the JGroups configuration files.

The default configuration being included with Infinispan is designed to work out of the box in most cases, but it's not possible to make sure of that: networks can be setup in many different ways.

I would suggest testing this first on a loopback network by running the two Tomcat instances on the same machine, make sure you can make that work first.

A useful step in setting up a JGroups based cluster is to run one of the JGroups demos first; they are very simple and might help to confirm your basic configuration is fine.

Running a JGroups demo

The JGroups jar includes some simple demos. It doesn't need any dependency so it's easy to run directly from a commandline.

See the JGroups documentation for several examples.

Test your custom configuration using the JGroups demo

Once you have a demo running across multiple machines, use it to test your custom configuration files.

N.B. you might need to adjust some of your network routing options, for example many systems don't have a reasonable default for multicast IP.

Also check the amount of hops across the network your packets have to walk through. In JGroups configuration files you'll find a ip_ttl setting, if it's not high enough your packets will be dropped by the routers before reaching their destination.

Body:
We are attempting to use Hibernate Search in our project together with Infinispan. We have looked in the documentation and tried the easiest configuration, just to define Infinispan as provider. When starting the application (deployed in Tomcat) on two machines on the network, the index on both machines are updated individually but there is no communication between the machines.

This is my configuration.
We are using default tcp communication. What could be wrong?

<?xml version="1.0" encoding="UTF-8"?>
<infinispan
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="urn:infinispan:config:7.0 http://www.infinispan.org/schemas/infinispan-config-7.0.xsd
                    urn:infinispan:config:store:jdbc:7.0 http://www.infinispan.org/schemas/infinispan-cachestore-jdbc-config-7.0.xsd"
xmlns="urn:infinispan:config:7.0"
xmlns:jdbc="urn:infinispan:config:store:jdbc:7.0">

<jgroups>

  <stack-file name="default-jgroups-tcp" path="default-configs/default-jgroups-tcp.xml" />
</jgroups>

<cache-container name="HibernateSearch" default-cache="default" statistics="false" shutdown-hook="DONT_REGISTER">

    <transport stack="default-jgroups-tcp" cluster="venkatcluster"/>

    <jmx duplicate-domains="true" />

     <replicated-cache name="LuceneIndexesMetadata" mode="SYNC" remote-timeout="25000">
        <transaction mode="NONE"/>
        <state-transfer enabled="true" timeout="480000" await-initial-transfer="true" />
        <indexing index="NONE" />
        <locking striping="false" acquire-timeout="10000" concurrency-level="500" write-skew="false" />
        <eviction max-entries="-1" strategy="NONE"/>
        <expiration max-idle="-1"/>
        <persistence passivation="false">
            <jdbc:string-keyed-jdbc-store preload="true" fetch-state="true" read-only="false" purge="false">
                <property name="key2StringMapper">org.infinispan.lucene.LuceneKey2StringMapper</property>
                <jdbc:connection-pool connection-url="jdbc:mysql://192.168.2.15:3306/entityindex" driver="com.mysql.jdbc.Driver" password="pf_user1!" username="pf_user"></jdbc:connection-pool>
                <jdbc:string-keyed-table drop-on-exit="false" create-on-start="true" prefix="ISPN_STRING_TABLE">
                    <jdbc:id-column name="ID" type="VARCHAR(255)"/>
                    <jdbc:data-column name="DATA" type="BLOB"/>
                    <jdbc:timestamp-column name="TIMESTAMP" type="BIGINT"/>
                </jdbc:string-keyed-table>
            </jdbc:string-keyed-jdbc-store>
        </persistence>
     </replicated-cache>

     <distributed-cache name="LuceneIndexesData" mode="SYNC" remote-timeout="25000">
        <transaction mode="NONE"/>
        <state-transfer enabled="true" timeout="480000" await-initial-transfer="true" />
        <indexing index="NONE" />
        <locking striping="false" acquire-timeout="10000" concurrency-level="500" write-skew="false" />
        <eviction max-entries="-1" strategy="NONE"/>
        <expiration max-idle="-1"/>
        <persistence passivation="false">
            <jdbc:string-keyed-jdbc-store preload="true" fetch-state="true" read-only="false" purge="false">
                <property name="key2StringMapper">org.infinispan.lucene.LuceneKey2StringMapper</property>
                <jdbc:connection-pool connection-url="jdbc:mysql://192.168.2.15:3306/entityindex" driver="com.mysql.jdbc.Driver" password="pf_user1!" username="pf_user"></jdbc:connection-pool>
                <jdbc:string-keyed-table drop-on-exit="false" create-on-start="true" prefix="ISPN_STRING_TABLE">
                    <jdbc:id-column name="ID" type="VARCHAR(255)"/>
                    <jdbc:data-column name="DATA" type="BLOB"/>
                    <jdbc:timestamp-column name="TIMESTAMP" type="BIGINT"/>
                </jdbc:string-keyed-table>
            </jdbc:string-keyed-jdbc-store>
        </persistence>
     </distributed-cache>

    <replicated-cache name="LuceneIndexesLocking" mode="SYNC" remote-timeout="25000">
        <transaction mode="NONE"/>
        <state-transfer enabled="true" timeout="480000" await-initial-transfer="true" />
        <indexing index="NONE" />
        <locking striping="false" acquire-timeout="10000" concurrency-level="500" write-skew="false" />
        <eviction max-entries="-1" strategy="NONE"/>
        <expiration max-idle="-1"/>
        <persistence passivation="false">
            <jdbc:string-keyed-jdbc-store preload="true" fetch-state="true" read-only="false" purge="false">
                <property name="key2StringMapper">org.infinispan.lucene.LuceneKey2StringMapper</property>
                <jdbc:connection-pool connection-url="jdbc:mysql://192.168.2.15:3306/entityindex" driver="com.mysql.jdbc.Driver" password="pf_user1!" username="pf_user"></jdbc:connection-pool>
                <jdbc:string-keyed-table drop-on-exit="false" create-on-start="true" prefix="ISPN_STRING_TABLE">
                    <jdbc:id-column name="ID" type="VARCHAR(255)"/>
                    <jdbc:data-column name="DATA" type="BLOB"/>
                    <jdbc:timestamp-column name="TIMESTAMP" type="BIGINT"/>
                </jdbc:string-keyed-table>
            </jdbc:string-keyed-jdbc-store>
        </persistence>
    </replicated-cache>

</cache-container>


问:
How to run java program in command prompt by outputting results to log file and also to console
I have a Java Program which needs to be executed from command line where the output should be printed in console and also to a file(log file).</p>

答:
If you are using Log4j for logging you should setup appropriate appenders for both Console and File output. Also you could use Remote appender.

Here is an example of such appender:

```<code>log4j.rootLogger=DEBUG, FILE, CONSOLE, REMOTE
log4j.appender.FILE=org.apache.log4j.FileAppender
log4j.appender.FILE.file=/tmp/logs/log.txt
log4j.appender.FILE.layout=org.apache.log4j.PatternLayout
log4j.appender.FILE.layout.ConversionPattern=[%d{MMM dd HH:mm:ss}] %-5p (%F:%L) - %m%n
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=[%d{MMM dd HH:mm:ss}] %-5p (%F:%L) - %m%n
log4j.appender.REMOTE=com.holub.log4j.RemoteAppender
log4j.appender.REMOTE.Port=1234
log4j.appender.REMOTE.layout=org.apache.log4j.PatternLayout
log4j.appender.REMOTE.layout.ConversionPattern=[%d{MMM dd HH:mm:ss}] %-5p (%F:%L) - %m%n
</code>```

Body:
If you are using Log4j for logging you should setup appropriate appenders for both Console and File output. Also you could use Remote appender.

Here is an example of such appender:

log4j.rootLogger=DEBUG, FILE, CONSOLE, REMOTE
log4j.appender.FILE=org.apache.log4j.FileAppender
log4j.appender.FILE.file=/tmp/logs/log.txt
log4j.appender.FILE.layout=org.apache.log4j.PatternLayout
log4j.appender.FILE.layout.ConversionPattern=[%d{MMM dd HH:mm:ss}] %-5p (%F:%L) - %m%n
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=[%d{MMM dd HH:mm:ss}] %-5p (%F:%L) - %m%n
log4j.appender.REMOTE=com.holub.log4j.RemoteAppender
log4j.appender.REMOTE.Port=1234
log4j.appender.REMOTE.layout=org.apache.log4j.PatternLayout
log4j.appender.REMOTE.layout.ConversionPattern=[%d{MMM dd HH:mm:ss}] %-5p (%F:%L) - %m%n


问:
What's the difference between traveling salesman and chinese traveling?
What's the difference between travelling salesman problem (TSP) and Chinese postman problem (CPP)?

For me, both wants go to a destination, and then back.

答:
I think it's just another variation of the pathing problem presented in computer science college courses.

The Chinese traveling salesman problem (C-TSP) is a typical symmetric TSP problem. Its simple description is: Given a list of 31 Chinese capital cities and their pairwise distances, the task is to find the shortest possible tour that visits each city exactly once. The C-TSP is a mediumscale TSP problem, which has (31−1)! / 2 = 1.326 *1032 possible routes.


问:
SQL : Select a table name containing specific string
Suppose I have string to search "Sample String" and I have 100 tables in my database.
I want to search if any of the table contains this string.
Eg. If tlbSample contains string "Sample String" then it should show it.

I tried :-

```<code>SELECT name
FROM sys.tables
WHERE name LIKE '%Sample String%'
</code>```

But no luck.

Please help me.

答:
You can use this. I have copied it from here : https://stackoverflow.com/a/13588431/400447</p>

```<code>DECLARE @SearchStrTableName nvarchar(255), @SearchStrColumnName nvarchar(255), @SearchStrColumnValue nvarchar(255), @SearchStrInXML bit, @FullRowResult bit, @FullRowResultRows int
SET @SearchStrColumnValue = '%searchthis%' /* use LIKE syntax */
SET @FullRowResult = 1
SET @FullRowResultRows = 3
SET @SearchStrTableName = NULL /* NULL for all tables, uses LIKE syntax */
SET @SearchStrColumnName = NULL /* NULL for all columns, uses LIKE syntax */
SET @SearchStrInXML = 0 /* Searching XML data may be slow */

IF OBJECT_ID('tempdb..#Results') IS NOT NULL DROP TABLE #Results
CREATE TABLE #Results (TableName nvarchar(128), ColumnName nvarchar(128), ColumnValue nvarchar(max),ColumnType nvarchar(20))

SET NOCOUNT ON

DECLARE @TableName nvarchar(256) = '',@ColumnName nvarchar(128),@ColumnType nvarchar(20), @QuotedSearchStrColumnValue nvarchar(110), @QuotedSearchStrColumnName nvarchar(110)
SET @QuotedSearchStrColumnValue = QUOTENAME(@SearchStrColumnValue,'''')
DECLARE @ColumnNameTable TABLE (COLUMN_NAME nvarchar(128),DATA_TYPE nvarchar(20))

WHILE @TableName IS NOT NULL
BEGIN
    SET @TableName =
    (
        SELECT MIN(QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME))
        FROM    INFORMATION_SCHEMA.TABLES
        WHERE       TABLE_TYPE = 'BASE TABLE'
            AND TABLE_NAME LIKE COALESCE(@SearchStrTableName,TABLE_NAME)
            AND QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME) > @TableName
            AND OBJECTPROPERTY(OBJECT_ID(QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME)), 'IsMSShipped') = 0
    )
    IF @TableName IS NOT NULL
    BEGIN
        DECLARE @sql VARCHAR(MAX)
        SET @sql = 'SELECT QUOTENAME(COLUMN_NAME),DATA_TYPE
                FROM    INFORMATION_SCHEMA.COLUMNS
                WHERE       TABLE_SCHEMA    = PARSENAME(''' + @TableName + ''', 2)
                AND TABLE_NAME  = PARSENAME(''' + @TableName + ''', 1)
                AND DATA_TYPE IN (' + CASE WHEN ISNUMERIC(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@SearchStrColumnValue,'%',''),'_',''),'[',''),']',''),'-','')) = 1 THEN '''tinyint'',''int'',''smallint'',''bigint'',''numeric'',''decimal'',''smallmoney'',''money'',' ELSE '' END + '''char'',''varchar'',''nchar'',''nvarchar'',''timestamp'',''uniqueidentifier''' + CASE @SearchStrInXML WHEN 1 THEN ',''xml''' ELSE '' END + ')
                AND COLUMN_NAME LIKE COALESCE(' + CASE WHEN @SearchStrColumnName IS NULL THEN 'NULL' ELSE '''' + @SearchStrColumnName + '''' END  + ',COLUMN_NAME)'
        INSERT INTO @ColumnNameTable
        EXEC (@sql)
        WHILE EXISTS (SELECT TOP 1 COLUMN_NAME FROM @ColumnNameTable)
        BEGIN
            PRINT @ColumnName
            SELECT TOP 1 @ColumnName = COLUMN_NAME,@ColumnType = DATA_TYPE FROM @ColumnNameTable
            SET @sql = 'SELECT ''' + @TableName + ''',''' + @ColumnName + ''',' + CASE @ColumnType WHEN 'xml' THEN 'LEFT(CAST(' + @ColumnName + ' AS nvarchar(MAX)), 4096),'''
            WHEN 'timestamp' THEN 'master.dbo.fn_varbintohexstr('+ @ColumnName + '),'''
            ELSE 'LEFT(' + @ColumnName + ', 4096),''' END + @ColumnType + '''
                    FROM ' + @TableName + ' (NOLOCK) ' +
                    ' WHERE ' + CASE @ColumnType WHEN 'xml' THEN 'CAST(' + @ColumnName + ' AS nvarchar(MAX))'
                    WHEN 'timestamp' THEN 'master.dbo.fn_varbintohexstr('+ @ColumnName + ')'
                    ELSE @ColumnName END + ' LIKE ' + @QuotedSearchStrColumnValue
            INSERT INTO #Results
            EXEC(@sql)
            IF @@ROWCOUNT > 0 IF @FullRowResult = 1
            BEGIN
                SET @sql = 'SELECT TOP ' + CAST(@FullRowResultRows AS VARCHAR(3)) + ' ''' + @TableName + ''' AS [TableFound],''' + @ColumnName + ''' AS [ColumnFound],''FullRow>'' AS [FullRow>],*' +
                    ' FROM ' + @TableName + ' (NOLOCK) ' +
                    ' WHERE ' + CASE @ColumnType WHEN 'xml' THEN 'CAST(' + @ColumnName + ' AS nvarchar(MAX))'
                    WHEN 'timestamp' THEN 'master.dbo.fn_varbintohexstr('+ @ColumnName + ')'
                    ELSE @ColumnName END + ' LIKE ' + @QuotedSearchStrColumnValue
                EXEC(@sql)
            END
            DELETE FROM @ColumnNameTable WHERE COLUMN_NAME = @ColumnName
        END
    END
END
SET NOCOUNT OFF

SELECT TableName, ColumnName, ColumnValue, ColumnType, COUNT(*) AS Count FROM #Results
GROUP BY TableName, ColumnName, ColumnValue, ColumnType
</code>```

Body:
Suppose I have string to search "Sample String" and I have 100 tables in my database.
I want to search if any of the table contains this string.
Eg. If tlbSample contains string "Sample String" then it should show it.

I tried :-

SELECT name
FROM sys.tables
WHERE name LIKE '%Sample String%'

But no luck.

Please help me.

Body:
You can use this. I have copied it from here : https://stackoverflow.com/a/13588431/400447

DECLARE @SearchStrTableName nvarchar(255), @SearchStrColumnName nvarchar(255), @SearchStrColumnValue nvarchar(255), @SearchStrInXML bit, @FullRowResult bit, @FullRowResultRows int
SET @SearchStrColumnValue = '%searchthis%' /* use LIKE syntax */
SET @FullRowResult = 1
SET @FullRowResultRows = 3
SET @SearchStrTableName = NULL /* NULL for all tables, uses LIKE syntax */
SET @SearchStrColumnName = NULL /* NULL for all columns, uses LIKE syntax */
SET @SearchStrInXML = 0 /* Searching XML data may be slow */

IF OBJECT_ID('tempdb..#Results') IS NOT NULL DROP TABLE #Results
CREATE TABLE #Results (TableName nvarchar(128), ColumnName nvarchar(128), ColumnValue nvarchar(max),ColumnType nvarchar(20))

SET NOCOUNT ON

DECLARE @TableName nvarchar(256) = '',@ColumnName nvarchar(128),@ColumnType nvarchar(20), @QuotedSearchStrColumnValue nvarchar(110), @QuotedSearchStrColumnName nvarchar(110)
SET @QuotedSearchStrColumnValue = QUOTENAME(@SearchStrColumnValue,'''')
DECLARE @ColumnNameTable TABLE (COLUMN_NAME nvarchar(128),DATA_TYPE nvarchar(20))

WHILE @TableName IS NOT NULL
BEGIN
    SET @TableName =
    (
        SELECT MIN(QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME))
        FROM    INFORMATION_SCHEMA.TABLES
        WHERE       TABLE_TYPE = 'BASE TABLE'
            AND TABLE_NAME LIKE COALESCE(@SearchStrTableName,TABLE_NAME)
            AND QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME) > @TableName
            AND OBJECTPROPERTY(OBJECT_ID(QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME)), 'IsMSShipped') = 0
    )
    IF @TableName IS NOT NULL
    BEGIN
        DECLARE @sql VARCHAR(MAX)
        SET @sql = 'SELECT QUOTENAME(COLUMN_NAME),DATA_TYPE
                FROM    INFORMATION_SCHEMA.COLUMNS
                WHERE       TABLE_SCHEMA    = PARSENAME(''' + @TableName + ''', 2)
                AND TABLE_NAME  = PARSENAME(''' + @TableName + ''', 1)
                AND DATA_TYPE IN (' + CASE WHEN ISNUMERIC(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@SearchStrColumnValue,'%',''),'_',''),'[',''),']',''),'-','')) = 1 THEN '''tinyint'',''int'',''smallint'',''bigint'',''numeric'',''decimal'',''smallmoney'',''money'',' ELSE '' END + '''char'',''varchar'',''nchar'',''nvarchar'',''timestamp'',''uniqueidentifier''' + CASE @SearchStrInXML WHEN 1 THEN ',''xml''' ELSE '' END + ')
                AND COLUMN_NAME LIKE COALESCE(' + CASE WHEN @SearchStrColumnName IS NULL THEN 'NULL' ELSE '''' + @SearchStrColumnName + '''' END  + ',COLUMN_NAME)'
        INSERT INTO @ColumnNameTable
        EXEC (@sql)
        WHILE EXISTS (SELECT TOP 1 COLUMN_NAME FROM @ColumnNameTable)
        BEGIN
            PRINT @ColumnName
            SELECT TOP 1 @ColumnName = COLUMN_NAME,@ColumnType = DATA_TYPE FROM @ColumnNameTable
            SET @sql = 'SELECT ''' + @TableName + ''',''' + @ColumnName + ''',' + CASE @ColumnType WHEN 'xml' THEN 'LEFT(CAST(' + @ColumnName + ' AS nvarchar(MAX)), 4096),'''
            WHEN 'timestamp' THEN 'master.dbo.fn_varbintohexstr('+ @ColumnName + '),'''
            ELSE 'LEFT(' + @ColumnName + ', 4096),''' END + @ColumnType + '''
                    FROM ' + @TableName + ' (NOLOCK) ' +
                    ' WHERE ' + CASE @ColumnType WHEN 'xml' THEN 'CAST(' + @ColumnName + ' AS nvarchar(MAX))'
                    WHEN 'timestamp' THEN 'master.dbo.fn_varbintohexstr('+ @ColumnName + ')'
                    ELSE @ColumnName END + ' LIKE ' + @QuotedSearchStrColumnValue
            INSERT INTO #Results
            EXEC(@sql)
            IF @@ROWCOUNT > 0 IF @FullRowResult = 1
            BEGIN
                SET @sql = 'SELECT TOP ' + CAST(@FullRowResultRows AS VARCHAR(3)) + ' ''' + @TableName + ''' AS [TableFound],''' + @ColumnName + ''' AS [ColumnFound],''FullRow>'' AS [FullRow>],*' +
                    ' FROM ' + @TableName + ' (NOLOCK) ' +
                    ' WHERE ' + CASE @ColumnType WHEN 'xml' THEN 'CAST(' + @ColumnName + ' AS nvarchar(MAX))'
                    WHEN 'timestamp' THEN 'master.dbo.fn_varbintohexstr('+ @ColumnName + ')'
                    ELSE @ColumnName END + ' LIKE ' + @QuotedSearchStrColumnValue
                EXEC(@sql)
            END
            DELETE FROM @ColumnNameTable WHERE COLUMN_NAME = @ColumnName
        END
    END
END
SET NOCOUNT OFF

SELECT TableName, ColumnName, ColumnValue, ColumnType, COUNT(*) AS Count FROM #Results
GROUP BY TableName, ColumnName, ColumnValue, ColumnType


问:
All apps associated with this action have been disabled, blocked, or are not installed Storage Access Framework
In my application I am trying to get MS-Word and PDF files through Storage Access Framework which works well on some devices I've tested upon but on Samsung note 4 API 6 I am getting an error

All apps associated with this action have been disabled, blocked, or
  are not installed

Code:

```<code>warantyButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                intent.addCategory(Intent.CATEGORY_OPENABLE);
                intent.setType("application/pdf,application/msword");
                Intent i = Intent.createChooser(intent, "File");
                getActivity().startActivityForResult(i, FILE_REQ_CODE);

            }
        });
</code>```

答:
Since setType() method of Intent takes one argument as String i.e MIME type and its compulsary because based on the MIME type requested android system finds all actions that are supported.

For example if you want to choose any type of content then you can simply write setType("*/*").

Body:
In my application I am trying to get MS-Word and PDF files through Storage Access Framework which works well on some devices I've tested upon but on Samsung note 4 API 6 I am getting an error

All apps associated with this action have been disabled, blocked, or
  are not installed

Code:

warantyButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                intent.addCategory(Intent.CATEGORY_OPENABLE);
                intent.setType("application/pdf,application/msword");
                Intent i = Intent.createChooser(intent, "File");
                getActivity().startActivityForResult(i, FILE_REQ_CODE);

            }
        });


问:
Font not found SKLabelNode warning in Xcode Log
I am using sprite kit to create a custom view in my apple watch. I have added a custom font to SKLabelNode. That font is applied and works too when I run the code in my device and watch. But every time I get below warning

SKLabelNode: "SFCompactText-Regular" font not found.

Fonts are applied to the label and works perfect and doesn't crash too. So why is this warning shown everytime?

Below is the list which came from output of apple watch:

```<code>Arial Hebrew
   ArialHebrew-Bold
   ArialHebrew-Light
   ArialHebrew
Myanmar Sangam MN
   MyanmarSangamMN-Bold
   MyanmarSangamMN
Oriya Sangam MN
   OriyaSangamMN-Bold
   OriyaSangamMN
Symbol
   Symbol
Gurmukhi MN
   GurmukhiMN-Bold
   GurmukhiMN
Tamil Sangam MN
   TamilSangamMN-Bold
   TamilSangamMN
Courier New
   CourierNewPSMT
   CourierNewPS-BoldMT
   CourierNewPS-BoldItalicMT
   CourierNewPS-ItalicMT
Courier
   Courier-BoldOblique
   Courier-Oblique
   Courier
   Courier-Bold
Kohinoor Bangla
   KohinoorBangla-Regular
   KohinoorBangla-Semibold
   KohinoorBangla-Light
Apple Color Emoji
   AppleColorEmoji
Lao Sangam MN
   LaoSangamMN
Bangla Sangam MN
Telugu Sangam MN
Kailasa
   Kailasa-Bold
   Kailasa
PingFang TC
   PingFangTC-Light
   PingFangTC-Thin
   PingFangTC-Ultralight
   PingFangTC-Semibold
   PingFangTC-Regular
   PingFangTC-Medium
Heiti SC
Malayalam Sangam MN
   MalayalamSangamMN
   MalayalamSangamMN-Bold
Thonburi
   Thonburi
   Thonburi-Bold
   Thonburi-Light
Zapf Dingbats
   ZapfDingbatsITC
Kohinoor Telugu
   KohinoorTelugu-Medium
   KohinoorTelugu-Regular
   KohinoorTelugu-Light
Avenir Next
   AvenirNext-HeavyItalic
   AvenirNext-DemiBoldItalic
   AvenirNext-BoldItalic
   AvenirNext-UltraLight
   AvenirNext-MediumItalic
   AvenirNext-Bold
   AvenirNext-Medium
   AvenirNext-Italic
   AvenirNext-UltraLightItalic
   AvenirNext-Regular
   AvenirNext-Heavy
   AvenirNext-DemiBold
Apple SD Gothic Neo
   AppleSDGothicNeo-Bold
   AppleSDGothicNeo-Medium
   AppleSDGothicNeo-UltraLight
   AppleSDGothicNeo-Regular
   AppleSDGothicNeo-Light
   AppleSDGothicNeo-Thin
   AppleSDGothicNeo-SemiBold
Helvetica
   Helvetica-BoldOblique
   Helvetica-Light
   Helvetica-Oblique
   Helvetica-LightOblique
   Helvetica-Bold
   Helvetica
Euphemia UCAS
   EuphemiaUCAS
   EuphemiaUCAS-Italic
   EuphemiaUCAS-Bold
PingFang SC
   PingFangSC-Thin
   PingFangSC-Medium
   PingFangSC-Regular
   PingFangSC-Ultralight
   PingFangSC-Semibold
   PingFangSC-Light
PingFang HK
   PingFangHK-Thin
   PingFangHK-Ultralight
   PingFangHK-Semibold
   PingFangHK-Light
   PingFangHK-Medium
   PingFangHK-Regular
Gujarati Sangam MN
   GujaratiSangamMN
   GujaratiSangamMN-Bold
Heiti TC
Sinhala Sangam MN
   SinhalaSangamMN-Bold
   SinhalaSangamMN
Kannada Sangam MN
   KannadaSangamMN
   KannadaSangamMN-Bold
Hiragino Sans
   HiraginoSans-W3
   HiraginoSans-W6
Khmer Sangam MN
   KhmerSangamMN
Times New Roman
   TimesNewRomanPSMT
   TimesNewRomanPS-ItalicMT
   TimesNewRomanPS-BoldItalicMT
   TimesNewRomanPS-BoldMT
Geeza Pro
   GeezaPro
   GeezaPro-Bold
Helvetica Neue
   HelveticaNeue-ThinItalic
   HelveticaNeue-CondensedBold
   HelveticaNeue-Light
   HelveticaNeue-UltraLightItalic
   HelveticaNeue-CondensedBlack
   HelveticaNeue-MediumItalic
   HelveticaNeue-Thin
   HelveticaNeue-Italic
   HelveticaNeue-Bold
   HelveticaNeue
   HelveticaNeue-LightItalic
   HelveticaNeue-UltraLight
   HelveticaNeue-BoldItalic
   HelveticaNeue-Medium
Kohinoor Devanagari
   KohinoorDevanagari-Regular
   KohinoorDevanagari-Semibold
   KohinoorDevanagari-Light
Avenir
   Avenir-Roman
   Avenir-Black
   Avenir-BlackOblique
   Avenir-HeavyOblique
   Avenir-Oblique
   Avenir-Medium
   Avenir-Light
   Avenir-MediumOblique
   Avenir-BookOblique
   Avenir-LightOblique
   Avenir-Book
   Avenir-Heavy
</code>```

答:
I solved my question with below steps:

-Added my font in Watch Extension target.

-Added target membership to both WatchApp and WatchExtension.

-Added entry of fonts in both WatchApp and WatchExtension info.plist files.

-Check the actual font name using below code.

```<code>for fontFamily in UIFont.familyNames {
        print("Font family name = \(fontFamily as String)")
        for fontName in UIFont.fontNames(forFamilyName: fontFamily as String) {
            print("- Font name = \(fontName)")
        }
}
</code>```

-Created a struct constant for my custom fonts.

```<code>struct UIFontConst {
    static let SF_COMPACT_TEXT_REGULAR  = UIFont(name: "SFCompactText-Regular", size: 9.0)
}
</code>```

-And using like UIFontConst.SF_COMPACT_TEXT_REGULAR?.fontName.

Body:
I am using sprite kit to create a custom view in my apple watch. I have added a custom font to SKLabelNode. That font is applied and works too when I run the code in my device and watch. But every time I get below warning

SKLabelNode: "SFCompactText-Regular" font not found.

Fonts are applied to the label and works perfect and doesn't crash too. So why is this warning shown everytime?

Below is the list which came from output of apple watch:

Arial Hebrew
   ArialHebrew-Bold
   ArialHebrew-Light
   ArialHebrew
Myanmar Sangam MN
   MyanmarSangamMN-Bold
   MyanmarSangamMN
Oriya Sangam MN
   OriyaSangamMN-Bold
   OriyaSangamMN
Symbol
   Symbol
Gurmukhi MN
   GurmukhiMN-Bold
   GurmukhiMN
Tamil Sangam MN
   TamilSangamMN-Bold
   TamilSangamMN
Courier New
   CourierNewPSMT
   CourierNewPS-BoldMT
   CourierNewPS-BoldItalicMT
   CourierNewPS-ItalicMT
Courier
   Courier-BoldOblique
   Courier-Oblique
   Courier
   Courier-Bold
Kohinoor Bangla
   KohinoorBangla-Regular
   KohinoorBangla-Semibold
   KohinoorBangla-Light
Apple Color Emoji
   AppleColorEmoji
Lao Sangam MN
   LaoSangamMN
Bangla Sangam MN
Telugu Sangam MN
Kailasa
   Kailasa-Bold
   Kailasa
PingFang TC
   PingFangTC-Light
   PingFangTC-Thin
   PingFangTC-Ultralight
   PingFangTC-Semibold
   PingFangTC-Regular
   PingFangTC-Medium
Heiti SC
Malayalam Sangam MN
   MalayalamSangamMN
   MalayalamSangamMN-Bold
Thonburi
   Thonburi
   Thonburi-Bold
   Thonburi-Light
Zapf Dingbats
   ZapfDingbatsITC
Kohinoor Telugu
   KohinoorTelugu-Medium
   KohinoorTelugu-Regular
   KohinoorTelugu-Light
Avenir Next
   AvenirNext-HeavyItalic
   AvenirNext-DemiBoldItalic
   AvenirNext-BoldItalic
   AvenirNext-UltraLight
   AvenirNext-MediumItalic
   AvenirNext-Bold
   AvenirNext-Medium
   AvenirNext-Italic
   AvenirNext-UltraLightItalic
   AvenirNext-Regular
   AvenirNext-Heavy
   AvenirNext-DemiBold
Apple SD Gothic Neo
   AppleSDGothicNeo-Bold
   AppleSDGothicNeo-Medium
   AppleSDGothicNeo-UltraLight
   AppleSDGothicNeo-Regular
   AppleSDGothicNeo-Light
   AppleSDGothicNeo-Thin
   AppleSDGothicNeo-SemiBold
Helvetica
   Helvetica-BoldOblique
   Helvetica-Light
   Helvetica-Oblique
   Helvetica-LightOblique
   Helvetica-Bold
   Helvetica
Euphemia UCAS
   EuphemiaUCAS
   EuphemiaUCAS-Italic
   EuphemiaUCAS-Bold
PingFang SC
   PingFangSC-Thin
   PingFangSC-Medium
   PingFangSC-Regular
   PingFangSC-Ultralight
   PingFangSC-Semibold
   PingFangSC-Light
PingFang HK
   PingFangHK-Thin
   PingFangHK-Ultralight
   PingFangHK-Semibold
   PingFangHK-Light
   PingFangHK-Medium
   PingFangHK-Regular
Gujarati Sangam MN
   GujaratiSangamMN
   GujaratiSangamMN-Bold
Heiti TC
Sinhala Sangam MN
   SinhalaSangamMN-Bold
   SinhalaSangamMN
Kannada Sangam MN
   KannadaSangamMN
   KannadaSangamMN-Bold
Hiragino Sans
   HiraginoSans-W3
   HiraginoSans-W6
Khmer Sangam MN
   KhmerSangamMN
Times New Roman
   TimesNewRomanPSMT
   TimesNewRomanPS-ItalicMT
   TimesNewRomanPS-BoldItalicMT
   TimesNewRomanPS-BoldMT
Geeza Pro
   GeezaPro
   GeezaPro-Bold
Helvetica Neue
   HelveticaNeue-ThinItalic
   HelveticaNeue-CondensedBold
   HelveticaNeue-Light
   HelveticaNeue-UltraLightItalic
   HelveticaNeue-CondensedBlack
   HelveticaNeue-MediumItalic
   HelveticaNeue-Thin
   HelveticaNeue-Italic
   HelveticaNeue-Bold
   HelveticaNeue
   HelveticaNeue-LightItalic
   HelveticaNeue-UltraLight
   HelveticaNeue-BoldItalic
   HelveticaNeue-Medium
Kohinoor Devanagari
   KohinoorDevanagari-Regular
   KohinoorDevanagari-Semibold
   KohinoorDevanagari-Light
Avenir
   Avenir-Roman
   Avenir-Black
   Avenir-BlackOblique
   Avenir-HeavyOblique
   Avenir-Oblique
   Avenir-Medium
   Avenir-Light
   Avenir-MediumOblique
   Avenir-BookOblique
   Avenir-LightOblique
   Avenir-Book
   Avenir-Heavy

Body:
I solved my question with below steps:

-Added my font in Watch Extension target.

-Added target membership to both WatchApp and WatchExtension.

-Added entry of fonts in both WatchApp and WatchExtension info.plist files.

-Check the actual font name using below code.

for fontFamily in UIFont.familyNames {
        print("Font family name = \(fontFamily as String)")
        for fontName in UIFont.fontNames(forFamilyName: fontFamily as String) {
            print("- Font name = \(fontName)")
        }
}

-Created a struct constant for my custom fonts.

struct UIFontConst {
    static let SF_COMPACT_TEXT_REGULAR  = UIFont(name: "SFCompactText-Regular", size: 9.0)
}

-And using like UIFontConst.SF_COMPACT_TEXT_REGULAR?.fontName.


问:
How to eliminate empty columns to be inserted to DB if CSV files contains empty columns?
I have a table in database with 5 columns. In CSV file I have data like below.  How to process it into Oracle database by elimating empty columns (because CSV file contains 6 columns, it will mismatch in database columns having 5 columns).</p>

```<code>    111, ,John,2000,   ,US
    222, ,Alle,3000,   ,China
    333, ,Kite,4000,LCD,IND
    444, ,King,5000,LED,Aust

package com.java;
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.List;
import java.util.Vector;
public class Test3
{
    public static void main(String[] args)
    {
        try
        {
            int commas = 0;
            List data = new Vector();
            List columnCount = new Vector();
            String[] cols = null;
            String[] strArray = null;
            String file = "D:/temp/CSV/data.csv";
            BufferedReader br = new BufferedReader(new FileReader(file));
            String line = br.readLine();
            do
            {
                commas = 0;
                cols = line.split(",");
                strArray = new String[cols.length];
                int i=0;
                for (String element : cols)
                {
                    if (!isBlank(element))
                    {
                        strArray[i] = element;
                        i++;
                    }
                }
                int newFile = line.length();
                for(int k = 0; k < newFile; k ++ )
                {
                    char eachChar = line.charAt(k);
                    if(eachChar == ',')
                    {
                        commas ++;
                    }
                }

                data.add(strArray);
                line = br.readLine();
            }
            while (line != null);
            Vector columns = new Vector(commas + 1);
            for(int i = 0; i < commas +1 ; i ++ )
            {
                columns.add("" + i);
            }
        } catch (Exception e) {

        }
    }
    public static boolean isBlank(String str) {
        int strLen;

        if (str == null || (strLen = str.length()) == 0)
        {

            return true;
        }

        for (int i = 0; i < strLen; i++)
        {
            if ((Character.isWhitespace(str.charAt(i)) == false)) {
                return false;
            }
        }
        return true;

    }

}
</code>```

答:
You can use a util method to check if it is empty string or not.

```<code>public static boolean isBlank(String str) {
        int strLen;
        if (str == null || (strLen = str.length()) == 0) {
            return true;
        }
        for (int i = 0; i < strLen; i++) {
            if ((Character.isWhitespace(str.charAt(i)) == false)) {
                return false;
            }
        }
        return true;
    }
</code>```

and use it in your reader like below

```<code>Scanner s = null;
        try {
            s = new Scanner(new File("D:/sri/Test.txt"));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        while (s.hasNextLine()) {
            String[] line = s.nextLine().split(",");
            for (String element : line) {
                if (!isBlank(element))
                    System.out.println(element);
            }

        }
</code>```

Body:
I have a table in database with 5 columns. In CSV file I have data like below.  How to process it into Oracle database by elimating empty columns (because CSV file contains 6 columns, it will mismatch in database columns having 5 columns).

    111, ,John,2000,   ,US
    222, ,Alle,3000,   ,China
    333, ,Kite,4000,LCD,IND
    444, ,King,5000,LED,Aust

package com.java;
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.List;
import java.util.Vector;
public class Test3
{
    public static void main(String[] args)
    {
        try
        {
            int commas = 0;
            List data = new Vector();
            List columnCount = new Vector();
            String[] cols = null;
            String[] strArray = null;
            String file = "D:/temp/CSV/data.csv";
            BufferedReader br = new BufferedReader(new FileReader(file));
            String line = br.readLine();
            do
            {
                commas = 0;
                cols = line.split(",");
                strArray = new String[cols.length];
                int i=0;
                for (String element : cols)
                {
                    if (!isBlank(element))
                    {
                        strArray[i] = element;
                        i++;
                    }
                }
                int newFile = line.length();
                for(int k = 0; k < newFile; k ++ )
                {
                    char eachChar = line.charAt(k);
                    if(eachChar == ',')
                    {
                        commas ++;
                    }
                }

                data.add(strArray);
                line = br.readLine();
            }
            while (line != null);
            Vector columns = new Vector(commas + 1);
            for(int i = 0; i < commas +1 ; i ++ )
            {
                columns.add("" + i);
            }
        } catch (Exception e) {

        }
    }
    public static boolean isBlank(String str) {
        int strLen;

        if (str == null || (strLen = str.length()) == 0)
        {

            return true;
        }

        for (int i = 0; i < strLen; i++)
        {
            if ((Character.isWhitespace(str.charAt(i)) == false)) {
                return false;
            }
        }
        return true;

    }

}

Body:
You can use a util method to check if it is empty string or not.

public static boolean isBlank(String str) {
        int strLen;
        if (str == null || (strLen = str.length()) == 0) {
            return true;
        }
        for (int i = 0; i < strLen; i++) {
            if ((Character.isWhitespace(str.charAt(i)) == false)) {
                return false;
            }
        }
        return true;
    }

and use it in your reader like below

Scanner s = null;
        try {
            s = new Scanner(new File("D:/sri/Test.txt"));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        while (s.hasNextLine()) {
            String[] line = s.nextLine().split(",");
            for (String element : line) {
                if (!isBlank(element))
                    System.out.println(element);
            }

        }


问:
Alternative to View for complex Data?
I have a table that contains partial data that is of no use to the user viewing my application. The viewer wants to see a similar table that has all the values calculated out, and wants to be able to quickly query THAT data. Normally, this would be the perfect place to use a View. Unfortunately the complex nature of the calculations limit my use of Views, so I need an alternate solution. I was thinking of doing something like the following...

Table A contains back-end data. Any time this table is updated, a trigger fired that updates Table B, which shows the result of these calculations. Table B can be queried quickly at this point.

My only concern is that the calculation procedure is somewhat lengthy, and Table A has the potential to be updated many times in bursts. Are there any solutions that are almost like a "Before Select" trigger? So basically Table A could be updated many times in a row, but the calculation would only occur when Table B was queried?

Here's an example timeline:

Table A is Updated

Table A is Updated Again [Don't run SP since nobody needs Table B data yet]

Data is requested from Table B [Run SP to update Table B before getting data]

Table A is Updated

Data is requested from Table B [Run SP to update Table B before getting data]

Data is requested from Table B [Don't run stored procedure because Table A wasn't updated between requests for Table B data]

So my questions are:

Is there anything existing like what I described above?

If not, is there a way to make triggers hold off until the completion of a batch of updates/inserts? Table A won't be modified very often, so I can live with a slow trigger when it is updated. The only problem is that when Table A does get updated, it is normally hundreds of rows at a time and I don't want a slow trigger to run every time.

Thanks for any solutions/insight!

Edit - A little more detail on why (I think at least) the trigger implementation would be slow:

The application that will be sending the Update/Insert/Delete statements is using LINQ-to-SQL, which isn't particularly good with batch operations. So if I wanted to delete a bunch of records, it would send a bunch of delete statements instead of a batch delete statement. Is there any way to group delete statements and have the trigger run after that? (Maybe I'm getting too far off topic here).

The "calculations" I'm speaking of involve some recursive functions and some decision-making processes. The data I'm actually dealing with is scheduling data. So Table A contains tasks which may or may not have a scheduled start. If there is no scheduled start defined, it has to derive it from its predecessors scheduled start + its predecessors duration. In some cases the predecessor might not have that information either, hence the recursive query that keeps digging until it finds the result. It's not painfully slow, but if it had to run on every insert/update/delete, it would get there. The "Table B" I refer to above is basically the same table, but it already has the calculated scheduled start data within (which needs to change on update of Table A).

答:
Triggers operate on the entire batch of records that are inserted or updated, not one row at a time.

If the calculations are taking too long with a only a few hundred new records, then the calculation itself probably needs to be performance tuned.

If you do the calculations in a trigger, then they are part of each transaction and they will finish before another transaction is allowed, so it could conceivably slow down inserts. If you write the trigger properly to deal with sets of data and not row-by-agonizing-row, it probably will not cause an issue. Hundreds of rows are a trivial amount to do most calulations on. If you were inserting millions of rows in a batch, I would be more concerned about the trigger performance interfering with other processes.

You could create a proc to do the calculations and schedule it to run every ten minutes or so and then run again when the report is called for. This way it might do most of the precalcualting in advance and just catch the last couple of new records at the report time.

Give us a sample of the calculation and the potential trigger and we can better help you.

There is no way to group a bunch if individual transactions into one group trigger run. Perhaps you should stop using LINQ for this and and senda abatch stament if you need batches to process together. Set-based operations are usually preferable if you are working with more than one record at a time.

Title: Alternative to View for complex Data?