问:
Hi, I am currently upgrading wicket application from 1.5.3 to 6.30.0 but i am getting error and login page is not getting instantiated
org.apache.wicket.WicketRuntimeException: Can't instantiate page using constructor 'public com.ecs.test.web.page.Login()'. An exception has been thrown during construction!
    at org.apache.wicket.session.DefaultPageFactory.newPage(DefaultPageFactory.java:194)

Caused by: java.lang.NoClassDefFoundError: javax/inject/Inject
    at org.apache.wicket.spring.injection.annot.AnnotProxyFieldValueFactory.supportsField(AnnotProxyFieldValueFactory.java:324)
    at org.apache.wicket.injection.Injector.findFields(Injector.java:148)

答: it might help tring to add Objenesis lib to your project dependencies. Wicket CI checks if this lib is available and if so, it's used to build proxy objects even if they don't provide a no args (i.e. Default) constructor.</p>


来源: stackexchange

问:
I am unable to remove index.php from URl in codeigniter 3.1.11
I tried adding .htaccess in root folder from the documentation available. i searched all over the internet but nothing solved my problem.

code inside .htaccess

```<code>RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]

</code>```

made a changes in apache file httpd

```<code>LoadModule rewrite_module modules/mod_rewrite.so

</code>```

can anyone tell me what could be the reason?

答:
```<code>some cases the default setting for uri_protocol does not work properly. To solve this
issue just open the file config.php located in application/config and then find and
replace the code as:

  Find the below code

 $config['uri_protocol'] = "AUTO"

  Replace it as

 $config['uri_protocol'] = "REQUEST_URI"
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I tried adding .htaccess in root folder from the documentation available. i searched all over the internet but nothing solved my problem.

code inside .htaccess

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]

made a changes in apache file httpd

LoadModule rewrite_module modules/mod_rewrite.so

can anyone tell me what could be the reason?


问:
How to set value to new column in Rails 3?
This is probably in another question, but I cannot find it.

I am a relative noobie to Rails.  I am trying to add a new column to a table that already has data in it.  This column is not going to allow nulls.  What is the easiest way to update all the existing records to have a value in this new column?  I know it is probably in the up block of my migration, but I don't know what the syntax would be.

```<code>def self.up
  change_table :reminders do |t|
    t.boolean :active
  end
  #model name is Reminder - how to update data with a value?
end
</code>```

答:
Try this:

```<code>def self.up
  change_table :reminders do |t|
   t.boolean :active, :default => true #or your value
  end
#model name is Reminder - how to update data with a value?
end
</code>```

ContentLicense: CC BY-SA 3.0

Body:
This is probably in another question, but I cannot find it.

I am a relative noobie to Rails.  I am trying to add a new column to a table that already has data in it.  This column is not going to allow nulls.  What is the easiest way to update all the existing records to have a value in this new column?  I know it is probably in the up block of my migration, but I don't know what the syntax would be.

def self.up
  change_table :reminders do |t|
    t.boolean :active
  end
  #model name is Reminder - how to update data with a value?
end

Body:
Try this:

def self.up
  change_table :reminders do |t|
   t.boolean :active, :default => true #or your value
  end
#model name is Reminder - how to update data with a value?
end


问:
mongodump and mongorestore on PythonAnywhere
I am using PythonAnywhere to host my web application. Using Mongodb as my database. Now my task is to take backup periodically and restore specific version of mongodb whenever I want.

To do it on local(windows machine), it is pretty easy. Install Mongodb utilities and execute command

```<code>mongodump --mongodbConnectionString   //From location where this executable is stored
mongorestore --mongodbConnectionString
</code>```

Now my challenge is to do it from PythonAnywhere. Here how should I use these utilities?

I have Linux executables for mongodb from mongodb site, I extracted bin folder from it, it look like below

Now I moved this bin folder to PythonAnywhere and tried to execute mongodump command

```<code>~/../applications/mongodb-linux-x86_64-ubuntu1404-3.4.0/bin$ ./mongodump mongodbConnectionString
</code>```

it failed with below error

bash: ./mongodump: Permission denied

My question is how to do mongodump and mongorestore from PythonAnywhere? My final goal is to do periodic backup of mongodb database

答:
As there is less documentation about mongodb backup and restore on PythonAnywhere environment, so writing here all steps to do backup and restore of mongodb on PythonAnywhere.

Prerequisite: You need Pythonanywhere account and Mongodb connection string.

Steps to backup and restore mongodb on PythonAnywhere:

Download mongodump and mongorestore executables for Linux machine from mongodb site
  https://www.mongodb.org/dl/linux/x86_64-ubuntu1404

I downloaded mongodb-linux-x86_64-ubuntu1404-4.0.16, because I am using MongoDB 4.0

Extract it and upload required files(like mongodump and mongorestore) to PythonAnywhere's specific directory location.

After uploading these files, update its permission. I am windows user, so updated permission using WinSCP -> right click to file -> properties -> Select Groups/Owner permission.

Open Bash console from PythonAnywhere, go to directory where you stored mongodump and execute below command

~directory of your bin folder$ ./mongodump mongodb_connection_string.

I was getting bash: ./mongodump: Permission denied, because I was not giving proper permissions to these files.

Body:
I am using PythonAnywhere to host my web application. Using Mongodb as my database. Now my task is to take backup periodically and restore specific version of mongodb whenever I want.

To do it on local(windows machine), it is pretty easy. Install Mongodb utilities and execute command

mongodump --mongodbConnectionString   //From location where this executable is stored
mongorestore --mongodbConnectionString

Now my challenge is to do it from PythonAnywhere. Here how should I use these utilities?

I have Linux executables for mongodb from mongodb site, I extracted bin folder from it, it look like below

Now I moved this bin folder to PythonAnywhere and tried to execute mongodump command

~/../applications/mongodb-linux-x86_64-ubuntu1404-3.4.0/bin$ ./mongodump mongodbConnectionString

it failed with below error

bash: ./mongodump: Permission denied

My question is how to do mongodump and mongorestore from PythonAnywhere? My final goal is to do periodic backup of mongodb database


问:
How to Calculate change between rows in Pandas Data Frame
Suppose I have a daily sales record column. And from it I want to create two new columns. That keep track of the change from a month a go. For each day on the record. How would I go about doing this in Pandas Data frame. new to pandas and stuck here.
here is a sample data set

And what I am looking for is to create a new column "Change from a month ago",
which will tracks the difference between in daily sales between today and 30 days ago.

答:
you can use pandas.DataFrame.diff

```<code>df['new_col'] = df.sales.diff(periods=30)
</code>```

this will find the difference of current row and 30 rows above (this may or may not be 30 days ago)

Body:
you can use pandas.DataFrame.diff

df['new_col'] = df.sales.diff(periods=30)

this will find the difference of current row and 30 rows above (this may or may not be 30 days ago)


问:
Running one specific Laravel migration (single file)
I have 5 migrations in my project. I only want to run one of these migrations. Is it possible to pass the name of a single file to the php artisan migrate command?

答:
If you want to run(single file) migration in Laravel you would do the following:

```<code>php artisan migrate --path=/database/migrations/migrations_file_name
</code>```

eg.

```<code>C:\xampp\htdocs\laravelv3s>php artisan migrate --path=/database/migrations/2020_02_14_102647_create_blogs_table.php
</code>```

Body:
If you want to run(single file) migration in Laravel you would do the following:

php artisan migrate --path=/database/migrations/migrations_file_name

eg.

C:\xampp\htdocs\laravelv3s>php artisan migrate --path=/database/migrations/2020_02_14_102647_create_blogs_table.php


问:
Python "list order"
I have 2 troubles with my data, can anyone help me:

How can I get from this:

1.

```<code>k=[['1','7', 'U1'],
 ['1.5', '8', 'U1'],
 ['2', '5.5', 'U1']]
</code>```

get this

```<code>1,7,U1
1.5,8,U1
2,5.5,U1
</code>```

EDIT 2   I MAKE SOME CHANGE ON  second case:, still searching solution for this one:

2. And how to get, from this

```<code>l=array([[[ 4.24231542], 'U1'],
       [[ 3.41424819], 'U1'],
       [[ 2.17214734], 'U1'],], dtype=object)
</code>```

get

```<code>4.24231542,U1
3.41424819,U1
2.17214734,U1
</code>```

Thanks

答:
One-line functional style:</p>

```<code>print '\n'.join(','.join(x) for x in k)
</code>```

Title: Python "list order"

Body:
I have 2 troubles with my data, can anyone help me:

How can I get from this:

1.

k=[['1','7', 'U1'],
 ['1.5', '8', 'U1'],
 ['2', '5.5', 'U1']]

get this

1,7,U1
1.5,8,U1
2,5.5,U1

EDIT 2   I MAKE SOME CHANGE ON  second case:, still searching solution for this one:

2. And how to get, from this

l=array([[[ 4.24231542], 'U1'],
       [[ 3.41424819], 'U1'],
       [[ 2.17214734], 'U1'],], dtype=object)

get

4.24231542,U1
3.41424819,U1
2.17214734,U1

Thanks

Body:
One-line functional style:

print '\n'.join(','.join(x) for x in k)


问:
How can I get my Community Connector to trigger a "Date Range Dimension" in Datastudio?
I've created a working Community Connector by following the Community Connector Codelab but how can I get it to have a 'Date Range Dimension' when it is selected as a datasource in datastudio ?

Here's what my datasource looks like (No 'Date Range Dimension'):

And here's an example of a datasource with a 'Date Range Dimension':

I don't understand what I'm missing. The connector returns date dimensions from getFields()

```<code>  fields.newDimension()
    .setId('date_created')
    .setType(types.YEAR_MONTH_DAY)
    .setGroup('Date');
</code>```

We're setting the date range required to true in getConfig too:

```<code>function getConfig(request) {
  var cc = DataStudioApp.createCommunityConnector();
  var config = cc.getConfig();

  config.newInfo()
    .setId('instructions')
    .setText('Use the date range to specify what activities to return.');

  config.setDateRangeRequired(true);

  return config.build();
}
</code>```

and here's the getSchema(), it's all basically ripped off from the codelab

```<code>function getSchema(request) {
  var fields = getFields(request).build();
  return { schema: fields };
}

