问:
"python manage.py makemigrations" Traceback errors after creating models.py in Django
All of these errors only started happening when i did the models.py, to the best of my knowledge i didn't write any of my code wrong. Previous "makemigrations" worked.

It seems like a lot of the Traceback errors have nothing to do with the models.py though.

(hopefully these are easy to read, sorry)

The traceback error:

Traceback (most recent call last):

File "manage.py", line 21, in  main()

File "manage.py", line 17, in main execute_from_command_line(sys.argv)

File
  "/home/alatimer/Environments/DjangoTutorial_env/lib/python3.6/site-packages/django
  /core/management/init.py", line 401, in execute_from_command_line
  utility.execute()

File
  "/home/alatimer/Environments/DjangoTutorial_env/lib/python3.6/site-packages/django/core/management/init.py",
  line 377, in execute django.setup()

File
  "/home/alatimer/Environments/DjangoTutorial_env/lib/python3.6/site-packages/django/init.py",
  line 24, in setup apps.populate(settings.INSTALLED_APPS)

File
  "/home/alatimer/Environments/DjangoTutorial_env/lib/python3.6/site-packages/django/apps/registry.py",
  line 114, in populate app_config.import_models()

File
  "/home/alatimer/Environments/DjangoTutorial_env/lib/python3.6/site-packages/django/apps/config.py",
  line 211, in import_models self.models_module =
  import_module(models_module_name)

File "/usr/lib/python3.6/importlib/init.py", line 126, in
  import_module return _bootstrap._gcd_import(name[level:], package,
  level)

File "", line 994, in _gcd_import

File "", line 971, in _find_and_load

File "", line 955, in
  _find_and_load_unlocked

File "", line 665, in _load_unlocked

File "", line 678, in
  exec_module

File "", line 219, in
  _call_with_frames_removed

File "/home/alatimer/Environments/djangoproject/blog/models.py", line
  6, in  class Post(models.Model):

File "/home/alatimer/Environments/djangoproject/blog/models.py", line
  9, in Post date_posted = models.DateTimeField(defualt=timezone.now)

File
  "/home/alatimer/Environments/DjangoTutorial_env/lib/python3.6/site-packages/django/db/models/fields/init.py", line 1107, in init super().init(verbose_name, name, **kwargs)

TypeError: init() got an unexpected keyword argument 'defualt'

models.py:

```<code>from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User

class Post(models.Model):
    title = models.CharField(max_length=100)
    content = models.TextField()
    date_posted = models.DateTimeField(defualt=timezone.now)
    author = models.ForeignKey(User, on_delete=models.CASCADE)
</code>```

答:
Well, the error actually says it all (last line):

TypeError: init() got an unexpected keyword argument 'defualt'

So, in your models.py this line should be corrected:

```<code>date_posted = models.DateTimeField(defualt=timezone.now)
</code>```

It is not defualt, it is default. You made a typo!

Body:
All of these errors only started happening when i did the models.py, to the best of my knowledge i didn't write any of my code wrong. Previous "makemigrations" worked.

It seems like a lot of the Traceback errors have nothing to do with the models.py though.

(hopefully these are easy to read, sorry)

The traceback error:

Traceback (most recent call last):

File "manage.py", line 21, in  main()

File "manage.py", line 17, in main execute_from_command_line(sys.argv)

File
  "/home/alatimer/Environments/DjangoTutorial_env/lib/python3.6/site-packages/django
  /core/management/init.py", line 401, in execute_from_command_line
  utility.execute()

File
  "/home/alatimer/Environments/DjangoTutorial_env/lib/python3.6/site-packages/django/core/management/init.py",
  line 377, in execute django.setup()

File
  "/home/alatimer/Environments/DjangoTutorial_env/lib/python3.6/site-packages/django/init.py",
  line 24, in setup apps.populate(settings.INSTALLED_APPS)

File
  "/home/alatimer/Environments/DjangoTutorial_env/lib/python3.6/site-packages/django/apps/registry.py",
  line 114, in populate app_config.import_models()

File
  "/home/alatimer/Environments/DjangoTutorial_env/lib/python3.6/site-packages/django/apps/config.py",
  line 211, in import_models self.models_module =
  import_module(models_module_name)

File "/usr/lib/python3.6/importlib/init.py", line 126, in
  import_module return _bootstrap._gcd_import(name[level:], package,
  level)

File "", line 994, in _gcd_import

File "", line 971, in _find_and_load

File "", line 955, in
  _find_and_load_unlocked

File "", line 665, in _load_unlocked

File "", line 678, in
  exec_module

File "", line 219, in
  _call_with_frames_removed

File "/home/alatimer/Environments/djangoproject/blog/models.py", line
  6, in  class Post(models.Model):

File "/home/alatimer/Environments/djangoproject/blog/models.py", line
  9, in Post date_posted = models.DateTimeField(defualt=timezone.now)

File
  "/home/alatimer/Environments/DjangoTutorial_env/lib/python3.6/site-packages/django/db/models/fields/init.py", line 1107, in init super().init(verbose_name, name, **kwargs)

TypeError: init() got an unexpected keyword argument 'defualt'

models.py:

from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User

class Post(models.Model):
    title = models.CharField(max_length=100)
    content = models.TextField()
    date_posted = models.DateTimeField(defualt=timezone.now)
    author = models.ForeignKey(User, on_delete=models.CASCADE)

Body:
Well, the error actually says it all (last line):

TypeError: init() got an unexpected keyword argument 'defualt'

So, in your models.py this line should be corrected:

date_posted = models.DateTimeField(defualt=timezone.now)

It is not defualt, it is default. You made a typo!


来源: stackexchange

问:
What is the difference between primaryColor and primarySwatch in Flutter?
In Flutter, one can apply a theme to the app using ThemeData class. But there two propeties of this class that confuses me: primaryColor and primarySwatch. What's the difference between these two properties and when to use one or the other? Thanks.

答:
The following is taking from my perusal of theme_data.dart:

primarySwatch defaults to Colors.blue and sets the following fields (including primaryColor) to various shades of the MaterialColor input depending on whether the theme brightness is light or dark (default is light):

Light Themes

// The default shade for the color is used
primaryColor = primarySwatch; // [500] for normal colors and [200] for accent colors
```

<pre class="lang-dart prettyprint-override"><code>primaryColorLight = primarySwatch[100];
</code>```

primaryColorDark = primarySwatch[700];
```

<pre class="lang-dart prettyprint-override"><code>// This can be overridden by setting accentColor (below) manually
toggleableActiveColor = primarySwatch[600];
</code>```

accentColor = primarySwatch[500];
```

<pre class="lang-dart prettyprint-override"><code>secondaryHeaderColor = primarySwatch[50];
</code>```

textSelectionColor = primarySwatch[200];
```

<pre class="lang-dart prettyprint-override"><code>textSelectionHandleColor = primarySwatch[300]
</code>```

backgroundColor = primarySwatch[200];
```

<p>*buttonColor is set to its default (grey[300])</p>

<h2>Dark Themes</h2>

<pre class="lang-dart prettyprint-override"><code>buttonColor = primarySwatch[600];
</code>```

*The remaining fields listed above for light themes are set to their dark defaults (various shades of tealAccent, grey or black)

All Themes (light or dark)

// Brightness.dark/light is estimated based on the default shade for the color
// This also sets the bool primaryIsDark
primaryColorBrightness = estimateBrightnessForColor(primarySwatch);
```

<pre class="lang-dart prettyprint-override"><code>// This generates the modern simplified set of theme colors flutter recommends
// using when theming Widgets based on the theme. Set it manually if you need
// more control over individual colors
colorScheme = ColorScheme.fromSwatch(
      primarySwatch: primarySwatch, // as above
      primaryColorDark: primaryColorDark, // as above
      accentColor: accentColor, // as above
      cardColor: cardColor, // default based on theme brightness, can be set manually
      backgroundColor: backgroundColor, // as above
      errorColor: errorColor, // default (Colors.red[700]), can be set manually
      brightness: brightness, // default (Brightness.light), can be set manually
    );
</code>```

As mentioned in the accepted answer, only setting primaryColor could leave Widgets open to selecting some other default color (various shades of blue) based on one of the other fields above if they are not also set individually, so primarySwatch is a convenient shorthand for simple themes.

In general, however, the colorScheme field is most important as per modern conventions you should be using Theme.of(context).colorScheme.<Color> (though it may not work everywhere yet depending on when you read this).

So, if you need more control over individual theme colors, you could either make do with setting the fields used in ColorScheme.fromSwatch, or just set the primarySwatch (for backwards compatibility of Flutter Widgets that have not yet been migrated), and then set the colorScheme manually for extra control. See also this document for more information…

ContentLicense: CC BY-SA 4.0

Body:
The following is taking from my perusal of theme_data.dart:

primarySwatch defaults to Colors.blue and sets the following fields (including primaryColor) to various shades of the MaterialColor input depending on whether the theme brightness is light or dark (default is light):

Light Themes

// The default shade for the color is used
primaryColor = primarySwatch; // [500] for normal colors and [200] for accent colors

primaryColorLight = primarySwatch[100];

primaryColorDark = primarySwatch[700];

// This can be overridden by setting accentColor (below) manually
toggleableActiveColor = primarySwatch[600];

accentColor = primarySwatch[500];

secondaryHeaderColor = primarySwatch[50];

textSelectionColor = primarySwatch[200];

textSelectionHandleColor = primarySwatch[300]

backgroundColor = primarySwatch[200];

*buttonColor is set to its default (grey[300])

Dark Themes

buttonColor = primarySwatch[600];

*The remaining fields listed above for light themes are set to their dark defaults (various shades of tealAccent, grey or black)

All Themes (light or dark)

// Brightness.dark/light is estimated based on the default shade for the color
// This also sets the bool primaryIsDark
primaryColorBrightness = estimateBrightnessForColor(primarySwatch);

// This generates the modern simplified set of theme colors flutter recommends
// using when theming Widgets based on the theme. Set it manually if you need
// more control over individual colors
colorScheme = ColorScheme.fromSwatch(
      primarySwatch: primarySwatch, // as above
      primaryColorDark: primaryColorDark, // as above
      accentColor: accentColor, // as above
      cardColor: cardColor, // default based on theme brightness, can be set manually
      backgroundColor: backgroundColor, // as above
      errorColor: errorColor, // default (Colors.red[700]), can be set manually
      brightness: brightness, // default (Brightness.light), can be set manually
    );

As mentioned in the accepted answer, only setting primaryColor could leave Widgets open to selecting some other default color (various shades of blue) based on one of the other fields above if they are not also set individually, so primarySwatch is a convenient shorthand for simple themes.

In general, however, the colorScheme field is most important as per modern conventions you should be using Theme.of(context).colorScheme.<Color> (though it may not work everywhere yet depending on when you read this).

So, if you need more control over individual theme colors, you could either make do with setting the fields used in ColorScheme.fromSwatch, or just set the primarySwatch (for backwards compatibility of Flutter Widgets that have not yet been migrated), and then set the colorScheme manually for extra control. See also this document for more information…


问:
Problems with playing videos ARCore
I followed the example code listed on the AugmentedImageController for ARCore unity on github at: https://github.com/google-ar/arcore-unity-sdk/blob/master/Assets/GoogleARCore/Examples/AugmentedImage/Scripts/AugmentedImageExampleController.cs.  Even after I've followed the code on this example, it doesn't play the video from the video player as shown on the AugmentedImageVisualizer code below:

