问:
Rock Paper Scissors IIF but IIF is not changing the values of the const named outcome
So I'm trying to get a rock paper scissors game to work using the ternary operator in vb.net, but no matter how I set it up, I get the wrong results(continues to output the same outcome, no matter what the actual outcome should be I.E, R vs P = lose, R vs S = lose, R vs R = lose)  </p>

<p>I had originally tried using outcome/draw bool as a placeholder with an if at the end to display the outcome, and added an exit switch inside the ifs immediately following the IIF but still it would result in a loop of not changing the outcome. </p>

```<code>Public Class Form1
    Const ROCK As Integer = 1
    Const PAPER As Integer = 2
    Const SCISSORS As Integer = 3
    Dim computerThrow As Integer
    Dim comThrow As String = "Rock"
    Dim wins As Integer
    Dim losses As Integer
    Dim draws As Integer
    Dim outcome As Boolean = True
    Dim draw As Boolean = True

    'Spent two days debugging, kept getting more broken. hmm
    Private Sub btnThrow_Click(sender As Object, e As EventArgs) Handles btnThrow.Click

        'Generate computer throw
        Randomize()
        computerThrow = Int(3 * Rnd() + 1)

        'Select case block
        Select Case computerThrow
            Case ROCK
                comThrow = "rock"
                IIf(Me.radRock.Checked = True, draw = True, 1 = 1) 'Ternarys to decide outcome/draw
                If draw = True Then 'If to decide whether to exit or not
                    Me.lblWinner.Text = "Computer throws " + comThrow + ", it's a draw!"
                    draws = draws + 1
                End If
                IIf(Me.radPaper.Checked = True, outcome = True, 1 = 1)
                If outcome = True Then
                    Me.lblWinner.Text = "Computer throws " + comThrow + ", you win!"
                    wins = wins + 1
                End If
                IIf(Me.radScissors.Checked = True, outcome = False, 1 = 1)
                If outcome = False And draw = False Then
                    Me.lblWinner.Text = "Computer throws " + comThrow + ", you lose!"
                    losses = losses + 1
                End If
            Case PAPER
                comThrow = "paper"
                IIf(Me.radRock.Checked = True, outcome = False, 1 = 1)
                If outcome = False And draw = False Then
                    Me.lblWinner.Text = "Computer throws " + comThrow + ", you lose!"
                    losses = losses + 1
                End If
                IIf(Me.radPaper.Checked = True, draw = True, 1 = 1)
                If draw = True Then
                    Me.lblWinner.Text = "Computer throws " + comThrow + ", it's a draw!"
                    draws = draws + 1
                End If
                IIf(Me.radScissors.Checked = True, outcome = True, 1 = 1)
                If outcome = True Then
                    Me.lblWinner.Text = "Computer throws " + comThrow + ", you win!"
                    wins = wins + 1
                End If
            Case SCISSORS
                comThrow = "scissors"
                IIf(Me.radRock.Checked = True, outcome = True, 1 = 1)
                If outcome = True Then
                    Me.lblWinner.Text = "Computer throws " + comThrow + ", you win!"
                    wins = wins + 1
                End If
                IIf(Me.radPaper.Checked = True, outcome = False, 1 = 1)
                If outcome = False And draw = False Then
                    Me.lblWinner.Text = "Computer throws " + comThrow + ", you lose!"
                    losses = losses + 1
                End If
                IIf(Me.radScissors.Checked = True, draw = True, 1 = 1)
                If draw = True Then
                    Me.lblWinner.Text = "Computer throws " + comThrow + ", it's a draw!"
                    draws = draws + 1
                End If
        End Select

        Me.lblResults.Text = "wins: " + wins.ToString() + " Lose: " + losses.ToString() + " draws: " + draws.ToString()

    End Sub
End Class
</code>```

答:
IIF is not the ternary operator in VB.NET. IIF is a function and both the true part and the false part are evaluated. This means that, whatever is the checked state of your checkboxes, the true part of the IIF function is always executed, thus you always get the variable assigned to true or false.

On the contrary the conditional ternary operator in VB.NET is If(expression, true part,false part), which uses shortcircuit evaluation to choose the expression value.
Thus you should rewrite your code in this way

```<code>  draw = If(Me.radRock.Checked, True, False)
  If draw Then
     ....
</code>```

But at this point you could simply write

```<code>  draw = Me.radRock.Checked
  If draw Then
     ....
</code>```

or

```<code>  outcome = Not Me.radRock.Checked
  ....
</code>```

Body:
So I'm trying to get a rock paper scissors game to work using the ternary operator in vb.net, but no matter how I set it up, I get the wrong results(continues to output the same outcome, no matter what the actual outcome should be I.E, R vs P = lose, R vs S = lose, R vs R = lose)

I had originally tried using outcome/draw bool as a placeholder with an if at the end to display the outcome, and added an exit switch inside the ifs immediately following the IIF but still it would result in a loop of not changing the outcome.

Public Class Form1
    Const ROCK As Integer = 1
    Const PAPER As Integer = 2
    Const SCISSORS As Integer = 3
    Dim computerThrow As Integer
    Dim comThrow As String = "Rock"
    Dim wins As Integer
    Dim losses As Integer
    Dim draws As Integer
    Dim outcome As Boolean = True
    Dim draw As Boolean = True

    'Spent two days debugging, kept getting more broken. hmm
    Private Sub btnThrow_Click(sender As Object, e As EventArgs) Handles btnThrow.Click

        'Generate computer throw
        Randomize()
        computerThrow = Int(3 * Rnd() + 1)

        'Select case block
        Select Case computerThrow
            Case ROCK
                comThrow = "rock"
                IIf(Me.radRock.Checked = True, draw = True, 1 = 1) 'Ternarys to decide outcome/draw
                If draw = True Then 'If to decide whether to exit or not
                    Me.lblWinner.Text = "Computer throws " + comThrow + ", it's a draw!"
                    draws = draws + 1
                End If
                IIf(Me.radPaper.Checked = True, outcome = True, 1 = 1)
                If outcome = True Then
                    Me.lblWinner.Text = "Computer throws " + comThrow + ", you win!"
                    wins = wins + 1
                End If
                IIf(Me.radScissors.Checked = True, outcome = False, 1 = 1)
                If outcome = False And draw = False Then
                    Me.lblWinner.Text = "Computer throws " + comThrow + ", you lose!"
                    losses = losses + 1
                End If
            Case PAPER
                comThrow = "paper"
                IIf(Me.radRock.Checked = True, outcome = False, 1 = 1)
                If outcome = False And draw = False Then
                    Me.lblWinner.Text = "Computer throws " + comThrow + ", you lose!"
                    losses = losses + 1
                End If
                IIf(Me.radPaper.Checked = True, draw = True, 1 = 1)
                If draw = True Then
                    Me.lblWinner.Text = "Computer throws " + comThrow + ", it's a draw!"
                    draws = draws + 1
                End If
                IIf(Me.radScissors.Checked = True, outcome = True, 1 = 1)
                If outcome = True Then
                    Me.lblWinner.Text = "Computer throws " + comThrow + ", you win!"
                    wins = wins + 1
                End If
            Case SCISSORS
                comThrow = "scissors"
                IIf(Me.radRock.Checked = True, outcome = True, 1 = 1)
                If outcome = True Then
                    Me.lblWinner.Text = "Computer throws " + comThrow + ", you win!"
                    wins = wins + 1
                End If
                IIf(Me.radPaper.Checked = True, outcome = False, 1 = 1)
                If outcome = False And draw = False Then
                    Me.lblWinner.Text = "Computer throws " + comThrow + ", you lose!"
                    losses = losses + 1
                End If
                IIf(Me.radScissors.Checked = True, draw = True, 1 = 1)
                If draw = True Then
                    Me.lblWinner.Text = "Computer throws " + comThrow + ", it's a draw!"
                    draws = draws + 1
                End If
        End Select

        Me.lblResults.Text = "wins: " + wins.ToString() + " Lose: " + losses.ToString() + " draws: " + draws.ToString()

    End Sub
End Class

Body:
IIF is not the ternary operator in VB.NET. IIF is a function and both the true part and the false part are evaluated. This means that, whatever is the checked state of your checkboxes, the true part of the IIF function is always executed, thus you always get the variable assigned to true or false.

On the contrary the conditional ternary operator in VB.NET is If(expression, true part,false part), which uses shortcircuit evaluation to choose the expression value.
Thus you should rewrite your code in this way

  draw = If(Me.radRock.Checked, True, False)
  If draw Then
     ....

But at this point you could simply write

  draw = Me.radRock.Checked
  If draw Then
     ....

or

  outcome = Not Me.radRock.Checked
  ....


来源: stackexchange

问:
C read file line by line
I wrote this function to read a line from a file:

```<code>const char *readLine(FILE *file) {

    if (file == NULL) {
        printf("Error: file pointer is null.");
        exit(1);
    }

    int maximumLineLength = 128;
    char *lineBuffer = (char *)malloc(sizeof(char) * maximumLineLength);

    if (lineBuffer == NULL) {
        printf("Error allocating memory for line buffer.");
        exit(1);
    }

    char ch = getc(file);
    int count = 0;

    while ((ch != '\n') && (ch != EOF)) {
        if (count == maximumLineLength) {
            maximumLineLength += 128;
            lineBuffer = realloc(lineBuffer, maximumLineLength);
            if (lineBuffer == NULL) {
                printf("Error reallocating space for line buffer.");
                exit(1);
            }
        }
        lineBuffer[count] = ch;
        count++;

        ch = getc(file);
    }

    lineBuffer[count] = '\0';
    char line[count + 1];
    strncpy(line, lineBuffer, (count + 1));
    free(lineBuffer);
    const char *constLine = line;
    return constLine;
}
</code>```

The function reads the file correctly, and using printf I see that the constLine string did get read correctly as well.

However, if I use the function e.g. like this:

```<code>while (!feof(myFile)) {
    const char *line = readLine(myFile);
    printf("%s\n", line);
}
</code>```

printf outputs gibberish. Why?

答:
Implement method to read, and get content from a file (input1.txt)

```<code>#include <stdio.h>
#include <stdlib.h>

void testGetFile() {
    // open file
    FILE *fp = fopen("input1.txt", "r");
    size_t len = 255;
    // need malloc memory for line, if not, segmentation fault error will occurred.
    char *line = malloc(sizeof(char) * len);
    // check if file exist (and you can open it) or not
    if (fp == NULL) {
        printf("can open file input1.txt!");
        return;
    }
    while(fgets(line, len, fp) != NULL) {
        printf("%s\n", line);
    }
    free(line);
}
</code>```

Hope this help. Happy coding!

ContentLicense: CC BY-SA 2.5

Title: C read file line by line

