答:
you can try to calculate the data before plotting

```<code>library(tidyverse)
df %>%
  group_by(time_point) %>%
  count(chill_number) %>%
  mutate(perc = n/sum(n)) %>%
  ggplot(aes(time_point, perc, fill =chill_number)) +
    geom_col(position = position_stack()) +
    geom_text(aes(label = n), position = position_stack(vjust =0.5), size =12)
</code>```

or try

```<code>ggplot(df, aes(x = time_point, y = (..count..)/sum(..count..), fill = chill_number)) +
  geom_bar() +
  stat_count(geom = "text", aes(label = ..count..), position = position_stack(vjust =0.5))
</code>```

Title: Adding count label to bar chart of proportional data in ggplot

Body:
I have a stacked bar chart of proportional data made with ggplot. I'd like to add the counts contributing to those proportions.

A subset of my data:

dput(sus_dev_data)
structure(list(individual_code = structure(c(9L, 10L, 7L, 6L,
8L, 1L, 4L, 3L, 2L, 25L, 23L, 21L, 22L, 24L, 20L, 16L, 17L, 19L,
29L, 30L, 26L, 28L, 15L, 13L, 14L, 12L, 11L), .Label = c("D5WMA-113",
"D5WMA-133", "D5WMA-136", "D5WMA-137", "D5WMA-141", "D6UIC-109",
"D6UIC-72", "D6UIC-87", "D6UIC-89", "D6UIC-97", "S6WMA-806",
"S6WMA-810", "S6WMA-811", "S6WMA-815", "S6WMA-820", "S6WMA-859",
"S6WMA-863", "S6WMA-866", "S6WMA-875", "S6WMA-876", "S7UIC-1202",
"S7UIC-1215", "S7UIC-1250", "S7UIC-1252", "S7UIC-1253", "S7UIC-709",
"S7UIC-724", "S7UIC-780", "S7UIC-827", "S7UIC-840"), class = "factor"),
    population = structure(c(1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L,
    2L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 2L,
    2L, 2L, 2L, 2L), .Label = c("UIC", "WMA"), class = "factor"),
    time_point = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
    1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L,
    3L, 3L, 3L, 3L), .Label = c("3", "8", "12"), class = "factor"),
    days_to_feeding = c(3L, 3L, 4L, 3L, 5L, 4L, 3L, 4L, 5L, 4L,
    3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L,
    3L, 4L), chill_number = structure(c(2L, 2L, 2L, 2L, 2L, 2L,
    2L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 1L, 1L, 1L,
    1L, 1L, 1L, 1L, 1L, 1L), .Label = c("1", "2"), class = "factor"),
    days_to_pupation = c(135L, 142L, 143L, 155L, 149L, 159L,
    153L, 171L, 9L, 67L, 53L, 49L, 72L, 67L, 55L, 64L, 60L, 122L,
    53L, 51L, 49L, 53L, 50L, 56L, 44L, 47L, 60L)), row.names = c(1L,
2L, 3L, 4L, 5L, 6L, 8L, 9L, 10L, 11L, 12L, 13L, 14L, 15L, 16L,
17L, 18L, 20L, 21L, 22L, 23L, 24L, 26L, 27L, 28L, 29L, 30L), class = "data.frame")

My current ggplot code:

(prop_plot <- ggplot(sus_dev_data, aes(x = time_point, fill = chill_number)) +
  Alex_Theme +
  geom_bar(position = "fill", color = "black") +
  scale_fill_manual(values = c("grey90", "white")) +
  scale_x_discrete(labels=c("3" = "13", "8" = "18",
                             "12" = "22")) +
  labs(y = 'Proportion pupated after 79 days', x = 'Weeks post-hatch')
)

Now I'd like to add the counts contributing to those proportions. All options that I've tried either pin the values at the top of the plot or I get errors. I've been following this similar thread (https://stackoverflow.com/questions/6644997/showing-data-values-on-stacked-bar-chart-in-ggplot2), but none of those options are working for me.

Body:
you can try to calculate the data before plotting

library(tidyverse)
df %>%
  group_by(time_point) %>%
  count(chill_number) %>%
  mutate(perc = n/sum(n)) %>%
  ggplot(aes(time_point, perc, fill =chill_number)) +
    geom_col(position = position_stack()) +
    geom_text(aes(label = n), position = position_stack(vjust =0.5), size =12)

or try

ggplot(df, aes(x = time_point, y = (..count..)/sum(..count..), fill = chill_number)) +
  geom_bar() +
  stat_count(geom = "text", aes(label = ..count..), position = position_stack(vjust =0.5))


来源: stackexchange

问:
How to build Customizable Apps in .Net?
We are building a LOB Thick WPF Client / WCF Server application. I need to create an architecture that allows "pluggable" workflows on the Client side, to facilitate a business selling point of per customer flexibility.

In .Net however, adding projects to a solution for every customer modification and for nearly every component that is deemed "replaceable" seems dangerous, at best.

The alternative that comes to mind is abstracting all classes to an interface and to let configuration feed through the correct implementation.

Then there is the logistical perspective: how do you best manage this in source control for instance?

What experiences can you share and what options do you know of?

PS: I'm not really aiming for extensibility. I need existing features to be "customizable". Things like changing page order in a wizard. I think Colin's suggestion of configuration will possibly be the best option. But beyond that?

答: Since it seems clear you have an idea on how to create plugin, I just give you my way for the "logistic" part. Create an assembly for the extension points, ie the interfaces plugins must implements, and have it as the unique common reference between the main shell and the varius plugin. If the extension mechanism grows, try to mantain the old interfaces so you don't break existing plugins. </p>

ContentLicense: CC BY-SA 3.0

Title: How to build Customizable Apps in .Net?


问:
Setting the initial directory of an SaveFileDialog?
I'd like a SaveFileDialog with the following behavior:

The first time you open it, it goes to "My Documents".

Afterwards, it goes to the last selected folder.
What's the best way to accomplish this?

If I don't set the InitialDirectory, it goes to the exe's directory - which is not what I want. It rememebers the last selected directory though - even between executions.

