问:
Windows Forms and Exceptionless Report
I have started using exceptionless for a windows forms application.  Whenever it notices that the program is crashed it throws up this window:

I really do not want it to do this, as I want it to submit the errors to me, with out a user being able to stop it.  Is there anyway to do this?

答:
I find it :)

ExceptionlessClient.Default.Register(showDialog: false);
```

showDialog: Controls whether a dialog is shown when an unhandled exception occurs.

Title: Windows Forms and Exceptionless Report

Body:
I find it :)

ExceptionlessClient.Default.Register(showDialog: false);

showDialog: Controls whether a dialog is shown when an unhandled exception occurs.


来源: stackexchange

问:
Why are my radio buttons in Tkinter not returning values?
I am building a gui in Tkinter and found that my radiobuttons aren't working properly, specifically, they can be updated and selected normally by the user, but they return what appears to be an empty string ("") instead of the coded value.  I've written a short script with the same problem to help figure this out. When I run the following script on my machine, I can obtain the entry1 value just fine but btn1.get() returns the empty string.

I am running the Anaconda distribution of Python 3.7.6 64-bit on Windows 10 using Spyder 4.0.1 IDE.

And the code:

```<code>from tkinter import *

root = Tk()
btn1 = StringVar()

def do_something():
    val0 = entry1.get()
    val1 = btn1.get()
    print("The variable values are " + val1 + " and " + val0)
    print("The method values are " + btn1.get() + " and " + entry1.get())

rb1=Radiobutton(root,text="Euro",value = "euro",variable = btn1).grid(row=2, column=1, sticky=W)
rb2=Radiobutton(root,text="Dollar",value = "dollar",variable = btn1).grid(row=3, column=1, sticky=W)
rb3=Radiobutton(root,text="Yen",value = "yen",variable = btn1).grid(row=4, column=1, sticky=W)
label1 = Label(root, text="Input Here")
label1.grid(row=1, sticky=E)
entry1 = Entry(root)
entry1.grid(row=1, column=1, sticky=W)

go = Button(root, text="Print Selection", fg="white", bg="black", command=do_something)
go.grid(row=10, columnspan=3)

root.mainloop()```
```

<p>So if I enter 'this works' in the entry box and select the 'Euro' radiobutton and press the 'Print Selection' command button, here is my output:</p>

```The variable values are  and this works
The method values are  and this works
```

