问:
Create unique index on custom tables in Dynamics 365 CRM
While using Dynamics365 Sdk to write data to a custom entity, new_licenseRecordsSet, in Dynamis CRM database, I encountered some concurrency issue where an exact duplicate record sometimes would be created in the targeted table. The code to check existing record (and created new License only when the existing record is null) as shown below seemed not always working (in 98% of time it did work).

```<code>private LicenseRecDto GetExistingLicRecord(int accountId, short instanceId, int licenseId, IOrganizationService service)
    {
        var context = new DynamicsCrmProxyContext(service);
        var dynamicsExpectedInstanceId = (Int32)instanceId; // Dynamic sdk will throw exception of not casting a short; weird but true

        //In some rare cases we found there were exact duplicates of same License record in Dynamics CRM. Using FirstOrDefault instead of SingleOrDefault will avoid throwing unnecessary exception and
        //make the same record got created again and again in Dynamics.
        var license = context.new_licenseRecordsSet
            .Where(
                l => l.new_LicenseID == licenseId
                     && l.new_InstanceID == dynamicsExpectedInstanceId
                     && l.new_AccountId == accountId)
            .OrderByDescending(d => d.VersionNumber)
            .FirstOrDefault();

        return license?.MapToDynamicsObject<LicenseRecDto>();
    }

private void CreateUpdateLicense(LicenseRecDto license, IOrganizationService service)
    {
        var dynamicsLicense = GetExistingLicRecord(license.AccountId, license.InstanceId, license.LicenseId, service);

            if (dynamicsLicense != null)
            {
                license.DynamicsLicenseGuid = dynamicsLicense.DynamicsLicenseGuid;
                UpdateLicense(license, service);
            }
            else
            {
                var result = CreateLicense(license, service);
                if (result != Guid.Empty)
                    license.DynamicsLicenseGuid = result;
            }

    }
</code>```

Not sure why this check failed in 2% of time and exact duplicated record still got created in the new_licenseRecordsSet, I decided to create unique index on the targeted table with these three columns included: LicenseId, AccountId, and InstanceId. But how will I proceed? Our DBA disallowed any alternation in schema from SQL Server and I couldn't find any other way from Dynamics CRM UI to let me add unique constraint on the custom entity.

My questions:

What could have caused the codes to fail while checking existing record? My speculation is there might be two concurrent threads checking on same record at the same time and both returned null and both led to creating new record. If that's the case, how can I impose locking to avoid concurrent check?

About creating unique index on the custom new_LicenseRecords table, what's the best approach? Is there Sdk method to do it? I searched and found none at this point.

Thanks in advance.

答:
A few thoughts for you:

Last I checked, there are only two supported direct interactions with SQL:

Access the filtered views for queries, SSRS reports, etc.

Create custom indexes

Any other modifications to the SQL database are unsupported, including adding constraints.

Rather than doing anything with SQL you might want to think about creating an alternate key.

You might also want to look into the out-of-box duplicate detection functionality.

Also, how are you launching the code? a plugin?

Body:
While using Dynamics365 Sdk to write data to a custom entity, new_licenseRecordsSet, in Dynamis CRM database, I encountered some concurrency issue where an exact duplicate record sometimes would be created in the targeted table. The code to check existing record (and created new License only when the existing record is null) as shown below seemed not always working (in 98% of time it did work).

private LicenseRecDto GetExistingLicRecord(int accountId, short instanceId, int licenseId, IOrganizationService service)
    {
        var context = new DynamicsCrmProxyContext(service);
        var dynamicsExpectedInstanceId = (Int32)instanceId; // Dynamic sdk will throw exception of not casting a short; weird but true

        //In some rare cases we found there were exact duplicates of same License record in Dynamics CRM. Using FirstOrDefault instead of SingleOrDefault will avoid throwing unnecessary exception and
        //make the same record got created again and again in Dynamics.
        var license = context.new_licenseRecordsSet
            .Where(
                l => l.new_LicenseID == licenseId
                     && l.new_InstanceID == dynamicsExpectedInstanceId
                     && l.new_AccountId == accountId)
            .OrderByDescending(d => d.VersionNumber)
            .FirstOrDefault();

        return license?.MapToDynamicsObject<LicenseRecDto>();
    }

private void CreateUpdateLicense(LicenseRecDto license, IOrganizationService service)
    {
        var dynamicsLicense = GetExistingLicRecord(license.AccountId, license.InstanceId, license.LicenseId, service);

            if (dynamicsLicense != null)
            {
                license.DynamicsLicenseGuid = dynamicsLicense.DynamicsLicenseGuid;
                UpdateLicense(license, service);
            }
            else
            {
                var result = CreateLicense(license, service);
                if (result != Guid.Empty)
                    license.DynamicsLicenseGuid = result;
            }

    }

Not sure why this check failed in 2% of time and exact duplicated record still got created in the new_licenseRecordsSet, I decided to create unique index on the targeted table with these three columns included: LicenseId, AccountId, and InstanceId. But how will I proceed? Our DBA disallowed any alternation in schema from SQL Server and I couldn't find any other way from Dynamics CRM UI to let me add unique constraint on the custom entity.

My questions:

What could have caused the codes to fail while checking existing record? My speculation is there might be two concurrent threads checking on same record at the same time and both returned null and both led to creating new record. If that's the case, how can I impose locking to avoid concurrent check?

About creating unique index on the custom new_LicenseRecords table, what's the best approach? Is there Sdk method to do it? I searched and found none at this point.

Thanks in advance.


来源: stackexchange

问:
Regex - Convert pattern from php to Java
In php I can check if a word is in a String like that

```<code>$muster = "/\b($word)\b/i";
if(preg_match($muster, $text)) {
        return true;
}
</code>```

Example:

```<code>$word = "test";
$text = "This is a :::test!!!";
</code>```

Returns true

I tried converting this into Java:

```<code>if (Pattern.matches("(?i)\\b(" + word + ")\\b", text)) {
   return true;
}
</code>```

The same example :

```<code>String word = "test";
String text = "This is a :::test!!!";
</code>```

would return false

