Title: Remove caution from json obj

Body:
Here I attached json result.

"properties": {
                "id": 99,
                "county": "Ashe",
                "cen_lat": 36.4343964583676,
                "cen_long": -81.5004915302458,
                "county_id": "5",
                "extent": "[-9099469.85881319,4333729.96758589,-9044051.86962052,4381852.80674575]"
            }

when I read extent and getting result is

"[-9099469.85881319,4333729.96758589,-9044051.86962052,4381852.80674575]"

but I need

[-9099469.85881319,4333729.96758589,-9044051.86962052,4381852.80674575]

How can I get?

Body:
As stated in the comments.

JSON.parse("[-9099469.85881319,4333729.96758589,-9044051.86962052,4381852.80674575]");


来源: stackexchange

问:
How to calculate alternating sum of digits of an integer in Perl 6?

A number is divisible by 11 if its alternating sum of digits is
  divisible by 11.

So, e.g. if number is 1595, +1 -5 +9 -5 == 0, so 1595 is divisible by 11. How to implement such a sum? Here is my solution, but it's too complex and works only if the number of digits is even.

```<code>my $number = 1595;
say [+] $number.comb.map({$^a - $^b});
</code>```

What's the best way to do it?

答:
The cross that Moritz uses is interesting (and quite pleasing) but you can also take chunks of a list. This is close to what you were trying initially. I think you were going toward rotor:

```<code>my $number = 1595;
say  [+] $number.comb.rotor(2, :partial).map: { $^a.[0] - ($^a.[1] // 0) }
</code>```

Notice that you get one argument to your block. That's the list. It's a bit ugly because the odd digit case makes $^a.[1] Nil which would give a warning.

Now that I've played with this a bit more I handle that with a signature so I can give $b a default. This is much better:

```<code>my $number = 1595;
say  [+] $number
    .comb
    .rotor(2, :partial)
    .map: -> ( $a, $b = 0 ) { $a - $b }
</code>```

But you don't even need the rotor because the map will grab as many positional parameters as it needs (h/t to timotimo in the comments). This means you were really close and merely missed the signature:

```<code>my $number = 1595;
say  [+] $number
    .comb
    .map: -> ( $a, $b = 0 ) { $a - $b }
</code>```

The solution you have in the comment doesn't quite work for the odd number of digits cases:

```<code>say [+] $number.comb.rotor(2, :partial).map({[-] $_});
</code>```

And, I know this problem wasn't really about divisors but I'm quite pleased that Perl 6 has a "divisible by" operator, the %%:

```<code>$ perl6
> 121 %% 11
True
> 122 %% 11
False
> 1595 %% 11
True
> 1596 %% 11
False
</code>```

ContentLicense: CC BY-SA 3.0

Body:
A number is divisible by 11 if its alternating sum of digits is
  divisible by 11.

So, e.g. if number is 1595, +1 -5 +9 -5 == 0, so 1595 is divisible by 11. How to implement such a sum? Here is my solution, but it's too complex and works only if the number of digits is even.

my $number = 1595;
say [+] $number.comb.map({$^a - $^b});

What's the best way to do it?

Body:
The cross that Moritz uses is interesting (and quite pleasing) but you can also take chunks of a list. This is close to what you were trying initially. I think you were going toward rotor:

