问:
Recursively advancing a variable by a growth rate variable in SAS
I have a panel/longitudinal dataset in SAS.

One field indicates a class or type, another a point in time without breaks, another is the observed history and another is the log difference forecast for said history. I'd like to add a new field: the history field, advanced by the forecast field.

So if the time field is in the 'future', I want to recursively advance my goal variable with its own lag, multiplied by the exp of the log-difference forecast variable. A trivial operation it seems to me.

I've attempted to replicate the problem with a toy dataset below.

```<code>data in;
input class time hist forecast;
datalines;
1   1  100 .
1   2   .  .1
1   3   .  .15
1   4   .  .17
2   1  100 .
2   2   .  .18
2   3   .  .12
2   4   .  .05
run;

proc sort data=work.in;
by class time;
run;

data out;
    set in;
    by class time;
retain goal hist;
if time > 1 then goal= lag1(goal) * exp(forecast);
run;
</code>```

答:
JP:

You might want this:

```<code>data out;
    set in;
    by class time;

    retain goal;

    if first.class
      then goal=hist;
      else goal = goal * exp(forecast);
run;
</code>```

Retaining a non data set variable can mostly be considered a lag1 type of stack.  The initial goal needs to be reset at the start of each group.

Your first attempt is conditionally LAG1'ng a retained variable while BY group processing -- makes my head spin.  LAG-n is tricky because the implicit LAG stack is updated only when processing flow goes through it.  If a conditional bypasses the LAG function invocation there is no way the LAG stack can get updated.  If you do see LAG in other SAS coding, it might appear in an unconditional place prior to any ifs.

NOTE: retaining data set variables (such as hist) is atypical because their values are overwritten when the SET statement is reached.  The atypical case is when testing the retained data set variable prior to the SET statement has a functional purpose.

Body:
I have a panel/longitudinal dataset in SAS.

One field indicates a class or type, another a point in time without breaks, another is the observed history and another is the log difference forecast for said history. I'd like to add a new field: the history field, advanced by the forecast field.

So if the time field is in the 'future', I want to recursively advance my goal variable with its own lag, multiplied by the exp of the log-difference forecast variable. A trivial operation it seems to me.

I've attempted to replicate the problem with a toy dataset below.

data in;
input class time hist forecast;
datalines;
1   1  100 .
1   2   .  .1
1   3   .  .15
1   4   .  .17
2   1  100 .
2   2   .  .18
2   3   .  .12
2   4   .  .05
run;

proc sort data=work.in;
by class time;
run;

data out;
    set in;
    by class time;
retain goal hist;
if time > 1 then goal= lag1(goal) * exp(forecast);
run;

Body:
JP:

You might want this:

data out;
    set in;
    by class time;

    retain goal;

    if first.class
      then goal=hist;
      else goal = goal * exp(forecast);
run;

Retaining a non data set variable can mostly be considered a lag1 type of stack.  The initial goal needs to be reset at the start of each group.

Your first attempt is conditionally LAG1'ng a retained variable while BY group processing -- makes my head spin.  LAG-n is tricky because the implicit LAG stack is updated only when processing flow goes through it.  If a conditional bypasses the LAG function invocation there is no way the LAG stack can get updated.  If you do see LAG in other SAS coding, it might appear in an unconditional place prior to any ifs.

NOTE: retaining data set variables (such as hist) is atypical because their values are overwritten when the SET statement is reached.  The atypical case is when testing the retained data set variable prior to the SET statement has a functional purpose.


来源: stackexchange

问:
Android - How to read txt file in JAVA
Please Will some one help me out i am trying to read an Arabic .txt file and it always give me the Arabic word like this "????? ???"</p>

```<code>private String ReadArabic() {

    String words="";
    try {
        InputStream stream = getAssets().open("arabwords.txt");

        int size = stream.available();
        byte[] buffer = new byte[size];
        stream.read(buffer);
        stream.close();
        words = new String(buffer, "UTF-8");
        words = words.replaceAll("(\\r|\\n)", "");
    } catch (IOException e) {
        // Handle exceptions here
    }
    return words;
}
</code>```

答: Try using: "cp864" instead of "UTF-8"</p>

ContentLicense: CC BY-SA 3.0

Title: Android - How to read txt file in JAVA

Body:
Please Will some one help me out i am trying to read an Arabic .txt file and it always give me the Arabic word like this "????? ???"

private String ReadArabic() {

    String words="";
    try {
        InputStream stream = getAssets().open("arabwords.txt");

        int size = stream.available();
        byte[] buffer = new byte[size];
        stream.read(buffer);
        stream.close();
        words = new String(buffer, "UTF-8");
        words = words.replaceAll("(\\r|\\n)", "");
    } catch (IOException e) {
        // Handle exceptions here
    }
    return words;
}

Body: Try using: "cp864" instead of "UTF-8"


问:
Serilog LogContext and custom args don't combine
Is there a way to mix custom serilog args and LogContext properties? I have looked through the docs but it doesn't seem to be mentioned.

```<code>    static void Main()
    {
        Log.Logger = new LoggerConfiguration()
            .Enrich.FromLogContext()
            .WriteTo.LiterateConsole(outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss} [{Level}] {Message} [{Properties}]{NewLine}")
            .CreateLogger();

        using (LogContext.PushProperty("A", 5))
        {
            Log.Information("Message using context {A}");

            var b = 1;
            Log.Information("Message usign context {A} and custom {b}", b);
        }

        Console.ReadLine();
    }
</code>```

Output

```<code>//output:
//2017-11-14 15:47:03 [Information] Message using context 5 [{}]
//2017-11-14 15:47:54 [Information] Message usign context 1 and custom {b} [{}]
</code>```

Expected output

```<code>//output:
//2017-11-14 15:47:03 [Information] Message using context 5 [{}]
//2017-11-14 15:47:54 [Information] Message usign context 5 and custom 1 [{}]
</code>```

Is there any way to achieve this?

答:
In Serilog's API, any method that accepts a message template expects an exact number of matching arguments.

Serilog won't blow up if the number of placeholders in the template and the provided argument count doesn't match, but there's no guarantee this will work predictably - as you see here.

So in this case, it's necessary to include both A and b in the arguments to Information() in order to get the output you expect.

Body:
Is there a way to mix custom serilog args and LogContext properties? I have looked through the docs but it doesn't seem to be mentioned.

    static void Main()
    {
        Log.Logger = new LoggerConfiguration()
            .Enrich.FromLogContext()
            .WriteTo.LiterateConsole(outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss} [{Level}] {Message} [{Properties}]{NewLine}")
            .CreateLogger();

        using (LogContext.PushProperty("A", 5))
        {
            Log.Information("Message using context {A}");

            var b = 1;
            Log.Information("Message usign context {A} and custom {b}", b);
        }

        Console.ReadLine();
    }

Output

//output:
//2017-11-14 15:47:03 [Information] Message using context 5 [{}]
//2017-11-14 15:47:54 [Information] Message usign context 1 and custom {b} [{}]

Expected output

//output:
//2017-11-14 15:47:03 [Information] Message using context 5 [{}]
//2017-11-14 15:47:54 [Information] Message usign context 5 and custom 1 [{}]

Is there any way to achieve this?


问:
Access - Field size for numerical field?
With text boxes, you can set field size on how many characters can be entered.
Is it possible to do this to a numerical field?</p>

答: You could use the format property.  Another option would be to treat the field as a text box and the format property.  Then when you want to use the value numerically use the val function.</p>


问:
Nested While and For loops not stopping in python
I am converting Markdown(.md) file into HTML using a Python 2.7 program. There is an instance, however, where a while loop is not exiting correctly and just looping through the same number over and over again.

def link(line):
    link_list = []
    link_string = ''
    count = 0
    left_bracket = 0
    right_bracket = 0
    left_parenth = 0
    right_parenth = 0
    for char in line:
        link_list.append(char)
    while count < (len(link_list)):
        if link_list[count] == "[":
            left_bracket = count
            for x in link_list[left_bracket+1:]:
                if x == "]":
                    right_bracket = link_list.index(x)
                if x == "(":
                    left_parenth = link_list.index(x)
                if x == ")":
                    right_parenth = link_list.index(x)
                    break
            a_list = link_list[left_bracket+1:right_bracket]
            str1 = ''.join(a_list)
            href_list = link_list[left_parenth+1:right_parenth]
            str2 = ''.join(href_list)
            link_string = link_string + '' + str1 + ''
            count = right_parenth +1
        if link_list[count] != "[":
            link_string = link_string + link_list[count]
            count += 1
    print link_string
link("lorem ipsum [inside bracket](URL LINK), [inside_bracket2](URL2)")```
</div>
</div>
</p>

<p>In this function, it is converting Markdown link formats to HTML link formats. </p>

<p>If you call the function with the argument below</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>link("lorem ipsum [inside bracket](URL LINK")</code>```

it gives you the correct output. However, when you put more than one markdown link in a string, then the while loops and for loops do not function properly.

答:
Here:

```<code>            if x == "]":
                right_bracket = link_list.index(x)
            if x == "(":
                left_parenth = link_list.index(x)
            if x == ")":
                right_parenth = link_list.index(x)
                break
</code>```

You're using the bracket/parenths as indexes, so you should directly pass x to them. By using link_list.index(x), it always returns the first character it finds from the left, and that's why your loop got stuck.

Body:
I am converting Markdown(.md) file into HTML using a Python 2.7 program. There is an instance, however, where a while loop is not exiting correctly and just looping through the same number over and over again.

def link(line):
    link_list = []
    link_string = ''
    count = 0
    left_bracket = 0
    right_bracket = 0
    left_parenth = 0
    right_parenth = 0
    for char in line:
        link_list.append(char)
    while count < (len(link_list)):
        if link_list[count] == "[":
            left_bracket = count
            for x in link_list[left_bracket+1:]:
                if x == "]":
                    right_bracket = link_list.index(x)
                if x == "(":
                    left_parenth = link_list.index(x)
                if x == ")":
                    right_parenth = link_list.index(x)
                    break
            a_list = link_list[left_bracket+1:right_bracket]
            str1 = ''.join(a_list)
            href_list = link_list[left_parenth+1:right_parenth]
            str2 = ''.join(href_list)
            link_string = link_string + '' + str1 + ''
            count = right_parenth +1
        if link_list[count] != "[":
            link_string = link_string + link_list[count]
            count += 1
    print link_string
link("lorem ipsum [inside bracket](URL LINK), [inside_bracket2](URL2)")

In this function, it is converting Markdown link formats to HTML link formats.

If you call the function with the argument below

link("lorem ipsum [inside bracket](URL LINK")

it gives you the correct output. However, when you put more than one markdown link in a string, then the while loops and for loops do not function properly.

Body:
Here:

            if x == "]":
                right_bracket = link_list.index(x)
            if x == "(":
                left_parenth = link_list.index(x)
            if x == ")":
                right_parenth = link_list.index(x)
                break

You're using the bracket/parenths as indexes, so you should directly pass x to them. By using link_list.index(x), it always returns the first character it finds from the left, and that's why your loop got stuck.


问:
Google sheets wrap cell content in other content
Im looking to create a formula in one column that takes the content from the adjacent column and wraps it inside some other content, can anyone help with this?

For example, given:

```
           A     |     B
    1|           | someText1
    2|           | someText2
    3|           | someText3
    4|           | someText4

```

expected outcome content for Col A, after applying appropriate formula:

```
                A        |     B
    1| wrap("someText1") | someText1
    2| wrap("someText2") | someText2
    3| wrap("someText3") | someText3
    4| wrap("someText4") | someText4

```

