问:
Is it possible to connect to a BTLE device in a WPF application?
So I am trying to connect to a Polar H7 Heart Rate Monitor, and I need to use a WPF application to do it. I'm using Windows 10.

Now I have done this with a UWP application already and it works perfectly, but I'd like to use WPF (if it is possible) instead to do the same.

I found this post on how to use Windows 10 APIs in WPF/winforms/etc and thought perfect, that's what I need. I successfully added the Bluetooth API to my WPF project and threw in the code that was working for my UWP project, but it doesn't work.

Here's a snippet of my code up to where it stops working:

```<code>        DeviceInformation _devicePolar = null;
        string StatusInformation;
        string StatusInformation2;
        var devices = await DeviceInformation.FindAllAsync(GattDeviceService.GetDeviceSelectorFromUuid(GattServiceUuids.HeartRate));
        foreach(var d in devices)
        {
            Debug.WriteLine(d.Name + " " + d.Id);
        }
        if (null == devices || devices.Count <= 0) return;
        foreach (var device in devices.Where(device => device.Name == "Polar H7 DCB16C16"))
        {
            _devicePolar = device;
            StatusInformation = string.Format("Found {0}", _devicePolar.Name);
            break;
        }
        if (_devicePolar == null) return;
        var service = await GattDeviceService.FromIdAsync(_devicePolar.Id);
        if (service == null) return;
</code>```

Now, this call

```<code>await GattDeviceService.FromIdAsync(_devicePolar.Id)
</code>```

is returning null. I was actually having the same problem when I made the UWP application and I found out it was because I forgot to throw in this

```<code>  <Capabilities>
    <Capability Name="internetClient" />
    <DeviceCapability Name="bluetooth" />
  </Capabilities>
</code>```

Into my manifest file. Once I put that in (on my UWP application) it worked fine. But there seems to be no equivalent place for this piece in a WPF application. Now going back to the blog post on how to add Win 10 libraries to WPF, this bit seems to be telling me that was the case all along:

The second set of APIs that you can’t use are ones that depend on an app’s package identity. UWP apps have package identities while PC software does not. Package identity information can be found in the app manifest file.

And looking further into the Microsoft topic linked in the post it does specify about Bluetooth that "Not all APIs are currently supported for packaged apps." Which is terribly non-specific.

Also should mention, before trying this I tried to use the 32feet library, but my device was not showing up at all while other devices (not LE) were, so I am assuming that 32feet just doesn't support BTLE. I found this asking the same about 32feet and that is what led me to try what I have detailed above instead, but I'm still not 100% clear on whether or not I can simply use 32feet to connect to BTLE devices.

So my question is, am I right that what am I trying to do (WPF application using Windows 10 API to connect to Bluetooth device) can't currently be done? If not, what am I doing wrong?

答:
Update after two years the question posted: I think there's still no library supporting WPF Bluetooth LE. A pretty straight forward proof is that, Windows settings, which is under UWP, supports Bluetooth LE devices, while Control Panel on Windows 10 doesn't.

The only solution I can come up with now is buying a Bluetooth dongle which has virtual COM port feature, so ideally I can talk to the BLE device like using serial connection. Haven't tested yet, will update later if this works.

Body:
So I am trying to connect to a Polar H7 Heart Rate Monitor, and I need to use a WPF application to do it. I'm using Windows 10.

Now I have done this with a UWP application already and it works perfectly, but I'd like to use WPF (if it is possible) instead to do the same.

I found this post on how to use Windows 10 APIs in WPF/winforms/etc and thought perfect, that's what I need. I successfully added the Bluetooth API to my WPF project and threw in the code that was working for my UWP project, but it doesn't work.

Here's a snippet of my code up to where it stops working:

        DeviceInformation _devicePolar = null;
        string StatusInformation;
        string StatusInformation2;
        var devices = await DeviceInformation.FindAllAsync(GattDeviceService.GetDeviceSelectorFromUuid(GattServiceUuids.HeartRate));
        foreach(var d in devices)
        {
            Debug.WriteLine(d.Name + " " + d.Id);
        }
        if (null == devices || devices.Count <= 0) return;
        foreach (var device in devices.Where(device => device.Name == "Polar H7 DCB16C16"))
        {
            _devicePolar = device;
            StatusInformation = string.Format("Found {0}", _devicePolar.Name);
            break;
        }
        if (_devicePolar == null) return;
        var service = await GattDeviceService.FromIdAsync(_devicePolar.Id);
        if (service == null) return;

Now, this call

await GattDeviceService.FromIdAsync(_devicePolar.Id)

is returning null. I was actually having the same problem when I made the UWP application and I found out it was because I forgot to throw in this

  <Capabilities>
    <Capability Name="internetClient" />
    <DeviceCapability Name="bluetooth" />
  </Capabilities>

Into my manifest file. Once I put that in (on my UWP application) it worked fine. But there seems to be no equivalent place for this piece in a WPF application. Now going back to the blog post on how to add Win 10 libraries to WPF, this bit seems to be telling me that was the case all along:

The second set of APIs that you can’t use are ones that depend on an app’s package identity. UWP apps have package identities while PC software does not. Package identity information can be found in the app manifest file.

And looking further into the Microsoft topic linked in the post it does specify about Bluetooth that "Not all APIs are currently supported for packaged apps." Which is terribly non-specific.

Also should mention, before trying this I tried to use the 32feet library, but my device was not showing up at all while other devices (not LE) were, so I am assuming that 32feet just doesn't support BTLE. I found this asking the same about 32feet and that is what led me to try what I have detailed above instead, but I'm still not 100% clear on whether or not I can simply use 32feet to connect to BTLE devices.

So my question is, am I right that what am I trying to do (WPF application using Windows 10 API to connect to Bluetooth device) can't currently be done? If not, what am I doing wrong?


来源: stackexchange

问:
Java split string at certain length in pixels
I need to split a String that is going to be displayed in a box using java.awt.Graphics. The problem is, I need the string to automatically be split when it reaches the rectangles width in pixels. For example,

```<code>"This is an example string. What goes into the string does not matter"
[----------------------------------------] <-- Hypothetical width of box/rect
</code>```

I need the string to be split between "goes" and "into" so I can then have the  rest of the text on a new line:

```<code>"This is an example string. What goes
into the string does not matter"
[----------------------------------------] <-- Hypothetical width of box/rect
</code>```

I know how to get the width of a string, but I do not know how to go about splitting it.

答:
I know I am super late to stating if I figured it out or not, but I managed to do it myself without a 3rd party API. It isn't super efficient as if the string length gets too long, the last word is cut off. (You can look at the code if you wish, but I can no longer explain how it works as I have not looked at it in a long time. </p>

```<code>public class ConsoleLog {
private static Color c = Color.WHITE;
public static Color getC() {
    return c;
}

public static void setC(Color c) {
    ConsoleLog.c = c;
}

private static int pos;
private static List<String[]> logs;
private static List<Point>linesPos = new ArrayList<Point>();
private static Rectangle r = Main.Main.screenSize;
public static void log(List <String[]> logs, Graphics g) {
    g.setColor(c);
    ConsoleLog.logs = logs;
    splitConsole(g);
}

public static void splitConsole(Graphics g){
    pos = 0;
    for(int i = 0; i < (r.height / 2) / 10 - 10; i++) {
        linesPos.add(new Point(10, (i * (r.height / (50 + 3) + 5) + 15)));
    }
    for(int i = 0; i < logs.size(); i++) {
        for(int ie = 0; ie < logs.get(i).length || pos < logs.get(i).length; ie++) {
            g.drawString(logs.get(i)[ie], linesPos.get(pos).x, linesPos.get(pos).y);
            pos++;
        }
    }
}
</code>```

<p>To be clear, I was developing a small game engine and decided to scrap it as it was getting too messy, inefficient, and was built around a clicker game. I am working on a second one that will be able to create any 2D game the user wants and it is very user friendly. It is almost ready for its first version and I am excited to see what can be made out of it! </p>

ContentLicense: CC BY-SA 4.0

Body:
I need to split a String that is going to be displayed in a box using java.awt.Graphics. The problem is, I need the string to automatically be split when it reaches the rectangles width in pixels. For example,

"This is an example string. What goes into the string does not matter"
[----------------------------------------] <-- Hypothetical width of box/rect

I need the string to be split between "goes" and "into" so I can then have the  rest of the text on a new line:

"This is an example string. What goes
into the string does not matter"
[----------------------------------------] <-- Hypothetical width of box/rect

I know how to get the width of a string, but I do not know how to go about splitting it.

Body:
I know I am super late to stating if I figured it out or not, but I managed to do it myself without a 3rd party API. It isn't super efficient as if the string length gets too long, the last word is cut off. (You can look at the code if you wish, but I can no longer explain how it works as I have not looked at it in a long time.

public class ConsoleLog {
private static Color c = Color.WHITE;
public static Color getC() {
    return c;
}

public static void setC(Color c) {
    ConsoleLog.c = c;
}

private static int pos;
private static List<String[]> logs;
private static List<Point>linesPos = new ArrayList<Point>();
private static Rectangle r = Main.Main.screenSize;
public static void log(List <String[]> logs, Graphics g) {
    g.setColor(c);
    ConsoleLog.logs = logs;
    splitConsole(g);
}

public static void splitConsole(Graphics g){
    pos = 0;
    for(int i = 0; i < (r.height / 2) / 10 - 10; i++) {
        linesPos.add(new Point(10, (i * (r.height / (50 + 3) + 5) + 15)));
    }
    for(int i = 0; i < logs.size(); i++) {
        for(int ie = 0; ie < logs.get(i).length || pos < logs.get(i).length; ie++) {
            g.drawString(logs.get(i)[ie], linesPos.get(pos).x, linesPos.get(pos).y);
            pos++;
        }
    }
}

To be clear, I was developing a small game engine and decided to scrap it as it was getting too messy, inefficient, and was built around a clicker game. I am working on a second one that will be able to create any 2D game the user wants and it is very user friendly. It is almost ready for its first version and I am excited to see what can be made out of it!


问:
Rename a directory and its sub-directory with a one liner in Bash
I have a android app that i decompiled and im writing a script to rename directories.

Inside the decompiled folder is a path:

```<code>smali/com/FOLDER/SUB-FOLDER
</code>```

I want to rename the EXISTING folders to:

```<code>smali/com/NEW-NAME/SUB-NEW-NAME
</code>```

I was thinking i could use the mv command but digging through the man page it looks like it cant be done. I was trying this:

```<code>mv smali/com/FOLDER smali/com/FOLDER/SUB-FOLDER -t smali/com/NEW-NAME/SUB-NEW-NAME
</code>```

This only works for moving multiple files to a single destination.

EDIT:

Exisiting folders:

```<code>  smali/com/FOLDER/SUB-FOLDER
</code>```

I am trying to rename both folders while keeping the contents of each folder.

A example of renaming each folder one by one would be:

```<code>mv smali/com/FOLDER/ smali/com/NEW-NAME
mv smali/com/NEW-NAME/SUB-FOLDER smali/com/NEW-NAME/SUB-NEW-NAME
</code>```

答:
Can't think of anything more elegant, but the following should work:
find . -path '.*com/FOLDER/SUBFOLDER' | awk '{new_dir=$1; sub("/FOLDER/SUBFOLDER","/NEW/SUBNEW", $new_dir); printf("mkdir -p %s\nmv %s %s\n", $new_dir, $1, $new_dir);}' > cmds

That gets all the required mv commands in the cmds file. Verify it is correct, and then execute using sh cmds. Although this isn't the most fun, I like this approach when dealing with important data because it is always better to verify what you're going to run.

Edit: Fixed the issue pointed out in comments about the script not creating the directory if it does not exist.

Body:
I have a android app that i decompiled and im writing a script to rename directories.

Inside the decompiled folder is a path:

smali/com/FOLDER/SUB-FOLDER

I want to rename the EXISTING folders to:

smali/com/NEW-NAME/SUB-NEW-NAME

I was thinking i could use the mv command but digging through the man page it looks like it cant be done. I was trying this:

mv smali/com/FOLDER smali/com/FOLDER/SUB-FOLDER -t smali/com/NEW-NAME/SUB-NEW-NAME

This only works for moving multiple files to a single destination.

EDIT:

Exisiting folders:

  smali/com/FOLDER/SUB-FOLDER

I am trying to rename both folders while keeping the contents of each folder.

A example of renaming each folder one by one would be:

mv smali/com/FOLDER/ smali/com/NEW-NAME
mv smali/com/NEW-NAME/SUB-FOLDER smali/com/NEW-NAME/SUB-NEW-NAME


问:
How to create a simple app that displays weather details
I want to create a simple weather app that displays the weather details for three consecutive days.

When I click on the weather tab the weather details for three consecutive days should be shown on a table view. How is this possible? Can anybody provide me any links regarding this problem? Thanks.

答:
u can use Google API to get weather detail
please have a look on Google API</p>

ContentLicense: CC BY-SA 3.0


问:
Is there an aggregateByKey function in Spark DataFrame?
In Spark, is there an equivalent of the aggregateByKey method available for RDD in the DataFrame API?

RDD aggregateByKey API doc

答:
Most common aggregation operations in the DataFrame interface can be done with agg and an already-defined aggregator e.g. sum, first, max, etc. If you're looking to do something like a GROUP BY and aggregation, a la SQL, you should look into those existing aggregation functions first.

The aggregateByKey method exposes more complex logic, however, which allows you to implement some sophisticated aggregation routines. If you're looking to do that, you'll want to use the Dataset interface, which is very similar to what you're already used to from RDDs. Specifically, look into creating a custom aggregator:

https://docs.databricks.com/spark/latest/spark-sql/udaf-scala.html

There, you define the aggregator methods like initialize, merge, etc. that specify how to create the aggregator, merge individual elements into the aggregate, and combine intermediate aggregates together across executors/tasks.

Once your aggregator is defined, you can use it on a Dataset, e.g.

ds.groupBy(_.myKey).agg(myCustomAggregator)


问:
RegEx for identifying alphanumeric patterns with special chars and boundaries
I am attempting to return one of these strings (depends on input):

```<code>f23/24  /or/  f23-24   /or/  f23+24
</code>```

(Ideally, it would be great if it ALWAYS returned format f23-24), regardless of input

from this type of string:

```<code>build-f23/24 1st pass demo (50:50)   #Should output f23-24 or f23/24
build-f17-22 1st pass demo (50:50)   #Should output f17-22
build-f-1 +14 1st pass demo (50:50)  #Should output f1-14 or f1+14
</code>```

Exception:

Some of the strings will not have the second set of numbers:

```<code>build-f45 1st pass demo (50:50)      #Should output f45
</code>```

Where I am currently at:

Thus far, I have this regex, but it always fails if the separator char is a slash:

```<code>regex = r"(\s?)(\-?)(f)(\s?)([\+\-\/]?)(\d\d*)(-?)(\d?\d*)"
tmp = re.search(regex, val)[0]
</code>```

Body:
I am attempting to return one of these strings (depends on input):

f23/24  /or/  f23-24   /or/  f23+24

(Ideally, it would be great if it ALWAYS returned format f23-24), regardless of input

from this type of string:

build-f23/24 1st pass demo (50:50)   #Should output f23-24 or f23/24
build-f17-22 1st pass demo (50:50)   #Should output f17-22
build-f-1 +14 1st pass demo (50:50)  #Should output f1-14 or f1+14

Exception:

Some of the strings will not have the second set of numbers:

build-f45 1st pass demo (50:50)      #Should output f45

Where I am currently at:

Thus far, I have this regex, but it always fails if the separator char is a slash:

regex = r"(\s?)(\-?)(f)(\s?)([\+\-\/]?)(\d\d*)(-?)(\d?\d*)"
tmp = re.search(regex, val)[0]

Body:
import re

dat = """build-f23/24 1st pass demo (50:50)
      build-f17-22 1st pass demo (50:50)
      build-f-1 +14 1st pass demo (50:50)
      build-f45 1st pass demo (50:50)"""

rgx = r'(?mi)^.*(?<=-)(f)\D?(\d+)(?:\s?([+\/-]\d+))?.*$'
re.sub(rgx,r'\1\2\3',dat).split()
['f23/24', 'f17-22', 'f1+14', 'f45']

or you could do:

rgx1 = r'(?mi)^.*(?<=-)(f)\D?(\d+)(?:\s?[+\/-](\d+))?.*$'
re.sub('(?m)-$','',re.sub(rgx1 ,r'\1\2-\3',dat)).split()
['f23-24', 'f17-22', 'f1-14', 'f45']

or instead of using sub twice you could replace directly:

re.sub(rgx1,lambda x: f'{x.group(1)}{x.group(2)}-{x.group(3)}'
                         if x.group(3) else f'{x.group(1)}{x.group(2)}',dat).split()
['f23-24', 'f17-22', 'f1-14', 'f45']


问:
ERROR: Failed building wheel for pocketsphinx while trying to install pocketsphinx with pip
I'm trying to install pocketsphinx and get following error:</p>

```<code>jandornhege@JanDornhegeUbuntu:~/Hermes/Basefunktions$ pip install pocketsphinx
Collecting pocketsphinx
  Using cached https://files.pythonhosted.org/packages/cd/4a/adea55f189a81aed88efa0b0e1d25628e5ed22622ab9174bf696dd4f9474/pocketsphinx-0.1.15.tar.gz
Building wheels for collected packages: pocketsphinx
  Building wheel for pocketsphinx (setup.py) ... error
  ERROR: Complete output from command /home/jandornhege/anaconda3

.....

  deps/sphinxbase/src/libsphinxad/ad_pulse.c:44:10: fatal error: pulse/pulseaudio.h: Datei oder Verzeichnis nicht gefunden
   #include <pulse/pulseaudio.h>
            ^~~~~~~~~~~~~~~~~~~~
  compilation terminated.
  error: command 'gcc' failed with exit status 1
  ----------------------------------------
  ERROR: Failed building wheel for pocketsphinx
</code>```

答:
Ubuntu installation requirements:</p>

```<code>sudo apt-get install -qq python python-dev python-pip build-essential swig git libpulse-dev libasound2-dev
</code>```

Body:
I'm trying to install pocketsphinx and get following error:

jandornhege@JanDornhegeUbuntu:~/Hermes/Basefunktions$ pip install pocketsphinx
Collecting pocketsphinx
  Using cached https://files.pythonhosted.org/packages/cd/4a/adea55f189a81aed88efa0b0e1d25628e5ed22622ab9174bf696dd4f9474/pocketsphinx-0.1.15.tar.gz
Building wheels for collected packages: pocketsphinx
  Building wheel for pocketsphinx (setup.py) ... error
  ERROR: Complete output from command /home/jandornhege/anaconda3

.....