Body:
I wrote this function to read a line from a file:

const char *readLine(FILE *file) {

    if (file == NULL) {
        printf("Error: file pointer is null.");
        exit(1);
    }

    int maximumLineLength = 128;
    char *lineBuffer = (char *)malloc(sizeof(char) * maximumLineLength);

    if (lineBuffer == NULL) {
        printf("Error allocating memory for line buffer.");
        exit(1);
    }

    char ch = getc(file);
    int count = 0;

    while ((ch != '\n') && (ch != EOF)) {
        if (count == maximumLineLength) {
            maximumLineLength += 128;
            lineBuffer = realloc(lineBuffer, maximumLineLength);
            if (lineBuffer == NULL) {
                printf("Error reallocating space for line buffer.");
                exit(1);
            }
        }
        lineBuffer[count] = ch;
        count++;

        ch = getc(file);
    }

    lineBuffer[count] = '\0';
    char line[count + 1];
    strncpy(line, lineBuffer, (count + 1));
    free(lineBuffer);
    const char *constLine = line;
    return constLine;
}

The function reads the file correctly, and using printf I see that the constLine string did get read correctly as well.

However, if I use the function e.g. like this:

while (!feof(myFile)) {
    const char *line = readLine(myFile);
    printf("%s\n", line);
}

printf outputs gibberish. Why?

Body:
Implement method to read, and get content from a file (input1.txt)

#include <stdio.h>
#include <stdlib.h>

void testGetFile() {
    // open file
    FILE *fp = fopen("input1.txt", "r");
    size_t len = 255;
    // need malloc memory for line, if not, segmentation fault error will occurred.
    char *line = malloc(sizeof(char) * len);
    // check if file exist (and you can open it) or not
    if (fp == NULL) {
        printf("can open file input1.txt!");
        return;
    }
    while(fgets(line, len, fp) != NULL) {
        printf("%s\n", line);
    }
    free(line);
}

Hope this help. Happy coding!

ContentLicense: CC BY-SA 3.0


问:
PHP - How to use Foreach to turn a list into a column rather than a row of items?
I have a database, and am trying to get a list using PHP with foreach, but  the list are returning like this:

RiquelmeMacielLewBrMarcuus

But it like so:

RiquelmeMaciel
 LewBr
 Marcuus

My code:

```<code><?php
        include_once("conexao.php");
        $select = "SELECT * FROM usuarios ORDER BY id";
        $query = mysqli_query($conn, $select);
        $rows = mysqli_fetch_assoc($query);
              ?>
              <?php foreach($rows as $row){
              echo '<td class="mdl-data-table__cell--non-numeric name">'.$row['nome'].'</td>';
              } ?>
</code>```

答:
The problem in your foreach cycle - for eache element you output  tag, but  is a table cell tag.

If you want fill first column in your 3-column table, you must do something like this:

```<code><?php foreach($resultado_usuario as $teste){
     echo '<tr>';
     echo '<td class="mdl-data-table__cell--non-numeric name">'.$teste['nome'].'</td>';
     echo '<td>second column</td>';
     echo '<td>third column</td>';
     echo '</tr>';
} ?>
</code>```

Body:
I have a database, and am trying to get a list using PHP with foreach, but  the list are returning like this:

RiquelmeMacielLewBrMarcuus

But it like so:

RiquelmeMaciel
 LewBr
 Marcuus

My code:

<?php
        include_once("conexao.php");
        $select = "SELECT * FROM usuarios ORDER BY id";
        $query = mysqli_query($conn, $select);
        $rows = mysqli_fetch_assoc($query);
              ?>
              <?php foreach($rows as $row){
              echo ''.$row['nome'].'	';
              } ?>

Body:
The problem in your foreach cycle - for eache element you output  tag, but  is a table cell tag.

If you want fill first column in your 3-column table, you must do something like this:

<?php foreach($resultado_usuario as $teste){
     echo '<tr>';
     echo '<td class="mdl-data-table__cell--non-numeric name">'.$teste['nome'].'</td>';
     echo '<td>second column</td>';
     echo '<td>third column</td>';
     echo '</tr>';
} ?>


问:
Error installing tizen studio on windows 10
No matter which of the three tizen studio 2.0 installers I try they all don't work as they won't accept any path. The CLI installer gives the most detailed description:

** The directory you specify is not allowed to install the Tizen Studio. Some tools of the Tizen Studio will not properly work in the directory with administrator privilege or read-only access rights for your account.=> path

I have tried starting the installer with admin rights and owning the destination folders. Additionally, I switched from JDK 9 to 8.

Still, there seems no way to get the installer running. Any ideas what the reason could be? Thanks!

答:
I've successfully installed the IDE version with the following method:

Download Tizen Studio Web IDE installer

Open installer with 7-zip archive manager

You should find tizen-sdk.zip archive

Open it and extract it into the C:\tizen-studio folder

Create C:\tizen-studio-data folder

Create sdk.info file inside C:\tizen-studio folder

Put following lines into this file

TIZEN_SDK_INSTALLED_PATH=C:\tizen-studio

TIZEN_SDK_DATA_PATH=C:\tizen-studio-data

You can download packages with C:\tizen-studio\package-manager\package-manager.exe

You can start IDE from C:\tizen-studio\ide\TizenStudio.exe

This worked for me, hope this helps...


问:
Easiest way to extract the urls from an html page using sed or awk only
I want to extract the URL from within the anchor tags of an html file.
This needs to be done in BASH using SED/AWK. No perl please.

What is the easiest way to do this?

答:
This is my first post, so I try to do my best explaining why I post this answer...

Since the first 7 most voted answers, 4 include GREP even when the
post explicitly says "using sed or awk only".

Even when the post requires "No perl please", due to the previous
point, and because use PERL regex inside grep.

and because this is the simplest way ( as far I know , and was
required ) to do it in BASH.

So here come the simplest script from GNU grep 2.28:

```<code>grep -Po 'href="\K.*?(?=")'
</code>```

About the \K switch , not info was founded in MAN and INFO pages, so I came here for the answer....
the \K switch get rid the previous chars ( and the key itself ).
Bear in mind following the advice from man pages:
"This is highly experimental and grep -P may warn of unimplemented features."

Of course, you can modify the script to meet your tastes or needs, but I found it pretty straight for what was requested in the post , and also for many of us...

I hope folks you find it very useful.

thanks!!!

Body:
This is my first post, so I try to do my best explaining why I post this answer...

Since the first 7 most voted answers, 4 include GREP even when the
post explicitly says "using sed or awk only".

Even when the post requires "No perl please", due to the previous
point, and because use PERL regex inside grep.

and because this is the simplest way ( as far I know , and was
required ) to do it in BASH.

So here come the simplest script from GNU grep 2.28:

grep -Po 'href="\K.*?(?=")'

About the \K switch , not info was founded in MAN and INFO pages, so I came here for the answer....
the \K switch get rid the previous chars ( and the key itself ).
Bear in mind following the advice from man pages:
"This is highly experimental and grep -P may warn of unimplemented features."

Of course, you can modify the script to meet your tastes or needs, but I found it pretty straight for what was requested in the post , and also for many of us...

I hope folks you find it very useful.

thanks!!!


问:
how to concatenate timestamp in different rows in postgresql?
I'm looking for a way to concatenate timestamp in two difference row, for an example, I have this table:

I want it to be grouped by weekday and concatenate the min(start_hour) with max(start_hour), to get something like this

and I'm using this query to retrieve the first image result

答:
The query below should give you what you are looking for provided the information supplied. I made some assumptions. That the '00:00:00' in the start and end hours is not a valid time and can be ignored. If they should be considered valid, then Friday's output would be one entry of '00:00:00' - '11:30:00'.

I created two CTEs, one for the start hours and the other for the end hours where the values are not '00:00:00'. Added a row number to the CTEs so i can match up the day & row_number to get you a set.

```<code>SELECT day
    ,array_to_string(array_agg(t.shift), ',') shifts
FROM (
    WITH cte_start AS (
            SELECT row_number() OVER (PARTITION BY day)
                ,day
                ,start_hour
            FROM test22
            WHERE start_hour <> '00:00:00'::time
            )
        ,cte_stop AS (
            SELECT row_number() OVER (PARTITION BY day)
                ,day
                ,stop_hour
            FROM test22
            WHERE stop_hour <> '00:00:00'::time
            )
    SELECT cte_start.day
        ,cte_start.start_hour::varchar || ' - ' || cte_stop.stop_hour::varchar AS shift
    FROM cte_start
    LEFT OUTER JOIN cte_stop ON cte_start.day = cte_stop.day
        AND cte_start.row_number = cte_stop.row_number
    ) T
GROUP BY T.day
</code>```

-HTH

Body:
The query below should give you what you are looking for provided the information supplied. I made some assumptions. That the '00:00:00' in the start and end hours is not a valid time and can be ignored. If they should be considered valid, then Friday's output would be one entry of '00:00:00' - '11:30:00'.

I created two CTEs, one for the start hours and the other for the end hours where the values are not '00:00:00'. Added a row number to the CTEs so i can match up the day & row_number to get you a set.

SELECT day
    ,array_to_string(array_agg(t.shift), ',') shifts
FROM (
    WITH cte_start AS (
            SELECT row_number() OVER (PARTITION BY day)
                ,day
                ,start_hour
            FROM test22
            WHERE start_hour <> '00:00:00'::time
            )
        ,cte_stop AS (
            SELECT row_number() OVER (PARTITION BY day)
                ,day
                ,stop_hour
            FROM test22
            WHERE stop_hour <> '00:00:00'::time
            )
    SELECT cte_start.day
        ,cte_start.start_hour::varchar || ' - ' || cte_stop.stop_hour::varchar AS shift
    FROM cte_start
    LEFT OUTER JOIN cte_stop ON cte_start.day = cte_stop.day
        AND cte_start.row_number = cte_stop.row_number
    ) T
GROUP BY T.day

-HTH


问:
Downloading a folder with phpseclib Net_SFTP.get does not work
I am trying to access a file in an SFTP folder server using phpseclib. But when I try using $sftp->get, it returns false. I am not sure how to debug the problem at all.

```<code>public function get_file_from_ftps_server()
{
    $sftp = new \phpseclib\Net\SFTP(getenv('INSTRUM_SERVER'));
    if (!$sftp->login(getenv('INSTRUM_USERNAME'), getenv('INSTRUM_PASSWORD'))) {
        exit('Login Failed');
    }

    $this->load->helper('file');
    $root  = dirname(dirname(__FILE__));
    $root .= '/third_party/collections_get/';
    $path_to_server = 'testdownload/';
    $result = $sftp->get($path_to_server, $root);

    var_dump($result);
}
</code>```

