问:
sonar.cs.fxcop.assembly must be set
MSBuild SonarQube is raising the issue 'sonar.cs.fxcop.assembly must be set' when using FxCop rules in the QualityProfile. See exception below.

It is working fine with other StyleCop and C# rules.
I had a look to similar posts but couldn't find a solution.

I am using :

```<code>C:\Sonar\sonarqube-5.2
C:\Sonar\MSBuild.SonarQube.Runner-1.0.2
</code>```

The following plugins are installed:
    Plugin C# 4.3
    Plugin StyleCop 1.1

Targeting the following sample project:

```<code>C:\Sonar\sonar-examples-master\projects\languages\csharp\ConsoleApplication1
</code>```

I am executing the following commands :

```<code>cd Sonar\MSBuild.SonarQube.Runner-1.0.2\

MSBuild.SonarQube.Runner.exe begin /k:"MyProjectKey" /n:"MyProjectName" /v:"MyProjectVersion"

"C:\Program Files (x86)\MSBuild\12.0\Bin\MSBuild.exe" "C:\Sonar\sonar-examples-master\projects\languages\csharp\ConsoleApplication1\ConsoleApplication1.csproj" /t:Rebuild

MSBuild.SonarQube.Runner.exe end
</code>```

I have tried to declare the assembly location in the .csproj file but without success. What does the expected path looks like ?

```<code><ItemGroup>
    <SonarQubeSetting Include="sonar.cs.fxcop.assembly">
        <Value>path to dll</Value>
    </SonarQubeSetting>
</ItemGroup>
</code>```

Thank you for your help !

Exception :

```<code>10:33:14.564 INFO  - Sensor org.sonar.plugins.csharp.CSharpFxCopProvider$CSharpF
xCopSensor@1eeeda8
INFO: ------------------------------------------------------------------------
INFO: EXECUTION FAILURE
INFO: ------------------------------------------------------------------------
Total time: 12.017s
Final Memory: 14M/113M
INFO: ------------------------------------------------------------------------
ERROR: Error during Sonar runner execution
org.sonar.runner.impl.RunnerException: Unable to execute Sonar
        at org.sonar.runner.impl.BatchLauncher$1.delegateExecution(BatchLauncher
.java:91)
        at org.sonar.runner.impl.BatchLauncher$1.run(BatchLauncher.java:75)
        at java.security.AccessController.doPrivileged(Native Method)
        at org.sonar.runner.impl.BatchLauncher.doExecute(BatchLauncher.java:69)
        at org.sonar.runner.impl.BatchLauncher.execute(BatchLauncher.java:50)
        at org.sonar.runner.api.EmbeddedRunner.doExecute(EmbeddedRunner.java:102
)
        at org.sonar.runner.api.Runner.execute(Runner.java:100)
        at org.sonar.runner.Main.executeTask(Main.java:70)
        at org.sonar.runner.Main.execute(Main.java:59)
        at org.sonar.runner.Main.main(Main.java:53)
Caused by: java.lang.IllegalArgumentException: Cannot find the assembly "C:\Prog
ram Files (x86)\Microsoft Visual Studio 11.0\Team Tools\Static Analysis Tools\Fx
CopSdk.dll" provided by the property "sonar.cs.fxcop.assembly".
        at com.google.common.base.Preconditions.checkArgument(Preconditions.java
:88)
        at org.sonar.plugins.fxcop.FxCopConfiguration.checkAssemblyProperty(FxCo
pConfiguration.java:115)
        at org.sonar.plugins.fxcop.FxCopConfiguration.checkProperties(FxCopConfi
guration.java:97)
</code>```

答:
The issue will get fixed if you make fxcop assembly to point your application dll as shown below.

sonar.cs.fxcop.fxCopCmdPath=C:/Program Files (x86)/Microsoft Visual Studio 12.0/Team Tools/Static Analysis Tools/FxCop/FxCopCmd.exe
sonar.cs.fxcop.assembly=APPLICATIONNAME/bin/APPLICATIONNAME.dll

Note: Please be sure that you are giving the correct path to point to bin folder.

Title: sonar.cs.fxcop.assembly must be set

Body:
MSBuild SonarQube is raising the issue 'sonar.cs.fxcop.assembly must be set' when using FxCop rules in the QualityProfile. See exception below.

It is working fine with other StyleCop and C# rules.
I had a look to similar posts but couldn't find a solution.

I am using :

C:\Sonar\sonarqube-5.2
C:\Sonar\MSBuild.SonarQube.Runner-1.0.2

The following plugins are installed:
    Plugin C# 4.3
    Plugin StyleCop 1.1

Targeting the following sample project:

C:\Sonar\sonar-examples-master\projects\languages\csharp\ConsoleApplication1

I am executing the following commands :

cd Sonar\MSBuild.SonarQube.Runner-1.0.2\

MSBuild.SonarQube.Runner.exe begin /k:"MyProjectKey" /n:"MyProjectName" /v:"MyProjectVersion"

"C:\Program Files (x86)\MSBuild\12.0\Bin\MSBuild.exe" "C:\Sonar\sonar-examples-master\projects\languages\csharp\ConsoleApplication1\ConsoleApplication1.csproj" /t:Rebuild

MSBuild.SonarQube.Runner.exe end

I have tried to declare the assembly location in the .csproj file but without success. What does the expected path looks like ?

<ItemGroup>
    <SonarQubeSetting Include="sonar.cs.fxcop.assembly">
        <Value>path to dll</Value>
    </SonarQubeSetting>
</ItemGroup>

Thank you for your help !

Exception :

10:33:14.564 INFO  - Sensor org.sonar.plugins.csharp.CSharpFxCopProvider$CSharpF
xCopSensor@1eeeda8
INFO: ------------------------------------------------------------------------
INFO: EXECUTION FAILURE
INFO: ------------------------------------------------------------------------
Total time: 12.017s
Final Memory: 14M/113M
INFO: ------------------------------------------------------------------------
ERROR: Error during Sonar runner execution
org.sonar.runner.impl.RunnerException: Unable to execute Sonar
        at org.sonar.runner.impl.BatchLauncher$1.delegateExecution(BatchLauncher
.java:91)
        at org.sonar.runner.impl.BatchLauncher$1.run(BatchLauncher.java:75)
        at java.security.AccessController.doPrivileged(Native Method)
        at org.sonar.runner.impl.BatchLauncher.doExecute(BatchLauncher.java:69)
        at org.sonar.runner.impl.BatchLauncher.execute(BatchLauncher.java:50)
        at org.sonar.runner.api.EmbeddedRunner.doExecute(EmbeddedRunner.java:102
)
        at org.sonar.runner.api.Runner.execute(Runner.java:100)
        at org.sonar.runner.Main.executeTask(Main.java:70)
        at org.sonar.runner.Main.execute(Main.java:59)
        at org.sonar.runner.Main.main(Main.java:53)
Caused by: java.lang.IllegalArgumentException: Cannot find the assembly "C:\Prog
ram Files (x86)\Microsoft Visual Studio 11.0\Team Tools\Static Analysis Tools\Fx
CopSdk.dll" provided by the property "sonar.cs.fxcop.assembly".
        at com.google.common.base.Preconditions.checkArgument(Preconditions.java
:88)
        at org.sonar.plugins.fxcop.FxCopConfiguration.checkAssemblyProperty(FxCo
pConfiguration.java:115)
        at org.sonar.plugins.fxcop.FxCopConfiguration.checkProperties(FxCopConfi
guration.java:97)


来源: stackexchange

问:
What is the use of double underscore in repeat() or other steps in Tinkerpop Gremlin?
I have noticed double underscore being used in some step functions in Tinkerpop Gremlin 3.3. Could someone please tell why we use this double underscore with an example ? I could not find enough information about this in the documentation.</p>

答:
__ is used to refer to the incoming traversal (vertex or edge) in Java API. For example: in gremlin shell, one can write something like this

```<code>graph.traversal().V().repeat(out("edgeType")).until(hasLabel("label")).toList()
</code>```

But in java one needs an anonymous traversal to call the functions "out" and "hasLabel" within repeat and until (or any other function like by, choose etc.). The above traversal in Java will look like:

```<code>graph.traversal().V().repeat(__.out("edgeType")).until(__.hasLabel("label")).toList()
</code>```

ContentLicense: CC BY-SA 3.0

Body:
__ is used to refer to the incoming traversal (vertex or edge) in Java API. For example: in gremlin shell, one can write something like this

graph.traversal().V().repeat(out("edgeType")).until(hasLabel("label")).toList()

But in java one needs an anonymous traversal to call the functions "out" and "hasLabel" within repeat and until (or any other function like by, choose etc.). The above traversal in Java will look like:

graph.traversal().V().repeat(__.out("edgeType")).until(__.hasLabel("label")).toList()


问:
How to filter an array using NSPredicate in swift 3
I have an arraycontaining several dictionaries.

```<code>{
   DisplayName?:"Name of the employee"
   Age:28
   Department:"Dept 2"
}
</code>```

I just converted my objective-c code into swift and trying to filter like this.

```<code>let exists = NSPredicate(format: "DisplayName2 CONTAINS[cd] \(searchText!)")
    let aList: Array<Any> = arrayDirectory.filter { exists.evaluate(with: $0) }
    if(aList.count>0)
    {
        arrayDirectory=aList
        facesCarousel.reloadData()
    }
</code>```

But I am always getting the aList count as 0. It seems like not filtering my array. How can I write proper NSPredicatein swift 3 and filter my array using it.

答:
Use this code its worked fine in my side I hope this code will be help you

I have an array that array containing several dictionaries. Structure will be like this

```<code> [
 {
  DisplayName:"Name of the employee1"
  Age:28
  Department:"Dept 2"
 }
 ]
</code>```

In above array i am filtering with displayName key using apple search controller with help of predicate method