If I set the InitialDirectory, it does not remember the last selected directory. Of course, I could save the last selected directory in the registry :( but I am looking for a better solution.

```<code>      SaveFileDialog dialog = new SaveFileDialog();
      //??? dialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
      dialog.ShowDialog();
</code>```

Any advice?

答:
use the saveFileDialog.InitialDirectory property as follows:

```<code>Stream stream;
SaveFileDialog saveFileDialog = new SaveFileDialog();

saveFileDialog.Filter = "dat files (*.dat)|*.dat|All files (*.*)|*.*";
saveFileDialog.FilterIndex = 1;
saveFileDialog.RestoreDirectory = true;
saveFileDialog.InitialDirectory = @"D:\Data\...\foldername\";
saveFileDialog.ShowDialog();

if (!saveFileDialog.FileName.Equals(string.Empty))
    Console.WriteLine(saveFileDialog.FileName);
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I'd like a SaveFileDialog with the following behavior:

The first time you open it, it goes to "My Documents".

Afterwards, it goes to the last selected folder.
What's the best way to accomplish this?

If I don't set the InitialDirectory, it goes to the exe's directory - which is not what I want. It rememebers the last selected directory though - even between executions.

If I set the InitialDirectory, it does not remember the last selected directory. Of course, I could save the last selected directory in the registry :( but I am looking for a better solution.

      SaveFileDialog dialog = new SaveFileDialog();
      //??? dialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
      dialog.ShowDialog();

Any advice?

Body:
use the saveFileDialog.InitialDirectory property as follows:

Stream stream;
SaveFileDialog saveFileDialog = new SaveFileDialog();

saveFileDialog.Filter = "dat files (*.dat)|*.dat|All files (*.*)|*.*";
saveFileDialog.FilterIndex = 1;
saveFileDialog.RestoreDirectory = true;
saveFileDialog.InitialDirectory = @"D:\Data\...\foldername\";
saveFileDialog.ShowDialog();

if (!saveFileDialog.FileName.Equals(string.Empty))
    Console.WriteLine(saveFileDialog.FileName);

ContentLicense: CC BY-SA 4.0


问:
Calculating process cpu usage from Process.TotalProcessorTime
I've been trying to move away from using the PerformanceCounter class for monitoring a process's CPU usage since it seems it requires a decent amount of CPU when the process count gets decently high (when monitoring a lot of processes).

My first approach was to take the WMI route using Win32_PerfFormattedData_PerfOS_Processor class and the PercentProcessorTime property, but there seems to be an issue when trying to calculate the CPU usage over multiple cores (the max value it's returning is 100% making it impossible to divide it based on the CPU core count, resulting in inaccurate results).

So finally I decided to use the Process's class TotalProcessorTime property. Sadly I am unsure how to calculate the percentage of the total CPU usage used by the Process based the value. I know that I should subtract the current PercentProcessorTime value from a previous PercentProcessorTime value to get how much time the processor spent on the process within a certain time limit but I am unsure how to continue from there.

Thanks in advance.

答:
Building upon 111WARLOCK111's answer, you can use the following minimal code to measure the current CPU load:

async Task<double> GetCpuLoadAsync(TimeSpan MeasurementWindow)
{
    Process CurrentProcess = Process.GetCurrentProcess();

    TimeSpan StartCpuTime = CurrentProcess.TotalProcessorTime;
    Stopwatch Timer = Stopwatch.StartNew();

    await Task.Delay(MeasurementWindow);

    TimeSpan EndCpuTime = CurrentProcess.TotalProcessorTime;
    Timer.Stop();

    return (EndCpuTime - StartCpuTime).TotalMilliseconds / (Environment.ProcessorCount * Timer.ElapsedMilliseconds);
}
```

<p>Use the following code to call the function and replace the TimeSpan with the window to monitor:</p>

<pre class="lang-cs prettyprint-override"><code>double CpuLoad = await GetCpuLoadAsync(TimeSpan.FromSeconds(10));
</code>```

Body:
Building upon 111WARLOCK111's answer, you can use the following minimal code to measure the current CPU load:

async Task<double> GetCpuLoadAsync(TimeSpan MeasurementWindow)
{
    Process CurrentProcess = Process.GetCurrentProcess();

    TimeSpan StartCpuTime = CurrentProcess.TotalProcessorTime;
    Stopwatch Timer = Stopwatch.StartNew();

    await Task.Delay(MeasurementWindow);

    TimeSpan EndCpuTime = CurrentProcess.TotalProcessorTime;
    Timer.Stop();

    return (EndCpuTime - StartCpuTime).TotalMilliseconds / (Environment.ProcessorCount * Timer.ElapsedMilliseconds);
}

Use the following code to call the function and replace the TimeSpan with the window to monitor:

double CpuLoad = await GetCpuLoadAsync(TimeSpan.FromSeconds(10));


问:
Animation of tangent line of a 3D curve
I am writing a Python program to animate a tangent line along a 3D curve. However, my tangent line is not moving. I think the problem is

line.set_data(np.array(Tangent[:,0]).T,np.array(Tangent[:,1]).T)

in animate(i) but I can't figure out. Any help will be appreciated. The following is the code.

```<code>from mpl_toolkits import mplot3d
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import matplotlib

matplotlib.use( 'tkagg' )
plt.style.use('seaborn-pastel')

fig = plt.figure()
ax = plt.axes(projection='3d')
ax = plt.axes(projection='3d')

# Data for a three-dimensional line
zline = np.linspace(0, 15, 1000)
xline = np.sin(zline)
yline = np.cos(zline)
ax.plot3D(xline, yline, zline, 'red')

def curve(t):
    return [np.sin(t),np.cos(t),t]

def vector_T(t):
    T = [np.cos(t),-np.sin(t),1]
    return T/np.linalg.norm(T)

len = 2
def tangent_line(t):
    P = np.add(curve(t),len*vector_T(t))
    Q = np.subtract(curve(t),len*vector_T(t))
    return np.array([P, Q]).T

t0 = 0
Tangent=tangent_line(t0)
line, = ax.plot3D(Tangent[0], Tangent[1], Tangent[2], 'green')

def init():
    line.set_data([], [])
    return line,

def animate(i):
    t0 = 15* (i/200)
    Tangent=tangent_line(t0)
    #print(Tangent)
    line.set_data(np.array(Tangent[:,0]).T,np.array(Tangent[:,1]).T)
    return line,

anim = FuncAnimation(fig, animate, init_func=init,
                               frames=200, interval=20, blit=True)

plt.show()
</code>```

答:
you've called the wrong function in animate:
Replace line.set_data(...) with line.set_data_3d(Tangent[0], Tangent[1], Tangent[2]) and it will work.

There are still some minor issues in the code (e.g., don't use len as a variable name).
I'd recommend using the following:

```<code>#!/usr/bin/env python3

from mpl_toolkits import mplot3d
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import matplotlib

matplotlib.use('tkagg')
plt.style.use('seaborn-pastel')

fig = plt.figure()
ax = plt.axes(projection='3d')

# Data for a three-dimensional line
zline = np.linspace(0, 15, 1000)
xline = np.sin(zline)
yline = np.cos(zline)
ax.plot3D(xline, yline, zline, 'red')

def curve(t):
    return [ np.sin(t), np.cos(t), t ]

def tangent(t):
    t = [ np.cos(t), -np.sin(t), 1.0 ]
    return t/np.linalg.norm(t)

def tangent_line(t):
    length = 2.0
    offset = length * tangent(t)
    pos = curve(t)
    return np.array([ pos-offset, pos+offset ]).T

line = ax.plot3D(*tangent_line(0), 'green')[0]

def animate(i):
    line.set_data_3d(*tangent_line(15* (i/200)))
    return [ line ]

anim = FuncAnimation(fig, animate, frames=200, interval=20, blit=True)

plt.show()
</code>```

Title: Animation of tangent line of a 3D curve

Body:
I am writing a Python program to animate a tangent line along a 3D curve. However, my tangent line is not moving. I think the problem is

line.set_data(np.array(Tangent[:,0]).T,np.array(Tangent[:,1]).T)

in animate(i) but I can't figure out. Any help will be appreciated. The following is the code.

from mpl_toolkits import mplot3d
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import matplotlib

matplotlib.use( 'tkagg' )
plt.style.use('seaborn-pastel')

fig = plt.figure()
ax = plt.axes(projection='3d')
ax = plt.axes(projection='3d')

# Data for a three-dimensional line
zline = np.linspace(0, 15, 1000)
xline = np.sin(zline)
yline = np.cos(zline)
ax.plot3D(xline, yline, zline, 'red')

def curve(t):
    return [np.sin(t),np.cos(t),t]

def vector_T(t):
    T = [np.cos(t),-np.sin(t),1]
    return T/np.linalg.norm(T)

len = 2
def tangent_line(t):
    P = np.add(curve(t),len*vector_T(t))
    Q = np.subtract(curve(t),len*vector_T(t))
    return np.array([P, Q]).T

t0 = 0
Tangent=tangent_line(t0)
line, = ax.plot3D(Tangent[0], Tangent[1], Tangent[2], 'green')

def init():
    line.set_data([], [])
    return line,

def animate(i):
    t0 = 15* (i/200)
    Tangent=tangent_line(t0)
    #print(Tangent)
    line.set_data(np.array(Tangent[:,0]).T,np.array(Tangent[:,1]).T)
    return line,

anim = FuncAnimation(fig, animate, init_func=init,
                               frames=200, interval=20, blit=True)

plt.show()

Body:
you've called the wrong function in animate:
Replace line.set_data(...) with line.set_data_3d(Tangent[0], Tangent[1], Tangent[2]) and it will work.

There are still some minor issues in the code (e.g., don't use len as a variable name).
I'd recommend using the following:

#!/usr/bin/env python3

from mpl_toolkits import mplot3d
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import matplotlib

matplotlib.use('tkagg')
plt.style.use('seaborn-pastel')

fig = plt.figure()
ax = plt.axes(projection='3d')

# Data for a three-dimensional line
zline = np.linspace(0, 15, 1000)
xline = np.sin(zline)
yline = np.cos(zline)
ax.plot3D(xline, yline, zline, 'red')

def curve(t):
    return [ np.sin(t), np.cos(t), t ]

def tangent(t):
    t = [ np.cos(t), -np.sin(t), 1.0 ]
    return t/np.linalg.norm(t)

def tangent_line(t):
    length = 2.0
    offset = length * tangent(t)
    pos = curve(t)
    return np.array([ pos-offset, pos+offset ]).T

line = ax.plot3D(*tangent_line(0), 'green')[0]

def animate(i):
    line.set_data_3d(*tangent_line(15* (i/200)))
    return [ line ]

anim = FuncAnimation(fig, animate, frames=200, interval=20, blit=True)

plt.show()


问:
Knowing when a photo is deleted with Flickr API
In my application, I have to run a periodical job where I need data about all the photos on my client's Flickr account. Currently, I perform several calls to flickr.photos.search to retrieve meta about all the photos each time.
What I ask is: is there a way to be get informed by Flickr when a photo is modified or deleted, so that I don't need to retrieve metas for each photos, but rather store theme once, and only download what has changed since the last time I run the job ?
Thx in advance for your help.</p>

答:
There is no such notification possible from the Flickr API to your code.

What you can do on the other hand is (recommended only if volume for change of photo metadata is high) -

Setup a cron job which would scan through the photos and store if the photo id's are deleted or not - which can be used later.


问:
How to invalid a string line url with regex
I want to use regex on my project, and my issue is the following.

My regex is the following /([a-z_"\/\{\},\[\]]+)\b/g

Each string is considered valid if it contains only these characters:

lower case letters

Any of these: _/{}[],

My string

```<code>[
  "/persons/AA",
  "/personsTest/throw_web_Application",
  "/persons/{id}",
  "/personsSSS",
  "/persons/ping"
]
</code>```

As you can see, it stop when it's "/"

And i want to invalid my entire line when it's doesn't good for my regex.

Thank you :)

答:
This declares a string invalid if it finds any character that is not in the acceptable set of characters:

```<code>[^a-z_\/{}[\],]
</code>```

See Regex Demo

let strings = [
  "/persons/AA",
  "/personsTest/throw_web_Application",
  "/persons/{id}",
  "/personsSSS",
  "/persons/ping"
];

for (let string of strings) {
    if (/[^a-z_\/{}[\],]/.test(string)) {
        console.log("Invalid string: ", string);
    }
    else {
        console.log("Valid string: ", string);
    }
}```

Body:
I want to use regex on my project, and my issue is the following.

My regex is the following /([a-z_"\/\{\},\[\]]+)\b/g

Each string is considered valid if it contains only these characters:

lower case letters

Any of these: _/{}[],

My string

[
  "/persons/AA",
  "/personsTest/throw_web_Application",
  "/persons/{id}",
  "/personsSSS",
  "/persons/ping"
]

As you can see, it stop when it's "/"

And i want to invalid my entire line when it's doesn't good for my regex.

Thank you :)

Body:
This declares a string invalid if it finds any character that is not in the acceptable set of characters:

[^a-z_\/{}[\],]

See Regex Demo

let strings = [
  "/persons/AA",
  "/personsTest/throw_web_Application",
  "/persons/{id}",
  "/personsSSS",
  "/persons/ping"
];

for (let string of strings) {
    if (/[^a-z_\/{}[\],]/.test(string)) {
        console.log("Invalid string: ", string);
    }
    else {
        console.log("Valid string: ", string);
    }
}


问:
Prevent calling a function more than once if the parameters have been used before
I would like a way to limit the calling of a function to once per values of parameters.

For example

```<code>def unique_func(x):
    return x

>>> unique_func([1])
[1]
>>> unique_func([1])
*** wont return anything ***
>>> unique_func([2])
[2]
</code>```

Any suggestions? I've looked into using memoization but not established a solution just yet.

This is not solved by the suggested Prevent a function from being called twice in a row since that only solves when the previous func call had them parameters.

答:
Consider using the built-in functools.lru_cache() instead of rolling your own.

It won't return nothing on the second function call with the same arugments (it will return the same thing as the first function call) but maybe you can live with that. It would seem like a negligible price to pay, compared to the advantages of using something that's maintained as part of the standard library.

Requires your argument x to be hashable, so won't work with lists. Strings are fine.

```<code>from functools import lru_cache

@lru_cache()
def unique_fun(x):
    ...
</code>```

Body:
I would like a way to limit the calling of a function to once per values of parameters.

For example

def unique_func(x):
    return x

>>> unique_func([1])
[1]
>>> unique_func([1])
*** wont return anything ***
>>> unique_func([2])
[2]

Any suggestions? I've looked into using memoization but not established a solution just yet.

This is not solved by the suggested Prevent a function from being called twice in a row since that only solves when the previous func call had them parameters.

Body:
Consider using the built-in functools.lru_cache() instead of rolling your own.

It won't return nothing on the second function call with the same arugments (it will return the same thing as the first function call) but maybe you can live with that. It would seem like a negligible price to pay, compared to the advantages of using something that's maintained as part of the standard library.

Requires your argument x to be hashable, so won't work with lists. Strings are fine.

from functools import lru_cache

@lru_cache()
def unique_fun(x):
    ...


问:
Get value of a variable from another session in org-mode
How to share variables' values in org-mode between different sessions?

Simple example: in session one I create _gpg_tmpdir

```<code>#+name: make_temporary_directories
#+begin_src bash :session *one*
_gpg_tmpdir="$( mktemp -d )"
#+end_src
</code>```

and need to clean up it in session two:

```<code>#+name: clean_temporary_directories
#+begin_src bash :session *two*
rm -rf $_gpg_tmpdir
#+end_src
</code>```

The example is for the demonstration purpose only.
The question is what is the less painfull way to share variables between different code sessions (perhaps with different code languages) in org-mode.

答:
You can use the name of the codeblock to reference its output from a different codeblock using the "var" attribute. For more info you can check in the orgmode documentation.

The first block needs to output the value:

```<code>#+name: make_temporary_directories
#+BEGIN_SRC bash :session *one* :results output
variable=`ls`
echo $variable
#+END_SRC

#+RESULTS: make_temporary_directories
:
: file1 file2 file3 file4 file5 file6 file7 file8
</code>```

The second block can refer to that value using the name of the previous codeblock:

```<code>#+BEGIN_SRC bash :session *two* :results output :var ls_result=make_temporary_directories
echo $ls_result
#+END_SRC

#+RESULTS:
#+begin_example

bash-5.0$ file1 file2 file3 file4 file5 file6 file7 file8
#+end_example
</code>```

Body:
How to share variables' values in org-mode between different sessions?

Simple example: in session one I create _gpg_tmpdir

#+name: make_temporary_directories
#+begin_src bash :session *one*
_gpg_tmpdir="$( mktemp -d )"
#+end_src

and need to clean up it in session two:

#+name: clean_temporary_directories
#+begin_src bash :session *two*
rm -rf $_gpg_tmpdir
#+end_src

The example is for the demonstration purpose only.
The question is what is the less painfull way to share variables between different code sessions (perhaps with different code languages) in org-mode.

Body:
You can use the name of the codeblock to reference its output from a different codeblock using the "var" attribute. For more info you can check in the orgmode documentation.

The first block needs to output the value:

#+name: make_temporary_directories
#+BEGIN_SRC bash :session *one* :results output
variable=`ls`
echo $variable
#+END_SRC

#+RESULTS: make_temporary_directories
:
: file1 file2 file3 file4 file5 file6 file7 file8

The second block can refer to that value using the name of the previous codeblock:

#+BEGIN_SRC bash :session *two* :results output :var ls_result=make_temporary_directories
echo $ls_result
#+END_SRC

#+RESULTS:
#+begin_example

bash-5.0$ file1 file2 file3 file4 file5 file6 file7 file8
#+end_example


问:
How can i create both the child and parent object in one request Django rest framework
I have a company object that has a OneToOneField(Profile), and Profile has OneToOneField(User)
My question is: is it possible to create all three in one request and if so, how can i do it?

Structure of my company object

```<code>"company":{

    "profile" :{

        "user" : {

            "first_name" : "",
            "last_name" : "",
            "username" : "",
            "email" : ""
        },

        "phone" : "",

        "registered_date" : ""

    },

    "name": "",
    "address": "",
    "currency": "",
    "id_number": "",
    "vat_number": "",
    "vat_company_name": "",
    "company_email": "",
    "fixed_phone": ""
}

</code>```

I tried sending this into the POST request to the Company serializer and this is what i get:

```<code>{
    "profile": [
        "Incorrect type. Expected pk value, received dict."
    ]
}

</code>```

Can i do this without overriding .create() in the serializer?

答:
Yes, you can do it from a single API. You can update your serializers create method. As you are explaining the input request format you can do the following changes in your serilizer.

def create(self, validated_data):
  profile_data = validated_data.pop('profile')
  user_data = profile_data.pop('user')
  user = User.objects.create(**user_data)
  profile = Profile.objects.create(user=user, **profile_data)
  company = Company.objects.create(profile=profile, **validated_data)
  return company
```

The above example is the solution to your question. You can add extra information and play with the data as your requirement inside the create function.

Body:
I have a company object that has a OneToOneField(Profile), and Profile has OneToOneField(User)
My question is: is it possible to create all three in one request and if so, how can i do it?

Structure of my company object

"company":{

    "profile" :{

        "user" : {

            "first_name" : "",
            "last_name" : "",
            "username" : "",
            "email" : ""
        },

        "phone" : "",

        "registered_date" : ""

    },

    "name": "",
    "address": "",
    "currency": "",
    "id_number": "",
    "vat_number": "",
    "vat_company_name": "",
    "company_email": "",
    "fixed_phone": ""
}

I tried sending this into the POST request to the Company serializer and this is what i get:

{
    "profile": [
        "Incorrect type. Expected pk value, received dict."
    ]
}

Can i do this without overriding .create() in the serializer?

Body:
Yes, you can do it from a single API. You can update your serializers create method. As you are explaining the input request format you can do the following changes in your serilizer.

def create(self, validated_data):
  profile_data = validated_data.pop('profile')
  user_data = profile_data.pop('user')
  user = User.objects.create(**user_data)
  profile = Profile.objects.create(user=user, **profile_data)
  company = Company.objects.create(profile=profile, **validated_data)
  return company

The above example is the solution to your question. You can add extra information and play with the data as your requirement inside the create function.


问:
Images of slideshow appear in codepen but not when I open the file on my browser?
I copied a code from W3C to make a slideshow for my website. I was writing my code on codepen and the images were appearing. Then when I copied my code to my editor (Sublime)to add to my html file,the images don't appear. I tried copy the code again from the W3C thinking I left a part of the code and nothing appears. I had the images saved on my computer and tried to put them instead of the image address that I copied from the website I got them from and it still doesn't appear. I attached some images to help understand what I'm doing wrong. I'm new at coding.

答:
Save your html file in parent directory of images(in your case it is pictures folder on your pc). I think that's why it's not showing the images.
or copy your images to the project folder.</p>


问:
unable to run phpunit tests on api rest served by a docker with php-fpm and nginx
I have a docker-compose.yml file where i configure following service :

nginx (web) -> server_php_web_1

php-fpm (php) -> server_php_php_1

mysql (db) -> server_php_db_1

My nginx serve an api rest php over https and vhost is : back-php.dev with associated and working certificates

From outside docker i can curl back-php.dev without problem

there is a directory test where i can run the test when running this command :

```<code>docker exec server_php_php_1 php /code/vendor/phpunit/bin /code/tests
</code>```

But when i m running tests i obtains the following result :

```<code>GuzzleHttp\Exception\ConnectException: cURL error 6: Could not resolve host: back-php.dev
</code>```

I have also tried the following :

```<code>docker exec -it server_php_php_1 /bin/bash
curl server_php_web_1
</code>```

And i can curl successfully the container running nginx, but how can i do if i want to test the following url https://back-php.dev

Here is the structure of docker-compose.yml simplified :

```<code>services:
    web:
        image: nginx:latest
        ports:
            - "80:80"
            - "443:443"
        networks:
            - code-network
        extra_hosts:
            - "back-php.dev:127.0.0.1"
        links:
            - php

    php:
        build: ./
        networks:
            - code-network
    db:
        image: mariadb:10.1
        ports:
            - "3306:3306"
        environment:
            - MYSQL_ROOT_PASSWORD=root
        networks:
            - code-network

networks:
    code-network:
        driver: bridge
</code>```

And the dockerfile associated to php :

```<code>FROM phpdockerio/php74-fpm

RUN apt update
RUN apt install -y \
        php7.4-pdo \
        php7.4-json \
        php7.4-curl \
        php7.4-mbstring \
        php7.4-common \
        php7.4-mysql

RUN echo "ENV_NAME=dev" >> /etc/php/7.4/cli/php.ini
</code>```

答:
extra_hosts:
      - "back-php.dev:127.0.0.1"

Create hostname mapping "inside containers" not outside(host).

So if you want to access you app from "outside"(host) you'll need to create a new entry on /etc/hosts and add

```<code><container_ip> back-php.dev
</code>```

To find your container ip do

```<code>docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' container_name_or_id
</code>```

Update1:

```<code>php:
  ...
  links:
    - back-php.dev:web
</code>```

Body:
I have a docker-compose.yml file where i configure following service :

nginx (web) -> server_php_web_1

php-fpm (php) -> server_php_php_1

mysql (db) -> server_php_db_1

My nginx serve an api rest php over https and vhost is : back-php.dev with associated and working certificates

From outside docker i can curl back-php.dev without problem

there is a directory test where i can run the test when running this command :

docker exec server_php_php_1 php /code/vendor/phpunit/bin /code/tests

But when i m running tests i obtains the following result :

GuzzleHttp\Exception\ConnectException: cURL error 6: Could not resolve host: back-php.dev

I have also tried the following :

docker exec -it server_php_php_1 /bin/bash
curl server_php_web_1

And i can curl successfully the container running nginx, but how can i do if i want to test the following url https://back-php.dev

Here is the structure of docker-compose.yml simplified :

services:
    web:
        image: nginx:latest
        ports:
            - "80:80"
            - "443:443"
        networks:
            - code-network
        extra_hosts:
            - "back-php.dev:127.0.0.1"
        links:
            - php

    php:
        build: ./
        networks:
            - code-network
    db:
        image: mariadb:10.1
        ports:
            - "3306:3306"
        environment:
            - MYSQL_ROOT_PASSWORD=root
        networks:
            - code-network

networks:
    code-network:
        driver: bridge

And the dockerfile associated to php :

FROM phpdockerio/php74-fpm

RUN apt update
RUN apt install -y \
        php7.4-pdo \
        php7.4-json \
        php7.4-curl \
        php7.4-mbstring \
        php7.4-common \
        php7.4-mysql

RUN echo "ENV_NAME=dev" >> /etc/php/7.4/cli/php.ini

Body:
extra_hosts:
      - "back-php.dev:127.0.0.1"

Create hostname mapping "inside containers" not outside(host).

So if you want to access you app from "outside"(host) you'll need to create a new entry on /etc/hosts and add

<container_ip> back-php.dev

To find your container ip do

docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' container_name_or_id

Update1:

php:
  ...
  links:
    - back-php.dev:web


问:
maven plug-ins specified in pom.xml don't execute
I'm building my Java project and have specified 2 maven plug-ins, maven-jar-plugin and maven-dependency-plugin. I execute mvn clean package from the command line. The source code is compiled successfully; however, I never see the dependency plugin executing. In addition, when doing mvn --debug clean package I don't see the jar-plugin executing with my specified parameters.

I'm looking for some assistance as to why these plugins are not running when doing mvn clean package.

A snippet of the pom.xml:

FYI, I did not include all of the dependencies and the groupId, main class information was changed to protect the innocent. However, the structure of the pom.xml is intact.

```<code>`<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.mygroupId</groupId>
  <artifactId>ssmgr</artifactId>
  <version>0.1</version>

  <name>ssmgr</name>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
    <mainClass>com.myclass.App</mainClass>
    <dependenciesDirectory>libs</dependenciesDirectory>
  </properties>

  <build>
    <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
      <plugins>
        <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-dependency-plugin</artifactId>
          <version>3.1.1</version>
          <executions>
            <execution>
              <id>copy-dependencies</id>
              <phase>package</phase>
              <goals>
                <goal>copy-dependencies</goal>
              </goals>
              <configuration>
                <outputDirectory>${project.build.directory}/${dependenciesDirectory}</outputDirectory>
                <overWriteReleases>false</overWriteReleases>
                <overWriteSnapshots>false</overWriteSnapshots>
                <overWriteIfNewer>true</overWriteIfNewer>
                <!-- <overWriteIfNewer>true</overWriteIfNewer> -->
                <!--<includeScope>runtime</includeScope>
                <excludeScope>test</excludeScope>
                <useBaseVersion>false</useBaseVersion> -->
              </configuration>
            </execution>
          </executions>
        </plugin>
        <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-jar-plugin</artifactId>
          <version>3.2.0</version>
          <executions>
            <execution>
              <id>create-jar</id>
              <configuration>
                <archive>
                  <manifest>
                    <addClasspath>true</addClasspath>
                    <classpathPrefix>${dependenciesDirectory}</classpathPrefix>
                    <mainClass>com.myclass.App</mainClass>
                  </manifest>
                </archive>
              </configuration>
            </execution>
          </executions>
        </plugin>
      </plugins>
    </pluginManagement>
  </build>
  <dependencies>
    <dependency>
    </dependency>
  </dependencies>
</project>
</code>```

答:
Both plugins are defined in <pluginManagement>. pluginManagement is used to define plugin versions and configuration. It does not add the plugins to the lifecycle. You need to define the dependency plugin in <plugins> as well (outside pluginManagement).

The Maven Jar Plugin is actually implicitly included in the lifecycle, but as you do not configure the plugin itself but an execution of the plugin, the values never have any effect.

Body:
I'm building my Java project and have specified 2 maven plug-ins, maven-jar-plugin and maven-dependency-plugin. I execute mvn clean package from the command line. The source code is compiled successfully; however, I never see the dependency plugin executing. In addition, when doing mvn --debug clean package I don't see the jar-plugin executing with my specified parameters.

I'm looking for some assistance as to why these plugins are not running when doing mvn clean package.

A snippet of the pom.xml:

FYI, I did not include all of the dependencies and the groupId, main class information was changed to protect the innocent. However, the structure of the pom.xml is intact.

`<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.mygroupId</groupId>
  <artifactId>ssmgr</artifactId>
  <version>0.1</version>

  <name>ssmgr</name>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
    <mainClass>com.myclass.App</mainClass>
    <dependenciesDirectory>libs</dependenciesDirectory>
  </properties>

  <build>
    <pluginManagement>
      <plugins>
        <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-dependency-plugin</artifactId>
          <version>3.1.1</version>
          <executions>
            <execution>
              <id>copy-dependencies</id>
              <phase>package</phase>
              <goals>
                <goal>copy-dependencies</goal>
              </goals>
              <configuration>
                <outputDirectory>${project.build.directory}/${dependenciesDirectory}</outputDirectory>
                <overWriteReleases>false</overWriteReleases>
                <overWriteSnapshots>false</overWriteSnapshots>
                <overWriteIfNewer>true</overWriteIfNewer>

              </configuration>
            </execution>
          </executions>
        </plugin>
        <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-jar-plugin</artifactId>
          <version>3.2.0</version>
          <executions>
            <execution>
              <id>create-jar</id>
              <configuration>
                <archive>
                  <manifest>
                    <addClasspath>true</addClasspath>
                    <classpathPrefix>${dependenciesDirectory}</classpathPrefix>
                    <mainClass>com.myclass.App</mainClass>
                  </manifest>
                </archive>
              </configuration>
            </execution>
          </executions>
        </plugin>
      </plugins>
    </pluginManagement>
  </build>
  <dependencies>
    <dependency>
    </dependency>
  </dependencies>
</project>


问:
Detect waypoint click on DirectionsRenderer marker in Google Maps v3
In the Google Maps API v3, how can I get the waypoint markers from the DirectionsRenderer in order to add click events to them (such as a delete menu).</p>

答:
Instead of creating a click event on a waypoint, you can create it on a marker, and assign it a high z-index so it overlays the waypoint.

Create the single markers and assign the a high z-index

    marker = new google.maps.Marker({
      map:map,
      position: new google.maps.LatLng(1.99, 2.99),
    });
    marker.setZIndex(999);
```

<ol start="2">
<li>Add a listener to the markers
</li>
</ol>

```google.maps.event.addListener(marker, 'click', function(event){
      alert(marker.title);
    });
```

And now create the waypoints.

Body:
Instead of creating a click event on a waypoint, you can create it on a marker, and assign it a high z-index so it overlays the waypoint.

Create the single markers and assign the a high z-index

    marker = new google.maps.Marker({
      map:map,
      position: new google.maps.LatLng(1.99, 2.99),
    });
    marker.setZIndex(999);

Add a listener to the markers

google.maps.event.addListener(marker, 'click', function(event){
      alert(marker.title);
    });

And now create the waypoints.


问:
Flink:StreamingFileSink.withRollingPolicy doesn't work
The rollover time i set is 5s,but it doesn't work.New file was created in 10s or 20s or 30s or more. I don't know why and how it work.The checkpoint time i set is 60s.</p>

```<code>DefaultRollingPolicy.builder()
.withRolloverInterval(5000)
.withInactivityInterval(5000)
.build())
</code>```

答:
Could you provide more information?
What does it mean it does not work? You cannot see any files being committed or you have an exception? Also what do you mean "New file was created in 10s or 20s or 30s or more"?

A first thing to note is that files are going to be committed after the checkpoint is completed, so at least after the 60s.

Body:
The rollover time i set is 5s,but it doesn't work.New file was created in 10s or 20s or 30s or more. I don't know why and how it work.The checkpoint time i set is 60s.

DefaultRollingPolicy.builder()
.withRolloverInterval(5000)
.withInactivityInterval(5000)
.build())


问:
How to return different error message resolved by concrete derived AuthenticationException type in custom AuthenticationFailureHandler
I am using Spring Security to construct my blog application's authentication/authorization. We've decided to use RESTful api, in order to return json message to the client while handling the authentication error in the server side, i have to write custom AuthenticationFailureHandler, like:

public class RganAuthenticationFailureHandler implements AuthenticationFailureHandler {
    private static Logger logger = LoggerFactory.getLogger(RganAuthenticationFailureHandler.class);

    @Override
    public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
        httpServletResponse.setContentType(MediaType.APPLICATION_JSON_VALUE);
        httpServletResponse.setStatus(HttpStatus.UNAUTHORIZED.value());
        httpServletResponse.getWriter().write("some description");
    }
}
```

<p>The <code>AuthenticationException</code> have some concrete derived type, describe what's the exact error, like:
<code>UsernameNotFoundException</code>, <code>BadCredentialsException</code>, <code>AuthenticationServiceException</code>...</p>

<p>It seems to me that i should return different error message for different exception type. For example, for <code>UsernameNotFoundException</code> and <code>BadCredentialsException</code>, i might return "wrong username or password, for <code>AuthenticationServiceException</code>, i might return "some sth wrong happen during getting your credentials, please retry later" and a different HTTP status code(like 500).</p>

<p>Now here's the problem, i know i can write code like:</p>

<pre class="lang-java prettyprint-override"><code>if(e instanceof UsernameNotFoundException || e instanceof BadCredentialsException){
    httpServletResponse.getWriter.write("message1");
}else if(e instance of AuthenticationServiceException){
    httpServletResponse.getWriter.write("message2");
}else if(...){
    // ...
}
</code>```