Just now I changed btn1 to an IntVar() and ran a similar test printing str(val1) and str(btn1.get() and it has the same problem, the value is always 0.

Any ideas?

答:
I have solved this problem. The problem is caused by activating the tkinter backend in Spyder as the default renderer. I was able to get the script to behave as required by going to Tools>Preferences>Ipython Console>Graphics>Graphics Backend and switching the default backend from 'Tkinter' to 'Automatic'.

Why this worked, I have no idea, but I wanted to close the question out with an answer.

ContentLicense: CC BY-SA 4.0

Body:
I am building a gui in Tkinter and found that my radiobuttons aren't working properly, specifically, they can be updated and selected normally by the user, but they return what appears to be an empty string ("") instead of the coded value.  I've written a short script with the same problem to help figure this out. When I run the following script on my machine, I can obtain the entry1 value just fine but btn1.get() returns the empty string.

I am running the Anaconda distribution of Python 3.7.6 64-bit on Windows 10 using Spyder 4.0.1 IDE.

And the code:

from tkinter import *

root = Tk()
btn1 = StringVar()

def do_something():
    val0 = entry1.get()
    val1 = btn1.get()
    print("The variable values are " + val1 + " and " + val0)
    print("The method values are " + btn1.get() + " and " + entry1.get())

rb1=Radiobutton(root,text="Euro",value = "euro",variable = btn1).grid(row=2, column=1, sticky=W)
rb2=Radiobutton(root,text="Dollar",value = "dollar",variable = btn1).grid(row=3, column=1, sticky=W)
rb3=Radiobutton(root,text="Yen",value = "yen",variable = btn1).grid(row=4, column=1, sticky=W)
label1 = Label(root, text="Input Here")
label1.grid(row=1, sticky=E)
entry1 = Entry(root)
entry1.grid(row=1, column=1, sticky=W)

go = Button(root, text="Print Selection", fg="white", bg="black", command=do_something)
go.grid(row=10, columnspan=3)

root.mainloop()```

So if I enter 'this works' in the entry box and select the 'Euro' radiobutton and press the 'Print Selection' command button, here is my output:

The variable values are  and this works
The method values are  and this works

Just now I changed btn1 to an IntVar() and ran a similar test printing str(val1) and str(btn1.get() and it has the same problem, the value is always 0.

Any ideas?


问:
Dotfuscator says "was expecting one of:" when building in Visual Studio
I've got a solution in Visual Studio that includes a Dotfuscator project. The exact same code base builds and obfuscates correctly on another machine (my old laptop), but not on my newly setup laptop. Of course we let our support contract expire since this is used on a legacy project.

The output during the build is:

```<code>8>Compiling Project  MyAppObfuscation ...
8>Dotfuscator Professional Version 4.41.1.9417-95d9eec7a
8>Copyright 2002-2019 PreEmptive Solutions, LLC All Rights Reserved.
8>Use of this software implies acceptance of accompanying license agreement.
8>Build machine license. This software may be used on binaries for general release.
8>
8>Your protection is out of date. Learn more at https://www.preemptive.com/keep-your-protection-up-to-date?product=dotfuscator&sku=pro&version=4.41.1.9417. Upgrade at https://www.preemptive.com/products/dotfuscator/downloads.
8>
8>Loading Assemblies...
---several of these lines---
8>Running ...\ildasm.exe /OUT=...\MyApp.exe.il /TEXT /NOBAR /RAWEH /QUOTEALLNAMES /UTF8 /LINENUM /FORWARD "...\MyApp.exe"
8>
--- immediately followed by: ---
8>Encountered - at line 18065, column 26.
8>Was expecting one of:
8>    <FLOAT64> ...
8>    "float64" ...
8>    "float32" ...
8>    <INT> ...
8>    "(" ...
8>
8>Build Error.
8>MyAppObfuscation build failed.
</code>```

Has anyone encountered this? I'm inclined to believe it's something on the new machine, but if anyone has tips about diagnosing this I would appreciate it.

Thanks!

Edit: Just wanted to add the same error happens in Visual Studio and the Dotfuscator Professional Config Editor.

Edit 2: Upon further inspection, the folder listed in the /OUT parameter of ildasm doesn't contain a .il file for the last ildasm command. The output folder for the assemblies prior to the .exe DO have a .il file. So, I thought ildasm might be failing on the .exe, but I can copy the command into a command prompt and it runs correctly and creates an .il file as expected. So, why would ildasm not work when run from Visual Studio, but would work from the command line -- and only for one assembly / exe in the project?

The mystery grows...

答:
Solved it! I opened Visual Studio Installer on both the old and new machine to compare what features were installed on the old one vs the new one. Most notably, one of the missing features on the Individual components tab was an older .NET Framework SDK (4.6.1 in my case) and an older Windows 10 SDK (10.0.17763.0 in my case).

I hope someone else finds this helpful.

Body:
I've got a solution in Visual Studio that includes a Dotfuscator project. The exact same code base builds and obfuscates correctly on another machine (my old laptop), but not on my newly setup laptop. Of course we let our support contract expire since this is used on a legacy project.

The output during the build is:

8>Compiling Project  MyAppObfuscation ...
8>Dotfuscator Professional Version 4.41.1.9417-95d9eec7a
8>Copyright 2002-2019 PreEmptive Solutions, LLC All Rights Reserved.
8>Use of this software implies acceptance of accompanying license agreement.
8>Build machine license. This software may be used on binaries for general release.
8>
8>Your protection is out of date. Learn more at https://www.preemptive.com/keep-your-protection-up-to-date?product=dotfuscator&sku=pro&version=4.41.1.9417. Upgrade at https://www.preemptive.com/products/dotfuscator/downloads.
8>
8>Loading Assemblies...
---several of these lines---
8>Running ...\ildasm.exe /OUT=...\MyApp.exe.il /TEXT /NOBAR /RAWEH /QUOTEALLNAMES /UTF8 /LINENUM /FORWARD "...\MyApp.exe"
8>
--- immediately followed by: ---
8>Encountered - at line 18065, column 26.
8>Was expecting one of:
8>    <FLOAT64> ...
8>    "float64" ...
8>    "float32" ...
8>    <INT> ...
8>    "(" ...
8>
8>Build Error.
8>MyAppObfuscation build failed.

Has anyone encountered this? I'm inclined to believe it's something on the new machine, but if anyone has tips about diagnosing this I would appreciate it.

Thanks!

Edit: Just wanted to add the same error happens in Visual Studio and the Dotfuscator Professional Config Editor.

Edit 2: Upon further inspection, the folder listed in the /OUT parameter of ildasm doesn't contain a .il file for the last ildasm command. The output folder for the assemblies prior to the .exe DO have a .il file. So, I thought ildasm might be failing on the .exe, but I can copy the command into a command prompt and it runs correctly and creates an .il file as expected. So, why would ildasm not work when run from Visual Studio, but would work from the command line -- and only for one assembly / exe in the project?

The mystery grows...


问:
Xamarin Forms Global variable updates slower than code
I have a problem. I am using the following code in my App.xaml.cs:

```<code>public static int agentId;
public static List<Agent> agents;

public App()
{
    InitializeComponent();

    loadingAgents += onLoadingAgents;
    LoadAgentList();

    MainPage = new MainPage();
}

private event EventHandler loadingAgents = delegate { };
private async void onLoadingAgents(object sender, EventArgs args)
{
    Agents = await RestService.GetAgents();
}
private void LoadAgentList()
{
    loadingAgents(this, EventArgs.Empty);
}

public static int AgentId
{
    get
    {
        return agentId;
    }
    set
    {
        agentId = value;
    }
}

public static List<Agent> Agents
{
    get
    {
        if (agents == null)
        {
            agents = new List<Agent>();
        }
        return agents;
    }
    set
    {
        agents = value;
        AgentId = Agents.Min(x => x.Id);
    }
}
</code>```

Now what this simply should do is the following:

On startup, it collects all the Agents from a webcall and puts it in a List<Agent> Agents

Once the List<Agent> Agents is set, it sets the AgentId to the minimum Id of the Agents list

The problem is that in the ViewModel of the MainPage I use those variables that are supposed to be set, but the code of the ViewModel is faster than the code that needs to update the variables.

How can I wait for the variables to finish before hitting this line: MainPage = new MainPage();?

答:
First i don't think it is necessary to use private event EventHandler loadingAgents.Then you get Agents is an asynchronous operation,so MainPage = new MainPage(); has been executed when the method is called(at this time, the Agents may be null).And in general we don't call asynchronous tasks in the constructor to get the data,you could do it in the OnStart() method.

You could try to change like below :

```<code>public App()
{
  InitializeComponent();
}

protected async override void OnStart()
{
   Agents = await RestService.GetAgents();
   MainPage = new MainPage();
}
</code>```

Body:
I have a problem. I am using the following code in my App.xaml.cs:

public static int agentId;
public static List<Agent> agents;

public App()
{
    InitializeComponent();

    loadingAgents += onLoadingAgents;
    LoadAgentList();

    MainPage = new MainPage();
}

private event EventHandler loadingAgents = delegate { };
private async void onLoadingAgents(object sender, EventArgs args)
{
    Agents = await RestService.GetAgents();
}
private void LoadAgentList()
{
    loadingAgents(this, EventArgs.Empty);
}

public static int AgentId
{
    get
    {
        return agentId;
    }
    set
    {
        agentId = value;
    }
}

public static List<Agent> Agents
{
    get
    {
        if (agents == null)
        {
            agents = new List<Agent>();
        }
        return agents;
    }
    set
    {
        agents = value;
        AgentId = Agents.Min(x => x.Id);
    }
}

Now what this simply should do is the following:

On startup, it collects all the Agents from a webcall and puts it in a List<Agent> Agents

Once the List<Agent> Agents is set, it sets the AgentId to the minimum Id of the Agents list

The problem is that in the ViewModel of the MainPage I use those variables that are supposed to be set, but the code of the ViewModel is faster than the code that needs to update the variables.

How can I wait for the variables to finish before hitting this line: MainPage = new MainPage();?

Body:
First i don't think it is necessary to use private event EventHandler loadingAgents.Then you get Agents is an asynchronous operation,so MainPage = new MainPage(); has been executed when the method is called(at this time, the Agents may be null).And in general we don't call asynchronous tasks in the constructor to get the data,you could do it in the OnStart() method.

You could try to change like below :

public App()
{
  InitializeComponent();
}

protected async override void OnStart()
{
   Agents = await RestService.GetAgents();
   MainPage = new MainPage();
}


问:
Run java code passing file as input argument on Jetbrain's Intelij IDEA
I'm trying to run a Java code using on Intelij IDEA passing a .txt file as argument.

I followed this up this discussion but it didn't help much Run Program from IntelliJ with Command Line File Input

Also, I trid the EXACT same thing (I guess..) in another computer and it worked, but in my personal computer I have a newer version of Intelij and some little things are different. I don't know if something has changed or if I'm doing something wrong...

Here is my code:

```<code> public static void main(String[] args) {
        // read the n points from a file
        StdOut.println("Args: " + Arrays.toString(args));
        StdOut.println("Args: " + args[0]);
    }
</code>```

My configurations:

run configuration

And the output:

```<code>Args: []
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 0 out of bounds for length 0
    at BruteCollinearPoints.main(BruteCollinearPoints.java:89)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at com.intellij.rt.execution.application.AppMainV2.main(AppMainV2.java:128)

Process finished with exit code 1
</code>```

If I run this code at the console everything goes fine.

答:
You should provide the path to file in the Program arguments section instead of "Redirect input from" as explained in this answer https://stackoverflow.com/a/32951928/3012352

"Redirect input from" option will allow you to redirect input stream (stdin) to your program from provided file. https://www.jetbrains.com/help/idea/run-debug-configuration-application.html

Body:
I'm trying to run a Java code using on Intelij IDEA passing a .txt file as argument.

I followed this up this discussion but it didn't help much Run Program from IntelliJ with Command Line File Input

Also, I trid the EXACT same thing (I guess..) in another computer and it worked, but in my personal computer I have a newer version of Intelij and some little things are different. I don't know if something has changed or if I'm doing something wrong...

Here is my code:

 public static void main(String[] args) {
        // read the n points from a file
        StdOut.println("Args: " + Arrays.toString(args));
        StdOut.println("Args: " + args[0]);
    }

My configurations:

run configuration

And the output:

Args: []
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 0 out of bounds for length 0
    at BruteCollinearPoints.main(BruteCollinearPoints.java:89)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at com.intellij.rt.execution.application.AppMainV2.main(AppMainV2.java:128)

Process finished with exit code 1

If I run this code at the console everything goes fine.


问:
Python Pandas: TypeError: first argument must be string or compiled pattern in user defined function
I have defined a function which looks like below:

```<code>def incident_rate(substation,year,events):

    age = conductor_yearly_df.loc[conductor_yearly_df['SUBSTATION']==substation,conductor_yearly_df.columns.str.contains(year)].reset_index(drop=True).values[0][0]
    length = conductor_yearly_df.loc[conductor_yearly_df['SUBSTATION']==substation,conductor_yearly_df.columns.str.contains(year)].reset_index(drop=True).values[0][1]
    temp = events / (age * length)
    return temp
</code>```

When I call the function in the code (for example: incident_rate('WB',2019,6), it throws following error:

```<code>TypeError: first argument must be string or compiled pattern
</code>```

I am not sure where am I making the mistake. Could anyone please guide me how to fix the error?

答:
Change year to string with str(year), since str.contains accept type of string

```<code>age = conductor_yearly_df.loc[conductor_yearly_df['SUBSTATION']==substation,conductor_yearly_df.columns.str.contains(str(year))].reset_index(drop=True).values[0][0]
</code>```

Body:
I have defined a function which looks like below:

def incident_rate(substation,year,events):

    age = conductor_yearly_df.loc[conductor_yearly_df['SUBSTATION']==substation,conductor_yearly_df.columns.str.contains(year)].reset_index(drop=True).values[0][0]
    length = conductor_yearly_df.loc[conductor_yearly_df['SUBSTATION']==substation,conductor_yearly_df.columns.str.contains(year)].reset_index(drop=True).values[0][1]
    temp = events / (age * length)
    return temp

When I call the function in the code (for example: incident_rate('WB',2019,6), it throws following error:

TypeError: first argument must be string or compiled pattern

I am not sure where am I making the mistake. Could anyone please guide me how to fix the error?

Body:
Change year to string with str(year), since str.contains accept type of string

age = conductor_yearly_df.loc[conductor_yearly_df['SUBSTATION']==substation,conductor_yearly_df.columns.str.contains(str(year))].reset_index(drop=True).values[0][0]


问:
How do I change the background color in JavaScript?
I am trying to change the background color of the wrapper every time I click the button. When it is clicked, it is supposed to change to a random color that is in the array. Any thoughts for a beginner? Also the CSS was done with SASS so it may not look pretty.

function change_Color() {
  var color = ["blue", "red", "green", "yellow"];
  document.getElementById("wrapper").style.backgroundColor = color;
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  margin: 0;
}

* {
  box-sizing: border-box;
}

#wrapper {
  width: 100%;
  height: 100vh;
  background-color: skyblue;
  display: flex;
  justify-content: center;
  align-items: center;
  button {
    padding: 10px;
    background: orange;
    color: white;
    border: none;
    border-radius: 10px;
    font-size: 2rem;
    transition: .5s ease;
    &:hover {
      box-shadow: 0 4px 3px 0px rgba(255, 255, 255, 0.8);
      cursor: pointer;
    }
    &:focus {
      outline: 0;
      color: skyblue;
    }
  }
}</code>```

  <button onclick="change_Color()">Click me!</button>

```

答: You can use math.random() to choose random color from your array.</p>

Body:
I am trying to change the background color of the wrapper every time I click the button. When it is clicked, it is supposed to change to a random color that is in the array. Any thoughts for a beginner? Also the CSS was done with SASS so it may not look pretty.

function change_Color() {
  var color = ["blue", "red", "green", "yellow"];
  document.getElementById("wrapper").style.backgroundColor = color;
}

body {
  margin: 0;
}

* {
  box-sizing: border-box;
}

#wrapper {
  width: 100%;
  height: 100vh;
  background-color: skyblue;
  display: flex;
  justify-content: center;
  align-items: center;
  button {
    padding: 10px;
    background: orange;
    color: white;
    border: none;
    border-radius: 10px;
    font-size: 2rem;
    transition: .5s ease;
    &:hover {
      box-shadow: 0 4px 3px 0px rgba(255, 255, 255, 0.8);
      cursor: pointer;
    }
    &:focus {
      outline: 0;
      color: skyblue;
    }
  }
}

  <button onclick="change_Color()">Click me!</button>


问:
Is retainCount giving me the correct information for my NSDate?
I have NSDate property

In .h

```<code>...
@interface MyAppDelegate : NSObject <UIApplicationDelegate> {
...
      NSDate *pageStartDate;
...
}
...
@property (nonatomic, retain) NSDate *pageStartDate;
...
</code>```

In .m

```<code>...
-(void)myMethod
{
   ...
   // set date of start showing page
   NSDate *tempStartDate = [NSDate date];
   [tempStartDate retain];
   pageStartDate = tempStartDate;
   [tempStartDate release];
   ...
}
...
</code>```

After running this code the [tempStartDate retainCount] = 1 - is it normal?
If I write self.pageStartDate = tempStartDate than [pageStartDate retainCount] = 2.

Is there right use of NSDate, or not is?

答:
If you don't write self.pageStartDate it won't use the property, so yes, the retain count of 1 is expected. Also, note that this instance is autoreleased (because you created it with [NSDate date]), so it will be released later.

If you were using the property, you wouldn't need the retain and release statements.

ContentLicense: CC BY-SA 3.0

Body:
I have NSDate property

In .h

...
@interface MyAppDelegate : NSObject <UIApplicationDelegate> {
...
      NSDate *pageStartDate;
...
}
...
@property (nonatomic, retain) NSDate *pageStartDate;
...

In .m

...
-(void)myMethod
{
   ...
   // set date of start showing page
   NSDate *tempStartDate = [NSDate date];
   [tempStartDate retain];
   pageStartDate = tempStartDate;
   [tempStartDate release];
   ...
}
...

After running this code the [tempStartDate retainCount] = 1 - is it normal?
If I write self.pageStartDate = tempStartDate than [pageStartDate retainCount] = 2.

Is there right use of NSDate, or not is?


答:
Check this one. I merged body and wrapper in CSS and I gave id for body

var colors = ["red", "blue", "green", "yellow"];
    function changeColor() {
        document.getElementById("body").style.backgroundColor = colors[Math.floor(Math.random() * colors.length)];}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#body {
margin: 0;
box-sizing: border-box;
  width: 100%;
  height: 100vh;
  background-color: skyblue;
  display: flex;
  justify-content: center;
  align-items: center;
}
 button {
    padding: 10px;
    background: orange;
    color: white;
    border: none;
    border-radius: 10px;
    font-size: 2rem;
    transition: .5s ease;
    &:hover {
      box-shadow: 0 4px 3px 0px rgba(255, 255, 255, 0.8);
      cursor: pointer;
    }
    &:focus {
      outline: 0;
      color: skyblue;
    }
  }</code>```

    <button onclick="changeColor();">Click me!</button>
    ```

Title: How do I change the background color in JavaScript?

Body:
Check this one. I merged body and wrapper in CSS and I gave id for body

var colors = ["red", "blue", "green", "yellow"];
    function changeColor() {
        document.getElementById("body").style.backgroundColor = colors[Math.floor(Math.random() * colors.length)];}

#body {
margin: 0;
box-sizing: border-box;
  width: 100%;
  height: 100vh;
  background-color: skyblue;
  display: flex;
  justify-content: center;
  align-items: center;
}
 button {
    padding: 10px;
    background: orange;
    color: white;
    border: none;
    border-radius: 10px;
    font-size: 2rem;
    transition: .5s ease;
    &:hover {
      box-shadow: 0 4px 3px 0px rgba(255, 255, 255, 0.8);
      cursor: pointer;
    }
    &:focus {
      outline: 0;
      color: skyblue;
    }
  }

<body id='body'>
    <button onclick="changeColor();">Click me!</button>
    </body>


问:
Bad input error in Python 2.7 in multiple inputs
I am taking an intro course in Python and the assignment is to figure the area I have the inputs working, but I'm getting an error on the first elif (triangle).  It has something to do with the data type, but I'm new to Python and would appreciate a hand...

```<code>def get_shape(input):
  #print("You entered %s inside the function.") % (input)
  return input.upper()
allowed_shapes = ["C", "T", "R"]
print
print("Let's calculate the area of a shape!")
print
print("Enter \"C\" for a circle, \"T\" for a triangle, or \"R\" for a rectangle...")
print
shape = get_shape(input = raw_input("Enter a shape:"))

while shape not in allowed_shapes:
  print("You must enter either a (C)ircle, (T)riangle or (R)ectangle.")
  print
  shape = get_shape(input = raw_input("Enter a shape:"))

if shape == "C":
  print("You chose C.")
  radius = float(raw_input("Enter the radius of the circle...:"))
  print
  print "The area of your circle is %f square units." % ((radius**2) * 3.14159)
elif shape == "T":
  print("You chose T.")
  t_base = float(raw_input("Enter the base of the triangle...:"))
  t_height = float(raw_input("Enter the height of the triangle...:"))
  print
  print "The area of your triangle is %f square units." % ((t_base * t_height) / 2))