my $number = 1595;
say  [+] $number.comb.rotor(2, :partial).map: { $^a.[0] - ($^a.[1] // 0) }

Notice that you get one argument to your block. That's the list. It's a bit ugly because the odd digit case makes $^a.[1] Nil which would give a warning.

Now that I've played with this a bit more I handle that with a signature so I can give $b a default. This is much better:

my $number = 1595;
say  [+] $number
    .comb
    .rotor(2, :partial)
    .map: -> ( $a, $b = 0 ) { $a - $b }

But you don't even need the rotor because the map will grab as many positional parameters as it needs (h/t to timotimo in the comments). This means you were really close and merely missed the signature:

my $number = 1595;
say  [+] $number
    .comb
    .map: -> ( $a, $b = 0 ) { $a - $b }

The solution you have in the comment doesn't quite work for the odd number of digits cases:

say [+] $number.comb.rotor(2, :partial).map({[-] $_});

And, I know this problem wasn't really about divisors but I'm quite pleased that Perl 6 has a "divisible by" operator, the %%:

$ perl6
> 121 %% 11
True
> 122 %% 11
False
> 1595 %% 11
True
> 1596 %% 11
False


问:
How do I keep internal state in a WebAssembly module written in Rust?
I want to do computations on a large set of data each frame of my web app. Only a subset of this will be used by JavaScript, so instead of sending the entire set of data back and forth between WebAssembly and JavaScript each frame, it would be nice if the data was maintained internally in my WebAssembly module.

In C, something like this works:

#include <emscripten/emscripten.h>

int state = 0;

void EMSCRIPTEN_KEEPALIVE inc() {
    state++;
}

int EMSCRIPTEN_KEEPALIVE get() {
    return state;
}
```

<p>Is the same thing possible in Rust? I tried doing it with a <code>static</code> like this:</p>

```static mut state: i32 = 0;

pub fn main() {}

#[no_mangle]
pub fn add() {
    state += 1;
}

#[no_mangle]
pub fn get() -> i32 {
    state
}
```

But it seems static variables cannot be mutable.

答:
Francis Gagné is absolutely correct that global variables generally make your code worse and you should avoid them.

However, for the specific case of WebAssembly as it is today, we don't have to worry about this concern:

if you have multiple threads

We can thus choose to use mutable static variables, if we have a very good reason to do so:

```<code>// Only valid because we are using this in a WebAssembly
// context without threads.
static mut STATE: i32 = 0;

#[no_mangle]
pub extern fn add() {
    unsafe { STATE += 1 };
}

#[no_mangle]
pub extern fn get() -> i32 {
    unsafe { STATE }
}
</code>```

We can see the behavior with this NodeJS driver program:

```<code>const fs = require('fs-extra');

fs.readFile(__dirname + '/target/wasm32-unknown-unknown/release/state.wasm')
  .then(bytes => WebAssembly.instantiate(bytes))
  .then(({ module, instance }) => {
    const { get, add } = instance.exports;
    console.log(get());
    add();
    add();
    console.log(get());
});
</code>```

0
2
```

Body:
I want to do computations on a large set of data each frame of my web app. Only a subset of this will be used by JavaScript, so instead of sending the entire set of data back and forth between WebAssembly and JavaScript each frame, it would be nice if the data was maintained internally in my WebAssembly module.

In C, something like this works:

#include <emscripten/emscripten.h>

int state = 0;

void EMSCRIPTEN_KEEPALIVE inc() {
    state++;
}

int EMSCRIPTEN_KEEPALIVE get() {
    return state;
}

Is the same thing possible in Rust? I tried doing it with a static like this:

static mut state: i32 = 0;

pub fn main() {}

#[no_mangle]
pub fn add() {
    state += 1;
}

#[no_mangle]
pub fn get() -> i32 {
    state
}

But it seems static variables cannot be mutable.

Body:
Francis Gagné is absolutely correct that global variables generally make your code worse and you should avoid them.

However, for the specific case of WebAssembly as it is today, we don't have to worry about this concern:

if you have multiple threads

We can thus choose to use mutable static variables, if we have a very good reason to do so:

// Only valid because we are using this in a WebAssembly
// context without threads.
static mut STATE: i32 = 0;

#[no_mangle]
pub extern fn add() {
    unsafe { STATE += 1 };
}

#[no_mangle]
pub extern fn get() -> i32 {
    unsafe { STATE }
}

We can see the behavior with this NodeJS driver program:

const fs = require('fs-extra');

fs.readFile(__dirname + '/target/wasm32-unknown-unknown/release/state.wasm')
  .then(bytes => WebAssembly.instantiate(bytes))
  .then(({ module, instance }) => {
    const { get, add } = instance.exports;
    console.log(get());
    add();
    add();
    console.log(get());
});

0
2


问:
SQL Select Statement with order by as parameter
Having trouble getting this code to print what I need it to print.
I have a Drop Down list that lets the user select what they want the table to be sorted as. Im getting that Value and binding it to the Parameter '@param'. It is not putting the items of the table in the correct order.

NOTE: when I change the 'string sql' to a value that is in my Drop down list it works fine.

```<code>string sql = "Select * from yeet order by @param desc;";
MySqlCommand cmd = new MySqlCommand(sql, conn);
cmd.Prepare();
cmd.Parameters.AddWithValue("@param", DropTopWop.SelectedValue.ToString());
MySqlDataReader reader = cmd.ExecuteReader();
</code>```

答:
You need to do it like this instead:

```<code>order by
    case @param
        when 'PutYourColumNameHere' then PutYourColumNameHere
        when 'AnotherColumn' then AnotherColumn--, and so on
    end desc
</code>```

So for example if your table players has 2 columns named Age and Name, then it will look like this:

```<code>Select * from players
order by
    case @param
        when 'Age' then Age
        when 'Name' then Name
    end desc;
</code>```

Body:
Having trouble getting this code to print what I need it to print.
I have a Drop Down list that lets the user select what they want the table to be sorted as. Im getting that Value and binding it to the Parameter '@param'. It is not putting the items of the table in the correct order.

NOTE: when I change the 'string sql' to a value that is in my Drop down list it works fine.

string sql = "Select * from yeet order by @param desc;";
MySqlCommand cmd = new MySqlCommand(sql, conn);
cmd.Prepare();
cmd.Parameters.AddWithValue("@param", DropTopWop.SelectedValue.ToString());
MySqlDataReader reader = cmd.ExecuteReader();

Body:
You need to do it like this instead:

order by
    case @param
        when 'PutYourColumNameHere' then PutYourColumNameHere
        when 'AnotherColumn' then AnotherColumn--, and so on
    end desc

So for example if your table players has 2 columns named Age and Name, then it will look like this:

Select * from players
order by
    case @param
        when 'Age' then Age
        when 'Name' then Name
    end desc;


问:
Use map() for functions that does not return a value
I have a quick question:

If I have a function:

```<code>a = [1,2,3,4,5,6,7]
def f(x):
    return (x**2)
result = list(map(f, a))
print(result)
>>> [1, 4, 9, 16, 25, 36, 49]
</code>```

but if I:

```<code>result = []
a = [1,2,3,4,5,6,7]
def f(x):
    result.append(x**2)
map(f, a)
print(result)
>>> []
</code>```

it won't work.

However, it will work if I write the function this way:

```<code>result = []
a = [1,2,3,4,5,6,7]
def f(x):
    result.append(x**2)
for i in a:
    f(i)
print(result)
>>> [1, 4, 9, 16, 25, 36, 49]
</code>```

even if I include a return value for it:

```<code>result = []
a = [1,2,3,4,5,6,7]
def f(x):
    result.append(x**2)
    return x**2
map(f, a)
print(result)           # >>> []
print(list(map(f,a)))   # >>> [1,2,3,4,5,6,7]
</code>```

Should I understand it as the map() must be applied on a function with a return value and return value only.

答:
map creates an iterator. It doesn't do the mapping immediately, it does it one by one as you consume the iterator. list(map(...)) immediately consumes the entire iterator to turn it into a list. But in your tests where it doesn't work, you're never consuming the iterator, so f never gets called even once.

In other words: doesn't work:

```<code>map(f, a)
print(result)
</code>```

Works:

```<code>list(map(f, a))  # ← list consumes the iterator
print(result)
</code>```

Body:
I have a quick question:

If I have a function:

a = [1,2,3,4,5,6,7]
def f(x):
    return (x**2)
result = list(map(f, a))
print(result)
>>> [1, 4, 9, 16, 25, 36, 49]

but if I:

result = []
a = [1,2,3,4,5,6,7]
def f(x):
    result.append(x**2)
map(f, a)
print(result)
>>> []

it won't work.

However, it will work if I write the function this way:

result = []
a = [1,2,3,4,5,6,7]
def f(x):
    result.append(x**2)
for i in a:
    f(i)
print(result)
>>> [1, 4, 9, 16, 25, 36, 49]

even if I include a return value for it:

result = []
a = [1,2,3,4,5,6,7]
def f(x):
    result.append(x**2)
    return x**2
map(f, a)
print(result)           # >>> []
print(list(map(f,a)))   # >>> [1,2,3,4,5,6,7]

Should I understand it as the map() must be applied on a function with a return value and return value only.

Body:
map creates an iterator. It doesn't do the mapping immediately, it does it one by one as you consume the iterator. list(map(...)) immediately consumes the entire iterator to turn it into a list. But in your tests where it doesn't work, you're never consuming the iterator, so f never gets called even once.

In other words: doesn't work:

map(f, a)
print(result)

Works:

list(map(f, a))  # ← list consumes the iterator
print(result)


问:
Azure web job: Can't bind Queue to type 'System.String'
I've created a web job in Azure. This web job gets triggered by my web api. This web job also is set to run "continuously". However, from the moment I start the web job, I receive this error message (seen in the logs):

Can't bind Queue to type 'System.String'

And my web job tries to restart, and gets the same error message again, and again.

I've tried to do some research on this error message, but I'm not finding much of anything. Has anyone ever seen this error before? Here is my code in the functions.cs file:

```<code>namespace DownloadProcessor
{
    public class Functions
    {
        public static void ProcessQueueMessage([Queue("ringclonedownloadprocessorqueue")] string message, TextWriter log)
        {
            log.WriteLine("Processing" + message);
        }
    }
}
</code>```

It seems very straightforward. Also, here is my function in my Program.cs file:

```<code>namespace DownloadProcessor
{
    // To learn more about Microsoft Azure WebJobs SDK, please see http://go.microsoft.com/fwlink/?LinkID=320976
    class Program
    {
        // Please set the following connection strings in app.config for this WebJob to run:
        // AzureWebJobsDashboard and AzureWebJobsStorage
        static void Main()
        {
            var host = new JobHost();
            // The following code ensures that the WebJob will be running continuously
            host.RunAndBlock();
        }
    }
}
</code>```

It all seems very straightforward, and I have created other similar web jobs exactly like this. Has anyone ever seen this error message before? Any idea what I might be doing wrong?

答:
Just in case someone runs into this issue, I found out what was going on (in my case). My problem was with this line:

```<code>public static void ProcessQueueMessage([Queue("ringclonedownloadprocessorqueue")] string message, TextWriter log)
</code>```

This web job was not a continuous job when I first created it. And when Visual Studio created the code template, it used [Queue("ringclonedownloadprocessorqueue")] string message as the default parameter type. I recently changed the job to a continuous job, and a continuous job uses a slightly different param type (QueueTrigger instead of Queue). But when I changed the job to continuous, Visual Studio did not change the param type accordingly. I needed to go in and manually update the param type. Changing the function to this did the trick:

```<code>namespace DownloadProcessor
{
    public class Functions
    {
        public static void ProcessQueueMessage([QueueTrigger("ringclonedownloadprocessorqueue")] string message, TextWriter log)
        {
            log.WriteLine("Processing" + message);
        }
    }
}
</code>```

Body:
I've created a web job in Azure. This web job gets triggered by my web api. This web job also is set to run "continuously". However, from the moment I start the web job, I receive this error message (seen in the logs):

Can't bind Queue to type 'System.String'

And my web job tries to restart, and gets the same error message again, and again.

I've tried to do some research on this error message, but I'm not finding much of anything. Has anyone ever seen this error before? Here is my code in the functions.cs file:

namespace DownloadProcessor
{
    public class Functions
    {
        public static void ProcessQueueMessage([Queue("ringclonedownloadprocessorqueue")] string message, TextWriter log)
        {
            log.WriteLine("Processing" + message);
        }
    }
}

It seems very straightforward. Also, here is my function in my Program.cs file:

namespace DownloadProcessor
{
    // To learn more about Microsoft Azure WebJobs SDK, please see http://go.microsoft.com/fwlink/?LinkID=320976
    class Program
    {
        // Please set the following connection strings in app.config for this WebJob to run:
        // AzureWebJobsDashboard and AzureWebJobsStorage
        static void Main()
        {
            var host = new JobHost();
            // The following code ensures that the WebJob will be running continuously
            host.RunAndBlock();
        }
    }
}

It all seems very straightforward, and I have created other similar web jobs exactly like this. Has anyone ever seen this error message before? Any idea what I might be doing wrong?

Body:
Just in case someone runs into this issue, I found out what was going on (in my case). My problem was with this line:

public static void ProcessQueueMessage([Queue("ringclonedownloadprocessorqueue")] string message, TextWriter log)

This web job was not a continuous job when I first created it. And when Visual Studio created the code template, it used [Queue("ringclonedownloadprocessorqueue")] string message as the default parameter type. I recently changed the job to a continuous job, and a continuous job uses a slightly different param type (QueueTrigger instead of Queue). But when I changed the job to continuous, Visual Studio did not change the param type accordingly. I needed to go in and manually update the param type. Changing the function to this did the trick:

namespace DownloadProcessor
{
    public class Functions
    {
        public static void ProcessQueueMessage([QueueTrigger("ringclonedownloadprocessorqueue")] string message, TextWriter log)
        {
            log.WriteLine("Processing" + message);
        }
    }
}


问:
PHP socket shoud return json but returns warning
Never used socket before. I have to make socket to get an answer from server in json format. This is code:

```<code>$host = '11.11.11.1';//for example
$port = 1111;
$message = "xgm";
set_time_limit(2);
if(!($sock = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP)))
{
    $errorcode = socket_last_error();
    $errormsg = socket_strerror($errorcode);
    die("Couldn't create socket: [$errorcode] $errormsg \n");
}
echo "Socket created \n";
if(!socket_connect($sock , $host , $port))
{
    $errorcode = socket_last_error();
    $errormsg = socket_strerror($errorcode);
    die("Could not connect: [$errorcode] $errormsg \n");
}
echo "Connection established \n";
if( ! socket_send ( $sock , $message , strlen($message) , 0))
{
    $errorcode = socket_last_error();
    $errormsg = socket_strerror($errorcode);
    die("Could not send data: [$errorcode] $errormsg \n");
}
echo "Message send successfully \n";
if(socket_recv ( $sock , $buf , 2045 , MSG_WAITALL ) === FALSE)
{
    $errorcode = socket_last_error();
    $errormsg = socket_strerror($errorcode);
    die("Could not receive data: [$errorcode] $errormsg \n");
}

var_dump($buf);
socket_close($sock);
</code>```

And this is response I get:

Socket created

Connection established

Message send successfully

Warning: socket_recv(): unable to read from socket [10045]: The    attempted operation is not supported for the type of object

  referenced. in C:\wamp64\www\json\index.php on line 73

Could not receive data: [10045] The attempted operation is not    supported for the type of object referenced.

So it seems socket_recv  returns false. why? Is that because of json object in response from server? And how to fix that? Any directions?

答:
UDP unlike TCP is a connectionless protocol, which means that two ends can exchange messages without having to establich a communication channel.

So, it's best to use socket_recvfrom and socket_sendto  because they work well with not connection-oriented sockets.

```<code>$host = '11.11.11.1';//for example
$port = 1111;
$message = "xgm";
set_time_limit(2);
if(!($sock = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP))){
    $errorcode = socket_last_error();
    $errormsg = socket_strerror($errorcode);
    die("Couldn't create socket: [$errorcode] $errormsg \n");
}
echo "Socket created \n";

if(!socket_sendto($sock, $message, strlen($message), 0, $host, $port)){
    $errorcode = socket_last_error();
    $errormsg = socket_strerror($errorcode);
    die("Could not send data: [$errorcode] $errormsg \n");
}
echo "Message send successfully \n";

if(socket_recvfrom($sock , $buf , 2045 , 0, $host, $port) === FALSE){
    $errorcode = socket_last_error();
    $errormsg = socket_strerror($errorcode);
    die("Could not receive data: [$errorcode] $errormsg \n");
}
var_dump($buf);
socket_close($sock);
</code>```

Body:
Never used socket before. I have to make socket to get an answer from server in json format. This is code:

$host = '11.11.11.1';//for example
$port = 1111;
$message = "xgm";
set_time_limit(2);
if(!($sock = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP)))
{
    $errorcode = socket_last_error();
    $errormsg = socket_strerror($errorcode);
    die("Couldn't create socket: [$errorcode] $errormsg \n");
}
echo "Socket created \n";
if(!socket_connect($sock , $host , $port))
{
    $errorcode = socket_last_error();
    $errormsg = socket_strerror($errorcode);
    die("Could not connect: [$errorcode] $errormsg \n");
}
echo "Connection established \n";
if( ! socket_send ( $sock , $message , strlen($message) , 0))
{
    $errorcode = socket_last_error();
    $errormsg = socket_strerror($errorcode);
    die("Could not send data: [$errorcode] $errormsg \n");
}
echo "Message send successfully \n";
if(socket_recv ( $sock , $buf , 2045 , MSG_WAITALL ) === FALSE)
{
    $errorcode = socket_last_error();
    $errormsg = socket_strerror($errorcode);
    die("Could not receive data: [$errorcode] $errormsg \n");
}

var_dump($buf);
socket_close($sock);

And this is response I get:

Socket created

Connection established

Message send successfully

Warning: socket_recv(): unable to read from socket [10045]: The    attempted operation is not supported for the type of object

  referenced. in C:\wamp64\www\json\index.php on line 73

Could not receive data: [10045] The attempted operation is not    supported for the type of object referenced.

So it seems socket_recv  returns false. why? Is that because of json object in response from server? And how to fix that? Any directions?

Body:
UDP unlike TCP is a connectionless protocol, which means that two ends can exchange messages without having to establich a communication channel.

So, it's best to use socket_recvfrom and socket_sendto  because they work well with not connection-oriented sockets.

$host = '11.11.11.1';//for example
$port = 1111;
$message = "xgm";
set_time_limit(2);
if(!($sock = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP))){
    $errorcode = socket_last_error();
    $errormsg = socket_strerror($errorcode);
    die("Couldn't create socket: [$errorcode] $errormsg \n");
}
echo "Socket created \n";

if(!socket_sendto($sock, $message, strlen($message), 0, $host, $port)){
    $errorcode = socket_last_error();
    $errormsg = socket_strerror($errorcode);
    die("Could not send data: [$errorcode] $errormsg \n");
}
echo "Message send successfully \n";

if(socket_recvfrom($sock , $buf , 2045 , 0, $host, $port) === FALSE){
    $errorcode = socket_last_error();
    $errormsg = socket_strerror($errorcode);
    die("Could not receive data: [$errorcode] $errormsg \n");
}
var_dump($buf);
socket_close($sock);


问:
Serving Images with on-the-fly resize
my company has recently started to get problems with the image handling for our websites.

We have several websites (adult entertainment) that display images like dvd covers, snapshots and similar. We have about 100'000 movies and for each movie we have an average of 30 snapshots + covers. Almost every image has an additional version with blurring and overlay for non-members, this results in about 50 images per movie or a total of 5 million base images. Each of the images is available in several versions, depending on where it's placed on the page (thumbnail, original, small preview, not-so-small preview, small image in the top-list, etc.) which results in more images than i cared to count.

Now i had the idea to use a server to generate the images on-the-fly since it became quite clumsy to generate all the different images for all the different pages (as different pages sometimes even need different image sizes for basically the same task).

Does anyone know of an image processing server that can scale down images on-the-fly so we only need to provide the original images and the web guys can just request whatever size they need?

Requirements:

Very High performance (Several thousand users per day)

On-the-fly blurring and overlay creation

On-the-fly resize (with and without keeping aspect ratio)

Can handle millions of images

Must be able to read JPG, GIF, PNG and BMP and convert between them