I hope this makes sense, any help would be appreciated. Thanks

答:
What i ended up doing:  Add a function and applied it to the whole column A</p>

```

    function getAdjacentValue() {
    var range = SpreadsheetApp.getActiveRange();
    var col = range.getColumn();
    var row = range.getRow();
    var range2 = SpreadsheetApp.getActiveSheet().getRange(row,col+1);
    return 'wrap("'+range2.getValue()+'")';
    }

```

Body:
Im looking to create a formula in one column that takes the content from the adjacent column and wraps it inside some other content, can anyone help with this?

For example, given:

           A     |     B
    1|           | someText1
    2|           | someText2
    3|           | someText3
    4|           | someText4

expected outcome content for Col A, after applying appropriate formula:

                A        |     B
    1| wrap("someText1") | someText1
    2| wrap("someText2") | someText2
    3| wrap("someText3") | someText3
    4| wrap("someText4") | someText4

I hope this makes sense, any help would be appreciated. Thanks

Body:
What i ended up doing:  Add a function and applied it to the whole column A

    function getAdjacentValue() {
    var range = SpreadsheetApp.getActiveRange();
    var col = range.getColumn();
    var row = range.getRow();
    var range2 = SpreadsheetApp.getActiveSheet().getRange(row,col+1);
    return 'wrap("'+range2.getValue()+'")';
    }


问:
Does C correctly handle sizeof(...) and sizeof ... in this case?
In the following code, are the functions test and test2 equivalent?

```<code>typedef int rofl;

void test(void) {
    rofl * rofl = malloc(sizeof(rofl)); // Is the final rofl here the TYPE?
}

void test2(void) {
    rofl * rofl = malloc(sizeof *rofl); // Is the final rofl here the VARIABLE?
}
</code>```

In other words:

Does rofl in sizeof(rofl) correctly pick the rofl type because of the parentheses?

Does rofl in sizeof *rofl correctly pick the rofl variable because of a lack of parentheses?

Note: This is a silly-looking example, but it can actually happen in practice that you have a type name that's the same as a variable name. Hence the question.

答:
In this declaration

```<code>rofl * rofl = malloc(sizeof(rofl)); // Is the final rofl here the TYPE?
</code>```

the name of the variable rofl hides the typedef name rofl. Thus in the sizeof operator there is used the pointer rofl that is the expression has the type int *.

The same is valid for this declaration

```<code>rofl * rofl = malloc(sizeof *rofl);
</code>```

except that there is used an expression with the dereferenced pointer rofl that has the type of the typedef name rofl that is the type int.

It seems that the confusion arises due to this C grammar definition

```<code>sizeof unary-expression
sizeof ( type-name )
</code>```

However unary-expression can be a primary expression that is an expression enclosed in parentheses.

From the C Standard (6.5.1 Primary expressions)

```<code>primary-expression:
    ( expression )
    //...
</code>```

So for example if x is a name of a variable then you may write either

```<code>sizeof x
</code>```

or

```<code>sizeof( x )
</code>```

For clarity you could insert blanks between the sizeof operator and the primary expression

```<code>sizeof    ( x )
operator  primary expression
</code>```

For comparison consider another unary operator: the unary plus. You can write for example

```<code>+ x
</code>```

or

```<code>+ ( x )
</code>```

Now just substitute the unary plus for another unary operator sizeof.

As for hiding names the problem is resolvable for structures, unions and enumerations because their names include keywords for tags.

For example

```<code>typedef struct rofl { int x; } rofl;

void test(void) {
    rofl * rofl = malloc(sizeof( struct rofl));
}
</code>```

In this function with the sizeof operator there is used type-name struct rofl.

While in this function

```<code>typedef struct rofl { int x; } rofl;

void test(void) {
    rofl * rofl = malloc(sizeof( rofl));
}
</code>```

with the sizeof operator there is used a primary expression with the variable rofl, that has the type struct rofl *.

Body:
In the following code, are the functions test and test2 equivalent?

typedef int rofl;

void test(void) {
    rofl * rofl = malloc(sizeof(rofl)); // Is the final rofl here the TYPE?
}

void test2(void) {
    rofl * rofl = malloc(sizeof *rofl); // Is the final rofl here the VARIABLE?
}

In other words:

Does rofl in sizeof(rofl) correctly pick the rofl type because of the parentheses?

Does rofl in sizeof *rofl correctly pick the rofl variable because of a lack of parentheses?

Note: This is a silly-looking example, but it can actually happen in practice that you have a type name that's the same as a variable name. Hence the question.

Body:
In this declaration

rofl * rofl = malloc(sizeof(rofl)); // Is the final rofl here the TYPE?

the name of the variable rofl hides the typedef name rofl. Thus in the sizeof operator there is used the pointer rofl that is the expression has the type int *.

The same is valid for this declaration

rofl * rofl = malloc(sizeof *rofl);

except that there is used an expression with the dereferenced pointer rofl that has the type of the typedef name rofl that is the type int.

It seems that the confusion arises due to this C grammar definition

sizeof unary-expression
sizeof ( type-name )

However unary-expression can be a primary expression that is an expression enclosed in parentheses.

From the C Standard (6.5.1 Primary expressions)

primary-expression:
    ( expression )
    //...

So for example if x is a name of a variable then you may write either

sizeof x

or

sizeof( x )

For clarity you could insert blanks between the sizeof operator and the primary expression

sizeof    ( x )
operator  primary expression

For comparison consider another unary operator: the unary plus. You can write for example

+ x

or

+ ( x )

Now just substitute the unary plus for another unary operator sizeof.

As for hiding names the problem is resolvable for structures, unions and enumerations because their names include keywords for tags.

For example

typedef struct rofl { int x; } rofl;

void test(void) {
    rofl * rofl = malloc(sizeof( struct rofl));
}

In this function with the sizeof operator there is used type-name struct rofl.

While in this function

typedef struct rofl { int x; } rofl;

void test(void) {
    rofl * rofl = malloc(sizeof( rofl));
}

with the sizeof operator there is used a primary expression with the variable rofl, that has the type struct rofl *.


问:
Check which styles are applied to an HTML element in a view in MVC 5 project
For example, let's say there is a markup with fancy colors:

```<code><p>Something written here</p>
</code>```

Using Visual Studio 2017 and a MVC 5 project, is there a way to check and locate which styles are currently being applied to it, and the CSS source file responsible for it?

答:
Use Chrome, just right click your element, click inspect and it will open the dev tools. This shows the css applied and also which css stylesheet files it comes from.

You can't do this magically from VS, since JavaScript can change the stylesheet after the page is loaded, which VS doesn't know anything about since it isn't actually attempting to render it.

Body:
For example, let's say there is a markup with fancy colors:

Something written here

Using Visual Studio 2017 and a MVC 5 project, is there a way to check and locate which styles are currently being applied to it, and the CSS source file responsible for it?


问:
OptaPlanner Understanding a rule
We have below rule in our rule file, I am trying to understand the LHS part of the rule, there are two lines RoomAssignment and Schedule. Can someone explain how it evaluates to? An AND or OR operator is used between  RoomAssignment and Schedule? </p>

```<code>Rule "Test"
when
        RoomAssignment(schedule.isFixed == true, startingTimeGrain != null, room != null, manager != null, $startingTimeGrainIndex : startingTimeGrainIndex, $room: room, $manager: manager, $schedule: schedule)
        Schedule(id == $schedule.id, fixedDateTime == true, startTimeGrainIndex != $startingTimeGrainIndex)
    then
        scoreHolder.addHardConstraintMatch(kcontext, -100000);

        end
</code>```

答: A logical and is implicit between patterns. Working Memory must contain (at least) one RoomAssignment and (at least) one Schedule object with suitable field values. The rule fires once for each matching combination of fact objects.

Title: OptaPlanner Understanding a rule

Body:
We have below rule in our rule file, I am trying to understand the LHS part of the rule, there are two lines RoomAssignment and Schedule. Can someone explain how it evaluates to? An AND or OR operator is used between  RoomAssignment and Schedule?

Rule "Test"
when
        RoomAssignment(schedule.isFixed == true, startingTimeGrain != null, room != null, manager != null, $startingTimeGrainIndex : startingTimeGrainIndex, $room: room, $manager: manager, $schedule: schedule)
        Schedule(id == $schedule.id, fixedDateTime == true, startTimeGrainIndex != $startingTimeGrainIndex)
    then
        scoreHolder.addHardConstraintMatch(kcontext, -100000);

        end


问:
How to create a new page in Wordpress Admin for Editing the Details
Can you please help me with my proble regarding creating a New Page for Editing Details.

Currently, I have a list of Properties. This is a Custom Table not a post type. I already listed the properties but my problem is how am I gonna make the Edit Details Page?

```<code>add_action( 'admin_menu', 'pp_create_property_management_menu' ); function pp_create_property_management_menu() {
add_menu_page( 'PP M', 'PP M', 'manage_options', 'property-management', 'pp_property_management_page', 'dashicons-tickets', 5 ); }
</code>```

Many thanks,

答:
The fifth parameter in the add_menu_page() function calls a function to output the contents of the menu page.  Here's an example I have taken from the WordPress site on how to add a custom admin menu and show the details of the page.

```<code>add_action( 'admin_menu', 'my_plugin_menu' );

function my_plugin_menu() {
    add_menu_page( 'My Page Title', 'My Menu Title', 'manage_options', 'my-unique-identifier', 'my_plugin_options' );
}

function my_plugin_options() {
    if ( !current_user_can( 'manage_options' ) )  {
        wp_die( __( 'You do not have sufficient permissions to access this page.' ) );
    }
    echo '<div class="wrap">';
    echo '<p>Put all your options in here</p>';
    echo '</div>';
}
</code>```

Body:
Can you please help me with my proble regarding creating a New Page for Editing Details.

Currently, I have a list of Properties. This is a Custom Table not a post type. I already listed the properties but my problem is how am I gonna make the Edit Details Page?

add_action( 'admin_menu', 'pp_create_property_management_menu' ); function pp_create_property_management_menu() {
add_menu_page( 'PP M', 'PP M', 'manage_options', 'property-management', 'pp_property_management_page', 'dashicons-tickets', 5 ); }

Many thanks,

Body:
The fifth parameter in the add_menu_page() function calls a function to output the contents of the menu page.  Here's an example I have taken from the WordPress site on how to add a custom admin menu and show the details of the page.

add_action( 'admin_menu', 'my_plugin_menu' );

function my_plugin_menu() {
    add_menu_page( 'My Page Title', 'My Menu Title', 'manage_options', 'my-unique-identifier', 'my_plugin_options' );
}

function my_plugin_options() {
    if ( !current_user_can( 'manage_options' ) )  {
        wp_die( __( 'You do not have sufficient permissions to access this page.' ) );
    }
    echo '<div class="wrap">';
    echo '<p>Put all your options in here</p>';
    echo '</div>';
}


答:
You simply call

```<code>diff(primes)
</code>```

For a simple dataset:

```<code>> primes <- c(2,3,5,7)
> diff(primes)
[1] 1 2 2
</code>```

Title: Successive prime numbers in R

Body:
I'm using RStudio and am pretty new to R. I have a dataset that shows the prime numbers from 1- 301. How do you use the diff function to compute the differences between successive primes?