The video plays if I drag and drop the AugmentedImageVirtulizer onto the scene and put playOnAwake.  However it doesn't play when I take the playOnAwake off, send the app to my phone, and then point the camera to the augmented image (in my case a empty milk bottle label).  I want an object such as a ghost to appear coming out of the milk bottle.

```<code>    using GoogleARCore;
    using UnityEngine;
    using UnityEngine.Video;

    public class AugmentedImageVisualizer : MonoBehaviour {

    private VideoPlayer vidPlayer;
    public VideoClip[] vidClips;
    public AugmentedImage Image;

// Use this for initialization
void Start () {
    vidPlayer = GetComponent<VideoPlayer>();
    vidPlayer.loopPointReached += OnStop;

}

   private void OnStop(VideoPlayer source)
   {
      gameObject.SetActive(false);
   }

   // Update is called once per frame
   void Update () {

    if (Image == null || Image.TrackingState != TrackingState.Tracking)
    {
        return;
    }

    if (!vidPlayer.isPlaying)
    {
        vidPlayer.clip = vidClips[Image.DatabaseIndex];
        vidPlayer.Play();
    }

    transform.localScale = new Vector3(Image.ExtentX, Image.ExtentZ,
    1f);

  }
      }
</code>```

no console errors showing, but no videos showing

答:
EDIT: I had to edit answer to give more explanation:
I used the examples of augmented image that comes with GoogleARCore to create the AR. Here the controller needs an augmented image visualizer prefab. This prefab is a Quad (right click on hierarchy area, then 3D Object > Quad) and moved it to prefab folder (this creates prefab from quad). This quad/prefab has a videoplayer (added in inspector). This quad(prefab) also has a script (augmentedimagevisualizer) which contains your code snippet. So in the inspector (with augmentedimagevisualizer script) the quad already has videoclips where you can set your videos.
In hierarchy, there is an arcore device and inside is the camera. This camera has Tracked Pose Driver (set it in inspector) with Pose source: Color Camera and AR Core Background Renderer script.
The 2. videolink makes the same and contains your code as well, so this video is very descriptive regarding your question.
I found 2 similar video on youtube.

that shows 1 video: https://www.youtube.com/watch?v=yjj5dV2v9Fs

that shows multiple videos on multiple ref. images:
https://www.youtube.com/watch?v=GkzMFNmvums

The 2. was tricky for me, the guy in video created quad that he renamed to AugmentedImageVisualizer and then he placed it in Prefabs. Since I've realized this my videos appear on ref. images.
I used Unity 2019.3.15 and arcore-unity-sdk-1.17.0.unitypackage

Title: Problems with playing videos ARCore

Body:
I followed the example code listed on the AugmentedImageController for ARCore unity on github at: https://github.com/google-ar/arcore-unity-sdk/blob/master/Assets/GoogleARCore/Examples/AugmentedImage/Scripts/AugmentedImageExampleController.cs.  Even after I've followed the code on this example, it doesn't play the video from the video player as shown on the AugmentedImageVisualizer code below:

The video plays if I drag and drop the AugmentedImageVirtulizer onto the scene and put playOnAwake.  However it doesn't play when I take the playOnAwake off, send the app to my phone, and then point the camera to the augmented image (in my case a empty milk bottle label).  I want an object such as a ghost to appear coming out of the milk bottle.

    using GoogleARCore;
    using UnityEngine;
    using UnityEngine.Video;

    public class AugmentedImageVisualizer : MonoBehaviour {

    private VideoPlayer vidPlayer;
    public VideoClip[] vidClips;
    public AugmentedImage Image;

// Use this for initialization
void Start () {
    vidPlayer = GetComponent<VideoPlayer>();
    vidPlayer.loopPointReached += OnStop;

}

   private void OnStop(VideoPlayer source)
   {
      gameObject.SetActive(false);
   }

   // Update is called once per frame
   void Update () {

    if (Image == null || Image.TrackingState != TrackingState.Tracking)
    {
        return;
    }

    if (!vidPlayer.isPlaying)
    {
        vidPlayer.clip = vidClips[Image.DatabaseIndex];
        vidPlayer.Play();
    }

    transform.localScale = new Vector3(Image.ExtentX, Image.ExtentZ,
    1f);

  }
      }

no console errors showing, but no videos showing


问:
displaying data as a line in charts
```<code>df <- read.csv('https://raw.githubusercontent.com/ulklc/covid19-
timeseries/master/countryReport/raw/rawReport.csv')
df$countryName = as.character(df$countryName)
</code>```

I processed the dataset.

Can we show the patient and population charts of the continents as separate line charts on the same chart?

as output;

''date         region    confirmed
''2020/01/03   europa     850

The data in the output I created are examples. The data in the example are not real.

答:
Here's an approach with dplyr, tidyr and ggplot:

```<code>library(dplyr)
library(tidyr)
library(ggplot2)
df %>%
  group_by(region, day) %>%
  dplyr::summarize(confirmed = sum(confirmed),
            recovered = sum(recovered),
            death = sum(death)) %>%
  pivot_longer(cols = c("confirmed","recovered","death"), names_to = "condition") %>%
ggplot(aes(x= as.Date(day), y = value, group = region, color = region)) +
  geom_line() +
  facet_grid(rows = vars(condition), scales = "free_y") +
  labs(x = "Date", y = "Number of Individuals")
</code>```

Title: displaying data as a line in charts

Body:
df <- read.csv('https://raw.githubusercontent.com/ulklc/covid19-
timeseries/master/countryReport/raw/rawReport.csv')
df$countryName = as.character(df$countryName)

I processed the dataset.

Can we show the patient and population charts of the continents as separate line charts on the same chart?

as output;

''date         region    confirmed
''2020/01/03   europa     850

The data in the output I created are examples. The data in the example are not real.

Body:
Here's an approach with dplyr, tidyr and ggplot:

library(dplyr)
library(tidyr)
library(ggplot2)
df %>%
  group_by(region, day) %>%
  dplyr::summarize(confirmed = sum(confirmed),
            recovered = sum(recovered),
            death = sum(death)) %>%
  pivot_longer(cols = c("confirmed","recovered","death"), names_to = "condition") %>%
ggplot(aes(x= as.Date(day), y = value, group = region, color = region)) +
  geom_line() +
  facet_grid(rows = vars(condition), scales = "free_y") +
  labs(x = "Date", y = "Number of Individuals")


问:
ScalaFX - How to get the title of a Scene using a method
I am using ScalaFX and trying to learn how it works. As an exerpiment (not what I will do in production) I want a method that gets the title of a window.

So here is my Graph.scala file:

```<code>package graphing

import scalafx.application.JFXApp
import scalafx.scene.Scene
import scalafx.scene.paint.Color

class Graph {
  val app = new JFXApp {
    stage = new JFXApp.PrimaryStage {
      title = "First GUI"
      scene = new Scene {
        fill = Color.Coral
      }
    }
  }

  def getTitle() = {
    app.stage.getTitle
  }

  def generateChart(args: Array[String]) = app.main(args)
}
</code>```

Here is my driver object that makes use of this Graph class:

```<code>package graphing

import graphing.Graph

object Driver extends App {
  val graph = new Graph

println(graph.getTitle())

  graph.generateChart(args)
}
</code>```

However, this does not work due to the line

println(graph.getTitle())

The error that is thrown:

Could someone kindly explain what is going on and how I can achieve my goal here?

答:
The problem here concerns JavaFX (and hence, ScalaFX) initialization.

Initializing JavaFX is a complex business. (Indeed, I only recently learned that it was even more complicated than I originally believed it to be. Refer to this recent answer here on StackOverflow for further background. Fortunately, your problem is a little easier to resolve.)

ScalaFX simplifies JavaFX initialization greatly, but requires that the JFXApp trait be used as part of the definition of an object.

JFXApp contains a main method, which must be the starting point of your application; it is this method that takes care of the complexities of initializing JavaFX for you.

In your example, you have your Driver object extend scala.App, and so it is App's  (and hence, Driver's) main method that becomes the starting point of your own application. This is fine for a regular command line interface (CLI) application, but it cannot be used with ScalaFX/JavaFX applications without a great deal of additional complexity.

In your code, JFXApp's main method never executes, because, as it is defined as a class member, it is not the main method of a Scala object, and so is not a candidate for automatic execution by the JVM. You do call it manually from your Graph.generateChart() method, but that method itself is not called until after you try to get the title of the scene, hence the NPE as the stage has not yet been initialized.

What if you put the graph.generateChart(args) call before the println(graph.getTitle()) statement? Will that fix it? Sadly, no.

Here's why...

JFXApp also performs one other bit of magic: it executes the construction code for its object (and for any other classes extended by that object, but not for extended traits) on the JavaFX Application Thread (JAT). This is important: only code that executes on the JAT can interact directly with JavaFX (even if through ScalaFX). If you attempt to perform JavaFX operations on any other thread, including the application's main thread, then you will get exceptions.

(This magic relies on a deprecated Scala trait, scala.DelayedInit, which has been removed from the libraries for Scala 3.0, aka Dotty, so a different mechanism will be required in the future. However, it's worth reading the documentation for that trait for further background.)

So, when Driver's construction code calls graph.generateChart(args), it causes JavaFX to be initialized, starts the JAT, and executes Graph's construction code upon it. However, by the time Driver's constructor calls println(graph.getTitle()), which is still executing on the main thread, there are two problems:

Graph's construction code may, or may not, have been executed, as it is being executed on a different thread. (This problem is called a race condition, because there's a race between the main thread trying to call println(graph.getTitle()), and the JAT trying to initialize the graph instance.) You may win the race on some occasions, but you're going to lose quite often, too.

You're trying to interact with JavaFX from the main thread, instead of from the JAT.

Here is the recommended approach for your application to work:

package graphing

import scalafx.application.JFXApp
import scalafx.scene.Scene
import scalafx.scene.paint.Color

object GraphDriver
extends JFXApp {

  // This executes at program startup, automatically, on the JAT.
  stage = new JFXApp.PrimaryStage {
    title = "First GUI"
    scene = new Scene {
      fill = Color.Coral
    }
  }

  // Print the title. Works, because we're executing on the JAT. If we're NOT on the JAT,
  // Then getTitle() would need to be called via scalafx.application.Platform.runLater().
  println(getTitle())

  // Retrieve the title of the stage. Should equal "First GUI".
  //
  // It's guaranteed that "stage" will be initialized and valid when called.
  def getTitle() = stage.title.value
}
```

<p>Note that I've combined your <code>Graph</code> class and <code>Driver</code> object into a single object, <code>GraphDriver</code>. While I'm not sure what your application needs to look like architecturally, this should be an OK starting point for you.</p>

<p>Note also that <code>scala.App</code> is not used at all.</p>

<p>Take care when calling <code>GraphDriver.getTitle()</code>: this code needs to execute on the <em>JAT</em>. The standard workaround for executing any code, that might be running on a different thread, is to pass it <em>by name</em> to <code>scalafx.application.Platform.runLater()</code>. For example:</p>

<pre class="lang-scala prettyprint-override"><code>import scalafx.application.Platform

// ...
Platform.runLater(println(ObjectDriver.getTitle()))
// ...
</code>```

Body:
I am using ScalaFX and trying to learn how it works. As an exerpiment (not what I will do in production) I want a method that gets the title of a window.

So here is my Graph.scala file:

package graphing

import scalafx.application.JFXApp
import scalafx.scene.Scene
import scalafx.scene.paint.Color