to handle this, but it seems not to be the best solution, i have to write a serie of else if block.

I've read some post like https://stackoverflow.com/a/46530064/8510613, it seems that use @ControllerAdvice and HandlerExceptionResolver is also not the best solution.

So how should i handle this problem?

答:
You could make the decision further up the stack by using DelegatingAuthenticationFailureHandler

An AuthenticationFailureHandler that delegates to other
  AuthenticationFailureHandler instances based upon the type of
  AuthenticationException passed into onAuthenticationFailure

Body:
I am using Spring Security to construct my blog application's authentication/authorization. We've decided to use RESTful api, in order to return json message to the client while handling the authentication error in the server side, i have to write custom AuthenticationFailureHandler, like:

public class RganAuthenticationFailureHandler implements AuthenticationFailureHandler {
    private static Logger logger = LoggerFactory.getLogger(RganAuthenticationFailureHandler.class);

    @Override
    public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
        httpServletResponse.setContentType(MediaType.APPLICATION_JSON_VALUE);
        httpServletResponse.setStatus(HttpStatus.UNAUTHORIZED.value());
        httpServletResponse.getWriter().write("some description");
    }
}

The AuthenticationException have some concrete derived type, describe what's the exact error, like:
UsernameNotFoundException, BadCredentialsException, AuthenticationServiceException...

