问:
Access to existing html
How to handle click on existing html anchor in react?

For example:
Before react loading we got code like this

click me

```

<pre class="lang-js prettyprint-override"><code>// App Component should contains logic for click listener
ReactDOM.render(<App />, document.getElementById('root')
</code>```

So, is it possible to interact with existing html dom in react or it only provides the ability to work with rendered inside react components?

答:
It is, as far as I know, not possible to do what you ask.

The best workaround I can think of would be something like this:

```<code><div id="root">
  <a href="/some_href">click me</a>
</div>
</code>```

```<code>ReactDOM.render(<App>
  <a href="/some_href" onClick={react should execute me}>click me</a>
</App>, document.getElementById('root')
</code>```

The original link would be removed as soon as React mounts, and replaced with a similar one wired to React.

Title: Access to existing html

Body:
How to handle click on existing html anchor in react?

For example:
Before react loading we got code like this

click me

// App Component should contains logic for click listener
ReactDOM.render(<App />, document.getElementById('root')

So, is it possible to interact with existing html dom in react or it only provides the ability to work with rendered inside react components?

Body:
It is, as far as I know, not possible to do what you ask.

The best workaround I can think of would be something like this:

<div id="root">
  <a href="/some_href">click me</a>
</div>

ReactDOM.render(<App>
  <a href="/some_href" onClick={react should execute me}>click me</a>
</App>, document.getElementById('root')

The original link would be removed as soon as React mounts, and replaced with a similar one wired to React.


来源: stackexchange

问:
Caching with service workers - Chrome & Android Webview
I work on an old application that used ApplicationCache to work offline. Because of its deprecation, we would like to move to Service Workers to achieve the same goal.

Firefox 67 works very well with my current service worker implementation: when I first access to the application, every file listed as 'to-be-cached' is effectively downloaded and cached. The app can then be accessed offline.

Nevertheless, Chrome 74 and Android WebView (which looks like to be based on Chrome 73 - inside a Cordova app) have a slightly different comportment. When I first access to the application, a request per 'to-be-cached' file is put inside the cache. Navigating through the app works great when I'm online. But then I switch offline and only pages I have already accessed to are now accessible.

Is this a bug or a feature? Whatever it is, is there any workaround?

答:
Finally, here is what I have understood: Firefox compares cached resources on their URLs (string). Thus, giving a list of URLs (string) is sufficient for Firefox to cache them and retrieve them later with a Request object (sent when browsing the web application).

Chrome apparently compares cached resources on another value (I haven't managed to find which one). Then, giving a list of URLs (string) wasn't sufficient for Chrome. Request objects and URLs (string) were not recognized as the same.

Based on W3C's specification cache.addAll method, Chrome behaviour should be the right one. But Firefox behaviour is simplier.

ContentLicense: CC BY-SA 4.0


问:
Tomcat STDOUT as Error in Eclipse
I am configuring Tomcat (5.5) server in Eclipse (3.3.2). Once I add Tomcat and start it, the output is printed in Eclipse Console. This output is printed in RED indicating its Standard Error. Although the server gets started without any error the normal INFO is also marked as error.

```<code>Jul 29, 2010 7:06:14 PM org.apache.catalina.core.AprLifecycleListener init
INFO: The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: C:\Program Files\Java\jdk1.5.0_10\bin;.;C:\WINDOWS\system32;C:\WINDOWS;C:\Program Files\Java\jdk1.5.0_10\bin\..\jre\bin\client;C:\Program Files\Java\jdk1.5.0_10\bin\..\jre\bin;C:\Program Files\CollabNet Subversion Client;C:\Program Files\Java\jdk1.5.0_10\bin;C:\Program Files\Java\jre1.5.0_07\bin;C:\Program Files\Oracle\Oracle9i\9201\bin;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\Program Files\Sybase125\OCS-12_5\bin;C:\Program Files\Sybase125\OCS-12_5\dll;C:\Program Files\Sybase125\OLEDB;C:\Program Files\Rational\ClearCase\bin;C:\Program Files\Ubsw\Wire\Core;Z:\ZUR_GCOMP_DOC\Project_Trust\datamodel\scripts\GC_trust\Release\1.36\01-DDL;K:\scripts\;C:\Program Files\Ubsw\Wire\Core\;C:\Program Files\TortoiseSVN\bin;C:\Program Files\Windows Imaging\;C:\Program Files\MySQL\MySQL Server 5.1\bin;C:\Program Files\apache-maven-2.2.1\bin;C:\Program Files\apache-ant-1.7.0\bin;C:\Viral\Tech\Java\javadb/bin;C:\Program Files\JAD
Jul 29, 2010 7:06:15 PM org.apache.coyote.http11.Http11BaseProtocol init
INFO: Initializing Coyote HTTP/1.1 on http-8080
Jul 29, 2010 7:06:15 PM org.apache.catalina.startup.Catalina load
INFO: Initialization processed in 1187 ms
Jul 29, 2010 7:06:15 PM org.apache.catalina.core.StandardService start
INFO: Starting service Catalina
Jul 29, 2010 7:06:15 PM org.apache.catalina.core.StandardEngine start
INFO: Starting Servlet Engine: Apache Tomcat/5.5.30
Jul 29, 2010 7:06:15 PM org.apache.catalina.core.StandardHost start
INFO: XML validation disabled
Jul 29, 2010 7:06:15 PM org.apache.coyote.http11.Http11BaseProtocol start
INFO: Starting Coyote HTTP/1.1 on http-8080
Jul 29, 2010 7:06:15 PM org.apache.jk.common.ChannelSocket init
INFO: JK: ajp13 listening on /0.0.0.0:8009
Jul 29, 2010 7:06:15 PM org.apache.jk.server.JkMain start
INFO: Jk running ID=0 time=0/110  config=null
Jul 29, 2010 7:06:15 PM org.apache.catalina.storeconfig.StoreLoader load
INFO: Find registry server-registry.xml at classpath resource
Jul 29, 2010 7:06:15 PM org.apache.catalina.startup.Catalina start
INFO: Server startup in 922 ms
</code>```

Can anyone let me know how to overcome this and change the output back to BLACK as STDOUT?

答:
There is a short answer to your question :

Right clic in Console view > Preferences...

and then set "Standard Error text color" to black.

But of course, it would be better if Eclipse knew that Tomcat server log is not to be shown in red.

It looks like there are no better answers for now :
http://www.eclipse.org/forums/index.php?t=msg&goto=531848&

The problem can be reproduced with Tomcat 6 and Tomcat 7 in Eclipse 3.6.2

ContentLicense: CC BY-SA 2.5

Title: Tomcat STDOUT as Error in Eclipse

Body:
I am configuring Tomcat (5.5) server in Eclipse (3.3.2). Once I add Tomcat and start it, the output is printed in Eclipse Console. This output is printed in RED indicating its Standard Error. Although the server gets started without any error the normal INFO is also marked as error.

Jul 29, 2010 7:06:14 PM org.apache.catalina.core.AprLifecycleListener init
INFO: The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: C:\Program Files\Java\jdk1.5.0_10\bin;.;C:\WINDOWS\system32;C:\WINDOWS;C:\Program Files\Java\jdk1.5.0_10\bin\..\jre\bin\client;C:\Program Files\Java\jdk1.5.0_10\bin\..\jre\bin;C:\Program Files\CollabNet Subversion Client;C:\Program Files\Java\jdk1.5.0_10\bin;C:\Program Files\Java\jre1.5.0_07\bin;C:\Program Files\Oracle\Oracle9i\9201\bin;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\Program Files\Sybase125\OCS-12_5\bin;C:\Program Files\Sybase125\OCS-12_5\dll;C:\Program Files\Sybase125\OLEDB;C:\Program Files\Rational\ClearCase\bin;C:\Program Files\Ubsw\Wire\Core;Z:\ZUR_GCOMP_DOC\Project_Trust\datamodel\scripts\GC_trust\Release\1.36\01-DDL;K:\scripts\;C:\Program Files\Ubsw\Wire\Core\;C:\Program Files\TortoiseSVN\bin;C:\Program Files\Windows Imaging\;C:\Program Files\MySQL\MySQL Server 5.1\bin;C:\Program Files\apache-maven-2.2.1\bin;C:\Program Files\apache-ant-1.7.0\bin;C:\Viral\Tech\Java\javadb/bin;C:\Program Files\JAD
Jul 29, 2010 7:06:15 PM org.apache.coyote.http11.Http11BaseProtocol init
INFO: Initializing Coyote HTTP/1.1 on http-8080
Jul 29, 2010 7:06:15 PM org.apache.catalina.startup.Catalina load
INFO: Initialization processed in 1187 ms
Jul 29, 2010 7:06:15 PM org.apache.catalina.core.StandardService start
INFO: Starting service Catalina
Jul 29, 2010 7:06:15 PM org.apache.catalina.core.StandardEngine start
INFO: Starting Servlet Engine: Apache Tomcat/5.5.30
Jul 29, 2010 7:06:15 PM org.apache.catalina.core.StandardHost start
INFO: XML validation disabled
Jul 29, 2010 7:06:15 PM org.apache.coyote.http11.Http11BaseProtocol start
INFO: Starting Coyote HTTP/1.1 on http-8080
Jul 29, 2010 7:06:15 PM org.apache.jk.common.ChannelSocket init
INFO: JK: ajp13 listening on /0.0.0.0:8009
Jul 29, 2010 7:06:15 PM org.apache.jk.server.JkMain start
INFO: Jk running ID=0 time=0/110  config=null
Jul 29, 2010 7:06:15 PM org.apache.catalina.storeconfig.StoreLoader load
INFO: Find registry server-registry.xml at classpath resource
Jul 29, 2010 7:06:15 PM org.apache.catalina.startup.Catalina start
INFO: Server startup in 922 ms

Can anyone let me know how to overcome this and change the output back to BLACK as STDOUT?

ContentLicense: CC BY-SA 3.0


问:
Ignore Self-Signed Certificates
I have this code that lists all local computer SSL certificates details and stores them in a csv file. yet,There are some self-signed certificates that I  found them useless so I want to exclude them from appearing and I could not get it right

Below is the code I wrote

```<code>$StartDate = Get-Date
$CertPath = 'Cert:\LocalMachine\'
$CertsDetail = Get-ChildItem -Path $CertPath -Recurse | Where-Object {
$_.PsIsContainer -ne $true} | ForEach-Object {
$DaysLeft = (New-TimeSpan -Start $StartDate -End $_.NotAfter).Days
if ($DaysLeft -lt 1) {
    $Under30 = $true
    $Expired = $true
    $Text = "The Certificate is expired"
} elseif ($DaysLeft -lt 30) {
    $Under30 = $true
    $Expired = $false
    $Text = "The Certificate is but valid about to expire"
} else {
    $Under30 = $false
    $Expired = $false
    $Text = "The Certificate is still valid and not going soon to expire"
}
$FinalDate = Get-Date $_.NotAfter -Format 'dd/MM/yyyy hh:mm'
$Usages = ($_.Extensions | Where-Object {$_.KeyUsages}).KeyUsages
if ($Usages) {

$issuer = '{0}, {1}' -f
                     ([regex] 'O=([^,]+)').Match($_.Issuer).Groups[1].Value,
                     ([regex] 'CN=([^,]+)').Match($_.Issuer).Groups[1].Value
$issuer = $issuer.Trim(", ")
[PSCustomObject]@{
    Text         = $Text
    Issuer  = $issuer.TrimStart('"')

    Subject       = $_.Subject
    ExpireDate    = $FinalDate
    DaysRemaining = $DaysLeft
    Usages  = $Usages.ToString() -replace ',', ';'
    Under30Days   = $Under30
    Expired       = $Expired

}
}
}

$CertsDetail | Where-Object {$_.DaysRemaining -lt 3650 -and $_.Usages -ne ""
 } | Export-Csv -NoTypeInformation -Path 'C:\SECnology\Data\Utilities\Certificate_State.csv'
</code>```

答:
For self-signed certificates, the Subject and Issuer fields will be the same:

```<code># Filter out self-signed certificates
Get-ChildItem -Path $CertPath -Recurse |Where { $_.Subject -ne $_.Issuer }
</code>```

Title: Ignore Self-Signed Certificates

Body:
I have this code that lists all local computer SSL certificates details and stores them in a csv file. yet,There are some self-signed certificates that I  found them useless so I want to exclude them from appearing and I could not get it right

Below is the code I wrote

$StartDate = Get-Date
$CertPath = 'Cert:\LocalMachine\'
$CertsDetail = Get-ChildItem -Path $CertPath -Recurse | Where-Object {
$_.PsIsContainer -ne $true} | ForEach-Object {
$DaysLeft = (New-TimeSpan -Start $StartDate -End $_.NotAfter).Days
if ($DaysLeft -lt 1) {
    $Under30 = $true
    $Expired = $true
    $Text = "The Certificate is expired"
} elseif ($DaysLeft -lt 30) {
    $Under30 = $true
    $Expired = $false
    $Text = "The Certificate is but valid about to expire"
} else {
    $Under30 = $false
    $Expired = $false
    $Text = "The Certificate is still valid and not going soon to expire"
}
$FinalDate = Get-Date $_.NotAfter -Format 'dd/MM/yyyy hh:mm'
$Usages = ($_.Extensions | Where-Object {$_.KeyUsages}).KeyUsages
if ($Usages) {

$issuer = '{0}, {1}' -f
                     ([regex] 'O=([^,]+)').Match($_.Issuer).Groups[1].Value,
                     ([regex] 'CN=([^,]+)').Match($_.Issuer).Groups[1].Value
$issuer = $issuer.Trim(", ")
[PSCustomObject]@{
    Text         = $Text
    Issuer  = $issuer.TrimStart('"')

    Subject       = $_.Subject
    ExpireDate    = $FinalDate
    DaysRemaining = $DaysLeft
    Usages  = $Usages.ToString() -replace ',', ';'
    Under30Days   = $Under30
    Expired       = $Expired

}
}
}

$CertsDetail | Where-Object {$_.DaysRemaining -lt 3650 -and $_.Usages -ne ""
 } | Export-Csv -NoTypeInformation -Path 'C:\SECnology\Data\Utilities\Certificate_State.csv'

Body:
For self-signed certificates, the Subject and Issuer fields will be the same:

# Filter out self-signed certificates
Get-ChildItem -Path $CertPath -Recurse |Where { $_.Subject -ne $_.Issuer }


问:
Ansible playbook with variable
Trying to run script with different arguments on different servers using ansible, example:

```<code>server 192.168.0.1 -> fabric.sh generic1 status
server 192.168.0.2 -> fabric.sh generic2dr status
server 192.168.0.3 -> fabric.sh generic3 status
</code>```

How to use variables in playbook below?

It works when I create group for each server, but it's not efficient

```<code>---
- hosts: esb
  remote_user: root
  tasks:
  - name: Generic_1
    become_user: esb
    shell: "/home/fabric.sh generic1 status"
</code>```

Host file:

```<code>[esb]
192.168.0.1
192.168.0.2
192.168.0.3
</code>```

答:
You can set per-host variables in your inventory.  For example, modify your inventory so it looks like this:

```<code>[esb]
192.168.0.1 fabric_args="generic1 status"
192.168.0.2 fabric_args="generic2dr status"
192.168.0.3 fabric_args="generic3 status"
</code>```

And then use the fabric_args variable in your playbook:

```<code>---
- hosts: esb
  remote_user: root
  tasks:
  - name: Generic_1
    become_user: esb
    shell: "/home/fabric.sh {{ fabric_args }}"
</code>```

For more information, read the Using Variables and Working with Inventory sections of the Ansible documentation.

Title: Ansible playbook with variable

Body:
Trying to run script with different arguments on different servers using ansible, example:

server 192.168.0.1 -> fabric.sh generic1 status
server 192.168.0.2 -> fabric.sh generic2dr status
server 192.168.0.3 -> fabric.sh generic3 status

How to use variables in playbook below?

It works when I create group for each server, but it's not efficient

---
- hosts: esb
  remote_user: root
  tasks:
  - name: Generic_1
    become_user: esb
    shell: "/home/fabric.sh generic1 status"

Host file:

[esb]
192.168.0.1
192.168.0.2
192.168.0.3

Body:
You can set per-host variables in your inventory.  For example, modify your inventory so it looks like this:

[esb]
192.168.0.1 fabric_args="generic1 status"
192.168.0.2 fabric_args="generic2dr status"
192.168.0.3 fabric_args="generic3 status"

And then use the fabric_args variable in your playbook:

---
- hosts: esb
  remote_user: root
  tasks:
  - name: Generic_1
    become_user: esb
    shell: "/home/fabric.sh {{ fabric_args }}"

For more information, read the Using Variables and Working with Inventory sections of the Ansible documentation.


问:
Javascript (ES6) Date to String format
In Javascript I have Date object which I need to convert to string of format dd.mm.yyyy and dd.mm.yyyy hh24:mi:ss. How do I format the Date in Javascript?

答:
Looks like a German locale format, so you can use Date.toLocaleDateString() and Date.toLocaleTimeString() with a German locale setting (de-DE):

const date = new Date();

const dateString = date.toLocaleDateString('de-DE');
const timeString = date.toLocaleTimeString('de-DE');

const string = `${dateString} ${timeString}`;

console.log(string);```

Title: Javascript (ES6) Date to String format


问:
How to add up unique values from table in SQL
I have a table in SQL that looks like this

```<code>Person  brand   brand_spend category    category_spend
0   p1  b1       20           c1           100
1   p1  b2       50           c1           100
2   p2  b1       25           c2           40
3   p1  b3       30           c1           100
4   p1  b2       15           c2           70
</code>```

I need to tag every customer based on percentage spend he has made  at a brand based on total category spend where that brand is present.
So essentially I would want to tag Person p1 for brand b1' as percentage spend at 'b1 which should be calculated as  45/ 140

How this can be achieved. If I roll up on brand level to find total category spend then I think duplicates rows would add up.

I just want to find customer's Spend at a brand based on total spend at Brand for all categories where that brand is present.

答:
Sometimes things are not as complicated as it seems and a simple query does the trick.

```<code>select person , brand , sum(prsn_brand_spend) ,
sum(category_spend)  , (sum(prsn_brand_spend)/sum(category_spend)) as perc_spend
from tbl group by person , brand
</code>```

The Results are

```<code>person  brand   brand_spend category_spend  perc
    p1  b1       20            100           0.200000
    p1  b2       65            170          0.382353
    p1  b3       30            100          0.300000
    p2  b1       25            40          0.625000
</code>```

Body:
I have a table in SQL that looks like this

Person  brand   brand_spend category    category_spend
0   p1  b1       20           c1           100
1   p1  b2       50           c1           100
2   p2  b1       25           c2           40
3   p1  b3       30           c1           100
4   p1  b2       15           c2           70

I need to tag every customer based on percentage spend he has made  at a brand based on total category spend where that brand is present.
So essentially I would want to tag Person p1 for brand b1' as percentage spend at 'b1 which should be calculated as  45/ 140

How this can be achieved. If I roll up on brand level to find total category spend then I think duplicates rows would add up.

I just want to find customer's Spend at a brand based on total spend at Brand for all categories where that brand is present.

Body:
Sometimes things are not as complicated as it seems and a simple query does the trick.

select person , brand , sum(prsn_brand_spend) ,
sum(category_spend)  , (sum(prsn_brand_spend)/sum(category_spend)) as perc_spend
from tbl group by person , brand

The Results are

person  brand   brand_spend category_spend  perc
    p1  b1       20            100           0.200000
    p1  b2       65            170          0.382353
    p1  b3       30            100          0.300000
    p2  b1       25            40          0.625000


问:
Android Picasso library not loading image from URL
For some reason Picasso is not loading image from URLs. I just see a blank white screen.
I have already tried doing solutions to previous questions like these but nothing works for me.

Here is the Java code of Activity:

```<code>public class MainActivity extends AppCompatActivity {

    ImageView mImageView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mImageView = (ImageView) findViewById(R.id.picassoImage);
        Picasso.with(this).load("https://futurestud.io/images/books/picasso.png").into(mImageView);
    }
}
</code>```

And here is the XML layout code:

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.sourabh.usingpicasso.MainActivity">

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/picassoImage"/>

</LinearLayout>
</code>```

Note:-

I tried with different URLs but no luck.

I have already set the permission for Internet in Manifest.XML

When I chain the error with Picasso.with(this).load("https://futurestud.io/images/books/picasso.png").into(mImageView)(ie

Picasso.with(this).load("https://futurestud.io/images/books/picasso.png")
                .error(R.drawable.ic_launcher_background).
                into(mImageView);

) and pass to it an Image from the drawable, the drawable image is displayed. Seems that Picasso is not loading image from URLs only.

答:
Please check https://github.com/square/picasso for Picasso library in details.

Maybe you are using the previous version. Please add following line in your app level build.gradle file.

```<code>implementation 'com.squareup.picasso:picasso:2.71828'
</code>```

Then in your activity do this.

```<code>public class MainActivity extends AppCompatActivity {

    ImageView mImageView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mImageView = (ImageView) findViewById(R.id.picassoImage);
        Picasso.get()
                .load("https://futurestud.io/images/books/picasso.png")
                .placeholder(R.drawable.placeholder_image)
                .error(R.drawable.error_image)
                .into(mImageView);
    }
}
</code>```

Body:
For some reason Picasso is not loading image from URLs. I just see a blank white screen.
I have already tried doing solutions to previous questions like these but nothing works for me.

Here is the Java code of Activity:

public class MainActivity extends AppCompatActivity {

    ImageView mImageView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mImageView = (ImageView) findViewById(R.id.picassoImage);
        Picasso.with(this).load("https://futurestud.io/images/books/picasso.png").into(mImageView);
    }
}

And here is the XML layout code:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.sourabh.usingpicasso.MainActivity">

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/picassoImage"/>

</LinearLayout>

Note:-

I tried with different URLs but no luck.

I have already set the permission for Internet in Manifest.XML

When I chain the error with Picasso.with(this).load("https://futurestud.io/images/books/picasso.png").into(mImageView)(ie

Picasso.with(this).load("https://futurestud.io/images/books/picasso.png")
                .error(R.drawable.ic_launcher_background).
                into(mImageView);

) and pass to it an Image from the drawable, the drawable image is displayed. Seems that Picasso is not loading image from URLs only.

Body:
Please check https://github.com/square/picasso for Picasso library in details.

Maybe you are using the previous version. Please add following line in your app level build.gradle file.

implementation 'com.squareup.picasso:picasso:2.71828'

Then in your activity do this.

public class MainActivity extends AppCompatActivity {

    ImageView mImageView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mImageView = (ImageView) findViewById(R.id.picassoImage);
        Picasso.get()
                .load("https://futurestud.io/images/books/picasso.png")
                .placeholder(R.drawable.placeholder_image)
                .error(R.drawable.error_image)
                .into(mImageView);
    }
}