What am I missing here? :(

答:
You have to use Matcher and call find like this :</p>

```<code>Pattern pattern = Pattern.compile("(?i)\\b(" + word + ")\\b");
Matcher matcher = pattern.matcher(text);
System.out.println(matcher.find());// true if match false if not
</code>```

ContentLicense: CC BY-SA 3.0

Body:
In php I can check if a word is in a String like that

$muster = "/\b($word)\b/i";
if(preg_match($muster, $text)) {
        return true;
}

Example:

$word = "test";
$text = "This is a :::test!!!";

Returns true

I tried converting this into Java:

if (Pattern.matches("(?i)\\b(" + word + ")\\b", text)) {
   return true;
}

The same example :

String word = "test";
String text = "This is a :::test!!!";

would return false

What am I missing here? :(

Body:
You have to use Matcher and call find like this :

Pattern pattern = Pattern.compile("(?i)\\b(" + word + ")\\b");
Matcher matcher = pattern.matcher(text);
System.out.println(matcher.find());// true if match false if not


问:
Update AWS S3 object key (key name)
I need to rename a huge number of files stored in an AWS S3 bucket. Each file/object will be renamed individually (based on the certain criteria - there is no common "prefix/suffix"). I came up with the list of 'current_filename' and 'new_filename' which can be executed the CLI as a .bat file/queue.

Is it possible to update just an object key (key name) in AWS S3 bucket via CLI or programmatically, without have to copy/move file as below:

```<code>aws s3 cp s3://mybucket/folder/myfilename.jpg s3://mybucket/folder/my_NEW_filename.jpg
</code>```

I can keep all other object metadata the same, but file name (key name) has to change.

答:
You can also use the AWS S3 Move command to move files to new names rather than copy and delete files. AWS S3 Move</p>

```<code># AWS Example
aws s3 mv s3://mybucket/test.txt s3://mybucket/test2.txt

# Copy file from local to S3
aws s3 cp robots.txt s3://ascisolutions.com

# Rename/move file
aws s3 mv s3://ascisolutions.com/robots.txt s3://ascisolutions.com/robots.txt.bak

# Move file to a directory in S3
aws s3 mv s3://ascisolutions.com/robots.txt.bak s3://ascisolutions.com/test/robots.txt.bak

# Rename/move file
aws s3 mv s3://ascisolutions.com/test/robots.txt.bak s3://ascisolutions.com/test/robots.txt

# Move file back to root directory of S3 bucket
aws s3 mv s3://ascisolutions.com/test/robots.txt s3://ascisolutions.com/robots.txt
</code>```

ContentLicense: CC BY-SA 4.0

Title: Update AWS S3 object key (key name)

Body:
I need to rename a huge number of files stored in an AWS S3 bucket. Each file/object will be renamed individually (based on the certain criteria - there is no common "prefix/suffix"). I came up with the list of 'current_filename' and 'new_filename' which can be executed the CLI as a .bat file/queue.

Is it possible to update just an object key (key name) in AWS S3 bucket via CLI or programmatically, without have to copy/move file as below:

aws s3 cp s3://mybucket/folder/myfilename.jpg s3://mybucket/folder/my_NEW_filename.jpg

I can keep all other object metadata the same, but file name (key name) has to change.

Body:
You can also use the AWS S3 Move command to move files to new names rather than copy and delete files. AWS S3 Move

# AWS Example
aws s3 mv s3://mybucket/test.txt s3://mybucket/test2.txt

# Copy file from local to S3
aws s3 cp robots.txt s3://ascisolutions.com

# Rename/move file
aws s3 mv s3://ascisolutions.com/robots.txt s3://ascisolutions.com/robots.txt.bak

# Move file to a directory in S3
aws s3 mv s3://ascisolutions.com/robots.txt.bak s3://ascisolutions.com/test/robots.txt.bak

# Rename/move file
aws s3 mv s3://ascisolutions.com/test/robots.txt.bak s3://ascisolutions.com/test/robots.txt

# Move file back to root directory of S3 bucket
aws s3 mv s3://ascisolutions.com/test/robots.txt s3://ascisolutions.com/robots.txt


问:
Replace random value in string with random value
virus is supposed to be a string of nucleotides, and the function should return a string consisting of the same amount of nucleotides, but one is changed.

```<code>def mutate(virus):
    mutations = ['A', 'T', 'C', 'G']
    virus.split
    random.randrange(1, stop=len(virus), step=1) = random.choice(mutations)
</code>```

so for example if the virus is ATCG it should return something like ATCC or GTCG, how can I go about this, I tried making virus into a list, and replacing a random variable in it with a random of my possible mutations list.

So it should probably make a list from the string virus, do a mutation, put the list back into a string and return the string.

答:
Since string are immutable, I would recommend working with list instead of string. Readability will be increase also in my opinion.

```<code>import random
def mutate(virus):
    mutations = ['A', 'T', 'C', 'G']
    virus = list(virus)
    virus[random.randint(0, len(virus)-1)] = random.choice(mutations)
    return "".join(virus)
</code>```

Output

```<code>>>> print(mutate('ATCG'))
ATCT

>>> print(mutate('ATCG'))
ATTG

>>> print(mutate('ATCG'))
ATCC
</code>```

Body:
virus is supposed to be a string of nucleotides, and the function should return a string consisting of the same amount of nucleotides, but one is changed.

def mutate(virus):
    mutations = ['A', 'T', 'C', 'G']
    virus.split
    random.randrange(1, stop=len(virus), step=1) = random.choice(mutations)

so for example if the virus is ATCG it should return something like ATCC or GTCG, how can I go about this, I tried making virus into a list, and replacing a random variable in it with a random of my possible mutations list.

So it should probably make a list from the string virus, do a mutation, put the list back into a string and return the string.

Body:
Since string are immutable, I would recommend working with list instead of string. Readability will be increase also in my opinion.

import random
def mutate(virus):
    mutations = ['A', 'T', 'C', 'G']
    virus = list(virus)
    virus[random.randint(0, len(virus)-1)] = random.choice(mutations)
    return "".join(virus)

Output

>>> print(mutate('ATCG'))
ATCT

>>> print(mutate('ATCG'))
ATTG

>>> print(mutate('ATCG'))
ATCC


问:
Visual Studio: how to control specific configuration parameters on student PCs?
Can anyone tell me how to control default configuration parameters in VS 2017 C++?  The scenario is that we generate one sample PC with the software we want (Win10, VS2017, et cetera), and this image is cloned onto about 100 PCs in student CS labs.

The two specific things I would like to control are (1) use of precompiled headers and (2) message C4706 (= versus == in an if condition).  There are some others, but these are at top of the list.

I know students could fix this themselves, but so many are confused in the first few weeks of an introductory programming class that I don't want to try that.

A search of MSDN has not been productive, but I probably am using the wrong search terms.

Thank you in advance!

答:
For enabling Precompiled header.

Right click your project->Properties->( a property pages window appears)Configuration Properties-> C/C++ -> Precompiled Headers -> (on the right side) Select Use(/Yu) by clicking Precompiled Header.

And for suppressing C4706, set compiler warning to level less than 4

Right click your project->Properties->( a property pages window appears)Configuration Properties-> C/C++ -> General ->Warning Level to less than 4

To retain the settings and share with others....

I do not have proper VS2017.... Can you try as said below.....

First export the existing project settings using

project(visual studio menu)->Export template.... continue and and save the template and make a note of the path....

usually by default the templates is saved in below path as a zip file.

C:\Users\<>\Documents\Visual Studio 2017\My Exported Templates

Now copy the zip file and and put it in

C:\Users\<>\Documents\Visual Studio 2017\Templates\ProjectTemplates\Visual C++ Project

Check if your template is automatically picked up.

If not open visual studio command prompt tool and run

devenv /installvstemplates.


问:
ShellCheck warning: "Iterating over ls output is fragile. Use globs. [SC2045]"
I am getting a ShellCheck warning [SC2045] for the second line in the code below. Is it fine to ignore it as I am making sure the directory is not empty before I try the last ls?

```<code> if [ "$(ls -A "$retryDir")" ]  ; then
    for thisRetryFile in $(ls "$retryDir"/*.tar.gz) ; do
        scp -o ConnectTimeout=30  "$thisRetryFile"  \
              "$remoteUser@$remoteHost:$remotePath" >> "$BACKUPLOG"
    done
 fi
</code>```

UPDATE:
After reading the post comments. I have changed the line to:

```<code>for thisRetryFile in "$retryDir"/*.tar.gz ; do
</code>```

This has removed the warnings.

答:
This is safer. Try it.

```<code> if [ "$(ls -A "$retryDir")" ]  ; then
    for thisRetryFile in ${retryDir}'/*.tar.gz' ; do
        scp -o ConnectTimeout=30  "$thisRetryFile"  "$remoteUser@$remoteHost:$remotePath" >> "$BACKUPLOG"
    done
 fi
</code>```

Regards!

Body:
I am getting a ShellCheck warning [SC2045] for the second line in the code below. Is it fine to ignore it as I am making sure the directory is not empty before I try the last ls?

 if [ "$(ls -A "$retryDir")" ]  ; then
    for thisRetryFile in $(ls "$retryDir"/*.tar.gz) ; do
        scp -o ConnectTimeout=30  "$thisRetryFile"  \
              "$remoteUser@$remoteHost:$remotePath" >> "$BACKUPLOG"
    done
 fi

UPDATE:
After reading the post comments. I have changed the line to:

for thisRetryFile in "$retryDir"/*.tar.gz ; do

This has removed the warnings.

Body:
This is safer. Try it.

 if [ "$(ls -A "$retryDir")" ]  ; then
    for thisRetryFile in ${retryDir}'/*.tar.gz' ; do
        scp -o ConnectTimeout=30  "$thisRetryFile"  "$remoteUser@$remoteHost:$remotePath" >> "$BACKUPLOG"
    done
 fi

Regards!


问:
Logging and Exception handling in a micro-service in Java
I am working on a microservice which does some calculation based on certain configurations stored in its own data store. The calculations apis are stored via REST APIs. The application is a spring boot application.
Now there are mainly 3 layers in the application :

REST Controller

Service layer

DAO layer - it used spring data.

I am planning to handle the logging and exception handling using below points:

Log each request that the service receives and response or at least
the response if the status is not in 2xx series.

If there are any    checked exception in either DAO layer or Service
layer then log them    and throw a custom exception derived from
RuntimeException.

Have Several custom exception which    should be thrown from Service
layer mainly if we come across    scenarios like invalid values, null
values etc.

Have a try catch    block in the REST Controller and log the
exception i.e. message along    with stacktrace and return the
response accordingly.

So overall idea is to let the RuntimeExceptions propagate all the way to REST Controller where they should be logged and accordingly the response should be sent. Incase of checked exceptions log them in the same method and throw custom exceptions instead.

Please suggest what should be the correct or a good approach for logging exception in such applications.

答:
Choose only one place to log the exceptions.

In your design, if an exception occurs in DAO, it will:

Get logged in DAO

Then trigger a runtime exception, which will be caught and logged in controller

Which should then return non-2xx response status via REST, which will trigger logging the response as per your first point

So you'll have either the same information in three places, or you will have the different bits of information regarding a single error scattered in two or three places across the log.

Choose a single place to log the errors, and make sure all relevant info is present at that place (i.e. set the underlying DAO exception as a cause of the runtime exception, and don't forget to log the runtime exception along with its cause).


问:
How do I parse a string with 'h', 'm', 's' suffixes to a TimeSpan?

I need to parse the string "26h44m3s" to  a TimeSpan in C#. I cannot find anything implemented in .NET that can handle it. So how do I accomplish it, and in clean way? And are there any existing nugets for this?

I am receiving the string from the "duration" property on Twitch API endpoint GetVideos.

答:
You can use Noda Time for this, parsing as a Duration. You could then convert it to a TimeSpan - or you could use Noda Time everywhere and have a nicer experience :)

Sample code:

```<code>using System;
using NodaTime;
using NodaTime.Text;

class Program
{
    static void Main()
    {
        string text = "26h44m3s";
        var pattern = DurationPattern.CreateWithInvariantCulture("H'h'm'm's's'");
        var duration = pattern.Parse(text).Value;
        Console.WriteLine(duration);
        var ts = duration.ToTimeSpan();
        Console.WriteLine(ts);
    }
}
</code>```

If you have multiple patterns that need to match, you can create a composite pattern - although you'll need to list all the patterns explicitly. Here's an example of that:

```<code>using System;
using System.Linq;
using NodaTime;
using NodaTime.Text;

class Program
{
    static void Main()
    {

        string[] formats =
        {
            "H'h'm'm's's'", "H'h'm'm'", "M'm's's'", "H'h'", "M'm'", "S's'"
        };
        var patterns = formats.Select(DurationPattern.CreateWithInvariantCulture);
        var builder = new CompositePatternBuilder<Duration>();
        foreach (var pattern in patterns)
        {
            // The second parameter is used to choose which pattern is
            // used for formatting. Let's ignore it for now.
            builder.Add(pattern, _ => true);
        }
        var composite = builder.Build();

        string[] values = { "26h8m", "26h", "15s", "56m47s" };
        foreach (var value in values)
        {
            Console.WriteLine(composite.Parse(value).Value);
        }
    }
}
</code>```

Body:
You can use Noda Time for this, parsing as a Duration. You could then convert it to a TimeSpan - or you could use Noda Time everywhere and have a nicer experience :)

Sample code:

using System;
using NodaTime;
using NodaTime.Text;

class Program
{
    static void Main()
    {
        string text = "26h44m3s";
        var pattern = DurationPattern.CreateWithInvariantCulture("H'h'm'm's's'");
        var duration = pattern.Parse(text).Value;
        Console.WriteLine(duration);
        var ts = duration.ToTimeSpan();
        Console.WriteLine(ts);
    }
}

If you have multiple patterns that need to match, you can create a composite pattern - although you'll need to list all the patterns explicitly. Here's an example of that:

using System;
using System.Linq;
using NodaTime;
using NodaTime.Text;

class Program
{
    static void Main()
    {

        string[] formats =
        {
            "H'h'm'm's's'", "H'h'm'm'", "M'm's's'", "H'h'", "M'm'", "S's'"
        };
        var patterns = formats.Select(DurationPattern.CreateWithInvariantCulture);
        var builder = new CompositePatternBuilder<Duration>();
        foreach (var pattern in patterns)
        {
            // The second parameter is used to choose which pattern is
            // used for formatting. Let's ignore it for now.
            builder.Add(pattern, _ => true);
        }
        var composite = builder.Build();

        string[] values = { "26h8m", "26h", "15s", "56m47s" };
        foreach (var value in values)
        {
            Console.WriteLine(composite.Parse(value).Value);
        }
    }
}


问:
How to deploy node app on openshift and run it?

Just created a very simple hello world app using node:

```<code>var express = require('express');
var app = express();
app.get('/', function (req, res) {
  res.send('Hello World!');
});
var server_port = process.env.OPENSHIFT_NODEJS_PORT || 8080
var server_ip_address = process.env.OPENSHIFT_NODEJS_IP || '127.0.0.1'

app.listen(server_port, server_ip_address, function () {
  console.log( "Listening on " + server_ip_address + ", port " + server_port )
});
</code>```

and it works as it is expected in my local machine,

put that on github and deployed it on openshift, pod created and server running fine:

 but when I browse the route which I could find it in Application>>routes menu it says:

```<code>Application is not available

The application is currently not serving requests at this endpoint. It may not have been started or is still starting.
I guess I'm using the latest version of openshift since just created an account.
</code>```

I'm expecting it to show me the Hello world!

update1:

here is my package.json:

```<code>{
  "name": "npmtest",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "node index.js"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "express": "^4.16.2"
  }
}
</code>```

答:
have you configure main file in package.json

and maybe you need to get port dynamically from the environment variables check below link for openshift sample

https://github.com/openshift/nodejs-ex

Body:
Just created a very simple hello world app using node:

var express = require('express');
var app = express();
app.get('/', function (req, res) {
  res.send('Hello World!');
});
var server_port = process.env.OPENSHIFT_NODEJS_PORT || 8080
var server_ip_address = process.env.OPENSHIFT_NODEJS_IP || '127.0.0.1'

app.listen(server_port, server_ip_address, function () {
  console.log( "Listening on " + server_ip_address + ", port " + server_port )
});

and it works as it is expected in my local machine,

put that on github and deployed it on openshift, pod created and server running fine:

 but when I browse the route which I could find it in Application>>routes menu it says:

Application is not available

The application is currently not serving requests at this endpoint. It may not have been started or is still starting.
I guess I'm using the latest version of openshift since just created an account.

I'm expecting it to show me the Hello world!

update1:

here is my package.json:

{
  "name": "npmtest",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "node index.js"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "express": "^4.16.2"
  }
}


问:
Number of largest element exchanges for quicksort
I'm improving my algorithms knowledge reading Robert Sedgewick "Algorithms" book and completing exercises. There's the one I have difficulties with:

What is the maximum number of times during the execution of Quick.sort()
  that the largest item can be exchanged, for an array of length N ?

I have determined experimentally, that the maximum number of exchanges of the largest item is floor(N/2), assuming all elements in array are distinct. How do I prove this mathematically? If I'm wrong, what's my mistake?

I have found several mentions of this question (such as this one), however, the answers do not match my results. That answers suggest the maximum number is N-1, but I wasn't able to find such an array, that will give me exactly N-1 exchanges of its largest item, when sorting it with my quicksort version (see below).

The code of quicksort that I use:

```<code>template<typename BiDirIterator, typename Compare = std::less<typename BiDirIterator::value_type>>
BiDirIterator partition(BiDirIterator begin, BiDirIterator end, Compare compare = Compare())
{
    auto partition_item = begin;
    while (true)
    {
        while (++begin != end && !compare(*partition_item, *begin));
        while (begin != end && !compare(*--end, *partition_item));

        if (begin == end)
            break;

        std::iter_swap(begin, end);
    }

    if (partition_item != --begin)
        std::iter_swap(partition_item, begin);

    return begin;
}

template<typename BiDirIterator, typename Compare = std::less<typename BiDirIterator::value_type>>
void quicksort(BiDirIterator begin, BiDirIterator end, Compare compare = Compare())
{
    if (begin == end || std::next(begin) == end)
        return;

    auto pos = partition(begin, end, compare);
    quicksort(begin, pos, compare);
    quicksort(++pos, end, compare);
}
</code>```

And the code that I used to calculate the number of exchanges for the lasgest item:

```<code>struct exchange_counter
{
    exchange_counter(int value)
        : value(value)
    {
    }

    int value;
    int number_of_exchanges = 0;

    exchange_counter(const exchange_counter& other) = default;
    exchange_counter& operator=(const exchange_counter& other) = default;
    exchange_counter(exchange_counter&& other) = default;

    exchange_counter& operator=(exchange_counter&& other)
    {
        value = other.value;
        number_of_exchanges = other.number_of_exchanges + 1;
        return *this;
    }

    friend bool operator<(const exchange_counter& left, const exchange_counter& right) noexcept
    {
        return left.value < right.value;
    }

    friend bool operator==(const exchange_counter& left, const exchange_counter& right) noexcept
    {
        return left.value == right.value;
    }
};

for (int i = 1; i != 15; ++i)
{
    std::vector<exchange_counter> values;
    for (int j = 0; j != i; ++j)
        values.emplace_back(j);

    auto max_element = i - 1;
    auto max_number_of_exchanges = 0;
    do
    {
        for (auto& value : values)
            value.number_of_exchanges = 0;

        auto copy = values;
        quicksort(copy.begin(), copy.end());
        max_number_of_exchanges = (std::max)(max_number_of_exchanges,
            std::find(copy.begin(), copy.end(), max_element)->number_of_exchanges);
    }
    while (std::next_permutation(values.begin(), values.end()));

    std::cout << "Elements: " << i << "; max exchanges: " << max_number_of_exchanges << std::endl;
}
</code>```

PS. If I test std::sort in Visual Studio 2015 (which is implemented as quicksort) using the same method, the number of exchanges of the largest item is N - 1.

答:
The largest item must be moved by 2 positions each time we partition the array in order to exchange it the maximum number of times. It cannot be moved by just 1 position, because in this case it will become a pivot element and will be moved to its final position. For example, consider the following array:

```<code>4 10 3 x x x ...
P i  j
</code>```

After partitioning the array the largest element (10) is moved by 1 position to the right

```<code>3 4 10 x x x ...
    P
</code>```

But now the largest item becomes a pivot element and will be moved to the end of the array, adding only 1 exchange.

Instead, we need to arrange the items so that the largest item is moved by 2 positions keeping 1 item in front to become a pivot element:

```<code>2 10 4 1 x x x ...
P i    j
</code>```

After partitioning:

```<code>1 2 4 10 x x x ...
    P i    j
</code>```

The largest item is moved every time by 2 positions, therefore the number of exchanges is floor(N/2).

Example (N = 10)

```<code>2 10 4 1 6 3 8 5 7 9
</code>```

The maximum number of times that the largest item (10) is exchanged is 5 in this case.

Body:
I'm improving my algorithms knowledge reading Robert Sedgewick "Algorithms" book and completing exercises. There's the one I have difficulties with:

What is the maximum number of times during the execution of Quick.sort()
  that the largest item can be exchanged, for an array of length N ?

I have determined experimentally, that the maximum number of exchanges of the largest item is floor(N/2), assuming all elements in array are distinct. How do I prove this mathematically? If I'm wrong, what's my mistake?

I have found several mentions of this question (such as this one), however, the answers do not match my results. That answers suggest the maximum number is N-1, but I wasn't able to find such an array, that will give me exactly N-1 exchanges of its largest item, when sorting it with my quicksort version (see below).

The code of quicksort that I use:

template<typename BiDirIterator, typename Compare = std::less<typename BiDirIterator::value_type>>
BiDirIterator partition(BiDirIterator begin, BiDirIterator end, Compare compare = Compare())
{
    auto partition_item = begin;
    while (true)
    {
        while (++begin != end && !compare(*partition_item, *begin));
        while (begin != end && !compare(*--end, *partition_item));

        if (begin == end)
            break;

        std::iter_swap(begin, end);
    }

    if (partition_item != --begin)
        std::iter_swap(partition_item, begin);

    return begin;
}

template<typename BiDirIterator, typename Compare = std::less<typename BiDirIterator::value_type>>
void quicksort(BiDirIterator begin, BiDirIterator end, Compare compare = Compare())
{
    if (begin == end || std::next(begin) == end)
        return;

    auto pos = partition(begin, end, compare);
    quicksort(begin, pos, compare);
    quicksort(++pos, end, compare);
}

And the code that I used to calculate the number of exchanges for the lasgest item:

struct exchange_counter
{
    exchange_counter(int value)
        : value(value)
    {
    }

    int value;
    int number_of_exchanges = 0;

    exchange_counter(const exchange_counter& other) = default;
    exchange_counter& operator=(const exchange_counter& other) = default;
    exchange_counter(exchange_counter&& other) = default;

    exchange_counter& operator=(exchange_counter&& other)
    {
        value = other.value;
        number_of_exchanges = other.number_of_exchanges + 1;
        return *this;
    }

    friend bool operator<(const exchange_counter& left, const exchange_counter& right) noexcept
    {
        return left.value < right.value;
    }

    friend bool operator==(const exchange_counter& left, const exchange_counter& right) noexcept
    {
        return left.value == right.value;
    }
};

for (int i = 1; i != 15; ++i)
{
    std::vector<exchange_counter> values;
    for (int j = 0; j != i; ++j)
        values.emplace_back(j);

    auto max_element = i - 1;
    auto max_number_of_exchanges = 0;
    do
    {
        for (auto& value : values)
            value.number_of_exchanges = 0;

        auto copy = values;
        quicksort(copy.begin(), copy.end());
        max_number_of_exchanges = (std::max)(max_number_of_exchanges,
            std::find(copy.begin(), copy.end(), max_element)->number_of_exchanges);
    }
    while (std::next_permutation(values.begin(), values.end()));

    std::cout << "Elements: " << i << "; max exchanges: " << max_number_of_exchanges << std::endl;
}

PS. If I test std::sort in Visual Studio 2015 (which is implemented as quicksort) using the same method, the number of exchanges of the largest item is N - 1.

Body:
The largest item must be moved by 2 positions each time we partition the array in order to exchange it the maximum number of times. It cannot be moved by just 1 position, because in this case it will become a pivot element and will be moved to its final position. For example, consider the following array:

4 10 3 x x x ...
P i  j

After partitioning the array the largest element (10) is moved by 1 position to the right

3 4 10 x x x ...
    P

But now the largest item becomes a pivot element and will be moved to the end of the array, adding only 1 exchange.

Instead, we need to arrange the items so that the largest item is moved by 2 positions keeping 1 item in front to become a pivot element:

2 10 4 1 x x x ...
P i    j

After partitioning:

1 2 4 10 x x x ...
    P i    j

The largest item is moved every time by 2 positions, therefore the number of exchanges is floor(N/2).

Example (N = 10)

2 10 4 1 6 3 8 5 7 9

The maximum number of times that the largest item (10) is exchanged is 5 in this case.


问:
Error with timezone into Google Forms with Apps Script
I have a Google Forms with a date information like this:

enter image description here

This information I store into Google Spreadsheet along Google Apps Script; however in this spreadsheet, it doesn't store right date, it stores other date.

enter image description here

I use this Javascript code:

```<code> var response = '2017-12-07 08:00'; //Value from Google Form
 var fecha_inicial = Utilities.formatString(response);
 fecha_inicial_Date = new Date(fecha_inicial.substr(0, 10) + "T" +
   fecha_inicial.substr(11, fecha_inicial.length)); //Thu Dec 07 2017 08:00:00 GMT-0500 (EST)
</code>```

This form is executed in a gmail account in Spain.

答:
I'm guessing the question here is, how do I make the form date and the sheet date the same?

In the google sheet have you tried changing the format of the date column? Select the whole column and in the menu click Format -> Number and then choose the format you want.

If you want to manipulate the timestamp in the App script I recommend using the moment library - Mlj57Yi463PVmHumHxq4bkaUlUqvRc4KT then add this code to use it:

```<code>  var moment = Moment.moment
</code>```

Body:
I have a Google Forms with a date information like this:

enter image description here

This information I store into Google Spreadsheet along Google Apps Script; however in this spreadsheet, it doesn't store right date, it stores other date.

enter image description here

I use this Javascript code:

 var response = '2017-12-07 08:00'; //Value from Google Form
 var fecha_inicial = Utilities.formatString(response);
 fecha_inicial_Date = new Date(fecha_inicial.substr(0, 10) + "T" +
   fecha_inicial.substr(11, fecha_inicial.length)); //Thu Dec 07 2017 08:00:00 GMT-0500 (EST)

This form is executed in a gmail account in Spain.

Body:
I'm guessing the question here is, how do I make the form date and the sheet date the same?

In the google sheet have you tried changing the format of the date column? Select the whole column and in the menu click Format -> Number and then choose the format you want.

If you want to manipulate the timestamp in the App script I recommend using the moment library - Mlj57Yi463PVmHumHxq4bkaUlUqvRc4KT then add this code to use it:

  var moment = Moment.moment


问:
Posts are not refreshing when removing one from the database
I'm making a simple blog using a MEAN stack, and I'm running into a simple issue.

Here's the HTML portion I'm using to retrieve all my posts:

index.html:

```<code><div ng-repeat="post in posts">
  <h2>
    {{post.title}}
    <a ng-click="deletePost(post._id)"class="pull-right"><i class="fa fa-times" aria-hidden="true"></i></a>
  </h2>
  <em>{{post.posted}}</em>
  <p>{{post.body}}</p>
</div>
</code>```

Note that:  is an icon taken from the FontAwesome library

Here's my controller for the angular app:

```<code>(function () {
  angular
    .module("BlogApp", [])
    .controller("BlogController", BlogController);

    function BlogController($scope, $http) {
      $scope.createPost = createPost;
      $scope.deletePost = deletePost;

      function init() {
        getAllPosts();
      }
      init();

      function deletePost(postId) {
        $http.delete('/api/blogpost/' + postId).then(getAllPosts);
      }
      function getAllPosts() {
        $http.get("/api/blogpost").then(function(posts){
        $scope.posts = posts.data
    });
  }
</code>```

And here's the portion of my server handling the delete request:

```<code>// deletePost
app.delete('/api/blogpost/:id', deletePost);

function deletePost(req, res) {
  var postId = req.params.id;
  PostModel.remove({_id: postId}).then(
    function() {
      res.sendstatus(200);
    },
    function() {
      res.sendStatus(400);
    }
  );
}
</code>```

When clicking on X icon, the action does hit my controller, reaches the server and manages to delete the post from my database but for some reason, it doesn't update the page automatically with all my posts. I have to refresh it. That's why I thought invoking the function getAllPosts in the controller right after hitting the server would update the data. What am I missing?

答:
I ended up re-writing the mongoose promise after removing the specific post and it worked.

```<code>// deletePost
function deletePost(req, res) {
  var postId = req.params.id;
  PostModel.remove({ _id: postId}).then(function(err){
    if (err) { console.log(err); }
    res.send('Post deleted');
  });
}
</code>```

This also seems to work:

```<code>function deletePost(req, res) {
  var postId = req.params.id;
  PostModel.remove({ _id: postId}).then(
    function(status) {
      res.sendStatus(200)
    }, function() {
      res.send(400);
    }
  );
}
</code>```

Still a bit confused as to how to work with the mongoose promises...

Body:
I'm making a simple blog using a MEAN stack, and I'm running into a simple issue.

Here's the HTML portion I'm using to retrieve all my posts:

index.html:

    {{post.title}}

  {{post.posted}}

{{post.body}}

Note that:  is an icon taken from the FontAwesome library

Here's my controller for the angular app:

(function () {
  angular
    .module("BlogApp", [])
    .controller("BlogController", BlogController);

    function BlogController($scope, $http) {
      $scope.createPost = createPost;
      $scope.deletePost = deletePost;

      function init() {
        getAllPosts();
      }
      init();

      function deletePost(postId) {
        $http.delete('/api/blogpost/' + postId).then(getAllPosts);
      }
      function getAllPosts() {
        $http.get("/api/blogpost").then(function(posts){
        $scope.posts = posts.data
    });
  }

And here's the portion of my server handling the delete request:

// deletePost
app.delete('/api/blogpost/:id', deletePost);

function deletePost(req, res) {
  var postId = req.params.id;
  PostModel.remove({_id: postId}).then(
    function() {
      res.sendstatus(200);
    },
    function() {
      res.sendStatus(400);
    }
  );
}

When clicking on X icon, the action does hit my controller, reaches the server and manages to delete the post from my database but for some reason, it doesn't update the page automatically with all my posts. I have to refresh it. That's why I thought invoking the function getAllPosts in the controller right after hitting the server would update the data. What am I missing?

Body:
I ended up re-writing the mongoose promise after removing the specific post and it worked.

// deletePost
function deletePost(req, res) {
  var postId = req.params.id;
  PostModel.remove({ _id: postId}).then(function(err){
    if (err) { console.log(err); }
    res.send('Post deleted');
  });
}

This also seems to work:

function deletePost(req, res) {
  var postId = req.params.id;
  PostModel.remove({ _id: postId}).then(
    function(status) {
      res.sendStatus(200)
    }, function() {
      res.send(400);
    }
  );
}

Still a bit confused as to how to work with the mongoose promises...


问:
How to attach pTooltip to p-slider's handle (prime-ng angular components)
I'm using prime-ng components library in my Angular application.
I use p-slider component:

```<code><p-slider id="slider" [(ngModel)]="rankItem.itemSliderNumber" class="slider" [step]="sliderStep" [min]="0" [max]="rankItem.itemSliderMaxValue"></p-slider>
</code>```

And I want to add tooltip to the p-slider handle (to be sticked and displayed above the handle). When I add [pTootip] directive to the p-slider component, tooltip displays over the slider, not the handle.

```<code><p-slider id="slider" [(ngModel)]="rankItem.itemSliderNumber" class="slider" [step]="sliderStep" [min]="0" [max]="rankItem.itemSliderMaxValue" [pTooltip]="rankItem.itemSliderNumber"></p-slider>
</code>```

How to stick the tooltip to the slider's handle?

答:
After some investigation, I can confirm that there is no simple solution. Finally I extended the ng-prime tooltip directive:

```<code>import {AfterViewInit, Directive, ElementRef, Input, Renderer2} from '@angular/core';
import {DomHandler, Tooltip} from "primeng/primeng";

@Directive({
    selector: '[ext-tooltip]'
})

export class ExtendedTooltipDirective extends Tooltip implements AfterViewInit {

    @Input('ext-tooltip')
    _text: any;

    @Input('stickTo')
    stickTo: string;

    constructor(el: ElementRef, domHandler: DomHandler, renderer: Renderer2) {
        super(el, domHandler, renderer);
    }

    ngAfterViewInit(): void {
        this.el = new ElementRef(this.el.nativeElement.querySelector(this.stickTo));
    }
}
</code>```

This directive can be used as the tooltip directive, but it has additional propery stickTo, where possible to use query to get element inside component, to which the tooltip should be attached. For p-slider we can use hanler's class ".ui-slider-handle".

```<code><p-slider [ext-tooltip]="rankItem.itemSliderNumber" stickTo=".ui-slider-handle" tooltipPosition="top" [(ngModel)]="rankItem.itemSliderNumber" class="slider" [step]="sliderStep" [min]="0" [max]="rankItem.itemSliderMaxValue" ></p-slider>
</code>```

All original properties of the prime-ng tooltip can also be used.

Body:
I'm using prime-ng components library in my Angular application.
I use p-slider component:

And I want to add tooltip to the p-slider handle (to be sticked and displayed above the handle). When I add [pTootip] directive to the p-slider component, tooltip displays over the slider, not the handle.

How to stick the tooltip to the slider's handle?

Body:
After some investigation, I can confirm that there is no simple solution. Finally I extended the ng-prime tooltip directive:

import {AfterViewInit, Directive, ElementRef, Input, Renderer2} from '@angular/core';
import {DomHandler, Tooltip} from "primeng/primeng";

@Directive({
    selector: '[ext-tooltip]'
})

export class ExtendedTooltipDirective extends Tooltip implements AfterViewInit {

    @Input('ext-tooltip')
    _text: any;

    @Input('stickTo')
    stickTo: string;

    constructor(el: ElementRef, domHandler: DomHandler, renderer: Renderer2) {
        super(el, domHandler, renderer);
    }

    ngAfterViewInit(): void {
        this.el = new ElementRef(this.el.nativeElement.querySelector(this.stickTo));
    }
}

This directive can be used as the tooltip directive, but it has additional propery stickTo, where possible to use query to get element inside component, to which the tooltip should be attached. For p-slider we can use hanler's class ".ui-slider-handle".

<p-slider [ext-tooltip]="rankItem.itemSliderNumber" stickTo=".ui-slider-handle" tooltipPosition="top" [(ngModel)]="rankItem.itemSliderNumber" class="slider" [step]="sliderStep" [min]="0" [max]="rankItem.itemSliderMaxValue" ></p-slider>

All original properties of the prime-ng tooltip can also be used.


问:
Chart.js y axis labels are truncated
I have a bootstrap modal where I have a chart.js in it.

The problem is that left Y axis values are truncated.

This is the HTML in the inspector:

```<code>  <div class="modal-dialog modal-center">
            <div class="modal-content">
                <div class="modal-header" style="background-color:#62a8ea;">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">×</span>
                    </button>
                    <h4 class="modal-title" style="color:white;">Reading Details</h4>
                </div>
                <div class="modal-body" style="height: 400px;"><div><div class="chartjs-size-monitor" style="position: absolute; left: 0px; top: 0px; right: 0px; bottom: 0px; overflow: hidden; pointer-events: none; visibility: hidden; z-index: -1;"><div class="chartjs-size-monitor-expand" style="position:absolute;left:0;top:0;right:0;bottom:0;overflow:hidden;pointer-events:none;visibility:hidden;z-index:-1;"><div style="position:absolute;width:1000000px;height:1000000px;left:0;top:0"></div></div><div class="chartjs-size-monitor-shrink" style="position:absolute;left:0;top:0;right:0;bottom:0;overflow:hidden;pointer-events:none;visibility:hidden;z-index:-1;"><div style="position:absolute;width:200%;height:200%;left:0; top:0"></div></div></div>
    <canvas id="detail-chart" width="560" height="280" class="chartjs-render-monitor" style="display: block; width: 560px; height: 280px;"></canvas>
</div>
</div>
                <div class="modal-footer">

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

Any clue?

答:
Just add the following:

```<code>options: {
                                layout: {
                                    padding: {
                                        // Any unspecified dimensions are assumed to be 0
                                        left: 10,
                                        bottom: 5
                                    }
                                },
</code>```

That will fix the problem.

Title: Chart.js y axis labels are truncated

Body:
I have a bootstrap modal where I have a chart.js in it.

The problem is that left Y axis values are truncated.

This is the HTML in the inspector:

                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        ×
                    </button>

Reading Details

    <canvas id="detail-chart" width="560" height="280" class="chartjs-render-monitor" style="display: block; width: 560px; height: 280px;"></canvas>

Any clue?

Body:
Just add the following:

options: {
                                layout: {
                                    padding: {
                                        // Any unspecified dimensions are assumed to be 0
                                        left: 10,
                                        bottom: 5
                                    }
                                },

That will fix the problem.


问:
how to have multiple $http call inside of a ng-repeat
i tried to retrieve two data, one from the API and from my json, when i make the call i receive just the second call on my view.

json 1

```<code>[
    {
        "id": 1,
        "img":"images/clientlogos/21747.jpg"
    },
    {
        "id": 2,
        "img": "images/clientlogos/FMI.png"
        }
]
</code>```

jason @ from APi call

```<code>[
    {
        "id": 1,
        "name": "Enough",
        "forecasted": 22,
        "budget": 40,
        "hoursspent": 3.53999997675419,
        "currentcosts": 965.393393660635,
        "xerototal": 2800
    },
    {
        "id": 2,
        "name": "Fad Ltd",
        "forecasted": 96.5,
        "budget": 300,
        "hoursspent": 199.91000029631,
        "currentcosts": 66234.589716303,
        "xerototal": 176472
    },
]
</code>```

my factory

```<code>app.factory('myFactory', function($http){
  return{
client: function(callback){
        $http({
          method: "GET",
          url: "http://www.outleading.co.za/api/api/clientdashboarddata",
          cache:true
        }).then(callback);
    },
list: function(callback){
        $http({
          method: "GET",
          url: "data/Client.json",
          cache:true
        }).then(callback);
    }
  };
});
</code>```

my controller

```<code>    app.controller('myController', function ($scope, $http, myFactory) {
      myFactory.client(function (response) {
        var data = response.data;
        $scope.myClients = data;
      })
      myFactory.list(function(response){
        var data= response.data;
        $scope.myClients= data;
      })
        };
      }
    })
</code>```

my html

inside my ng-repeat i want to get{{client.img}} from my json and {{client.clientname}} from the api call

```<code><div class="card client-card" ng-repeat="client in myClients>
                <div class="client-logo">
                     <img ng-src="{{client.img}}" alt="{{client.name}}">
                </div>
        </div>
</code>```

so Any help will be much appreaciated.

答:
You are calling two APIs and overriding the input.

```<code>app.controller('myController', function ($scope, $http, myFactory) {
      myFactory.client(function (response) {
        var data = response.data;
        $scope.myClients = data;  //Same variable
      })
      myFactory.list(function(response){
        var data= response.data;
        $scope.myClients= data; //Same variable
      })
        };
      }
    })
</code>```

Instead of saving data in $scope.myClients in both the calls, use some different variable name. I guess second one should be $scope.lists

Body:
i tried to retrieve two data, one from the API and from my json, when i make the call i receive just the second call on my view.

json 1

[
    {
        "id": 1,
        "img":"images/clientlogos/21747.jpg"
    },
    {
        "id": 2,
        "img": "images/clientlogos/FMI.png"
        }
]

jason @ from APi call

[
    {
        "id": 1,
        "name": "Enough",
        "forecasted": 22,
        "budget": 40,
        "hoursspent": 3.53999997675419,
        "currentcosts": 965.393393660635,
        "xerototal": 2800
    },
    {
        "id": 2,
        "name": "Fad Ltd",
        "forecasted": 96.5,
        "budget": 300,
        "hoursspent": 199.91000029631,
        "currentcosts": 66234.589716303,
        "xerototal": 176472
    },
]

my factory

app.factory('myFactory', function($http){
  return{
client: function(callback){
        $http({
          method: "GET",
          url: "http://www.outleading.co.za/api/api/clientdashboarddata",
          cache:true
        }).then(callback);
    },
list: function(callback){
        $http({
          method: "GET",
          url: "data/Client.json",
          cache:true
        }).then(callback);
    }
  };
});

my controller

    app.controller('myController', function ($scope, $http, myFactory) {
      myFactory.client(function (response) {
        var data = response.data;
        $scope.myClients = data;
      })
      myFactory.list(function(response){
        var data= response.data;
        $scope.myClients= data;
      })
        };
      }
    })

my html

inside my ng-repeat i want to get{{client.img}} from my json and {{client.clientname}} from the api call

so Any help will be much appreaciated.

Body:
You are calling two APIs and overriding the input.

app.controller('myController', function ($scope, $http, myFactory) {
      myFactory.client(function (response) {
        var data = response.data;
        $scope.myClients = data;  //Same variable
      })
      myFactory.list(function(response){
        var data= response.data;
        $scope.myClients= data; //Same variable
      })
        };
      }
    })

Instead of saving data in $scope.myClients in both the calls, use some different variable name. I guess second one should be $scope.lists


问:
Spark DataFrame - Get the average of two column combinations
How I get the average of Price for each combination of 2 columns?

My DataFrame:

```<code>relevantTable = df.select(df['Price'], df['B'], df['A'])
</code>```

looks like:

```<code>+-------+------------+------------------+
|  Price|     B      |          A       |
+-------+------------+------------------+
| 0.2947|   i3.xlarge|                 x|
|  0.105|    c4.large|                 x|
| 0.2179|   m4.xlarge|                 x|
| 2.2534| m4.10xlarge|                 x|
| 2.1801| m4.10xlarge|                 x|
|  0.108|    r4.large|                 x|
|  0.108|    r4.large|                 x|
| 0.0213|    i3.large|                 y|
| 0.5572|  i2.4xlarge|                 y|
| 0.1542|  c4.4xlarge|                 y|
| 0.3624| m4.10xlarge|                 y|
| 0.3596| m4.10xlarge|                 y|
|   0.11|    m4.large|                 x|
| 0.4436|  m4.2xlarge|                 x|
| 0.1458|  m4.2xlarge|                 y|

... and so on real huge set
</code>```

What would be a simple and scalable solution to get the average for all combinations of A and B?

答:
How about:

```<code>df.groupBy("A", "B").avg("Price")
</code>```

or if you want to include aggregates by single column:

```<code>df.cube("A", "B").avg("Price")
</code>```

Body:
How I get the average of Price for each combination of 2 columns?

My DataFrame:

relevantTable = df.select(df['Price'], df['B'], df['A'])

looks like:

+-------+------------+------------------+
|  Price|     B      |          A       |
+-------+------------+------------------+
| 0.2947|   i3.xlarge|                 x|
|  0.105|    c4.large|                 x|
| 0.2179|   m4.xlarge|                 x|
| 2.2534| m4.10xlarge|                 x|
| 2.1801| m4.10xlarge|                 x|
|  0.108|    r4.large|                 x|
|  0.108|    r4.large|                 x|
| 0.0213|    i3.large|                 y|
| 0.5572|  i2.4xlarge|                 y|
| 0.1542|  c4.4xlarge|                 y|
| 0.3624| m4.10xlarge|                 y|
| 0.3596| m4.10xlarge|                 y|
|   0.11|    m4.large|                 x|
| 0.4436|  m4.2xlarge|                 x|
| 0.1458|  m4.2xlarge|                 y|

... and so on real huge set

What would be a simple and scalable solution to get the average for all combinations of A and B?

Body:
How about:

df.groupBy("A", "B").avg("Price")

or if you want to include aggregates by single column:

df.cube("A", "B").avg("Price")


问:
How to remove overflow menu 3-dots?
Please help me understand.  I read somewhere saying that if I set up android:targetSdkVersion="14.
These 3-dots will be gone.

Why these 3-dots still show up on mine?

They don't show up until I come back from another activity. I pressed the menu key after I came back from another activity, they showed up....

I am using actionbar menus so I don't need these ugly 3-dots on my app.

How can I remove them completely?

Thanks

Manifest:

```<code>  <uses-sdk
    android:minSdkVersion="14"
    android:targetSdkVersion="19" />

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/MyAppActionBarTheme" >
</code>```

MainActivity:

```<code>  @Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the actionbar menu; this adds items to the action bar.
    getMenuInflater().inflate(R.menu.actionbar_menu, menu);
    return super.onCreateOptionsMenu(menu);
}
</code>```

答:
I just thought i should share the easiest process of removing the three dots...

go to the menu folder

go to the second dropdown .xml

view the design on the right pane after clicking on the layout you will see a checkbox which says visible check and uncheck it to make it invisible.

then the 3dots is gone

Title: How to remove overflow menu 3-dots?

Body:
Please help me understand.  I read somewhere saying that if I set up android:targetSdkVersion="14.
These 3-dots will be gone.

Why these 3-dots still show up on mine?

They don't show up until I come back from another activity. I pressed the menu key after I came back from another activity, they showed up....

I am using actionbar menus so I don't need these ugly 3-dots on my app.

How can I remove them completely?

Thanks

Manifest:

  <uses-sdk
    android:minSdkVersion="14"
    android:targetSdkVersion="19" />

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/MyAppActionBarTheme" >

MainActivity:

  @Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the actionbar menu; this adds items to the action bar.
    getMenuInflater().inflate(R.menu.actionbar_menu, menu);
    return super.onCreateOptionsMenu(menu);
}


问:
How to join multiple queryDSL tables
I have some tables and I want to get result using queryDSL join, but haven't found any examples on multiple joins using queryDSL.

I have these tables:

Account table: accountId (PK) | email | password

account_profile table: accountId (PK)(fk to account) | nickname

Community table: articleId (PK) | accountId (fk to account) | title | content

Now I want below JPQL to be queryDSL code

```<code>select r from community r join r.account.profile a where a.nickname = :nickname
</code>```

I have entity metamodels - QAccount, QAccountProfile, QCommunity

Additionally, I have to get the result with pagination, so the query should be called with pageable object.

Here is my work that doesn't work yet.

```<code>JPAQuery</*What generic type expected?*/> query = new JPAQuery</*???*/>(entityManager);
Predicate predicate = query.from(QCommunity.community).join(/*join directly accountProfile? or account? is it QEntity or real entity?*/);

// where should I place nickname matching condition ?

...

list = (repository.findAll(predicate, pageable)).getContent();
</code>```

Where should I place the nickname matching condition?

EDIT: Appended entity information

Account.java

```<code>@Entity
@Table(name="account", uniqueConstraints={
    @UniqueConstraint(columnNames="account_seq"),
    @UniqueConstraint(columnNames="email")
})
@DynamicInsert
@DynamicUpdate
@Data
@EqualsAndHashCode
@ToString(includeFieldNames=true)
@RequiredArgsConstructor(staticName="of")
@NoArgsConstructor
public class Account implements Serializable{

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name="account_seq", nullable=false, unique=true)
    private Integer accountId;

    @Column(name="email", nullable=false, unique=true)
    @NonNull
    private String email;

    @NonNull
    private String password;

    @OneToOne(cascade=CascadeType.ALL, mappedBy="account")
    private AccountProfile profile;

    @OneToOne(cascade=CascadeType.ALL, mappedBy="account")
    private AccountSecurity security;
}
</code>```

AccountProfile.java

```<code>@Entity
@Table(name="account_profile", uniqueConstraints={
    @UniqueConstraint(columnNames={"account_seq"}),
    @UniqueConstraint(columnNames={"nickname"})
})
@DynamicInsert
@DynamicUpdate
@Data
@EqualsAndHashCode
@ToString(includeFieldNames=true)
@RequiredArgsConstructor(staticName="of")
@NoArgsConstructor
public class AccountProfile implements Serializable{

    private static final long serialVersionUID = 1L;

    @Id
    @OneToOne(cascade=CascadeType.ALL)
    @JoinColumn(name="account_seq", referencedColumnName="account_seq")
    private Account account;

    @Column(name="nickname", nullable=false)
    @NonNull
    private String nickname;

}
</code>```

Community.java

```<code>@Entity
@Table(name="community", uniqueConstraints = {
        @UniqueConstraint(columnNames="article_seq")
})
@DynamicInsert
@DynamicUpdate
@Data
@NoArgsConstructor
@EqualsAndHashCode
@ToString(includeFieldNames=true)
public class Community {

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name="article_seq", nullable=false, unique=true)
    private Long articleId;

    @ManyToOne(cascade=CascadeType.ALL)
    @JoinColumn(name="account_seq", referencedColumnName="account_seq")
    private Account account;

    @Column(name="title", nullable=false)
    private String title;

    @Column(name="content", nullable=false)
    private String content;

    @Temporal(TemporalType.TIMESTAMP)
    @Column(name="reg_dt")
    private Date date;

    @Column(name="read_cnt", nullable=false)
    private int readCount;

    @Column(name="attach_url")
    private String attachUrl;

    @Column(name="attach_filename")
    private String attachFileName;

    @OneToMany(cascade=CascadeType.ALL, mappedBy="article")
    private Set<CommunityReply> replies;
}
</code>```

EDIT: PROBLEM SOLVED

To help others who is facing the problem like me, I am gonna post my working code. the code is searching any community articles with matching specific nickname.

```<code>@PersistenceContext
    private EntityManager entityManager;

    private List<Community> getList(int pageNo, String keyword, int rowsOnPage){

        int offset = (pageNo -1) * rowsOnPage;
        int limit = rowsOnPage;

        JPAQuery<Community> query = new JPAQuery<Community>(entityManager);

        QCommunity qCommunity = QCommunity.community;
        QAccount qAccount = QAccount.account;
        QAccountProfile qAccountProfile = QAccountProfile.accountProfile;

        return query
            .from(qCommunity)
            .innerJoin(qCommunity.account ,qAccount)
            .innerJoin(qAccount.profile, qAccountProfile)
            .where(qAccountProfile.nickname.like("%"+keyword+"%"))
            .orderBy(qCommunity.articleId.desc())
            .offset(offset)
            .limit(limit)
        .fetch();
    }
</code>```

答:
First of all, declare a custom extended base repository class for QueryDSL queries.

First the interface:

```<code>@NoRepositoryBean
public interface ExtendedQueryDslJpaRepository<T, ID extends Serializable>
        extends JpaRepository<T, ID>, QueryDslPredicateExecutor<T> {

    <T1> Page<T1> findAll(JPQLQuery jpqlQuery, Pageable pageable);
}
</code>```

And then the implementation:

```<code>public class ExtendedQueryDslJpaRepositoryImpl<T, ID extends Serializable>
        extends QueryDslJpaRepository<T, ID> implements ExtendedQueryDslJpaRepository<T, ID> {

    private static final EntityPathResolver DEFAULT_ENTITY_PATH_RESOLVER = SimpleEntityPathResolver.INSTANCE;

    private final EntityPath<T> path;
    private final PathBuilder<T> builder;
    private final Querydsl querydsl;

    private EntityManager entityManager;

    public ExtendedQueryDslJpaRepositoryImpl(JpaEntityInformation<T, ID> entityInformation, EntityManager entityManager) {
        this(entityInformation, entityManager, DEFAULT_ENTITY_PATH_RESOLVER);
    }

    public ExtendedQueryDslJpaRepositoryImpl(JpaEntityInformation<T, ID> entityInformation,
           EntityManager entityManager, EntityPathResolver resolver) {

        super(entityInformation, entityManager);
        this.path = resolver.createPath(entityInformation.getJavaType());
        this.builder = new PathBuilder(this.path.getType(), this.path.getMetadata());
        this.querydsl = new Querydsl(entityManager, this.builder);
        this.entityManager = entityManager;
    }

    @Override
    public <T1> Page<T1> findAll(JPQLQuery jpqlQuery, Pageable pageable) {

        // Count query
        final JPQLQuery<?> countQuery = jpqlQuery;

        // Apply pagination
        JPQLQuery<T1> query = querydsl.applyPagination(pageable, jpqlQuery);

        // Run query
        return PageableExecutionUtils.getPage(query.fetch(), pageable, countQuery::fetchCount);
    }
}
</code>```

Define the new class as base for base and repositories in a @Configuration class.

```<code>@Configuration
@EnableJpaRepositories(basePackageClasses = ..., repositoryBaseClass = ExtendedQueryDslJpaRepositoryImpl.class)
</code>```

Your repositories then should extend from the new interface (which of course extends JpaRepository):

```<code>@Repository
public interface CommunityRepository extends ExtendedQueryDslJpaRepository<Community, Long> {
}
</code>```

Then, you can try the following code:

```<code>String nickname = "nick";

QAccount account = QAccount.account;
QAccountProfile accountProfile = QAccountProfile.accountProfile;
QCommunity community = QCommunity.community;

JPQLQuery query = new JPAQuery(entityManager);

BooleanBuilder predicate = new BooleanBuilder();
predicate.and(accountProfile.nickname.eq(nickname));

// select r from community r join r.account.profile a where a.nickname = :nickname
query.from(community)
     .join(community.account, account)
     .join(account.accountProfile, accountProfile)
     .where(predicate);

repository.findAll(query, pageable);
</code>```

Hope that helps.

Title: How to join multiple queryDSL tables

Body:
I have some tables and I want to get result using queryDSL join, but haven't found any examples on multiple joins using queryDSL.

I have these tables:

Account table: accountId (PK) | email | password

account_profile table: accountId (PK)(fk to account) | nickname

Community table: articleId (PK) | accountId (fk to account) | title | content

Now I want below JPQL to be queryDSL code

select r from community r join r.account.profile a where a.nickname = :nickname

I have entity metamodels - QAccount, QAccountProfile, QCommunity

Additionally, I have to get the result with pagination, so the query should be called with pageable object.

Here is my work that doesn't work yet.

JPAQuery</*What generic type expected?*/> query = new JPAQuery</*???*/>(entityManager);
Predicate predicate = query.from(QCommunity.community).join(/*join directly accountProfile? or account? is it QEntity or real entity?*/);

// where should I place nickname matching condition ?

...

list = (repository.findAll(predicate, pageable)).getContent();

Where should I place the nickname matching condition?

EDIT: Appended entity information

Account.java

@Entity
@Table(name="account", uniqueConstraints={
    @UniqueConstraint(columnNames="account_seq"),
    @UniqueConstraint(columnNames="email")
})
@DynamicInsert
@DynamicUpdate
@Data
@EqualsAndHashCode
@ToString(includeFieldNames=true)
@RequiredArgsConstructor(staticName="of")
@NoArgsConstructor
public class Account implements Serializable{

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name="account_seq", nullable=false, unique=true)
    private Integer accountId;

    @Column(name="email", nullable=false, unique=true)
    @NonNull
    private String email;

    @NonNull
    private String password;

    @OneToOne(cascade=CascadeType.ALL, mappedBy="account")
    private AccountProfile profile;

    @OneToOne(cascade=CascadeType.ALL, mappedBy="account")
    private AccountSecurity security;
}

AccountProfile.java

@Entity
@Table(name="account_profile", uniqueConstraints={
    @UniqueConstraint(columnNames={"account_seq"}),
    @UniqueConstraint(columnNames={"nickname"})
})
@DynamicInsert
@DynamicUpdate
@Data
@EqualsAndHashCode
@ToString(includeFieldNames=true)
@RequiredArgsConstructor(staticName="of")
@NoArgsConstructor
public class AccountProfile implements Serializable{

    private static final long serialVersionUID = 1L;

    @Id
    @OneToOne(cascade=CascadeType.ALL)
    @JoinColumn(name="account_seq", referencedColumnName="account_seq")
    private Account account;

    @Column(name="nickname", nullable=false)
    @NonNull
    private String nickname;

}

Community.java

@Entity
@Table(name="community", uniqueConstraints = {
        @UniqueConstraint(columnNames="article_seq")
})
@DynamicInsert
@DynamicUpdate
@Data
@NoArgsConstructor
@EqualsAndHashCode
@ToString(includeFieldNames=true)
public class Community {

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name="article_seq", nullable=false, unique=true)
    private Long articleId;

    @ManyToOne(cascade=CascadeType.ALL)
    @JoinColumn(name="account_seq", referencedColumnName="account_seq")
    private Account account;

    @Column(name="title", nullable=false)
    private String title;

    @Column(name="content", nullable=false)
    private String content;

    @Temporal(TemporalType.TIMESTAMP)
    @Column(name="reg_dt")
    private Date date;

    @Column(name="read_cnt", nullable=false)
    private int readCount;

    @Column(name="attach_url")
    private String attachUrl;

    @Column(name="attach_filename")
    private String attachFileName;

    @OneToMany(cascade=CascadeType.ALL, mappedBy="article")
    private Set<CommunityReply> replies;
}

EDIT: PROBLEM SOLVED

To help others who is facing the problem like me, I am gonna post my working code. the code is searching any community articles with matching specific nickname.

@PersistenceContext
    private EntityManager entityManager;

    private List<Community> getList(int pageNo, String keyword, int rowsOnPage){

        int offset = (pageNo -1) * rowsOnPage;
        int limit = rowsOnPage;

        JPAQuery<Community> query = new JPAQuery<Community>(entityManager);

        QCommunity qCommunity = QCommunity.community;
        QAccount qAccount = QAccount.account;
        QAccountProfile qAccountProfile = QAccountProfile.accountProfile;

        return query
            .from(qCommunity)
            .innerJoin(qCommunity.account ,qAccount)
            .innerJoin(qAccount.profile, qAccountProfile)
            .where(qAccountProfile.nickname.like("%"+keyword+"%"))
            .orderBy(qCommunity.articleId.desc())
            .offset(offset)
            .limit(limit)
        .fetch();
    }

Body:
First of all, declare a custom extended base repository class for QueryDSL queries.

First the interface:

@NoRepositoryBean
public interface ExtendedQueryDslJpaRepository<T, ID extends Serializable>
        extends JpaRepository<T, ID>, QueryDslPredicateExecutor<T> {

    <T1> Page<T1> findAll(JPQLQuery jpqlQuery, Pageable pageable);
}

And then the implementation:

public class ExtendedQueryDslJpaRepositoryImpl<T, ID extends Serializable>
        extends QueryDslJpaRepository<T, ID> implements ExtendedQueryDslJpaRepository<T, ID> {

    private static final EntityPathResolver DEFAULT_ENTITY_PATH_RESOLVER = SimpleEntityPathResolver.INSTANCE;

    private final EntityPath<T> path;
    private final PathBuilder<T> builder;
    private final Querydsl querydsl;

    private EntityManager entityManager;

    public ExtendedQueryDslJpaRepositoryImpl(JpaEntityInformation<T, ID> entityInformation, EntityManager entityManager) {
        this(entityInformation, entityManager, DEFAULT_ENTITY_PATH_RESOLVER);
    }

    public ExtendedQueryDslJpaRepositoryImpl(JpaEntityInformation<T, ID> entityInformation,
           EntityManager entityManager, EntityPathResolver resolver) {

        super(entityInformation, entityManager);
        this.path = resolver.createPath(entityInformation.getJavaType());
        this.builder = new PathBuilder(this.path.getType(), this.path.getMetadata());
        this.querydsl = new Querydsl(entityManager, this.builder);
        this.entityManager = entityManager;
    }

    @Override
    public <T1> Page<T1> findAll(JPQLQuery jpqlQuery, Pageable pageable) {

        // Count query
        final JPQLQuery<?> countQuery = jpqlQuery;

        // Apply pagination
        JPQLQuery<T1> query = querydsl.applyPagination(pageable, jpqlQuery);

        // Run query
        return PageableExecutionUtils.getPage(query.fetch(), pageable, countQuery::fetchCount);
    }
}

Define the new class as base for base and repositories in a @Configuration class.

@Configuration
@EnableJpaRepositories(basePackageClasses = ..., repositoryBaseClass = ExtendedQueryDslJpaRepositoryImpl.class)

Your repositories then should extend from the new interface (which of course extends JpaRepository):

@Repository
public interface CommunityRepository extends ExtendedQueryDslJpaRepository<Community, Long> {
}

Then, you can try the following code:

String nickname = "nick";

QAccount account = QAccount.account;
QAccountProfile accountProfile = QAccountProfile.accountProfile;
QCommunity community = QCommunity.community;

JPQLQuery query = new JPAQuery(entityManager);

BooleanBuilder predicate = new BooleanBuilder();
predicate.and(accountProfile.nickname.eq(nickname));

// select r from community r join r.account.profile a where a.nickname = :nickname
query.from(community)
     .join(community.account, account)
     .join(account.accountProfile, accountProfile)
     .where(predicate);

repository.findAll(query, pageable);

Hope that helps.


问:
Prevent users from submitting a form by hitting Enter
I have a survey on a website, and there seems to be some issues with the users hitting enter (I don't know why) and accidentally submitting the survey (form) without clicking the submit button. Is there a way to prevent this?

I'm using HTML, PHP 5.2.9, and jQuery on the survey.

答:
ONLY BLOCK SUBMIT but not other, important functionality of enter key, such as creating a new paragraph in a <textarea>:

window.addEventListener('keydown', function(event) {
  //set default value for variable that will hold the status of keypress
  pressedEnter = false;

  //if user pressed enter, set the variable to true
  if (event.keyCode == 13)
    pressedEnter = true;

  //we want forms to disable submit for a tenth of a second only
  setTimeout(function() {
    pressedEnter = false;
  }, 100)

})

//find all forms
var forms = document.getElementsByTagName('form')

//loop through forms
for (i = 0; i < forms.length; i++) {
  //listen to submit event
  forms[i].addEventListener('submit', function(e) {
    //if user just pressed enter, stop the submit event
    if (pressedEnter == true) {
      updateLog('Form prevented from submit.')
      e.preventDefault();
      return false;
    }

    updateLog('Form submitted.')
  })
}

var log = document.getElementById('log')
updateLog = function(msg) {
  log.innerText = msg
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>input,
textarea {
  display: inline-block;
  margin-bottom: 1em;
  border: 1px solid #6f6f6f;
  padding: 5px;
  border-radius: 2px;
  width: 90%;
  font-size: 14px;
}

input[type=submit] {
  background: lightblue;
  color: #fff;
}</code>```

<form>

Sample textarea (try enter key):

  <textarea rows="4">Hit enter, a new line will be added. But the form won't submit</textarea>

Sample textfield (try enter key):

  <input type="text" placeholder="" />

  <input type="submit" value="Save" />

</form>```

Body:
ONLY BLOCK SUBMIT but not other, important functionality of enter key, such as creating a new paragraph in a <textarea>:

window.addEventListener('keydown', function(event) {
  //set default value for variable that will hold the status of keypress
  pressedEnter = false;

  //if user pressed enter, set the variable to true
  if (event.keyCode == 13)
    pressedEnter = true;

  //we want forms to disable submit for a tenth of a second only
  setTimeout(function() {
    pressedEnter = false;
  }, 100)

})

//find all forms
var forms = document.getElementsByTagName('form')

//loop through forms
for (i = 0; i < forms.length; i++) {
  //listen to submit event
  forms[i].addEventListener('submit', function(e) {
    //if user just pressed enter, stop the submit event
    if (pressedEnter == true) {
      updateLog('Form prevented from submit.')
      e.preventDefault();
      return false;
    }

    updateLog('Form submitted.')
  })
}

var log = document.getElementById('log')
updateLog = function(msg) {
  log.innerText = msg
}

input,
textarea {
  display: inline-block;
  margin-bottom: 1em;
  border: 1px solid #6f6f6f;
  padding: 5px;
  border-radius: 2px;
  width: 90%;
  font-size: 14px;
}

input[type=submit] {
  background: lightblue;
  color: #fff;
}

<form>
  <p>Sample textarea (try enter key):</p>
  <textarea rows="4">Hit enter, a new line will be added. But the form won't submit</textarea><br/>
  <p>Sample textfield (try enter key):</p>
  <input type="text" placeholder="" />
  <br/>
  <input type="submit" value="Save" />
  <h3 id="log"></h3>
</form>


问:
progressive web app OCR SDK (JavaScript)
We have developed a web-application which uses OCR technology. We use a paid API-service for that which works pretty well.
Our backend/server uses a Ruby/Rails based API and our frontend/client uses VUE.js.
Now the OCR tech was server side but we want to grow into the offline/PWA (progressive web app) market as well and are currently developing an offline-version of our app. Since the OCR-part of our app has to run in the client, we'd move the OCR tech also client side which means we have to use some sort of PWA compatible OCR tech, e.g. a JavaScript SDK

I have probably searched the whole internet but there does not really seem to be a solution. It all came down to two major providers:

tesseract / the probably biggest OCR project (open source). They offer a JS SDK (tesseract.js) -> http://tesseract.projectnaptha.com/ but this works pretty bad. We have compared results to the API that we're using and the results are terrible. Hence, we cannot use it.

ABBYY which is probably the most well known OCR provider in the web and they offer OCR scanning for reasonable prices. After calling them they unfortunately also do not provide any solution for PWAs, only for native apps

multiple other small projects which use everything except JS libraries unfortunately

Before giving up and consider developing a native app (which will be quote cost intensive for us) I considered to ask here if any known OCR solution for PWAs is known which I did not consider yet. Thx

答:
No JavaScript solution, but you could try Scandit. It works offline on next to all platforms and can be web integrated using Cordova. https://www.scandit.com/tag/ocr/. Or use the newest web platform https://www.scandit.com/scandit-launches-barcode-scanner-sdk-for-web-brings-scanning-to-the-browser/

Try it here:
https://websdk.scandit.com/


问:
notepad++ complicated regular expression
I have a huge HTML file and I'd like to delete all the parts starting with [sound: and ending with

Here is a sample of my document:

```<code><div class=Answer>
        <div style='font-family: Arial; font-size: 50px;'>你好</div>
        <br />nĭ hăo<br />[sound:pronunciation_zh_你好.mp3]
        <a href='javascript:py.link("ankiplaypronunciation_zh_你好.mp3");' title="pronunciation_zh_你好.mp3" class="replaybutton browserhide">
           <span>
              <svg viewBox="0 0 32 32">
                 <polygon points="11,25 25,16 11,7"/>
                 Replay
              </svg>
           </span>
        </a>
        <span style="display: none;">[sound:pronunciation_zh_你好.mp3]</span><br />
        <div style='color: DarkSlateGray; font-size: 25px;' ></div>
        <br />
        <div style='font-family: Arial; font-size: 15px;'></div>
     </div>
</code>```

Expected result:

```<code><div class=Answer>
        <div style='font-family: Arial; font-size: 50px;'>你好</div>
        <br />nĭ hăo<br />
     </div>
</code>```

I tried using regular expressions in Notepad++ but I can't figure out this one, especially because I always get "invalid expression" probably due to the <, /, > caracters.

Thanks in advance for your help!

答:
Search for this expression and replace it with nothing:</p>

```<code>\[sound:.*?<div\s+style='font-family:\s+Arial;\s+font-size:\s+15px;'></div>
</code>```

Body:
I have a huge HTML file and I'd like to delete all the parts starting with [sound: and ending with

Here is a sample of my document:

你好

nĭ hăo
[sound:pronunciation_zh_你好.mp3]

              <svg viewBox="0 0 32 32">
                 <polygon points="11,25 25,16 11,7"/>
                 Replay
              </svg>

        [sound:pronunciation_zh_你好.mp3]

Expected result:

你好

nĭ hăo

I tried using regular expressions in Notepad++ but I can't figure out this one, especially because I always get "invalid expression" probably due to the <, /, > caracters.

Thanks in advance for your help!

Body:
Search for this expression and replace it with nothing:

\[sound:.*?<div\s+style='font-family:\s+Arial;\s+font-size:\s+15px;'></div>


问:
Determine the number of NA values in a column
I want to count the number of NA values in a data frame column. Say my data frame is called df, and the name of the column I am considering is col. The way I have come up with is following:

```<code>sapply(df$col, function(x) sum(length(which(is.na(x)))))
</code>```

Is this a good/most efficient way to do this?

答:
You can use this to count number of NA or blanks in every column</p>

```<code>colSums(is.na(data_set_name)|data_set_name == '')
</code>```

Body:
I want to count the number of NA values in a data frame column. Say my data frame is called df, and the name of the column I am considering is col. The way I have come up with is following:

sapply(df$col, function(x) sum(length(which(is.na(x)))))

Is this a good/most efficient way to do this?

Body:
You can use this to count number of NA or blanks in every column

colSums(is.na(data_set_name)|data_set_name == '')


问:
Sending two AJAX requests at the same time
I am probably missing something very simple here, but what I am trying to do is update two divs on my page with AJAX requests that are called at the same time when an item is clicked.

I have looked at here
but unfortunately I am still missing something in the code.

I have the following JavaScript code:

```<code>$(document.body).on('click', '.details', function(event) {
    //  $(this) = your current element that clicked.
    // additional code
    var id = event.target.id;
    //alert(id);
    //alert($(this));
    _formurl = "home_stocktake_locations_list_group.php";
    _formdata = {
        'store_id': id
    };
    _formurl2 = "home_stocktake_list.php";
    $.ajax({
            type: "GET",
            url: _formurl,
            data: _formdata,
            success: function(xhrResponse) {
                $('#current').html(xhrResponse);
                var rowCount = $('#locations').length;
                row_count = parseInt(rowCount);
            },
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                $('#alert_msg').html(errorThrown);
                $('#alert_msg').fadeIn("slow");
            }
        }),
        $.ajax({

            type: "GET",
            url: _formurl2,
            data: _formdata,
            success: function(xhrResponse) {
                $('#previous').html(xhrResponse);
                var rowCount = $('#dd_home_stocktake').length;
                row_count = parseInt(rowCount);
            },
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                $('#alert_msg').html(errorThrown);
                $('#alert_msg').fadeIn("slow");
            }
        });

});
</code>```

When I look at what happens in the console, only home_stocktake_locations_list_group.php file gets called, the second AJAX call is completely ignored. What is causing this?

In the console I can only see the following:

答:
AJAX requests are done asynchronously, so you could start them one after the other directly (i.e. no comma before you second $.ajax command).

If your AJAX requests depend on each other and must be done in a specific ordre, start the second request in the "success" portion of the first request.

Body:
I am probably missing something very simple here, but what I am trying to do is update two divs on my page with AJAX requests that are called at the same time when an item is clicked.

I have looked at here
but unfortunately I am still missing something in the code.

I have the following JavaScript code:

$(document.body).on('click', '.details', function(event) {
    //  $(this) = your current element that clicked.
    // additional code
    var id = event.target.id;
    //alert(id);
    //alert($(this));
    _formurl = "home_stocktake_locations_list_group.php";
    _formdata = {
        'store_id': id
    };
    _formurl2 = "home_stocktake_list.php";
    $.ajax({
            type: "GET",
            url: _formurl,
            data: _formdata,
            success: function(xhrResponse) {
                $('#current').html(xhrResponse);
                var rowCount = $('#locations').length;
                row_count = parseInt(rowCount);
            },
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                $('#alert_msg').html(errorThrown);
                $('#alert_msg').fadeIn("slow");
            }
        }),
        $.ajax({

            type: "GET",
            url: _formurl2,
            data: _formdata,
            success: function(xhrResponse) {
                $('#previous').html(xhrResponse);
                var rowCount = $('#dd_home_stocktake').length;
                row_count = parseInt(rowCount);
            },
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                $('#alert_msg').html(errorThrown);
                $('#alert_msg').fadeIn("slow");
            }
        });

});

When I look at what happens in the console, only home_stocktake_locations_list_group.php file gets called, the second AJAX call is completely ignored. What is causing this?

In the console I can only see the following:


问:
How to convert a raw 64-byte binary to Hex or ASCII in C
I´m using SHA512 in C to get an Hash-Value. I did it like this:

```<code>#include <stdlib.h>
#include <stdio.h>
#include <openssl/sha.h>

