问:
Why does mktime() need to know about daylight saving time?
So mktime() returns a time_t value which is defined as "an integral value representing the number of seconds elapsed since 00:00 hours, Jan 1, 1970 UTC" (source). I can convert a date to a time_t value by using mktime(). For example, to convert the date 10-Sep-2017 08:34:56 to a time_t I'd do the following:

```<code>struct tm tm;
time_t tv;

tm.tm_sec = 56;
tm.tm_min = 34;
tm.tm_hour = 8;
tm.tm_mday = 10;
tm.tm_mon = 8;
tm.tm_year = 117;
tm.tm_isdst = ????;

tv = mktime(&tm);
</code>```

Now what I don't understand is the idea behind the tm_isdst parameter: It is described as "a flag that indicates whether daylight saving time is in effect at the time described" (source).

This description is somewhat confusing me because I'm of the opinion that the time I'm describing in struct tm is in fact already a UTC time and the time_t value I want to have from mktime() is UTC as well. But UTC time doesn't change with a change of seasons, so why does mktime() need to bother with daylight saving time at all? Isn't the advantage of using UTC instead of local time that I won't have to bother with daylight saving time? So why do I have to set tm_isdst then?

I'm sure the answer is really simple but at the moment I'm failing to see it. Could somebody please provide a simple example that illustrates why mktime() needs the tm_isdst parameter to convert a certain date and time to a time_t value?

答:
Whether DST is in effect changes what the epoch time will be because mktime uses the current time zone to determine the time.

For example, if I populate tm with 1/1/70 00:00:00 as follows:

```<code>tm.tm_sec = 0;
tm.tm_min = 0;
tm.tm_hour = 0;
tm.tm_mday = 1;
tm.tm_mon = 0;
tm.tm_year = 70;
tm.tm_isdst = 0;
</code>```

I get a value of 18000 for tv because my timezone is GMT-5 (18000 = 3600 * 5).  If I change the value of tm_isdst to 1, then tv will be set to 14400 (3600 * 4).

Setting tm_isdst to -1 will look at the local timezone database to see if DST is in effect for the given date/time.

Body:
So mktime() returns a time_t value which is defined as "an integral value representing the number of seconds elapsed since 00:00 hours, Jan 1, 1970 UTC" (source). I can convert a date to a time_t value by using mktime(). For example, to convert the date 10-Sep-2017 08:34:56 to a time_t I'd do the following:

struct tm tm;
time_t tv;

tm.tm_sec = 56;
tm.tm_min = 34;
tm.tm_hour = 8;
tm.tm_mday = 10;
tm.tm_mon = 8;
tm.tm_year = 117;
tm.tm_isdst = ????;

tv = mktime(&tm);

Now what I don't understand is the idea behind the tm_isdst parameter: It is described as "a flag that indicates whether daylight saving time is in effect at the time described" (source).

This description is somewhat confusing me because I'm of the opinion that the time I'm describing in struct tm is in fact already a UTC time and the time_t value I want to have from mktime() is UTC as well. But UTC time doesn't change with a change of seasons, so why does mktime() need to bother with daylight saving time at all? Isn't the advantage of using UTC instead of local time that I won't have to bother with daylight saving time? So why do I have to set tm_isdst then?

I'm sure the answer is really simple but at the moment I'm failing to see it. Could somebody please provide a simple example that illustrates why mktime() needs the tm_isdst parameter to convert a certain date and time to a time_t value?

Body:
Whether DST is in effect changes what the epoch time will be because mktime uses the current time zone to determine the time.

For example, if I populate tm with 1/1/70 00:00:00 as follows:

tm.tm_sec = 0;
tm.tm_min = 0;
tm.tm_hour = 0;
tm.tm_mday = 1;
tm.tm_mon = 0;
tm.tm_year = 70;
tm.tm_isdst = 0;

I get a value of 18000 for tv because my timezone is GMT-5 (18000 = 3600 * 5).  If I change the value of tm_isdst to 1, then tv will be set to 14400 (3600 * 4).

Setting tm_isdst to -1 will look at the local timezone database to see if DST is in effect for the given date/time.


来源: stackexchange

问:
BigQuery add number to row_number()
I'm new to BigQuery and I would like to ask if there is a possible way to set a starting number for row_number() function using the Legacy SQL. I have tried this code:

```<code>SELECT
ROW_NUMBER() OVER(order by col1) + 20 AS xxx
From tb1
</code>```

but it return this error:

Error: Encountered " "+" "+ "" at line 2, column 44. Was expecting:

Any answer will be greatly appreciated

Thanks!

答:
If you are new to BigQuery - it is highly recommended to start with BigQuery Standard SQL

And if you willing to follow this advice - below will work without any workarounds (subselect for example in legacy sql)

#standardSQL
SELECT
  20 + ROW_NUMBER() OVER(ORDER BY col1) AS xxx
FROM `project.dataset.tb1`
```

<p>You can test / play with above using dummy data as below  </p>

<pre class="lang-sql prettyprint-override"><code>#standardSQL
WITH `project.dataset.tb1` AS (
  SELECT 1 col1 UNION ALL
  SELECT 111 col1 UNION ALL
  SELECT 11 col1
)
SELECT
  col1, 20 + ROW_NUMBER() OVER(ORDER BY col1) AS xxx
FROM `project.dataset.tb1`
</code>```

with output as

col1    xxx
1       21
11      22
111     23
```

ContentLicense: CC BY-SA 3.0

Title: BigQuery add number to row_number()

Body:
I'm new to BigQuery and I would like to ask if there is a possible way to set a starting number for row_number() function using the Legacy SQL. I have tried this code:

SELECT
ROW_NUMBER() OVER(order by col1) + 20 AS xxx
From tb1

but it return this error:

Error: Encountered " "+" "+ "" at line 2, column 44. Was expecting:

Any answer will be greatly appreciated

Thanks!

Body:
If you are new to BigQuery - it is highly recommended to start with BigQuery Standard SQL

And if you willing to follow this advice - below will work without any workarounds (subselect for example in legacy sql)

#standardSQL
SELECT
  20 + ROW_NUMBER() OVER(ORDER BY col1) AS xxx
FROM `project.dataset.tb1`

You can test / play with above using dummy data as below

#standardSQL
WITH `project.dataset.tb1` AS (
  SELECT 1 col1 UNION ALL
  SELECT 111 col1 UNION ALL
  SELECT 11 col1
)
SELECT
  col1, 20 + ROW_NUMBER() OVER(ORDER BY col1) AS xxx
FROM `project.dataset.tb1`

with output as

col1    xxx
1       21
11      22
111     23


问:
finding the average of array then finding the number above the average to print
```<code>import java.util.Scanner;
public class ProjectFour {
    public static void main(String args[]) {
int[] firstArray = {1,2,3,2,1,6,3,4,5};
System.out.println("this is the average of array : "+analyzeNumbers(firstArray));
System.out.println("These are the numbers above the average : "+aboveAvg(firstArray));
    }
    //finding the average
    public static int analyzeNumbers(int[] firstArray){
    int avg;
    avg=sumArray(firstArray);
    avg=avg/firstArray.length;
    return avg;
    }
    //suming the array method
    public static int sumArray(int[] firstArray){
    int sum = 0;
    for(int x=0;x<firstArray.length;x++){
        sum+=firstArray[x];
    }
    return sum;
}

**this is where im running into problems im kinda stumpted**
</code>```

<p>// this is my method i cant figure out trying to take the average and find all the numbers in the array above the average and printing them.</p>

```<code> public static int aboveAvg(int[] firstArray){
    int[] aboveAvg;
    aboveAvg = new int[0];
    int x;
    for(x=analyzeNumbers(firstArray);x<firstArray.length;x++){
        aboveAvg+=firstArray[x];
    }
    return aboveAvg;
    }
    }
</code>```

答:
This aboveAvg function is completly wrong.

```<code>public static List<Integer> aboveAvg(int[] firstArray){
    List<Integer> aboveAvg = new ArrayList<Integer>();
    int Avg = analyzeNumbers(firstArray);
    for(int i = 0; i<firstArray.length; i++)
    {
        if(firstArray[i] > Avg)
        {
            aboveAvg.add(firstArray[i]);
        }
    }
    return aboveAvg;
}
</code>```

Check your for loop and more examples about it

+= will sum two values, won't add new element on any array.

you have to define your return value correctly.

You can use List for create arrays, it's more flexible.

Body:
import java.util.Scanner;
public class ProjectFour {
    public static void main(String args[]) {
int[] firstArray = {1,2,3,2,1,6,3,4,5};
System.out.println("this is the average of array : "+analyzeNumbers(firstArray));
System.out.println("These are the numbers above the average : "+aboveAvg(firstArray));
    }
    //finding the average
    public static int analyzeNumbers(int[] firstArray){
    int avg;
    avg=sumArray(firstArray);
    avg=avg/firstArray.length;
    return avg;
    }
    //suming the array method
    public static int sumArray(int[] firstArray){
    int sum = 0;
    for(int x=0;x<firstArray.length;x++){
        sum+=firstArray[x];
    }
    return sum;
}

**this is where im running into problems im kinda stumpted**

// this is my method i cant figure out trying to take the average and find all the numbers in the array above the average and printing them.

 public static int aboveAvg(int[] firstArray){
    int[] aboveAvg;
    aboveAvg = new int[0];
    int x;
    for(x=analyzeNumbers(firstArray);x<firstArray.length;x++){
        aboveAvg+=firstArray[x];
    }
    return aboveAvg;
    }
    }

Body:
This aboveAvg function is completly wrong.

public static List<Integer> aboveAvg(int[] firstArray){
    List<Integer> aboveAvg = new ArrayList<Integer>();
    int Avg = analyzeNumbers(firstArray);
    for(int i = 0; i<firstArray.length; i++)
    {
        if(firstArray[i] > Avg)
        {
            aboveAvg.add(firstArray[i]);
        }
    }
    return aboveAvg;
}

Check your for loop and more examples about it

+= will sum two values, won't add new element on any array.

you have to define your return value correctly.

You can use List for create arrays, it's more flexible.


问:
unable to grant LOCK TABLES permission to user
I'm running MySQL 5.1.73-0ubuntu0.10.04.1-log and I'm trying to make it so a user can LOCK TABLES. I GRANTed LOCK TABLEs with the following:

GRANT SELECT, LOCK TABLES ON *.* TO 'dbuser';

That responds with Query OK, 0 rows affected (0.00 sec).

After that, when I login as dbuser, and try to do LOCK TABLES table_name WRITE; I get the following error:

```<code>ERROR 1044 (42000): Access denied for user 'dbuser'@'localhost' to database 'dbname'
</code>```

I do SHOW GRANTS as dbuser and do not see any GRANT for LOCK TABLES.

Any ideas?

答: It´s been long time since you post this question. Anyway in my opinion you should be more specific on what database to lock. Perhaps is not quite good to lock all of them (.) because mysql itself uses a database for system puporses so once you adquire a lock to a table you have only access to that table as documentation says. Perhaps the information about locking is stored on that system database named mysql. So you're locking the one wich store the lock itself.

Body:
I'm running MySQL 5.1.73-0ubuntu0.10.04.1-log and I'm trying to make it so a user can LOCK TABLES. I GRANTed LOCK TABLEs with the following:

GRANT SELECT, LOCK TABLES ON *.* TO 'dbuser';

That responds with Query OK, 0 rows affected (0.00 sec).

After that, when I login as dbuser, and try to do LOCK TABLES table_name WRITE; I get the following error:

ERROR 1044 (42000): Access denied for user 'dbuser'@'localhost' to database 'dbname'

I do SHOW GRANTS as dbuser and do not see any GRANT for LOCK TABLES.

Any ideas?


问:
Permission denied: '/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/dateutil'
I'm trying to install a package on my macbook, but I get this error. I already tried to give the map acces with chmod. What can I do to fix this?

Thnx!

```<code>OSError: [Errno 13] Permission denied: '/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/dateutil'
</code>```

答: You can use pip install --user scikit-learn or try sudo -H pip install scikit-learn but I would rather use Virtual Envrionment instead of previous 2 options, cause it's more easy and safe. After launching virtualenv just type pip install scikit-learn and it should work.

Body:
I'm trying to install a package on my macbook, but I get this error. I already tried to give the map acces with chmod. What can I do to fix this?

Thnx!

OSError: [Errno 13] Permission denied: '/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/dateutil'


问:
how to split a string without delimiters?
I have string "513". I need array ["5", "1", "3"]. My solution:

```<code>function nextBigger(num){
    let numStr = '' + num;
  let numArr = [];

  for(let i = 0; i < numStr.length; ++i) {
    numArr.push(numStr[i]);
  }

  console.log(numArr);
}