答:
You can use momentjs library for your requirement.

```<code>constructor(  ) {
  let now = moment().format("YYYY-MM-DD HH:mm:ss");
  let now2 = moment().format("DD.MM.YYYY");
     this.format1 = now;
     this.format2 = now2;
     console.log(now);

    this.date = moment(this.format1, "YYYY-MM-DD HH:mm:ss");

  }
</code>```

https://stackblitz.com/edit/momentjs-format-date?file=app/app.component.ts

Title: Javascript (ES6) Date to String format

Body: In Javascript I have Date object which I need to convert to string of format dd.mm.yyyy and dd.mm.yyyy hh24:mi:ss. How do I format the Date in Javascript?

Body:
You can use momentjs library for your requirement.

constructor(  ) {
  let now = moment().format("YYYY-MM-DD HH:mm:ss");
  let now2 = moment().format("DD.MM.YYYY");
     this.format1 = now;
     this.format2 = now2;
     console.log(now);

    this.date = moment(this.format1, "YYYY-MM-DD HH:mm:ss");

  }

https://stackblitz.com/edit/momentjs-format-date?file=app/app.component.ts


问:
Can't get mongoose to properly save an array
I'm trying to build an e-commerce from scratch using NodeJS, express and mongoose following this tutorial: https://www.youtube.com/playlist?list=PL55RiY5tL51rajp7Xr_zk-fCFtzdlGKUp but when I save() the program ends up writing a duplicate of everything and keeping the original too.