It seems to me that i should return different error message for different exception type. For example, for UsernameNotFoundException and BadCredentialsException, i might return "wrong username or password, for AuthenticationServiceException, i might return "some sth wrong happen during getting your credentials, please retry later" and a different HTTP status code(like 500).

Now here's the problem, i know i can write code like:

if(e instanceof UsernameNotFoundException || e instanceof BadCredentialsException){
    httpServletResponse.getWriter.write("message1");
}else if(e instance of AuthenticationServiceException){
    httpServletResponse.getWriter.write("message2");
}else if(...){
    // ...
}

to handle this, but it seems not to be the best solution, i have to write a serie of else if block.

I've read some post like https://stackoverflow.com/a/46530064/8510613, it seems that use @ControllerAdvice and HandlerExceptionResolver is also not the best solution.

So how should i handle this problem?


问:
Using sensitive environment variables in Kubernetes configMaps
I know you can use ConfigMap properties as environment variables in the pod spec, but can you use environment variables declared in the pods spec inside the configmap?

For example:

I have a secret password which I wish to access in my configmap application.properties. The secret looks like so:

```<code>apiVersion: v1
data:
  pw: THV3OE9vcXVpYTll==
kind: Secret
metadata:
  name: foo
  namespace: foo-bar
type: Opaque
</code>```

so inside the pod spec I reference the secret as an env var. The configMap will be mounted as a volume from within the spec:

```<code>    env:
      - name: PASSWORD
        valueFrom:
          secretKeyRef:
            name: foo
            key: pw
...
</code>```

and inside my configMap I can then reference the secret value like so:

```<code>apiVersion: v1
kind: ConfigMap
metadata:
  name: application.properties
  namespace: foo-bar
data:
  application.properties: /
    secret.password=$(PASSWORD)
</code>```

Anything I've found online is just about consuming configMap values as env vars and doesn't mention consuming env vars in configMap values.

答:
Currently it's not a Kubernetes Feature.

