问:
Modify the Outlook CustomUI XML by powershell
friends.  I want to check every of my company users' outlook customUI configuration file. Delete 2 UI buttons if any. I am trying to do it by powershell. But failed to do so. Any advice for my script?

Below is the XML content of olkexpplorer.officeUI. I need to check & delete the items in blockquotes in case they are existed in the configuration file.

```<code><mso:customUI xmlns:x1="Microsoft.Forefront.SpamReporterAddin.Connect" xmlns:mso="http://schemas.microsoft.com/office/2009/07/customui">
  <mso:ribbon>
    <mso:qat />
    <mso:tabs>
      <mso:tab idQ="mso:TabMail">
      <mso:group id="mso_c1.45620CF" label="Phishing Report" imageMso="TrustCenter" autoScale="true"
      <mso:control idQ="x1:ExplorerPhishReportMenuButton" imageMso="TrustCenter" visible="true"/>
      </mso:group>

>     <mso:group id="mso_c2.14817EBA" label="Junk" autoScale="true">
>        <mso:control idQ="x1:ExplorerSpamReportMenuButton" visible="true" />
>        <mso:control idQ="x1:ExplorerPhishReportMenuButton" imageMso="GreenBall" visible="true" />
>     </mso:group>

      </mso:tab>
    </mso:tabs>
  </mso:ribbon>
</mso:customUI>
</code>```

Here is my script

```<code>$input = [xml](Get-Content -Path “$path_to_office\olkexplorer.officeUI”)
$deletenames="mso_c2.14817EBA"
($input.customUI.ChildNodes |Where-object { $deletenames -contains $_.Name}) | ForEach-
   Object{[void]$_.ParentNode.RemoveChild($_)}
$input.save(“$path_to_office\new.officeUI”)
</code>```

答:
The problem with your approach is that ChildNodes() only returns the immediate child nodes and not all child nodes (and using $input as a variable name is not considered a good practice anyway because its a reserved variable name).

So instead of ChildNodes() I would access the child node directly like so

```<code>$input.customUI.ribbon.tabs.tab.group | where-object { $DeleteNames -contains $_.id}
</code>```

I would prefer the System.Xml.Linq classes like XDocument and XElement over the [xml] type alias because they make dealing with Xml inside a PowerShell script a little more convenient.

if this is the input xml:

```<code>$XmlCode = @'
 <mso:customUI xmlns:mso="http://schemas.microsoft.com/office/2009/07/customui">
  <mso:ribbon>
   <mso:qat><mso:sharedControls>
    <mso:control idQ="mso:FileNewDefault" visible="false"/>
    <mso:control idQ="mso:FileOpen" visible="false"/>
    <mso:control idQ="mso:FileSave" visible="true"/>
    <mso:control idQ="mso:FileSendAsAttachment" visible="false"/>
     <mso:control idQ="mso:FilePrintQuick" visible="false"/>
     <mso:control idQ="mso:SpellingAndGrammar" visible="false"
      insertBeforeQ="mso:PrintPreviewAndPrint"/>
     <mso:control idQ="mso:Undo" visible="true"
      insertBeforeQ="mso:PrintPreviewAndPrint"/>
     <mso:control idQ="mso:RedoOrRepeat" visible="true"
      insertBeforeQ="mso:PrintPreviewAndPrint"/>
     <mso:control idQ="mso:TableDrawTable" visible="false"
      insertBeforeQ="mso:PrintPreviewAndPrint"/>
     <mso:control idQ="mso:FileOpenRecentFile" visible="false"
      insertBeforeQ="mso:PrintPreviewAndPrint"/>
     <mso:control idQ="mso:FontDialog" visible="true"
      insertBeforeQ="mso:PrintPreviewAndPrint"/>
     <mso:control idQ="mso:FontSizeDecreaseWord" visible="true"
      insertBeforeQ="mso:PrintPreviewAndPrint"/>
     <mso:control idQ="mso:FontSize" visible="true"
      insertBeforeQ="mso:PrintPreviewAndPrint"/>
     <mso:control idQ="mso:PageSetupDialog" visible="true"
      insertBeforeQ="mso:PrintPreviewAndPrint"/>
     <mso:control idQ="mso:PrintPreviewAndPrint" visible="true"/>
    </mso:sharedControls>
   </mso:qat>
  </mso:ribbon>
 </mso:customUI>
'@
</code>```

the following Powershell commands would remove all mso:control nodes with visible="false":

```<code>using namespace System.Xml.Linq

Add-Type -Assembly System.Xml.Linq

$xmlCode = "<<as shown above>>"

$xRoot = [XDocument]::Parse($xmlCode)
$msoNs = [XNamespace]::get("http://schemas.microsoft.com/office/2009/07/customui")
$DeleteNodes = $xRoot.Descendants($msoNs + "control").where{$_.Attribute("visible").Value -eq "false"}
$DeleteNodes.ForEach{$_.Remove()}
$xRoot.ToString()

# Save the new xml
$XmlPath = [System.IO.Path]::GetTempFileName()
$xRoot.Save($XmlPath)
</code>```

XDocument has a Load() method for loading a xml file directly so there is no need to use the Parse() method (I was using for the sake of this example).

The only small drawback comparing to [xml] is that you have to consider namespaces.

Body:
friends.  I want to check every of my company users' outlook customUI configuration file. Delete 2 UI buttons if any. I am trying to do it by powershell. But failed to do so. Any advice for my script?

Below is the XML content of olkexpplorer.officeUI. I need to check & delete the items in blockquotes in case they are existed in the configuration file.

<mso:customUI xmlns:x1="Microsoft.Forefront.SpamReporterAddin.Connect" xmlns:mso="http://schemas.microsoft.com/office/2009/07/customui">
  <mso:ribbon>
    <mso:qat />
    <mso:tabs>
      <mso:tab idQ="mso:TabMail">
      <mso:group id="mso_c1.45620CF" label="Phishing Report" imageMso="TrustCenter" autoScale="true"
      <mso:control idQ="x1:ExplorerPhishReportMenuButton" imageMso="TrustCenter" visible="true"/>
      </mso:group>

>     <mso:group id="mso_c2.14817EBA" label="Junk" autoScale="true">
>        <mso:control idQ="x1:ExplorerSpamReportMenuButton" visible="true" />
>        <mso:control idQ="x1:ExplorerPhishReportMenuButton" imageMso="GreenBall" visible="true" />
>     </mso:group>

      </mso:tab>
    </mso:tabs>
  </mso:ribbon>
</mso:customUI>

Here is my script

$input = [xml](Get-Content -Path “$path_to_office\olkexplorer.officeUI”)
$deletenames="mso_c2.14817EBA"
($input.customUI.ChildNodes |Where-object { $deletenames -contains $_.Name}) | ForEach-
   Object{[void]$_.ParentNode.RemoveChild($_)}
$input.save(“$path_to_office\new.officeUI”)

Body:
The problem with your approach is that ChildNodes() only returns the immediate child nodes and not all child nodes (and using $input as a variable name is not considered a good practice anyway because its a reserved variable name).

So instead of ChildNodes() I would access the child node directly like so

$input.customUI.ribbon.tabs.tab.group | where-object { $DeleteNames -contains $_.id}

I would prefer the System.Xml.Linq classes like XDocument and XElement over the [xml] type alias because they make dealing with Xml inside a PowerShell script a little more convenient.

if this is the input xml:

$XmlCode = @'
 <mso:customUI xmlns:mso="http://schemas.microsoft.com/office/2009/07/customui">
  <mso:ribbon>
   <mso:qat><mso:sharedControls>
    <mso:control idQ="mso:FileNewDefault" visible="false"/>
    <mso:control idQ="mso:FileOpen" visible="false"/>
    <mso:control idQ="mso:FileSave" visible="true"/>
    <mso:control idQ="mso:FileSendAsAttachment" visible="false"/>
     <mso:control idQ="mso:FilePrintQuick" visible="false"/>
     <mso:control idQ="mso:SpellingAndGrammar" visible="false"
      insertBeforeQ="mso:PrintPreviewAndPrint"/>
     <mso:control idQ="mso:Undo" visible="true"
      insertBeforeQ="mso:PrintPreviewAndPrint"/>
     <mso:control idQ="mso:RedoOrRepeat" visible="true"
      insertBeforeQ="mso:PrintPreviewAndPrint"/>
     <mso:control idQ="mso:TableDrawTable" visible="false"
      insertBeforeQ="mso:PrintPreviewAndPrint"/>
     <mso:control idQ="mso:FileOpenRecentFile" visible="false"
      insertBeforeQ="mso:PrintPreviewAndPrint"/>
     <mso:control idQ="mso:FontDialog" visible="true"
      insertBeforeQ="mso:PrintPreviewAndPrint"/>
     <mso:control idQ="mso:FontSizeDecreaseWord" visible="true"
      insertBeforeQ="mso:PrintPreviewAndPrint"/>
     <mso:control idQ="mso:FontSize" visible="true"
      insertBeforeQ="mso:PrintPreviewAndPrint"/>
     <mso:control idQ="mso:PageSetupDialog" visible="true"
      insertBeforeQ="mso:PrintPreviewAndPrint"/>
     <mso:control idQ="mso:PrintPreviewAndPrint" visible="true"/>
    </mso:sharedControls>
   </mso:qat>
  </mso:ribbon>
 </mso:customUI>
'@

the following Powershell commands would remove all mso:control nodes with visible="false":

using namespace System.Xml.Linq

Add-Type -Assembly System.Xml.Linq

$xmlCode = "<<as shown above>>"

$xRoot = [XDocument]::Parse($xmlCode)
$msoNs = [XNamespace]::get("http://schemas.microsoft.com/office/2009/07/customui")
$DeleteNodes = $xRoot.Descendants($msoNs + "control").where{$_.Attribute("visible").Value -eq "false"}
$DeleteNodes.ForEach{$_.Remove()}
$xRoot.ToString()

# Save the new xml
$XmlPath = [System.IO.Path]::GetTempFileName()
$xRoot.Save($XmlPath)

XDocument has a Load() method for loading a xml file directly so there is no need to use the Parse() method (I was using for the sake of this example).

The only small drawback comparing to [xml] is that you have to consider namespaces.


来源: stackexchange