I've tried using updateMany() and insertMany() but it didn't help.

This is the Schema located in product.js

```<code>const schema = new Schema({
  imagePath: {type: String, required: true},
  title: {type: String, required: true},
  description: {type: String, required: true},
  price: {type: Number, required: true}
});

module.exports = mongoose.model('Product', schema);
</code>```

And this is in product-seeder.js

```<code>const Product = require('../models/product');

const products = [
  new Product({
    imagePath: 'https://images-na.ssl-images-amazon.com/images/I/41mPFjDCaXL.jpg',
    title: 'Gfuel 1',
    description: 'Lorem Ipsum',
    price: 20
  }), ...x4
]

let done = 0;
for (let i = 0; i < products.length; i++) {
  products[i].updateOne((err, result) => {
    done++;
    if (done === products.length) {
      exit();
    }
  });
}

const exit = () => {
  mongoose.disconnect();
}
</code>```

This works fine if there's nothing in the database but when I run this code multiple times, it keeps writing the same thing multiple times when it should just keep one of every object and if I change some info it should update it automatically.

答:
You should call save instead of updateOne there could nothing be updated because you didn't  pass a valid ObjectId and therefore there is no reference to what should be updated.

Read the docs to see what I mean.

Let's assume your Product-seeder.js is to store the products into the database. If you want to modify them you have to get the single product or a set of products from the database, modify them and save them again.

```<code>const Product = require('../models/product');

Product.find().exec((err, docs) => {
  if (err) return false; // log the error, send it to front-end, etc...
  docs.forEach((doc) => {
    doc.title = 'New Title here'
    doc.save()
  })
})

</code>```

This should update every single product in your database. Now all your products should have the title "New Title here".

To get a single document use findOne with the _id attribute or title or anything else.

Body:
I'm trying to build an e-commerce from scratch using NodeJS, express and mongoose following this tutorial: https://www.youtube.com/playlist?list=PL55RiY5tL51rajp7Xr_zk-fCFtzdlGKUp but when I save() the program ends up writing a duplicate of everything and keeping the original too.

I've tried using updateMany() and insertMany() but it didn't help.

This is the Schema located in product.js

const schema = new Schema({
  imagePath: {type: String, required: true},
  title: {type: String, required: true},
  description: {type: String, required: true},
  price: {type: Number, required: true}
});

module.exports = mongoose.model('Product', schema);

And this is in product-seeder.js

const Product = require('../models/product');

const products = [
  new Product({
    imagePath: 'https://images-na.ssl-images-amazon.com/images/I/41mPFjDCaXL.jpg',
    title: 'Gfuel 1',
    description: 'Lorem Ipsum',
    price: 20
  }), ...x4
]

let done = 0;
for (let i = 0; i < products.length; i++) {
  products[i].updateOne((err, result) => {
    done++;
    if (done === products.length) {
      exit();
    }
  });
}

const exit = () => {
  mongoose.disconnect();
}

This works fine if there's nothing in the database but when I run this code multiple times, it keeps writing the same thing multiple times when it should just keep one of every object and if I change some info it should update it automatically.

Body:
You should call save instead of updateOne there could nothing be updated because you didn't  pass a valid ObjectId and therefore there is no reference to what should be updated.

Read the docs to see what I mean.

Let's assume your Product-seeder.js is to store the products into the database. If you want to modify them you have to get the single product or a set of products from the database, modify them and save them again.

const Product = require('../models/product');

Product.find().exec((err, docs) => {
  if (err) return false; // log the error, send it to front-end, etc...
  docs.forEach((doc) => {
    doc.title = 'New Title here'
    doc.save()
  })
})

This should update every single product in your database. Now all your products should have the title "New Title here".

To get a single document use findOne with the _id attribute or title or anything else.


问:
AndroidManifest in androidTest directory being ignored
I'm trying to test using the following directory structure (which was setup by Android Studio):

I can run some tests just fine, and even the AllTests.java runs fine without the AndroidManifest.xml file even being there. The thing is, for one of my new tests, I need the android.permission.INTERNET permission. So, I added the following to the AndroidManifest.xml file located within the androidTest directory:

```<code><manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="com.example.core"
          android:versionCode="2"
          android:versionName="2.0" >

    <uses-sdk android:minSdkVersion="8" />

    <uses-permission android:name="android.permission.INTERNET" />
</manifest>
</code>```

Unfortunately, this doesn't work. I'm still getting the following error when I run one of my tests:

E/RestAPIRequestTest﹕ Permission denied (missing INTERNET permission?)

I've tried setting the package to be com.example.core.test in my AndroidManifest.xml file (since that is what it shows up as in my Settings->Apps list), but with no joy.

I'm thinking it's not even recognizing the AndroidManifest.xml file, since the version number doesn't show in the Settings for the test app, either.

How can I inject the correct permissions for my test project?

答:
This is a known problem.

Currently (AGP <= 3.4.X) is not supporting AndroidManifest test merging.

This is reported here: https://issuetracker.google.com/issues/127986458
and here there is the issue created by one of the Roboelectric maintainers.

The workaround as described here its near the same proposed by user3286293 and currently is the only way to have the manifest merged for testing purposes.

Hope to see a fix for AGP 3.5 or 3.6

Body:
I'm trying to test using the following directory structure (which was setup by Android Studio):

I can run some tests just fine, and even the AllTests.java runs fine without the AndroidManifest.xml file even being there. The thing is, for one of my new tests, I need the android.permission.INTERNET permission. So, I added the following to the AndroidManifest.xml file located within the androidTest directory:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="com.example.core"
          android:versionCode="2"
          android:versionName="2.0" >

    <uses-sdk android:minSdkVersion="8" />

    <uses-permission android:name="android.permission.INTERNET" />
</manifest>

Unfortunately, this doesn't work. I'm still getting the following error when I run one of my tests:

E/RestAPIRequestTest﹕ Permission denied (missing INTERNET permission?)

I've tried setting the package to be com.example.core.test in my AndroidManifest.xml file (since that is what it shows up as in my Settings->Apps list), but with no joy.

I'm thinking it's not even recognizing the AndroidManifest.xml file, since the version number doesn't show in the Settings for the test app, either.

How can I inject the correct permissions for my test project?


问:
Retrieve sharepoint object list from C# using JavaScript
I'm trying to retrieve list from Sharepoint using C# and get that list using JavaScript from client.

Can someone help me?

This is my C# code.

```<code>        SPWeb web = SPContext.Current.Web;
        SPList maListe = web.Lists["Lycee"];
        SPListItemCollection mesItem = maListe.Items;

        foreach (SPListItem monItem in mesItem)
        {
            //get Liste but i don't kwnow what to do?
        }
</code>```

答:
it's working now.

i just call my function like this.

_spBodyOnLoadFunctionNames.push("getListLycee");

tanks for your help.

Body:
I'm trying to retrieve list from Sharepoint using C# and get that list using JavaScript from client.

Can someone help me?

This is my C# code.

        SPWeb web = SPContext.Current.Web;
        SPList maListe = web.Lists["Lycee"];
        SPListItemCollection mesItem = maListe.Items;

        foreach (SPListItem monItem in mesItem)
        {
            //get Liste but i don't kwnow what to do?
        }


问:
Select 2 products from each category in MySQL
Pretty similar to MYSQL - select first 4 records for each category in a table but there isn't an accepted answer and the one answer there doesn't make much sense so i'm asking again.

I have a PRODUCTS table with 3 columns: ID, NAME and CATEGORY
What i would like to know now is if it's at all possible to select 2 products for each distinct category without doing queries in a PHP loop.

The order of the selected products is of no importance, they might as well be random. But it's important that i only have max 2 products per category.

So a good result set would be

```<code>ID  ; NAME   ; CATEGORY
:::::::::::::::::::::::
152 ; APPLE  ; FRUIT
185 ; ORANGE ; FRUIT
145 ; BEEF   ; MEAT
141 ; PORK   ; MEAT
410 ; PEPSI  ; DRINKS
585 ; CARROT ; VEGETABLES
585 ; TOMATO ; VEGETABLES
</code>```

答:
This should do what you are looking for.</p>

```<code>SET @I=0;
SET @C='';
SELECT ID, Name, Category FROM (
    SELECT B.*,
    IF(@C != B.Category, @I:=1, @I:=@I+1) AS RowNum,
    @C:=B.Category
    FROM (
        SELECT ID, Name, Category FROM Products GROUP BY Name, Category ORDER BY Category
    ) AS B HAVING RowNum <= 2
) AS A
</code>```

Body:
Pretty similar to MYSQL - select first 4 records for each category in a table but there isn't an accepted answer and the one answer there doesn't make much sense so i'm asking again.

I have a PRODUCTS table with 3 columns: ID, NAME and CATEGORY
What i would like to know now is if it's at all possible to select 2 products for each distinct category without doing queries in a PHP loop.

The order of the selected products is of no importance, they might as well be random. But it's important that i only have max 2 products per category.

So a good result set would be

ID  ; NAME   ; CATEGORY
:::::::::::::::::::::::
152 ; APPLE  ; FRUIT
185 ; ORANGE ; FRUIT
145 ; BEEF   ; MEAT
141 ; PORK   ; MEAT
410 ; PEPSI  ; DRINKS
585 ; CARROT ; VEGETABLES
585 ; TOMATO ; VEGETABLES

Body:
This should do what you are looking for.

SET @I=0;
SET @C='';
SELECT ID, Name, Category FROM (
    SELECT B.*,
    IF(@C != B.Category, @I:=1, @I:=@I+1) AS RowNum,
    @C:=B.Category
    FROM (
        SELECT ID, Name, Category FROM Products GROUP BY Name, Category ORDER BY Category
    ) AS B HAVING RowNum <= 2
) AS A


问:
How to filter many value in same time?
I'm using elastic search to filter 1 document and i use a loop to filer many documents. But now i want to filter many document in one request to optimize my script.