function getFields(request) {
  var cc = DataStudioApp.createCommunityConnector();
  var fields = cc.getFields();
  var types = cc.FieldType;
  var aggregations = cc.AggregationType;

  fields.newDimension()
    .setId('id')
    .setType(types.NUMBER);

  fields.newDimension()
    .setId('owner_id')
    .setType(types.NUMBER);

  fields.newDimension()
    .setId('subject')
    .setType(types.TEXT);

  fields.newDimension()
    .setId('medium')
    .setType(types.TEXT);

  fields.newDimension()
    .setId('date_logged')
    .setType(types.YEAR_MONTH_DAY);

  fields.newDimension()
    .setId('date_started')
    .setType(types.YEAR_MONTH_DAY);

  fields.newDimension()
    .setId('date_ended')
    .setType(types.YEAR_MONTH_DAY);

  fields.newMetric()
    .setId('billable')
    .setType(types.NUMBER)
    .setAggregation(aggregations.SUM);

  fields.newMetric()
    .setId('nonbillable')
    .setType(types.NUMBER)
    .setAggregation(aggregations.SUM);

 fields.newMetric()
    .setId('time_allocation')
    .setType(types.NUMBER)
    .setAggregation(aggregations.SUM);

  fields.newMetric()
    .setId('scheduled_duration')
    .setType(types.NUMBER)
    .setAggregation(aggregations.SUM);

  return fields;
}
</code>```

Cheers.

答:
You don't have to check if date range is selected. If data range is not selected there is 1 month date range by default. So you can just save start and end date to the variables.

```<code>var sinceDate = request.dateRange.startDate;
var untilDate = request.dateRange.endDate;
</code>```

For better understanding later, you can always console.log(request) and see what is requested.

Body:
I've created a working Community Connector by following the Community Connector Codelab but how can I get it to have a 'Date Range Dimension' when it is selected as a datasource in datastudio ?

Here's what my datasource looks like (No 'Date Range Dimension'):

And here's an example of a datasource with a 'Date Range Dimension':

I don't understand what I'm missing. The connector returns date dimensions from getFields()

  fields.newDimension()
    .setId('date_created')
    .setType(types.YEAR_MONTH_DAY)
    .setGroup('Date');

We're setting the date range required to true in getConfig too:

function getConfig(request) {
  var cc = DataStudioApp.createCommunityConnector();
  var config = cc.getConfig();

  config.newInfo()
    .setId('instructions')
    .setText('Use the date range to specify what activities to return.');

  config.setDateRangeRequired(true);

  return config.build();
}

and here's the getSchema(), it's all basically ripped off from the codelab

function getSchema(request) {
  var fields = getFields(request).build();
  return { schema: fields };
}

function getFields(request) {
  var cc = DataStudioApp.createCommunityConnector();
  var fields = cc.getFields();
  var types = cc.FieldType;
  var aggregations = cc.AggregationType;

  fields.newDimension()
    .setId('id')
    .setType(types.NUMBER);

  fields.newDimension()
    .setId('owner_id')
    .setType(types.NUMBER);

  fields.newDimension()
    .setId('subject')
    .setType(types.TEXT);

  fields.newDimension()
    .setId('medium')
    .setType(types.TEXT);

  fields.newDimension()
    .setId('date_logged')
    .setType(types.YEAR_MONTH_DAY);

  fields.newDimension()
    .setId('date_started')
    .setType(types.YEAR_MONTH_DAY);

  fields.newDimension()
    .setId('date_ended')
    .setType(types.YEAR_MONTH_DAY);

  fields.newMetric()
    .setId('billable')
    .setType(types.NUMBER)
    .setAggregation(aggregations.SUM);

  fields.newMetric()
    .setId('nonbillable')
    .setType(types.NUMBER)
    .setAggregation(aggregations.SUM);

 fields.newMetric()
    .setId('time_allocation')
    .setType(types.NUMBER)
    .setAggregation(aggregations.SUM);

  fields.newMetric()
    .setId('scheduled_duration')
    .setType(types.NUMBER)
    .setAggregation(aggregations.SUM);

  return fields;
}

Cheers.

Body:
You don't have to check if date range is selected. If data range is not selected there is 1 month date range by default. So you can just save start and end date to the variables.

var sinceDate = request.dateRange.startDate;
var untilDate = request.dateRange.endDate;

For better understanding later, you can always console.log(request) and see what is requested.


问:
Why is $_POST[''] not working with <form>
This is a Rock Paper Scissors game and I am just starting on it, but it will not display the $_POST['keuzen'].

So I don't get why this is not working. Tried many things but can't find a good solution.

```<code><?php session_start(); ?>
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>RockPaperScissor</title>
    </head>
    <body>
        <form action="RockPaperScissor.php" method="post">
            <input type="image" src="steen.jpg" alt="steen" name="keuzen" value="steen" title="Steen">
            <input type="image" src="papier.jpg" alt="papier" name="keuzen" value="papier" title="Papier">
            <input type="image" src="schaar.jpg" alt="schaar" name="keuzen" value="schaar" title="Schaar">
        </form>
        <?php
            if (isset($_POST['keuzen'])) {
                $keuzen = $_POST['keuzen'];
                $kiezenuit = array("steen", "papier", "schaar");
                $random = rand(0, 2);
                $computer = $kiezenuit[$random];

                echo 'jij koos ' . $keuzen . '<br>';
                echo 'De computer koos ' . $computer . '<br';

                if ($keuzen == $computer) {
                    echo 'Resultaat : Draw ';
                }
            }
        ?>
    </body>
</html>
</code>```

答:
Assuming the form is in the same RockPaperScissor.php page, better introduce a hidden field that takes the value of a clicked image, but remove the name tag from the images itself:

```<code><?php session_start(); ?>
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>RockPaperScissor</title>
    </head>
    <body>
        <form action="RockPaperScissor.php" method="post">
            <input type="hidden" name="keuzen" value="">
            <input type="image" src="steen.jpg" alt="steen" value="steen" title="Steen" onclick="document.forms[0].keuzen.value=this.value">
            <input type="image" src="papier.jpg" alt="papier" value="papier" title="Papier" onclick="document.forms[0].keuzen.value=this.value">
            <input type="image" src="schaar.jpg" alt="schaar" value="schaar" title="Schaar" onclick="document.forms[0].keuzen.value=this.value">
        </form>
        <?php
            if (!empty($_POST['keuzen'])) {
                $keuzen = $_POST['keuzen'];
                $kiezenuit = array("steen", "papier", "schaar");
                $random = rand(0, 2);
                $computer = $kiezenuit[$random];

                echo 'jij koos ' . $keuzen . '<br>';
                echo 'De computer koos ' . $computer . '<br>';

                if ($keuzen == $computer) {
                    echo 'Resultaat : Draw ';
                }
            }
        ?>
    </body>
</html>
</code>```

Upon POST, you will get the following:

```<code>Array
(
    [keuzen] => schaar
    [x] => 7
    [y] => 3
)

jij koos schaar
De computer koos schaar
Resultaat : Draw
</code>```

Body:
This is a Rock Paper Scissors game and I am just starting on it, but it will not display the $_POST['keuzen'].

So I don't get why this is not working. Tried many things but can't find a good solution.

<?php session_start(); ?>
<!DOCTYPE html>

        <meta charset="UTF-8">
        <title>RockPaperScissor</title>

        <form action="RockPaperScissor.php" method="post">
            <input type="image" src="steen.jpg" alt="steen" name="keuzen" value="steen" title="Steen">
            <input type="image" src="papier.jpg" alt="papier" name="keuzen" value="papier" title="Papier">
            <input type="image" src="schaar.jpg" alt="schaar" name="keuzen" value="schaar" title="Schaar">
        </form>
        <?php
            if (isset($_POST['keuzen'])) {
                $keuzen = $_POST['keuzen'];
                $kiezenuit = array("steen", "papier", "schaar");
                $random = rand(0, 2);
                $computer = $kiezenuit[$random];

                echo 'jij koos ' . $keuzen . '
';
                echo 'De computer koos ' . $computer . '

Body:
Assuming the form is in the same RockPaperScissor.php page, better introduce a hidden field that takes the value of a clicked image, but remove the name tag from the images itself:

<?php session_start(); ?>
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>RockPaperScissor</title>
    </head>
    <body>
        <form action="RockPaperScissor.php" method="post">
            <input type="hidden" name="keuzen" value="">
            <input type="image" src="steen.jpg" alt="steen" value="steen" title="Steen" onclick="document.forms[0].keuzen.value=this.value">
            <input type="image" src="papier.jpg" alt="papier" value="papier" title="Papier" onclick="document.forms[0].keuzen.value=this.value">
            <input type="image" src="schaar.jpg" alt="schaar" value="schaar" title="Schaar" onclick="document.forms[0].keuzen.value=this.value">
        </form>
        <?php
            if (!empty($_POST['keuzen'])) {
                $keuzen = $_POST['keuzen'];
                $kiezenuit = array("steen", "papier", "schaar");
                $random = rand(0, 2);
                $computer = $kiezenuit[$random];

                echo 'jij koos ' . $keuzen . '<br>';
                echo 'De computer koos ' . $computer . '<br>';

                if ($keuzen == $computer) {
                    echo 'Resultaat : Draw ';
                }
            }
        ?>
    </body>
</html>

Upon POST, you will get the following:

Array
(
    [keuzen] => schaar
    [x] => 7
    [y] => 3
)

jij koos schaar
De computer koos schaar
Resultaat : Draw


问:
Does universal link work on the apps from enterprise program?
I've followed instructions from the apple for enabling universal links.

Following is my aasa file

```<code>{
    "applinks": {
        "apps": [],
        "details": [
            {
                "appID": "app.store.app",
                "paths": ["*"]
            },
            {
                "appID": "enterprise.app",
                "paths": ["*"]
            }
        ]
    }
}
</code>```

I am able to use universal link for the app store app. But I've never been able to open links for the enterprise app(apps that are created for internal distribution https://developer.apple.com/programs/enterprise/)...

I have followed https://developer.apple.com/library/archive/documentation/General/Conceptual/AppSearch/UniversalLinks.html and made sure that "The appID value is the same value that’s associated with the “application-identifier” key in your app’s entitlements after you build it". I have also check the entitlement file having the domain

Is there any document from Apple stating that enterprise apps cannot use universal link?

Thanks in advance!

答:
YES

In order to allow such a behavior, be sure to provide the apporiate TEAMID in the json file, as described https://developer.apple.com/documentation/uikit/inter-process_communication/allowing_apps_and_websites_to_link_to_your_content/enabling_universal_links

```<code>"details": [{
            "appID": "D3KQX62K1A.com.example.photoapp",
            "paths": ["/albums"]
</code>```

Moreover if your internal apps point to another server than the public one, remind to add a new associated domain in your app capabilities

Body:
I've followed instructions from the apple for enabling universal links.

Following is my aasa file

{
    "applinks": {
        "apps": [],
        "details": [
            {
                "appID": "app.store.app",
                "paths": ["*"]
            },
            {
                "appID": "enterprise.app",
                "paths": ["*"]
            }
        ]
    }
}

I am able to use universal link for the app store app. But I've never been able to open links for the enterprise app(apps that are created for internal distribution https://developer.apple.com/programs/enterprise/)...

I have followed https://developer.apple.com/library/archive/documentation/General/Conceptual/AppSearch/UniversalLinks.html and made sure that "The appID value is the same value that’s associated with the “application-identifier” key in your app’s entitlements after you build it". I have also check the entitlement file having the domain

Is there any document from Apple stating that enterprise apps cannot use universal link?

Thanks in advance!

Body:
YES

In order to allow such a behavior, be sure to provide the apporiate TEAMID in the json file, as described https://developer.apple.com/documentation/uikit/inter-process_communication/allowing_apps_and_websites_to_link_to_your_content/enabling_universal_links

"details": [{
            "appID": "D3KQX62K1A.com.example.photoapp",
            "paths": ["/albums"]

Moreover if your internal apps point to another server than the public one, remind to add a new associated domain in your app capabilities


问:
Is it possible to create a generic impl for a trait that works with all but one subset of types?
I am trying to write a generic method that accepts a function that returns either a Serialize value or an Arc<Serialize> value. My solution is to create a trait to unwrap the Arc if needed and produce a reference to the underlying value:

use serde::Serialize;
use std::sync::Arc;

pub trait Unwrapper {
    type Inner: Serialize;

    fn unwrap(&self) -> &Self::Inner;
}

impl<T> Unwrapper for T
where
    T: Serialize,
{
    type Inner = T;
    fn unwrap(&self) -> &Self::Inner {
        self
    }
}

impl<T> Unwrapper for Arc<T>
where
    T: Serialize,
{
    type Inner = T;
    fn unwrap(&self) -> &Self::Inner {
        self
    }
}

fn use_processor<F, O>(processor: F)
where
    O: Unwrapper,
    F: Fn() -> O,
{
    // do something useful processor
}
```

<p>I get a <code>E0119</code> error due to the potential that <code>Arc</code> may implement <code>Serialize</code> in the future, like if I enable the serde crate's feature to allow just that:</p>

<pre class="lang-none prettyprint-override"><code>error[E0119]: conflicting implementations of trait `Unwrapper` for type `std::sync::Arc<_>`:
  --> src/lib.rs:20:1
   |
10 | / impl<T> Unwrapper for T
11 | | where
12 | |     T: Serialize,
13 | | {
...  |
17 | |     }
18 | | }
   | |_- first implementation here
19 |
20 | / impl<T> Unwrapper for Arc<T>
21 | | where
22 | |     T: Serialize,
23 | | {
...  |
27 | |     }
28 | | }
   | |_^ conflicting implementation for `std::sync::Arc<_>`