nextBigger(513);
</code>```

But this solution is large and redundant. I need shorter solution.

答:
You can just .split() with an empty string as the delimiter. This will split the string at each character:

function nextBigger(num){
  console.log(num.toString().split(""));
}

nextBigger(513);```

Body:
I have string "513". I need array ["5", "1", "3"]. My solution:

function nextBigger(num){
    let numStr = '' + num;
  let numArr = [];

  for(let i = 0; i < numStr.length; ++i) {
    numArr.push(numStr[i]);
  }

  console.log(numArr);
}

nextBigger(513);

But this solution is large and redundant. I need shorter solution.


问:
Error while connecting to IBM DB2 with Tableau Desktop?
I'm trying to connect to a IBM DB2(v10.5) database with Tableau Desktop v10. When i enter the credentials and try to login, it shows the below error:

```<code>[Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified
</code>```

The DB2 database is available in a Linux machine(rhel 6.5).What are the prerequisites and odbc drivers i need to install to resolve this issue.

答:
You need to download and install the IBM DB2 driver from Tableau's website at https://www.tableau.com/support/drivers.

Tableau's online help includes a page for setting up a connection to DB2. I am abbreviating them here.

Start Tableau and under Connect, select IBM DB2. For a complete list of data connections, select More under To a Server. Then do the following:

Enter the name of the server that hosts the database and the name of the database that you want to connect to.

Enter your user name and password.

If Tableau can't make the connection, verify that your credentials are correct. If you still can't connect, your computer is having trouble locating the server. Contact your network administrator or database administrator.    -

Select Sign In.

On the data source page, do the following:

(Optional) Select the default data source name at the top of the page, and then enter a unique data source name for use in Tableau. For example, use a data source naming convention that helps other users of the data source figure out which data source to connect to.

From the Schema drop-down list, select a schema or use the text box to      search for a schema by name.

Under Table, select a table or use the text box to search for a table by name.

Drag a table to the canvas, and then select the sheet tab to start your analysis.

Body:
I'm trying to connect to a IBM DB2(v10.5) database with Tableau Desktop v10. When i enter the credentials and try to login, it shows the below error:

[Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified

The DB2 database is available in a Linux machine(rhel 6.5).What are the prerequisites and odbc drivers i need to install to resolve this issue.


问:
show paragraph that contains a search
Ii have several paragraph in my  page, i just want to show a paragraph that contains my search
i tried with my code unsuccesfully.

(and my second problem)I Also know i shoud use a code like:

```<code>if(!$( "p#all_text" ).has("#searchfor").length
</code>```

to show element if has a search result, but how can i reassume more than 20 elements in just one jquery filter?

$('#searchfor').keyup(function(){
         var Parag = $('#all_text');
         var ParagText = Parag.text().replace("","").replace("");
         var searchedText = $('#searchfor').val();
         var theRegEx = new RegExp("("+searchedText+")", "igm");
         var newHtml = ParagText.replace(theRegEx ,"$1");
         Parag.html(newHtml);

         if($(this).has("").length)
{
$(this).parent().show()
$(this).show();
}
    });```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#all_text span
{
    text-decoration:underline;
    background-color:yellow;
}
  .starthidden {
       display: none;
   }</code>```

<input type="text" id="searchfor"/>

Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euism modo typi, qui nunc nobis videntur parum clari, fiant sollemnes in futurum.

Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euism modo typi, qui nunc nobis videntur parum clari, fiant sollemnes in futurum.

Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euism modo typi, qui nunc nobis videntur parum clari, fiant sollemnes in futurum..

Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euism modo typi, qui nunc nobis videntur parum clari, fiant sollemnes in futurum..
```

答:
With var Parag = $('#all_text'); you only search the first paragraph.

Instead, you want to loop all the paragraphs... You can use $('[id^=all_text]') for that. It gets all elements which id starts with 'all_text'.

As alternative you could add a class to the elements and use a class selector. That way you don't end up with all_text248.

After selecting the paragraphs, you loop them with .each() and use the rest of your code...

$('#searchfor').keyup(function() {
  var searchedText = $('#searchfor').val();
  $('[id^=all_text]').each(function() {
    var ParagText = $(this).text().replace("", "").replace("","");
    var theRegEx = new RegExp("(" + searchedText + ")", "igm");
    var newHtml = ParagText.replace(theRegEx, "$1");
    $(this).html(newHtml);
    $(this).show();
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>[id^=all_text] span {
  text-decoration: underline;
  background-color: yellow;
}

p {
  margin-bottom: 1em;
}

.starthidden {
  display: none;
}</code>```

<input type="text" id="searchfor" />

Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euism modo typi, qui nunc nobis videntur parum clari, fiant sollemnes in futurum.

Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euism modo typi, qui nunc nobis videntur parum clari, fiant sollemnes in futurum.

Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euism modo typi, qui nunc nobis videntur parum clari, fiant sollemnes in futurum..

Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euism modo typi, qui nunc nobis videntur parum clari, fiant sollemnes in futurum..
```

Title: show paragraph that contains a search

Body:
Ii have several paragraph in my  page, i just want to show a paragraph that contains my search
i tried with my code unsuccesfully.

(and my second problem)I Also know i shoud use a code like:

if(!$( "p#all_text" ).has("#searchfor").length

to show element if has a search result, but how can i reassume more than 20 elements in just one jquery filter?

$('#searchfor').keyup(function(){
         var Parag = $('#all_text');
         var ParagText = Parag.text().replace("","").replace("");
         var searchedText = $('#searchfor').val();
         var theRegEx = new RegExp("("+searchedText+")", "igm");
         var newHtml = ParagText.replace(theRegEx ,"$1");
         Parag.html(newHtml);

         if($(this).has("").length)
{
$(this).parent().show()
$(this).show();
}
    });

#all_text span
{
    text-decoration:underline;
    background-color:yellow;
}
  .starthidden {
       display: none;
   }

<input type="text" id="searchfor"/>

Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euism modo typi, qui nunc nobis videntur parum clari, fiant sollemnes in futurum.

Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euism modo typi, qui nunc nobis videntur parum clari, fiant sollemnes in futurum.

Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euism modo typi, qui nunc nobis videntur parum clari, fiant sollemnes in futurum..

Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euism modo typi, qui nunc nobis videntur parum clari, fiant sollemnes in futurum..

Body:
With var Parag = $('#all_text'); you only search the first paragraph.

Instead, you want to loop all the paragraphs... You can use $('[id^=all_text]') for that. It gets all elements which id starts with 'all_text'.

As alternative you could add a class to the elements and use a class selector. That way you don't end up with all_text248.

After selecting the paragraphs, you loop them with .each() and use the rest of your code...

$('#searchfor').keyup(function() {
  var searchedText = $('#searchfor').val();
  $('[id^=all_text]').each(function() {
    var ParagText = $(this).text().replace("<span>", "").replace("</span>","");
    var theRegEx = new RegExp("(" + searchedText + ")", "igm");
    var newHtml = ParagText.replace(theRegEx, "<span>$1</span>");
    $(this).html(newHtml);
    $(this).show();
  });
});

[id^=all_text] span {
  text-decoration: underline;
  background-color: yellow;
}

p {
  margin-bottom: 1em;
}

.starthidden {
  display: none;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<input type="text" id="searchfor" />
<p id="all_text" class='starthidden'>Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euism modo typi, qui nunc nobis videntur parum clari, fiant sollemnes in futurum.</p>

<p id="all_text1" class='starthidden'>Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euism modo typi, qui nunc nobis videntur parum clari, fiant sollemnes in futurum.</p>

<p id="all_text2" class='starthidden'>Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euism modo typi, qui nunc nobis videntur parum clari, fiant sollemnes in futurum..</p>

<p id="all_text3" class='starthidden'>Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euism modo typi, qui nunc nobis videntur parum clari, fiant sollemnes in futurum..</p>


问:
Find a database with a particular table OR Find a table in every database of SQL Server
I have a SQL Server with hundreds of databases and each database having hundreds of tables.
Now I would like to find where in these databases is a table that I am looking for.

I could find if a table existed in individual database using

```<code>use myDatabase
select * from sys.tables  where name = 'mytable'
GO
</code>```

but using this means I have to manually change the database for hundreds of times .
I would like to find the database name only.
Is there a way out ?

答:
This should do what you are looking for:

```<code>EXEC sp_MSforeachdb "use [?];select * from sys.tables where name='TableName' "
</code>```

To include the name of the current database in the output use:

```<code>EXEC sp_MSforeachdb "use [?];select '[?]' as DatabaseName, * from sys.tables where name='TableName' "
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have a SQL Server with hundreds of databases and each database having hundreds of tables.
Now I would like to find where in these databases is a table that I am looking for.

I could find if a table existed in individual database using

use myDatabase
select * from sys.tables  where name = 'mytable'
GO

but using this means I have to manually change the database for hundreds of times .
I would like to find the database name only.
Is there a way out ?

Body:
This should do what you are looking for:

EXEC sp_MSforeachdb "use [?];select * from sys.tables where name='TableName' "

To include the name of the current database in the output use:

EXEC sp_MSforeachdb "use [?];select '[?]' as DatabaseName, * from sys.tables where name='TableName' "


问:
Firebase Deeplink not redirecting to app if select goo.gl
I'm integrating firebase in application. I created universal link that worked for Android & iOS both.

This worked great. BUT I got scenario where I clicked on goo.gl (PFA) link which was displaying on launched app right-top side. And from then no matter what I do, Deeplink will never launch my application.

I checked to clear history of device-browser but it's same. Any suggestion how to get rid of this issue/feature ??

答: In addition to imgx64 post. I had a similar problem: Firebase redirected to z99zz-c.app.goo.gl/zzzz and in this case system was not redirected to my app. I added "applinks:mzn3g-c.app.goo.gl" as Associated domain in my target capabilities and this does the trick! Even if you redirected to domain with "-c" suffix iOS can recognize it and will redirect to your app and show suggestion in Safari


问:
Expression Language in JSP not working while i am generating a xml file in Jsp
In My Jsp Page(name.jsp)

```<code><%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ page contentType="text/xml" %><%@ page isELIgnored="false" %>
<?xml version="2.5" encoding="UTF-8" standalone="no"?>
<document type="freeswitch/xml">
<section name="configuration">
<configuration name="sofia.conf" description="sofia Endpoint">
  <global_settings>
    <param name="log-level" value="0"/>
    <param name="debug-presence" value="0"/>
    <param name="bind-params" value="transport=udp"/>
  </global_settings>
  <profiles>
     <profile name="external">
        <gateways>

        </gateways>
        <aliases/>
          <domains>
                <domain name="all" alias="false" parse="true"/>
          </domains>
        <settings>

        </settings>

    </profile>
    <profile name="internal">
        <settings>

        </settings>
    </profile>
  </profiles>
</configuration>
<configuration name="ivr.conf" description="IVR menus">
  <menus>
    <menu name="ivr-test" greet-long="say:welcome to neron.  press 1 for sales .   press 2 for support.  press 3 for accounts.  press 4 for me " greet-short="" invalid-sound="say:it was an invalid sound" exit-sound="say:thankyou for contacting us" confirm-macro="" confirm-key="" tts-engine="flite" tts-voice="slt" confirm-attempts="" timeout="10000" inter-digits-timeout="2000" max-failures="3" max-timeouts="" digit-len="4">
      <entry action="menu-exec-app" digits="1" param="bridge sofia/internal/2001@192.168.1.105"/>
      <entry action="menu-exec-app" digits="2" param="bridge sofia/internal/2002@192.168.1.105"/>
      <entry action="menu-exec-app" digits="3" param="bridge sofia/internal/2003@192.168.1.105"/>
    </menu>
  </menus>
</configuration>
</code>```

And it gives me

This page contains the following errors:
      error on line 1 at column 7: XML declaration allowed only at the start of
     the document
      Below is a rendering of the page up to the first error.

When i remove <?xml version="2.5" encoding="UTF-8" standalone="no"?> then it works fine. This project is totally annotation based not here web.xml file . Can You solve it?  Thanks

答:
I often avoid empty lines at the top of text, doing:

```<code><%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"
%><%@ page contentType="text/xml" %><%@ page isELIgnored="false"
%><?xml version="2.5" encoding="UTF-8" standalone="no"?>
</code>```

Whether this would help here is the question. Though you can do:

```<code><c:out value='<?xml version="2.5" encoding="UTF-8" standalone="no"?>'
 escapeXml="false"/>
</code>```

Body:
In My Jsp Page(name.jsp)

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ page contentType="text/xml" %><%@ page isELIgnored="false" %>
<?xml version="2.5" encoding="UTF-8" standalone="no"?>
<document type="freeswitch/xml">

<configuration name="sofia.conf" description="sofia Endpoint">
  <global_settings>
    <param name="log-level" value="0"/>
    <param name="debug-presence" value="0"/>
    <param name="bind-params" value="transport=udp"/>
  </global_settings>
  <profiles>
     <profile name="external">
        <gateways>

        </gateways>
        <aliases/>
          <domains>
                <domain name="all" alias="false" parse="true"/>
          </domains>
        <settings>

        </settings>

    </profile>
    <profile name="internal">
        <settings>

        </settings>
    </profile>
  </profiles>
</configuration>
<configuration name="ivr.conf" description="IVR menus">
  <menus>
    <menu name="ivr-test" greet-long="say:welcome to neron.  press 1 for sales .   press 2 for support.  press 3 for accounts.  press 4 for me " greet-short="" invalid-sound="say:it was an invalid sound" exit-sound="say:thankyou for contacting us" confirm-macro="" confirm-key="" tts-engine="flite" tts-voice="slt" confirm-attempts="" timeout="10000" inter-digits-timeout="2000" max-failures="3" max-timeouts="" digit-len="4">
      <entry action="menu-exec-app" digits="1" param="bridge sofia/internal/2001@192.168.1.105"/>
      <entry action="menu-exec-app" digits="2" param="bridge sofia/internal/2002@192.168.1.105"/>
      <entry action="menu-exec-app" digits="3" param="bridge sofia/internal/2003@192.168.1.105"/>
    </menu>
  </menus>
</configuration>

And it gives me

This page contains the following errors:
      error on line 1 at column 7: XML declaration allowed only at the start of
     the document
      Below is a rendering of the page up to the first error.

When i remove <?xml version="2.5" encoding="UTF-8" standalone="no"?> then it works fine. This project is totally annotation based not here web.xml file . Can You solve it?  Thanks

Body:
I often avoid empty lines at the top of text, doing:

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"
%><%@ page contentType="text/xml" %><%@ page isELIgnored="false"
%><?xml version="2.5" encoding="UTF-8" standalone="no"?>

Whether this would help here is the question. Though you can do:

<c:out value='&lt;?xml version="2.5" encoding="UTF-8" standalone="no"?&gt;'
 escapeXml="false"/>


问:
R- how to read in data dynamically
I'm looking for a solution of not reading in the data statically to R and cannot find a way.
My aim is to read in data depending on the memory location of the R-Code.
That means not specify the exact path of the data, the only thing which I know about it's memory location is that it is saved in the same file as the code(name will always stay the same). The problem is, that the memory code of this file can change.
Do you have any idea how to solve this or did you have any similar problem?
thanks a lot for your help

c.

答:
I'm  not sure that I understand your question entirely.  It would help if you had some code related to an attempt to address the problem.  I also don't have enough points to comment on your post so I have to use the answer feature of stack overflow.

If R isn't provided a full path to a file to read in, it will look for it in the working directory.  You can retrieve your current working directory from within the R console using

```<code>getwd()
</code>```

and you can change the working directory, either by starting R from a terminal (in linux) while in the directory of interest, or by using

```<code>setwd(file.path("my","full","or relative","path"))
</code>```

If you always have your script in the same directory as your data or file of interest, then all you ever need to do is make sure that you start R from the directory your files are in and specify the filename only in your read.csv() or file reading command.

I hope this helps.

Title: R- how to read in data dynamically

Body:
I'm  not sure that I understand your question entirely.  It would help if you had some code related to an attempt to address the problem.  I also don't have enough points to comment on your post so I have to use the answer feature of stack overflow.

If R isn't provided a full path to a file to read in, it will look for it in the working directory.  You can retrieve your current working directory from within the R console using

getwd()

and you can change the working directory, either by starting R from a terminal (in linux) while in the directory of interest, or by using

setwd(file.path("my","full","or relative","path"))

If you always have your script in the same directory as your data or file of interest, then all you ever need to do is make sure that you start R from the directory your files are in and specify the filename only in your read.csv() or file reading command.

I hope this helps.


问:
Mamp localhost resolving very slowly
When I make local changes to my PHP / WordPress website, the localhost does not seem to update for 20-30 minutes.

I'm on Mac OSX 10.8.4 and using MAMP Pro. I have two sites that I have created separate host entries for, let's call them mysite1.dev and mysite2.dev.

Here is my MAMP Server configuration:

```<code>Apache: 80
MySQL: 3306
SSL: 443
</code>```

I saw this article ( How can I eliminate slow resolving/loading of localhost/virtualhost (a 2-3 second lag) on Mac OS X Lion? ) on the Bonjour conflicts and edited my /private/etc/hosts file with the suggestions in this article:

I changed the host names from mysite1.localhost to mysite.dev because it sounds like the conflict is with .local names - DID NOT WORK

I updated the Hosts file to have separate ::1 addresses - DID NOT WORK:

```<code>::1 <tab> mysite1.dev
::1 <tab> mysite2.dev
</code>```

I tried putting all of my host entries onto one line - also didn't work:

```<code>127.0.0.1 localhost mysite1.dev mysite2.dev
::1 localhost
fe80::1%lo0 localhost
</code>```

It seems like MAMP Pro overwrites the hosts file any time I restart the server.

I would be SUPER grateful for any help you can offer.

答:
MAMP's default ports are non-standard.  When I switched to standard ports (80 for Apache & 443 for SSL), it sped up dramatically.

I'm not sure if this is what Paul Bakker did, or if he switched the other way.

I'm using MAMP Pro 4.2, PHP 7.1.6, Apache, OS X 10.11.6.

Title: Mamp localhost resolving very slowly

Body:
When I make local changes to my PHP / WordPress website, the localhost does not seem to update for 20-30 minutes.

I'm on Mac OSX 10.8.4 and using MAMP Pro. I have two sites that I have created separate host entries for, let's call them mysite1.dev and mysite2.dev.

Here is my MAMP Server configuration:

Apache: 80
MySQL: 3306
SSL: 443

I saw this article ( How can I eliminate slow resolving/loading of localhost/virtualhost (a 2-3 second lag) on Mac OS X Lion? ) on the Bonjour conflicts and edited my /private/etc/hosts file with the suggestions in this article:

I changed the host names from mysite1.localhost to mysite.dev because it sounds like the conflict is with .local names - DID NOT WORK

I updated the Hosts file to have separate ::1 addresses - DID NOT WORK:

::1 <tab> mysite1.dev
::1 <tab> mysite2.dev

I tried putting all of my host entries onto one line - also didn't work:

127.0.0.1 localhost mysite1.dev mysite2.dev
::1 localhost
fe80::1%lo0 localhost

It seems like MAMP Pro overwrites the hosts file any time I restart the server.

I would be SUPER grateful for any help you can offer.


问:
React Native: setState() does not re-render FlatList child component
In short, I have been following a tutorial found here.

It makes sense and it works, however, I have trouble understanding why the FlatList component needs to be assigned a prop to which a state is associated in order to re-render it when the state changes. If I omit the extraData prop as per the example, the FlatList doesn't get re-rendered. I thought setState() was supposed to re-render a component and all its children, but it doesn't in this instance: am I missing something here?

Thank you.

答:
if you take a look at this page https://facebook.github.io/react-native/docs/flatlist.html

you can see they are setting the state.selected, but i can't see that you/him are doing that in that tutorial, maybe its the this.state.selected that isnt set as a property?

i think you'll need to add the selected to state in your onSelectItem() method as this:

```<code>onSelectItem: (item) => {
    console.log('onSelectItem ', item);
    this.setState({
        selected: item
    });
},
</code>```

Body:
if you take a look at this page https://facebook.github.io/react-native/docs/flatlist.html

you can see they are setting the state.selected, but i can't see that you/him are doing that in that tutorial, maybe its the this.state.selected that isnt set as a property?

i think you'll need to add the selected to state in your onSelectItem() method as this:

onSelectItem: (item) => {
    console.log('onSelectItem ', item);
    this.setState({
        selected: item
    });
},


问:
Troubleshooting PNUnit at the client end
I'm using PNUnit framework (based on NUnit) to run tests in Parallel. Basically the Runner deploys the PNUnitAgent on a client machine and sends it an NUnit Test as a dll file (as is normal for running PNUnit tests).

The problem is that the test is failing unexpectedly on the client machine. I need to troubleshoot how the test is running at client end but cannot use Visual Studio as its not installed.

How can we troubleshoot PNUnit test failures? Is there any tool or any easy way to do this?

Expecting any quick suggestions as it is very urgent.

答: you can review the test errors at the smoke-errors.log file, it's automatically generated by the PNunit launcher and saved, by default, on the PNunit launcher binary path.</p>


问:
Sublime Text 3, how to add to right click?
How do I add Sublime Text just like how Edit with Notepad++ is there it's nothing big but it saves time.

答:
UPDATE May 2018: No longer available, package has been removed.

If you have chocolatey, you could just run:

```<code>choco install sublimetext3-contextmenu
</code>```

Body:
UPDATE May 2018: No longer available, package has been removed.

If you have chocolatey, you could just run:

choco install sublimetext3-contextmenu

ContentLicense: CC BY-SA 4.0


问:
Finishing File Class
I keep getting an error telling me lineNumber cannot be resolved to a variable? I'm not really sure how to fix this exactly. Am I not importing a certain file to java that helps with this?

And also how would I count the number of chars with spaces and without spaces.

Also I need a method to count unique words but I'm not really sure what unique words are.

```<code>import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
import java.util.StringTokenizer;
import java.util.ArrayList;
import java.util.List;

public class LineWordChar {
public void main(String[] args) throws IOException {
    // Convert our text file to string
String text = new Scanner( new File("way to your file"), "UTF-8" ).useDelimiter("\\A").next();
BufferedReader bf=new BufferedReader(new FileReader("way to your file"));
String lines="";
int linesi=0;
int words=0;
int chars=0;
String s="";

// while next lines are present in file int linesi will add 1
    while ((lines=bf.readLine())!=null){
    linesi++;}
// Tokenizer separate our big string "Text" to little string and count them
StringTokenizer st=new StringTokenizer(text);
 while (st.hasMoreTokens()){
    s = st.nextToken();
      words++;
// We take every word during separation and count number of char in this words
      for (int i = 0; i < s.length(); i++) {
          chars++;}
    }
 System.out.println("Number of lines: "+linesi);
 System.out.println("Number of words: "+words);
 System.out.print("Number of chars: "+chars);
}
}
 abstract class WordCount {

/**
 * @return HashMap a map containing the Character count, Word count and
 *         Sentence count
 * @throws FileNotFoundException
 *
 */
public static void main() throws FileNotFoundException {
    lineNumber=2; // as u want
    File f = null;
    ArrayList<Integer> list=new ArrayList<Integer>();

    f = new File("file_stats.txt");
    Scanner sc = new Scanner(f);
    int totalLines=0;
    int totalWords=0;
    int totalChars=0;
    int totalSentences=0;
    while(sc.hasNextLine())
    {
        totalLines++;
        if(totalLines==lineNumber){
            String line = sc.nextLine();
            totalChars += line.length();
            totalWords += new StringTokenizer(line, " ,").countTokens();  //line.split("\\s").length;
            totalSentences += line.split("\\.").length;
            break;
        }
        sc.nextLine();

    }

    list.add(totalChars);
    list.add(totalWords);
    list.add(totalSentences);
    System.out.println(lineNumber+";"+totalWords+";"+totalChars+";"+totalSentences);

}
}
</code>```

答:
lineNumber variable should be declared with datatype.

int lineNumber=2; // as u want

change the first line in the main method from just lineNumber to int lineNumber = 2 by setting its data type, as it is important to set data type of every variable in Java.

Title: Finishing File Class

Body:
I keep getting an error telling me lineNumber cannot be resolved to a variable? I'm not really sure how to fix this exactly. Am I not importing a certain file to java that helps with this?

And also how would I count the number of chars with spaces and without spaces.

Also I need a method to count unique words but I'm not really sure what unique words are.

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
import java.util.StringTokenizer;
import java.util.ArrayList;
import java.util.List;

public class LineWordChar {
public void main(String[] args) throws IOException {
    // Convert our text file to string
String text = new Scanner( new File("way to your file"), "UTF-8" ).useDelimiter("\\A").next();
BufferedReader bf=new BufferedReader(new FileReader("way to your file"));
String lines="";
int linesi=0;
int words=0;
int chars=0;
String s="";

// while next lines are present in file int linesi will add 1
    while ((lines=bf.readLine())!=null){
    linesi++;}
// Tokenizer separate our big string "Text" to little string and count them
StringTokenizer st=new StringTokenizer(text);
 while (st.hasMoreTokens()){
    s = st.nextToken();
      words++;
// We take every word during separation and count number of char in this words
      for (int i = 0; i < s.length(); i++) {
          chars++;}
    }
 System.out.println("Number of lines: "+linesi);
 System.out.println("Number of words: "+words);
 System.out.print("Number of chars: "+chars);
}
}
 abstract class WordCount {

/**
 * @return HashMap a map containing the Character count, Word count and
 *         Sentence count
 * @throws FileNotFoundException
 *
 */
public static void main() throws FileNotFoundException {
    lineNumber=2; // as u want
    File f = null;
    ArrayList<Integer> list=new ArrayList<Integer>();

    f = new File("file_stats.txt");
    Scanner sc = new Scanner(f);
    int totalLines=0;
    int totalWords=0;
    int totalChars=0;
    int totalSentences=0;
    while(sc.hasNextLine())
    {
        totalLines++;
        if(totalLines==lineNumber){
            String line = sc.nextLine();
            totalChars += line.length();
            totalWords += new StringTokenizer(line, " ,").countTokens();  //line.split("\\s").length;
            totalSentences += line.split("\\.").length;
            break;
        }
        sc.nextLine();

    }

    list.add(totalChars);
    list.add(totalWords);
    list.add(totalSentences);
    System.out.println(lineNumber+";"+totalWords+";"+totalChars+";"+totalSentences);

}
}


问:
Unicode (Hexadecimal) to varchar conversion
Here is the problem, the system I use can create a saved search which basically generates a 'Where' clause and saves it in the database as type Image ..
I am trying to convert the image entry to a readable format, it is saved in 2 forms (Unicode and non unicode) now I can get the non unicode entries fine and they display correctly, however when I try and convert the Unicode entries it does not display correctly an example of what I am trying to convert is

```<code>[encoded data, 4656 characters]
</code>```

the SQL code I am using to convert is the following

```<code>with saved_lookups_cte as
(select
table_id,
table_name,
saved_lookups_id,
saved_lookup_name,
case
  when charindex('WhereDelim',query_text) > 0 then
    substring(query_text,len(query_text) - charindex(reverse('WhereDelim'),reverse(query_text)) + 3,4000)
  else query_text
end query_text
, sql_tree_binary
from (select
  table_id,
  table_name,
  saved_lookups_id,
  saved_lookup_name,
  case isUnicode
    when 1 then [Production_ED].dbo.[RemoveNonASCII] (cast(cast(substring(sql_tree_binary, startIndex, queryLength * 2) as nvarchar(max))as varchar(max)))
    else cast(substring(sql_tree_binary, startIndex, queryLength) as varchar(8000))
  end query_text
 , sql_tree_binary
from (
    select
        saved_lookup_name,
        case
            when substring(sql_tree_binary,1,5) = 0x0100000000 then 0
            when substring(sql_tree_binary,1,5) = 0x01000000FF then 1
        end isUnicode,
        cast(case
            when substring(sql_tree_binary,1,5) = 0x0100000000 then
                case
                    when substring(sql_tree_binary,6,1) = 0xFF then substring(sql_tree_binary,8,1) + substring(sql_tree_binary,7,1)
                    else substring(sql_tree_binary,6,1)
                end
            when substring(sql_tree_binary,1,5) = 0x01000000FF then
                case
                    when substring(sql_tree_binary,12,1) = 0xFF then substring(sql_tree_binary,14,1) + substring(sql_tree_binary,13,1)
                    else substring(sql_tree_binary,12,1)
                end
        end as int) queryLength,
        case
            when substring(sql_tree_binary,1,5) = 0x0100000000 then
                case
                    when substring(sql_tree_binary,6,1) = 0xFF then 9
                    else 7
                end
            when substring(sql_tree_binary,1,5) = 0x01000000FF then
                case
                    when substring(sql_tree_binary,12,1) = 0xFF then 15
                    else 13
                end
        end    startIndex,
        s.table_id,
        t.table_name,
        s.saved_lookups_id,
        s.sql_tree_binary
    from
      Production_Ed.dbo.Saved_Lookups s inner join
      tables t on s.table_id = t.tables_id
    -- where substring(saved_lookups_id,1,1) <> 0x00
   where saved_lookup_name = 'DE Quotes Open Account Manager >=2000'
) x
) y

)
select * from saved_lookups_cte
</code>```

The part of the query that does the conversion is

```<code> when 1 then [Production_ED].dbo.[RemoveNonASCII]
(cast(cast(substring(sql_tree_binary, startIndex, queryLength * 2) as
 nvarchar(max))as varchar(max)))
</code>```

now this actually returns nothing, however if I set the startIndex to 17 and change the queryLength to 3000 * 2 (unicode byte = 2) I get

```<code>??Quote?????Norgren_Group Id = 0x0000000000000023???A??????????????? ????????????? ??????????????????????? ? ??????????????????????????????A?????????? ? ???A??Aa??TTID_25R12454.TTID_23R864R12454 __SQ
</code>```

Returned, although I can read parts, it is not the full query ... yet even if I extend the length I get no more.

Any help would be greatly appreciated.

Code for the RemoveNonASCII function:

```<code>ALTER FUNCTION [dbo].[RemoveNonASCII]
(
@nstring nvarchar(max)
)
RETURNS varchar(max)
AS
BEGIN

DECLARE @Result varchar(max)
SET @Result = ''

DECLARE @nchar nvarchar(1)
DECLARE @position int

SET @position = 1
WHILE @position <= LEN(@nstring)
BEGIN
    SET @nchar = SUBSTRING(@nstring, @position, 1)
    IF ASCII(@nchar) between 32 and 255
        SET @Result = @Result + @nchar
    SET @position = @position + 1
END

RETURN @Result

END

GO
</code>```

答:
Ok, so I found the issue, inside the hex string there were null values, which caused the rest of the returned varchar string to become null .. So I just changed the function to:

```<code>AS
BEGIN

DECLARE @Result varchar(max)
SET @Result = ''

DECLARE @nchar nvarchar(1)
DECLARE @position int

SET @position = 1
WHILE @position <= LEN(@nstring)
BEGIN
    SET @nchar = SUBSTRING(@nstring, @position, 1)
    IF ASCII(@nchar) between 1 and 125
        SET @Result = @Result + @nchar
    SET @position = @position + 1
END

RETURN @Result

END
</code>```

Eradicating 0 being the ASCII Null value!

Body:
Here is the problem, the system I use can create a saved search which basically generates a 'Where' clause and saves it in the database as type Image ..
I am trying to convert the image entry to a readable format, it is saved in 2 forms (Unicode and non unicode) now I can get the non unicode entries fine and they display correctly, however when I try and convert the Unicode entries it does not display correctly an example of what I am trying to convert is

[encoded data, 4656 characters]

the SQL code I am using to convert is the following

with saved_lookups_cte as
(select
table_id,
table_name,
saved_lookups_id,
saved_lookup_name,
case
  when charindex('WhereDelim',query_text) > 0 then
    substring(query_text,len(query_text) - charindex(reverse('WhereDelim'),reverse(query_text)) + 3,4000)
  else query_text
end query_text
, sql_tree_binary
from (select
  table_id,
  table_name,
  saved_lookups_id,
  saved_lookup_name,
  case isUnicode
    when 1 then [Production_ED].dbo.[RemoveNonASCII] (cast(cast(substring(sql_tree_binary, startIndex, queryLength * 2) as nvarchar(max))as varchar(max)))
    else cast(substring(sql_tree_binary, startIndex, queryLength) as varchar(8000))
  end query_text
 , sql_tree_binary
from (
    select
        saved_lookup_name,
        case
            when substring(sql_tree_binary,1,5) = 0x0100000000 then 0
            when substring(sql_tree_binary,1,5) = 0x01000000FF then 1
        end isUnicode,
        cast(case
            when substring(sql_tree_binary,1,5) = 0x0100000000 then
                case
                    when substring(sql_tree_binary,6,1) = 0xFF then substring(sql_tree_binary,8,1) + substring(sql_tree_binary,7,1)
                    else substring(sql_tree_binary,6,1)
                end
            when substring(sql_tree_binary,1,5) = 0x01000000FF then
                case
                    when substring(sql_tree_binary,12,1) = 0xFF then substring(sql_tree_binary,14,1) + substring(sql_tree_binary,13,1)
                    else substring(sql_tree_binary,12,1)
                end
        end as int) queryLength,
        case
            when substring(sql_tree_binary,1,5) = 0x0100000000 then
                case
                    when substring(sql_tree_binary,6,1) = 0xFF then 9
                    else 7
                end
            when substring(sql_tree_binary,1,5) = 0x01000000FF then
                case
                    when substring(sql_tree_binary,12,1) = 0xFF then 15
                    else 13
                end
        end    startIndex,
        s.table_id,
        t.table_name,
        s.saved_lookups_id,
        s.sql_tree_binary
    from
      Production_Ed.dbo.Saved_Lookups s inner join
      tables t on s.table_id = t.tables_id
    -- where substring(saved_lookups_id,1,1) <> 0x00
   where saved_lookup_name = 'DE Quotes Open Account Manager >=2000'
) x
) y

)
select * from saved_lookups_cte

The part of the query that does the conversion is

 when 1 then [Production_ED].dbo.[RemoveNonASCII]
(cast(cast(substring(sql_tree_binary, startIndex, queryLength * 2) as
 nvarchar(max))as varchar(max)))

now this actually returns nothing, however if I set the startIndex to 17 and change the queryLength to 3000 * 2 (unicode byte = 2) I get

??Quote?????Norgren_Group Id = 0x0000000000000023???A??????????????? ????????????? ??????????????????????? ? ??????????????????????????????A?????????? ? ???A??Aa??TTID_25R12454.TTID_23R864R12454 __SQ

Returned, although I can read parts, it is not the full query ... yet even if I extend the length I get no more.

Any help would be greatly appreciated.

Code for the RemoveNonASCII function:

ALTER FUNCTION [dbo].[RemoveNonASCII]
(
@nstring nvarchar(max)
)
RETURNS varchar(max)
AS
BEGIN

DECLARE @Result varchar(max)
SET @Result = ''

DECLARE @nchar nvarchar(1)
DECLARE @position int

SET @position = 1
WHILE @position <= LEN(@nstring)
BEGIN
    SET @nchar = SUBSTRING(@nstring, @position, 1)
    IF ASCII(@nchar) between 32 and 255
        SET @Result = @Result + @nchar
    SET @position = @position + 1
END

RETURN @Result

END

GO

Body:
Ok, so I found the issue, inside the hex string there were null values, which caused the rest of the returned varchar string to become null .. So I just changed the function to:

AS
BEGIN

DECLARE @Result varchar(max)
SET @Result = ''

DECLARE @nchar nvarchar(1)
DECLARE @position int

SET @position = 1
WHILE @position <= LEN(@nstring)
BEGIN
    SET @nchar = SUBSTRING(@nstring, @position, 1)
    IF ASCII(@nchar) between 1 and 125
        SET @Result = @Result + @nchar
    SET @position = @position + 1
END

RETURN @Result

END

Eradicating 0 being the ASCII Null value!


问:
Copy stack trace from IntelliJ Idea
When the program has stopped at a breakpoint, I want to copy the current stack trace (the call stack) and paste it into a text file.

Unfortunately, the current version of IntelliJ Idea does not provide such functionality in the debugger frames window.

答:
You can use:

IDEA 2018.1 where "copy stack" action was finally introduced

Export threads action from the frames view context menu

Thread dump action from the left debugger toolbar

Title: Copy stack trace from IntelliJ Idea


问:
Laravel external(from another domain) api request to check if the user is logged in a server (main server)
How can I make a logged-in-check via an external call (external domain) to a main server? Should be a js client-server call.

In other words domain1.com makes a client-server call to the main-domain.com to check if the user is already logged-in in main-domain.com

答:
What you are looking for is crossdomain request with cookies, this requires that you must specify some header output on the domains, you can find more information @ this stackoverflow link.

You'll need some kind of handler on the main domain that can start the session, verify that it has the necessary session data that says its logged in and return true/false for the caller.


问:
How can I refresh an OLAP table in the background? I have a table in powerpivot that is linked to a SQL database
Please can you assist me? I have a table on Powerpivot that is linked to a SQL database. I'd like it to refresh even when the file is closed so that when users read the dashboard that's linked to the dataset, its the latest version.

Please can you help me? I have Excel 2013. Can Excel 2016 run background refresh? Thanks in advance :)