class Graph {
  val app = new JFXApp {
    stage = new JFXApp.PrimaryStage {
      title = "First GUI"
      scene = new Scene {
        fill = Color.Coral
      }
    }
  }

  def getTitle() = {
    app.stage.getTitle
  }

  def generateChart(args: Array[String]) = app.main(args)
}

Here is my driver object that makes use of this Graph class:

package graphing

import graphing.Graph

object Driver extends App {
  val graph = new Graph

println(graph.getTitle())

  graph.generateChart(args)
}

However, this does not work due to the line

println(graph.getTitle())

The error that is thrown:

Could someone kindly explain what is going on and how I can achieve my goal here?

Body:
The problem here concerns JavaFX (and hence, ScalaFX) initialization.

Initializing JavaFX is a complex business. (Indeed, I only recently learned that it was even more complicated than I originally believed it to be. Refer to this recent answer here on StackOverflow for further background. Fortunately, your problem is a little easier to resolve.)

ScalaFX simplifies JavaFX initialization greatly, but requires that the JFXApp trait be used as part of the definition of an object.

JFXApp contains a main method, which must be the starting point of your application; it is this method that takes care of the complexities of initializing JavaFX for you.

In your example, you have your Driver object extend scala.App, and so it is App's  (and hence, Driver's) main method that becomes the starting point of your own application. This is fine for a regular command line interface (CLI) application, but it cannot be used with ScalaFX/JavaFX applications without a great deal of additional complexity.

In your code, JFXApp's main method never executes, because, as it is defined as a class member, it is not the main method of a Scala object, and so is not a candidate for automatic execution by the JVM. You do call it manually from your Graph.generateChart() method, but that method itself is not called until after you try to get the title of the scene, hence the NPE as the stage has not yet been initialized.

What if you put the graph.generateChart(args) call before the println(graph.getTitle()) statement? Will that fix it? Sadly, no.

Here's why...

JFXApp also performs one other bit of magic: it executes the construction code for its object (and for any other classes extended by that object, but not for extended traits) on the JavaFX Application Thread (JAT). This is important: only code that executes on the JAT can interact directly with JavaFX (even if through ScalaFX). If you attempt to perform JavaFX operations on any other thread, including the application's main thread, then you will get exceptions.

(This magic relies on a deprecated Scala trait, scala.DelayedInit, which has been removed from the libraries for Scala 3.0, aka Dotty, so a different mechanism will be required in the future. However, it's worth reading the documentation for that trait for further background.)

So, when Driver's construction code calls graph.generateChart(args), it causes JavaFX to be initialized, starts the JAT, and executes Graph's construction code upon it. However, by the time Driver's constructor calls println(graph.getTitle()), which is still executing on the main thread, there are two problems:

Graph's construction code may, or may not, have been executed, as it is being executed on a different thread. (This problem is called a race condition, because there's a race between the main thread trying to call println(graph.getTitle()), and the JAT trying to initialize the graph instance.) You may win the race on some occasions, but you're going to lose quite often, too.

You're trying to interact with JavaFX from the main thread, instead of from the JAT.

Here is the recommended approach for your application to work:

package graphing

import scalafx.application.JFXApp
import scalafx.scene.Scene
import scalafx.scene.paint.Color

object GraphDriver
extends JFXApp {

  // This executes at program startup, automatically, on the JAT.
  stage = new JFXApp.PrimaryStage {
    title = "First GUI"
    scene = new Scene {
      fill = Color.Coral
    }
  }

  // Print the title. Works, because we're executing on the JAT. If we're NOT on the JAT,
  // Then getTitle() would need to be called via scalafx.application.Platform.runLater().
  println(getTitle())

  // Retrieve the title of the stage. Should equal "First GUI".
  //
  // It's guaranteed that "stage" will be initialized and valid when called.
  def getTitle() = stage.title.value
}

Note that I've combined your Graph class and Driver object into a single object, GraphDriver. While I'm not sure what your application needs to look like architecturally, this should be an OK starting point for you.

Note also that scala.App is not used at all.

Take care when calling GraphDriver.getTitle(): this code needs to execute on the JAT. The standard workaround for executing any code, that might be running on a different thread, is to pass it by name to scalafx.application.Platform.runLater(). For example:

import scalafx.application.Platform

// ...
Platform.runLater(println(ObjectDriver.getTitle()))
// ...


问:
Instasharper does not return Likers and Tags list
I have this piece of code in C# using InstaSharper to return information of a media id from Instagram.

```<code>public async Task<UserSessionData> SignIn(string userName, string password)
        {
            userSessionData = new UserSessionData();
            userSessionData.UserName = "username";
            userSessionData.Password = "password";
            api = InstaApiBuilder.CreateBuilder()
                .SetUser(userSessionData)
                .Build();
            var loginRequest = await api.LoginAsync();
            if (loginRequest.Succeeded && api.IsUserAuthenticated)
            {
                IResult<InstaUser> userSearch = await api.GetUserAsync(userName);
                IResult<InstaMediaList> media = await api.GetUserMediaAsync(userName, PaginationParameters.MaxPagesToLoad(1));
                IResult<InstaMedia> mediaInfo =  await api.GetMediaByIdAsync("1924613027431050955");
                return userSessionData;
            }
            else
            {
                return null;
            }
        }
</code>```

GetMediaByIdAsync method correctly returns data about the requested media but the Likers and Tags collection is empty. Is there any way to include those data?

答:
Had the same issue, I found the solution.
Try using this code:

```<code>var posts = await api.GetUserMediaAsync("username", PaginationParameters.MaxPagesToLoad(Int32.MaxValue)); // If you want to load all of the posts. If not, replace the "Int32.MaxValue" with the amount of posts you want to load
foreach (var post in posts.Value)
{
    var likers = await api.GetMediaLikersAsync(post.InstaIdentifier);
    foreach (var liker in likers.Value)
    {
        Console.WriteLine(liker.UserName);
    }
}
</code>```

This works fine for me, try it out, Im sure it will work for you as well.

Body:
I have this piece of code in C# using InstaSharper to return information of a media id from Instagram.

public async Task<UserSessionData> SignIn(string userName, string password)
        {
            userSessionData = new UserSessionData();
            userSessionData.UserName = "username";
            userSessionData.Password = "password";
            api = InstaApiBuilder.CreateBuilder()
                .SetUser(userSessionData)
                .Build();
            var loginRequest = await api.LoginAsync();
            if (loginRequest.Succeeded && api.IsUserAuthenticated)
            {
                IResult<InstaUser> userSearch = await api.GetUserAsync(userName);
                IResult<InstaMediaList> media = await api.GetUserMediaAsync(userName, PaginationParameters.MaxPagesToLoad(1));
                IResult<InstaMedia> mediaInfo =  await api.GetMediaByIdAsync("1924613027431050955");
                return userSessionData;
            }
            else
            {
                return null;
            }
        }

GetMediaByIdAsync method correctly returns data about the requested media but the Likers and Tags collection is empty. Is there any way to include those data?

Body:
Had the same issue, I found the solution.
Try using this code:

var posts = await api.GetUserMediaAsync("username", PaginationParameters.MaxPagesToLoad(Int32.MaxValue)); // If you want to load all of the posts. If not, replace the "Int32.MaxValue" with the amount of posts you want to load
foreach (var post in posts.Value)
{
    var likers = await api.GetMediaLikersAsync(post.InstaIdentifier);
    foreach (var liker in likers.Value)
    {
        Console.WriteLine(liker.UserName);
    }
}

This works fine for me, try it out, Im sure it will work for you as well.


问:
How to create a list of instances of a given class
I'm facing problem with my code. In fact, I need to create a list of instances of my class( Patent). The name of the list is patent_ints. But when I'm trying to verify if any element in that list is a Patent one, I'm always getting a False response. And when iterating the first element is like "<__main__.Patent at 0x7f107820b710>".
Here is my code, I need help !

```<code>import json
import datetime

patent_data = json.loads(open('NASA_data.json', "r").read())
unique_center = []
for thing in patent_data["Patent_Information"]["Results"]:
    for val in thing:
        if(val == 'NASA Center'):
            unique_center.append(thing[val])

total_num_centers = len(set(unique_center))
class Patent:
    def __init__(self, abbreviated_organization_name, dict_data):
        self.org_name = abbreviated_organization_name
        self.title = dict_data["Title"]
        # initialize instance variable called year. The value can be extracted from dict_data.
        # This should be a four digit string.
        self.year = str(datetime.datetime.strptime(dict_data['Date'], '%m/%d/%Y').year) #dict_data['Date'].split('/')[2]
        # initialize an instance variable called month. The value can be extracted from dict_data.
        # This should be a two digit string.
        self.month = str(datetime.datetime.strptime(dict_data['Date'], '%m/%d/%Y').month) #dict_data['Date'].split('/')[0]
        # initialize an instance variable called day. The value can be extracted from dict_data.
        # This should be a two digit string.
        self.day = str(datetime.datetime.strptime(dict_data['Date'], '%m/%d/%Y').day) #dict_data['Date'].split('/')[1]
        self.id = dict_data['Case Number']
        self.access_limit = dict_data['SRA Final']

patent_ints = [Patent(i, data) for i in unique_center for data in patent_data["Patent_Information"]["Results"]]
patent_ints[0]
</code>```

Thank you in advance!

答:
<__main__.Patent at 0x7f107820b710> is the default representation of the class when you try to print it. Add an __str__ or __repr__ method to the class and define some custom logic to return your desired details as a string:

class Patent:
    def __init__(self, abbreviated_organization_name, dict_data):
        ...

    def __repr__(self):
        # return a dictionary of items in the class but you can return whatever you want
        # you could do f'{self.title} {self.id} {self.year}-{self.month}-{self.day}' but str(self.__dict__) is quick to test
        return str(self.__dict__)
```

Body:
I'm facing problem with my code. In fact, I need to create a list of instances of my class( Patent). The name of the list is patent_ints. But when I'm trying to verify if any element in that list is a Patent one, I'm always getting a False response. And when iterating the first element is like "<__main__.Patent at 0x7f107820b710>".
Here is my code, I need help !

import json
import datetime

patent_data = json.loads(open('NASA_data.json', "r").read())
unique_center = []
for thing in patent_data["Patent_Information"]["Results"]:
    for val in thing:
        if(val == 'NASA Center'):
            unique_center.append(thing[val])

total_num_centers = len(set(unique_center))
class Patent:
    def __init__(self, abbreviated_organization_name, dict_data):
        self.org_name = abbreviated_organization_name
        self.title = dict_data["Title"]
        # initialize instance variable called year. The value can be extracted from dict_data.
        # This should be a four digit string.
        self.year = str(datetime.datetime.strptime(dict_data['Date'], '%m/%d/%Y').year) #dict_data['Date'].split('/')[2]
        # initialize an instance variable called month. The value can be extracted from dict_data.
        # This should be a two digit string.
        self.month = str(datetime.datetime.strptime(dict_data['Date'], '%m/%d/%Y').month) #dict_data['Date'].split('/')[0]
        # initialize an instance variable called day. The value can be extracted from dict_data.
        # This should be a two digit string.
        self.day = str(datetime.datetime.strptime(dict_data['Date'], '%m/%d/%Y').day) #dict_data['Date'].split('/')[1]
        self.id = dict_data['Case Number']
        self.access_limit = dict_data['SRA Final']

patent_ints = [Patent(i, data) for i in unique_center for data in patent_data["Patent_Information"]["Results"]]
patent_ints[0]

Thank you in advance!


问:
How to hide aliases from help screen in a cobra app
Is it possible to suppress Aliases to show up in the help screen of a golang cobra app? I basically would like to get rid of the whole "Aliases" section below:

```<code>Usage:
  my-app [flags]