For the moment i have this query, and i'm using a "for" loop to filter by uuid.

```<code>for id in id_list:
    filter (id)

def filter(id):

    result = requests.get(
            settings + '/data/_search?size=10000',
            json={
                "query": {
                    "bool": {
                        "filter": {
                            "terms": {
                                "id": id
                            }
                        }
                    }
                },
                "_source": {
                    "exclude": ["type", "date"]
                }
            }
        )
</code>```

I would like to do only one request to get all my document at once to optimize my code.

答: The terms query takes an array of arguments, see the reference for an example.</p>

Title: How to filter many value in same time?

Body:
I'm using elastic search to filter 1 document and i use a loop to filer many documents. But now i want to filter many document in one request to optimize my script.

For the moment i have this query, and i'm using a "for" loop to filter by uuid.

for id in id_list:
    filter (id)

def filter(id):

    result = requests.get(
            settings + '/data/_search?size=10000',
            json={
                "query": {
                    "bool": {
                        "filter": {
                            "terms": {
                                "id": id
                            }
                        }
                    }
                },
                "_source": {
                    "exclude": ["type", "date"]
                }
            }
        )

I would like to do only one request to get all my document at once to optimize my code.


问:
method in data access class not working because of wrong sql-statement (I think)
I made a method in a data access class that needs to get data from multiple tables. I want to show a table on a webpage with this data.

I tried to use inner joins the get the different data and filled each class up underneath it. I think the problem is located in the sql-statement since the other code 'matches' previously used code that did work. The webpage and servlet should be fine as well.

```<code>          ArrayList<Vlucht> vluchtGegevens = new ArrayList<>();

         try (
             Connection connection = DriverManager.getConnection(url, login, password);
             Statement statement = connection.createStatement();
             ResultSet resultSet = statement.executeQuery("SELECT * FROM vlucht "
                     + " inner join vliegtuig on vlucht.vliegtuig_id = vliegtuig.id "
                     + " inner join vliegtuigtype on vliegtuig.vliegtuigtype_id = vliegtuigtype.id "
                     + " inner join luchthaven as VL on vlucht.vertrekluchthaven_id = VL.id "
                     + " inner join luchthaven as AL on vlucht.aankomstluchthaven_id = AL.id");)
            {
            while (resultSet.next()) {
                 Vlucht vlucht = new Vlucht();
                 vlucht.setId(resultSet.getInt(1));
                 vlucht.setCode(resultSet.getString("code"));
                 vlucht.setVertrekTijd(resultSet.getDate("vertrekTijd"));
                 vlucht.setAankomstTijd(resultSet.getDate("aankomstTijd"));
                 vlucht.setVliegtuig_id(resultSet.getInt("vliegtuig_id"));
                 vlucht.setVertrekluchthaven_id(resultSet.getInt("vertrekluchthaven_id"));
                 vlucht.setAankomstluchthaven_id(resultSet.getInt("aankomstluchthaven_id"));

                 Vliegtuig vliegtuig = new Vliegtuig();
                 vliegtuig.setId(resultSet.getInt("id"));
                 vliegtuig.setVliegtuigType_id(resultSet.getInt("vliegtuigtype_id"));
                 vliegtuig.setLuchtvaartMaatschappij_id(resultSet.getInt("luchtvaartMaatschappij_id"));
                 vlucht.setVliegtuig(vliegtuig);

                 VliegtuigType vliegtuigType = new VliegtuigType();
                 vliegtuigType.setId(resultSet.getInt(5));
                 vliegtuigType.setTypenaam(resultSet.getString("typenaam"));

                 vlucht.setVliegtuigType(vliegtuigType);

                 Luchthaven vertrekLuchthaven = new Luchthaven();
                 vertrekLuchthaven.setId(resultSet.getInt(6));
                 vertrekLuchthaven.setLuchthavennaam(resultSet.getString("luchthavennaam"));
                 vertrekLuchthaven.setStad(resultSet.getString("stad"));
                 vertrekLuchthaven.setLand_id(resultSet.getInt("land_id"));

                 vlucht.setVertrekLuchthaven(vertrekLuchthaven);

                 Luchthaven aankomstLuchthaven = new Luchthaven();
                 aankomstLuchthaven.setId(resultSet.getInt(7));
                 aankomstLuchthaven.setLuchthavennaam(resultSet.getString("luchthavennaam"));
                 aankomstLuchthaven.setStad(resultSet.getString("stad"));
                 aankomstLuchthaven.setLand_id(resultSet.getInt("land_id"));

                 vlucht.setAankomstLuchthaven(aankomstLuchthaven);
                 vluchtGegevens.add(vlucht);

                            }
        } catch (Exception e) {
            e.printStackTrace();
        }
         return vluchtGegevens  ;
    }
    ```
```

答: The word 'as' had to be removed from the sql-statement. This caused a problem because I was using Netbeans. </p>

Body:
I made a method in a data access class that needs to get data from multiple tables. I want to show a table on a webpage with this data.

I tried to use inner joins the get the different data and filled each class up underneath it. I think the problem is located in the sql-statement since the other code 'matches' previously used code that did work. The webpage and servlet should be fine as well.

          ArrayList<Vlucht> vluchtGegevens = new ArrayList<>();

         try (
             Connection connection = DriverManager.getConnection(url, login, password);
             Statement statement = connection.createStatement();
             ResultSet resultSet = statement.executeQuery("SELECT * FROM vlucht "
                     + " inner join vliegtuig on vlucht.vliegtuig_id = vliegtuig.id "
                     + " inner join vliegtuigtype on vliegtuig.vliegtuigtype_id = vliegtuigtype.id "
                     + " inner join luchthaven as VL on vlucht.vertrekluchthaven_id = VL.id "
                     + " inner join luchthaven as AL on vlucht.aankomstluchthaven_id = AL.id");)
            {
            while (resultSet.next()) {
                 Vlucht vlucht = new Vlucht();
                 vlucht.setId(resultSet.getInt(1));
                 vlucht.setCode(resultSet.getString("code"));
                 vlucht.setVertrekTijd(resultSet.getDate("vertrekTijd"));
                 vlucht.setAankomstTijd(resultSet.getDate("aankomstTijd"));
                 vlucht.setVliegtuig_id(resultSet.getInt("vliegtuig_id"));
                 vlucht.setVertrekluchthaven_id(resultSet.getInt("vertrekluchthaven_id"));
                 vlucht.setAankomstluchthaven_id(resultSet.getInt("aankomstluchthaven_id"));

                 Vliegtuig vliegtuig = new Vliegtuig();
                 vliegtuig.setId(resultSet.getInt("id"));
                 vliegtuig.setVliegtuigType_id(resultSet.getInt("vliegtuigtype_id"));
                 vliegtuig.setLuchtvaartMaatschappij_id(resultSet.getInt("luchtvaartMaatschappij_id"));
                 vlucht.setVliegtuig(vliegtuig);

                 VliegtuigType vliegtuigType = new VliegtuigType();
                 vliegtuigType.setId(resultSet.getInt(5));
                 vliegtuigType.setTypenaam(resultSet.getString("typenaam"));

                 vlucht.setVliegtuigType(vliegtuigType);

                 Luchthaven vertrekLuchthaven = new Luchthaven();
                 vertrekLuchthaven.setId(resultSet.getInt(6));
                 vertrekLuchthaven.setLuchthavennaam(resultSet.getString("luchthavennaam"));
                 vertrekLuchthaven.setStad(resultSet.getString("stad"));
                 vertrekLuchthaven.setLand_id(resultSet.getInt("land_id"));

                 vlucht.setVertrekLuchthaven(vertrekLuchthaven);

                 Luchthaven aankomstLuchthaven = new Luchthaven();
                 aankomstLuchthaven.setId(resultSet.getInt(7));
                 aankomstLuchthaven.setLuchthavennaam(resultSet.getString("luchthavennaam"));
                 aankomstLuchthaven.setStad(resultSet.getString("stad"));
                 aankomstLuchthaven.setLand_id(resultSet.getInt("land_id"));

                 vlucht.setAankomstLuchthaven(aankomstLuchthaven);
                 vluchtGegevens.add(vlucht);

                            }
        } catch (Exception e) {
            e.printStackTrace();
        }
         return vluchtGegevens  ;
    }
    ```


答:
You can use groupByKey to get a sequence of values and then filter out sequences with less than two values

```<code>rdd.groupByKey().filter(lambda t: len(t[1]) >= 2).flatMapValues(lambda x: x).foreach(lambda x: print(x))
</code>```

output:

```<code>(((1, 2), 1.0), (2, 3))
(((1, 2), 1.0), (3, 4))
(((2, 3), 1.0), (1, 2))
(((2, 3), 1.0), (3, 4))
(((3, 4), 1.0), (1, 2))
(((3, 4), 1.0), (2, 3))
</code>```

Title: code to filter (key:value) pair having common keys in RDD

Body:
I have a RDD as follows :

[(((1, 2), 1.0), (2, 3)),
 (((1, 2), 1.0), (3, 4)),
 (((1, 2), 3.0), (2, 5)),
 (((2, 3), 1.0), (1, 2)),
 (((2, 3), 1.0), (3, 4)),
 (((2, 3), 'inf'), (2, 5)),
 (((3, 4), 1.0), (1, 2)),
 (((3, 4), 1.0), (2, 3)),
 (((3, 4), -1.0), (2, 5)),
 (((2, 5), 3.0), (1, 2)),
 (((2, 5), 'inf'), (2, 3)),
 (((2, 5), -1.0), (3, 4))]

I want to filter out another RDD from this RDD which only contains those Key:value pairs which have common Keys. That is my output RDD should be :

[(((1,2),1.0), (2,3)),
 ((1,2),1.0), (3,4)),
 ((2,3),1.0), (1,2)),
 ((2,3),1.0), (3,4)),
 ((3,4),1.0), (1,2)),
 ((3,4),1.0), (2,3)))]

I tried the following code-

rdd.countByKey() which returned me a dictionary containing

defaultdict(int,
            {((1, 2), 1.0): 2,
             ((1, 2), 3.0): 1,
             ((2, 3), 1.0): 2,
             ((2, 3), 'inf'): 1,
             ((3, 4), 1.0): 2,
             ((3, 4), -1.0): 1,
             ((2, 5), 3.0): 1,
             ((2, 5), 'inf'): 1,
             ((2, 5), -1.0): 1})

I thought of iterating on this dictionary as my next step so that I could filter out those items which has values > 1 but unable to succeed with the code. Can anyone help me out with solution to this problem?

Body:
You can use groupByKey to get a sequence of values and then filter out sequences with less than two values

rdd.groupByKey().filter(lambda t: len(t[1]) >= 2).flatMapValues(lambda x: x).foreach(lambda x: print(x))

output:

(((1, 2), 1.0), (2, 3))
(((1, 2), 1.0), (3, 4))
(((2, 3), 1.0), (1, 2))
(((2, 3), 1.0), (3, 4))
(((3, 4), 1.0), (1, 2))
(((3, 4), 1.0), (2, 3))


问:
Error loading hostpolicy.dll while deploying .NET Core console app to Azure WebJobs
I have followed this tutorial to deploy a .NET Core console application to an Azure Web Service WebJob.

My app is running locally without any issue (with dotnet 1.0.0-preview2-003131) but when I try to run it from Azure console I have the following error :