  deps/sphinxbase/src/libsphinxad/ad_pulse.c:44:10: fatal error: pulse/pulseaudio.h: Datei oder Verzeichnis nicht gefunden
   #include <pulse/pulseaudio.h>
            ^~~~~~~~~~~~~~~~~~~~
  compilation terminated.
  error: command 'gcc' failed with exit status 1
  ----------------------------------------
  ERROR: Failed building wheel for pocketsphinx

Body:
Ubuntu installation requirements:

sudo apt-get install -qq python python-dev python-pip build-essential swig git libpulse-dev libasound2-dev


问:
SImple code runs correctly in DevC++ but not Visual Studio Code
Code runs fine DevC++ but not Visual Studio Code

Was doing a homework question. Simple code adding two integers. Code looked fine but running it kept giving me the wrong result. After losing my mind I tried to run it in DevC++ to which it gave me the result I expected.

I'm very very new to coding. Visual Studio Code is trying to tell me something in the output window but I don't know what it's is trying to tell me.

```<code>#include <stdio.h>
int main()
{
    double x,y,z;

    printf("Enter first number:" );

    scanf("%i", &x);

    printf("Enter second number:" );

    scanf("%i", &y);

    printf("the first number is: %d \n",x);
    printf("the second number is: %d \n ",y);

    z= x+y;

    printf("Output 1: The result is %d . \n",z);
    printf("Output 2: The sum of %d and %d is %d . ",x,y,z);

    return 0;
}

</code>```

-------------------VS Code output Window-------------------------

```<code>hwidk.cpp:19:8: warning: format '%d' expects argument of type 'int', but argument 2 has type 'double' [-Wformat=]
 printf("Output 1: The result is %d . \n",z);
        ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~

[hwidk.cpp 2019-05-27 21:35:01.608]
hwidk.cpp:20:8: warning: format '%d' expects argument of type 'int', but argument 2 has type 'double' [-Wformat=]
 printf("Output 2: The sum of %d and %d is %d . ",x,y,z);
        ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~
hwidk.cpp:20:8: warning: format '%d' expects argument of type 'int', but argument 3 has type 'double' [-Wformat=]

[hwidk.cpp 2019-05-27 21:35:01.608]
hwidk.cpp:20:8: warning: format '%d' expects argument of type 'int', but argument 4 has type 'double' [-Wformat=]
</code>```

--------------Visual Studio Runs the code as------------------------

```<code>
Enter first number:5
Enter second number:6
the first number is: 5
the second number is: 6
Output 1: The result is 7 .
Output 2: The sum of 5 and 0 is 6
</code>```

答: I think the compiler that DevC++ uses is different than the one that you use with VS Code, mainly the problem is in the printf. You're using %d, which means an integer argument, but you're passing a double to it. DevC++ compiler might automatically truncate the double value to an integer value. Switching it to %f should do the trick

Body:
Code runs fine DevC++ but not Visual Studio Code

Was doing a homework question. Simple code adding two integers. Code looked fine but running it kept giving me the wrong result. After losing my mind I tried to run it in DevC++ to which it gave me the result I expected.

I'm very very new to coding. Visual Studio Code is trying to tell me something in the output window but I don't know what it's is trying to tell me.

#include <stdio.h>
int main()
{
    double x,y,z;

    printf("Enter first number:" );

    scanf("%i", &x);

    printf("Enter second number:" );

    scanf("%i", &y);

    printf("the first number is: %d \n",x);
    printf("the second number is: %d \n ",y);

    z= x+y;

    printf("Output 1: The result is %d . \n",z);
    printf("Output 2: The sum of %d and %d is %d . ",x,y,z);

    return 0;
}

-------------------VS Code output Window-------------------------

hwidk.cpp:19:8: warning: format '%d' expects argument of type 'int', but argument 2 has type 'double' [-Wformat=]
 printf("Output 1: The result is %d . \n",z);
        ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~

[hwidk.cpp 2019-05-27 21:35:01.608]
hwidk.cpp:20:8: warning: format '%d' expects argument of type 'int', but argument 2 has type 'double' [-Wformat=]
 printf("Output 2: The sum of %d and %d is %d . ",x,y,z);
        ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~
hwidk.cpp:20:8: warning: format '%d' expects argument of type 'int', but argument 3 has type 'double' [-Wformat=]

[hwidk.cpp 2019-05-27 21:35:01.608]
hwidk.cpp:20:8: warning: format '%d' expects argument of type 'int', but argument 4 has type 'double' [-Wformat=]

--------------Visual Studio Runs the code as------------------------

Enter first number:5
Enter second number:6
the first number is: 5
the second number is: 6
Output 1: The result is 7 .
Output 2: The sum of 5 and 0 is 6


问:
Akeneo never stop loading when login
I've installed Akeneo Community Edition 3.1 on Ubuntu 18.04 with the folowing:

PHP 7.2

Ver 14.14 Distrib 5.7.26, for Linux (x86_64) using  EditLine wrapper

yarn 1.16.0

node v8.10.0

The installation seems to have been completed successfully, I can connect to mysql for creating the database, requirements tests have been passed.

I have configured the vhosts with:

```<code><VirtualHost *:80>

    ServerName <my.server>

    DocumentRoot /var/www/html/akeneo/web
    <Directory /var/www/html/akeneo/web>
        AllowOverride None
        Order Allow,Deny
        Allow from All

        <IfModule mod_rewrite.c>
            Options -MultiViews
            RewriteEngine On
            RewriteCond %{REQUEST_FILENAME} !-f
            RewriteRule ^(.*)$ app.php [QSA,L]
        </IfModule>
    </Directory>

    ErrorLog /var/log/apache2/akeneo_error.log
    CustomLog /var/log/apache2/akeneo_access.log combined

</VirtualHost>
</code>```

The project is installed in /var/www/html/akeneo.

I can access to the home/login page, the css works correctly but when I enter admin/admin and try to connect, it never stop to load.

In the console, I can read 3 errors with 404 for vendor.js and main.js unreachable.

And in my symfony logs :

```<code>Symfony\Component\HttpKernel\Exception\NotFoundHttpException: "No route found for "GET /dist/main.min.js" (from "<http://my.server>")" at /var/www/html/akeneo/vendor/symfony/symfony/src/Symfony/Component/HttpKernel/EventListener/RouterListener.php line 139 {"exception":"[object] (Symfony\\Component\\HttpKernel\\Exception\\NotFoundHttpException(code: 0): No route found for \"GET /dist/main.min.js\" (from \"<http://my.server>") at /var/www/html/akeneo/vendor/symfony/symfony/src/Symfony/Component/HttpKernel/EventListener/RouterListener.php:139, Symfony\\Component\\Routing\\Exception\\ResourceNotFoundException(code: 0):  at /var/www/html/akeneo/var/cache/prod/appProdProjectContainerUrlMatcher.php:3585)"} []
</code>```

I also encounter errors when I try the command:

```<code>yarn run webpack
</code>```

Like :

```<code>Starting LESS compilation

‣ /var/www/html/akeneo/vendor/akeneo/pim-community-dev/src/Oro/Bundle/PimDataGridBundle/Resources/public/less/index.less
‣ /var/www/html/akeneo/vendor/akeneo/pim-community-dev/src/Akeneo/Platform/Bundle/UIBundle/Resources/public/less/index.less

Updating form extensions.json
✓ Saved CSS to web/css/pim.css
Version: webpack 4.29.6
Time: 17079ms
Built at: 05/27/2019 6:03:50 PM
 2 assets
Entrypoint main = vendor.min.js main.min.js

ERROR in /var/www/html/akeneo/pim-community-standard/vendor/akeneo/pim-community-dev/tests/front/unit/pimenrich/js/i18n.unit.ts
[tsl] ERROR in /var/www/html/akeneo/pim-community-standard/vendor/akeneo/pim-community-dev/tests/front/unit/pimenrich/js/i18n.unit.ts(36,12)
      TS2554: Expected 1-2 arguments, but got 0.

ERROR in /var/www/html/akeneo/pim-community-standard/vendor/symfony/symfony/src/Symfony/Component/Translation/Tests/fixtures/resources.ts
[tsl] ERROR in /var/www/html/akeneo/pim-community-standard/vendor/symfony/symfony/src/Symfony/Component/Translation/Tests/fixtures/resources.ts(1,7)
      TS1005: '>' expected.

ERROR in /var/www/html/akeneo/pim-community-standard/vendor/symfony/symfony/src/Symfony/Component/Translation/Tests/fixtures/resources.ts
[tsl] ERROR in /var/www/html/akeneo/pim-community-standard/vendor/symfony/symfony/src/Symfony/Component/Translation/Tests/fixtures/resources.ts(1,14)
      TS1005: ';' expected.

ERROR in /var/www/html/akeneo/pim-community-standard/vendor/symfony/symfony/src/Symfony/Component/Translation/Tests/fixtures/resources.ts
[tsl] ERROR in /var/www/html/akeneo/pim-community-standard/vendor/symfony/symfony/src/Symfony/Component/Translation/Tests/fixtures/resources.ts(1,21)
      TS1005: ';' expected.
</code>```

I've tried the following commands but it still doesn't work :

composer install --optimize-autoloader --prefer-dist

yarn install

php bin/console --env=prod cache:clear --no-warmup

php bin/console --env=prod pim:installer:assets --symlink --clean

yarn run webpack

I would be very happy if there was someone who has found a solution to this problem ?

I've checked how to i solve akeneo still loading after logged in main page? but it hasn't resolved the problem.

答:
I've found why it didn't work. It was because I've moved the content of the pim-community-standard directly into my-project.

It had created two web folder, and lead to problems with redirections.

I've installed another projet my-project with
- composer.phar

- pim-community-standard

And launch all the command from pim-community-standard.

Ccl : keep the exact same folder hierarchy if you install akeneo

Title: Akeneo never stop loading when login

Body:
I've installed Akeneo Community Edition 3.1 on Ubuntu 18.04 with the folowing:

PHP 7.2

Ver 14.14 Distrib 5.7.26, for Linux (x86_64) using  EditLine wrapper

yarn 1.16.0

node v8.10.0

The installation seems to have been completed successfully, I can connect to mysql for creating the database, requirements tests have been passed.

I have configured the vhosts with:

<VirtualHost *:80>

    ServerName <my.server>

    DocumentRoot /var/www/html/akeneo/web
    <Directory /var/www/html/akeneo/web>
        AllowOverride None
        Order Allow,Deny
        Allow from All

        <IfModule mod_rewrite.c>
            Options -MultiViews
            RewriteEngine On
            RewriteCond %{REQUEST_FILENAME} !-f
            RewriteRule ^(.*)$ app.php [QSA,L]
        </IfModule>
    </Directory>