Aliases:
 alias1 , alias2

Flags:
  -h, --help              help for this command
</code>```

I know it's possible to hide flags from showing up in help (cmd.Flags().MarkHidden("myflag")). Is it somehow possible to hide Aliases as well?

答:
That would mean defining your own Usage function, which is possible using usageFunc

Or using a specific Usage template (command#SetUsageTemplate()), as stated in the "Defining your own usage" README section.

You can see the default template here. It does include an Aliases section:

```<code>Aliases:
  {{.NameAndAliases}}{{end}}{{if .HasExample}}
</code>```

All you would need is define the same temaplate, but exclusing the Aliases part.

You can see an example of such a temmplate for emacski/redact.

And yes, it has no Aliases.

```<code>{{with (or .Long .Short)}}{{. | trimTrailingWhitespaces}}{{end}}
{{if .HasAvailableLocalFlags}}
Options:
{{.LocalFlags.FlagUsages | trimTrailingWhitespaces}}{{end}}{{if .HasAvailableSubCommands}}
Commands:{{range .Commands}}{{if (or .IsAvailableCommand (eq .Name "help"))}}
  {{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}{{end}}{{if .HasAvailableSubCommands}}
Use "{{.CommandPath}} COMMAND --help" for more information about a command.{{end}}
</code>```

Body:
Is it possible to suppress Aliases to show up in the help screen of a golang cobra app? I basically would like to get rid of the whole "Aliases" section below:

Usage:
  my-app [flags]

Aliases:
 alias1 , alias2

Flags:
  -h, --help              help for this command

I know it's possible to hide flags from showing up in help (cmd.Flags().MarkHidden("myflag")). Is it somehow possible to hide Aliases as well?

Body:
That would mean defining your own Usage function, which is possible using usageFunc

Or using a specific Usage template (command#SetUsageTemplate()), as stated in the "Defining your own usage" README section.

You can see the default template here. It does include an Aliases section:

Aliases:
  {{.NameAndAliases}}{{end}}{{if .HasExample}}

All you would need is define the same temaplate, but exclusing the Aliases part.

You can see an example of such a temmplate for emacski/redact.

And yes, it has no Aliases.

{{with (or .Long .Short)}}{{. | trimTrailingWhitespaces}}{{end}}
{{if .HasAvailableLocalFlags}}
Options:
{{.LocalFlags.FlagUsages | trimTrailingWhitespaces}}{{end}}{{if .HasAvailableSubCommands}}
Commands:{{range .Commands}}{{if (or .IsAvailableCommand (eq .Name "help"))}}
  {{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}{{end}}{{if .HasAvailableSubCommands}}
Use "{{.CommandPath}} COMMAND --help" for more information about a command.{{end}}


问:
Problem with Laravel routes - all sub folder traffic ending up in route view
Sorry - was difficult to give this one a clear title! But I have an issue and a difference between how my local laravel install is dealing with some routes compared to my live server.

Locally, I have this working:

```<code>Route::get('/blog', 'BlogController@home');
Route::get('/blog/{post_slug}', 'BlogController@viewPost');
</code>```

As you can probably guess, I want to serve up a list of posts via the home() function if /blog is hit. Then all other traffic with a "slug" after /blog/, I want to load the blog post.

This all works locally.

However on live,

/blog/my-blog-post

Is serving up the home() function every time.

Where would I start with debugging this. Laravel versions? Server caching?

答:
Maybe you can do this in laravel 5.7+

```<code>Route::prefix('blog')->group(function () {
    Route::get('/', 'BlogController@home');
    Route::get('/{post_slug}', 'BlogController@viewPost');
});

</code>```

before just use: php artisan optimize, to clear all cache route and config.

for more info see the docs

Body:
Sorry - was difficult to give this one a clear title! But I have an issue and a difference between how my local laravel install is dealing with some routes compared to my live server.

Locally, I have this working:

Route::get('/blog', 'BlogController@home');
Route::get('/blog/{post_slug}', 'BlogController@viewPost');

As you can probably guess, I want to serve up a list of posts via the home() function if /blog is hit. Then all other traffic with a "slug" after /blog/, I want to load the blog post.

This all works locally.

However on live,

/blog/my-blog-post

Is serving up the home() function every time.

Where would I start with debugging this. Laravel versions? Server caching?

Body:
Maybe you can do this in laravel 5.7+

Route::prefix('blog')->group(function () {
    Route::get('/', 'BlogController@home');
    Route::get('/{post_slug}', 'BlogController@viewPost');
});

before just use: php artisan optimize, to clear all cache route and config.

for more info see the docs


问:
I want recover breakpoints which was deleted accidently. (Eclipse)
I accidently delete all my breakpoints and I want to know how to restore them back. Can someone please help me? Thanks</p>

答: Restart the application by killing the process. It worked in IntelliJ too</p>

ContentLicense: CC BY-SA 3.0


问:
What's the meaning of the ethereum Parity console output lines?
Parity doesn't seem to have any documentation on what it's console output means. At least none that I've found which admittedly doesn't mean a whole lot. Can anyone give me a breakdown of the meaning of the following line?

```<code>2018-03-09 00:05:12 UTC Syncing #4896969 61ee…bdad     2 blk/s  508 tx/s  16 Mgas/s    645+    1 Qed  #4897616   17/25 peers      4 MiB chain  135 MiB db   42 MiB queue    5 MiB sync  RPC:  0 conn,  0 req/s, 182 µs
</code>```

Thanks.

答:
Now the answer to this question is also included in Parity's FAQ. It provides a comprehensive explanation of different command line output:

What does Parity's command line output mean?

Body:
Parity doesn't seem to have any documentation on what it's console output means. At least none that I've found which admittedly doesn't mean a whole lot. Can anyone give me a breakdown of the meaning of the following line?

2018-03-09 00:05:12 UTC Syncing #4896969 61ee…bdad     2 blk/s  508 tx/s  16 Mgas/s    645+    1 Qed  #4897616   17/25 peers      4 MiB chain  135 MiB db   42 MiB queue    5 MiB sync  RPC:  0 conn,  0 req/s, 182 µs

Thanks.


问:
CSS Navbar items are not in order?
I have my navbar items in the order of "offerings," "about," and "contact us."

On the live website it is "about" then "contact us" then "offering"

Is there some sort of code or div grouping I can use to make sure they display in the order listed?

Pasting the code from my application.html.erb:

```<code>div class="navbar-order">
    <ul class="nav navbar-nav navbar-right">
      <div class="dropdown">
        <button class="dropbtn"><li><%= link_to "Offerings", offerings_path %></li></button>

        <div class="dropdown-content">
          <li><%= link_to "Public Speaking", pages_public_speaking_path %></li>
          <li><%= link_to "Nonverbal Communication", nonverbal_path %></li>
          <li><%= link_to "Group Dynamics", group_dynamics_path %></li>
          <li><%= link_to "Intercultural Communication", intercultural_communication_path %></li>
          <li><%= link_to "Editing", editing_path %></li>
          <li><%= link_to "Interviewing", interviewing_path %></li>
          <li><%= link_to "Business Etiquette", business_etiquette_path %></li>
          <li><%= link_to "Business Writing", business_writing_path %></li>
        </div>
      </div>

     <li><%= link_to "About", about_path %></li>
     <li><%= link_to "Contact Form", new_contact_path %></li>

     </ul>
   </div>

</code>```

答:
ul {
display:flex;
list-style-type: none;
}
ul li {
  margin-right:20px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><nav>
<ul>
<li>The</li>
<li> Correct</li>
<li>Order</li>
</ul>
</nav></code>```

Try to re-structure Your HTML nav markup.

The point is that You should put
's in the
 and not the divs. If You create the markup properly and put some
display:flex or display:inline-block on the
, there is no way that it's displayed in the broken order

Title: CSS Navbar items are not in order?

Body:
I have my navbar items in the order of "offerings," "about," and "contact us."

On the live website it is "about" then "contact us" then "offering"

Is there some sort of code or div grouping I can use to make sure they display in the order listed?

Pasting the code from my application.html.erb:

div class="navbar-order">

        <button class="dropbtn">
<%= link_to "Offerings", offerings_path %>
</button>

<%= link_to "Public Speaking", pages_public_speaking_path %>

<%= link_to "Nonverbal Communication", nonverbal_path %>

<%= link_to "Group Dynamics", group_dynamics_path %>

<%= link_to "Intercultural Communication", intercultural_communication_path %>

<%= link_to "Editing", editing_path %>

<%= link_to "Interviewing", interviewing_path %>

<%= link_to "Business Etiquette", business_etiquette_path %>

<%= link_to "Business Writing", business_writing_path %>

<%= link_to "About", about_path %>

<%= link_to "Contact Form", new_contact_path %>

Body:
ul {
display:flex;
list-style-type: none;
}
ul li {
  margin-right:20px;
}

<nav>
<ul>
<li>The</li>
<li> Correct</li>
<li>Order</li>
</ul>
</nav>

Try to re-structure Your HTML nav markup.

The point is that You should put <li>'s in the <ul> and not the divs. If You create the markup properly and put some
display:flex or display:inline-block on the <ul>, there is no way that it's displayed in the broken order


问:
Semantic UI React- button size has no impact on size
I'm trying to incorporate Semantic-UI into my site due to some apparent limitations with react-strap. However, I've run into an issue. The content width is fixed, and therefore the rightmost button is getting slightly truncated.

I tried resizing per the docs:

```<code>  <div>
    <Button size='mini'>Mini</Button>
    <Button size='tiny'>Tiny</Button>
    <Button size='small'>Small</Button>
    <Button size='medium'>Medium</Button>
    <Button size='large'>Large</Button>
    <Button size='big'>Big</Button>
    <Button size='huge'>Huge</Button>
    <Button size='massive'>Massive</Button>
  </div>
</code>```

But nothing seems to make a difference here the code:

```<code><Button.Group>
    <Button class="tiny ui button" positive as={Link} to={"/licenses/" + license.id}>Edit</Button>
    <Button class="tiny ui button" color='blue' onClick={() => this.download(license.url)}>Download</Button>
    <Button class="tiny ui button"  negative onClick={() => this.remove(license.id)}>xDelete</Button>
  </Button.Group>
</code>```

Any ideas?

答: You need to use the same attribute as per the docs - instead of giving your buttons a class of tiny, it should be a size of tiny.

Body:
I'm trying to incorporate Semantic-UI into my site due to some apparent limitations with react-strap. However, I've run into an issue. The content width is fixed, and therefore the rightmost button is getting slightly truncated.

I tried resizing per the docs:

    <Button size='mini'>Mini</Button>
    <Button size='tiny'>Tiny</Button>
    <Button size='small'>Small</Button>
    <Button size='medium'>Medium</Button>
    <Button size='large'>Large</Button>
    <Button size='big'>Big</Button>
    <Button size='huge'>Huge</Button>
    <Button size='massive'>Massive</Button>

But nothing seems to make a difference here the code:

<Button.Group>
    <Button class="tiny ui button" positive as={Link} to={"/licenses/" + license.id}>Edit</Button>
    <Button class="tiny ui button" color='blue' onClick={() => this.download(license.url)}>Download</Button>
    <Button class="tiny ui button"  negative onClick={() => this.remove(license.id)}>xDelete</Button>
  </Button.Group>

Any ideas?


问:
Some issues with "read access violation"
```<code>#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdarg.h>
#include <string.h>
typedef struct  {
    char name[128], code[128];
} info;
info db[3];
info* data=db;
void find (const char *code, int size, ...) {

    bool mismatch = true;
    va_list arg;
    va_start(arg,size);
    while (size-- > 0) {
        data = va_arg(arg,info*);
        printf("%s", data->code);
        if (!strcmp(data->code,code))
        {
            printf("%s [id:%s]\n",data->name,data->code), mismatch = false;
            }
    }
    if (mismatch) printf("No data available!");
    return;
}

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

    const char *spec[] = {
        "Physics of Elementary Particles",
        "Physics of Hign Energy",
        "Low-level Programming"
    };
    const char *code[] = {
        "2396","0812", "0773"
    };`enter code here`
    for (int count = 0; count < 3; ++count) {
        strncpy(db[count].name,spec[count],128);
        strncpy(db[count].code,code[count],128);
    }
    find("0812",3,db[0],db[1],db[2]);

    return 0;
}
</code>```

After running it says "read access violation", although I hope everything is correct, it happens after function "va_arg(arg, info*)". Is it some troubles with   stack or decrypting?

答:
The problem is in the function call:

```<code>find("0812",3,db[0],db[1],db[2]);
</code>```

The variadic argument that you're passing in are of type info.  However, when you retrieve them with va_arg you're looking for a info *.  These don't match up.

You want to pass in the address of each array member.

```<code>find("0812",3,&db[0],&db[1],&db[2]);
</code>```

Also, you need to call va_end at the bottom of find before you return.

Body:
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdarg.h>
#include <string.h>
typedef struct  {
    char name[128], code[128];
} info;
info db[3];
info* data=db;
void find (const char *code, int size, ...) {

    bool mismatch = true;
    va_list arg;
    va_start(arg,size);
    while (size-- > 0) {
        data = va_arg(arg,info*);
        printf("%s", data->code);
        if (!strcmp(data->code,code))
        {
            printf("%s [id:%s]\n",data->name,data->code), mismatch = false;
            }
    }
    if (mismatch) printf("No data available!");
    return;
}

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

    const char *spec[] = {
        "Physics of Elementary Particles",
        "Physics of Hign Energy",
        "Low-level Programming"
    };
    const char *code[] = {
        "2396","0812", "0773"
    };`enter code here`
    for (int count = 0; count < 3; ++count) {
        strncpy(db[count].name,spec[count],128);
        strncpy(db[count].code,code[count],128);
    }
    find("0812",3,db[0],db[1],db[2]);

    return 0;
}