</code>```

I don't want to do this as I only want to allow the Arc at the top level and not within the value (for the same reasons the feature is not on by default). Given this, Is there a way to disable my first impl only for an Arc? Or is there a better approach to the to problem?

答:
Your attempt does not work because
it is not possible to have overlapping implementations of a trait.

Below an attempt to write a generic method that accept a Serialize value or an
Arc of a  Serialize value.

It leverages the Borrow trait and its blanket implementation for any T.

Note the use of the turbo fish syntax on the calling site of the generic method.

```<code>use std::sync::Arc;
use std::borrow::Borrow;
use serde::Serialize;

#[derive(Serialize, Debug)]
struct Point {
    x: i32,
    y: i32,
}

fn myserialize<T: Borrow<I>, I: Serialize>(value: T) {
    let value = value.borrow();
    let serialized = serde_json::to_string(value).unwrap();
    println!("serialized = {}", serialized);
}

fn main() {
    let point = Point { x: 1, y: 2 };
    myserialize(point);

    let arc_point = Arc::new(Point { x: 1, y: 2 });
    myserialize::<_, Point>(arc_point);

}
</code>```

Body:
I am trying to write a generic method that accepts a function that returns either a Serialize value or an Arc<Serialize> value. My solution is to create a trait to unwrap the Arc if needed and produce a reference to the underlying value:

use serde::Serialize;
use std::sync::Arc;

pub trait Unwrapper {
    type Inner: Serialize;

    fn unwrap(&self) -> &Self::Inner;
}

impl<T> Unwrapper for T
where
    T: Serialize,
{
    type Inner = T;
    fn unwrap(&self) -> &Self::Inner {
        self
    }
}

impl<T> Unwrapper for Arc<T>
where
    T: Serialize,
{
    type Inner = T;
    fn unwrap(&self) -> &Self::Inner {
        self
    }
}

fn use_processor<F, O>(processor: F)
where
    O: Unwrapper,
    F: Fn() -> O,
{
    // do something useful processor
}

I get a E0119 error due to the potential that Arc may implement Serialize in the future, like if I enable the serde crate's feature to allow just that:

error[E0119]: conflicting implementations of trait `Unwrapper` for type `std::sync::Arc<_>`:
  --> src/lib.rs:20:1
   |
10 | / impl<T> Unwrapper for T
11 | | where
12 | |     T: Serialize,
13 | | {
...  |
17 | |     }
18 | | }
   | |_- first implementation here
19 |
20 | / impl<T> Unwrapper for Arc<T>
21 | | where
22 | |     T: Serialize,
23 | | {
...  |
27 | |     }
28 | | }
   | |_^ conflicting implementation for `std::sync::Arc<_>`

I don't want to do this as I only want to allow the Arc at the top level and not within the value (for the same reasons the feature is not on by default). Given this, Is there a way to disable my first impl only for an Arc? Or is there a better approach to the to problem?

Body:
Your attempt does not work because
it is not possible to have overlapping implementations of a trait.

Below an attempt to write a generic method that accept a Serialize value or an
Arc of a  Serialize value.

It leverages the Borrow trait and its blanket implementation for any T.

Note the use of the turbo fish syntax on the calling site of the generic method.

use std::sync::Arc;
use std::borrow::Borrow;
use serde::Serialize;

#[derive(Serialize, Debug)]
struct Point {
    x: i32,
    y: i32,
}

fn myserialize<T: Borrow<I>, I: Serialize>(value: T) {
    let value = value.borrow();
    let serialized = serde_json::to_string(value).unwrap();
    println!("serialized = {}", serialized);
}

fn main() {
    let point = Point { x: 1, y: 2 };
    myserialize(point);

    let arc_point = Arc::new(Point { x: 1, y: 2 });
    myserialize::<_, Point>(arc_point);

}


问:
React: How can i access a attribute within a  tag
in my code, i am trying to pass some data from my onClick() function

```<code><TableCell value={i} align="center" onClick={e => this.deleteUser(e)}><DeleteIcon /></TableCell>
</code>```

My table cell is created in a for loop, and it is assigned the value i when it is first created. When the delete user icon is clicked, i want the value i to be passed along as well. in my onClick function, the even is passed along

```<code>deleteUser(e) {
        console.log(e.currentTarget).
    }
</code>```

this is my delete user function. When i test the function with console.log(). This is printed

```<code><td class="MuiTableCell-root MuiTableCell-alignCenter" value="0"> ... </td>
</code>```

How can i get value from within the td tag? I cant access it with event.currentTarget.value

答:
Pass i to your deleteUser function

```<code><TableCell value={i} align="center" onClick={e => this.deleteUser(e, i)}><DeleteIcon /></TableCell>
</code>```

you will get value as a second argument

```<code>deleteUser(e, value) {
  console.log(e.currentTarget, value);
}
</code>```

Title: React: How can i access a attribute within a <td> tag

Body:
in my code, i am trying to pass some data from my onClick() function

<TableCell value={i} align="center" onClick={e => this.deleteUser(e)}><DeleteIcon /></TableCell>

My table cell is created in a for loop, and it is assigned the value i when it is first created. When the delete user icon is clicked, i want the value i to be passed along as well. in my onClick function, the even is passed along

deleteUser(e) {
        console.log(e.currentTarget).
    }

this is my delete user function. When i test the function with console.log(). This is printed

 ...

How can i get value from within the td tag? I cant access it with event.currentTarget.value

Body:
Pass i to your deleteUser function

<TableCell value={i} align="center" onClick={e => this.deleteUser(e, i)}><DeleteIcon /></TableCell>

you will get value as a second argument

deleteUser(e, value) {
  console.log(e.currentTarget, value);
}


问:
Firebase InstanceId unresolved identifier swift4
I have recently updated My SWIFT applications pod file, And because of that firebase version is now updated to a 5.2.
Which now gives me following error while getting a device instance id.

```<code>let tokenId = InstanceID.instanceID().token()
</code>```

error: Use of unresolved identifier 'InstanceID'

Previously this code was working fine and I was getting Application's Instance Id.

Following is content of my pod file.

```<code>   # Uncomment the next line to define a global platform for your project
# platform :ios, '11.2'

target 'FirebaseChat' do
  # Comment the next line if you're not using Swift and don't want to use dynamic frameworks
  use_frameworks!

  # Pods for FirebaseChat

pod 'Firebase/Database'
pod 'Firebase/Auth'
pod 'Firebase/Storage'
pod 'UnderLineTextField', '~> 2.0'
pod 'Alamofire'
pod 'TCPickerView'
pod 'Toast-Swift', '~> 3.0.1'
pod 'IQKeyboardManagerSwift'
end
</code>```

Any suggestions will be helpful.
Thank You.

答:
Syntax changed in latest update</p>

```<code>if let refreshedToken = FIRInstanceID.instanceID().token() {
        print("InstanceID token: \(refreshedToken)")
    }
</code>```

Body:
I have recently updated My SWIFT applications pod file, And because of that firebase version is now updated to a 5.2.
Which now gives me following error while getting a device instance id.

let tokenId = InstanceID.instanceID().token()

error: Use of unresolved identifier 'InstanceID'

Previously this code was working fine and I was getting Application's Instance Id.

Following is content of my pod file.

   # Uncomment the next line to define a global platform for your project
# platform :ios, '11.2'

target 'FirebaseChat' do
  # Comment the next line if you're not using Swift and don't want to use dynamic frameworks
  use_frameworks!

  # Pods for FirebaseChat

pod 'Firebase/Database'
pod 'Firebase/Auth'
pod 'Firebase/Storage'
pod 'UnderLineTextField', '~> 2.0'
pod 'Alamofire'
pod 'TCPickerView'
pod 'Toast-Swift', '~> 3.0.1'
pod 'IQKeyboardManagerSwift'
end

Any suggestions will be helpful.
Thank You.

Body:
Syntax changed in latest update

if let refreshedToken = FIRInstanceID.instanceID().token() {
        print("InstanceID token: \(refreshedToken)")
    }


问:
PHP: tmpfs vs memcached
I want to store information (sessions and a lot of strings) in RAM and I don't know if I should use a tmpfs or a memcached server. Someone did some benchmark and knows which one is faster? It's needed for some ajax scripts that requests informations every 1-5 seconds per user who is logged in, like a webchat in PHP. So PHP has to connect to memcache quite often.

The advantage of using tmpfs whould be that I can create a lot of files and have a structur (dirs), while I only have a key-value system in memcached, but there i could use arrays or objects to store information.
CPU load whould be interesting, too, if there is any difference.

Thanks.

答:
Just a couple points

tmpfs or ramdisk are more mature than memcached (been around longer but both are stable

tmpfs is scalable (you can resize or increase as needed without loosing the contents of tmpfs

memcahced is great if you need memory on another machine or if you need to share that information between machines.

local file/socket/pipe performance is ALWAYS faster than a network socket and accessing a file in tmpfs is the same as any other file so it does not require any 3rd party libraries.

If you don't expect you data to our grow the memory on your server use tmpfs.

If you must share the data between servers or want to store more data that whats fits into the RAM on your local server use memcahed.

ContentLicense: CC BY-SA 2.5

Title: PHP: tmpfs vs memcached


问:
How do I sort my text file if it has Integers and Strings in Python
I'm doing a high score system for my code for coursework, I managed to sort my numbers with some help from here, but now i decided to add the names so the high scores correlate to a person, it doeskin sort it, this is my code so far:

```<code>player1=input("input")
player1score=int(input("input"))

highscore = open("Scores.txt", "r")
whowon=("{0}-{1}".format(player1score,player1))
highscores = highscore.readlines()
highscore.close()
highscore = open("Scores.txt", "a")
highscore.write(whowon)
highscore.write("\n")
highscore.close()
highscore = open("Scores.txt", "r")
highscores = highscore.readlines()

highscores = [ x.rstrip() for x in highscores ]
highscores.sort(reverse=True, key=int)

top1=highscores[0]
top2=highscores[1]
top3=highscores[2]
top4=highscores[3]
top5=highscores[4]
top=("{0}\n{1}\n{2}\n{3}\n{4}\n".format(top1, top2, top3, top4, top5))

highscore.close()

highscore=open("Scores.txt", "w")
highscore.write(top)
highscore.close()

</code>```

the file outputs

```<code>68-Dylan
45-Snones
70-Pedro
</code>```

Is there a way i can separate the integer values, sort them, then put them back together respectively?
The error code im getting for this is

```<code>highscores.sort(reverse=True, key=int)
ValueError: invalid literal for int() with base 10: '68-Dylan'
</code>```

答:
Let's say this is your input string. You can use sorted, which takes a key argument to transform the data prior to sorting:

```<code>l = '''68-Dylan
45-Snones
70-Pedro'''.splitlines()