    ErrorLog /var/log/apache2/akeneo_error.log
    CustomLog /var/log/apache2/akeneo_access.log combined

</VirtualHost>

The project is installed in /var/www/html/akeneo.

I can access to the home/login page, the css works correctly but when I enter admin/admin and try to connect, it never stop to load.

In the console, I can read 3 errors with 404 for vendor.js and main.js unreachable.

And in my symfony logs :

Symfony\Component\HttpKernel\Exception\NotFoundHttpException: "No route found for "GET /dist/main.min.js" (from "<http://my.server>")" at /var/www/html/akeneo/vendor/symfony/symfony/src/Symfony/Component/HttpKernel/EventListener/RouterListener.php line 139 {"exception":"[object] (Symfony\\Component\\HttpKernel\\Exception\\NotFoundHttpException(code: 0): No route found for \"GET /dist/main.min.js\" (from \"<http://my.server>") at /var/www/html/akeneo/vendor/symfony/symfony/src/Symfony/Component/HttpKernel/EventListener/RouterListener.php:139, Symfony\\Component\\Routing\\Exception\\ResourceNotFoundException(code: 0):  at /var/www/html/akeneo/var/cache/prod/appProdProjectContainerUrlMatcher.php:3585)"} []

I also encounter errors when I try the command:

yarn run webpack

Like :

Starting LESS compilation

‣ /var/www/html/akeneo/vendor/akeneo/pim-community-dev/src/Oro/Bundle/PimDataGridBundle/Resources/public/less/index.less
‣ /var/www/html/akeneo/vendor/akeneo/pim-community-dev/src/Akeneo/Platform/Bundle/UIBundle/Resources/public/less/index.less

Updating form extensions.json
✓ Saved CSS to web/css/pim.css
Version: webpack 4.29.6
Time: 17079ms
Built at: 05/27/2019 6:03:50 PM
 2 assets
Entrypoint main = vendor.min.js main.min.js

ERROR in /var/www/html/akeneo/pim-community-standard/vendor/akeneo/pim-community-dev/tests/front/unit/pimenrich/js/i18n.unit.ts
[tsl] ERROR in /var/www/html/akeneo/pim-community-standard/vendor/akeneo/pim-community-dev/tests/front/unit/pimenrich/js/i18n.unit.ts(36,12)
      TS2554: Expected 1-2 arguments, but got 0.

ERROR in /var/www/html/akeneo/pim-community-standard/vendor/symfony/symfony/src/Symfony/Component/Translation/Tests/fixtures/resources.ts
[tsl] ERROR in /var/www/html/akeneo/pim-community-standard/vendor/symfony/symfony/src/Symfony/Component/Translation/Tests/fixtures/resources.ts(1,7)
      TS1005: '>' expected.

ERROR in /var/www/html/akeneo/pim-community-standard/vendor/symfony/symfony/src/Symfony/Component/Translation/Tests/fixtures/resources.ts
[tsl] ERROR in /var/www/html/akeneo/pim-community-standard/vendor/symfony/symfony/src/Symfony/Component/Translation/Tests/fixtures/resources.ts(1,14)
      TS1005: ';' expected.

ERROR in /var/www/html/akeneo/pim-community-standard/vendor/symfony/symfony/src/Symfony/Component/Translation/Tests/fixtures/resources.ts
[tsl] ERROR in /var/www/html/akeneo/pim-community-standard/vendor/symfony/symfony/src/Symfony/Component/Translation/Tests/fixtures/resources.ts(1,21)
      TS1005: ';' expected.

I've tried the following commands but it still doesn't work :

composer install --optimize-autoloader --prefer-dist

yarn install

php bin/console --env=prod cache:clear --no-warmup

php bin/console --env=prod pim:installer:assets --symlink --clean

yarn run webpack

I would be very happy if there was someone who has found a solution to this problem ?

I've checked how to i solve akeneo still loading after logged in main page? but it hasn't resolved the problem.


问:
How to create CGPathRef from UILabel text?
I'm going to make an shadow path for UILabel, which outlines the text of it. Is the UILabel text somehow convertable to CGPath?</p>

答:
I’d suggest that the easiest approach is set the shadow properties of the layer.

In Objective-C:

```<code>self.label.layer.shadowColor = UIColor.blackColor.CGColor;
self.label.layer.shadowRadius = 10;
self.label.layer.shadowOpacity = 1;
self.label.layer.shadowOffset = CGSizeZero;
</code>```

In Swift:

```<code>label.layer.shadowColor = UIColor.black.cgColor
label.layer.shadowRadius = 10
label.layer.shadowOpacity = 1
label.layer.shadowOffset = .zero
</code>```

Yielding:

You said:

But, in layers I have some additional content, where I don't want to add the shadow.

If you have subviews or sublayers that are interfering with the shadow, I’d suggest you move that content out of the label and into their own view hierarchy. It’s hard to be specific without knowing what sublayers/subviews you’ve added to your label.

You said:

... I need opacity of the shadow too and it's impossible without layers.

That’s not entirely true. You can use the NSAttributedString pattern and specify the alpha as part of the shadowColor.

E.g. in Objective-C:

```<code>NSShadow *shadow = [[NSShadow alloc] init];
shadow.shadowOffset = CGSizeZero;
shadow.shadowBlurRadius = 20;
shadow.shadowColor = [UIColor.blackColor colorWithAlphaComponent:1];

NSDictionary<NSAttributedStringKey, id> *attributes = @{ NSShadowAttributeName: shadow };

NSMutableAttributedString *string = [self.label.attributedText mutableCopy];
[string setAttributes:attributes range:NSMakeRange(0, string.length)];

self.label.attributedText = string;
</code>```

Or in Swift:

```<code>let shadow = NSShadow()
shadow.shadowOffset = .zero
shadow.shadowBlurRadius = 20
shadow.shadowColor = UIColor.black.withAlphaComponent(1)

let attributes: [NSAttributedString.Key: Any] = [.shadow: shadow]

guard let string = label.attributedText?.mutableCopy() as? NSMutableAttributedString else { return }
string.setAttributes(attributes, range: NSRange(location: 0, length: string.length))
label.attributedText = string
</code>```

Body:
I’d suggest that the easiest approach is set the shadow properties of the layer.

In Objective-C:

self.label.layer.shadowColor = UIColor.blackColor.CGColor;
self.label.layer.shadowRadius = 10;
self.label.layer.shadowOpacity = 1;
self.label.layer.shadowOffset = CGSizeZero;

In Swift:

label.layer.shadowColor = UIColor.black.cgColor
label.layer.shadowRadius = 10
label.layer.shadowOpacity = 1
label.layer.shadowOffset = .zero

Yielding:

You said:

But, in layers I have some additional content, where I don't want to add the shadow.

If you have subviews or sublayers that are interfering with the shadow, I’d suggest you move that content out of the label and into their own view hierarchy. It’s hard to be specific without knowing what sublayers/subviews you’ve added to your label.

You said:

... I need opacity of the shadow too and it's impossible without layers.

That’s not entirely true. You can use the NSAttributedString pattern and specify the alpha as part of the shadowColor.

E.g. in Objective-C:

NSShadow *shadow = [[NSShadow alloc] init];
shadow.shadowOffset = CGSizeZero;
shadow.shadowBlurRadius = 20;
shadow.shadowColor = [UIColor.blackColor colorWithAlphaComponent:1];

NSDictionary<NSAttributedStringKey, id> *attributes = @{ NSShadowAttributeName: shadow };

NSMutableAttributedString *string = [self.label.attributedText mutableCopy];
[string setAttributes:attributes range:NSMakeRange(0, string.length)];

self.label.attributedText = string;

Or in Swift:

let shadow = NSShadow()
shadow.shadowOffset = .zero
shadow.shadowBlurRadius = 20
shadow.shadowColor = UIColor.black.withAlphaComponent(1)

let attributes: [NSAttributedString.Key: Any] = [.shadow: shadow]

guard let string = label.attributedText?.mutableCopy() as? NSMutableAttributedString else { return }
string.setAttributes(attributes, range: NSRange(location: 0, length: string.length))
label.attributedText = string


问:
what is the difference between runtime and speed of an algorithm?
I am reading a book that implies they are different. According to the book Big O tells how the speed of an algorithm relates to the number of items, but it does to refer to the running time of an algorithm for a given number of items.
I don't understand the difference.</p>

答:
Big 'O' is how the algorithm's runtime scales with the number of inputs

Building  pyramids is O(n) it has a slow runtime but scales linearly with the number of pyramids.

Sorting the names of pyramids you have built into alphabetical order is O(n log n) it is 'slower' than building them but in practice the runtime of the algorithm is probably quicker. Unless you have a large number of pyramids.


问:
Trying to totally reload scene
I made a scene that represents the main menu of a game. In this menu there is an option for single player, and, when I press it, it opens a new "level 1" scene.

Also, there is a pause menu that allows the player to quit the game and get back to the main menu.

However, after it backs to the main menu, when I try to get into the level 1 scene using SceneManager.LoadScene("level 1"), it makes a lot of problems. It means that a lot of game objects don't act like they should.

I dont know why it happened, and I would appreciate if someone can help me solve it. Thank you.

答:
You can use SceneManager.LoadScene("level 1", LoadSceneMode.Single); to clear the old scene and only load the new one in, which will let you get a clear scene and shouldn't have any problems.

If you have scripts that need to last into the new scene, you can use DontDestroyOnLoad(this); in your scripts and they will move into the new scene. The problem is you have to make sure your scripts that aren't being destroyed don't try and access destroyed objects. From your comment it looks like you have a player movement controller that isn't being destroyed, or it's being created in the menu scene and it doesn't have it's references updated correctly when the scene is reloaded. You can also use Destroy(this); in your scripts that are saved through scene changes to get rid of them when they're done running.

Title: Trying to totally reload scene


问:
How can I add a field after the table in my Woocommerce new order email template?
In woocommerce I would like to add 2 pieces of information to email_after_order_table. How can i eat it? Please advise...</p>

答:
Is it in file yourtheme/woocommerce/emails/email-order-details.php?
If it is you can create hook in your functions file.

```<code>add_action( 'woocommerce_email_after_order_table', 'your_example_function', 90, 4 );
function your_example_function( $order, $sent_to_admin, $plain_text, $email ){
    // code
}
</code>```

That function your_example_function will start after action woocommerce_email_after_order_table inside email-order-details.php.

Body:
Is it in file yourtheme/woocommerce/emails/email-order-details.php?
If it is you can create hook in your functions file.

add_action( 'woocommerce_email_after_order_table', 'your_example_function', 90, 4 );
function your_example_function( $order, $sent_to_admin, $plain_text, $email ){
    // code
}

That function your_example_function will start after action woocommerce_email_after_order_table inside email-order-details.php.


问:
Core Data Store included in App Bundle
I can't find a clear description of these steps in Apple docs...

I have a xcdatamodeld in my xcode project

At launch time, my app parses a XML (project resource) to fill the Core Data Store (SQLLite)

During lifetime of my app, I add, remove, update data of that Store

Now, I want to stop doing that heavy XML parsing process on device and directly include a Store containing the required data.

I have some questions regarding this :

Can I fill a store with a OS X app and then include this store in my XCode-iOs project ?

My store does not appear in Xcode. In fact it is created at run time. How can I add a store in the project and link it to my xcdatamodeld ?

I have read that doing so will prevent my store from being writable... I guess I have to copy it in the right place at launch time (the Core Data utility Tutorial is a great help for that). Am I right ?

Thanks for your hints. URL or other SO questions would be really appreciate !

Kheraud

答:
What you're currently doing (populating at first launch) is the "recommended" way of populating a Core Data store. Although its a bit hackish, you could however seed the on-device database as follows:

Launch your app in the simulator

Do whatever you need to do for the simulator app to populate the Core Data store

Stop the simulator app

Navigate to the simulated Documents folder (something like ~/Library/Application Support/iPhone Simulator/4.3/Applications/335567A0-760D-48AF-BC05-7F0D9BD085B6/<app-name>.app/)

Find the sqlite database (it has the name you gave it when initializing Core Data)

Copy this database to your project, and add it to be copied as a resource

Add some code to your application:didFinishLaunchingWithOptions: method so that on first launch, it copies the database from the read-only resources directory to the app's documents directory. Of course you need to do this before initializing Core Data.

Depending on exactly what you're storing in your database, you may however discover big- vs. little-endianness issues, or other incompatibilities. To make the approach a bit safer, you could dump the simulator database (splite3 databasefile .dump >dumpfile) on your Mac, then include the dumpfile in your project (as above), and slurp the dump in your app on first launch (reading it line-by-line, and handing the sql statements to the sqlite API).

Title: Core Data Store included in App Bundle


问:
a video repeatedly on idle event and restore back to the previous window on the detection of user activity
I have a requirement on WPF to play a video repeatedly on idle event and restore back to the previous window on the detection of user activity.

For this, I followed the answered https://stackoverflow.com/a/4970019/6696609 by Martin Buberl.

In XAML, I have VideoGrid and WindowGrid Grid, With the detection of idle event, I changed the visibility of each other.

Here is the source code for the illustration of described issue https://github.com/DavidSilwal/wpfvideoissue
The idle event is suppose to be occurred at 5 sec. When you click on button, idle event occurred at the 10 sec.

It works perfectly fine except

For the first idle event of the button click, VideoGrid attempts to be visible but it couldn’t be visible (it just blinks) and then every next idle event worked fine.

Feedback and suggestion to get rid of the blink issue are appreciated.

```<code>    // set UI on inactivity
    private  void OnInactivity(object sender, EventArgs e)
    {
        _inactiveMousePosition = Mouse.GetPosition(this);

        System.Windows.Application.Current.Dispatcher.BeginInvoke(new Action(() =>
          {
              if (WindowGrid.Visibility == Visibility.Visible)
              {
                  WindowGrid.Visibility = Visibility.Collapsed;
              }

              if (VideoGrid.Visibility == Visibility.Collapsed)
              {
                  WindowState = WindowState.Maximized;
                  WindowStyle = WindowStyle.None;
                  //play video
                  videoplayer.Play();
                  VideoGrid.Visibility = Visibility.Visible;

              }
          }));
    }

     private void OnActivity(object sender, PreProcessInputEventArgs e)
    {
        var inputEventArgs = e.StagingItem.Input;

        if (inputEventArgs is System.Windows.Input.MouseEventArgs || inputEventArgs is KeyboardEventArgs)
        {
            if (e.StagingItem.Input is System.Windows.Input.MouseEventArgs)
            {
                var mouseEventArgs = (System.Windows.Input.MouseEventArgs)e.StagingItem.Input;

                 // no button is pressed and the position is still the same as the application became inactive
                if (!(
                    mouseEventArgs.LeftButton == MouseButtonState.Pressed ||
                    mouseEventArgs.RightButton == MouseButtonState.Pressed ||
                    mouseEventArgs.MiddleButton == MouseButtonState.Pressed ||
                    mouseEventArgs.XButton1 == MouseButtonState.Pressed ||
                    mouseEventArgs.XButton2 == MouseButtonState.Pressed
                    //|| _inactiveMousePosition != mouseEventArgs.GetPosition(this)
                    ))
                {
                    return;
                }
            }

            // set UI on activity
            System.Windows.Application.Current.Dispatcher.BeginInvoke(new Action(() =>
              {
                  if (VideoGrid.Visibility == Visibility.Visible)
                  {
                      WindowState = WindowState.Normal;
                      WindowStyle = WindowStyle.SingleBorderWindow;
                      //stop video
                      videoplayer.Stop();
                      VideoGrid.Visibility = Visibility.Collapsed;
                  }

                  if (WindowGrid.Visibility == Visibility.Collapsed)
                  {
                      WindowGrid.Visibility = Visibility.Visible;
                  }
              }));

            _activityTimer.Stop();
            _activityTimer.Start();
        }
    }
</code>```

答:
By debugging your code, I can give you a answer, but maybe not a very satisfactory one.

I added some debug output to your code, in OnInactivity ...

```<code>private async void OnInactivity(object sender, EventArgs e)
{
    // remember mouse position
    _inactiveMousePosition = Mouse.GetPosition(this);
    // set UI on inactivity

    Debug.WriteLine ( DateTime.Now.ToString("HH:mm:ss.fffffff") + " Inactivity" ) ;

    await System.Windows.Application.Current.Dispatcher.InvokeAsync(new Action(() =>
    {
        Grid1.Visibility = Visibility.Collapsed;
        videoplayer.Play();
        Grid2.Visibility = Visibility.Visible;
    }));
}
</code>```

and in OnActivity ...

```<code>private async void OnActivity(object sender, PreProcessInputEventArgs e)
{
    var inputEventArgs = e.StagingItem.Input;

    if (inputEventArgs is System.Windows.Input.MouseEventArgs || inputEventArgs is KeyboardEventArgs)
    {
        if (e.StagingItem.Input is System.Windows.Input.MouseEventArgs)
        {
            var mouseEventArgs = (System.Windows.Input.MouseEventArgs)e.StagingItem.Input;

            if (!(
                mouseEventArgs.LeftButton == MouseButtonState.Pressed ||
                mouseEventArgs.RightButton == MouseButtonState.Pressed ||
                mouseEventArgs.MiddleButton == MouseButtonState.Pressed ||
                mouseEventArgs.XButton1 == MouseButtonState.Pressed ||
                mouseEventArgs.XButton2 == MouseButtonState.Pressed
                || _inactiveMousePosition != mouseEventArgs.GetPosition(this)
                ))
            {
                return;
            }
        }

        Debug.WriteLine ( DateTime.Now.ToString("HH:mm:ss.fffffff") + " Activity " + inputEventArgs.RoutedEvent.ToString() ) ;

        // set UI on activity
        await System.Windows.Application.Current.Dispatcher.InvokeAsync(new Action(() =>
        {
            videoplayer.Stop();
            Grid1.Visibility = Visibility.Visible;

            Grid2.Visibility = Visibility.Hidden;
        }));

        _activityTimer.Stop();
        _activityTimer.Start();
    }
}
</code>```

Here is a bit of the output after pressing the button:

```<code>23:45:31.0583181 Activity Mouse.MouseMove
23:45:31.0643177 Activity Mouse.QueryCursor
23:45:31.0653178 Activity Mouse.PreviewMouseMove
23:45:31.0663188 Activity Mouse.MouseMove
23:45:31.0723180 Activity Mouse.QueryCursor
23:45:31.0753176 Activity Mouse.PreviewMouseMove
23:45:31.0763193 Activity Mouse.MouseMove
23:45:36.0722537 Inactivity
23:45:36.0752537 Activity Keyboard.PreviewGotKeyboardFocus
23:45:36.0782576 Activity Keyboard.PreviewKeyboardInputProviderAcquireFocus
23:45:36.0802536 Activity Keyboard.KeyboardInputProviderAcquireFocus
23:45:36.0832529 Activity Keyboard.LostKeyboardFocus
23:45:36.0842549 Activity Keyboard.GotKeyboardFocus
23:45:41.1041883 Inactivity
23:45:42.4981698 Activity Mouse.QueryCursor
23:45:42.5001740 Activity Mouse.PreviewMouseMove
23:45:42.5031736 Activity Mouse.MouseMove
23:45:42.5071741 Activity Mouse.QueryCursor
23:45:42.5091736 Activity Mouse.PreviewMouseMove
23:45:42.5111735 Activity Mouse.MouseMove
</code>```

After 5 seconds of inactivity, it tries to start the video, but immediately causes some events related to the changing focus.

I guess that means that clicking on the button gives the button the focus. Starting the video causes it to lose the focus, generating some events.

I was able to fix the problem by filtering out these events. This is my modified version of the OnActivity function, in which I filter out these events by name:

```<code>private async void OnActivity(object sender, PreProcessInputEventArgs e)
{
    var inputEventArgs = e.StagingItem.Input;

    switch ( inputEventArgs.RoutedEvent.Name )
    {
        case "PreviewGotKeyboardFocus":
        case "PreviewKeyboardInputProviderAcquireFocus":
        case "KeyboardInputProviderAcquireFocus":
        case "LostKeyboardFocus":
        case "GotKeyboardFocus":
            return ;
    }

    if (inputEventArgs is System.Windows.Input.MouseEventArgs || inputEventArgs is KeyboardEventArgs)
    {
        if (e.StagingItem.Input is System.Windows.Input.MouseEventArgs)
        {
            var mouseEventArgs = (System.Windows.Input.MouseEventArgs)e.StagingItem.Input;

            if (!(
                mouseEventArgs.LeftButton == MouseButtonState.Pressed ||
                mouseEventArgs.RightButton == MouseButtonState.Pressed ||
                mouseEventArgs.MiddleButton == MouseButtonState.Pressed ||
                mouseEventArgs.XButton1 == MouseButtonState.Pressed ||
                mouseEventArgs.XButton2 == MouseButtonState.Pressed
                || _inactiveMousePosition != mouseEventArgs.GetPosition(this)
                ))
            {
                return;
            }
        }

        // set UI on activity
        await System.Windows.Application.Current.Dispatcher.InvokeAsync(new Action(() =>
        {
            videoplayer.Stop();
            Grid1.Visibility = Visibility.Visible;

            Grid2.Visibility = Visibility.Hidden;
        }));

        _activityTimer.Stop();
        _activityTimer.Start();
    }
}
</code>```

I do not know if there are other events which you should filter out, and I do not know whether filtering by the event name is the best way to do it.

Body:
I have a requirement on WPF to play a video repeatedly on idle event and restore back to the previous window on the detection of user activity.

For this, I followed the answered https://stackoverflow.com/a/4970019/6696609 by Martin Buberl.

In XAML, I have VideoGrid and WindowGrid Grid, With the detection of idle event, I changed the visibility of each other.

Here is the source code for the illustration of described issue https://github.com/DavidSilwal/wpfvideoissue
The idle event is suppose to be occurred at 5 sec. When you click on button, idle event occurred at the 10 sec.

It works perfectly fine except

For the first idle event of the button click, VideoGrid attempts to be visible but it couldn’t be visible (it just blinks) and then every next idle event worked fine.

Feedback and suggestion to get rid of the blink issue are appreciated.

