问:
Bundle splitting with Webpack 4 - duplicate vendor bundle
We have a legacy multipage application where each page has its own js file. We use Webpack 4 and now we start to use react as well. I want to separate react bundle from our own code. So each page loads its own legacy pageXJS.js file, the new pageXReact.js file, and the react.bundle.js

We have a webpack config below that works almost fine.

```<code>const path = require('path');
const webpack = require('webpack');

const jsModuleFolder = './src/main/resources/static/js/module/';

module.exports = {
    mode: 'development',
    devtool: 'inline-source-map',
    entry: {
        'pageA/pageAJS': jsModuleFolder + 'pageA/pageAJS.js',
        'pageB/pageBJS': jsModuleFolder + 'pageB/pageBJS.js',
        'pageC/pageCJS': jsModuleFolder + 'pageC/pageCJS.js',
        'pageC/PageCReact': jsModuleFolder + 'pageC/pageCReact.js',
        vendor: ['react', 'react-dom']
    },
    output: {
        filename: '[name].bundle.js',
        path: path.join(__dirname, jsModuleFolder )
    },
    optimization: {
        splitChunks: {
            chunks: 'all',
            cacheGroups: {
                vendor: {
                    chunks: 'initial',
                    test: 'vendor',
                    name: '../react/react',
                    enforce: true
                }
            },
        },
    },
};
</code>```

It generates the react.bundle.js in the react folder. However, it also generates a vendor.bundle.js file in the module folder. The vendor.bundle.js is just a webpackBoostrap file without real content. The webpackBootstrap is also part of the generated PageCReact.bundle.js so the vendor.bundle.js seems to be unnecessary. (And my site works fine without it.)

How can I prevent this file from being generated as well?

答:
It's the runtime file and is needed by webpack.

You can include the file in your entry point file like this:

```<code>optimization: {
            runtimeChunk: false // <-- set to false
</code>```

I would suggest to configure it like this:

```<code>optimization: {
        runtimeChunk: 'single', // creates a single runtime chunk for all entry points.
</code>```

Body:
We have a legacy multipage application where each page has its own js file. We use Webpack 4 and now we start to use react as well. I want to separate react bundle from our own code. So each page loads its own legacy pageXJS.js file, the new pageXReact.js file, and the react.bundle.js

We have a webpack config below that works almost fine.

const path = require('path');
const webpack = require('webpack');

const jsModuleFolder = './src/main/resources/static/js/module/';

module.exports = {
    mode: 'development',
    devtool: 'inline-source-map',
    entry: {
        'pageA/pageAJS': jsModuleFolder + 'pageA/pageAJS.js',
        'pageB/pageBJS': jsModuleFolder + 'pageB/pageBJS.js',
        'pageC/pageCJS': jsModuleFolder + 'pageC/pageCJS.js',
        'pageC/PageCReact': jsModuleFolder + 'pageC/pageCReact.js',
        vendor: ['react', 'react-dom']
    },
    output: {
        filename: '[name].bundle.js',
        path: path.join(__dirname, jsModuleFolder )
    },
    optimization: {
        splitChunks: {
            chunks: 'all',
            cacheGroups: {
                vendor: {
                    chunks: 'initial',
                    test: 'vendor',
                    name: '../react/react',
                    enforce: true
                }
            },
        },
    },
};

It generates the react.bundle.js in the react folder. However, it also generates a vendor.bundle.js file in the module folder. The vendor.bundle.js is just a webpackBoostrap file without real content. The webpackBootstrap is also part of the generated PageCReact.bundle.js so the vendor.bundle.js seems to be unnecessary. (And my site works fine without it.)

How can I prevent this file from being generated as well?

Body:
It's the runtime file and is needed by webpack.

You can include the file in your entry point file like this:

optimization: {
            runtimeChunk: false // <-- set to false

I would suggest to configure it like this:

optimization: {
        runtimeChunk: 'single', // creates a single runtime chunk for all entry points.


来源: stackexchange

问:
Python Selenium geckodriver required in path
```<code>Traceback (most recent call last):
  File "/home/ubuntu/.local/lib/python3.6/site-packages/selenium/webdriver/common/service.py", line 76, in start
    stdin=PIPE)
  File "/usr/lib/python3.6/subprocess.py", line 729, in __init__
    restore_signals, start_new_session)
  File "/usr/lib/python3.6/subprocess.py", line 1364, in _execute_child
    raise child_exception_type(errno_num, err_msg, err_filename)
FileNotFoundError: [Errno 2] No such file or directory: '/home/ubuntu/bin/python/DLX/geckodriver': '/home/ubuntu/bin/python/DLX/geckodriver'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "test.py", line 25, in <module>
    driver = webdriver.Firefox(executable_path=geckoPath,options=options)
  File "/home/ubuntu/.local/lib/python3.6/site-packages/selenium/webdriver/firefox/webdriver.py", line 164, in __init__
    self.service.start()
  File "/home/ubuntu/.local/lib/python3.6/site-packages/selenium/webdriver/common/service.py", line 83, in start
    os.path.basename(self.path), self.start_error_message)
selenium.common.exceptions.WebDriverException: Message: 'geckodriver' executable needs to be in PATH.
</code>```

The above is the error I am getting while trying to use geckodriver and selenium. Geckodriver is in the path /home/ubuntu/bin/python/DLX/, that path has been added to the PATH var and I can see it when using echo $PATH. Below is the code I'm trying to get running.

```<code>from selenium import webdriver
from selenium.webdriver.firefox.firefox_binary import FirefoxBinary
from selenium.webdriver.firefox.options import Options
from selenium.webdriver.common.proxy import Proxy, ProxyType
from selenium.webdriver import DesiredCapabilities
from sys import platform

# setting browser to be heaadless
options = Options()
options.add_argument("--headless")
#Telling it where to find the required file
currentDir = os.path.dirname(os.path.realpath(__file__))
geckoPath = os.path.realpath(os.path.join(currentDir,'geckodriver'))
print(geckoPath)
binary = FirefoxBinary(geckoPath)
driver = webdriver.Firefox(executable_path=geckoPath,options=options)
</code>```

I've looked at other posts, tried their fixes and I've still got the issue. Running it on RPI3b+ Ubuntu server if that helps.
Selenium Ver=3.141.0
geckodriver ver=v0.23.0

Edit:
PATH is as follows
/home/ubuntu/.cargo/bin:/home/ubuntu/.local/bin:/home/ubuntu/bin:/home/ubuntu/.cargo/bin:/home/ubuntu/.local/bin:/home/ubuntu/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin:/home/ubuntu/bin/python/DLX

答:
It would be fine if you create once driver folder in you project and place geckodriver there and provide path as mentioned below.

Lets say folder name is drivers

```<code>firefox_driver = "/drivers/geckodriver"
driver = webdriver.Firefox(executable_path=firefox_driver,options=options)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Traceback (most recent call last):
  File "/home/ubuntu/.local/lib/python3.6/site-packages/selenium/webdriver/common/service.py", line 76, in start
    stdin=PIPE)
  File "/usr/lib/python3.6/subprocess.py", line 729, in __init__
    restore_signals, start_new_session)
  File "/usr/lib/python3.6/subprocess.py", line 1364, in _execute_child
    raise child_exception_type(errno_num, err_msg, err_filename)
FileNotFoundError: [Errno 2] No such file or directory: '/home/ubuntu/bin/python/DLX/geckodriver': '/home/ubuntu/bin/python/DLX/geckodriver'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "test.py", line 25, in <module>
    driver = webdriver.Firefox(executable_path=geckoPath,options=options)
  File "/home/ubuntu/.local/lib/python3.6/site-packages/selenium/webdriver/firefox/webdriver.py", line 164, in __init__
    self.service.start()
  File "/home/ubuntu/.local/lib/python3.6/site-packages/selenium/webdriver/common/service.py", line 83, in start
    os.path.basename(self.path), self.start_error_message)
selenium.common.exceptions.WebDriverException: Message: 'geckodriver' executable needs to be in PATH.

The above is the error I am getting while trying to use geckodriver and selenium. Geckodriver is in the path /home/ubuntu/bin/python/DLX/, that path has been added to the PATH var and I can see it when using echo $PATH. Below is the code I'm trying to get running.

from selenium import webdriver
from selenium.webdriver.firefox.firefox_binary import FirefoxBinary
from selenium.webdriver.firefox.options import Options
from selenium.webdriver.common.proxy import Proxy, ProxyType
from selenium.webdriver import DesiredCapabilities
from sys import platform

# setting browser to be heaadless
options = Options()
options.add_argument("--headless")
#Telling it where to find the required file
currentDir = os.path.dirname(os.path.realpath(__file__))
geckoPath = os.path.realpath(os.path.join(currentDir,'geckodriver'))
print(geckoPath)
binary = FirefoxBinary(geckoPath)
driver = webdriver.Firefox(executable_path=geckoPath,options=options)

I've looked at other posts, tried their fixes and I've still got the issue. Running it on RPI3b+ Ubuntu server if that helps.
Selenium Ver=3.141.0
geckodriver ver=v0.23.0

Edit:
PATH is as follows
/home/ubuntu/.cargo/bin:/home/ubuntu/.local/bin:/home/ubuntu/bin:/home/ubuntu/.cargo/bin:/home/ubuntu/.local/bin:/home/ubuntu/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin:/home/ubuntu/bin/python/DLX

Body:
It would be fine if you create once driver folder in you project and place geckodriver there and provide path as mentioned below.

Lets say folder name is drivers

firefox_driver = "/drivers/geckodriver"
driver = webdriver.Firefox(executable_path=firefox_driver,options=options)


问:
Sum of two variables in RobotFramework
I have two variables:

```<code>${calculatedTotalPrice} = 42,42

${productPrice1} = 43,15
</code>```

I executed

```<code>${calculatedTotalPrice}     Evaluate ${calculatedTotalPrice}+${productPrice1}
</code>```

I got

```<code>42,85,15
</code>```

How can I resolve it?

答:
the simplest way to add two variables in robotframework without the need to call keywords:
you declare it in the VARIABLES  sections

```<code>*** Variables ***
${A1}               ${1}
${A2}               ${2}
${A3}               ${${A1}+${A2}}
</code>```

then the output of ${A3} is: 3

ContentLicense: CC BY-SA 3.0

Title: Sum of two variables in RobotFramework

Body:
I have two variables:

${calculatedTotalPrice} = 42,42

${productPrice1} = 43,15

I executed

${calculatedTotalPrice}     Evaluate ${calculatedTotalPrice}+${productPrice1}

I got

42,85,15

How can I resolve it?

Body:
the simplest way to add two variables in robotframework without the need to call keywords:
you declare it in the VARIABLES  sections

*** Variables ***
${A1}               ${1}
${A2}               ${2}
${A3}               ${${A1}+${A2}}

then the output of ${A3} is: 3


问:
Laravel package custom migration command
I would like to make a package which uses a custom stub for creating migrations needed for my package. More precisely, running the command should make pivot tables for models which have a specific trait present.

If I make a "normal" command, I can register it within my service provider:

```<code>public function boot()
{
    if ($this->app->runningInConsole()) {

        $this->commands([
            MakeContainerMigration::class,
        ]);
    }
}
</code>```

However in this case I wanted to reuse Laravel's coding and save myself the trouble to reinvent the wheel. So my command looks like this:

```<code>class MakeContainerMigration extends MigrateMakeCommand
{
    protected $name = 'custom:make-container';

    protected $description = '...';
}
</code>```

Since MigrateMakeCommand doesn't have stubs defined, but rather it's dependency MigrationCreator, I needed to find a way to provide custom stub path to it without disrupting "regular" migration stubs.

I tried doing something like this but failed:

```<code>public function register()
{
    $this->registerCreator();
    $this->registerMigrateMakeCommand();

    if ($this->app->runningInConsole()) {

        $this->commands([
            //MakeContainerMigration::class,
            'custom.command.migrate.make'
        ]);
    }
}

protected function registerCreator()
{
    $this->app->singleton('custom.migration.creator', function ($app) {
        return new MigrationCreator($app['files'], __DIR__ . '/stubs');
    });
}

protected function registerMigrateMakeCommand()
{
    $this->app->singleton('custom.command.migrate.make', function ($app) {
        $creator = $app['custom.migration.creator'];
        $composer = $app['composer'];

        return new MakeContainerMigration($creator, $composer);
    });
}
</code>```

I'm aware that registering the command shouldn't function like this as I am simply registering singletons to Laravel app instance, but I have no idea how to register it through the class while ensuring that the right version of MigrationCreator will be injected. I'm kinda stuck here, is there a way to do it?

答:
Turns out everything is working, I just needed to replace

```<code>protected $name = 'custom:make-container';
</code>```

with

```<code>protected $signature = 'custom:make-container';
</code>```

Body:
I would like to make a package which uses a custom stub for creating migrations needed for my package. More precisely, running the command should make pivot tables for models which have a specific trait present.

If I make a "normal" command, I can register it within my service provider:

public function boot()
{
    if ($this->app->runningInConsole()) {

        $this->commands([
            MakeContainerMigration::class,
        ]);
    }
}

However in this case I wanted to reuse Laravel's coding and save myself the trouble to reinvent the wheel. So my command looks like this:

class MakeContainerMigration extends MigrateMakeCommand
{
    protected $name = 'custom:make-container';

    protected $description = '...';
}

Since MigrateMakeCommand doesn't have stubs defined, but rather it's dependency MigrationCreator, I needed to find a way to provide custom stub path to it without disrupting "regular" migration stubs.

I tried doing something like this but failed:

public function register()
{
    $this->registerCreator();
    $this->registerMigrateMakeCommand();

    if ($this->app->runningInConsole()) {

        $this->commands([
            //MakeContainerMigration::class,
            'custom.command.migrate.make'
        ]);
    }
}

protected function registerCreator()
{
    $this->app->singleton('custom.migration.creator', function ($app) {
        return new MigrationCreator($app['files'], __DIR__ . '/stubs');
    });
}

protected function registerMigrateMakeCommand()
{
    $this->app->singleton('custom.command.migrate.make', function ($app) {
        $creator = $app['custom.migration.creator'];
        $composer = $app['composer'];

        return new MakeContainerMigration($creator, $composer);
    });
}

I'm aware that registering the command shouldn't function like this as I am simply registering singletons to Laravel app instance, but I have no idea how to register it through the class while ensuring that the right version of MigrationCreator will be injected. I'm kinda stuck here, is there a way to do it?

Body:
Turns out everything is working, I just needed to replace

protected $name = 'custom:make-container';

with

protected $signature = 'custom:make-container';


问:
Estimation of difficulty - measuring the volume of dust particles in the tank
my goal is just to get an expert estimation of how difficult a project described below could be.
I work in a company that produces chemicals (phosphates) in a form of powder. We store the powder in tanks (500m3 volume approx., 3 meters radius, 17 meters high). Our problem for many years has been that we have not been able to measure how much powder there is in the tank in a specific moment. This is mainly due to physical properties of powder (liquids would be easy to measure). When the powder is produced and put into the tank, it is hill-shaped, when the powder is getting out of the silo to be packed, a pit forms in the middle. I attached an image for better imagination.

I got an idea if we could place a camera on the top of the tank, take some photos of different amounts and shapes of powder in the tank (and weigh the powder each time for these samples) and let the machine learning algorithm estimate the amount (in tons) of powder in the future. As far as I know there is no technology suitable for weighing the powder in a tank with constant in- or outflow of material (either its super expensive or very inaccurate).

So I would like to ask:

Do you think it would work?

How difficult would it be to write the code? I know some basic python programming and I am on an "intermediate" level in VBA. But I read several articles about image recognition and it does not seem so hard.

Estimation of how many samples (photo of a shape and its weight) we would need to teach the algorithm make a useful estimation?

Thanks for your opinions

答:
It's certainly not an unreasonable idea. To answer your questions:

This depends on whether there is indeed a perceivable difference between the images. If two images look near-identical but their weights are different, then this is unlikely to work (note that it is possible that the computer detects differences that you might not, so don't dismiss it right away).

You will need to learn some basics of machine learning before you get started (your Python knowledge will help), but most of you're learning will likely be while working on the project. I would recommend the Kaggle courses for you.

This is not easy to estimate - it depends heavily on the variation within your data, and the complexity of your model. I just noticed you added a comment mentioning that you'd ideally like to use less than 50 images - that is very likely to be nowhere near enough. The 500+ you fear is more than likely to be the case. However, keep in mind that the number of pictures used in training is not necessarily the number of pictures you'll have to take - through data augmentation (such as flipping, rotating, flipping+rotating and other techniques), you can increase the number of images in your dataset.


问:
Multiple boxplot with seaborn, but not within the same frame
In case of pandas boxplot, we could use:

```<code>for column in df:
    plt.figure()
    df.boxplot([column])
</code>```

What could be done equivalently using seaborn, I want to plot multiple boxplots, but not in the same frame, rather for every column individually in loop

答:
You can pass an Axes object to sns.boxplot:

```<code>for column in df:
    fig, ax = plt.subplots()
    sns.boxplot(df[column], ax=ax)
</code>```

Body:
In case of pandas boxplot, we could use:

for column in df:
    plt.figure()
    df.boxplot([column])

What could be done equivalently using seaborn, I want to plot multiple boxplots, but not in the same frame, rather for every column individually in loop

Body:
You can pass an Axes object to sns.boxplot:

for column in df:
    fig, ax = plt.subplots()
    sns.boxplot(df[column], ax=ax)


问:
Java: producer-consumer two threads stop working, freeze
I have this code that takes data from the first array and puts it in the second array and then removes it from the first array. It works fine for a while, but then stops, while there are still values in the first array to paste:

```<code>import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Main  {
    private static String buffer;
    private static String lock = "lock";

    public static void main(String[] args) throws  Exception  {
        Usb usb1 = new Usb(getListFromValues("1", "2", "3", "4", "5"));
        Usb usb2 = new Usb(getListFromValues("10", "20", "30", "40", "50"));

        Thread usbCutThread = new Thread(new UsbCutThread(usb1));
        Thread usbPasteThread = new Thread(new UsbPasteThread(usb2));

        usbCutThread.start();
        usbPasteThread.start();

        usbCutThread.join();
        usbPasteThread.join();

    }

    static class UsbCutThread implements Runnable  {
      private Usb usb;
      public UsbCutThread(Usb usb)  {this.usb = usb;}

      @Override
      public void run() {
          try {
              System.out.println("inside cut");
              for (int i = 0; i < usb.getData().size(); i++) {
                  buffer = usb.getValue();
                  System.out.println("cutting value " + buffer);

                  synchronized (lock) {
                      System.out.println("copied to buffer, waiting for paste");
                      lock.notify();
                      try {
                          lock.wait();
                      } catch (Exception e) {
                          e.printStackTrace();
                      }
                      System.out.println("erasing");
                      usb.eraseValue();
                  }
              }
          }
        catch (Exception e)  {
              e.printStackTrace();
        }
      }
    }

    static class UsbPasteThread implements Runnable  {
        private Usb usb;
        public UsbPasteThread(Usb usb)  {this.usb = usb;}

        @Override
        public void run() {
            try {
                while (true) {
                    System.out.println("inside paste");
                    //while it copies, cut thread can't erase - what if copy fails
                    synchronized (lock) {
                        usb.addValue("stuff");
                        System.out.println("pasted");
                        lock.notify();
                        try {
                            lock.wait();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                    }
                }
            }
            catch (Exception e)  {
                e.printStackTrace();
            }
        }

    }

    static class Usb  {
      List<String> data = new ArrayList<>();

      public Usb(List<String> data)  {this.data = data;}

        public String getValue()  {return data.get(data.size() - 1);}

        public void addValue(String value)  {
          data.add(value);
        }

        public void eraseValue()  {
          data.remove(data.size() - 1);
        }

        public List<String> getData()  {return data;}
    }

    public static ArrayList<String> getListFromValues(String... values)  {
        ArrayList<String> result = new ArrayList<>();
        for (String v: values)  {
            result.add(v);
        }
        return result;
    }
}
</code>```

Output:

```<code>inside cut
inside paste
pasted
cutting value 5
copied to buffer, waiting for paste
inside paste
pasted
erasing
cutting value 4
copied to buffer, waiting for paste
inside paste
pasted
erasing
cutting value 3
copied to buffer, waiting for paste
inside paste
pasted
erasing
</code>```

答:
UsbCutThread iterates from 0 to usb.getData().size():

              for (int i = 0; i < usb.getData().size(); i++) {
```

<p>In the loop you are <em>changing</em> the size of <code>usb.getData()</code> by <code>usb.eraseValue()</code>. This will obviously affect the amount of iterations. In your case you'll get 3 iterations until <code>i == usb.getData().size()</code> is <code>true</code> and you exit the loop.</p>

<p>The other thread goes into <code>lock.wait()</code> as you've put the whole thing into a <code>while (true)</code>. Here is where your program won't terminate.</p>

<p>To solve the first problem you just need to iterate to a fixed limit:</p>

<pre class="lang-java prettyprint-override"><code>              int n = usb.getData().size();
              for (int i = 0; i < n; i++) {
</code>```

I think the second problem is actually not a problem for you and is what you want. So I just stop here.

Body:
I have this code that takes data from the first array and puts it in the second array and then removes it from the first array. It works fine for a while, but then stops, while there are still values in the first array to paste:

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Main  {
    private static String buffer;
    private static String lock = "lock";

    public static void main(String[] args) throws  Exception  {
        Usb usb1 = new Usb(getListFromValues("1", "2", "3", "4", "5"));
        Usb usb2 = new Usb(getListFromValues("10", "20", "30", "40", "50"));

        Thread usbCutThread = new Thread(new UsbCutThread(usb1));
        Thread usbPasteThread = new Thread(new UsbPasteThread(usb2));

        usbCutThread.start();
        usbPasteThread.start();

        usbCutThread.join();
        usbPasteThread.join();

    }

    static class UsbCutThread implements Runnable  {
      private Usb usb;
      public UsbCutThread(Usb usb)  {this.usb = usb;}

      @Override
      public void run() {
          try {
              System.out.println("inside cut");
              for (int i = 0; i < usb.getData().size(); i++) {
                  buffer = usb.getValue();
                  System.out.println("cutting value " + buffer);

                  synchronized (lock) {
                      System.out.println("copied to buffer, waiting for paste");
                      lock.notify();
                      try {
                          lock.wait();
                      } catch (Exception e) {
                          e.printStackTrace();
                      }
                      System.out.println("erasing");
                      usb.eraseValue();
                  }
              }
          }
        catch (Exception e)  {
              e.printStackTrace();
        }
      }
    }

    static class UsbPasteThread implements Runnable  {
        private Usb usb;
        public UsbPasteThread(Usb usb)  {this.usb = usb;}

        @Override
        public void run() {
            try {
                while (true) {
                    System.out.println("inside paste");
                    //while it copies, cut thread can't erase - what if copy fails
                    synchronized (lock) {
                        usb.addValue("stuff");
                        System.out.println("pasted");
                        lock.notify();
                        try {
                            lock.wait();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                    }
                }
            }
            catch (Exception e)  {
                e.printStackTrace();
            }
        }

    }

    static class Usb  {
      List<String> data = new ArrayList<>();

      public Usb(List<String> data)  {this.data = data;}

        public String getValue()  {return data.get(data.size() - 1);}

        public void addValue(String value)  {
          data.add(value);
        }

        public void eraseValue()  {
          data.remove(data.size() - 1);
        }

        public List<String> getData()  {return data;}
    }

    public static ArrayList<String> getListFromValues(String... values)  {
        ArrayList<String> result = new ArrayList<>();
        for (String v: values)  {
            result.add(v);
        }
        return result;
    }
}

Output:

inside cut
inside paste
pasted
cutting value 5
copied to buffer, waiting for paste
inside paste
pasted
erasing
cutting value 4
copied to buffer, waiting for paste
inside paste
pasted
erasing
cutting value 3
copied to buffer, waiting for paste
inside paste
pasted
erasing

Body:
UsbCutThread iterates from 0 to usb.getData().size():

              for (int i = 0; i < usb.getData().size(); i++) {

In the loop you are changing the size of usb.getData() by usb.eraseValue(). This will obviously affect the amount of iterations. In your case you'll get 3 iterations until i == usb.getData().size() is true and you exit the loop.

The other thread goes into lock.wait() as you've put the whole thing into a while (true). Here is where your program won't terminate.

To solve the first problem you just need to iterate to a fixed limit:

              int n = usb.getData().size();
              for (int i = 0; i < n; i++) {

I think the second problem is actually not a problem for you and is what you want. So I just stop here.


问:
django filter if object appears in another table
I have a model Device and a model BrokenSensor. In the BrokenSensor table, all the devices with broken sensor get a row.

The BrokenSensor model looks like this:

```<code>class BrokenSensor(models.Model):
    sensor = models.PositiveIntegerField(choices=Sensor.choices())
    device = models.ForeignKey(
        Device, on_delete=models.CASCADE, related_name="brokensensor"
    )

    def __str__(self):  # pragma: no cover
        return "pk{} - device: {} - sensor: {}".format(
            self.pk, self.device_id, self.sensor
        )
</code>```

How can I do the most efficient way this query:

Give me all the devices, except the devices the BrokenSensor table

答:
You can filter with the brokensensor being None in the related model:

```<code>Device.objects.filter(<b>brokensensor=None</b>)</code>```

This works since Django makes a LEFT OUTER JOIN, so if there is no BrokenSensor, it will include a row with NULL, and we filter on that one.

As @AKX says however, the reverse of a ForeignKey is plural, since multiple BrokenSensors can point to the same device, you thus might want to rename it to:

```<code>class BrokenSensor(models.Model):
    device = models.ForeignKey(
        Device, on_delete=models.CASCADE, <b>related_name='broken_sensors'</b>
    )
    # …</code>```

then the query is:

```<code>Device.objects.filter(<b>broken_sensors=None</b>)</code>```

Body:
I have a model Device and a model BrokenSensor. In the BrokenSensor table, all the devices with broken sensor get a row.

The BrokenSensor model looks like this:

class BrokenSensor(models.Model):
    sensor = models.PositiveIntegerField(choices=Sensor.choices())
    device = models.ForeignKey(
        Device, on_delete=models.CASCADE, related_name="brokensensor"
    )

    def __str__(self):  # pragma: no cover
        return "pk{} - device: {} - sensor: {}".format(
            self.pk, self.device_id, self.sensor
        )

How can I do the most efficient way this query:

Give me all the devices, except the devices the BrokenSensor table

Body:
You can filter with the brokensensor being None in the related model:

Device.objects.filter(brokensensor=None)

This works since Django makes a LEFT OUTER JOIN, so if there is no BrokenSensor, it will include a row with NULL, and we filter on that one.

As @AKX says however, the reverse of a ForeignKey is plural, since multiple BrokenSensors can point to the same device, you thus might want to rename it to:

class BrokenSensor(models.Model):
    device = models.ForeignKey(
        Device, on_delete=models.CASCADE, related_name='broken_sensors'
    )
    # …

then the query is:

Device.objects.filter(broken_sensors=None)


问:
Parse JSON data from file upload
I have an input that select json file

In my controller, I did

```<code>dd(Input::all());
</code>```

I got

My goal is to parse the JSON file that I got and loop through them.

I've tried

```<code>$string = file_get_contents(Input::get('fileinput'));
$json = json_decode($string, true);
</code>```

How can I proceed?

答:
I am using Laravel version 6 and the other solutions did not work. Following worked for me:</p>

```<code>$file = request()->fileinput;      // <input type="file" name="fileinput" />
$content = file_get_contents($file);
$json = json_decode($content, true);
</code>```

Title: Parse JSON data from file upload

Body:
I have an input that select json file

In my controller, I did

dd(Input::all());

I got

My goal is to parse the JSON file that I got and loop through them.

I've tried

$string = file_get_contents(Input::get('fileinput'));
$json = json_decode($string, true);

How can I proceed?

Body:
I am using Laravel version 6 and the other solutions did not work. Following worked for me:

$file = request()->fileinput;      // <input type="file" name="fileinput" />
$content = file_get_contents($file);
$json = json_decode($content, true);


问:
How to dinamically change Angular FullCalendar event color (of a specific event)?
I am working on an Angular application using PrimeNG Full Calendar component, this one: https://primefaces.org/primeng/showcase/#/fullcalendar

That is based on the Angular FullCalendar component, this one: https://fullcalendar.io/

Here you can find my entire code: https://bitbucket.org/dgs_poste_team/soc_calendar/src/master/

I am finding some difficulties trying to dinamically change the background color of the event rendered on my calendar. I have to have different event background color based on different event information (the start event time, for example: if an event start at 07:00 is green, if it start at 15:00 it is red, if it start at 23:00 it is blue, but this logic is not important at this time).

In my project I am dragging external event into my calendar, something like this: https://fullcalendar.io/docs/external-dragging-demo

So what I want is that when I drag an event into my calendar its background will have a specific color based on the startime.

So, as you can see in my BitBucket repository I have this FullcalendarComponent handling the component that contains the calendar that recives events from an external component:

```<code>import { Component, OnInit, ViewChild, ElementRef } from '@angular/core';
import { EventService } from '../event.service';
import dayGridPlugin from '@fullcalendar/daygrid';
import timeGridPlugin from '@fullcalendar/timegrid';
import listPlugin from '@fullcalendar/list';
import interactionPlugin, { Draggable } from '@fullcalendar/interaction';
import { FullCalendar } from 'primeng';

@Component({
  selector: 'app-fullcalendar',
  templateUrl: './fullcalendar.component.html',
  styleUrls: ['./fullcalendar.component.css']
})
export class FullcalendarComponent implements OnInit {

  events: any[];
  options: any;
  header: any;

  //people: any[];

  @ViewChild('fullcalendar') fullcalendar: FullCalendar;

  constructor(private eventService: EventService) {}

  ngOnInit() {
    this.eventService.getEvents().then(events => { this.events = events;});

    this.options = {
        plugins:[ dayGridPlugin, timeGridPlugin, interactionPlugin, listPlugin ],
        defaultDate: '2017-02-01',
        header: {
            left: 'prev,next',
            center: 'title',
            right: 'dayGridMonth,timeGridWeek,timeGridDay'
        },
        editable: true,
        nextDayThreshold: '06:00:00',
        //eventColor: '#378006',

        dateClick: (dateClickEvent) =>  {         // <-- add the callback here as one of the properties of `options`
          console.log("DATE CLICKED !!!");
        },

        eventClick: (eventClickEvent) => {
          console.log("EVENT CLICKED !!!");
        },

        eventDragStop: (eventDragStopEvent) => {
          console.log("EVENT DRAG STOP !!!");
        },

        eventReceive: (eventReceiveEvent) => {
          console.log(eventReceiveEvent);
          eventReceiveEvent.event.setAllDay(false, {maintainDuration: true});
          eventReceiveEvent.eventColor = '#378006';
          eventReceiveEvent.event.eventColor = '#378006';
          eventReceiveEvent.event.css('background-color', '#378006');
          this.eventService.addEvent(eventReceiveEvent);
        }
    };

  }

}
</code>```

I discovered that adding this option eventColor: '#378006', I can change the default event background color...but in this way it is static and I can't handle different color for different type of events (I simply change the default color for all the event, so it is not good for my use case).

I have this method that is used to revice the events dragged into my calendar:

```<code>eventReceive: (eventReceiveEvent) => {
  console.log(eventReceiveEvent);
  eventReceiveEvent.event.setAllDay(false, {maintainDuration: true});
  eventReceiveEvent.eventColor = '#378006';
  eventReceiveEvent.event.eventColor = '#378006';
  eventReceiveEvent.event.css('background-color', '#378006');
  this.eventService.addEvent(eventReceiveEvent);
}
</code>```

and I was thinking that it could be a good candidate place where to put this behavior...as you can see in my code I tried to use some method to set the event color but it is not working...I still obtain the defaul event color when my page is rendered.

Why? What is wrong? What am I missing? How can I obtain the desired behavior and set the event color by code?

答:
Every event supports a property backgroundColor to decide what should be the background color of your event.

Check here :- https://fullcalendar.io/docs/event-object

To make this color decision automatic whenever a event is added, i changed promise in your service to observable. whenever you will push new event through your addevent method of service. your subscription in ngoninit of component will receive updated data and apply background colors. This will also prevent your original data from changing, as only your component needs this color to display. Not your original data.

Changes in service :-

```<code>  1. public eventData = new BehaviorSubject(this.events);
  2. getEvents(): Observable<any[]> {
      return this.eventData.asObservable();
     }
  3. addEvent(event) {
      //this.events.push(event);
      //console.log("EVENT:")
      //console.log(event.event.title);
      console.log(event.event.start);
      console.log(event);
      const newEvent = {id: 5, title: event.event.title, start: event.event.start, end: event.event.end};
      this.events.push(newEvent);
      this.eventData.next([...this.events]);
     }
</code>```

Complete Service After Changes :-

```<code>import { Injectable } from '@angular/core';
//import { Http } from '@angular/http';
import { HttpClientModule, HttpClient } from '@angular/common/http'
import { BehaviorSubject, Observable } from 'rxjs';

@Injectable()
export class EventService {

  private events = [
    {id: 1, title: 'All Day Event', start: '2017-02-01'},
    {id: 2, title: 'Long Event', start: '2017-02-07', end: '2017-02-10T7:00:00'},
    {id: 3, title: 'Repeating Event', start: '2017-02-09T16:00:00'},
    {id: 3, title: 'test', start: '2017-02-20T07:00:00'},
  ];

  private people = [
    {id: 1, name: "PERSONA 1"},
    {id: 2, name: "PERSONA 2"},
    {id: 3, name: "PERSONA 3"},
    {id: 4, name: "PERSONA 4"},
    {id: 5, name: "PERSONA 5"},
  ]

  public eventData = new BehaviorSubject(this.events);

  constructor(private http: HttpClient) {}

  /*
  getEvents(): Promise<any[]> {
    return this.http.get('assets/json_mock/calendarevents.json')
      .toPromise()
      .then(res => JSON.parse(JSON.stringify(res)).data)
      .then(res => {
        console.log(res);
        // you returned no value here!
        return res;
      })
  }
  */

getEvents(): Observable<any[]> {
  return this.eventData.asObservable();
}

addEvent(event) {
  //this.events.push(event);
  //console.log("EVENT:")
  //console.log(event.event.title);
  console.log(event.event.start);
  console.log(event);
  const newEvent = {id: 5, title: event.event.title, start: event.event.start, end: event.event.end};
  this.events.push(newEvent);
  this.eventData.next([...this.events]);
}

getPeople(): Promise<any[]> {
  return Promise.all(this.people)
      .then(res => {
        console.log(res);
        return res;
      })
}

}
</code>```

In your fullcalendar.component.ts, you can change the color in observable where you are receiveing events from service like :-

```<code>this.eventService.getEvents().subscribe(events => { this.events = events.map((event) => {
  var date = new Date(event.start);
  var hour = date.getHours();
  event['backgroundColor'] = hour === 5? 'red': (hour === 7 ? 'green' : 'black');
  return event;
})});
</code>```

Output :-

Your complete fullcalendar.component.ts after changes:-

```<code>import { Component, OnInit, ViewChild, ElementRef } from '@angular/core';
import { EventService } from '../event.service';
import dayGridPlugin from '@fullcalendar/daygrid';
import timeGridPlugin from '@fullcalendar/timegrid';
import listPlugin from '@fullcalendar/list';
import interactionPlugin, { Draggable } from '@fullcalendar/interaction';
import { FullCalendar } from 'primeng';

@Component({
  selector: 'app-fullcalendar',
  templateUrl: './fullcalendar.component.html',
  styleUrls: ['./fullcalendar.component.css']
})
export class FullcalendarComponent implements OnInit {
  //backgroundColor
  events: any[];
  options: any;
  header: any;

  //people: any[];

  @ViewChild('fullcalendar') fullcalendar: FullCalendar;

  constructor(private eventService: EventService) {}

  ngOnInit() {
    this.eventService.getEvents().subscribe(events => { this.events = events.map((event) => {
      var date = new Date(event.start);
      var hour = date.getHours();
      event['backgroundColor'] = hour === 5? 'red': (hour === 7 ? 'green' : 'black');
      return event;
    })});

    this.options = {
        plugins:[ dayGridPlugin, timeGridPlugin, interactionPlugin, listPlugin ],
        defaultDate: '2017-02-01',
        header: {
            left: 'prev,next',
            center: 'title',
            right: 'dayGridMonth,timeGridWeek,timeGridDay'
        },
        editable: true,
        nextDayThreshold: '06:00:00',

        dateClick: (dateClickEvent) =>  {         // <-- add the callback here as one of the properties of `options`
          console.log("DATE CLICKED !!!");
        },

        eventClick: (eventClickEvent) => {
          console.log("EVENT CLICKED !!!");
        },

        eventDragStop: (eventDragStopEvent) => {
          console.log("EVENT DRAG STOP !!!");
        },

        eventReceive: (eventReceiveEvent) => {
          console.log(eventReceiveEvent);
          eventReceiveEvent.event.setAllDay(false, {maintainDuration: true});
          this.eventService.addEvent(eventReceiveEvent);
        }
    };

  }

}
</code>```

I modified events time in service to below to achieve the output i have in image.

```<code>private events = [
    {id: 1, title: 'All Day Event', start: '2017-02-01'},
    {id: 2, title: 'Long Event', start: '2017-02-07', end: '2017-02-10T7:00:00'},
    {id: 3, title: 'Repeating Event', start: '2017-02-09T16:00:00'},
    {id: 3, title: 'test', start: '2017-02-20T07:00:00'},
  ];
</code>```

Body:
I am working on an Angular application using PrimeNG Full Calendar component, this one: https://primefaces.org/primeng/showcase/#/fullcalendar

That is based on the Angular FullCalendar component, this one: https://fullcalendar.io/

Here you can find my entire code: https://bitbucket.org/dgs_poste_team/soc_calendar/src/master/

I am finding some difficulties trying to dinamically change the background color of the event rendered on my calendar. I have to have different event background color based on different event information (the start event time, for example: if an event start at 07:00 is green, if it start at 15:00 it is red, if it start at 23:00 it is blue, but this logic is not important at this time).

In my project I am dragging external event into my calendar, something like this: https://fullcalendar.io/docs/external-dragging-demo

So what I want is that when I drag an event into my calendar its background will have a specific color based on the startime.

So, as you can see in my BitBucket repository I have this FullcalendarComponent handling the component that contains the calendar that recives events from an external component:

import { Component, OnInit, ViewChild, ElementRef } from '@angular/core';
import { EventService } from '../event.service';
import dayGridPlugin from '@fullcalendar/daygrid';
import timeGridPlugin from '@fullcalendar/timegrid';
import listPlugin from '@fullcalendar/list';
import interactionPlugin, { Draggable } from '@fullcalendar/interaction';
import { FullCalendar } from 'primeng';

@Component({
  selector: 'app-fullcalendar',
  templateUrl: './fullcalendar.component.html',
  styleUrls: ['./fullcalendar.component.css']
})
export class FullcalendarComponent implements OnInit {

  events: any[];
  options: any;
  header: any;

  //people: any[];

  @ViewChild('fullcalendar') fullcalendar: FullCalendar;

  constructor(private eventService: EventService) {}

  ngOnInit() {
    this.eventService.getEvents().then(events => { this.events = events;});

    this.options = {
        plugins:[ dayGridPlugin, timeGridPlugin, interactionPlugin, listPlugin ],
        defaultDate: '2017-02-01',
        header: {
            left: 'prev,next',
            center: 'title',
            right: 'dayGridMonth,timeGridWeek,timeGridDay'
        },
        editable: true,
        nextDayThreshold: '06:00:00',
        //eventColor: '#378006',

        dateClick: (dateClickEvent) =>  {         // <-- add the callback here as one of the properties of `options`
          console.log("DATE CLICKED !!!");
        },

        eventClick: (eventClickEvent) => {
          console.log("EVENT CLICKED !!!");
        },

        eventDragStop: (eventDragStopEvent) => {
          console.log("EVENT DRAG STOP !!!");
        },

        eventReceive: (eventReceiveEvent) => {
          console.log(eventReceiveEvent);
          eventReceiveEvent.event.setAllDay(false, {maintainDuration: true});
          eventReceiveEvent.eventColor = '#378006';
          eventReceiveEvent.event.eventColor = '#378006';
          eventReceiveEvent.event.css('background-color', '#378006');
          this.eventService.addEvent(eventReceiveEvent);
        }
    };

  }

}

I discovered that adding this option eventColor: '#378006', I can change the default event background color...but in this way it is static and I can't handle different color for different type of events (I simply change the default color for all the event, so it is not good for my use case).

I have this method that is used to revice the events dragged into my calendar:

eventReceive: (eventReceiveEvent) => {
  console.log(eventReceiveEvent);
  eventReceiveEvent.event.setAllDay(false, {maintainDuration: true});
  eventReceiveEvent.eventColor = '#378006';
  eventReceiveEvent.event.eventColor = '#378006';
  eventReceiveEvent.event.css('background-color', '#378006');
  this.eventService.addEvent(eventReceiveEvent);
}

and I was thinking that it could be a good candidate place where to put this behavior...as you can see in my code I tried to use some method to set the event color but it is not working...I still obtain the defaul event color when my page is rendered.

Why? What is wrong? What am I missing? How can I obtain the desired behavior and set the event color by code?

Body:
Every event supports a property backgroundColor to decide what should be the background color of your event.

Check here :- https://fullcalendar.io/docs/event-object

To make this color decision automatic whenever a event is added, i changed promise in your service to observable. whenever you will push new event through your addevent method of service. your subscription in ngoninit of component will receive updated data and apply background colors. This will also prevent your original data from changing, as only your component needs this color to display. Not your original data.

Changes in service :-

  1. public eventData = new BehaviorSubject(this.events);
  2. getEvents(): Observable<any[]> {
      return this.eventData.asObservable();
     }
  3. addEvent(event) {
      //this.events.push(event);
      //console.log("EVENT:")
      //console.log(event.event.title);
      console.log(event.event.start);
      console.log(event);
      const newEvent = {id: 5, title: event.event.title, start: event.event.start, end: event.event.end};
      this.events.push(newEvent);
      this.eventData.next([...this.events]);
     }

Complete Service After Changes :-

import { Injectable } from '@angular/core';
//import { Http } from '@angular/http';
import { HttpClientModule, HttpClient } from '@angular/common/http'
import { BehaviorSubject, Observable } from 'rxjs';

@Injectable()
export class EventService {

  private events = [
    {id: 1, title: 'All Day Event', start: '2017-02-01'},
    {id: 2, title: 'Long Event', start: '2017-02-07', end: '2017-02-10T7:00:00'},
    {id: 3, title: 'Repeating Event', start: '2017-02-09T16:00:00'},
    {id: 3, title: 'test', start: '2017-02-20T07:00:00'},
  ];

  private people = [
    {id: 1, name: "PERSONA 1"},
    {id: 2, name: "PERSONA 2"},
    {id: 3, name: "PERSONA 3"},
    {id: 4, name: "PERSONA 4"},
    {id: 5, name: "PERSONA 5"},
  ]

  public eventData = new BehaviorSubject(this.events);

  constructor(private http: HttpClient) {}

  /*
  getEvents(): Promise<any[]> {
    return this.http.get('assets/json_mock/calendarevents.json')
      .toPromise()
      .then(res => JSON.parse(JSON.stringify(res)).data)
      .then(res => {
        console.log(res);
        // you returned no value here!
        return res;
      })
  }
  */

getEvents(): Observable<any[]> {
  return this.eventData.asObservable();
}

addEvent(event) {
  //this.events.push(event);
  //console.log("EVENT:")
  //console.log(event.event.title);
  console.log(event.event.start);
  console.log(event);
  const newEvent = {id: 5, title: event.event.title, start: event.event.start, end: event.event.end};
  this.events.push(newEvent);
  this.eventData.next([...this.events]);
}

getPeople(): Promise<any[]> {
  return Promise.all(this.people)
      .then(res => {
        console.log(res);
        return res;
      })
}

}

In your fullcalendar.component.ts, you can change the color in observable where you are receiveing events from service like :-

this.eventService.getEvents().subscribe(events => { this.events = events.map((event) => {
  var date = new Date(event.start);
  var hour = date.getHours();
  event['backgroundColor'] = hour === 5? 'red': (hour === 7 ? 'green' : 'black');
  return event;
})});

Output :-

Your complete fullcalendar.component.ts after changes:-

import { Component, OnInit, ViewChild, ElementRef } from '@angular/core';
import { EventService } from '../event.service';
import dayGridPlugin from '@fullcalendar/daygrid';
import timeGridPlugin from '@fullcalendar/timegrid';
import listPlugin from '@fullcalendar/list';
import interactionPlugin, { Draggable } from '@fullcalendar/interaction';
import { FullCalendar } from 'primeng';

@Component({
  selector: 'app-fullcalendar',
  templateUrl: './fullcalendar.component.html',
  styleUrls: ['./fullcalendar.component.css']
})
export class FullcalendarComponent implements OnInit {
  //backgroundColor
  events: any[];
  options: any;
  header: any;

  //people: any[];

  @ViewChild('fullcalendar') fullcalendar: FullCalendar;

  constructor(private eventService: EventService) {}

  ngOnInit() {
    this.eventService.getEvents().subscribe(events => { this.events = events.map((event) => {
      var date = new Date(event.start);
      var hour = date.getHours();
      event['backgroundColor'] = hour === 5? 'red': (hour === 7 ? 'green' : 'black');
      return event;
    })});

    this.options = {
        plugins:[ dayGridPlugin, timeGridPlugin, interactionPlugin, listPlugin ],
        defaultDate: '2017-02-01',
        header: {
            left: 'prev,next',
            center: 'title',
            right: 'dayGridMonth,timeGridWeek,timeGridDay'
        },
        editable: true,
        nextDayThreshold: '06:00:00',

        dateClick: (dateClickEvent) =>  {         // <-- add the callback here as one of the properties of `options`
          console.log("DATE CLICKED !!!");
        },

        eventClick: (eventClickEvent) => {
          console.log("EVENT CLICKED !!!");
        },

        eventDragStop: (eventDragStopEvent) => {
          console.log("EVENT DRAG STOP !!!");
        },

        eventReceive: (eventReceiveEvent) => {
          console.log(eventReceiveEvent);
          eventReceiveEvent.event.setAllDay(false, {maintainDuration: true});
          this.eventService.addEvent(eventReceiveEvent);
        }
    };

  }

}

I modified events time in service to below to achieve the output i have in image.

private events = [
    {id: 1, title: 'All Day Event', start: '2017-02-01'},
    {id: 2, title: 'Long Event', start: '2017-02-07', end: '2017-02-10T7:00:00'},
    {id: 3, title: 'Repeating Event', start: '2017-02-09T16:00:00'},
    {id: 3, title: 'test', start: '2017-02-20T07:00:00'},
  ];


问:
sharepoint 2010 sitemap duplicate node urls
Is there any way at all to disable a link on a node?

For example, I would like to disable the "Dashboards" menu item/node, ie, clicking on it on the site will do nothing.

Is this possible?

thanks,

KS

```<code><?xml version="1.0" encoding="utf-8" ?>
<siteMap>
<siteMapNode title="" url="">
<siteMapNode title="BI Home" url="/Home.aspx"/>
<siteMapNode title="Scorecards" url="/Scorecards.aspx">
  <siteMapNode title="Performance Scorecard" url="/Perfomance-Card.aspx"/>
  <siteMapNode title="Quality Scorecard" url="/Quality-Card.aspx"/>
  <siteMapNode title="Service Scorecard" url="/Service-Card.aspx"/>
  <siteMapNode title="Financial Operations Scorecard" url="/FinancialOps-Card.aspx"/>
</siteMapNode>
<siteMapNode title="Dashboards">
  <siteMapNode title="Executive Dashboard" url="/Executive-Dash.aspx"/>
  <siteMapNode title="Operational Scorecard" url="/Operational-Card.aspx"/>
</siteMapNode>
<siteMapNode title="Manual Entry">
  <siteMapNode title="Labor Hours" url="/Labor-Hours.aspx"/>
  <siteMapNode title="Lost Time Accidents" url="/Lost-Time-Accidents.aspx"/>
  <siteMapNode title="Action Items" url="/Action-Items.aspx"/>
  </siteMapNode>
  <siteMapNode title="Reports" url="/Reports.aspx"/>
  </siteMapNode>
</siteMap>
</code>```

答:
Ok, so I settled for second best. What is second best?

Well, I set the main menu item to the same url as the first option beneath it.

But you cannot have duplicate urls in the sitemap nodes I hear you say!

Bypassed this by appending a querystring parameter to the end of the url.

I changed dashboards like so:

```<code><siteMapNode title="Dashboards" url="/Executive-Dash.aspx?S=1"/>
</code>```

Not very elegant but it is acceptable for my sce

Body:
Is there any way at all to disable a link on a node?

For example, I would like to disable the "Dashboards" menu item/node, ie, clicking on it on the site will do nothing.

Is this possible?

thanks,

KS

<?xml version="1.0" encoding="utf-8" ?>
<siteMap>
<siteMapNode title="" url="">
<siteMapNode title="BI Home" url="/Home.aspx"/>
<siteMapNode title="Scorecards" url="/Scorecards.aspx">
  <siteMapNode title="Performance Scorecard" url="/Perfomance-Card.aspx"/>
  <siteMapNode title="Quality Scorecard" url="/Quality-Card.aspx"/>
  <siteMapNode title="Service Scorecard" url="/Service-Card.aspx"/>
  <siteMapNode title="Financial Operations Scorecard" url="/FinancialOps-Card.aspx"/>
</siteMapNode>
<siteMapNode title="Dashboards">
  <siteMapNode title="Executive Dashboard" url="/Executive-Dash.aspx"/>
  <siteMapNode title="Operational Scorecard" url="/Operational-Card.aspx"/>
</siteMapNode>
<siteMapNode title="Manual Entry">
  <siteMapNode title="Labor Hours" url="/Labor-Hours.aspx"/>
  <siteMapNode title="Lost Time Accidents" url="/Lost-Time-Accidents.aspx"/>
  <siteMapNode title="Action Items" url="/Action-Items.aspx"/>
  </siteMapNode>
  <siteMapNode title="Reports" url="/Reports.aspx"/>
  </siteMapNode>
</siteMap>

Body:
Ok, so I settled for second best. What is second best?

Well, I set the main menu item to the same url as the first option beneath it.

But you cannot have duplicate urls in the sitemap nodes I hear you say!

Bypassed this by appending a querystring parameter to the end of the url.

I changed dashboards like so:

<siteMapNode title="Dashboards" url="/Executive-Dash.aspx?S=1"/>

Not very elegant but it is acceptable for my sce


问:
Is it better to use php time() function if there is no provision of timezone in database
I have to update a currently running application to work in multiple countries. Current database doesn't has any provision for time-zone of users. I am thinking to implement the creation/modification of records in unix seconds available from time(). Tried to look for it but couldn't find anything concrete, I don't have support to test in multiple time-zones right now.

Update: UI is not part of php api server.

答:
```<code>file: getTime.php
<?php
    $intClientTime=$_GET['intClentTime'];
    $intServerTime=time();

    echo $intClientTime;
    echo $intServerTime;
?>
<script>
    var objDate    = new Date();
    var objXHR = new XMLHttpRequest();
    objXHR.open('GET', 'getTime.php?intClientTime='+objDate.getTime());
    objXHR.onload = function()
         {
         var strStatus=objXHR.status;
         if(strStatus===200)
                {
                console.log('date sended');
                }
         else
                {
                console.log('Error');
                }
         };
         objXHR.send();
</script>
</code>```


问:
C++ bindings for MySQL
I'm running OSX(10.4.11) & I'm trying to get a decent C(preferably C++) binding for MySQL figured out. I have some data in an offsite database I want to analyze.

I'm trying to get MySQL++ working, but it's being funky.

I'm looking for other bindings, preferably ones with a no-headache install.

edit:

MySQL has C bindings. Clunky and low-level, but it works(after some library fiddling).

http://www.sqlapi.com/ supports Solaris/Windows/Linux.

答:
MySQL Connector/C++ is a C++ implementation of JDBC 4.0

The reference customers who use MySQL Connector/C++ are:
- OpenOffice - MySQL Workbench

Learn more: http://forums.mysql.com/read.php?167,221298

OwnerDisplayName: Vlion

ContentLicense: CC BY-SA 2.5

Title: C++ bindings for MySQL

LastEditorDisplayName: Vlion

OwnerDisplayName: MySQL Workbench


问:
php.ini wont work outside public_html directory
Just very quick question about php.ini file. I created my own on my php.ini file and it works fine if I put it inside my 'public_html' directory. However the problem is it can obviously be viewed in browser through HTTP requests.

So, I am trying to move it outside my 'public_html' directory however it does not seem to work when outside my 'public_html'.

I know I could perhaps set in my .htaccess the following to avoid it being read:

```<code><Files php.ini>
  Order allow,deny
  Deny from all
</Files>
</code>```

However I do not want to do this as my php.ini can still get cached by Google if it's in the 'public_html' directory. Is there any suggestions to make it work outside my public_html?

I am running an Apache server. Thanks for any suggestions

答:
Two suggestions:

Ensure that Apache can find your php.ini (PHPINIDIR /path/where/php.ini/is/located)

Ensure the file is readable by the webserver user.

Body:
Just very quick question about php.ini file. I created my own on my php.ini file and it works fine if I put it inside my 'public_html' directory. However the problem is it can obviously be viewed in browser through HTTP requests.

So, I am trying to move it outside my 'public_html' directory however it does not seem to work when outside my 'public_html'.

I know I could perhaps set in my .htaccess the following to avoid it being read:

<Files php.ini>
  Order allow,deny
  Deny from all
</Files>

However I do not want to do this as my php.ini can still get cached by Google if it's in the 'public_html' directory. Is there any suggestions to make it work outside my public_html?

I am running an Apache server. Thanks for any suggestions


问:
TextIO.Read().From() vs TextIO.ReadFiles() over withHintMatchesManyFiles()
In my usecase getting set of matching filepattern from Kafka,

PCollection<String> filepatterns = p.apply(KafkaIO.read()...);

Here each pattern could match upto 300+ files.

Q1. How can I use TextIO.Read() to match data from PCollection, as withHintMatchesManyFiles() available only for TextIO.Read() not for TextIO.ReadFiles().

Q2. If path via FileIO.Match->FileIO.ReadMatch()->TextIO.ReadFiles() is used, withHintMatchesManyFiles() isn't available in this path, how it will impact the read performance?

Q3. Is there any other optimized path for above usecase?

答:
How can I use TextIO.Read() to match data from PCollection, as withHintMatchesManyFiles() available only for TextIO.Read() not for TextIO.ReadFiles().

My very limited understanding of Apache Beam in general and PTransforms in particular is that TextIO.read() creates a root PTransform that can only be used at the very beginning of the pipeline. In other words, TextIO.Read cannot be used after a PTransform of any kind.


问:
Azure Web app connect to VM service on private network
I've created windows server virtual machine with active directory controller and my web app is communicating with it on public ip successfully (by ldap), but when i try connect to ldap on private ip (virtual network) it does not respond

to my Web app i have set VNet Configuration

my virtual machine network tab:

But it does not work when i try to connect to ldap://10.0.1.4:389

What should i do?

I can't even test my connection between webapp (by tcpping) and vm neither on public and private ip

i couldn't add to my webapp vnet integration on 10.0.1.0/24 because there was written that this subnet is already in use (or sth like that)

what should i type when i do vnet integration?

答:
heh...
i've created second virtual network, and integrated web app with it...
next i have connected my second virtual network to first and... everything works great, ping's are < 1 ms...
that's a bit embarassing that it did not work when both web app and virtual machine were in one virtual network and i don't know why</p>


问:
Find and Replace in a Large File
I want to find a piece of text in a large xml file and want to replace with some other text. The size of the file is around (50GB). I want to do this in command line. I am looking at PowerShell and want to know if it can handle the large size.

Currently I am trying something like this but it does not like it

```<code>Get-Content C:\File1.xml | Foreach-Object {$_ -replace "xmlns:xsi=\"http:\/\/www\.w3\.org\/2001\/XMLSchema-instance\"", ""} | Set-Content C:\File1.xml
</code>```

The text I want to replace is  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" with an empty string "".

Questions

Can PowerShell handle large
files

I don't want the replace to happen in
memory and prefer streaming assuming
that will not bring the server to
its knees.

Are there any other approaches I can take (different
tools/strategy?)

Thanks

答:
I had a similar need (and similar lack of powershell experience) but cobbled together a complete answer from the other answers on this page plus a bit more research.

I also wanted to avoid the regex processing, since I didn't need it either -- just a simple string replace -- but on a large file, so I didn't want it loaded into memory.

Here's the command I used (adding linebreaks for readability):

```<code>Get-Content sourcefile.txt
    | Foreach-Object {$_.Replace('http://example.com', 'http://another.example.com')}
    | Set-Content result.txt
</code>```

Worked perfectly!  Never sucked up much memory (it very obviously didn't load the whole file into memory), and just chugged along for a few minutes then finished.

Title: Find and Replace in a Large File

Body:
I want to find a piece of text in a large xml file and want to replace with some other text. The size of the file is around (50GB). I want to do this in command line. I am looking at PowerShell and want to know if it can handle the large size.

Currently I am trying something like this but it does not like it

Get-Content C:\File1.xml | Foreach-Object {$_ -replace "xmlns:xsi=\"http:\/\/www\.w3\.org\/2001\/XMLSchema-instance\"", ""} | Set-Content C:\File1.xml

The text I want to replace is  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" with an empty string "".

Questions

Can PowerShell handle large
files

I don't want the replace to happen in
memory and prefer streaming assuming
that will not bring the server to
its knees.

Are there any other approaches I can take (different
tools/strategy?)

Thanks

Body:
I had a similar need (and similar lack of powershell experience) but cobbled together a complete answer from the other answers on this page plus a bit more research.

I also wanted to avoid the regex processing, since I didn't need it either -- just a simple string replace -- but on a large file, so I didn't want it loaded into memory.

Here's the command I used (adding linebreaks for readability):

Get-Content sourcefile.txt
    | Foreach-Object {$_.Replace('http://example.com', 'http://another.example.com')}
    | Set-Content result.txt

Worked perfectly!  Never sucked up much memory (it very obviously didn't load the whole file into memory), and just chugged along for a few minutes then finished.


问:
Angular2 (ngSubmit) not working
I've just started Angular2 and facing following error when add (ngSubmit) attribute to my form

```<code>Template parse errors:
There is no directive with "exportAs" set to "ngForm" ("

    <form [ERROR ->]#form="ngForm" (ngSubmit)="onSubmit()" novalidate>
</code>```

Following are some of my dependencies from package.json.

```<code>"dependencies": {
    "@angular/common": "2.0.0",
    "@angular/compiler": "2.0.0",
    "@angular/core": "2.0.0",
    "@angular/forms": "2.0.0",
    "@angular/http": "2.0.0",
    "@angular/platform-browser": "2.0.0",
    "@angular/platform-browser-dynamic": "2.0.0",
    "@angular/router": "3.0.0",
    "@angular/upgrade": "2.0.0",
    "angular2-in-memory-web-api": "0.0.20",
    "core-js": "^2.4.1",
    "ie-shim": "^0.1.0",
    "jquery": "^3.1.0",
    "reflect-metadata": "^0.1.3",
    "rxjs": "5.0.0-beta.12",
    "systemjs": "0.19.27",
    "zone.js": "^0.6.23"
  }
</code>```

I've following html form.

```<code><form #form="ngForm" (ngSubmit)="onSubmit()" novalidate>

    <div class="form-group">
        <label>Title</label>
        <input [(ngModel)]="model.Title" #title="ngModel" name="title" id="title" type="text" class="form-control" value="">
    </div>

    <div class="form-group">
        <label>Description</label>
        <textarea [(ngModel)]="model.Description" #description="ngModel" class="summernote form-control" name="description" id="description"></textarea>
    </div>

</form>
</code>```

And following category.component file

```<code>import { Component } from '@angular/core';
import { FormBuilder} from '@angular/forms';
import { Category } from '../../../models/cms/Category';

@Component({
    selector: 'category',
    templateUrl: 'category.template.html'
})
export class CategoryComponent{

    model = new Category("dummyTitle","dummyDescription");

    onSubmit() {
        console.log(this.data);
    }
}
</code>```

Can someone please guide how to deal with this problem.

答:
Make sure that button is inside the form and has type="submit". For example,</p>

```<code><ion-button type="submit"></ion-button>
</code>```

Title: Angular2 (ngSubmit) not working

Body:
I've just started Angular2 and facing following error when add (ngSubmit) attribute to my form

Template parse errors:
There is no directive with "exportAs" set to "ngForm" ("

    <form [ERROR ->]#form="ngForm" (ngSubmit)="onSubmit()" novalidate>

Following are some of my dependencies from package.json.

"dependencies": {
    "@angular/common": "2.0.0",
    "@angular/compiler": "2.0.0",
    "@angular/core": "2.0.0",
    "@angular/forms": "2.0.0",
    "@angular/http": "2.0.0",
    "@angular/platform-browser": "2.0.0",
    "@angular/platform-browser-dynamic": "2.0.0",
    "@angular/router": "3.0.0",
    "@angular/upgrade": "2.0.0",
    "angular2-in-memory-web-api": "0.0.20",
    "core-js": "^2.4.1",
    "ie-shim": "^0.1.0",
    "jquery": "^3.1.0",
    "reflect-metadata": "^0.1.3",
    "rxjs": "5.0.0-beta.12",
    "systemjs": "0.19.27",
    "zone.js": "^0.6.23"
  }

I've following html form.

<form #form="ngForm" (ngSubmit)="onSubmit()" novalidate>

        Title
        <input [(ngModel)]="model.Title" #title="ngModel" name="title" id="title" type="text" class="form-control" value="">

        Description
        <textarea [(ngModel)]="model.Description" #description="ngModel" class="summernote form-control" name="description" id="description"></textarea>

</form>

And following category.component file

import { Component } from '@angular/core';
import { FormBuilder} from '@angular/forms';
import { Category } from '../../../models/cms/Category';

@Component({
    selector: 'category',
    templateUrl: 'category.template.html'
})
export class CategoryComponent{

    model = new Category("dummyTitle","dummyDescription");

    onSubmit() {
        console.log(this.data);
    }
}

Can someone please guide how to deal with this problem.

Body:
Make sure that button is inside the form and has type="submit". For example,

<ion-button type="submit"></ion-button>


问:
DataFrame.duplicated() error in function recursion TypeError: duplicated() got multiple values for argument 'keep'
I am using Python 3 on Jupyter notebook.

Use case:

Process all the records of an excel file.

Problem:

Duplicate records against the column Login id in excel while the underlaying processing can not process a Data set with duplicate records for a login id. So trying to process the records in batches by filtering and creating sub data sets for the duplicate records using recursive function.

Test data set:

Python code:

```<code># process withdrwal of duplicate enteries with recrursive function

def withdrw_user_balance(withdraw_records):
#create new data frame using the
duplicateRowsDF = withdraw_records.duplicated(['Login'], keep = "first")
duplicateRowsDF.head(10)

#remove duplicates from the original data frame
withdraw_records.drop_duplicates(['Login'], keep='first', inplace=True)

#process withdraw request for the non-duplicated row data frame
# processWithdraw()

#update the status
for row in withdraw_records.itertuples():
    withdraw_records.at[row.Index, 'status'] = 1

# write to excel the processed data frame
# writeExcel(withdraw_records)

# clear the object withdraw_records
withdraw_records = None

# check the size of new dataframe, if greater then 0, recruse the withdrw_user_balance() to find more duplicate records in the current
# else return
if duplicateRowsDF.size > 0:
    print("recrusion called")
    withdrw_user_balance(duplicateRowsDF)
else:
    return True;
</code>```

The next code is to execute the recursive function:

```<code># import the excel file
withdraw_records_excel = pd.read_excel("batch-withdraw-duplicate-login.xlsx")
withdraw_records_excel.tail()

withdraw_records_excel.size
withdrw_user_balance(withdraw_records_excel)
</code>```

Out put:

```<code>recrusion called
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-6-bae5054c7199> in <module>
  4
  5 withdraw_records_excel.size
----> 6 withdrw_user_balance(withdraw_records_excel)

<ipython-input-5-2ecdc243bfb2> in withdrw_user_balance(withdraw_records)
 27     if duplicateRowsDF.size > 0:
 28         print("recrusion called")
---> 29         withdrw_user_balance(duplicateRowsDF)
 30     else:
 31         return True;

<ipython-input-5-2ecdc243bfb2> in withdrw_user_balance(withdraw_records)
  4 def withdrw_user_balance(withdraw_records):
  5     #create new data frame using the
----> 6     duplicateRowsDF = withdraw_records.duplicated(['Login'], keep = "first")
  7     duplicateRowsDF.head(10)
  8

TypeError: duplicated() got multiple values for argument 'keep'
</code>```

I think that the error is because the function parameters are pass by reference in python so the data frame some how keeps the reference of previous function call hence the DataFrame.duplicate() method is throwing error.

To fix that, I have nullify the DataFrame object as withdraw_records = None after processing, but no help.
Note that I am a starter in python so I may have wrong information on the types and object reference.

Thanks for you help.

答:
Finally, I was able to fix the issue in the code.
rather than

```<code>#create new data frame using the
duplicateRowsDF = withdraw_records.duplicated(['Login'], keep = "first")
</code>```

I need to write:

```<code>duplicateRowsDF = withdraw_records[withdraw_records.duplicated(['Login'], keep = "first")]
</code>```

It will return the the sub-DataFrame of duplicate records in each call to the function which can be passed as parameter in the consecutive recursive function call to create batches of unique records.

I have used the pixidust debug tool to debug this program which helped a lot in identifying the issue. Following this link:
Use pixidust debugger with Jupyter notebook

Body:
I am using Python 3 on Jupyter notebook.

Use case:

Process all the records of an excel file.

Problem:

Duplicate records against the column Login id in excel while the underlaying processing can not process a Data set with duplicate records for a login id. So trying to process the records in batches by filtering and creating sub data sets for the duplicate records using recursive function.

Test data set:

Python code:

# process withdrwal of duplicate enteries with recrursive function

def withdrw_user_balance(withdraw_records):
#create new data frame using the
duplicateRowsDF = withdraw_records.duplicated(['Login'], keep = "first")
duplicateRowsDF.head(10)

#remove duplicates from the original data frame
withdraw_records.drop_duplicates(['Login'], keep='first', inplace=True)

#process withdraw request for the non-duplicated row data frame
# processWithdraw()

#update the status
for row in withdraw_records.itertuples():
    withdraw_records.at[row.Index, 'status'] = 1

# write to excel the processed data frame
# writeExcel(withdraw_records)

# clear the object withdraw_records
withdraw_records = None

# check the size of new dataframe, if greater then 0, recruse the withdrw_user_balance() to find more duplicate records in the current
# else return
if duplicateRowsDF.size > 0:
    print("recrusion called")
    withdrw_user_balance(duplicateRowsDF)
else:
    return True;

The next code is to execute the recursive function:

# import the excel file
withdraw_records_excel = pd.read_excel("batch-withdraw-duplicate-login.xlsx")
withdraw_records_excel.tail()

withdraw_records_excel.size
withdrw_user_balance(withdraw_records_excel)

Out put:

recrusion called
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-6-bae5054c7199> in <module>
  4
  5 withdraw_records_excel.size
----> 6 withdrw_user_balance(withdraw_records_excel)

<ipython-input-5-2ecdc243bfb2> in withdrw_user_balance(withdraw_records)
 27     if duplicateRowsDF.size > 0:
 28         print("recrusion called")
---> 29         withdrw_user_balance(duplicateRowsDF)
 30     else:
 31         return True;

<ipython-input-5-2ecdc243bfb2> in withdrw_user_balance(withdraw_records)
  4 def withdrw_user_balance(withdraw_records):
  5     #create new data frame using the
----> 6     duplicateRowsDF = withdraw_records.duplicated(['Login'], keep = "first")
  7     duplicateRowsDF.head(10)
  8

TypeError: duplicated() got multiple values for argument 'keep'

I think that the error is because the function parameters are pass by reference in python so the data frame some how keeps the reference of previous function call hence the DataFrame.duplicate() method is throwing error.

To fix that, I have nullify the DataFrame object as withdraw_records = None after processing, but no help.
Note that I am a starter in python so I may have wrong information on the types and object reference.

Thanks for you help.

Body:
Finally, I was able to fix the issue in the code.
rather than

#create new data frame using the
duplicateRowsDF = withdraw_records.duplicated(['Login'], keep = "first")

I need to write:

duplicateRowsDF = withdraw_records[withdraw_records.duplicated(['Login'], keep = "first")]

It will return the the sub-DataFrame of duplicate records in each call to the function which can be passed as parameter in the consecutive recursive function call to create batches of unique records.

I have used the pixidust debug tool to debug this program which helped a lot in identifying the issue. Following this link:
Use pixidust debugger with Jupyter notebook


问:
Codes not changing in android studio
I have a problem with android studio v4. I wrote some codes in Activity and run it with success. Now, When I change that code, There is no change in the program. For example, I added 5 records to SQLite-database as default and now, I want to add just one record. So I remove 4 records and run the project, But 5 records still showing.

I try to remove the application from device, Clean project, Rebuild project, Invalidate cache, and restart. But not be changed.

Can you help me?

答: I reinstall the android studio and the problem was solved.</p>

Title: Codes not changing in android studio


问:
How to name graphs in legend based on folder's name
I have plotted a graph for different sub-folders inside of a directory and I want to put a legend of each graph based on the name of the folder. I mean, the plot legend is being to be written according to the folder's name. The code for plotting is below:</p>

```<code>from __future__ import division
import sys
import os
import numpy as np
import matplotlib.pyplot as plt
import glob
import seaborn as sns
from scipy import stats
from scipy.stats.kde import gaussian_kde

root = r'C:\Users\Hasan\Desktop\output\new our scenario\beta 15\test'
mean_cu=[]
my_list = os.listdir(root)
my_list =  [file for file in my_list if os.path.isdir(os.path.join(root, file))]
for directory in my_list:
    CASES = [file for file in os.listdir(os.path.join(root, directory)) if file.startswith('config')]
    if len(CASES)==0:
        continue
    maxnum = np.max([int(os.path.splitext(f)[0].split('_')[1]) for f in CASES])
    CASES = ['configuration_%d.out' % i for i in range(maxnum)]
    mean_cu=[]
    for i, d in enumerate(CASES):
        a = np.loadtxt(os.path.join(root, directory,d)).T
        num = os.path.splitext(d)[0]
        local_cu = np.abs(a[4])
        mean_curv.append(np.mean(local_cu))
        pdf = stats.norm.pdf(mean_cu)

    Time = np.arange(0,len(pdf))
    plt.plot(Time,pdf)

</code>```

答:
From what I understand, you have different graphs, and for each of them you want a different legend based on current folder. You can set legend by adding label=directory in plot method. Maybe you should first extract current folder (using split or different method) if you don't want full directory. That depends on your directory variable.

Consider following example:

import matplotlib.pyplot as plt
import pandas as pd

legend1 = ["1", "2"]
df = pd.DataFrame({"A":[4,5], "B":[6,7]})

for item in legend1:
    fig, ax = plt.subplots()
    ax.plot(df["A"], df["B"], label=item)
    ax.legend(loc='upper left', frameon=False)
```

will result the following two graphs:

As you can see the only different is the legend, that was set by legend1 list. You can make it your directories.

Body:
I have plotted a graph for different sub-folders inside of a directory and I want to put a legend of each graph based on the name of the folder. I mean, the plot legend is being to be written according to the folder's name. The code for plotting is below:

from __future__ import division
import sys
import os
import numpy as np
import matplotlib.pyplot as plt
import glob
import seaborn as sns
from scipy import stats
from scipy.stats.kde import gaussian_kde

root = r'C:\Users\Hasan\Desktop\output\new our scenario\beta 15\test'
mean_cu=[]
my_list = os.listdir(root)
my_list =  [file for file in my_list if os.path.isdir(os.path.join(root, file))]
for directory in my_list:
    CASES = [file for file in os.listdir(os.path.join(root, directory)) if file.startswith('config')]
    if len(CASES)==0:
        continue
    maxnum = np.max([int(os.path.splitext(f)[0].split('_')[1]) for f in CASES])
    CASES = ['configuration_%d.out' % i for i in range(maxnum)]
    mean_cu=[]
    for i, d in enumerate(CASES):
        a = np.loadtxt(os.path.join(root, directory,d)).T
        num = os.path.splitext(d)[0]
        local_cu = np.abs(a[4])
        mean_curv.append(np.mean(local_cu))
        pdf = stats.norm.pdf(mean_cu)

    Time = np.arange(0,len(pdf))
    plt.plot(Time,pdf)

Body:
From what I understand, you have different graphs, and for each of them you want a different legend based on current folder. You can set legend by adding label=directory in plot method. Maybe you should first extract current folder (using split or different method) if you don't want full directory. That depends on your directory variable.

Consider following example:

import matplotlib.pyplot as plt
import pandas as pd

legend1 = ["1", "2"]
df = pd.DataFrame({"A":[4,5], "B":[6,7]})

for item in legend1:
    fig, ax = plt.subplots()
    ax.plot(df["A"], df["B"], label=item)
    ax.legend(loc='upper left', frameon=False)

will result the following two graphs:

As you can see the only different is the legend, that was set by legend1 list. You can make it your directories.


问:
PySpark group by collect_list over a window
I have a data frame with multiple columns. I'm trying to aggregate few columns using collect_list grouped on id, over a window function. I'm trying some thing like this:

```<code>exprs = [(collect_list(x).over(window)).alias(f"{x}_list") for x in cols]
df = df.groupBy('id').agg(*exprs)
</code>```

I'm getting the below error:

expression is neither present in the group by, nor is it an aggregate function. Add to group by or wrap in first() (or first_value) if you don't care which value you get

If I do the same for a single column, instead of for multiple columns it is working.

答:
I found a way for this. I guess, window functions wont work for agg(*exprs) operations. So, I modified the above to

```<code>for col_name in cols:
    df = df.withColumn(col_name + "_list", collect_list(col(col_name)).over(window_spec))
</code>```

This served my purpose.

Thank you.

Body:
I have a data frame with multiple columns. I'm trying to aggregate few columns using collect_list grouped on id, over a window function. I'm trying some thing like this:

exprs = [(collect_list(x).over(window)).alias(f"{x}_list") for x in cols]
df = df.groupBy('id').agg(*exprs)

I'm getting the below error:

expression is neither present in the group by, nor is it an aggregate function. Add to group by or wrap in first() (or first_value) if you don't care which value you get

If I do the same for a single column, instead of for multiple columns it is working.

Body:
I found a way for this. I guess, window functions wont work for agg(*exprs) operations. So, I modified the above to

for col_name in cols:
    df = df.withColumn(col_name + "_list", collect_list(col(col_name)).over(window_spec))

This served my purpose.

Thank you.


问:
How to upload images and file to a server in Flutter?
I use a web service for image processing , it works well in Postman:

Now I want to make http request in flutter with Dart:

```<code>import 'package:http/http.dart' as http;

static ocr(File image) async {
    var url = '${API_URL}ocr';
    var bytes = image.readAsBytesSync();

    var response = await http.post(
        url,
        headers:{ "Content-Type":"multipart/form-data" } ,
        body: { "lang":"fas" , "image":bytes},
        encoding: Encoding.getByName("utf-8")
    );

    return response.body;

  }
</code>```

but I don't know how to upload the image file, in above code I get exception: Bad state: Cannot set the body fields of a Request with content-type "multipart/form-data".

How should I write the body of request?

答:
With dio I do like this:</p>

```<code>Future<void> _uploadFileAsFormData(String path) async {
  try {
    final dio = Dio();

    dio.options.headers = {
      'Content-Type': 'application/x-www-form-urlencoded'
    };

    final file =
      await MultipartFile.fromFile(path, filename: 'test_file');

    final formData = FormData.fromMap({'file': file}); // 'file' - this is an api key, can be different

    final response = await dio.put( // or dio.post
      uploadFileUrlAsString,
      data: formData,
    );
  } catch (err) {
    print('uploading error: $err');
  }
}
</code>```

Body:
I use a web service for image processing , it works well in Postman:

Now I want to make http request in flutter with Dart:

import 'package:http/http.dart' as http;

static ocr(File image) async {
    var url = '${API_URL}ocr';
    var bytes = image.readAsBytesSync();

    var response = await http.post(
        url,
        headers:{ "Content-Type":"multipart/form-data" } ,
        body: { "lang":"fas" , "image":bytes},
        encoding: Encoding.getByName("utf-8")
    );

    return response.body;

  }

but I don't know how to upload the image file, in above code I get exception: Bad state: Cannot set the body fields of a Request with content-type "multipart/form-data".

How should I write the body of request?

Body:
With dio I do like this:

Future<void> _uploadFileAsFormData(String path) async {
  try {
    final dio = Dio();

    dio.options.headers = {
      'Content-Type': 'application/x-www-form-urlencoded'
    };

    final file =
      await MultipartFile.fromFile(path, filename: 'test_file');

    final formData = FormData.fromMap({'file': file}); // 'file' - this is an api key, can be different

    final response = await dio.put( // or dio.post
      uploadFileUrlAsString,
      data: formData,
    );
  } catch (err) {
    print('uploading error: $err');
  }
}


问:
Closure Syntax with and without parameters
iOS 13, Swift 5

I am trying get my head around closure syntax in Swift and almost there. I got the first three bon, and understand them; but the last no. How do I call self.theMethod4 here? the syntax shown is wrong!

```<code>struct ContentView: View {
var body: some View {
    Text("Hello, World!")
      .onAppear {
        self.theMethod {
          print("1")
        }
        self.the2Method("Ya ") {
          print("1")
        }
        self.the3Method("Hello") {arg2do in
          print("1 ",arg2do)
        }
        self.the4Method("World") { (arg2do) -> String in
          print("1 ",arg2do)
        }
      }
}

func theMethod(_ endOfMethod: @escaping () -> Void) {
  print("2")
  endOfMethod()
}

func the2Method(_ arg1:String, endOfMethod: @escaping () -> Void) {
  print("3")
  endOfMethod()
}

func the3Method(_ arg1:String, endOfMethod: @escaping (_ arg2:String) -> Void) {
  print("4")
  endOfMethod("Yo")
}

func the4Method(_ arg1:String, endOfMethod: @escaping (_ arg2: String) -> String) {
  print("5")
  let an = endOfMethod("Pe")
  print("An ",an)
}
}
</code>```

答:
The closure in method 4 is defined to return a string, so when you call it, that’s what you’d have to do:</p>

```<code>self.the4Method("World") { arg2do -> String in
    return "1 " + arg2do
}
</code>```

Body:
iOS 13, Swift 5

I am trying get my head around closure syntax in Swift and almost there. I got the first three bon, and understand them; but the last no. How do I call self.theMethod4 here? the syntax shown is wrong!

struct ContentView: View {
var body: some View {
    Text("Hello, World!")
      .onAppear {
        self.theMethod {
          print("1")
        }
        self.the2Method("Ya ") {
          print("1")
        }
        self.the3Method("Hello") {arg2do in
          print("1 ",arg2do)
        }
        self.the4Method("World") { (arg2do) -> String in
          print("1 ",arg2do)
        }
      }
}

func theMethod(_ endOfMethod: @escaping () -> Void) {
  print("2")
  endOfMethod()
}

func the2Method(_ arg1:String, endOfMethod: @escaping () -> Void) {
  print("3")
  endOfMethod()
}

func the3Method(_ arg1:String, endOfMethod: @escaping (_ arg2:String) -> Void) {
  print("4")
  endOfMethod("Yo")
}

func the4Method(_ arg1:String, endOfMethod: @escaping (_ arg2: String) -> String) {
  print("5")
  let an = endOfMethod("Pe")
  print("An ",an)
}
}

Body:
The closure in method 4 is defined to return a string, so when you call it, that’s what you’d have to do:

self.the4Method("World") { arg2do -> String in
    return "1 " + arg2do
}