In the $result, I get a false and I am not sure why its happening, I read their documentation but still not sure. Root is the directory where I want my information to be stored. Right now I only added a trial.xml file there, but also wondering how can I get multiple files if its in the folder.

Here is a picture of the server structure:

答:
The Net_SFTP.get method can download a single file only. You cannot use it to download a whole directory.

If you want to download whole directory, you have to use one of the "list" methods (Net_SFTP.nlist or Net_SFTP.rawlist) to retrieve list of files and then download the files one-by-one.

ContentLicense: CC BY-SA 4.0

Body:
I am trying to access a file in an SFTP folder server using phpseclib. But when I try using $sftp->get, it returns false. I am not sure how to debug the problem at all.

public function get_file_from_ftps_server()
{
    $sftp = new \phpseclib\Net\SFTP(getenv('INSTRUM_SERVER'));
    if (!$sftp->login(getenv('INSTRUM_USERNAME'), getenv('INSTRUM_PASSWORD'))) {
        exit('Login Failed');
    }

    $this->load->helper('file');
    $root  = dirname(dirname(__FILE__));
    $root .= '/third_party/collections_get/';
    $path_to_server = 'testdownload/';
    $result = $sftp->get($path_to_server, $root);

    var_dump($result);
}

In the $result, I get a false and I am not sure why its happening, I read their documentation but still not sure. Root is the directory where I want my information to be stored. Right now I only added a trial.xml file there, but also wondering how can I get multiple files if its in the folder.

Here is a picture of the server structure:


答:
Your are displaying your data the wrong way, your  should be inside
 which should be inside a
:

```<code><table>
    <tr>
        <th>Nome</th>
        <th>Email</th>
        <th>Senha</th>
    </tr>
    <?php
    foreach ($resultado_usuario as $teste){
        echo '<tr>';
        echo '<td class="mdl-data-table__cell--non-numeric name">'.$teste['nome'].'</td>';
        echo '<td class="mdl-data-table__cell--non-numeric email">'.$teste['email'].'</td>';
        echo '<td class="mdl-data-table__cell--non-numeric senha">'.$teste['senha'].'</td>';
        echo '</tr>';
    }
    ?>
</table>
</code>```

The data will then be displayed as you wanted it. Have a look at HTML - table.

If you want to change the order of your data from your SQL query, use the ORDER BY ... ASC|DESC.

Title: PHP - How to use Foreach to turn a list into a column rather than a row of items?

Body:
Your are displaying your data the wrong way, your <td> should be inside <tr> which should be inside a <table>:

<table>
    <tr>
        <th>Nome</th>
        <th>Email</th>
        <th>Senha</th>
    </tr>
    <?php
    foreach ($resultado_usuario as $teste){
        echo '<tr>';
        echo '<td class="mdl-data-table__cell--non-numeric name">'.$teste['nome'].'</td>';
        echo '<td class="mdl-data-table__cell--non-numeric email">'.$teste['email'].'</td>';
        echo '<td class="mdl-data-table__cell--non-numeric senha">'.$teste['senha'].'</td>';
        echo '</tr>';
    }
    ?>
</table>

The data will then be displayed as you wanted it. Have a look at HTML - table.

If you want to change the order of your data from your SQL query, use the ORDER BY ... ASC|DESC.


问:
How long does it take to update a version of Google Spreadsheet Scripts add-on?
I've found an important bug on my Google Spreadsheet Add-on. I pushed the new version yesterday and 24 hours later is still not updated. I have clients angry with this bug that is already solved, but pending on someone to be updated.

Last time, my updates takes minutes to perform it, but now it's taking too long.

What can I do?

This is the store link: https://chrome.google.com/webstore/detail/route-optimizer-smartmonk/ebjgghodfhffloccipkmahndnpemnjoj?authuser=0

Thanks

答:
In my experience I've found that it varies.

Add-ons are published to all regions world-wide by default. That means an update has to propagate to servers world over. I can't say definitively that this will work but if you reduce the number of regions where your add-on is available you might get better update times.

If you have analytics on add-on usage and can effectively pinpoint which regions don't use your add-on, then I would recommend that you disable those regions the next time you deploy your add-on.


问:
Upgrade to studio 3.0 is crashing my app with dalvik.system.BaseDexClassLoader.findClass
This is just happening after a migration from studio 2.x to studio 3.0 with android 4.4. Android 6 runs fine.
I googled this issue but didn't find crisp response. Just a particular app has this behavior. I have other apps which are fine.

The update process has broken something but what? Why is it impacting android 4.x only?

I tried clean sync, rebuild,restart studio, restart tablet, ...

here is my gradle:

```<code>apply plugin: 'com.android.application'

android {
    compileSdkVersion 26
    buildToolsVersion '26.0.2'
    defaultConfig {
        applicationId "com.narb.test"
        minSdkVersion 18
        targetSdkVersion 24
        versionName '3.2'
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        versionNameSuffix '-9-nov-2017'
        multiDexEnabled true
        versionCode 53
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    productFlavors {
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile files('libs/commons-net-3.5.jar')
    compile 'com.android.support:appcompat-v7:26.1.0'
    compile 'com.android.support:support-v4:26.1.0'
    compile 'com.google.android.gms:play-services-maps:10.0.1'
    testCompile 'junit:junit:4.12'
    compile 'org.jsoup:jsoup:1.10.3'
}
</code>```

and the logcat:

```<code>java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.narb.test/com.narb.test.MainActivity}: java.lang.ClassNotFoundException: Didn't find class "com.narb.test.MainActivity" on path: DexPathList[[zip file "/data/app/com.narb.test-29.apk"],nativeLibraryDirectories=[/data/app-lib/com.narb.test-29, /vendor/lib, /system/lib]]
     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2305)
     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2470)
     at android.app.ActivityThread.access$900(ActivityThread.java:174)
     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1307)
     at android.os.Handler.dispatchMessage(Handler.java:102)
     at android.os.Looper.loop(Looper.java:146)
     at android.app.ActivityThread.main(ActivityThread.java:5593)
     at java.lang.reflect.Method.invokeNative(Native Method)
     at java.lang.reflect.Method.invoke(Method.java:515)
     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283)
     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
     at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.ClassNotFoundException: Didn't find class "com.narb.test.MainActivity" on path: DexPathList[[zip file "/data/app/com.narb.test-29.apk"],nativeLibraryDirectories=[/data/app-lib/com.narb.test-29, /vendor/lib, /system/lib]]
     at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:67)
     at java.lang.ClassLoader.loadClass(ClassLoader.java:497)
     at java.lang.ClassLoader.loadClass(ClassLoader.java:457)
     at android.app.Instrumentation.newActivity(Instrumentation.java:1067)
     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2296)
     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2470)
     at android.app.ActivityThread.access$900(ActivityThread.java:174)
     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1307)
     at android.os.Handler.dispatchMessage(Handler.java:102)
     at android.os.Looper.loop(Looper.java:146)
     at android.app.ActivityThread.main(ActivityThread.java:5593)
     at java.lang.reflect.Method.invokeNative(Native Method)
     at java.lang.reflect.Method.invoke(Method.java:515)
     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283)
     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
     at dalvik.system.NativeStart.main(Native Method)
</code>```

and the manifest:

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.narb.test">

    <uses-feature
        android:glEsVersion="0x00020000"
        android:required="true" />

    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.MEDIA_CONTENT_CONTROL" />
    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />

    <application
        android:allowBackup="true"
        android:largeHeap="true"
        android:configChanges="keyboardHidden|screenSize"
        android:icon="@drawable/networksafe"
        android:label="test"
        android:logo="@drawable/networksafe"
        android:screenOrientation="portrait"
        android:supportsRtl="true"

        android:theme="@style/AppTheme">
        <activity
            android:name=".MainActivity"
            android:screenOrientation="portrait">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <service
            android:name=".vpn.services"
            android:enabled="true"
            android:exported="true"
            android:permission="android.permission.BIND_VPN_SERVICE">

            <intent-filter>
                <action android:name="android.Net.Services"/>
            </intent-filter>
        </service>
        <activity
            android:name=".Activities.Settings"
            android:windowSoftInputMode="stateHidden" />
        <activity android:name=".Activities.About" />
        <activity android:name=".Activities.History" />

        <service
            android:name=".Socket"
            android:exported="false" />

        <service
            android:name=".ServiceMonitoring"
            android:exported="false" />

        <!--
             The API key for Google Maps-based APIs is defined as a string resource.
             (See the file "res/values/google_maps_api.xml").
             Note that the API key is linked to the encryption key used to sign the APK.
             You need a different API key for each encryption key, including the release key that is used to
             sign the APK for publishing.
             You can define the keys for the debug and release targets in src/debug/ and src/release/.
        -->
        <meta-data
            android:name="com.google.android.gms.version"
            android:value="@integer/google_play_services_version" />
        <meta-data
            android:name="com.google.android.geo.API_KEY"
            android:value="@string/google_maps_key" />

        <activity android:name=".Activities.RateMe"></activity>
    </application>