Here is my dataset:

 [1]    2    3    5    7   11   13   17   19   23   29   31   37   41   43   47   53   59   61   67   71   73   79   83   89   97  101  103  107  109  113
 [31]  127  131  137  139  149  151  157  163  167  173  179  181  191  193  197  199  211  223  227  229  233  239  241  251  257  263  269  271  277  281
 [61]  283  293  307  311  313  317  331  337  347  349  353  359  367  373  379  383  389  397  401  409  419  421  431  433  439  443  449  457  461  463
 [91]  467  479  487  491  499  503  509  521  523  541  547  557  563  569  571  577  587  593  599  601  607  613  617  619  631  641  643  647  653  659
[121]  661  673  677  683  691  701  709  719  727  733  739  743  751  757  761  769  773  787  797  809  811  821  823  827  829  839  853  857  859  863
[151]  877  881  883  887  907  911  919  929  937  941  947  953  967  971  977  983  991  997 1009 1013 1019 1021 1031 1033 1039 1049 1051 1061 1063 1069
[181] 1087 1091 1093 1097 1103 1109 1117 1123 1129 1151 1153 1163 1171 1181 1187 1193 1201 1213 1217 1223 1229 1231 1237 1249 1259 1277 1279 1283 1289 1291
[211] 1297 1301 1303 1307 1319 1321 1327 1361 1367 1373 1381 1399 1409 1423 1427 1429 1433 1439 1447 1451 1453 1459 1471 1481 1483 1487 1489 1493 1499 1511
[241] 1523 1531 1543 1549 1553 1559 1567 1571 1579 1583 1597 1601 1607 1609 1613 1619 1621 1627 1637 1657 1663 1667 1669 1693 1697 1699 1709 1721 1723 1733
[271] 1741 1747 1753 1759 1777 1783 1787 1789 1801 1811 1823 1831 1847 1861 1867 1871 1873 1877 1879 1889 1901 1907 1913 1931 1933 1949 1951 1973 1979 1987
[301] 1993 1997 1999 2003

Would appreciate some help, thanks!

Body:
You simply call

diff(primes)

For a simple dataset:

> primes <- c(2,3,5,7)
> diff(primes)
[1] 1 2 2


问:
Convert CSV format as text in email body
I have a cron job which when run gives me a csv file which looks like below:

I have another cron job where I am trying to display the csv data directly in an email body and the output of that is as below:

As you can see above, the output from email is distorted and looks ugly. WHat changes should I make for the email format to be similar with the csv format?.

I am using the below bash commands in my cron :

```<code>EMAILBODY="$(${RUNDIR}/${DEV1} ${FILELOCATION} ${FILENAME})"

echo "$EMAILBODY" | mailx -r ${SENDER} -s "Alerts Email for $(date +%Y-%m-%d_%H:%M)" abcd@xyz.com
</code>```

I tried the below change to the script:

```<code>echo "$EMAILBODY" | column -s, -t | mailx -r ${SENDER} -s "Alerts Email for $(date +%Y-%m-%d_%H:%M)" abcd@xyz.com
</code>```

and now I see this in the email:

As you can notice, the format is little better than before. But how can I align the data perfectly with the headers?

答:
Perl would be a suitable tool to align text fields.
Try the following code:

```<code>#!/bin/bash

echo "$EMAILBODY" | perl -e '
format STDOUT =
@>>>>>>> @<<<<<<<<<<<<<<<<<< @>>>>>>> @<<<<<<<<<<<<<< @<<<<<<<< @<<<<<<<<<<<<<<<<<< @<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
$id, $type, $site, $city, $prov, $start, $elasp
.

while (<>) {
    split(/,/, $_);
    grep {s/^"//, s/"$//} @_;
    ($id, $type, $site, $city, $prov, $start, $elasp) = @_;
    write;
}'
</code>```

The result will look like:

```<code>Alert ID Type                IOL Site City            Province  Alert Start Time    Elasped Time since first alert
       4 Trasaction Alert       99196 NANAIMO         BC        2015-06-30 15:11:00     867 23:00
       6 Communication Alert    88395 GRANDE PRAIRIE  AB        2015-07-01 15:23:39     866 22:48
       7 Communication Alert    88433 HINTON          AB        2015-07-01 15:23:39     866 22:48
       8 Communication Alert    88484 LAC LA BICHE    AB        2015-07-01 15:23:39     866 22:48
      11 Transation Alert       88395 GRANDE PRAIRIE  AB        2015-07-02 16:40:59     865 22:53
</code>```

Note that the script above assumes each field does not contail commas. In such a case, Text::CSV module will work.

Hope this helps.

Body:
I have a cron job which when run gives me a csv file which looks like below:

I have another cron job where I am trying to display the csv data directly in an email body and the output of that is as below:

As you can see above, the output from email is distorted and looks ugly. WHat changes should I make for the email format to be similar with the csv format?.

I am using the below bash commands in my cron :

EMAILBODY="$(${RUNDIR}/${DEV1} ${FILELOCATION} ${FILENAME})"

echo "$EMAILBODY" | mailx -r ${SENDER} -s "Alerts Email for $(date +%Y-%m-%d_%H:%M)" abcd@xyz.com

I tried the below change to the script:

echo "$EMAILBODY" | column -s, -t | mailx -r ${SENDER} -s "Alerts Email for $(date +%Y-%m-%d_%H:%M)" abcd@xyz.com

and now I see this in the email:

As you can notice, the format is little better than before. But how can I align the data perfectly with the headers?

Body:
Perl would be a suitable tool to align text fields.
Try the following code:

#!/bin/bash

echo "$EMAILBODY" | perl -e '
format STDOUT =
@>>>>>>> @<<<<<<<<<<<<<<<<<< @>>>>>>> @<<<<<<<<<<<<<< @<<<<<<<< @<<<<<<<<<<<<<<<<<< @<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
$id, $type, $site, $city, $prov, $start, $elasp
.