    // set UI on inactivity
    private  void OnInactivity(object sender, EventArgs e)
    {
        _inactiveMousePosition = Mouse.GetPosition(this);

        System.Windows.Application.Current.Dispatcher.BeginInvoke(new Action(() =>
          {
              if (WindowGrid.Visibility == Visibility.Visible)
              {
                  WindowGrid.Visibility = Visibility.Collapsed;
              }

              if (VideoGrid.Visibility == Visibility.Collapsed)
              {
                  WindowState = WindowState.Maximized;
                  WindowStyle = WindowStyle.None;
                  //play video
                  videoplayer.Play();
                  VideoGrid.Visibility = Visibility.Visible;

              }
          }));
    }

     private void OnActivity(object sender, PreProcessInputEventArgs e)
    {
        var inputEventArgs = e.StagingItem.Input;

        if (inputEventArgs is System.Windows.Input.MouseEventArgs || inputEventArgs is KeyboardEventArgs)
        {
            if (e.StagingItem.Input is System.Windows.Input.MouseEventArgs)
            {
                var mouseEventArgs = (System.Windows.Input.MouseEventArgs)e.StagingItem.Input;

                 // no button is pressed and the position is still the same as the application became inactive
                if (!(
                    mouseEventArgs.LeftButton == MouseButtonState.Pressed ||
                    mouseEventArgs.RightButton == MouseButtonState.Pressed ||
                    mouseEventArgs.MiddleButton == MouseButtonState.Pressed ||
                    mouseEventArgs.XButton1 == MouseButtonState.Pressed ||
                    mouseEventArgs.XButton2 == MouseButtonState.Pressed
                    //|| _inactiveMousePosition != mouseEventArgs.GetPosition(this)
                    ))
                {
                    return;
                }
            }

            // set UI on activity
            System.Windows.Application.Current.Dispatcher.BeginInvoke(new Action(() =>
              {
                  if (VideoGrid.Visibility == Visibility.Visible)
                  {
                      WindowState = WindowState.Normal;
                      WindowStyle = WindowStyle.SingleBorderWindow;
                      //stop video
                      videoplayer.Stop();
                      VideoGrid.Visibility = Visibility.Collapsed;
                  }

                  if (WindowGrid.Visibility == Visibility.Collapsed)
                  {
                      WindowGrid.Visibility = Visibility.Visible;
                  }
              }));

            _activityTimer.Stop();
            _activityTimer.Start();
        }
    }

Body:
By debugging your code, I can give you a answer, but maybe not a very satisfactory one.

I added some debug output to your code, in OnInactivity ...

private async void OnInactivity(object sender, EventArgs e)
{
    // remember mouse position
    _inactiveMousePosition = Mouse.GetPosition(this);
    // set UI on inactivity

    Debug.WriteLine ( DateTime.Now.ToString("HH:mm:ss.fffffff") + " Inactivity" ) ;

    await System.Windows.Application.Current.Dispatcher.InvokeAsync(new Action(() =>
    {
        Grid1.Visibility = Visibility.Collapsed;
        videoplayer.Play();
        Grid2.Visibility = Visibility.Visible;
    }));
}

and in OnActivity ...

private async void OnActivity(object sender, PreProcessInputEventArgs e)
{
    var inputEventArgs = e.StagingItem.Input;

    if (inputEventArgs is System.Windows.Input.MouseEventArgs || inputEventArgs is KeyboardEventArgs)
    {
        if (e.StagingItem.Input is System.Windows.Input.MouseEventArgs)
        {
            var mouseEventArgs = (System.Windows.Input.MouseEventArgs)e.StagingItem.Input;

            if (!(
                mouseEventArgs.LeftButton == MouseButtonState.Pressed ||
                mouseEventArgs.RightButton == MouseButtonState.Pressed ||
                mouseEventArgs.MiddleButton == MouseButtonState.Pressed ||
                mouseEventArgs.XButton1 == MouseButtonState.Pressed ||
                mouseEventArgs.XButton2 == MouseButtonState.Pressed
                || _inactiveMousePosition != mouseEventArgs.GetPosition(this)
                ))
            {
                return;
            }
        }

        Debug.WriteLine ( DateTime.Now.ToString("HH:mm:ss.fffffff") + " Activity " + inputEventArgs.RoutedEvent.ToString() ) ;

        // set UI on activity
        await System.Windows.Application.Current.Dispatcher.InvokeAsync(new Action(() =>
        {
            videoplayer.Stop();
            Grid1.Visibility = Visibility.Visible;

            Grid2.Visibility = Visibility.Hidden;
        }));

        _activityTimer.Stop();
        _activityTimer.Start();
    }
}

Here is a bit of the output after pressing the button:

23:45:31.0583181 Activity Mouse.MouseMove
23:45:31.0643177 Activity Mouse.QueryCursor
23:45:31.0653178 Activity Mouse.PreviewMouseMove
23:45:31.0663188 Activity Mouse.MouseMove
23:45:31.0723180 Activity Mouse.QueryCursor
23:45:31.0753176 Activity Mouse.PreviewMouseMove
23:45:31.0763193 Activity Mouse.MouseMove
23:45:36.0722537 Inactivity
23:45:36.0752537 Activity Keyboard.PreviewGotKeyboardFocus
23:45:36.0782576 Activity Keyboard.PreviewKeyboardInputProviderAcquireFocus
23:45:36.0802536 Activity Keyboard.KeyboardInputProviderAcquireFocus
23:45:36.0832529 Activity Keyboard.LostKeyboardFocus
23:45:36.0842549 Activity Keyboard.GotKeyboardFocus
23:45:41.1041883 Inactivity
23:45:42.4981698 Activity Mouse.QueryCursor
23:45:42.5001740 Activity Mouse.PreviewMouseMove
23:45:42.5031736 Activity Mouse.MouseMove
23:45:42.5071741 Activity Mouse.QueryCursor
23:45:42.5091736 Activity Mouse.PreviewMouseMove
23:45:42.5111735 Activity Mouse.MouseMove

After 5 seconds of inactivity, it tries to start the video, but immediately causes some events related to the changing focus.

I guess that means that clicking on the button gives the button the focus. Starting the video causes it to lose the focus, generating some events.

I was able to fix the problem by filtering out these events. This is my modified version of the OnActivity function, in which I filter out these events by name:

private async void OnActivity(object sender, PreProcessInputEventArgs e)
{
    var inputEventArgs = e.StagingItem.Input;

    switch ( inputEventArgs.RoutedEvent.Name )
    {
        case "PreviewGotKeyboardFocus":
        case "PreviewKeyboardInputProviderAcquireFocus":
        case "KeyboardInputProviderAcquireFocus":
        case "LostKeyboardFocus":
        case "GotKeyboardFocus":
            return ;
    }

    if (inputEventArgs is System.Windows.Input.MouseEventArgs || inputEventArgs is KeyboardEventArgs)
    {
        if (e.StagingItem.Input is System.Windows.Input.MouseEventArgs)
        {
            var mouseEventArgs = (System.Windows.Input.MouseEventArgs)e.StagingItem.Input;

            if (!(
                mouseEventArgs.LeftButton == MouseButtonState.Pressed ||
                mouseEventArgs.RightButton == MouseButtonState.Pressed ||
                mouseEventArgs.MiddleButton == MouseButtonState.Pressed ||
                mouseEventArgs.XButton1 == MouseButtonState.Pressed ||
                mouseEventArgs.XButton2 == MouseButtonState.Pressed
                || _inactiveMousePosition != mouseEventArgs.GetPosition(this)
                ))
            {
                return;
            }
        }

        // set UI on activity
        await System.Windows.Application.Current.Dispatcher.InvokeAsync(new Action(() =>
        {
            videoplayer.Stop();
            Grid1.Visibility = Visibility.Visible;

            Grid2.Visibility = Visibility.Hidden;
        }));

        _activityTimer.Stop();
        _activityTimer.Start();
    }
}

I do not know if there are other events which you should filter out, and I do not know whether filtering by the event name is the best way to do it.


问:
Why do we need to pass the ViewBag of SelectList in HttpPost Action too?
I have select-list items that are stored in a ViewBag. I don't understand why we should declare this ViewBag in both, HttpGet and HttpPost actions?

If we don't declare it again in HttpPost action, the validation will not work and we will get exception. But how does this happen technically?

Actions:

```<code>    public ActionResult New()
    {
        ViewBag.Categories = new SelectList(db.Categories.ToList(),"Id", "Name");
        return View();

    }

    [HttpPost]
    public ActionResult New(Article article)
    {
        ViewBag.Categories = new SelectList(db.Categories.ToList(), "Id", "Name");
        if(ModelState.IsValid)
        {
            string FullName = HttpContext.GetOwinContext()
               .GetUserManager<ApplicationUserManager>()
               .FindById(User.Identity.GetUserId()).FullName;

            article.AuthorName = FullName;
            article.UserId = User.Identity.GetUserId();
            db.Aricles.Add(article);
            db.SaveChanges();
            return RedirectToAction("All");

        }
        return View();
    }
</code>```

List:

```<code>@Html.DropDownListFor(m => m.CategoryId, (IEnumerable<SelectListItem>)ViewBag.Categories, "Select Category", new { @class = "form-control" })
</code>```

The raised exception when I delete the ViewBag from HttpPost Action. I wonder why that
key = CategoryId? how does this key work?

Screenshot :

答:
You may be overthinking it.  Consider it simply...

Both actions return the same view:

```<code>public ActionResult New()
{
    //...
    return View();
}
</code>```

And that view uses a value from the ViewBag:

```<code>(IEnumerable<SelectListItem>)ViewBag.Categories
</code>```

In order for the view to use that value, that value has to be in the ViewBag.  So any action which returns that view will need to populate that value.  Which is why there's an error when you don't populate that value.  The error is telling you that you're trying to use a ViewBag value that doesn't exist.

Body:
I have select-list items that are stored in a ViewBag. I don't understand why we should declare this ViewBag in both, HttpGet and HttpPost actions?

If we don't declare it again in HttpPost action, the validation will not work and we will get exception. But how does this happen technically?

Actions:

    public ActionResult New()
    {
        ViewBag.Categories = new SelectList(db.Categories.ToList(),"Id", "Name");
        return View();

    }

    [HttpPost]
    public ActionResult New(Article article)
    {
        ViewBag.Categories = new SelectList(db.Categories.ToList(), "Id", "Name");
        if(ModelState.IsValid)
        {
            string FullName = HttpContext.GetOwinContext()
               .GetUserManager<ApplicationUserManager>()
               .FindById(User.Identity.GetUserId()).FullName;

            article.AuthorName = FullName;
            article.UserId = User.Identity.GetUserId();
            db.Aricles.Add(article);
            db.SaveChanges();
            return RedirectToAction("All");

        }
        return View();
    }

List:

@Html.DropDownListFor(m => m.CategoryId, (IEnumerable<SelectListItem>)ViewBag.Categories, "Select Category", new { @class = "form-control" })

The raised exception when I delete the ViewBag from HttpPost Action. I wonder why that
key = CategoryId? how does this key work?

Screenshot :

Body:
You may be overthinking it.  Consider it simply...

Both actions return the same view:

public ActionResult New()
{
    //...
    return View();
}

And that view uses a value from the ViewBag:

(IEnumerable<SelectListItem>)ViewBag.Categories

In order for the view to use that value, that value has to be in the ViewBag.  So any action which returns that view will need to populate that value.  Which is why there's an error when you don't populate that value.  The error is telling you that you're trying to use a ViewBag value that doesn't exist.


问:
Expose a base class function in qml
I am trying to invoke a function declared in a base class but I am unable to invoke from QML, Here's an example of my code

R.cpp

class R
{

public:
    virtual void startGui() = 0;
    void  toggleCameraView();

};

void R::toggleCameraView(){
  //do stuff
}
```

<p><strong>G.cpp</strong></p>

<pre class="lang-cpp prettyprint-override"><code>class G : public R
{
    Q_OBJECT
public:
  void startGui();
};

void G::startGui(){

  QQmlContext *ctxt = engine.rootContext();
  ctxt->setContextProperty("g", this);
}
</code>```

main.qml

```<code>function toggleCameraView(){
    g.toggleCameraView()
}
</code>```

This is giving me the error:

```<code>TypeError: Property 'toggleCameraView' of object G(0x2838a8) is not a function
</code>```

答:
Because you have not provided an MCVE I will not point out the cause of the error regarding your code. Instead I will show a workable example.

If you want a method to be accessible from QML this has to be a slot or Q_INVOKABLE, I will use this last method in my example:

main.cpp

#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include <QDebug>

class R: public QObject
{
    Q_OBJECT
public:
    using QObject::QObject;
    virtual void startGui() = 0;
    Q_INVOKABLE void  toggleCameraView();
};

void R::toggleCameraView()
{
    qDebug() << __FUNCTION__;
}

class G: public R
{
public:
    G(QObject *parent=nullptr): R(parent){
        startGui();
        const QUrl url(QStringLiteral("qrc:/main.qml"));
        engine.load(url);
    }
    void startGui() override;
private:
    QQmlApplicationEngine engine;
};

void G::startGui()
{
    QQmlContext *ctxt = engine.rootContext();
    ctxt->setContextProperty("g", this);
}

int main(int argc, char *argv[])
{
    QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);

    QGuiApplication app(argc, argv);
    G g;

    return app.exec();
}

#include "main.moc"
```

<p>main.qml</p>

```import QtQuick 2.12
import QtQuick.Window 2.12

Window {
    visible: true
    width: 640
    height: 480
    title: qsTr("Hello World")
    Component.onCompleted: g.toggleCameraView()
}
```

<p>Output:</p>

```toggleCameraView
```

Title: Expose a base class function in qml

Body:
I am trying to invoke a function declared in a base class but I am unable to invoke from QML, Here's an example of my code

R.cpp

class R
{

public:
    virtual void startGui() = 0;
    void  toggleCameraView();

};

void R::toggleCameraView(){
  //do stuff
}

G.cpp

class G : public R
{
    Q_OBJECT
public:
  void startGui();
};

void G::startGui(){

  QQmlContext *ctxt = engine.rootContext();
  ctxt->setContextProperty("g", this);
}

main.qml

function toggleCameraView(){
    g.toggleCameraView()
}

This is giving me the error:

TypeError: Property 'toggleCameraView' of object G(0x2838a8) is not a function

Body:
Because you have not provided an MCVE I will not point out the cause of the error regarding your code. Instead I will show a workable example.

If you want a method to be accessible from QML this has to be a slot or Q_INVOKABLE, I will use this last method in my example:

main.cpp

#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include <QDebug>

class R: public QObject
{
    Q_OBJECT
public:
    using QObject::QObject;
    virtual void startGui() = 0;
    Q_INVOKABLE void  toggleCameraView();
};

void R::toggleCameraView()
{
    qDebug() << __FUNCTION__;
}

class G: public R
{
public:
    G(QObject *parent=nullptr): R(parent){
        startGui();
        const QUrl url(QStringLiteral("qrc:/main.qml"));
        engine.load(url);
    }
    void startGui() override;
private:
    QQmlApplicationEngine engine;
};

void G::startGui()
{
    QQmlContext *ctxt = engine.rootContext();
    ctxt->setContextProperty("g", this);
}

int main(int argc, char *argv[])
{
    QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);

    QGuiApplication app(argc, argv);
    G g;

    return app.exec();
}

#include "main.moc"

main.qml

import QtQuick 2.12
import QtQuick.Window 2.12

Window {
    visible: true
    width: 640
    height: 480
    title: qsTr("Hello World")
    Component.onCompleted: g.toggleCameraView()
}

Output:

toggleCameraView


问:
how to compute correlation between two samples
I'm trying to compute the correlation between two samples (rows) in DataFrame type. I've found some codes that compute the correlation between features(columns), eventually, it converts the matrix to sorted List, and then remove correlation with itself. which I want the same thing for samples.

correlations_all = train_df[features].corr().abs().unstack().sort_values(kind="quicksort").reset_index()

correlations_all = correlations_all[correlations_all['level_0'] != correlations_all['level_1']]

output:
level_0        level_1        0
var_0          var_1          0.50
var_0          var_4          0.45
var_10         var_4          0.4
```

so how to do this in python?

答:
To sum your answer is

```<code>pd.concat([df,df2],axis=1).T.corr().drop(range(0,df.shape[1]),axis=1)[0:df.shape[1]+1]
</code>```

Detailed explonation:

Create a df

```<code>df = pd.DataFrame(np.random.randint(0, high=100, size=(10, 5)),columns=list('abcde'))
df2 = pd.DataFrame(np.random.randint(0, high=100, size=(10, 5)),columns=list('fghjk'))
</code>```

Output:

```<code>>>> df
a   b   c   d   e
0  47  68  60   8  27
1  52  36  50   0  46
2  21  53  55  43   0
3  32  63  42  37  38
4  91  95  28  81  55
5  68  14  16   5  27
6  51   2  73   8  49
7   2  83  54  77  61
8  44  89  87  93  42
9  75  50  78  31  80

>>> df2
    f   g   h   j   k
0  40  62  68   2  24
1  55   9  64  37  39
2  18   5  11  14  79
3  36  14  39  11  66
4  63  95  87  49  81
5  29  20  76  32  90
6  19  48  13   0  81
7  79  55  32   8  17
8  93   3  33   7  53
9  85  30  50  14   2
corr()
</code>```