Failed to load the dll from [D:\local\VirtualDirectory0\site\wwwroot\app_data\jobs\triggered\PopcornExportWebJob\hostpolicy.dll], HRESULT: 0x800700C1**

An error occurred while loading required library hostpolicy.dll from [D:\local\VirtualDirectory0\site\wwwroot\app_data\jobs\triggered\PopcornExportWebJob]

The version of Azure .Net is 1.0.0-rc4-004771  and the hostpolicy.dll file is the same than I use locally. In fact, when I download the zip of my deploy from Azure and when I run it locally, it is working fine. But it fails on Azure environment.

Also, here is my project.json:

```<code>{
      "publishOptions": {
        "include": [
          "run.cmd"
        ]
      },
      "buildOptions": {
        "emitEntryPoint": true,
        "copyToOutput": "appsettings.json"
      },
      "copyright": "bbougot",
      "dependencies": {
        "FubarCoder.RestSharp.Portable.Core": "4.0.7",
        "FubarCoder.RestSharp.Portable.HttpClient": "4.0.7",
        "Microsoft.ApplicationInsights.AspNetCore": "2.0.0",
        "Microsoft.Extensions.Configuration": "1.1.0",
        "Microsoft.Extensions.Configuration.Json": "1.1.0",
        "Microsoft.Extensions.DependencyInjection": "1.1.0",
        "Microsoft.Extensions.Logging": "1.1.0",
        "Microsoft.Extensions.Logging.Console": "1.1.0",
        "Microsoft.NETCore.App": "1.1.0",
        "MongoDB.Driver": "2.4.2",
        "StructureMap.Microsoft.DependencyInjection": "1.3.0"
      },
      "description": "Popcorn Api Exporter",
      "frameworks": {
        "netcoreapp1.1": {
          "imports": [
            "portable-net45+win8"
          ]
        }
      },
      "runtimes": {
        "win10-x64": {}
      },
      "scripts": {
        "postpublish": [ "7za.exe a -tzip PopcornExport.zip .\\bin\\Release\\PublishOutput\\*",
                         ".\\WAWSDeploy.exe .\\PopcornExport.zip .\\popcornexport.PublishSettings /t app_data\\jobs\\triggered\\PopcornExportWebJob /v /d" ]
      },
      "title": "PopcornExport",
      "version": "1.0.0-*"
    }
</code>```