After running it says "read access violation", although I hope everything is correct, it happens after function "va_arg(arg, info*)". Is it some troubles with   stack or decrypting?

Body:
The problem is in the function call:

find("0812",3,db[0],db[1],db[2]);

The variadic argument that you're passing in are of type info.  However, when you retrieve them with va_arg you're looking for a info *.  These don't match up.

You want to pass in the address of each array member.

find("0812",3,&db[0],&db[1],&db[2]);

Also, you need to call va_end at the bottom of find before you return.


问:
neo4j find paths between nodes with with the fewest stages
I start to learn neo4j. I am using the graph

http://neo4j.com/graphgist/b1f6439d-2904-4fcf-8017-8c83d57ef20b#listing_category=sports-and-recreation

and I have a small issue. I do not know how to find routes that you can get from Darjeeling to Sandakphu with the fewest stages

Could anyone see how should be build correct query, should I use shortest path function?

Currently I'm testing something like:

```<code>MATCH (p:peak{name:'Sandakphu'})-[r*..5]-(t:town{name:'Darjeeling'})
RETURN r
MATCH path = ShortestPath((p)-[*..5])-(t)]
RETURN path
</code>```

答:
Try the following:</p>

```<code> MATCH (p:peak{name:'Sandakphu'}), (t:town{name:'Darjeeling'})
 MATCH path = ShortestPath((p)-[*..5]-(t))
 RETURN path
</code>```

Body:
I start to learn neo4j. I am using the graph

http://neo4j.com/graphgist/b1f6439d-2904-4fcf-8017-8c83d57ef20b#listing_category=sports-and-recreation

and I have a small issue. I do not know how to find routes that you can get from Darjeeling to Sandakphu with the fewest stages

Could anyone see how should be build correct query, should I use shortest path function?

Currently I'm testing something like:

MATCH (p:peak{name:'Sandakphu'})-[r*..5]-(t:town{name:'Darjeeling'})
RETURN r
MATCH path = ShortestPath((p)-[*..5])-(t)]
RETURN path

Body:
Try the following:

 MATCH (p:peak{name:'Sandakphu'}), (t:town{name:'Darjeeling'})
 MATCH path = ShortestPath((p)-[*..5]-(t))
 RETURN path


问:
swap key value pairs in a dictionary with values as lists
I have a dictionary with keys and values as lists. something like:

```<code>d={1:[0,1,2,3,4],2:[1,3]}
</code>```

I was on the lookout for swapping key value pairs. The output I am trying to get is:

```<code>o={0:[1],1:[1,2],2:[1],3:[1,2],4:[1]}
</code>```

Was wondering if there is a way to achieve this in the most efficient way

Body:
I have a dictionary with keys and values as lists. something like:

d={1:[0,1,2,3,4],2:[1,3]}

I was on the lookout for swapping key value pairs. The output I am trying to get is:

o={0:[1],1:[1,2],2:[1],3:[1,2],4:[1]}

Was wondering if there is a way to achieve this in the most efficient way

Body:
Use defaultdict:

In [30]: d={1:[0,1,2,3,4],2:[1,3]}

In [31]: from collections import defaultdict
In [32]: out = defaultdict(list)
In [33]: for k, v in d.items():
    ...:     for vv in v:
    ...:         out[vv].append(k)
    ...:

In [34]: dict(out)
Out[34]: {0: [1], 1: [1, 2], 2: [1], 3: [1, 2], 4: [1]}


问:
Excel VBA (sub or function not defined error)
I am working on the following code in VBA excel and i get the compile error "sub or function not defined"
The code is meant to copy the cells and paste their transpose at a certain offset.
Any help would be highly appreciated.

Code

```<code>Sub copy_paste()
ActiveCells.Copy
Offset(-1, 1).Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
    :=False, Transpose:=True
Offset(3, -1).Select
Range(Selection, Selection.End(xlToRight)).Select
Application.CutCopyMode = False
Selection.Copy
Offset(-2, 0).Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
    :=False, Transpose:=True
Offset(1, 0).Select
Range(Selection, Selection.End(xlToRight)).Select
Application.CutCopyMode = False
Selection.ClearContents

End Sub
</code>```

Thanking in advance, here is the code along with the error:

答:
Try this code, please. It avoids selecting, which consumes Excel resources, without any benefit. Offset makes sense only if it references a range:

```<code>Sub testCopy()
    Dim sh As Worksheet, rng As Range
    Set sh = ActiveSheet 'use here your sheet
    Set rng = ActiveCell 'use here what range you need
    rng.Copy
    rng.Offset(-1, 1).PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
                                                                :=False, Transpose:=True
    sh.Range(rng.Offset(3, -1), rng.Offset(3, -1).End(xlToRight)).Copy

    rng.Offset(-2, 0).PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
                                                                :=False, Transpose:=True
    sh.Range(rng.Offset(1, 0), rng.Offset(1, 0).End(xlToRight)).ClearContents
End Sub
</code>```

Body:
I am working on the following code in VBA excel and i get the compile error "sub or function not defined"
The code is meant to copy the cells and paste their transpose at a certain offset.
Any help would be highly appreciated.

Code

Sub copy_paste()
ActiveCells.Copy
Offset(-1, 1).Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
    :=False, Transpose:=True
Offset(3, -1).Select
Range(Selection, Selection.End(xlToRight)).Select
Application.CutCopyMode = False
Selection.Copy
Offset(-2, 0).Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
    :=False, Transpose:=True
Offset(1, 0).Select
Range(Selection, Selection.End(xlToRight)).Select
Application.CutCopyMode = False
Selection.ClearContents

End Sub

Thanking in advance, here is the code along with the error:

Body:
Try this code, please. It avoids selecting, which consumes Excel resources, without any benefit. Offset makes sense only if it references a range:

Sub testCopy()
    Dim sh As Worksheet, rng As Range
    Set sh = ActiveSheet 'use here your sheet
    Set rng = ActiveCell 'use here what range you need
    rng.Copy
    rng.Offset(-1, 1).PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
                                                                :=False, Transpose:=True
    sh.Range(rng.Offset(3, -1), rng.Offset(3, -1).End(xlToRight)).Copy

    rng.Offset(-2, 0).PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
                                                                :=False, Transpose:=True
    sh.Range(rng.Offset(1, 0), rng.Offset(1, 0).End(xlToRight)).ClearContents
End Sub


问:
How to store user data locally in SwiftUI
I try to accomplish having an observable object with a published value training. On every change it should save the custom struct to the user defaults. On every load (AppState init) it should load the data:

```<code>class AppState: ObservableObject {

    var trainings: [Training] {
        willSet {
            if let encoded = try? JSONEncoder().encode(trainings) {
                let defaults = UserDefaults.standard
                 defaults.set(encoded, forKey: "trainings")
            }
            objectWillChange.send()
        }
    }

    init() {
        self.trainings = []
        if let savedTrainings = UserDefaults.standard.object(forKey: "trainings") as? Data {
            if let loadedTraining = try? JSONDecoder().decode([Training].self, from: savedTrainings) {
                self.trainings = loadedTraining
            }
        }
    }

}
</code>```

I know if this is best practice, but I want to save the data locally.
The code I wrote is not working and I can't figure out why.

I'm a beginner and I never stored data to a device.

答:
Each time you call the init method the first line resets the value stored in UserDefaults and in-turn returns the empty array instead of the value that was previously stored. Try this modification to your init method to fix it:

```<code>init() {
    if let savedTrainings = UserDefaults.standard.object(forKey: "trainings") as? Data,
        let loadedTraining = try? JSONDecoder().decode([Training].self, from: savedTrainings) {
        self.trainings = loadedTraining
    } else {
        self.trainings = []
    }
}
</code>```

Better Approach: A much better approach would to modify your trainings property to have a get and set instead of the current setup. Here is an example:

var trainings: [Training] {
    set {
        if let encoded = try? JSONEncoder().encode(newValue) {
            let defaults = UserDefaults.standard
             defaults.set(encoded, forKey: "trainings")
        }
        objectWillChange.send()
    }
    get {
        if let savedTrainings = UserDefaults.standard.object(forKey: "trainings") as? Data,
            let loadedTraining = try? JSONDecoder().decode([Training].self, from: savedTrainings) {
            return loadedTraining
        }
        return []
    }
}
```

<p>Note: This can again be improved using Swift 5.1's <code>@PropertyWrapper</code>. Let me know in the comments if anyone wants me to include that as well in the answer.</p>

<p>Update: Here's the solution that makes it simpler to use <code>UserDefaults</code> using Swift's <code>@PropertyWrapper</code> as you have requested for:-</p>

<pre class="lang-swift prettyprint-override"><code>@propertyWrapper struct UserDefault<T: Codable> {
    var key: String
    var wrappedValue: T? {
        get {
            if let data = UserDefaults.standard.object(forKey: key) as? Data {
                return try? JSONDecoder().decode(T.self, from: data)
            }
            return nil
        }
        set {
            if let encoded = try? JSONEncoder().encode(newValue) {
                UserDefaults.standard.set(encoded, forKey: key)
            }
        }
    }
}
class AppState: ObservableObject {
    @UserDefault(key: "trainings") var trainings: [Training]?
    @UserDefault(key: "anotherProperty") var anotherPropertyInUserDefault: AnotherType?
}
</code>```