</manifest>
</code>```

答: Run the Gradle clean command  then do the File -> Invalidate caches & restart. For me it solves the problem</p>

Body:
This is just happening after a migration from studio 2.x to studio 3.0 with android 4.4. Android 6 runs fine.
I googled this issue but didn't find crisp response. Just a particular app has this behavior. I have other apps which are fine.

The update process has broken something but what? Why is it impacting android 4.x only?

I tried clean sync, rebuild,restart studio, restart tablet, ...

here is my gradle:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 26
    buildToolsVersion '26.0.2'
    defaultConfig {
        applicationId "com.narb.test"
        minSdkVersion 18
        targetSdkVersion 24
        versionName '3.2'
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        versionNameSuffix '-9-nov-2017'
        multiDexEnabled true
        versionCode 53
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    productFlavors {
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile files('libs/commons-net-3.5.jar')
    compile 'com.android.support:appcompat-v7:26.1.0'
    compile 'com.android.support:support-v4:26.1.0'
    compile 'com.google.android.gms:play-services-maps:10.0.1'
    testCompile 'junit:junit:4.12'
    compile 'org.jsoup:jsoup:1.10.3'
}

and the logcat:

java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.narb.test/com.narb.test.MainActivity}: java.lang.ClassNotFoundException: Didn't find class "com.narb.test.MainActivity" on path: DexPathList[[zip file "/data/app/com.narb.test-29.apk"],nativeLibraryDirectories=[/data/app-lib/com.narb.test-29, /vendor/lib, /system/lib]]
     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2305)
     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2470)
     at android.app.ActivityThread.access$900(ActivityThread.java:174)
     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1307)
     at android.os.Handler.dispatchMessage(Handler.java:102)
     at android.os.Looper.loop(Looper.java:146)
     at android.app.ActivityThread.main(ActivityThread.java:5593)
     at java.lang.reflect.Method.invokeNative(Native Method)
     at java.lang.reflect.Method.invoke(Method.java:515)
     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283)
     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
     at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.ClassNotFoundException: Didn't find class "com.narb.test.MainActivity" on path: DexPathList[[zip file "/data/app/com.narb.test-29.apk"],nativeLibraryDirectories=[/data/app-lib/com.narb.test-29, /vendor/lib, /system/lib]]
     at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:67)
     at java.lang.ClassLoader.loadClass(ClassLoader.java:497)
     at java.lang.ClassLoader.loadClass(ClassLoader.java:457)
     at android.app.Instrumentation.newActivity(Instrumentation.java:1067)
     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2296)
     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2470)
     at android.app.ActivityThread.access$900(ActivityThread.java:174)
     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1307)
     at android.os.Handler.dispatchMessage(Handler.java:102)
     at android.os.Looper.loop(Looper.java:146)
     at android.app.ActivityThread.main(ActivityThread.java:5593)
     at java.lang.reflect.Method.invokeNative(Native Method)
     at java.lang.reflect.Method.invoke(Method.java:515)
     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283)
     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
     at dalvik.system.NativeStart.main(Native Method)

and the manifest:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.narb.test">

    <uses-feature
        android:glEsVersion="0x00020000"
        android:required="true" />

    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.MEDIA_CONTENT_CONTROL" />
    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />

    <application
        android:allowBackup="true"
        android:largeHeap="true"
        android:configChanges="keyboardHidden|screenSize"
        android:icon="@drawable/networksafe"
        android:label="test"
        android:logo="@drawable/networksafe"
        android:screenOrientation="portrait"
        android:supportsRtl="true"

        android:theme="@style/AppTheme">
        <activity
            android:name=".MainActivity"
            android:screenOrientation="portrait">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <service
            android:name=".vpn.services"
            android:enabled="true"
            android:exported="true"
            android:permission="android.permission.BIND_VPN_SERVICE">

            <intent-filter>
                <action android:name="android.Net.Services"/>
            </intent-filter>
        </service>
        <activity
            android:name=".Activities.Settings"
            android:windowSoftInputMode="stateHidden" />
        <activity android:name=".Activities.About" />
        <activity android:name=".Activities.History" />

        <service
            android:name=".Socket"
            android:exported="false" />

        <service
            android:name=".ServiceMonitoring"
            android:exported="false" />

        <meta-data
            android:name="com.google.android.gms.version"
            android:value="@integer/google_play_services_version" />
        <meta-data
            android:name="com.google.android.geo.API_KEY"
            android:value="@string/google_maps_key" />

        <activity android:name=".Activities.RateMe"></activity>
    </application>

</manifest>


问:
Razor View IF to a partial div
The thing is that Im trying to change background color of a div depending on an IF condition inside a foreach and I didnt wanted to make an entire replication of the code for every single condition(3 conditions actually).

My idea was to do something like:

```<code>@foreach (var item in Model.Models)
{

        @if (item.Status == "COMPLETED")
        {
            <div class="card teal darken-2 white-text">
                }
        @if (item.Status == "NOT STARTED")
                {
             <div class="card grey white-text">
                        }
        @if (item.Status == "RUNNING")
        {
            <div class="card blue white-text">
                }
                <div class="card content">

                </div>

            </div>
     </div>
}
</code>```

But it seems that HTML detects the 3 divs with no closure and it crushes saying that the foreach needs an ending }.

Any ideas?

答:
Your current code is failing because you are trying to mix C# code with plain text.

The if condition opens a C# code block. So if you want to mix plain text or html inside that, you need to use @: prefix. @: tells razor that the following is not C# code, but plain text. It is same as <text></text> tag

You also had an extra closing div.

This should work.

```<code>@foreach (var item in Model.SomeCollection)
{
    if (item.Status == "COMPLETED")
    {
        @:div class="card teal darken-2 white-text">
    }
    if (item.Status == "RUNNING")
    {
        @:div class="card grey white-text">
    }
    <div class="card content">@item.Name</div>
    @:</div>
}
</code>```

I personally prefer to add less C# code inside views. I like to keep my views more Htmly. I would create a separate method which can return the css class you need based on the Status value.

Here is an extension method.

```<code>public static class UiExtensionMethods
{
    public static IHtmlString GetStatusClass(this string item)
    {
        switch (item)
        {
            case "COMPLETED":
                return MvcHtmlString.Create("teal darken-2 white-text");
            case "RUNNING":
                return MvcHtmlString.Create("blue white-text");
            default:
                return MvcHtmlString.Create("gray white-text");
        }
    }
}
</code>```

Now all you have to do is, call this method in your view.

```<code><div>
    @foreach (var item in Model.Tags)
    {
        <div class="card @item.Status.GetStatusClass()">
            <div class="card content">
                @item.Status
            </div>
        </div>
    }
</div>
</code>```

I created the extension method on string. You can create it on more specific type (Your Status class/Status type(enum?)/ The type of each item in your collection.)

Title: Razor View IF to a partial div

Body:
The thing is that Im trying to change background color of a div depending on an IF condition inside a foreach and I didnt wanted to make an entire replication of the code for every single condition(3 conditions actually).

My idea was to do something like:

@foreach (var item in Model.Models)
{

        @if (item.Status == "COMPLETED")
        {

                }
        @if (item.Status == "NOT STARTED")
                {

                        }
        @if (item.Status == "RUNNING")
        {

                }

}

But it seems that HTML detects the 3 divs with no closure and it crushes saying that the foreach needs an ending }.

Any ideas?

Body:
Your current code is failing because you are trying to mix C# code with plain text.

The if condition opens a C# code block. So if you want to mix plain text or html inside that, you need to use @: prefix. @: tells razor that the following is not C# code, but plain text. It is same as <text></text> tag

You also had an extra closing div.

This should work.

@foreach (var item in Model.SomeCollection)
{
    if (item.Status == "COMPLETED")
    {
        @:div class="card teal darken-2 white-text">
    }
    if (item.Status == "RUNNING")
    {
        @:div class="card grey white-text">
    }
    <div class="card content">@item.Name</div>
    @:</div>
}

I personally prefer to add less C# code inside views. I like to keep my views more Htmly. I would create a separate method which can return the css class you need based on the Status value.

Here is an extension method.

public static class UiExtensionMethods
{
    public static IHtmlString GetStatusClass(this string item)
    {
        switch (item)
        {
            case "COMPLETED":
                return MvcHtmlString.Create("teal darken-2 white-text");
            case "RUNNING":
                return MvcHtmlString.Create("blue white-text");
            default:
                return MvcHtmlString.Create("gray white-text");
        }
    }
}

Now all you have to do is, call this method in your view.

<div>
    @foreach (var item in Model.Tags)
    {
        <div class="card @item.Status.GetStatusClass()">
            <div class="card content">
                @item.Status
            </div>
        </div>
    }
</div>

I created the extension method on string. You can create it on more specific type (Your Status class/Status type(enum?)/ The type of each item in your collection.)


问:
Make list of most recurring words in data frame, match and input suggestion(s) column
I have a very huge .csv document (hard to put a similar example) will try to explain here:

I need to use R Studio to look for the most recurring words in all of the columns, after that I want to match the list of recurring words in the category comparing them and choosing the match(es) (even if it matches only part of the category) and then input the matched word(s) in the same row but new column I'm calling "suggested_edit"

Here's a brief example before I state what codes I tried:

```<code>Category       ID       Place1    Place2  **suggested_edit**(i need to add this)

abc-cba bac     123321      bac       N/A   bac
adb- bac bad    213241      N/A       bac   bac
bdl- bdc bdd    613251      N/A       N/A   N/A
ajk- bcd dcx    613251      ddd       bcd   ddd, bcd
abc - bdd fcl   776445      trf       fss   trf, fss
abc - bnc vcc   767544      vcc       qap   vcc
</code>```

and the table is pretty big,

What i tried is this:

```<code>df<- df[order(dfFT$Place1), ]

df$rank <- rank(df$Place1, ties.method = "min")

df <- df[order(df$rank, decreasing = FALSE), ]