I had to add the node runtimes (win10-x64 otherwise the app can't run locally). But, the Azure Web Service is running on Windows Server 2012. May it be an issue?

What did I miss?

答:
I stopped seeing this error when I changed the contents of run.cmd from

dotnet MyWorker.dll

to

MyWorker.exe

Body:
I have followed this tutorial to deploy a .NET Core console application to an Azure Web Service WebJob.

My app is running locally without any issue (with dotnet 1.0.0-preview2-003131) but when I try to run it from Azure console I have the following error :

Failed to load the dll from [D:\local\VirtualDirectory0\site\wwwroot\app_data\jobs\triggered\PopcornExportWebJob\hostpolicy.dll], HRESULT: 0x800700C1**

An error occurred while loading required library hostpolicy.dll from [D:\local\VirtualDirectory0\site\wwwroot\app_data\jobs\triggered\PopcornExportWebJob]

The version of Azure .Net is 1.0.0-rc4-004771  and the hostpolicy.dll file is the same than I use locally. In fact, when I download the zip of my deploy from Azure and when I run it locally, it is working fine. But it fails on Azure environment.

Also, here is my project.json:

{
      "publishOptions": {
        "include": [
          "run.cmd"
        ]
      },
      "buildOptions": {
        "emitEntryPoint": true,
        "copyToOutput": "appsettings.json"
      },
      "copyright": "bbougot",
      "dependencies": {
        "FubarCoder.RestSharp.Portable.Core": "4.0.7",
        "FubarCoder.RestSharp.Portable.HttpClient": "4.0.7",
        "Microsoft.ApplicationInsights.AspNetCore": "2.0.0",
        "Microsoft.Extensions.Configuration": "1.1.0",
        "Microsoft.Extensions.Configuration.Json": "1.1.0",
        "Microsoft.Extensions.DependencyInjection": "1.1.0",
        "Microsoft.Extensions.Logging": "1.1.0",
        "Microsoft.Extensions.Logging.Console": "1.1.0",
        "Microsoft.NETCore.App": "1.1.0",
        "MongoDB.Driver": "2.4.2",
        "StructureMap.Microsoft.DependencyInjection": "1.3.0"
      },
      "description": "Popcorn Api Exporter",
      "frameworks": {
        "netcoreapp1.1": {
          "imports": [
            "portable-net45+win8"
          ]
        }
      },
      "runtimes": {
        "win10-x64": {}
      },
      "scripts": {
        "postpublish": [ "7za.exe a -tzip PopcornExport.zip .\\bin\\Release\\PublishOutput\\*",
                         ".\\WAWSDeploy.exe .\\PopcornExport.zip .\\popcornexport.PublishSettings /t app_data\\jobs\\triggered\\PopcornExportWebJob /v /d" ]
      },
      "title": "PopcornExport",
      "version": "1.0.0-*"
    }

I had to add the node runtimes (win10-x64 otherwise the app can't run locally). But, the Azure Web Service is running on Windows Server 2012. May it be an issue?

What did I miss?


问:
How to loop through two lists simultaneously?
I have referred to the following question at: Using foreach loop to iterate through two lists. My question is this, with regards to the chosen answer: Can the o.DoSomething be a comparison? As in:

```<code>For Each a in ListA.Concat(ListB)
    If(a from ListA=a from ListB) Then
        Do Something here
    End If
Next
</code>```

As you might've guessed, I'm using VB.Net and would like to know how I can do what I have shown here. That would basically be to iterate through a joined list separately/independently. Thanks!

答:
In .Net 4 you could use Zip. Adapted from my answer to this question from a Python fan specifically asking for tuples - you could remove the tuples if you like.</p>

```<code>Sub Main()
    Dim arr1() As String = {"a", "b", "c"} '' will also work with Lists
    Dim arr2() As String = {"1", "2", "3"}
    For Each t In TupleSequence(arr1, arr2)
        If t.Item1 = t.Item2 Then
          '' Do something
        End If
    Next
    Console.ReadLine()
End Sub
Function TupleSequence(Of T1, T2)(
    ByVal seq1 As IEnumerable(Of T1),
    ByVal seq2 As IEnumerable(Of T2)
    ) As IEnumerable(Of Tuple(Of T1, T2))
    Return Enumerable.Zip(seq1, seq2,
      Function(s1, s2) Tuple.Create(s1, s2)
    )
End Function
</code>```

Body:
I have referred to the following question at: Using foreach loop to iterate through two lists. My question is this, with regards to the chosen answer: Can the o.DoSomething be a comparison? As in:

For Each a in ListA.Concat(ListB)
    If(a from ListA=a from ListB) Then
        Do Something here
    End If
Next

As you might've guessed, I'm using VB.Net and would like to know how I can do what I have shown here. That would basically be to iterate through a joined list separately/independently. Thanks!

Body:
In .Net 4 you could use Zip. Adapted from my answer to this question from a Python fan specifically asking for tuples - you could remove the tuples if you like.

Sub Main()
    Dim arr1() As String = {"a", "b", "c"} '' will also work with Lists
    Dim arr2() As String = {"1", "2", "3"}
    For Each t In TupleSequence(arr1, arr2)
        If t.Item1 = t.Item2 Then
          '' Do something
        End If
    Next
    Console.ReadLine()
End Sub
Function TupleSequence(Of T1, T2)(
    ByVal seq1 As IEnumerable(Of T1),
    ByVal seq2 As IEnumerable(Of T2)
    ) As IEnumerable(Of Tuple(Of T1, T2))
    Return Enumerable.Zip(seq1, seq2,
      Function(s1, s2) Tuple.Create(s1, s2)
    )
End Function


问:
Extracting XY Coordinates from QTCharts (a line series) on Mouse click
I'm trying to pick the X and Y Coordinates from a 2D Chart in QT when a mouse click is done on the 2D Chart widget.

I tried to use the mapFromScene , mapToValue and other similar functions that are available in the QTChart Library. But I'm unable to get the values.

答:
I got the expected output for this problem.

This is my Code which works fine for me.

```<code>// function for mouse press events
void 2D_Graph::mousePressEvent (QMouseEvent * e) {
    if(chartView->chart()->isEnabled()) {
        auto curPoint = QCursor::pos();
        curPoint = chartView->mapFromGlobal(curPoint);
        auto pickVal = chartView->mapToScene(curPoint);
        pickVal = chartView->chart()->mapFromScene(curPoint);
        pickVal = chartView->chart()->mapToValue(curPoint,chartView->chart()->series().at(0));
        qDebug() << "Diagram Picked Value : " << pickVal;
    }
}
</code>```

Body:
I got the expected output for this problem.

This is my Code which works fine for me.

// function for mouse press events
void 2D_Graph::mousePressEvent (QMouseEvent * e) {
    if(chartView->chart()->isEnabled()) {
        auto curPoint = QCursor::pos();
        curPoint = chartView->mapFromGlobal(curPoint);
        auto pickVal = chartView->mapToScene(curPoint);
        pickVal = chartView->chart()->mapFromScene(curPoint);
        pickVal = chartView->chart()->mapToValue(curPoint,chartView->chart()->series().at(0));
        qDebug() << "Diagram Picked Value : " << pickVal;
    }
}


问:
Azure Service Fabric - Confusion around framework
I have 2 questions. When I create a new project using VS2017, I can't use.net Core as Frameworks listed are only for .net f/w. Why is it so?

See below:

The next screen asks for the template. While choosing a stateful or stateless service, we have a different template for .net core and .net framework categories but both of them mentions .net core in the name

答: As you can see, if you choose to target .NET Framework you can still create ASP.NET Core service and use ASP.NET Core features. That's not a problem. The only downside is if you want your application to be multi platform (for example run on Linux) you cannot do that. You need to target .NET Core instead.</p>


问:
Replace a parameter in an expression with a constant
I have an expression of type Expression<Func<TElement, TElement, bool>> and a constant of type TElement. I need an expression of type Expression<Func<TElement, bool>> with one of the parameters replaced by the constant. In other words, I need the body to the following method:

```<code>public static Expression<Func<TElement, bool>> ReplaceParameter<TElement>
(
    Expression<Func<TElement, TElement, bool>> inputExpression,
    TElement element
)
{
    ...
}
</code>```

If I call ReplaceParameter((i1, i2) => i1 > i2, 5), I expect the result to be i => i > 5.

I was thinking, it might be able to recursively deconstruct and then reconstruct the input expression and replace all occurrences of the second parameter with a constant expression. Since there are so many different kind of expressions, I'm unsure on how to do that, though.

答:
Instead of using the ExpressionVisitor you could create a factory Func like this:

```<code>public static Expression<Func<TElement, bool>> ReplaceParameter<TElement>
(
    Expression<Func<TElement, TElement, bool>> inputExpression,
    TElement element
)
{
    var inner = Expression.Lambda<Func<TElement, bool>>
    (
        inputExpression.Body,
        inputExpression.Parameters[1]
    );
    var outer = Expression.Lambda<Func<TElement, Expression<Func<TElement, bool>>>>
    (
        inner,
        inputExpression.Parameters[0]
    );
    var factory = outer.Compile();
    return factory(element);
}
</code>```

To make it even more useful, you could save factory and call it every time you want to replace a parameter:

```<code>public static Func<TElement, Expression<Func<TElement, bool>>> CreateFactory<TElement>
(
    Expression<Func<TElement, TElement, bool>> inputExpression
)
{
    var inner = Expression.Lambda<Func<TElement, bool>>
    (
        inputExpression.Body,
        inputExpression.Parameters[1]
    );
    var outer = Expression.Lambda<Func<TElement, Expression<Func<TElement, bool>>>>
    (
        inner,
        inputExpression.Parameters[0]
    );
    return outer.Compile();
}

public static void Test()
{
    var factory = CreateFactory<int>((i1, i2) => i1 > i2);
    var greater5 = factory(5);
    var greater2 = factory(2);
}
</code>```

What is actually happening here?

When inputExpression is (i1, i2) => i1 > i2 then inner would be i1 => i1 > i2 and outer/factory would be i2 => i1 => i1 > i2.

Body:
I have an expression of type Expression<Func<TElement, TElement, bool>> and a constant of type TElement. I need an expression of type Expression<Func<TElement, bool>> with one of the parameters replaced by the constant. In other words, I need the body to the following method:

public static Expression<Func<TElement, bool>> ReplaceParameter<TElement>
(
    Expression<Func<TElement, TElement, bool>> inputExpression,
    TElement element
)
{
    ...
}

If I call ReplaceParameter((i1, i2) => i1 > i2, 5), I expect the result to be i => i > 5.

I was thinking, it might be able to recursively deconstruct and then reconstruct the input expression and replace all occurrences of the second parameter with a constant expression. Since there are so many different kind of expressions, I'm unsure on how to do that, though.

Body:
Instead of using the ExpressionVisitor you could create a factory Func like this:

public static Expression<Func<TElement, bool>> ReplaceParameter<TElement>
(
    Expression<Func<TElement, TElement, bool>> inputExpression,
    TElement element
)
{
    var inner = Expression.Lambda<Func<TElement, bool>>
    (
        inputExpression.Body,
        inputExpression.Parameters[1]
    );
    var outer = Expression.Lambda<Func<TElement, Expression<Func<TElement, bool>>>>
    (
        inner,
        inputExpression.Parameters[0]
    );
    var factory = outer.Compile();
    return factory(element);
}

To make it even more useful, you could save factory and call it every time you want to replace a parameter:

public static Func<TElement, Expression<Func<TElement, bool>>> CreateFactory<TElement>
(
    Expression<Func<TElement, TElement, bool>> inputExpression
)
{
    var inner = Expression.Lambda<Func<TElement, bool>>
    (
        inputExpression.Body,
        inputExpression.Parameters[1]
    );
    var outer = Expression.Lambda<Func<TElement, Expression<Func<TElement, bool>>>>
    (
        inner,
        inputExpression.Parameters[0]
    );
    return outer.Compile();
}

public static void Test()
{
    var factory = CreateFactory<int>((i1, i2) => i1 > i2);
    var greater5 = factory(5);
    var greater2 = factory(2);
}

What is actually happening here?

When inputExpression is (i1, i2) => i1 > i2 then inner would be i1 => i1 > i2 and outer/factory would be i2 => i1 => i1 > i2.


问:
Mark as deprecated function parameters in C++14
Reading this blog post and its comments, I have noticed that it gives as an example the possibility of marking specific function parameters as deprecated, as in (exaple taken from the post):

```<code>// Deprecate a function parameter
int triple([[deprecated]] int x);
</code>```

Now I was wondering, what is a good use case for such a feature? No one in the comments of that post or anywhere else I have searched seem to have a clue.

EDIT:

To see it in action, there is a compilable example on goldbolt

答:
Imagine a library that is implemented, used and maintained for many years. This library is used in multiple projects.

If you would simply remove the parameter, all the projects would have to immediately adapt the source code to be able to compile again, after they upgraded to the new library version.

If a default value is added to the parameter, but the parameter not used anymore, the projects would still compile without any change, but nobody would note that something has changed at all, and maybe some behaviour/feature that was controlled by this parameter does not work anymore.

So, by marking the parameter as deprecated the projects can compile without a change, but they get a warning that something has changed and that they should change their source code, because sooner or later this parameter will disappear.

Body:
Reading this blog post and its comments, I have noticed that it gives as an example the possibility of marking specific function parameters as deprecated, as in (exaple taken from the post):

// Deprecate a function parameter
int triple([[deprecated]] int x);

Now I was wondering, what is a good use case for such a feature? No one in the comments of that post or anywhere else I have searched seem to have a clue.

EDIT:

To see it in action, there is a compilable example on goldbolt


问:
How to remove quotes in my product description string?
I'm using OSCommerce for my online store and I'm currently optimizing my product page for rich snippets.
Some of my Google Indexed pages are being marked as "Failed" by Google due to double quotes in the description field.

I'm using an existing code which strips the html coding and truncates anything after 197 characters.

```<code><?php echo substr(trim(preg_replace('/\s\s+/', ' ', strip_tags($product_info['products_description']))), 0, 197); ?>
</code>```

How can I include the removal of quotes in that code so that the following string:

```<code><strong>This product is the perfect "fit"</strong>
</code>```

becomes:

```<code>This product is the perfect fit
</code>```

答:
We can try using preg_replace_callback here:

```<code>$input = "SOME TEXT HERE <strong>This product is the perfect \"fit\"</strong> SOME MORE TEXT HERE";
$output = preg_replace_callback(
    "/<([^>]+)>(.*?)<\/\\1>/",
    function($m) {
        return str_replace("\"", "", $m[2]);
    },
    $input);
echo $output;
</code>```

This prints:

```<code>SOME TEXT HERE This product is the perfect fit SOME MORE TEXT HERE
</code>```

The regex pattern used does the following:

```<code><([^>]+)>  match an opening HTML tag, and capture the tag name
(.*?)      then match and capture the content inside the tag
<\/\\1>    finally match the same closing tag
</code>```

Then, we use a callback function which does an additional replacement to strip off all double quotes.

Note that in general using regex against HTML is bad practice.  But, if your text only has single level/occasional HTML tags, then the solution I gave above might be viable.

Body:
I'm using OSCommerce for my online store and I'm currently optimizing my product page for rich snippets.
Some of my Google Indexed pages are being marked as "Failed" by Google due to double quotes in the description field.

I'm using an existing code which strips the html coding and truncates anything after 197 characters.

<?php echo substr(trim(preg_replace('/\s\s+/', ' ', strip_tags($product_info['products_description']))), 0, 197); ?>

How can I include the removal of quotes in that code so that the following string:

This product is the perfect "fit"

becomes:

This product is the perfect fit

Body:
We can try using preg_replace_callback here:

$input = "SOME TEXT HERE <strong>This product is the perfect \"fit\"</strong> SOME MORE TEXT HERE";
$output = preg_replace_callback(
    "/<([^>]+)>(.*?)<\/\\1>/",
    function($m) {
        return str_replace("\"", "", $m[2]);
    },
    $input);
echo $output;

This prints:

SOME TEXT HERE This product is the perfect fit SOME MORE TEXT HERE

The regex pattern used does the following:

<([^>]+)>  match an opening HTML tag, and capture the tag name
(.*?)      then match and capture the content inside the tag
<\/\\1>    finally match the same closing tag

Then, we use a callback function which does an additional replacement to strip off all double quotes.

Note that in general using regex against HTML is bad practice.  But, if your text only has single level/occasional HTML tags, then the solution I gave above might be viable.


问:
i can't able to run composer install command under my /var/www/html/magento2
i am facing problem while setting up the magento server on  Centos7 i have php 7.3 install in my centos ec2 instance

installed php 7.3.5, also tried to update composer using $composer update command it doesn't work

composer install

答: Magento 2 does not support php 7.3 as of yet. A significant numer of core modules specify the php versions they will allow. You will need to change your php version. See this link for the supported versions. https://devdocs.magento.com/guides/v2.3/install-gde/system-requirements-tech.html</p>


问:
how to list only security update via pip
With the recent change in pip having it upgrading packages only-if-needed by default (or using --upgrade-strategy eager) I would like to have pip listing only security updates of my packages in order to avoid upgrading modules for new features but to keep my system up-to-date regarding security.

答:
There is no way to do it. pip doesn't know what updates are what — security, bug fixes, feature releases. pip simply doesn't distinguish them.

You have to track release notes for all installed packages. There is no other way. I've heard there are commercial services that track security updates and notify you.


问:
Images not displaying in drupal nodes
I have added some images in the header inside page.tpl.php that shows up fine in the home page as well as /admin. But when I add a page, like /node/1, the images do not display. Please help me...........</p>

答: I think you have two template file for pages. like front-page.tpl.php and page.tpl.php. So you aslo need to add images in the header inside the front-page.tpl.php.</p>

Title: Images not displaying in drupal nodes


问:
download gz file on clicking a url and convert to csv using scala
I am really messing with syntax here need help...

I have a URL, on clicking of which a sample.csv.gz file gets downloaded

Please can someone help me fill the syntactic gaps below:

```<code>val outputFile = "C:\\sampleNew" + ".csv"
val inputFile = "C:\\sample.csv.gz"
val fileUrl = "someSamplehttpUrl"

// On hitting this Url, sample.csv.gz file should download at destination 'outputFile'
val in = new URL()(fileUrl).openStream()
Files.copy(in, Paths.get(outputFile), StandardCopyOption.REPLACE_EXISTING)

val filePath = new File(outputFile)
if(filePath.exists()) filePath.delete()
val fw = new FileWriter(outputFile, true)
var bf = new BufferedReader(new InputStreamReader(new GZIPInputStream(new FileInputStream(inputFile)), "UTF-8"))
while (bf.ready()) fw.append(bf.readLine() + "\n")
</code>```

I have been getting several errors with syntax... Any corrections here? I basically have an http get request that returns a URL, which I must open to download this gz file

Thanks!

答:
Here are two possible solutions:

import java.io.{File, PrintWriter}
import scala.io.Source

val outputFile = "out.csv"
val inputFile = "/tmp/marks.csv"
val fileUrl = s"file:///$inputFile"

// Method 1, a traditional copy from the input to the output.
val in = Source.fromURL(fileUrl)
val out = new PrintWriter(outputFile)
for (line <- in.getLines)
  out.println(line)

out.close
in.close

```

<p>Here is a one liner which basically pipes the data from the input to the output.</p>

<pre class="lang-scala prettyprint-override"><code>import sys.process._
import java.net.URL

val outputFile = "out.csv"
val inputFile = "/tmp/marks.csv"
val fileUrl = s"file:///$inputFile"

// Method 2, pipe the content of the URL to the output file.
new URL(fileUrl) #> new File(outputFile) !!
</code>```

Here is a version using Files.copy

val outputFile = "out.csv"
val inputFile = "/tmp/marks.csv"
val fileUrl = s"file:///$inputFile"

import java.nio.file.{Files, Paths, StandardCopyOption}
import java.net.URL

val in = new URL(fileUrl).openStream
val out = Paths.get(outputFile)

Files.copy(in, out, StandardCopyOption.REPLACE_EXISTING)
```

Hopefully one (or more) of the above will address your needs.

Body:
I am really messing with syntax here need help...

I have a URL, on clicking of which a sample.csv.gz file gets downloaded

Please can someone help me fill the syntactic gaps below:

val outputFile = "C:\\sampleNew" + ".csv"
val inputFile = "C:\\sample.csv.gz"
val fileUrl = "someSamplehttpUrl"

// On hitting this Url, sample.csv.gz file should download at destination 'outputFile'
val in = new URL()(fileUrl).openStream()
Files.copy(in, Paths.get(outputFile), StandardCopyOption.REPLACE_EXISTING)

val filePath = new File(outputFile)
if(filePath.exists()) filePath.delete()
val fw = new FileWriter(outputFile, true)
var bf = new BufferedReader(new InputStreamReader(new GZIPInputStream(new FileInputStream(inputFile)), "UTF-8"))
while (bf.ready()) fw.append(bf.readLine() + "\n")

I have been getting several errors with syntax... Any corrections here? I basically have an http get request that returns a URL, which I must open to download this gz file

Thanks!

Body:
Here are two possible solutions:

import java.io.{File, PrintWriter}
import scala.io.Source

val outputFile = "out.csv"
val inputFile = "/tmp/marks.csv"
val fileUrl = s"file:///$inputFile"

// Method 1, a traditional copy from the input to the output.
val in = Source.fromURL(fileUrl)
val out = new PrintWriter(outputFile)
for (line <- in.getLines)
  out.println(line)

out.close
in.close

Here is a one liner which basically pipes the data from the input to the output.

import sys.process._
import java.net.URL

val outputFile = "out.csv"
val inputFile = "/tmp/marks.csv"
val fileUrl = s"file:///$inputFile"

// Method 2, pipe the content of the URL to the output file.
new URL(fileUrl) #> new File(outputFile) !!

Here is a version using Files.copy

val outputFile = "out.csv"
val inputFile = "/tmp/marks.csv"
val fileUrl = s"file:///$inputFile"

import java.nio.file.{Files, Paths, StandardCopyOption}
import java.net.URL

val in = new URL(fileUrl).openStream
val out = Paths.get(outputFile)

Files.copy(in, out, StandardCopyOption.REPLACE_EXISTING)

Hopefully one (or more) of the above will address your needs.


问:
External IP is not get visible on my compute engine dashboard
External IP does not get visible for my one of the compute engine</p>

答:
You may have not reserved an external static IP. You can do it through the Google console using an ephemeral IP address1 or assignnating one custom IP address mannually.2
If your issue is more related to the Google Console UI, try to check if there is a reserved external IP address for your particular VM instance by using the Google Shell and the following command:

$ gcloud compute instances list

You will need to provide more details about whats exactly is your issue.


问:
Gradle subprojects won't compile with dependency on other subproject
I have a Multi project gradle project with the following structure.

```<code>Project A: The top level project that all sub projects reside in.
  SubProject B:
  SubProject C:
  SubProject D:
  SubProject E:
  SubProject Shared: Every 'SubProject' has a dependency to this project "compile project(':Shared')"
</code>```

Everything works correctly when running Gradle tasks from the top level 'Project A'

However, when I try to run an individual task on a subproject such as 'SubProject C' I get the following error.

FAILURE: Build failed with an exception

What went wrong:

A problem occurred evaluating root project 'SubProject C'.

Project with path ':Shared' could not be found in root project 'SubProject C'.

I think I see the problem here, Gradle thinks my sub project is a root project? However I do not know how to resolve this.

My top level settings.gradle file looks like this

```<code>rootProject.name = 'Project A'

include 'SubProject B'
include 'SubProject C'
include 'SubProject D'
include 'SubProject E'
include 'SubProject Shared'
</code>```

This is my build.gradle file for 'SubProject C'

```<code>dependencies {
    compile project(':Shared')
}
</code>```

Bonus question... Do the sub projects need a settings.gradle file with the 'rootProject.name' set as the sub projects name?

答:
In my case the problem was that my subproject had settings.gradle with

```<code>rootProject.name = 'MySubProject'
</code>```

removing the file fixed it. (It seems you must not have the file at all, it is not enough to remove the property.)

Body:
I have a Multi project gradle project with the following structure.

Project A: The top level project that all sub projects reside in.
  SubProject B:
  SubProject C:
  SubProject D:
  SubProject E:
  SubProject Shared: Every 'SubProject' has a dependency to this project "compile project(':Shared')"

Everything works correctly when running Gradle tasks from the top level 'Project A'

However, when I try to run an individual task on a subproject such as 'SubProject C' I get the following error.

FAILURE: Build failed with an exception

What went wrong:

A problem occurred evaluating root project 'SubProject C'.

Project with path ':Shared' could not be found in root project 'SubProject C'.

I think I see the problem here, Gradle thinks my sub project is a root project? However I do not know how to resolve this.

My top level settings.gradle file looks like this

rootProject.name = 'Project A'

include 'SubProject B'
include 'SubProject C'
include 'SubProject D'
include 'SubProject E'
include 'SubProject Shared'

This is my build.gradle file for 'SubProject C'

dependencies {
    compile project(':Shared')
}

Bonus question... Do the sub projects need a settings.gradle file with the 'rootProject.name' set as the sub projects name?

Body:
In my case the problem was that my subproject had settings.gradle with

rootProject.name = 'MySubProject'

removing the file fixed it. (It seems you must not have the file at all, it is not enough to remove the property.)


问:
C# Object Constructor - shorthand property syntax
A few months ago I read about a technique so that if there parameters you passed in matched the local variables then you could use some short hand syntax to set them. To avoid this:

```<code>public string Method(p1, p2, p3)
{
    this.p1 = p1;
    this.p2 = p2;
    this.p3 = p3;
}
</code>```

Any ideas?

答:
There's an even easier method of doing this in C# 7 - Expression bodied constructors.

Using your example above - your constructor can be simplified to one line of code. I've included the class fields for completeness, I presume they would be on your class anyway.

```<code>private string _p1;
private int _p2;
private bool _p3;

public Method(string p1, int p2, bool p3) => (_p1, _p2, _p3) = (p1, p2, p3);
</code>```

See the following link for more info :-

https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/statements-expressions-operators/expression-bodied-members

OwnerDisplayName: Schotime

Body:
A few months ago I read about a technique so that if there parameters you passed in matched the local variables then you could use some short hand syntax to set them. To avoid this:

public string Method(p1, p2, p3)
{
    this.p1 = p1;
    this.p2 = p2;
    this.p3 = p3;
}

Any ideas?

Body:
There's an even easier method of doing this in C# 7 - Expression bodied constructors.

Using your example above - your constructor can be simplified to one line of code. I've included the class fields for completeness, I presume they would be on your class anyway.

private string _p1;
private int _p2;
private bool _p3;

public Method(string p1, int p2, bool p3) => (_p1, _p2, _p3) = (p1, p2, p3);

See the following link for more info :-

https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/statements-expressions-operators/expression-bodied-members


问:
Jquery - Header banner rotator
Can anybody recommend a decent cross-browser jquery banner rotator that I can use to dynamically fade between click-able banners?

Thanks for your help
Paul

答: How about Shuffle, a jQuery banner rotator plugin featuring multiple transitions?</p>

Title: Jquery - Header banner rotator


问:
How to display inputted text along with some constant text in typing effect?
I am taking input using prompt and saving it in "a"
see:

```<code><script type="text/javascript" language="Javascript">
    var a=prompt("Please Enter Your Name ");
</script>
</code>```

and then i want the text stored in "a" and some text like "blah blah blah" printed in a single line with typewriter effect of css.

html {
  min-height: 100%;
  overflow: hidden;
}

body {
  display: flex;
  background-repeat: no-repeat;
  /* background-attachment: fixed;*/
  background-image: radial-gradient(black, white);
}

/* DEMO-SPECIFIC STYLES */
.typewriter h1 {
  color: #fff;
  font-family: monospace;
  overflow: hidden; /* Ensures the content is not revealed until the animation */
  border-right: .15em solid orange; /* The typwriter cursor */
  white-space: nowrap; /* Keeps the content on a single line */
  margin: 0 auto; /* Gives that scrolling effect as the typing happens */
  letter-spacing: .15em; /* Adjust as needed */
  animation:
  typing 3.5s steps(40, end),
  blink-caret .75s step-end infinite;
}

/* The typing effect */
@keyframes typing {
  from { width: 0 }
  to { width: 100% }
}

/* The typewriter cursor effect */
@keyframes blink-caret {
  from, to { border-color: transparent }
  50% { border-color: orange; }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
  <script type="text/javascript" language="Javascript">
    var a = prompt("Please Enter Your Name ");
  </script>
  <div class="typewriter">
    <h1>
      <script>
        docment.write(a)
      </script>blah blah
    </h1>
  </div>
</body></code>```

When i run it i onle see blah blah blah ani mation not the text stored in "a"

答:
Try like this.

var a=prompt("Please Enter Your Name ");
                 document.getElementById("name").innerHTML = a;```
<pre class="snippet-code-css lang-css prettyprint-override"><code>html {
      min-height: 100%;
      overflow: hidden;
}
body
    {
        display: flex;
        background-repeat: no-repeat;
       /* background-attachment: fixed;*/
        background-image: radial-gradient(black,white);
    }

/* DEMO-SPECIFIC STYLES */
.typewriter h1 {
  color: #fff;
  font-family: monospace;
  overflow: hidden; /* Ensures the content is not revealed until the animation */
  border-right: .15em solid orange; /* The typwriter cursor */
  white-space: nowrap; /* Keeps the content on a single line */
  margin: 0 auto; /* Gives that scrolling effect as the typing happens */
  letter-spacing: .15em; /* Adjust as needed */
     animation:
    typing 3.5s steps(40, end),
    blink-caret .75s step-end infinite;
}

/* The typing effect */
@keyframes typing {
  from { width: 0 }
  to { width: 100% }
}

/* The typewriter cursor effect */
@keyframes blink-caret {
  from, to { border-color: transparent }
  50% { border-color: orange; }
}
}</code>```

<title>HAPPY INDEPENDANCE DAY</title>
<link rel="stylesheet" href="full.css">

```

Body:
I am taking input using prompt and saving it in "a"
see:

and then i want the text stored in "a" and some text like "blah blah blah" printed in a single line with typewriter effect of css.

html {
  min-height: 100%;
  overflow: hidden;
}

body {
  display: flex;
  background-repeat: no-repeat;
  /* background-attachment: fixed;*/
  background-image: radial-gradient(black, white);
}

/* DEMO-SPECIFIC STYLES */
.typewriter h1 {
  color: #fff;
  font-family: monospace;
  overflow: hidden; /* Ensures the content is not revealed until the animation */
  border-right: .15em solid orange; /* The typwriter cursor */
  white-space: nowrap; /* Keeps the content on a single line */
  margin: 0 auto; /* Gives that scrolling effect as the typing happens */
  letter-spacing: .15em; /* Adjust as needed */
  animation:
  typing 3.5s steps(40, end),
  blink-caret .75s step-end infinite;
}

/* The typing effect */
@keyframes typing {
  from { width: 0 }
  to { width: 100% }
}

/* The typewriter cursor effect */
@keyframes blink-caret {
  from, to { border-color: transparent }
  50% { border-color: orange; }
}

      blah blah

When i run it i onle see blah blah blah ani mation not the text stored in "a"

Body:
Try like this.

var a=prompt("Please Enter Your Name ");
                 document.getElementById("name").innerHTML = a;

html {
      min-height: 100%;
      overflow: hidden;
}
body
    {
        display: flex;
        background-repeat: no-repeat;
       /* background-attachment: fixed;*/
        background-image: radial-gradient(black,white);
    }

/* DEMO-SPECIFIC STYLES */
.typewriter h1 {
  color: #fff;
  font-family: monospace;
  overflow: hidden; /* Ensures the content is not revealed until the animation */
  border-right: .15em solid orange; /* The typwriter cursor */
  white-space: nowrap; /* Keeps the content on a single line */
  margin: 0 auto; /* Gives that scrolling effect as the typing happens */
  letter-spacing: .15em; /* Adjust as needed */
     animation:
    typing 3.5s steps(40, end),
    blink-caret .75s step-end infinite;
}

/* The typing effect */
@keyframes typing {
  from { width: 0 }
  to { width: 100% }
}

/* The typewriter cursor effect */
@keyframes blink-caret {
  from, to { border-color: transparent }
  50% { border-color: orange; }
}
}

<html>
<head>
<!--Google Analytics code Here -->
<title>HAPPY INDEPENDANCE DAY</title>
<link rel="stylesheet" href="full.css">

</head>
<body>

<div class="typewriter">
    <h1 id="name"></h1>
</div>
</body>
</html>


答:
Say you had a function like this:

```<code>void* allocate(std::size_t sz, void* hint = nullptr) {
    // if you give `hint` it *might* be more efficient
}
</code>```

And then you decided that it is no longer worth the effort to do stuff based on hint. So you would do this:

```<code>void* allocate(std::size_t sz, [[deprecated]] void* hint = nullptr) {
    // `hint` is ignored. The compiler warns me if I use it in the
    // function body accidentally, and people reading the function
    // signature can see that it is probably going to be ignored.
}
</code>```

This allows the library to keep the same signature/ABI (So you don't need to recompile stuff that uses it and legacy code can still keep using it without doing any harm), and also prevents it from accidentally being used again when changing the function.

But this is mostly for developers of the function, not the users of the function, in the future so they know why a seemingly "useless" parameter is there.

I would also think that this would disable the "unused parameter" warning with the -Werror=unused-parameter flag in gcc/clang, but it doesn't. Using (void) deprecated_parameter also issues a warning about using a deprecated parameter, so this seems like a bug. If it did disable the unused param warning, that would be another use case for [[deprecated]].

Title: Mark as deprecated function parameters in C++14

Body:
Say you had a function like this:

void* allocate(std::size_t sz, void* hint = nullptr) {
    // if you give `hint` it *might* be more efficient
}

And then you decided that it is no longer worth the effort to do stuff based on hint. So you would do this:

void* allocate(std::size_t sz, [[deprecated]] void* hint = nullptr) {
    // `hint` is ignored. The compiler warns me if I use it in the
    // function body accidentally, and people reading the function
    // signature can see that it is probably going to be ignored.
}

This allows the library to keep the same signature/ABI (So you don't need to recompile stuff that uses it and legacy code can still keep using it without doing any harm), and also prevents it from accidentally being used again when changing the function.

But this is mostly for developers of the function, not the users of the function, in the future so they know why a seemingly "useless" parameter is there.

I would also think that this would disable the "unused parameter" warning with the -Werror=unused-parameter flag in gcc/clang, but it doesn't. Using (void) deprecated_parameter also issues a warning about using a deprecated parameter, so this seems like a bug. If it did disable the unused param warning, that would be another use case for [[deprecated]].


问:
How to get item from HTML select in Python Flask
Note:

I know there's a bunch of question like mine but I really try them but any works.

I'm trying to get the selected option by the user in my endpoint but it doesn't working.

I've tried:

To write the attribute name on the select html tag.
In the backend I tried this two options
type_user = request.form.get('type_user') and this
type_user = request.form['type_user']

I use debbuger mode and see that auth.py is not receiving any data just a  None.

register.html

```<code>#I don't know if it is for the desabled attribute, if the user
#is not logged so he cannot create a admin account only a normal account.
{% if g.user['type'] == 0 %}
        <div class="form-group">
          <label for="type_user">Type of User <span style="color: red">*</span></label>
          <select class="form-control" id="type_user" name="type_user" required>
            <option value="0">Admin</option>
            <option value="1">User</option>
          </select>
        </div>
      {% else %}
      <div class="form-group">
          <label for="type_user">Type of User <span style="color: red">*</span></label>
          <select class="form-control" id="type_user" name="type_user" required disabled>
            <option value="1">User</option>
          </select>
        </div>
      {% endif %}
</code>```

auth.py

```<code>@bp.route('/register', methods=('GET', 'POST'))
def register():
    if request.method == 'POST':
        first_name = request.form['first_name']
        last_name = request.form['last_name']
        type_user = int(request.form.get('type_user'))
        username = request.form['username']
        password = request.form['password']
        db = get_db()
        error = None
        print(type_user)
        print(first_name)
        if not (first_name and last_name and type_user and username and password):
            error = "Please fill all requiered fields"

        elif db.execute(
            'SELECT id FROM user WHERE username = ?', (username,)
        ).fetchone() is not None:
            error = 'User {} is already registered.'.format(username)

        if error is None:
            db.execute(
                'INSERT INTO user (first_name, last_name, type, username, password) VALUES (?, ?, ?, ?, ?)',
                (first_name, last_name, type_user, username, generate_password_hash(password))
            )
            db.commit()
            return redirect(url_for('auth.login'))

        flash(error)

    return render_template('auth/register.html')
</code>```

Error:

File "D:\Dev\patterns-project\study_room\auth.py", line 15, in
  register
        -----> type_user = request.form['type_user'] <-----    File "d:\dev\patterns-project\my-venv\lib\site-
        packages\werkzeug\datastructures.py", line 442, in getitem
         raise exceptions.BadRequestKeyError(key)

答:
I'm simplifying my answer to be more clear.

register.html - no need to change that.  What you've got works.

auth.py - minor change required.  The the if/else statement added below to your code:

@bp.route('/register', methods=('GET', 'POST'))
def register():
    if request.method == 'POST':
        first_name = request.form['first_name']
        last_name = request.form['last_name']

        ### Start of changed section ###
        # The line below will be None if type_user is disabled
        # type_user = int(request.form.get('type_user'))
        if "type_user" in request.form:
            # Current user must be an admin and have the option to select
            # the type_user for the new user, so read it here.
            type_user = request.form["type_user"]
        else:
            # The type_user field in the form must be disabled.
            # This means a  standard user or anonymouse person
            # must be registering a new user.  So the new user
            # must be a standard user.
            type_user = 1
        ### End of changed section ###

        username = request.form['username']
        password = request.form['password']
        db = get_db()
        error = None
        print(type_user)
        print(first_name)
        if not (first_name and last_name and type_user and username and password):
            error = "Please fill all requiered fields"

        elif db.execute(
            'SELECT id FROM user WHERE username = ?', (username,)
        ).fetchone() is not None:
            error = 'User {} is already registered.'.format(username)

        if error is None:
            db.execute(
                'INSERT INTO user (first_name, last_name, type, username, password) VALUES (?, ?, ?, ?, ?)',
                (first_name, last_name, type_user, username, generate_password_hash(password))
            )
            db.commit()
            return redirect(url_for('auth.login'))

        flash(error)

    return render_template('auth/register.html')
```

<p>The problem with using <code>disabled</code> in the HTML is that it makes the <code><select></code> totally unavailable.  Checking for <code>type_user</code> in the dictionary handles this case as shown above and below:</p>

<pre class="lang-py prettyprint-override"><code>if "type_user" in request.form:
    type_user = request.form["type_user"])
else:
    type_user = 1
</code>```

Thanks @roganjosh for pointing out my original mistake focusing on the
.

Implementation here: https://github.com/johnhut/flask/tree/so-q56338730

Body:
Note:

I know there's a bunch of question like mine but I really try them but any works.

I'm trying to get the selected option by the user in my endpoint but it doesn't working.

I've tried:

To write the attribute name on the select html tag.
In the backend I tried this two options
type_user = request.form.get('type_user') and this
type_user = request.form['type_user']

I use debbuger mode and see that auth.py is not receiving any data just a  None.

register.html

#I don't know if it is for the desabled attribute, if the user
#is not logged so he cannot create a admin account only a normal account.
{% if g.user['type'] == 0 %}

          Type of User *
          <select class="form-control" id="type_user" name="type_user" required>
            <option value="0">Admin</option>
            <option value="1">User</option>
          </select>

      {% else %}

          Type of User *
          <select class="form-control" id="type_user" name="type_user" required disabled>
            <option value="1">User</option>
          </select>

      {% endif %}

auth.py

@bp.route('/register', methods=('GET', 'POST'))
def register():
    if request.method == 'POST':
        first_name = request.form['first_name']
        last_name = request.form['last_name']
        type_user = int(request.form.get('type_user'))
        username = request.form['username']
        password = request.form['password']
        db = get_db()
        error = None
        print(type_user)
        print(first_name)
        if not (first_name and last_name and type_user and username and password):
            error = "Please fill all requiered fields"

        elif db.execute(
            'SELECT id FROM user WHERE username = ?', (username,)
        ).fetchone() is not None:
            error = 'User {} is already registered.'.format(username)

        if error is None:
            db.execute(
                'INSERT INTO user (first_name, last_name, type, username, password) VALUES (?, ?, ?, ?, ?)',
                (first_name, last_name, type_user, username, generate_password_hash(password))
            )
            db.commit()
            return redirect(url_for('auth.login'))

        flash(error)

    return render_template('auth/register.html')

Error:

File "D:\Dev\patterns-project\study_room\auth.py", line 15, in
  register
        -----> type_user = request.form['type_user'] <-----    File "d:\dev\patterns-project\my-venv\lib\site-
        packages\werkzeug\datastructures.py", line 442, in getitem
         raise exceptions.BadRequestKeyError(key)

Body:
I'm simplifying my answer to be more clear.

register.html - no need to change that.  What you've got works.

auth.py - minor change required.  The the if/else statement added below to your code:

@bp.route('/register', methods=('GET', 'POST'))
def register():
    if request.method == 'POST':
        first_name = request.form['first_name']
        last_name = request.form['last_name']

        ### Start of changed section ###
        # The line below will be None if type_user is disabled
        # type_user = int(request.form.get('type_user'))
        if "type_user" in request.form:
            # Current user must be an admin and have the option to select
            # the type_user for the new user, so read it here.
            type_user = request.form["type_user"]
        else:
            # The type_user field in the form must be disabled.
            # This means a  standard user or anonymouse person
            # must be registering a new user.  So the new user
            # must be a standard user.
            type_user = 1
        ### End of changed section ###

        username = request.form['username']
        password = request.form['password']
        db = get_db()
        error = None
        print(type_user)
        print(first_name)
        if not (first_name and last_name and type_user and username and password):
            error = "Please fill all requiered fields"

        elif db.execute(
            'SELECT id FROM user WHERE username = ?', (username,)
        ).fetchone() is not None:
            error = 'User {} is already registered.'.format(username)

        if error is None:
            db.execute(
                'INSERT INTO user (first_name, last_name, type, username, password) VALUES (?, ?, ?, ?, ?)',
                (first_name, last_name, type_user, username, generate_password_hash(password))
            )
            db.commit()
            return redirect(url_for('auth.login'))

        flash(error)

    return render_template('auth/register.html')

The problem with using disabled in the HTML is that it makes the <select> totally unavailable.  Checking for type_user in the dictionary handles this case as shown above and below:

if "type_user" in request.form:
    type_user = request.form["type_user"])
else:
    type_user = 1

Thanks @roganjosh for pointing out my original mistake focusing on the <div>.

Implementation here: https://github.com/johnhut/flask/tree/so-q56338730