sorted(l, key=lambda x: int(x.split('-', 1)[0]))
# ['45-Snones', '68-Dylan', '70-Pedro']
</code>```

Body:
I'm doing a high score system for my code for coursework, I managed to sort my numbers with some help from here, but now i decided to add the names so the high scores correlate to a person, it doeskin sort it, this is my code so far:

player1=input("input")
player1score=int(input("input"))

highscore = open("Scores.txt", "r")
whowon=("{0}-{1}".format(player1score,player1))
highscores = highscore.readlines()
highscore.close()
highscore = open("Scores.txt", "a")
highscore.write(whowon)
highscore.write("\n")
highscore.close()
highscore = open("Scores.txt", "r")
highscores = highscore.readlines()

highscores = [ x.rstrip() for x in highscores ]
highscores.sort(reverse=True, key=int)

top1=highscores[0]
top2=highscores[1]
top3=highscores[2]
top4=highscores[3]
top5=highscores[4]
top=("{0}\n{1}\n{2}\n{3}\n{4}\n".format(top1, top2, top3, top4, top5))

highscore.close()

highscore=open("Scores.txt", "w")
highscore.write(top)
highscore.close()

the file outputs

68-Dylan
45-Snones
70-Pedro

Is there a way i can separate the integer values, sort them, then put them back together respectively?
The error code im getting for this is

highscores.sort(reverse=True, key=int)
ValueError: invalid literal for int() with base 10: '68-Dylan'

Body:
Let's say this is your input string. You can use sorted, which takes a key argument to transform the data prior to sorting:

l = '''68-Dylan
45-Snones
70-Pedro'''.splitlines()

sorted(l, key=lambda x: int(x.split('-', 1)[0]))
# ['45-Snones', '68-Dylan', '70-Pedro']


问:
tf.shape() get wrong shape in tensorflow
I define a tensor like this:

x = tf.get_variable("x", [100])

But when I try to print shape of tensor :

print( tf.shape(x) )

I get Tensor("Shape:0", shape=(1,), dtype=int32), why the result of output should not be shape=(100)

答:
Tensorflow 2.0 Compatible Answer: Tensorflow 2.x (>= 2.0) compatible answer for nessuno's solution is shown below:

```<code>x = tf.compat.v1.get_variable("x", [100])

print(x.get_shape())
</code>```

Body:
Tensorflow 2.0 Compatible Answer: Tensorflow 2.x (>= 2.0) compatible answer for nessuno's solution is shown below:

x = tf.compat.v1.get_variable("x", [100])

print(x.get_shape())


问:
How to Move bottomsheet along with keyboard which has textfield(autofocused is true)?
I'm trying to make a bottomsheet that has a text field and autofocus is set to true so that the keyboard pops up. But, bottomsheet is overlapped by the keyboard. Is there a way to move bottomsheet above the keyboard?</p>
```<code>Padding(
  padding:
      EdgeInsets.only(bottom: MediaQuery.of(context).viewInsets.bottom),
  child: Column(children: <Widget>[
    TextField(
      autofocus: true,
      decoration: InputDecoration(hintText: 'Title'),
    ),
    TextField(
      decoration: InputDecoration(hintText: 'Details!'),
      keyboardType: TextInputType.multiline,
      maxLines: 4,
    ),
    TextField(
      decoration: InputDecoration(hintText: 'Additional details!'),
      keyboardType: TextInputType.multiline,
      maxLines: 4,
    ),]);
</code>```

答:
After combining different solutions I got this:

if you don't want it to be Full screen and don't want to use the Padding workaround use

  showModalBottomSheet(
      context: context,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
      ),
      enableDrag: true,
      isDismissible: true,
      useRootNavigator: true,
      builder: (BuildContext ctx) {
        return Scaffold( // use CupertinoPageScaffold for iOS
          backgroundColor: Colors.transparent,
          resizeToAvoidBottomInset: true, // important
          body: SingleChildScrollView(
            child: Form(
              child: Container(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.stretch,
                  children: <Widget>[
                    TextFormField(),
                    TextFormField(),
                  ],
                ),
              ),
            ),
          ),
        );
      },
    );
```

on Flutter (Channel master, v1.15.3-pre.37, on Mac OS X 10.15.2 19C57, locale en-US)

Body:
I'm trying to make a bottomsheet that has a text field and autofocus is set to true so that the keyboard pops up. But, bottomsheet is overlapped by the keyboard. Is there a way to move bottomsheet above the keyboard?

Padding(
  padding:
      EdgeInsets.only(bottom: MediaQuery.of(context).viewInsets.bottom),
  child: Column(children: <Widget>[
    TextField(
      autofocus: true,
      decoration: InputDecoration(hintText: 'Title'),
    ),
    TextField(
      decoration: InputDecoration(hintText: 'Details!'),
      keyboardType: TextInputType.multiline,
      maxLines: 4,
    ),
    TextField(
      decoration: InputDecoration(hintText: 'Additional details!'),
      keyboardType: TextInputType.multiline,
      maxLines: 4,
    ),]);

Body:
After combining different solutions I got this:

if you don't want it to be Full screen and don't want to use the Padding workaround use

  showModalBottomSheet(
      context: context,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
      ),
      enableDrag: true,
      isDismissible: true,
      useRootNavigator: true,
      builder: (BuildContext ctx) {
        return Scaffold( // use CupertinoPageScaffold for iOS
          backgroundColor: Colors.transparent,
          resizeToAvoidBottomInset: true, // important
          body: SingleChildScrollView(
            child: Form(
              child: Container(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.stretch,
                  children: <Widget>[
                    TextFormField(),
                    TextFormField(),
                  ],
                ),
              ),
            ),
          ),
        );
      },
    );

on Flutter (Channel master, v1.15.3-pre.37, on Mac OS X 10.15.2 19C57, locale en-US)


问:
SQL Find MAX Values for multiple rows
Data Set

Name    Number  Value
Alabama  254    100
Atlas    156    200
Alabama  354    300
Atlas    800    400
```

<p>SQL Statement as to return the Max Number per Name. </p>

<p>desired outcome </p>

<pre class="lang-none prettyprint-override"><code>Alabama  354    300
Atlas    800    400
</code>```

答:
You can use distinct on in PostgreSQL:

```<code>select distinct on (name) *
from table t
order by name, number desc;
</code>```

You can use row_number() to general :

```<code>select t.*
from (select t.*, row_number() over (partition by name order by number desc) as seq
      from table t
     ) t
where seq = 1;
</code>```

If number has ties then you can use rank() instead.

Title: SQL Find MAX Values for multiple rows

Body:
Data Set

Name    Number  Value
Alabama  254    100
Atlas    156    200
Alabama  354    300
Atlas    800    400

SQL Statement as to return the Max Number per Name.

desired outcome

Alabama  354    300
Atlas    800    400

Body:
You can use distinct on in PostgreSQL:

select distinct on (name) *
from table t
order by name, number desc;

You can use row_number() to general :

select t.*
from (select t.*, row_number() over (partition by name order by number desc) as seq
      from table t
     ) t
where seq = 1;

If number has ties then you can use rank() instead.


问:
Camel: How to stream a from SQL component using StreamList
I am trying to use Camels SQL component to stream from a database using outputType=StreamList.
I get the ResultIterator from a Java class with ConsumerTemplate :

```<code>public Flux<String> CreateFlux () {
ConsumerTemplate consumer = camelContext.createConsumerTemplate();

    ResultSetIterator resultSetIterator = consumer.receiveBody(
            "sql:SELECT DATA FROM TRANSAKSJON WHERE REQ_ID='" + recId + "'?outputType=StreamList", ResultSetIterator.class);
    ...
    while (result.hasNext()) {
        Map<String, String> map = (Map<String, String>) result.next();
        String data = map.get("DATA");

    }
}
</code>```

I get the following error when trying to iterate the ResultsetIterator:

org.h2.jdbc.JdbcSQLException: The object is already closed [90007-197]

Upon inspection I see that the connection is closed.
connection = {HikariProxyConnection@16287} "HikariProxyConnection@1048081993 wrapping
com.zaxxer.hikari.pool.ProxyConnection.ClosedConnection"

How can I use the camel SQL component to stream? I have to use it from a bean that is not inside a camel route. I see that the streaming works only if I am using the SQL component inside a camel route.

Camel version is: 2.24.1

Update1: After looking at the source code it is intended. onDone closes the conncetion. I am trying to set UnitOfWork on my defaultExchange to keep the connection open by marking the exchange as not done.

Update2: managed to get it to work by setting UnitOf Work:

```<code>        ProducerTemplate pTmp = camelContext.createProducerTemplate();

        DefaultExchange defaultExchange = new DefaultExchange(camelContext);
        UnitOfWork unitOfWork = new DefaultUnitOfWork(defaultExchange);
        defaultExchange.setUnitOfWork(unitOfWork);
        pTmp.send("direct:DbStream", defaultExchange);

</code>```

The route DbStream executes the SQL select described above

答: Do not use receiveBody, but just receive to get the Exchange back. Then you can get the iterator from its message body, and the after use, you can done the exchange (see the javadoc)

Body:
I am trying to use Camels SQL component to stream from a database using outputType=StreamList.
I get the ResultIterator from a Java class with ConsumerTemplate :

public Flux<String> CreateFlux () {
ConsumerTemplate consumer = camelContext.createConsumerTemplate();

    ResultSetIterator resultSetIterator = consumer.receiveBody(
            "sql:SELECT DATA FROM TRANSAKSJON WHERE REQ_ID='" + recId + "'?outputType=StreamList", ResultSetIterator.class);
    ...
    while (result.hasNext()) {
        Map<String, String> map = (Map<String, String>) result.next();
        String data = map.get("DATA");

    }
}

I get the following error when trying to iterate the ResultsetIterator:

org.h2.jdbc.JdbcSQLException: The object is already closed [90007-197]

Upon inspection I see that the connection is closed.
connection = {HikariProxyConnection@16287} "HikariProxyConnection@1048081993 wrapping
com.zaxxer.hikari.pool.ProxyConnection.ClosedConnection"

How can I use the camel SQL component to stream? I have to use it from a bean that is not inside a camel route. I see that the streaming works only if I am using the SQL component inside a camel route.

Camel version is: 2.24.1

Update1: After looking at the source code it is intended. onDone closes the conncetion. I am trying to set UnitOfWork on my defaultExchange to keep the connection open by marking the exchange as not done.

Update2: managed to get it to work by setting UnitOf Work:

        ProducerTemplate pTmp = camelContext.createProducerTemplate();

        DefaultExchange defaultExchange = new DefaultExchange(camelContext);
        UnitOfWork unitOfWork = new DefaultUnitOfWork(defaultExchange);
        defaultExchange.setUnitOfWork(unitOfWork);
        pTmp.send("direct:DbStream", defaultExchange);

The route DbStream executes the SQL select described above


问:
shared session-state over subdomain
I read thousand of doc but nothing work for me.

1) What I want : on my server-side I used the following variable :

```<code>(string)Session["myData"]
</code>```

2) When I changed the subdomain

```<code>www.myDomain.com/myPage.aspx
OR
myDomain.com/myPage.aspx
OR
myUser.myDomain.com/myPage.aspx
</code>```

My problem : I loose the Session data when I go from one of those domain to another.

3) I want to keep the session-state only with cookie and inproc mode :

```<code>  <sessionState mode="InProc" cookieless="UseCookies"  cookieName="myDomain.com" timeout="10000">     </sessionState>
  <authentication mode="Windows"/>
</code>```

I added in the web.config :

```<code><httpCookies domain="myDomain.com"  />
</code>```

or

```<code> <httpCookies domain=".myDomain.com"  />
</code>```

or

```<code> <httpCookies domain=".myDomain.com" httpOnlyCookies="true" />
</code>```

But nothing worked.

Thanks for any advices.

答:
Short answer, you can't fulfill all of your criteria.

Possible solutions:

Redirect any request with an incoming domain of "xxx.myDomain.com" to a common "www.myDomain.com". This may involve changing "myUser.myDomain.com" to "www.myDomain.com/default.aspx?&user=myUser". Because it's a redirect, your user will see the address in his bar change, and will therefore gain some knowledge of the sausage-making behind your website (useful to attackers).