install.packages("tm")
</code>```

tried to use the findFreqTerms() command but its returning an error message: no applicable method for 'findMostFreqTerms' applied to an object of class "data.frame"

答:
As per my last comment I am not sure if I understood you correctly, so I have updated you example as I understand it and have changed the "Place2" in the first row to "abc", so that there are two patterns matched. On this basis I have provided an answer based on str_extract from stringi package. I hope this is what you were looking for. I have imported your data as matrix since you have not provided a reproducible example. As long as the specified columns are of type character the solution should also work for data.frame (hopefully, not tested).

```<code>cat("
Category       ID       Place1    Place2  **suggested_edit**

abc-cba bac     123321      bac       abc   bac
adb- bac bad    213241      N/A       bac   bac
bdl- bdc bdd    613251      N/A       N/A   N/A
ajk- bcd dcx    613251      ddd       bcd   ddd, bcd
abc - bdd fcl   776445      trf       fss   trf, fss
abc - bnc vcc   767544      vcc       qap   vcc", file = "tmp.txt")
dat <- read.csv("tmp.txt", sep = "\n")
unlink("tmp.txt")

head <- unlist(strsplit(gsub("\\.+", "#", names(dat)), "#"))
dat <- unname(dat)
dat <- t(apply(dat, 1, function(x) {unlist(strsplit(x, "\\s{2,}"))}))
colnames(dat) <- head
dat[,"suggested_edit"] <- NA
dat
# dat[ dat == "N/A"] <- NA
# Category        ID       Place1 Place2 suggested_edit
# [1,] "abc-cba bac"   "123321" "bac"  NA     NA
# [2,] "adb- bac bad"  "213241" NA     "bac"  NA
# [3,] "bdl- bdc bdd"  "613251" NA     NA     NA
# [4,] "ajk- bcd dcx"  "613251" "ddd"  "bcd"  NA
# [5,] "abc - bdd fcl" "776445" "trf"  "fss"  NA
# [6,] "abc - bnc vcc" "767544" "vcc"  "qap"  NA

library(stringi)
check_edit <- function(mymatrix, categorycolumn, checkcolumns, suggestioncolumn) {

  edit <- t(apply(mymatrix, 1, function(x) {
               unlist(stri_extract_all_fixed(x[categorycolumn], x[checkcolumns]))
            }))

  mymatrix[, suggestioncolumn ] <- apply(edit, 1, function(x) paste(x[ !is.na(x)], collapse = ", "))
  return(mymatrix)
}

check_edit(dat, "Category", c("Place1", "Place2"), "suggested_edit")
# Category        ID       Place1 Place2 suggested_edit
# [1,] "abc-cba bac"   "123321" "bac"  "abc"  "bac, abc"
# [2,] "adb- bac bad"  "213241" "N/A"  "bac"  "bac"
# [3,] "bdl- bdc bdd"  "613251" "N/A"  "N/A"  ""
# [4,] "ajk- bcd dcx"  "613251" "ddd"  "bcd"  "bcd"
# [5,] "abc - bdd fcl" "776445" "trf"  "fss"  ""
# [6,] "abc - bnc vcc" "767544" "vcc"  "qap"  "vcc"
</code>```

Body:
I have a very huge .csv document (hard to put a similar example) will try to explain here:

I need to use R Studio to look for the most recurring words in all of the columns, after that I want to match the list of recurring words in the category comparing them and choosing the match(es) (even if it matches only part of the category) and then input the matched word(s) in the same row but new column I'm calling "suggested_edit"

Here's a brief example before I state what codes I tried:

Category       ID       Place1    Place2  **suggested_edit**(i need to add this)

abc-cba bac     123321      bac       N/A   bac
adb- bac bad    213241      N/A       bac   bac
bdl- bdc bdd    613251      N/A       N/A   N/A
ajk- bcd dcx    613251      ddd       bcd   ddd, bcd
abc - bdd fcl   776445      trf       fss   trf, fss
abc - bnc vcc   767544      vcc       qap   vcc

and the table is pretty big,

What i tried is this:

df<- df[order(dfFT$Place1), ]

df$rank <- rank(df$Place1, ties.method = "min")

df <- df[order(df$rank, decreasing = FALSE), ]

install.packages("tm")

tried to use the findFreqTerms() command but its returning an error message: no applicable method for 'findMostFreqTerms' applied to an object of class "data.frame"

Body:
As per my last comment I am not sure if I understood you correctly, so I have updated you example as I understand it and have changed the "Place2" in the first row to "abc", so that there are two patterns matched. On this basis I have provided an answer based on str_extract from stringi package. I hope this is what you were looking for. I have imported your data as matrix since you have not provided a reproducible example. As long as the specified columns are of type character the solution should also work for data.frame (hopefully, not tested).

cat("
Category       ID       Place1    Place2  **suggested_edit**

abc-cba bac     123321      bac       abc   bac
adb- bac bad    213241      N/A       bac   bac
bdl- bdc bdd    613251      N/A       N/A   N/A
ajk- bcd dcx    613251      ddd       bcd   ddd, bcd
abc - bdd fcl   776445      trf       fss   trf, fss
abc - bnc vcc   767544      vcc       qap   vcc", file = "tmp.txt")
dat <- read.csv("tmp.txt", sep = "\n")
unlink("tmp.txt")

head <- unlist(strsplit(gsub("\\.+", "#", names(dat)), "#"))
dat <- unname(dat)
dat <- t(apply(dat, 1, function(x) {unlist(strsplit(x, "\\s{2,}"))}))
colnames(dat) <- head
dat[,"suggested_edit"] <- NA
dat
# dat[ dat == "N/A"] <- NA
# Category        ID       Place1 Place2 suggested_edit
# [1,] "abc-cba bac"   "123321" "bac"  NA     NA
# [2,] "adb- bac bad"  "213241" NA     "bac"  NA
# [3,] "bdl- bdc bdd"  "613251" NA     NA     NA
# [4,] "ajk- bcd dcx"  "613251" "ddd"  "bcd"  NA
# [5,] "abc - bdd fcl" "776445" "trf"  "fss"  NA
# [6,] "abc - bnc vcc" "767544" "vcc"  "qap"  NA

library(stringi)
check_edit <- function(mymatrix, categorycolumn, checkcolumns, suggestioncolumn) {

  edit <- t(apply(mymatrix, 1, function(x) {
               unlist(stri_extract_all_fixed(x[categorycolumn], x[checkcolumns]))
            }))

  mymatrix[, suggestioncolumn ] <- apply(edit, 1, function(x) paste(x[ !is.na(x)], collapse = ", "))
  return(mymatrix)
}

check_edit(dat, "Category", c("Place1", "Place2"), "suggested_edit")
# Category        ID       Place1 Place2 suggested_edit
# [1,] "abc-cba bac"   "123321" "bac"  "abc"  "bac, abc"
# [2,] "adb- bac bad"  "213241" "N/A"  "bac"  "bac"
# [3,] "bdl- bdc bdd"  "613251" "N/A"  "N/A"  ""
# [4,] "ajk- bcd dcx"  "613251" "ddd"  "bcd"  "bcd"
# [5,] "abc - bdd fcl" "776445" "trf"  "fss"  ""
# [6,] "abc - bnc vcc" "767544" "vcc"  "qap"  "vcc"


问:
Permissions : I don't need user informations
I have just a quesition about facebook api.
I use this code to know if the user is logged on Facebook :

```<code>FB.init({appId: '**********', status: true, cookie: true, xfbml: false});
</code>```

I don't ask permissions. But when I redirect the user with this script :

```<code>if (!response.session) top.location = "https://graph.facebook.com/oauth/authorize?client_id=********&redirect_uri=http://apps.facebook.com/my_apps/";
</code>```

the user is redirect to the Permission Asking page...  But I don't need personnal informations in my application, I just need to verify if the user is logged on Facebook, and redirect it on login page. After he can use my application without permissions. maybe it's impossible... ?

Thanks you

答:
You need to get the user's permission before you can get his login status. Search for login using facebook and use it.

Some facebook components like "Like Button" will have iFrame from facebook, So it can access user's facebook details.

Body:
I have just a quesition about facebook api.
I use this code to know if the user is logged on Facebook :

FB.init({appId: '**********', status: true, cookie: true, xfbml: false});

I don't ask permissions. But when I redirect the user with this script :

if (!response.session) top.location = "https://graph.facebook.com/oauth/authorize?client_id=********&redirect_uri=http://apps.facebook.com/my_apps/";

the user is redirect to the Permission Asking page...  But I don't need personnal informations in my application, I just need to verify if the user is logged on Facebook, and redirect it on login page. After he can use my application without permissions. maybe it's impossible... ?

Thanks you


问:
Keeps using the wrong choice
```<code>    import time
dead = False

ally = input('Ally?: ')
if ally == 'Yes':
    ally = True
else:
    ally = False

User = input('Name?: ')

if not dead and ally:
    print('Sara\'s hand slipped from yours as you came to a fork in the hallways.')
    time.sleep(2)
    print('')
    print('"Quickly! Which road should we take? Right or Left?"')
    pick = input('Which way?!: ')
    if pick == 'Right' or pick == 'right':
        print('')
        print('"Ok, I trust you!"')
        print('')
        time.sleep(1)
        print('She ran towards the right, only to be stopped by a mysterious figure.')
        time.sleep(1)
        print('.')
        time.sleep(1)
        print('.')
        time.sleep(1)
        print('"ɖɨɖ ʏօʊ ȶʀʏ ȶօ ɛֆƈǟքɛ ɦօռɛʏ?~ ȶֆӄ ȶֆӄ~ ȶɦǟȶ աǟֆռ\'ȶ ɨռ ȶɦɛ ƈօռȶʀǟƈȶ"')
        time.sleep(1)
        print('.')
        time.sleep(1)
        print('.')
        time.sleep(0.5)
        print('')
        print('"' + User + '! It\'s the other way! I\'ll take care of this and be right back!"')
        time.sleep(3)
        print('"ʏօʊ ֆօռ օʄ ʄ*** ɨ աօʀӄɛɖ ȶօօ ɦǟʀɖ ʄօʀ ȶɦɨֆ. ʏօʊ ǟʀɛ ɖɛǟɖ ȶօ ʍɛ!"')
        time.sleep(2)
        print('Obeying her orders, you run as fast as your legs could take you.')
        time.sleep(1)
        print('Leaving her behind...')
        time.sleep(3)
        dead = False
        ally = False
    if pick == 'left' or pick == 'Left':
        print('')
        print('"Ok, I trust you!"')
        print('')
        time.sleep(2)
        print('She walked ahead of you, towards the left where the lights flickered.')
        time.sleep(2)
        print('A figure came from the right side as her eyes widened.')
        time.sleep(1)
        print('')
        print('"RUN AND FOLLOW ME"')
        print('')
        time.sleep(2)
        print('You follow her lead into the darkness as you hear a chuckle which'
              ' sends sparks down your spine, running out a door.')
        dead = False
        time.sleep(2)
if not dead and not ally:
    print('You leave the room from before, seeing a fork in the hallway.')
    time.sleep(2)
    print('Which direction do you take?')
    pick = input('Which?: ')
    if pick == 'Right' or pick == 'right':
        print('You decide to take the right path, going down your merry way '
              'as you felt...')
        time.sleep(2)
        print('Cold?')
        time.sleep(3)
        print('A mysterious figure had appeared in front of you covered your nose and '
              'mouth with a cloth containing a sweet smelling liquid')
        time.sleep(2)
        print('Before you went to darkness, you heard them whisper faintly in your ear.')
        time.sleep(0.9)
        print('∑ЯЯ◊Я')
        time.sleep(1)
        print('∑ЯЯ◊Я')
        time.sleep(1)
        print('∑ЯЯ◊Я')
        time.sleep(1)
        print('∑ЯЯ◊Я')
        time.sleep(1)
        print('∑ЯЯ◊Я')
        time.sleep(1)
        print('ㄚ◊ㄩῳ∑Я∑и\'₮ㄅㄩㄕㄕ◊ㄅ∑∂₮◊ﾚ∑∆√∑')
        time.sleep(2)
        print('ㄅｻｻｻ... ﾓ∆ﾚﾚ ∆ㄅﾚ∑∑ㄕ ∂∑∆Я ,' + User + 'ㄚ◊ㄩ ῳ∑Я∑и\'₮ ㄅㄩㄕㄕ◊ㄅ∑∂ ₮◊ ς◊㎡∑ ₮ｻⅰㄅ ﾓ∆Я...')
        time.sleep(5)
        dead = True
    if pick == 'left' or 'Left':
        print('You chose the left path, leading to a door.')
        time.sleep(2)
        print('It was that easy?')
        dead = False
if not dead and ally:
    print('You walk out the door, leading into reality once more.')
    time.sleep(2)
    print('Where was the girl from before?')
    time.sleep(2)
    print('Looking back, you see nothing behind you.')
    time.sleep(2)
    print('So... Was it all a dream??')
    time.sleep(2)
    print('Let\'s hope so.')
    time.sleep(4)
    print('END.')
if not dead and not ally:
    print('You walk out the door, leading into reality once more.')
    time.sleep(2)
    print('You had left her behind...')
    time.sleep(2)
    print('Looking back, you see nothing behind you.')
    time.sleep(2)
    print('So... Was it all a dream?')
    time.sleep(2)
    print('Let\'s hope so.')
    time.sleep(2)
    print('For both of your sakes...')
    time.sleep(4)
    print('END.')
    time.sleep(4)
</code>```

I don't exactly understand why this isn't working. When I have an Ally and go to the right, it decides to do the option that is done without the ally which confuses me. If I don't have an Ally and take the right again, it does the same nonsense.
It only works when I don't have an ally and go to the left, help, please?

答:
When you the time and story, only the game mechanism remains.

I also removed the  dead = False  and  not dead  since it does nothing (you already are alive).

This makes the code look something like:

```<code>dead = False

ally = input("Ally?: ")
if ally == 'Yes':
    ally = True
else:
    ally = False

if ally: # first scene with ally
    pick = input("Which way?: ")
    if pick == 'Right' or pick == 'right':
        ally = False
    if pick == 'Left' or pick == 'left':
        pass

if not ally: # first scene without ally
    pick = input("Which way?: ")
    if pick == 'Right' or pick == 'right':
        pass
    if pick == 'Left' or pick == 'left':
        pass

if ally: # end scene with ally
    print("Option with ally") ## temp statement
    print('End')

if not ally: # end scene without ally
    print("Option without ally") ## temp statement
    print('End')
</code>```

You basically got two parts: an interactive one and an end scene.

This results in the following options:

You have an ally and go to right: go to end scene without ally.

You have an ally and go to left: go to end scene with ally.

You have no ally and go to right: you're dead, no end scene for death.

You have no ally and go to left: go to end scene without ally.

I'm not sure when you say that it doesn't work, what doesn't work, but my guesses are it must be something in the game mechanism. Or else maybe you put a wrong text on the wrong place.

Anyway, hope this helps.

almost forgot:

on line 94 you have  if pick == 'Left' or 'left' , which should be:  if pick == 'Left' or pick == 'left' .

Title: Keeps using the wrong choice

Body:
    import time
dead = False

ally = input('Ally?: ')
if ally == 'Yes':
    ally = True
else:
    ally = False

User = input('Name?: ')

if not dead and ally:
    print('Sara\'s hand slipped from yours as you came to a fork in the hallways.')
    time.sleep(2)
    print('')
    print('"Quickly! Which road should we take? Right or Left?"')
    pick = input('Which way?!: ')
    if pick == 'Right' or pick == 'right':
        print('')
        print('"Ok, I trust you!"')
        print('')
        time.sleep(1)
        print('She ran towards the right, only to be stopped by a mysterious figure.')
        time.sleep(1)
        print('.')
        time.sleep(1)
        print('.')
        time.sleep(1)
        print('"ɖɨɖ ʏօʊ ȶʀʏ ȶօ ɛֆƈǟքɛ ɦօռɛʏ?~ ȶֆӄ ȶֆӄ~ ȶɦǟȶ աǟֆռ\'ȶ ɨռ ȶɦɛ ƈօռȶʀǟƈȶ"')
        time.sleep(1)
        print('.')
        time.sleep(1)
        print('.')
        time.sleep(0.5)
        print('')
        print('"' + User + '! It\'s the other way! I\'ll take care of this and be right back!"')
        time.sleep(3)
        print('"ʏօʊ ֆօռ օʄ ʄ*** ɨ աօʀӄɛɖ ȶօօ ɦǟʀɖ ʄօʀ ȶɦɨֆ. ʏօʊ ǟʀɛ ɖɛǟɖ ȶօ ʍɛ!"')
        time.sleep(2)
        print('Obeying her orders, you run as fast as your legs could take you.')
        time.sleep(1)
        print('Leaving her behind...')
        time.sleep(3)
        dead = False
        ally = False
    if pick == 'left' or pick == 'Left':
        print('')
        print('"Ok, I trust you!"')
        print('')
        time.sleep(2)
        print('She walked ahead of you, towards the left where the lights flickered.')
        time.sleep(2)
        print('A figure came from the right side as her eyes widened.')
        time.sleep(1)
        print('')
        print('"RUN AND FOLLOW ME"')
        print('')
        time.sleep(2)
        print('You follow her lead into the darkness as you hear a chuckle which'
              ' sends sparks down your spine, running out a door.')
        dead = False
        time.sleep(2)
if not dead and not ally:
    print('You leave the room from before, seeing a fork in the hallway.')
    time.sleep(2)
    print('Which direction do you take?')
    pick = input('Which?: ')
    if pick == 'Right' or pick == 'right':
        print('You decide to take the right path, going down your merry way '
              'as you felt...')
        time.sleep(2)
        print('Cold?')
        time.sleep(3)
        print('A mysterious figure had appeared in front of you covered your nose and '
              'mouth with a cloth containing a sweet smelling liquid')
        time.sleep(2)
        print('Before you went to darkness, you heard them whisper faintly in your ear.')
        time.sleep(0.9)
        print('∑ЯЯ◊Я')
        time.sleep(1)
        print('∑ЯЯ◊Я')
        time.sleep(1)
        print('∑ЯЯ◊Я')
        time.sleep(1)
        print('∑ЯЯ◊Я')
        time.sleep(1)
        print('∑ЯЯ◊Я')
        time.sleep(1)
        print('ㄚ◊ㄩῳ∑Я∑и\'₮ㄅㄩㄕㄕ◊ㄅ∑∂₮◊ﾚ∑∆√∑')
        time.sleep(2)
        print('ㄅｻｻｻ... ﾓ∆ﾚﾚ ∆ㄅﾚ∑∑ㄕ ∂∑∆Я ,' + User + 'ㄚ◊ㄩ ῳ∑Я∑и\'₮ ㄅㄩㄕㄕ◊ㄅ∑∂ ₮◊ ς◊㎡∑ ₮ｻⅰㄅ ﾓ∆Я...')
        time.sleep(5)
        dead = True
    if pick == 'left' or 'Left':
        print('You chose the left path, leading to a door.')
        time.sleep(2)
        print('It was that easy?')
        dead = False
if not dead and ally:
    print('You walk out the door, leading into reality once more.')
    time.sleep(2)
    print('Where was the girl from before?')
    time.sleep(2)
    print('Looking back, you see nothing behind you.')
    time.sleep(2)
    print('So... Was it all a dream??')
    time.sleep(2)
    print('Let\'s hope so.')
    time.sleep(4)
    print('END.')
if not dead and not ally:
    print('You walk out the door, leading into reality once more.')
    time.sleep(2)
    print('You had left her behind...')
    time.sleep(2)
    print('Looking back, you see nothing behind you.')
    time.sleep(2)
    print('So... Was it all a dream?')
    time.sleep(2)
    print('Let\'s hope so.')
    time.sleep(2)
    print('For both of your sakes...')
    time.sleep(4)
    print('END.')
    time.sleep(4)

I don't exactly understand why this isn't working. When I have an Ally and go to the right, it decides to do the option that is done without the ally which confuses me. If I don't have an Ally and take the right again, it does the same nonsense.
It only works when I don't have an ally and go to the left, help, please?

Body:
When you the time and story, only the game mechanism remains.

I also removed the  dead = False  and  not dead  since it does nothing (you already are alive).

This makes the code look something like:

dead = False

ally = input("Ally?: ")
if ally == 'Yes':
    ally = True
else:
    ally = False

if ally: # first scene with ally
    pick = input("Which way?: ")
    if pick == 'Right' or pick == 'right':
        ally = False
    if pick == 'Left' or pick == 'left':
        pass

if not ally: # first scene without ally
    pick = input("Which way?: ")
    if pick == 'Right' or pick == 'right':
        pass
    if pick == 'Left' or pick == 'left':
        pass

if ally: # end scene with ally
    print("Option with ally") ## temp statement
    print('End')

if not ally: # end scene without ally
    print("Option without ally") ## temp statement
    print('End')

You basically got two parts: an interactive one and an end scene.

This results in the following options:

You have an ally and go to right: go to end scene without ally.

You have an ally and go to left: go to end scene with ally.

You have no ally and go to right: you're dead, no end scene for death.

You have no ally and go to left: go to end scene without ally.

I'm not sure when you say that it doesn't work, what doesn't work, but my guesses are it must be something in the game mechanism. Or else maybe you put a wrong text on the wrong place.

Anyway, hope this helps.

almost forgot:

on line 94 you have  if pick == 'Left' or 'left' , which should be:  if pick == 'Left' or pick == 'left' .


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

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

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

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

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

}
</code>```

}

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