```<code>  func updateSearchResults(for searchController: UISearchController) {

    if (searchController.searchBar.text?.characters.count)! > 0 {
        guard let searchText = searchController.searchBar.text, searchText != "" else {
            return
        }

        let searchPredicate = NSPredicate(format: "DisplayName CONTAINS[C] %@", searchText)

        usersDataFromResponse = (filteredArray as NSArray).filtered(using: searchPredicate)

        print ("array = \(usersDataFromResponse)")

        self.tableview.reloadData()
    }

}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have an arraycontaining several dictionaries.

{
   DisplayName?:"Name of the employee"
   Age:28
   Department:"Dept 2"
}

I just converted my objective-c code into swift and trying to filter like this.

let exists = NSPredicate(format: "DisplayName2 CONTAINS[cd] \(searchText!)")
    let aList: Array<Any> = arrayDirectory.filter { exists.evaluate(with: $0) }
    if(aList.count>0)
    {
        arrayDirectory=aList
        facesCarousel.reloadData()
    }

But I am always getting the aList count as 0. It seems like not filtering my array. How can I write proper NSPredicatein swift 3 and filter my array using it.

Body:
Use this code its worked fine in my side I hope this code will be help you

I have an array that array containing several dictionaries. Structure will be like this

 [
 {
  DisplayName:"Name of the employee1"
  Age:28
  Department:"Dept 2"
 }
 ]

In above array i am filtering with displayName key using apple search controller with help of predicate method

  func updateSearchResults(for searchController: UISearchController) {

    if (searchController.searchBar.text?.characters.count)! > 0 {
        guard let searchText = searchController.searchBar.text, searchText != "" else {
            return
        }

        let searchPredicate = NSPredicate(format: "DisplayName CONTAINS[C] %@", searchText)

        usersDataFromResponse = (filteredArray as NSArray).filtered(using: searchPredicate)

        print ("array = \(usersDataFromResponse)")

        self.tableview.reloadData()
    }

}


问:
Question on my Class implemention in C#
Currently i have a class which has only properties

```<code>class MyEntity
{
    public string FirstName { get; set; }
    public string LastName  { get; set; }
}
</code>```

In my other class, I use to set the values like

```<code>MyEntity objEnt = new MyEntity();
objEnt.FirstName="abc";
objEnt.LastName = "edf";
</code>```

The reason i have the class MyEntity with only properties is to ensure adherence.

Question here is, if this approach is correct? I can have multiple instances of MyEntity

Can i use Static Class for this? How can i use Generics in this?

BTW the implementation is in C#

Thanks in advance

Cheers,

Karthik

答:
I had an answer half typed, but then Jon answered so my answer in its current form became pointless....

I will offer a counterpoint on Jon's answer though. Think carefully before using immutable objects - they are good from some perspectives, but you will quickly run into trouble if using them for binding to editable fields, or if serializing them (either to storage or for transferring, ie WCF web service calls).

ContentLicense: CC BY-SA 2.5

Title: Question on my Class implemention in C#

Body:
Currently i have a class which has only properties

class MyEntity
{
    public string FirstName { get; set; }
    public string LastName  { get; set; }
}

In my other class, I use to set the values like

MyEntity objEnt = new MyEntity();
objEnt.FirstName="abc";
objEnt.LastName = "edf";

The reason i have the class MyEntity with only properties is to ensure adherence.

Question here is, if this approach is correct? I can have multiple instances of MyEntity

Can i use Static Class for this? How can i use Generics in this?

BTW the implementation is in C#

Thanks in advance

Cheers,

Karthik


问:
How to minimize and maximize text inside
I have two variables of long and short versions of the text. In table inside cell  if long version of text is not null there is should be a button(or other suitable element) in the end of short text. And when user press this button(or other suitable element) long version of text is shown instead short.

I tied to to this next way. There is part of code of my table:

```<code><tbody>
    <tr ng-repeat="log in logs | orderBy:'-date'">
        <td>{{ log.date | date:"dd.MM.yyyy HH:mm:ss" }}</td>
        <td>{{ log.name }}</td>
        <td class="word-break">
            {{ isFullText ?  log.fullDescription : log.description  }}
            <button ng-click="showDiffText()">{{ isFullText ? textButton[0] : textButton[1] }}</button>
        </td>
    </tr>
</tbody>
</code>```

And there is js function:

```<code> $scope.isFullText = false;
 $scope.textButton = ['1', '2'];
 $scope.showDiffText = function ()
 {
      $scope.isFullText = !$scope.isFullText;
 }
</code>```

Well, my way doesn't work at all. Any help, please?

答:
Problem is isFullText as you are using ng-repeat if you set it to true it will start showing full text for all the rows try attaching it at log lavel something like:-

var myApp = angular.module('myApp',[]);
myApp.controller('MyCtrl',function($scope, $timeout) {
$scope.logs=[{description :"sort",fullDescription:"long"},{description :"sort",fullDescription:"long"},{description :"sort"}]
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.6/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MyCtrl">
<table>
<tbody>
    <tr ng-repeat="log in logs">
        <td class="word-break">
            {{log.showFull ? log.fullDescription : log.description}}
            <button ng-if="log.fullDescription" ng-click="log.showFull = !log.showFull">Show{{log.showFull ? "Sort":"Long"}}</button>
        </td>
    </tr>
</tbody>
</table>
</div></code>```

Title: How to minimize and maximize text inside <td>

Body:
I have two variables of long and short versions of the text. In table inside cell  if long version of text is not null there is should be a button(or other suitable element) in the end of short text. And when user press this button(or other suitable element) long version of text is shown instead short.

I tied to to this next way. There is part of code of my table:

        {{ log.date | date:"dd.MM.yyyy HH:mm:ss" }}
        {{ log.name }}

            {{ isFullText ?  log.fullDescription : log.description  }}
            <button ng-click="showDiffText()">{{ isFullText ? textButton[0] : textButton[1] }}</button>

And there is js function:

 $scope.isFullText = false;
 $scope.textButton = ['1', '2'];
 $scope.showDiffText = function ()
 {
      $scope.isFullText = !$scope.isFullText;
 }

Well, my way doesn't work at all. Any help, please?

Body:
Problem is isFullText as you are using ng-repeat if you set it to true it will start showing full text for all the rows try attaching it at log lavel something like:-

var myApp = angular.module('myApp',[]);
myApp.controller('MyCtrl',function($scope, $timeout) {
$scope.logs=[{description :"sort",fullDescription:"long"},{description :"sort",fullDescription:"long"},{description :"sort"}]
});

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.6/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MyCtrl">
<table>
<tbody>
    <tr ng-repeat="log in logs">
        <td class="word-break">
            {{log.showFull ? log.fullDescription : log.description}}
            <button ng-if="log.fullDescription" ng-click="log.showFull = !log.showFull">Show{{log.showFull ? "Sort":"Long"}}</button>
        </td>
    </tr>
</tbody>
</table>
</div>


问:
Remove only Horizontal Border from Table
I only want the horizontal line to be removed.

Meaning rows should not have lines and column should have lines.

In my code, there is no line in row as well as column.

I tried:

<!DOCTYPE html>

  <link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
  <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Raleway">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

Company
Number

Demo (2)

2017-11-16 12:18:15

        Sr.
        Item
        Qty
        Amount

          1

          Shirt  (DC Dry Clean)

          2

          100

          2

          Saree  (RP ROll Polish)

          2

          100

        Two Hundred Rupees Only
        Total:
        200

```

I only want the horizontal line to be removed after the first row, i.e after Sr, Item and all, and before amount row (the last row).

答:
just remove the inline stye (border:none!important;) and add

border-top:none;
border-bottom:none;

Body:
I only want the horizontal line to be removed.

Meaning rows should not have lines and column should have lines.

In my code, there is no line in row as well as column.

I tried:

<!DOCTYPE html>

  <link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
  <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Raleway">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

Company
Number

Demo (2)

2017-11-16 12:18:15

        Sr.
        Item
        Qty
        Amount

          1

          Shirt  (DC Dry Clean)

          2

          100

          2

          Saree  (RP ROll Polish)

          2

          100

        Two Hundred Rupees Only
        Total:
        200

I only want the horizontal line to be removed after the first row, i.e after Sr, Item and all, and before amount row (the last row).


问:
How to resolve repository certificate error in Gradle build
I installed latest version of android studio. I had jdk 8 which was already installed. When I opened android studio, I got below error.

```<code>Unable to resolve dependency for ':app@debugUnitTest/compileClasspath': Could not resolve com.android.support:appcompat-v7:26.1.0.

Could not resolve com.android.support:appcompat-v7:26.1.0.
Required by:
    project :app
 > Could not resolve com.android.support:appcompat-v7:26.1.0.
    > Could not get resource 'https://dl.google.com/dl/android/maven2/com/android/support/appcompat-v7/26.1.0/appcompat-v7-26.1.0.pom'.
          > Could not GET 'https://dl.google.com/dl/android/maven2/com/android/support/appcompat-v7/26.1.0/appcompat-v7-26.1.0.pom'.
                   > sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
                               > PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
                                              > unable to find valid certification path to requested target
</code>```

So I removed JDK 8 and installed JDK 9, added environment variables (in windows 10). Then I restarted my system and started android studio, I still got above error. I even added

```<code>repositories {
    maven { url "https://maven.google.com" }
}
</code>```

to gradle script. But I'm still getting same error. How do I fix this error?

答:
try replace with</p>

```<code>repositories {
    maven { url 'http://repo1.maven.org/maven2' }
}
</code>```

Body:
I installed latest version of android studio. I had jdk 8 which was already installed. When I opened android studio, I got below error.

Unable to resolve dependency for ':app@debugUnitTest/compileClasspath': Could not resolve com.android.support:appcompat-v7:26.1.0.

Could not resolve com.android.support:appcompat-v7:26.1.0.
Required by:
    project :app
 > Could not resolve com.android.support:appcompat-v7:26.1.0.
    > Could not get resource 'https://dl.google.com/dl/android/maven2/com/android/support/appcompat-v7/26.1.0/appcompat-v7-26.1.0.pom'.
          > Could not GET 'https://dl.google.com/dl/android/maven2/com/android/support/appcompat-v7/26.1.0/appcompat-v7-26.1.0.pom'.
                   > sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
                               > PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
                                              > unable to find valid certification path to requested target

So I removed JDK 8 and installed JDK 9, added environment variables (in windows 10). Then I restarted my system and started android studio, I still got above error. I even added

repositories {
    maven { url "https://maven.google.com" }
}

to gradle script. But I'm still getting same error. How do I fix this error?

Body:
try replace with

repositories {
    maven { url 'http://repo1.maven.org/maven2' }
}


问:
Convert number into culture specific
I have a number like  202667.4. I want to convert this to number based on culture.

For Ex:

In "de"(German) the number should be in 202.667,40.

Any help will be greatly appreciated.

Thanks.

答:
You can use this code to convert variables to different cultures:

```<code>int MyInt = 100;
string MyString = MyInt.ToString("C",CultureInfo.GetCultureInfo("de-DE"));
MessageBox.Show(MyString);
</code>```

If you want to build all programs with a German format you can this code at your main class:

```<code>using System.Globalization;`

Application.CurrentCulture = CultureInfo.GetCultureInfo("de-DE");`
</code>```

Title: Convert number into culture specific

Body:
You can use this code to convert variables to different cultures:

int MyInt = 100;
string MyString = MyInt.ToString("C",CultureInfo.GetCultureInfo("de-DE"));
MessageBox.Show(MyString);

If you want to build all programs with a German format you can this code at your main class:

using System.Globalization;`