There is a corrwith() function that The first one computes correlation with another dataframe.

corr() is more useful in your situation. But corr() computes it with itself. Because of that first we concat 2 df.

Output:

```<code>>>>pd.concat([df,df2],axis=1)
    a   b   c   d   e   f   g   h   j   k
0  47  68  60   8  27  40  62  68   2  24
1  52  36  50   0  46  55   9  64  37  39
2  21  53  55  43   0  18   5  11  14  79
3  32  63  42  37  38  36  14  39  11  66
4  91  95  28  81  55  63  95  87  49  81
5  68  14  16   5  27  29  20  76  32  90
6  51   2  73   8  49  19  48  13   0  81
7   2  83  54  77  61  79  55  32   8  17
8  44  89  87  93  42  93   3  33   7  53
9  75  50  78  31  80  85  30  50  14   2
</code>```

corr() method computes correlation between columns. To compute between rows first take transpose and drop the parts of df that you don't want to see.

```<code>pd.concat([df,df2],axis=1).T.corr().drop(range(0,df.shape[1]),axis=1)[0:df.shape[1]+1]
</code>```

Output:

```<code>pd.concat([df,df2],axis=1).T.corr().drop(range(0,df.shape[1]),axis=1)[0:df.shape[1]]
              5         6         7         8         9
    0  0.154824  0.161153 -0.006838 -0.301014 -0.125625
    1 -0.405248 -0.344024  0.413258  0.284815  0.367698
    2  0.146049 -0.390763  0.165186 -0.358735 -0.245411
    3 -0.018887 -0.084056 -0.239326  0.061516  0.488869
    4 -0.338686  0.256093  0.455395  0.741626 -0.130878
</code>```

To extract single row

```<code>def compute_corr(df,i):
    print(f"Correlation between {i}'th sample and other samples")
    return df.T.corr().loc[i]
</code>```

Output:

```<code>x= pd.concat([df,df2],axis=1).T.corr().drop(range(0,6),axis=1)
compute_corr(x,0)
Correlation between 0'th sample and other samples
0    1.000000
1    0.590134
2   -0.983648
3   -0.894758
4   -0.463191
Name: 0, dtype: float64
</code>```

I hope this time that code is your need.

Body:
I'm trying to compute the correlation between two samples (rows) in DataFrame type. I've found some codes that compute the correlation between features(columns), eventually, it converts the matrix to sorted List, and then remove correlation with itself. which I want the same thing for samples.

correlations_all = train_df[features].corr().abs().unstack().sort_values(kind="quicksort").reset_index()

correlations_all = correlations_all[correlations_all['level_0'] != correlations_all['level_1']]

output:
level_0        level_1        0
var_0          var_1          0.50
var_0          var_4          0.45
var_10         var_4          0.4

so how to do this in python?

Body:
To sum your answer is

pd.concat([df,df2],axis=1).T.corr().drop(range(0,df.shape[1]),axis=1)[0:df.shape[1]+1]

Detailed explonation:

Create a df

df = pd.DataFrame(np.random.randint(0, high=100, size=(10, 5)),columns=list('abcde'))
df2 = pd.DataFrame(np.random.randint(0, high=100, size=(10, 5)),columns=list('fghjk'))

Output:

>>> df
a   b   c   d   e
0  47  68  60   8  27
1  52  36  50   0  46
2  21  53  55  43   0
3  32  63  42  37  38
4  91  95  28  81  55
5  68  14  16   5  27
6  51   2  73   8  49
7   2  83  54  77  61
8  44  89  87  93  42
9  75  50  78  31  80

>>> df2
    f   g   h   j   k
0  40  62  68   2  24
1  55   9  64  37  39
2  18   5  11  14  79
3  36  14  39  11  66
4  63  95  87  49  81
5  29  20  76  32  90
6  19  48  13   0  81
7  79  55  32   8  17
8  93   3  33   7  53
9  85  30  50  14   2
corr()

There is a corrwith() function that The first one computes correlation with another dataframe.

corr() is more useful in your situation. But corr() computes it with itself. Because of that first we concat 2 df.

Output:

>>>pd.concat([df,df2],axis=1)
    a   b   c   d   e   f   g   h   j   k
0  47  68  60   8  27  40  62  68   2  24
1  52  36  50   0  46  55   9  64  37  39
2  21  53  55  43   0  18   5  11  14  79
3  32  63  42  37  38  36  14  39  11  66
4  91  95  28  81  55  63  95  87  49  81
5  68  14  16   5  27  29  20  76  32  90
6  51   2  73   8  49  19  48  13   0  81
7   2  83  54  77  61  79  55  32   8  17
8  44  89  87  93  42  93   3  33   7  53
9  75  50  78  31  80  85  30  50  14   2

corr() method computes correlation between columns. To compute between rows first take transpose and drop the parts of df that you don't want to see.

pd.concat([df,df2],axis=1).T.corr().drop(range(0,df.shape[1]),axis=1)[0:df.shape[1]+1]

Output:

pd.concat([df,df2],axis=1).T.corr().drop(range(0,df.shape[1]),axis=1)[0:df.shape[1]]
              5         6         7         8         9
    0  0.154824  0.161153 -0.006838 -0.301014 -0.125625
    1 -0.405248 -0.344024  0.413258  0.284815  0.367698
    2  0.146049 -0.390763  0.165186 -0.358735 -0.245411
    3 -0.018887 -0.084056 -0.239326  0.061516  0.488869
    4 -0.338686  0.256093  0.455395  0.741626 -0.130878

To extract single row

def compute_corr(df,i):
    print(f"Correlation between {i}'th sample and other samples")
    return df.T.corr().loc[i]

Output:

x= pd.concat([df,df2],axis=1).T.corr().drop(range(0,6),axis=1)
compute_corr(x,0)
Correlation between 0'th sample and other samples
0    1.000000
1    0.590134
2   -0.983648
3   -0.894758
4   -0.463191
Name: 0, dtype: float64

I hope this time that code is your need.


问:
Reflection doesn't work for CCScene, why?
I have a sub-class of CCLayer, named MyScene.  In the App Delegate I added this code:

```<code>-(void) applicationDidEnterBackground:(UIApplication*)application {
    [[CCDirector sharedDirector] stopAnimation];

    if( [[CCDirector sharedDirector] runningScene] != nil ) {
        if( [[[CCDirector sharedDirector] runningScene] isKindOfClass:[MyScene class]] ) {
            MyScene *scene = (MyScene*) [[CCDirector sharedDirector] runningScene];
            [scene goingToBackground];
    }
}
</code>```

}

The app has a running scene, and I know it's MyScene, but isKindOfClass doesn't return YES.  Why?

答:
[[CCDirector sharedDirector] runningScene]  always returns a CCScene not a CCLayer object.
As you are comparing a CCScene with your CCLayer sub class i.e. MyScene so it always return false. Try to set the tag of your MyScene object and get that object by tag and the compare it. it will return YES

Body:
I have a sub-class of CCLayer, named MyScene.  In the App Delegate I added this code:

-(void) applicationDidEnterBackground:(UIApplication*)application {
    [[CCDirector sharedDirector] stopAnimation];

    if( [[CCDirector sharedDirector] runningScene] != nil ) {
        if( [[[CCDirector sharedDirector] runningScene] isKindOfClass:[MyScene class]] ) {
            MyScene *scene = (MyScene*) [[CCDirector sharedDirector] runningScene];
            [scene goingToBackground];
    }
}

}

The app has a running scene, and I know it's MyScene, but isKindOfClass doesn't return YES.  Why?


问:
Cannot convert lambda expression to type 'ServiceLifetime' because it is not a delegate type on Asp.net core 2.2
Why do I get this error:

Cannot convert lambda expression to type 'ServiceLifetime' because it is not a delegate type [TokenAuthWebApiCore.Server]

on this line of code:

```<code>public virtual void SetUpDataBase(IServiceCollection services)
{
    // Add framework services.
        services.AddDbContext<SecurityContext>(options =>
            options.UseSqlServer(Configuration.GetConnectionString("SecurityConnection"), sqlOptions => sqlOptions.MigrationsAssembly("TokenAuthWebApiCore.Server")));
}
</code>```

This is how I use it:

```<code>public void ConfigureServices(IServiceCollection services)
{
    services.AddSingleton(Configuration);

    services.AddMvc();

    SetUpDataBase(services);

    // services.AddDbContext<SecurityContext>(options =>
    //      options.UseSqlServer(Configuration.GetConnectionString("SecurityConnection"), sqlOptions => sqlOptions.MigrationsAssembly("TokenAuthWebApiCore.Server")));

    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}

public virtual void SetUpDataBase(IServiceCollection services)
{
    // Add framework services.
        services.AddDbContext<SecurityContext>(options =>
            options.UseSqlServer(Configuration.GetConnectionString("SecurityConnection"), sqlOptions => sqlOptions.MigrationsAssembly("TokenAuthWebApiCore.Server")));
}
</code>```