int main(int argc, char *argv[]){

    unsigned char hash[SHA512_DIGEST_LENGTH];

    char data[] = "data to hash";          //Test Data
    SHA512(data, sizeof(data) - 1, hash);  //Kill termination character
    //Now there is the 64byte binary in hash
</code>```

I tried to convert it to hex by:

```<code>long int binaryval, hexadecimalval = 0, i = 1, remainder;

binaryval=(long int)hash;
        while (binaryval != 0)
        {
            remainder = binaryval % 10;
            hexadecimalval = hexadecimalval + remainder * i;
            i = i * 2;
            binaryval = binaryval / 10;
        }
        printf("Outpunt in Hex is: %lX \n", hexadecimalval);

        printf("%d\n",(long int) awhash );
        return 0;
    }
</code>```

But this is not wat i wantet.

How can i convert the binary which is in a unsigned char into a human readable format? Best case in a char[] for printing.

The Hash for "data to hash" should be:

d98f945fee6c9055592fa8f398953b3b7cf33a47cfc505667cbca1adb344ff18a4f442758810186fb480da89bc9dfa3328093db34bd9e4e4c394aec083e1773a

答:
Just print each char using %x in a printf().  Don't convert, just use the raw data:

```<code>int main(int argc, char *argv[]){

  unsigned char hash[SHA512_DIGEST_LENGTH];

  char data[] = "data to hash";          //Test Data
  SHA512(data, sizeof(data) - 1, hash);  //Kill termination character

  //Now there is the 64byte binary in hash
  for(int i=0; i<64; i++)
  {
    printf("%02x", hash[i]);
  }
  printf("\n");
}
</code>```

Edited to just output the hex value no commas or spaces.

Body:
I´m using SHA512 in C to get an Hash-Value. I did it like this:

#include <stdlib.h>
#include <stdio.h>
#include <openssl/sha.h>

int main(int argc, char *argv[]){

    unsigned char hash[SHA512_DIGEST_LENGTH];

    char data[] = "data to hash";          //Test Data
    SHA512(data, sizeof(data) - 1, hash);  //Kill termination character
    //Now there is the 64byte binary in hash

I tried to convert it to hex by:

long int binaryval, hexadecimalval = 0, i = 1, remainder;

binaryval=(long int)hash;
        while (binaryval != 0)
        {
            remainder = binaryval % 10;
            hexadecimalval = hexadecimalval + remainder * i;
            i = i * 2;
            binaryval = binaryval / 10;
        }
        printf("Outpunt in Hex is: %lX \n", hexadecimalval);

        printf("%d\n",(long int) awhash );
        return 0;
    }

But this is not wat i wantet.

How can i convert the binary which is in a unsigned char into a human readable format? Best case in a char[] for printing.

The Hash for "data to hash" should be:

d98f945fee6c9055592fa8f398953b3b7cf33a47cfc505667cbca1adb344ff18a4f442758810186fb480da89bc9dfa3328093db34bd9e4e4c394aec083e1773a

Body:
Just print each char using %x in a printf().  Don't convert, just use the raw data:

int main(int argc, char *argv[]){

  unsigned char hash[SHA512_DIGEST_LENGTH];

  char data[] = "data to hash";          //Test Data
  SHA512(data, sizeof(data) - 1, hash);  //Kill termination character

  //Now there is the 64byte binary in hash
  for(int i=0; i<64; i++)
  {
    printf("%02x", hash[i]);
  }
  printf("\n");
}

Edited to just output the hex value no commas or spaces.


问:
How to show data from database when you click item in a listview
having a problem with trying to access data in my database when I click an item in my listview.

Here is my method in my database handler:

```<code>    public Match getMatchFromId(int matchId)
    {
        SQLiteDatabase db = this.getReadableDatabase();
        Match m = null;
        Cursor cursor;

        cursor = db.rawQuery("select * from " + MATCH_TABLE + " where " +
        MATCH_ID_COL + "='" + matchId + "'" , null);

        while(cursor.moveToNext())
        {
            m = new Match();
            m.setHome(cursor.getString(cursor.getColumnIndex(MATCH_HOME_TEAM_COL)));
            m.setAway(cursor.getString(cursor.getColumnIndex(MATCH_AWAY_TEAM_COL)));
            m.setHomeScore(cursor.getString(cursor.getColumnIndex(MATCH_HOMESCORE_COL)));
            m.setAwayScore(cursor.getString(cursor.getColumnIndex(MATCH_AWAYSCORE_COL)));
            m.setDate(cursor.getString(cursor.getColumnIndex(MATCH_DATE_COL)));
            m.setTime(cursor.getString(cursor.getColumnIndex(MATCH_TIME_COL)));
            m.setRedCard(cursor.getString(cursor.getColumnIndex(MATCH_REDCARD_COL)));
            m.setBookings(cursor.getString(cursor.getColumnIndex(MATCH_BOOKINGS_COL)));
            m.setTypeOfMatch(cursor.getString(cursor.getColumnIndex(MATCH_TYPEOFMATCH_COL)));
//            m.setGroundId(cursor.getInt(cursor.getColumnIndex()));
        }
        cursor.close();

        return m;
    }