Body:
I try to accomplish having an observable object with a published value training. On every change it should save the custom struct to the user defaults. On every load (AppState init) it should load the data:

class AppState: ObservableObject {

    var trainings: [Training] {
        willSet {
            if let encoded = try? JSONEncoder().encode(trainings) {
                let defaults = UserDefaults.standard
                 defaults.set(encoded, forKey: "trainings")
            }
            objectWillChange.send()
        }
    }

    init() {
        self.trainings = []
        if let savedTrainings = UserDefaults.standard.object(forKey: "trainings") as? Data {
            if let loadedTraining = try? JSONDecoder().decode([Training].self, from: savedTrainings) {
                self.trainings = loadedTraining
            }
        }
    }

}

I know if this is best practice, but I want to save the data locally.
The code I wrote is not working and I can't figure out why.

I'm a beginner and I never stored data to a device.

Body:
Each time you call the init method the first line resets the value stored in UserDefaults and in-turn returns the empty array instead of the value that was previously stored. Try this modification to your init method to fix it:

init() {
    if let savedTrainings = UserDefaults.standard.object(forKey: "trainings") as? Data,
        let loadedTraining = try? JSONDecoder().decode([Training].self, from: savedTrainings) {
        self.trainings = loadedTraining
    } else {
        self.trainings = []
    }
}

Better Approach: A much better approach would to modify your trainings property to have a get and set instead of the current setup. Here is an example:

var trainings: [Training] {
    set {
        if let encoded = try? JSONEncoder().encode(newValue) {
            let defaults = UserDefaults.standard
             defaults.set(encoded, forKey: "trainings")
        }
        objectWillChange.send()
    }
    get {
        if let savedTrainings = UserDefaults.standard.object(forKey: "trainings") as? Data,
            let loadedTraining = try? JSONDecoder().decode([Training].self, from: savedTrainings) {
            return loadedTraining
        }
        return []
    }
}

Note: This can again be improved using Swift 5.1's @PropertyWrapper. Let me know in the comments if anyone wants me to include that as well in the answer.

Update: Here's the solution that makes it simpler to use UserDefaults using Swift's @PropertyWrapper as you have requested for:-

@propertyWrapper struct UserDefault<T: Codable> {
    var key: String
    var wrappedValue: T? {
        get {
            if let data = UserDefaults.standard.object(forKey: key) as? Data {
                return try? JSONDecoder().decode(T.self, from: data)
            }
            return nil
        }
        set {
            if let encoded = try? JSONEncoder().encode(newValue) {
                UserDefaults.standard.set(encoded, forKey: key)
            }
        }
    }
}
class AppState: ObservableObject {
    @UserDefault(key: "trainings") var trainings: [Training]?
    @UserDefault(key: "anotherProperty") var anotherPropertyInUserDefault: AnotherType?
}


问:
Plotting a cumulative histogram with exported data in Python
I am trying to plot a cumulative histogram similar to the one shown below. It shows the number of occurrences (y-axis) of the French pronoun “vous” in a text corpus (x-axis) represented from word 0 to 92,633. It’s been created using a corpus analysis application named TXM. TXM’s plots, however, are not adapted to the specific requirements of my publisher. I would like to produce my own plots exporting the data to python. The problem is that the data exported by TXM is a bit puzzling, and I am wondering how I it can be used to make plots:
it’s a one-column txt file with integers.

Each one of them indicates the position of “vous” in the text corpus. Word 2620 is one “vous,”
3376, another one, etc. One of my attempts with Matplotlib :

from matplotlib import pyplot as plt

pos = [2620,3367,3756,4522,4546,9914,9972,9979,9987,10013,10047,10087,10114,13635,13645,13646,13758,13771,13783,13796,23410,23420,28179,28265,28274,28297,28344,34579,34590,34612,40280,40449,40570,40932,40938,40969,40983,41006,41040,41069,41096,41120,41214,41474,41478,42524,42533,42534,45569,45587,45598,56450,57574,57587]
plt.bar(pos, 1)
plt.show()
```

But this doesn't come close.
What steps should I follow to complete the plot?

Desired plot:

答:
With matplotlib, you could create the step plot as follows. where='post' means the value changes at every x-position and stays so until the next x-position.
The x-values are the positions in the text, a zero is prepended to let the graph start with zero occurrences. The text-length is appended at the end. The y-values are the numbers 0, 1, 2, ..., where the last value is repeated to draw the last step in full.

from matplotlib import pyplot as plt
from matplotlib.ticker import MultipleLocator, StrMethodFormatter
import numpy as np

pos = [2620,3367,3756,4522,4546,9914,9972,9979,9987,10013,10047,10087,10114,13635,13645,13646,13758,13771,13783,13796,23410,23420,28179,28265,28274,28297,28344,34579,34590,34612,40280,40449,40570,40932,40938,40969,40983,41006,41040,41069,41096,41120,41214,41474,41478,42524,42533,42534,45569,45587,45598,56450,57574,57587]
text_len = 92633
cum = np.arange(0, len(pos) + 1)
fig, ax = plt.subplots(figsize=(12, 3))
ax.step([0] + pos + [text_len], np.pad(cum, (0, 1), 'edge'), where='post', label=f'vous {len(pos)}')
ax.xaxis.set_major_locator(MultipleLocator(5000)) # x-ticks every 5000
ax.xaxis.set_major_formatter(StrMethodFormatter('{x:,.0f}')) # use the thousands separator
ax.yaxis.set_major_locator(MultipleLocator(5)) # have a y-tick every 5
ax.grid(b=True, ls=':') # show a grid with dotted lines
ax.autoscale(enable=True, axis='x', tight=True) # disable padding x-direction
ax.set_xlabel(f'T={text_len:,d}')
ax.set_ylabel('Occurrences')
ax.set_title("Progression of 'vous' in TCN")
plt.legend() # add a legend (uses the label of ax.step)
plt.tight_layout()
plt.show()
```

Body:
I am trying to plot a cumulative histogram similar to the one shown below. It shows the number of occurrences (y-axis) of the French pronoun “vous” in a text corpus (x-axis) represented from word 0 to 92,633. It’s been created using a corpus analysis application named TXM. TXM’s plots, however, are not adapted to the specific requirements of my publisher. I would like to produce my own plots exporting the data to python. The problem is that the data exported by TXM is a bit puzzling, and I am wondering how I it can be used to make plots:
it’s a one-column txt file with integers.

Each one of them indicates the position of “vous” in the text corpus. Word 2620 is one “vous,”
3376, another one, etc. One of my attempts with Matplotlib :

from matplotlib import pyplot as plt

pos = [2620,3367,3756,4522,4546,9914,9972,9979,9987,10013,10047,10087,10114,13635,13645,13646,13758,13771,13783,13796,23410,23420,28179,28265,28274,28297,28344,34579,34590,34612,40280,40449,40570,40932,40938,40969,40983,41006,41040,41069,41096,41120,41214,41474,41478,42524,42533,42534,45569,45587,45598,56450,57574,57587]
plt.bar(pos, 1)
plt.show()

But this doesn't come close.
What steps should I follow to complete the plot?

Desired plot:


问:
SQL Join Returning 0 Rows on Basic Query
I am literally losing my mind over this. I have two tables that I am doing tests against from Microsoft's AdventureWorks and there is NO reason this should be happening. They are the Person.Person and Person.BusinessEntityContact and are being matched on with this query:

```<code>/****** Script for SelectTopNRows command from SSMS  ******/
USE AdventureWorks2017

SELECT
Person.Person.BusinessEntityID,
Person.Person.PersonType,
Person.Person.NameStyle,
Person.Person.Title,
Person.Person.FirstName,
Person.Person.MiddleName,
Person.Person.LastName,
Person.Person.Suffix,
Person.Person.EmailPromotion,
Person.Person.AdditionalContactInfo,
Person.Person.Demographics,
Person.Person.rowguid,
Person.Person.ModifiedDate,
Person.BusinessEntityContact.BusinessEntityID,
Person.BusinessEntityContact.PersonID,
Person.BusinessEntityContact.ContactTypeID,
Person.BusinessEntityContact.rowguid,
Person.BusinessEntityContact.ModifiedDate
FROM
Person.Person
JOIN
Person.BusinessEntityContact
ON
Person.Person.BusinessEntityID = Person.BusinessEntityContact.BusinessEntityID
</code>```

This should return at least something but this is all I get:

What is going on here to where this even is happening? This is stupid to even have to ask this question on here because this stupidly triggers the moderators or other people do, but this is seriously idiotic that this isn't even working. If someone can do this same query and get a result let me know because something is wrong with my computer or something else if it returns for you.

答:
Turns out I wasn't wrong and the setup was just being retarded. I decided to do the exact same thing with another set of tables that shared the same column and it did the returns as normal with all conditions being the same. There was no reason for any of it: character type, length, syntax and dot notation. All of it was the same and it worked for some reason.

```<code>Use AdventureWorks2017

SELECT
       Person.Person.BusinessEntityID
      ,Person.Person.PersonType
      ,Person.Person.NameStyle
      ,Person.Person.Title
      ,Person.Person.FirstName
      ,Person.Person.MiddleName
      ,Person.Person.LastName
      ,Person.Person.Suffix
      ,Person.Person.EmailPromotion
      ,Person.Person.AdditionalContactInfo
      ,Person.Person.Demographics
      ,Person.Person.rowguid
      ,Person.Person.ModifiedDate
      ,Person.BusinessEntity.BusinessEntityID
      ,Person.BusinessEntity.rowguid
      ,Person.BusinessEntity.ModifiedDate
  FROM
  Person.Person
  INNER JOIN
  Person.BusinessEntity
  ON Person.Person.BusinessEntityID = Person.BusinessEntity.BusinessEntityID
</code>```

This is the exact same query with just a different table and it works.

Body:
I am literally losing my mind over this. I have two tables that I am doing tests against from Microsoft's AdventureWorks and there is NO reason this should be happening. They are the Person.Person and Person.BusinessEntityContact and are being matched on with this query:

/****** Script for SelectTopNRows command from SSMS  ******/
USE AdventureWorks2017

SELECT
Person.Person.BusinessEntityID,
Person.Person.PersonType,
Person.Person.NameStyle,
Person.Person.Title,
Person.Person.FirstName,
Person.Person.MiddleName,
Person.Person.LastName,
Person.Person.Suffix,
Person.Person.EmailPromotion,
Person.Person.AdditionalContactInfo,
Person.Person.Demographics,
Person.Person.rowguid,
Person.Person.ModifiedDate,
Person.BusinessEntityContact.BusinessEntityID,
Person.BusinessEntityContact.PersonID,
Person.BusinessEntityContact.ContactTypeID,
Person.BusinessEntityContact.rowguid,
Person.BusinessEntityContact.ModifiedDate
FROM
Person.Person
JOIN
Person.BusinessEntityContact
ON
Person.Person.BusinessEntityID = Person.BusinessEntityContact.BusinessEntityID