Security is not that much of a concern as i.e. the unblurred images can already be reached by URL manipulation and more security would be nice but it's not required and frankly i stopped caring (After failing to get into my coworkers heads why (for our small reseller page) it's a bad idea to use http://example.com/view_image.php?filename=/data/images/01020304.jpg to display the images).

We tried PHP scripts to do this but the performance was too slow for this many users.

Thanks in advance for any suggestions you have.

答:
This exact same problem is now being solved by image resize services dedicated to this task. They provide following features:

In built CDN - you need not worry about image distribution

Image resize on the fly - any size needed is available

No storage needed - you just store base image and all variants are handled by service

Ecosystem libraries - you can just include javascript and your job is done for all devices and all browsers.

One such service is Gumlet. You can also try some open source alternative like nginx plugin which can also resize image on the fly.

(I work for Gumlet.)

ContentLicense: CC BY-SA 2.5

Title: Serving Images with on-the-fly resize


问:
Applying different themes in angular 4 component
I have a component library that I've designed for lets say theme A.
I want to have most of the components with a slight different variation (in both template and css) in them to make my theme B.

I've taken a look at most of these questions on SO and also on the web but nothing addresses my issue precisely unless I create a new tag with a different name which I don't believe to be an elegant way to address this issue.

I would appreciate if someone can provide me an approach to tackle this.

How to apply themes in angular2?

Can I add two template for one component in angular2?

Angular 2 component with multiple views

答:
Not sure about first two questions.

For "Angular 2 component with multiple views": Angular is all about composing views. So, you can use content-projection using "" tag to insert different content inside the existing component. You can control the visibility of these projected content by "ngIf".


问:
Django ajax file upload form - file not uploading
I have a file upload form in html with which I'm trying to upload a file(and file size to display) via ajax call. I'm using django. Whenever I try to do anything nothing happens. Here's the upload form:

```<code><form class="uploadForm" method="post" enctype="multipart/form-data">
  {% csrf_token %}
  <input type="file" id="uploadFile">
  <input type="submit" class="button" id="uploadButton" value="Upload">
</form>
</code>```

Here's my Jquery + Ajax:

```<code>$('.uploadForm').on('submit', function(event){
  event.preventDefault();
  var fileSize = ($('#uploadFile')[0].files[0].size/1024);
  var fileName = $('#uploadFile')[0].files[0].name;
  var realSize = sizeConverter(fileSize);
  var fileData = new FormData($('#uploadFile')[0]);
  var csrfToken = '{{ csrf_token }}';
  $.ajax({
    url: '{% url 'project:uploadFile' %}',
    type: 'post',
    data: {
      'fileData': fileData,
      'fileSize': realSize,
      csrfmiddlewaretoken: '{{ csrf_token }}'
     },
    cache: false,
    processData: false,
    contentType: false,
    success: function(data){
      alert(data);
    }
  });
});
</code>```

Here are views.py:

```<code>class uploadFile(TemplateView):
template_name = "project/uploadFile.html"

def post(self, request):
    fileSize = request.POST.get('fileSize')
    fileData = request.FILES['fileData']
    return JsonResponse(fileSize, safe=False)
</code>```

Now, with this setup when I submit the form nothing happens. I don't get any errors in the console, nothing.
When I remove 'fileData' from data and cache: false, processData: false, contentType: false, inside Ajax this works(text only though).
I tried changing new FormData($('#uploadFile')[0]); to new FormData($('#uploadFile').get(0)); but that did not help. I am guessing the issue here is with the fileData variable but what could be wrong with it? I appreciate your help.

Thanks

答:
I think you need to include enctype: 'multipart/form-data' in your ajax. And handle the csrfmiddlewaretoken with .append(..) method.

```<code>$('.uploadForm').on('submit', function(event){
  event.preventDefault();

  var fileSize = $('#uploadFile')[0].files[0].size/1024;
  var fileName = $('#uploadFile')[0].files[0].name;
  var realSize = sizeConverter(fileSize);

  var fileData = new FormData($('#uploadFile').get(0));
  fileData.append('csrfmiddlewaretoken', '{{ csrf_token }}');
  //fileData.append('fileData', fileData);
  fileData.append('realSize', realSize);

  $.ajax({
    url: "{% url 'project:uploadFile' %}",
    type: "POST",
    data: fileData,
    async: true,
    cache: false,
    processData: false,
    contentType: false,
    enctype: 'multipart/form-data',
    success: function(data){
      alert(data);
    }
  });
});
</code>```

For generic.TemplateView you have only get method implemented. You should implement post method to allow post form or try to use generic.FormView.

Body:
I have a file upload form in html with which I'm trying to upload a file(and file size to display) via ajax call. I'm using django. Whenever I try to do anything nothing happens. Here's the upload form:

<form class="uploadForm" method="post" enctype="multipart/form-data">
  {% csrf_token %}
  <input type="file" id="uploadFile">
  <input type="submit" class="button" id="uploadButton" value="Upload">
</form>

Here's my Jquery + Ajax:

$('.uploadForm').on('submit', function(event){
  event.preventDefault();
  var fileSize = ($('#uploadFile')[0].files[0].size/1024);
  var fileName = $('#uploadFile')[0].files[0].name;
  var realSize = sizeConverter(fileSize);
  var fileData = new FormData($('#uploadFile')[0]);
  var csrfToken = '{{ csrf_token }}';
  $.ajax({
    url: '{% url 'project:uploadFile' %}',
    type: 'post',
    data: {
      'fileData': fileData,
      'fileSize': realSize,
      csrfmiddlewaretoken: '{{ csrf_token }}'
     },
    cache: false,
    processData: false,
    contentType: false,
    success: function(data){
      alert(data);
    }
  });
});

Here are views.py:

class uploadFile(TemplateView):
template_name = "project/uploadFile.html"

def post(self, request):
    fileSize = request.POST.get('fileSize')
    fileData = request.FILES['fileData']
    return JsonResponse(fileSize, safe=False)

Now, with this setup when I submit the form nothing happens. I don't get any errors in the console, nothing.
When I remove 'fileData' from data and cache: false, processData: false, contentType: false, inside Ajax this works(text only though).
I tried changing new FormData($('#uploadFile')[0]); to new FormData($('#uploadFile').get(0)); but that did not help. I am guessing the issue here is with the fileData variable but what could be wrong with it? I appreciate your help.

Thanks

Body:
I think you need to include enctype: 'multipart/form-data' in your ajax. And handle the csrfmiddlewaretoken with .append(..) method.

$('.uploadForm').on('submit', function(event){
  event.preventDefault();

  var fileSize = $('#uploadFile')[0].files[0].size/1024;
  var fileName = $('#uploadFile')[0].files[0].name;
  var realSize = sizeConverter(fileSize);

  var fileData = new FormData($('#uploadFile').get(0));
  fileData.append('csrfmiddlewaretoken', '{{ csrf_token }}');
  //fileData.append('fileData', fileData);
  fileData.append('realSize', realSize);

  $.ajax({
    url: "{% url 'project:uploadFile' %}",
    type: "POST",
    data: fileData,
    async: true,
    cache: false,
    processData: false,
    contentType: false,
    enctype: 'multipart/form-data',
    success: function(data){
      alert(data);
    }
  });
});

For generic.TemplateView you have only get method implemented. You should implement post method to allow post form or try to use generic.FormView.


问:
Searching for service area businesses using Google API
I'm trying to understand a problem that I'm having at the moment,

I created a Google map on my web app so my users can search for their businesses,

It appears that they can search and find only businesses with a precise location,

Service area businesses cannot be found using my map,

This is the link to my map on my server: My Map

Then I found a Google link that I can find also the service area businesses,

This is the link to the Google Map: Google Map

I compared (vimdiff) the source codes of the two links and they are the same,

So my question is why I can't see service area businesses on my map ?

答:
Service Area Businesses are not available for Places API users and this is Google's decision. There was a feature request to enable SABs in Places API, but unfortunately Google rejected it.

You can read more here: https://issuetracker.google.com/issues/35828187

I copy the last answer from Google:

The Places API team has reviewed this feature request and decided against including Service Area Businesses results in API responses.

Places API mission is to enable developers to help users find relevant places to visit. Since Service Area Businesses are not places users can visit, and therefore do not belong in the Places API.

The ability to find Service Area Businesses have been removed from https://developers.google.com/maps/documentation/javascript/examples/places-placeid-finder to be consistent with the funtionality generally available in the Places API. Google My Business users can still find Place IDs for their Service Area Businesses using a dedicated PlaceID Lookup Tool at https://developers.google.com/my-business/content/faq#associate_locations_using_placeid_1

We do acknowledge there is demand for this feature and will look into accommodating it in the future. To this end, we would appreciate if you shared specific use cases and business needs that this feature would enable for you.

Referring to the Google My Business find place ID page, they use their own Cloud project where this feature is available, but no way for Google Maps API users to get this.

I hope my answer clarifies your doubt!


问:
Comparing only the first index of two array
I have two arrays one that has just one index which list id's. The other array has many indexes but I want to compare only the id index of both arrays which is index [0] I want to get only the rows that ids don't match and return those rows. Example:

```<code>$array1 = [
    '12345',
    '23457'
];

$array2 = [
   [id => '12345', 'fake_data' => 'something'],
   [id => '23457', 'more_data' => 'something else'],
   [id => '76389','more_data' => 'something else 3'],
   [id => '10293', 'more_data' => 'something else 4'],
   [id => '09229', 'more_data' => 'something else 5']
];
</code>```

The first array just have id's the other has ids place other data. I need to keep that data and only return the rows that don't match the first array. Help is very much appriciated.

答:
I think it looks like an array_intersect with two different types of arrays. To handle the different array types, you can use array_uintersect, which takes a callback to define the comparison between items.

```<code>$result = array_uintersect($array2, $array1, function($a, $b) {
    return ($a['id'] ?? $a) <=> ($b['id'] ?? $b);
});
</code>```

The two terms ($a['id'] ?? $a) and ($b['id'] ?? $b) in the callback are like that because they can be terms from either $array1 or $array2.

I don't know if this is any better or worse than the other solutions; it's just a different way of looking at it.

Body:
I have two arrays one that has just one index which list id's. The other array has many indexes but I want to compare only the id index of both arrays which is index [0] I want to get only the rows that ids don't match and return those rows. Example:

$array1 = [
    '12345',
    '23457'
];

$array2 = [
   [id => '12345', 'fake_data' => 'something'],
   [id => '23457', 'more_data' => 'something else'],
   [id => '76389','more_data' => 'something else 3'],
   [id => '10293', 'more_data' => 'something else 4'],
   [id => '09229', 'more_data' => 'something else 5']
];

The first array just have id's the other has ids place other data. I need to keep that data and only return the rows that don't match the first array. Help is very much appriciated.

Body:
I think it looks like an array_intersect with two different types of arrays. To handle the different array types, you can use array_uintersect, which takes a callback to define the comparison between items.

$result = array_uintersect($array2, $array1, function($a, $b) {
    return ($a['id'] ?? $a) <=> ($b['id'] ?? $b);
});

The two terms ($a['id'] ?? $a) and ($b['id'] ?? $b) in the callback are like that because they can be terms from either $array1 or $array2.

I don't know if this is any better or worse than the other solutions; it's just a different way of looking at it.


问:
Python: iterating over tuples in list
right now I have code that is giving me this output:

```[('KOR', [3, 1, 0]), ('ITA', [1, 0, 0]), ('TPE', [0, 1, 1]), ('CHN', [0, 1, 0]), ('JPN', [0, 1, 0]), ('AUS', [0, 0, 1]), ('GBR', [0, 0, 1]), ('UKR', [0, 0, 1])]```

but it needs to be in this form:

```['KOR 3 1 0', 'ITA 1 0 0', 'TPE 0 1 1', 'CHN 0 1 0', 'JPN 0 1 0', 'AUS 0 0 1', 'GBR 0 0 1', 'UKR 0 0 1']```