Application.CurrentCulture = CultureInfo.GetCultureInfo("de-DE");`


问:
Remove contents of custom properties in Word 2010 with Open XML SDK 2.0 or Linq
I'm trying to remove sensitive information from word-files before they are sent from our system.
Below is an example of the custom properties in a file that is going to be sent. I would like to remove the contents of filePath and templateFilePath.

```<code><?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Properties xmlns="http://schemas.openxmlformats.org/officeDocument/2006/custom-properties" xmlns:vt="http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes">
    <property fmtid="{D5CDD505-2E9C-101B-9397-08002B2CF9AE}" pid="2" name="docId">
        <vt:lpwstr>123</vt:lpwstr>
    </property>
    <property fmtid="{D5CDD505-2E9C-101B-9397-08002B2CF9AE}" pid="3" name="verId">
        <vt:lpwstr>1</vt:lpwstr>
    </property>
    <property fmtid="{D5CDD505-2E9C-101B-9397-08002B2CF9AE}" pid="4" name="templateId">
        <vt:lpwstr>321</vt:lpwstr>
    </property>
    <property fmtid="{D5CDD505-2E9C-101B-9397-08002B2CF9AE}" pid="5" name="fileId">
        <vt:lpwstr>123</vt:lpwstr>
    </property>
    <property fmtid="{D5CDD505-2E9C-101B-9397-08002B2CF9AE}" pid="6" name="filePath">
        <vt:lpwstr>I want to remove this</vt:lpwstr>
    </property>
    <property fmtid="{D5CDD505-2E9C-101B-9397-08002B2CF9AE}" pid="7" name="templateFilePath">
        <vt:lpwstr>I want to remove this</vt:lpwstr>
    </property>
    <property fmtid="{D5CDD505-2E9C-101B-9397-08002B2CF9AE}" pid="8" name="filePathOneNote">
        <vt:lpwstr>\</vt:lpwstr>
    </property>
    <property fmtid="{D5CDD505-2E9C-101B-9397-08002B2CF9AE}" pid="9" name="fileName">
        <vt:lpwstr>test.docx</vt:lpwstr>
    </property>
    <property fmtid="{D5CDD505-2E9C-101B-9397-08002B2CF9AE}" pid="10" name="comment">
        <vt:lpwstr>Test comment</vt:lpwstr>
    </property>
    <property fmtid="{D5CDD505-2E9C-101B-9397-08002B2CF9AE}" pid="11" name="sourceId">
        <vt:lpwstr>12345</vt:lpwstr>
    </property>
    <property fmtid="{D5CDD505-2E9C-101B-9397-08002B2CF9AE}" pid="12" name="module">
        <vt:lpwstr>Document</vt:lpwstr>
    </property>
</Properties>
</code>```

I got this code from the Open XML SDK productivity tool:

```<code>private static void ChangeCustomFilePropertiesPart(CustomFilePropertiesPart customFilePropertiesPart)
{
    CustomProperties.Properties properties = customFilePropertiesPart.Properties;

    CustomProperties.CustomDocumentProperty customDocumentProperty1 = properties.Elements<CustomProperties.CustomDocumentProperty>().ElementAt(4);
    CustomProperties.CustomDocumentProperty customDocumentProperty2 = properties.Elements<CustomProperties.CustomDocumentProperty>().ElementAt(5);

    VariantTypes.VTLPWSTR vTLPWSTR1 = customDocumentProperty1.GetFirstChild<VariantTypes.VTLPWSTR>();
    vTLPWSTR1.Text = "";

    VariantTypes.VTLPWSTR vTLPWSTR2 = customDocumentProperty2.GetFirstChild<VariantTypes.VTLPWSTR>();
    vTLPWSTR2.Text = "";

}
</code>```

But I can't trust that the properties I want to remove are number four and five, so I have to find them by the name attribute before I remove the text. Can anyone help me? I would like to use linq or the Open XML SDK in some way.

Thanks!

答: You don't to query by @pid, as that may change. Query by @name instead, which will always remain the same value for custom document properties; so in your case just use a Lambda to query Where @name = "templateFilePath" and then set it's .Value to nothing and copy that back and save.

Body:
I'm trying to remove sensitive information from word-files before they are sent from our system.
Below is an example of the custom properties in a file that is going to be sent. I would like to remove the contents of filePath and templateFilePath.

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Properties xmlns="http://schemas.openxmlformats.org/officeDocument/2006/custom-properties" xmlns:vt="http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes">
    <property fmtid="{D5CDD505-2E9C-101B-9397-08002B2CF9AE}" pid="2" name="docId">
        <vt:lpwstr>123</vt:lpwstr>
    </property>
    <property fmtid="{D5CDD505-2E9C-101B-9397-08002B2CF9AE}" pid="3" name="verId">
        <vt:lpwstr>1</vt:lpwstr>
    </property>
    <property fmtid="{D5CDD505-2E9C-101B-9397-08002B2CF9AE}" pid="4" name="templateId">
        <vt:lpwstr>321</vt:lpwstr>
    </property>
    <property fmtid="{D5CDD505-2E9C-101B-9397-08002B2CF9AE}" pid="5" name="fileId">
        <vt:lpwstr>123</vt:lpwstr>
    </property>
    <property fmtid="{D5CDD505-2E9C-101B-9397-08002B2CF9AE}" pid="6" name="filePath">
        <vt:lpwstr>I want to remove this</vt:lpwstr>
    </property>
    <property fmtid="{D5CDD505-2E9C-101B-9397-08002B2CF9AE}" pid="7" name="templateFilePath">
        <vt:lpwstr>I want to remove this</vt:lpwstr>
    </property>
    <property fmtid="{D5CDD505-2E9C-101B-9397-08002B2CF9AE}" pid="8" name="filePathOneNote">
        <vt:lpwstr>\</vt:lpwstr>
    </property>
    <property fmtid="{D5CDD505-2E9C-101B-9397-08002B2CF9AE}" pid="9" name="fileName">
        <vt:lpwstr>test.docx</vt:lpwstr>
    </property>
    <property fmtid="{D5CDD505-2E9C-101B-9397-08002B2CF9AE}" pid="10" name="comment">
        <vt:lpwstr>Test comment</vt:lpwstr>
    </property>
    <property fmtid="{D5CDD505-2E9C-101B-9397-08002B2CF9AE}" pid="11" name="sourceId">
        <vt:lpwstr>12345</vt:lpwstr>
    </property>
    <property fmtid="{D5CDD505-2E9C-101B-9397-08002B2CF9AE}" pid="12" name="module">
        <vt:lpwstr>Document</vt:lpwstr>
    </property>
</Properties>

I got this code from the Open XML SDK productivity tool:

private static void ChangeCustomFilePropertiesPart(CustomFilePropertiesPart customFilePropertiesPart)
{
    CustomProperties.Properties properties = customFilePropertiesPart.Properties;

    CustomProperties.CustomDocumentProperty customDocumentProperty1 = properties.Elements<CustomProperties.CustomDocumentProperty>().ElementAt(4);
    CustomProperties.CustomDocumentProperty customDocumentProperty2 = properties.Elements<CustomProperties.CustomDocumentProperty>().ElementAt(5);

    VariantTypes.VTLPWSTR vTLPWSTR1 = customDocumentProperty1.GetFirstChild<VariantTypes.VTLPWSTR>();
    vTLPWSTR1.Text = "";

    VariantTypes.VTLPWSTR vTLPWSTR2 = customDocumentProperty2.GetFirstChild<VariantTypes.VTLPWSTR>();
    vTLPWSTR2.Text = "";

}

But I can't trust that the properties I want to remove are number four and five, so I have to find them by the name attribute before I remove the text. Can anyone help me? I would like to use linq or the Open XML SDK in some way.

Thanks!


问:
Check no of occurance of all digits in array using single for Loop or use Any Collection
```<code>Integer a[]={10,20,30,10,10,20,50,60,50,50};

for(int i=0;i<a.length;i++)
{

             int count=0;
            for(int j=0;j<a.length;j++)
            {

                if(a[i]==a[j])
                {
                    count++;

                }
            }
            System.out.println(a[i]+" occurs times ="+count);
            count=0;
}
</code>```

答:
Consider the following piece of code:   </p>

```<code> public class HelloWorld{

    public int static[] apps = new int[10]; // stores the nr. of appearences of each digit

    public static int calcNr(int a) // calculates for each element in the array
    {
        while(a>0)
        {
            apps[a%10]++;
            a = a/10;
        }
    }

    public static calcArray(int [] v)
    {
        for(int i = 0; i<v.length; i++)
            calcNr(v[i]);
    }

     public static void main(String []args){
        //...
        int n; // nr of elements
        int [] array = new array[n];
        calcArray(array);
     }
}
</code>```

Body:
Consider the following piece of code:

 public class HelloWorld{

    public int static[] apps = new int[10]; // stores the nr. of appearences of each digit

    public static int calcNr(int a) // calculates for each element in the array
    {
        while(a>0)
        {
            apps[a%10]++;
            a = a/10;
        }
    }

    public static calcArray(int [] v)
    {
        for(int i = 0; i<v.length; i++)
            calcNr(v[i]);
    }

     public static void main(String []args){
        //...
        int n; // nr of elements
        int [] array = new array[n];
        calcArray(array);
     }
}


问:
How to reduce boilerplate nested Result in Rust
I have code using a nested Result like this:

```<code>fn ip4(s: &str) -> Result<(u8, u8, u8, u8), num::ParseIntError> {
    let t: Vec<_> = s.split('.').collect();
    match t[0].parse::<u8>() {
        Ok(a1) => {
            match t[1].parse::<u8>() {
                Ok(a2) => {
                    match t[2].parse::<u8>() {
                        Ok(a3) => {
                            match t[3].parse::<u8>() {
                                Ok(a4) => {
                                    Ok((a1, a2, a3, a4))
                                }
                                Err(er) => Err(er)
                            }
                        },
                        Err(er) => Err(er)
                    }
                }
                Err(er) => Err(er)
            }
        }
        Err(er) => Err(er),
    }
}
</code>```

Is there any function or composing way to reduce this? Something like Haskell or Scala programmers do:

```<code>fn ip4(s: &str) -> Result<(u8, u8, u8, u8), num::ParseIntError> {
  let t: Vec<_> = s.split('.').collect();
  Result
  .lift((,,,))
  .ap(() -> t[0].parse::<u8>())
  .ap(() -> t[1].parse::<u8>())
  .ap(() -> t[2].parse::<u8>())
  .ap(() -> t[3].parse::<u8>()) // maybe more concise in Haskell or Scala but I think it's enough :)
}
</code>```

答:
Though, I do not see anything bad in @loganfsmyth's answer, I want to add another solution.

Your problem is a very simple and general problem of all programming languages which can be solved very easily if you would have enough time or practice in optimizing solutions. There is some divide and conquer recursive technique which is usually used to solve such problems. For a start, imagine a more simple thing: parsing a single octet from a string. This is a simple parse which you already know. Then mentally try to expand this problem to a larger one - parsing all octets which is a simple repeating process of the smallest problem we have solved earlier (parsing a single octet). This leads us to an iterative/recursive process: do something until. Keeping this in mind I have rewritten your function to a simple iterative process which uses tail-recursion which will not cause a stack overflow as a usual recursion due to it's form:

```<code>use std::num;