else:
  print("You chose R.")
  legnth = float(raw_input("Enter the legnth of the rectangle...:"))
  width = float(raw_input("Enter the width of the rectangle...:"))
  print
  print "The area of your rectangle is %f square units." % (legnth * width)
</code>```

答:
You have got an extra round bracket here

```<code>print "The area of your triangle is %f square units." % ((t_base * t_height) / 2))
</code>```

It should look like this

```<code>print "The area of your triangle is %f square units." % ((t_base * t_height) / 2)
</code>```

Body:
I am taking an intro course in Python and the assignment is to figure the area I have the inputs working, but I'm getting an error on the first elif (triangle).  It has something to do with the data type, but I'm new to Python and would appreciate a hand...

def get_shape(input):
  #print("You entered %s inside the function.") % (input)
  return input.upper()
allowed_shapes = ["C", "T", "R"]
print
print("Let's calculate the area of a shape!")
print
print("Enter \"C\" for a circle, \"T\" for a triangle, or \"R\" for a rectangle...")
print
shape = get_shape(input = raw_input("Enter a shape:"))

while shape not in allowed_shapes:
  print("You must enter either a (C)ircle, (T)riangle or (R)ectangle.")
  print
  shape = get_shape(input = raw_input("Enter a shape:"))

if shape == "C":
  print("You chose C.")
  radius = float(raw_input("Enter the radius of the circle...:"))
  print
  print "The area of your circle is %f square units." % ((radius**2) * 3.14159)
elif shape == "T":
  print("You chose T.")
  t_base = float(raw_input("Enter the base of the triangle...:"))
  t_height = float(raw_input("Enter the height of the triangle...:"))
  print
  print "The area of your triangle is %f square units." % ((t_base * t_height) / 2))
else:
  print("You chose R.")
  legnth = float(raw_input("Enter the legnth of the rectangle...:"))
  width = float(raw_input("Enter the width of the rectangle...:"))
  print
  print "The area of your rectangle is %f square units." % (legnth * width)

Body:
You have got an extra round bracket here

print "The area of your triangle is %f square units." % ((t_base * t_height) / 2))

It should look like this

print "The area of your triangle is %f square units." % ((t_base * t_height) / 2)


问:
Question about Java synchronized
The Java documentation says that "it is not possible for two invocations of synchronized methods on the same object to interleave".  What I need to know is whether synchronized will also prevent a synchronized method in two different instances of the same class from interleaving.

E.g. class Worker has method called process().  We have several instances of Worker running in their own threads.  We want to prevent more than one instance running the process() method simultaneously.  Will synchronized do this?

Thanks.

答:
Only one thread can hold a lock on an object at any one time.

A synchronized method attempt to hold a lock on the instance. Another thread can also hold a lock on another instance of the same class.  Another thread cannot enter another synchronized method of the same instance. i.e. it is not the method which is locked.

However a thread can enter a non-synchronized method while another thread holds a lock on that object. Only synchronized methods are protected.

A static synchronized method obtains a lock on the Class rather than the object. However, the follows the same rules as non-static method except with a different object.

Note: There is no "instance" for static method even though you can write code which appears to use an instance. e.g. instance.staticMethod()

Title: Question about Java synchronized


问:
How to create a dummy account for App Store Connect review
I have apple signin on my app that im trying to submit but in order to get approved I need to provide a dummy account that they can use to review the app.  However when I create an apple id it has 2-factor authentication enabled so they wouldnt be able to use it for login.</p>

答:
Sign in to App Store Connect.
On the homepage, click Users and Access.
Under Sandbox, click Testers.
Click “+” to set up your tester accounts.
Complete the tester information form and click Invite.
Sign out of your Apple ID on all testing devices and sign back in with your new sandbox tester account.</p>


问:
How numpy printoptions will work with images?
I was trying to print an image to analyze, if there are some changes in the pixel intensities if the images are forged. Anyways my doubt is related  with the numpy.printoptions.
I was trying below code and numpy.printoptions was not working:
Image of code snippet
Code:

```<code>import numpy
import numpy as np
DIR = "D:/Work/ML/API/MNB/28 - Forgery/data/phase-01-training.tar/dataset-dist/chunks/1500_64_16"
TRAIN_CHUNKS = os.path.join(DIR, "train")
TRAIN_FAKE_CHUNKS = os.path.join(TRAIN_CHUNKS, "fake")
TRAIN_PRISTINE_CHUNKS = os.path.join(TRAIN_CHUNKS, "pristine")

IND=2000
train_chunk_files = os.listdir(TRAIN_FAKE_CHUNKS)
src = cv2.imread(os.path.join(TRAIN_FAKE_CHUNKS, train_chunk_files[IND]))
print(src[:, :, 1].shape)
with numpy.printoptions(threshold=64):
    ok = np.copy(src[:, :, 1])
    print(ok)
# print(src[:, :, 1])
plt.imshow(src)

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

But on the other end numpy printoptions is working fine for mnist dataset!!!
Working code snippet
code:

```<code>import tensorflow as tf
print(tf.__version__)

mnist = tf.keras.datasets.fashion_mnist

(training_images, training_labels), (test_images, test_labels) = mnist.load_data()

import numpy as np
np.set_printoptions(linewidth=200)
import matplotlib.pyplot as plt
print(type(training_images[0]))
plt.imshow(training_images[0])
print(training_labels[0])
print(training_images[0])
</code>```

What is the mistake I am doing over here? How to print the RGB image for each channel? I have checked the datatype for both of the image, it is numpy, ndarray.

Edit 1:
Things are not working by using linewidth.
Code with linewidth in np.printoptions

答:
From the diagram you have given in "Image of code snippet" link, it seems printoptions print the values in both cases, incase if the values needs to be printed properly (displaying all values), u could use,

```

    with np.printoptions(linewidth=200):
        ok = np.copy(src[:, :, 1])
        print(ok)

```

if this is not what you are looking for, please let me know in the comments section. Happy to correct the answer!

Body:
I was trying to print an image to analyze, if there are some changes in the pixel intensities if the images are forged. Anyways my doubt is related  with the numpy.printoptions.
I was trying below code and numpy.printoptions was not working:
Image of code snippet
Code:

import numpy
import numpy as np
DIR = "D:/Work/ML/API/MNB/28 - Forgery/data/phase-01-training.tar/dataset-dist/chunks/1500_64_16"
TRAIN_CHUNKS = os.path.join(DIR, "train")
TRAIN_FAKE_CHUNKS = os.path.join(TRAIN_CHUNKS, "fake")
TRAIN_PRISTINE_CHUNKS = os.path.join(TRAIN_CHUNKS, "pristine")

IND=2000
train_chunk_files = os.listdir(TRAIN_FAKE_CHUNKS)
src = cv2.imread(os.path.join(TRAIN_FAKE_CHUNKS, train_chunk_files[IND]))
print(src[:, :, 1].shape)
with numpy.printoptions(threshold=64):
    ok = np.copy(src[:, :, 1])
    print(ok)
# print(src[:, :, 1])
plt.imshow(src)

plt.show()

But on the other end numpy printoptions is working fine for mnist dataset!!!
Working code snippet
code:

import tensorflow as tf
print(tf.__version__)

mnist = tf.keras.datasets.fashion_mnist

(training_images, training_labels), (test_images, test_labels) = mnist.load_data()

import numpy as np
np.set_printoptions(linewidth=200)
import matplotlib.pyplot as plt
print(type(training_images[0]))
plt.imshow(training_images[0])
print(training_labels[0])
print(training_images[0])

What is the mistake I am doing over here? How to print the RGB image for each channel? I have checked the datatype for both of the image, it is numpy, ndarray.

Edit 1:
Things are not working by using linewidth.
Code with linewidth in np.printoptions

Body:
From the diagram you have given in "Image of code snippet" link, it seems printoptions print the values in both cases, incase if the values needs to be printed properly (displaying all values), u could use,

    with np.printoptions(linewidth=200):
        ok = np.copy(src[:, :, 1])
        print(ok)

if this is not what you are looking for, please let me know in the comments section. Happy to correct the answer!


问:
CS50 Pset 7 13.sql, I can't solve it, nested sqlite3 database
DataBase movies.db

tables

directors (movie_id, person_id)

movies (id, title, year)

people (id, name, birth)

ratings (movie_id, rating, votes)

stars (movie_id, person_id)

you can download the database.

Question

I'm new in programming, so I decided, to begin with, CS50 Harvard course here is the problem and the test solution:

In 13.sql, write a SQL query to list the names of all people who starred in a movie in which Kevin Bacon also starred.
Your query should output a table with a single column for the name of each person.
There may be multiple people named Kevin Bacon in the database. Be sure to only select the Kevin Bacon born in 1958.
Kevin Bacon himself should not be included in the resulting list.

solution hint

Executing 13.sql results in a table with 1 column and 176 rows.

executing code in PowerShell or bash
cat 13.sql | sqlite3 movies.db

My Code:

```<code>SELECT COUNT(name)
FROM people
JOIN stars ON stars.person_id = people.id
JOIN movies ON movies.id = stars.movie_id
WHERE people.id IN(
SELECT stars.person_id
FROM stars
GROUP BY stars.person_id
HAVING name = "Kevin Bacon");
</code>```

problem:

when I execute code it stop working, I can't choose stars with Kevin

答:
I solved this problem by using DISTINCT and NOT EQUAL operator in SQL.

Here are the steps I took:

```<code>SELECT DISTINCT(name)
FROM people
JOIN stars ON stars.person_id = people.id
JOIN movies ON movies.id = stars.movie_id
WHERE movies.id IN
    (SELECT movie_id
     FROM movies
     JOIN stars ON stars.movie_id = movies.id
     JOIN people ON people.id = stars.person_id
     WHERE people.name = "Kevin Bacon"
       AND people.birth = 1958)
  AND people.name != "Kevin Bacon";
</code>```

Result is 176 distinct rows of names.

Body:
DataBase movies.db

tables

directors (movie_id, person_id)

movies (id, title, year)

people (id, name, birth)

ratings (movie_id, rating, votes)

stars (movie_id, person_id)

you can download the database.

Question

I'm new in programming, so I decided, to begin with, CS50 Harvard course here is the problem and the test solution:

In 13.sql, write a SQL query to list the names of all people who starred in a movie in which Kevin Bacon also starred.
Your query should output a table with a single column for the name of each person.
There may be multiple people named Kevin Bacon in the database. Be sure to only select the Kevin Bacon born in 1958.
Kevin Bacon himself should not be included in the resulting list.

solution hint

Executing 13.sql results in a table with 1 column and 176 rows.

executing code in PowerShell or bash
cat 13.sql | sqlite3 movies.db

My Code:

SELECT COUNT(name)
FROM people
JOIN stars ON stars.person_id = people.id
JOIN movies ON movies.id = stars.movie_id
WHERE people.id IN(
SELECT stars.person_id
FROM stars
GROUP BY stars.person_id
HAVING name = "Kevin Bacon");

problem:

when I execute code it stop working, I can't choose stars with Kevin

Body:
I solved this problem by using DISTINCT and NOT EQUAL operator in SQL.

Here are the steps I took:

SELECT DISTINCT(name)
FROM people
JOIN stars ON stars.person_id = people.id
JOIN movies ON movies.id = stars.movie_id
WHERE movies.id IN
    (SELECT movie_id
     FROM movies
     JOIN stars ON stars.movie_id = movies.id
     JOIN people ON people.id = stars.person_id
     WHERE people.name = "Kevin Bacon"
       AND people.birth = 1958)
  AND people.name != "Kevin Bacon";

Result is 176 distinct rows of names.


问:
Use variable as entity table name
Is there a way to dynmaically define the table name so I do not have to do multiple calls if the table I'm accessing is different for different conditions? I don't want to have an if/else for every table I am accessing if I can use a variable name instead.</p>

```<code>using (Entity ctx = new Entity())
{
    dbTableVal = "EntityTables";
    var query = from d in dbTableVal
                where d == "Yes"
                select d;
}
</code>```

答:
have a look at the below:

Using LINQ to SQL with Dynamic tables

Title: Use variable as entity table name

Body:
Is there a way to dynmaically define the table name so I do not have to do multiple calls if the table I'm accessing is different for different conditions? I don't want to have an if/else for every table I am accessing if I can use a variable name instead.

using (Entity ctx = new Entity())
{
    dbTableVal = "EntityTables";
    var query = from d in dbTableVal
                where d == "Yes"
                select d;
}


问:
Unable to load language.json and css files in Firebase hosting
I have my app developed in StackBlitz, and incldued with ngx-translate package.
It is working perfectly until it deployed to firebase.... basically everything broken (sobbing...)
I tried my best to detail out my configs and the error log as i couldn't resolve it myself.
I also dig through the internet but no luck to resolve any of them.
Sorry for the lengthy post.

index.html

```<code><link rel="stylesheet" type="text/css" href="/node_modules/primeicons/primeicons.css" />
<link rel="stylesheet" type="text/css" href="/node_modules/primeng/resources/themes/nova-light/theme.css" />
<link rel="stylesheet" type="text/css" href="/node_modules/primeng/resources/primeng.min.css" />
</code>```

The above code error out in Firebase but not StackBlitz (run perfectly)

```<code>Resource interpreted as Stylesheet but transferred with MIME type text/html: "https://fireforgez.firebaseapp.com/node_modules/primeng/resources/themes/nova-light/theme.css".
Resource interpreted as Stylesheet but transferred with MIME type text/html: "https://fireforgez.firebaseapp.com/node_modules/primeng/resources/primeng.min.css".
Resource interpreted as Stylesheet but transferred with MIME type text/html: "https://fireforgez.firebaseapp.com/node_modules/primeicons/primeicons.css".
</code>```

To get rid of it, i did a silly patch by replace it with actual web URL

```<code><link rel="stylesheet" type="text/css" href="https://unpkg.com/primeicons@4.0.0-rc.2/primeicons.css" />
<link rel="stylesheet" type="text/css" href="https://unpkg.com/primeng@9.1.0/resources/themes/nova-light/theme.css" />
<link rel="stylesheet" type="text/css" href="https://unpkg.com/primeng@9.1.0/resources/primeng.min.css" />
</code>```

PrimeFlex package also hit the similar error

```<code>    DevTools failed to load SourceMap: Could not parse content for
https://fireforgez.firebaseapp.com/primeflex.css.map: Unexpected token < in JSON at position 0
</code>```

I compared both StackBlitz and Firebase, the stylesheet files are all load-able. But when i replace with firebase hosting url, all .css revert back to firebase main url
e.g.
https://fireforgez.firebaseapp.com/node_modules/primeng/resources/themes/nova-light/theme.css
will redirect to
https://fireforgez.firebaseapp.com/
and generated a series of error

```<code>Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'node_modules/primeng/resources/themes/nova-light/theme.css'
Error: Cannot match any routes. URL Segment: 'node_modules/primeng/resources/themes/nova-light/theme.css'
    at ApplyRedirects.noMatchError (router.umd.js:2284) [angular]
    at CatchSubscriber.eval [as selector] (router.umd.js:2265) [angular]
    at CatchSubscriber.error (catchError.js:48) [angular]
    at MapSubscriber.Subscriber._error (Subscriber.js:92) [angular]
    at MapSubscriber.Subscriber.error (Subscriber.js:72) [angular]
    at MapSubscriber.Subscriber._error (Subscriber.js:92) [angular]
    at MapSubscriber.Subscriber.error (Subscriber.js:72) [angular]
    at MapSubscriber.Subscriber._error (Subscriber.js:92) [angular]
    at MapSubscriber.Subscriber.error (Subscriber.js:72) [angular]
    at ThrowIfEmptySubscriber.Subscriber._error (Subscriber.js:92) [angular]
    at ThrowIfEmptySubscriber.Subscriber.error (Subscriber.js:72) [angular]
    at TakeLastSubscriber.Subscriber._error (Subscriber.js:92) [angular]
    at TakeLastSubscriber.Subscriber.error (Subscriber.js:72) [angular]
    at MergeMapSubscriber.OuterSubscriber.notifyError (OuterSubscriber.js:26) [angular]
    at resolvePromise (zone.js:816) [angular]
    at resolvePromise (zone.js:768) [angular]
    at eval (zone.js:878) [angular]
    at Object.onInvokeTask (core.umd.js:19397) [angular]
    at drainMicroTaskQueue (zone.js:591) [<root>]
</code>```

For ngx-translate, it's also working correctly in StackBlitz but couldn't load language files.

```<code>SyntaxError: Unexpected token < in JSON at position 0
at JSON.parse (<anonymous>)
at XMLHttpRequest.onLoad (https://fireforgez.firebaseapp.com/turbo_modules/@angular/common@9.1.9/bundles/common-http.umd.js:1390:55)
at ZoneDelegate.invokeTask (https://fireforgez.firebaseapp.com/turbo_modules/zone.js@0.10.3/dist/zone.js:411:35)
at Object.onInvokeTask (https://fireforgez.firebaseapp.com/turbo_modules/@angular/core@9.1.9/bundles/core.umd.js:19397:37)
at ZoneDelegate.invokeTask (https://fireforgez.firebaseapp.com/turbo_modules/zone.js@0.10.3/dist/zone.js:410:40)
at Zone.runTask (https://fireforgez.firebaseapp.com/turbo_modules/zone.js@0.10.3/dist/zone.js:178:51)
at ZoneTask.invokeTask [as invoke] (https://fireforgez.firebaseapp.com/turbo_modules/zone.js@0.10.3/dist/zone.js:493:38)
at invokeTask (https://fireforgez.firebaseapp.com/turbo_modules/zone.js@0.10.3/dist/zone.js:1633:18)
at XMLHttpRequest.globalZoneAwareCallback (https://fireforgez.firebaseapp.com/turbo_modules/zone.js@0.10.3/dist/zone.js:1670:25)
...
message: "Http failure during parsing for https://fireforgez.firebaseapp.com/assets/i18n/en.json"
name: "HttpErrorResponse"
ok: false
status: 200
statusText: "OK"
url: "https://fireforgez.firebaseapp.com/assets/i18n/en.json"
</code>```

Here i my complete angular.json file

```<code>{
  "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
  "version": 1,
  "newProjectRoot": "projects",
  "projects": {
    "demo": {
      "root": "",
      "sourceRoot": "src",
      "projectType": "application",
      "prefix": "app",
      "schematics": {},
      "architect": {
        "build": {
          "builder": "@angular-devkit/build-angular:browser",
          "options": {
            "outputPath": "dist/demo",
            "index": "src/index.html",
            "main": "src/main.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "src/tsconfig.app.json",
            "assets": [
              "src/favicon.ico",
              "src/assets"
            ],
            "styles": [
              "src/styles.css",
              "node_modules/primeicons/primeicons.css",
              "node_modules/primeng/resources/themes/nova-light/theme.css",
              "node_modules/primeng/resources/primeng.min.css",
              "../node_modules/quill/dist/quill.core.css",
              "../node_modules/quill/dist/quill.snow.css",
              "node_modules/primeflex/primeflex.css"
            ],
            "scripts": [
              "../node_modules/quill/dist/quill.js"
            ]
          },
          "configurations": {
            "production": {
              "fileReplacements": [
                {
                  "replace": "src/environments/environment.ts",
                  "with": "src/environments/environment.prod.ts"
                }
              ],
              "optimization": true,
              "outputHashing": "all",
              "sourceMap": false,
              "extractCss": true,
              "namedChunks": false,
              "aot": true,
              "extractLicenses": true,
              "vendorChunk": false,
              "buildOptimizer": true
            }
          }
        },
        "serve": {
          "builder": "@angular-devkit/build-angular:dev-server",
          "options": {
            "browserTarget": "demo:build"
          },
          "configurations": {
            "production": {
              "browserTarget": "demo:build:production"
            }
          }
        },
        "extract-i18n": {
          "builder": "@angular-devkit/build-angular:extract-i18n",
          "options": {
            "browserTarget": "demo:build"
          }
        },
        "test": {
          "builder": "@angular-devkit/build-angular:karma",
          "options": {
            "main": "src/test.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "src/tsconfig.spec.json",
            "karmaConfig": "src/karma.conf.js",
            "styles": [
              "styles.css"
            ],
            "scripts": [
              "../node_modules/quill/dist/quill.js"
            ],
            "assets": [
              "src/favicon.ico",
              "src/assets"
            ]
          }
        },
        "lint": {
          "builder": "@angular-devkit/build-angular:tslint",
          "options": {
            "tsConfig": [
              "src/tsconfig.app.json",
              "src/tsconfig.spec.json"
            ],
            "exclude": [
              "**/node_modules/**"
            ]
          }
        }
      }
    }
  },
  "defaultProject": "demo"
}
</code>```