however the current format is:
"First Name: "

Any advice would be much appreciated

答:
Note: this is not the best solution, but I just want you to see what's wrong with your original code and how to correct it in case you see similar problems in the future. Please see other answers for most efficient ways to accomplish the task.

When you initialized the array, the values for all the variables you wanted to print are empty strings.

```<code>String fname ="", lname="", add="", city="", country="", post="", id="", grd = "";
</code>```

What you need to do if you want to keep using your current method, is to update the variables with actual values within the for loop.

Like this:

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

        for (int j = 0; j < 8; j++)
        {
            Console.WriteLine(index[0, i] + index[1,j]);
        }
    }
    Console.WriteLine("");
}
</code>```

Title: Print string values in object list

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

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

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

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

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

}

}

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

however the current format is:
"First Name: "

Any advice would be much appreciated

Body:
Note: this is not the best solution, but I just want you to see what's wrong with your original code and how to correct it in case you see similar problems in the future. Please see other answers for most efficient ways to accomplish the task.

When you initialized the array, the values for all the variables you wanted to print are empty strings.

String fname ="", lname="", add="", city="", country="", post="", id="", grd = "";

What you need to do if you want to keep using your current method, is to update the variables with actual values within the for loop.

Like this:

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

        for (int j = 0; j < 8; j++)
        {
            Console.WriteLine(index[0, i] + index[1,j]);
        }
    }
    Console.WriteLine("");
}


问:
How to write a command line C# program that posts to Twitter
I'd like to write a console program in C# that posts a Tweet to Twitter.  I've never used the Twitter APIs before and don't know anything about how their authentication works.  I found an API library called Twitterizer, but it seems geared towards web applications and wants the user to logon with a web browser.  All the API docs on Twitter's website seems geared around this scenario as well.

Is it possible to access the Twitter APIs using a console app with no web browser access?  I'm perfectly fine hard coding in the name and password for the Twitter user I want to post under as well.  Thanks!

Mike

答:
Also take a loot at linq2twitter lib. From it's documentation;

The Twitter API is built using
  Representable State Transfer (REST).
  Wikipaedia defines REST as "...a style
  of software architecture for
  distributed hypermedia systems...",
  but I'm going to be so bold as to try
  to simplify what that means. In
  practice, REST is a Web service
  protocol built upon Hypertext Transfer
  Protocol (HTTP). You use the REST Web
  service by making an HTTP call with a
  URL and getting text back in some
  form, which is often XML or JSON. So,
  if you were to write code that made an
  HTTP request with the following URL:

http://api.twitter.com/1/statuses/public_timeline.xml

You would get back an XML document
  with all of the Twitter statuses from
  the public timeline, which is a
  snapshot in time of the last 20 tweets
  at the time of your request. Go ahead
  and open your browser, copy and paste
  the URL above into the address bar,
  and see what you get back.


问:
FileSystemWatcher cannot access files because used in other process
I'm writing a FileSystemWatcher which is to copy images from folder A to folder B, whenever an image is uploaded to folder A. I'm trying to use this as a windows service on the server PC but I'm having some issues where my files are locked when they are to be copied. I think I've found the root to my issue, but I'm not having any luck solving it. So, when I run my windows service it always ends unexpectedly at either the first or the second picture upload. The error message I'm getting says this: The process cannot access the file 'filepath' because it is being used by another process.

Relevant parts of my code:

```<code>public void WatchForChanges()
{
    FileSystemWatcher watcher = new FileSystemWatcher();
    watcher.Path = Program.SourceFolder;
    watcher.Created += new FileSystemEventHandler(OnImageAdded);
    watcher.EnableRaisingEvents = true;
    watcher.IncludeSubdirectories = true;
}