#[derive(Debug, Copy, Clone)]
struct IpAddressOctets(pub u8, pub u8, pub u8, pub u8);
type Result = std::result::Result<IpAddressOctets, num::ParseIntError>;

fn ipv4(s: &str) -> Result {
    let octets_str_array: Vec<_> = s.split('.').collect();

    // If it does not contain 4 octets then there is a error.
    if octets_str_array.len() != 4 {
        return Ok(IpAddressOctets(0, 0, 0, 0))  // or other error type
    }

    let octets = Vec::new();

    fn iter_parse(octets_str_array: Vec<&str>, mut octets: Vec<u8>) -> Result {
        if octets.len() == 4 {
            return Ok(IpAddressOctets(octets[0], octets[1], octets[2], octets[3]))
        }

        let index = octets.len();
        octets.push(octets_str_array[index].parse::<u8>()?);
        iter_parse(octets_str_array, octets)
    }

    iter_parse(octets_str_array, octets)
}

fn main() {
    println!("IP address octets parsed: {:#?}", ipv4("10.0.5.234"));
}
</code>```

Keep in mind that Rust language is a bit more functional than you might think.

Also, I would recommend you to read this book which greatly explains the solution.

Body:
I have code using a nested Result like this:

fn ip4(s: &str) -> Result<(u8, u8, u8, u8), num::ParseIntError> {
    let t: Vec<_> = s.split('.').collect();
    match t[0].parse::<u8>() {
        Ok(a1) => {
            match t[1].parse::<u8>() {
                Ok(a2) => {
                    match t[2].parse::<u8>() {
                        Ok(a3) => {
                            match t[3].parse::<u8>() {
                                Ok(a4) => {
                                    Ok((a1, a2, a3, a4))
                                }
                                Err(er) => Err(er)
                            }
                        },
                        Err(er) => Err(er)
                    }
                }
                Err(er) => Err(er)
            }
        }
        Err(er) => Err(er),
    }
}

Is there any function or composing way to reduce this? Something like Haskell or Scala programmers do:

fn ip4(s: &str) -> Result<(u8, u8, u8, u8), num::ParseIntError> {
  let t: Vec<_> = s.split('.').collect();
  Result
  .lift((,,,))
  .ap(() -> t[0].parse::<u8>())
  .ap(() -> t[1].parse::<u8>())
  .ap(() -> t[2].parse::<u8>())
  .ap(() -> t[3].parse::<u8>()) // maybe more concise in Haskell or Scala but I think it's enough :)
}

Body:
Though, I do not see anything bad in @loganfsmyth's answer, I want to add another solution.

Your problem is a very simple and general problem of all programming languages which can be solved very easily if you would have enough time or practice in optimizing solutions. There is some divide and conquer recursive technique which is usually used to solve such problems. For a start, imagine a more simple thing: parsing a single octet from a string. This is a simple parse which you already know. Then mentally try to expand this problem to a larger one - parsing all octets which is a simple repeating process of the smallest problem we have solved earlier (parsing a single octet). This leads us to an iterative/recursive process: do something until. Keeping this in mind I have rewritten your function to a simple iterative process which uses tail-recursion which will not cause a stack overflow as a usual recursion due to it's form:

use std::num;

#[derive(Debug, Copy, Clone)]
struct IpAddressOctets(pub u8, pub u8, pub u8, pub u8);
type Result = std::result::Result<IpAddressOctets, num::ParseIntError>;

fn ipv4(s: &str) -> Result {
    let octets_str_array: Vec<_> = s.split('.').collect();

    // If it does not contain 4 octets then there is a error.
    if octets_str_array.len() != 4 {
        return Ok(IpAddressOctets(0, 0, 0, 0))  // or other error type
    }

    let octets = Vec::new();

    fn iter_parse(octets_str_array: Vec<&str>, mut octets: Vec<u8>) -> Result {
        if octets.len() == 4 {
            return Ok(IpAddressOctets(octets[0], octets[1], octets[2], octets[3]))
        }

        let index = octets.len();
        octets.push(octets_str_array[index].parse::<u8>()?);
        iter_parse(octets_str_array, octets)
    }

    iter_parse(octets_str_array, octets)
}

fn main() {
    println!("IP address octets parsed: {:#?}", ipv4("10.0.5.234"));
}

Keep in mind that Rust language is a bit more functional than you might think.

Also, I would recommend you to read this book which greatly explains the solution.


问:
react & i18next, why do i need react-i18next
I am new to i18next and I dont really understand why there is a need to use react-i18next when playing with react.

Using an external library like moment.js in my component i do : const date = moment(this.state.date)

Can I do the something like below with i18next :

```<code>import i18next from 'i18next';

const translated = () => (
 <h1>{i18next.t('title')}</h1>
)
</code>```

Thanks

答: sure you can directly use i18next. react-i18next is only some optimization to use it in react -> eg. rerender on language change, or dynamic load of the namespaces using the hoc or render prop. Or the Trans component which allows you to nest react components into translations. But there is no magic, like there is no magic in jquery-i18next or vue-i18next -> it just simplifies your task.</p>

Body:
I am new to i18next and I dont really understand why there is a need to use react-i18next when playing with react.

Using an external library like moment.js in my component i do : const date = moment(this.state.date)

Can I do the something like below with i18next :

import i18next from 'i18next';

const translated = () => (

{i18next.t('title')}

)

Thanks


答:
You can use a Map<Integer, Integer>:

```<code>Map<Integer, Integer> map = new HashMap<>();

for(int i : a){
    map.compute(i, ( key, value ) -> value == null ? 1 : value + 1);
}
</code>```

Which results in map containing the items in the array a as Keys and the amount of occurances of that item as the Value

Title: Check no of occurance of all digits in array using single for Loop or use Any Collection

Body:
Integer a[]={10,20,30,10,10,20,50,60,50,50};

for(int i=0;i<a.length;i++)
{

             int count=0;
            for(int j=0;j<a.length;j++)
            {

                if(a[i]==a[j])
                {
                    count++;

                }
            }
            System.out.println(a[i]+" occurs times ="+count);
            count=0;
}

Body:
You can use a Map<Integer, Integer>:

Map<Integer, Integer> map = new HashMap<>();

for(int i : a){
    map.compute(i, ( key, value ) -> value == null ? 1 : value + 1);
}

Which results in map containing the items in the array a as Keys and the amount of occurances of that item as the Value


问:
How to read XML attributes in order using Java?
My background in C#. I am facing behavioral difference while retrieving attribute count in JAVA compared to C#.

XML:

```<code>    <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
    <book xmlns:v="urn:schemas-microsoft-com:vml" style="width:149.65pt"
    xmlns:w="urn:schemas-microsoft-com:office:office">
    <v:object w:dxaOrig="1440" w:dyaOrig="1440">
    </v:object>
    </book>
</code>```

In C#, the ‘Xmlns’ tag is considered as the attribute and hence while retrieving the attribute count the value is 3 for the above Xml element ‘book’. Whereas in JAVA (as per my understating, correct me if am wrong) ‘Xmlns’ is not an attribute, it is used as namespace declaration and it is also considered as reserved XML  pseudo-attribute to declare a namespace. So the attribute count for above case will be 1 in JAVA. I can retrieve the ‘xmlns’ tag as namespace count which is 2.

C# Code:

```<code>    for(int i=0;i<reader.AttributeCount;i++)
    {
    //Here the attribute count is 3
    }