答:
Even in Excel 2016, you have to have the file open to update the power pivot model.

Your only real options are either write some VBA which opens the file  runs the update, then saves and closes the file.  Then have that run on a schedule.

The VBA involved would be below which loads the model, then refreshes it

```<code>ThisWorkbook.Model.Initialize
ThisWorkbook.Model.Refresh
</code>```

The other option, though I have never used it, is Power Update which is a third party program for automating Power Pivot updates.
Link to a blog post talking about it:
https://powerpivotpro.com/2015/02/introducing-power-update/

Body:
Even in Excel 2016, you have to have the file open to update the power pivot model.

Your only real options are either write some VBA which opens the file  runs the update, then saves and closes the file.  Then have that run on a schedule.

The VBA involved would be below which loads the model, then refreshes it

ThisWorkbook.Model.Initialize
ThisWorkbook.Model.Refresh

The other option, though I have never used it, is Power Update which is a third party program for automating Power Pivot updates.
Link to a blog post talking about it:
https://powerpivotpro.com/2015/02/introducing-power-update/


问:
Base Virtual Method not called or called twice
Here my code.

```<code>public class EventItem
{
    public int Id { get; set; } = -1;
    public int ClientId { get; set; }

    public EventItem(IDataRecord rdr)
    {
        FillAttributs(rdr);
    }

    public virtual void FillAttributs(IDataRecord rdr)
    {
        this.Id = (int)rdr["EventId"];
        this.ClientId = (int)rdr["ClientId"];
    }
}

public class ControlItem : EventItem
{
    public int ControlId { get; set; }

    public ControlItem(IDataRecord rdr) : base(rdr)
    {
        FillAttributs(rdr);
    }

    public override void FillAttributs(IDataRecord rdr)
    {
        base.FillAttributs(rdr); // Version 1
        this.ControlId = (int)rdr["ControlId"];
    }
}
...
ControlItem ctrl = new ControlItem(rdr)
</code>```