</code>```

I'm just having a problem with how to access the data via a listview. I want to be able to click the item, and bring it to another activity to edit it.

```<code>public class ViewMatchesActivity extends AppCompatActivity {
DBHandler myDB;
ArrayList<Match> matches = new ArrayList<Match>();
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_view_matches);
    myDB = new DBHandler(this);
    final ListView listView = (ListView) findViewById(R.id.listview);

    matches = myDB.getAllMatches();
    MyAdapter myAdapter = new MyAdapter(ViewMatchesActivity.this, R.layout.list2col, matches);

    listView.setAdapter(myAdapter);
</code>```

Any help would be nice as I'm very new to Android Studio.

答:
You need to add a Listener to Listen to the respective event (likely Item Click). Then extract the id (or whatever can be used to uniquely identify the row in the table id or rowid (normally the same thing) is frequently used), place that data into an Intent Extra, after creating an Intent and then invoke the other activity using the Intent.

You could code something along the lines of :-

```<code>    listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            //>>>> position is the position of the clicked item, 0 for the first item.
            //>>>> position will also be the respective offset into matches
            //>>>> position SHOULD NOT BE USED to try to perform arithmetic
            //>>>> calculation of rowid/id of the row in the table
            //>>>> So get rowid via matches.get(position).
            Intent intent = new Intent(getApplicationContext(),your_other_activity.class);
            intent.putExtra("KEYFORDATA",row_id_to_so_selected_item_can_be_edited);
            StartActivity(intent);
        }
    });