How do I change the data into the correct form? I have been trying to iterate through the elements, but the closest I've gotten is

```['KOR', 3, 1, 0, 'ITA', 1, 0, 0, 'TPE', 0, 1, 1, 'CHN', 0, 1, 0, 'JPN', 0, 1, 0, 'AUS', 0, 0, 1, 'GBR', 0, 0, 1, 'UKR', 0, 0, 1]```

by using this code

```<code>for item in alist:
    for x in item:
        answer.append(x)

for item in answer:
    if type(item)==str:
        answer2.append(item)
    else:
        for f in item:
            answer2.append(f)
return answer2
</code>```

Thank you in advance!

答:
If you don't want to use a list comprehension, your original code could be changed as follows:</p>

```<code>answer = []
for item in data:
    result = item[0]
    for x in item[1]:
        result = result + ' ' + str(x)
    answer.append(result)
return answer
</code>```

Title: Python: iterating over tuples in list

Body:
right now I have code that is giving me this output:

[('KOR', [3, 1, 0]), ('ITA', [1, 0, 0]), ('TPE', [0, 1, 1]), ('CHN', [0, 1, 0]), ('JPN', [0, 1, 0]), ('AUS', [0, 0, 1]), ('GBR', [0, 0, 1]), ('UKR', [0, 0, 1])]

but it needs to be in this form:

['KOR 3 1 0', 'ITA 1 0 0', 'TPE 0 1 1', 'CHN 0 1 0', 'JPN 0 1 0', 'AUS 0 0 1', 'GBR 0 0 1', 'UKR 0 0 1']

How do I change the data into the correct form? I have been trying to iterate through the elements, but the closest I've gotten is

['KOR', 3, 1, 0, 'ITA', 1, 0, 0, 'TPE', 0, 1, 1, 'CHN', 0, 1, 0, 'JPN', 0, 1, 0, 'AUS', 0, 0, 1, 'GBR', 0, 0, 1, 'UKR', 0, 0, 1]

by using this code

for item in alist:
    for x in item:
        answer.append(x)

for item in answer:
    if type(item)==str:
        answer2.append(item)
    else:
        for f in item:
            answer2.append(f)
return answer2

Thank you in advance!

Body:
If you don't want to use a list comprehension, your original code could be changed as follows:

answer = []
for item in data:
    result = item[0]
    for x in item[1]:
        result = result + ' ' + str(x)
    answer.append(result)
return answer


问:
How can I make the backgorund image cover all of the screen?
I have an page with a header and a footer. The footer is pushed to the bottom of the page if no content is available to push it down. The problem is that a div with a background image isn't filling up the space from the header to the footer. Also it's parent main isn't resizing to fill the page. What can I do?

html {
  height: 100%;
  box-sizing: border-box;
}

*,
*:before,
*:after {
  box-sizing: inherit;
}

body {
  background-color: #f5f5f5;
  margin: 0;
  padding: 0;
  position: relative;
  min-height: 100%;
}

#in {
  width: 1000px;
  margin-left: auto;
  margin-right: auto;
  height: 100%;
}

header {
  background-color: #131b23;
  border-bottom: 6px solid #0f151a;
  text-align: center;
  left: 0;
  top: 0;
  width: 100%;
  height: 160px;
  box-shadow: 0 3px 6px rgba(0, 0, 0, 0.16), 0 3px 6px rgba(0, 0, 0, 0.23);
  z-index: 99;
}

#heading {
  font-family: "titlefont";
  color: #c03221;
  font-size: 55px;
  display: inline-block;
  margin-bottom: -7px;
  margin-top: 15px;
}

#subheading {
  font-family: "slogantextfont";
  font-size: 25px;
  margin-top: 0px;
  color: #f6ae2d;
  margin-bottom: 30px;
}

main {
  text-align: center;
  background: #f5f5f5 url("https://images.unsplash.com/photo-1510940725340-44c002560b46?dpr=1&auto=format&fit=crop&w=1000&q=80&cs=tinysrgb&ixid=dW5zcGxhc2guY29tOzs7Ozs%3D") no-repeat center center;
  background-size: cover;
}

#title {
  margin: 0px;
  padding: 0px;
}

footer {
  position: absolute;
  right: 0;
  bottom: 0;
  left: 0;
  padding: 1rem;
  background-color: #25211e;
  border-top: 6px solid #1d1a18;
  text-align: center;
  height: 80px;
  z-index: 98;
  box-shadow: 0 3px 6px rgba(0, 0, 0, 0.16), 0 3px 6px rgba(0, 0, 0, 0.23);
}

#credit {
  font-family: "Helvetica";
  font-size: 14px;
  color: #c1b497;
  font-weight: 600;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>

<head>
  <title>My Page</title>
</head>

<body>
  <header>
    <h1 id="heading">My Page</h1>
    <h2 id="subheading">BLABLA BLA BLA BLA BLA BLA</h2>
  </header>
  <main>
    <h2 id="title">PICTURE</h2>
    <h2 id="title">PICTURE</h2>
    <h2 id="title">PICTURE</h2>
  </main>
  <footer>
    <p id="credit">BLABLA BLA BLA BLA BLA BLA</p>
  </footer>
</body>

</html></code>```

答:
You'll have to do two things:

Set an explicit height on the body (100%)

Set an explicit height on the main (79% to account for the space already taken up by the header and footer)

See below:

html {
  height: 100%;
  box-sizing: border-box;
}

*,
*:before,
*:after {
  box-sizing: inherit;
}

body {
  background-color: #f5f5f5;
  margin: 0;
  padding: 0;
  position: relative;
  min-height: 100%;
  height: 100%;
}

#in {
  width: 1000px;
  margin-left: auto;
  margin-right: auto;
  height: 100%;
}

header {
  background-color: #131b23;
  border-bottom: 6px solid #0f151a;
  text-align: center;
  left: 0;
  top: 0;
  width: 100%;
  height: 160px;
  box-shadow: 0 3px 6px rgba(0, 0, 0, 0.16), 0 3px 6px rgba(0, 0, 0, 0.23);
  z-index: 99;
}

#heading {
  font-family: "titlefont";
  color: #c03221;
  font-size: 55px;
  display: inline-block;
  margin-bottom: -7px;
  margin-top: 15px;
}

#subheading {
  font-family: "slogantextfont";
  font-size: 25px;
  margin-top: 0px;
  color: #f6ae2d;
  margin-bottom: 30px;
}

main {
  text-align: center;
  background: #f5f5f5 url("https://images.unsplash.com/photo-1510940725340-44c002560b46?dpr=1&auto=format&fit=crop&w=1000&q=80&cs=tinysrgb&ixid=dW5zcGxhc2guY29tOzs7Ozs%3D") no-repeat center center;
  background-size: cover;
  height: 79%;
}

#title {
  margin: 0px;
  padding: 0px;
}

footer {
  position: absolute;
  right: 0;
  bottom: 0;
  left: 0;
  padding: 1rem;
  background-color: #25211e;
  border-top: 6px solid #1d1a18;
  text-align: center;
  height: 80px;
  z-index: 98;
  box-shadow: 0 3px 6px rgba(0, 0, 0, 0.16), 0 3px 6px rgba(0, 0, 0, 0.23);
}

#credit {
  font-family: "Helvetica";
  font-size: 14px;
  color: #c1b497;
  font-weight: 600;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>

<head>
  <title>My Page</title>
</head>

<body>
  <header>
    <h1 id="heading">My Page</h1>
    <h2 id="subheading">BLABLA BLA BLA BLA BLA BLA</h2>
  </header>
  <main>
    <h2 id="title">PICTURE</h2>
    <h2 id="title">PICTURE</h2>
    <h2 id="title">PICTURE</h2>
  </main>
  <footer>
    <p id="credit">BLABLA BLA BLA BLA BLA BLA</p>
  </footer>
</body>

</html></code>```

Body:
I have an page with a header and a footer. The footer is pushed to the bottom of the page if no content is available to push it down. The problem is that a div with a background image isn't filling up the space from the header to the footer. Also it's parent main isn't resizing to fill the page. What can I do?

html {
  height: 100%;
  box-sizing: border-box;
}

*,
*:before,
*:after {
  box-sizing: inherit;
}

body {
  background-color: #f5f5f5;
  margin: 0;
  padding: 0;
  position: relative;
  min-height: 100%;
}

#in {
  width: 1000px;
  margin-left: auto;
  margin-right: auto;
  height: 100%;
}

header {
  background-color: #131b23;
  border-bottom: 6px solid #0f151a;
  text-align: center;
  left: 0;
  top: 0;
  width: 100%;
  height: 160px;
  box-shadow: 0 3px 6px rgba(0, 0, 0, 0.16), 0 3px 6px rgba(0, 0, 0, 0.23);
  z-index: 99;
}

#heading {
  font-family: "titlefont";
  color: #c03221;
  font-size: 55px;
  display: inline-block;
  margin-bottom: -7px;
  margin-top: 15px;
}

#subheading {
  font-family: "slogantextfont";
  font-size: 25px;
  margin-top: 0px;
  color: #f6ae2d;
  margin-bottom: 30px;
}

main {
  text-align: center;
  background: #f5f5f5 url("https://images.unsplash.com/photo-1510940725340-44c002560b46?dpr=1&auto=format&fit=crop&w=1000&q=80&cs=tinysrgb&ixid=dW5zcGxhc2guY29tOzs7Ozs%3D") no-repeat center center;
  background-size: cover;
}

#title {
  margin: 0px;
  padding: 0px;
}

footer {
  position: absolute;
  right: 0;
  bottom: 0;
  left: 0;
  padding: 1rem;
  background-color: #25211e;
  border-top: 6px solid #1d1a18;
  text-align: center;
  height: 80px;
  z-index: 98;
  box-shadow: 0 3px 6px rgba(0, 0, 0, 0.16), 0 3px 6px rgba(0, 0, 0, 0.23);
}

#credit {
  font-family: "Helvetica";
  font-size: 14px;
  color: #c1b497;
  font-weight: 600;
}

<!DOCTYPE html>

  <title>My Page</title>

My Page

BLABLA BLA BLA BLA BLA BLA

PICTURE

PICTURE

PICTURE

BLABLA BLA BLA BLA BLA BLA

Body:
You'll have to do two things:

Set an explicit height on the body (100%)

Set an explicit height on the main (79% to account for the space already taken up by the header and footer)

See below:

html {
  height: 100%;
  box-sizing: border-box;
}

*,
*:before,
*:after {
  box-sizing: inherit;
}

body {
  background-color: #f5f5f5;
  margin: 0;
  padding: 0;
  position: relative;
  min-height: 100%;
  height: 100%;
}

#in {
  width: 1000px;
  margin-left: auto;
  margin-right: auto;
  height: 100%;
}

header {
  background-color: #131b23;
  border-bottom: 6px solid #0f151a;
  text-align: center;
  left: 0;
  top: 0;
  width: 100%;
  height: 160px;
  box-shadow: 0 3px 6px rgba(0, 0, 0, 0.16), 0 3px 6px rgba(0, 0, 0, 0.23);
  z-index: 99;
}

#heading {
  font-family: "titlefont";
  color: #c03221;
  font-size: 55px;
  display: inline-block;
  margin-bottom: -7px;
  margin-top: 15px;
}

#subheading {
  font-family: "slogantextfont";
  font-size: 25px;
  margin-top: 0px;
  color: #f6ae2d;
  margin-bottom: 30px;
}

main {
  text-align: center;
  background: #f5f5f5 url("https://images.unsplash.com/photo-1510940725340-44c002560b46?dpr=1&auto=format&fit=crop&w=1000&q=80&cs=tinysrgb&ixid=dW5zcGxhc2guY29tOzs7Ozs%3D") no-repeat center center;
  background-size: cover;
  height: 79%;
}

#title {
  margin: 0px;
  padding: 0px;
}