public void OnImageAdded(object source, FileSystemEventArgs e)
{
    FileInfo file = new FileInfo(e.FullPath);
    ImageHandler handler = new ImageHandler();
    if (handler.IsImage(file))
    {
        handler.CopyImage(file);
    }
}
</code>```

and, my CopyImage method, which includes one of my proposed solutions to this problem, utilizing a while loop that catches the error and retries the copying of the image:

```<code>public void CopyImage(FileSystemInfo file)
{
    // code that sets folder paths
    // code that sets folder paths

    bool retry = true;
    if (!Directory.Exists(targetFolderPath))
    {
        Directory.CreateDirectory(targetFolderPath);
    }
    while (retry)
    {
        try
        {
            File.Copy(file.FullName, targetPath, true);
            retry = false;
        }
        catch (Exception e)
        {
            Thread.Sleep(2000);
        }
    }
}
</code>```

but this CopyImage solution just keeps on copying the same file, which is not very ideal in my case. I wish it was enough but sadly I've got a queue of images waiting.

答:
While it seems straightforward, it's really unsatisfactorily complex.

The problem is, the application that's writing the file isn't done with it when you get the notification...and so you have a concurrency problem. There is no great way to know when the file closes. Well..one way is to subscribe to journal events - which is what FileSystemWatcher does - but this is fairly involved and requires a lot of moving parts. Going this route, you can be notified when the file closes. If you're interested, see https://msdn.microsoft.com/en-us/library/windows/desktop/aa363798(v=vs.85).aspx.

I'd divide the work into two parts. I think I'd start a ThreadPool thread to do the work, and have it read it's work from a list that the FileSystemWatcher's event handler writes to. That way, the event handler returns quickly. The ThreadPool thread would go through it's list, attempting to get an exclusive lock (similar to Tommaso's code) on the file. If it can't, it just moves on to the next file. Every time it successfully copies, it removes that file from the list.

You need to be concerned about thread safety...so you'd want to make a static object to coordinate writes to the list. Both the event handler and the ThreadPool thread would hold the lock while writing.

Here's a scaffold of the whole approach:

```<code>internal sealed class Copier: IDisposable
{
  static object sync = new object();
  bool quit;
  FileSystemWatcher watcher;
  List<string> work;

  internal Copier( string pathToWatch )
  {
    work = new List<string>();
    watcher = new FileSystemWatcher();
    watcher.Path = pathToWatch;
    watcher.Create += QueueWork;
    ThreadPool.QueueUserWorkItem( TryCopy );
  }

  void Dispose()
  {
    lock( sync ) quit = true;
  }

  void QueueWork( object source, FileSystemEventArgs args )
  {
    lock ( sync )
    {
      work.Add( args.FullPath );
    }
  }

  void TryCopy( object args )
  {
    List<string> localWork;
    while( true )
    {
      lock ( sync )
      {
        if ( quit ) return;  //--> we've been disposed
        localWork = new List<string>( work );
      }
      foreach( var fileName in localWork )
      {
        var locked = true;
        try
        {
          using
          ( var throwAway = new FileStream
            ( fileName,
              FileMode.Open,
              FileAccess.Read,
              FileShare.None
            )
          ); //--> no-op  - will throw if we can't get exclusive read
          locked = false;
        }
        catch { }
        if (!locked )
        {
          File.Copy( fileName, ... );
          lock( sync ) work.Remove( fileName );
        }
      }
    }
  }
}
</code>```

Not tested - wrote it right here in the answer...but it, or something like it will cover the bases.

Body:
I'm writing a FileSystemWatcher which is to copy images from folder A to folder B, whenever an image is uploaded to folder A. I'm trying to use this as a windows service on the server PC but I'm having some issues where my files are locked when they are to be copied. I think I've found the root to my issue, but I'm not having any luck solving it. So, when I run my windows service it always ends unexpectedly at either the first or the second picture upload. The error message I'm getting says this: The process cannot access the file 'filepath' because it is being used by another process.

Relevant parts of my code:

public void WatchForChanges()
{
    FileSystemWatcher watcher = new FileSystemWatcher();
    watcher.Path = Program.SourceFolder;
    watcher.Created += new FileSystemEventHandler(OnImageAdded);
    watcher.EnableRaisingEvents = true;
    watcher.IncludeSubdirectories = true;
}

public void OnImageAdded(object source, FileSystemEventArgs e)
{
    FileInfo file = new FileInfo(e.FullPath);
    ImageHandler handler = new ImageHandler();
    if (handler.IsImage(file))
    {
        handler.CopyImage(file);
    }
}

and, my CopyImage method, which includes one of my proposed solutions to this problem, utilizing a while loop that catches the error and retries the copying of the image:

public void CopyImage(FileSystemInfo file)
{
    // code that sets folder paths
    // code that sets folder paths

    bool retry = true;
    if (!Directory.Exists(targetFolderPath))
    {
        Directory.CreateDirectory(targetFolderPath);
    }
    while (retry)
    {
        try
        {
            File.Copy(file.FullName, targetPath, true);
            retry = false;
        }
        catch (Exception e)
        {
            Thread.Sleep(2000);
        }
    }
}

but this CopyImage solution just keeps on copying the same file, which is not very ideal in my case. I wish it was enough but sadly I've got a queue of images waiting.

Body:
While it seems straightforward, it's really unsatisfactorily complex.

The problem is, the application that's writing the file isn't done with it when you get the notification...and so you have a concurrency problem. There is no great way to know when the file closes. Well..one way is to subscribe to journal events - which is what FileSystemWatcher does - but this is fairly involved and requires a lot of moving parts. Going this route, you can be notified when the file closes. If you're interested, see https://msdn.microsoft.com/en-us/library/windows/desktop/aa363798(v=vs.85).aspx.

I'd divide the work into two parts. I think I'd start a ThreadPool thread to do the work, and have it read it's work from a list that the FileSystemWatcher's event handler writes to. That way, the event handler returns quickly. The ThreadPool thread would go through it's list, attempting to get an exclusive lock (similar to Tommaso's code) on the file. If it can't, it just moves on to the next file. Every time it successfully copies, it removes that file from the list.

You need to be concerned about thread safety...so you'd want to make a static object to coordinate writes to the list. Both the event handler and the ThreadPool thread would hold the lock while writing.

Here's a scaffold of the whole approach:

internal sealed class Copier: IDisposable
{
  static object sync = new object();
  bool quit;
  FileSystemWatcher watcher;
  List<string> work;

  internal Copier( string pathToWatch )
  {
    work = new List<string>();
    watcher = new FileSystemWatcher();
    watcher.Path = pathToWatch;
    watcher.Create += QueueWork;
    ThreadPool.QueueUserWorkItem( TryCopy );
  }

  void Dispose()
  {
    lock( sync ) quit = true;
  }

  void QueueWork( object source, FileSystemEventArgs args )
  {
    lock ( sync )
    {
      work.Add( args.FullPath );
    }
  }

  void TryCopy( object args )
  {
    List<string> localWork;
    while( true )
    {
      lock ( sync )
      {
        if ( quit ) return;  //--> we've been disposed
        localWork = new List<string>( work );
      }
      foreach( var fileName in localWork )
      {
        var locked = true;
        try
        {
          using
          ( var throwAway = new FileStream
            ( fileName,
              FileMode.Open,
              FileAccess.Read,
              FileShare.None
            )
          ); //--> no-op  - will throw if we can't get exclusive read
          locked = false;
        }
        catch { }
        if (!locked )
        {
          File.Copy( fileName, ... );
          lock( sync ) work.Remove( fileName );
        }
      }
    }
  }
}

Not tested - wrote it right here in the answer...but it, or something like it will cover the bases.


问:
Is possible to concatenate multible fields with one that is a conditional iif statement
I'm working on an ssrs report using Report builder 2008, currently trying to concatenate using something like this but when I do so, I receive an error for the field 'lifeamount' specifying that the expression can only refer to fields within the current dataset scope. I've tried different ways to specify the dataset which is the same for all the fields but to no avail. Is this even possible?

=rtrim(First(Fields!FRSTNAME.Value,"EmployeeInfo")) & " " & rtrim(First(Fields!MIDLNAME.Value, "EmployeeInfo")) & " " & rtrim(First(Fields!LASTNAME.Value, "EmployeeInfo")) & " " & IIF((Fields!Lifeamount.Value)> 100000.00, 100000.00, Fields!lifeamount.value, "EmployeeInfo"))

答:
SSRS expressions are case sensitive which means that your second lifeamount reference is more than likely wrong.

Try this instead:

```<code>=rtrim(First(Fields!FRSTNAME.Value,"EmployeeInfo")) & " " &
rtrim(First(Fields!MIDLNAME.Value, "EmployeeInfo")) & " " &
rtrim(First(Fields!LASTNAME.Value, "EmployeeInfo")) & " " &
IIF((Fields!Lifeamount.Value)> 100000.00, 100000.00, Fields!Lifeamount.value, "EmployeeInfo"))
</code>```

Body:
SSRS expressions are case sensitive which means that your second lifeamount reference is more than likely wrong.

Try this instead:

=rtrim(First(Fields!FRSTNAME.Value,"EmployeeInfo")) & " " &
rtrim(First(Fields!MIDLNAME.Value, "EmployeeInfo")) & " " &
rtrim(First(Fields!LASTNAME.Value, "EmployeeInfo")) & " " &
IIF((Fields!Lifeamount.Value)> 100000.00, 100000.00, Fields!Lifeamount.value, "EmployeeInfo"))


问:
Java generics - Map of (typed) maps
I'm working on a (simple) caching solution of sorts, where a service can request a Cache object from a Map of caches. A Cache object works essentially just like a Map, too, with a key and a value and methods to access and store objects.

I came up with the following solution, but as you can see, it contains a cast (because get() can't know what the types of the nested object are supposed to be).

```<code>private final  Map<String, Cache<?, ?>> caches = new HashMap<String, Cache<?, ?>>();