</code>```

Java Code:

```<code>    for (int i = 0; i < reader.getAttributeCount(); i++) {
    //Here the attribute count is 1  }
</code>```

I have included a wrapper class for “XmlReader” to process attributes as in C# . Please refer the  wrapper method I have used to retrieve attribute count to meet c# behavior.

Java:

```<code>    public int getAttributeCount()
    {
    if (_reader.getEventType() == XMLStreamConstants.START_ELEMENT
            || _reader.getEventType() == XMLStreamConstants.ATTRIBUTE) {
        int i = 0;
        i = _reader.getAttributeCount();
        if (_reader.getNamespaceCount() > 0) {
            i += _reader.getNamespaceCount();

        }
        return i; //now the count will be 3.
        } else {
        return 0;
        }
        }
</code>```

My concern is I would like to know how to read the element”book” attributes in order as in C#. Since ‘xmlns’ tag is considered as namespace, it is only possible to process namespace and attribute separately and it’s difficult to know which is in first while iterating the attribute count. Kindly let me know your suggestions in this?

答:
xmlns is a reserved prefix/name  in XML.
As is explained here: http://www.w3.org/TR/xml-names/#xmlReserved

If you need to include those in you parse try handling the type

```<code>XmlStreamConstants.NAMESPACE
</code>```

as well

Body:
My background in C#. I am facing behavioral difference while retrieving attribute count in JAVA compared to C#.

XML:

    <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
    <book xmlns:v="urn:schemas-microsoft-com:vml" style="width:149.65pt"
    xmlns:w="urn:schemas-microsoft-com:office:office">
    <v:object w:dxaOrig="1440" w:dyaOrig="1440">
    </v:object>
    </book>

In C#, the ‘Xmlns’ tag is considered as the attribute and hence while retrieving the attribute count the value is 3 for the above Xml element ‘book’. Whereas in JAVA (as per my understating, correct me if am wrong) ‘Xmlns’ is not an attribute, it is used as namespace declaration and it is also considered as reserved XML  pseudo-attribute to declare a namespace. So the attribute count for above case will be 1 in JAVA. I can retrieve the ‘xmlns’ tag as namespace count which is 2.

C# Code:

    for(int i=0;i<reader.AttributeCount;i++)
    {
    //Here the attribute count is 3
    }

Java Code:

    for (int i = 0; i < reader.getAttributeCount(); i++) {
    //Here the attribute count is 1  }

I have included a wrapper class for “XmlReader” to process attributes as in C# . Please refer the  wrapper method I have used to retrieve attribute count to meet c# behavior.

Java:

    public int getAttributeCount()
    {
    if (_reader.getEventType() == XMLStreamConstants.START_ELEMENT
            || _reader.getEventType() == XMLStreamConstants.ATTRIBUTE) {
        int i = 0;
        i = _reader.getAttributeCount();
        if (_reader.getNamespaceCount() > 0) {
            i += _reader.getNamespaceCount();

        }
        return i; //now the count will be 3.
        } else {
        return 0;
        }
        }

My concern is I would like to know how to read the element”book” attributes in order as in C#. Since ‘xmlns’ tag is considered as namespace, it is only possible to process namespace and attribute separately and it’s difficult to know which is in first while iterating the attribute count. Kindly let me know your suggestions in this?

Body:
xmlns is a reserved prefix/name  in XML.
As is explained here: http://www.w3.org/TR/xml-names/#xmlReserved

If you need to include those in you parse try handling the type

XmlStreamConstants.NAMESPACE

as well


问:
Specific Linux distros for running high-reliability spaceflight software?
Edited for clarity:

With reliability and fault-tolerance being extremely important, are there any specific Linux distros (or perhaps types of Linux distros) recommended for running high-reliability C++ software?

I am developing C++ software to perform some simple tasks (reading serial-input data, setting logic highs and lows on output pins, taking video (and saving), and some floating point mathematics) aboard a Blue Origin rocket. The software will be running on Linux.

Thank you for your knowledge and experience.

答:
A company called Astronoutics is producing displays for airplanes. They have an "Electronic Flight Book" product on the Boing-787 dreamliner. Their main appeal is the ability to run two sets of applications. Highly reliable applications, which the pilot is allowed to rely on (certified applications) as well as uncertified applications, running on the same display.

In order to achieve this feat, their displays have two computers in them. One is running a certified operating system, and the other can run anything at all (usually Windows).

The certified OS they are running is Linux. It is not, however, your vanilla Linux. It is greatly stripped down version, with just enough functionality for what they need and no more. This is because the certification process itself is very expensive, and the number of lines greatly affects this.

So you can run Linux in high reliability environments, but it's not the usual Linux.


问:
Stream from WCF method is not correct when invoked from unit test
I have a wcf service as following:

```<code>public class DocumentReadService : IDocumentReader
{
    public Stream GetDocument(string docName)
    {
        //read file
        if (WebOperationContext.Current != null)
        {
            WebOperationContext.Current.OutgoingResponse.ContentType = "application/pdf";
        }
        //return file stream
    }
}
</code>```

But when I do unit test(using moq) the above method, I don't get expected stream which is a pdf if saved to a file.

Meaning the pdf should be same as that of what I get when I browse the same wcf service hosted url.

Could anybody give me some advice about this issue?

答:
I got it working, Issue was with the way stream was saved to file in unit test. It should be done with BinaryWriter as following and not as normal stream save to file,</p>

```<code>Stream serviceResult = documentReaderMock.GetDocument("abc");

using (FileStream fileStream = File.Create(_sourceFilePath + "\\DownloadedFile.pdf",(int)serviceResult.Length))
{
  BinaryWriter bw = new BinaryWriter(fileStream);
  byte[] bytesInStream = new byte[serviceResult.Length];
  serviceResult.Read(bytesInStream, 0, bytesInStream.Length);
  bw.Write(bytesInStream);
  bw.Close();
}
</code>```

Body:
I have a wcf service as following:

public class DocumentReadService : IDocumentReader
{
    public Stream GetDocument(string docName)
    {
        //read file
        if (WebOperationContext.Current != null)
        {
            WebOperationContext.Current.OutgoingResponse.ContentType = "application/pdf";
        }
        //return file stream
    }
}

But when I do unit test(using moq) the above method, I don't get expected stream which is a pdf if saved to a file.

Meaning the pdf should be same as that of what I get when I browse the same wcf service hosted url.

Could anybody give me some advice about this issue?

Body:
I got it working, Issue was with the way stream was saved to file in unit test. It should be done with BinaryWriter as following and not as normal stream save to file,

Stream serviceResult = documentReaderMock.GetDocument("abc");

using (FileStream fileStream = File.Create(_sourceFilePath + "\\DownloadedFile.pdf",(int)serviceResult.Length))
{
  BinaryWriter bw = new BinaryWriter(fileStream);
  byte[] bytesInStream = new byte[serviceResult.Length];
  serviceResult.Read(bytesInStream, 0, bytesInStream.Length);
  bw.Write(bytesInStream);
  bw.Close();
}


问:
Redis access from MS Excel?
I would like to use redis to query data from commandline, scripts, web and from within spreadsheets.  I can find good examples for all but spreadsheets...
I don't quite know where to start for access from a MS Excel spreadsheet, though.  Google is failing me.

Please let me know how you would suggest doing this, thanks!

p.s. for those unfamiliar redis is a key-value datastore described here: http://code.google.com/p/redis/

答: I think I found what I want with XLLoop http://xlloop.sourceforge.net/</p>

Title: Redis access from MS Excel?


问:
unable to retrieve $_POST variable in php
After searching a lot and working endlessly on this problem I decided to post here.
I am passing a formdata with a filename variable to php using ajax. I then try to access the variable name so I can pass it to a second php that loads the name into the database. I am unable to pass or echo the data in php though. Can anyone help?

My javascript

```<code>function uploadFile() {
  var input = document.getElementById("picture");
  file = input.files[0];
  newFileName = elementHandle[9].val() + elementHandle[10].val() + elementHandle[11].val();
  console.log(newFileName);
  if (file != undefined) {
    formData = new FormData();

    if (!!file.type.match(/image.*/)) {
      formData.append("newFileName1", newFileName);
      $.ajax({
        url: "upload_file.php",
        type: "POST",
        data: formData,
        processData: false,
        contentType: false,
        success: function(data) {}
      });
    } else {
      alert('Not a valid image!');
    }
  } else {
    alert('Input something!');
  }
}
</code>```

My php

```<code><?php
    $dir = "im_ges/";
    $file_name = $dir. $_REQUEST["newFileName1"].".jpg";
    echo $file_name;
    move_uploaded_file($_FILES["image"]["tmp_name"], $dir. $_POST ['newFileName1'].".jpg");
?>
</code>```

答:
Try this  sample  code

form.html

```<code><html>
  <head>
    <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
    <script>
      $(function () {

        $('form').on('submit', function (e) {

          e.preventDefault();

          $.ajax({
            type: 'post',
            url: 'post.php',
            data: new FormData(this), // Data sent to server, a set of key/value pairs (i.e. form fields and values)
            contentType: false,       // The content type used when sending data to the server.
            cache: false,             // To unable request pages to be cached
            processData:false,        // To send DOMDocument or non processed data file it is set to false
            success: function (responce) {
             alert(responce);
            }
          });

        });

      });
    </script>
  </head>
  <body>
    <form  action="" method="post" enctype="multipart/form-data"><form id="uploadimage" action="" method="post" enctype="multipart/form-data">
      <input name="name" value="First Name"><br>
      <input name="file" type ="file" ><br>
      <input name="submit" type="submit" value="Submit">
    </form>
  </body>
</html>
</code>```

create post.php

```<code>    echo "Name Value : ".$_POST["name"]."\n\n";
    echo "\n File Details\n";
    print_r($_FILES);
</code>```

This will alert the values from form

Body:
After searching a lot and working endlessly on this problem I decided to post here.
I am passing a formdata with a filename variable to php using ajax. I then try to access the variable name so I can pass it to a second php that loads the name into the database. I am unable to pass or echo the data in php though. Can anyone help?

My javascript

function uploadFile() {
  var input = document.getElementById("picture");
  file = input.files[0];
  newFileName = elementHandle[9].val() + elementHandle[10].val() + elementHandle[11].val();
  console.log(newFileName);
  if (file != undefined) {
    formData = new FormData();

    if (!!file.type.match(/image.*/)) {
      formData.append("newFileName1", newFileName);
      $.ajax({
        url: "upload_file.php",
        type: "POST",
        data: formData,
        processData: false,
        contentType: false,
        success: function(data) {}
      });
    } else {
      alert('Not a valid image!');
    }
  } else {
    alert('Input something!');
  }
}

My php

<?php
    $dir = "im_ges/";
    $file_name = $dir. $_REQUEST["newFileName1"].".jpg";
    echo $file_name;
    move_uploaded_file($_FILES["image"]["tmp_name"], $dir. $_POST ['newFileName1'].".jpg");
?>

Body:
Try this  sample  code

form.html

<html>
  <head>
    <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
    <script>
      $(function () {

        $('form').on('submit', function (e) {

          e.preventDefault();

          $.ajax({
            type: 'post',
            url: 'post.php',
            data: new FormData(this), // Data sent to server, a set of key/value pairs (i.e. form fields and values)
            contentType: false,       // The content type used when sending data to the server.
            cache: false,             // To unable request pages to be cached
            processData:false,        // To send DOMDocument or non processed data file it is set to false
            success: function (responce) {
             alert(responce);
            }
          });

        });

      });
    </script>
  </head>
  <body>
    <form  action="" method="post" enctype="multipart/form-data"><form id="uploadimage" action="" method="post" enctype="multipart/form-data">
      <input name="name" value="First Name"><br>
      <input name="file" type ="file" ><br>
      <input name="submit" type="submit" value="Submit">
    </form>
  </body>
</html>

create post.php

    echo "Name Value : ".$_POST["name"]."\n\n";
    echo "\n File Details\n";
    print_r($_FILES);

This will alert the values from form


问:
My class cannot be used as type parameter 'TEventArgs' in the generic type or method 'System.EventHandler<TEventArgs>' in .Net 4
I have trying to learn about EventHandler and I have to use a notification project.
Here is the link of project :
https://codeload.github.com/mike-eason/WPF_ToastNotifications/zip/master

All I did is changing .Net-framework from 4.5 to 4

And I faced with this error:

My class cannot be used as type parameter 'TEventArgs' in the generic
  type or method 'System.EventHandler'

ToastNotification Class:

```<code> [TemplatePart(Name = "PART_DismissButton", Type = typeof(Button))]
    public class ToastNotification : ContentControl
    {
        public event EventHandler Dismissed;

        public string Title
        {
            get { return (string)GetValue(TitleProperty); }
            set { SetValue(TitleProperty, value); }
        }

        public static readonly DependencyProperty TitleProperty =
            DependencyProperty.Register("Title", typeof(string), typeof(ToastNotification));

        public string Message
        {
            get { return (string)GetValue(MessageProperty); }
            set { SetValue(MessageProperty, value); }
        }

        public static readonly DependencyProperty MessageProperty =
            DependencyProperty.Register("Message", typeof(string), typeof(ToastNotification));

        public ToastTypes ToastType
        {
            get { return (ToastTypes)GetValue(ToastTypeProperty); }
            set { SetValue(ToastTypeProperty, value); }
        }

        public static readonly DependencyProperty ToastTypeProperty =
            DependencyProperty.Register("ToastType", typeof(ToastTypes), typeof(ToastNotification), new PropertyMetadata(new PropertyChangedCallback(OnToastTypeChanged)));

        private static void OnToastTypeChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            ToastNotification toast = (ToastNotification)d;

            toast.RefreshBackgroundColour();
        }

        private void RefreshBackgroundColour()
        {
            switch (ToastType)
            {
                case ToastTypes.Success:
                    Background = ColourSuccess;
                    break;
                case ToastTypes.Error:
                    Background = ColourDanger;
                    break;
                case ToastTypes.Info:
                    Background = ColourInfo;
                    break;
                case ToastTypes.Warning:
                    Background = ColourWarning;
                    break;
            }
        }

        public bool IsPersistent
        {
            get { return (bool)GetValue(IsPersistentProperty); }
            set { SetValue(IsPersistentProperty, value); }
        }

        public static readonly DependencyProperty IsPersistentProperty =
            DependencyProperty.Register("IsPersistent", typeof(bool), typeof(ToastNotification));

        public double FontSizeTitle
        {
            get { return (double)GetValue(FontSizeTitleProperty); }
            set { SetValue(FontSizeTitleProperty, value); }
        }

        public static readonly DependencyProperty FontSizeTitleProperty =
            DependencyProperty.Register("FontSizeTitle", typeof(double), typeof(ToastNotification));

        public Brush ColourSuccess
        {
            get { return (Brush)GetValue(ColourSuccessProperty); }
            set { SetValue(ColourSuccessProperty, value); }
        }

        public static readonly DependencyProperty ColourSuccessProperty =
            DependencyProperty.Register("ColourSuccess", typeof(Brush), typeof(ToastNotification));

        public Brush ColourDanger
        {
            get { return (Brush)GetValue(ColourDangerProperty); }
            set { SetValue(ColourDangerProperty, value); }
        }

        public static readonly DependencyProperty ColourDangerProperty =
            DependencyProperty.Register("ColourDanger", typeof(Brush), typeof(ToastNotification));

        public Brush ColourInfo
        {
            get { return (Brush)GetValue(ColourInfoProperty); }
            set { SetValue(ColourInfoProperty, value); }
        }

        public static readonly DependencyProperty ColourInfoProperty =
            DependencyProperty.Register("ColourInfo", typeof(Brush), typeof(ToastNotification));

        public Brush ColourWarning
        {
            get { return (Brush)GetValue(ColourWarningProperty); }
            set { SetValue(ColourWarningProperty, value); }
        }

        public static readonly DependencyProperty ColourWarningProperty =
            DependencyProperty.Register("ColourWarning", typeof(Brush), typeof(ToastNotification));

        static ToastNotification()
        {
            DefaultStyleKeyProperty.OverrideMetadata(typeof(ToastNotification), new FrameworkPropertyMetadata(typeof(ToastNotification)));
        }

        public ToastNotification()
        {
            this.Loaded += ToastNotification_Loaded;
        }

        private void ToastNotification_Loaded(object sender, RoutedEventArgs e)
        {
            Storyboard sb = this.FindResource("ToastScaleInStoryboard") as Storyboard;
            Storyboard.SetTarget(sb, this);
            sb.Begin();
        }

        public override void OnApplyTemplate()
        {
            ButtonBase PART_DismissButton = this.GetTemplateChild("PART_DismissButton") as ButtonBase;

            if (PART_DismissButton != null)
                PART_DismissButton.Click += OnDismissed;

            base.OnApplyTemplate();

            RefreshBackgroundColour();
        }

        protected void OnDismissed(object sender, RoutedEventArgs e)
        {
            var eh = Dismissed;

            if (eh != null)
                eh(this, EventArgs.Empty);
        }
    }