Version 1 : With base.FillAttributs(rdr), FillAttributs of base class and child class are called twice. Without, only FillAttributs of child class is called twice.

Version 2 : I remove base.FillAttributs(rdr), virtual and replace override with public new void FillAttributs(IDataRecord rdr). So It works but I'm not sure if it's a good practice.

Version 3 : I rename FillAttributs of base class to FillEventAttributs and of chil class to FillControlAttributs.

what is the right way to go here ? Or should I use another way to do it ?

答:
Remove FillAttributs(rdr) from ControlItem constructor.
its look like this:

```<code>public class EventItem
{
public int Id { get; set; } = -1;
public int ClientId { get; set; }

public EventItem(IDataRecord rdr)
{
    FillAttributs(rdr);
}

public virtual void FillAttributs(IDataRecord rdr)
{
    this.Id = (int)rdr["EventId"];
    this.ClientId = (int)rdr["ClientId"];
}
}

public class ControlItem : EventItem
{
public int ControlId { get; set; }

public ControlItem(IDataRecord rdr) : base(rdr)
{
    //FillAttributs(rdr);
}

public override void FillAttributs(IDataRecord rdr)
{
    base.FillAttributs(rdr); // Version 1
    this.ControlId = (int)rdr["ControlId"];
}
}
...
ControlItem ctrl = new ControlItem(rdr)
</code>```

Now base and derived called once.
I hope this help you.

Body:
Here my code.

public class EventItem
{
    public int Id { get; set; } = -1;
    public int ClientId { get; set; }

    public EventItem(IDataRecord rdr)
    {
        FillAttributs(rdr);
    }

    public virtual void FillAttributs(IDataRecord rdr)
    {
        this.Id = (int)rdr["EventId"];
        this.ClientId = (int)rdr["ClientId"];
    }
}

public class ControlItem : EventItem
{
    public int ControlId { get; set; }

    public ControlItem(IDataRecord rdr) : base(rdr)
    {
        FillAttributs(rdr);
    }

    public override void FillAttributs(IDataRecord rdr)
    {
        base.FillAttributs(rdr); // Version 1
        this.ControlId = (int)rdr["ControlId"];
    }
}
...
ControlItem ctrl = new ControlItem(rdr)

Version 1 : With base.FillAttributs(rdr), FillAttributs of base class and child class are called twice. Without, only FillAttributs of child class is called twice.

Version 2 : I remove base.FillAttributs(rdr), virtual and replace override with public new void FillAttributs(IDataRecord rdr). So It works but I'm not sure if it's a good practice.

Version 3 : I rename FillAttributs of base class to FillEventAttributs and of chil class to FillControlAttributs.

what is the right way to go here ? Or should I use another way to do it ?