public <K, V> Cache<K, V> getOrCreateCache(String identifier) {
    if (caches.containsKey(identifier)) {
        return (Cache<K, V>) caches.get(identifier);
    } else {
        Cache<K, V> cache = new CacheImpl<K, V>();
        caches.put(identifier, cache);
        return cache;
    }
}

private void test() {
    Cache<String, String> strCache = getOrCreateCache("string cache");
    strCache.set("key", "value");
}
</code>```

Now, my questions:

Is this a 'safe' approach, as long as classcastexceptions are handled properly? (probably going to catch those and pack them into a custom exception class)

Is there a 'safe' alternative? One with generics, if at all possible, because I like them and dislike casts.

(not directly related) Is this threadsafe? I assume not, but then, I'm no threading expert. Is it enough to just make the whole method synchronized, or would that (with half a dozen clients) cause too much overhead / locking? Is there a neat solution for that?

Edit: Woo, lots of answers, thanks! Editing here to describe an oddity I found while actually testing this:

```<code>    Cache<String, String> someCache = service.getOrCreateCache(cacheIdentifier);
    someCache.set("asdf", "sdfa");
    Cache<String, Integer> someCacheRetrievedAgain = service.getOrCreateCache(cacheIdentifier);
    System.out.println(someCacheRetrievedAgain.get("asdf")); // prints "sdfa". No errors whatsoever. Odd.
</code>```

答:
You can just make the whole method synchornized to make it thread safe. Provided its not called often it will be efficient enough.  If you want to make the code safer I suggest you try the following add a runtime check for the types.</p>

```<code>public <K, V> Cache<K, V> getOrCreateCache(String identifier, Class<K> kClass, Class<V> vClass) {
    Cache<K, V> cache = (Cache<K, V>) caches.get(identifier);
    if(cache == null)
        caches.put(identifier, cache = new CacheImpl<K, V>(kClass, vClass));
    assert cache.kClass() == kClass;
    assert cache.vClass() == vClass;
    return cache;
}
</code>```

Title: Java generics - Map of (typed) maps

Body:
I'm working on a (simple) caching solution of sorts, where a service can request a Cache object from a Map of caches. A Cache object works essentially just like a Map, too, with a key and a value and methods to access and store objects.

I came up with the following solution, but as you can see, it contains a cast (because get() can't know what the types of the nested object are supposed to be).

private final  Map<String, Cache<?, ?>> caches = new HashMap<String, Cache<?, ?>>();

public <K, V> Cache<K, V> getOrCreateCache(String identifier) {
    if (caches.containsKey(identifier)) {
        return (Cache<K, V>) caches.get(identifier);
    } else {
        Cache<K, V> cache = new CacheImpl<K, V>();
        caches.put(identifier, cache);
        return cache;
    }
}

private void test() {
    Cache<String, String> strCache = getOrCreateCache("string cache");
    strCache.set("key", "value");
}

Now, my questions:

Is this a 'safe' approach, as long as classcastexceptions are handled properly? (probably going to catch those and pack them into a custom exception class)

Is there a 'safe' alternative? One with generics, if at all possible, because I like them and dislike casts.

(not directly related) Is this threadsafe? I assume not, but then, I'm no threading expert. Is it enough to just make the whole method synchronized, or would that (with half a dozen clients) cause too much overhead / locking? Is there a neat solution for that?

Edit: Woo, lots of answers, thanks! Editing here to describe an oddity I found while actually testing this:

    Cache<String, String> someCache = service.getOrCreateCache(cacheIdentifier);
    someCache.set("asdf", "sdfa");
    Cache<String, Integer> someCacheRetrievedAgain = service.getOrCreateCache(cacheIdentifier);
    System.out.println(someCacheRetrievedAgain.get("asdf")); // prints "sdfa". No errors whatsoever. Odd.

Body:
You can just make the whole method synchornized to make it thread safe. Provided its not called often it will be efficient enough.  If you want to make the code safer I suggest you try the following add a runtime check for the types.

public <K, V> Cache<K, V> getOrCreateCache(String identifier, Class<K> kClass, Class<V> vClass) {
    Cache<K, V> cache = (Cache<K, V>) caches.get(identifier);
    if(cache == null)
        caches.put(identifier, cache = new CacheImpl<K, V>(kClass, vClass));
    assert cache.kClass() == kClass;
    assert cache.vClass() == vClass;
    return cache;
}


问:
How can I check if a string is a valid number?
I'm hoping there's something in the same conceptual space as the old VB6 IsNumeric() function?

答:
You could make use of types, like with the flow library, to get static, compile time checking.  Of course not terribly useful for user input.</p>

```<code>// @flow

function acceptsNumber(value: number) {
  // ...
}

acceptsNumber(42);       // Works!
acceptsNumber(3.14);     // Works!
acceptsNumber(NaN);      // Works!
acceptsNumber(Infinity); // Works!
acceptsNumber("foo");    // Error!
</code>```

Body:
You could make use of types, like with the flow library, to get static, compile time checking.  Of course not terribly useful for user input.

// @flow

function acceptsNumber(value: number) {
  // ...
}

acceptsNumber(42);       // Works!
acceptsNumber(3.14);     // Works!
acceptsNumber(NaN);      // Works!
acceptsNumber(Infinity); // Works!
acceptsNumber("foo");    // Error!


问:
MyBatis - How to transform data before saving to DB table
I'm using MyBatis to save data to SQLite database in simple Java application. Is it possible to configure MyBatis to perform data transformation in communication between Java class and DB table?

For example, I have java.util.Date object in my Java class and I want to save it as number (Unix time). Another example: in Java class I have a BigDecimal number which I want to store as text (I don't want to loose any precision).

In Java objects, I use appropriate getters and setters to convert such data, but I don't see any possibilities to specify them in MyBatis .xml files.

To sum up, my questions:

1. Can I use Java getters and setters in MyBatis Result Map? If yes, than how?

2. How to properly store complex data (such as Dates and BigDecimals) in DB via MyBatis?

答:
I'm pretty sure the 'bind' element of mybatis could save you the trouble

```<code><select id="selectBlogsLike" resultType="Blog">
  <bind name="pattern" value="'%' + _parameter.getTitle() + '%'" />
  SELECT * FROM BLOG
  WHERE title LIKE #{pattern}
</select>
</code>```

In this case, it's using the getter and concatenating %. In your case, you can make simple transformations there.

http://www.mybatis.org/mybatis-3/dynamic-sql.html

Body:
I'm pretty sure the 'bind' element of mybatis could save you the trouble

<select id="selectBlogsLike" resultType="Blog">
  <bind name="pattern" value="'%' + _parameter.getTitle() + '%'" />
  SELECT * FROM BLOG
  WHERE title LIKE #{pattern}
</select>

In this case, it's using the getter and concatenating %. In your case, you can make simple transformations there.

http://www.mybatis.org/mybatis-3/dynamic-sql.html


问:
Alternative of sp_depends in Azure Data Warehouse
I need to get the list of tables used in a stored procedure,However in Azure Datawarehouse sp_depends is not supported.

The other alternative I thought of having is to get the stored proc code from INFORMATION_SCHEMA.ROUTINES and then run a script to get the [schema].[tablename] from the stored procedure definition but here the issue is in storing the whole stored proc into a variable. VARCHAR(MAX)has a limit of 8000 to store and if my proc exceeds this limit then I wont be able to get the complete table list.

答:
Try using sys.sql_expression_dependencies. The following query may help you:</p>

```<code>SELECT ReferencingObjectType = o1.type,
       ReferencingObject = SCHEMA_NAME(o1.schema_id)+'.'+o1.name,
       ReferencedObject = SCHEMA_NAME(o2.schema_id)+'.'+ed.referenced_entity_name,
       ReferencedObjectType = o2.type
FROM   sys.sql_expression_dependencies ed
       INNER JOIN  sys.objects o1
         ON ed.referencing_id = o1.object_id
       INNER JOIN sys.objects o2
         ON ed.referenced_id = o2.object_id
WHERE o1.type in ('P','TR','V', 'TF')
ORDER BY ReferencingObjectType, ReferencingObject
</code>```

Body:
Try using sys.sql_expression_dependencies. The following query may help you:

SELECT ReferencingObjectType = o1.type,
       ReferencingObject = SCHEMA_NAME(o1.schema_id)+'.'+o1.name,
       ReferencedObject = SCHEMA_NAME(o2.schema_id)+'.'+ed.referenced_entity_name,
       ReferencedObjectType = o2.type
FROM   sys.sql_expression_dependencies ed
       INNER JOIN  sys.objects o1
         ON ed.referencing_id = o1.object_id
       INNER JOIN sys.objects o2
         ON ed.referenced_id = o2.object_id
WHERE o1.type in ('P','TR','V', 'TF')
ORDER BY ReferencingObjectType, ReferencingObject


问:
R package Reporters can't set height and width of a new paragraph
I'm trying to add a paragraph in an pptx object in R using ReporteRs, but I can't set the height and the width even when using the right arguments.

For example :

```<code>doc = pptx()

doc <- addSlide(doc, "Slide")

doc <- addParagraph(doc,"ok",height=2,width=2,offx = 0,offy = 0)

writeDoc(doc, "test.pptx" )
</code>```

Anyone manage to get a paragraph with custom sizes ?

Thank you

答:
The following should solve your issue</p>

```<code>library(ReporteRs)
doc = pptx()
doc <- addSlide(doc, "Title and Content")
doc <- addParagraph(doc,
                    pot("ok"),
                    par.properties = parProperties(),height=2,width=2,offx = 0,offy = 0)
writeDoc(doc, "test.pptx" )
</code>```

Body:
I'm trying to add a paragraph in an pptx object in R using ReporteRs, but I can't set the height and the width even when using the right arguments.

For example :

doc = pptx()

doc <- addSlide(doc, "Slide")

doc <- addParagraph(doc,"ok",height=2,width=2,offx = 0,offy = 0)

writeDoc(doc, "test.pptx" )

Anyone manage to get a paragraph with custom sizes ?

Thank you

Body:
The following should solve your issue

library(ReporteRs)
doc = pptx()
doc <- addSlide(doc, "Title and Content")
doc <- addParagraph(doc,
                    pot("ok"),
                    par.properties = parProperties(),height=2,width=2,offx = 0,offy = 0)
writeDoc(doc, "test.pptx" )