This are all my using statements

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Security;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.IdentityModel.Tokens;
using System.Text;
</code>```

I am thinking probably this is because the tutorial I am following a tutorial for a different version of .net core and I am using .net core version 2.2. Can you please show me how to fix this? Thank you.

答:
I had the same error in my project. The problem was that my context class was not derived from DbContext.</p>

```<code>public class SecurityContext : DbContext
{
}
</code>```

Body:
Why do I get this error:

Cannot convert lambda expression to type 'ServiceLifetime' because it is not a delegate type [TokenAuthWebApiCore.Server]

on this line of code:

public virtual void SetUpDataBase(IServiceCollection services)
{
    // Add framework services.
        services.AddDbContext<SecurityContext>(options =>
            options.UseSqlServer(Configuration.GetConnectionString("SecurityConnection"), sqlOptions => sqlOptions.MigrationsAssembly("TokenAuthWebApiCore.Server")));
}

This is how I use it:

public void ConfigureServices(IServiceCollection services)
{
    services.AddSingleton(Configuration);

    services.AddMvc();

    SetUpDataBase(services);

    // services.AddDbContext<SecurityContext>(options =>
    //      options.UseSqlServer(Configuration.GetConnectionString("SecurityConnection"), sqlOptions => sqlOptions.MigrationsAssembly("TokenAuthWebApiCore.Server")));

    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}

public virtual void SetUpDataBase(IServiceCollection services)
{
    // Add framework services.
        services.AddDbContext<SecurityContext>(options =>
            options.UseSqlServer(Configuration.GetConnectionString("SecurityConnection"), sqlOptions => sqlOptions.MigrationsAssembly("TokenAuthWebApiCore.Server")));
}

This are all my using statements

using System;
using System.Collections.Generic;
using System.Linq;
using System.Security;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.IdentityModel.Tokens;
using System.Text;

I am thinking probably this is because the tutorial I am following a tutorial for a different version of .net core and I am using .net core version 2.2. Can you please show me how to fix this? Thank you.

Body:
I had the same error in my project. The problem was that my context class was not derived from DbContext.

public class SecurityContext : DbContext
{
}


问:
Do I have to write a privacy policy if i'm using unity analytics or unity advertisement or facebook sdk
I have set up unity analytics and unity advertisement and Facebook SDK on my android game, I have published it several times and it got suspended two times, I don't want to risk anymore so I wanted to know if I should write a private policy telling the users why I use unity and stuff?
Thank you in advance :)</p>

答:
Yes. It's pretty clear in Facebook policies that you need a Privacy policy:

Privacy Policy

a. Provide a publicly available and easily accessible privacy policy that explains what data you are collecting and how you will use that data.


问:
Permission denied inside /var/www/html when creating a website and it's files with the apache2 server

UPDATE** The screenshot is within atom, but when I navigate to the directory using the file explorer, and right click, the option to rename or create a new folder are restricted and I cannot click on them.

I just finished setting up the LAMP stack on my fresh UBUNTU 18.04 installation. I have everything working, the default /var/www/html/index.html page from Apache2 is being served on localhost, no port forwarding or any unique domain name, i just wanna run this on my network from my computer for now.

If there is a simple way to create multiple websites and easily choose which folder to serve than that's fine, but I want to serve just one website for now.

When I go to my /var/www/html folder and try to edit the index.html file it says permission denied. What do I need to do in order to work inside this directory for the remaining time that I am building the website. I am signed in as the root user on my system.

Also, if I do change permissions to allow me to work in this directory, what does it mean for people trying to access my server if it was available to the public. (RIGHT NOW JUST ON LOCALHOST).

Lemme know if you need more info or explanation thanks!

答:
File ownership issues can be fixed at the command line by typing:

sudo chmod 777 /var/www/html -R

One caveat from
 turnkeyLinux.com:

Changing file permissions is a trade off
  (often increasing security reduces user-friendliness and/or
  usability). For security 'best practice' only the folders that require
  write access by the webserver should be owned by the webserver.
  If your webserver has write access everywhere and your server
  is compromised it makes it easier to hack your WordPress install) but
  for ease of use giving the webserver ownership should resolve all your
  issues...

This article on Understanding File Permissions was great, too.


问:
Switch statement using substring of a user's input
Objective: I am trying to ouput a message based on a user's input.

Situation: Basically a user will input a few characters like 5r (5 Red) or 8y (8 Yellow). The notation expected is a digit first and a character after but it is possible that the user doesn't follow the rule.

I used switch statements (part of the exercise) but the output doesn't give me what I expect

Code:

```<code>        String input = reader.nextLine().toLowerCase();
        String firstChar = input.substring(0,1);
        String secondChar = input.substring(1);
        String answer = "";

        switch(firstChar)
        {
            case "0":
            {
                switch(secondChar)
                {
                    case "b":
                        answer = "Zero Blue";
                    case "r":
                        answer = "Zero Red";
                    case "g":
                        answer = "Zero Green";
                    case "y":
                        answer = "Zero Yellow";
                }
            }
            case "1":
            {
                switch(secondChar)
                {
                    case "b":
                        answer = "One Blue";
                    case "r":
                        answer = "One Red";
                    case "g":
                        answer = "One Green";
                    case "y":
                        answer = "One Yellow";
                }
            }
           ... other case statements....
           default:
              answer = "not valid";
</code>```

When the user writes 0b, my output should be "Zero Blue" but currently it is displaying "not valid". Why?

答:
As @markspace mentioned you were missing a break statement. Here is a short excerpt from Java documentation on switch statements:

Each break statement terminates the enclosing switch statement. Control flow continues with the first statement following the switch block. The break statements are necessary because without them, statements in switch blocks fall through.

Also I recommend using a dedicated method and for loops for easier debugging.

The following code produces the result you want:

```<code>public static String getAnswer() {

        Scanner reader = new Scanner(System.in);
        String input = reader.nextLine().toLowerCase();
        String firstChar = input.substring(0, 1);
        String secondChar = input.substring(1);

        String[] chars = new String[] { "b", "r", "g", "y" };
        String[] answers1 = new String[] { "Zero Blue", "Zero Red", "Zero Green", "Zero Yellow" };
        String[] answers2 = new String[] { "One Blue", "One Red", "One Green", "One Yellow" };

        if ((firstChar.equals("0"))) {
            for (int i = 0; i < chars.length; i++) {
                if (secondChar.equals(chars[i])) {
                    return answers1[i];
                }
            }
        }
        else if ((firstChar.equals("1"))) {
            for (int i = 0; i < chars.length; i++) {
                if (secondChar.equals(chars[i])) {
                    return answers2[i];
                }
            }
        }
        return "not valid";
    }

    public static void main(String[] args) throws IOException {

        System.out.println(getAnswer());
    }
</code>```

EDIT: In addition to the solution above I would like to offer a more sophisticated one that involves the use of enumerators. It should make your code feel more clean and to the point as well as being more modular:

```<code>public enum Answer {

    BLUE('b',"Blue"), RED('r',"Red"),
    GREEN('g',"Green"), YELLOW('y',"Yellow");

    private static final String[] prefix = new String[] {"Zero", "One"};

    char letter;
    String name;

    Answer(char letter, String name) {
        this.letter = letter;
        this.name = name;
    }

    public static String getForInput(char input, int index) {

        if (index > prefix.length)
            return "value out of range " + index;

        for (Answer answer : Answer.values()) {
            if (input == answer.letter)
                return prefix[index] + " " + answer.name;
        }
        return "unable to find answer for input " + input;
    }
}

public static String getAnswer() {

    System.out.println("Enter your input: ");
    Scanner reader = new Scanner(System.in);
    String input = reader.nextLine().toLowerCase();
    int number = Integer.valueOf(input.substring(0, 1));
    char letter = input.substring(1).charAt(0);

    return Answer.getForInput(letter, number);

}
</code>```

Body:
Objective: I am trying to ouput a message based on a user's input.

Situation: Basically a user will input a few characters like 5r (5 Red) or 8y (8 Yellow). The notation expected is a digit first and a character after but it is possible that the user doesn't follow the rule.

I used switch statements (part of the exercise) but the output doesn't give me what I expect

Code:

        String input = reader.nextLine().toLowerCase();
        String firstChar = input.substring(0,1);
        String secondChar = input.substring(1);
        String answer = "";

        switch(firstChar)
        {
            case "0":
            {
                switch(secondChar)
                {
                    case "b":
                        answer = "Zero Blue";
                    case "r":
                        answer = "Zero Red";
                    case "g":
                        answer = "Zero Green";
                    case "y":
                        answer = "Zero Yellow";
                }
            }
            case "1":
            {
                switch(secondChar)
                {
                    case "b":
                        answer = "One Blue";
                    case "r":
                        answer = "One Red";
                    case "g":
                        answer = "One Green";
                    case "y":
                        answer = "One Yellow";
                }
            }
           ... other case statements....
           default:
              answer = "not valid";

When the user writes 0b, my output should be "Zero Blue" but currently it is displaying "not valid". Why?

Body:
As @markspace mentioned you were missing a break statement. Here is a short excerpt from Java documentation on switch statements:

Each break statement terminates the enclosing switch statement. Control flow continues with the first statement following the switch block. The break statements are necessary because without them, statements in switch blocks fall through.

Also I recommend using a dedicated method and for loops for easier debugging.

The following code produces the result you want:

public static String getAnswer() {

        Scanner reader = new Scanner(System.in);
        String input = reader.nextLine().toLowerCase();
        String firstChar = input.substring(0, 1);
        String secondChar = input.substring(1);

        String[] chars = new String[] { "b", "r", "g", "y" };
        String[] answers1 = new String[] { "Zero Blue", "Zero Red", "Zero Green", "Zero Yellow" };
        String[] answers2 = new String[] { "One Blue", "One Red", "One Green", "One Yellow" };

        if ((firstChar.equals("0"))) {
            for (int i = 0; i < chars.length; i++) {
                if (secondChar.equals(chars[i])) {
                    return answers1[i];
                }
            }
        }
        else if ((firstChar.equals("1"))) {
            for (int i = 0; i < chars.length; i++) {
                if (secondChar.equals(chars[i])) {
                    return answers2[i];
                }
            }
        }
        return "not valid";
    }

    public static void main(String[] args) throws IOException {

        System.out.println(getAnswer());
    }

EDIT: In addition to the solution above I would like to offer a more sophisticated one that involves the use of enumerators. It should make your code feel more clean and to the point as well as being more modular:

public enum Answer {

    BLUE('b',"Blue"), RED('r',"Red"),
    GREEN('g',"Green"), YELLOW('y',"Yellow");

    private static final String[] prefix = new String[] {"Zero", "One"};

    char letter;
    String name;

    Answer(char letter, String name) {
        this.letter = letter;
        this.name = name;
    }

    public static String getForInput(char input, int index) {

        if (index > prefix.length)
            return "value out of range " + index;

        for (Answer answer : Answer.values()) {
            if (input == answer.letter)
                return prefix[index] + " " + answer.name;
        }
        return "unable to find answer for input " + input;
    }
}

public static String getAnswer() {

    System.out.println("Enter your input: ");
    Scanner reader = new Scanner(System.in);
    String input = reader.nextLine().toLowerCase();
    int number = Integer.valueOf(input.substring(0, 1));
    char letter = input.substring(1).charAt(0);

    return Answer.getForInput(letter, number);

}


问:
Single Redis Instance with multiple simultaneous uses
So I know that redis is an in-memory data store, but I don't really understand that much about under the hood.

My question is, if I have three separate uses for it, such as python-socketio to enable multiple instances of the socket server, Celery to send tasks to another microservice (which would also use the same redis instance), and just a standard subscriber to listen for notifications to emit, can I use the same redis instance for all three tasks, or will I run into collisions between the different data (i.e celery misinterpreting a call to python-socketio as a task)?

答:
It depends on how your data flows, the question is not clear about how the data flows between each component and their relations.

If there's no relation or dependency between these messages, you can avoid collisions by storing your messages into different DBs in the same redis instance.

Or, in case you need to use the same DB for all of them, you can use namespaces aka prefixes for your redis keys to make sure there will be no key collisions. Here's more information about how to name keys under Redis keys section.

However this is not scalable to have one instance handling this but still it depends on how much traffic you have and what are you exactly trying to achieve.

Please leave comments in case there's anything not clear or I misunderstood your question


问:
How to store a reference in boost::variant<T> instead of copying the object?
Suppose I have a boost::variant defined as boost::variant<Point, Line, Circle> shape. Now if I make an object of the Point class, Point p and store it in shape as shape = p what I'm doing here is making a copy of p. How do I actually store a reference to p such that when I call boost::apply_visitior(visitor, shape) the visitor mutates not just the Point stored in the variant but also p itself?

答:
You can't store a reference in variant (see the std::variant reference which explicitly spells that out but boost::variant is very similar) since a reference is just another name for a variable. variant is a fancy implementation of union. In both cases the value is stored inside the union/variant. Getting your object in there might come at the cost of a copy.

For small objects I wouldn't worry about the copy. If your objects are large and you need to avoid the copy you might want to consider using pointers instead:

```<code>boost::variant<Point*, Line*, Circle*> shape;
shape s = &p;
</code>```

With pointers you might even decide to implement this using a traditional polymorphic approach rather than using variant (define an abstract class shape that Point, Line, and Circle inherit from and make s a pointer of the parent type:

```<code>shape s = &p;
</code>```

Note that the latter can be more error prone than using variant.

Body:
You can't store a reference in variant (see the std::variant reference which explicitly spells that out but boost::variant is very similar) since a reference is just another name for a variable. variant is a fancy implementation of union. In both cases the value is stored inside the union/variant. Getting your object in there might come at the cost of a copy.

For small objects I wouldn't worry about the copy. If your objects are large and you need to avoid the copy you might want to consider using pointers instead:

boost::variant<Point*, Line*, Circle*> shape;
shape s = &p;

With pointers you might even decide to implement this using a traditional polymorphic approach rather than using variant (define an abstract class shape that Point, Line, and Circle inherit from and make s a pointer of the parent type:

shape s = &p;

Note that the latter can be more error prone than using variant.