Body:
Remove FillAttributs(rdr) from ControlItem constructor.
its look like this:

public class EventItem
{
public int Id { get; set; } = -1;
public int ClientId { get; set; }

public EventItem(IDataRecord rdr)
{
    FillAttributs(rdr);
}

public virtual void FillAttributs(IDataRecord rdr)
{
    this.Id = (int)rdr["EventId"];
    this.ClientId = (int)rdr["ClientId"];
}
}

public class ControlItem : EventItem
{
public int ControlId { get; set; }

public ControlItem(IDataRecord rdr) : base(rdr)
{
    //FillAttributs(rdr);
}

public override void FillAttributs(IDataRecord rdr)
{
    base.FillAttributs(rdr); // Version 1
    this.ControlId = (int)rdr["ControlId"];
}
}
...
ControlItem ctrl = new ControlItem(rdr)

Now base and derived called once.
I hope this help you.


问:
Sum list of Option[Int] Scala using fold
I was trying to sum all elements in a list, they are of type Option[Int], if any of them are None, the whole result is None, if all are Some(value), I want the sum of all of them:

```<code>val ls = List(Some(2), Some(5), Some(4), Some(1))

ls.fold(None)((rs,x) => for(n <- x; m <- rs) yield {n+m})
</code>```

but I always get None, no matter what.

答:
I realize what was my error, it was the base case in fold:

```<code>val ls = List(Some(2), Some(5), Some(4), Some(1))

ls.fold(Some(0))((rs,x) => for(n <- x; m <- rs) yield {n+m})
</code>```

Instead of None as case Base, I put 0, but with the context of Option.

Body:
I was trying to sum all elements in a list, they are of type Option[Int], if any of them are None, the whole result is None, if all are Some(value), I want the sum of all of them:

val ls = List(Some(2), Some(5), Some(4), Some(1))

ls.fold(None)((rs,x) => for(n <- x; m <- rs) yield {n+m})

but I always get None, no matter what.

Body:
I realize what was my error, it was the base case in fold:

val ls = List(Some(2), Some(5), Some(4), Some(1))

ls.fold(Some(0))((rs,x) => for(n <- x; m <- rs) yield {n+m})

Instead of None as case Base, I put 0, but with the context of Option.


问:
jQuery Mobile navigate or changePage?
With the arrival of jQuery Mobile 1.3, the .navigate() function has been added.  I've heard that is the recommended way to change pages, and it seems they addressed the issues of transferring data between pages.

The problem is, since it has been simplified, how do I access the other options that changePage offered?  I would really like to use the {data} portion of the .navigate() but I would also like to set a few options that I do normally with changePage (such as transition, direction, etc).

I currently have a "router" that listens for all navigate events, then passes along any data that it receives on to the next page (doing some other simple logic as well, like setting up the views controller).

Is there some hidden properties in the [,options] that I would be able to set up simple things like direction and transition?

答:
Use the Pagecontainer widget added in v1.4.

```<code>$(":mobile-pagecontainer").pagecontainer("change", "jquerypageIdentifier",{ options in key value format } );
</code>```

e.g

```<code>$(":mobile-pagecontainer").pagecontainer("change", "#nextpage",{ transition: "slide",role: "dialog" } );
</code>```

Title: jQuery Mobile navigate or changePage?

Body:
Use the Pagecontainer widget added in v1.4.

$(":mobile-pagecontainer").pagecontainer("change", "jquerypageIdentifier",{ options in key value format } );

e.g

$(":mobile-pagecontainer").pagecontainer("change", "#nextpage",{ transition: "slide",role: "dialog" } );


问:
Synchronize WPF ColorAnimation across several controls
I have several toggle-like buttons that I want to pulsate in unison when in the pressed state.

I have defined a style with a trigger that kicks-off the glow animation and this works just fine, apart from the fact that each button pulsates asynchronously from the others.

How can I have each button synchronize its pulse to the others?

Here's the style:

```<code><Storyboard x:Key="pulseStory">
    <ColorAnimation
        Storyboard.TargetProperty="(Control.Background).(SolidColorBrush.Color)"
                    From="Red"
                    To="Transparent"
                    Duration="0:0:1" />
</Storyboard>

<Style x:Key="pulseButton" TargetType="Button">
    <Style.Triggers>
        <DataTrigger Binding="{Binding Tag,RelativeSource={RelativeSource Self}}" Value="True">
            <DataTrigger.EnterActions>
                <BeginStoryboard Storyboard="{StaticResource pulseStory}"/>
            </DataTrigger.EnterActions>
        </DataTrigger>
    </Style.Triggers>
</Style>
</code>```

Cheers!

答:
OK ... I'll take a stab at this one ...

The WPF framework doesn't have any facility for synchronizing animations that are running concurrently, so you are going to have to come up with a different method. One idea springs to mind ...

Animate some Color property of a hidden UI element within your storyboard, then use UI binding (i.e. ElementName bindings) to connect to the Color of each of your buttons to this hidden UI element.

Body:
I have several toggle-like buttons that I want to pulsate in unison when in the pressed state.

I have defined a style with a trigger that kicks-off the glow animation and this works just fine, apart from the fact that each button pulsates asynchronously from the others.

How can I have each button synchronize its pulse to the others?

Here's the style:

<Storyboard x:Key="pulseStory">
    <ColorAnimation
        Storyboard.TargetProperty="(Control.Background).(SolidColorBrush.Color)"
                    From="Red"
                    To="Transparent"
                    Duration="0:0:1" />
</Storyboard>

</Style>

Cheers!


问:
Eclipse modifies server.xml each time run the project (Run-->Run on Server)
I'm using Tomcat 7 on Eclipse Juno. I use workspace metadata as server location (Please see my tomcat configurations below).

Also I got a Server project in eclipse [please see the image below] with separate server.xml and other configuration files.

Normally it works fine. The issue came across after I changed the server.xml (in eclipse project) for SSL configurations.

Configurations are working fine. But each time I run the project (Run-->Run on Server) server.xml get modified to the default version. My customized SSL changes are missing.

Also I tried to change server.xml in tomcat installation location (C:\apache-tomcat-7.0.35\conf), but it didn't pick from eclipse.

Can anyone please help me on this?

Thanks

答:
On Eclipse, double click on Server to view properties.

check "publish module contexts to separate XML files", and save it.
Run Tomcat server.
Eclipse will be create conf/[enginename]/[hostname]/[appname].xml without touching server.xml


问:
how to split a string without delimiters?
I have string "513". I need array ["5", "1", "3"]. My solution:

```<code>function nextBigger(num){
    let numStr = '' + num;
  let numArr = [];

  for(let i = 0; i < numStr.length; ++i) {
    numArr.push(numStr[i]);
  }

  console.log(numArr);
}

nextBigger(513);
</code>```

But this solution is large and redundant. I need shorter solution.

答: You can do it by numString.split(''). (Two single quotes without space). That will return an array with all the characters.

Body:
I have string "513". I need array ["5", "1", "3"]. My solution:

function nextBigger(num){
    let numStr = '' + num;
  let numArr = [];

  for(let i = 0; i < numStr.length; ++i) {
    numArr.push(numStr[i]);
  }

  console.log(numArr);
}

nextBigger(513);

But this solution is large and redundant. I need shorter solution.


问:
Liquibase diff - Driver issue
i tried to make a

liquibase xml with liquibase diff

command.

I want to do this based on this documentation: http://www.liquibase.org/documentation/diff.html

If I try to exec the example command with my custom properties,
with

--driver:org.postgresql.Driver,
I got this problem:

"Unexpected error running Liquibase: java.lang.RuntimeException:
  Cannot find database driver: org.postgresql.Driver"

答:
You have to specify the classpath where the driver jar file is located using the classpath key (liquibase documentation).

Your properties file should look like:

```<code>driver: org.postgresql.Driver
classpath: postgresql-driver.jar
url: jdbc:postgres@localhost:5432
username: scott
password: tiger
</code>```

Title: Liquibase diff - Driver issue

Body:
You have to specify the classpath where the driver jar file is located using the classpath key (liquibase documentation).

Your properties file should look like:

driver: org.postgresql.Driver
classpath: postgresql-driver.jar
url: jdbc:postgres@localhost:5432
username: scott
password: tiger


问:
TypeScript: Sometimes don't show the latest data when delete user
I'm working on chrome browser. I have a table list users, and want to CRUD on that. Try to delete user, sometimes data reload is OK, but sometimes it's not change (need to press f5, the page will show latest data)
In ts file:

```<code> deleteUser(user: User) {
    if(user){
      this.userService.deleteUser(user);
      this.ngOnInit();
    }
  }

 ngOnInit() { //when component loading get all users and set the users[]
    this.getAllUsers();
  }

 getAllUsers() {
    this.userService.getUsers().then(user =>
        this.users = user
       );

  }
</code>```

service

```<code>deleteUser(user: User): Promise<void> {
        const url = `${this.userUrl}/${user.id}`;
        return this.http.delete(url, { headers: this.headers })
          .toPromise()
          .then(() => null)
          .catch(this.handleError);
      }

 getUsers(): Promise<User[]> {
        return this.http.get(this.userUrl)
          .toPromise()
          .then(response => response.json().content as User[])
          .catch(this.handleError)
      }
</code>```

html

```<code><button  type="button" class="btn btn-warning" (click)="deleteUser(user)">Delete</button>
</code>```

Please advice me. Many thanks.

答:
```<code>deleteUser(user: User) {
    if(user){
      this.userService.deleteUser(user)
           .then(() => this.ngOnInit());
    }
  }
</code>```

The deleteUser function service is returning a promise so you need to call onInit only after the promise is resolved.

Body:
I'm working on chrome browser. I have a table list users, and want to CRUD on that. Try to delete user, sometimes data reload is OK, but sometimes it's not change (need to press f5, the page will show latest data)
In ts file:

 deleteUser(user: User) {
    if(user){
      this.userService.deleteUser(user);
      this.ngOnInit();
    }
  }

 ngOnInit() { //when component loading get all users and set the users[]
    this.getAllUsers();
  }

 getAllUsers() {
    this.userService.getUsers().then(user =>
        this.users = user
       );

  }

service

deleteUser(user: User): Promise<void> {
        const url = `${this.userUrl}/${user.id}`;
        return this.http.delete(url, { headers: this.headers })
          .toPromise()
          .then(() => null)
          .catch(this.handleError);
      }

 getUsers(): Promise<User[]> {
        return this.http.get(this.userUrl)
          .toPromise()
          .then(response => response.json().content as User[])
          .catch(this.handleError)
      }

html

<button  type="button" class="btn btn-warning" (click)="deleteUser(user)">Delete</button>

Please advice me. Many thanks.

Body:
deleteUser(user: User) {
    if(user){
      this.userService.deleteUser(user)
           .then(() => this.ngOnInit());
    }
  }

The deleteUser function service is returning a promise so you need to call onInit only after the promise is resolved.


答:
With ES6, you could use the spread syntax ... which takes an iterable and iterates the single items.

Or just take the power of Array.from, which does nearly the same (and much more).