NEVER refer to your domain explicitly from within your own site. All URIs should be relative to the root of your web structure. This should allow you to avoid changing domains and thus losing your session state.

Use SQLServer to manage session state: http://support.microsoft.com/kb/2527105. This will require changing your session handling from InProc with cookies to SQLServer, as well as some other config changes.

Title: shared session-state over subdomain

Body:
I read thousand of doc but nothing work for me.

1) What I want : on my server-side I used the following variable :

(string)Session["myData"]

2) When I changed the subdomain

www.myDomain.com/myPage.aspx
OR
myDomain.com/myPage.aspx
OR
myUser.myDomain.com/myPage.aspx

My problem : I loose the Session data when I go from one of those domain to another.

3) I want to keep the session-state only with cookie and inproc mode :

  <sessionState mode="InProc" cookieless="UseCookies"  cookieName="myDomain.com" timeout="10000">     </sessionState>
  <authentication mode="Windows"/>

I added in the web.config :

<httpCookies domain="myDomain.com"  />

or

 <httpCookies domain=".myDomain.com"  />

or

 <httpCookies domain=".myDomain.com" httpOnlyCookies="true" />

But nothing worked.

Thanks for any advices.


问:
Set default branch using REST API
Is it somehow possible to set the default branch of a Git repository using Visual Studio Team Service REST API? There is an API for repositories and an UI for setting the default branch, but I couldn't find a possibility to set the default branch through the REST API.</p>

答:
The API can be found here: Update repository

Call:

```<code>PATCH https://dev.azure.com/{organization}/{project}/_apis/git/repositories/{repositoryId}?api-version=5.1
</code>```

With payload:

```<code>{
    "defaultBranch": "refs/heads/{branchName}"
}
</code>```

Title: Set default branch using REST API

Body:
The API can be found here: Update repository

Call:

PATCH https://dev.azure.com/{organization}/{project}/_apis/git/repositories/{repositoryId}?api-version=5.1

With payload:

{
    "defaultBranch": "refs/heads/{branchName}"
}


问:
logback not generating new log file
I am using below logback.xml in my Micronaut project, it is not generating new log file as per rollingPolicy provided in xml configuration. I tried with SizeAndTimeBasedRollingPolicy and TimeBasedRollingPolicy but it did't worked.

Micronaut version: 1.2.2

logback-classic : 1.2.3

File: logback.xml

```<code><configuration>

    <appender name="FILE" class="ch.qos.logback.core.FileAppender">
        <file>logs/my-app.log</file>
        <encoder>
            <pattern>%cyan(%d{yyyy-MM-dd HH:mm:ss.SSS}) %gray([%thread]) %highlight(%-5level) %magenta(%logger{36}):%line- %msg%n</pattern>
        </encoder>

        <rollingPolicy class="ch.qos.logback.core.rolling.RollingFileAppender">
            <fileNamePattern>
                logs/my-app.log-%d{yyyy-MM-dd}-%i.log.gz
            </fileNamePattern>
            <maxHistory>30</maxHistory>
            <totalSizeCap>1MB</totalSizeCap>
        </rollingPolicy>

    </appender>

    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>%cyan(%d{yyyy-MM-dd HH:mm:ss.SSS}) %gray([%thread]) %highlight(%-5level) %magenta(%logger{36}):%line- %msg%n</pattern>
        </encoder>
    </appender>

    <root level="ALL">
        <appender-ref ref="FILE" />
        <appender-ref ref="STDOUT" />
    </root>

</configuration>
</code>```

答:
Based on my own experience with logback, you should do something like:

```<code><appender name="FILE"  class="ch.qos.logback.core.rolling.RollingFileAppender">
...
    <rollingPolicy class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy">
        <fileNamePattern>logs/my-app.log-%d{yyyy-MM-dd}-%i.log.gz</fileNamePattern>
    </rollingPolicy>
    <triggeringPolicy
            class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
        <MaxFileSize>1MB</MaxFileSize>
    </triggeringPolicy>
...
</appender>
</code>```

Currently, you are using "RollingFileAppender" for policy, so it can't work.

Title: logback not generating new log file

Body:
I am using below logback.xml in my Micronaut project, it is not generating new log file as per rollingPolicy provided in xml configuration. I tried with SizeAndTimeBasedRollingPolicy and TimeBasedRollingPolicy but it did't worked.

Micronaut version: 1.2.2

logback-classic : 1.2.3

File: logback.xml

<configuration>

    <appender name="FILE" class="ch.qos.logback.core.FileAppender">
        <file>logs/my-app.log</file>
        <encoder>
            <pattern>%cyan(%d{yyyy-MM-dd HH:mm:ss.SSS}) %gray([%thread]) %highlight(%-5level) %magenta(%logger{36}):%line- %msg%n</pattern>
        </encoder>

        <rollingPolicy class="ch.qos.logback.core.rolling.RollingFileAppender">
            <fileNamePattern>
                logs/my-app.log-%d{yyyy-MM-dd}-%i.log.gz
            </fileNamePattern>
            <maxHistory>30</maxHistory>
            <totalSizeCap>1MB</totalSizeCap>
        </rollingPolicy>

    </appender>

    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>%cyan(%d{yyyy-MM-dd HH:mm:ss.SSS}) %gray([%thread]) %highlight(%-5level) %magenta(%logger{36}):%line- %msg%n</pattern>
        </encoder>
    </appender>

    <root level="ALL">
        <appender-ref ref="FILE" />
        <appender-ref ref="STDOUT" />
    </root>

</configuration>

Body:
Based on my own experience with logback, you should do something like:

<appender name="FILE"  class="ch.qos.logback.core.rolling.RollingFileAppender">
...
    <rollingPolicy class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy">
        <fileNamePattern>logs/my-app.log-%d{yyyy-MM-dd}-%i.log.gz</fileNamePattern>
    </rollingPolicy>
    <triggeringPolicy
            class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
        <MaxFileSize>1MB</MaxFileSize>
    </triggeringPolicy>
...
</appender>

Currently, you are using "RollingFileAppender" for policy, so it can't work.


问:
3D plot of x1 and x2 versus z, where z is defined as z = x1^2 + 0.1*x1 in R
Heres my code:

```<code>x1 = seq(from=0,to=1,length.out=10)
x2 = seq(from=0,to=1,length.out=10)
x1x2 = expand.grid(x1,x2)

z = (x1)^2+0.1*(x1)

z = length(length(x1x2))
x1x2z = data.frame(x1x2,z)
x1x2z

colnames(xyz) = c("x1=","x2","z")
head(x1x2z,3)
plot_ly(x1x2z,x1=~x,x2=~x2,z=~z,color="red")
</code>```

I am getting the error:

```<code>No trace type specified:
  Based on info supplied, a 'scatter3d' trace seems appropriate.
  Read more about this trace type -> https://plot.ly/r/reference/#scatter3d
Error: Tibble columns must have consistent lengths, only values of length one are recycled:
* Length 10: Column `x`
* Length 100: Columns `y`, `z`
</code>```

答:
The easiest way to do this is with the rgl package:

```<code>library(rgl)
plot3d(function(x1,x2) (x1)^2+0.1*(x1), xlim=0:1, ylim=0:1, col = "red", zlab = "z")
</code>```

This produces this plot:

Body:
Heres my code:

x1 = seq(from=0,to=1,length.out=10)
x2 = seq(from=0,to=1,length.out=10)
x1x2 = expand.grid(x1,x2)

z = (x1)^2+0.1*(x1)

z = length(length(x1x2))
x1x2z = data.frame(x1x2,z)
x1x2z

colnames(xyz) = c("x1=","x2","z")
head(x1x2z,3)
plot_ly(x1x2z,x1=~x,x2=~x2,z=~z,color="red")

I am getting the error:

No trace type specified:
  Based on info supplied, a 'scatter3d' trace seems appropriate.
  Read more about this trace type -> https://plot.ly/r/reference/#scatter3d
Error: Tibble columns must have consistent lengths, only values of length one are recycled:
* Length 10: Column `x`
* Length 100: Columns `y`, `z`

Body:
The easiest way to do this is with the rgl package:

library(rgl)
plot3d(function(x1,x2) (x1)^2+0.1*(x1), xlim=0:1, ylim=0:1, col = "red", zlab = "z")

This produces this plot:


问:
Bash, need to change word order in multiple directories
I have a considerable classical FLAC collection where each album is a directory. I've realized that I have used a sub-optimal structure and need to rename all the directories.

My current naming convention is:

COMPOSER (CONDUCTOR) - NAME OF PIECE

E.g.

"Bach (Celibidache) - Mass in F minor"

I want to change the naming to

COMPOSER - NAME OF PIECE (CONDUCTOR)

I.e.

"Bach - Mass in F minor (Celibidache)"

There are some possible exceptions, the (CONDUCTOR) may be (CONDUCTOR, SOLOIST)  and some directories do not have the (CONDUCTOR) part and should be left as is. The NAME OF PIECE can contain all legal letters and symbols.

All albums are located in the same parent directory, so no sub-directories.

What is the easy way to do this?

答:
use perl rename (some distributions have this as rename - Ubuntu and related, some as prename - Fedora and Redhat AFAIK). Check first.

```<code>prename -n -- '-d && s/(\(.*\)) - (.*)/- \2 \1/' *
</code>```

-n don't rename just print the results - remove after you are ok with the results.

-- end of the options, start of the perlexpr and files

-d check that the file is a directory

s/.../.../ - substitution

Example:

[test01@localhost composers]$ ls -la
total 12
drwxrwxr-x  3 test01 test01 4096 Feb 14 12:37  .
drwxrwxr-x. 7 test01 test01 4096 Feb 14 12:23  ..
drwxrwxr-x  2 test01 test01 4096 Feb 14 12:37 'Bach (Celibidache) - Mass in F minor'
-rw-rw-r--  1 test01 test01    0 Feb 14 12:27 'Bach (Celibidache) - Mass in F minor.flac'
[test01@localhost composers]$ prename -n -- '-d && s/(\(.*\)) - (.*)/- \2 \1/' *
Bach (Celibidache) - Mass in F minor -> Bach - Mass in F minor (Celibidache)
[test01@localhost composers]$ prename -- '-d && s/(\(.*\)) - (.*)/- \2 \1/' *
[test01@localhost composers]$ ls -la
total 12
drwxrwxr-x  3 test01 test01 4096 Feb 14 12:38  .
drwxrwxr-x. 7 test01 test01 4096 Feb 14 12:23  ..
-rw-rw-r--  1 test01 test01    0 Feb 14 12:27 'Bach (Celibidache) - Mass in F minor.flac'
drwxrwxr-x  2 test01 test01 4096 Feb 14 12:37 'Bach - Mass in F minor (Celibidache)'
```

Note that without -d both the file and the directory would have been renamed.

Body:
use perl rename (some distributions have this as rename - Ubuntu and related, some as prename - Fedora and Redhat AFAIK). Check first.

prename -n -- '-d && s/(\(.*\)) - (.*)/- \2 \1/' *

-n don't rename just print the results - remove after you are ok with the results.

-- end of the options, start of the perlexpr and files

-d check that the file is a directory

s/.../.../ - substitution

Example:

[test01@localhost composers]$ ls -la
total 12
drwxrwxr-x  3 test01 test01 4096 Feb 14 12:37  .
drwxrwxr-x. 7 test01 test01 4096 Feb 14 12:23  ..
drwxrwxr-x  2 test01 test01 4096 Feb 14 12:37 'Bach (Celibidache) - Mass in F minor'
-rw-rw-r--  1 test01 test01    0 Feb 14 12:27 'Bach (Celibidache) - Mass in F minor.flac'
[test01@localhost composers]$ prename -n -- '-d && s/(\(.*\)) - (.*)/- \2 \1/' *
Bach (Celibidache) - Mass in F minor -> Bach - Mass in F minor (Celibidache)
[test01@localhost composers]$ prename -- '-d && s/(\(.*\)) - (.*)/- \2 \1/' *
[test01@localhost composers]$ ls -la
total 12
drwxrwxr-x  3 test01 test01 4096 Feb 14 12:38  .
drwxrwxr-x. 7 test01 test01 4096 Feb 14 12:23  ..
-rw-rw-r--  1 test01 test01    0 Feb 14 12:27 'Bach (Celibidache) - Mass in F minor.flac'
drwxrwxr-x  2 test01 test01 4096 Feb 14 12:37 'Bach - Mass in F minor (Celibidache)'

Note that without -d both the file and the directory would have been renamed.


问:
How yo output file using bash coloring?
I would like to print a MOTD using styled text when an user connects to the server (ubuntu 18.04) using SSH.

The only way I found is to print the file by myself because Ubuntu originally only cats the motd file.

So now, I have a colord motd file but I don't found any way to print out the contents with the style.

I found this command on stackoverflow:

```<code>cat /home/user/conf/bash/motd | sed  's/$/\\n/' | sed 's/ /\\a /g'
</code>```

But this is not working propertly with large ASCII text.

here is the current test motd file

```<code> ____      ____  ________  _____       ______    ___   ____    ____  ________
|_  _|    |_  _||_   __  ||_   _|    .' ___  | .'   `.|_   \  /   _||_   __  |
  \ \  /\  / /    | |_ \_|  | |     / .'   \_|/  .-.  \ |   \/   |    | |_ \_|
   \ \/  \/ /     |  _| _   | |   _ | |       | |   | | | |\  /| |    |  _| _
    \  /\  /     _| |__/ | _| |__/ |\ `.___.'\\  `-'  /_| |_\/_| |_  _| |__/ |
     \/  \/     |________||________| `.____ .' `.___.'|_____||_____||________|