There is a closed issue requesting this feature and it's kind of controversial topic because the discussion is ongoing many months after being closed:
Reference Secrets from ConfigMap #79224

Referencing the closing comment:

Best practice is to not use secret values in envvars, only as mounted files. if you want to keep all config values in a single object, you can place all the values in a secret object and reference them that way.
  Referencing secrets via configmaps is a non-goal... it confuses whether things mounting or injecting the config map are mounting confidential values.

I suggest you to read the entire thread to understand his reasons and maybe find another approach for your environment to get this variables.

"OK, but this is Real Life, I need to make this work"

Then I recommend you this workaround:

Import Data to Config Map from Kubernetes Secret

It makes the substitution with a shell in the entrypoint of the container.

Body:
I know you can use ConfigMap properties as environment variables in the pod spec, but can you use environment variables declared in the pods spec inside the configmap?

For example:

I have a secret password which I wish to access in my configmap application.properties. The secret looks like so:

apiVersion: v1
data:
  pw: THV3OE9vcXVpYTll==
kind: Secret
metadata:
  name: foo
  namespace: foo-bar
type: Opaque

so inside the pod spec I reference the secret as an env var. The configMap will be mounted as a volume from within the spec:

    env:
      - name: PASSWORD
        valueFrom:
          secretKeyRef:
            name: foo
            key: pw
...

and inside my configMap I can then reference the secret value like so:

apiVersion: v1
kind: ConfigMap
metadata:
  name: application.properties
  namespace: foo-bar
data:
  application.properties: /
    secret.password=$(PASSWORD)

Anything I've found online is just about consuming configMap values as env vars and doesn't mention consuming env vars in configMap values.


问:
Why does itoa expect a signed character instead of an unsigned?
Learning embedded C while working in MPLAB X with a PIC24FJ128GB204.

So far, I've mostly heard that you should use unsigned types as much as possible (especially?) on embedded devices, so I've started to use uint8_t arrays to hold strings. However, if I call itoa from stdlib.h, it expects a pointer to a signed char (int8_t) array:

extern char *    itoa(char * buf, int val, int base);

This is made specifically clear when I try to compile after using itoa on an unsigned array:

```<code>main.c:317:9: warning: pointer targets in passing argument 1 of 'itoa' differ in signedness
c:\program files (x86)\microchip\xc16\v1.36\bin\bin\../..\include/stdlib.h:131:15: note: expected 'char *' but argument is of type 'unsigned char *'
</code>```

Searching for implementations of itoa on other platforms, that seems to be the common case.

Why is that?

(I've also noticed that most implementations expect value/pointer/radix whereas -for some reason- the stdlib.h from Microchip expects the pointer first. It took me a while to realize this.)

答:
So far, I've mostly heard that you should use unsigned types as much as possible (especially?) on embedded devices,

Have the people you heard this from explained why?  Is that explanation grounded in solid analysis and engineering, or is it pulled out of thin air?

The problem with rules of thumb is that they often get applied unthinkingly in the wrong situation.  Use unsigned types when you need to use unsigned types, use signed types when you need to use signed types.

I've started to use uint8_t arrays to hold strings.

Don't.  That's not what it's there for.

Plain char may be signed or unsigned, depending on the environment.  The character encodings for the basic character set (upper- and lower-case Latin alphabet, decimal digits, and the basic set of graphical characters) are always going to be non-negative, but extended characters may have positive or negative encodings.

6.2.5 Types

...

3 An object declared as type char is large enough to store any member of the basic
execution character set. If a member of the basic execution character set is stored in a
char object, its value is guaranteed to be nonnegative. If any other character is stored in
a char object, the resulting value is implementation-defined but shall be within the range
of values that can be represented in that type.

C 2011 Online Draft

The C library functions that handle strings expect pointers to char, not unsigned char or uint8_t or anything else.  While it's highly likely that for any platform that offers it uint8_t is simply a typedef name for unsigned char, that's not a guarantee.  char must be at least 8 bits wide, but there are platforms where it could be wider (one of the old PDPs used 9-bit bytes and 36-bit words, and depending on the application I can see some special-purpose embedded systems using wonky sizes).

Body:
Learning embedded C while working in MPLAB X with a PIC24FJ128GB204.

So far, I've mostly heard that you should use unsigned types as much as possible (especially?) on embedded devices, so I've started to use uint8_t arrays to hold strings. However, if I call itoa from stdlib.h, it expects a pointer to a signed char (int8_t) array:

extern char *    itoa(char * buf, int val, int base);

This is made specifically clear when I try to compile after using itoa on an unsigned array:

main.c:317:9: warning: pointer targets in passing argument 1 of 'itoa' differ in signedness
c:\program files (x86)\microchip\xc16\v1.36\bin\bin\../..\include/stdlib.h:131:15: note: expected 'char *' but argument is of type 'unsigned char *'

Searching for implementations of itoa on other platforms, that seems to be the common case.

Why is that?

(I've also noticed that most implementations expect value/pointer/radix whereas -for some reason- the stdlib.h from Microchip expects the pointer first. It took me a while to realize this.)


问:
How to set multiple attributes for calender object at once?
This is my existing code snippet:

```<code>Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
</code>```

I just want to assign those attributes at once, something like:

```<code>Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, Calendar.MINUTE, Calendar.SECOND, Calendar.MILLISECOND, 0);
</code>```

I am not sure it is possible or not, because I am new to java. Please help me if there is other way around to achive this.

If possible, please give others solutions also. Objective is to set the given cal object to 00:00:00.000A.M.

Edit 1: I think this question was clear and understandable. Please consider upvoting as I couldn't ask anymore questions on stackoverflow.

答:
There is an overloaded set method in the Calendar class:

```<code>void java.util.Calendar.set(int year, int month, int date, int hourOfDay, int minute, int second)
</code>```

Unfortunately you have to set your milliseconds manually. And you also have to use date formatter. Here an example

```<code>SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss.SSS aa");
Calendar cal = Calendar.getInstance();
cal.set(0, 0, 0, 0, 0, 0);
cal.set(Calendar.MILLISECOND, 0);
System.out.println(sdf.format(cal.getTime()));
</code>```

It returns 00:00:00.000 AM

Body:
This is my existing code snippet:

Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);

I just want to assign those attributes at once, something like:

Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, Calendar.MINUTE, Calendar.SECOND, Calendar.MILLISECOND, 0);

I am not sure it is possible or not, because I am new to java. Please help me if there is other way around to achive this.

If possible, please give others solutions also. Objective is to set the given cal object to 00:00:00.000A.M.

Edit 1: I think this question was clear and understandable. Please consider upvoting as I couldn't ask anymore questions on stackoverflow.

Body:
There is an overloaded set method in the Calendar class:

void java.util.Calendar.set(int year, int month, int date, int hourOfDay, int minute, int second)

Unfortunately you have to set your milliseconds manually. And you also have to use date formatter. Here an example

SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss.SSS aa");
Calendar cal = Calendar.getInstance();
cal.set(0, 0, 0, 0, 0, 0);
cal.set(Calendar.MILLISECOND, 0);
System.out.println(sdf.format(cal.getTime()));

It returns 00:00:00.000 AM


问:
pip installing Flask-Ask raises ModuleNotFound pip.req
When I try to install Flask-Ask, I get the following error. How do I fix it?</p>

```<code>$ pip install flask-ask
Collecting flask-ask
Using cached Flask-Ask-0.9.8.tar.gz (40 kB)
ERROR: Command errored out with exit status 1:
 command: 'c:\users\loz99\appdata\local\programs\python\python38-32\python.exe' -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\loz99\\AppData\\Local\\Temp\\pip-install-kw14h5ho\\flask-ask\\setup.py'"'"'; __file__='"'"'C:\\Users\\loz99\\AppData\\Local\\Temp\\pip-install-kw14h5ho\\flask-ask\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base 'C:\Users\loz99\AppData\Local\Temp\pip-install-kw14h5ho\flask-ask\pip-egg-info'
     cwd: C:\Users\loz99\AppData\Local\Temp\pip-install-kw14h5ho\flask-ask\
Complete output (5 lines):
Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "C:\Users\loz99\AppData\Local\Temp\pip-install-kw14h5ho\flask-ask\setup.py", line 8, in <module>
    from pip.req import parse_requirements
ModuleNotFoundError: No module named 'pip.req'
----------------------------------------
ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output.
</code>```

答:
Your problem has been fixed but that version was never released to PyPi.

You can try to install from github directly:

```<code>pip install https://github.com/johnwheeler/flask-ask/archive/master.zip
</code>```

Body:
When I try to install Flask-Ask, I get the following error. How do I fix it?

$ pip install flask-ask
Collecting flask-ask
Using cached Flask-Ask-0.9.8.tar.gz (40 kB)
ERROR: Command errored out with exit status 1:
 command: 'c:\users\loz99\appdata\local\programs\python\python38-32\python.exe' -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\loz99\\AppData\\Local\\Temp\\pip-install-kw14h5ho\\flask-ask\\setup.py'"'"'; __file__='"'"'C:\\Users\\loz99\\AppData\\Local\\Temp\\pip-install-kw14h5ho\\flask-ask\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base 'C:\Users\loz99\AppData\Local\Temp\pip-install-kw14h5ho\flask-ask\pip-egg-info'
     cwd: C:\Users\loz99\AppData\Local\Temp\pip-install-kw14h5ho\flask-ask\
Complete output (5 lines):
Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "C:\Users\loz99\AppData\Local\Temp\pip-install-kw14h5ho\flask-ask\setup.py", line 8, in <module>
    from pip.req import parse_requirements
ModuleNotFoundError: No module named 'pip.req'
----------------------------------------
ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output.

Body:
Your problem has been fixed but that version was never released to PyPi.

You can try to install from github directly:

pip install https://github.com/johnwheeler/flask-ask/archive/master.zip


问:
What is the Ideal way to return data from function without leaking memory?
In IPhone Development ObjC , I wonder what is the right approach for functions to return some values in Dictionaries or Arrays. I mean should they return autorelease objects, but wouldn't it be bad if I am using too many functions to return values, like getUserRecordsFromDB() function will return all the user records, so should they return me autorelease objects? also when I am calling them multiple times, suppose with a span of 4 seconds to get the newely updated data. Can somebody let me an ideal scanario of how to get data from a function called frequently in the flow of program, and not leaking the memory.</p>

答: Yes you should use autoreleased objects as return values.</p>


问:
Scala MultipartEntityBuilder is not creating the boundary correctly for a Spring Rest point
I have a request body that consists of more than one body part and below is how I am handling it in scala using a multipartentitybuilder library in scala.

val data = MultipartEntityBuilder.create()
        .setMode(HttpMultipartMode.BROWSER_COMPATIBLE)
        .addPart("actual Header", new StringBody(actualHeader,ContentType.APPLICATION_JSON))
        .addBinaryBody("payload", requestBody)
        .build()