</code>```

Note! Obviously the above will not work as is, it will need to be tailored to suit.

Body:
having a problem with trying to access data in my database when I click an item in my listview.

Here is my method in my database handler:

    public Match getMatchFromId(int matchId)
    {
        SQLiteDatabase db = this.getReadableDatabase();
        Match m = null;
        Cursor cursor;

        cursor = db.rawQuery("select * from " + MATCH_TABLE + " where " +
        MATCH_ID_COL + "='" + matchId + "'" , null);

        while(cursor.moveToNext())
        {
            m = new Match();
            m.setHome(cursor.getString(cursor.getColumnIndex(MATCH_HOME_TEAM_COL)));
            m.setAway(cursor.getString(cursor.getColumnIndex(MATCH_AWAY_TEAM_COL)));
            m.setHomeScore(cursor.getString(cursor.getColumnIndex(MATCH_HOMESCORE_COL)));
            m.setAwayScore(cursor.getString(cursor.getColumnIndex(MATCH_AWAYSCORE_COL)));
            m.setDate(cursor.getString(cursor.getColumnIndex(MATCH_DATE_COL)));
            m.setTime(cursor.getString(cursor.getColumnIndex(MATCH_TIME_COL)));
            m.setRedCard(cursor.getString(cursor.getColumnIndex(MATCH_REDCARD_COL)));
            m.setBookings(cursor.getString(cursor.getColumnIndex(MATCH_BOOKINGS_COL)));
            m.setTypeOfMatch(cursor.getString(cursor.getColumnIndex(MATCH_TYPEOFMATCH_COL)));
//            m.setGroundId(cursor.getInt(cursor.getColumnIndex()));
        }
        cursor.close();

        return m;
    }

I'm just having a problem with how to access the data via a listview. I want to be able to click the item, and bring it to another activity to edit it.

public class ViewMatchesActivity extends AppCompatActivity {
DBHandler myDB;
ArrayList<Match> matches = new ArrayList<Match>();
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_view_matches);
    myDB = new DBHandler(this);
    final ListView listView = (ListView) findViewById(R.id.listview);

    matches = myDB.getAllMatches();
    MyAdapter myAdapter = new MyAdapter(ViewMatchesActivity.this, R.layout.list2col, matches);

    listView.setAdapter(myAdapter);

Any help would be nice as I'm very new to Android Studio.

Body:
You need to add a Listener to Listen to the respective event (likely Item Click). Then extract the id (or whatever can be used to uniquely identify the row in the table id or rowid (normally the same thing) is frequently used), place that data into an Intent Extra, after creating an Intent and then invoke the other activity using the Intent.

You could code something along the lines of :-

    listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            //>>>> position is the position of the clicked item, 0 for the first item.
            //>>>> position will also be the respective offset into matches
            //>>>> position SHOULD NOT BE USED to try to perform arithmetic
            //>>>> calculation of rowid/id of the row in the table
            //>>>> So get rowid via matches.get(position).
            Intent intent = new Intent(getApplicationContext(),your_other_activity.class);
            intent.putExtra("KEYFORDATA",row_id_to_so_selected_item_can_be_edited);
            StartActivity(intent);
        }
    });

Note! Obviously the above will not work as is, it will need to be tailored to suit.