while (<>) {
    split(/,/, $_);
    grep {s/^"//, s/"$//} @_;
    ($id, $type, $site, $city, $prov, $start, $elasp) = @_;
    write;
}'

The result will look like:

Alert ID Type                IOL Site City            Province  Alert Start Time    Elasped Time since first alert
       4 Trasaction Alert       99196 NANAIMO         BC        2015-06-30 15:11:00     867 23:00
       6 Communication Alert    88395 GRANDE PRAIRIE  AB        2015-07-01 15:23:39     866 22:48
       7 Communication Alert    88433 HINTON          AB        2015-07-01 15:23:39     866 22:48
       8 Communication Alert    88484 LAC LA BICHE    AB        2015-07-01 15:23:39     866 22:48
      11 Transation Alert       88395 GRANDE PRAIRIE  AB        2015-07-02 16:40:59     865 22:53

Note that the script above assumes each field does not contail commas. In such a case, Text::CSV module will work.

Hope this helps.


问:
Accessing the front facing camera. iPhone/iPod 4
Hey I was wondering how I can access the front facing camera. Maybe there's some guide for it?
But I don't want all buttons etc. I just want to access the from facing camera, I don't ant the button to take a photo or anything like that.</p>

答: Just set the cameraDevice property of UIImagePickerController to  UIImagePickerControllerCameraDeviceFront. But you should check if the device is available.

ContentLicense: CC BY-SA 2.5


问:
How to skip / avoid some specific elements to be cached by Guava Cache
Is there a way to not cache some specific elements using Guava Cache? I still want the element to be returned, but not cached.

For example:

```<code>LoadingCache guavaCache;

public Element load(String key) {
  Element element = requestElement(key);

  if(element.isActive == false){
    guavaCache.dontCache(element);
  }

  return element;
}
</code>```

答:
I implemented a solution for this problem: invalidate the element after return it. This will removed the element from the cache right after inserted it.

Cache config:

```<code>public Element load(String key) {
  return requestElement(key);
}
</code>```

then:

```<code>element = guavaCache.get(key);
if(element.isActive == false){
  guavaCache.invalidate(key)
}
</code>```

This seems not very clean but it's being done internally by Guava.

Body:
Is there a way to not cache some specific elements using Guava Cache? I still want the element to be returned, but not cached.

For example:

LoadingCache guavaCache;

public Element load(String key) {
  Element element = requestElement(key);

  if(element.isActive == false){
    guavaCache.dontCache(element);
  }

  return element;
}

Body:
I implemented a solution for this problem: invalidate the element after return it. This will removed the element from the cache right after inserted it.

Cache config:

public Element load(String key) {
  return requestElement(key);
}

then:

element = guavaCache.get(key);
if(element.isActive == false){
  guavaCache.invalidate(key)
}

This seems not very clean but it's being done internally by Guava.


答:
Alternatively, you could use regex. It will greatly reduce code.

```<code>import re
def link(line):
    return re.sub(r'\[(.*?)\]\((.*?)\)', r'<a href="\2">\1</a>', line)

link("The biggest headliners usually perform at the Orpheum Theatre, the [Overture Center](https://en.wikipedia.org/wiki/Overture_Center), [Breese Stevens Field](https://en.wikipedia.org/wiki/Breese_Stevens_Field), the [Alliant Energy Center](https://en.wikipedia.org/wiki/Alliant_Energy_Center), or the UW Theatre on campus.")
</code>```

Output:

```<code>The biggest headliners usually perform at the Orpheum Theatre, the <a href="https://en.wikipedia.org/wiki/Overture_Center">Overture Center</a>, <a href="https://en.wikipedia.org/wiki/Breese_Stevens_Field">Breese Stevens Field</a>, the <a href="https://en.wikipedia.org/wiki/Alliant_Energy_Center">Alliant Energy Center</a>, or the UW Theatre on campus.
</code>```

Go ahead and try it out on Regex101:

https://regex101.com/r/S3oFLH/1

Title: Nested While and For loops not stopping in python

Body:
Alternatively, you could use regex. It will greatly reduce code.

import re
def link(line):
    return re.sub(r'\[(.*?)\]\((.*?)\)', r'<a href="\2">\1</a>', line)

link("The biggest headliners usually perform at the Orpheum Theatre, the [Overture Center](https://en.wikipedia.org/wiki/Overture_Center), [Breese Stevens Field](https://en.wikipedia.org/wiki/Breese_Stevens_Field), the [Alliant Energy Center](https://en.wikipedia.org/wiki/Alliant_Energy_Center), or the UW Theatre on campus.")

Output:

The biggest headliners usually perform at the Orpheum Theatre, the <a href="https://en.wikipedia.org/wiki/Overture_Center">Overture Center</a>, <a href="https://en.wikipedia.org/wiki/Breese_Stevens_Field">Breese Stevens Field</a>, the <a href="https://en.wikipedia.org/wiki/Alliant_Energy_Center">Alliant Energy Center</a>, or the UW Theatre on campus.

Go ahead and try it out on Regex101:

https://regex101.com/r/S3oFLH/1


问:
Passing session between pages
here is my requirement. I wanted to pass a variable from one html to another html both has php in it. I know the logic is pretty bad. On clicking the button meant for $row['Room_ID'], it needs to go to plugload6.php . In that php, I wanted to get the Room_ID and handle that in a query.
As far as I know, I should do this with onclick listener which calls JS file. In JS file, I should create a session and call the php file. Could you please help me in achieving the same.Please find the code below
Main.html:

```<code>if(mysqli_num_rows($result)>0)
{
    while($row=mysqli_fetch_assoc($result))
    {
        //$variable=$row['Room_ID'];
        $_SESSION['myVar']=$row['Room_ID'];
        //echo $row['Room_ID'];
        $newval=$_SESSION['myVar'];
        echo $newval;
        echo "<tr style='border-bottom: ridge;'>";

        echo "<td align='center'>";
        echo "<a class=".$row['Room_ID']." onclick='plugButton(Room_ID)' href='plugload6.php' class='action-button shadow animate blue' style='color: rgb(255,255,255)'>".$row['Room_ID']."</a>";
        echo "<td>";
        echo "<a href='plugload6.php' class='action-button shadow animate  blue' style='color: rgb(255,255,255)'>".$row['Room_ID']."</a>";
        echo "</td>";
</code>```

plugload6.php:

```<code><?php
//connecting to SQL database plug to retrieve the list of plugs
$room=$_SESSION['myVar'];
echo $room;

$conn=mysqli_connect("localhost","root","") or die("failed");
$db=mysqli_select_db($conn,"splug");
$result=mysqli_query($conn,"select Plug_ID from plug where       Room_ID='".$room."'") or die("failed to connect database".mysql_error());
//$row=mysqli_fetch_array($result);
//count=1;
</code>```

I wanted to handle in the form of session which can make my life easier. Please guide me in completing the same.

答:
Make sure that you started the session with session_start();.

Or instead of using PHP session pass the Room_ID at the end of URL as a GET parameter

```<code>echo "<a href='plugload6.php?roomId=".$row['Room_ID']."' class='action-button shadow animate  blue' style='color: rgb(255,255,255)'>".$row['Room_ID']."</a>";
</code>```

And than in plugload6.php use

```<code>$room = $_GET['roomId'];
</code>```

to get the room id.

Title: Passing session between pages

Body:
here is my requirement. I wanted to pass a variable from one html to another html both has php in it. I know the logic is pretty bad. On clicking the button meant for $row['Room_ID'], it needs to go to plugload6.php . In that php, I wanted to get the Room_ID and handle that in a query.
As far as I know, I should do this with onclick listener which calls JS file. In JS file, I should create a session and call the php file. Could you please help me in achieving the same.Please find the code below
Main.html:

if(mysqli_num_rows($result)>0)
{
    while($row=mysqli_fetch_assoc($result))
    {
        //$variable=$row['Room_ID'];
        $_SESSION['myVar']=$row['Room_ID'];
        //echo $row['Room_ID'];
        $newval=$_SESSION['myVar'];
        echo $newval;
        echo "
";

        echo "";
        echo "".$row['Room_ID']."";
        echo "";
        echo "".$row['Room_ID']."";
        echo "	";

plugload6.php:

<?php
//connecting to SQL database plug to retrieve the list of plugs
$room=$_SESSION['myVar'];
echo $room;

$conn=mysqli_connect("localhost","root","") or die("failed");
$db=mysqli_select_db($conn,"splug");
$result=mysqli_query($conn,"select Plug_ID from plug where       Room_ID='".$room."'") or die("failed to connect database".mysql_error());
//$row=mysqli_fetch_array($result);
//count=1;

I wanted to handle in the form of session which can make my life easier. Please guide me in completing the same.

Body:
Make sure that you started the session with session_start();.

Or instead of using PHP session pass the Room_ID at the end of URL as a GET parameter

echo "<a href='plugload6.php?roomId=".$row['Room_ID']."' class='action-button shadow animate  blue' style='color: rgb(255,255,255)'>".$row['Room_ID']."</a>";

And than in plugload6.php use

$room = $_GET['roomId'];

to get the room id.


问:
MS SQL Server 2017 How to Write a Trigger that moves the updated value and the old value to a new table
When the pay is updated in the Employees table, I want the EmpID, oldrate and newrate to be moved to the changeLog table.

When I run the code below it moves all employee ID and gives me Null for oldRate and some newrate

```<code>ALTER TRIGGER trg_PayChange
ON Employees
AFTER Update
AS
    IF NOT UPDATE(pay)
       DECLARE @oldRate VARCHAR(100)

    DECLARE @newRate VARCHAR(100)

    BEGIN
        INSERT INTO ChangeLog (EmpID)
            SELECT EmployeeID
            FROM Employees

        INSERT INTO ChangeLog (OldRate)
            SELECT OldRate = (SELECT Pay FROM Deleted)

        INSERT INTO ChangeLog (NewRate)
            SELECT NewRate = (SELECT Pay FROM Inserted)
END
GO
</code>```

答:
Assuming EmployeeId is the PRIMARY KEY or a unique key on the Employees table, and the value of the EmployeeId wasn't updated:

```<code>IF NOT UPDATE(EmployeeId)

   INSERT INTO ChangeLog (EmpId, OldRate, NewRate)
   SELECT d.EmployeeId
        , d.Pay
        , i.Pay
     FROM deleted d
     JOIN inserted i
       ON i.EmployeeId = d.EmployeeId
   ;
</code>```

Note that if the value of EmployeeId is changed, this insert wouldn't necessarily insert a row to the ChangeLog table. Consider a query of the form:

```<code>UPDATE Employees SET Pay = 7, EmployeeId = 757 WHERE EmployeeId = 42
</code>```

If that is successful, we expect the deleted table will contain

```<code>EmployeeId  Pay  somecol ...
----------  ---  ------- ---
        42    4  someval
</code>```

and inserted table will contain

```<code>EmployeeId  Pay  somecol ...
----------  ---  ------- ---
       757    7  someval ...
</code>```

A couple of queries using an anti-join pattern would pick up those changes which would be missed by our first query...

```<code>  -- deleted with no matching inserted
  INSERT INTO ChangeLog (EmpId, OldRate, NewRate)
  SELECT d.EmployeeId
       , d.Pay
       , NULL
    FROM deleted d
    LEFT
    JOIN inserted i
      ON i.EmployeeId = d.EmployeeId
   WHERE i.EmployeeId IS NULL
  ;

  -- inserted with no matching deleted
  INSERT INTO ChangeLog (EmpId, OldRate, NewRate)
  SELECT i.EmployeeId
       , NULL
       , i.Pay
    FROM inserted i
    LEFT
    JOIN deleted d
      ON d.EmployeeId = i.EmployeeId
   WHERE d.EmployeeId IS NULL
  ;
</code>```

But... that falls down if we "swap" EmployeeId values. Consider rows with EmployeeId values of 757 and 42 exist in the table, and we issue a statement like this:

```<code> UPDATE Employees
    SET EmployeeId = CASE WHEN EmployeeId = 42  THEN 757
                          WHEN EmployeeId = 757 THEN 42
                     END
      , Pay        = CASE WHEN EmployeeId = 42  THEN 4
                          WHEN EmployeeId = 757 THEN 7
                     END
 WHERE EmployeeId IN (42,757)
</code>```

With that, the rows in the inserted and deleted tables will be "cross wired"... EmployeeId values will match, but will match a different row. So we probably want to test whether an UPDATE statement attempted to assign a new value to EmployeeId column, so we can take the appropriate action.

We might be better off just recording the changes...

```<code>INSERT INTO ChangeLog (action, empid, pay )
SELECT 'update old', EmployeeId, Pay
  FROM deleted
;
INSERT INTO ChangeLog (action, empid, pay )
SELECT 'update new', EmployeeId, Pay
  FROM inserted
;
</code>```

Body:
When the pay is updated in the Employees table, I want the EmpID, oldrate and newrate to be moved to the changeLog table.

When I run the code below it moves all employee ID and gives me Null for oldRate and some newrate

ALTER TRIGGER trg_PayChange
ON Employees
AFTER Update
AS
    IF NOT UPDATE(pay)
       DECLARE @oldRate VARCHAR(100)

    DECLARE @newRate VARCHAR(100)

    BEGIN
        INSERT INTO ChangeLog (EmpID)
            SELECT EmployeeID
            FROM Employees

        INSERT INTO ChangeLog (OldRate)
            SELECT OldRate = (SELECT Pay FROM Deleted)

        INSERT INTO ChangeLog (NewRate)
            SELECT NewRate = (SELECT Pay FROM Inserted)
END
GO

Body:
Assuming EmployeeId is the PRIMARY KEY or a unique key on the Employees table, and the value of the EmployeeId wasn't updated:

IF NOT UPDATE(EmployeeId)

   INSERT INTO ChangeLog (EmpId, OldRate, NewRate)
   SELECT d.EmployeeId
        , d.Pay
        , i.Pay
     FROM deleted d
     JOIN inserted i
       ON i.EmployeeId = d.EmployeeId
   ;

Note that if the value of EmployeeId is changed, this insert wouldn't necessarily insert a row to the ChangeLog table. Consider a query of the form:

UPDATE Employees SET Pay = 7, EmployeeId = 757 WHERE EmployeeId = 42

If that is successful, we expect the deleted table will contain

EmployeeId  Pay  somecol ...
----------  ---  ------- ---
        42    4  someval

and inserted table will contain

EmployeeId  Pay  somecol ...
----------  ---  ------- ---
       757    7  someval ...

A couple of queries using an anti-join pattern would pick up those changes which would be missed by our first query...

  -- deleted with no matching inserted
  INSERT INTO ChangeLog (EmpId, OldRate, NewRate)
  SELECT d.EmployeeId
       , d.Pay
       , NULL
    FROM deleted d
    LEFT
    JOIN inserted i
      ON i.EmployeeId = d.EmployeeId
   WHERE i.EmployeeId IS NULL
  ;

  -- inserted with no matching deleted
  INSERT INTO ChangeLog (EmpId, OldRate, NewRate)
  SELECT i.EmployeeId
       , NULL
       , i.Pay
    FROM inserted i
    LEFT
    JOIN deleted d
      ON d.EmployeeId = i.EmployeeId
   WHERE d.EmployeeId IS NULL
  ;

But... that falls down if we "swap" EmployeeId values. Consider rows with EmployeeId values of 757 and 42 exist in the table, and we issue a statement like this:

 UPDATE Employees
    SET EmployeeId = CASE WHEN EmployeeId = 42  THEN 757
                          WHEN EmployeeId = 757 THEN 42
                     END
      , Pay        = CASE WHEN EmployeeId = 42  THEN 4
                          WHEN EmployeeId = 757 THEN 7
                     END
 WHERE EmployeeId IN (42,757)

With that, the rows in the inserted and deleted tables will be "cross wired"... EmployeeId values will match, but will match a different row. So we probably want to test whether an UPDATE statement attempted to assign a new value to EmployeeId column, so we can take the appropriate action.

We might be better off just recording the changes...

INSERT INTO ChangeLog (action, empid, pay )
SELECT 'update old', EmployeeId, Pay
  FROM deleted
;
INSERT INTO ChangeLog (action, empid, pay )
SELECT 'update new', EmployeeId, Pay
  FROM inserted
;


问:
__FILE__ is deprecated and will be removed in swift 3
I have this line of code

```<code>NSLog("\(__FILE__)  \(__LINE__)  \(__COLUMN__)  \(__FUNCTION__)")
</code>```

I updated to xcode 7.3 and I now get a warning that states that this method has been deprecated and will be removed in swift 3.

I tried changing the code to

```<code>NSLog("\(#file)  \(#line)  \(#column)  \(#function)")
</code>```

but I still get the same warning. What is causing this?

答:
It works fine with print and maybe wrap it into a public funciton:

public func superLog(_ fileName: String, definition: String, lineNumber: Int, variable: String, value: Any) {
let fn = fileName.replacingOccurrences(of:"/Users/userName/Documents/IOS/project/", with: "")
print("\n \(fn)  \(lineNumber)\n \(definition)\n\n(variable)\n➳",value,"\n")
}
superLog(#file, definition: "log", lineNumber: #line, variable: "var", value: value)

Body:
I have this line of code

NSLog("\(__FILE__)  \(__LINE__)  \(__COLUMN__)  \(__FUNCTION__)")

I updated to xcode 7.3 and I now get a warning that states that this method has been deprecated and will be removed in swift 3.

I tried changing the code to

NSLog("\(#file)  \(#line)  \(#column)  \(#function)")

but I still get the same warning. What is causing this?


问:
swift UITapGestureRecognizer not working on view
I had to create a new thread bcoz it's driving me crazy and all the other answers online are exactly the same. I have done this countless of times but I cannot see what I am missing for the life of me. I am using a "test" view controller just to get the tap gesture working but it isn't working at all... I am fairly certain that I am setting this up correctly, as this is how I've always implemented it in the past: (yes, I have checked the box for isUserInteractionEnabled). I am even implementing this on a different viewcontroller this exact way and it is working...

```<code>class TestViewController: UIViewController {

  override func viewDidLoad() {
    super.viewDidLoad()
    view.addGestureRecognizer(tap)
  }

  let tap = UITapGestureRecognizer(target: self, action: #selector(wasTapped))

  @objc func wasTapped() {
    print("tapped")
  }
}
</code>```

I have also tried adding the parameters to wasTapped:

```<code>@objc func wasTapped(gestureRecognizer: UITapGestureRecognizer) {
  print("tapped")
}
</code>```

答:
You are saying:

```<code>override func viewDidLoad() {
    super.viewDidLoad()

    view.addGestureRecognizer(tap)
}

let tap = UITapGestureRecognizer(target: self, action: #selector(wasTapped))
</code>```

The problem is the last line:

```<code>let tap = UITapGestureRecognizer(target: self, action: #selector(wasTapped))
</code>```

You cannot just say let tap like that in the middle of nowhere. You are implicitly making an instance property. But you cannot initialize an instance property with a target of self, because self does not exist at the time an instance property is initialized. (I regard the fact that that code even compiles as a bug, and have reported it as such.)

Move that line to the start of viewDidLoad, like this:

```<code>override func viewDidLoad() {
    super.viewDidLoad()

    let tap = UITapGestureRecognizer(target: self, action: #selector(wasTapped))
    view.addGestureRecognizer(tap)
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I had to create a new thread bcoz it's driving me crazy and all the other answers online are exactly the same. I have done this countless of times but I cannot see what I am missing for the life of me. I am using a "test" view controller just to get the tap gesture working but it isn't working at all... I am fairly certain that I am setting this up correctly, as this is how I've always implemented it in the past: (yes, I have checked the box for isUserInteractionEnabled). I am even implementing this on a different viewcontroller this exact way and it is working...

class TestViewController: UIViewController {

  override func viewDidLoad() {
    super.viewDidLoad()
    view.addGestureRecognizer(tap)
  }

  let tap = UITapGestureRecognizer(target: self, action: #selector(wasTapped))

  @objc func wasTapped() {
    print("tapped")
  }
}

I have also tried adding the parameters to wasTapped:

@objc func wasTapped(gestureRecognizer: UITapGestureRecognizer) {
  print("tapped")
}

Body:
You are saying:

override func viewDidLoad() {
    super.viewDidLoad()

    view.addGestureRecognizer(tap)
}

let tap = UITapGestureRecognizer(target: self, action: #selector(wasTapped))

The problem is the last line:

let tap = UITapGestureRecognizer(target: self, action: #selector(wasTapped))

You cannot just say let tap like that in the middle of nowhere. You are implicitly making an instance property. But you cannot initialize an instance property with a target of self, because self does not exist at the time an instance property is initialized. (I regard the fact that that code even compiles as a bug, and have reported it as such.)

Move that line to the start of viewDidLoad, like this:

override func viewDidLoad() {
    super.viewDidLoad()

    let tap = UITapGestureRecognizer(target: self, action: #selector(wasTapped))
    view.addGestureRecognizer(tap)
}


问:
PHP Upload multiple files only upload 1 file
i edited this code alot of times (im noob whit php) and my problem is upload multiples files with this code. i can upload only 1 file.

Here is the code:

```<code><?php
/**
 * uploadFile()
 *
 * @param string $file_field name of file upload field in html form
 * @param bool $check_image check if uploaded file is a valid image
 * @param bool $random_name generate random filename for uploaded file
 * @return array
 */
function uploadFile ($file_field = null, $check_image = false, $random_name = false) {

  //Config Section
  //Set file upload path
  $path = 'c:/xampp/htdocs/'; //with trailing slash
  //Set max file size in bytes
  $max_size = 1000000;
  //Set default file extension whitelist
  $whitelist_ext = array('jpg','png','gif');
  //Set default file type whitelist
  $whitelist_type = array('image/jpeg', 'image/png','image/gif');

  //The Validation
  // Create an array to hold any output
  $out = array('error'=>null);

  if (!$file_field) {
    $out['error'][] = "Please specify a valid form field name";
  }

  if (!$path) {
    $out['error'][] = "Please specify a valid upload path";
  }

  if (count($out['error'])>0) {
    return $out;
  }

  //Make sure that there is a file
  if((!empty($_FILES[$file_field])) && ($_FILES[$file_field]['error'] == 0)) {

    // Get filename
    $file_info = pathinfo($_FILES[$file_field]['name']);
    $name = $file_info['filename'];
    $ext = $file_info['extension'];

    //Check file has the right extension
    if (!in_array($ext, $whitelist_ext)) {
      $out['error'][] = "Invalid file Extension";
    }

    //Check that the file is of the right type
    if (!in_array($_FILES[$file_field]["type"], $whitelist_type)) {
      $out['error'][] = "Invalid file Type";
    }

    //Check that the file is not too big
    if ($_FILES[$file_field]["size"] > $max_size) {
      $out['error'][] = "File is too big";
    }

    //If $check image is set as true
    if ($check_image) {
      if (!getimagesize($_FILES[$file_field]['tmp_name'])) {
        $out['error'][] = "Uploaded file is not a valid image";
      }
    }

    //Create full filename including path
    if ($random_name) {
      // Generate random filename
      $tmp = str_replace(array('.',' '), array('',''), microtime());

      if (!$tmp || $tmp == '') {
        $out['error'][] = "File must have a name";
      }
      $newname = $tmp.'.'.$ext;
    } else {
        $newname = $name.'.'.$ext;
    }

    //Check if file already exists on server
    if (file_exists($path.$newname)) {
      $out['error'][] = "A file with this name already exists";
    }

    if (count($out['error'])>0) {
      //The file has not correctly validated
      return $out;
    }

    if (move_uploaded_file($_FILES[$file_field]['tmp_name'], $path.$newname)) {
      //Success
      $out['filepath'] = $path;
      $out['filename'] = $newname;
      return $out;
    } else {
      $out['error'][] = "Server Error!";
    }

  } else {
    $out['error'][] = "No file uploaded";
    return $out;
  }
}
?>
<?php
if (isset($_POST['submit'])) {
  $file = uploadFile('file', true, true);
  if (is_array($file['error'])) {
    $message = '';
    foreach ($file['error'] as $msg) {
      $message .= '<p>'.$msg.'</p>';
    }
  } else {
    $message = "File uploaded successfully";
  }
  echo $message;
}
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" enctype="multipart/form-data">
<input name="file" type="file" size="20" multiple="multiple" />
<input name="submit" type="submit" value="Upload files" />
</form>
</code>```

please help me understand... i know i must use foreach

答:
To successfully send multiple files from you're browser, you need your inputs to pass an array to PHP. This is done by appending [] to the end of your <input>s name:

```<code><input type="file" name="filesToUpload[]" multiple>
</code>```

Processing these files is the tricky part. PHP handles file uploads differently than it would handle other POST or GET data provided in an array. File uploads have a metadata key inserted between the input's name, and the index of the file that was uploaded. So $_FILES['filesToUpload']['name'][0] will get the name of the first file, and $_FILES['filesToUpload']['name'][1] will get the name of the second file... and so on.

Because of this foreach is absolutely the wrong loop to use. You will end up processing each piece of metadata on it's own, without any context. That's dreafully unnatural.

Let's get the index of each file and process one file at a time instead. We'll use a for loop for this. This is an entirely self contained, functioning example of a user uploading multiple files to a folder on the server:

```<code><?php
/*
 * sandbox.php
 */

if (isset($_POST['submit'])) {

    // We need to know how many files the user actually uploaded.
    $numberOfFilesUploaded = count($_FILES['filesToUpload']['name']);

    for ($i = 0; $i < $numberOfFilesUploaded; $i++) {
        // Each iteration of this loop contains a single file.
        $fileName = $_FILES['filesToUpload']['name'][$i];
        $fileTmpName = $_FILES['filesToUpload']['tmp_name'][$i];
        $fileSize = $_FILES['filesToUpload']['size'][$i];
        $fileError = $_FILES['filesToUpload']['error'][$i];
        $fileType = $_FILES['filesToUpload']['type'][$i];

        // PHP has saved the uploaded file as a temporary file which PHP will
        // delete after the script has ended.
        // Let's move the file to an output directory so PHP will not delete it.
        move_uploaded_file($fileTmpName, './output/' . $fileName);
    }
}

?>

<form method="post" enctype="multipart/form-data">
                              <!-- adding [] Allows us to upload multiple files -->
    <input type="file" name="filesToUpload[]" multiple>
    <input type="submit" name="submit"/>Submit
</form>
</code>```

To run this example, your files should look like this

You can startup the PHP builtin webserver with:

```<code>$ php -S localhost:8000
</code>```

Then going to http://localhost:8000/sandbox.php will run the example.

Important note: The above example does not do any validation. You will need to validate that all the uploaded files are safe.

Body:
i edited this code alot of times (im noob whit php) and my problem is upload multiples files with this code. i can upload only 1 file.

Here is the code:

<?php
/**
 * uploadFile()
 *
 * @param string $file_field name of file upload field in html form
 * @param bool $check_image check if uploaded file is a valid image
 * @param bool $random_name generate random filename for uploaded file
 * @return array
 */
function uploadFile ($file_field = null, $check_image = false, $random_name = false) {

  //Config Section
  //Set file upload path
  $path = 'c:/xampp/htdocs/'; //with trailing slash
  //Set max file size in bytes
  $max_size = 1000000;
  //Set default file extension whitelist
  $whitelist_ext = array('jpg','png','gif');
  //Set default file type whitelist
  $whitelist_type = array('image/jpeg', 'image/png','image/gif');

  //The Validation
  // Create an array to hold any output
  $out = array('error'=>null);

  if (!$file_field) {
    $out['error'][] = "Please specify a valid form field name";
  }

  if (!$path) {
    $out['error'][] = "Please specify a valid upload path";
  }

  if (count($out['error'])>0) {
    return $out;
  }

  //Make sure that there is a file
  if((!empty($_FILES[$file_field])) && ($_FILES[$file_field]['error'] == 0)) {

    // Get filename
    $file_info = pathinfo($_FILES[$file_field]['name']);
    $name = $file_info['filename'];
    $ext = $file_info['extension'];

    //Check file has the right extension
    if (!in_array($ext, $whitelist_ext)) {
      $out['error'][] = "Invalid file Extension";
    }

    //Check that the file is of the right type
    if (!in_array($_FILES[$file_field]["type"], $whitelist_type)) {
      $out['error'][] = "Invalid file Type";
    }

    //Check that the file is not too big
    if ($_FILES[$file_field]["size"] > $max_size) {
      $out['error'][] = "File is too big";
    }

    //If $check image is set as true
    if ($check_image) {
      if (!getimagesize($_FILES[$file_field]['tmp_name'])) {
        $out['error'][] = "Uploaded file is not a valid image";
      }
    }

    //Create full filename including path
    if ($random_name) {
      // Generate random filename
      $tmp = str_replace(array('.',' '), array('',''), microtime());

      if (!$tmp || $tmp == '') {
        $out['error'][] = "File must have a name";
      }
      $newname = $tmp.'.'.$ext;
    } else {
        $newname = $name.'.'.$ext;
    }

    //Check if file already exists on server
    if (file_exists($path.$newname)) {
      $out['error'][] = "A file with this name already exists";
    }

    if (count($out['error'])>0) {
      //The file has not correctly validated
      return $out;
    }

    if (move_uploaded_file($_FILES[$file_field]['tmp_name'], $path.$newname)) {
      //Success
      $out['filepath'] = $path;
      $out['filename'] = $newname;
      return $out;
    } else {
      $out['error'][] = "Server Error!";
    }

  } else {
    $out['error'][] = "No file uploaded";
    return $out;
  }
}
?>
<?php
if (isset($_POST['submit'])) {
  $file = uploadFile('file', true, true);
  if (is_array($file['error'])) {
    $message = '';
    foreach ($file['error'] as $msg) {
      $message .= '
'.$msg.'
';
    }
  } else {
    $message = "File uploaded successfully";
  }
  echo $message;
}
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" enctype="multipart/form-data">
<input name="file" type="file" size="20" multiple="multiple" />
<input name="submit" type="submit" value="Upload files" />
</form>

please help me understand... i know i must use foreach

Body:
To successfully send multiple files from you're browser, you need your inputs to pass an array to PHP. This is done by appending [] to the end of your <input>s name:

<input type="file" name="filesToUpload[]" multiple>

Processing these files is the tricky part. PHP handles file uploads differently than it would handle other POST or GET data provided in an array. File uploads have a metadata key inserted between the input's name, and the index of the file that was uploaded. So $_FILES['filesToUpload']['name'][0] will get the name of the first file, and $_FILES['filesToUpload']['name'][1] will get the name of the second file... and so on.

Because of this foreach is absolutely the wrong loop to use. You will end up processing each piece of metadata on it's own, without any context. That's dreafully unnatural.

Let's get the index of each file and process one file at a time instead. We'll use a for loop for this. This is an entirely self contained, functioning example of a user uploading multiple files to a folder on the server:

<?php
/*
 * sandbox.php
 */

if (isset($_POST['submit'])) {

    // We need to know how many files the user actually uploaded.
    $numberOfFilesUploaded = count($_FILES['filesToUpload']['name']);

    for ($i = 0; $i < $numberOfFilesUploaded; $i++) {
        // Each iteration of this loop contains a single file.
        $fileName = $_FILES['filesToUpload']['name'][$i];
        $fileTmpName = $_FILES['filesToUpload']['tmp_name'][$i];
        $fileSize = $_FILES['filesToUpload']['size'][$i];
        $fileError = $_FILES['filesToUpload']['error'][$i];
        $fileType = $_FILES['filesToUpload']['type'][$i];

        // PHP has saved the uploaded file as a temporary file which PHP will
        // delete after the script has ended.
        // Let's move the file to an output directory so PHP will not delete it.
        move_uploaded_file($fileTmpName, './output/' . $fileName);
    }
}

?>

<form method="post" enctype="multipart/form-data">
                              <!-- adding [] Allows us to upload multiple files -->
    <input type="file" name="filesToUpload[]" multiple>
    <input type="submit" name="submit"/>Submit
</form>

To run this example, your files should look like this

You can startup the PHP builtin webserver with:

$ php -S localhost:8000

Then going to http://localhost:8000/sandbox.php will run the example.

Important note: The above example does not do any validation. You will need to validate that all the uploaded files are safe.


问:
catching all invalid URLs
I recently upgraded a site and almost all URLs have changed. I have redirected all of them (or so I hope) but it may be possible that some of them have slipped by me. Is there a way to somehow catch all invalid URLs and send the user to a certain page and somehow know what URL the person came from so I could log this, and fix those? I'm thinking I could use .htaccess somehow but am not sure how. I am using PHP Thanks so much!</p>

答:
Easiest would be to add a custom 404 redirect in htaccess.

Just add something like this:

```<code>ErrorDocument 404 /errors/404.php
</code>```

to a .htaccess (create one if needed) in your application root. And all request to none extistent pages will be redircted to your own custom 404 page.

Title: catching all invalid URLs

Body:
Easiest would be to add a custom 404 redirect in htaccess.

Just add something like this:

ErrorDocument 404 /errors/404.php

to a .htaccess (create one if needed) in your application root. And all request to none extistent pages will be redircted to your own custom 404 page.


问:
TNS-12542: TNS:address already in use TNS-12560:TNS:protocol adapter error
Facing error below when lsnrctl START  start listener.

Error listening on: (ADDRESS=(PROTOCOL=tcp)(HOST=)(PORT=1521))
  TNS-12542: TNS:address already in use  TNS-12560: TNS:protocol adapter
  error   TNS-00512: Address already in use    Linux Error: 98: Address
  already in use

listener.ora content as below. NSMS = (DESCRIPTION_LIST = (DESCRIPTION = (ADDRESS_LIST = (ADDRESS = (PROTOCOL = IPC)(KEY = NSMS)) (ADDRESS = (PROTOCOL = TCP)(HOST = 10.99.33.22)(Port = 1522)) ) ) ) SID_LIST_NSMS = (SID_LIST = (SID_DESC = (GLOBAL_DBNAME = NSMS) (ORACLE_HOME = /opt/oracle/product/11.2.0) (SID_NAME = NSMS) ) ) ADMIN_RESTRICTION_NSMS = ON

sqlnet.ora content NAMES.DIRECTORY_PATH= (TNSNAMES) AUTOMATIC_IPC = ON TRACE_LEVEL_CLIENT = OFF TRACE_FILE_CLIENT = /opt/oracle/product/11.2.0/network/trace/client.trc SQLNET.EXPIRE_TIME = 10 TCP.VALIDNODE_CHECKING = YES TCP.INVITED_NODES = (LA) #TCP.EXCLUDED_NODES = (1.22.33.44) # DIAG_SIGHANDLER_ENABLED=NO

tnsname.ora content NSMS = (DESCRIPTION = (ADDRESS_LIST = (ADDRESS = (PROTOCOL = TCP)(HOST = 10.99.33.22)(Port = 1522)) (ADDRESS = (PROTOCOL = IPC)(KEY = NSMS)) ) (CONNECT_DATA = (SERVER = DEDICATED) (SERVICE_NAME = NSMS) ) )

答: Try checking host name used in listner.ora if file set properly in OS level. Then try working with the default port 1521</p>


问:
SafetyNet attestation fails with internal error
I want to use the SafetyNet Attestation API (mind that this documentation seems to be outdated since the methods it uses are deprecated). Using the latest version of Play Services (11.0.1) I came up with the following code:

```<code>SecureRandom secureRandom = new SecureRandom();
byte[] nonce = new byte[16];
secureRandom.nextBytes(nonce); // just some random bytes for testing

SafetyNet.getClient(this)
    .attest(nonce, API_KEY)
    .addOnCompleteListener(this, task -> {
        if (task.isSuccessful()) {
            SafetyNetApi.AttestationResponse result = task.getResult();
            String jws = result.getJwsResult();
            Log.d(TAG, "JWS: " + jws);
        } else {
            Exception e = task.getException();

            if (e instanceof ApiException) {
                Log.e(TAG, "Attestation failure: " + ((ApiException) e).getStatusMessage() + ", code: " + ((ApiException) e).getStatusCode(), e);
            } else {
                Log.e(TAG, "Attestation failure: " + e, e);
            }
        }
    });
</code>```

where API_KEY is the API key from the Google Developer Console. This code is called in an Activity's onCreate(...). Whatever I tried, it results in failure and the e is an instance of ApiException, but it does not provide any useful information about what went wrong since the status message is null and the status code is 8, which - according to the documentation - is an "internal error". I tried to call this with a 5 second delay but no success. The test device has API 24 and Google Play services 11.0.55.

Anyone has any idea what goes wrong and what's the solution for this?

Edit: the old SafetyNet.SafetyNetApi.attest(googleApiClient, nonce) way seems to work fine but it's deprecated so I don't want to use it.

答:
Ensure that you are using correct WEB API KEY in your following code:

```<code>SafetyNet.getClient(this)
    .attest(nonce, WEB_API_KEY)......
</code>```

See following image to find  WEB API KEY:
FCM Console

Body:
I want to use the SafetyNet Attestation API (mind that this documentation seems to be outdated since the methods it uses are deprecated). Using the latest version of Play Services (11.0.1) I came up with the following code:

SecureRandom secureRandom = new SecureRandom();
byte[] nonce = new byte[16];
secureRandom.nextBytes(nonce); // just some random bytes for testing

SafetyNet.getClient(this)
    .attest(nonce, API_KEY)
    .addOnCompleteListener(this, task -> {
        if (task.isSuccessful()) {
            SafetyNetApi.AttestationResponse result = task.getResult();
            String jws = result.getJwsResult();
            Log.d(TAG, "JWS: " + jws);
        } else {
            Exception e = task.getException();

            if (e instanceof ApiException) {
                Log.e(TAG, "Attestation failure: " + ((ApiException) e).getStatusMessage() + ", code: " + ((ApiException) e).getStatusCode(), e);
            } else {
                Log.e(TAG, "Attestation failure: " + e, e);
            }
        }
    });

where API_KEY is the API key from the Google Developer Console. This code is called in an Activity's onCreate(...). Whatever I tried, it results in failure and the e is an instance of ApiException, but it does not provide any useful information about what went wrong since the status message is null and the status code is 8, which - according to the documentation - is an "internal error". I tried to call this with a 5 second delay but no success. The test device has API 24 and Google Play services 11.0.55.

Anyone has any idea what goes wrong and what's the solution for this?

Edit: the old SafetyNet.SafetyNetApi.attest(googleApiClient, nonce) way seems to work fine but it's deprecated so I don't want to use it.

Body:
Ensure that you are using correct WEB API KEY in your following code:

SafetyNet.getClient(this)
    .attest(nonce, WEB_API_KEY)......

See following image to find  WEB API KEY:
FCM Console


问:
How to convert a date format YYYY-MM-DD into integer YYYYMMDD in Presto/Hive?
How to CONVERT a date in format YYYY-MM-DD into integer YYYYMMDD in Presto/Hive?

I am trying to convert the below list into YYYYMMDD integers

```<code>WITH  all_dates  as (SELECT
    CAST(date_column AS DATE) date_column
FROM
    (VALUES
        (SEQUENCE(FROM_ISO8601_DATE('2017-07-01'),
                  FROM_ISO8601_DATE('2017-11-15'),
                  INTERVAL '1' DAY)
        )
    ) AS t1(date_array)
CROSS JOIN
    UNNEST(date_array) AS t2(date_column)
    )
</code>```

I tried something like this but it doesn't work

```<code>   SELECT
   CAST(
      CAST(year(date_column) AS VARCHAR(4)) +
      right('0' + CAST(month(date_column) AS VARCHAR(2)), 2) +
      right('0' + CAST(day(date_column) AS VARCHAR(2)), 2)
   AS DATETIME)
   FROM all_dates
</code>```

答:
If you just need to transform your date YYYY-MM-DD into an integer YYYYMMDD why don't you try to first remove all the occurrences of "-" from the string representation of your date before casting the result to int by using something like this?

```<code>cast(regexp_replace(str_column,'-','') as int)
</code>```

Body:
How to CONVERT a date in format YYYY-MM-DD into integer YYYYMMDD in Presto/Hive?

I am trying to convert the below list into YYYYMMDD integers

WITH  all_dates  as (SELECT
    CAST(date_column AS DATE) date_column
FROM
    (VALUES
        (SEQUENCE(FROM_ISO8601_DATE('2017-07-01'),
                  FROM_ISO8601_DATE('2017-11-15'),
                  INTERVAL '1' DAY)
        )
    ) AS t1(date_array)
CROSS JOIN
    UNNEST(date_array) AS t2(date_column)
    )

I tried something like this but it doesn't work

   SELECT
   CAST(
      CAST(year(date_column) AS VARCHAR(4)) +
      right('0' + CAST(month(date_column) AS VARCHAR(2)), 2) +
      right('0' + CAST(day(date_column) AS VARCHAR(2)), 2)
   AS DATETIME)
   FROM all_dates

Body:
If you just need to transform your date YYYY-MM-DD into an integer YYYYMMDD why don't you try to first remove all the occurrences of "-" from the string representation of your date before casting the result to int by using something like this?

cast(regexp_replace(str_column,'-','') as int)


问:
Shall I use mySQL to store value or format with function
I have a two separate tables that contain parts of user name (don't ask why)...

```<code>t1
---------------
firstName
lastName

t2
---------------
middleName
stage_firstName
stage_middleName
stage_lastName
</code>```

So before I output the name I run it through a function that capitalizes First letter of Name and uses Stage name if provided.

It works OK, but I now have a case where I need to display multiple names. The question I have, is: shall I use mySQL to store properly formatted name when the user formats it initially, or keep the values in multiple tables and keep on using the function to format them. For some reason I think I can improve some performance by utilizing a single value from a table, even if I add additional table column rather than keeping the fields separately in two separate tables and then parsing each name through this huge function.

Am I wrong with these assumptions?

答:
And if, at some point, you need to extract the name and display/use it in a different format, you will need to then perform some kind of translation on the already formatted string.

You could write the formatting into the query though.

Body:
I have a two separate tables that contain parts of user name (don't ask why)...

t1
---------------
firstName
lastName

t2
---------------
middleName
stage_firstName
stage_middleName
stage_lastName

So before I output the name I run it through a function that capitalizes First letter of Name and uses Stage name if provided.

It works OK, but I now have a case where I need to display multiple names. The question I have, is: shall I use mySQL to store properly formatted name when the user formats it initially, or keep the values in multiple tables and keep on using the function to format them. For some reason I think I can improve some performance by utilizing a single value from a table, even if I add additional table column rather than keeping the fields separately in two separate tables and then parsing each name through this huge function.

Am I wrong with these assumptions?


问:
C++ Ntstrsafe.h / ntifs.h
I just came back to an old code of mine and I had the following errors.

Cannot Open Source File "Ntstrsafe.h" / Cannot Open Source File
  "ntifs.h"

Should be an easy fix, how ever I did try to google and all I find are answears from 2004 and they don't really help.

I'm on Windows 10, with visual studio 2015 update 3.

答: They are part of WindowsDriverKit you can dowload WDK here</p>

Title: C++ Ntstrsafe.h / ntifs.h


问:
RPC semantics of gRPC
I am trying the find out what RPC semantics the gRPC library provides? Is it at-most once? Does it guarantee that an RPC call made by a client is not executed more than once on a server? I couldn't find this explicitly mentioned anywhere in the docs.

From what I understand, gRPC channels have an exponential back-off based retry mechanism of re-initiating TCP connections after transient failures. So, if a server fails after executing an RPC call but before responding, and later comes back up, a client RPC may end up getting executed twice.

Can someone throw more light on this?

答:
gRPC provides at-most-once guarantee by default. Things like retries and similar can change that, but they are opt-in. Another example of this is marking your RPC idempotent or no-side-effects; you've explicitly told gRPC it is okay to replay the RPC.

gRPC may also replay when it is provided assurances elsewhere the RPC was not processed. We call this transparent retries, which we're implementing now, and is based on HTTP/2 semantics where a server tells us the RPC was not seen by the service application.

gRPC's exponential back-off for reconnecting (not retrying RPCs) doesn't change the behavior. Normal RPCs fail outright when the connection is known-bad, but wait-for-ready RPCs that have not been sent are simply delayed until the connection is ready. There is no "replay" of the RPC involved; it is only sent once.

Title: RPC semantics of gRPC


问:
If input is NULL, return -1
Code works fine except I need to add this constraint.
"If input is NULL, return -1".

Im just wondering how I can do this. Everytime I put NULL in for s, it crashes.

Side Note: If you need to know, this converts the excel titles to numbers like A = 1, Z = 26, AA = 27, AB = 28, etc.

```<code>#include <iostream>

using namespace std;

class CIS14
{
public:
int convertExcelTitleToNumber(string* s)
{

    string str = *s;

    int num = 0;
    for (unsigned int i = 0; i < str.length(); i++)
    {
        num = num * 26 + str[i] - 64;
    }
    return num;
}
};
int main()
{
CIS14 cis14;
string s = "AA";
cout << cis14.convertExcelTitleToNumber(&s) << endl;

return 0;
</code>```

}

答:
Everytime I put NULL in for s, it crashes.

That doesn't surprise me at all, dereferencing a null pointer (with string str = *s in your case) is undefined behaviour.

To prevent this when passing a null string pointer:

```<code>cout << cis14.convertExcelTitleToNumber(nullptr) << endl;
</code>```

you need something like this as the first thing in your function, before trying to dereference s:

```<code>if (s == nullptr)
    return -1
</code>```

Feel free to use NULL instead of nullptr if you're stuck in the dark ages :-)

Title: If input is NULL, return -1

Body:
Code works fine except I need to add this constraint.
"If input is NULL, return -1".

Im just wondering how I can do this. Everytime I put NULL in for s, it crashes.

Side Note: If you need to know, this converts the excel titles to numbers like A = 1, Z = 26, AA = 27, AB = 28, etc.

#include <iostream>

using namespace std;

class CIS14
{
public:
int convertExcelTitleToNumber(string* s)
{

    string str = *s;

    int num = 0;
    for (unsigned int i = 0; i < str.length(); i++)
    {
        num = num * 26 + str[i] - 64;
    }
    return num;
}
};
int main()
{
CIS14 cis14;
string s = "AA";
cout << cis14.convertExcelTitleToNumber(&s) << endl;

return 0;

}

Body:
Everytime I put NULL in for s, it crashes.

That doesn't surprise me at all, dereferencing a null pointer (with string str = *s in your case) is undefined behaviour.

To prevent this when passing a null string pointer:

cout << cis14.convertExcelTitleToNumber(nullptr) << endl;

you need something like this as the first thing in your function, before trying to dereference s:

if (s == nullptr)
    return -1

Feel free to use NULL instead of nullptr if you're stuck in the dark ages :-)


问:
Slow LINQ Query
I have a query that's running slow (in a loop of about 100 it takes 5-10 seconds) and have no clue why.  It's simply querying against a List of objects... your help is much appreciated!

I'm basically querying for Schedules that have been assigned to specific managers.  It must be from the specified Shifts week OR the first 2 days of next week OR the last 2 days of the previous week.

I tried calculating .AddDays before but that didn't help.  When I ran a performance test it highlighted the "from" statement below.

```<code>List<Schedule> _schedule = Schedule.GetAll();
List<Shift> _shifts = Shift.GetAll();

// Then later...
List<Schedule> filteredSchedule = (from sch in _schedule
                                    from s in _shifts
                                    where
                                        **sch.ShiftID == s.ShiftID
                                        & (sch.ManagerID == 1 | sch.ManagerID == 2 | sch.ManagerID == 3)
                                        & ((s.ScheduleWeek == shift.ScheduleWeek)
                                                | (s.ScheduleWeek == shift.ScheduleWeek.AddDays(7)
                                                        & (s.DayOfWeek == 1 | s.Code == 2))
                                                | (sch.ScheduleWeek == shift.ScheduleWeek.AddDays(-7)
                                                        & (s.DayOfWeek == 5 | s.Code == 6)))**
                                    select sch)
                                    .OrderBy(sch => sch.ScheduleWeek)
                                    .ThenBy(sch => sch.DayOfWeek)
                                    .ToList();
</code>```

答:
First port of call: use && instead of & and || instead of |. Otherwise all the subexpressions in the where clause will be evaluated, even if the answer is already known.

Second port of call: use a join instead of two "from" clauses with a where:

```<code>var filteredSchedule = (from sch in _schedule
                        join s in _shifts on s.ShiftID equals sch.ShiftID
                        where ... rest of the condition ...
</code>```

Basically that's going to create a hash of all the shift IDs, so it can quickly look up possible matches for each schedule.

Title: Slow LINQ Query

Body:
I have a query that's running slow (in a loop of about 100 it takes 5-10 seconds) and have no clue why.  It's simply querying against a List of objects... your help is much appreciated!

I'm basically querying for Schedules that have been assigned to specific managers.  It must be from the specified Shifts week OR the first 2 days of next week OR the last 2 days of the previous week.

I tried calculating .AddDays before but that didn't help.  When I ran a performance test it highlighted the "from" statement below.

List<Schedule> _schedule = Schedule.GetAll();
List<Shift> _shifts = Shift.GetAll();

// Then later...
List<Schedule> filteredSchedule = (from sch in _schedule
                                    from s in _shifts
                                    where
                                        **sch.ShiftID == s.ShiftID
                                        & (sch.ManagerID == 1 | sch.ManagerID == 2 | sch.ManagerID == 3)
                                        & ((s.ScheduleWeek == shift.ScheduleWeek)
                                                | (s.ScheduleWeek == shift.ScheduleWeek.AddDays(7)
                                                        & (s.DayOfWeek == 1 | s.Code == 2))
                                                | (sch.ScheduleWeek == shift.ScheduleWeek.AddDays(-7)
                                                        & (s.DayOfWeek == 5 | s.Code == 6)))**
                                    select sch)
                                    .OrderBy(sch => sch.ScheduleWeek)
                                    .ThenBy(sch => sch.DayOfWeek)
                                    .ToList();

Body:
First port of call: use && instead of & and || instead of |. Otherwise all the subexpressions in the where clause will be evaluated, even if the answer is already known.

Second port of call: use a join instead of two "from" clauses with a where:

var filteredSchedule = (from sch in _schedule
                        join s in _shifts on s.ShiftID equals sch.ShiftID
                        where ... rest of the condition ...

Basically that's going to create a hash of all the shift IDs, so it can quickly look up possible matches for each schedule.


问:
IIS Website with multiple web applications underneath and different ports?
I am relatively new at configuring IIS and am wondering if the following scenario is possible.

My application consists of 2 Web apps.  1 is an ASP.NET Core App that hosts a Javascript SPA.  I have a second MVC App that is a combined Authorization Server using OpenIddict and the main API that the SPA talks to.

On my dev machine these 2 apps run on different ports.

These 2 apps go together to make our solution for any given customer.  I can get this all working on IIS treating each app as it's own website with it's own port.

But I would like to be able to bundle these 2 apps under 1 website.  Ultimately we will have several customer websites and each "website" really consists of these 2 apps bundled together.

I understand that I can create a single website and then convert my 2 existing sites to a web application.  So 2 web apps sit under the main web site. But these all will run under the same port.

I would really like my API and Authserver to run on a different port.  Is there a way to each this type of scenario?

What is the recommended best practice for what I am describing?

I do not want the API / Auth Server project to be shared by all the customer sites.  I want each customer site to have it's own instance of the Authorization server and API.

It would be great if you could create 2 websites and then sort of group them into a parent website container (if that makes any sense).

答: You can create two applications within your website on IIS. Then each application would be accessed as http://customerwebsite/app1 and http://customerwebsite/app2</p>


问:
"Cannot change DataType of a column once it has data" error in Visual Studio 2005 DataSet Designer
I've got a DataSet in VisualStudio 2005.  I need to change the datatype of a column in one of the datatables from System.Int32 to System.Decimal.  When I try to change the datatype in the DataSet Designer I receive the following error:

Property value is not valid.  Cannot change DataType of a column once
  it has data.

From my understanding, this should be changing the datatype in the schema for the DataSet.  I don't see how there can be any data to cause this error.

Does any one have any ideas?

答:
Since filled Datatables do not entertain a change in the schema a workaround can be applied as follows:

Make a new datatable

Use datatable's Clone method to
    create the datatable with the same
    structure and make changes to that
    column

In the end use datatable's ImportRow
    method to populate it with data.

HTH

OwnerDisplayName: firedfly

OwnerDisplayName: Codeslayer


问:
Display an alert over the lock screen?
On the iPhone, when your phone is locked and screen off, if a SMS message comes in, the screen turns on and an alert shows up.

Currently I am using UIAlertView to create the alert dialog (with 2 buttons).
If the phone is off/locked, nothing shows up until I turn it back on and unlock it.
Is there any way to simulate the 'SMS preview' behavior, possibly with another class, and hopefully still allow the user to interact with the buttons there?

答: What you want to do is not currently supported by the SDK. You should file a request with Apple.</p>

OwnerDisplayName: justinb

Title: Display an alert over the lock screen?

LastEditorDisplayName: Chris Hanson

OwnerDisplayName: August


问:
integration of paypal on drupal site
hi every on
I have created  paypal integration while registering i.e. paid registration.
my code is following  in module

```<code>function paidregistration_user($op, &$edit, &$account, $category = NULL){

                switch ($op) {
        case 'validate': {

                                $paypal = array();
                                $paypal['cmd'] = '_xclick';
                                $paypal['business'] = 'sachin.acetechpvtltd@gmail.com';  // doing this here prevents email harvesting
                                $paypal['page_style'] = 'Primary';
                                $paypal['bn'] = 'PP-DonationsBF';
                                $paypal['item_name'] = 'Donation';
                                $paypal['amount'] = '200';
                                $paypal['currency_code'] = 'USD';
                                $paypal['no_shipping'] = '1';
                                $paypal['tax'] = '0';
                                $paypal['lc'] = 'US';
                                $paypal['rm'] = '1';
                                $paypal['return'] = 'http://localhost/drupaldemo/pay';
                                $paypal['cancel_return'] = 'http://localhost/drupaldemo/user/register';

                                // Append the Paypal data to the $form_values['submitted_tree']
                                $data = array_merge($edit, $paypal);

                                // Put the data in a query string
                                $query = http_build_query($data, '', '&');

                                // Set the URL to Paypal's processing site and append the query string
                                $url = 'https://www.sandbox.paypal.com/cgi-bin/webscr?' .$query;
                                drupal_goto($url);
                                print_r($_REQUEST);
                                // Set the webform's confirmation page to Paypal
                                //$node->webform['confirmation'] = $url;

             //drupal_goto();exit;
                             }
            case 'insert' :{
                            print_r($_REQUEST);
                            }
             }
}
</code>```

and for success return page

```<code>function imagemenu_menu()
{
    $items['imagemenu'] = array(
    'title' => 'Add Image',
    'type' => MENU_NORMAL_ITEM,
    );

    $items['pay'] = array(
        'title' => 'Add Image',
        'access arguments' => array('all'),
        'page callback' => 'pay',
        'type' => MENU_NORMAL_ITEM,
    );

return $items;
}

function imagemenu_perm()
{
    return array('all');
}

function pay()
{
    print_r($_REQUEST);
}
</code>```

here every thing is working fine  but does not display data returned  from paypal.

any help will be appriciated
Thanks

答: Why not just use the existing PayPal module for Drupal? You're re-inventing the wheel here.</p>

Title: integration of paypal on drupal site

Body:
hi every on
I have created  paypal integration while registering i.e. paid registration.
my code is following  in module

function paidregistration_user($op, &$edit, &$account, $category = NULL){

                switch ($op) {
        case 'validate': {

                                $paypal = array();
                                $paypal['cmd'] = '_xclick';
                                $paypal['business'] = 'sachin.acetechpvtltd@gmail.com';  // doing this here prevents email harvesting
                                $paypal['page_style'] = 'Primary';
                                $paypal['bn'] = 'PP-DonationsBF';
                                $paypal['item_name'] = 'Donation';
                                $paypal['amount'] = '200';
                                $paypal['currency_code'] = 'USD';
                                $paypal['no_shipping'] = '1';
                                $paypal['tax'] = '0';
                                $paypal['lc'] = 'US';
                                $paypal['rm'] = '1';
                                $paypal['return'] = 'http://localhost/drupaldemo/pay';
                                $paypal['cancel_return'] = 'http://localhost/drupaldemo/user/register';

                                // Append the Paypal data to the $form_values['submitted_tree']
                                $data = array_merge($edit, $paypal);

                                // Put the data in a query string
                                $query = http_build_query($data, '', '&');

                                // Set the URL to Paypal's processing site and append the query string
                                $url = 'https://www.sandbox.paypal.com/cgi-bin/webscr?' .$query;
                                drupal_goto($url);
                                print_r($_REQUEST);
                                // Set the webform's confirmation page to Paypal
                                //$node->webform['confirmation'] = $url;

             //drupal_goto();exit;
                             }
            case 'insert' :{
                            print_r($_REQUEST);
                            }
             }
}

and for success return page

function imagemenu_menu()
{
    $items['imagemenu'] = array(
    'title' => 'Add Image',
    'type' => MENU_NORMAL_ITEM,
    );

    $items['pay'] = array(
        'title' => 'Add Image',
        'access arguments' => array('all'),
        'page callback' => 'pay',
        'type' => MENU_NORMAL_ITEM,
    );

return $items;
}

function imagemenu_perm()
{
    return array('all');
}

function pay()
{
    print_r($_REQUEST);
}

here every thing is working fine  but does not display data returned  from paypal.

any help will be appriciated
Thanks


问:
3-Way Modal in Telerik
Good day!

I just wish to ask if any of you have a way to Open a modal from a modal, then from that second modal, There is another modal to be opened.

Because in the current behavior of my modal, the 3rd modal will be always in the back of the second modal. I already read this article on how to get the parent modal, and it works perfectly for the second modal, but the problem is that the 3rd modal is not working properly.

Thank you so much.

答:
Try to change its z-index using CSS style. You could even assign one to each RadWindow.</p>

```<code><telerik:RadWindow ID="modalPopup" runat="server" Modal="true" Style="z-index: 100001;">
</code>```

Title: 3-Way Modal in Telerik

Body:
Try to change its z-index using CSS style. You could even assign one to each RadWindow.

<telerik:RadWindow ID="modalPopup" runat="server" Modal="true" Style="z-index: 100001;">


问:
Can't save the output of minicom into a file
When I use Minicom to capture data from a serial port, I need to save the big data into a file, named minicom.cap. However, if I press Ctrl+A and L to capture file, it failed. No file was created (minicom.cap did not exist beforehand). My download directory was properly created. My OS is Mint, and I read data from Arduino nano v3.0

答:
OP might miss step "Shift + L" after writing, so the overall procedure is as below:

1 (inside minicom)

2 Ctrl A + Z

3 Shift + L

4 (wait for writing ... )

5 Shift + L

6 (check the file you have written, default is minicom.cap, you may want to find it at /root/minicom.cap)


问:
How to resize bitmap to low resolution without loosing image information?
I am creating a deep learning based android app. I have a Canvas where I am allowing the user to draw something. Then I will pass the bitmap of the Canvas to my model for classification. I am using Tensorflow MNIST project as the base for my project. My problem is, in the MNIST example user are allowed to draw on a 28x28 size Canvas. But I don't want to do that because drawing on that Canvas is pixelating the drawing. I am drawing on a full size Canvas but while sending the Bitmap of the canvas to the Tensorflow model I want to resize it to 28x28 for classification (else I am getting ArrayIndexOutOfBoundException).

How can I resize the bitmap to 28x28 without loosing information ? or any other possible solution for this ?

Here is the image of the MNIST canvas:

This is the image of my application canvas. I tried resizing it to 28x28 but I am loosing the image information:

答:
Let's say you have an input of 100 x 100  image and you want to resize it to 28 x 28.

100 x 100 pixels -> 10000 features

28 x 28 pixels -> 784 features

It is mathematically impossible not to lose input information while resizing.

However there are other ways to work around.

Get rid of white areas around drawing. It will already filter most of the unnecessary pixels. Then you can apply resizing.

Try a different interpolation method. During the resizing operation, we are using different kinds of interpolations (bilinear, bicubic etc.).

Try to make the input images bigger for your network (resize 28 x 28 MNIST to 56 x 56 for example) and train with bigger size. Then, you will be losing less information for inference in cost of speed as it will be slightly slower to classify larger image.


问:
Love2d: Creating multiple of the same object from a different file
I was wondering if it is possible to create multiple of the same object that is written in a separate file.
I have two files: main.lua and player.lua.
This is player.lua:

```<code>    local player = { }
function player:create (x, y, sp)
    self.img = love.graphics.newImage ('images/player.png')
    self.x = x
    self.y = y
    self.speed = sp
end

return player
</code>```

I want to include this file in main.lua. I know I can't use require "player" because require only allows a file to be loaded once but it doesn't need me to specify a file path. I tried using dofile() which actually did exactly what I wanted it to do, however, it does requires me to specify a full file path which I don't want to do.
So this is the part from main.lua:

```<code>local Player = require "player"
local Player2 = require "player"
-- local Player = dofile("/long/path/to/game/player.lua")
</code>```

If I can't use require, is there a way to get the current file directory and use it like this:

```<code>local Player = dofile(filepath .. "player.lua")
</code>```

答:
that loads the image serveral times... couldnt you just load an image once then call that image in a varable later like so:</p>

```<code>-- Player.lua
local Player = {}
local img1 = love.graphics.newImage('images/player.png') <-- loaded one time

function Player:create (x, y, sp)
    self.__index = self

    return setmetatable({
        img = img1,
        x = x,
        y = y,
        speed = sp
    }, self)
end

return Player
</code>```

Body:
I was wondering if it is possible to create multiple of the same object that is written in a separate file.
I have two files: main.lua and player.lua.
This is player.lua:

    local player = { }
function player:create (x, y, sp)
    self.img = love.graphics.newImage ('images/player.png')
    self.x = x
    self.y = y
    self.speed = sp
end

return player

I want to include this file in main.lua. I know I can't use require "player" because require only allows a file to be loaded once but it doesn't need me to specify a file path. I tried using dofile() which actually did exactly what I wanted it to do, however, it does requires me to specify a full file path which I don't want to do.
So this is the part from main.lua:

local Player = require "player"
local Player2 = require "player"
-- local Player = dofile("/long/path/to/game/player.lua")

If I can't use require, is there a way to get the current file directory and use it like this:

local Player = dofile(filepath .. "player.lua")

Body:
that loads the image serveral times... couldnt you just load an image once then call that image in a varable later like so:

-- Player.lua
local Player = {}
local img1 = love.graphics.newImage('images/player.png') <-- loaded one time

function Player:create (x, y, sp)
    self.__index = self

    return setmetatable({
        img = img1,
        x = x,
        y = y,
        speed = sp
    }, self)
end

return Player