</code>```

Toast Class:

```<code>  internal class Toast
    {
        public event EventHandler<ToastNotification> ToastClosing;

        private DispatcherTimer _Timer;
        private ToastNotification _Notification;

        public Toast(ToastNotification notification)
        {
            _Notification = notification;

            _Notification.Dismissed += Notification_Dismissed;
        }

        private void Notification_Dismissed(object sender, EventArgs e)
        {
            OnToastClosing();
        }

        private void Timer_Tick(object sender, EventArgs e)
        {
            //Stop and close the window.
            _Timer.Stop();

            OnToastClosing();
        }

        public void Show(TimeSpan displayTime)
        {
            //Only start the timer if the notification is not persistent.
            if (!_Notification.IsPersistent)
            {
                //Set up the timer
                _Timer = new DispatcherTimer();
                _Timer.Interval = displayTime;
                _Timer.Tick += Timer_Tick;

                //Start the timer
                _Timer.Start();
            }
        }

        protected void OnToastClosing()
        {
            //Unsubscribe from the on dismiss event first (to avoid memory leaks)
            _Notification.Dismissed -= Notification_Dismissed;

            var eh = ToastClosing;

            if (eh != null)
                eh(this, _Notification);
        }
    }
</code>```

答:
```<code>public event Action<object, ToastNotification> ToastClosing;
</code>```

I think the recommendation is to inherit 'EventArgs'.

```<code>public class MyEventArgs : EventArgs
{ }

public event EventHandler<MyEventArgs> MyEvent;
</code>```

Body:
I have trying to learn about EventHandler and I have to use a notification project.
Here is the link of project :
https://codeload.github.com/mike-eason/WPF_ToastNotifications/zip/master

All I did is changing .Net-framework from 4.5 to 4

And I faced with this error:

My class cannot be used as type parameter 'TEventArgs' in the generic
  type or method 'System.EventHandler'

ToastNotification Class:

 [TemplatePart(Name = "PART_DismissButton", Type = typeof(Button))]
    public class ToastNotification : ContentControl
    {
        public event EventHandler Dismissed;

        public string Title
        {
            get { return (string)GetValue(TitleProperty); }
            set { SetValue(TitleProperty, value); }
        }

        public static readonly DependencyProperty TitleProperty =
            DependencyProperty.Register("Title", typeof(string), typeof(ToastNotification));

        public string Message
        {
            get { return (string)GetValue(MessageProperty); }
            set { SetValue(MessageProperty, value); }
        }

        public static readonly DependencyProperty MessageProperty =
            DependencyProperty.Register("Message", typeof(string), typeof(ToastNotification));

        public ToastTypes ToastType
        {
            get { return (ToastTypes)GetValue(ToastTypeProperty); }
            set { SetValue(ToastTypeProperty, value); }
        }

        public static readonly DependencyProperty ToastTypeProperty =
            DependencyProperty.Register("ToastType", typeof(ToastTypes), typeof(ToastNotification), new PropertyMetadata(new PropertyChangedCallback(OnToastTypeChanged)));

        private static void OnToastTypeChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            ToastNotification toast = (ToastNotification)d;

            toast.RefreshBackgroundColour();
        }

        private void RefreshBackgroundColour()
        {
            switch (ToastType)
            {
                case ToastTypes.Success:
                    Background = ColourSuccess;
                    break;
                case ToastTypes.Error:
                    Background = ColourDanger;
                    break;
                case ToastTypes.Info:
                    Background = ColourInfo;
                    break;
                case ToastTypes.Warning:
                    Background = ColourWarning;
                    break;
            }
        }

        public bool IsPersistent
        {
            get { return (bool)GetValue(IsPersistentProperty); }
            set { SetValue(IsPersistentProperty, value); }
        }

        public static readonly DependencyProperty IsPersistentProperty =
            DependencyProperty.Register("IsPersistent", typeof(bool), typeof(ToastNotification));

        public double FontSizeTitle
        {
            get { return (double)GetValue(FontSizeTitleProperty); }
            set { SetValue(FontSizeTitleProperty, value); }
        }

        public static readonly DependencyProperty FontSizeTitleProperty =
            DependencyProperty.Register("FontSizeTitle", typeof(double), typeof(ToastNotification));

        public Brush ColourSuccess
        {
            get { return (Brush)GetValue(ColourSuccessProperty); }
            set { SetValue(ColourSuccessProperty, value); }
        }

        public static readonly DependencyProperty ColourSuccessProperty =
            DependencyProperty.Register("ColourSuccess", typeof(Brush), typeof(ToastNotification));

        public Brush ColourDanger
        {
            get { return (Brush)GetValue(ColourDangerProperty); }
            set { SetValue(ColourDangerProperty, value); }
        }

        public static readonly DependencyProperty ColourDangerProperty =
            DependencyProperty.Register("ColourDanger", typeof(Brush), typeof(ToastNotification));

        public Brush ColourInfo
        {
            get { return (Brush)GetValue(ColourInfoProperty); }
            set { SetValue(ColourInfoProperty, value); }
        }

        public static readonly DependencyProperty ColourInfoProperty =
            DependencyProperty.Register("ColourInfo", typeof(Brush), typeof(ToastNotification));

        public Brush ColourWarning
        {
            get { return (Brush)GetValue(ColourWarningProperty); }
            set { SetValue(ColourWarningProperty, value); }
        }

        public static readonly DependencyProperty ColourWarningProperty =
            DependencyProperty.Register("ColourWarning", typeof(Brush), typeof(ToastNotification));

        static ToastNotification()
        {
            DefaultStyleKeyProperty.OverrideMetadata(typeof(ToastNotification), new FrameworkPropertyMetadata(typeof(ToastNotification)));
        }

        public ToastNotification()
        {
            this.Loaded += ToastNotification_Loaded;
        }

        private void ToastNotification_Loaded(object sender, RoutedEventArgs e)
        {
            Storyboard sb = this.FindResource("ToastScaleInStoryboard") as Storyboard;
            Storyboard.SetTarget(sb, this);
            sb.Begin();
        }

        public override void OnApplyTemplate()
        {
            ButtonBase PART_DismissButton = this.GetTemplateChild("PART_DismissButton") as ButtonBase;

            if (PART_DismissButton != null)
                PART_DismissButton.Click += OnDismissed;

            base.OnApplyTemplate();

            RefreshBackgroundColour();
        }

        protected void OnDismissed(object sender, RoutedEventArgs e)
        {
            var eh = Dismissed;

            if (eh != null)
                eh(this, EventArgs.Empty);
        }
    }

Toast Class:

  internal class Toast
    {
        public event EventHandler<ToastNotification> ToastClosing;

        private DispatcherTimer _Timer;
        private ToastNotification _Notification;

        public Toast(ToastNotification notification)
        {
            _Notification = notification;

            _Notification.Dismissed += Notification_Dismissed;
        }

        private void Notification_Dismissed(object sender, EventArgs e)
        {
            OnToastClosing();
        }

        private void Timer_Tick(object sender, EventArgs e)
        {
            //Stop and close the window.
            _Timer.Stop();

            OnToastClosing();
        }

        public void Show(TimeSpan displayTime)
        {
            //Only start the timer if the notification is not persistent.
            if (!_Notification.IsPersistent)
            {
                //Set up the timer
                _Timer = new DispatcherTimer();
                _Timer.Interval = displayTime;
                _Timer.Tick += Timer_Tick;

                //Start the timer
                _Timer.Start();
            }
        }

        protected void OnToastClosing()
        {
            //Unsubscribe from the on dismiss event first (to avoid memory leaks)
            _Notification.Dismissed -= Notification_Dismissed;

            var eh = ToastClosing;

            if (eh != null)
                eh(this, _Notification);
        }
    }

Body:
public event Action<object, ToastNotification> ToastClosing;

I think the recommendation is to inherit 'EventArgs'.

public class MyEventArgs : EventArgs
{ }

public event EventHandler<MyEventArgs> MyEvent;


问:
Is it a bad practice seeking a data in list by index multiple times?
I have like below code,

```<code>override fun onBindViewHolder(holder: ViewHolder, position: Int) {
    val view = holder.view
    view.apply {
        name.text = list[position].name
        age.text = list[position].age
        address1.text = list[position].address1
        address2.text = list[position].address2
        zip_code.text = list[position].zip_code
    }
}
</code>```

it's seeking the data multiple times to get each property, like name, age, address1..

And I'm wondered is it better assign the data to a variable and use it? like this,

```<code>val view = holder.view
val data = list[position]
view.apply {
    name.text = data.name
    age.text = data.age
    address1.text = data.address1
    address2.text = data.address2
    zip_code.text = data.zip_code
}
</code>```

Assigning to new variable is cost more?

Please advise me which is better and why?

答:
The second is probably better due to 2 reasons:

You don't have to access the list at a specified index multiple times, but only once (access costs depending on the actual implementation)

it's much more readable and also less error-prone to reduce these duplicates

Body:
I have like below code,

override fun onBindViewHolder(holder: ViewHolder, position: Int) {
    val view = holder.view
    view.apply {
        name.text = list[position].name
        age.text = list[position].age
        address1.text = list[position].address1
        address2.text = list[position].address2
        zip_code.text = list[position].zip_code
    }
}

it's seeking the data multiple times to get each property, like name, age, address1..

And I'm wondered is it better assign the data to a variable and use it? like this,

val view = holder.view
val data = list[position]
view.apply {
    name.text = data.name
    age.text = data.age
    address1.text = data.address1
    address2.text = data.address2
    zip_code.text = data.zip_code
}

Assigning to new variable is cost more?

Please advise me which is better and why?


问:
How to extract parts of nested multi-level JSON objects / array and flatten it with JavaScript
I'm working with the following data structure:

```<code>"data": {
    "products": [
        [
            {
                "category": "A",
                "items": [
                    {
                        "name": "Aloe",
                        "price": 10
                    },
                    {
                        "name": "Apples",
                        "price": 5
                    }
                ]
            },
            {
                "category": "B",
                "items": [
                    {
                        "name": "Bread",
                        "price": 5
                    }
                ]
            }
        ],
        [
            {
                "category": "C",
                "items": [
                    {
                        "name": "Candy",
                        "price": 5
                    },
                    {
                        "name": "Crayon",
                        "price": 5
                    }
                ]
            },
            {
                "category": "D",
                "items": [
                    {
                        "name": "Dice",
                        "price": 5
                    },
                    {
                        "name": "Doll",
                        "price": 10
                    }
                ]
            }
        ]
    ]
}
</code>```

I'd like extract parts of it to flatten so the results is as follows:

```<code>[
    {
        "name": "Aloe",
        "price": 10
    },
    {
        "name": "Apples",
        "price": 5
    },
    {
        "name": "Bread",
        "price": 5
    },
    {
        "name": "Candy",
        "price": 5
    },
    {
        "name": "Crayon",
        "price": 5
    },
    {
        "name": "Dice",
        "price": 5
    },
    {
        "name": "Doll",
        "price": 10
    }
]
</code>```

How can I accomplish this?

I have tried this:

```<code>for (var sets in data.products) {
  for (var categories in sets) {
    for (var items in categories) {
      for (var item in items) {
        // assemble new array
      }
    }
  }
}
</code>```

... but had problems looping through the children objects. I've found a couple other similar questions, but they seem to address simpler data structures, and flatten the entire object rather than parts of it.

Any pointers would be appreciated.

答:
You can use array#reduce, array#forEach and array#concat.

var input =  { data: { products: [[{ category: "A", items: [{ name: "Aloe", price: 10 }, { name: "Apples", price: 5 }] }, { category: "B", items: [{ name: "Bread", price: 5 }] }], [{ category: "C", items: [{ name: "Candy", price: 5 }, { name: "Crayon", price: 5 }] }, { category: "D", items: [{ name: "Dice", price: 5 }, { name: "Doll", price: 10 }] }]] } };

const result = input.data.products.reduce((res, arr) => {
  arr.forEach( o => res = res.concat(o.items));
  return res;
},[]);
console.log(result);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

Body:
I'm working with the following data structure:

"data": {
    "products": [
        [
            {
                "category": "A",
                "items": [
                    {
                        "name": "Aloe",
                        "price": 10
                    },
                    {
                        "name": "Apples",
                        "price": 5
                    }
                ]
            },
            {
                "category": "B",
                "items": [
                    {
                        "name": "Bread",
                        "price": 5
                    }
                ]
            }
        ],
        [
            {
                "category": "C",
                "items": [
                    {
                        "name": "Candy",
                        "price": 5
                    },
                    {
                        "name": "Crayon",
                        "price": 5
                    }
                ]
            },
            {
                "category": "D",
                "items": [
                    {
                        "name": "Dice",
                        "price": 5
                    },
                    {
                        "name": "Doll",
                        "price": 10
                    }
                ]
            }
        ]
    ]
}

I'd like extract parts of it to flatten so the results is as follows:

[
    {
        "name": "Aloe",
        "price": 10
    },
    {
        "name": "Apples",
        "price": 5
    },
    {
        "name": "Bread",
        "price": 5
    },
    {
        "name": "Candy",
        "price": 5
    },
    {
        "name": "Crayon",
        "price": 5
    },
    {
        "name": "Dice",
        "price": 5
    },
    {
        "name": "Doll",
        "price": 10
    }
]

How can I accomplish this?

I have tried this:

for (var sets in data.products) {
  for (var categories in sets) {
    for (var items in categories) {
      for (var item in items) {
        // assemble new array
      }
    }
  }
}

... but had problems looping through the children objects. I've found a couple other similar questions, but they seem to address simpler data structures, and flatten the entire object rather than parts of it.

Any pointers would be appreciated.

Body:
You can use array#reduce, array#forEach and array#concat.

var input =  { data: { products: [[{ category: "A", items: [{ name: "Aloe", price: 10 }, { name: "Apples", price: 5 }] }, { category: "B", items: [{ name: "Bread", price: 5 }] }], [{ category: "C", items: [{ name: "Candy", price: 5 }, { name: "Crayon", price: 5 }] }, { category: "D", items: [{ name: "Dice", price: 5 }, { name: "Doll", price: 10 }] }]] } };

const result = input.data.products.reduce((res, arr) => {
  arr.forEach( o => res = res.concat(o.items));
  return res;
},[]);
console.log(result);

.as-console-wrapper { max-height: 100% !important; top: 0; }


问:
Javascript executed only on page refresh when included using <jsp:include>
Hi I have included an html page into an adf jsff page using the tag <jsp:include>

```<code><f:facet name="parenContent">
            <jsp:include page="www/included.html"></jsp:include>
