问:
PHP MySql: update table with value of an array combine
I have the following array

```<code>Array
(
["1074d0"] => "160.16"
["19f726"] => "234.32"
["1072ba"] => "256.88"
["183444"] => "325.42"
["1071bf"] => "342.22"
["112438"] => "353.30"
["1b326e"] => "365.78"
["15d8ab"] => "372.84"
["19d885"] => "395.72"
["193e61"] => "478.66"
["10aab2"] => "503.36"
["107155"] => "543.39"
["110669"] => "584.61"
["189b95"] => "584.61"
["16d78f"] => "597.70"
["18dd7d"] => "601.63"
["110851"] => "601.63"

)
</code>```

obtained with the following code (with the help of a user):

```<code>$codici_hotel_arr = $codici_price_arr = [];
foreach($data_destin['results'] as $key=>$val) {
$codici_hotel_arr[] = '"' . $val['hotel_code'] . '"';
$codici_price_arr[] = '"' . $val['products'][0]['price'] . '"'; }
$result = array_combine($codici_hotel_arr,$codici_price_arr);
print '```';
print_r($result);
print '```';
</code>```

Now I would like to update the values of a table, through a foreach; more precisely, I should do something like that:

UPDATE table_demo SET price="160.16" WHERE id = "1074d0";

UPDATE table_demo SET price="234.32" WHERE id = "19f726";

UPDATE table_demo SET price="256.88" WHERE id = "1072ba";

etc....

答:
Well, here is my version. It has error reporting and internal reporting functions activated. The code prepares an UPDATE statement. This preparation is needed, in order to avoid SQL injection. To the statement's markers (?) are binded two binding variables ($bindPrice & $bindCode). Further, the array is looped through. In each iteration step the current array values ($price & $code) are assigned to the binded variables, and the statement is executed. At last the prepared statement is closed.

```<code><?php

// Db configs.
define('HOST', 'localhost');
define('PORT', 3306);
define('DATABASE', 'dbname');
define('USERNAME', 'user');
define('PASSWORD', 'pass');

// Error reporting.
error_reporting(E_ALL);
ini_set('display_errors', 1); // Set it to 0 on a live server!

/**
 * Enable internal report functions. This enables the exception handling,
 * e.g. mysqli will not throw PHP warnings anymore, but mysqli exceptions
 * (mysqli_sql_exception). They are catched in the try-catch block.
 *
 * MYSQLI_REPORT_ERROR: Report errors from mysqli function calls.
 * MYSQLI_REPORT_STRICT: Throw a mysqli_sql_exception for errors instead of warnings.
 *
 * See: http://php.net/manual/en/class.mysqli-driver.php
 * See: http://php.net/manual/en/mysqli-driver.report-mode.php
 * See: http://php.net/manual/en/mysqli.constants.php
 */