const getCharacters1 = string => [...string];
const getCharacters2 = string => Array.from(string);

console.log(getCharacters1('513'));
console.log(getCharacters2('513'));```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

Title: how to split a string without delimiters?

Body:
With ES6, you could use the spread syntax ... which takes an iterable and iterates the single items.

Or just take the power of Array.from, which does nearly the same (and much more).

const getCharacters1 = string => [...string];
const getCharacters2 = string => Array.from(string);

console.log(getCharacters1('513'));
console.log(getCharacters2('513'));

.as-console-wrapper { max-height: 100% !important; top: 0; }


问:
File is already use in some other process
Here I want to delete  line in a textfiles  containg  specific string like "21309#003" where item1 is a filename but It shows runtime exception that item1 (file) is already use in some process.How I Solve this problem.I am new in .net C#.</p>

```<code>    private void button1_Click(object sender, EventArgs e)
    {
        var selectedItems = listBox1.SelectedItems.Cast<String>().ToList();
        foreach (var item in selectedItems)
        {
            listBox1.Items.Remove(item);

        }

        foreach (var item1 in selectedItems)
        {
            listBox1.Items.Remove(item1);
            string line = null;
            //string line_to_delete = "the line i want to delete";

           using (StreamReader reader = new StreamReader(item1))
            //item1=  "C:\\IMP2711\\textpresent.txt"
            {

                using (StreamWriter writer = new StreamWriter(item1))
                {
                    while ((line = reader.ReadLine()) != null)
                   {
                        //if (String.Compare(line, @"*21349#003*") == 0)

                       //if (!line.Contains("21349#003") )
                       if (!line.StartsWith("21349#003"))
                       {**strong text**

                           writer.WriteLine(line);
                       }

                    }
                }
</code>```

答:
There's some process that's locking the file c:\imp2711\textpresent.txt. You have to find and kill it.

To find it out, please refer to this question: https://superuser.com/questions/117902/find-out-which-process-is-locking-a-file-or-folder-in-windows

Body:
Here I want to delete  line in a textfiles  containg  specific string like "21309#003" where item1 is a filename but It shows runtime exception that item1 (file) is already use in some process.How I Solve this problem.I am new in .net C#.

    private void button1_Click(object sender, EventArgs e)
    {
        var selectedItems = listBox1.SelectedItems.Cast<String>().ToList();
        foreach (var item in selectedItems)
        {
            listBox1.Items.Remove(item);

        }

        foreach (var item1 in selectedItems)
        {
            listBox1.Items.Remove(item1);
            string line = null;
            //string line_to_delete = "the line i want to delete";

           using (StreamReader reader = new StreamReader(item1))
            //item1=  "C:\\IMP2711\\textpresent.txt"
            {

                using (StreamWriter writer = new StreamWriter(item1))
                {
                    while ((line = reader.ReadLine()) != null)
                   {
                        //if (String.Compare(line, @"*21349#003*") == 0)

                       //if (!line.Contains("21349#003") )
                       if (!line.StartsWith("21349#003"))
                       {**strong text**

                           writer.WriteLine(line);
                       }

                    }
                }


问:
Print string values in object list
Im currently trying to make an addressbook application that holds some person data in an object which is then added to a list. Im currently making a method to try and list the data when prompted but the information isnt showing, does anyone know how I can go about fixing this?

```<code>namespace AddressBook
{
    class Student : Person
    {
    public String StudentID { get; set; }
    public String grade { get; set; }

    public List<Student> studentList = new List<Student>();

 public void addStudent(string firstName, string lastName, string address, string city, string country, string postcode, string StudentID, string grade )
    {
        Student student = new Student();
        student.firstName = firstName;
        student.lastName = lastName;
        student.address = address;
        student.city = city;
        student.country = country;
        student.postcode = postcode;
        student.StudentID = StudentID;
        student.grade = grade;
        studentList.Add(student);
    }

 public void listStudentData()
    {
        String fname ="", lname="", add="", city="", country="", post="", id="", grd = "";
        String[,] index = { { "First name: ", "Last Name: ", "Address: ", "City: ", "Country: ", "Postcode: ", "StudentID: ", "Grade: " }, { fname, lname, add, city, country, post, id, grd }, };
        for (int i = 0; i < studentList.Count; i++)
        {
            fname = (studentList[i].firstName.ToString());
            lname = (studentList[i].lastName.ToString());
            add = (studentList[i].address.ToString());
            city = (studentList[i].city.ToString());
            country = (studentList[i].country.ToString());
            post = (studentList[i].postcode.ToString());
            id = (studentList[i].StudentID.ToString());
            grd = (studentList[i].grade.ToString());
            Console.WriteLine(index[0, i] + index[1,i]);
        }
        Console.WriteLine("");
    }

}
</code>```

}

The format I want to print out is
"First Name: John"
"Last Name: Smith" etc

however the current format is:
"First Name: "

Any advice would be much appreciated

答:
You are really over complicating things, just to list the students. It's as easy as this:

```<code>public void ListStudentData()
{
    foreach (Student student in studentList)
    {
        Console.WriteLine("First Name: {0}", student.firstName);
        Console.WriteLine("Last Name: {0}", student.lastName);
        Console.WriteLine("Address: {0}", student.address);
        ...
        ...
        ...
    }
}
</code>```

Also, usually as a standard naming convention, method names should begin with a capital letter.

Title: Print string values in object list

Body:
Im currently trying to make an addressbook application that holds some person data in an object which is then added to a list. Im currently making a method to try and list the data when prompted but the information isnt showing, does anyone know how I can go about fixing this?

namespace AddressBook
{
    class Student : Person
    {
    public String StudentID { get; set; }
    public String grade { get; set; }

    public List<Student> studentList = new List<Student>();

 public void addStudent(string firstName, string lastName, string address, string city, string country, string postcode, string StudentID, string grade )
    {
        Student student = new Student();
        student.firstName = firstName;
        student.lastName = lastName;
        student.address = address;
        student.city = city;
        student.country = country;
        student.postcode = postcode;
        student.StudentID = StudentID;
        student.grade = grade;
        studentList.Add(student);
    }

 public void listStudentData()
    {
        String fname ="", lname="", add="", city="", country="", post="", id="", grd = "";
        String[,] index = { { "First name: ", "Last Name: ", "Address: ", "City: ", "Country: ", "Postcode: ", "StudentID: ", "Grade: " }, { fname, lname, add, city, country, post, id, grd }, };
        for (int i = 0; i < studentList.Count; i++)
        {
            fname = (studentList[i].firstName.ToString());
            lname = (studentList[i].lastName.ToString());
            add = (studentList[i].address.ToString());
            city = (studentList[i].city.ToString());
            country = (studentList[i].country.ToString());
            post = (studentList[i].postcode.ToString());
            id = (studentList[i].StudentID.ToString());
            grd = (studentList[i].grade.ToString());
            Console.WriteLine(index[0, i] + index[1,i]);
        }
        Console.WriteLine("");
    }

}

}

The format I want to print out is
"First Name: John"
"Last Name: Smith" etc

however the current format is:
"First Name: "

Any advice would be much appreciated

Body:
You are really over complicating things, just to list the students. It's as easy as this:

public void ListStudentData()
{
    foreach (Student student in studentList)
    {
        Console.WriteLine("First Name: {0}", student.firstName);
        Console.WriteLine("Last Name: {0}", student.lastName);
        Console.WriteLine("Address: {0}", student.address);
        ...
        ...
        ...
    }
}

Also, usually as a standard naming convention, method names should begin with a capital letter.


答:
You are reading and writing to the same file at the same time.

```<code>var item2 = item1;
</code>```

If the file is not to big you can read the lines into memory and then write the lines you want to keep back to the file. We can even simplify your code a little bit.

```<code>File.WriteAllLines(item1,
    File.ReadLines(item1).Where(l => !l.StartsWith("21349#003")).ToList());
</code>```

Another option if the file is very large is to write to a temporary file. Delete the original and then rename the temporary.

```<code>var tmp = Path.GetTempFileName();
File.WriteAllLines(tmp, File.ReadLines(item1).Where(l => !l.StartsWith("21349#003")));
File.Delete(item1);
File.Move(tmp, item1);
</code>```

Title: File is already use in some other process

Body:
You are reading and writing to the same file at the same time.

var item2 = item1;

If the file is not to big you can read the lines into memory and then write the lines you want to keep back to the file. We can even simplify your code a little bit.

File.WriteAllLines(item1,
    File.ReadLines(item1).Where(l => !l.StartsWith("21349#003")).ToList());

Another option if the file is very large is to write to a temporary file. Delete the original and then rename the temporary.

var tmp = Path.GetTempFileName();
File.WriteAllLines(tmp, File.ReadLines(item1).Where(l => !l.StartsWith("21349#003")));
File.Delete(item1);
File.Move(tmp, item1);


问:
how to serialize class to database instead of file system c#
we can easily serialize class to flat file but if i want to serialize class to database then how could i do it and if it is possible then how can i deserialize data from db to class.
please give a sample code in c#.

thanks

答:
Like other said at already, you can use binary serialization to get the Byte[] array in a memory stream and then create a column in database of type Blob / image to store the the byte array.

Then while reading back, you just read the value of the column in the stream back by using technique called deserialization

Serialization

```<code>  BinaryFormatter bf = new BinaryFormatter();

        List<SearchFilterDetails> _list = QueryFilterDetails.ToList<SearchFilterDetails>();

        using (MemoryStream ms = new MemoryStream())
        {
            bf.Serialize(ms, _list);
            return ms.GetBuffer();
        }
</code>```

Deserialization

```<code>  private void DeSerilizeQueryFilters(byte[] items)
    {
        BinaryFormatter bf = new BinaryFormatter();

        List<SearchFilterDetails> _list = new List<SearchFilterDetails>();

        try
        {
            using (MemoryStream ms = new MemoryStream())
            {
                ms.Write(items, 0, items.Length);
                ms.Position = 0;

                _list = bf.Deserialize(ms) as List<SearchFilterDetails>;
            }

            foreach (SearchFilterDetails mobj in _list)
            {
                QueryFilterDetails.Add(mobj);
            }
        }
        catch (Exception ex)
        {
        }
    }
</code>```

Body:
Like other said at already, you can use binary serialization to get the Byte[] array in a memory stream and then create a column in database of type Blob / image to store the the byte array.

Then while reading back, you just read the value of the column in the stream back by using technique called deserialization

Serialization

  BinaryFormatter bf = new BinaryFormatter();

        List<SearchFilterDetails> _list = QueryFilterDetails.ToList<SearchFilterDetails>();

        using (MemoryStream ms = new MemoryStream())
        {
            bf.Serialize(ms, _list);
            return ms.GetBuffer();
        }

Deserialization

  private void DeSerilizeQueryFilters(byte[] items)
    {
        BinaryFormatter bf = new BinaryFormatter();

        List<SearchFilterDetails> _list = new List<SearchFilterDetails>();

        try
        {
            using (MemoryStream ms = new MemoryStream())
            {
                ms.Write(items, 0, items.Length);
                ms.Position = 0;

                _list = bf.Deserialize(ms) as List<SearchFilterDetails>;
            }

            foreach (SearchFilterDetails mobj in _list)
            {
                QueryFilterDetails.Add(mobj);
            }
        }
        catch (Exception ex)
        {
        }
    }


问:
How to add Tag Value to Elements/ Entities in Spark EA using VBA?
I am trying to port some data from Excel sheet into EA model. I have managed to build a model, However I want to add some tag values to the elements/entities I have created through VBA. I have used Geert Bellekens EAExcelimporter utility and modified/amended it to suit my requirements.I am however not able to extend it to add tagged values to Entities. Anyhelp in this regards shall be greatly appreciated.

Thanks,
Rahul.

答:
I have now managed to write code for this.

Public Function addOrUpdateElementTag(anElement As EA.element, Tagname As String, tagValue As String) As EA.taggedvalue
    Dim currentElementTag As EA.taggedvalue
    'update all tagged values with the given name
    'Dim parentPackage As EA.package
    'get the selected package
    'Set parentPackage = eaConn.getSelectedPackage()

```<code>For Each currentElementTag In anElement.TaggedValues
    If currentElementTag.name = Tagname Then
        currentElementTag.Value = tagValue
        Set addOrUpdateElementTag = currentElementTag
        currentElementTag.Update
    End If
Next
'no tagged value found, so create it
If addOrUpdateElementTag Is Nothing Then
    Set addOrUpdateElementTag = anElement.TaggedValues.AddNew(Tagname, "ElementTag")
    addOrUpdateElementTag.Value = tagValue
    addOrUpdateElementTag.Update
End If
</code>```

End Function

Hope this will be helpful to someone in future.

Thanks,
Rahul.

Body:
I have now managed to write code for this.

Public Function addOrUpdateElementTag(anElement As EA.element, Tagname As String, tagValue As String) As EA.taggedvalue
    Dim currentElementTag As EA.taggedvalue
    'update all tagged values with the given name
    'Dim parentPackage As EA.package
    'get the selected package
    'Set parentPackage = eaConn.getSelectedPackage()

For Each currentElementTag In anElement.TaggedValues
    If currentElementTag.name = Tagname Then
        currentElementTag.Value = tagValue
        Set addOrUpdateElementTag = currentElementTag
        currentElementTag.Update
    End If
Next
'no tagged value found, so create it
If addOrUpdateElementTag Is Nothing Then
    Set addOrUpdateElementTag = anElement.TaggedValues.AddNew(Tagname, "ElementTag")
    addOrUpdateElementTag.Value = tagValue
    addOrUpdateElementTag.Update
End If

End Function

Hope this will be helpful to someone in future.

Thanks,
Rahul.


问:
Retrieving JSON elements in Swift 3
I have following JSON file

```<code>{
    "events": [
               {
               "date": "01/11/2017",
               "name": [
                        "Tulsi Vivah",
                        "Pradosh Vrat"
                        ],
               "photo": [
                         "photo_chaturthi",
                         "photo_ekadashi"
                         ]
               },
               {
               "date": "03/11/2017",
               "name": [
                        "Guru Nanak Jayanti"
                        ],
               "photo": [
                         "photo_chaturthi",
                         "photo_ekadashi"
                         ]
               }
               ]
}
</code>```

I want to parse this and put the elements in the objectArray in the code below:

```<code>struct Objects {

        var sectionName : String!
        var sectionObjects : [String]!
        var sectionImages : [String]!
    }
    var objectArray = [Objects]()
</code>```

I have written following code for reading the file:

```<code>if let file = Bundle.main.url(forResource: "EventsEnglish112017", withExtension: "json") {
            let data = try Data(contentsOf: file)
            let json = try JSONSerialization.jsonObject(with: data as Data, options: [])
</code>```

My question is how do I typecast "json" to read the individual elements to fill the above objectArray.

Thanks!

答:
A JSON is a dictionary of type [String:Any?]
To parse it:

```<code>if let dictionary = json as? [String: Any?] {
    if let events = dictionary["events"] as? [[String: Any?]] {

    // events is an array of JSON objects, so it's an array of dictionaries
       for item in events
       {
          let date = item["date"] as? String // this is a String?
          let name = item["name"] as? [String]
          // same goes for 'photo'
        }
    }
}
</code>```

Now that you have retrieved the data, you can use it to costruct your custom objects.
But it's better if you use some library that will make it for you, or use Swift4

Title: Retrieving JSON elements in Swift 3

Body:
I have following JSON file

{
    "events": [
               {
               "date": "01/11/2017",
               "name": [
                        "Tulsi Vivah",
                        "Pradosh Vrat"
                        ],
               "photo": [
                         "photo_chaturthi",
                         "photo_ekadashi"
                         ]
               },
               {
               "date": "03/11/2017",
               "name": [
                        "Guru Nanak Jayanti"
                        ],
               "photo": [
                         "photo_chaturthi",
                         "photo_ekadashi"
                         ]
               }
               ]
}

I want to parse this and put the elements in the objectArray in the code below:

struct Objects {

        var sectionName : String!
        var sectionObjects : [String]!
        var sectionImages : [String]!
    }
    var objectArray = [Objects]()

I have written following code for reading the file:

if let file = Bundle.main.url(forResource: "EventsEnglish112017", withExtension: "json") {
            let data = try Data(contentsOf: file)
            let json = try JSONSerialization.jsonObject(with: data as Data, options: [])

My question is how do I typecast "json" to read the individual elements to fill the above objectArray.

Thanks!

Body:
A JSON is a dictionary of type [String:Any?]
To parse it:

if let dictionary = json as? [String: Any?] {
    if let events = dictionary["events"] as? [[String: Any?]] {

    // events is an array of JSON objects, so it's an array of dictionaries
       for item in events
       {
          let date = item["date"] as? String // this is a String?
          let name = item["name"] as? [String]
          // same goes for 'photo'
        }
    }
}

Now that you have retrieved the data, you can use it to costruct your custom objects.
But it's better if you use some library that will make it for you, or use Swift4


问:
Why is not the compiler giving error?
I am using the following sample program in C++

```<code>#include<iostream>
#include<ctime>
#include<cstdlib>

using namespace std;

namespace mine{
    template<class T>
    inline void swap(T &a, T &b){
        char c= a; //This should not have compiled
        a=b;
        b=c;
    }

}
int main(){
    int a,b;
    cout<< "Enter two values: ";
    cin>>a>>b;
    mine::swap(a,b); //type variable T is instantiated as in
    cout << a <<' '<<b << endl;
}
</code>```

I am expecting the compiler to throw an error in the swap function, because c is declared as a char, but assigned a variable of generic type variable T. Not only that, when invoking swap, T is instantiated as int. However, not only is g++ not giving any error, the program works perfectly. Why is this the case?

答:
First of all, converting int to char is legal, it is a narrowing conversion, and the compiler might warn you if you configure it to do so.

As for why the code compiles, this is due to the fact that the type is known at compile time, therefore the compiler knows that for all the instances of T that it initialised, T is convertible to char.

If you will change a to a type that is not convertible to char, the compiler will complain: e.g with MSVC
The following code give error C2440: 'initializing' : cannot convert from 'std::string' to 'char':

```<code>#include "stdafx.h"
#include<iostream>
#include<ctime>
#include<cstdlib>

using namespace std;

namespace mine{
    template<class T>
    inline void swap(T &a, T &b){
        char c= a; //This should not have compiled
        a=b;
        b=c;
    }

}

int _tmain(int argc, _TCHAR* argv[])
{
    string a("test");
    string b("test2");
    mine::swap(a,b); //type variable T is instantiated as in
}
</code>```

Title: Why is not the compiler giving error?

Body:
I am using the following sample program in C++

#include<iostream>
#include<ctime>
#include<cstdlib>

using namespace std;

namespace mine{
    template<class T>
    inline void swap(T &a, T &b){
        char c= a; //This should not have compiled
        a=b;
        b=c;
    }

}
int main(){
    int a,b;
    cout<< "Enter two values: ";
    cin>>a>>b;
    mine::swap(a,b); //type variable T is instantiated as in
    cout << a <<' '<<b << endl;
}

I am expecting the compiler to throw an error in the swap function, because c is declared as a char, but assigned a variable of generic type variable T. Not only that, when invoking swap, T is instantiated as int. However, not only is g++ not giving any error, the program works perfectly. Why is this the case?

Body:
First of all, converting int to char is legal, it is a narrowing conversion, and the compiler might warn you if you configure it to do so.

As for why the code compiles, this is due to the fact that the type is known at compile time, therefore the compiler knows that for all the instances of T that it initialised, T is convertible to char.

If you will change a to a type that is not convertible to char, the compiler will complain: e.g with MSVC
The following code give error C2440: 'initializing' : cannot convert from 'std::string' to 'char':

#include "stdafx.h"
#include<iostream>
#include<ctime>
#include<cstdlib>

using namespace std;

namespace mine{
    template<class T>
    inline void swap(T &a, T &b){
        char c= a; //This should not have compiled
        a=b;
        b=c;
    }

}

int _tmain(int argc, _TCHAR* argv[])
{
    string a("test");
    string b("test2");
    mine::swap(a,b); //type variable T is instantiated as in
}


问:
REGEX to get ID ath the end of an URL without /
I'm trying to do a GreaseMonkey script and i'm stucked on a REGEX to get the ID of an article in URL.

I have URL like https://www.blabla.com/poney-2000-poneys-dance-bla,272317

And i want to use the ID at the end after the Comma : 272317

I tried this REGEX : (,([\d]+)) to avoid taking digit in the rest of the URL and it get me ,272317 but I want it without the comma at the begining.

Do you have an idea how i can improve my REGEX ?

Thanks a lot :)

答:
Just need to remove that outer paran since you don't want to capture the , </p>

```<code>,(\d+)$
</code>```

Body:
Just need to remove that outer paran since you don't want to capture the ,

,(\d+)$


问:
Laravel external(from another domain) api request to check if the user is logged in a server (main server)
How can I make a logged-in-check via an external call (external domain) to a main server? Should be a js client-server call.

In other words domain1.com makes a client-server call to the main-domain.com to check if the user is already logged-in in main-domain.com

答:
According to me, easiest way is to maintain a flag in your main domain.
So what you need to do is.

Add one field in users table, let's say isLoggedIn

Create an API which return true or false when you make a call from domain1.com

Handle data based on the result of the API.


答:
Maybe use .split() function.</p>

```<code>"513".split("")
</code>```

Body:
Maybe use .split() function.

"513".split("")


答:
You can use the Spread syntax if you want something really short

let a = [...'513']

Body:
I have string "513". I need array ["5", "1", "3"]. My solution:

function nextBigger(num){
    let numStr = '' + num;
  let numArr = [];

  for(let i = 0; i < numStr.length; ++i) {
    numArr.push(numStr[i]);
  }

  console.log(numArr);
}

nextBigger(513);

But this solution is large and redundant. I need shorter solution.