</f:facet>
</code>```

The page is rendered successfully, but the javascripts inside the included page is executed only on the refresh of the whole page (by manually refreshing).

included.html

```<code><html>
<head>
    <link rel="stylesheet" type="text/css" href="grapheditor.css">
</head>
<body class="geEditor">
    <script>console.log('loading page');</script>
    <h1>Hello</h1>
    <script>console.log("check");</script>
</body>
</html>
</code>```

When refreshed the page the script tag is executed. The same is the case with javascript included using

```<code><script type="text/javascript" src="javascript.js"></script>
</code>```

I have tried placing the script tag in both  and

I need to execute the js when the first time the page is loaded without a refresh. How is it possible?

Update

I tried giving a non existing path to the src in

On the first load it is not even trying to load this file. On page refresh it is giving 404 error for this file.

答:
You can call a javascript method on startup.

```<code><af:document>
 <af:clientListener method=“nameOfTheJavascriptMethod" type="load"/>
<af:resource type="javascript" source="/customJsCode.js"/> ...
</af:document>
</code>```

But I am not sure how can you prevent that from re-executing when user refreshes the browser.

Body:
Hi I have included an html page into an adf jsff page using the tag <jsp:include>

<f:facet name="parenContent">
            <jsp:include page="www/included.html"></jsp:include>
</f:facet>

The page is rendered successfully, but the javascripts inside the included page is executed only on the refresh of the whole page (by manually refreshing).

included.html

    <link rel="stylesheet" type="text/css" href="grapheditor.css">

Hello

When refreshed the page the script tag is executed. The same is the case with javascript included using

I have tried placing the script tag in both  and

I need to execute the js when the first time the page is loaded without a refresh. How is it possible?

Update

I tried giving a non existing path to the src in

On the first load it is not even trying to load this file. On page refresh it is giving 404 error for this file.

Body:
You can call a javascript method on startup.

<af:document>
 <af:clientListener method=“nameOfTheJavascriptMethod" type="load"/>
<af:resource type="javascript" source="/customJsCode.js"/> ...
</af:document>

But I am not sure how can you prevent that from re-executing when user refreshes the browser.


问:
How do I open a new window/tab and dynamically fill it with content?
I am building a website that displays recipes. Each recipe appears as part of a blog entry, and will have a link at the bottom to Print this recipe.

What I want to happen is a click on the link opens a new window and fills it with a print-friendly-styled version of the recipe, which is already inside its own
.

Can I do this with JS/jQuery alone, or do I need to process from the server side? Any ideas how to do this?

EDIT: What would be ideal would be to generate a PDF on the fly, but in lieu of that I'd like a new window, containing only the recipe, for the visitor to print out or save, as they see fit. Print-styles are nice, but most people don't know they exist and can't be bothered to check and see by printing out a page that doesn't look print ready.

答: You'll probably need to do a request to the server on the print page and fill in the form fields with the data.</p>


答:
```<code> System.Globalization.CultureInfo EnglishCulture = new
System.Globalization.CultureInfo("en-EN");
System.Globalization.CultureInfo GermanCulture = new
System.Globalization.CultureInfo("de-de");
</code>```

neccesary transformation,

```<code>double val;
if(double.TryParse("65,89875", System.Globalization.NumberStyles.Float,
GermanCulture,  out val))
{
string valInGermanFormat = val.ToString(GermanCulture);
string valInEnglishFormat = val.ToString(EnglishCulture);
 }

if(double.TryParse("65.89875", System.Globalization.NumberStyles.Float,
EnglishCulture,  out val))
{
string valInGermanFormat = val.ToString(GermanCulture);
string valInEnglishFormat = val.ToString(EnglishCulture);
 }