footer {
  position: absolute;
  right: 0;
  bottom: 0;
  left: 0;
  padding: 1rem;
  background-color: #25211e;
  border-top: 6px solid #1d1a18;
  text-align: center;
  height: 80px;
  z-index: 98;
  box-shadow: 0 3px 6px rgba(0, 0, 0, 0.16), 0 3px 6px rgba(0, 0, 0, 0.23);
}

#credit {
  font-family: "Helvetica";
  font-size: 14px;
  color: #c1b497;
  font-weight: 600;
}

<!DOCTYPE html>
<html>

<head>
  <title>My Page</title>
</head>

<body>
  <header>
    <h1 id="heading">My Page</h1>
    <h2 id="subheading">BLABLA BLA BLA BLA BLA BLA</h2>
  </header>
  <main>
    <h2 id="title">PICTURE</h2>
    <h2 id="title">PICTURE</h2>
    <h2 id="title">PICTURE</h2>
  </main>
  <footer>
    <p id="credit">BLABLA BLA BLA BLA BLA BLA</p>
  </footer>
</body>

</html>


问:
PHP Regular expression tag matching
Been beating my head against a wall trying to get this to work - help from any regex gurus would be greatly appreciated!

The text that has to be matched

```<code>[template option="whatever"]

<p>any amount of html would go here</p>

[/template]
</code>```

I need to pull the 'option' value (i.e. 'whatever') and the html between the template tags.

So far I have:

```<code>> /\[template\s*option=["\']([^"\']+)["\']\]((?!\[\/template\]))/
</code>```

Which gets me everything except the html between the template tags.

Any ideas?

Thanks, Chris

答:
Try this

```<code>/\[template\s*option=\"(.*)\"\](.*)\[\/template]/
</code>```

basically instead of using complex regex to match every single thing just use (.*) which means all since you want everything in between its not like you want to verify the data in between

Title: PHP Regular expression tag matching

Body:
Been beating my head against a wall trying to get this to work - help from any regex gurus would be greatly appreciated!

The text that has to be matched

[template option="whatever"]

any amount of html would go here

[/template]

I need to pull the 'option' value (i.e. 'whatever') and the html between the template tags.

So far I have:

> /\[template\s*option=["\']([^"\']+)["\']\]((?!\[\/template\]))/

Which gets me everything except the html between the template tags.

Any ideas?

Thanks, Chris

Body:
Try this

/\[template\s*option=\"(.*)\"\](.*)\[\/template]/

basically instead of using complex regex to match every single thing just use (.*) which means all since you want everything in between its not like you want to verify the data in between


问:
Adding dynamic meta tags to a React static site, created using StaticSiteGeneratorPlugin
We're doing a website using StaticSiteGeneratorPlugin, is a website plugin that render the site locally and then we can upload it to S3.

Our code looks basically like this github project

We're using React Helmet to manage our head, meta info and all that, and is working great in the browser, but not when running the prod build.

In the entry.js I have the following. Missing a way to add the generated strings by Helmet into the resulting html, or if there's a better manager than helmet that will work better with the plugin we're using.

```<code>export default function render(locals, callback) {
    const element = React.createElement(Root, props);
    const helmet = Helmet.renderStatic();
    const html = ReactDOMServer.renderToString(element);
    callback(null, `<!DOCTYPE html>${html}`);
}
</code>```

答:
Try this, but "don't blog about html":</p>

```<code>const helmet = Helmet.renderStatic();
var html = ReactDOMServer.renderToString(element);
html.replace("</head>", helmet+"</head>");
callback(null, `<!DOCTYPE html>${html}`);
</code>```

Body:
We're doing a website using StaticSiteGeneratorPlugin, is a website plugin that render the site locally and then we can upload it to S3.

Our code looks basically like this github project

We're using React Helmet to manage our head, meta info and all that, and is working great in the browser, but not when running the prod build.

In the entry.js I have the following. Missing a way to add the generated strings by Helmet into the resulting html, or if there's a better manager than helmet that will work better with the plugin we're using.

export default function render(locals, callback) {
    const element = React.createElement(Root, props);
    const helmet = Helmet.renderStatic();
    const html = ReactDOMServer.renderToString(element);
    callback(null, `<!DOCTYPE html>${html}`);
}

Body:
Try this, but "don't blog about html":

const helmet = Helmet.renderStatic();
var html = ReactDOMServer.renderToString(element);
html.replace("</head>", helmet+"</head>");
callback(null, `<!DOCTYPE html>${html}`);


问:
Counting rows in multiple partitions using Oracle SQL
For a partitioned table I can count the rows in a partition quickly with a query like this:

```<code>select count(*)
from db.table Partition (P)
where column value is Null
</code>```

Is there a way to do this for multiple partitions?

My desired result is the following-

```<code>Partition name         Count of Null Rows
P1                         20000
P2                         12000
P3                          30000
</code>```

答:
This has been answered before. If your table is not partitioned on date, simply change the predicate and allow Oracle to do the work for you. Many thanks to Mr. Cave :)

Select from several partitions at once

You almost never want to use the PARTITION clause when querying a
  partitioned table. You almost always want to specify a predicate that
  allows Oracle to do partition pruning on its own.

SELECT t.column1, t.column2

       FROM first_table t

    WHERE t.partitioned_date_column >= <> AND t.column3 = 'someVal'

When you specify a predicate on the date
  column that the table is partitioned on, Oracle can automatically
  determine which partition(s) need to be accessed.

Body:
For a partitioned table I can count the rows in a partition quickly with a query like this:

select count(*)
from db.table Partition (P)
where column value is Null

Is there a way to do this for multiple partitions?

My desired result is the following-

Partition name         Count of Null Rows
P1                         20000
P2                         12000
P3                          30000


问:
How to delete GIT branch completely?
My local GIT repository became very big and I'm trying to free some hard drive space. I deleted all my old branches and left only the last one.
In order to delete branches from my repository, I used the command

```<code>git branch -d [my branch name]
</code>```

The problem is that when I check the repository space usage, it still uses the same amount.
Running the garbage collector

```<code>git gc
</code>```

after branches deletion didn't help.

The biggest git repository file is a .pack file inside the .git/objects/pack folder, it takes about 750MB, while the latest branch takes 112MB.

EDIT:
I also tried all the

```<code>git reflog expire --all --expire=now
git gc --prune=now --aggressive
</code>```

Neither helped.

答:
If you want to delete your remote branch as of v1.7.0, use this command:

```<code>git push origin --delete the_remote_branch
</code>```

Source https://makandracards.com/makandra/621-git-delete-a-branch-local-or-remote

Title: How to delete GIT branch completely?

Body:
My local GIT repository became very big and I'm trying to free some hard drive space. I deleted all my old branches and left only the last one.
In order to delete branches from my repository, I used the command

git branch -d [my branch name]

The problem is that when I check the repository space usage, it still uses the same amount.
Running the garbage collector

git gc

after branches deletion didn't help.

The biggest git repository file is a .pack file inside the .git/objects/pack folder, it takes about 750MB, while the latest branch takes 112MB.

EDIT:
I also tried all the

git reflog expire --all --expire=now
git gc --prune=now --aggressive

Neither helped.

Body:
If you want to delete your remote branch as of v1.7.0, use this command:

git push origin --delete the_remote_branch

Source https://makandracards.com/makandra/621-git-delete-a-branch-local-or-remote


问:
Get Current date in SQLBase
I have an SQLBase and I am trying to get the current date of the system to be equal to the date of a column (create_date).

The MySQL Code will be:

```<code>Select * From Date D
Where D.Create_date=CURDATE();
</code>```

Can someone suggest me a way to take the current date in a SQLBase?

The date format should only contain the date(yyyy-MM-dd) and not the timestamp.

答: To get the current date, and not time, you should be able to use @DATEVALUE(@NOW).

Title: Get Current date in SQLBase

Body:
I have an SQLBase and I am trying to get the current date of the system to be equal to the date of a column (create_date).

The MySQL Code will be:

Select * From Date D
Where D.Create_date=CURDATE();

Can someone suggest me a way to take the current date in a SQLBase?

The date format should only contain the date(yyyy-MM-dd) and not the timestamp.


问:
How to Insert Session Array into MySQL DB using PHP
I have a multi page form and am trying to capture an array as a session to insert into mysql. Page two of the form is the  "Address" section. Here I ask for Address information. The user can hit a "enter another address" button which expands another box.

The user hits next to go to the next page (phone.php) where I ask for phone info. On this page I think I am  registering the session data correctly like so:

```<code>if(!isset($_SESSION))
{
@session_start();
}
header("Cache-control: private");
ob_start();

include('header.php');

//now, let's register our session variables from address.php
session_register('addressLineOne');
session_register('addressLineTwo');

//finally, let's store our posted values in the session variables
$_SESSION['addressLineOne'] = $_POST['addressLineOne'];
$_SESSION['addressLineTwo'] = $_POST['addressLineTwo'];
</code>```

Eventually we hit the submit.php . If I disable the code to add an additional address, this is the insert I am using which works fine.

```<code> $insertAddress="INSERT INTO address (idperson, addressLineOne, addressLineTwo)
 VALUES ( '$id','$_SESSION[addressLineOne]','$_SESSION[addressLineTwo]')";
 if (!mysql_query($insertAddress,$con))
   {die('Error: ' . mysql_error());}
 echo "";
</code>```

When I enable the "add additional address" code, the insert above will insert "ARRAY" into every DB field. I have been trying out the following:

```<code> foreach($_SESSION['idperson'] as $row=>$id)
{
    $idperson=$id;
    $addressLineOne=$_SESSION['addressLineOne'][$row];
    $addressLineTwo=$_SESSION['addressLineTwo'][$row];
}
 //enter rows into database
 foreach($_SESSION['idperson'] as $row=>$id)
{
    $idperson=mysql_real_escape_string($id);
    $addressLineOne=mysql_real_escape_string($_SESSION['addressLineOne'][$row]);
    $addressLineTwo=mysql_real_escape_string($_SESSION['addressLineTwo'][$row]);
}

 $insertAddress="INSERT INTO address (idperson, addressLineOne, addressLineTwo)
 VALUES ('.$id.','.$addressLineOne.','.$addressLineTwo.')";

 if (!mysql_query($insertAddress,$con))
 {
 die('Error: ' . mysql_error());
 }
 echo "$row record added";
</code>```

Instead of working, however, the above just inserts a couple of dots like "..." into the database. I don't know what else to do. Am I not grabbing the session data correctly? Is my foreach code way off? Thanks for any help.

Here is the code i'm using to add another table on address.php:

```<code> <?php for($i=1; $i<6; $i++):?>
 <div id='hidden<?php echo $i; ?>' style='display: none'>
<tr class="odd">
    <td width="33%">Street/Number</td>
    <td><input type="text" name="addressLineOne[]" id="addressLineOne<?php echo $i; ?>"/></td>
</tr>
<tr>
    <td>Address 2</td>
    <td><input type="text" name="addressLineTwo[]" id="addressLineTwo<?php echo $i; ?>"/></td>
</tr>
 <?php endfor; ?>
</code>```

Submit.php doesn't have anything besides connecting to the db and the above insert.

答: Without knowing what your "add additional address code" is, it seems that the addressLineOne and addressLineTwo variables come out as arrays. To check exactly what you're storing, you can use PHP's var_dump function. I suggest adding var_dump($_SESSION); somewhere in your code to see exactly what is being stored in the session so you can make sure it's what you think it is.

Body:
I have a multi page form and am trying to capture an array as a session to insert into mysql. Page two of the form is the  "Address" section. Here I ask for Address information. The user can hit a "enter another address" button which expands another box.

The user hits next to go to the next page (phone.php) where I ask for phone info. On this page I think I am  registering the session data correctly like so:

if(!isset($_SESSION))
{
@session_start();
}
header("Cache-control: private");
ob_start();

include('header.php');

//now, let's register our session variables from address.php
session_register('addressLineOne');
session_register('addressLineTwo');

//finally, let's store our posted values in the session variables
$_SESSION['addressLineOne'] = $_POST['addressLineOne'];
$_SESSION['addressLineTwo'] = $_POST['addressLineTwo'];

Eventually we hit the submit.php . If I disable the code to add an additional address, this is the insert I am using which works fine.

 $insertAddress="INSERT INTO address (idperson, addressLineOne, addressLineTwo)
 VALUES ( '$id','$_SESSION[addressLineOne]','$_SESSION[addressLineTwo]')";
 if (!mysql_query($insertAddress,$con))
   {die('Error: ' . mysql_error());}
 echo "";

When I enable the "add additional address" code, the insert above will insert "ARRAY" into every DB field. I have been trying out the following:

 foreach($_SESSION['idperson'] as $row=>$id)
{
    $idperson=$id;
    $addressLineOne=$_SESSION['addressLineOne'][$row];
    $addressLineTwo=$_SESSION['addressLineTwo'][$row];
}
 //enter rows into database
 foreach($_SESSION['idperson'] as $row=>$id)
{
    $idperson=mysql_real_escape_string($id);
    $addressLineOne=mysql_real_escape_string($_SESSION['addressLineOne'][$row]);
    $addressLineTwo=mysql_real_escape_string($_SESSION['addressLineTwo'][$row]);
}

 $insertAddress="INSERT INTO address (idperson, addressLineOne, addressLineTwo)
 VALUES ('.$id.','.$addressLineOne.','.$addressLineTwo.')";

 if (!mysql_query($insertAddress,$con))
 {
 die('Error: ' . mysql_error());
 }
 echo "$row record added";

Instead of working, however, the above just inserts a couple of dots like "..." into the database. I don't know what else to do. Am I not grabbing the session data correctly? Is my foreach code way off? Thanks for any help.

Here is the code i'm using to add another table on address.php:

 <?php for($i=1; $i<6; $i++):?>
 <div id='hidden<?php echo $i; ?>' style='display: none'>

    Street/Number
    <input type="text" name="addressLineOne[]" id="addressLineOne<?php echo $i; ?>"/>

    Address 2
    <input type="text" name="addressLineTwo[]" id="addressLineTwo<?php echo $i; ?>"/>

 <?php endfor; ?>

Submit.php doesn't have anything besides connecting to the db and the above insert.


问:
How can I make this function without classes - Python 3 Tkinter

```<code>from tkinter import *
class App():
    def __init__(self, root):
        self.root = root

    def Function(self):
        self.grid = []
        for i in range(7):
            row = []
            for j in range(6):
                row.append(Button(self.root,width=2,height=1,command=lambda i=i, j=j: self.Click1(i, j)))
                row[-1].grid(row=i,column=j)
            self.grid.append(row)

    def Click1(self, i, j):
        self.grid[i][j]["bg"]="blue"

root = Tk()
app = App(root)
app.Function()
root.mainloop()
</code>```

I need this to function without class. I tried removing the class option but I think that will cause a chain effect for everything else. Please help me remove the classes and just keep methods.

答:
Well, you can do that but I recommend you don't. But first, a possible solution. This is based on something I started out with: Instead of class you use a main function that runs the loop and has all the methods as subdefs. The external function wrapper is optional but very useful. It clears away all the variables created by the GUI when it exits. Furthermore it allows you to import the script safely and launch it only when you need to.

```<code>def App():
    root = tk.Tk()
    #app = App(root)

    def Function():
        grid = []
        for i in range(7):
            row = []
            for j in range(6):
                row.append(ttk.Button(root,command=lambda i=i, j=j: Click1(i, j)))
                row[-1].grid(row=i,column=j)
            grid.append(row)

        return grid

    grid = Function()

    def Click1(i, j):
        grid[i][j]["bg"]="blue"

    root.mainloop()

App()
</code>```

Some key points:

This script doesn't actually work. It's throwing loads of exceptions because of things it doesn't recognise (e.g. "height" and width"). I'm guessing your version is different from mine? Still, it creates a grid of buttons, which is a first step, I suppose.

All the selfs must go since you're no longer using a class

All the methods, now subdefs, must return the variables they're supposed to create or use global variables, since self.something is no longer available.

Now, some advice from someone who initially built their GUI in this very style: Don't! For your own sake.

As it grows it'll become increasingly difficult to manage and expand and, not least, debug and simply read.

It may not play well with other scripts if you ever plan to import your work from elsewhere.

When you finally give up and embrace classes, as I did, it will be extraordinarily tedious to translate everything you have created (back) into a class.

Classes are the way to go with tkinter.

Body:
from tkinter import *
class App():
    def __init__(self, root):
        self.root = root

    def Function(self):
        self.grid = []
        for i in range(7):
            row = []
            for j in range(6):
                row.append(Button(self.root,width=2,height=1,command=lambda i=i, j=j: self.Click1(i, j)))
                row[-1].grid(row=i,column=j)
            self.grid.append(row)

    def Click1(self, i, j):
        self.grid[i][j]["bg"]="blue"

root = Tk()
app = App(root)
app.Function()
root.mainloop()

I need this to function without class. I tried removing the class option but I think that will cause a chain effect for everything else. Please help me remove the classes and just keep methods.

Body:
Well, you can do that but I recommend you don't. But first, a possible solution. This is based on something I started out with: Instead of class you use a main function that runs the loop and has all the methods as subdefs. The external function wrapper is optional but very useful. It clears away all the variables created by the GUI when it exits. Furthermore it allows you to import the script safely and launch it only when you need to.

def App():
    root = tk.Tk()
    #app = App(root)

    def Function():
        grid = []
        for i in range(7):
            row = []
            for j in range(6):
                row.append(ttk.Button(root,command=lambda i=i, j=j: Click1(i, j)))
                row[-1].grid(row=i,column=j)
            grid.append(row)

        return grid

    grid = Function()

    def Click1(i, j):
        grid[i][j]["bg"]="blue"

    root.mainloop()

App()

Some key points:

This script doesn't actually work. It's throwing loads of exceptions because of things it doesn't recognise (e.g. "height" and width"). I'm guessing your version is different from mine? Still, it creates a grid of buttons, which is a first step, I suppose.

All the selfs must go since you're no longer using a class

All the methods, now subdefs, must return the variables they're supposed to create or use global variables, since self.something is no longer available.

Now, some advice from someone who initially built their GUI in this very style: Don't! For your own sake.

As it grows it'll become increasingly difficult to manage and expand and, not least, debug and simply read.

It may not play well with other scripts if you ever plan to import your work from elsewhere.

When you finally give up and embrace classes, as I did, it will be extraordinarily tedious to translate everything you have created (back) into a class.

Classes are the way to go with tkinter.


问:
Configuring GitLab to use SAML OmniAuth with an Active Directory IdP
I am in the process of altering an existing GitLab installation to use SAML rather than LDAP for authentication.

At this point, users can successfully sign into the Web application using the 'Sign in with Saml' button. I am unclear, however, about what seems to be a difference between the LDAP and SAML approaches: users with accounts created via an LDAP sign-in can then access Git repositories (e.g. using clone, push, ...) using their LDAP usernames and passwords, but users with accounts created via a SAML sign-in cannot.

Through experimentation, I’ve found that users can access the Git repositories if they use the GitLab UI to set a separate GitLab account password on the account that is created during the initial SAML interaction. I was pointed in this direction by a GitLab message that appeared after creating a project under one of the new user accounts: 'You won't be able to pull or push project code via HTTPS until you set a password on your account'.

It seems possible that this separate password configuration is only necessary because I’ve misconfigured the SAML integration somehow. So, my question is whether I am wrong to expect that authenticating access to the GitLab-hosted Git repositories would work the same regardless of whether SAML or LDAP is used? If not, does anyone know of relevant SAML configuration settings that I should review?

In case it’s of interest: I have posted a similar question to the GitLab Google group, but I have not received any responses there yet.

答:
This is an old question, but I'm responding anyway in hopes it helps someone else who stumbles upon this question.

An important distinction between LDAP and SAML is that SAML is a web-based single sign on technology. Part of the SAML sign in process happens between the user's client (browser) and the SAML server directly and then GitLab verifies that information on the backend. In contrast, when given a user's LDAP password GitLab can connect directly to the LDAP server and verify the identity.

Many GitLab users utilize a combination of LDAP and SAML. SAML provides seamless single sign-on for the web side while LDAP allows Git over HTTPS to accept passwords and also opens the door to advanced features like LDAP Group Sync in Enterprise Edition.


问:
Solr 7 Forcing q value
I'm using the Drupal ApacheSolr Multisite Module which due to it's dependency Apache Solr Search config currently only support Solr 5.x. I'm using Solr 7 and have update most of the config. I've got everything working except on /select. I believe this is because the query the module supplies (example shown below) features a "q" value which apparently causes it to fail. Is there a way in the solrconfig.xml to set q equal to "* . *" for all selects? I'd like to avoid code changes to the Drupal module itself if possible for deployment purposes.

Solar REST request example

```<code>http://localhost:8983/solr/drupal_multisite/select?start=0&rows=10&fq=%28hash%3A6qegyq%20OR%20access__all%3A0%29&fq=%28hash%3A6qegyq%29&spellcheck=true&q=test&fl=id%2Centity_id%2Centity_type%2Cbundle%2Cbundle_name%2Clabel%2Css_language%2Cis_comment_count%2Cds_created%2Cds_changed%2Cscore%2Cpath%2Curl%2Cis_uid%2Ctos_name%2Chash%2Csite&mm=1&pf=content%5E2.0&ps=15&hl=true&hl.fl=content&hl.snippets=3&hl.mergeContigious=true&f.content.hl.alternateField=teaser&f.content.hl.maxAlternateFieldLength=256&spellcheck.q=test&qf=content%5E40&qf=label%5E5.0&qf=tags_h1%5E5.0&qf=tags_h2_h3%5E3.0&qf=tags_h4_h5_h6%5E2.0&qf=tags_inline%5E1.0&qf=tos_content_extra%5E0.1&qf=tos_name%5E3.0&qf=ts_comments%5E20&wt=json&json.nl=map
</code>```

solarconfig.xml example

```<code><requestHandler name="/select" class="solr.SearchHandler">
 <lst name="defaults">
  <str name="df">text</str>
  <str name="q">*:*</str>
  <str name="q.alt">*:*</str>
 </lst>
</requestHandler>
</code>```

Thank you for any advice!

答: If you are ok writing some code (no in drupal module, but a standalone class/jar) then you can write a solr plugin (https://wiki.apache.org/solr/SolrPlugins) and write a custom handler for "/select" (https://medium.com/@wkaichan/custom-request-handler-in-apache-solr-4f76521b031a) and in that handler override "q" parameter to "." and call the original handler.

Title: Solr 7 Forcing q value

Body:
I'm using the Drupal ApacheSolr Multisite Module which due to it's dependency Apache Solr Search config currently only support Solr 5.x. I'm using Solr 7 and have update most of the config. I've got everything working except on /select. I believe this is because the query the module supplies (example shown below) features a "q" value which apparently causes it to fail. Is there a way in the solrconfig.xml to set q equal to "* . *" for all selects? I'd like to avoid code changes to the Drupal module itself if possible for deployment purposes.

Solar REST request example

http://localhost:8983/solr/drupal_multisite/select?start=0&rows=10&fq=%28hash%3A6qegyq%20OR%20access__all%3A0%29&fq=%28hash%3A6qegyq%29&spellcheck=true&q=test&fl=id%2Centity_id%2Centity_type%2Cbundle%2Cbundle_name%2Clabel%2Css_language%2Cis_comment_count%2Cds_created%2Cds_changed%2Cscore%2Cpath%2Curl%2Cis_uid%2Ctos_name%2Chash%2Csite&mm=1&pf=content%5E2.0&ps=15&hl=true&hl.fl=content&hl.snippets=3&hl.mergeContigious=true&f.content.hl.alternateField=teaser&f.content.hl.maxAlternateFieldLength=256&spellcheck.q=test&qf=content%5E40&qf=label%5E5.0&qf=tags_h1%5E5.0&qf=tags_h2_h3%5E3.0&qf=tags_h4_h5_h6%5E2.0&qf=tags_inline%5E1.0&qf=tos_content_extra%5E0.1&qf=tos_name%5E3.0&qf=ts_comments%5E20&wt=json&json.nl=map

solarconfig.xml example

<requestHandler name="/select" class="solr.SearchHandler">
 <lst name="defaults">
  <str name="df">text</str>
  <str name="q">*:*</str>
  <str name="q.alt">*:*</str>
 </lst>
</requestHandler>

Thank you for any advice!


问:
How do I compare attributes of an object in an ArrayList against Scanner input?
I have a simple 'Supplier/Product' Java application running in the Eclipse console.

Each 'Supplier' object has an ArrayList of 'Product' objects.

```<code>public class Supplier {

private int supCode;
private String supName;
private Address supAddress;
private SupRegion supRegion;
private ArrayList<Product> supProducts;

public Supplier(int supCode, String supName, Address supAddress, SupRegion supRegion,
        ArrayList<Product> supProducts) {
    super();
    this.supCode = supCode;
    this.supName = supName;
    this.supAddress = supAddress;
    this.supRegion = supRegion;
    this.supProducts = supProducts;
}
</code>```

I then have another ArrayList containing the Supplier objects "supDatabase"

There are only 2 suppliers present at runtime created below:

```<code>//Suppliers
Supplier hendys = new Supplier(101, "Hendersons" , add1, SupRegion.UNITED_KINGDOM, hendysPros);
Supplier palasFoods = new Supplier(102, "Palas Foods", add2, SupRegion.UNITED_KINGDOM, palasPros);

ArrayList<Supplier> supDatabase = new ArrayList<Supplier>();

//method to add all products into ProductArrayList
//also to add all suppliers to SupplierArrayList
public ArrayList<Supplier> populateDatabase(ArrayList<Supplier> supDB) {

    hendysPros.add(remote);
    hendysPros.add(remote1);
    hendysPros.add(remote2);
    hendysPros.add(remote3);

    supDatabase.add(hendys);

    palasPros.add(strawberries);
    palasPros.add(raspberries);
    palasPros.add(blueberries);

    supDatabase.add(palasFoods);

    return supDatabase;
}
</code>```

I am now trying to add functionality to add a new product to a specific supplier.

The following method attempts to compare user's input of a Supplier 'code' with the data in the ArrayList (supDatabase):

```<code>private static void addNewProduct(Scanner sc)
{
    System.out.println("Enter supplier code you would like to add a product to: ");
    int choice = getUserInput(sc);

    //***PROBLEM*** - trying to validate whether the user has entered an existing Supplier code i.e.
    //does the integer entered match a Suppliers's code, contained within a Supplier object
    //which are then contained within an ArrayList (supDatabase)

    for (int i=0; i<supDB.supDatabase.size();i++)           //for loop to cycle through ArrayList of Supplier objects??
    {
        if (choice == supDB.supDatabase.get(i).getSupCode())
        {
            System.out.println("You have chosen to add a product to: " + supDB.supDatabase.get(i).getSupName());

            Product newProduct  = new Product(0, "", "", 0, 0, false);

            System.out.println("Enter a code for the new product: ");
            newProduct.setProCode(sc.nextInt());

            System.out.println("Enter make: ");
            newProduct.setProMake(sc.next());

            System.out.println("Enter model: ");
            newProduct.setProModel(sc.next());

            System.out.println("Enter price: ");
            newProduct.setProPrice(sc.nextDouble());

            System.out.println("Enter the quantity available: ");
            newProduct.setProQtyAvailable(sc.nextInt());

            System.out.println("Is the product available? (Y/N)");
            newProduct.setProDiscontinued(sc.hasNext());

            //add the new created Product to the database ArrayList
            supDB.supDatabase.get(i).getSupProducts().add(newProduct);
        }
        else
        {
            System.out.println("Supplier code not present. Try again");
        }
    }

}
</code>```

The comparison is only working for the first Supplier in the ArrayList and is not recognizing anything past it. I know this has something to do with the structure of addNewProduct().

Can anyone recommend any restructuring or indeed any other techniques I could adopt for this? (I realise the code i'm using at the minute is very basic so I am open to any new features I could bring in to tidy things up!)

答:
I would recommend you use HashMap to store and look up suppliers instead of the ArrayList. Here is how the function would be different.

```<code>Map<Integer, Supplier> supDatabase = new HashMap<Integer, Supplier>();

//method to add all products into ProductArrayList
//also to add all suppliers to SupplierArrayList
public Map<Integer, Supplier> populateDatabase() {
    hendys.add(prod1);
    hendys.add(prod2);
    hendys.add(prod3);
    hendys.add(prod4);

    supDatabase.put(hendys.getSupCode(), hendys);

    palasFoods.add(strawberries);
    palasFoods.add(raspberries);
    palasFoods.add(blueberries);

    supDatabase.add(palasFoods.getSupCode(), palasFoods);

    return supDatabase;
}
</code>```

This is assuming you have getters defined for supplier code in the Supplier object.

This would make the addNewProduct look as below:

```<code>private static void addNewProduct(Scanner sc)
{
    System.out.println("Enter supplier code you would like to add a product to: ");
    int choice = getUserInput(sc);

    Map<Integer, Supplier> supDatabase = new HashMap<Integer, Supplier>();

    if (supDatabase.containsKey(sc)) {
        System.out.println("You have chosen to add a product to: " + supDB.supDatabase.get(i).getSupName());

        Product newProduct  = new Product(0, "", "", 0, 0, false);

        System.out.println("Enter a code for the new product: ");
        newProduct.setProCode(sc.nextInt());

        System.out.println("Enter make: ");
        newProduct.setProMake(sc.next());

        System.out.println("Enter model: ");
        newProduct.setProModel(sc.next());

        System.out.println("Enter price: ");
        newProduct.setProPrice(sc.nextDouble());

        System.out.println("Enter the quantity available: ");
        newProduct.setProQtyAvailable(sc.nextInt());

        System.out.println("Is the product available? (Y/N)");
        newProduct.setProDiscontinued(sc.hasNext());

        //add the new created Product to the database ArrayList
        supDatabase.get(sc).getSupProducts().add(newProduct);
    }
    else
    {
        System.out.println("Supplier code not present. Try again");
    }
}
</code>```

In case of an error, if you want the user to try again, you might need to put it in a loop so it asks the user again for input. Might be a good idea to put a counter on it or an exit loop if there are no suppliers or the user wants to exit.

Body:
I have a simple 'Supplier/Product' Java application running in the Eclipse console.

Each 'Supplier' object has an ArrayList of 'Product' objects.

public class Supplier {

private int supCode;
private String supName;
private Address supAddress;
private SupRegion supRegion;
private ArrayList<Product> supProducts;

public Supplier(int supCode, String supName, Address supAddress, SupRegion supRegion,
        ArrayList<Product> supProducts) {
    super();
    this.supCode = supCode;
    this.supName = supName;
    this.supAddress = supAddress;
    this.supRegion = supRegion;
    this.supProducts = supProducts;
}

I then have another ArrayList containing the Supplier objects "supDatabase"

There are only 2 suppliers present at runtime created below:

//Suppliers
Supplier hendys = new Supplier(101, "Hendersons" , add1, SupRegion.UNITED_KINGDOM, hendysPros);
Supplier palasFoods = new Supplier(102, "Palas Foods", add2, SupRegion.UNITED_KINGDOM, palasPros);

ArrayList<Supplier> supDatabase = new ArrayList<Supplier>();

//method to add all products into ProductArrayList
//also to add all suppliers to SupplierArrayList
public ArrayList<Supplier> populateDatabase(ArrayList<Supplier> supDB) {

    hendysPros.add(remote);
    hendysPros.add(remote1);
    hendysPros.add(remote2);
    hendysPros.add(remote3);

    supDatabase.add(hendys);

    palasPros.add(strawberries);
    palasPros.add(raspberries);
    palasPros.add(blueberries);

    supDatabase.add(palasFoods);

    return supDatabase;
}

I am now trying to add functionality to add a new product to a specific supplier.

The following method attempts to compare user's input of a Supplier 'code' with the data in the ArrayList (supDatabase):

private static void addNewProduct(Scanner sc)
{
    System.out.println("Enter supplier code you would like to add a product to: ");
    int choice = getUserInput(sc);

    //***PROBLEM*** - trying to validate whether the user has entered an existing Supplier code i.e.
    //does the integer entered match a Suppliers's code, contained within a Supplier object
    //which are then contained within an ArrayList (supDatabase)

    for (int i=0; i<supDB.supDatabase.size();i++)           //for loop to cycle through ArrayList of Supplier objects??
    {
        if (choice == supDB.supDatabase.get(i).getSupCode())
        {
            System.out.println("You have chosen to add a product to: " + supDB.supDatabase.get(i).getSupName());

            Product newProduct  = new Product(0, "", "", 0, 0, false);

            System.out.println("Enter a code for the new product: ");
            newProduct.setProCode(sc.nextInt());

            System.out.println("Enter make: ");
            newProduct.setProMake(sc.next());

            System.out.println("Enter model: ");
            newProduct.setProModel(sc.next());

            System.out.println("Enter price: ");
            newProduct.setProPrice(sc.nextDouble());

            System.out.println("Enter the quantity available: ");
            newProduct.setProQtyAvailable(sc.nextInt());

            System.out.println("Is the product available? (Y/N)");
            newProduct.setProDiscontinued(sc.hasNext());

            //add the new created Product to the database ArrayList
            supDB.supDatabase.get(i).getSupProducts().add(newProduct);
        }
        else
        {
            System.out.println("Supplier code not present. Try again");
        }
    }

}

The comparison is only working for the first Supplier in the ArrayList and is not recognizing anything past it. I know this has something to do with the structure of addNewProduct().

Can anyone recommend any restructuring or indeed any other techniques I could adopt for this? (I realise the code i'm using at the minute is very basic so I am open to any new features I could bring in to tidy things up!)

Body:
I would recommend you use HashMap to store and look up suppliers instead of the ArrayList. Here is how the function would be different.

Map<Integer, Supplier> supDatabase = new HashMap<Integer, Supplier>();

//method to add all products into ProductArrayList
//also to add all suppliers to SupplierArrayList
public Map<Integer, Supplier> populateDatabase() {
    hendys.add(prod1);
    hendys.add(prod2);
    hendys.add(prod3);
    hendys.add(prod4);

    supDatabase.put(hendys.getSupCode(), hendys);

    palasFoods.add(strawberries);
    palasFoods.add(raspberries);
    palasFoods.add(blueberries);

    supDatabase.add(palasFoods.getSupCode(), palasFoods);

    return supDatabase;
}

This is assuming you have getters defined for supplier code in the Supplier object.

This would make the addNewProduct look as below:

private static void addNewProduct(Scanner sc)
{
    System.out.println("Enter supplier code you would like to add a product to: ");
    int choice = getUserInput(sc);

    Map<Integer, Supplier> supDatabase = new HashMap<Integer, Supplier>();

    if (supDatabase.containsKey(sc)) {
        System.out.println("You have chosen to add a product to: " + supDB.supDatabase.get(i).getSupName());

        Product newProduct  = new Product(0, "", "", 0, 0, false);

        System.out.println("Enter a code for the new product: ");
        newProduct.setProCode(sc.nextInt());

        System.out.println("Enter make: ");
        newProduct.setProMake(sc.next());

        System.out.println("Enter model: ");
        newProduct.setProModel(sc.next());

        System.out.println("Enter price: ");
        newProduct.setProPrice(sc.nextDouble());

        System.out.println("Enter the quantity available: ");
        newProduct.setProQtyAvailable(sc.nextInt());

        System.out.println("Is the product available? (Y/N)");
        newProduct.setProDiscontinued(sc.hasNext());

        //add the new created Product to the database ArrayList
        supDatabase.get(sc).getSupProducts().add(newProduct);
    }
    else
    {
        System.out.println("Supplier code not present. Try again");
    }
}

In case of an error, if you want the user to try again, you might need to put it in a loop so it asks the user again for input. Might be a good idea to put a counter on it or an exit loop if there are no suppliers or the user wants to exit.


问:
Count match ratio between two dataset
I have two dataset wanted to count match Ratio

```<code>> events_data
  LONGITUDE LATITUDE  matchvalue
1     122.5    9.5    0.006269592
2     122.5   10.5    0.050156740
3     125.5   10.5    0.043887147
4     146.5   40.5    0.048213166
5     142.5   40.5    0.035078370
6     146.5   40.5    0.028213166

> events
  LATITUDE LONGITUDE
1    9.880  124.1167
2   37.156  144.6611
</code>```

using events(within 5 both in latitude and longitude) to select data in events_data

when  events_data.matchvalue > 0.04, set this row data in events_data is ture, or is flase

count match Ratio = (totalRows in events_data is ture)/(totalRows in events_data is ture + totalRows in events_data is false)

take event 1 for example

```<code>1. select data in events_data within latitude(9.880 +/- 5) and longitude(124.1167 +/-5),you can get data in events_data:
   LONGITUDE LATITUDE  matchvalue
 1     122.5    9.5    0.006269592
 2     122.5   10.5    0.050156740
 3     125.5   10.5    0.043887147
2. count(events_data.matchvalue > 0.04) = 2
3. count match Ratio = 2/3 = 0.67
</code>```

my expect is add a new column match_Ratio

```<code>  LATITUDE LONGITUDE  match_Ratio
1    9.880  124.1167  0.67
2   37.156  144.6611  0.33
</code>```

my data used are:

```<code>events_data <- structure(list(LONGITUDE = c(122.5, 122.5, 122.5, 146.5, 142.5,
146.5), LATITUDE = c(9.5, 10.5, 10.5, 40.5, 40.5, 40.5
), matchvalue = c(0.00626959247648903, 0.0501567398119122, 0.0438871473354232,
0.0482131661442006, 0.0350783699059561, 0.0282131661442006)), .Names = c("LONGITUDE",
"LATITUDE", "matchvalue"), row.names = c(NA, 6L), class = "data.frame")

events <- structure(list(LATITUDE = c(9.88, 37.156), LONGITUDE = c(124.1167,
144.6611)), .Names = c("LATITUDE", "LONGITUDE"), class = "data.frame", row.names = 1:2)
</code>```

How to implement it, thanks

答:
Here is a straightforward base R solution.

```<code>long <- events_data$LONGITUDE
lat <- events_data$LATITUDE
myVals <- events_data$matchvalue

events$match_Ratio <- apply(events, 1, function(x) {
    z <- which(lat > (x[1] - 5) & lat < (x[1] + 5))
    v <- which(long > (x[2] - 5) & long < (x[2] + 5))
    ind <- intersect(z, v)
    sum(myVals[ind] > 0.04)/length(ind)
})

events
  LATITUDE LONGITUDE match_Ratio
1    9.880  124.1167   0.6666667
2   37.156  144.6611   0.3333333
</code>```

Title: Count match ratio between two dataset

Body:
I have two dataset wanted to count match Ratio

> events_data
  LONGITUDE LATITUDE  matchvalue
1     122.5    9.5    0.006269592
2     122.5   10.5    0.050156740
3     125.5   10.5    0.043887147
4     146.5   40.5    0.048213166
5     142.5   40.5    0.035078370
6     146.5   40.5    0.028213166

> events
  LATITUDE LONGITUDE
1    9.880  124.1167
2   37.156  144.6611

using events(within 5 both in latitude and longitude) to select data in events_data

when  events_data.matchvalue > 0.04, set this row data in events_data is ture, or is flase

count match Ratio = (totalRows in events_data is ture)/(totalRows in events_data is ture + totalRows in events_data is false)

take event 1 for example

1. select data in events_data within latitude(9.880 +/- 5) and longitude(124.1167 +/-5),you can get data in events_data:
   LONGITUDE LATITUDE  matchvalue
 1     122.5    9.5    0.006269592
 2     122.5   10.5    0.050156740
 3     125.5   10.5    0.043887147
2. count(events_data.matchvalue > 0.04) = 2
3. count match Ratio = 2/3 = 0.67

my expect is add a new column match_Ratio

  LATITUDE LONGITUDE  match_Ratio
1    9.880  124.1167  0.67
2   37.156  144.6611  0.33

my data used are:

events_data <- structure(list(LONGITUDE = c(122.5, 122.5, 122.5, 146.5, 142.5,
146.5), LATITUDE = c(9.5, 10.5, 10.5, 40.5, 40.5, 40.5
), matchvalue = c(0.00626959247648903, 0.0501567398119122, 0.0438871473354232,
0.0482131661442006, 0.0350783699059561, 0.0282131661442006)), .Names = c("LONGITUDE",
"LATITUDE", "matchvalue"), row.names = c(NA, 6L), class = "data.frame")

events <- structure(list(LATITUDE = c(9.88, 37.156), LONGITUDE = c(124.1167,
144.6611)), .Names = c("LATITUDE", "LONGITUDE"), class = "data.frame", row.names = 1:2)

How to implement it, thanks

Body:
Here is a straightforward base R solution.

long <- events_data$LONGITUDE
lat <- events_data$LATITUDE
myVals <- events_data$matchvalue

events$match_Ratio <- apply(events, 1, function(x) {
    z <- which(lat > (x[1] - 5) & lat < (x[1] + 5))
    v <- which(long > (x[2] - 5) & long < (x[2] + 5))
    ind <- intersect(z, v)
    sum(myVals[ind] > 0.04)/length(ind)
})

events
  LATITUDE LONGITUDE match_Ratio
1    9.880  124.1167   0.6666667
2   37.156  144.6611   0.3333333


问:
Insert data into MySQL Databse with PHP/AJAX, execute success option AFTER it's inserted (Callback)
I've been trying to make a simple site, and I can't quite wrap my head around some of the things said here, some of which are also unrelated to my situation.

The site has a form with 3 input boxes, a button, and a list. The info is submitted through a separate PHP file to a MySQL database, once the submit button is clicked. I'm supposed to make the list (it's inside a div) update once the info is successfully sent and updated in the database. So far I've made it work with async:false but I'm not supposed to, because of society.

Without this (bad) option, the list doesn't load after submitting the info, because (I assume) the method is executed past it, since it doesn't wait for it to finish.

What do I exactly have to do in "success:" to make it work? (Or, I've read something about .done() within the $.ajax clause, but I'm not sure how to make it work.)

What's the callback supposed to be like? I've never done it before and I can get really disoriented with the results here because each case is slightly different.

function save() {
    var name = document.getElementById('name');
    var email = document.getElementById('email');
    var telephone = document.getElementById('telephone');

    $.ajax({
        url: "save.php",
        method: "POST",
        data: { name: name.value, email: email.value, telephone: telephone.value },
        success: $("List").load(" List")
    });
}```

Thank you in advanced and if I need include further info don't hesitate to ask.

答:
I would first create an AJAX call inside a function which runs when the page loads to populate the list.

```<code>window.onload = populatelist();

function populatelist() {
   $.ajax({
      type: "POST",
      url: "list.php",
      data: {function: 'populate'},
      success: function(data) { $("#list").html("data"); }
   });
}
</code>```

Note: #list refers to
 and your list should be inside this.

I would then have another AJAX call inside a different function which updates the database when the form is submitted. Upon success, it will run the populatelist function.

```<code>function save() {
   var name = document.getElementById('name');
   var email = document.getElementById('email');
   var telephone = document.getElementById('telephone');

   $.ajax({
       type: "POST",
       url: "list.php",
       data: {function: 'update', name: name.value, email: email.value, telephone: telephone.value },
       success: function() { populatelist(); }
   });
}
</code>```

list.php should look like this:

```<code><?php

if($_POST['function'] == "populate") {
   // your code to get the content from the database and put it in a list
}

if($_POST['function'] == "update") {
   // your code to update the database
}

?>
</code>```

Body:
I've been trying to make a simple site, and I can't quite wrap my head around some of the things said here, some of which are also unrelated to my situation.

The site has a form with 3 input boxes, a button, and a list. The info is submitted through a separate PHP file to a MySQL database, once the submit button is clicked. I'm supposed to make the list (it's inside a div) update once the info is successfully sent and updated in the database. So far I've made it work with async:false but I'm not supposed to, because of society.

Without this (bad) option, the list doesn't load after submitting the info, because (I assume) the method is executed past it, since it doesn't wait for it to finish.

What do I exactly have to do in "success:" to make it work? (Or, I've read something about .done() within the $.ajax clause, but I'm not sure how to make it work.)

What's the callback supposed to be like? I've never done it before and I can get really disoriented with the results here because each case is slightly different.

function save() {
    var name = document.getElementById('name');
    var email = document.getElementById('email');
    var telephone = document.getElementById('telephone');

    $.ajax({
        url: "save.php",
        method: "POST",
        data: { name: name.value, email: email.value, telephone: telephone.value },
        success: $("List").load(" List")
    });
}

Thank you in advanced and if I need include further info don't hesitate to ask.

Body:
I would first create an AJAX call inside a function which runs when the page loads to populate the list.

window.onload = populatelist();

function populatelist() {
   $.ajax({
      type: "POST",
      url: "list.php",
      data: {function: 'populate'},
      success: function(data) { $("#list").html("data"); }
   });
}

Note: #list refers to <div id="list> and your list should be inside this.

I would then have another AJAX call inside a different function which updates the database when the form is submitted. Upon success, it will run the populatelist function.

function save() {
   var name = document.getElementById('name');
   var email = document.getElementById('email');
   var telephone = document.getElementById('telephone');

   $.ajax({
       type: "POST",
       url: "list.php",
       data: {function: 'update', name: name.value, email: email.value, telephone: telephone.value },
       success: function() { populatelist(); }
   });
}

list.php should look like this:

<?php

if($_POST['function'] == "populate") {
   // your code to get the content from the database and put it in a list
}

if($_POST['function'] == "update") {
   // your code to update the database
}

?>


问:
VBA: Code review - Skip 1st line of a sheet
I was trying to understand how to skip the 1st row (A) of my sheet when i use below code which check whether any value available on my excel sheet.

```<code>Sub IsActiveSheetEmpty()
    If WorksheetFunction.CountA(Cells) = 0 Then
       MsgBox ActiveSheet.Name & " is empty"
    Else
      MsgBox ActiveSheet.Name & " is not empty"
    End If
End Sub
</code>```

Thanks in Advance

答:
```<code>Sub IsActiveSheetEmpty()
If WorksheetFunction.CountA("A2:A5") = 0 Then 'skips A1
   MsgBox ActiveSheet.Name & " is empty"
Else
  MsgBox ActiveSheet.Name & " is not empty"
End If
</code>```

End Sub

Body:
I was trying to understand how to skip the 1st row (A) of my sheet when i use below code which check whether any value available on my excel sheet.

Sub IsActiveSheetEmpty()
    If WorksheetFunction.CountA(Cells) = 0 Then
       MsgBox ActiveSheet.Name & " is empty"
    Else
      MsgBox ActiveSheet.Name & " is not empty"
    End If
End Sub

Thanks in Advance

Body:
Sub IsActiveSheetEmpty()
If WorksheetFunction.CountA("A2:A5") = 0 Then 'skips A1
   MsgBox ActiveSheet.Name & " is empty"
Else
  MsgBox ActiveSheet.Name & " is not empty"
End If

End Sub