This should return at least something but this is all I get:

What is going on here to where this even is happening? This is stupid to even have to ask this question on here because this stupidly triggers the moderators or other people do, but this is seriously idiotic that this isn't even working. If someone can do this same query and get a result let me know because something is wrong with my computer or something else if it returns for you.

Body:
Turns out I wasn't wrong and the setup was just being retarded. I decided to do the exact same thing with another set of tables that shared the same column and it did the returns as normal with all conditions being the same. There was no reason for any of it: character type, length, syntax and dot notation. All of it was the same and it worked for some reason.

Use AdventureWorks2017

SELECT
       Person.Person.BusinessEntityID
      ,Person.Person.PersonType
      ,Person.Person.NameStyle
      ,Person.Person.Title
      ,Person.Person.FirstName
      ,Person.Person.MiddleName
      ,Person.Person.LastName
      ,Person.Person.Suffix
      ,Person.Person.EmailPromotion
      ,Person.Person.AdditionalContactInfo
      ,Person.Person.Demographics
      ,Person.Person.rowguid
      ,Person.Person.ModifiedDate
      ,Person.BusinessEntity.BusinessEntityID
      ,Person.BusinessEntity.rowguid
      ,Person.BusinessEntity.ModifiedDate
  FROM
  Person.Person
  INNER JOIN
  Person.BusinessEntity
  ON Person.Person.BusinessEntityID = Person.BusinessEntity.BusinessEntityID

This is the exact same query with just a different table and it works.