</code>```

Title: Convert number into culture specific

Body:
I have a number like  202667.4. I want to convert this to number based on culture.

For Ex:

In "de"(German) the number should be in 202.667,40.

Any help will be greatly appreciated.

Thanks.

Body:
 System.Globalization.CultureInfo EnglishCulture = new
System.Globalization.CultureInfo("en-EN");
System.Globalization.CultureInfo GermanCulture = new
System.Globalization.CultureInfo("de-de");

neccesary transformation,

double val;
if(double.TryParse("65,89875", System.Globalization.NumberStyles.Float,
GermanCulture,  out val))
{
string valInGermanFormat = val.ToString(GermanCulture);
string valInEnglishFormat = val.ToString(EnglishCulture);
 }

if(double.TryParse("65.89875", System.Globalization.NumberStyles.Float,
EnglishCulture,  out val))
{
string valInGermanFormat = val.ToString(GermanCulture);
string valInEnglishFormat = val.ToString(EnglishCulture);
 }


问:
WordPress: User with custom role cannot access wp-admin
First of all I am a WordPress learner. So sorry if my code looks stupid!

I have created a custom theme with a custom user role. I am not developing any plugin.

In my fucntions.php file I have written the following code to create a User role. Users assigned to this role are supposed to login to the admin but only be able to access their Profile pages.

```<code>add_action('init', 'yrc_cst_register_role_customer_service_rep');

/**
 * Register new user role
 */

function yrc_cst_register_role_customer_service_rep() {

    $wp_roles = new WP_Roles();

    $wp_roles->remove_role('subscriber');
    $wp_roles->remove_role('editor');
    $wp_roles->remove_role('contributor');
    $wp_roles->remove_role('author');

    $service_rep_caps = array(
        'read'              => false,
        'create_posts'      => false,
        'edit_posts'        => false,
        'edit_others_posts' => false,
        'publish_posts'     => false,
        'manage_categories' => false,
        'manage_options'    => false,
    );

    add_role('customer_service', __('Customer Service'), $service_rep_caps);
}
</code>```

I have removed all roles except Administrator, because no other role is required for this portal. Administrator will only create Users with Customer Service role.

I have no third party plugin installed in the system.

Users with the custom role are able to login to the system through a custom login page which is working OK. But whenever they are trying to access their Profile page the following error message comes up:

Sorry, you are not allowed to access this page.

Is there anything like 'edit_profile' => true?

I must be doing something wrong but my limited knowledge is not enough to figure this out. Any suggestion would be highly appreciated.

答:
You might be able to do it like this :

This should clone the subscriber role capabilities and create your role for it.

```<code>add_action('init', 'CreatecloneRoleSubscriber');

function CreatecloneRoleSubscriber()
{
    global $wp_roles;
    if ( ! isset( $wp_roles ) )
        $wp_roles = new WP_Roles();

    $sub = $wp_roles->get_role('Subscriber');
    //Adding a 'new_role' with all subscriber caps
    $wp_roles->add_role('customer_service', 'Customer Service', $sub->capabilities);
}
</code>```

EDIT : Read discussion in question comments

Body:
First of all I am a WordPress learner. So sorry if my code looks stupid!

I have created a custom theme with a custom user role. I am not developing any plugin.

In my fucntions.php file I have written the following code to create a User role. Users assigned to this role are supposed to login to the admin but only be able to access their Profile pages.

add_action('init', 'yrc_cst_register_role_customer_service_rep');

/**
 * Register new user role
 */

function yrc_cst_register_role_customer_service_rep() {

    $wp_roles = new WP_Roles();

    $wp_roles->remove_role('subscriber');
    $wp_roles->remove_role('editor');
    $wp_roles->remove_role('contributor');
    $wp_roles->remove_role('author');

    $service_rep_caps = array(
        'read'              => false,
        'create_posts'      => false,
        'edit_posts'        => false,
        'edit_others_posts' => false,
        'publish_posts'     => false,
        'manage_categories' => false,
        'manage_options'    => false,
    );

    add_role('customer_service', __('Customer Service'), $service_rep_caps);
}

I have removed all roles except Administrator, because no other role is required for this portal. Administrator will only create Users with Customer Service role.

I have no third party plugin installed in the system.

Users with the custom role are able to login to the system through a custom login page which is working OK. But whenever they are trying to access their Profile page the following error message comes up:

Sorry, you are not allowed to access this page.

Is there anything like 'edit_profile' => true?

I must be doing something wrong but my limited knowledge is not enough to figure this out. Any suggestion would be highly appreciated.

Body:
You might be able to do it like this :

This should clone the subscriber role capabilities and create your role for it.

add_action('init', 'CreatecloneRoleSubscriber');

function CreatecloneRoleSubscriber()
{
    global $wp_roles;
    if ( ! isset( $wp_roles ) )
        $wp_roles = new WP_Roles();

    $sub = $wp_roles->get_role('Subscriber');
    //Adding a 'new_role' with all subscriber caps
    $wp_roles->add_role('customer_service', 'Customer Service', $sub->capabilities);
}

EDIT : Read discussion in question comments


问:
how to join table in grid view in yii2
i want to join my company table name to employee id. here my code in
   employee model

```<code>   public function attributeLabels()
        {
            return [
               'id' => 'ID',
                //'company_id' => 'Company ID',
                'emp_name' => 'Emp Name',
                'emp_email' => 'Emp Email',
                'emp_salery' => 'Emp Salery',
            ];
        }

       public function getCompany()
       {
       return $this->hasOne(Company::className(),['id' => 'company_id']);

       }
</code>```

in index file i use this code

```<code>    <?php PJax::begin();?>
        <?= GridView::widget([
            'dataProvider' => $dataProvider,
            'filterModel' => $searchModel,
            'columns' => [
                //['class' => 'yii\grid\SerialColumn'],

                //'id',
                [
              'attribute' => 'company_id',
              'value' => 'company.name',
             ],
                'emp_name',
                'emp_email:email',
                'emp_salery',

                ['class' => 'yii\grid\ActionColumn'],
            ],
        ]); ?>
    <?php PJax::end();?></div>
</code>```

in employee search table i use this code

```<code>    public function search($params)
        {
            $query = Employee::find();
          $query->joinWith(['company']);
            // add conditions that should always apply here

            $dataProvider = new ActiveDataProvider([
                'query' => $query,
            ]);

            $this->load($params);

            if (!$this->validate()) {
                // uncomment the following line if you do not want to return any records when validation fails
                 $query->where('0=1');
                return $dataProvider;
            }

            // grid filtering conditions
            $query->andFilterWhere([
                'id' => $this->id,
            ]);

            $query->andFilterWhere(['like', 'company_id', $this->company_id])
                ->andFilterWhere(['like', 'emp_name', $this->emp_name])
                ->andFilterWhere(['like', 'emp_email', $this->emp_email])
                ->andFilterWhere(['like', 'emp_salery', $this->emp_salery])
                ->andFilterWhere(['like', 'Company.name', $this->company_id])
             ->andFilterWhere(['like', 'company.name', $this->company])
    ;

            return $dataProvider;
        }
</code>```

http://localhost/test/web/employee/

is shows in company field (not set)
    pls help me

答:
you can do this in two difference way : 1 . If you want use active record you must set property in first model you want to select it and join table with that like:

public $pin;

then when you get data you can access to pin in second table

the second way is you use asArray() that return all off data in both table
$model = News::find()->leftJoin('comment', 'news.id = comment.news_id')->asArray()->all();
then you can use it in your gridview

Title: how to join table in grid view in yii2

Body:
i want to join my company table name to employee id. here my code in
   employee model

   public function attributeLabels()
        {
            return [
               'id' => 'ID',
                //'company_id' => 'Company ID',
                'emp_name' => 'Emp Name',
                'emp_email' => 'Emp Email',
                'emp_salery' => 'Emp Salery',
            ];
        }

       public function getCompany()
       {
       return $this->hasOne(Company::className(),['id' => 'company_id']);

       }

in index file i use this code

    <?php PJax::begin();?>
        <?= GridView::widget([
            'dataProvider' => $dataProvider,
            'filterModel' => $searchModel,
            'columns' => [
                //['class' => 'yii\grid\SerialColumn'],

                //'id',
                [
              'attribute' => 'company_id',
              'value' => 'company.name',
             ],
                'emp_name',
                'emp_email:email',
                'emp_salery',

                ['class' => 'yii\grid\ActionColumn'],
            ],
        ]); ?>
    <?php PJax::end();?>

in employee search table i use this code

    public function search($params)
        {
            $query = Employee::find();
          $query->joinWith(['company']);
            // add conditions that should always apply here

            $dataProvider = new ActiveDataProvider([
                'query' => $query,
            ]);

            $this->load($params);

            if (!$this->validate()) {
                // uncomment the following line if you do not want to return any records when validation fails
                 $query->where('0=1');
                return $dataProvider;
            }

            // grid filtering conditions
            $query->andFilterWhere([
                'id' => $this->id,
            ]);

            $query->andFilterWhere(['like', 'company_id', $this->company_id])
                ->andFilterWhere(['like', 'emp_name', $this->emp_name])
                ->andFilterWhere(['like', 'emp_email', $this->emp_email])
                ->andFilterWhere(['like', 'emp_salery', $this->emp_salery])
                ->andFilterWhere(['like', 'Company.name', $this->company_id])
             ->andFilterWhere(['like', 'company.name', $this->company])
    ;

            return $dataProvider;
        }

http://localhost/test/web/employee/

is shows in company field (not set)
    pls help me


问:
SLIME on Emacs with paredit in repl - how to prevent execution of incomplete but balanced expressions?
I use paredit on emacs with SLIME's repl. This means that at any point during my typing on the repl, my s-expressions are balanced.

However, they may not be complete, and I might want to continue typing inside them in another line, as follows:

```<code>CL-USER> (defun print-hello ()
            )
</code>```

When I start a new line by pressing the enter key, however, the SLIME repl executes my incomplete expression. I want it to wait for me to complete the expression, as follows:

```<code>CL-USER> (defun print-hello ()
            (format t "Hello, world"))
</code>```

How do I make this happen please?

答:
For that situations, when writing long s-expressions in REPL I think that the best way is to use the slime scratch buffer. you can edit it and after that execute with

C-j

No problem pressing enter inside the buffer, I'm using sly but the capture could be like this:

```<code>(defun print-hello ()
            (format t "Hello, world"))
 ; => PRINT-HELLO
</code>```

Also another alternative is working without the last parent :-(

or as suggested in a comment by @jkiisky, type the expression and add in the middle of the s expression C-j

```<code>CL-USER> (defun
)
</code>```

Body:
I use paredit on emacs with SLIME's repl. This means that at any point during my typing on the repl, my s-expressions are balanced.

However, they may not be complete, and I might want to continue typing inside them in another line, as follows:

CL-USER> (defun print-hello ()
            )

When I start a new line by pressing the enter key, however, the SLIME repl executes my incomplete expression. I want it to wait for me to complete the expression, as follows:

CL-USER> (defun print-hello ()
            (format t "Hello, world"))

How do I make this happen please?

Body:
For that situations, when writing long s-expressions in REPL I think that the best way is to use the slime scratch buffer. you can edit it and after that execute with

C-j

No problem pressing enter inside the buffer, I'm using sly but the capture could be like this:

(defun print-hello ()
            (format t "Hello, world"))
 ; => PRINT-HELLO

Also another alternative is working without the last parent :-(

or as suggested in a comment by @jkiisky, type the expression and add in the middle of the s expression C-j

CL-USER> (defun
)