答:
I very appreciate Eric, who is the owner of StackBlitz being so grateful and patient to explained that the Firebase deployment still in Beta (i didn't aware before that!...)
https://github.com/stackblitz/core/issues/1254#issuecomment-636860107

I keep trying every possible ways to solve it in SB for deployment but no luck. With his advise, i crack my head and bring down the project to local, and manually build the broken dependencies in local. After that i deployed to firebase and everything is now WORKING!

So for the time being, if you guys having serious projects and need to deploy from SB to Firebase, i advise you to wait until the deployment got a stable release.

Body:
I have my app developed in StackBlitz, and incldued with ngx-translate package.
It is working perfectly until it deployed to firebase.... basically everything broken (sobbing...)
I tried my best to detail out my configs and the error log as i couldn't resolve it myself.
I also dig through the internet but no luck to resolve any of them.
Sorry for the lengthy post.

index.html

<link rel="stylesheet" type="text/css" href="/node_modules/primeicons/primeicons.css" />
<link rel="stylesheet" type="text/css" href="/node_modules/primeng/resources/themes/nova-light/theme.css" />
<link rel="stylesheet" type="text/css" href="/node_modules/primeng/resources/primeng.min.css" />

The above code error out in Firebase but not StackBlitz (run perfectly)

Resource interpreted as Stylesheet but transferred with MIME type text/html: "https://fireforgez.firebaseapp.com/node_modules/primeng/resources/themes/nova-light/theme.css".
Resource interpreted as Stylesheet but transferred with MIME type text/html: "https://fireforgez.firebaseapp.com/node_modules/primeng/resources/primeng.min.css".
Resource interpreted as Stylesheet but transferred with MIME type text/html: "https://fireforgez.firebaseapp.com/node_modules/primeicons/primeicons.css".

To get rid of it, i did a silly patch by replace it with actual web URL

<link rel="stylesheet" type="text/css" href="https://unpkg.com/primeicons@4.0.0-rc.2/primeicons.css" />
<link rel="stylesheet" type="text/css" href="https://unpkg.com/primeng@9.1.0/resources/themes/nova-light/theme.css" />
<link rel="stylesheet" type="text/css" href="https://unpkg.com/primeng@9.1.0/resources/primeng.min.css" />

PrimeFlex package also hit the similar error

    DevTools failed to load SourceMap: Could not parse content for
https://fireforgez.firebaseapp.com/primeflex.css.map: Unexpected token < in JSON at position 0

I compared both StackBlitz and Firebase, the stylesheet files are all load-able. But when i replace with firebase hosting url, all .css revert back to firebase main url
e.g.
https://fireforgez.firebaseapp.com/node_modules/primeng/resources/themes/nova-light/theme.css
will redirect to
https://fireforgez.firebaseapp.com/
and generated a series of error

Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'node_modules/primeng/resources/themes/nova-light/theme.css'
Error: Cannot match any routes. URL Segment: 'node_modules/primeng/resources/themes/nova-light/theme.css'
    at ApplyRedirects.noMatchError (router.umd.js:2284) [angular]
    at CatchSubscriber.eval [as selector] (router.umd.js:2265) [angular]
    at CatchSubscriber.error (catchError.js:48) [angular]
    at MapSubscriber.Subscriber._error (Subscriber.js:92) [angular]
    at MapSubscriber.Subscriber.error (Subscriber.js:72) [angular]
    at MapSubscriber.Subscriber._error (Subscriber.js:92) [angular]
    at MapSubscriber.Subscriber.error (Subscriber.js:72) [angular]
    at MapSubscriber.Subscriber._error (Subscriber.js:92) [angular]
    at MapSubscriber.Subscriber.error (Subscriber.js:72) [angular]
    at ThrowIfEmptySubscriber.Subscriber._error (Subscriber.js:92) [angular]
    at ThrowIfEmptySubscriber.Subscriber.error (Subscriber.js:72) [angular]
    at TakeLastSubscriber.Subscriber._error (Subscriber.js:92) [angular]
    at TakeLastSubscriber.Subscriber.error (Subscriber.js:72) [angular]
    at MergeMapSubscriber.OuterSubscriber.notifyError (OuterSubscriber.js:26) [angular]
    at resolvePromise (zone.js:816) [angular]
    at resolvePromise (zone.js:768) [angular]
    at eval (zone.js:878) [angular]
    at Object.onInvokeTask (core.umd.js:19397) [angular]
    at drainMicroTaskQueue (zone.js:591) [<root>]

For ngx-translate, it's also working correctly in StackBlitz but couldn't load language files.

SyntaxError: Unexpected token < in JSON at position 0
at JSON.parse (<anonymous>)
at XMLHttpRequest.onLoad (https://fireforgez.firebaseapp.com/turbo_modules/@angular/common@9.1.9/bundles/common-http.umd.js:1390:55)
at ZoneDelegate.invokeTask (https://fireforgez.firebaseapp.com/turbo_modules/zone.js@0.10.3/dist/zone.js:411:35)
at Object.onInvokeTask (https://fireforgez.firebaseapp.com/turbo_modules/@angular/core@9.1.9/bundles/core.umd.js:19397:37)
at ZoneDelegate.invokeTask (https://fireforgez.firebaseapp.com/turbo_modules/zone.js@0.10.3/dist/zone.js:410:40)
at Zone.runTask (https://fireforgez.firebaseapp.com/turbo_modules/zone.js@0.10.3/dist/zone.js:178:51)
at ZoneTask.invokeTask [as invoke] (https://fireforgez.firebaseapp.com/turbo_modules/zone.js@0.10.3/dist/zone.js:493:38)
at invokeTask (https://fireforgez.firebaseapp.com/turbo_modules/zone.js@0.10.3/dist/zone.js:1633:18)
at XMLHttpRequest.globalZoneAwareCallback (https://fireforgez.firebaseapp.com/turbo_modules/zone.js@0.10.3/dist/zone.js:1670:25)
...
message: "Http failure during parsing for https://fireforgez.firebaseapp.com/assets/i18n/en.json"
name: "HttpErrorResponse"
ok: false
status: 200
statusText: "OK"
url: "https://fireforgez.firebaseapp.com/assets/i18n/en.json"

Here i my complete angular.json file

{
  "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
  "version": 1,
  "newProjectRoot": "projects",
  "projects": {
    "demo": {
      "root": "",
      "sourceRoot": "src",
      "projectType": "application",
      "prefix": "app",
      "schematics": {},
      "architect": {
        "build": {
          "builder": "@angular-devkit/build-angular:browser",
          "options": {
            "outputPath": "dist/demo",
            "index": "src/index.html",
            "main": "src/main.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "src/tsconfig.app.json",
            "assets": [
              "src/favicon.ico",
              "src/assets"
            ],
            "styles": [
              "src/styles.css",
              "node_modules/primeicons/primeicons.css",
              "node_modules/primeng/resources/themes/nova-light/theme.css",
              "node_modules/primeng/resources/primeng.min.css",
              "../node_modules/quill/dist/quill.core.css",
              "../node_modules/quill/dist/quill.snow.css",
              "node_modules/primeflex/primeflex.css"
            ],
            "scripts": [
              "../node_modules/quill/dist/quill.js"
            ]
          },
          "configurations": {
            "production": {
              "fileReplacements": [
                {
                  "replace": "src/environments/environment.ts",
                  "with": "src/environments/environment.prod.ts"
                }
              ],
              "optimization": true,
              "outputHashing": "all",
              "sourceMap": false,
              "extractCss": true,
              "namedChunks": false,
              "aot": true,
              "extractLicenses": true,
              "vendorChunk": false,
              "buildOptimizer": true
            }
          }
        },
        "serve": {
          "builder": "@angular-devkit/build-angular:dev-server",
          "options": {
            "browserTarget": "demo:build"
          },
          "configurations": {
            "production": {
              "browserTarget": "demo:build:production"
            }
          }
        },
        "extract-i18n": {
          "builder": "@angular-devkit/build-angular:extract-i18n",
          "options": {
            "browserTarget": "demo:build"
          }
        },
        "test": {
          "builder": "@angular-devkit/build-angular:karma",
          "options": {
            "main": "src/test.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "src/tsconfig.spec.json",
            "karmaConfig": "src/karma.conf.js",
            "styles": [
              "styles.css"
            ],
            "scripts": [
              "../node_modules/quill/dist/quill.js"
            ],
            "assets": [
              "src/favicon.ico",
              "src/assets"
            ]
          }
        },
        "lint": {
          "builder": "@angular-devkit/build-angular:tslint",
          "options": {
            "tsConfig": [
              "src/tsconfig.app.json",
              "src/tsconfig.spec.json"
            ],
            "exclude": [
              "**/node_modules/**"
            ]
          }
        }
      }
    }
  },
  "defaultProject": "demo"
}


问:
How to upgrade node js version on google cloud build
So I recently upgraded my app from Angular 7 to Angular 8 and I'm having issues with the node version of the cloud build VM as Angular 8 requires node version 10.9 or greater as shown below:

How can I upgrade the node version of the Google cloud VM so I won't get this error again?

Thanks.

答:
This link has all the current versions and their tags:

https://console.cloud.google.com/gcr/images/cloud-builders/GLOBAL/npm

For example in cloudbuild.yaml I used

which uses the current tag.


问:
Angular 6 Unit Tests: An error was thrown in afterAll\nReferenceError: Can't find variable: $ thrown
When running my unit tests, from time to time, even if they pass, at the end of all the tests running, I will get the following error.

On my Jenkins CI build running PhantomJS:

```<code>.PhantomJS 2.1.1 (Linux 0.0.0) ERROR
  {
    "message": "An error was thrown in afterAll\nReferenceError: Can't find variable: $ thrown",
    "str": "An error was thrown in afterAll\nReferenceError: Can't find variable: $ thrown"
  }
</code>```

Or on Chrome:

```<code>Chrome 67.0.3396 (Windows 7 0.0.0) ERROR
  {
    "message": "An error was thrown in afterAll\n[object ErrorEvent] thrown",
    "str": "An error was thrown in afterAll\n[object ErrorEvent] thrown"
  }
</code>```

I also have really unreliable tests, without changing anything some times they would succeed and other times the same tests would fail, so I knew something weird was going on.

答:
Another thing which has helped me as well and solved a few of my problems was to add the statement to destroy the fixture after each test

  afterEach(() => {
    fixture.destroy();
  });```

Body:
When running my unit tests, from time to time, even if they pass, at the end of all the tests running, I will get the following error.

On my Jenkins CI build running PhantomJS:

.PhantomJS 2.1.1 (Linux 0.0.0) ERROR
  {
    "message": "An error was thrown in afterAll\nReferenceError: Can't find variable: $ thrown",
    "str": "An error was thrown in afterAll\nReferenceError: Can't find variable: $ thrown"
  }

Or on Chrome:

Chrome 67.0.3396 (Windows 7 0.0.0) ERROR
  {
    "message": "An error was thrown in afterAll\n[object ErrorEvent] thrown",
    "str": "An error was thrown in afterAll\n[object ErrorEvent] thrown"
  }

I also have really unreliable tests, without changing anything some times they would succeed and other times the same tests would fail, so I knew something weird was going on.


问:
OSB with Java Callout
I'm facing an issue. On testing a java code with external jar dependency separately, it is working. But when trying to deploy OSB code with java callout calling the same java code, it is throwing method does not exist.</p>

答:
There are multiple ways to resolve this issue.

you can create a fat jar(it will contain all class files, Tools are available online or can use Eclipse or any ide to export the code.) for your Java code along with Dependencies and libraries.

You can deploy your dependencies as libraries/Application or copy Weblogic lib folder it depends on your dependency type. after deployment, you must restart the domain. Then u can deploy import your java callout Jar/Archive in OSB.

Title: OSB with Java Callout


问:
Rounding R simple features linestring geometry coordinates
I need to round the coordinates of a simple features object (containing approx. 1,000,000 linestring features) to the nearest 5 decimal places. The code below does this correctly, but runtime is very slow because the last line of the for loop (indata$geometry[i] <- st_linestring(coords) takes several seconds for each iteration.

Does anyone know a more efficient way to code this?

```<code>indata <- st_read(dsn=dir, layer=layer)
indata <- st_cast(indata,"LINESTRING")

for (i in 1:nrow(indata)) {
  coords <- st_coordinates(indata$geometry[i])
  coords <- round(coords, 5)
  indata$geometry[i] <- st_linestring(coords) #This is the slow part
}
</code>```

答:
I don't think you can improve much upon what you have without writing out a shapefile. The limitation seems to be dealing with linestring. However, you can use the st_set_precision function to set the precision and write out a file. It doesn't change the geometry precision until your write a file. You can read more about how precision works in the st_binary section of the sf manual on page 48 of the sf manual. Basically it is related to the number of zeros.

```<code>outdata <- st_set_precision(indata, precision=10^5)
st_write(outdata, "/path/to/file.shp")
indata <- st_read("/path/to/file.shp")
</code>```

Body:
I need to round the coordinates of a simple features object (containing approx. 1,000,000 linestring features) to the nearest 5 decimal places. The code below does this correctly, but runtime is very slow because the last line of the for loop (indata$geometry[i] <- st_linestring(coords) takes several seconds for each iteration.

Does anyone know a more efficient way to code this?

indata <- st_read(dsn=dir, layer=layer)
indata <- st_cast(indata,"LINESTRING")

for (i in 1:nrow(indata)) {
  coords <- st_coordinates(indata$geometry[i])
  coords <- round(coords, 5)
  indata$geometry[i] <- st_linestring(coords) #This is the slow part
}

Body:
I don't think you can improve much upon what you have without writing out a shapefile. The limitation seems to be dealing with linestring. However, you can use the st_set_precision function to set the precision and write out a file. It doesn't change the geometry precision until your write a file. You can read more about how precision works in the st_binary section of the sf manual on page 48 of the sf manual. Basically it is related to the number of zeros.

outdata <- st_set_precision(indata, precision=10^5)
st_write(outdata, "/path/to/file.shp")
indata <- st_read("/path/to/file.shp")


问:
On Orchard CMS, how can I display a message when the query returns no records for a projection
Using the admin panel on Orchard CMS I've created the following:

A content type called CalendarEvent, it contains several fields including the EventDate;

A query that has 2 filters, one by the content type (= CalendarEvent) and another one based on the date of the event. The Display Mode on the Layout is set to Properties;

A projection to display the query when a menu item is clicked.

The problem is that based on the EventDate we only display upcoming events, not the ones in the past. If for some reason there are no events to be displayed, all the user gets is an empty page with no information whatsoever.

My question is, how can I modify my query or projection in order to display something like: "There are no current events scheduled"?

I know the Properties on the Query's Layout allow me to specify a "No Result", but this implies that a record is present and that the actual property is empty. However, in my example, no record is present.

Thank you all in advance.

Rafael

By the way, I am using the latest Orchard version 1.6.

答:
If your projections are Layouts elements, you can create a Projection.cshtml file in your theme's Views/Elements folder with the following:

```<code>@{
    var list = Model.List;
    var pager = Model.Pager;

    if (list != null)
    {
        @Display(list)

        if (list.Items.Count == 0)
        {
            <div>There are currently no items.</div>
        }
    }

    if (pager != null)
    {
        @Display(pager)
    }
}
</code>```

This is a copy of the default template with the if (list.Items.Count == 0) section added. Edit as needed.

Body:
If your projections are Layouts elements, you can create a Projection.cshtml file in your theme's Views/Elements folder with the following:

@{
    var list = Model.List;
    var pager = Model.Pager;

    if (list != null)
    {
        @Display(list)

        if (list.Items.Count == 0)
        {
            <div>There are currently no items.</div>
        }
    }

    if (pager != null)
    {
        @Display(pager)
    }
}

This is a copy of the default template with the if (list.Items.Count == 0) section added. Edit as needed.


问:
Dev Tools, Inspect Element, why is my CSS unchecked?
On a freshly loaded site, when I go inspect an element, a CSS property is always unchecked. It's there and I can enable it, but it's unchecked by default.

The style is position: sticky

Tried this in different browsers:

 * Chrome and Firefox: it's unchecked, but I can toggle it

 * Safari: it's "commented out" and also I can toggle it

To be clear: I don't see any other position styles being applied on that same element.

Any ideas?

答:
An element with position: sticky; is positioned based on the user's scroll position.

A sticky element toggles between relative and fixed, depending on the scroll position. It is positioned relative until a given offset position is met in the viewport - then it "sticks" in place (like position:fixed).

Safari requires a -webkit- prefix


问:
Create json structure in Android
I'm trying to create a json structure like this in Android but cannot find any way to complete it.

```<code>{
  "FirstName": Fred,
  "LastName": "Poulsen",
  "Age": "18",
  "Phone": {
    "mobile": {}
  }
}
</code>```

This is what I have tried to do.

```<code>        Map<Object, Object> objectMap = new HashMap<>();
        Map<Object, Object> phone = new HashMap<>();

        objectMap.put("FirstName", "Fred");
        objectMap.put("LastName", "Poulsen");
        objectMap.put("Age", "18");
        objectMap.put("Phone", phone);
        input.put("mobile", body);
</code>```

答:
You can using Gson to make your json. Add Gson dependency app/build.gradle, create User class. Try this

```<code>implementation 'com.google.code.gson:gson:2.8.6'
</code>```

```<code>public class User {

    @SerializedName("FirstName")
    private String mFirstName;

    @SerializedName("LastName")
    private String mLastName;

    @SerializedName("Age")
    private int mAge;

    @SerializedName("Phone")
    private Phone mPhone;

    public class Phone {
        @SerializedName("mobile")
        private String mobile;

        public Phone(String mobile) {
            this.mobile = mobile;
        }
    }

    public User(String firstName, String lastName, int age, String phone) {
        mFirstName = firstName;
        mLastName = lastName;
        mAge = age;
        mPhone = new Phone(phone);
    }
}
</code>```

```<code>new Gson().toJson(new User("Fred", "Poulsen", 18, "0123456789")); // your json
</code>```

Title: Create json structure in Android

Body:
I'm trying to create a json structure like this in Android but cannot find any way to complete it.

{
  "FirstName": Fred,
  "LastName": "Poulsen",
  "Age": "18",
  "Phone": {
    "mobile": {}
  }
}

This is what I have tried to do.

        Map<Object, Object> objectMap = new HashMap<>();
        Map<Object, Object> phone = new HashMap<>();

        objectMap.put("FirstName", "Fred");
        objectMap.put("LastName", "Poulsen");
        objectMap.put("Age", "18");
        objectMap.put("Phone", phone);
        input.put("mobile", body);

Body:
You can using Gson to make your json. Add Gson dependency app/build.gradle, create User class. Try this

implementation 'com.google.code.gson:gson:2.8.6'

public class User {

    @SerializedName("FirstName")
    private String mFirstName;

    @SerializedName("LastName")
    private String mLastName;

    @SerializedName("Age")
    private int mAge;

    @SerializedName("Phone")
    private Phone mPhone;

    public class Phone {
        @SerializedName("mobile")
        private String mobile;

        public Phone(String mobile) {
            this.mobile = mobile;
        }
    }

    public User(String firstName, String lastName, int age, String phone) {
        mFirstName = firstName;
        mLastName = lastName;
        mAge = age;
        mPhone = new Phone(phone);
    }
}

new Gson().toJson(new User("Fred", "Poulsen", 18, "0123456789")); // your json


问:
How to match an array in order with intervening elements using a MongoDB aggregation
I have documents with an array of events objects :

```<code>  {
    "events": [
      {
        "name": "A"
      },
      {
        "name": "C"
      },
      {
        "name": "D"
      },
      {
        "name": "B"
      },
      {
        "name": "E"
      }
    ]
  },
  {
    "events": [
      {
        "name": "A"
      },
      {
        "name": "B"
      },
      {
        "name": "S"
      },
      {
        "name": "C"
      }
    ]
  }
]
</code>```

In this array, I want to count the number of events that are in a said order, with intervening events. For example, I look for the order [A,B,C], with the array [A,x,x,B,x], I should count 2, with [A,B,x,x,C] I should have 3. (x is just a placeholder for anything else)

I want to summarize this information for all my documents in the shape of an array, with the number of matches for each element. With the previous example that would give me [2,2,1], 2 matches for A, 2 matches for B, 1 match for C.

My Current aggregation is generated in javascript and follow this pattern :

Match documents with the event array containing A

Slice the array from A to the end of the array

Count the number of documents

Append the count of matching document to the summarizing array

Match documents with the event array containing B

Slice the array from B to the end of the array

Count the number of documents

etc

However, when an event does not appear in any of the arrays, it falls shorts,  as there are no documents, I do not have a way to store the summarizing array. For example, with the events array [A,x,x,B,x]  [A,B,x,x,C] and trying to match [A,B,D], I would expect [2,2,0], but I have [] as when trying to match D nothing comes up, and the aggregation cannot continue.

Here is the aggregation I'm working with : https://mongoplayground.net/p/rEdQD4FbyC4
change the matching letter l.75 to something not in the array to have the problematic behavior.

So is there a way to not lose my data when there is no match? like bypassing aggregation stages, I could not find anything related to bypassing stages in the mongoDB documentation.

Or are you aware of another way of doing this?

答:
We ended using a reduce to solve our problem

The reduce is on the events array and with every event we try to match it with the  element in sequence at the position "size of the accumulator", if it is a match it's added to the accumulator, ortherwise no, etc

here is the mongo playground : https://mongoplayground.net/p/ge4nlFWuLsZ\

The sequence we want to match is in the field "sequence"

The matched elements are in the "matching" field

Body:
I have documents with an array of events objects :

  {
    "events": [
      {
        "name": "A"
      },
      {
        "name": "C"
      },
      {
        "name": "D"
      },
      {
        "name": "B"
      },
      {
        "name": "E"
      }
    ]
  },
  {
    "events": [
      {
        "name": "A"
      },
      {
        "name": "B"
      },
      {
        "name": "S"
      },
      {
        "name": "C"
      }
    ]
  }
]

In this array, I want to count the number of events that are in a said order, with intervening events. For example, I look for the order [A,B,C], with the array [A,x,x,B,x], I should count 2, with [A,B,x,x,C] I should have 3. (x is just a placeholder for anything else)

I want to summarize this information for all my documents in the shape of an array, with the number of matches for each element. With the previous example that would give me [2,2,1], 2 matches for A, 2 matches for B, 1 match for C.

My Current aggregation is generated in javascript and follow this pattern :

Match documents with the event array containing A

Slice the array from A to the end of the array

Count the number of documents

Append the count of matching document to the summarizing array

Match documents with the event array containing B

Slice the array from B to the end of the array

Count the number of documents

etc

However, when an event does not appear in any of the arrays, it falls shorts,  as there are no documents, I do not have a way to store the summarizing array. For example, with the events array [A,x,x,B,x]  [A,B,x,x,C] and trying to match [A,B,D], I would expect [2,2,0], but I have [] as when trying to match D nothing comes up, and the aggregation cannot continue.

Here is the aggregation I'm working with : https://mongoplayground.net/p/rEdQD4FbyC4
change the matching letter l.75 to something not in the array to have the problematic behavior.

So is there a way to not lose my data when there is no match? like bypassing aggregation stages, I could not find anything related to bypassing stages in the mongoDB documentation.

Or are you aware of another way of doing this?


问:
How can I speed up this json string cleaning function?
I am storing alternative names for country administrative districts in a json string, and I have a function to clean up NA and duplicate values; however, it is a very slow function, particularly when I have tens of thousands of rows in some of the data. I've been using tidy syntax because I am the most familiar with it. It works, but does anyone have ideas on how I can optimize this function?

Here is some example data and the function:

```<code>library(tidyverse)
library(magrittr)
library(rio)
library(jsonlite)
library(tictoc)

data <- import(
  'https://docs.google.com/spreadsheets/d/1Zd_gUj4ejZoTph5i7l_XTRg3pIS2_6tM2mde0SFykzM/edit?usp=sharing',
  setclass = 'tibble'
)

cleanAlternateNames <- function(altNames) {
  tic()
  altNames %<>% lapply(function(x) {
    if (!x %>% is.na()) {
      x %>% fromJSON() %>% plyr::ldply(rbind) %>%
        pivot_longer(-one_of('.id')) %>%
        filter(!is.na(value),!value == 'NA') %>%
        distinct(value, .keep_all = T) %>%
        select(-name) %>%
        pivot_wider(names_from = '.id', values_from = 'value') %>%
        toJSON()
    }
  })
  toc()
  return(altNames)
}

data %<>%
  mutate(AlternateNames = AlternateNames %>% str_replace_all('""','"') %>%
           cleanAlternateNames)
</code>```

I modified the sample data to provide a better range of what I am trying to convert.

答:
Thanks to the helpful example uses of map from Ian Campbell and another user I was able to go back in my code to where I originally combined json lists and remove duplicates and duplicates using the map function. This code is significantly faster and eliminates the need to use the function I was using to try to clean the code afterwards. I'm posting this here in case anyone has similar problem.s</p>

```<code>library(tidyverse)
library(magrittr)
library(rio)
library(jsonlite)

# filters out duplicates from first string
.lfilter <- function(x1,x2){
  nm <- names(x1)
  x1 %<>%  unlist
  x1 <- x1[!x1 %in% unlist(x2)]
  if(length(x1) > 0){
    x1 %<>%
      unname() %>%
      list() %>% set_names(nm)
  }
  return(x1)
}

# combines two columns that are in json format while removing duplicates
.combineJSONlists <- function(x){
  x %<>% str_split("\\|")
  x1 <- x[[1]][1] %>% fromJSON()
  x2 <- x[[1]][-1] %>% fromJSON()
  x1 <- map(x1, .lfilter, x2 = x2)
  com <- x1  %>% c(x2) %>% toJSON()
  return(com)
}

# load data
data <- import(
  'https://docs.google.com/spreadsheets/d/1Zd_gUj4ejZoTph5i7l_XTRg3pIS2_6tM2mde0SFykzM/edit?usp=sharing',
  setclass = 'tibble'
)

# combine new and old AlternateNames
data %<>%
  mutate(
    ISO = ISO %>% str_replace_all('""','"'),
    AlternateNames = AlternateNames %>% str_replace_all('""','"') %>%
      paste0("|",ISO),
    AlternateNames = AlternateNames %>%
      map_chr(.combineJSONlists)) %>%
  select(-ISO)

</code>```

Body:
I am storing alternative names for country administrative districts in a json string, and I have a function to clean up NA and duplicate values; however, it is a very slow function, particularly when I have tens of thousands of rows in some of the data. I've been using tidy syntax because I am the most familiar with it. It works, but does anyone have ideas on how I can optimize this function?

Here is some example data and the function:

library(tidyverse)
library(magrittr)
library(rio)
library(jsonlite)
library(tictoc)

data <- import(
  'https://docs.google.com/spreadsheets/d/1Zd_gUj4ejZoTph5i7l_XTRg3pIS2_6tM2mde0SFykzM/edit?usp=sharing',
  setclass = 'tibble'
)

cleanAlternateNames <- function(altNames) {
  tic()
  altNames %<>% lapply(function(x) {
    if (!x %>% is.na()) {
      x %>% fromJSON() %>% plyr::ldply(rbind) %>%
        pivot_longer(-one_of('.id')) %>%
        filter(!is.na(value),!value == 'NA') %>%
        distinct(value, .keep_all = T) %>%
        select(-name) %>%
        pivot_wider(names_from = '.id', values_from = 'value') %>%
        toJSON()
    }
  })
  toc()
  return(altNames)
}

data %<>%
  mutate(AlternateNames = AlternateNames %>% str_replace_all('""','"') %>%
           cleanAlternateNames)

I modified the sample data to provide a better range of what I am trying to convert.

Body:
Thanks to the helpful example uses of map from Ian Campbell and another user I was able to go back in my code to where I originally combined json lists and remove duplicates and duplicates using the map function. This code is significantly faster and eliminates the need to use the function I was using to try to clean the code afterwards. I'm posting this here in case anyone has similar problem.s

library(tidyverse)
library(magrittr)
library(rio)
library(jsonlite)

# filters out duplicates from first string
.lfilter <- function(x1,x2){
  nm <- names(x1)
  x1 %<>%  unlist
  x1 <- x1[!x1 %in% unlist(x2)]
  if(length(x1) > 0){
    x1 %<>%
      unname() %>%
      list() %>% set_names(nm)
  }
  return(x1)
}

# combines two columns that are in json format while removing duplicates
.combineJSONlists <- function(x){
  x %<>% str_split("\\|")
  x1 <- x[[1]][1] %>% fromJSON()
  x2 <- x[[1]][-1] %>% fromJSON()
  x1 <- map(x1, .lfilter, x2 = x2)
  com <- x1  %>% c(x2) %>% toJSON()
  return(com)
}

# load data
data <- import(
  'https://docs.google.com/spreadsheets/d/1Zd_gUj4ejZoTph5i7l_XTRg3pIS2_6tM2mde0SFykzM/edit?usp=sharing',
  setclass = 'tibble'
)

# combine new and old AlternateNames
data %<>%
  mutate(
    ISO = ISO %>% str_replace_all('""','"'),
    AlternateNames = AlternateNames %>% str_replace_all('""','"') %>%
      paste0("|",ISO),
    AlternateNames = AlternateNames %>%
      map_chr(.combineJSONlists)) %>%
  select(-ISO)


问:
What does fwnode in struct device do in linux kernel?
In the definition of struct device，there is a fwnode field defined，

```<code>struct device {
    ...
    struct fwnode_handle    *fwnode; /* firmware device node */
    ...
}
</code>```

And the corresponding file is in include/linux/fwnode.h:

```<code>struct fwnode_reference_args {
    struct fwnode_handle *fwnode;
    unsigned int nargs;
    unsigned int args[NR_FWNODE_REFERENCE_ARGS];
};
...
</code>```

Then I search it on the website, but can not find the detail explaining of this part (fwnode) of kernel so what does it mean? And what does it do?
Can you provide a documentation for reference.

答:
The fwnode refers to a firmware node usually representing an entry in either Device Tree or ACPI (generally the DSDT table). Device Tree and ACPI are two different ways to define devices and their properties and interconnections between them. They both use tree structures to encode this information.

The fwnode member on a given struct device is the node in the corresponding firmware table for that device. ACPI is common in x86/UEFI based systems and device tree is common in ARM systems.

fwnode can be used with kernel APIs which accept fwnode handles. One such API is the V4l2 (Video For Linux 2) fwnode API: https://www.kernel.org/doc/html/latest/media/kapi/v4l2-fwnode.html

Some good reference docs:

Device tree: https://www.kernel.org/doc/Documentation/devicetree/usage-model.txt

_DSD graphs in DSDT: https://www.kernel.org/doc/Documentation/acpi/dsd/graph.txt

Body:
In the definition of struct device，there is a fwnode field defined，

struct device {
    ...
    struct fwnode_handle    *fwnode; /* firmware device node */
    ...
}

And the corresponding file is in include/linux/fwnode.h:

struct fwnode_reference_args {
    struct fwnode_handle *fwnode;
    unsigned int nargs;
    unsigned int args[NR_FWNODE_REFERENCE_ARGS];
};
...

Then I search it on the website, but can not find the detail explaining of this part (fwnode) of kernel so what does it mean? And what does it do?
Can you provide a documentation for reference.


问:
How would I build an entire form using just json?
I was given a little quiz to build out a form in html using only a json file using javascript.
Is that even possible just using js?
Can anyone provide me a link or something to reference on google to accomplish this task?
I have searched for "json file to html" but havent been able to find anything that could help thus far.
The json file contain a menu of items which can be ordered in quantity so I need to have form elements in there as well so as you can see its not an easy search.  Any tips or pointers would be great.
I have attached the json form so you can understand the task better.</p>

```<code>{
    "menu": {
        "slice of pizza": "2.00",
        "toppings": {
            "pepperoni": ".25",
            "meatballs": ".35",
            "mushrooms": ".40",
            "olives": ".20"
        },
        "sides": {
            "potato salad": "1.25",
            "hummus": "2.50",
            "caesar salad": "3.50",
            "garden salad": "2.25"
        },
        "drinks": {
            "soda": {
                "small": "1.95",
                "medium": "2.20",
                "large": "2.50"
            },
            "juice": "2.00",
            "water": "1.25"
        }
    }
}
</code>```

答:
correct me, you are gonna to achieve something like this ?

```<code><h1>SLice of pizza: 2.00</h1>
<label>toping</label>
<select>
<option>peperoni .25</option>
...
<option>olive .20</option>
</select>
</code>```

if you do so then all you need to do is looping through the json if has more than one valiue then you generate the select tag and then attach it to your html

i still dont post any code, i am afraid i catch your question wrong

Body:
I was given a little quiz to build out a form in html using only a json file using javascript.
Is that even possible just using js?
Can anyone provide me a link or something to reference on google to accomplish this task?
I have searched for "json file to html" but havent been able to find anything that could help thus far.
The json file contain a menu of items which can be ordered in quantity so I need to have form elements in there as well so as you can see its not an easy search.  Any tips or pointers would be great.
I have attached the json form so you can understand the task better.

{
    "menu": {
        "slice of pizza": "2.00",
        "toppings": {
            "pepperoni": ".25",
            "meatballs": ".35",
            "mushrooms": ".40",
            "olives": ".20"
        },
        "sides": {
            "potato salad": "1.25",
            "hummus": "2.50",
            "caesar salad": "3.50",
            "garden salad": "2.25"
        },
        "drinks": {
            "soda": {
                "small": "1.95",
                "medium": "2.20",
                "large": "2.50"
            },
            "juice": "2.00",
            "water": "1.25"
        }
    }
}

Body:
correct me, you are gonna to achieve something like this ?

<h1>SLice of pizza: 2.00</h1>
<label>toping</label>
<select>
<option>peperoni .25</option>
...
<option>olive .20</option>
</select>

if you do so then all you need to do is looping through the json if has more than one valiue then you generate the select tag and then attach it to your html

i still dont post any code, i am afraid i catch your question wrong


问:
In Python, how can I combine a set of tuples from a list of given tuples without using itertools?
Given a list as follows:

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

I know it's very easy to combine the list of tuples by using itertools.

(1, 3, 6), (1, 4, 6), (1, 5, 6), (2, 3, 6), (2, 4, 6), (2, 5, 6)

But how can I solve it without using itertools?

答:
Here's a fairly generic approach with a series of loops over the input:

```<code>lst = [(1, 2), (3, 4, 5), (6,)]

result = [tuple([l]) for l in lst[0]]
for l in lst[1:]:
    out = []
    for r in result:
        for i in range(len(l)):
            out.append((*r, l[i]))
    result = out

print(result)
</code>```

Output:

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

Body:
Here's a fairly generic approach with a series of loops over the input:

lst = [(1, 2), (3, 4, 5), (6,)]

result = [tuple([l]) for l in lst[0]]
for l in lst[1:]:
    out = []
    for r in result:
        for i in range(len(l)):
            out.append((*r, l[i]))
    result = out

print(result)

Output:

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


问:
What are some good resources for aspiring web designers?
What are some good resources for aspiring web designers? I've been a software developer and web app builder for nearly a decade but my UI skills are from an engineer's perspective. I appreciate quality design and great UX and I'd like to become a better designer myself, what are some good resources to get started with and/or follow (i.e. blogs, twitter accounts, etc)?

I'll start with a couple that I think are relevant:

http://www.alistapart.com/

http://www.sitepoint.com/books/design2/ (the principles of beautiful web design)

Thanks in advance.

答:
Here are a few I think are relevant...

http://www.awwwards.com

http://www.smashingmagazine.com

http://css-tricks.com


问:
Getting an error with react-router-dom, that I can't solve
I have the following code

```<code>import React from 'react';
import ReactDOM from 'react-dom'
import { BrowserRouter as Router, Route, Switch, Link } from 'react-router-dom'
import 'normalize.css/normalize.css'
import './styles/styles.scss'

const ExpenseDashboardPage = () => (
    <div>
        This is from my dashboard component
    </div>
)

const AddExpensePage = () => (
    <div>
        This is from my add expense component
    </div>
)

const EditExpensePage = () => (
    <div>
        This is for editing expenses component
    </div>
)

const HelpPage = () => (
    <div>
        This is help component
    </div>
)

const NotFoundPage = () => (
    <div>
        404! <Link to='/'>Go Home</Link>
    </div>
)

const Header = () => (
    <header>
        <h1>Expensify</h1>
        <Link to="/">Home</Link>
        <Link to='/create'>Add Expense</Link>
        <Link to='/edit'>Edit Expense</Link>
        <Link to='/help'>Help</Link>
    </header>
)

const routes = (
    <div>
        <Header />
        <Router>
            <Switch>
                <Route exact path='/' component={ExpenseDashboardPage} />
                <Route path='/create' component={AddExpensePage} />
                <Route path='/edit' component={EditExpensePage} />
                <Route path='/help' component={HelpPage} />
                <Route component={NotFoundPage} />
            </Switch>
        </Router>
    </div>
)

ReactDOM.render(routes, document.getElementById('app'))
</code>```

I am following a tutorial, however their header component works as is above; however, I am getting an error in the console with nothing rendering on the page.

VM84 bundle.js:40892 Uncaught Error: Invariant failed: You should not use <Link> outside a <Router>

I believe I have to do something with withRouter, but am not sure how to proceed.

I have a link to the github repo where the code is as well, as I am using webpack and babel to bundle my project. https://github.com/altafmquadri/expensify-app.

答:
Header component needs to be inside the Router in order to be able to access link inside Header component.

    <Router>

      <Switch>
        <Route exact path="/" component={ExpenseDashboardPage} />
        <Route path="/create" component={AddExpensePage} />
        <Route path="/edit" component={EditExpensePage} />
        <Route path="/help" component={HelpPage} />
        <Route component={NotFoundPage} />
      </Switch>
    </Router>
```

Body:
I have the following code

import React from 'react';
import ReactDOM from 'react-dom'
import { BrowserRouter as Router, Route, Switch, Link } from 'react-router-dom'
import 'normalize.css/normalize.css'
import './styles/styles.scss'

const ExpenseDashboardPage = () => (

        This is from my dashboard component

)

const AddExpensePage = () => (

        This is from my add expense component

)

const EditExpensePage = () => (

        This is for editing expenses component

)

const HelpPage = () => (

        This is help component

)

const NotFoundPage = () => (

        404! <Link to='/'>Go Home</Link>

)

const Header = () => (

Expensify

        <Link to="/">Home</Link>
        <Link to='/create'>Add Expense</Link>
        <Link to='/edit'>Edit Expense</Link>
        <Link to='/help'>Help</Link>

)

const routes = (

        <Router>
            <Switch>
                <Route exact path='/' component={ExpenseDashboardPage} />
                <Route path='/create' component={AddExpensePage} />
                <Route path='/edit' component={EditExpensePage} />
                <Route path='/help' component={HelpPage} />
                <Route component={NotFoundPage} />
            </Switch>
        </Router>

)

ReactDOM.render(routes, document.getElementById('app'))

I am following a tutorial, however their header component works as is above; however, I am getting an error in the console with nothing rendering on the page.

VM84 bundle.js:40892 Uncaught Error: Invariant failed: You should not use <Link> outside a <Router>

I believe I have to do something with withRouter, but am not sure how to proceed.

I have a link to the github repo where the code is as well, as I am using webpack and babel to bundle my project. https://github.com/altafmquadri/expensify-app.

Body:
Header component needs to be inside the Router in order to be able to access link inside Header component.

    <Router>
      <Header />
      <Switch>
        <Route exact path="/" component={ExpenseDashboardPage} />
        <Route path="/create" component={AddExpensePage} />
        <Route path="/edit" component={EditExpensePage} />
        <Route path="/help" component={HelpPage} />
        <Route component={NotFoundPage} />
      </Switch>
    </Router>


答:
The error tells you that Links can't be rendered outside a Router. All the links are rendered within the header component. Move the Header into the Router.

```<code>const routes = (
  <div>
    <Router>
      <Header />
      <Switch>
        <Route exact path='/' component={ExpenseDashboardPage} />
        <Route path='/create' component={AddExpensePage} />
        <Route path='/edit' component={EditExpensePage} />
        <Route path='/help' component={HelpPage} />
        <Route component={NotFoundPage} />
      </Switch>
    </Router>
  </div>
);
</code>```

Title: Getting an error with react-router-dom, that I can't solve

Body:
The error tells you that Links can't be rendered outside a Router. All the links are rendered within the header component. Move the Header into the Router.

const routes = (
  <div>
    <Router>
      <Header />
      <Switch>
        <Route exact path='/' component={ExpenseDashboardPage} />
        <Route path='/create' component={AddExpensePage} />
        <Route path='/edit' component={EditExpensePage} />
        <Route path='/help' component={HelpPage} />
        <Route component={NotFoundPage} />
      </Switch>
    </Router>
  </div>
);


问:
asp.net objectdatasource pass parameter from control as well as textbox
I have configured a GridView to fill data by an ObjectDataSource. This ObjectDataSource requires only one parameter which is bound to a DropDownList. This all works well.

When i load the page, it fills the DropDownList and whatever field is displayed in this DropDownListis passed as a parameter to the ObjectDataSource which further fills the GridView.

Now, i want to enhance the functionality and have a TextBox and Button next to this DropDownList. I want to give my user the option to either select a value from the DropDownList, OR TYPE IT IN THE TextBox AND PRESS ENTER TO UPDATE THE GridView.

Any idea how to do it?

I have tried dataSource.Selecting event. but it isn't working the way i want it to be.
please help

答:
There is the SelectParameters.Add method which takes the ColumnName and value as a parameter to pass in the parameter value.

```<code>protected void btn_Click(object sender, EventArgs e)
{
  ods.SelectParameters.Clear();
  ods.SelectParameters.Add("ColumnName", SetparameterValue);
}
</code>```

Body:
There is the SelectParameters.Add method which takes the ColumnName and value as a parameter to pass in the parameter value.

protected void btn_Click(object sender, EventArgs e)
{
  ods.SelectParameters.Clear();
  ods.SelectParameters.Add("ColumnName", SetparameterValue);
}


问:
Valid characters of a hostname?
What are the valid characters of a hostname? This would be something like a networked computer or a web domain.

To put it in context, I am writing a PC game which connects to a remote server; so I have a field for hostname and a field for port. Obviously the port is a number in the Short range, but I need to know what all the possible hostname characters are (and any other pattern that might be required - does a hostname need to start with a letter?).

Examples of hostname include localhost or google.com.

答:
If you're registering a domain and the termination (ex .com) it is not IDN, as Aaron Hathaway said:
Hostnames are composed of series of labels concatenated with dots, as are all domain names. For example, en.wikipedia.org is a hostname. Each label must be between 1 and 63 characters long, and the entire hostname (including the delimiting dots but not a trailing dot) has a maximum of 253 ASCII characters.

The Internet standards (Requests for Comments) for protocols mandate that component hostname labels may contain only the ASCII letters a through z (in a case-insensitive manner), the digits 0 through 9, and the hyphen -. The original specification of hostnames in RFC 952, mandated that labels could not start with a digit or with a hyphen, and must not end with a hyphen. However, a subsequent specification (RFC 1123) permitted hostname labels to start with digits. No other symbols, punctuation characters, or white space are permitted.

Later, Spain with it's .es, .com.es, .org.es, .nom,es, .gob.es and .edu.es introduced IDN tlds, if your tld is one of .es or any other that supports it, any character can be used, but you can't combine alphabets like Latin, Greek or Cyril in one hostname, and that it respects the things that can't go at the start or at the end.

If you're using non-registered tlds, just for local networking, like with local DNS or with hosts files, you can treat them all as IDN.

Keep in mind some programs could not work well, especially old, outdated and unpopular ones.

ContentLicense: CC BY-SA 2.5

Title: Valid characters of a hostname?


问:
Why does my print function print garbled message?
Why does my print function print garbled message?

答: I don't think this is normal for println(); to do but either way i think print(); should solve your problem.