问:
Splitting a string with Swift using a PHP-equivalent regular expression (#\n\s*\n#Uis)
I need to split a given multi-line string (sample here) using a regular expression with Swift. With PHP (the language I use for building web applications) I do this (after removing comments and substituting some tokens):

```<code>// split the file contents in fragments
$fragments = preg_split("#\n\s*\n#Uis", $contents);
</code>```

And this is what I get if execute preg_split over the code sample:

```<code>Array
(
    ...
    [2] =>
CREATE TABLE IF NOT EXISTS c_search_history (
    entry_id BIGINT(64) UNSIGNED NOT NULL AUTO_INCREMENT,
    entry_date_added DATETIME NOT NULL,
    entry_language CHAR(2) NOT NULL DEFAULT 'es',
    entry_query TEXT NOT NULL,
    PRIMARY KEY (entry_id),
    INDEX (entry_date_added),
    INDEX (entry_language)
) ENGINE=InnoDB DEFAULT CHARSET utf8mb4 COLLATE utf8mb4_unicode_520_ci;
    [3] =>
CREATE TABLE IF NOT EXISTS c_search_weight_entries (
    entry_id BIGINT(64) UNSIGNED NOT NULL AUTO_INCREMENT,
    entry_date DATETIME NOT NULL,
    entry_model VARCHAR(175) NOT NULL,
    entry_model_id BIGINT(64) UNSIGNED NOT NULL,
    entry_value DOUBLE NOT NULL,
    PRIMARY KEY (entry_id),
    INDEX (entry_date),
    INDEX (entry_model),
    INDEX (entry_model_id),
    INDEX (entry_value)
) ENGINE=InnoDB DEFAULT CHARSET utf8mb4 COLLATE utf8mb4_unicode_520_ci;
...
)
</code>```

The goal for this is to take an .sql file and flatten its contents so each function, table, procedure, trigger or view definition becomes a one-liner for later execution. The problem is I'm fairly new to Swift and I haven't been able to translate the #\n\s*\n#Uis regular expression into something usable for NSRegularExpression.

I tried to use this solution but it outputs nothing for me (but I may be that I have used it in the wrong way or I don't understand how it really works).

Can you give me a hint? Any help would be greatly appreciated :)

答: After doing, undoing and trying different approaches, seems the only thing I needed to do was to substitute #\n\s*\n#Uis with \\n\\s*\\n and it worked. I still need to do some serious research on NSRegularExpression and a lot of other Swift concepts but, for now, that did the trick :)

Body:
I need to split a given multi-line string (sample here) using a regular expression with Swift. With PHP (the language I use for building web applications) I do this (after removing comments and substituting some tokens):

// split the file contents in fragments
$fragments = preg_split("#\n\s*\n#Uis", $contents);

And this is what I get if execute preg_split over the code sample:

Array
(
    ...
    [2] =>
CREATE TABLE IF NOT EXISTS c_search_history (
    entry_id BIGINT(64) UNSIGNED NOT NULL AUTO_INCREMENT,
    entry_date_added DATETIME NOT NULL,
    entry_language CHAR(2) NOT NULL DEFAULT 'es',
    entry_query TEXT NOT NULL,
    PRIMARY KEY (entry_id),
    INDEX (entry_date_added),
    INDEX (entry_language)
) ENGINE=InnoDB DEFAULT CHARSET utf8mb4 COLLATE utf8mb4_unicode_520_ci;
    [3] =>
CREATE TABLE IF NOT EXISTS c_search_weight_entries (
    entry_id BIGINT(64) UNSIGNED NOT NULL AUTO_INCREMENT,
    entry_date DATETIME NOT NULL,
    entry_model VARCHAR(175) NOT NULL,
    entry_model_id BIGINT(64) UNSIGNED NOT NULL,
    entry_value DOUBLE NOT NULL,
    PRIMARY KEY (entry_id),
    INDEX (entry_date),
    INDEX (entry_model),
    INDEX (entry_model_id),
    INDEX (entry_value)
) ENGINE=InnoDB DEFAULT CHARSET utf8mb4 COLLATE utf8mb4_unicode_520_ci;
...
)

The goal for this is to take an .sql file and flatten its contents so each function, table, procedure, trigger or view definition becomes a one-liner for later execution. The problem is I'm fairly new to Swift and I haven't been able to translate the #\n\s*\n#Uis regular expression into something usable for NSRegularExpression.

I tried to use this solution but it outputs nothing for me (but I may be that I have used it in the wrong way or I don't understand how it really works).

Can you give me a hint? Any help would be greatly appreciated :)


问:
Convert from timestamp (Epoch time) to Proper Pandas DateTime colimn
Trying to convert a column from timestamps to datetime, desired result printed last.
The source is a Unix epoch timestamp. I can convert a single value, but am not able to do it on a full column of data.
Thank you!!</p>

```<code>import pandas as pd
import numpy as np
from datetime import datetime
thd = pd.DataFrame(data=data["candles"])
data={'candles': [{'open': 1417.5,
   'high': 1417.52,
   'low': 1416.95,
   'close': 1416.95,
   'volume': 508,
   'datetime': 1590758940},
  {'open': 1416.95,
   'high': 1420.18,
   'low': 1415.06,
   'close': 1416.64,
   'volume': 32934,
   'datetime': 1590759000},]
}

thd["Time"]=pd.to_datetime(thd["datetime"])
display(thd)
datetime.fromtimestamp(1590759060) #<---this is the result I want to get on dataframe
</code>```

答:
You can use apply on a column to execute this function for each value in a column

```<code>thd['datetime'].apply(datetime.fromtimestamp)
</code>```

Full code

```<code>import pandas as pd
import numpy as np
from datetime import datetime

data={'candles': [{'open': 1417.5,
'high': 1417.52,
'low': 1416.95,
'close': 1416.95,
'volume': 508,
'datetime': 1590758940},
{'open': 1416.95,
'high': 1420.18,
'low': 1415.06,
'close': 1416.64,
'volume': 32934,
'datetime': 1590759000},]
}

thd = pd.DataFrame(data=data["candles"])

thd['datetime_converted'] = thd['datetime'].apply(datetime.fromtimestamp)

thd
</code>```

Result

Body:
Trying to convert a column from timestamps to datetime, desired result printed last.
The source is a Unix epoch timestamp. I can convert a single value, but am not able to do it on a full column of data.
Thank you!!

import pandas as pd
import numpy as np
from datetime import datetime
thd = pd.DataFrame(data=data["candles"])
data={'candles': [{'open': 1417.5,
   'high': 1417.52,
   'low': 1416.95,
   'close': 1416.95,
   'volume': 508,
   'datetime': 1590758940},
  {'open': 1416.95,
   'high': 1420.18,
   'low': 1415.06,
   'close': 1416.64,
   'volume': 32934,
   'datetime': 1590759000},]
}

thd["Time"]=pd.to_datetime(thd["datetime"])
display(thd)
datetime.fromtimestamp(1590759060) #<---this is the result I want to get on dataframe

Body:
You can use apply on a column to execute this function for each value in a column

thd['datetime'].apply(datetime.fromtimestamp)

Full code

import pandas as pd
import numpy as np
from datetime import datetime

data={'candles': [{'open': 1417.5,
'high': 1417.52,
'low': 1416.95,
'close': 1416.95,
'volume': 508,
'datetime': 1590758940},
{'open': 1416.95,
'high': 1420.18,
'low': 1415.06,
'close': 1416.64,
'volume': 32934,
'datetime': 1590759000},]
}

thd = pd.DataFrame(data=data["candles"])

thd['datetime_converted'] = thd['datetime'].apply(datetime.fromtimestamp)

thd

Result


问:
File is not `goimports`-ed with -local somePath
I made some changes in Golang project and later ran make test which takes care of linting, formatting and unit testing. But when it run linter.sh, it throws following error

```<code>pkg/skaffold/kubernetes/wait.go:23: File is not `goimports`-ed with -local github.com/GoogleContainerTools/skaffold (goimports)
        "github.com/GoogleContainerTools/skaffold/pkg/skaffold/kubectl"
</code>```

Here is the link to Code.

答:
In my case, I had to change this:

```<code>import (
    "fmt"
    "github.com/gin-gonic/gin"
    "net/http"
    "strconv"
)
</code>```

To this:

```<code>import (
    "fmt"
    "net/http"
    "strconv"

    "github.com/gin-gonic/gin"
)
</code>```

Body:
I made some changes in Golang project and later ran make test which takes care of linting, formatting and unit testing. But when it run linter.sh, it throws following error

pkg/skaffold/kubernetes/wait.go:23: File is not `goimports`-ed with -local github.com/GoogleContainerTools/skaffold (goimports)
        "github.com/GoogleContainerTools/skaffold/pkg/skaffold/kubectl"

Here is the link to Code.

Body:
In my case, I had to change this:

import (
    "fmt"
    "github.com/gin-gonic/gin"
    "net/http"
    "strconv"
)

To this:

import (
    "fmt"
    "net/http"
    "strconv"

    "github.com/gin-gonic/gin"
)


问:
Annoying Android - RSS problem
I'm struggling big time with a stupid problem which i can't seem to fix.
Basicly what i do in my application is the following:

I download all the RSS content to a local database, including the enclosure of every feed (images) but not every feed contains an image.

about 10 of the 100 feeds don't contain an image
What happens with the feeds that don't contain an image is shown in the following image:

http://i.stack.imgur.com/FTUBl.png

The feeds with no image get the image of the previouse feed for some reason...

I'll place all my code below in hope someone can tell me what in the world i'm doing wrong...

This part is where i download the image to the local storage, this function works correctly however for some reason the feed with no enclosure gets the enclosure of the previouse feed send back to it...

```<code>for (Message msg : wildLife){

                String imageURL = msg.getEnclosure();
                String imageName = imageURL.substring(imageURL.lastIndexOf("/"));
                String imagePath = ImageDir + imageName;

                //-- Call upon the function that will download the image.
                if (imageURL !=null){
                    DownloadFromUrl(imageURL, imagePath);
                }

                //-- We add all rows we find in the rrs feed to our local stored database.
                db.addWildlifeRow(
                    msg.getTitle(),
                    msg.getDescription(),
                    "Empty slot",
                    imagePath,
                    msg.getLink());
            }
</code>```

I checked in the RSS parser and it doesn't store the same URL twice. So no problem there. It goes wrong (for as far as i know) when requisting the URL enclosure from a message item.

Is there anyone who might have encountered this same problem?

All advice is welcome i've been stuck in this problem for days now, and i can't seem to figure it out...

If you would require more code to find a possible solution just ask and i will provide it.

P.S. it goes wrong before placing the data into my database, so when reading the info from the message out and placing it in the database, its already gone wrong there. The enclosure is copied from the reviouse one (if there was none)

Regards, joery

答:
```<code> //-- Call upon the function that will download the image.
                if (imageURL !=null){
                    DownloadFromUrl(imageURL, imagePath);
                }
            else
                imageview.setImageDrawable(null);
</code>```

Try adding an else part here and clear any old image in ur imageview

Title: Annoying Android - RSS problem

Body:
I'm struggling big time with a stupid problem which i can't seem to fix.
Basicly what i do in my application is the following:

I download all the RSS content to a local database, including the enclosure of every feed (images) but not every feed contains an image.

about 10 of the 100 feeds don't contain an image
What happens with the feeds that don't contain an image is shown in the following image:

http://i.stack.imgur.com/FTUBl.png

The feeds with no image get the image of the previouse feed for some reason...

I'll place all my code below in hope someone can tell me what in the world i'm doing wrong...

This part is where i download the image to the local storage, this function works correctly however for some reason the feed with no enclosure gets the enclosure of the previouse feed send back to it...

for (Message msg : wildLife){

                String imageURL = msg.getEnclosure();
                String imageName = imageURL.substring(imageURL.lastIndexOf("/"));
                String imagePath = ImageDir + imageName;

                //-- Call upon the function that will download the image.
                if (imageURL !=null){
                    DownloadFromUrl(imageURL, imagePath);
                }

                //-- We add all rows we find in the rrs feed to our local stored database.
                db.addWildlifeRow(
                    msg.getTitle(),
                    msg.getDescription(),
                    "Empty slot",
                    imagePath,
                    msg.getLink());
            }

I checked in the RSS parser and it doesn't store the same URL twice. So no problem there. It goes wrong (for as far as i know) when requisting the URL enclosure from a message item.

Is there anyone who might have encountered this same problem?

All advice is welcome i've been stuck in this problem for days now, and i can't seem to figure it out...

If you would require more code to find a possible solution just ask and i will provide it.

P.S. it goes wrong before placing the data into my database, so when reading the info from the message out and placing it in the database, its already gone wrong there. The enclosure is copied from the reviouse one (if there was none)

Regards, joery

Body:
 //-- Call upon the function that will download the image.
                if (imageURL !=null){
                    DownloadFromUrl(imageURL, imagePath);
                }
            else
                imageview.setImageDrawable(null);

Try adding an else part here and clear any old image in ur imageview


问:
remember the last state of the Bool variable
I’m doing a show. And I wanted to know how I saved the last status of my Bool variable so that when I leave the program and come back in it’s the same as when I leave, someone has some idea of how to do it. Thank you!</p>

答: Well, the app can be closed or killed by the system, so it surely needs some persistent storage usage. It can be on the phone or in the cloud. For your need the most simplest would be to use Shared Preferences library and keep your Boolean locally as a setting/configuration.</p>


问:
Type annotations needed for String when using AsRef
I'm using Warp like this:

```<code>
#[derive(Default)]
struct State {
    topics: HashMap<String, Topic>,
}

struct Topic {
    name: String,
    description: String,
    items: Vec<String>,
}

fn with_state(state: Arc<Mutex<State>>) -> impl Filter<Extract = (Arc<Mutex<State>>,), Error = std::convert::Infallible> + Clone {
    warp::any().map(move || state.clone())
}

#[tokio::main]
async fn main() {
    let state = Arc::new(Mutex::new(State::default()));

    let survey = warp::get()
        .and(warp::path!("survey" / String))
        .and(warp::path::end())
        .and(with_state(state.clone()))
        .and_then(|topic: String, state: Arc<Mutex<State>>| async move {
            let state = state.lock().unwrap();

            let topic = state.topics.get(&topic).ok_or(warp::reject::not_found())?;

            let res: Result<Value, Rejection> = Ok(json!({
                "name": topic.name,
                "items": topic.items.iter().map(AsRef::as_ref).collect::<Value>(),
            }));
            res
        })
    ...
</code>```

If I compile it gives this error:

```<code>error[E0283]: type annotations needed for `std::string::String`
   --> src/main.rs:210:20
    |
210 |         .and_then(|topic: String, state: Arc<Mutex<State>>| async move {
    |                    ^^^^^ consider giving this closure parameter a type
    |
    = note: cannot resolve `std::string::String: std::convert::AsRef<_>`
    = note: required by `std::convert::AsRef::as_ref`
</code>```

This is really weird. What does it mean consider giving this closure parameter a type? Doesn't it already have a type? Even weirder, if I comment out this line:

```<code>            "items": topic.items.iter().map(AsRef::as_ref).collect::<Value>(),
</code>```

Then it compiles! Even though that line apparently has nothing to do with the topic parameter. What's going on?

答:
Ah I just figured out it wanted me to change this:

```<code>AsRef::as_ref
</code>```

to this:

```<code>AsRef::<str>::as_ref
</code>```

The error message is just totally wrong.

Body:
I'm using Warp like this:

#[derive(Default)]
struct State {
    topics: HashMap<String, Topic>,
}

struct Topic {
    name: String,
    description: String,
    items: Vec<String>,
}

fn with_state(state: Arc<Mutex<State>>) -> impl Filter<Extract = (Arc<Mutex<State>>,), Error = std::convert::Infallible> + Clone {
    warp::any().map(move || state.clone())
}

#[tokio::main]
async fn main() {
    let state = Arc::new(Mutex::new(State::default()));

    let survey = warp::get()
        .and(warp::path!("survey" / String))
        .and(warp::path::end())
        .and(with_state(state.clone()))
        .and_then(|topic: String, state: Arc<Mutex<State>>| async move {
            let state = state.lock().unwrap();

            let topic = state.topics.get(&topic).ok_or(warp::reject::not_found())?;

            let res: Result<Value, Rejection> = Ok(json!({
                "name": topic.name,
                "items": topic.items.iter().map(AsRef::as_ref).collect::<Value>(),
            }));
            res
        })
    ...

If I compile it gives this error:

error[E0283]: type annotations needed for `std::string::String`
   --> src/main.rs:210:20
    |
210 |         .and_then(|topic: String, state: Arc<Mutex<State>>| async move {
    |                    ^^^^^ consider giving this closure parameter a type
    |
    = note: cannot resolve `std::string::String: std::convert::AsRef<_>`
    = note: required by `std::convert::AsRef::as_ref`

This is really weird. What does it mean consider giving this closure parameter a type? Doesn't it already have a type? Even weirder, if I comment out this line:

            "items": topic.items.iter().map(AsRef::as_ref).collect::<Value>(),

Then it compiles! Even though that line apparently has nothing to do with the topic parameter. What's going on?

Body:
Ah I just figured out it wanted me to change this:

AsRef::as_ref

to this:

AsRef::<str>::as_ref

The error message is just totally wrong.


问:
Remove the double quotes from a float in a dataframe
I have some options chain data:

```<code>Contract Name,Last Trade Date,Strike,Last Price,Bid,Ask,Change

AMZN200605P03320000,2020-05-28 3:24PM EDT,3320.0,900.65,876.0,893.5,+900.65

AMZN200605P03500000,2020-05-28 3:51PM EDT,3500.0,1099.55,1055.5,1073.5,"+1,099.55"
</code>```

The entry - "+1,099.55" seems to be a bad entry in the data, since there are not any other records like that and I need to sanitize it before inserting into a SQLDB. I have tried a couple different things but none have worked. Any insight would be greatly appreciated:

```<code>optionsChainPuts['Change'] = optionsChainPuts['Change'].map(lambda x: x.lstrip('\"+').rstrip('\"'))
optionsChainPuts['Change'] = optionsChainPuts['Change'].astype(str).str.replace('\D', '')
optionsChainPuts['Change'] = optionsChainPuts['Change'].astype(str).map(lambda x: x.replace('"', ''))
</code>```

Thank you

答:
It's the comma that is causing issues. One option is to split it at the comma and join the values

```<code>>>> val = "+1,099.55"
>>> val = val.split(",")
>>> num = float(val[0] + val[1])
>>> num
1099.55
</code>```

Hope that helps!

Body:
I have some options chain data:

Contract Name,Last Trade Date,Strike,Last Price,Bid,Ask,Change

AMZN200605P03320000,2020-05-28 3:24PM EDT,3320.0,900.65,876.0,893.5,+900.65

AMZN200605P03500000,2020-05-28 3:51PM EDT,3500.0,1099.55,1055.5,1073.5,"+1,099.55"

The entry - "+1,099.55" seems to be a bad entry in the data, since there are not any other records like that and I need to sanitize it before inserting into a SQLDB. I have tried a couple different things but none have worked. Any insight would be greatly appreciated:

optionsChainPuts['Change'] = optionsChainPuts['Change'].map(lambda x: x.lstrip('\"+').rstrip('\"'))
optionsChainPuts['Change'] = optionsChainPuts['Change'].astype(str).str.replace('\D', '')
optionsChainPuts['Change'] = optionsChainPuts['Change'].astype(str).map(lambda x: x.replace('"', ''))

Thank you

Body:
It's the comma that is causing issues. One option is to split it at the comma and join the values

>>> val = "+1,099.55"
>>> val = val.split(",")
>>> num = float(val[0] + val[1])
>>> num
1099.55

Hope that helps!


问:
R- Populating a dataframe based on another one with conditions
im new on R and i have a data set of 22x252, the 252 have many repeated values on column 1(ID). I made another dataset that has nrows of the unique values (with those values already populated), and i want to populate the rest of the columns based on the other dataset (basically summing all the values that share the same value in column 1.)

Is there a basic function that enables me to do this?

Thanks & Regards

答:
We can use aggregate in base R.  Assuming the column name of first column is 'ID' and all other columns are numeric class, we group by 'ID' and get the sum of the rest of the columns in aggregate

```<code>aggregate(.~ ID, df1, sum, na.rm = TRUE)
</code>```

Or with dplyr

```<code>library(dplyr)
df1 %>%
  group_by(ID) %>%
  summarise_at(vars(-group_cols()), sum, na.rm = TRUE)
</code>```

Or with new version with across

```<code>df1 %>%
  group_by(ID) %>%
  summarise(across(-group_cols(), sum, na.rm = TRUE))
</code>```

Body:
We can use aggregate in base R.  Assuming the column name of first column is 'ID' and all other columns are numeric class, we group by 'ID' and get the sum of the rest of the columns in aggregate

aggregate(.~ ID, df1, sum, na.rm = TRUE)

Or with dplyr

library(dplyr)
df1 %>%
  group_by(ID) %>%
  summarise_at(vars(-group_cols()), sum, na.rm = TRUE)

Or with new version with across

df1 %>%
  group_by(ID) %>%
  summarise(across(-group_cols(), sum, na.rm = TRUE))