Welcome to my Server !

Aliases:
\e[4ml\e[0m => ls -lA
\e[1;93mll\e[0m => ls -l
</code>```

Have you any solution to do it please ?

答:
I would use variable in my file but It's seems that parsing variable implies parsing other things so it's not compatible with the banner that is ASCII only.
So I exported the banner to another file and now, I am able to print color and the banner.

Here is the SH sample

```<code>RED="\e[31m"
BANNER=$(<banner.txt)
printf "$(eval "echo \"$(<myfile.txt)\"")"
</code>```

banner.txt

```<code> ____      ____  ________  _____       ______    ___   ____    ____  ________
|_  _|    |_  _||_   __  ||_   _|    .' ___  | .'   `.|_   \  /   _||_   __  |
  \ \  /\  / /    | |_ \_|  | |     / .'   \_|/  .-.  \ |   \/   |    | |_ \_|
   \ \/  \/ /     |  _| _   | |   _ | |       | |   | | | |\  /| |    |  _| _
    \  /\  /     _| |__/ | _| |__/ |\ `.___.'\\  `-'  /_| |_\/_| |_  _| |__/ |
     \/  \/     |________||________| `.____ .' `.___.'|_____||_____||________|
</code>```

myfile.txt

```<code>$BANNER

Welcome to my Server !

TEXT FIRST
${RED}TEXT IS RED
\e[34mTEXT IS BLUE\e[0m
TEXT THIRD
</code>```

I am now looking for a prettier solution.

Title: How yo output file using bash coloring?

Body:
I would like to print a MOTD using styled text when an user connects to the server (ubuntu 18.04) using SSH.

The only way I found is to print the file by myself because Ubuntu originally only cats the motd file.

So now, I have a colord motd file but I don't found any way to print out the contents with the style.

I found this command on stackoverflow:

cat /home/user/conf/bash/motd | sed  's/$/\\n/' | sed 's/ /\\a /g'

But this is not working propertly with large ASCII text.

here is the current test motd file

 ____      ____  ________  _____       ______    ___   ____    ____  ________
|_  _|    |_  _||_   __  ||_   _|    .' ___  | .'   `.|_   \  /   _||_   __  |
  \ \  /\  / /    | |_ \_|  | |     / .'   \_|/  .-.  \ |   \/   |    | |_ \_|
   \ \/  \/ /     |  _| _   | |   _ | |       | |   | | | |\  /| |    |  _| _
    \  /\  /     _| |__/ | _| |__/ |\ `.___.'\\  `-'  /_| |_\/_| |_  _| |__/ |
     \/  \/     |________||________| `.____ .' `.___.'|_____||_____||________|

Welcome to my Server !

Aliases:
\e[4ml\e[0m => ls -lA
\e[1;93mll\e[0m => ls -l

Have you any solution to do it please ?

Body:
I would use variable in my file but It's seems that parsing variable implies parsing other things so it's not compatible with the banner that is ASCII only.
So I exported the banner to another file and now, I am able to print color and the banner.

Here is the SH sample

RED="\e[31m"
BANNER=$(<banner.txt)
printf "$(eval "echo \"$(<myfile.txt)\"")"

banner.txt

 ____      ____  ________  _____       ______    ___   ____    ____  ________
|_  _|    |_  _||_   __  ||_   _|    .' ___  | .'   `.|_   \  /   _||_   __  |
  \ \  /\  / /    | |_ \_|  | |     / .'   \_|/  .-.  \ |   \/   |    | |_ \_|
   \ \/  \/ /     |  _| _   | |   _ | |       | |   | | | |\  /| |    |  _| _
    \  /\  /     _| |__/ | _| |__/ |\ `.___.'\\  `-'  /_| |_\/_| |_  _| |__/ |
     \/  \/     |________||________| `.____ .' `.___.'|_____||_____||________|

myfile.txt

$BANNER

Welcome to my Server !

TEXT FIRST
${RED}TEXT IS RED
\e[34mTEXT IS BLUE\e[0m
TEXT THIRD

I am now looking for a prettier solution.


问:
How to get multiple elements by class name that are changing?
Can anyone help me?
I am trying to select multiple elements by class name.
Everything is good until somewhere in the middle of page comments text is not available, just reviewers name and product that has been reviewed.
How to set it to skip the element and move to the next row if it is not present for that particular row?

edited:
  So after suggestions, I tried using the below code but Console is saying

-forEach is not a function. I am running this on the following page:
https://www.etsy.com/shop/FamilyshirtsCo/reviews

```<code>var productRows = document.getElementsByClassName("div.flag-body pb-xs-0");
productRows.forEach(function(productRow){
var name = productRow.querySelector(".p.shop2-review-attribution");
var comments = productRow.querySelector(".p.prose break-word m-xs-0");
var product = productRow.querySelector(".flag-body hide-xs hide-sm");
var final = product[i].innerText +" | "+ price[i].innerText +" | "+
quantity[i].innerText;
console.log(final);
});
</code>```

答:
getElementsByClassName returns all the element having the specified class, irrespective of its siblings or parent.
Here you can give the some class to the row's parent class:

So as the html structure will be as follows :

```<code><div class="product-row">
    <div class="product">
        some product
    </div>
    <div class="price">
        some price
    </div>
    <div class="quantity">
        some quantity
    </div>
</div>
</code>```

Javascript :

```<code>var productRows = document.getElementsByClassName("product-row");
productRows.forEach(function(productRow){
    var product = productRow.querySelector(".product");
    var price = productRow.querySelector(".price");
    var quantity = productRow.querySelector(".quantity");
    var order = product[i].innerText +" | "+ price[i].innerText +" | "+ quantity[i].innerText;
    console.log(order);
});
</code>```

I hope this will resolve your issue

Body:
Can anyone help me?
I am trying to select multiple elements by class name.
Everything is good until somewhere in the middle of page comments text is not available, just reviewers name and product that has been reviewed.
How to set it to skip the element and move to the next row if it is not present for that particular row?

edited:
  So after suggestions, I tried using the below code but Console is saying

-forEach is not a function. I am running this on the following page:
https://www.etsy.com/shop/FamilyshirtsCo/reviews

var productRows = document.getElementsByClassName("div.flag-body pb-xs-0");
productRows.forEach(function(productRow){
var name = productRow.querySelector(".p.shop2-review-attribution");
var comments = productRow.querySelector(".p.prose break-word m-xs-0");
var product = productRow.querySelector(".flag-body hide-xs hide-sm");
var final = product[i].innerText +" | "+ price[i].innerText +" | "+
quantity[i].innerText;
console.log(final);
});

Body:
getElementsByClassName returns all the element having the specified class, irrespective of its siblings or parent.
Here you can give the some class to the row's parent class:

So as the html structure will be as follows :

<div class="product-row">
    <div class="product">
        some product
    </div>
    <div class="price">
        some price
    </div>
    <div class="quantity">
        some quantity
    </div>
</div>

Javascript :

var productRows = document.getElementsByClassName("product-row");
productRows.forEach(function(productRow){
    var product = productRow.querySelector(".product");
    var price = productRow.querySelector(".price");
    var quantity = productRow.querySelector(".quantity");
    var order = product[i].innerText +" | "+ price[i].innerText +" | "+ quantity[i].innerText;
    console.log(order);
});

I hope this will resolve your issue


答:
In case of SQL Server and MySQL you can use MAX() function with group by. Try like:

```<code>SELECT Name,MAX(Number),MAX(Value)
FROM myTable
GROUP BY Name
</code>```

SQL Fiddle

Title: SQL Find MAX Values for multiple rows

Body:
In case of SQL Server and MySQL you can use MAX() function with group by. Try like:

SELECT Name,MAX(Number),MAX(Value)
FROM myTable
GROUP BY Name

SQL Fiddle


问:
Draw differents latitude and longitude using thymeleaf and google maps
I am getting multiples latitude and longitude and I am trying to draw in Google Maps, but I don't know exactly how to do it, I think my problem is in the HTML.

Here is my Java Code using Spring:

``

```<code>@RequestMapping("/mapausuarios") //controlador que controla lo que viene a la raíz
public String mapausers(Model model) throws ParseException {

        tablausuario tu = new tablausuario();
        ArrayList<usuario> user = tu.listausuarios();
        Collections.sort(user, (o1, o2) -> o2.getCreatedAt().compareTo(o1.getCreatedAt())); //tabla ordenada
        model.addAttribute("TodosLosUsuarios", user);

    return "mapausers";

}
</code>```

I can extract de latitudes and longitudes in a table using that:

```<code>                    <tbody  th:each="usuariosTotales: ${TodosLosUsuarios}" >
                        <tr>
                        <td th:text=" ${usuariosTotales.getLatitude()} " ></td>
                        <td th:text=" ${usuariosTotales.getLongitude()} " ></td>
                        </tr>
                    </tbody>
</code>```

But I don't know how can I loop and draw into my script:

```<code>

       <div id="map"></div>
       var geocoder;
       var map;

       <script>
           // Initialize and add the map
           function initMap() {
               // The location of Uluru
               var uluru = {lat: 40.416775, lng: -3.703790};
               // The map, centered at Uluru
               var map = new google.maps.Map(
                       document.getElementById('map'), {zoom: 4, center: uluru});
               // The marker, positioned at Uluru
               var marker = new google.maps.Marker({position: uluru, map: map});
           }
       </script>
       <script async defer
               src="https://maps.googleapis.com/maps/api/js?key=***********&callback=initMap">
       </script>

</code>```

Help please!

答:
```<code><script th:inline="javascript">
  var user = ${TodosLosUsuarios} ;

   function plotUser(user) {
       // The location of Uluru
       var uluru = {lat: user.latitude, lng: user.longitude};
       // The map, centered at Uluru
       var map = new google.maps.Map(
               document.getElementById('map'), {zoom: 4, center: uluru});
       // The marker, positioned at Uluru
       var marker = new google.maps.Marker({position: uluru, map: map});
   }

  function loadUsers()
   {
        var user = ${TodosLosUsuarios} ;
        for(var i=0;i<users.length;i++)
        {
            plotUser(users[i]);
        }
   }
</code>```

```<code><script async defer
   src="https://maps.googleapis.com/maps/api/js?key=***********&callback=loadUsers">
</code>```

In order to plot users you need to store your users data on front end here is one of the solution. I hope it work for you

Body:
I am getting multiples latitude and longitude and I am trying to draw in Google Maps, but I don't know exactly how to do it, I think my problem is in the HTML.

Here is my Java Code using Spring:

``

@RequestMapping("/mapausuarios") //controlador que controla lo que viene a la raíz
public String mapausers(Model model) throws ParseException {

        tablausuario tu = new tablausuario();
        ArrayList<usuario> user = tu.listausuarios();
        Collections.sort(user, (o1, o2) -> o2.getCreatedAt().compareTo(o1.getCreatedAt())); //tabla ordenada
        model.addAttribute("TodosLosUsuarios", user);

    return "mapausers";

}

I can extract de latitudes and longitudes in a table using that:

But I don't know how can I loop and draw into my script:

       var geocoder;
       var map;

Help please!

Body:
<script th:inline="javascript">
  var user = ${TodosLosUsuarios} ;

   function plotUser(user) {
       // The location of Uluru
       var uluru = {lat: user.latitude, lng: user.longitude};
       // The map, centered at Uluru
       var map = new google.maps.Map(
               document.getElementById('map'), {zoom: 4, center: uluru});
       // The marker, positioned at Uluru
       var marker = new google.maps.Marker({position: uluru, map: map});
   }

  function loadUsers()
   {
        var user = ${TodosLosUsuarios} ;
        for(var i=0;i<users.length;i++)
        {
            plotUser(users[i]);
        }
   }

<script async defer
   src="https://maps.googleapis.com/maps/api/js?key=***********&callback=loadUsers">

In order to plot users you need to store your users data on front end here is one of the solution. I hope it work for you


问:
Call a method for List in parallel?
I must iterate over an list and call for every object a method, but in parallel. After the loop, there other statements, which must wait for the parallel method invocations. How can I do that in JAVA? </p>

```<code>public void a(List<Object> list) {
    for(Object o : list) {
        asynchMethod(o); // this n method call must run in the same time
    }

    // wait for all asynchMethod result
    /**
     * ...other statements
     */
}

private void asynchMethod(Object o) {
    // some code
}
</code>```

答:
I see that you are using java 8, you can then use the parallelStream approach:

```<code>public void a(List<Object> list) {
    list.parallelStream().forEach(s -> asyncMethod(o));
}
</code>```

which must wait for the parallel method invocations

The foreach is a terminal operation aka it will wait to be finished until moving forward to the next code line: Java parallel stream: how to wait for threads for a parallel stream to finish?

If you want some more information about parallelStream: https://docs.oracle.com/javase/tutorial/collections/streams/parallelism.html#executing_streams_in_parallel

If you want to know how many threads parallelstream uses: How many threads are spawned in parallelStream in Java 8?

Watch out with using threads and pararellStream, they come with their own heap of problems. Before using them you should always carefully examine the situation and see if they are worth the trouble they can possible bring: Should I always use a parallel stream when possible?

Title: Call a method for List in parallel?

Body:
I must iterate over an list and call for every object a method, but in parallel. After the loop, there other statements, which must wait for the parallel method invocations. How can I do that in JAVA?

public void a(List<Object> list) {
    for(Object o : list) {
        asynchMethod(o); // this n method call must run in the same time
    }

    // wait for all asynchMethod result
    /**
     * ...other statements
     */
}

private void asynchMethod(Object o) {
    // some code
}

Body:
I see that you are using java 8, you can then use the parallelStream approach:

public void a(List<Object> list) {
    list.parallelStream().forEach(s -> asyncMethod(o));
}

which must wait for the parallel method invocations

The foreach is a terminal operation aka it will wait to be finished until moving forward to the next code line: Java parallel stream: how to wait for threads for a parallel stream to finish?

If you want some more information about parallelStream: https://docs.oracle.com/javase/tutorial/collections/streams/parallelism.html#executing_streams_in_parallel

If you want to know how many threads parallelstream uses: How many threads are spawned in parallelStream in Java 8?

Watch out with using threads and pararellStream, they come with their own heap of problems. Before using them you should always carefully examine the situation and see if they are worth the trouble they can possible bring: Should I always use a parallel stream when possible?


问:
ViewHolder returns the old position in RecyclerView
I have a Fragment with BottomSheet behavior that contains a horizontal RecyclerView. RecyclerView is adjusted by SnapHelper to achieve a page effect. It looks something like this:

In the onCreateView event in the Fragment, I set Adapter and LayoutManager:

```<code>recycler_view.setAdapter(new MyRecyclerAdapter(getContext(), dataList));
recycler_view.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false));
</code>```

After I set Adapter, the onCreateViewHolder event is triggered in the MyRecyclerAdapter class object, followed by onBindViewHolder:

```<code>@Override
public MyRecyclerAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view = inflater.inflate(R.layout.fragment_recycler_item, parent, false);
    return new MyViewHolder(view, parent);
}

@Override
public void onBindViewHolder(MyRecyclerAdapter.MyViewHolder viewHolder, int position) {
    /**I do something using position**/
}
</code>```

When I create this Fragment and configure RecyclerView for the first time-everything works well, onBindViewHolder returns the correct position. But when I flip to the 1st, 2nd, etc. element RecyclerView, and then recreate the fragment, for some unknown reason onBindViewHolder return the old (last) position, although a new Adapter and LineraLayoutManager were created.

To make it clear, I'll break it down into steps:

Creating a Fragment.

Creating an object of the MyRecyclerAdapter class. Set it in RecyclerView.

Creating an object of the LinearLayoutManager class. Set it in RecyclerView.

The onBindViewHolder event in MyRecyclerAdapteris triggered. I get position = 0.

I scroll to the element with position = 2.

I do detach this fragment, and then immediately attach this fragment.

Creating an object of the MyRecyclerAdapter class. Set it in RecyclerView.

Creating an object of the LinearLayoutManager class. Set it in RecyclerView.

The onBindViewHolder event in MyRecyclerAdapteris triggered. I get position = 2.

Question: Why do I get the old position and most importantly how do I fix it?

I read that Android specifically saves the old ViewHolder to use memory more efficiently, but I don't need it.

UPD (Solution): It seems to me that this is a temporary solution (not ideal), but it works. You need to run smoothScrollToPosition(0) after you have installed Adapter and LayoutManager. It is very important to use smoothScrollToPosition(0), not scrollToPosition(0):

```<code>recycler_view.setAdapter(new MyRecyclerAdapter(getContext(), dataList));
recycler_view.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false));
recycler_view.smoothScrollToPosition(0);
</code>```

UPD.1 (Best Solution): Just use this:

```<code>recyclerView.setSaveEnabled(false);
</code>```

答:
Yes Android saved automatically saves the old ViewHolder to use memory more efficiently.

If you don't need.

Then setting the adapter again or do notifyDataSetChanged();

Body:
I have a Fragment with BottomSheet behavior that contains a horizontal RecyclerView. RecyclerView is adjusted by SnapHelper to achieve a page effect. It looks something like this:

In the onCreateView event in the Fragment, I set Adapter and LayoutManager:

recycler_view.setAdapter(new MyRecyclerAdapter(getContext(), dataList));
recycler_view.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false));

After I set Adapter, the onCreateViewHolder event is triggered in the MyRecyclerAdapter class object, followed by onBindViewHolder:

@Override
public MyRecyclerAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view = inflater.inflate(R.layout.fragment_recycler_item, parent, false);
    return new MyViewHolder(view, parent);
}

@Override
public void onBindViewHolder(MyRecyclerAdapter.MyViewHolder viewHolder, int position) {
    /**I do something using position**/
}

When I create this Fragment and configure RecyclerView for the first time-everything works well, onBindViewHolder returns the correct position. But when I flip to the 1st, 2nd, etc. element RecyclerView, and then recreate the fragment, for some unknown reason onBindViewHolder return the old (last) position, although a new Adapter and LineraLayoutManager were created.

To make it clear, I'll break it down into steps:

Creating a Fragment.

Creating an object of the MyRecyclerAdapter class. Set it in RecyclerView.

Creating an object of the LinearLayoutManager class. Set it in RecyclerView.

The onBindViewHolder event in MyRecyclerAdapteris triggered. I get position = 0.

I scroll to the element with position = 2.

I do detach this fragment, and then immediately attach this fragment.

Creating an object of the MyRecyclerAdapter class. Set it in RecyclerView.

Creating an object of the LinearLayoutManager class. Set it in RecyclerView.

The onBindViewHolder event in MyRecyclerAdapteris triggered. I get position = 2.

Question: Why do I get the old position and most importantly how do I fix it?

I read that Android specifically saves the old ViewHolder to use memory more efficiently, but I don't need it.

UPD (Solution): It seems to me that this is a temporary solution (not ideal), but it works. You need to run smoothScrollToPosition(0) after you have installed Adapter and LayoutManager. It is very important to use smoothScrollToPosition(0), not scrollToPosition(0):

recycler_view.setAdapter(new MyRecyclerAdapter(getContext(), dataList));
recycler_view.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false));
recycler_view.smoothScrollToPosition(0);

UPD.1 (Best Solution): Just use this:

recyclerView.setSaveEnabled(false);


问:
Link List Implementation. Hacker Rank Video
I am learning DS and came across a short video tutorial of Hacker Rank on Linked List.

It is pretty much self explanatory, but I am not able to understand one point where she said "If we pre-append then we will have little bit of issue". Here she basically tells that move append code outside in another class.
I am trying to understand and visualise what actually she meant and what could be the potential issue if we keep it in Node class itself. She mentioned but I am not able to grasp that concept.

Here is the link : https://www.youtube.com/watch?v=njTh_OwMljA&t=186s
Time: 3:01.

Could someone elaborate it bit more.

答:
The particular problem arises when you are trying to pre-append (append values at the start).

Multiples objects are created of the node class. Say your list is like this, 1->2->3->4->5 with each number being one node.

Now you want to do normal append (at the end), you call 3.append() . current points to 3, you iterate till the last node and append it. No issues over here.

Now when you try to pre-append it, you are ideally changing the head of each nodes present in the list.

Say you want to pre append 0. Your list should look like 0->1->2->3->4->5. 0 being the actual head of linked list.

If you call the same way 3.pre_append(), you would end up with something like

1->2->3 X 0->3->4->5, where you would be changing the head of the node from which you called the function and not the head of entire linked list which you meant to do.

So only that node will have its head changed and all other nodes won't know who head is or worse there might be multiple heads based on who calls pre_append.

In order to avoid this access to the head was limited and hence the pre_append method was shifted to another class where only one node can be referenced as the head.


问:
Implicit conversion not allowed on return
```<code>#include <optional>

bool f() {
  std::optional<int> opt;
  return opt;
}
</code>```

Does not compile: 'return': cannot convert from 'std::optional<int>' to 'bool'

Consulting reference I would have thought to find an explanation, but I read it as it should be ok.

Implicit conversions are performed whenever an expression of some type
  T1 is used in context that does not accept that type, but accepts some
  other type T2; in particular:

when the expression is used as the argument when calling a function that is declared with T2 as parameter;

when the expression is used as an operand with an operator that    expects T2;

when initializing a new object of type T2, including return statement    in a function returning T2;

when the expression is used in a switch statement (T2 is integral    type);

when the expression is used in an if statement or a loop (T2 is    bool).

答:
std::optional doesn't have any facility for implicitly converting to bool. (Allowing implicit conversions to bool is generally considered a bad idea, since bool is an integral type so something like int i = opt would compile and do completely the wrong thing.)

std::optional does have a "contextual conversion" to bool, the definition of  which looks similar to a cast operator: explicit operator bool(). This cannot be used for implicit conversions; it only applies in certain specific situations where the expected "context" is a boolean one, like the condition of an if-statement.

What you want is opt.has_value().

Body:
#include <optional>

bool f() {
  std::optional<int> opt;
  return opt;
}

Does not compile: 'return': cannot convert from 'std::optional<int>' to 'bool'

Consulting reference I would have thought to find an explanation, but I read it as it should be ok.

Implicit conversions are performed whenever an expression of some type
  T1 is used in context that does not accept that type, but accepts some
  other type T2; in particular:

when the expression is used as the argument when calling a function that is declared with T2 as parameter;

when the expression is used as an operand with an operator that    expects T2;

when initializing a new object of type T2, including return statement    in a function returning T2;

when the expression is used in a switch statement (T2 is integral    type);

when the expression is used in an if statement or a loop (T2 is    bool).


问:
Bash tool to get nth line from a file
Is there a "canonical" way of doing that? I've been using head -n | tail -1 which does the trick, but I've been wondering if there's a Bash tool that specifically extracts a line (or a range of lines) from a file.

By "canonical" I mean a program whose main function is doing that.

答:
You can also use Perl for this:</p>

```<code>perl -wnl -e '$.== NUM && print && exit;' some.file
</code>```

Title: Bash tool to get nth line from a file

Body:
You can also use Perl for this:

perl -wnl -e '$.== NUM && print && exit;' some.file


答:
From C++ docs:

When an object of type optional< T > is contextually converted to bool,
  the conversion returns true if the object contains a value and false
  if it does not contain a value.

Read about contextual conversions here:

In the following contexts, the type bool is expected and the implicit
  conversion is performed if the declaration bool t(e); is well-formed
  (that is, an explicit conversion function such as explicit T::operator
  bool() const; is considered). Such expression e is said to be
  contextually converted to bool.

the controlling expression of if, while, for;

the operands of the built-in logical operators !, && and ||;

the first operand of the conditional operator ?:;

the predicate in a static_assert declaration;

the expression in a noexcept specifier;

the expression in an explicit specifier;

You can do the following hack:

bool f() {
    std::optional<int> opt;
    return opt || false;
}
```

<p>because contextual conversion happens in case of the built-in logical operators, but contextual conversion does <strong>not</strong> include <code>return</code> statements and <code>std::optional</code> by itself does <strong>not</strong> have implicit conversion to <code>bool</code>. </p>

<p>Therefore, it would be the best to use the <code>std::optional<T>::has_value</code>:</p>

<pre class="lang-cpp prettyprint-override"><code>bool f() {
    std::optional<int> opt;
    return opt.has_value();
}
</code>```

Title: Implicit conversion not allowed on return

Body:
From C++ docs:

When an object of type optional< T > is contextually converted to bool,
  the conversion returns true if the object contains a value and false
  if it does not contain a value.

Read about contextual conversions here:

In the following contexts, the type bool is expected and the implicit
  conversion is performed if the declaration bool t(e); is well-formed
  (that is, an explicit conversion function such as explicit T::operator
  bool() const; is considered). Such expression e is said to be
  contextually converted to bool.

the controlling expression of if, while, for;

the operands of the built-in logical operators !, && and ||;

the first operand of the conditional operator ?:;

the predicate in a static_assert declaration;

the expression in a noexcept specifier;

the expression in an explicit specifier;

You can do the following hack:

bool f() {
    std::optional<int> opt;
    return opt || false;
}

because contextual conversion happens in case of the built-in logical operators, but contextual conversion does not include return statements and std::optional by itself does not have implicit conversion to bool.

Therefore, it would be the best to use the std::optional<T>::has_value:

bool f() {
    std::optional<int> opt;
    return opt.has_value();
}


问:
How to remove the back button in the header react native
I want to remove the button back, but leave the header.

My component is as follows. I want to leave the title, and I don’t need the back button.

```<code>import React from 'react';
import { View } from 'react-native';

export const TrucksScreen = () => {
    return (
        <View>
           ....
        </View>
    );
});

TrucksScreen.navigationOptions = {
    headerTitle: 'Trucks Screen',
};
</code>```

How can I remove the button back?

答:
Using headerLeft: null will be deprecated in future versions.

Instead use a function like so :

```<code>TrucksScreen.navigationOptions = {
    headerTitle: 'Trucks Screen',
    headerLeft: () => {
      return null;
    },
};
</code>```

Cheers !

Body:
I want to remove the button back, but leave the header.

My component is as follows. I want to leave the title, and I don’t need the back button.

import React from 'react';
import { View } from 'react-native';

export const TrucksScreen = () => {
    return (
        <View>
           ....
        </View>
    );
});

TrucksScreen.navigationOptions = {
    headerTitle: 'Trucks Screen',
};

How can I remove the button back?

Body:
Using headerLeft: null will be deprecated in future versions.

Instead use a function like so :

TrucksScreen.navigationOptions = {
    headerTitle: 'Trucks Screen',
    headerLeft: () => {
      return null;
    },
};

Cheers !


问:
Custom CSS Scrollbar for Firefox
I want to customize a scrollbar with CSS.

I use this WebKit CSS code, which works well for Safari and Chrome:

::-webkit-scrollbar {
  width: 15px;
  height: 15px;
}

::-webkit-scrollbar-track-piece {
  background-color: #c2d2e4;
}

::-webkit-scrollbar-thumb:vertical {
  height: 30px;
  background-color: #0a4c95;
}
```

How can I do the same thing in Firefox?

I know I can easily do it using jQuery, but I would prefer to do it with pure CSS if it's doable.

答:
Year 2020 this works

```<code>/* Thin Scrollbar */
:root{
  scrollbar-color: rgb(210,210,210) rgb(46,54,69) !important;
  scrollbar-width: thin !important;
}
</code>```

https://github.com/Aris-t2/CustomCSSforFx/issues/160

Title: Custom CSS Scrollbar for Firefox

Body:
I want to customize a scrollbar with CSS.

I use this WebKit CSS code, which works well for Safari and Chrome:

::-webkit-scrollbar {
  width: 15px;
  height: 15px;
}

::-webkit-scrollbar-track-piece {
  background-color: #c2d2e4;
}

::-webkit-scrollbar-thumb:vertical {
  height: 30px;
  background-color: #0a4c95;
}

How can I do the same thing in Firefox?

I know I can easily do it using jQuery, but I would prefer to do it with pure CSS if it's doable.

Body:
Year 2020 this works

/* Thin Scrollbar */
:root{
  scrollbar-color: rgb(210,210,210) rgb(46,54,69) !important;
  scrollbar-width: thin !important;
}

https://github.com/Aris-t2/CustomCSSforFx/issues/160


问:
Python "list order"
I have 2 troubles with my data, can anyone help me:

How can I get from this:

1.

```<code>k=[['1','7', 'U1'],
 ['1.5', '8', 'U1'],
 ['2', '5.5', 'U1']]
</code>```

get this

```<code>1,7,U1
1.5,8,U1
2,5.5,U1
</code>```

EDIT 2   I MAKE SOME CHANGE ON  second case:, still searching solution for this one:

2. And how to get, from this

```<code>l=array([[[ 4.24231542], 'U1'],
       [[ 3.41424819], 'U1'],
       [[ 2.17214734], 'U1'],], dtype=object)
</code>```

get

```<code>4.24231542,U1
3.41424819,U1
2.17214734,U1
</code>```

Thanks

答:
I'm going to venture a guess as to what you actually mean in terms of syntax

For the first one:

```<code>k=[['1','7', 'U1'],
 ['1.5', '8', 'U1'],
 ['2', '5.5', 'U1']]

for l in k:
    print ', '.join(l)
</code>```

For the second one:

```<code>for l in k:
    print l[0][0], l[1]
</code>```

Hope this helps

Title: Python "list order"

Body:
I have 2 troubles with my data, can anyone help me:

How can I get from this:

1.

k=[['1','7', 'U1'],
 ['1.5', '8', 'U1'],
 ['2', '5.5', 'U1']]

get this

1,7,U1
1.5,8,U1
2,5.5,U1

EDIT 2   I MAKE SOME CHANGE ON  second case:, still searching solution for this one:

2. And how to get, from this

l=array([[[ 4.24231542], 'U1'],
       [[ 3.41424819], 'U1'],
       [[ 2.17214734], 'U1'],], dtype=object)

get

4.24231542,U1
3.41424819,U1
2.17214734,U1

Thanks

Body:
I'm going to venture a guess as to what you actually mean in terms of syntax

For the first one:

k=[['1','7', 'U1'],
 ['1.5', '8', 'U1'],
 ['2', '5.5', 'U1']]

for l in k:
    print ', '.join(l)

For the second one:

for l in k:
    print l[0][0], l[1]

Hope this helps


问:
Limit access to method
I have made a custom-attribute that you can use to decorate your methods in your Controller.

I also have a method in my service-layer that only should be accessed from controller method that are decoraded with my attribute. Is this possible to do?

Example

```<code>[MyCustomAttribute]
[HttpGet]
public IEnumerable<WeatherForecast> Get()
{
    // Should be allowed to call the method below
    _service.GetWeatherInfo();
}

[HttpGet]
public IEnumerable<WeatherForecast> Get()
{
    // Should NOT be allowed to call the method below
    _service.GetWeatherInfo(); // This should not be accessible here
}
</code>```

答:
If you really wanted to do something like that you could try the below, though it's not very good because it only works with one controller at the moment. If you have no experience with ASP I would say to look at the Authorize attribute and then only call your service method from actions decorated with a certain policy.</p>

```<code>public void GetWeatherInfo([CallerMemberName] string methodName = null)
{
    var hasAttribute = typeof(WeatherController).GetMethod(methodName).GetCustomAttributes(typeof(MyCustomAttribute), true).Any();

    if(!hasAttribute)
         throw new Exception("Forbidden");
}
</code>```

Title: Limit access to method

Body:
I have made a custom-attribute that you can use to decorate your methods in your Controller.

I also have a method in my service-layer that only should be accessed from controller method that are decoraded with my attribute. Is this possible to do?

Example

[MyCustomAttribute]
[HttpGet]
public IEnumerable<WeatherForecast> Get()
{
    // Should be allowed to call the method below
    _service.GetWeatherInfo();
}

[HttpGet]
public IEnumerable<WeatherForecast> Get()
{
    // Should NOT be allowed to call the method below
    _service.GetWeatherInfo(); // This should not be accessible here
}

Body:
If you really wanted to do something like that you could try the below, though it's not very good because it only works with one controller at the moment. If you have no experience with ASP I would say to look at the Authorize attribute and then only call your service method from actions decorated with a certain policy.

public void GetWeatherInfo([CallerMemberName] string methodName = null)
{
    var hasAttribute = typeof(WeatherController).GetMethod(methodName).GetCustomAttributes(typeof(MyCustomAttribute), true).Any();

    if(!hasAttribute)
         throw new Exception("Forbidden");
}


答:
That's because implicit coversion of std::optional to bool is not supported: https://en.cppreference.com/w/cpp/utility/optional/operator_bool

constexpr explicit operator bool() const noexcept;

You have to explicitly convert to bool as bool(opt) or simply use opt.has_value() instead.