for context, the binary body is a Byte[] of an avro event that needs to be sent to this post request.

On Attempting to send this entity to a spring rest endpoint via httpPost, I am getting the following exception in response.

org.springframework.web.multipart.MultipartException: Failed to parse multipart servlet request; nested exception is java.io.IOException: org.apache.tomcat.util.http.fileupload.FileUploadException: the request was rejected because no multipart boundary was found

What I have tried:

I tried to manually add a boundary with .setBoundary() but that did not help.

There was another way to go in the other solutions available online. I could get rid of the headers that say ContentType.Application-JSON, however removing that is going to fail at the API level, since they have checks for it, so that wouldn't work either.

I tried adding the binary body as a part to make it consistent which made the code look like this

val data = MultipartEntityBuilder.create()
        .setMode(HttpMultipartMode.BROWSER_COMPATIBLE)
        .addPart("Event Header", new StringBody(eventHeader,ContentType.APPLICATION_JSON))
        .addPart("payload",new ByteArrayBody(requestBody, ContentType.DEFAULT_BINARY, null.asInstanceOf[String]))
        .build()

Tried to have the multipartEntityBuilder create the textbody (for JSON part)
and bytearray for payload part and got rid of content Type, using the following code

val data = MultipartEntityBuilder.create()
        .setBoundary(boundary)
        .addTextBody("Event Header",eventHeader,ContentType.APPLICATION_JSON)     .addBinaryBody("Payload",requestBody,ContentType.DEFAULT_BINARY,null.asInstanceOf[String])
        .build()

this got me further as in it autodetected the ContentType as multipart/form-data but when I setEntity to post, it did not transfer that information over to the POST and that still didn't correctly assign the boundary as part of the content type in the header

Also tried to add header from a file making sure the two bodies were consistent in nature with the following code

val file = new File("eventHeader.json")
  val data = MultipartEntityBuilder.create()
        .setMode(HttpMultipartMode.BROWSER_COMPATIBLE)
        .addBinaryBody("Event Header",file,ContentType.APPLICATION_JSON,"eventHeader.json")
        .addBinaryBody("Avro Payload",requestBody)
        .build()

No luck

For more context and info, below are the other attributes to the POST request

```<code>val post = new HttpPost(url);
val client: CloseableHttpClient = HttpClientBuilder.create().build();
post.setConfig(requestConfig)
post.setHeader("Content-type", "multipart/form-data")
post.setEntity(data)

val response: HttpResponse = client.execute(post)
</code>```

Another piece of information, when I debug the entity in IntelliJ it shows me a boundary that is created but I don't see it anywhere physically on the content.(not sure how helpful this information is)

Now, the exception is referencing to springframework and I have a nagging suspicion that scala is not playing well with that. However, we have successfully implemented gatling test scenarios in scala so it is not completely impossible to pull that off.

Hence, I now surrender to the community's expertise on how to go about solving this without being too invasive because this is going to be part of a spark service so let's not ignore the data distribution aspect of it all.

答:
I finally got it to work with a simple addition of boundary from the content type of the data originally generated.

Below is how I changed my code for the request to go through,

val file = new File("testHeader.json")

```<code>   val data = MultipartEntityBuilder.create()
  .setMode(HttpMultipartMode.BROWSER_COMPATIBLE)
  .addBinaryBody("Event Header",file,ContentType.APPLICATION_JSON,"testHeader.json")
  .addBinaryBody("Avro Payload",requestBody)
  .build()
</code>```

```<code>val client: CloseableHttpClient = HttpClientBuilder.create().build();

val APIUrl = url

val post = new HttpPost(APIUrl);
post.setConfig(requestConfig)
post.setHeader(data.getContentType)
post.setEntity(data)
</code>```

Simple solution but kind of a work around, for some reason (that I am not aware of) it didn't auto detect the type when I didn't set the content type at all. Hopefully this helps another poor dud like me sometime in the future.

Body:
I have a request body that consists of more than one body part and below is how I am handling it in scala using a multipartentitybuilder library in scala.

val data = MultipartEntityBuilder.create()
        .setMode(HttpMultipartMode.BROWSER_COMPATIBLE)
        .addPart("actual Header", new StringBody(actualHeader,ContentType.APPLICATION_JSON))
        .addBinaryBody("payload", requestBody)
        .build()

for context, the binary body is a Byte[] of an avro event that needs to be sent to this post request.

On Attempting to send this entity to a spring rest endpoint via httpPost, I am getting the following exception in response.

org.springframework.web.multipart.MultipartException: Failed to parse multipart servlet request; nested exception is java.io.IOException: org.apache.tomcat.util.http.fileupload.FileUploadException: the request was rejected because no multipart boundary was found

What I have tried:

I tried to manually add a boundary with .setBoundary() but that did not help.

There was another way to go in the other solutions available online. I could get rid of the headers that say ContentType.Application-JSON, however removing that is going to fail at the API level, since they have checks for it, so that wouldn't work either.

I tried adding the binary body as a part to make it consistent which made the code look like this

val data = MultipartEntityBuilder.create()
        .setMode(HttpMultipartMode.BROWSER_COMPATIBLE)
        .addPart("Event Header", new StringBody(eventHeader,ContentType.APPLICATION_JSON))
        .addPart("payload",new ByteArrayBody(requestBody, ContentType.DEFAULT_BINARY, null.asInstanceOf[String]))
        .build()

Tried to have the multipartEntityBuilder create the textbody (for JSON part)
and bytearray for payload part and got rid of content Type, using the following code

val data = MultipartEntityBuilder.create()
        .setBoundary(boundary)
        .addTextBody("Event Header",eventHeader,ContentType.APPLICATION_JSON)     .addBinaryBody("Payload",requestBody,ContentType.DEFAULT_BINARY,null.asInstanceOf[String])
        .build()

this got me further as in it autodetected the ContentType as multipart/form-data but when I setEntity to post, it did not transfer that information over to the POST and that still didn't correctly assign the boundary as part of the content type in the header

Also tried to add header from a file making sure the two bodies were consistent in nature with the following code

val file = new File("eventHeader.json")
  val data = MultipartEntityBuilder.create()
        .setMode(HttpMultipartMode.BROWSER_COMPATIBLE)
        .addBinaryBody("Event Header",file,ContentType.APPLICATION_JSON,"eventHeader.json")
        .addBinaryBody("Avro Payload",requestBody)
        .build()

No luck

For more context and info, below are the other attributes to the POST request

val post = new HttpPost(url);
val client: CloseableHttpClient = HttpClientBuilder.create().build();
post.setConfig(requestConfig)
post.setHeader("Content-type", "multipart/form-data")
post.setEntity(data)

val response: HttpResponse = client.execute(post)

Another piece of information, when I debug the entity in IntelliJ it shows me a boundary that is created but I don't see it anywhere physically on the content.(not sure how helpful this information is)

Now, the exception is referencing to springframework and I have a nagging suspicion that scala is not playing well with that. However, we have successfully implemented gatling test scenarios in scala so it is not completely impossible to pull that off.

Hence, I now surrender to the community's expertise on how to go about solving this without being too invasive because this is going to be part of a spark service so let's not ignore the data distribution aspect of it all.

Body:
I finally got it to work with a simple addition of boundary from the content type of the data originally generated.

Below is how I changed my code for the request to go through,

val file = new File("testHeader.json")

   val data = MultipartEntityBuilder.create()
  .setMode(HttpMultipartMode.BROWSER_COMPATIBLE)
  .addBinaryBody("Event Header",file,ContentType.APPLICATION_JSON,"testHeader.json")
  .addBinaryBody("Avro Payload",requestBody)
  .build()

val client: CloseableHttpClient = HttpClientBuilder.create().build();

val APIUrl = url

val post = new HttpPost(APIUrl);
post.setConfig(requestConfig)
post.setHeader(data.getContentType)
post.setEntity(data)

Simple solution but kind of a work around, for some reason (that I am not aware of) it didn't auto detect the type when I didn't set the content type at all. Hopefully this helps another poor dud like me sometime in the future.


问:
Will Python Daemon thread be blocked by busy parent thread given there is GIL?
I know Python daemon thread will auto exit if parent thread exit. The reason I ask if because my main thread is sometime working on CPU heavy calculation which blocks the heart beat message. Other module thinks this service is dead and planning for funeral.

I want to use some kind of daemon thread(or process?) that is the child of main thread, to send heart beat message.

My question is if my main thread is blocking, for example:

```<code>while True:
   a = a + 1
</code>```

Will my daemon child thread be blocked as well? any example or evidence? What role does GIL (Global Interpreter Lock) play here?

Edit

To @ShadowRanger's point, the following example shows, waiter can log out the the message, given the worker thread is blocking (taking 220% CPU resource)

```<code>import time
from threading import Thread

class worker(Thread):
    def run(self):
        t = 10
        x = 10
        while True:
            x = t + 1

class waiter(Thread):
    def run(self):
        for x in xrange(100,150):
            print x
            time.sleep(0.5)

def run():
    worker().start()
    waiter().start()

run()
</code>```

答:
If your main thread is executing Python byte code (not embedded in some expensive long term call to a C extension module that holds the GIL for the length of the call and doesn't return to the interpreter for a long time), then the daemon thread will eventually get a chance to run; the main thread will be preempted after a while (a matter of milliseconds) and the daemon thread will run while the main thread is blocked. As long as your heartbeat interval is measured in seconds, that should be fine.

Only one thread actually runs at any given time, but both will interleave execution.

The scenario with long term GIL holding by an extension can come up by accident, to be clear; all extensions default to holding the GIL. While popular, widely-used extensions like numpy are careful about releasing the GIL when they've got enough work to do, extensions written by less experienced developers (especially those writing in Cython with no knowledge of the GIL) are more likely to hold the GIL for long periods, so if your heartbeat isn't working and extension modules are involved, they're a likely culprit. A simple while True: a = a + 1 loop would be safe though (assuming a isn't some weirdo extension type); the GIL can be switched easily there.

Body:
I know Python daemon thread will auto exit if parent thread exit. The reason I ask if because my main thread is sometime working on CPU heavy calculation which blocks the heart beat message. Other module thinks this service is dead and planning for funeral.

I want to use some kind of daemon thread(or process?) that is the child of main thread, to send heart beat message.

My question is if my main thread is blocking, for example:

while True:
   a = a + 1

Will my daemon child thread be blocked as well? any example or evidence? What role does GIL (Global Interpreter Lock) play here?

Edit

To @ShadowRanger's point, the following example shows, waiter can log out the the message, given the worker thread is blocking (taking 220% CPU resource)

import time
from threading import Thread

class worker(Thread):
    def run(self):
        t = 10
        x = 10
        while True:
            x = t + 1