问:
Bootstrap collapse not collapsing element
I just implement the code of collapse from w3schools (light code than the bootstrap website .. I've tried this one also) and the collapse element isn't displayed

I'm using angular 9, bootstrap 4 and I've installed JQuery

here is the code :

```<code><p>
    <button class="btn btn-info m-3" type="button">Add Invoice</button>
    <button class="btn btn-primary m-3" type="button" data-toggle="collapse" data-target="#searchBloc">
         Search
    </button>
</p>
<div class="collapse" id="searchBloc">
    <div class="card card-body">
           Search Form
    </div>
</div>
</code>```

i've add the jquery cdn in my index.html :

```<code><script src="https://code.jquery.com/jquery-3.5.1.min.js"
         integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0="
         crossorigin="anonymous">
</script>
</code>```

答: Just don't. Angular already have its own tools and you should avoid using jquery inside because it could not work as expected. For something like a collapse function, you can find plenty of npm package that will provide you this functionality and that are probably lighter than bootstrap. Just make a quick search on internet with npm as keywords and you'll find what you need.

ContentLicense: CC BY-SA 4.0

Body:
I just implement the code of collapse from w3schools (light code than the bootstrap website .. I've tried this one also) and the collapse element isn't displayed

I'm using angular 9, bootstrap 4 and I've installed JQuery

here is the code :

    <button class="btn btn-info m-3" type="button">Add Invoice</button>
    <button class="btn btn-primary m-3" type="button" data-toggle="collapse" data-target="#searchBloc">
         Search
    </button>

           Search Form

i've add the jquery cdn in my index.html :


问:
Angular8 node js and npm installation problems
I'm learning angular js. For this  I've install nodejs  and git. And I've run following command on CMD:

```<code>  npm install -g @angular/cli@latest
</code>```

After some time following error occurred

```<code>npm WARN rollback Rolling back @schematics/angular@8.3.21 failed (this is
probably harmless): EPERM: operation not permitted, lstat 'C:\Users\User
Name\AppData\Roaming\npm\node_modules\@angular\cli\node_modules\@schematics'
npm ERR! code EEXIST
npm ERR! path C:\Users\User
Name\AppData\Roaming\npm\node_modules\@angular\cli\bin\ng
npm ERR! dest C:\Users\User Name\AppData\Roaming\npm\ng.ps1
npm ERR! EEXIST: file already exists, cmd shim 'C:\Users\Chaitanya
Kulkarni\AppData\Roaming\npm\node_modules\@angular\cli\bin\ng' ->
'C:\Users\Chaitanya Kulkarni\AppData\Roaming\npm\ng.ps1'
npm ERR! File exists: C:\Users\User Name\AppData\Roaming\npm\ng.ps1
npm ERR! Remove the existing file and try again, or run npm
npm ERR! with --force to overwrite files recklessly.
npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\User Name\AppData\Roaming\npm-cache\_logs\2020-01-
04T12_12_30_922Z-debug.log
</code>```

Can you please explain what is that error and how I could solve this. I am using Window 10.

答:
Try to run following command in terminal

npm install -g @angular/cli@latest --force

Body:
I'm learning angular js. For this  I've install nodejs  and git. And I've run following command on CMD:

  npm install -g @angular/cli@latest

After some time following error occurred

npm WARN rollback Rolling back @schematics/angular@8.3.21 failed (this is
probably harmless): EPERM: operation not permitted, lstat 'C:\Users\User
Name\AppData\Roaming\npm\node_modules\@angular\cli\node_modules\@schematics'
npm ERR! code EEXIST
npm ERR! path C:\Users\User
Name\AppData\Roaming\npm\node_modules\@angular\cli\bin\ng
npm ERR! dest C:\Users\User Name\AppData\Roaming\npm\ng.ps1
npm ERR! EEXIST: file already exists, cmd shim 'C:\Users\Chaitanya
Kulkarni\AppData\Roaming\npm\node_modules\@angular\cli\bin\ng' ->
'C:\Users\Chaitanya Kulkarni\AppData\Roaming\npm\ng.ps1'
npm ERR! File exists: C:\Users\User Name\AppData\Roaming\npm\ng.ps1
npm ERR! Remove the existing file and try again, or run npm
npm ERR! with --force to overwrite files recklessly.
npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\User Name\AppData\Roaming\npm-cache\_logs\2020-01-
04T12_12_30_922Z-debug.log

Can you please explain what is that error and how I could solve this. I am using Window 10.


答:
Here's a fairly straightforward way using reshape2::melt and dplyr:

```<code>library(dplyr)
library(reshape2)

melt(table(df$Date, df$Agent)) %>%
  filter(value == 0) %>%
  select(Date = Var1, Agent = Var2, -value)
#>         Date Agent
#> 1 2020-02-11     B
#> 2 2020-02-13     B
#> 3 2020-02-14     B
#> 4 2020-02-12     C
#> 5 2020-02-13     C

</code>```

Data

```<code>df <- structure(list(Date = structure(c(18302, 18303, 18304, 18305,
18306, 18302, 18304, 18302, 18303, 18306), class = "Date"), Agent = c("A",
"A", "A", "A", "A", "B", "B", "C", "C", "C")), row.names = c(NA,
-10L), class = "data.frame")
</code>```

Title: Extract rows from dataframe which were absent on certain days

Body:
I have a dataframe:

Date          Agent
2020-02-10    A
2020-02-11    A
2020-02-12    A
2020-02-13    A
2020-02-14    A
2020-02-10    B
2020-02-12    B
2020-02-10    C
2020-02-11    C
2020-02-14    C

I want to get a data frame with those row which were absent at certain days from 2020-02-10 to 2020-02-14. So desired output is:

Agent  Days_absent
B      2020-02-11; 2020-02-13; 2020-02-14
C      2020-02-12; 2020-02-13

or

Date          Agent
2020-02-11    B
2020-02-13    B
2020-02-14    B
2020-02-12    C
2020-02-13    C

How could i do that?

Body:
Here's a fairly straightforward way using reshape2::melt and dplyr:

library(dplyr)
library(reshape2)

melt(table(df$Date, df$Agent)) %>%
  filter(value == 0) %>%
  select(Date = Var1, Agent = Var2, -value)
#>         Date Agent
#> 1 2020-02-11     B
#> 2 2020-02-13     B
#> 3 2020-02-14     B
#> 4 2020-02-12     C
#> 5 2020-02-13     C

Data

df <- structure(list(Date = structure(c(18302, 18303, 18304, 18305,
18306, 18302, 18304, 18302, 18303, 18306), class = "Date"), Agent = c("A",
"A", "A", "A", "A", "B", "B", "C", "C", "C")), row.names = c(NA,
-10L), class = "data.frame")


问:
How to copy notebooks between different Sagemaker instances?
My search didn't yield anything useful so I was wondering if there is any easy way to copy notebooks from one instance to another instance on Sagemaker? Of course other than manually downloading the notebooks on one instance and uploading to the other one!</p>

答:
an easy way to transfer can be to tar (zip like) the file on one instance and download. Upload in the new instance and then untar.

tar --help


问:
java to firebase real time database
I have a question.

We received data from sensors through Arduino.

Then Arduino sent the data to Java.

And I want to send that data from Java to "Firebase realtime database."

To read data from Firebase, it was printed by switching to json string.

I want to know how to link the database to 'Firebase realtime database' from Java.

答:
Firebase has a Admin SDK for Java, which you can use in trusted environments. If your setup is a trusted environment, see: https://firebase.google.com/docs/database/admin/start

If it isn't a trusted environment, there is no Java SDK from Firebase. In that case the best solution would be to access the Realtime Database through its REST API, which is documented here: https://firebase.google.com/docs/database/rest/start

Title: java to firebase real time database


问:
How to replace part of string by position?
I have this string: ABCDEFGHIJ

I need to replace from position 4 to position 5 with the string ZX

It will look like this: ABCZXFGHIJ

But not to use with string.replace("DE","ZX") - I need to use with position

How can I do it?

答:
Here is a simple extension method:

    public static class StringBuilderExtensions
    {
        public static StringBuilder Replace(this StringBuilder sb, int position, string newString)
            => sb.Replace(position, newString.Length, newString);

        public static StringBuilder Replace(this StringBuilder sb, int position, int length, string newString)
            => (newString.Length <= length)
                ? sb.Remove(position, newString.Length).Insert(position, newString)
                : sb.Remove(position, length).Insert(position, newString.Substring(0, length));
    }
```

<p>Use it like this:</p>

<pre class="lang-cs prettyprint-override"><code>var theString = new string(' ', 10);
var sb = new StringBuilder(theString);
sb.Replace(5, "foo");
return sb.ToString();
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Here is a simple extension method:

    public static class StringBuilderExtensions
    {
        public static StringBuilder Replace(this StringBuilder sb, int position, string newString)
            => sb.Replace(position, newString.Length, newString);

        public static StringBuilder Replace(this StringBuilder sb, int position, int length, string newString)
            => (newString.Length <= length)
                ? sb.Remove(position, newString.Length).Insert(position, newString)
                : sb.Remove(position, length).Insert(position, newString.Substring(0, length));
    }

Use it like this:

var theString = new string(' ', 10);
var sb = new StringBuilder(theString);
sb.Replace(5, "foo");
return sb.ToString();


问:
Eclipse 2019-06 - Won't Run without Administrator Priviliges (Win10)
I'm trying to get this comparatively newer version of Eclipse running at work. However, here's what's happening when I try running eclipse.exe without running it as Administrator. Note: Running as Administrator works beautifully, but this is not a permanent solution, because I won't be able to permanently attain Admin priviliges.

Now, if I use the command line argument -configuration, Eclipse will start, but when I try to access OR create an entirely new workspace, I'm getting a similar error about being able to write to a directory.

I've tried numerous solutions for this problem, but nothing has worked. I hope someone out there has some suggestions.

Thanks so much!

答: We ended up having to wipe out my local Windows profile, and I was finally able to install Eclipse. Not ideal, but it got the job done.</p>


问:
How to make Screen Background Data visible in swift?
I want to make the screen like the following.

In source class, I write this code and push to side menu controller.

```<code>let vc = self.storyboard?.instantiateViewController(withIdentifier: "SidemenuController")as! SidemenuController

self.navigationController?.pushViewController(vc, animated: false)
</code>```

I write the following code in destination controller view did load method but just color opacity is decreased data is not visible.

```<code>override func viewDidLoad() {
    self.view.backgroundColor = self.hexStringToUIColor(hex: "BE8790").withAlphaComponent(0.4)
}
</code>```

答:
Instead of using .withAlphaComponent(0.4)

Try this  Adjust the number as needed

```<code>self.view.alpha = 0.5
</code>```

Body:
I want to make the screen like the following.

In source class, I write this code and push to side menu controller.

let vc = self.storyboard?.instantiateViewController(withIdentifier: "SidemenuController")as! SidemenuController

self.navigationController?.pushViewController(vc, animated: false)

I write the following code in destination controller view did load method but just color opacity is decreased data is not visible.

override func viewDidLoad() {
    self.view.backgroundColor = self.hexStringToUIColor(hex: "BE8790").withAlphaComponent(0.4)
}

Body:
Instead of using .withAlphaComponent(0.4)

Try this  Adjust the number as needed

self.view.alpha = 0.5


问:
javascript check if dictionary
I have a simple program like:

```<code>var a = {'a': 1, 'b': 2}
console.log(a)
console.log(a instanceof Array)
console.log(a.constructor instanceof Array)
</code>```

Here the value of a is a dictionary. I want to check for it.

How can I check it in javascript? Both tests above give me false result.

答:
Would that work ?

```<code>function isDictObj(obj: any) {
  try {
    const test = {...obj}
  } catch(err) {
    return false
  }
  return true
}
</code>```

My logic is that if it is a dictionnary object (key:values), then using spread operator with {} should work, otherwise throw an exception

Title: javascript check if dictionary

Body:
I have a simple program like:

var a = {'a': 1, 'b': 2}
console.log(a)
console.log(a instanceof Array)
console.log(a.constructor instanceof Array)

Here the value of a is a dictionary. I want to check for it.

How can I check it in javascript? Both tests above give me false result.

Body:
Would that work ?

function isDictObj(obj: any) {
  try {
    const test = {...obj}
  } catch(err) {
    return false
  }
  return true
}

My logic is that if it is a dictionnary object (key:values), then using spread operator with {} should work, otherwise throw an exception


问:
WCF chokes on properties with no "set ". Any workaround?
I have some class that I'm passing as a result of a service method, and that class has a get-only property:

```<code>[DataContract]
public class ErrorBase
{
  [DataMember]
  public virtual string Message { get { return ""; } }
}
</code>```

I'm getting an exception on service side:

System.Runtime.Serialization.InvalidDataContractException:  No set
  method for property 'Message' in type 'MyNamespace.ErrorBase'.

I have to have this property as only getter, I can't allow users to assign it a value. Any workaround I could use? Or am I missing some additional attribute?

答: If your serializer is of type DataContractJsonSerializer (or any DataContractSerializer) you can also use DataContractSerializerSettings in the constructor, with the SerializeReadOnlyTypes property set to true.

Body:
I have some class that I'm passing as a result of a service method, and that class has a get-only property:

[DataContract]
public class ErrorBase
{
  [DataMember]
  public virtual string Message { get { return ""; } }
}

I'm getting an exception on service side:

System.Runtime.Serialization.InvalidDataContractException:  No set
  method for property 'Message' in type 'MyNamespace.ErrorBase'.

I have to have this property as only getter, I can't allow users to assign it a value. Any workaround I could use? Or am I missing some additional attribute?


问:
Eclipse takes too long to start Program Execution
When I click the "Run" button or the F11 key to start a program execution it takes around 8-10 seconds to start the actual execution.

So considering the following same code

```<code>public class Demo {
    public static void main(String[] args) {
        System.out.println("Hello World");
    }
}
</code>```

After clicking the "Run" button or the F11 key it prints "Hello World" after 8-10 seconds. For bigger programs once the execution has started it runs fairly quick. But the initial starting is the only issue

I am using "Eclipse IDE for Java Developers"
Version: 2020-03 (4.15.0)

Have only a minimal set of plugins and infact tried disabling the Mylyn plugin as well but to no avail

答:
Found the issue. It was Dynatrace agent that was causing the problem.

Thanks to @howlger for directing to execute via the "Show Command Line" on the command line, which established the fact that the issue was not caused by Eclipse.

Running the java command with -verbose flag showed the following 3 jars getting loaded

[Opened
  C:/PROGRA~2/DYNATR~1/oneagent/agent/bin/1.175.224.20190905-115725/any/oneagentjava.jar]

[Opened
  C:/PROGRA~2/DYNATR~1/oneagent/agent/bin/1.175.224.20190905-115725/any/oneagentjava.rmi.jar]

[Opened
  C:/PROGRA~2/DYNATR~1/oneagent/agent/bin/1.175.224.20190905-115725/any/oneagentjava.sql.jar]

And then uninstalling the Dynatrace Agent did the trick

Now the program execution starts immediately from command prompt as well as Eclipse

Body:
When I click the "Run" button or the F11 key to start a program execution it takes around 8-10 seconds to start the actual execution.

So considering the following same code

public class Demo {
    public static void main(String[] args) {
        System.out.println("Hello World");
    }
}

After clicking the "Run" button or the F11 key it prints "Hello World" after 8-10 seconds. For bigger programs once the execution has started it runs fairly quick. But the initial starting is the only issue

I am using "Eclipse IDE for Java Developers"
Version: 2020-03 (4.15.0)

Have only a minimal set of plugins and infact tried disabling the Mylyn plugin as well but to no avail


问:
Angular function relies on result of async function

Setup:

I have a function, isAuthorized(), in a singleton, AuthSessionSingleton which relies on the result of an async function.

The async function is an api call, called in the constructor, which expects the return of an object. isAuthorized() relies on that object.

Issue:

Some component calls the function isAuthorized() immediately, before the backend call resolves.
I want to be able to wait inside the isAuthorized() function until the backend call resolves and the object is no longer null.

Simple Code:

//auth.singleton.ts
@Injectable({providedIn: 'root'})
export class AuthSessionSingleton {
  userInfo: UserInfo = null;
  constructor(private service: MyService) {
    this.loadUserInfo();
  }

  loadUserInfo() {
    this.service.makeBackendCall().subscribe({
      next: (obj: UserInfo) => {
        this.userInfo = obj;
      }
    });
  }

  isAuthorized() {
    if(this.userInfo == null) {
      // do something to wait asynchronously
    }

    // Very simple example
    if(this.userInfo.Role == 'Admin') {
      return true;
    }
    return false;
  }
}
```
<pre class="lang-js prettyprint-override"><code>//some.component.ts
export class SomeComponent {
  authorized: boolean = false;

  constructor(private auth: AuthSessionSingleton) {
    this.checkAuthorization();
  }

  async checkAuthorization() {
    this.authorized = await this.auth.isAuthorized();
  }
}
</code>```

In the above simplified program, SomeComponent calling isAuthorized() will likely check userInfo while it is still null. I need to wait for it to not be null.

Possible Solutions:

There are many solutions I've determined so far. I'm looking for the most correct solution and hopefully one that I haven't even thought of.

1. Listen to Subscription

In isAuthorized(), if(this.userInfo==null) subscribe to the same subscription made in loadUserInfo() and wait on it.

2. Wait Until Signaled

I could create a Subject in AuthSessionSingleton and Subscribe from SomeComponent, wait until I get a signal, then call IsAuthorized().

This seems especially roundabout.

3. Just Wait

There are many ways I could just spin my gears until the object I need is no longer null.

while(this.userInfo == null) {
  // do something
}
```
<hr />
<h1>Request:</h1>
<p>I want a way to wait asynchronously in <code>isAuthorized()</code> until <code>this.userInfo != null</code>. Any number of calls can be made to <code>isAuthorized()</code> (from different components) and all of them should wait until that value is resolved.</p>
<p>Any ideas?</p>
<hr />
<h1>Edit</h1>
<p>A more accurate use-case which I now realize changes the possible solutions follows. It is made more complex by accepting an array of values to loop through.</p>
<pre class="lang-js prettyprint-override"><code>isAuthorized(roles: string[]) {
  let(i = 0; i < roles.length; i++) {
    let role = roles[i];
    if(this.userInfo.Role == role) {
      return true;
    }
    return false;
  }
}
</code>```

答:
The below code will make sure that your app initialized only after your loadUserInfo is complete. So other components will only call isAuthenticated when app will initialize and your userinfo is already there.

In your AppModule have this :-

```<code>{
      provide: APP_INITIALIZER,
      useFactory: init_app,
      deps: [AuthSessionSingleton],
      multi: true
 }

 export function init_app(authService: SessionService) {
  return () => authService.loadUserInfo();
 }
</code>```

Change your AuthSessionSingleton :-

```<code>@Injectable({providedIn: 'root'})
export class AuthSessionSingleton {

  constructor(private service: MyService) {
  }

  loadUserInfo() {
    return this.service.makeBackendCall().pipe(map((obj: UserInfo) => {
        this.userInfo.next(obj);
    })).toPromise();
  }

   isAuthorized() {
      if(this.userInfo == null) {
          // do something to wait asynchronously
      }

      // Very simple example
      if(this.userInfo.Role == 'Admin') {
        return true;
      }
      return false;
   }
}
</code>```

Body:
Setup:

I have a function, isAuthorized(), in a singleton, AuthSessionSingleton which relies on the result of an async function.

The async function is an api call, called in the constructor, which expects the return of an object. isAuthorized() relies on that object.

Issue:

Some component calls the function isAuthorized() immediately, before the backend call resolves.
I want to be able to wait inside the isAuthorized() function until the backend call resolves and the object is no longer null.

Simple Code:

//auth.singleton.ts
@Injectable({providedIn: 'root'})
export class AuthSessionSingleton {
  userInfo: UserInfo = null;
  constructor(private service: MyService) {
    this.loadUserInfo();
  }

  loadUserInfo() {
    this.service.makeBackendCall().subscribe({
      next: (obj: UserInfo) => {
        this.userInfo = obj;
      }
    });
  }

  isAuthorized() {
    if(this.userInfo == null) {
      // do something to wait asynchronously
    }

    // Very simple example
    if(this.userInfo.Role == 'Admin') {
      return true;
    }
    return false;
  }
}

//some.component.ts
export class SomeComponent {
  authorized: boolean = false;

  constructor(private auth: AuthSessionSingleton) {
    this.checkAuthorization();
  }

  async checkAuthorization() {
    this.authorized = await this.auth.isAuthorized();
  }
}

In the above simplified program, SomeComponent calling isAuthorized() will likely check userInfo while it is still null. I need to wait for it to not be null.

Possible Solutions:

There are many solutions I've determined so far. I'm looking for the most correct solution and hopefully one that I haven't even thought of.

1. Listen to Subscription

In isAuthorized(), if(this.userInfo==null) subscribe to the same subscription made in loadUserInfo() and wait on it.

2. Wait Until Signaled

I could create a Subject in AuthSessionSingleton and Subscribe from SomeComponent, wait until I get a signal, then call IsAuthorized().

This seems especially roundabout.

3. Just Wait

There are many ways I could just spin my gears until the object I need is no longer null.

while(this.userInfo == null) {
  // do something
}

Request:

I want a way to wait asynchronously in isAuthorized() until this.userInfo != null. Any number of calls can be made to isAuthorized() (from different components) and all of them should wait until that value is resolved.

Any ideas?

Edit

A more accurate use-case which I now realize changes the possible solutions follows. It is made more complex by accepting an array of values to loop through.

isAuthorized(roles: string[]) {
  let(i = 0; i < roles.length; i++) {
    let role = roles[i];
    if(this.userInfo.Role == role) {
      return true;
    }
    return false;
  }
}

Body:
The below code will make sure that your app initialized only after your loadUserInfo is complete. So other components will only call isAuthenticated when app will initialize and your userinfo is already there.

In your AppModule have this :-

{
      provide: APP_INITIALIZER,
      useFactory: init_app,
      deps: [AuthSessionSingleton],
      multi: true
 }

 export function init_app(authService: SessionService) {
  return () => authService.loadUserInfo();
 }

Change your AuthSessionSingleton :-

@Injectable({providedIn: 'root'})
export class AuthSessionSingleton {

  constructor(private service: MyService) {
  }

  loadUserInfo() {
    return this.service.makeBackendCall().pipe(map((obj: UserInfo) => {
        this.userInfo.next(obj);
    })).toPromise();
  }

   isAuthorized() {
      if(this.userInfo == null) {
          // do something to wait asynchronously
      }

      // Very simple example
      if(this.userInfo.Role == 'Admin') {
        return true;
      }
      return false;
   }
}


问:
How to loop a menu if wrong selection occurred
I am trying to loop a menu when the user insert wrong choice:

```<code>public static void main(String[] args) {

    Scanner YourChoice = new Scanner(System.in);

    System.out.println("+-------------------------+");
    System.out.println("|        Welcome          |");
    System.out.println("|    To this program      |");
    System.out.println("+-------------------------+");
    System.out.println();

    System.out.println("Please Choose your preference: ");
    System.out.println();
    System.out.println("Press 1 - Test1");
    System.out.println("Press 2 - Test2");
    System.out.println("Press 3 - Test3");
    System.out.println("Press 0 - Exit");

    System.out.println();
    System.out.print("Your Choice is: ");
    int CHOICE = YourChoice.nextInt();

    if (CHOICE == 1) {
        System.out.println("You want Test1");
    }
    else if (CHOICE == 2) {
        System.out.println("You want Test2");
    }
    else if (CHOICE == 3) {
        System.out.println("You want Test3");
    }
    else if (CHOICE == 0) {
        System.out.println("You want Exit");
    }
    else {
        System.out.println("Wrong Input, please try again");

    }
</code>```

What I want is, if a user inserted wrong number, then the menu should start again, until the user enters a correct value (0 to 3).
I am not sure where and how to put the while loop,
Could you please clarify it?

答:
Use only while and switch-case in your program.

You can try the below code. It runs successfully.

```<code>import java.util.*;
public class Main
{
    public static void main(String[] args) {

        System.out.println("+-------------------------+");
        System.out.println("|        Welcome          |");
        System.out.println("|    To this program      |");
        System.out.println("+-------------------------+");
        System.out.println();

        Scanner yourChoice = new Scanner(System.in);
        int choice ;
        boolean tryAgain = true;

        while (tryAgain){

            System.out.println("Please Choose your preference: ");
            System.out.println();
            System.out.println("Press 1 - Test1");
            System.out.println("Press 2 - Test2");
            System.out.println("Press 3 - Test3");
            System.out.println("Press 0 - Exit");
            System.out.println();
            choice = yourChoice.nextInt();
            System.out.print("\nYour Choice is : " +choice + "\n");

            switch(choice){
                case 1 :
                    System.out.println("You want Test1");
                    tryAgain = false;
                    break;
                case 2 :
                    System.out.println("You want Test2");
                    tryAgain = false;
                    break;
                case 3 :
                    System.out.println("You want Test3");
                    tryAgain = false;
                    break;
                case 0 :
                    System.out.println("You want exit");
                    tryAgain = false;
                    break;
                default :
                    System.out.println("Wrong Input, please try again");
            }

        }

    }
}
</code>```

Body:
I am trying to loop a menu when the user insert wrong choice:

public static void main(String[] args) {

    Scanner YourChoice = new Scanner(System.in);

    System.out.println("+-------------------------+");
    System.out.println("|        Welcome          |");
    System.out.println("|    To this program      |");
    System.out.println("+-------------------------+");
    System.out.println();

    System.out.println("Please Choose your preference: ");
    System.out.println();
    System.out.println("Press 1 - Test1");
    System.out.println("Press 2 - Test2");
    System.out.println("Press 3 - Test3");
    System.out.println("Press 0 - Exit");

    System.out.println();
    System.out.print("Your Choice is: ");
    int CHOICE = YourChoice.nextInt();

    if (CHOICE == 1) {
        System.out.println("You want Test1");
    }
    else if (CHOICE == 2) {
        System.out.println("You want Test2");
    }
    else if (CHOICE == 3) {
        System.out.println("You want Test3");
    }
    else if (CHOICE == 0) {
        System.out.println("You want Exit");
    }
    else {
        System.out.println("Wrong Input, please try again");

    }

What I want is, if a user inserted wrong number, then the menu should start again, until the user enters a correct value (0 to 3).
I am not sure where and how to put the while loop,
Could you please clarify it?

Body:
Use only while and switch-case in your program.

You can try the below code. It runs successfully.

import java.util.*;
public class Main
{
    public static void main(String[] args) {

        System.out.println("+-------------------------+");
        System.out.println("|        Welcome          |");
        System.out.println("|    To this program      |");
        System.out.println("+-------------------------+");
        System.out.println();

        Scanner yourChoice = new Scanner(System.in);
        int choice ;
        boolean tryAgain = true;

        while (tryAgain){

            System.out.println("Please Choose your preference: ");
            System.out.println();
            System.out.println("Press 1 - Test1");
            System.out.println("Press 2 - Test2");
            System.out.println("Press 3 - Test3");
            System.out.println("Press 0 - Exit");
            System.out.println();
            choice = yourChoice.nextInt();
            System.out.print("\nYour Choice is : " +choice + "\n");

            switch(choice){
                case 1 :
                    System.out.println("You want Test1");
                    tryAgain = false;
                    break;
                case 2 :
                    System.out.println("You want Test2");
                    tryAgain = false;
                    break;
                case 3 :
                    System.out.println("You want Test3");
                    tryAgain = false;
                    break;
                case 0 :
                    System.out.println("You want exit");
                    tryAgain = false;
                    break;
                default :
                    System.out.println("Wrong Input, please try again");
            }

        }

    }
}


问:
"Fatal error: Uncaught Error: Cannot use object of type stdClass as array" while appending data to json payload
I need to append a new object to a JSON array using PHP.

The JSON:

```<code>{
   "maxSize":"3000",
   "thumbSize":"800",
   "loginHistory":[
   {
      "time": "1411053987",
      "location":"example-city"
   },
   {
      "time": "1411053988",
      "location":"example-city-2"
   }
]}
</code>```

The PHP so far:

```<code>$accountData = json_decode(file_get_contents("data.json"));
$newLoginHistory['time'] = "1411053989";
$newLoginHistory['location'] = "example-city-3";
array_push($accountData['loginHistory'],$newLoginHistory);
file_put_contents("data.json", json_encode($accountData));
</code>```

I keep getting:

Fatal error: Uncaught Error: Cannot use object of type stdClass as array

and null as the output for the "loginHistory" object upon saving the JSON file.

答:
This is a small and simple guide on how to modify a JSON file with PHP.

// Load the file
$contents = file_get_contents('data.json');

// Decode the JSON data into a PHP array.
$contentsDecoded = json_decode($contents, true);

// Create a new History Content.
$newContent = [
  'time'=> "1411053989",
  'location'=> "example-city-3"
];

// Add the new content data.
$contentsDecoded['loginHistory'][] = $newContent;

// Encode the array back into a JSON string.
$json = json_encode($contentsDecoded);

// Save the file.
file_put_contents('data.json', $json);
```

A step-by-step explanation of the code above.

We loaded the contents of our file. At this stage, it is a string that contains JSON data.

We decoded the string into an associative PHP array by using the function json_decode.
This allows us to modify the data.

We added new content to contentsDecoded variable.

We encoded the PHP array back into a JSON string using json_encode.

Finally, we modified our file by replacing the old contents of our file with the newly-created JSON string.

Body:
I need to append a new object to a JSON array using PHP.

The JSON:

{
   "maxSize":"3000",
   "thumbSize":"800",
   "loginHistory":[
   {
      "time": "1411053987",
      "location":"example-city"
   },
   {
      "time": "1411053988",
      "location":"example-city-2"
   }
]}

The PHP so far:

$accountData = json_decode(file_get_contents("data.json"));
$newLoginHistory['time'] = "1411053989";
$newLoginHistory['location'] = "example-city-3";
array_push($accountData['loginHistory'],$newLoginHistory);
file_put_contents("data.json", json_encode($accountData));

I keep getting:

Fatal error: Uncaught Error: Cannot use object of type stdClass as array

and null as the output for the "loginHistory" object upon saving the JSON file.

Body:
This is a small and simple guide on how to modify a JSON file with PHP.

// Load the file
$contents = file_get_contents('data.json');

// Decode the JSON data into a PHP array.
$contentsDecoded = json_decode($contents, true);

// Create a new History Content.
$newContent = [
  'time'=> "1411053989",
  'location'=> "example-city-3"
];

// Add the new content data.
$contentsDecoded['loginHistory'][] = $newContent;

// Encode the array back into a JSON string.
$json = json_encode($contentsDecoded);

// Save the file.
file_put_contents('data.json', $json);

A step-by-step explanation of the code above.

We loaded the contents of our file. At this stage, it is a string that contains JSON data.

We decoded the string into an associative PHP array by using the function json_decode.
This allows us to modify the data.

We added new content to contentsDecoded variable.

We encoded the PHP array back into a JSON string using json_encode.

Finally, we modified our file by replacing the old contents of our file with the newly-created JSON string.


问:
How to make User Input (STDIN) to move left and right in PERL - Unix Env
i'm a newbie in PERL. Whenever i tried to move left or right to delete characters in terminal it shows "^[[D^[[C^[[C^[[D". Is there a way to make User Input (STDIN) to scroll left and right to delete the data in PERL ?

i am looking for user to use keyboard arrows for example, to edit or correct what has just been typed without deleting the last entered characters with backspace.

Example code:
print  "What is your Fav Food?; $food= STDIN;

i want the readline to be flexible to delete the user entries.

答:
STDIN is a LINE input operator. You can change your input until you hit enter.

You probably want one of these:
https://www.cs.ait.ac.th/~on/O/oreilly/perl/prog3/ch02_11.htm


问:
Jfreechart - Refresh a chart according to changing data
I would like to know how to refresh a chart if we want to change "in live" some piece of data. I mean for instance, I have a chart with a TaskSeries which appears on 3 years and I would like to change 3 years by 5 years. I want the chart to change immediately.

Is there some kind of update chart or something like that ?

I know that you could say "get your TaskSeries, do your changes and it will be refreshed automatically" but my TaskSeries are generated and I cannot easily change these ones. That's why I would like to find a way to recalculate and to rebuild the whole chart.

答: The add() method of TaskSeries automatically sends a SeriesChangeEvent to all registered listeners, e.g. CategoryPlot. In this example, DynamicTimeSeriesCollection implements SeriesChangeEvent. In this case, the chart's XYPlot is a registered listener.


问:
Fsharp's Set seems to silently break
I have this simple code:

```<code>let httpSuccessCodes =
  Set.ofSeq [HttpStatusCode.OK; HttpStatusCode.NoContent]

let httpSuccess (httpSuccessCode:HttpStatusCode) =
  Console.WriteLine("{0}", httpSuccessCode)
  httpSuccessCodes.Contains httpSuccessCode
</code>```

Calling this code just silently exit the app, no error:

```<code>let isSuccess = httpSuccess stauscode
</code>```

Funny that it works in fsharpi. I am not sure why it breaks.

Update1:

The code that works:

```<code> let task = amazonS3client.GetACLAsync(getBucketAclRequest)
 task.Wait()
 let success = isHttpSuccess task.Result.HttpStatusCode
 if task.IsCompletedSuccessfully && success then
   Console.WriteLine("getBucketAcl finished successfully for bucket {0}", bucket)
   Some task.Result.AccessControlList
 else
   Console.Error.WriteLine("Could not get bucket acl: {0}", bucket)
   None
</code>```

Update2:

```<code>if ((Set.ofSeq [ HttpStatusCode.OK; HttpStatusCode.NoContent; ]).Contains task.Result.HttpStatusCode) then
  Console.WriteLine("1")

if (httpSuccessCodes.Contains task.Result.HttpStatusCode) then
  Console.WriteLine("2")

if (isHttpSuccess task.Result.HttpStatusCode) then
  Console.WriteLine("3")
</code>```

Output: 1

答: For some weird reason it matters which module the http status checking code lives. I was moving it into its own module and now it works.</p>

Title: Fsharp's Set seems to silently break

Body:
I have this simple code:

let httpSuccessCodes =
  Set.ofSeq [HttpStatusCode.OK; HttpStatusCode.NoContent]

let httpSuccess (httpSuccessCode:HttpStatusCode) =
  Console.WriteLine("{0}", httpSuccessCode)
  httpSuccessCodes.Contains httpSuccessCode

Calling this code just silently exit the app, no error:

let isSuccess = httpSuccess stauscode

Funny that it works in fsharpi. I am not sure why it breaks.

Update1:

The code that works:

 let task = amazonS3client.GetACLAsync(getBucketAclRequest)
 task.Wait()
 let success = isHttpSuccess task.Result.HttpStatusCode
 if task.IsCompletedSuccessfully && success then
   Console.WriteLine("getBucketAcl finished successfully for bucket {0}", bucket)
   Some task.Result.AccessControlList
 else
   Console.Error.WriteLine("Could not get bucket acl: {0}", bucket)
   None

Update2:

if ((Set.ofSeq [ HttpStatusCode.OK; HttpStatusCode.NoContent; ]).Contains task.Result.HttpStatusCode) then
  Console.WriteLine("1")

if (httpSuccessCodes.Contains task.Result.HttpStatusCode) then
  Console.WriteLine("2")

if (isHttpSuccess task.Result.HttpStatusCode) then
  Console.WriteLine("3")

Output: 1


问:
Cannot use jQuery in Laravel Blade file
I am trying to define my page specific Javascript in my blade file by defining a separate section for it in the file.  I can add the same jQuery code in the app.js file and it works without issue, but when I put it in the blade file I get an error of

```<code>Uncaught ReferenceError: $ is not defined
</code>```

Layout file - app.blade.php

```<code><!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <meta name="csrf-token" content="{{ csrf_token() }}">

    <title>{{ config('app.name', 'Laravel') }}</title>
    <script src="{{ asset('js/app.js') }}" defer></script>
    <link rel="dns-prefetch" href="https://fonts.gstatic.com">
    <link href="{{ asset('css/app.css') }}" rel="stylesheet">
</head>

<body class="fixed-nav sticky-footer bg-dark" id="page-top">
    <!-- Navigation-->
    <nav class="navbar navbar-expand-lg navbar-dark bg-dark fixed-top" id="mainNav">
        <!-- Nav Stuff -->
    </nav>
    <!--  End Navigation -->
    <!--  Body  -->
    <div class="content-wrapper">
        <div class="container-fluid">
            @yield('content')
        </div>
        <footer class="sticky-footer">
            <!-- footer stuff -->
        </footer>
    </div>
    @yield('script')
</body>
</html>
</code>```

Content Page - page1.blade.php

```<code>@extends('layouts.app')

@section('content')
<div class="container">
    <!--  Page Stuff -->
</div>
@endsection

@section('script')
<script>
    $(document).ready(function()
    {
        alert('hello world');
    });
</script>
@endsection
</code>```

I would prefer not to put all of my Javascript in the single app.js file, I would like to be able to use this section fine.  Straight Javascript works fine here, but the jQuery does not.

edit:

Here is the app.js file that includes the jQuery library.

```<code>require('jquery');
require('./bootstrap');
require('jquery-easing');

//  Administration Controller - Add System Type -> This code works just fine.
var numSysDataRows = 5;
$('#add-customer-information').click(function()
{
    $('#system-customer-information').append('<div class="form-group"><label for="col'+numSysDataRows+'">System Data:</label><input type="text" name="col[]" id="col'+numSysDataRows+'" class="form-control" /></div>');
    numSysDataRows++;
});
</code>```

If I look at the source code and check the app.js file from the web server, I do see that jQuery is loaded into the app.js file.

答:
Yes, I added jquery script tags
Jquery script tags</p>

Title: Cannot use jQuery in Laravel Blade file

Body:
I am trying to define my page specific Javascript in my blade file by defining a separate section for it in the file.  I can add the same jQuery code in the app.js file and it works without issue, but when I put it in the blade file I get an error of

Uncaught ReferenceError: $ is not defined

Layout file - app.blade.php

<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <meta name="csrf-token" content="{{ csrf_token() }}">

    <title>{{ config('app.name', 'Laravel') }}</title>

    <link rel="dns-prefetch" href="https://fonts.gstatic.com">
    <link href="{{ asset('css/app.css') }}" rel="stylesheet">

            @yield('content')

    @yield('script')

Content Page - page1.blade.php

@extends('layouts.app')

@section('content')

@endsection

@section('script')

@endsection

I would prefer not to put all of my Javascript in the single app.js file, I would like to be able to use this section fine.  Straight Javascript works fine here, but the jQuery does not.

edit:

Here is the app.js file that includes the jQuery library.

require('jquery');
require('./bootstrap');
require('jquery-easing');

//  Administration Controller - Add System Type -> This code works just fine.
var numSysDataRows = 5;
$('#add-customer-information').click(function()
{
    $('#system-customer-information').append('
System Data:<input type="text" name="col[]" id="col'+numSysDataRows+'" class="form-control" />
');
    numSysDataRows++;
});

If I look at the source code and check the app.js file from the web server, I do see that jQuery is loaded into the app.js file.


问:
React: onClick on Mobile (iPhone) requires 2 taps?
Video demonstrating issue

I have a bunch of clickable components that, when clicked, adds a "card" to a row. On desktop, it works fine, but on mobile (tested on iPhone, does not seem to be an issue for Android tablet), it requires 2 consecutive taps of the same button to fire the onClick function.

These components also have onMouseEnter/onMouseLeave effects on them, to control a global state, which in turn decides if several components should have additional CSS applied (so I can't make it a simple CSS hover effect).

I believe that the mouse effects are interfering with the click event, but I have no idea how I could fix that. Here is the relevant code for this component:

```<code>const CardSource = ({ addCard, note, setHoveredNote, hoveredNote }) => {
  return (
    <Source
      onClick={() => addCard(note)}
      onMouseEnter={() => setHoveredNote(note)}
      onMouseLeave={() => setHoveredNote(null)}
      className={
        hoveredNote && hoveredNote.index === note.index ? "highlight" : null
      }
    >
      {note.letters[0]}
    </Source>
  );
};
</code>```

Furthermore, once a button has been tapped twice, the hover effect CSS "sticks" to that button, and never moves to another button. This seems to happen on both iPhone and Android tablet. I would love to have this not happen anymore either.

I've created a working demonstration of this issue in a sandbox, which if viewed on mobile you should be able to recreate these issues: https://codesandbox.io/s/mobile-requires-2-taps-i9zri?file=/src/Components/CardSource/CardSource.js

答:
I remember having a similar problem. The issue was for me that the state of component does not change immediately, but only upon execution of the render() method. I believe you might have the same issue with asynchronicity for both effects you are describing.

The only render() call I see found in your code is in App.test.js, I usually place that in the respective component.tsx.

References

Submit button takes 2 clicks to call function in React

React.js events need 2 clicks to execute

Body:
Video demonstrating issue

I have a bunch of clickable components that, when clicked, adds a "card" to a row. On desktop, it works fine, but on mobile (tested on iPhone, does not seem to be an issue for Android tablet), it requires 2 consecutive taps of the same button to fire the onClick function.

These components also have onMouseEnter/onMouseLeave effects on them, to control a global state, which in turn decides if several components should have additional CSS applied (so I can't make it a simple CSS hover effect).

I believe that the mouse effects are interfering with the click event, but I have no idea how I could fix that. Here is the relevant code for this component:

const CardSource = ({ addCard, note, setHoveredNote, hoveredNote }) => {
  return (
    <Source
      onClick={() => addCard(note)}
      onMouseEnter={() => setHoveredNote(note)}
      onMouseLeave={() => setHoveredNote(null)}
      className={
        hoveredNote && hoveredNote.index === note.index ? "highlight" : null
      }
    >
      {note.letters[0]}
    </Source>
  );
};

Furthermore, once a button has been tapped twice, the hover effect CSS "sticks" to that button, and never moves to another button. This seems to happen on both iPhone and Android tablet. I would love to have this not happen anymore either.

I've created a working demonstration of this issue in a sandbox, which if viewed on mobile you should be able to recreate these issues: https://codesandbox.io/s/mobile-requires-2-taps-i9zri?file=/src/Components/CardSource/CardSource.js


问:
How to insert/update `ARRAY` column in Postgres using Bookshelf/Knex
I have a table in my Postgres database which contains a column with datatype ARRAY. I am using Bookshelf to perform operations on the database. Now, I want to insert/update (append new data to previous data in an array) data in this column and I could not find a way to do this. Can anybody guide me on how I can achieve this?
I think, one way of doing this could be using raw() function of Knex but I am not sure about how to use raw() function so please guide me on that too.
Thanks.

答:
UPDATE tableName
SET ColumnName = array_prepend( 'Value', ColumnName)
WHERE ColumnName = 'Value'

UPDATE tblTest
SET TestColumnName = array_prepend( 'TestData', TestColumnName)
WHERE TestColumnId = '1'
```


问:
Html ActionLink won't redirect me to another controller and view
I have a HomeController which I use to display items in a table from a text file, and each row has an Add | Edit | Delete action links. I have another controller called CategoryController which is responsible for creating and editing existing categories. The HomeController has an index.cshtml which contains those actions links. But when I click the edit link it has to call the Action in the CategoryController. But then I get the following error:

```<code>> Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable.  Please review the following URL and make sure that it is spelled correctly.
>
> Requested URL: /Home/Edit
</code>```

Here is my partial code for my action links (Index.cshtml):

```<code> @using ToDoList
 @model ToDoList.ViewModels.CategoryItemViewModel
 //Other codes
    <td>
                            @Html.ActionLink("Add", "Create", new { id = @cats.categoryID }) |
                            @Html.ActionLink("Edit", "Edit", "Category", new { id = @cats.categoryID }) |
                            @Html.ActionLink("Delete", "Delete", new { id = @cats.categoryID })
                        </td>
</code>```

Here is my code for the CategoryController ActionResult Edit function:

```<code>// GET: Category/Edit/5
        [Route("~/Category/Edit/{id}")]
        public ActionResult Edit(int id)
        {

            Category thisCategory = db.Cat.FirstOrDefault(category => category.categoryID == id);

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

EDIT: My RouteConfig.cs is as follows:

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;

namespace ToDoList
{
    public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );
        }
    }
}
</code>```

I have no idea why it does not redirect to the CategoryController and call the Edit action.

My file structure is as follows:

EDIT: My HomeController class is as follows:

```<code>using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ToDoList.Models;
using ToDoList.ViewModels;

namespace ToDoList.Controllers
{
    public class HomeController : Controller
    {
        // GET: Home
        //Reading in both text files
        List<Category> categories = new List<Category>();
        List<Item> it = new List<Item>();
        public ActionResult Index()
        {
            //CatData means CategoryData
            string CatData = System.IO.File.ReadAllText(Server.MapPath("~/Data/Categories.txt"));
            string ItemData = System.IO.File.ReadAllText(Server.MapPath("~/Data/Item.txt"));

            foreach (string rowInItem in ItemData.Split('\n')) {

                if (!string.IsNullOrEmpty(rowInItem)) {

                    it.Add(new Item {

                        itemName = rowInItem.Split(',')[0],
                        itemID = Convert.ToInt32(rowInItem.Split(',')[1]),
                        categoryID = Convert.ToInt32(rowInItem.Split(',')[2]),
                        check = rowInItem.Split(',')[3]
                    });
                }
            }
            foreach (string row in CatData.Split('\n')) {

                if (!string.IsNullOrEmpty(row)) {

                    categories.Add(new Category
                    {
                        categoryName = row.Split(',')[0],
                        categoryID = Convert.ToInt32(row.Split(',')[1]),

                    }) ;
                }
            }

            var categoryItemViewControler = new CategoryItemViewModel
            {
                Cat = categories,
                It = it
            };
            return View(categoryItemViewControler);
        }

    }
}
</code>```

EDIT: My CategoryItemViewModel is this:

```<code>using System;
using System.Collections.Generic;
using System.ComponentModel.Design;
using System.Linq;
using System.Web;
using ToDoList.Models;

namespace ToDoList.ViewModels
{
    public class CategoryItemViewModel
    {
        //For Category
        public List<Category> Cat { get; set; }
        //For Items
        public List<Item> It { get; set; }
    }
}
</code>```

EDIT: My Category.cs model class is as follows:

```<code>using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Web;

namespace ToDoList.Models
{
    public class Category
    {
        [Required]
        public string categoryName { get; set; }
        public int categoryID { get; set; }
        public List<Item> items { get; set; }
    }
}
</code>```

Any help or advice will be highly appreciated.

答: the Edit and the Index does not existe at the same folder, i think that you should use /category/edit as url</p>

Body:
I have a HomeController which I use to display items in a table from a text file, and each row has an Add | Edit | Delete action links. I have another controller called CategoryController which is responsible for creating and editing existing categories. The HomeController has an index.cshtml which contains those actions links. But when I click the edit link it has to call the Action in the CategoryController. But then I get the following error:

> Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable.  Please review the following URL and make sure that it is spelled correctly.
>
> Requested URL: /Home/Edit

Here is my partial code for my action links (Index.cshtml):

 @using ToDoList
 @model ToDoList.ViewModels.CategoryItemViewModel
 //Other codes

                            @Html.ActionLink("Add", "Create", new { id = @cats.categoryID }) |
                            @Html.ActionLink("Edit", "Edit", "Category", new { id = @cats.categoryID }) |
                            @Html.ActionLink("Delete", "Delete", new { id = @cats.categoryID })

Here is my code for the CategoryController ActionResult Edit function:

// GET: Category/Edit/5
        [Route("~/Category/Edit/{id}")]
        public ActionResult Edit(int id)
        {

            Category thisCategory = db.Cat.FirstOrDefault(category => category.categoryID == id);

            return View(thisCategory);
        }

EDIT: My RouteConfig.cs is as follows:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;

namespace ToDoList
{
    public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );
        }
    }
}

I have no idea why it does not redirect to the CategoryController and call the Edit action.

My file structure is as follows:

EDIT: My HomeController class is as follows:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ToDoList.Models;
using ToDoList.ViewModels;

namespace ToDoList.Controllers
{
    public class HomeController : Controller
    {
        // GET: Home
        //Reading in both text files
        List<Category> categories = new List<Category>();
        List<Item> it = new List<Item>();
        public ActionResult Index()
        {
            //CatData means CategoryData
            string CatData = System.IO.File.ReadAllText(Server.MapPath("~/Data/Categories.txt"));
            string ItemData = System.IO.File.ReadAllText(Server.MapPath("~/Data/Item.txt"));

            foreach (string rowInItem in ItemData.Split('\n')) {

                if (!string.IsNullOrEmpty(rowInItem)) {

                    it.Add(new Item {

                        itemName = rowInItem.Split(',')[0],
                        itemID = Convert.ToInt32(rowInItem.Split(',')[1]),
                        categoryID = Convert.ToInt32(rowInItem.Split(',')[2]),
                        check = rowInItem.Split(',')[3]
                    });
                }
            }
            foreach (string row in CatData.Split('\n')) {

                if (!string.IsNullOrEmpty(row)) {

                    categories.Add(new Category
                    {
                        categoryName = row.Split(',')[0],
                        categoryID = Convert.ToInt32(row.Split(',')[1]),

                    }) ;
                }
            }

            var categoryItemViewControler = new CategoryItemViewModel
            {
                Cat = categories,
                It = it
            };
            return View(categoryItemViewControler);
        }

    }
}

EDIT: My CategoryItemViewModel is this:

using System;
using System.Collections.Generic;
using System.ComponentModel.Design;
using System.Linq;
using System.Web;
using ToDoList.Models;

namespace ToDoList.ViewModels
{
    public class CategoryItemViewModel
    {
        //For Category
        public List<Category> Cat { get; set; }
        //For Items
        public List<Item> It { get; set; }
    }
}

EDIT: My Category.cs model class is as follows:

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Web;

namespace ToDoList.Models
{
    public class Category
    {
        [Required]
        public string categoryName { get; set; }
        public int categoryID { get; set; }
        public List<Item> items { get; set; }
    }
}

Any help or advice will be highly appreciated.


问:
Min and max values on livecharts cartesian chart wpf
I want to force the Y axis to be centered on 0 and I have to ensure that min and max values are the same.

I use the MinValue and MaxValue properties of the Axis but it doesn't work (note that there is usually a binding on those values but i changed them for this post).

```<code><lvc:CartesianChart.AxisY>
            <lvc:Axis Title="{Binding SelectedLine.Unit}"
                      LabelFormatter="{Binding Formatter}"
                      FontSize="14"
                      MinValue="-390000"
                      MaxValue="390000"
                      Foreground="{StaticResource GeneralForegroundColor}">
                <lvc:Axis.Separator>
                    <lvc:Separator Stroke="LightGray"

                                   StrokeThickness="1">
                        <lvc:Separator.StrokeDashArray>
                            <DoubleCollection>
                                <sys:Double>6</sys:Double>
                            </DoubleCollection>
                        </lvc:Separator.StrokeDashArray>
                    </lvc:Separator>
                </lvc:Axis.Separator>
                <lvc:Axis.Sections>
                    <lvc:AxisSection Value="0" StrokeThickness="1"  Stroke="Black">
                    </lvc:AxisSection>
                </lvc:Axis.Sections>
            </lvc:Axis>
        </lvc:CartesianChart.AxisY>
</code>```

The max value is not 390000 and I don't know how to do to force it

Max value not the one i'm expecting

答:
You have to calculate min/max when you add values to the chart.

It's best to add corresponding binding sources to your data model.

In case you are adding values dynamically you have to recalculate min/max. An most important, the data model must implement INotifyPropertyChanged and the properties MaxAxisValue and MinAxisValue must raise the INotifyPropertyChanged.PropertyChanged event:

```<code>class ChartModel
{
  public double MaxAxisValue { get; set; }
  public double MinAxisValue { get; set; }

  public ChartModel()
  {
    var chartValues = new ChartValues<double> { 10, 50, -3, -25 };
    this.MaxAxisValue = chartValues
      .Select(value => Math.Abs(value))
      .Max();
    this.MinAxisValue = this.MaxAxisValue * -1;

    this.SeriesCollection = new SeriesCollection
    {
      new ColumnSeries()
      {
        Title = "Series 1",
        Values = chartValues
      }
    };
  }
}
</code>```

View

```<code><Grid>
  <Grid.DataContext>
    <ChartModel />
  </Grid.DataContext>

  <wpf:CartesianChart Series="{Binding SeriesCollection}">
    <wpf:CartesianChart.AxisY>
      <wpf:Axis MaxValue="{Binding MaxAxisValue}"
                MinValue="{Binding MinAxisValue}">

        ...

      </wpf:Axis>
    </wpf:CartesianChart.AxisY>
  </wpf:CartesianChart>
</Grid>
</code>```

Update

It seems that your problem is related to the separators of the axis or their distribution.

First note that although the distribution is not even, the values of Axis.MinValue and Axis.MaxValue are still respected by the chart. It's just a visual discrepancy, which is introduced by the interval of the divisions.

By default the interval is calculated automatically. I guess the algorithm takes the decimal position of values into account. If max absolute value is 39, then the interval will be either 10^1 or (10^1)/2. In your case you have 390,000 which uses position 10^5. So the interval is set to either 100,000 or 50,000 depending on the range. The divisions start from the lower border e.g. -390,000. Applying the interval of 100,000 will get the highest possible division, which is lesser than or equal to max value (390,000), of 310,000.

This explains why you get the divisions ranging from -390,000 to 310,000.

To "fix" this, you have to decide the number of steps (or divisions) you want to have and set Separator.Step explicitly. Separator.Step is set to 0 by default, which enables the automatic interval calculations.

The basic formula would be

step = value_range / desired_divisions_count

I find the terminology used by LiveCharts quite irritating. I naturally would call the steps interval and the number of divisions steps. But apparently the designers had a different perception.

Let's say you want to have 10 divisions or grid lines. You would have to set Separator.Step="78000" because 78000 = (390,000 - (-390,000)) / 10.
This will distribute the divisions evenly, where min/max value will each fall on a division.

```<code><wpf:CartesianChart.AxisY>
  <wpf:Axis MaxValue="390000"
            MinValue="-390000">
    <wpf:Axis.Separator>
      <wpf:Separator Step="78000" />
    </wpf:Axis.Separator>
  </wpf:Axis>
</wpf:CartesianChart.AxisY>
</code>```

Body:
I want to force the Y axis to be centered on 0 and I have to ensure that min and max values are the same.

I use the MinValue and MaxValue properties of the Axis but it doesn't work (note that there is usually a binding on those values but i changed them for this post).

<lvc:CartesianChart.AxisY>
            <lvc:Axis Title="{Binding SelectedLine.Unit}"
                      LabelFormatter="{Binding Formatter}"
                      FontSize="14"
                      MinValue="-390000"
                      MaxValue="390000"
                      Foreground="{StaticResource GeneralForegroundColor}">
                <lvc:Axis.Separator>
                    <lvc:Separator Stroke="LightGray"

                                   StrokeThickness="1">
                        <lvc:Separator.StrokeDashArray>
                            <DoubleCollection>
                                <sys:Double>6</sys:Double>
                            </DoubleCollection>
                        </lvc:Separator.StrokeDashArray>
                    </lvc:Separator>
                </lvc:Axis.Separator>
                <lvc:Axis.Sections>
                    <lvc:AxisSection Value="0" StrokeThickness="1"  Stroke="Black">
                    </lvc:AxisSection>
                </lvc:Axis.Sections>
            </lvc:Axis>
        </lvc:CartesianChart.AxisY>

The max value is not 390000 and I don't know how to do to force it

Max value not the one i'm expecting

Body:
You have to calculate min/max when you add values to the chart.

It's best to add corresponding binding sources to your data model.

In case you are adding values dynamically you have to recalculate min/max. An most important, the data model must implement INotifyPropertyChanged and the properties MaxAxisValue and MinAxisValue must raise the INotifyPropertyChanged.PropertyChanged event:

class ChartModel
{
  public double MaxAxisValue { get; set; }
  public double MinAxisValue { get; set; }

  public ChartModel()
  {
    var chartValues = new ChartValues<double> { 10, 50, -3, -25 };
    this.MaxAxisValue = chartValues
      .Select(value => Math.Abs(value))
      .Max();
    this.MinAxisValue = this.MaxAxisValue * -1;

    this.SeriesCollection = new SeriesCollection
    {
      new ColumnSeries()
      {
        Title = "Series 1",
        Values = chartValues
      }
    };
  }
}

View

<Grid>
  <Grid.DataContext>
    <ChartModel />
  </Grid.DataContext>

  <wpf:CartesianChart Series="{Binding SeriesCollection}">
    <wpf:CartesianChart.AxisY>
      <wpf:Axis MaxValue="{Binding MaxAxisValue}"
                MinValue="{Binding MinAxisValue}">

        ...

      </wpf:Axis>
    </wpf:CartesianChart.AxisY>
  </wpf:CartesianChart>
</Grid>

Update

It seems that your problem is related to the separators of the axis or their distribution.

First note that although the distribution is not even, the values of Axis.MinValue and Axis.MaxValue are still respected by the chart. It's just a visual discrepancy, which is introduced by the interval of the divisions.

By default the interval is calculated automatically. I guess the algorithm takes the decimal position of values into account. If max absolute value is 39, then the interval will be either 10^1 or (10^1)/2. In your case you have 390,000 which uses position 10^5. So the interval is set to either 100,000 or 50,000 depending on the range. The divisions start from the lower border e.g. -390,000. Applying the interval of 100,000 will get the highest possible division, which is lesser than or equal to max value (390,000), of 310,000.

This explains why you get the divisions ranging from -390,000 to 310,000.

To "fix" this, you have to decide the number of steps (or divisions) you want to have and set Separator.Step explicitly. Separator.Step is set to 0 by default, which enables the automatic interval calculations.

The basic formula would be

step = value_range / desired_divisions_count

I find the terminology used by LiveCharts quite irritating. I naturally would call the steps interval and the number of divisions steps. But apparently the designers had a different perception.

Let's say you want to have 10 divisions or grid lines. You would have to set Separator.Step="78000" because 78000 = (390,000 - (-390,000)) / 10.
This will distribute the divisions evenly, where min/max value will each fall on a division.

<wpf:CartesianChart.AxisY>
  <wpf:Axis MaxValue="390000"
            MinValue="-390000">
    <wpf:Axis.Separator>
      <wpf:Separator Step="78000" />
    </wpf:Axis.Separator>
  </wpf:Axis>
</wpf:CartesianChart.AxisY>


问:
Xcode 11.5 Post-Update Error: Unable to activate constraint with anchors
I just updated to Xcode 11.5 and suddenly my application is throwing up this error (listed below).

My application has a TabBar as a foundation and houses different views for each of the five TabBar Items. All views work fine, except for the 3rd one, where on clicking the icon, I get the below error message.

This view has a segControl that changes data in a tableView. I've added pull to refresh and a search functionality. There's also a UILabel that appears when data can't be pulled / no internet scenario and is otherwise hidden.

Error

```<code>Terminating app due to uncaught exception 'NSGenericException', reason: 'Unable to activate constraint with anchors <NSLayoutYAxisAnchor:0x60000064b4c0 "UILabel:0x7fb6dd8b8b80'Day 1'.centerY"> and <NSLayoutYAxisAnchor:0x600000649780 "UIView:0x7fb6dd4b89d0.centerY"> because they have no common ancestor. Does the constraint or its anchors reference items in different view hierarchies?  That's illegal.'
</code>```

Now, I haven't changed this piece of code at all and it was working perfectly fine till the update happened. So I'm confused how to fix it.

I see that there might be some label and view conflicting their constraint hierarchies but I can't seem to figure out which ones and how to fix them.

Also there is nothing in my code that refers to 'Day 1' and I'm not adding any subViews programmatically.

Troubleshooting done so far

Discarded all code changes - still the same issue

Rolled back code to a previous working time through time machine - still the same issue

Rolled back Xcode to 11.4.x - still the same issue

Debugged my code, step by step - everything seems okay

Deleted any label or additional views - still throws the error

Reset the constraints to auto-constraints - still the same issue

Current Constraints [after discarding all code, working earlier]

```<code> label.top = top - 9
 bottom = label.bottom + 1
 label.leading = leading + 8
 label.centerX = centerX
</code>```

These are the only constrains, as I added a view below the tableView and that view contains the label.

[These are auto-constraints]

Appreciate any help. Thanks in advance.

答:
Managed to figure out the bug - it seems the update flipped over a custom class I was using, which in turn missed the reference to a dependency.

After reverting the custom class (in the storyboard - tableViewCell) correctly, it worked.

The answer here was the inspiration to try out this solution.

Body:
I just updated to Xcode 11.5 and suddenly my application is throwing up this error (listed below).

My application has a TabBar as a foundation and houses different views for each of the five TabBar Items. All views work fine, except for the 3rd one, where on clicking the icon, I get the below error message.

This view has a segControl that changes data in a tableView. I've added pull to refresh and a search functionality. There's also a UILabel that appears when data can't be pulled / no internet scenario and is otherwise hidden.

Error

Terminating app due to uncaught exception 'NSGenericException', reason: 'Unable to activate constraint with anchors <NSLayoutYAxisAnchor:0x60000064b4c0 "UILabel:0x7fb6dd8b8b80'Day 1'.centerY"> and <NSLayoutYAxisAnchor:0x600000649780 "UIView:0x7fb6dd4b89d0.centerY"> because they have no common ancestor. Does the constraint or its anchors reference items in different view hierarchies?  That's illegal.'

Now, I haven't changed this piece of code at all and it was working perfectly fine till the update happened. So I'm confused how to fix it.

I see that there might be some label and view conflicting their constraint hierarchies but I can't seem to figure out which ones and how to fix them.

Also there is nothing in my code that refers to 'Day 1' and I'm not adding any subViews programmatically.

Troubleshooting done so far

Discarded all code changes - still the same issue

Rolled back code to a previous working time through time machine - still the same issue

Rolled back Xcode to 11.4.x - still the same issue

Debugged my code, step by step - everything seems okay

Deleted any label or additional views - still throws the error

Reset the constraints to auto-constraints - still the same issue

Current Constraints [after discarding all code, working earlier]

 label.top = top - 9
 bottom = label.bottom + 1
 label.leading = leading + 8
 label.centerX = centerX

These are the only constrains, as I added a view below the tableView and that view contains the label.

[These are auto-constraints]

Appreciate any help. Thanks in advance.


问:
Query to return exact match for item in comma delimited string using MYSQL and PHP
I am struggling with writing a MYSQL query in PHP that can find an exact match with one item in a comma delimited string. Note, for various reasons I cannot change the data model

```<code>Musicians
id|artist
1|beatles
2|rolling stones

$searchterm = "beatles"
</code>```

It is easy to match the string exactly with:

```<code>WHERE artist = '$searchterm'
</code>```

How could I determine an exact match in the following

```<code>Musicians
id|artist
1|beatles,the beatles,the fab four,fab four,fab for
2|rolling stones,the rolling stones,stones,the stones

$searchterm = "fab four"

//something like the following although it does not work

WHERE $searchterm IN artist
</code>```

Thanks for any suggestions

答:
You could use find_in_set():

```<code>WHERE FIND_IN_SET(:searchterm, artist)
</code>```

Important notes:

do not concatenate variables into the query string, as this makes your code inefficient and exposes you to SQL injection; instead, do use parameterized queries. Related reading: How can I prevent SQL injection in PHP?

storing delimited lists in a database column is bad practice; it basically defeats the purpose of a relational databases, and makes simple things unecessarily complicated (as you are starting to see). Recommended related reading: Is storing a delimited list in a database column really that bad?

Body:
I am struggling with writing a MYSQL query in PHP that can find an exact match with one item in a comma delimited string. Note, for various reasons I cannot change the data model

Musicians
id|artist
1|beatles
2|rolling stones

$searchterm = "beatles"

It is easy to match the string exactly with:

WHERE artist = '$searchterm'

How could I determine an exact match in the following

Musicians
id|artist
1|beatles,the beatles,the fab four,fab four,fab for
2|rolling stones,the rolling stones,stones,the stones

$searchterm = "fab four"

//something like the following although it does not work

WHERE $searchterm IN artist

Thanks for any suggestions

Body:
You could use find_in_set():

WHERE FIND_IN_SET(:searchterm, artist)

Important notes:

do not concatenate variables into the query string, as this makes your code inefficient and exposes you to SQL injection; instead, do use parameterized queries. Related reading: How can I prevent SQL injection in PHP?

storing delimited lists in a database column is bad practice; it basically defeats the purpose of a relational databases, and makes simple things unecessarily complicated (as you are starting to see). Recommended related reading: Is storing a delimited list in a database column really that bad?


问:
Adding first occurence column to groupy dataframe
I have a data frame like this-

```<code>df=pd.DataFrame({'DT':[1,1,1,2,2,2,1,1],'city':['A','A','A','A','A','A','B','B'],'O':[22,33,44,55,66,77,88,99]})
</code>```

Now for each unique city, I want to add up all the values in the O column first occurring in the Dt column.
Output-

```<code>   city  O
0   A   77
1   B   88
</code>```

Explanation-
For the city 'A' the first unique occurring DT is 1 so we add the corresponding O column value that is 22. Next for the same city 'A' the first occurring 2 in the DT column is the 4th row so we add its corresponding O column== 22+55=77. Similarly for city B since only 1 is there in DT column the O will be 88.

答:
You need drop_duplicates and then groupby

```<code>df1  = (

 df.drop_duplicates(subset=["DT", "city"], keep="first")
    .groupby("city")["O"]
    .sum()
    .reset_index()
)
</code>```

```<code>print(df1)

 city   O
0    A  77
1    B  88
</code>```

or you could use a double group by first using first then sum

```<code>df.groupby(["city", "DT"]).first().groupby(level=0).sum().reset_index()

  city   O
0    A  77
1    B  88
</code>```

Body:
I have a data frame like this-

df=pd.DataFrame({'DT':[1,1,1,2,2,2,1,1],'city':['A','A','A','A','A','A','B','B'],'O':[22,33,44,55,66,77,88,99]})

Now for each unique city, I want to add up all the values in the O column first occurring in the Dt column.
Output-

   city  O
0   A   77
1   B   88

Explanation-
For the city 'A' the first unique occurring DT is 1 so we add the corresponding O column value that is 22. Next for the same city 'A' the first occurring 2 in the DT column is the 4th row so we add its corresponding O column== 22+55=77. Similarly for city B since only 1 is there in DT column the O will be 88.

Body:
You need drop_duplicates and then groupby

df1  = (

 df.drop_duplicates(subset=["DT", "city"], keep="first")
    .groupby("city")["O"]
    .sum()
    .reset_index()
)

print(df1)

 city   O
0    A  77
1    B  88

or you could use a double group by first using first then sum

df.groupby(["city", "DT"]).first().groupby(level=0).sum().reset_index()

  city   O
0    A  77
1    B  88


问:
Remove duplicates in Laravel collection only if previous item is identical
I have a Laravel Collection of items:

```<code>[
    [
    'id' => 1,
    'path' => '/',
    'created_at' => '2020-05-20 20:12:00'
    ],
    [
    'id' => 2,
    'path' => '/somewhere',
    'created_at' => '2020-05-20 21:01:00'
    ],
    [
    'id' => 3,
    'path' => '/somewhere',
    'created_at' => '2020-05-20 21:21:00'
    ],
    [
    'id' => 4,
    'path' => '/somewhere/else',
    'created_at' => '2020-05-20 21:09:00'
    ],
    [
    'id' => 5,
    'path' => '/somewhere/else',
    'created_at' => '2020-05-20 21:10:00'
    ],
]
</code>```

This is the raw data that would be found in the collection if I cast it to an array, but I need it to remain in collection format.

I need to remove any duplicates where the current item has the same path and is less than 5 minutes old compared to the previous item.

So in this case, item #4 would be removed leaving only #5, but items #2 and #3 would be kept even tho their paths are the same.

How would I do this?

答:
Use the following namespace in your controller file:

```<code>use DateTime;
</code>```

Use the following code in your controller file:

```<code>$collection = [
        [
            'id' => 1,
            'path' => '/',
            'created_at' => '2020-05-20 20:12:00'
        ],
        [
            'id' => 2,
            'path' => '/somewhere',
            'created_at' => '2020-05-20 21:01:00'
        ],
        [
            'id' => 3,
            'path' => '/somewhere',
            'created_at' => '2020-05-20 21:21:00'
        ],
        [
            'id' => 4,
            'path' => '/somewhere/else',
            'created_at' => '2020-05-20 21:09:00'
        ],
        [
            'id' => 5,
            'path' => '/somewhere/else',
            'created_at' => '2020-05-20 21:10:00'
        ],
    ];

    $paths = [];
    $time_count = [];
    foreach ($collection as $key => $data) {

        if (in_array($data['path'], $paths)) {
            $arr_pos = array_search($data['path'], array_values($paths));

            $datetime1 = new DateTime($data['created_at']);
            $datetime2 = new DateTime($collection[$arr_pos]['created_at']);

            $interval = $datetime1->diff($datetime2);
            $mins = $interval->format('%i');
            if ($mins < 5) {
                unset($collection[$arr_pos]);
            }
        }
        $paths[] = $data['path'];
    }
</code>```

This will return result:

```<code>array:4 [▼
     0 => array:3 [▼
       "id" => 1
       "path" => "/"
       "created_at" => "2020-05-20 20:12:00"
      ]
      1 => array:3 [▼
          "id" => 2
          "path" => "/somewhere"
         "created_at" => "2020-05-20 21:01:00"
      ]
      2 => array:3 [▼
         "id" => 3
         "path" => "/somewhere"
         "created_at" => "2020-05-20 21:21:00"
      ]
      4 => array:3 [▼
        "id" => 5
        "path" => "/somewhere/else"
        "created_at" => "2020-05-20 21:10:00"
      ]
     ]
</code>```

I hope this works for you.

Body:
I have a Laravel Collection of items:

[
    [
    'id' => 1,
    'path' => '/',
    'created_at' => '2020-05-20 20:12:00'
    ],
    [
    'id' => 2,
    'path' => '/somewhere',
    'created_at' => '2020-05-20 21:01:00'
    ],
    [
    'id' => 3,
    'path' => '/somewhere',
    'created_at' => '2020-05-20 21:21:00'
    ],
    [
    'id' => 4,
    'path' => '/somewhere/else',
    'created_at' => '2020-05-20 21:09:00'
    ],
    [
    'id' => 5,
    'path' => '/somewhere/else',
    'created_at' => '2020-05-20 21:10:00'
    ],
]

This is the raw data that would be found in the collection if I cast it to an array, but I need it to remain in collection format.

I need to remove any duplicates where the current item has the same path and is less than 5 minutes old compared to the previous item.

So in this case, item #4 would be removed leaving only #5, but items #2 and #3 would be kept even tho their paths are the same.

How would I do this?

Body:
Use the following namespace in your controller file:

use DateTime;

Use the following code in your controller file:

$collection = [
        [
            'id' => 1,
            'path' => '/',
            'created_at' => '2020-05-20 20:12:00'
        ],
        [
            'id' => 2,
            'path' => '/somewhere',
            'created_at' => '2020-05-20 21:01:00'
        ],
        [
            'id' => 3,
            'path' => '/somewhere',
            'created_at' => '2020-05-20 21:21:00'
        ],
        [
            'id' => 4,
            'path' => '/somewhere/else',
            'created_at' => '2020-05-20 21:09:00'
        ],
        [
            'id' => 5,
            'path' => '/somewhere/else',
            'created_at' => '2020-05-20 21:10:00'
        ],
    ];

    $paths = [];
    $time_count = [];
    foreach ($collection as $key => $data) {

        if (in_array($data['path'], $paths)) {
            $arr_pos = array_search($data['path'], array_values($paths));

            $datetime1 = new DateTime($data['created_at']);
            $datetime2 = new DateTime($collection[$arr_pos]['created_at']);

            $interval = $datetime1->diff($datetime2);
            $mins = $interval->format('%i');
            if ($mins < 5) {
                unset($collection[$arr_pos]);
            }
        }
        $paths[] = $data['path'];
    }

This will return result:

array:4 [▼
     0 => array:3 [▼
       "id" => 1
       "path" => "/"
       "created_at" => "2020-05-20 20:12:00"
      ]
      1 => array:3 [▼
          "id" => 2
          "path" => "/somewhere"
         "created_at" => "2020-05-20 21:01:00"
      ]
      2 => array:3 [▼
         "id" => 3
         "path" => "/somewhere"
         "created_at" => "2020-05-20 21:21:00"
      ]
      4 => array:3 [▼
        "id" => 5
        "path" => "/somewhere/else"
        "created_at" => "2020-05-20 21:10:00"
      ]
     ]

I hope this works for you.


问:
How to make k8s allocate gpu/npu devices following specific rule
I have multiple gpu cards within one machine, and I need to let the k8s allocate gpu/npus device following some rules I set.

For example, supposing there are 8 gpu cards whose id is from 0-7, and only device0、device1、device6 and device7 are available. Now I need to create one pod with 2 devices, these two devices must be either of (device0, device1) or (device6, device7). Other device combinations such as (device0, device6) are not valid.

Is there any way to do that?  I am using kubernetes of version 1.18 and implemented my own device plugin.

答:
I don't understand why would you write a rule like this:

every device-id be smaller than 4

If you want to limit the amount of GPUs you should be using limits and requests which is nicely explained on Schedule GPUs.
So you can just limit the resource to only 4 GPUs like so:

apiVersion: v1
kind: Pod
metadata:
  name: cuda-vector-add
spec:
  restartPolicy: OnFailure
  containers:
    - name: cuda-vector-add
      # https://github.com/kubernetes/kubernetes/blob/v1.7.11/test/images/nvidia-cuda/Dockerfile
      image: "k8s.gcr.io/cuda-vector-add:v0.1"
      resources:
        limits:
          nvidia.com/gpu: 4 # requesting 1 GPU
```

<p>If you have different types of GPUs on different nodes you can use <code>labels</code> which you can read here Clusters containing different types of GPUs.</p>

<blockquote>
  <pre class="lang-sh prettyprint-override"><code># Label your nodes with the accelerator type they have.
kubectl label nodes <node-with-k80> accelerator=nvidia-tesla-k80
kubectl label nodes <node-with-p100> accelerator=nvidia-tesla-p100
</code>```

If your nodes are running different versions of GPUs, then use Node Labels and Node Selectors to schedule pods to appropriate GPUs. Following is an illustration of this workflow:

As part of your Node bootstrapping, identify the GPU hardware type on your nodes and expose it as a node label.

```<code>NVIDIA_GPU_NAME=$(nvidia-smi --query-gpu=gpu_name --format=csv,noheader --id=0)
source /etc/default/kubelet
KUBELET_OPTS="$KUBELET_OPTS --node-labels='alpha.kubernetes.io/nvidia-gpu-name=$NVIDIA_GPU_NAME'"
echo "KUBELET_OPTS=$KUBELET_OPTS" > /etc/default/kubelet
</code>```

Specify the GPU types a pod can use via Node Affinity rules.

```<code>kind: pod
apiVersion: v1
metadata:
  annotations:
    scheduler.alpha.kubernetes.io/affinity: >
      {
        "nodeAffinity": {
          "requiredDuringSchedulingIgnoredDuringExecution": {
            "nodeSelectorTerms": [
              {
                "matchExpressions": [
                  {
                    "key": "alpha.kubernetes.io/nvidia-gpu-name",
                    "operator": "In",
                    "values": ["Tesla K80", "Tesla P100"]
                  }
                ]
              }
            ]
          }
        }
      }
spec:
  containers:
    -
      name: gpu-container-1
      resources:
        limits:
          alpha.kubernetes.io/nvidia-gpu: 2
</code>```

This will ensure that the pod will be scheduled to a node that has a Tesla K80 or a Tesla P100 Nvidia GPU.

You could find other relevant information on unofficial-kubernetes Scheduling gpus.

Body:
I don't understand why would you write a rule like this:

every device-id be smaller than 4

If you want to limit the amount of GPUs you should be using limits and requests which is nicely explained on Schedule GPUs.
So you can just limit the resource to only 4 GPUs like so:

apiVersion: v1
kind: Pod
metadata:
  name: cuda-vector-add
spec:
  restartPolicy: OnFailure
  containers:
    - name: cuda-vector-add
      # https://github.com/kubernetes/kubernetes/blob/v1.7.11/test/images/nvidia-cuda/Dockerfile
      image: "k8s.gcr.io/cuda-vector-add:v0.1"
      resources:
        limits:
          nvidia.com/gpu: 4 # requesting 1 GPU

If you have different types of GPUs on different nodes you can use labels which you can read here Clusters containing different types of GPUs.

# Label your nodes with the accelerator type they have.
kubectl label nodes <node-with-k80> accelerator=nvidia-tesla-k80
kubectl label nodes <node-with-p100> accelerator=nvidia-tesla-p100

If your nodes are running different versions of GPUs, then use Node Labels and Node Selectors to schedule pods to appropriate GPUs. Following is an illustration of this workflow:

As part of your Node bootstrapping, identify the GPU hardware type on your nodes and expose it as a node label.

NVIDIA_GPU_NAME=$(nvidia-smi --query-gpu=gpu_name --format=csv,noheader --id=0)
source /etc/default/kubelet
KUBELET_OPTS="$KUBELET_OPTS --node-labels='alpha.kubernetes.io/nvidia-gpu-name=$NVIDIA_GPU_NAME'"
echo "KUBELET_OPTS=$KUBELET_OPTS" > /etc/default/kubelet

Specify the GPU types a pod can use via Node Affinity rules.

kind: pod
apiVersion: v1
metadata:
  annotations:
    scheduler.alpha.kubernetes.io/affinity: >
      {
        "nodeAffinity": {
          "requiredDuringSchedulingIgnoredDuringExecution": {
            "nodeSelectorTerms": [
              {
                "matchExpressions": [
                  {
                    "key": "alpha.kubernetes.io/nvidia-gpu-name",
                    "operator": "In",
                    "values": ["Tesla K80", "Tesla P100"]
                  }
                ]
              }
            ]
          }
        }
      }
spec:
  containers:
    -
      name: gpu-container-1
      resources:
        limits:
          alpha.kubernetes.io/nvidia-gpu: 2

This will ensure that the pod will be scheduled to a node that has a Tesla K80 or a Tesla P100 Nvidia GPU.

You could find other relevant information on unofficial-kubernetes Scheduling gpus.


问:
Is there a way to configure a specific consumer when using ConfigureEndpoints method in MassTransit?
I've got a lot of consumers and I don't want to configure each of them manually, so I use methods AddConsumers and ConfigureEndpoints.

Now I need to configure a repeat policy for one of the consumers.

If additionally call the ReceiveEndPoint method (before or after calling ConfigureEndpoints), the exception "A receive endpoint with the same key was already added" is thrown.

Is it possible to combine convention based endpoints configuration and custom configuration of individual consumers?

答:
It seems to be working:

    services.AddMassTransit(cfg =>
        {
            cfg.AddConsumers(Assembly.GetExecutingAssembly());
            // this consumer is also present in the assembly:
            cfg.AddConsumer<SpecificConsumer>(x => x.UseRetry(r => r.Immediate(5)));
            cfg.AddBus(sp => Bus.Factory.CreateUsingRabbitMq(x => x.ConfigureEndpoints(sp)));
        });
```


问:
listen EADDRINUSE: address already in use :::5000
In my application, I use concurrently to run both backend and front end simultaneously. After ctrl + c, strill the port 5000 is running. Also, port 3000 is running. I have to manually kill processes. How can I solve this?</p>

答:
Restart your laptop/server, it will release all the busy ports, then try again... you can also use

```<code>ps aux | grep node
</code>```

and then kill the process using:

```<code>kill -9 PID..
</code>```

You can kill all the processes that are using node it can also kill a system process

Not preferred: killall -9 node

but most of the times it wont work for nodemon, and didnt work for me.

Body:
Restart your laptop/server, it will release all the busy ports, then try again... you can also use

ps aux | grep node

and then kill the process using:

kill -9 PID..

You can kill all the processes that are using node it can also kill a system process

Not preferred: killall -9 node

but most of the times it wont work for nodemon, and didnt work for me.