$mysqliDriver = new mysqli_driver();
$mysqliDriver->report_mode = (MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

$codePricesArray = [
    "1074d0" => "160.16",
    "19f726" => "234.32",
    "1072ba" => "256.88",
    "183444" => "325.42",
    "1071bf" => "342.22",
    "112438" => "353.30",
    "1b326e" => "365.78",
    "15d8ab" => "372.84",
    "19d885" => "395.72",
    "193e61" => "478.66",
    "10aab2" => "503.36",
    "107155" => "543.39",
    "110669" => "584.61",
    "189b95" => "584.61",
    "16d78f" => "597.70",
    "18dd7d" => "601.63",
    "110851" => "601.63",
];

/**
 * Create a new db connection.
 *
 * @see http://php.net/manual/en/mysqli.construct.php
 */
$connection = new mysqli(HOST, USERNAME, PASSWORD, DATABASE, PORT);

/*
 * The SQL statement to be prepared. Notice the so-called markers,
 * e.g. the "?" signs. They will be replaced later with the
 * corresponding values when using mysqli_stmt::bind_param.
 *
 * See: http://php.net/manual/en/mysqli.prepare.php
 */
$sql = 'UPDATE `table_demo` SET price = ? WHERE code = ?';

/*
 * Prepare the SQL statement for execution - ONLY ONCE.
 *
 * See: http://php.net/manual/en/mysqli.prepare.php
 */
$statement = $connection->prepare($sql);

/*
 * Bind variables for the parameter markers (?) in the
 * SQL statement that was passed to prepare(). The first
 * argument of bind_param() is a string that contains one
 * or more characters which specify the types for the
 * corresponding bind variables.
 *
 * See: http://php.net/manual/en/mysqli-stmt.bind-param.php
 */
$statement->bind_param('ds', $bindPrice, $bindCode);

foreach ($codePricesArray as $code => $price) {
    // Assign iteration values ($code, $price) to the binded variables ($bindCode, $bindPrice).
    $bindPrice = $price;
    $bindCode = $code;

    /*
     * Execute the prepared SQL statement.
     * When executed, any parameter markers which exist ("?") will
     * automatically be replaced with the appropriate data of the
     * binded variables.
     *
     * See: http://php.net/manual/en/mysqli-stmt.execute.php
     */
    $executed = $statement->execute();
}

/*
 * Close the prepared statement. It also deallocates the statement handle.
 * If the statement has pending or unread results, it cancels them
 * so that the next query can be executed.
 *
 * See: http://php.net/manual/en/mysqli-stmt.close.php
 */
$statementClosed = $statement->close();
</code>```

I used the following table structure:

```<code>CREATE TABLE `table_demo` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `code` varchar(100) DEFAULT NULL,
  `price` double DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;
</code>```

Notice the fact, that the id column is an integer column, primary key and autoincremented. It does NOT contain the hotel codes, because, for multiple reasons, it is not a good idea to save strings in a data identification column (like id). That's why I created a column code for the hotel codes.

Good luck.

P.S: Since you were speaking only about updating data, I provided a solution involving only this operation type.

Body:
I have the following array

Array
(
["1074d0"] => "160.16"
["19f726"] => "234.32"
["1072ba"] => "256.88"
["183444"] => "325.42"
["1071bf"] => "342.22"
["112438"] => "353.30"
["1b326e"] => "365.78"
["15d8ab"] => "372.84"
["19d885"] => "395.72"
["193e61"] => "478.66"
["10aab2"] => "503.36"
["107155"] => "543.39"
["110669"] => "584.61"
["189b95"] => "584.61"
["16d78f"] => "597.70"
["18dd7d"] => "601.63"
["110851"] => "601.63"

)

obtained with the following code (with the help of a user):

$codici_hotel_arr = $codici_price_arr = [];
foreach($data_destin['results'] as $key=>$val) {
$codici_hotel_arr[] = '"' . $val['hotel_code'] . '"';
$codici_price_arr[] = '"' . $val['products'][0]['price'] . '"'; }
$result = array_combine($codici_hotel_arr,$codici_price_arr);
print '
';
print_r($result);
print '
';

Now I would like to update the values of a table, through a foreach; more precisely, I should do something like that:

UPDATE table_demo SET price="160.16" WHERE id = "1074d0";

UPDATE table_demo SET price="234.32" WHERE id = "19f726";

UPDATE table_demo SET price="256.88" WHERE id = "1072ba";

etc....

Body:
Well, here is my version. It has error reporting and internal reporting functions activated. The code prepares an UPDATE statement. This preparation is needed, in order to avoid SQL injection. To the statement's markers (?) are binded two binding variables ($bindPrice & $bindCode). Further, the array is looped through. In each iteration step the current array values ($price & $code) are assigned to the binded variables, and the statement is executed. At last the prepared statement is closed.

<?php

// Db configs.
define('HOST', 'localhost');
define('PORT', 3306);
define('DATABASE', 'dbname');
define('USERNAME', 'user');
define('PASSWORD', 'pass');

// Error reporting.
error_reporting(E_ALL);
ini_set('display_errors', 1); // Set it to 0 on a live server!

/**
 * Enable internal report functions. This enables the exception handling,
 * e.g. mysqli will not throw PHP warnings anymore, but mysqli exceptions
 * (mysqli_sql_exception). They are catched in the try-catch block.
 *
 * MYSQLI_REPORT_ERROR: Report errors from mysqli function calls.
 * MYSQLI_REPORT_STRICT: Throw a mysqli_sql_exception for errors instead of warnings.
 *
 * See: http://php.net/manual/en/class.mysqli-driver.php
 * See: http://php.net/manual/en/mysqli-driver.report-mode.php
 * See: http://php.net/manual/en/mysqli.constants.php
 */
$mysqliDriver = new mysqli_driver();
$mysqliDriver->report_mode = (MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

$codePricesArray = [
    "1074d0" => "160.16",
    "19f726" => "234.32",
    "1072ba" => "256.88",
    "183444" => "325.42",
    "1071bf" => "342.22",
    "112438" => "353.30",
    "1b326e" => "365.78",
    "15d8ab" => "372.84",
    "19d885" => "395.72",
    "193e61" => "478.66",
    "10aab2" => "503.36",
    "107155" => "543.39",
    "110669" => "584.61",
    "189b95" => "584.61",
    "16d78f" => "597.70",
    "18dd7d" => "601.63",
    "110851" => "601.63",
];

/**
 * Create a new db connection.
 *
 * @see http://php.net/manual/en/mysqli.construct.php
 */
$connection = new mysqli(HOST, USERNAME, PASSWORD, DATABASE, PORT);

/*
 * The SQL statement to be prepared. Notice the so-called markers,
 * e.g. the "?" signs. They will be replaced later with the
 * corresponding values when using mysqli_stmt::bind_param.
 *
 * See: http://php.net/manual/en/mysqli.prepare.php
 */
$sql = 'UPDATE `table_demo` SET price = ? WHERE code = ?';

/*
 * Prepare the SQL statement for execution - ONLY ONCE.
 *
 * See: http://php.net/manual/en/mysqli.prepare.php
 */
$statement = $connection->prepare($sql);

/*
 * Bind variables for the parameter markers (?) in the
 * SQL statement that was passed to prepare(). The first
 * argument of bind_param() is a string that contains one
 * or more characters which specify the types for the
 * corresponding bind variables.
 *
 * See: http://php.net/manual/en/mysqli-stmt.bind-param.php
 */
$statement->bind_param('ds', $bindPrice, $bindCode);

foreach ($codePricesArray as $code => $price) {
    // Assign iteration values ($code, $price) to the binded variables ($bindCode, $bindPrice).
    $bindPrice = $price;
    $bindCode = $code;

    /*
     * Execute the prepared SQL statement.
     * When executed, any parameter markers which exist ("?") will
     * automatically be replaced with the appropriate data of the
     * binded variables.
     *
     * See: http://php.net/manual/en/mysqli-stmt.execute.php
     */
    $executed = $statement->execute();
}

/*
 * Close the prepared statement. It also deallocates the statement handle.
 * If the statement has pending or unread results, it cancels them
 * so that the next query can be executed.
 *
 * See: http://php.net/manual/en/mysqli-stmt.close.php
 */
$statementClosed = $statement->close();

I used the following table structure:

CREATE TABLE `table_demo` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `code` varchar(100) DEFAULT NULL,
  `price` double DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;

Notice the fact, that the id column is an integer column, primary key and autoincremented. It does NOT contain the hotel codes, because, for multiple reasons, it is not a good idea to save strings in a data identification column (like id). That's why I created a column code for the hotel codes.

Good luck.

P.S: Since you were speaking only about updating data, I provided a solution involving only this operation type.


来源: stackexchange

问:
Powershell ArrayList turns a single array item back into a string
I have a powershell script that generates an ArrayList based on the names of the folders in a given directory. So if the directory looked like the following:

C:\Directory\One

C:\Directory\Two

C:\Directory\Three

$list is an array that contains [One, Two, Three]. The line is as follows:

```<code>[System.Collections.ArrayList]$list = (Get-ChildItem C:\Directory -dir).Name
</code>```

I can then iterate through the array of strings and do various things with them. However this stops working when there is only one folder in the directory. It seems it is no longer an ArrayList and becomes just a string. I get the following error:

```<code>Cannot convert the "Directory" value of type "System.String" to type "System.Collections.ArrayList"
</code>```

What can be done here? Should I be using a different kind of array type?

答:
You need to force the output into an array.

@((Get-ChildItem C:\Directory -dir).Name)

ContentLicense: CC BY-SA 3.0

Body:
I have a powershell script that generates an ArrayList based on the names of the folders in a given directory. So if the directory looked like the following:

C:\Directory\One

C:\Directory\Two

C:\Directory\Three

$list is an array that contains [One, Two, Three]. The line is as follows:

[System.Collections.ArrayList]$list = (Get-ChildItem C:\Directory -dir).Name

I can then iterate through the array of strings and do various things with them. However this stops working when there is only one folder in the directory. It seems it is no longer an ArrayList and becomes just a string. I get the following error:

Cannot convert the "Directory" value of type "System.String" to type "System.Collections.ArrayList"

What can be done here? Should I be using a different kind of array type?


问:
For images, what is the benefit of using the name element? name="...."
I want to know what the difference is between alt="" and name=""

Would it be better to put the filename within the alt tag, or the description of the photo?

What makes better sense, both from SEO and validation stand-point?

答: You definitly want to use the ALT tag - for all the reasons mentioned above, and: this tag is mandatory according to W3C so you need it if you want to create "compliant code" (see e.g. w3schools).

OwnerDisplayName: Brad

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: ISW


问:
Reencoding a file with "Encode::from_to" or "PerlIO::encoding"
Between Encode::from_to and PerlIO::encoding, what's the preferred way to reencode a file within a perl script?

This uses PerlIO::encoding

```<code>use warnings FATAL => 'utf8';
open(my $f1, "<:encoding(iso-8859-1)", "infile");
open(my $f2, ">:encoding(utf-8)", "outfile");
print $f2 $_ while <$f1>;
</code>```

Or, should I use Encode::from_to or is there a better way?

It seems that the first option, with PerlIO::encoding, would support not-slurping the file into memory.

Are there any downsides to using that method?

答:
You don't show what you intend to do with Encode, but the generally-accepted best practice is to work with Perl's internal coding (basically UTF-8, but you don't need to know) and apply the conversions to input and output file handles accordingly

I don't understand where you got the idea that using a PerlIO layer would affect slurping a file. Maybe you're getting confused with line endings, but even so there should be little difference

If you think you must read the entire file into memory then you should think again. It is almost always best to keep state variables across single lines, or perhaps to modify Perl's input record separator $/ to read multi-line records

Nothing will affect the decoding or encoding of file data unless you are misusing it

Body:
Between Encode::from_to and PerlIO::encoding, what's the preferred way to reencode a file within a perl script?

This uses PerlIO::encoding

use warnings FATAL => 'utf8';
open(my $f1, "<:encoding(iso-8859-1)", "infile");
open(my $f2, ">:encoding(utf-8)", "outfile");
print $f2 $_ while <$f1>;

Or, should I use Encode::from_to or is there a better way?

It seems that the first option, with PerlIO::encoding, would support not-slurping the file into memory.

Are there any downsides to using that method?


问:
Add a custom color palette to Xcode Interface Builder
My current long term project utilizes a palette of custom colors. In code, we are using a category to access these colors by name. This works great but there are times, such as when building a nib, that these colors won't be set programmatically.

I am looking for a way to define a named set of colors. For instance, when setting a background color for a UIView, I would like my drop list in Interface Builder to list my custom colors by name. Does anyone know of a way to achieve this?

答:
Xcode 9

You now have another option to add Color Sets or Named Colors to your assets. This is new in Xcode 9.

1. Adding Named Colors to Your Project

In *.xcassets > right-click > New Color Set

2. Assigning Name Colors to Views

Your new Named Colors show up in your Color Picker now in their own section.

ContentLicense: CC BY-SA 4.0


问:
java.lang.NumberFormatException: For input string: "null" .. can't figure out why
I keep getting this error even though I'm following someone on Youtube and copying his code. He doesn't get the error, but I do.

The following code is in class Cart

```<code>  // Calculating the total price

   int total = 0 ;
    for(Order order:cart)
        total += (Integer.parseInt(order.getPrice())) * (Integer.parseInt(order.getQuantity()));

    Locale locale = new Locale("en" , "US"  );
    NumberFormat fmt = NumberFormat.getCurrencyInstance(locale);

    txtTotalPrice.setText(fmt.format(total));
</code>```

The following code is in class CartAdapter

```<code>    int price = (Integer.parseInt(listData.get(position).getPrice()))
            *(Integer.parseInt(listData.get(position).getQuantity()));
    holder.txt_price.setText(fmt.format(price));

    holder.txt_cart_name.setText(listData.get(position).getProductName());
</code>```

答:
Iorder.getPrice() may be null .And order.getQuantity() may be null

If one of them or both of them are null,it will cause NumberFormatException

So you can do like this .

If you want use them .

```<code>total += (Integer.parseInt(TextUtils.isEmpty(order.getPrice()) ? "0" : order.getPrice())) * (Integer.parseInt(TextUtils.isEmpty(order.getQuantity()) ? "0" : order.getQuantity()));
</code>```

And

```<code>int price = (Integer.parseInt(TextUtils.isEmpty(listData.get(position).getPrice()) ? "0" : listData.get(position).getPrice()))
            *(TextUtils.isEmpty(listData.get(position).getQuantity()) ? "0" : listData.get(position).getQuantity());
</code>```

Note

You can do like this , if your response is null ,you can return a default value .It will not cause NumberFormatException .

```<code>TextUtils.isEmpty(response) ? "0" : response;
</code>```

Body:
I keep getting this error even though I'm following someone on Youtube and copying his code. He doesn't get the error, but I do.

The following code is in class Cart

  // Calculating the total price

   int total = 0 ;
    for(Order order:cart)
        total += (Integer.parseInt(order.getPrice())) * (Integer.parseInt(order.getQuantity()));

    Locale locale = new Locale("en" , "US"  );
    NumberFormat fmt = NumberFormat.getCurrencyInstance(locale);

    txtTotalPrice.setText(fmt.format(total));

The following code is in class CartAdapter

    int price = (Integer.parseInt(listData.get(position).getPrice()))
            *(Integer.parseInt(listData.get(position).getQuantity()));
    holder.txt_price.setText(fmt.format(price));

    holder.txt_cart_name.setText(listData.get(position).getProductName());

Body:
Iorder.getPrice() may be null .And order.getQuantity() may be null

If one of them or both of them are null,it will cause NumberFormatException

So you can do like this .

If you want use them .

total += (Integer.parseInt(TextUtils.isEmpty(order.getPrice()) ? "0" : order.getPrice())) * (Integer.parseInt(TextUtils.isEmpty(order.getQuantity()) ? "0" : order.getQuantity()));

And

int price = (Integer.parseInt(TextUtils.isEmpty(listData.get(position).getPrice()) ? "0" : listData.get(position).getPrice()))
            *(TextUtils.isEmpty(listData.get(position).getQuantity()) ? "0" : listData.get(position).getQuantity());

Note

You can do like this , if your response is null ,you can return a default value .It will not cause NumberFormatException .

TextUtils.isEmpty(response) ? "0" : response;


问:
Why does using ServiceStack JwtAuthProviderReader add auth endpoints to my resource API?
I have set up an authentication server that issues JWT Tokens.

I now have setup my first resource service that will authenticate/authorize using the bearer token provided in a request. This service is not my auth server, it is a resource server.

I added the ServiceStack JwtAuthProviderReader to my resource service:

```<code>Plugins.Add(new AuthFeature(() => new AuthUserSession(),
new IAuthProvider[] {
    new JwtAuthProviderReader() {
        HashAlgorithm = "HS256",
        AuthKeyBase64 = AuthSettings.JwtAuthKeyBase64
    },
}));
</code>```

Why does my resource server now have all the auth server endpoints, I am using the JwtAuthProviderReader, not the JwtAuthProvider that my auth service does. As the documentation states, my resource service is only validating tokens.

答:
These aren't limited to just the JWT AuthProvider, they're ServiceStack's built-in Auth Services for handling any ServiceStack Authentication, i.e. when registering the ServiceStack's AuthFeature plugin.

If you're not using Assign/Unassign Roles Services, they can be disabled with:

```<code>Plugins.Add(new AuthFeature(...) {
    IncludeAssignRoleServices = false
});
</code>```

You can also hide Services from showing up in the metadata pages and Services by dynamically adding Exclude attributes in the AppHost's constructor, e.g:

```<code>public AppHost() : base("MyApp", typeof(MyServices).Assembly)
{
    typeof(Authenticate)
        .AddAttributes(new ExcludeAttribute(Feature.Metadata));
}
</code>```

Which is equivalent to adding the attribute on the Request DTO, e.g:

```<code>[Exclude(Feature.Metadata)]
public class Authenticate { ... }
</code>```

Body:
I have set up an authentication server that issues JWT Tokens.

I now have setup my first resource service that will authenticate/authorize using the bearer token provided in a request. This service is not my auth server, it is a resource server.

I added the ServiceStack JwtAuthProviderReader to my resource service:

Plugins.Add(new AuthFeature(() => new AuthUserSession(),
new IAuthProvider[] {
    new JwtAuthProviderReader() {
        HashAlgorithm = "HS256",
        AuthKeyBase64 = AuthSettings.JwtAuthKeyBase64
    },
}));

Why does my resource server now have all the auth server endpoints, I am using the JwtAuthProviderReader, not the JwtAuthProvider that my auth service does. As the documentation states, my resource service is only validating tokens.

Body:
These aren't limited to just the JWT AuthProvider, they're ServiceStack's built-in Auth Services for handling any ServiceStack Authentication, i.e. when registering the ServiceStack's AuthFeature plugin.

If you're not using Assign/Unassign Roles Services, they can be disabled with:

Plugins.Add(new AuthFeature(...) {
    IncludeAssignRoleServices = false
});

You can also hide Services from showing up in the metadata pages and Services by dynamically adding Exclude attributes in the AppHost's constructor, e.g:

public AppHost() : base("MyApp", typeof(MyServices).Assembly)
{
    typeof(Authenticate)
        .AddAttributes(new ExcludeAttribute(Feature.Metadata));
}

Which is equivalent to adding the attribute on the Request DTO, e.g:

[Exclude(Feature.Metadata)]
public class Authenticate { ... }


问:
How do I make a real-time updating grid in c++
So I'm making a sudoku solver to kind of test myself, and I have seem to hit a wall.

I'm trying to get the user to input values into a grid, and it'll automatically update every couple of seconds to see the next value they put in the grid.

I don't know how to get the user input into the grid itself.

Here is my code for the grid itself.

```<code>void draw()
{
int given;
cout << endl;
for (int i = 0; i < 13; i++)
{
    for (int j = 0; j <= 9; j++)
    {
        if (j == 0)
        {
            cout << "|";
        }
        if (j == 3 || j == 6 || j == 9 )
        {
            cout << "|";
        }
        if (i == 0 || i == 4 || i == 8 || i == 12)
        {
            cout << "#";
        }
        else
        {
            cout << " ";
        }
    }

    cout << endl;

}
</code>```

}

To get this to refresh, I have this loop.

```<code>while (gameOver != TRUE)
{
    system("cls");
    draw();
    cout << "\nEnter the next given number, or 0 for a blank space: ";
    Sleep(600);
}
</code>```

So I need help getting the user input value to both

Display on the grid

Save in any way (I think an array might work best?)

Thanks.

答:
By this line I guess you're programming on Windows:

```<code>system("cls");
</code>```

So my answer will be based on that and utilize a lot of WinAPI.

Normally, you can stick to cin and update the grid after user presses Enter. But since you want a real-time display refresh, this doesn't seem optimal. You have conio.h on Windows so go for it:

```<code>#include <conio.h>
...
char ch;
while (true) {
    while (!kbhit()); // Wait for user input
    ch = getch();
    switch (ch) {
        // Process input here.
    }
}
</code>```

Body:
So I'm making a sudoku solver to kind of test myself, and I have seem to hit a wall.

I'm trying to get the user to input values into a grid, and it'll automatically update every couple of seconds to see the next value they put in the grid.

I don't know how to get the user input into the grid itself.

Here is my code for the grid itself.

void draw()
{
int given;
cout << endl;
for (int i = 0; i < 13; i++)
{
    for (int j = 0; j <= 9; j++)
    {
        if (j == 0)
        {
            cout << "|";
        }
        if (j == 3 || j == 6 || j == 9 )
        {
            cout << "|";
        }
        if (i == 0 || i == 4 || i == 8 || i == 12)
        {
            cout << "#";
        }
        else
        {
            cout << " ";
        }
    }

    cout << endl;

}

}

To get this to refresh, I have this loop.

while (gameOver != TRUE)
{
    system("cls");
    draw();
    cout << "\nEnter the next given number, or 0 for a blank space: ";
    Sleep(600);
}

So I need help getting the user input value to both

Display on the grid

Save in any way (I think an array might work best?)

Thanks.

Body:
By this line I guess you're programming on Windows:

system("cls");

So my answer will be based on that and utilize a lot of WinAPI.

Normally, you can stick to cin and update the grid after user presses Enter. But since you want a real-time display refresh, this doesn't seem optimal. You have conio.h on Windows so go for it:

#include <conio.h>
...
char ch;
while (true) {
    while (!kbhit()); // Wait for user input
    ch = getch();
    switch (ch) {
        // Process input here.
    }
}


问:
Aws database error php mysql
I have connected my appication with aws rds with the script below:

function db_connect() {
   $result = new mysqli($_SERVER['RDS_HOSTNAME'], $_SERVER['RDS_USERNAME'], $_SERVER['RDS_PASSWORD'], $_SERVER['RDS_DB_NAME'], $_SERVER['RDS_PORT']);
   if (!$result) {
     throw new Exception('Could not connect to database server');
   } else {
     return $result;
   }
}
```

<p>It was working fine then i had to change it due to a new feature which someone else wrote the code for:<br></p>

```$dbOptions = array(
    'db_host' => 'RDS_HOSTNAME',
    'db_user' => 'RDS_USERNAME',
    'db_pass' => 'RDS_PASSWORD',
    'db_name' => 'RDS_DB_NAME'
);
```

I didn't add the port because he didn't and i never connected to database with an array and key like this, how do i go about adding port like at what position.

答:
I was forgetting the $_SERVER variable:

```<code>$dbOptions = array(
'db_host' => $_SERVER['RDS_HOSTNAME'],
'db_user' => $_SERVER['RDS_USERNAME'],
'db_pass' => $_SERVER['RDS_PASSWORD'],
'db_name' => $_SERVER['RDS_DB_NAME']
</code>```

);

Title: Aws database error php mysql

Body:
I have connected my appication with aws rds with the script below:

function db_connect() {
   $result = new mysqli($_SERVER['RDS_HOSTNAME'], $_SERVER['RDS_USERNAME'], $_SERVER['RDS_PASSWORD'], $_SERVER['RDS_DB_NAME'], $_SERVER['RDS_PORT']);
   if (!$result) {
     throw new Exception('Could not connect to database server');
   } else {
     return $result;
   }
}

It was working fine then i had to change it due to a new feature which someone else wrote the code for:

$dbOptions = array(
    'db_host' => 'RDS_HOSTNAME',
    'db_user' => 'RDS_USERNAME',
    'db_pass' => 'RDS_PASSWORD',
    'db_name' => 'RDS_DB_NAME'
);

I didn't add the port because he didn't and i never connected to database with an array and key like this, how do i go about adding port like at what position.

Body:
I was forgetting the $_SERVER variable:

$dbOptions = array(
'db_host' => $_SERVER['RDS_HOSTNAME'],
'db_user' => $_SERVER['RDS_USERNAME'],
'db_pass' => $_SERVER['RDS_PASSWORD'],
'db_name' => $_SERVER['RDS_DB_NAME']

);


问:
Getting data from my Database Handler to a Text View in my Activity
New to Android Studio so some help would go a long way!

Trying to do a search where the user inputs an email and if its in the database, then it shows up in a text view.

I think my select is correct but here's the method in my Database Handler class:

```<code>public String searchEmail(String email)
    {
        SQLiteDatabase db = this.getWritableDatabase();

        String fName;
        String sName;
        String selectQuery = "SELECT FIRSTNAME, SURNAME FROM friends_table WHERE EMAIL=? ";
        Cursor c = db.rawQuery(selectQuery, new String[] { email });
        if (c.moveToFirst()) {
            fName = c.getString(c.getColumnIndex("FIRSTNAME"));
            sName = c.getString(c.getColumnIndex("SURNAME"));
        }
        c.close();

        return email;
    }
</code>```

Then my search:

```<code>public void searchFriend(View v) {
        EditText emailSearch = (EditText) findViewById(R.id.emailSearch);

        String emailSearchString = emailSearch.getText().toString();
        myDB.searchEmail(emailSearchString);

    //I need to get the first name and surname from the db handler class
        TextView firstName = (TextView)findViewById(R.id.firstname);
        TextView surname = (TextView)findViewById(R.id.surname);

        firstName.setText("");
        surname.setText("");

    }
</code>```

I'm just finding to difficult to understand how I'll show the first name and surname if the email matches.

Thanks guys, I love you

答:
Create a new class User and try this:

```<code>public User searchEmail(String email)
    {
        SQLiteDatabase db = this.getWritableDatabase();

        User u = null;
        String selectQuery = "SELECT FIRSTNAME, SURNAME FROM friends_table WHERE EMAIL=? ";
        Cursor c = db.rawQuery(selectQuery, new String[] { email });
        if (c.moveToFirst()) {
            u = new User();
            u.setfName(c.getString(c.getColumnIndex("FIRSTNAME")));
            u.setsName(c.getString(c.getColumnIndex("SURNAME")));
        }
        c.close();

        return u;
    }
</code>```

Body:
New to Android Studio so some help would go a long way!

Trying to do a search where the user inputs an email and if its in the database, then it shows up in a text view.

I think my select is correct but here's the method in my Database Handler class:

public String searchEmail(String email)
    {
        SQLiteDatabase db = this.getWritableDatabase();

        String fName;
        String sName;
        String selectQuery = "SELECT FIRSTNAME, SURNAME FROM friends_table WHERE EMAIL=? ";
        Cursor c = db.rawQuery(selectQuery, new String[] { email });
        if (c.moveToFirst()) {
            fName = c.getString(c.getColumnIndex("FIRSTNAME"));
            sName = c.getString(c.getColumnIndex("SURNAME"));
        }
        c.close();

        return email;
    }

Then my search:

public void searchFriend(View v) {
        EditText emailSearch = (EditText) findViewById(R.id.emailSearch);

        String emailSearchString = emailSearch.getText().toString();
        myDB.searchEmail(emailSearchString);

    //I need to get the first name and surname from the db handler class
        TextView firstName = (TextView)findViewById(R.id.firstname);
        TextView surname = (TextView)findViewById(R.id.surname);

        firstName.setText("");
        surname.setText("");

    }

I'm just finding to difficult to understand how I'll show the first name and surname if the email matches.

Thanks guys, I love you

Body:
Create a new class User and try this:

public User searchEmail(String email)
    {
        SQLiteDatabase db = this.getWritableDatabase();

        User u = null;
        String selectQuery = "SELECT FIRSTNAME, SURNAME FROM friends_table WHERE EMAIL=? ";
        Cursor c = db.rawQuery(selectQuery, new String[] { email });
        if (c.moveToFirst()) {
            u = new User();
            u.setfName(c.getString(c.getColumnIndex("FIRSTNAME")));
            u.setsName(c.getString(c.getColumnIndex("SURNAME")));
        }
        c.close();

        return u;
    }


问:
Sorting through array c++
So I am attempting to do a bubble-like sort. Not a bubble sort because I don't want to exchange every single value that i run into. I simply want to find the smallest value of each index and place it in order. Such as in the arrayVal[3, 5, 2].

Instead of replacing the value 3 with 2 and then replacing 5 with 3. I want to find the smallest number of the entire array and place it at arrayVal[0] and then move to arrayVal[1].

I can't quite figure out how to do this and am kind of stuck.(I took out the <> on the libraries so you could see which libraries I am using)

```<code>#include iostream
#include cmath
#include ctime
using namespace std;

int main()
{
    const int STARTLOOP = 0;
    const int MAXLOOP = 5;
    const int MINRANGE = 1;
    const int MAXRANGE = 10;

    //int temp = 0;
    int smallestVal = 0;
    int arrayVal[MAXLOOP];

    srand(time(0));

    for (int i = STARTLOOP; i < MAXLOOP; i++)
    {
        arrayVal[i] = (rand() % MAXRANGE) + MINRANGE;
    }

    for (int i = STARTLOOP; i < MAXLOOP; i++)
    {
        cout << arrayVal[i] << endl;
    }

    cout << "Before the sort" << endl;

    for (int i = STARTLOOP; i < MAXLOOP; i++)
    {
        for (int j = i; j < MAXLOOP; j++)
        {
            if (arrayVal[j] < arrayVal[i])
            {
                arrayVal[i] = smallestVal;
            }

        }
    }

    for (int i = STARTLOOP; i < MAXLOOP; i++)
    {
        cout << arrayVal[i] << endl;
    }

    cout << "After the sort" << endl;

    return 0;
</code>```

I also recognize I'm not using functions, i just wrote up the code because I was trying to figure this out. Thank you in advance.

答:
What you want to achieve is some sort of a modified insertion sort. Check out this implementation :

```<code>void sort(int values[], int n)
{
    for (int i = 0; i < n; ++i)
    {
        int min = i;
        for ( int j = i ; j < n ; j++)
        {
            if (values[j]<values[min]) min =j;
        }
        while(values[min-1]>values[min])
        {
            if(min==0)
                break;
            if(values[min-1]!=values[min])
                swap (values+min-1,values+min);
            min--;

        }
    }
    return;
}
</code>```

What this function does is that it searches the array every time for the smallest element starting from index i and when it finds this element it keeps on swapping it will all of the previous elements in the array until it reaches a smaller element.

Title: Sorting through array c++

Body:
So I am attempting to do a bubble-like sort. Not a bubble sort because I don't want to exchange every single value that i run into. I simply want to find the smallest value of each index and place it in order. Such as in the arrayVal[3, 5, 2].

Instead of replacing the value 3 with 2 and then replacing 5 with 3. I want to find the smallest number of the entire array and place it at arrayVal[0] and then move to arrayVal[1].

I can't quite figure out how to do this and am kind of stuck.(I took out the <> on the libraries so you could see which libraries I am using)

#include iostream
#include cmath
#include ctime
using namespace std;

int main()
{
    const int STARTLOOP = 0;
    const int MAXLOOP = 5;
    const int MINRANGE = 1;
    const int MAXRANGE = 10;

    //int temp = 0;
    int smallestVal = 0;
    int arrayVal[MAXLOOP];

    srand(time(0));

    for (int i = STARTLOOP; i < MAXLOOP; i++)
    {
        arrayVal[i] = (rand() % MAXRANGE) + MINRANGE;
    }

    for (int i = STARTLOOP; i < MAXLOOP; i++)
    {
        cout << arrayVal[i] << endl;
    }

    cout << "Before the sort" << endl;

    for (int i = STARTLOOP; i < MAXLOOP; i++)
    {
        for (int j = i; j < MAXLOOP; j++)
        {
            if (arrayVal[j] < arrayVal[i])
            {
                arrayVal[i] = smallestVal;
            }

        }
    }

    for (int i = STARTLOOP; i < MAXLOOP; i++)
    {
        cout << arrayVal[i] << endl;
    }

    cout << "After the sort" << endl;

    return 0;

I also recognize I'm not using functions, i just wrote up the code because I was trying to figure this out. Thank you in advance.

Body:
What you want to achieve is some sort of a modified insertion sort. Check out this implementation :

void sort(int values[], int n)
{
    for (int i = 0; i < n; ++i)
    {
        int min = i;
        for ( int j = i ; j < n ; j++)
        {
            if (values[j]<values[min]) min =j;
        }
        while(values[min-1]>values[min])
        {
            if(min==0)
                break;
            if(values[min-1]!=values[min])
                swap (values+min-1,values+min);
            min--;

        }
    }
    return;
}

What this function does is that it searches the array every time for the smallest element starting from index i and when it finds this element it keeps on swapping it will all of the previous elements in the array until it reaches a smaller element.


问:
Find and extract a number from a string
I have a requirement to find and extract a number contained within a string.

For example, from these strings:

```<code>string test = "1 test"
string test1 = " 1 test"
string test2 = "test 99"
</code>```

How can I do this?

答:
```<code>var match=Regex.Match(@"a99b",@"\d+");
if(match.Success)
{
    int val;
    if(int.TryParse(match.Value,out val))
    {
        //val is set
    }
}
</code>```

Title: Find and extract a number from a string

Body:
I have a requirement to find and extract a number contained within a string.

For example, from these strings:

string test = "1 test"
string test1 = " 1 test"
string test2 = "test 99"

How can I do this?


问:
ValueError: Cannot convert a partially known TensorShape to a Tensor: (?,)
I am getting error which is specify "ValueError: Cannot convert a partially known TensorShape to a Tensor: (?,)"
I just want to get prediction results bu I can not run fit method.(estimator.fit(input_fn=get_input_fn_train(), steps=10000) I get the error while trying to run this code. I have 10000 rows and 8 int columns.I dropped string columns for now . (x_train.shape) -->(8000, 8).y_train.shape--> (8000,).What kind of shape is talking about? I am googling bu I can not find useful things. What shoul I do? What am I missing? All codes below. Thanks.

```<code>import pandas as pd
import tensorflow as tf
import numpy as np
import tempfile
from sklearn.model_selection import train_test_split

def split_data(data, rate, label):
    data = data.dropna()

    train_data, test_data = train_test_split(data, test_size=rate)

    train_label = train_data[label]
    train_data = train_data.drop(label, 1)

    test_label = test_data[label]
    test_data = test_data.drop(label, 1)
    return train_data, train_label, test_data, test_label

LABEL="Exited"

data = pd.read_csv("Churn_Modelling.csv", skipinitialspace=True, header=0)

data.drop("Surname", axis=1, inplace=True)
data.drop("RowNumber", axis=1, inplace=True)
data.drop("CustomerId", axis=1, inplace=True)
data.drop("Geography", axis=1, inplace=True)
data.drop("Gender", axis=1, inplace=True)

x_train, y_train, x_test, y_test = split_data(data, 0.20, LABEL)

def get_input_fn_train():
        input_fn = tf.estimator.inputs.pandas_input_fn(
            x=x_train.astype('float64'),
            y=y_train.astype('float32'),
            shuffle=False
        )
        return input_fn

def get_input_fn_test():
        input_fn = tf.estimator.inputs.pandas_input_fn(
            x=x_test.astype('float64'),
            y=y_test.astype('float32'),
            shuffle=False
        )
        return input_fn

feature_columns = tf.contrib.learn.infer_real_valued_columns_from_input_fn(
                                                       get_input_fn_train())

model_dir = tempfile.mkdtemp()
estimator = tf.contrib.learn.SVM(
example_id_column=tf.constant(np.arange(len(y_train))),
feature_columns=feature_columns, l2_regularization=10.0,model_dir=model_dir)

estimator.fit(input_fn=get_input_fn_train(), steps=10000)
#(I am getting  error this line)

results=estimator.evaluate(input_fn=get_input_fn_test(), steps=1)

for key in sorted(results):
  print("%s: %s" % (key, results[key]))

pred=list(estimator.predict(input_fn=get_input_fn_test()))
</code>```

答: I don't know if there are other problems but one problem you have is that example_id_column argument to SVM needs to be a string. It is a name of the feature column representing example ids. In your code it is an integer Tensor. See https://www.tensorflow.org/api_docs/python/tf/contrib/learn/SVM

Body:
I am getting error which is specify "ValueError: Cannot convert a partially known TensorShape to a Tensor: (?,)"
I just want to get prediction results bu I can not run fit method.(estimator.fit(input_fn=get_input_fn_train(), steps=10000) I get the error while trying to run this code. I have 10000 rows and 8 int columns.I dropped string columns for now . (x_train.shape) -->(8000, 8).y_train.shape--> (8000,).What kind of shape is talking about? I am googling bu I can not find useful things. What shoul I do? What am I missing? All codes below. Thanks.

import pandas as pd
import tensorflow as tf
import numpy as np
import tempfile
from sklearn.model_selection import train_test_split

def split_data(data, rate, label):
    data = data.dropna()

    train_data, test_data = train_test_split(data, test_size=rate)

    train_label = train_data[label]
    train_data = train_data.drop(label, 1)

    test_label = test_data[label]
    test_data = test_data.drop(label, 1)
    return train_data, train_label, test_data, test_label

LABEL="Exited"

data = pd.read_csv("Churn_Modelling.csv", skipinitialspace=True, header=0)

data.drop("Surname", axis=1, inplace=True)
data.drop("RowNumber", axis=1, inplace=True)
data.drop("CustomerId", axis=1, inplace=True)
data.drop("Geography", axis=1, inplace=True)
data.drop("Gender", axis=1, inplace=True)

x_train, y_train, x_test, y_test = split_data(data, 0.20, LABEL)

def get_input_fn_train():
        input_fn = tf.estimator.inputs.pandas_input_fn(
            x=x_train.astype('float64'),
            y=y_train.astype('float32'),
            shuffle=False
        )
        return input_fn

def get_input_fn_test():
        input_fn = tf.estimator.inputs.pandas_input_fn(
            x=x_test.astype('float64'),
            y=y_test.astype('float32'),
            shuffle=False
        )
        return input_fn

feature_columns = tf.contrib.learn.infer_real_valued_columns_from_input_fn(
                                                       get_input_fn_train())

model_dir = tempfile.mkdtemp()
estimator = tf.contrib.learn.SVM(
example_id_column=tf.constant(np.arange(len(y_train))),
feature_columns=feature_columns, l2_regularization=10.0,model_dir=model_dir)

estimator.fit(input_fn=get_input_fn_train(), steps=10000)
#(I am getting  error this line)

results=estimator.evaluate(input_fn=get_input_fn_test(), steps=1)

for key in sorted(results):
  print("%s: %s" % (key, results[key]))

pred=list(estimator.predict(input_fn=get_input_fn_test()))


问:
Stubbing one method that calls a real method with jasmine
I need to test a FileReader's onload, using Jasmine + Sinon.

This is the function to be tested:

MyObject.prototype.uploadFile = function (file, callback) {
    const fileReader = new FileReader();

    fileReader.onload = event => {
        if (typeof callback === 'function') {
            callback(event);
        }
    };

    fileReader.readAsDataURL(file);
};```
</div>
</div>
</p>

<p>And this is the test:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>describe('uploadFile', () => {
        it('should execute the callback', () => {
            let testFunction = jasmine.createSpy();
            let readData = {
                readAsDataURL: () => {
                    this.onload();
                },
                onload: () => {
                }
            };

            file = new Blob(['image']);
            sandbox.stub(window, 'FileReader').returns(readData);

            component = sandbox.render(BioProfile);
            component.replaceImage(file, testFunction);

            expect(testFunction).toHaveBeenCalled();
        });
    });</code>```

As you can see, I stubbed readData from FileReader (not sure if done properly, though), but I need a stubbed method to call a FileReader's actual method (onload) to be able to test.

Is that possible?

答:
You've stubbed FileReader incorrectly.

With object literals, this is the whatever context the object literal was constructed in.

Unless you use the shorthand notation introduced in es6.

So when you call this.onload inside readAsDataURL, its not trying to call the onload function on the readData object.

To do that:

```<code>let readData = {
    readAsDataURL() {
        this.onload();
    },
    onload() {}
};
</code>```

Body:
I need to test a FileReader's onload, using Jasmine + Sinon.

This is the function to be tested:

MyObject.prototype.uploadFile = function (file, callback) {
    const fileReader = new FileReader();

    fileReader.onload = event => {
        if (typeof callback === 'function') {
            callback(event);
        }
    };

    fileReader.readAsDataURL(file);
};

And this is the test:

describe('uploadFile', () => {
        it('should execute the callback', () => {
            let testFunction = jasmine.createSpy();
            let readData = {
                readAsDataURL: () => {
                    this.onload();
                },
                onload: () => {
                }
            };

            file = new Blob(['image']);
            sandbox.stub(window, 'FileReader').returns(readData);

            component = sandbox.render(BioProfile);
            component.replaceImage(file, testFunction);

            expect(testFunction).toHaveBeenCalled();
        });
    });

As you can see, I stubbed readData from FileReader (not sure if done properly, though), but I need a stubbed method to call a FileReader's actual method (onload) to be able to test.

Is that possible?

Body:
You've stubbed FileReader incorrectly.

With object literals, this is the whatever context the object literal was constructed in.

Unless you use the shorthand notation introduced in es6.

So when you call this.onload inside readAsDataURL, its not trying to call the onload function on the readData object.

To do that:

let readData = {
    readAsDataURL() {
        this.onload();
    },
    onload() {}
};


问:
AngularFire2 Suscribe return values FAIL
I have this code in my authService

```<code>    constructor(
    private afAuth: AngularFireAuth,
    private db: AngularFireDatabase,
    private router: Router
  ) {
    this.authState = afAuth.authState;
    this.authState.subscribe((user: firebase.User) => {
        this.authState = user;
    });
    if ( this.authenticated ) {
      // this.router.navigate([`/content`]);
    }
  }

  // Returns true if user is logged in
  get authenticated(): any {
    return this.authState;
  }
</code>```

I call the get authenticated and it returns undefined:

COMPONENT

```<code>    constructor(
    private auth: AuthService
  ) {
      this.currentUser = this.auth.authenticated;
  }
showUser() {
    console.log(this.currentUser.uid);
  }
</code>```

I need help to fix it, any idea?

答:
What happens is normal. console.log is synchronous call. what is inside the subscription is asynchronous. so even if the console.log is written after the .subcribe and can be executed faster indeed. That is why console.log( this.authState.uid ); prints undefined.

Also, I would avoid adding any logic in the contructor.

Better having the .subscribe OnInit() and try to access the this. authState on AfterViewInit() lifecycle.

Final note, you can even save the subscription that you will have OnInit and .unsubscribe OnDestroy :)

Body:
I have this code in my authService

    constructor(
    private afAuth: AngularFireAuth,
    private db: AngularFireDatabase,
    private router: Router
  ) {
    this.authState = afAuth.authState;
    this.authState.subscribe((user: firebase.User) => {
        this.authState = user;
    });
    if ( this.authenticated ) {
      // this.router.navigate([`/content`]);
    }
  }

  // Returns true if user is logged in
  get authenticated(): any {
    return this.authState;
  }

I call the get authenticated and it returns undefined:

COMPONENT

    constructor(
    private auth: AuthService
  ) {
      this.currentUser = this.auth.authenticated;
  }
showUser() {
    console.log(this.currentUser.uid);
  }

I need help to fix it, any idea?


问:
Excel - Function to use in CHOOSE - Return list of values from range
Which excel function can I use in this CHOOSE formula to convert the range to a list and allow the return of the below CHOOSE function to be b

Example this problem to get value 'b'. Where range B2:F2 is equal to a,b,c,d,e.

```<code>CHOOSE(2, B2:F2)
</code>```

This will fail as we have supplied a range to choose not a list.

答:
You should "choose" a more appropriate function:

```<code>=INDEX(B2:F2,2)
</code>```

Body:
Which excel function can I use in this CHOOSE formula to convert the range to a list and allow the return of the below CHOOSE function to be b

Example this problem to get value 'b'. Where range B2:F2 is equal to a,b,c,d,e.

CHOOSE(2, B2:F2)

This will fail as we have supplied a range to choose not a list.

Body:
You should "choose" a more appropriate function:

=INDEX(B2:F2,2)


问:
Eclipse Team Synchronize shows Outgoing changes in 'Java Workspace' Model, where Git Model shows none
I've looked at the answers to similar questions here, and none fit the bill, or manage to solve the issue.

Using Eclipse Neon.3 (4.6.3) with EGit 4.7.0, and no other versioning system like SVN or CVS, calling Team > Synchronize on some of my Java projects, which have been synced with a Bitbucket repo many times over, and which show absolutely no changes whatsoever in the compare editor, including any whitespace differences, Eclipse still lists several .java source files as Outgoing changes under the "Java Workspace" model.

So for instance, calling Team > Synchronize on a project in my workspace, that is tracked in my local Git repo and remotely in a Cloud hosted Bitbucket, returns the following message:

There are no more Incoming/Outgoing changes for Git Commits. However Java Workspace has changes in Incoming/Outgoing mode.

Change to Java Workspace

  Show All Models

A Google search for "However Java Workspace has changes" only yields a single result:

The sole hit is a reported bug in Subversive (one of the two main SVN integrations for Eclipse). However, while the described issue sounds like a rather accurate match of the issue I'm having, it claims that doing another Team > Synchronize, or restarting Eclipse would resolve the phantom Outgoing changes. Not so in my case, not with EGit.

Like I said, the remote and local files are exactly the same, incl. their whitespace/line endings.

Fetch/Pull from origin says there are no changes, everything is up to date.
Calling Replace With > HEAD Revision also doesn't help, Eclipse keeps insisting, that my workspace has Outgoing changes. Outgoing where?

This is obviously no big issue, merely an irritating nuissance. Still would be nice to get to the bottom of it.

答:
...Did you try doing the Eclipse dance?

Edit: I find after some time Eclipse will behave strangely (example: dumping views I have enabled, losing track of files, or behaviour similar to what you are experiencing). When this happens I usually select and delete the project from my workspace, close Eclipse, reopen it and reopen the project.

I don't know why this happens or why this works as a fix.


问:
json_normalize for dicts within dicts
I have been trying to normalize a very nested json file I will later analyze. What I am struggling with is how to go more than one level deep to normalize.

I went through the pandas.io.json.json_normalize documentation, since it does exactly what I want it to do.

I have been able to normalize part of it and now understand how dictionaries work, but I am still not there.

With below code I am able to get only the first level.

```<code>import json
import pandas as pd
from pandas.io.json import json_normalize

with open('authors_sample.json') as f:
    d = json.load(f)

raw = json_normalize(d['hits']['hits'])

authors = json_normalize(data = d['hits']['hits'],
                         record_path = '_source',
                         meta = ['_id', ['_source', 'journal'], ['_source', 'title'],
                                 ['_source', 'normalized_venue_name']
                                 ])
</code>```

I am trying to 'dig' into the 'authors' dictionary with below code, but the record_path = ['_source', 'authors'] throws me TypeError: string indices must be integers. As far as I understand json_normalize the logic should be good, but I still don't quite understand how to dive into a json with dict vs list.

I even went through this simple example.

```<code>authors = json_normalize(data = d['hits']['hits'],
                         record_path = ['_source', 'authors'],
                         meta = ['_id', ['_source', 'journal'], ['_source', 'title'],
                                 ['_source', 'normalized_venue_name']
                                 ])
</code>```

Below is a chunk of the json file (5 records).

```<code>{u'_shards': {u'failed': 0, u'successful': 5, u'total': 5},
 u'hits': {u'hits': [{u'_id': u'7CB3F2AD',
    u'_index': u'scibase_listings',
    u'_score': 1.0,
    u'_source': {u'authors': None,
     u'deleted': 0,
     u'description': None,
     u'doi': u'',
     u'is_valid': 1,
     u'issue': None,
     u'journal': u'Physical Review Letters',
     u'link': None,
     u'meta_description': None,
     u'meta_keywords': None,
     u'normalized_venue_name': u'phys rev lett',
     u'pages': None,
     u'parent_keywords': [u'Chromatography',
      u'Quantum mechanics',
      u'Particle physics',
      u'Quantum field theory',
      u'Analytical chemistry',
      u'Quantum chromodynamics',
      u'Physics',
      u'Mass spectrometry',
      u'Chemistry'],
     u'pub_date': u'1987-03-02 00:00:00',
     u'pubtype': None,
     u'rating_avg_weighted': 0,
     u'rating_clarity': 0.0,
     u'rating_clarity_weighted': 0.0,
     u'rating_innovation': 0.0,
     u'rating_innovation_weighted': 0.0,
     u'rating_num_weighted': 0,
     u'rating_reproducability': 0,
     u'rating_reproducibility_weighted': 0.0,
     u'rating_versatility': 0.0,
     u'rating_versatility_weighted': 0.0,
     u'review_count': 0,
     u'tag': [u'mass spectra', u'elementary particles', u'bound states'],
     u'title': u'Evidence for a new meson: A quasinuclear NN-bar bound state',
     u'userAvg': 0.0,
     u'user_id': None,
     u'venue_name': u'Physical Review Letters',
     u'views_count': 0,
     u'volume': None},
    u'_type': u'listing'},
   {u'_id': u'7AF8EBC3',
    u'_index': u'scibase_listings',
    u'_score': 1.0,
    u'_source': {u'authors': [{u'affiliations': [u'Punjabi University'],
       u'author_id': u'780E3459',
       u'author_name': u'munish puri'},
      {u'affiliations': [u'Punjabi University'],
       u'author_id': u'48D92C79',
       u'author_name': u'rajesh dhaliwal'},
      {u'affiliations': [u'Punjabi University'],
       u'author_id': u'7D9BD37C',
       u'author_name': u'r s singh'}],
     u'deleted': 0,
     u'description': None,
     u'doi': u'',
     u'is_valid': 1,
     u'issue': None,
     u'journal': u'Journal of Industrial Microbiology & Biotechnology',
     u'link': None,
     u'meta_description': None,
     u'meta_keywords': None,
     u'normalized_venue_name': u'j ind microbiol biotechnol',
     u'pages': None,
     u'parent_keywords': [u'Nuclear medicine',
      u'Psychology',
      u'Hydrology',
      u'Chromatography',
      u'X-ray crystallography',
      u'Nuclear fusion',
      u'Medicine',
      u'Fluid dynamics',
      u'Thermodynamics',
      u'Physics',
      u'Gas chromatography',
      u'Radiobiology',
      u'Engineering',
      u'Organic chemistry',
      u'High-performance liquid chromatography',
      u'Chemistry',
      u'Organic synthesis',
      u'Psychotherapist'],
     u'pub_date': u'2008-04-04 00:00:00',
     u'pubtype': None,
     u'rating_avg_weighted': 0,
     u'rating_clarity': 0.0,
     u'rating_clarity_weighted': 0.0,
     u'rating_innovation': 0.0,
     u'rating_innovation_weighted': 0.0,
     u'rating_num_weighted': 0,
     u'rating_reproducability': 0,
     u'rating_reproducibility_weighted': 0.0,
     u'rating_versatility': 0.0,
     u'rating_versatility_weighted': 0.0,
     u'review_count': 0,
     u'tag': [u'flow rate',
      u'operant conditioning',
      u'packed bed reactor',
      u'immobilized enzyme',
      u'specific activity'],
     u'title': u'Development of a stable continuous flow immobilized enzyme reactor for the hydrolysis of inulin',
     u'userAvg': 0.0,
     u'user_id': None,
     u'venue_name': u'Journal of Industrial Microbiology & Biotechnology',
     u'views_count': 0,
     u'volume': None},
    u'_type': u'listing'},
   {u'_id': u'7521A721',
    u'_index': u'scibase_listings',
    u'_score': 1.0,
    u'_source': {u'authors': [{u'author_id': u'7FF872BC',
       u'author_name': u'barbara eileen ryan'}],
     u'deleted': 0,
     u'description': None,
     u'doi': u'',
     u'is_valid': 1,
     u'issue': None,
     u'journal': u'The American Historical Review',
     u'link': None,
     u'meta_description': None,
     u'meta_keywords': None,
     u'normalized_venue_name': u'american historical review',
     u'pages': None,
     u'parent_keywords': [u'Social science',
      u'Politics',
      u'Sociology',
      u'Law'],
     u'pub_date': u'1992-01-01 00:00:00',
     u'pubtype': None,
     u'rating_avg_weighted': 0,
     u'rating_clarity': 0.0,
     u'rating_clarity_weighted': 0.0,
     u'rating_innovation': 0.0,
     u'rating_innovation_weighted': 0.0,
     u'rating_num_weighted': 0,
     u'rating_reproducability': 0,
     u'rating_reproducibility_weighted': 0.0,
     u'rating_versatility': 0.0,
     u'rating_versatility_weighted': 0.0,
     u'review_count': 0,
     u'tag': [u'social movements'],
     u'title': u"Feminism and the women's movement : dynamics of change in social movement ideology, and activism",
     u'userAvg': 0.0,
     u'user_id': None,
     u'venue_name': u'The American Historical Review',
     u'views_count': 0,
     u'volume': None},
    u'_type': u'listing'},
   {u'_id': u'7DAEB9A4',
    u'_index': u'scibase_listings',
    u'_score': 1.0,
    u'_source': {u'authors': [{u'author_id': u'0299B8E9',
       u'author_name': u'fraser j harbutt'}],
     u'deleted': 0,
     u'description': None,
     u'doi': u'',
     u'is_valid': 1,
     u'issue': None,
     u'journal': u'The American Historical Review',
     u'link': None,
     u'meta_description': None,
     u'meta_keywords': None,
     u'normalized_venue_name': u'american historical review',
     u'pages': None,
     u'parent_keywords': [u'Superconductivity',
      u'Nuclear fusion',
      u'Geology',
      u'Chemistry',
      u'Metallurgy'],
     u'pub_date': u'1988-01-01 00:00:00',
     u'pubtype': None,
     u'rating_avg_weighted': 0,
     u'rating_clarity': 0.0,
     u'rating_clarity_weighted': 0.0,
     u'rating_innovation': 0.0,
     u'rating_innovation_weighted': 0.0,
     u'rating_num_weighted': 0,
     u'rating_reproducability': 0,
     u'rating_reproducibility_weighted': 0.0,
     u'rating_versatility': 0.0,
     u'rating_versatility_weighted': 0.0,
     u'review_count': 0,
     u'tag': [u'iron'],
     u'title': u'The iron curtain : Churchill, America, and the origins of the Cold War',
     u'userAvg': 0.0,
     u'user_id': None,
     u'venue_name': u'The American Historical Review',
     u'views_count': 0,
     u'volume': None},
    u'_type': u'listing'},
   {u'_id': u'7B3236C5',
    u'_index': u'scibase_listings',
    u'_score': 1.0,
    u'_source': {u'authors': [{u'author_id': u'7DAB7B72',
       u'author_name': u'richard m freeland'}],
     u'deleted': 0,
     u'description': None,
     u'doi': u'',
     u'is_valid': 1,
     u'issue': None,
     u'journal': u'The American Historical Review',
     u'link': None,
     u'meta_description': None,
     u'meta_keywords': None,
     u'normalized_venue_name': u'american historical review',
     u'pages': None,
     u'parent_keywords': [u'Political Science', u'Economics'],
     u'pub_date': u'1985-01-01 00:00:00',
     u'pubtype': None,
     u'rating_avg_weighted': 0,
     u'rating_clarity': 0.0,
     u'rating_clarity_weighted': 0.0,
     u'rating_innovation': 0.0,
     u'rating_innovation_weighted': 0.0,
     u'rating_num_weighted': 0,
     u'rating_reproducability': 0,
     u'rating_reproducibility_weighted': 0.0,
     u'rating_versatility': 0.0,
     u'rating_versatility_weighted': 0.0,
     u'review_count': 0,
     u'tag': [u'foreign policy'],
     u'title': u'The Truman Doctrine and the origins of McCarthyism : foreign policy, domestic politics, and internal security, 1946-1948',
     u'userAvg': 0.0,
     u'user_id': None,
     u'venue_name': u'The American Historical Review',
     u'views_count': 0,
     u'volume': None},
    u'_type': u'listing'}],
  u'max_score': 1.0,
  u'total': 36429433},
 u'timed_out': False,
 u'took': 170}
</code>```

答:
```<code>In [23]: lst = [l for l in raw['hits']['hits'] if l['_source'].get('authors')]

In [24]: json_normalize(lst,
                        [['_source', 'authors']],
                        ['_id', ['_source', 'journal'], ['_source', 'title']])
Out[24]:
           affiliations author_id          author_name       _id                                    _source.journal  \
0  [Punjabi University]  780E3459          munish puri  7AF8EBC3  Journal of Industrial Microbiology & Biotechno...
1  [Punjabi University]  48D92C79      rajesh dhaliwal  7AF8EBC3  Journal of Industrial Microbiology & Biotechno...
2  [Punjabi University]  7D9BD37C            r s singh  7AF8EBC3  Journal of Industrial Microbiology & Biotechno...
3                   NaN  7FF872BC  barbara eileen ryan  7521A721                     The American Historical Review
4                   NaN  0299B8E9     fraser j harbutt  7DAEB9A4                     The American Historical Review
5                   NaN  7DAB7B72   richard m freeland  7B3236C5                     The American Historical Review

                                       _source.title
0  Development of a stable continuous flow immobi...
1  Development of a stable continuous flow immobi...
2  Development of a stable continuous flow immobi...
3  Feminism and the women's movement : dynamics o...
4  The iron curtain : Churchill, America, and the...
5  The Truman Doctrine and the origins of McCarth...
</code>```

Title: json_normalize for dicts within dicts

Body:
I have been trying to normalize a very nested json file I will later analyze. What I am struggling with is how to go more than one level deep to normalize.

I went through the pandas.io.json.json_normalize documentation, since it does exactly what I want it to do.

I have been able to normalize part of it and now understand how dictionaries work, but I am still not there.

With below code I am able to get only the first level.

import json
import pandas as pd
from pandas.io.json import json_normalize

with open('authors_sample.json') as f:
    d = json.load(f)

raw = json_normalize(d['hits']['hits'])

authors = json_normalize(data = d['hits']['hits'],
                         record_path = '_source',
                         meta = ['_id', ['_source', 'journal'], ['_source', 'title'],
                                 ['_source', 'normalized_venue_name']
                                 ])

I am trying to 'dig' into the 'authors' dictionary with below code, but the record_path = ['_source', 'authors'] throws me TypeError: string indices must be integers. As far as I understand json_normalize the logic should be good, but I still don't quite understand how to dive into a json with dict vs list.

I even went through this simple example.

authors = json_normalize(data = d['hits']['hits'],
                         record_path = ['_source', 'authors'],
                         meta = ['_id', ['_source', 'journal'], ['_source', 'title'],
                                 ['_source', 'normalized_venue_name']
                                 ])

Below is a chunk of the json file (5 records).

{u'_shards': {u'failed': 0, u'successful': 5, u'total': 5},
 u'hits': {u'hits': [{u'_id': u'7CB3F2AD',
    u'_index': u'scibase_listings',
    u'_score': 1.0,
    u'_source': {u'authors': None,
     u'deleted': 0,
     u'description': None,
     u'doi': u'',
     u'is_valid': 1,
     u'issue': None,
     u'journal': u'Physical Review Letters',
     u'link': None,
     u'meta_description': None,
     u'meta_keywords': None,
     u'normalized_venue_name': u'phys rev lett',
     u'pages': None,
     u'parent_keywords': [u'Chromatography',
      u'Quantum mechanics',
      u'Particle physics',
      u'Quantum field theory',
      u'Analytical chemistry',
      u'Quantum chromodynamics',
      u'Physics',
      u'Mass spectrometry',
      u'Chemistry'],
     u'pub_date': u'1987-03-02 00:00:00',
     u'pubtype': None,
     u'rating_avg_weighted': 0,
     u'rating_clarity': 0.0,
     u'rating_clarity_weighted': 0.0,
     u'rating_innovation': 0.0,
     u'rating_innovation_weighted': 0.0,
     u'rating_num_weighted': 0,
     u'rating_reproducability': 0,
     u'rating_reproducibility_weighted': 0.0,
     u'rating_versatility': 0.0,
     u'rating_versatility_weighted': 0.0,
     u'review_count': 0,
     u'tag': [u'mass spectra', u'elementary particles', u'bound states'],
     u'title': u'Evidence for a new meson: A quasinuclear NN-bar bound state',
     u'userAvg': 0.0,
     u'user_id': None,
     u'venue_name': u'Physical Review Letters',
     u'views_count': 0,
     u'volume': None},
    u'_type': u'listing'},
   {u'_id': u'7AF8EBC3',
    u'_index': u'scibase_listings',
    u'_score': 1.0,
    u'_source': {u'authors': [{u'affiliations': [u'Punjabi University'],
       u'author_id': u'780E3459',
       u'author_name': u'munish puri'},
      {u'affiliations': [u'Punjabi University'],
       u'author_id': u'48D92C79',
       u'author_name': u'rajesh dhaliwal'},
      {u'affiliations': [u'Punjabi University'],
       u'author_id': u'7D9BD37C',
       u'author_name': u'r s singh'}],
     u'deleted': 0,
     u'description': None,
     u'doi': u'',
     u'is_valid': 1,
     u'issue': None,
     u'journal': u'Journal of Industrial Microbiology & Biotechnology',
     u'link': None,
     u'meta_description': None,
     u'meta_keywords': None,
     u'normalized_venue_name': u'j ind microbiol biotechnol',
     u'pages': None,
     u'parent_keywords': [u'Nuclear medicine',
      u'Psychology',
      u'Hydrology',
      u'Chromatography',
      u'X-ray crystallography',
      u'Nuclear fusion',
      u'Medicine',
      u'Fluid dynamics',
      u'Thermodynamics',
      u'Physics',
      u'Gas chromatography',
      u'Radiobiology',
      u'Engineering',
      u'Organic chemistry',
      u'High-performance liquid chromatography',
      u'Chemistry',
      u'Organic synthesis',
      u'Psychotherapist'],
     u'pub_date': u'2008-04-04 00:00:00',
     u'pubtype': None,
     u'rating_avg_weighted': 0,
     u'rating_clarity': 0.0,
     u'rating_clarity_weighted': 0.0,
     u'rating_innovation': 0.0,
     u'rating_innovation_weighted': 0.0,
     u'rating_num_weighted': 0,
     u'rating_reproducability': 0,
     u'rating_reproducibility_weighted': 0.0,
     u'rating_versatility': 0.0,
     u'rating_versatility_weighted': 0.0,
     u'review_count': 0,
     u'tag': [u'flow rate',
      u'operant conditioning',
      u'packed bed reactor',
      u'immobilized enzyme',
      u'specific activity'],
     u'title': u'Development of a stable continuous flow immobilized enzyme reactor for the hydrolysis of inulin',
     u'userAvg': 0.0,
     u'user_id': None,
     u'venue_name': u'Journal of Industrial Microbiology & Biotechnology',
     u'views_count': 0,
     u'volume': None},
    u'_type': u'listing'},
   {u'_id': u'7521A721',
    u'_index': u'scibase_listings',
    u'_score': 1.0,
    u'_source': {u'authors': [{u'author_id': u'7FF872BC',
       u'author_name': u'barbara eileen ryan'}],
     u'deleted': 0,
     u'description': None,
     u'doi': u'',
     u'is_valid': 1,
     u'issue': None,
     u'journal': u'The American Historical Review',
     u'link': None,
     u'meta_description': None,
     u'meta_keywords': None,
     u'normalized_venue_name': u'american historical review',
     u'pages': None,
     u'parent_keywords': [u'Social science',
      u'Politics',
      u'Sociology',
      u'Law'],
     u'pub_date': u'1992-01-01 00:00:00',
     u'pubtype': None,
     u'rating_avg_weighted': 0,
     u'rating_clarity': 0.0,
     u'rating_clarity_weighted': 0.0,
     u'rating_innovation': 0.0,
     u'rating_innovation_weighted': 0.0,
     u'rating_num_weighted': 0,
     u'rating_reproducability': 0,
     u'rating_reproducibility_weighted': 0.0,
     u'rating_versatility': 0.0,
     u'rating_versatility_weighted': 0.0,
     u'review_count': 0,
     u'tag': [u'social movements'],
     u'title': u"Feminism and the women's movement : dynamics of change in social movement ideology, and activism",
     u'userAvg': 0.0,
     u'user_id': None,
     u'venue_name': u'The American Historical Review',
     u'views_count': 0,
     u'volume': None},
    u'_type': u'listing'},
   {u'_id': u'7DAEB9A4',
    u'_index': u'scibase_listings',
    u'_score': 1.0,
    u'_source': {u'authors': [{u'author_id': u'0299B8E9',
       u'author_name': u'fraser j harbutt'}],
     u'deleted': 0,
     u'description': None,
     u'doi': u'',
     u'is_valid': 1,
     u'issue': None,
     u'journal': u'The American Historical Review',
     u'link': None,
     u'meta_description': None,
     u'meta_keywords': None,
     u'normalized_venue_name': u'american historical review',
     u'pages': None,
     u'parent_keywords': [u'Superconductivity',
      u'Nuclear fusion',
      u'Geology',
      u'Chemistry',
      u'Metallurgy'],
     u'pub_date': u'1988-01-01 00:00:00',
     u'pubtype': None,
     u'rating_avg_weighted': 0,
     u'rating_clarity': 0.0,
     u'rating_clarity_weighted': 0.0,
     u'rating_innovation': 0.0,
     u'rating_innovation_weighted': 0.0,
     u'rating_num_weighted': 0,
     u'rating_reproducability': 0,
     u'rating_reproducibility_weighted': 0.0,
     u'rating_versatility': 0.0,
     u'rating_versatility_weighted': 0.0,
     u'review_count': 0,
     u'tag': [u'iron'],
     u'title': u'The iron curtain : Churchill, America, and the origins of the Cold War',
     u'userAvg': 0.0,
     u'user_id': None,
     u'venue_name': u'The American Historical Review',
     u'views_count': 0,
     u'volume': None},
    u'_type': u'listing'},
   {u'_id': u'7B3236C5',
    u'_index': u'scibase_listings',
    u'_score': 1.0,
    u'_source': {u'authors': [{u'author_id': u'7DAB7B72',
       u'author_name': u'richard m freeland'}],
     u'deleted': 0,
     u'description': None,
     u'doi': u'',
     u'is_valid': 1,
     u'issue': None,
     u'journal': u'The American Historical Review',
     u'link': None,
     u'meta_description': None,
     u'meta_keywords': None,
     u'normalized_venue_name': u'american historical review',
     u'pages': None,
     u'parent_keywords': [u'Political Science', u'Economics'],
     u'pub_date': u'1985-01-01 00:00:00',
     u'pubtype': None,
     u'rating_avg_weighted': 0,
     u'rating_clarity': 0.0,
     u'rating_clarity_weighted': 0.0,
     u'rating_innovation': 0.0,
     u'rating_innovation_weighted': 0.0,
     u'rating_num_weighted': 0,
     u'rating_reproducability': 0,
     u'rating_reproducibility_weighted': 0.0,
     u'rating_versatility': 0.0,
     u'rating_versatility_weighted': 0.0,
     u'review_count': 0,
     u'tag': [u'foreign policy'],
     u'title': u'The Truman Doctrine and the origins of McCarthyism : foreign policy, domestic politics, and internal security, 1946-1948',
     u'userAvg': 0.0,
     u'user_id': None,
     u'venue_name': u'The American Historical Review',
     u'views_count': 0,
     u'volume': None},
    u'_type': u'listing'}],
  u'max_score': 1.0,
  u'total': 36429433},
 u'timed_out': False,
 u'took': 170}


问:
JQuery not keyword
```<code>$("li a").click(function() {
    $(this).parent().css({ width: 160 });
    $("li").unbind('mouseenter mouseleave');
    $("#Container").css({ width: 200 }).animate({ width: 700 }, 1000);
});
</code>```

I wanna set width 120 for all li's except current(this).

Thanks

Title: JQuery not keyword

Body:
$("li a").click(function() {
    $(this).parent().css({ width: 160 });
    $("li").unbind('mouseenter mouseleave');
    $("#Container").css({ width: 200 }).animate({ width: 700 }, 1000);
});

I wanna set width 120 for all li's except current(this).

Thanks

Body: $("li").not($(this).closest('li')).width(120);


问:
Calling setValuesForKeys fails in my Swift 4 code
I'm having this problem, im trying to retrieve data from the firebase database, but it's saying the profilepic isn't a key, but it is. This is the object class.

```<code>class User: NSObject {
    var firstname: String?
    var lastname: String?
    var username: String?
    var profilepic: String?
}
</code>```

and this is me trying to retrieve

```<code>func getusers(){
        ref.child("Friends").child(currentuser!).observe(.childAdded, with: { (snapshot) in
            print(snapshot)
            if let dic = snapshot.value as? [String: AnyObject]{
                let user = User()
                user.setValuesForKeys(dic)
                print(user.firstname, user.lastname)

                DispatchQueue.main.async {
                    self.tableview.reloadData()
                }}
        }) { (error) in
            print(error.localizedDescription)
        }

    }
</code>```

and the crash is here user.setValuesForKeys(dic).

Anyone has any idea why isn't working?

答:
Try this instead:

```<code>@objcMembers
class User: NSObject {
    ...
}
</code>```

The setValuesForKeys API is implemented by the Foundation framework and requires Objective-C compatibility.

The rules for exposing Swift code to Objective-C have changed considerably in Swift 4. Please check the evolution proposal for further information.

User class design. If any of the four properties can be missing from Firebase than your class design might be a good fit. Otherwise, consider declaring the fixed properties as non-optional and creating an initializer instead.

Body:
I'm having this problem, im trying to retrieve data from the firebase database, but it's saying the profilepic isn't a key, but it is. This is the object class.

class User: NSObject {
    var firstname: String?
    var lastname: String?
    var username: String?
    var profilepic: String?
}

and this is me trying to retrieve

func getusers(){
        ref.child("Friends").child(currentuser!).observe(.childAdded, with: { (snapshot) in
            print(snapshot)
            if let dic = snapshot.value as? [String: AnyObject]{
                let user = User()
                user.setValuesForKeys(dic)
                print(user.firstname, user.lastname)

                DispatchQueue.main.async {
                    self.tableview.reloadData()
                }}
        }) { (error) in
            print(error.localizedDescription)
        }

    }

and the crash is here user.setValuesForKeys(dic).

Anyone has any idea why isn't working?

Body:
Try this instead:

@objcMembers
class User: NSObject {
    ...
}

The setValuesForKeys API is implemented by the Foundation framework and requires Objective-C compatibility.

The rules for exposing Swift code to Objective-C have changed considerably in Swift 4. Please check the evolution proposal for further information.

User class design. If any of the four properties can be missing from Firebase than your class design might be a good fit. Otherwise, consider declaring the fixed properties as non-optional and creating an initializer instead.


问:
Javascript: Merging a dynamic object's value into another object's array
In React/Redux, I have a dynamic object (action.payload):

```<code>{
  cars: "Ferrari"
}
</code>```

which I need to combine to a nested object (redux):

```<code>{
  filters: {
    ships: ['Star'],
    cars: ['Ford']
    airplanes: ['Boeing']
  }
}
</code>```

I tried this but it seems this is merging with 'filters' still being maintained:

```<code>return {
  ...state,
  filters: Object.assign({}, state.filters, action.payload)
}
</code>```

I am expecting the arrays to merge and get something like:

```<code>{
  filters: {
    ships: ['Star'],
    cars: ['Ford', 'Ferrari']
    airplanes: ['Boeing']
  }
}
</code>```

答:
You can try this :</p>

```<code>return{
...state,
filters: {...state.filters,
cars: [...state.filters.cars, action.payload.cars],
ships: [...state.filters.ships, action.payload.ships],
airplanes: [...state.filters.airplanes, action.payload.airplanes]}
 }
</code>```

Body:
In React/Redux, I have a dynamic object (action.payload):

{
  cars: "Ferrari"
}

which I need to combine to a nested object (redux):

{
  filters: {
    ships: ['Star'],
    cars: ['Ford']
    airplanes: ['Boeing']
  }
}

I tried this but it seems this is merging with 'filters' still being maintained:

return {
  ...state,
  filters: Object.assign({}, state.filters, action.payload)
}

I am expecting the arrays to merge and get something like:

{
  filters: {
    ships: ['Star'],
    cars: ['Ford', 'Ferrari']
    airplanes: ['Boeing']
  }
}

Body:
You can try this :

return{
...state,
filters: {...state.filters,
cars: [...state.filters.cars, action.payload.cars],
ships: [...state.filters.ships, action.payload.ships],
airplanes: [...state.filters.airplanes, action.payload.airplanes]}
 }


问:
JOIN or Conditional Logic Between 4+ Tables
Full disclosure, this is a homework question, but I have 20 more of these that are much more difficult, I just really can't wrap my head around some of the more complicated statements, so I'd appreciate the help before I just give up on the assignment completely. The professor and TA declined any help.

I'm using the 'HR' table that is present as a demo in all Oracle DBs. I need to create a unique listing of all jobs in a particular department along with the locations. It has the tables: REGIONS, LOCATIONS, DEPARTMENTS, JOBS, and EMPLOYEES of the form described below:

Locations:

```<code> Name                      Null?    Type
 ----------------------------------------- -------- ----------------------------
 LOCATION_ID                   NOT NULL NUMBER(4)
 STREET_ADDRESS                     VARCHAR2(40)
 POSTAL_CODE                        VARCHAR2(12)
 CITY                      NOT NULL VARCHAR2(30)
 STATE_PROVINCE                     VARCHAR2(25)
 COUNTRY_ID                     CHAR(2)
</code>```

Jobs:

```<code> Name                      Null?    Type
 ----------------------------------------- -------- ----------------------------
 JOB_ID                    NOT NULL VARCHAR2(10)
 JOB_TITLE                 NOT NULL VARCHAR2(35)
 MIN_SALARY                     NUMBER(6)
 MAX_SALARY                     NUMBER(6)
</code>```

Employees:

```<code> Name                      Null?    Type
 ----------------------------------------- -------- ----------------------------
 EMPLOYEE_ID                   NOT NULL NUMBER(6)
 FIRST_NAME                     VARCHAR2(20)
 LAST_NAME                 NOT NULL VARCHAR2(25)
 EMAIL                     NOT NULL VARCHAR2(25)
 PHONE_NUMBER                       VARCHAR2(20)
 HIRE_DATE                 NOT NULL DATE
 JOB_ID                    NOT NULL VARCHAR2(10)
 SALARY                         NUMBER(8,2)
 COMMISSION_PCT                     NUMBER(2,2)
 MANAGER_ID                     NUMBER(6)
 DEPARTMENT_ID                      NUMBER(4)
</code>```

Departments:

```<code> Name                      Null?    Type
 ----------------------------------------- -------- ----------------------------
 DEPARTMENT_ID                 NOT NULL NUMBER(4)
 DEPARTMENT_NAME               NOT NULL VARCHAR2(30)
 MANAGER_ID                     NUMBER(6)
 LOCATION_ID                        NUMBER(4)
</code>```

So of course I can think through how the relational algebra kind of goes, but I have no clue how it would go in SQL syntax. I of course know how to do more trivial joins, but I'm not understanding how to agregate all of the requirements into one statement. I want to get all UNIQUE or DISTINCT JOB_IDs where DEPARTMENT_ID=80,Then do a join on Jobs to get the matching JOB_TITLE,then derive LOCATION_ID from DEPARTMENTS.DEPARTMENT_ID and finally join Locations to my original JOB_TITLE selection WHERE LOCATION.LOCATION_ID=DEPARTMENTS.DEPARTMENT_ID. So what does that look like. Do I have to do 3 joins to get all the information in one selection?

答:
Smth like that, perhaps

New-fashioned joins:

```<code>select tloc.*, tdept.*, tjobs.*
from locations tloc
  inner join departments tdept on (tloc.location_id=tdept.location_id)
  inner join employees templ on (tdept.department_id=templ.department_id)
  inner join jobs tjobs on (templ.employee_id=tjobs.employee_id)
where
  tdept.department_id=80
</code>```

Old-fashioned joins:

```<code>select tloc.*, tdept.*, tjobs.*
from locations tloc, departments tdept, employees templ, jobs tjobs
where
  tloc.location_id=tdept.location_id
  and tdept.department_id=templ.department_id
  and templ.employee_id=tjobs.employee_id
  ----
  and tdept.department_id=80
</code>```

Body:
Full disclosure, this is a homework question, but I have 20 more of these that are much more difficult, I just really can't wrap my head around some of the more complicated statements, so I'd appreciate the help before I just give up on the assignment completely. The professor and TA declined any help.

I'm using the 'HR' table that is present as a demo in all Oracle DBs. I need to create a unique listing of all jobs in a particular department along with the locations. It has the tables: REGIONS, LOCATIONS, DEPARTMENTS, JOBS, and EMPLOYEES of the form described below:

Locations:

 Name                      Null?    Type
 ----------------------------------------- -------- ----------------------------
 LOCATION_ID                   NOT NULL NUMBER(4)
 STREET_ADDRESS                     VARCHAR2(40)
 POSTAL_CODE                        VARCHAR2(12)
 CITY                      NOT NULL VARCHAR2(30)
 STATE_PROVINCE                     VARCHAR2(25)
 COUNTRY_ID                     CHAR(2)

Jobs:

 Name                      Null?    Type
 ----------------------------------------- -------- ----------------------------
 JOB_ID                    NOT NULL VARCHAR2(10)
 JOB_TITLE                 NOT NULL VARCHAR2(35)
 MIN_SALARY                     NUMBER(6)
 MAX_SALARY                     NUMBER(6)

Employees:

 Name                      Null?    Type
 ----------------------------------------- -------- ----------------------------
 EMPLOYEE_ID                   NOT NULL NUMBER(6)
 FIRST_NAME                     VARCHAR2(20)
 LAST_NAME                 NOT NULL VARCHAR2(25)
 EMAIL                     NOT NULL VARCHAR2(25)
 PHONE_NUMBER                       VARCHAR2(20)
 HIRE_DATE                 NOT NULL DATE
 JOB_ID                    NOT NULL VARCHAR2(10)
 SALARY                         NUMBER(8,2)
 COMMISSION_PCT                     NUMBER(2,2)
 MANAGER_ID                     NUMBER(6)
 DEPARTMENT_ID                      NUMBER(4)

Departments:

 Name                      Null?    Type
 ----------------------------------------- -------- ----------------------------
 DEPARTMENT_ID                 NOT NULL NUMBER(4)
 DEPARTMENT_NAME               NOT NULL VARCHAR2(30)
 MANAGER_ID                     NUMBER(6)
 LOCATION_ID                        NUMBER(4)

So of course I can think through how the relational algebra kind of goes, but I have no clue how it would go in SQL syntax. I of course know how to do more trivial joins, but I'm not understanding how to agregate all of the requirements into one statement. I want to get all UNIQUE or DISTINCT JOB_IDs where DEPARTMENT_ID=80,Then do a join on Jobs to get the matching JOB_TITLE,then derive LOCATION_ID from DEPARTMENTS.DEPARTMENT_ID and finally join Locations to my original JOB_TITLE selection WHERE LOCATION.LOCATION_ID=DEPARTMENTS.DEPARTMENT_ID. So what does that look like. Do I have to do 3 joins to get all the information in one selection?

Body:
Smth like that, perhaps

New-fashioned joins:

select tloc.*, tdept.*, tjobs.*
from locations tloc
  inner join departments tdept on (tloc.location_id=tdept.location_id)
  inner join employees templ on (tdept.department_id=templ.department_id)
  inner join jobs tjobs on (templ.employee_id=tjobs.employee_id)
where
  tdept.department_id=80

Old-fashioned joins:

select tloc.*, tdept.*, tjobs.*
from locations tloc, departments tdept, employees templ, jobs tjobs
where
  tloc.location_id=tdept.location_id
  and tdept.department_id=templ.department_id
  and templ.employee_id=tjobs.employee_id
  ----
  and tdept.department_id=80


问:
C# How to turn String with Carriage Return symbols in to an array
I am calling some external method that returns a string like this.

```<code>"[\r\n  \"0\",\r\n  \"1\",\r\n  \"2\"\r\n]"
</code>```

How do I turn this in to an Array with the values 1,2,3 ?

Should I be trying to split/substring methods to do this, or is there some kind of built in .net method that can do this?

I have tried,

```<code>string theStringResult = Class.ExternalMethod();
theStringResult.ToArray()
</code>```

答:
The method you're looking for is String.Split.  It takes a single character as a parameter and returns an array of pieces split wherever that character is found.

In your case you have two characters ("\r\n") so either you split and post-process the array, or you replace the pair with a single character and then split.

In code it looks like this:

```<code>string source = "\r\n0\r\n1\r\n2\r\n";
string parts = source.Replace("\r\n", "\n").Split('\n');
</code>```

The resultant array is ["0", "1", "2"].

Oh, that's a literal JSON string... that wasn't entirely clear on first viewing.

If the array is fairly consistent you could do string manipulation, but it's not ideal.

Add the NewtonSoft.Json NuGet package to your project and use the following:

```<code>string source = "[\r\n  \"0\",\r\n  \"1\",\r\n  \"2\"\r\n]";
string[] parts = Newtonsoft.Json.JsonConvert.DeserializeObject<string[]>(source);
</code>```

Same output as above.

Body:
I am calling some external method that returns a string like this.

"[\r\n  \"0\",\r\n  \"1\",\r\n  \"2\"\r\n]"

How do I turn this in to an Array with the values 1,2,3 ?

Should I be trying to split/substring methods to do this, or is there some kind of built in .net method that can do this?

I have tried,

string theStringResult = Class.ExternalMethod();
theStringResult.ToArray()

Body:
The method you're looking for is String.Split.  It takes a single character as a parameter and returns an array of pieces split wherever that character is found.

In your case you have two characters ("\r\n") so either you split and post-process the array, or you replace the pair with a single character and then split.

In code it looks like this:

string source = "\r\n0\r\n1\r\n2\r\n";
string parts = source.Replace("\r\n", "\n").Split('\n');

The resultant array is ["0", "1", "2"].

Oh, that's a literal JSON string... that wasn't entirely clear on first viewing.

If the array is fairly consistent you could do string manipulation, but it's not ideal.

Add the NewtonSoft.Json NuGet package to your project and use the following:

string source = "[\r\n  \"0\",\r\n  \"1\",\r\n  \"2\"\r\n]";
string[] parts = Newtonsoft.Json.JsonConvert.DeserializeObject<string[]>(source);

Same output as above.


答:
\d+ is the regex for an integer number. So

```<code>//System.Text.RegularExpressions.Regex
resultString = Regex.Match(subjectString, @"\d+").Value;
</code>```

returns a string containing the first occurrence of a number in subjectString.

Int32.Parse(resultString) will then give you the number.

Title: Find and extract a number from a string

Body:
I have a requirement to find and extract a number contained within a string.

For example, from these strings:

string test = "1 test"
string test1 = " 1 test"
string test2 = "test 99"

How can I do this?

Body:
\d+ is the regex for an integer number. So

//System.Text.RegularExpressions.Regex
resultString = Regex.Match(subjectString, @"\d+").Value;

returns a string containing the first occurrence of a number in subjectString.

Int32.Parse(resultString) will then give you the number.


问:
Domain not resolving to elastic IP amazon linux
I pointed my domain name that I registered through route 53 here: Response returned by Route 53

```<code>DNS request sent to Route 53
arcadeidea.com.     IN     A
EDNS0 client subnet IP
24
DNS response code
NOERROR
Protocol
UDP
Response returned by Route 53
34.214.33.108
</code>```

And when I try going to the elastic IP (34.214.33.108) I get the hello world html page served by a sample

```<code>arcadeidea.com’s server DNS address could not be found.
DNS_PROBE_FINISHED_NXDOMAIN
</code>```

I think it may be a problem with port forwarding, as I'm forwarding 80 to 8080 which is what the sample node app was setup as a default. Not sure how to debug that though...Any thoughts?

答: So what worked for me was resetting my wireless router...my other computer that was directly plugged into the modem was able to load the site after associating the IP with the domain, but not the computer that was wired to my router. I was able to verify this when I used my phone to check the site, while connected to my wireless router's network...Network admins, I understand a little more of your pain now.</p>

Body:
I pointed my domain name that I registered through route 53 here: Response returned by Route 53

DNS request sent to Route 53
arcadeidea.com.     IN     A
EDNS0 client subnet IP
24
DNS response code
NOERROR
Protocol
UDP
Response returned by Route 53
34.214.33.108

And when I try going to the elastic IP (34.214.33.108) I get the hello world html page served by a sample

arcadeidea.com’s server DNS address could not be found.
DNS_PROBE_FINISHED_NXDOMAIN

I think it may be a problem with port forwarding, as I'm forwarding 80 to 8080 which is what the sample node app was setup as a default. Not sure how to debug that though...Any thoughts?


答:
Try this.

```<code>string Originalstring = "[\r\n  \"0\",\r\n  \"1\",\r\n  \"2\"\r\n]";
string[] result = Originalstring.Split(new String[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
</code>```

This should split a string that has a carriage return into an array and remove any empty entries

Title: C# How to turn String with Carriage Return symbols in to an array

Body:
Try this.

string Originalstring = "[\r\n  \"0\",\r\n  \"1\",\r\n  \"2\"\r\n]";
string[] result = Originalstring.Split(new String[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);

This should split a string that has a carriage return into an array and remove any empty entries


问:
How do I PIVOT on an XML column?
Is it possible, using SQL Server 2014 Standard Edition, to PIVOT on the value of an XML column name?  Ultimately I'd like to take this:

```<code><table>
  <id>{3d2699c4-3159-4e8b-b48c-c2c4c9b5bd77}</id>
  <rows>
    <row>
      <columns>
        <column name="DESC" value="DACS" type="System.String" />
        <column name="ec_amount" value="5000" type="System.Decimal" />
        <column name="ec_exrate" value="1" type="System.Decimal" />
        <column name="ec_total" value="5000.00" type="System.Decimal" />
        <column name="ItemNo" value="PVT-C30" type="System.String" />
        <column name="UOM" value="EA" type="System.String" />
        <column name="DefaultKey" value="1" type="System.Int32" /><----THIS IS THE COLUMN ON WHICH I WOULD LIKE TO PIVOT
      </columns>
    </row>
    <row>
      <columns>
        <column name="DESC" value="DACS" type="System.String" />
        <column name="ec_amount" value="1500" type="System.Decimal" />
        <column name="ec_exrate" value="5" type="System.Decimal" />
        <column name="ec_total" value="7500.00" type="System.Decimal" />
        <column name="ItemNo" value="PVT-C30" type="System.String" />
        <column name="UOM" value="EA" type="System.String" />
        <column name="DefaultKey" value="2" type="System.Int32" />
      </columns>
    </row>
  </rows>
  <key>DefaultKey</key>
  <total>12500.00</total>
  <data />
  <parameters />
</table>
</code>```

....and create these results:

```<code>DefaultKey  DESC    ec_amount   ec_exrate   ec_total    ItemNo      UOM
1           DACS    5000        1           5000        PVT-C30     EA
2           DACS    1500        5           7500        PVT-C30     EA
</code>```

I've searched the Stack Overflow site and of everything I came across, these two posts came close, but they don't quite get me there:

SQL Pivot using an XML column

How do I Pivot on an XML column's attributes in T-SQL

My apologies if this has already been addressed and I simply gave up too soon.

答:
You essentially need to assign a row number to each "row" of XML (or figure out some other way of distinguishing each "row"). One way you could go about this is by extracting the default key from each "row" (by using a window function and partitioning):

```<code>SELECT *
FROM
(
    SELECT Name = C2.X.value('@name', 'varchar(max)'),
           Val = C2.X.value('@value', 'varchar(max)'),
           DefaultKey = MAX(CASE WHEN C2.X.value('@name', 'varchar(max)') = 'DefaultKey' THEN C2.X.value('@value', 'varchar(max)') END) OVER(PARTITION BY C1.X)
    FROM myTable
    CROSS APPLY myXMLColumn.nodes('table/rows/row/columns') AS C1(X)
    CROSS APPLY C1.X.nodes('column') AS C2(X)
) AS T
PIVOT (MAX(Val) FOR Name IN ([DESC], [ec_amount], [ec_exrate], [ec_total], [ItemNo], [UOM])) AS P;
</code>```

If DefaultKey weren't unique, you could use a row number or rank window function instead to each a similar result:

```<code>SELECT *
FROM
(
    SELECT Name = C2.X.value('@name', 'varchar(max)'),
           Val = C2.X.value('@value', 'varchar(max)'),
           RowInXML = DENSE_RANK() OVER (ORDER BY C1.X)
    FROM myTable
    CROSS APPLY myXMLColumn.nodes('table/rows/row/columns') AS C1(X)
    CROSS APPLY C1.X.nodes('column') AS C2(X)
) AS T
PIVOT (MAX(Val) FOR Name IN ([DefaultKey], [DESC], [ec_amount], [ec_exrate], [ec_total], [ItemNo], [UOM])) AS P;
</code>```

Title: How do I PIVOT on an XML column?

Body:
Is it possible, using SQL Server 2014 Standard Edition, to PIVOT on the value of an XML column name?  Ultimately I'd like to take this:

  <id>{3d2699c4-3159-4e8b-b48c-c2c4c9b5bd77}</id>
  <rows>
    <row>
      <columns>
        <column name="DESC" value="DACS" type="System.String" />
        <column name="ec_amount" value="5000" type="System.Decimal" />
        <column name="ec_exrate" value="1" type="System.Decimal" />
        <column name="ec_total" value="5000.00" type="System.Decimal" />
        <column name="ItemNo" value="PVT-C30" type="System.String" />
        <column name="UOM" value="EA" type="System.String" />
        <column name="DefaultKey" value="1" type="System.Int32" /><----THIS IS THE COLUMN ON WHICH I WOULD LIKE TO PIVOT
      </columns>
    </row>
    <row>
      <columns>
        <column name="DESC" value="DACS" type="System.String" />
        <column name="ec_amount" value="1500" type="System.Decimal" />
        <column name="ec_exrate" value="5" type="System.Decimal" />
        <column name="ec_total" value="7500.00" type="System.Decimal" />
        <column name="ItemNo" value="PVT-C30" type="System.String" />
        <column name="UOM" value="EA" type="System.String" />
        <column name="DefaultKey" value="2" type="System.Int32" />
      </columns>
    </row>
  </rows>
  <key>DefaultKey</key>
  <total>12500.00</total>
  <data />
  <parameters />

....and create these results:

DefaultKey  DESC    ec_amount   ec_exrate   ec_total    ItemNo      UOM
1           DACS    5000        1           5000        PVT-C30     EA
2           DACS    1500        5           7500        PVT-C30     EA

I've searched the Stack Overflow site and of everything I came across, these two posts came close, but they don't quite get me there:

SQL Pivot using an XML column

How do I Pivot on an XML column's attributes in T-SQL

My apologies if this has already been addressed and I simply gave up too soon.

Body:
You essentially need to assign a row number to each "row" of XML (or figure out some other way of distinguishing each "row"). One way you could go about this is by extracting the default key from each "row" (by using a window function and partitioning):

SELECT *
FROM
(
    SELECT Name = C2.X.value('@name', 'varchar(max)'),
           Val = C2.X.value('@value', 'varchar(max)'),
           DefaultKey = MAX(CASE WHEN C2.X.value('@name', 'varchar(max)') = 'DefaultKey' THEN C2.X.value('@value', 'varchar(max)') END) OVER(PARTITION BY C1.X)
    FROM myTable
    CROSS APPLY myXMLColumn.nodes('table/rows/row/columns') AS C1(X)
    CROSS APPLY C1.X.nodes('column') AS C2(X)
) AS T
PIVOT (MAX(Val) FOR Name IN ([DESC], [ec_amount], [ec_exrate], [ec_total], [ItemNo], [UOM])) AS P;

If DefaultKey weren't unique, you could use a row number or rank window function instead to each a similar result:

SELECT *
FROM
(
    SELECT Name = C2.X.value('@name', 'varchar(max)'),
           Val = C2.X.value('@value', 'varchar(max)'),
           RowInXML = DENSE_RANK() OVER (ORDER BY C1.X)
    FROM myTable
    CROSS APPLY myXMLColumn.nodes('table/rows/row/columns') AS C1(X)
    CROSS APPLY C1.X.nodes('column') AS C2(X)
) AS T
PIVOT (MAX(Val) FOR Name IN ([DefaultKey], [DESC], [ec_amount], [ec_exrate], [ec_total], [ItemNo], [UOM])) AS P;