class waiter(Thread):
    def run(self):
        for x in xrange(100,150):
            print x
            time.sleep(0.5)

def run():
    worker().start()
    waiter().start()

run()


问:
Why Angular evaluates first route only?
I have the following routes which all have the same path. The route is activated based on logic in the canLoad but Angular evaluates the first route with data A only and does not go through second if the first fails. I tested the logic in the canLoad and there is nothing wrong there. It returns true and false.

```<code>const routes: Routes = [
  {
    path: '',
    component: NbAuthComponent,
    children: [
      {
        path: '',
        canLoad: [AuthGuardProviderService],
        data: {provider: 'A'},
        loadChildren: () => import('./xx/auth.module').then(m => m.AuthModule),
      },
      {
        path: '',
        canLoad: [AuthGuardProviderService],
        loadChildren: () => import('./x/auth.module').then(m => m.AuthModule),
      }
    ]
  }
];
</code>```

CanLoad:

```<code>export class AuthGuardProviderService implements CanLoad {

  constructor() {
  }

  canLoad(route: Route): boolean {
    const data = route.data.provider;
    return this.getRoute(data);
  }

  private getRoute(data): boolean {
    const paths = location.href.split('/');
    if (data === 'A') {
      return true;
    } else if (!data) {
      return true;
    }
  }
}
</code>```

Updated question using UrlMatcher:

what you're trying to accomplish with this implementation

User case: I have multiple modules and load a module based on URL. For instance:
User A hits: localhost/a and the module loads.

```<code>path: '',
loadChildren: () => import('./a/auth.module').then(m => m.AuthModule)
</code>```

And if User B hits: localhost/b I want to load:

```<code>path: '',
loadChildren: () => import('./b/auth.module').then(m => m.AuthModule)
</code>```

I can use UrlMatcher but this works only for first route.

```<code>const matcher = (url: UrlSegment[], providerParam) => {
  const paths = location.href.split('/');
  if ((paths[3] === '' || paths[3] === 'auth') && providerParam === 'win') {
    return {consumed: url};
  } else if (paths[3] !== '') {
    const provider = providers.find(p => paths[3].toLowerCase() === p.shortName);
    return provider && provider.shortName === providerParam ? {consumed: url} : null;
  }
  return null;
};
</code>```

And the lazy load module has:

```<code>const routes: Routes = [
  {
    path: '',
    component: NbAuthComponent,
    children: [
      {
        path: '',
        component: NbLoginComponent,
      },
      {
        path: 'sign-in',
        component: NbLoginComponent,
      },
      {
        path: 'sign-up',
        component: NbRegisterComponent,
      }
    ],
  },
];
</code>```

Now the problem with this approach is that it always loads sign-in component. It always hits path: '' not going to other paths like auth/sign-up

It might be worth to mention that if user hits localhost/a I am setting a as baseHref, therefore, I cannot use this as a path. It would be straight forward if I don't set it as baseHref. The a or b path is not part of the route.

It would also help provide more context if we could see your guard
  implementation

I also tried using guard but that is not helpful either since all paths are same '' empty string, and Angular routes matches the first one and does not evaluate guard on the rest.

what data you want to associate with the first route and how you're
  planning to use it

The purpose of the data is just to know which route is being evaluated.

答:
Angular only matches on the first. It won't proceed even if your guard fails. You can look into something called a matcher which can replace the path argument as one way around this.

https://angular.io/api/router/UrlMatcher

Title: Why Angular evaluates first route only?

Body:
I have the following routes which all have the same path. The route is activated based on logic in the canLoad but Angular evaluates the first route with data A only and does not go through second if the first fails. I tested the logic in the canLoad and there is nothing wrong there. It returns true and false.

const routes: Routes = [
  {
    path: '',
    component: NbAuthComponent,
    children: [
      {
        path: '',
        canLoad: [AuthGuardProviderService],
        data: {provider: 'A'},
        loadChildren: () => import('./xx/auth.module').then(m => m.AuthModule),
      },
      {
        path: '',
        canLoad: [AuthGuardProviderService],
        loadChildren: () => import('./x/auth.module').then(m => m.AuthModule),
      }
    ]
  }
];

CanLoad:

export class AuthGuardProviderService implements CanLoad {

  constructor() {
  }

  canLoad(route: Route): boolean {
    const data = route.data.provider;
    return this.getRoute(data);
  }

  private getRoute(data): boolean {
    const paths = location.href.split('/');
    if (data === 'A') {
      return true;
    } else if (!data) {
      return true;
    }
  }
}

Updated question using UrlMatcher:

what you're trying to accomplish with this implementation

User case: I have multiple modules and load a module based on URL. For instance:
User A hits: localhost/a and the module loads.

path: '',
loadChildren: () => import('./a/auth.module').then(m => m.AuthModule)

And if User B hits: localhost/b I want to load:

path: '',
loadChildren: () => import('./b/auth.module').then(m => m.AuthModule)

I can use UrlMatcher but this works only for first route.

const matcher = (url: UrlSegment[], providerParam) => {
  const paths = location.href.split('/');
  if ((paths[3] === '' || paths[3] === 'auth') && providerParam === 'win') {
    return {consumed: url};
  } else if (paths[3] !== '') {
    const provider = providers.find(p => paths[3].toLowerCase() === p.shortName);
    return provider && provider.shortName === providerParam ? {consumed: url} : null;
  }
  return null;
};

And the lazy load module has:

const routes: Routes = [
  {
    path: '',
    component: NbAuthComponent,
    children: [
      {
        path: '',
        component: NbLoginComponent,
      },
      {
        path: 'sign-in',
        component: NbLoginComponent,
      },
      {
        path: 'sign-up',
        component: NbRegisterComponent,
      }
    ],
  },
];

Now the problem with this approach is that it always loads sign-in component. It always hits path: '' not going to other paths like auth/sign-up

It might be worth to mention that if user hits localhost/a I am setting a as baseHref, therefore, I cannot use this as a path. It would be straight forward if I don't set it as baseHref. The a or b path is not part of the route.

It would also help provide more context if we could see your guard
  implementation

I also tried using guard but that is not helpful either since all paths are same '' empty string, and Angular routes matches the first one and does not evaluate guard on the rest.

what data you want to associate with the first route and how you're
  planning to use it

The purpose of the data is just to know which route is being evaluated.


答:
If possible, avoid the use of the legacy Calendar class.  Do use the classes from the java.time package, e.g.:

```<code>LocalDateTime todayAtStartOfDay = LocalDate.now().atStartOfDay();
</code>```

But if Calendar must be used, then consider using Calendar.Builder, e.g,:

```<code>Calendar cal = new Calendar.Builder()
            .setTimeOfDay(0, 0, 0, 0)  // hour, minute, second, millis
            .build();
</code>```

Title: How to set multiple attributes for calender object at once?

Body:
If possible, avoid the use of the legacy Calendar class.  Do use the classes from the java.time package, e.g.:

LocalDateTime todayAtStartOfDay = LocalDate.now().atStartOfDay();

But if Calendar must be used, then consider using Calendar.Builder, e.g,:

Calendar cal = new Calendar.Builder()
            .setTimeOfDay(0, 0, 0, 0)  // hour, minute, second, millis
            .build();


问:
Change order of blocks for mobile and desktop both vertically and horizontally
I am trying to create a layout which allows me change the order of elements between mobile and desktop as demonstrated by the diagram bellow:

I have ordered them in the DOM within a single container in the order as they are numbered. I'm trying to get the second item to display to the left as shown. I tried with flex but couldn't get it right. I also tried floating the second div to the left and the rest to the right, but this is messy, especially if the 4th element in right column overlaps the 3rd.

Can somebody help me with this?

Thanks

答:
try this

.container {
  display: flex;
  flex-wrap: wrap;
  position: relative;
}

.container .inner-container1 {
  flex-grow: 2;
}

.container .inner-container2 {
  flex-grow: 1;
}

.box {
  flex-grow: 1;
}

.diff {
  position: absolute;
  width: 50%;
  background-color: red;
  left: 0px;
  top: 0px;
  height: 100%;
}

/* set your desired max-width */

@media screen and (max-width: 500px) {
  .diff {
    position: initial;
    width: initial;
  }
  .container .inner-container1 {
    display: none;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>  <div class="container">

    <div class="inner-container1">
    </div>

    <div class="inner-container2">

      <div class="box">1</div>
      <div class="box diff">2</div>
      <div class="box">3</div>
      <div class="box">4</div>

    </div>

</div></code>```

Body:
try this

.container {
  display: flex;
  flex-wrap: wrap;
  position: relative;
}

.container .inner-container1 {
  flex-grow: 2;
}

.container .inner-container2 {
  flex-grow: 1;
}

.box {
  flex-grow: 1;
}

.diff {
  position: absolute;
  width: 50%;
  background-color: red;
  left: 0px;
  top: 0px;
  height: 100%;
}

/* set your desired max-width */

@media screen and (max-width: 500px) {
  .diff {
    position: initial;
    width: initial;
  }
  .container .inner-container1 {
    display: none;
  }
}

  <div class="container">

    <div class="inner-container1">
    </div>

    <div class="inner-container2">

      <div class="box">1</div>
      <div class="box diff">2</div>
      <div class="box">3</div>
      <div class="box">4</div>

    </div>

</div>


问:
How to increment a value in ngfor angular 6 for every third iteration
How to increment a value for every 3rd iteration in ngFor.

 I want to achieve like this in angular ngfor, how to do this

I am using array of objects like below and I am looping tempArr[] using ngFor

  tempArrA = ['item a', 'item b', 'item c', 'item d', 'item e', 'item f', 'item g', 'item h','item i', 'item j', 'item k', 'item l','item m', 'item n', 'item o', 'item p'];
  tempArrB = ['item f', 'item g', 'item h','item i', 'item j'];
  tempArrC = [ 'item j', 'item k', 'item l','item m', 'item n', 'item o', 'item p'];
  tempArr:any = [
    {
      name: "one",
      items: this.tempArrA
      },
       {
      name: "two",
      items: this.tempArrB
      },
       {
      name: "three",
      items: this.tempArrC
      },
      ];```

item a -- 1

item b -- 1

item c -- 1

item d -- 2

item e -- 2

item f -- 2

item g -- 3

item h -- 3

item i -- 3

and so on....

答:
You could use an array.reduce to reduce your flat array into a 2-dimensional array.

component.ts

```<code>// simple array for this example
const source = [1, 2, 3, 4, 5, 6];

this.model = source.reduce((arr, current, idx) => {
  const index = Math.floor(idx / 3);
  if (arr.length === index) {
    arr.push([]);
  }

  arr[index].push(current);
  return arr;
}, []);
</code>```

component.html

```<code><ng-container *ngFor="let group of model; let i = index">
  <div *ngFor="let item of group">
    {{item}} -- {{i + 1}}
  </div>
</ng-container>
</code>```

This simple example transforms an array of length 6

```<code>[ 1, 2, 3, 4, 5, 6 ]
</code>```

Into a 2D array of length 2:

```<code>[
  [ 1, 2, 3 ],
  [ 4, 5, 6 ]
]
</code>```

Once you have your model in a structure that matches your needs, it becomes easy to use the outer index as your counter that increments by 3. You could even map the outer index to a new object if you need to do more with it.

It would be simple enough for you to convert this using your model.

Working demo: https://stackblitz.com/edit/angular-c2hcrz

How does this work?

I'm using the first 3 parameters of the reduce callback function here

```<code>(arr, current, idx)
</code>```

And invoking reduce with an empty array - the second argument.

Think of reduce like map - it loops through the source array, and lets you put each value where you want.

In the callback:

arr is the new array that gets built up and ultimately returned.

current is the current value in the loop from the source array

idx is the current index in the loop from the source array

Firstly I work out where in the new array we should add the current index by doing Math.floor(idx / 3). This allows us to increment the target index by 1 every third increment of the source array. The rest is fairly simple javascript.

With objects

It is trivial to use this with objects. The content doesn't matter here, it's the index in the original array that is driving the grouping:

```<code>    const source = [
      { name: 'One', id: 1 },
      { name: 'Two', id: 2 },
      { name: 'Three', id: 3 },
      { name: 'Four', id: 4 },
      { name: 'Five', id: 5 },
      { name: 'Six', id: 6 }
    ];

    this.objModel = source.reduce((arr, current, idx) => {
      const index = Math.floor(idx / 3);
      if (arr.length === index) {
        arr.push([]);
      }

      arr[index].push(current);
      return arr;
    }, []);
</code>```

Body:
How to increment a value for every 3rd iteration in ngFor.

 I want to achieve like this in angular ngfor, how to do this

I am using array of objects like below and I am looping tempArr[] using ngFor

  tempArrA = ['item a', 'item b', 'item c', 'item d', 'item e', 'item f', 'item g', 'item h','item i', 'item j', 'item k', 'item l','item m', 'item n', 'item o', 'item p'];
  tempArrB = ['item f', 'item g', 'item h','item i', 'item j'];
  tempArrC = [ 'item j', 'item k', 'item l','item m', 'item n', 'item o', 'item p'];
  tempArr:any = [
    {
      name: "one",
      items: this.tempArrA
      },
       {
      name: "two",
      items: this.tempArrB
      },
       {
      name: "three",
      items: this.tempArrC
      },
      ];

item a -- 1

item b -- 1

item c -- 1

item d -- 2

item e -- 2

item f -- 2

item g -- 3

item h -- 3

item i -- 3

and so on....

Body:
You could use an array.reduce to reduce your flat array into a 2-dimensional array.

component.ts

// simple array for this example
const source = [1, 2, 3, 4, 5, 6];

this.model = source.reduce((arr, current, idx) => {
  const index = Math.floor(idx / 3);
  if (arr.length === index) {
    arr.push([]);
  }

  arr[index].push(current);
  return arr;
}, []);

component.html

<ng-container *ngFor="let group of model; let i = index">
  <div *ngFor="let item of group">
    {{item}} -- {{i + 1}}
  </div>
</ng-container>

This simple example transforms an array of length 6

[ 1, 2, 3, 4, 5, 6 ]

Into a 2D array of length 2:

[
  [ 1, 2, 3 ],
  [ 4, 5, 6 ]
]

Once you have your model in a structure that matches your needs, it becomes easy to use the outer index as your counter that increments by 3. You could even map the outer index to a new object if you need to do more with it.

It would be simple enough for you to convert this using your model.

Working demo: https://stackblitz.com/edit/angular-c2hcrz

How does this work?

I'm using the first 3 parameters of the reduce callback function here

(arr, current, idx)

And invoking reduce with an empty array - the second argument.

Think of reduce like map - it loops through the source array, and lets you put each value where you want.

In the callback:

arr is the new array that gets built up and ultimately returned.

current is the current value in the loop from the source array

idx is the current index in the loop from the source array

Firstly I work out where in the new array we should add the current index by doing Math.floor(idx / 3). This allows us to increment the target index by 1 every third increment of the source array. The rest is fairly simple javascript.

With objects

It is trivial to use this with objects. The content doesn't matter here, it's the index in the original array that is driving the grouping:

    const source = [
      { name: 'One', id: 1 },
      { name: 'Two', id: 2 },
      { name: 'Three', id: 3 },
      { name: 'Four', id: 4 },
      { name: 'Five', id: 5 },
      { name: 'Six', id: 6 }
    ];

    this.objModel = source.reduce((arr, current, idx) => {
      const index = Math.floor(idx / 3);
      if (arr.length === index) {
        arr.push([]);
      }

      arr[index].push(current);
      return arr;
    }, []);


答:
If you are running on tf version >= 2.0, try using

```<code>model.compile(loss=custom_loss, optimizer='adam', run_eagerly=True)
</code>```

if you are using Keras api.

Title: Custom Loss Function in TF2.0

Body:
For a image segmentation problem, I need to write a custom loss function. I am getting below said error.

Code Base: https://www.tensorflow.org/tutorials/images/segmentation

Last layer:
Conv2DTrans (128,128,2) [Note that in my case it is only 2 values]

       def call(self, y_true, y_pred):
              ytrue = ytrue.numpy()
              .....

Error:

AttributeError: 'Tensor' object has no attribute 'numpy'

I tried py_function and numpy_function but both return the same error
and also

      with tf.compat.v1.Session() as sess:
        for i,j in enumerate(sess.run(y_true),sess.run(y_pred)):

Current Model Layers:

Layer (type)                    Output Shape         Param #     Connected to
==================================================================================================
input_82 (InputLayer)           [(None, 128, 128, 3) 0
__________________________________________________________________________________________________
model_80 (Model)                [(None, 64, 64, 96), 1841984     input_82[0][0]
__________________________________________________________________________________________________
sequential_160 (Sequential)     (None, 8, 8, 512)    1476608     model_80[1][4]
__________________________________________________________________________________________________
concatenate_160 (Concatenate)   (None, 8, 8, 1088)   0           sequential_160[0][0]
                                                                 model_80[1][3]
__________________________________________________________________________________________________
sequential_161 (Sequential)     (None, 16, 16, 256)  2507776     concatenate_160[0][0]
__________________________________________________________________________________________________
concatenate_161 (Concatenate)   (None, 16, 16, 448)  0           sequential_161[0][0]
                                                                 model_80[1][2]
__________________________________________________________________________________________________
sequential_162 (Sequential)     (None, 32, 32, 128)  516608      concatenate_161[0][0]
__________________________________________________________________________________________________
concatenate_162 (Concatenate)   (None, 32, 32, 272)  0           sequential_162[0][0]
                                                                 model_80[1][1]
__________________________________________________________________________________________________
sequential_163 (Sequential)     (None, 64, 64, 64)   156928      concatenate_162[0][0]
__________________________________________________________________________________________________
concatenate_163 (Concatenate)   (None, 64, 64, 160)  0           sequential_163[0][0]
                                                                 model_80[1][0]
__________________________________________________________________________________________________
conv2d_transpose_204 (Conv2DTra (None, 128, 128, 2)  2882        concatenate_163[0][0]
==================================================================================================

I need a numpy array to focus only more on 1's and not on zeroes. Now the metric and accuracy are overwhelmed by the presence of lot of zeros.

def tumor_loss(y_true,y_pred):
  y_true = y_true.reshape((SHAPE,SHAPE))
  y_pred = y_pred.reshape((SHAPE,SHAPE))

  y_true_ind = np.where(y_true ==1)[1]
  y_pred_ind = np.where(y_pred==1)[1]

  if np.array_equal(y_true_ind,y_pred_ind):
    return 0

  if y_true_ind.shape[0] > y_pred_ind.shape[0]:
    return y_true_ind.shape[0] - np.setdiff1d(y_true_ind,y_pred_ind).shape[0]
  else:
    return y_true_ind.shape[0] - np.setdiff1d(y_pred_ind,y_true_ind).shape[0]

Body:
If you are running on tf version >= 2.0, try using

model.compile(loss=custom_loss, optimizer='adam', run_eagerly=True)

if you are using Keras api.


问:
Is there any way of generating exact HTML page from a PDF file?
I am trying different python libraries like pdftotree, pdfminer, tabula etc. But could not get the exact results. I mean I can get text from PDF, Images and Tabular data in HTML, but not as maintained and organized as original PDF file. Can someone help me with something regarding this? I would be thankful.

答:
Mostly yes.  Translate the PDF to SVG, and embed the SVG in your web page.

SVG's image model (what it can represent and how) is a near-superset of the PDF image model (which is itself a superset of PostScript), though SVG lacks some of the print-specific features of PDF.  There are probably quite a few PDF->SVG converters out there already.  Googling "Pdf to SVG" turned up quite a few promising hits

There will be some complications:

Many PDF files are longer than 1 page.  You might need to generate 10 SVG files for a single 10 page PDF file, and then build a web page around those 10 SVGs.  Throw in some dynamic HTML to "turn pages" and you've got a good web-based PDF viewer.

There are parts of PDF that aren't within its image model at all... bookmarks, annotations (form fields, digital signatures), document metadata (author, creation date, etc), and so forth.  Some of the non-image-model stuff is common enough that a PDF to SVG utility might handle it directly (links), while other stuff doesn't have an HTML equivalent and would be lost.

You could preserve the appearance of a digital signature, but the actual security represented by those visuals would be gone.  Preserving that signature's appearance could be considered lying about the security.


问:
Unspecified Margin Problem?
On this page, the title says it has a margin top & bottom of 25px (when I use inspect element in Chrome 10) - but the CSS looks like this:

```<code>.post h2 {
margin:0;
text-align: left;
font-size: 18px;
overflow:hidden;
font-weight:normal;
}
</code>```

I'm trying to decrease the top and bottom margins around the title.

Here's a screenshot of the problem:

答:
The
 is displaying a default margin (which varies depending on the browser); if you want to edit the margin, use .title h2 or the generic h2 (line 405 of style.css according to FireBug - this will alter all
s on the site though).

Title: Unspecified Margin Problem?

Body:
On this page, the title says it has a margin top & bottom of 25px (when I use inspect element in Chrome 10) - but the CSS looks like this:

.post h2 {
margin:0;
text-align: left;
font-size: 18px;
overflow:hidden;
font-weight:normal;
}

I'm trying to decrease the top and bottom margins around the title.

Here's a screenshot of the problem:

Body: The <h2> is displaying a default margin (which varies depending on the browser); if you want to edit the margin, use .title h2 or the generic h2 (line 405 of style.css according to FireBug - this will alter all <h2>s on the site though).