问:
I can't login to my Django app when debug is set to False
Short Story: I get locked out of my Django app when Debug is set to False.

Long story:

Case 1 (the first time it happened):

I enter my login info, but It just redirects to the login page.

I restart the server, try to login, and it works fine, I get in.

a few hours later I come back, log out, try to log back in and I can't. It just redirects to the login page.

Case 2 (I figure out how to provoke the login failure):

I restart the server and am able to login to the site.

I log in and log out several times, everything is fine.

I go to a non-existing page and get a server error.

I log out and try to log back in, and I can't, just get redirected back to the login page.

Case 3 (I can't provoke the login failure with Debug set to True):
1. I restart the server and am able to login to the site.
2. I log in and log out several times, everything is fine.
3. I go to a non-existing page and get a traceback.
4. I log out and log back in, everything works.
5. I wait and play around with it and can't get the login to fail while in Debug mode.

Please help!

答:
Make sure the urls.py file imports everything from django.conf.urls.defaults.

You may have explicitly imported certain methods such as patterns and include (as I did to combat PyDev's 'wild import' warning messages).
As a result, crucial statements that assign Django's default handlers to 404 and 500 HTTP error codes will be omitted.
This is obviously undesired and leads to the odd behavior described in the question.


来源: stackexchange

问:
How to exclude a month from my time-series data?
I have time series data "workdata". I am trying to exclude "7" month from my data. I have already tried:

```<code>workdata[as.integer(format(workdata$date, "%m")) != 7, ]
</code>```

It works, but when i use command:

```<code>view(workdata)
</code>```

The workdata shows all the months. It is not deleting the July month.

What is wrong with my script?

Best,

答:
have you tried assigning the result back to your frame?

workdata = workdata[as.integer(format(workdata$date, "%m")) != 7, ]
```

OwnerDisplayName: Hasan Sohail

ContentLicense: CC BY-SA 4.0

Body:
I have time series data "workdata". I am trying to exclude "7" month from my data. I have already tried:

workdata[as.integer(format(workdata$date, "%m")) != 7, ]

It works, but when i use command:

view(workdata)

The workdata shows all the months. It is not deleting the July month.

What is wrong with my script?

Best,

OwnerDisplayName: Emil Mirzayev


问:
Escaping a PHP function as an Array value
I'm working on a Drupal 8 starter kit with Composer, similar to drupal-composer/drupal-project.

In my post-install script, I want to re-generate a settings.php file with my custom values.
I've seen that can be done with the drupal_rewrite_settings function.

For example, I'm rewriting the config_sync_directory value like that :

require_once $drupalRoot . '/core/includes/bootstrap.inc';
require_once $drupalRoot . '/core/includes/install.inc';
new Settings([]);
$settings['settings']['config_sync_directory'] = (object) [
  'value' => '../config/sync',
  'required' => TRUE,
];
drupal_rewrite_settings($settings, $drupalRoot . '/sites/default/settings.php');
```

<p>Problem is I want my Drupal 8 project to have a Dotenv so the maintainers don't have to modify the <code>settings.php</code> but only a <code>.env</code> file in the root folder of the project. To make it work, my <code>settings.php</code> must look like this :</p>

<pre class="lang-php prettyprint-override"><code>$databases['default']['default'] = [
  'database' => getenv('MYSQL_DATABASE'),
  'driver' => 'mysql',
  'host' => getenv('MYSQL_HOSTNAME'),
  'namespace' => 'Drupal\\Core\\Database\\Driver\\mysql',
  'password' => getenv('MYSQL_PASSWORD'),
  'port' => '',
  'prefix' => '',
  'username' => getenv('MYSQL_USER'),
];
$settings['trusted_host_patterns'] = explode(',', '^'.getenv('SITE_URL').'$');
</code>```

As you can see, the values are replaced by PHP functions, and I can't see a good way to print those values, to the point I'm not even sure that's possible.

So my question is : is it possible to escape a PHP function as an Array value when declaring this variable ?

答:
Looks like it's not possible because of the way the Drupal function works.

Solution 1 by @misorude

Using the drupal_rewrite_settings function, we can add the value of settings as a String, like this :

$settings['settings']['trusted_host_patterns'] = (object) [
  'value' => "FUNC[explode(',', '^'.getenv('SITE_URL').'$')]",
  'required' => TRUE,
];
```

<p>And after that, we can replace all occurrences of <code>"FUNC[***]"</code> by <code>***</code> directly in the <code>settings.php</code> file.</p>

<hr>

<h2>Solution 2</h2>

<p>Put all your settings in a separate file. Example here, a <code>custom.settings.php</code> file :</p>

<pre class="lang-php prettyprint-override"><code>if (getenv('DEBUG') == 'true') {
  $settings['container_yamls'][] = DRUPAL_ROOT . '/sites/dev.services.yml';
  $config['system.performance']['css']['preprocess'] = FALSE;
  $config['system.performance']['js']['preprocess'] = FALSE;
}
$databases['default']['default'] = [
  'database' => getenv('MYSQL_DATABASE'),
  'driver' => 'mysql',
  'host' => getenv('MYSQL_HOSTNAME'),
  'namespace' => 'Drupal\\Core\\Database\\Driver\\mysql',
  'password' => getenv('MYSQL_PASSWORD'),
  'port' => '',
  'prefix' => '',
  'username' => getenv('MYSQL_USER'),
];
$settings['trusted_host_patterns'] = explode(',', '^'.getenv('SITE_URL').'$');
$settings['file_private_path'] = 'sites/default/files/private';
$settings['config_sync_directory'] = '../config/sync';
</code>```

Then we can copy the default.settings.php and add our custom settings.

$fs = new Filesystem();
$settings_generated = $drupalRoot . '/sites/default/settings.php';
$settings_default = $drupalRoot . '/sites/default/default.settings.php';
$settings_custom = $drupalRoot . '/../includes/custom.settings.php';
$fs->remove($settings_generated);
$fs->dumpFile($settings_generated, file_get_contents($settings_default) . file_get_contents($settings_custom));
```

There's also a appendToFile method that seems way better than dumping a new file with dumpFile, but it was not working unfortunatly.

Body:
I'm working on a Drupal 8 starter kit with Composer, similar to drupal-composer/drupal-project.

In my post-install script, I want to re-generate a settings.php file with my custom values.
I've seen that can be done with the drupal_rewrite_settings function.

For example, I'm rewriting the config_sync_directory value like that :

require_once $drupalRoot . '/core/includes/bootstrap.inc';
require_once $drupalRoot . '/core/includes/install.inc';
new Settings([]);
$settings['settings']['config_sync_directory'] = (object) [
  'value' => '../config/sync',
  'required' => TRUE,
];
drupal_rewrite_settings($settings, $drupalRoot . '/sites/default/settings.php');

Problem is I want my Drupal 8 project to have a Dotenv so the maintainers don't have to modify the settings.php but only a .env file in the root folder of the project. To make it work, my settings.php must look like this :

$databases['default']['default'] = [
  'database' => getenv('MYSQL_DATABASE'),
  'driver' => 'mysql',
  'host' => getenv('MYSQL_HOSTNAME'),
  'namespace' => 'Drupal\\Core\\Database\\Driver\\mysql',
  'password' => getenv('MYSQL_PASSWORD'),
  'port' => '',
  'prefix' => '',
  'username' => getenv('MYSQL_USER'),
];
$settings['trusted_host_patterns'] = explode(',', '^'.getenv('SITE_URL').'$');

As you can see, the values are replaced by PHP functions, and I can't see a good way to print those values, to the point I'm not even sure that's possible.

So my question is : is it possible to escape a PHP function as an Array value when declaring this variable ?

Body:
Looks like it's not possible because of the way the Drupal function works.

Solution 1 by @misorude

Using the drupal_rewrite_settings function, we can add the value of settings as a String, like this :

$settings['settings']['trusted_host_patterns'] = (object) [
  'value' => "FUNC[explode(',', '^'.getenv('SITE_URL').'$')]",
  'required' => TRUE,
];

And after that, we can replace all occurrences of "FUNC[***]" by *** directly in the settings.php file.

Solution 2

Put all your settings in a separate file. Example here, a custom.settings.php file :

if (getenv('DEBUG') == 'true') {
  $settings['container_yamls'][] = DRUPAL_ROOT . '/sites/dev.services.yml';
  $config['system.performance']['css']['preprocess'] = FALSE;
  $config['system.performance']['js']['preprocess'] = FALSE;
}
$databases['default']['default'] = [
  'database' => getenv('MYSQL_DATABASE'),
  'driver' => 'mysql',
  'host' => getenv('MYSQL_HOSTNAME'),
  'namespace' => 'Drupal\\Core\\Database\\Driver\\mysql',
  'password' => getenv('MYSQL_PASSWORD'),
  'port' => '',
  'prefix' => '',
  'username' => getenv('MYSQL_USER'),
];
$settings['trusted_host_patterns'] = explode(',', '^'.getenv('SITE_URL').'$');
$settings['file_private_path'] = 'sites/default/files/private';
$settings['config_sync_directory'] = '../config/sync';

Then we can copy the default.settings.php and add our custom settings.

$fs = new Filesystem();
$settings_generated = $drupalRoot . '/sites/default/settings.php';
$settings_default = $drupalRoot . '/sites/default/default.settings.php';
$settings_custom = $drupalRoot . '/../includes/custom.settings.php';
$fs->remove($settings_generated);
$fs->dumpFile($settings_generated, file_get_contents($settings_default) . file_get_contents($settings_custom));

There's also a appendToFile method that seems way better than dumping a new file with dumpFile, but it was not working unfortunatly.


问:
The SELECT permission was denied on the object 'executions', database 'SSISDB', schema 'internal'
I'm using SQL Server 2014 SP2.  I have a SSIS Package that executes 100% interactively via Visual Studio.

When I deploy to the SSIS Catalog and schedule via a SQL Agent Job I receive the below message.

The SQL Agent Account is being executed via a Proxy Account which in turn is a Role Member of the SSIS_Admin Role.

```<code>The SELECT permission was denied on the object 'executions', database 'SSISDB', schema 'internal'
</code>```

I'm assuming this is permissions? How do I resolve or where should I at least be looking?

答:
are you running the package with SQL Agent Service Account? If yes, service account should have permissions on SSISDB. you can check it here:

If you have created a proxy and run the package with it, that user in the proxy should have permissions in SSISDB. You can check if the proxy account exists here:

Body:
I'm using SQL Server 2014 SP2.  I have a SSIS Package that executes 100% interactively via Visual Studio.

When I deploy to the SSIS Catalog and schedule via a SQL Agent Job I receive the below message.

The SQL Agent Account is being executed via a Proxy Account which in turn is a Role Member of the SSIS_Admin Role.

The SELECT permission was denied on the object 'executions', database 'SSISDB', schema 'internal'

I'm assuming this is permissions? How do I resolve or where should I at least be looking?


问:
How to apply a function to a list of timestamp to create a pandas serie?
OK, the working part of the code:
I have a function that given a timestamp, and a period (minute, hour, month...) returns the period duration as a timedelta.
Basically, for minute, hour, day, it directly call pandas Timedelta function.
For month, it is a bit 'smarter' as it checks in which month the timestamp is, and return the number of days of identified month.

```<code>import pandas as pd

def as_timedelta(ref_ts: pd.Timestamp = None):
    """
    Return the duration of a time period.
    For a month, obtaining its duration requires a reference timestamp to identify
    how many days have to be accounted for in the month.
    """

    # An input timestamp has to be given.
    # It is assumed given timestamp is at beginning of time period for which a time delta is requested.
    # Because of a possible timezone, the timestamp is max 12 hours before or after
    # beginning of month in UTC.
    # To assume the current month, we check what is the closest month beginning
    # As an example, if 31st of January, 6:00 PM is reference timestamp, duration is given for month of February

    # Get month starts
    current_month = pd.Timestamp(year=ref_ts.year, month=ref_ts.month, day=1)
    next_month = current_month + pd.DateOffset(months=1)
    nex_next_month = current_month + pd.DateOffset(months=2)
    # Get month of interest
    dist_to_next = next_month - ref_ts
    dist_to_prev = ref_ts - current_month
    # Return timedelta corresponding as the duration between current month and begining of next month
    td_13 = pd.Timedelta(13, 'h')
    if dist_to_next < td_13:
        return nex_next_month - next_month
    elif dist_to_prev < td_13:
        return next_month - current_month
</code>```

Given a list of timestamps, I would like to apply this function to each timestamps. But trying with following line of code, but I get an AttributeError.
To illustrate the trouble now, I am taking an example:

```<code>ts_list_1M = [
          "Thu Feb 01 2019 00:00:00 GMT+0100",
          "Thu Mar 01 2019 00:00:00 GMT+0100",
          "Sun Apr 01 2019 00:00:00 GMT+0200"]
op_list_1M = [7134.0, 7134.34, 7135.03]
GC_1M = pd.DataFrame(list(zip(ts_list_1M, op_list_1M)), columns =['date', 'open'])
GC_1M['date'] = pd.to_datetime(GC_1M['date'], utc=True)
GC_1M.rename(columns={'date': 'Timestamp'}, inplace=True)
GC_1M.set_index('Timestamp', inplace = True, verify_integrity = True)
</code>```

The famous line of code:

```<code>GC_1M.reset_index().apply(as_timedelta,axis=1).values
</code>```

And the error message I get:

```<code>File "<ipython-input-49-ff9556f2ec44>", line 18, in as_timedelta
current_month = pd.Timestamp(year=ref_ts.year, month=ref_ts.month, day=1)

File "C:\Users\pierre.juillard\Documents\Programs\Anaconda\lib\site-packages\pandas\core\generic.py", line 5179, in __getattr__
return object.__getattribute__(self, name)

AttributeError: ("'Series' object has no attribute 'year'", 'occurred at index 0')
</code>```

When I test the function on a single value, it works, but when applying it like this, it doesn't. Please, any advice on how to achieve that?

I thank you in advance for your help!
Bests,

答:
So when you want to apply your function to your 'dates' series only you could do the following:

```<code>GC_1M['date'].apply(as_timedelta)
</code>```

However, this does not seem to work, as in your example 'date' is not a datetime object, so you will need to convert it first (you could also do this upon creation):

```<code>GC_1M['date'] = pd.to_datetime(GC_1M['date'])
</code>```

And finally, your as_timedelta function cannot deal with timezone-aware inputs, I added a comment to the line that needs fixing:

```<code>def as_timedelta(ref_ts: pd.Timestamp = None):
    """
    Return the duration of a time period.
    For a month, obtaining its duration requires a reference timestamp to identify
    how many days have to be accounted for in the month.
    """

    # An input timestamp has to be given.
    # It is assumed given timestamp is at beginning of time period for which a time delta is requested.
    # Because of a possible timezone, the timestamp is max 12 hours before or after
    # beginning of month in UTC.
    # To assume the current month, we check what is the closest month beginning
    # As an example, if 31st of January, 6:00 PM is reference timestamp, duration is given for month of February

    # Get month starts
    current_month = pd.Timestamp(year=ref_ts.year, month=ref_ts.month, day=1, tzinfo=ref_ts.tzinfo)  # Make current_month timezone aware
    next_month = current_month + pd.DateOffset(months=1)
    nex_next_month = current_month + pd.DateOffset(months=2)
    # Get month of interest
    dist_to_next = next_month - ref_ts
    dist_to_prev = ref_ts - current_month
    # Return timedelta corresponding as the duration between current month and begining of next month
    td_13 = pd.Timedelta(13, 'h')
    if dist_to_next < td_13:
        return nex_next_month - next_month
    elif dist_to_prev < td_13:
        return next_month - current_month
</code>```

Body:
OK, the working part of the code:
I have a function that given a timestamp, and a period (minute, hour, month...) returns the period duration as a timedelta.
Basically, for minute, hour, day, it directly call pandas Timedelta function.
For month, it is a bit 'smarter' as it checks in which month the timestamp is, and return the number of days of identified month.

import pandas as pd

def as_timedelta(ref_ts: pd.Timestamp = None):
    """
    Return the duration of a time period.
    For a month, obtaining its duration requires a reference timestamp to identify
    how many days have to be accounted for in the month.
    """

    # An input timestamp has to be given.
    # It is assumed given timestamp is at beginning of time period for which a time delta is requested.
    # Because of a possible timezone, the timestamp is max 12 hours before or after
    # beginning of month in UTC.
    # To assume the current month, we check what is the closest month beginning
    # As an example, if 31st of January, 6:00 PM is reference timestamp, duration is given for month of February

    # Get month starts
    current_month = pd.Timestamp(year=ref_ts.year, month=ref_ts.month, day=1)
    next_month = current_month + pd.DateOffset(months=1)
    nex_next_month = current_month + pd.DateOffset(months=2)
    # Get month of interest
    dist_to_next = next_month - ref_ts
    dist_to_prev = ref_ts - current_month
    # Return timedelta corresponding as the duration between current month and begining of next month
    td_13 = pd.Timedelta(13, 'h')
    if dist_to_next < td_13:
        return nex_next_month - next_month
    elif dist_to_prev < td_13:
        return next_month - current_month

Given a list of timestamps, I would like to apply this function to each timestamps. But trying with following line of code, but I get an AttributeError.
To illustrate the trouble now, I am taking an example:

ts_list_1M = [
          "Thu Feb 01 2019 00:00:00 GMT+0100",
          "Thu Mar 01 2019 00:00:00 GMT+0100",
          "Sun Apr 01 2019 00:00:00 GMT+0200"]
op_list_1M = [7134.0, 7134.34, 7135.03]
GC_1M = pd.DataFrame(list(zip(ts_list_1M, op_list_1M)), columns =['date', 'open'])
GC_1M['date'] = pd.to_datetime(GC_1M['date'], utc=True)
GC_1M.rename(columns={'date': 'Timestamp'}, inplace=True)
GC_1M.set_index('Timestamp', inplace = True, verify_integrity = True)

The famous line of code:

GC_1M.reset_index().apply(as_timedelta,axis=1).values

And the error message I get:

File "<ipython-input-49-ff9556f2ec44>", line 18, in as_timedelta
current_month = pd.Timestamp(year=ref_ts.year, month=ref_ts.month, day=1)

File "C:\Users\pierre.juillard\Documents\Programs\Anaconda\lib\site-packages\pandas\core\generic.py", line 5179, in __getattr__
return object.__getattribute__(self, name)

AttributeError: ("'Series' object has no attribute 'year'", 'occurred at index 0')

When I test the function on a single value, it works, but when applying it like this, it doesn't. Please, any advice on how to achieve that?

I thank you in advance for your help!
Bests,

Body:
So when you want to apply your function to your 'dates' series only you could do the following:

GC_1M['date'].apply(as_timedelta)

However, this does not seem to work, as in your example 'date' is not a datetime object, so you will need to convert it first (you could also do this upon creation):

GC_1M['date'] = pd.to_datetime(GC_1M['date'])

And finally, your as_timedelta function cannot deal with timezone-aware inputs, I added a comment to the line that needs fixing:

def as_timedelta(ref_ts: pd.Timestamp = None):
    """
    Return the duration of a time period.
    For a month, obtaining its duration requires a reference timestamp to identify
    how many days have to be accounted for in the month.
    """

    # An input timestamp has to be given.
    # It is assumed given timestamp is at beginning of time period for which a time delta is requested.
    # Because of a possible timezone, the timestamp is max 12 hours before or after
    # beginning of month in UTC.
    # To assume the current month, we check what is the closest month beginning
    # As an example, if 31st of January, 6:00 PM is reference timestamp, duration is given for month of February

    # Get month starts
    current_month = pd.Timestamp(year=ref_ts.year, month=ref_ts.month, day=1, tzinfo=ref_ts.tzinfo)  # Make current_month timezone aware
    next_month = current_month + pd.DateOffset(months=1)
    nex_next_month = current_month + pd.DateOffset(months=2)
    # Get month of interest
    dist_to_next = next_month - ref_ts
    dist_to_prev = ref_ts - current_month
    # Return timedelta corresponding as the duration between current month and begining of next month
    td_13 = pd.Timedelta(13, 'h')
    if dist_to_next < td_13:
        return nex_next_month - next_month
    elif dist_to_prev < td_13:
        return next_month - current_month


问:
How to set title above each component of a UIPickerView?
I implemented a UIPickerview with 2 components. I want to set a title above each one. How can I do that?

I don't want do place a separate label above the picker.

答:
I often add an additional component to my UIPickerView with just one row and set that row's title to the header for the next component.

For example for an "hours and minutes" UIPickerView.

```<code>func numberOfComponents(in pickerView: UIPickerView) -> Int {
    return 4 //2 headers and 2 values
}

func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
    if component == 0 {
       return 1 //hours header
    } else if component == 1 {
       return 100 //hours
    } else if component == 2{
       return 1 //minutes header
    } else {
       return 4 //minutes
    }
}

func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
    if component == 0 {
        return "Hours:" //header
    } else if component == 1 {
        return "\(row + 1)" //value
    } else if component == 2 {
        return "Minutes:" //header
    } else if component == 3 {
        return "\(row * 15)" //value
    }
    return nil
}
</code>```

The result will be this:

Result image

ContentLicense: CC BY-SA 3.0

Body:
I often add an additional component to my UIPickerView with just one row and set that row's title to the header for the next component.

For example for an "hours and minutes" UIPickerView.

func numberOfComponents(in pickerView: UIPickerView) -> Int {
    return 4 //2 headers and 2 values
}

func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
    if component == 0 {
       return 1 //hours header
    } else if component == 1 {
       return 100 //hours
    } else if component == 2{
       return 1 //minutes header
    } else {
       return 4 //minutes
    }
}

func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
    if component == 0 {
        return "Hours:" //header
    } else if component == 1 {
        return "\(row + 1)" //value
    } else if component == 2 {
        return "Minutes:" //header
    } else if component == 3 {
        return "\(row * 15)" //value
    }
    return nil
}

The result will be this:

Result image


问:
Unable to pass intent value to next activity
I am facing an issue to pass intent values to next activity.

While creating profile I created two databasereferences 1. with pushid 2. without push id

Now I am trying to pass values from databaseref with pushid

My code looks like this

```<code>        mDatabaseReference = mDatabase!!.reference.child("Tokens").child(userId).push()
</code>```

to store push id key value, i used variable like below one

```<code>        var tokenID: String = mDatabaseReference!!.key!!
</code>```

to push this value to intent, I used

```<code>        intent.putExtra(TOKENID,tokenID)
</code>```

when I used log I can see push id value

TOKENID I created at initial activity with companion object

To pass this push id value to next activity

```<code>        tokenreq = intent.getStringExtra(Profile.TOKENID)
</code>```

to retreive values i used below databasereference

```<code>mDatabaseReference = mDatabase!!.reference.child("Tokens").child(userId).child(tokenreq!!)
</code>```

when I run the program, app crash mentioning KotlinNullPointerException for tokenreq in log data

log file

```<code>    kotlin.KotlinNullPointerException
    at com.luvpi.luvproject.activities.Verification$onCreate$2.onClick(Verification.kt:96)
    at android.view.View.performClick(View.java:5612)
    at android.view.View$PerformClick.run(View.java:22288)
    at android.os.Handler.handleCallback(Handler.java:751)
    at android.os.Handler.dispatchMessage(Handler.java:95)
    at android.os.Looper.loop(Looper.java:154)
    at android.app.ActivityThread.main(ActivityThread.java:6123)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:757)
</code>```

complete code for process

```<code>            checkcode.setOnClickListener {
            val userId = FirebaseAuth.getInstance().currentUser!!.uid

            mDatabase = FirebaseDatabase.getInstance()

            Log.d(TAG,"Push id is $tokenrequest")

            mDatabaseReference = mDatabase!!.reference.child("Tokens").child(userId).child(tokenrequest!!)

            mDatabaseReference!!.addListenerForSingleValueEvent(object :ValueEventListener{
                override fun onCancelled(databaseError: DatabaseError) {
                }

                override fun onDataChange(dataSnapshot: DataSnapshot) {

                    var tokenkey = dataSnapshot.child("tokenid").value.toString()

                    Log.d(TAG,"Verification Code is $tokenkey")

                    if (tokenkey == userverify.toString()) {

                        Toast.makeText(this@Verification, "Successfully Verified", Toast.LENGTH_LONG)
                            .show()
                        startActivity(Intent(this@Verification, LatestMessage::class.java))
                    } else {
                        Toast.makeText(this@Verification, "Verification code is incorrect", Toast.LENGTH_LONG).show()
                        return
                    }
                }

            })

        }
</code>```

答:
Your reqToken is not child. It should be value. So you should use this for mDatabaseReference;

```<code>mDatabaseReference = mDatabase!!.reference.child("Tokens").child(userId)
</code>```

Second step;

```<code>mDatabaseReference.setValue(reqToken)
</code>```

Third step;

```<code>val valueEventListenerUser2 = object : ValueEventListener {
    override fun onDataChange(dataSnapshot: DataSnapshot) {
        var tokenreq = dataSnapshot.getValue(String::class.java)!!
    }

    override fun onCancelled(databaseError: DatabaseError) {
    }
}
mDatabaseReference.addValueEventListener(valueEventListenerUser2)
</code>```

Body:
I am facing an issue to pass intent values to next activity.

While creating profile I created two databasereferences 1. with pushid 2. without push id

Now I am trying to pass values from databaseref with pushid

My code looks like this

        mDatabaseReference = mDatabase!!.reference.child("Tokens").child(userId).push()

to store push id key value, i used variable like below one

        var tokenID: String = mDatabaseReference!!.key!!

to push this value to intent, I used

        intent.putExtra(TOKENID,tokenID)

when I used log I can see push id value

TOKENID I created at initial activity with companion object

To pass this push id value to next activity

        tokenreq = intent.getStringExtra(Profile.TOKENID)

to retreive values i used below databasereference

mDatabaseReference = mDatabase!!.reference.child("Tokens").child(userId).child(tokenreq!!)

when I run the program, app crash mentioning KotlinNullPointerException for tokenreq in log data

log file

    kotlin.KotlinNullPointerException
    at com.luvpi.luvproject.activities.Verification$onCreate$2.onClick(Verification.kt:96)
    at android.view.View.performClick(View.java:5612)
    at android.view.View$PerformClick.run(View.java:22288)
    at android.os.Handler.handleCallback(Handler.java:751)
    at android.os.Handler.dispatchMessage(Handler.java:95)
    at android.os.Looper.loop(Looper.java:154)
    at android.app.ActivityThread.main(ActivityThread.java:6123)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:757)

complete code for process

            checkcode.setOnClickListener {
            val userId = FirebaseAuth.getInstance().currentUser!!.uid

            mDatabase = FirebaseDatabase.getInstance()

            Log.d(TAG,"Push id is $tokenrequest")

            mDatabaseReference = mDatabase!!.reference.child("Tokens").child(userId).child(tokenrequest!!)

            mDatabaseReference!!.addListenerForSingleValueEvent(object :ValueEventListener{
                override fun onCancelled(databaseError: DatabaseError) {
                }

                override fun onDataChange(dataSnapshot: DataSnapshot) {

                    var tokenkey = dataSnapshot.child("tokenid").value.toString()

                    Log.d(TAG,"Verification Code is $tokenkey")

                    if (tokenkey == userverify.toString()) {

                        Toast.makeText(this@Verification, "Successfully Verified", Toast.LENGTH_LONG)
                            .show()
                        startActivity(Intent(this@Verification, LatestMessage::class.java))
                    } else {
                        Toast.makeText(this@Verification, "Verification code is incorrect", Toast.LENGTH_LONG).show()
                        return
                    }
                }

            })

        }

Body:
Your reqToken is not child. It should be value. So you should use this for mDatabaseReference;

mDatabaseReference = mDatabase!!.reference.child("Tokens").child(userId)

Second step;

mDatabaseReference.setValue(reqToken)

Third step;

val valueEventListenerUser2 = object : ValueEventListener {
    override fun onDataChange(dataSnapshot: DataSnapshot) {
        var tokenreq = dataSnapshot.getValue(String::class.java)!!
    }

    override fun onCancelled(databaseError: DatabaseError) {
    }
}
mDatabaseReference.addValueEventListener(valueEventListenerUser2)


问:
cant set onclick on recylerview(cardview)
MainActivity.java

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

RecyclerView recyclerView;
DatabaseReference reference;
FirebaseRecyclerAdapter<Bookdeets,Bkhomeholder>adapter;
FirebaseRecyclerOptions<Bookdeets> options;
ProgressBar loading;
FloatingActionButton searchbtn;
TextView logout;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    reference = FirebaseDatabase.getInstance().getReference().child("books");
    reference.keepSynced(true);
    recyclerView = (RecyclerView) findViewById(R.id.rv);
    recyclerView.setHasFixedSize(true);
    recyclerView.setLayoutManager(new LinearLayoutManager(this));
    recyclerView.addItemDecoration(new DividerItemDecoration(this, LinearLayoutManager.VERTICAL));
    loading=(ProgressBar)findViewById(R.id.loading);
    searchbtn=(FloatingActionButton)findViewById(R.id.searchbtn);
    logout = (TextView) findViewById(R.id.Logout);
    logout.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Logout();
        }
    });
    searchbtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Opensearchpage();

        }
    });

    options = new FirebaseRecyclerOptions.Builder<Bookdeets>()
            .setQuery(reference, Bookdeets.class).build();
    adapter = new FirebaseRecyclerAdapter<Bookdeets, Bkhomeholder>(options) {
        @Override
        protected void onBindViewHolder(@NonNull Bkhomeholder holder, int position, @NonNull Bookdeets model) {

            Picasso.get().load(model.getImage()).into(holder.bookimg, new Callback() {
                @Override
                public void onSuccess() {
                    loading.setVisibility(View.GONE);

                }

                @Override
                public void onError(Exception e) {
                    Toast.makeText(getApplicationContext(), "could not get the image", Toast.LENGTH_LONG).show();
                    loading.setVisibility(View.GONE);
                }
            });

            holder.title.setText(model.getBookname());

        }

        @NonNull
        @Override
        public Bkhomeholder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.cardviewlay, parent, false);
            return new Bkhomeholder(view);
        }
            };
    GridLayoutManager gridLayoutManager=new GridLayoutManager(getApplicationContext(),3);
    recyclerView.setLayoutManager(gridLayoutManager);
    adapter.startListening();
    recyclerView.setAdapter(adapter);
}

@Override
protected void onStart() {
    super.onStart();
    if(adapter!=null)
        adapter.startListening();
    loading.setVisibility(View.VISIBLE);
}

@Override
protected void onStop() {
    super.onStop();
    if(adapter!=null)
        adapter.stopListening();
}

@Override
protected void onResume() {
    super.onResume();
    if(adapter!=null)
        adapter.startListening();
}
public void Opensearchpage(){
    Intent intent=new Intent(this, SearchPage.class);
    startActivity(intent);
}
public void Logout() {
    FirebaseAuth.getInstance().signOut();
    startActivity(new Intent(getApplicationContext(), Login.class));
    finish();
}
</code>```

Bkhomeholder.java

```<code>public class Bkhomeholder extends RecyclerView.ViewHolder {
public TextView title;
public ImageView bookimg;

public Bkhomeholder(@NonNull View itemView) {
    super(itemView);
    title = itemView.findViewById(R.id.bkdettitle);

    bookimg = itemView.findViewById(R.id.bkdetimg);

}
</code>```

activity_main.xml

```<code><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".homepage.MainActivity"
android:orientation="vertical">

<TextView
    android:layout_width="match_parent"
    android:layout_height="60dp"
    android:layout_marginTop="4dp"
    android:layout_marginStart="8dp"
    android:layout_marginEnd="8dp"
    android:text="Library App"
    android:textAlignment="center"
    android:textColor="#E21B1B"
    android:textSize="32dp"

    android:textStyle="bold" />
<androidx.recyclerview.widget.RecyclerView
    android:clipChildren="true"
    android:id="@+id/rv"
    android:layout_width="match_parent"
    android:layout_height="525dp"
    android:layout_marginStart="8dp"
    android:layout_marginTop="75dp"
    android:layout_marginEnd="8dp"
    android:layout_marginBottom="8dp"
    android:clickable="true"
    android:foreground="?android:attr/selectableItemBackground"/>

<com.google.android.material.floatingactionbutton.FloatingActionButton
    android:id="@+id/searchbtn"
    android:layout_width="100dp"
    android:layout_height="100dp"
    android:layout_marginStart="345dp"
    android:layout_marginTop="480dp"
    android:layout_marginEnd="12dp"
    android:background="#B3E5FC"
    android:clickable="true"

    app:srcCompat="@drawable/customicon" />

<ProgressBar
    android:id="@+id/loading"
    style="?android:attr/progressBarStyle"
    android:layout_width="76dp"
    android:layout_height="76dp"
    android:layout_marginStart="163dp"
    android:layout_marginTop="253dp"
    android:layout_marginEnd="163dp"
    android:layout_marginBottom="253dp"
    android:visibility="invisible"

    />
<TextView
    android:layout_width="match_parent"
    android:layout_height="25dp"
    android:id="@+id/Logout"
    android:layout_centerHorizontal="true"
    android:text="Logout"
    android:textAlignment="center"
    android:textSize="14sp"
    android:layout_marginBottom="8dp"
    android:layout_marginTop="565dp"
</code>```

cardview xml

```<code><androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:cardview="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:clickable="true"
android:foreground="?android:attr/selectableItemBackground"
android:id="@+id/bookcardview"
android:layout_width="120dp"
android:layout_height="190dp"
android:layout_margin="5dp"
cardview:cardCornerRadius="4dp">

<LinearLayout
    android:id="@+id/bkdetlinear"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:ignore="ExtraText"
    android:clickable="true"
    android:foreground="?android:attr/selectableItemBackground"
    android:layout_marginEnd="4dp"
    >

    <ImageView

        android:id="@+id/bkdetimg"
        android:layout_width="match_parent"
        android:layout_height="160dp"
        android:background="#2d2d2d"
        android:clickable="true"
        android:scaleType="fitXY" />

    <TextView
        android:id="@+id/bkdettitle"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:text="Book title"
        android:textColor="#2d2d2d"
        android:textSize="12sp" />

</LinearLayout>
</androidx.cardview.widget.CardView>
</RelativeLayout>
</code>```

i tried setting on click on the cardviewholder that is separate xml file which is inflated in my mainactivity oncreate and set the onclick listener  under
onBindViewHolder but i got a error regarding null object refference as if the activity could not detect the cardview

答:
You can set OnClickListener on RecyclerView item inside onBindViewHolder like below:

```<code>@Override
protected void onBindViewHolder(@NonNull Bkhomeholder holder, int position, @NonNull Bookdeets model) {

    ....

    holder.title.setText(model.getBookname());

    holder.itemView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            // Do your operation here
        }
    });

}
</code>```

Update:  Remove   android:clickable="true"  from cardview layout like below:

```<code><androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:cardview="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:foreground="?android:attr/selectableItemBackground"
    android:id="@+id/bookcardview"
    android:layout_width="120dp"
    android:layout_height="190dp"
    android:layout_margin="5dp"
    cardview:cardCornerRadius="4dp">

    <LinearLayout
        android:id="@+id/bkdetlinear"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        tools:ignore="ExtraText"
        android:foreground="?android:attr/selectableItemBackground"
        android:layout_marginEnd="4dp"
        >

        <ImageView

            android:id="@+id/bkdetimg"
            android:layout_width="match_parent"
            android:layout_height="160dp"
            android:background="#2d2d2d"
            android:scaleType="fitXY" />

        <TextView
            android:id="@+id/bkdettitle"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:gravity="center"
            android:text="Book title"
            android:textColor="#2d2d2d"
            android:textSize="12sp" />

    </LinearLayout>
</androidx.cardview.widget.CardView>
</code>```

Body:
MainActivity.java

public class MainActivity extends AppCompatActivity {

RecyclerView recyclerView;
DatabaseReference reference;
FirebaseRecyclerAdapter<Bookdeets,Bkhomeholder>adapter;
FirebaseRecyclerOptions<Bookdeets> options;
ProgressBar loading;
FloatingActionButton searchbtn;
TextView logout;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    reference = FirebaseDatabase.getInstance().getReference().child("books");
    reference.keepSynced(true);
    recyclerView = (RecyclerView) findViewById(R.id.rv);
    recyclerView.setHasFixedSize(true);
    recyclerView.setLayoutManager(new LinearLayoutManager(this));
    recyclerView.addItemDecoration(new DividerItemDecoration(this, LinearLayoutManager.VERTICAL));
    loading=(ProgressBar)findViewById(R.id.loading);
    searchbtn=(FloatingActionButton)findViewById(R.id.searchbtn);
    logout = (TextView) findViewById(R.id.Logout);
    logout.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Logout();
        }
    });
    searchbtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Opensearchpage();

        }
    });

    options = new FirebaseRecyclerOptions.Builder<Bookdeets>()
            .setQuery(reference, Bookdeets.class).build();
    adapter = new FirebaseRecyclerAdapter<Bookdeets, Bkhomeholder>(options) {
        @Override
        protected void onBindViewHolder(@NonNull Bkhomeholder holder, int position, @NonNull Bookdeets model) {

            Picasso.get().load(model.getImage()).into(holder.bookimg, new Callback() {
                @Override
                public void onSuccess() {
                    loading.setVisibility(View.GONE);

                }

                @Override
                public void onError(Exception e) {
                    Toast.makeText(getApplicationContext(), "could not get the image", Toast.LENGTH_LONG).show();
                    loading.setVisibility(View.GONE);
                }
            });

            holder.title.setText(model.getBookname());

        }

        @NonNull
        @Override
        public Bkhomeholder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.cardviewlay, parent, false);
            return new Bkhomeholder(view);
        }
            };
    GridLayoutManager gridLayoutManager=new GridLayoutManager(getApplicationContext(),3);
    recyclerView.setLayoutManager(gridLayoutManager);
    adapter.startListening();
    recyclerView.setAdapter(adapter);
}

@Override
protected void onStart() {
    super.onStart();
    if(adapter!=null)
        adapter.startListening();
    loading.setVisibility(View.VISIBLE);
}

@Override
protected void onStop() {
    super.onStop();
    if(adapter!=null)
        adapter.stopListening();
}

@Override
protected void onResume() {
    super.onResume();
    if(adapter!=null)
        adapter.startListening();
}
public void Opensearchpage(){
    Intent intent=new Intent(this, SearchPage.class);
    startActivity(intent);
}
public void Logout() {
    FirebaseAuth.getInstance().signOut();
    startActivity(new Intent(getApplicationContext(), Login.class));
    finish();
}

Bkhomeholder.java

public class Bkhomeholder extends RecyclerView.ViewHolder {
public TextView title;
public ImageView bookimg;

public Bkhomeholder(@NonNull View itemView) {
    super(itemView);
    title = itemView.findViewById(R.id.bkdettitle);

    bookimg = itemView.findViewById(R.id.bkdetimg);

}

activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".homepage.MainActivity"
android:orientation="vertical">

<TextView
    android:layout_width="match_parent"
    android:layout_height="60dp"
    android:layout_marginTop="4dp"
    android:layout_marginStart="8dp"
    android:layout_marginEnd="8dp"
    android:text="Library App"
    android:textAlignment="center"
    android:textColor="#E21B1B"
    android:textSize="32dp"

    android:textStyle="bold" />
<androidx.recyclerview.widget.RecyclerView
    android:clipChildren="true"
    android:id="@+id/rv"
    android:layout_width="match_parent"
    android:layout_height="525dp"
    android:layout_marginStart="8dp"
    android:layout_marginTop="75dp"
    android:layout_marginEnd="8dp"
    android:layout_marginBottom="8dp"
    android:clickable="true"
    android:foreground="?android:attr/selectableItemBackground"/>

<com.google.android.material.floatingactionbutton.FloatingActionButton
    android:id="@+id/searchbtn"
    android:layout_width="100dp"
    android:layout_height="100dp"
    android:layout_marginStart="345dp"
    android:layout_marginTop="480dp"
    android:layout_marginEnd="12dp"
    android:background="#B3E5FC"
    android:clickable="true"

    app:srcCompat="@drawable/customicon" />

<ProgressBar
    android:id="@+id/loading"
    style="?android:attr/progressBarStyle"
    android:layout_width="76dp"
    android:layout_height="76dp"
    android:layout_marginStart="163dp"
    android:layout_marginTop="253dp"
    android:layout_marginEnd="163dp"
    android:layout_marginBottom="253dp"
    android:visibility="invisible"

    />
<TextView
    android:layout_width="match_parent"
    android:layout_height="25dp"
    android:id="@+id/Logout"
    android:layout_centerHorizontal="true"
    android:text="Logout"
    android:textAlignment="center"
    android:textSize="14sp"
    android:layout_marginBottom="8dp"
    android:layout_marginTop="565dp"

cardview xml

<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:cardview="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:clickable="true"
android:foreground="?android:attr/selectableItemBackground"
android:id="@+id/bookcardview"
android:layout_width="120dp"
android:layout_height="190dp"
android:layout_margin="5dp"
cardview:cardCornerRadius="4dp">

<LinearLayout
    android:id="@+id/bkdetlinear"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:ignore="ExtraText"
    android:clickable="true"
    android:foreground="?android:attr/selectableItemBackground"
    android:layout_marginEnd="4dp"
    >

    <ImageView

        android:id="@+id/bkdetimg"
        android:layout_width="match_parent"
        android:layout_height="160dp"
        android:background="#2d2d2d"
        android:clickable="true"
        android:scaleType="fitXY" />

    <TextView
        android:id="@+id/bkdettitle"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:text="Book title"
        android:textColor="#2d2d2d"
        android:textSize="12sp" />

</LinearLayout>
</androidx.cardview.widget.CardView>
</RelativeLayout>

i tried setting on click on the cardviewholder that is separate xml file which is inflated in my mainactivity oncreate and set the onclick listener  under
onBindViewHolder but i got a error regarding null object refference as if the activity could not detect the cardview

Body:
You can set OnClickListener on RecyclerView item inside onBindViewHolder like below:

@Override
protected void onBindViewHolder(@NonNull Bkhomeholder holder, int position, @NonNull Bookdeets model) {

    ....

    holder.title.setText(model.getBookname());

    holder.itemView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            // Do your operation here
        }
    });

}

Update:  Remove   android:clickable="true"  from cardview layout like below:

<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:cardview="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:foreground="?android:attr/selectableItemBackground"
    android:id="@+id/bookcardview"
    android:layout_width="120dp"
    android:layout_height="190dp"
    android:layout_margin="5dp"
    cardview:cardCornerRadius="4dp">

    <LinearLayout
        android:id="@+id/bkdetlinear"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        tools:ignore="ExtraText"
        android:foreground="?android:attr/selectableItemBackground"
        android:layout_marginEnd="4dp"
        >

        <ImageView

            android:id="@+id/bkdetimg"
            android:layout_width="match_parent"
            android:layout_height="160dp"
            android:background="#2d2d2d"
            android:scaleType="fitXY" />

        <TextView
            android:id="@+id/bkdettitle"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:gravity="center"
            android:text="Book title"
            android:textColor="#2d2d2d"
            android:textSize="12sp" />

    </LinearLayout>
</androidx.cardview.widget.CardView>


问:
Visualize big git graph
I would like to analyse to git project with a common history but forked since a long time.

Is there a way to display git history with a long commit history? Each git client I know don't allow to zoom out the git graph.

答: you can use tig and zoom out your console to visualise the branches.

Title: Visualize big git graph


问:
WebImage returning as PNG when source file is JPG
I have this confusing problem when WebImage retrieves an image saved as ".jpg" it returns as ".png".

Here's the image of the problem:

Any ideas why this is happening?

UPDATE: The lighthouse.jpg is one of the My Picture samples of Windows 7 and was uploaded and saved with no frills.

Here is my upload method when uploading the lighthouse.jpg which is saved with uploadImage.SaveAs(path);

答: The image's Mime type may be set differently to its file-suffix. Ref. https://stackoverflow.com/a/14587821/6812820</p>


问:
java regex : getting a substring from a string which can vary
I have a String like - "Bangalore,India=Karnataka". From this String I would like to extract only the substring "Bangalore". In this case the regex can be - (.+),.*=.*. But the problem is, the String can sometimes come like only "Bangalore". Then in that case the above regex wont work. What will be the regex to get the substring "Bangalore" whatever the String be ?

答: Are you somehow forced to solve this using one regexp and nothing else? (Stupid interview question? Extremely inflexible external API?) In general, don't try to make regexes do what plain old programming constructs do better. Just use the obvious regex, and it it doesn't match, return the entire string instead. </p>


问:
React JS Toogle Class
I have a project that I am developing with React JS. The problem is that I have a button and when I click on it, I just want the icon on the button I click to change. But the icons on all the buttons I click change. My code is below.

```<code>constructor(props){
super(props)
this.state={
    icon: false
}
}

active = (event) => {
    this.setState({icon: !this.state.icon})
}

.....

const menu = ['A','B','C','A','B','C','A','B','C']
<div className="nav_menu">
<ul>
    {menu.map((item,index) =>
        <li key = {index}>
            <Link data-id = {index} className="inactive" to={`${match.url}`} onClick={this.active}>
                <span>
                    <span>
                        <FontAwesomeIcon icon={faHome} className="icon"/>
                    </span>
                    {item}
                </span>
                <FontAwesomeIcon data-id = {index} icon={icon ? faAngleDown:faAngleRight} className="angle"/>
            </Link>
        </li>
    )}
</ul>
</code>```

How do I fix this?

答:
Sample how you can select particular. live demo https://codesandbox.io/s/focused-browser-fls2w</p>

```<code>export default class Abc extends Component {
  constructor(props) {
    super(props);
    this.state = { icon: false };
  }
  active = item => {
    this.setState({ icon: item });
  };
  render() {
    const menu = ["A", "B", "C", "A", "B", "C", "A", "B", "C"];
    return (
      <div className="nav_menu">
        <ul>
          {menu.map((item, index) => (
            <li
              key={index}
              onClick={() => this.active(index)}
              style={{ color: this.state.icon === index ? "red" : "" }}
            >
              {item}
            </li>
          ))}
        </ul>
      </div>
    );
  }
}
</code>```

Title: React JS Toogle Class

Body:
I have a project that I am developing with React JS. The problem is that I have a button and when I click on it, I just want the icon on the button I click to change. But the icons on all the buttons I click change. My code is below.

constructor(props){
super(props)
this.state={
    icon: false
}
}

active = (event) => {
    this.setState({icon: !this.state.icon})
}

.....

const menu = ['A','B','C','A','B','C','A','B','C']

    {menu.map((item,index) =>

            <Link data-id = {index} className="inactive" to={`${match.url}`} onClick={this.active}>

                        <FontAwesomeIcon icon={faHome} className="icon"/>

                    {item}

                <FontAwesomeIcon data-id = {index} icon={icon ? faAngleDown:faAngleRight} className="angle"/>
            </Link>

    )}

How do I fix this?

Body:
Sample how you can select particular. live demo https://codesandbox.io/s/focused-browser-fls2w

export default class Abc extends Component {
  constructor(props) {
    super(props);
    this.state = { icon: false };
  }
  active = item => {
    this.setState({ icon: item });
  };
  render() {
    const menu = ["A", "B", "C", "A", "B", "C", "A", "B", "C"];
    return (
      <div className="nav_menu">
        <ul>
          {menu.map((item, index) => (
            <li
              key={index}
              onClick={() => this.active(index)}
              style={{ color: this.state.icon === index ? "red" : "" }}
            >
              {item}
            </li>
          ))}
        </ul>
      </div>
    );
  }
}


问:
MenuItemDefinition property "requiredPermissionName" is missing from 5.2.0 release (and pre-release)
There seems to be a breaking change in the latest release (5.2.0)

To replicate:

download the latest stable template for mvc core

Update all nuget packages to latest stable

The property requiredPermissionName is no longer available

Any steps to overcome would be appreciated...

Sample Code from Template (.net core MVC)

```<code>public class GpNavigationProvider : NavigationProvider
{
    public override void SetNavigation(INavigationProviderContext context)
    {
        context.Manager.MainMenu
            .AddItem(
                new MenuItemDefinition(
                    PageNames.Home,
                    L("HomePage"),
                    url: "",
                    icon: "home",
                    requiresAuthentication: true
                )
            ).AddItem(
                new MenuItemDefinition(
                    PageNames.Tenants,
                    L("Tenants"),
                    url: "Tenants",
                    icon: "business",
                    requiredPermissionName: PermissionNames.Pages_Tenants
                )
</code>```

Compile Error:

Severity   Code    Description Project File    Line    Suppression State
  Error   CS1739

  The best overload for 'MenuItemDefinition' does not have a parameter named 'requiredPermissionName'

  ...\5.1.1\aspnet-core\src\Gp.Web.Mvc\Startup\GpNavigationProvider.cs   29  Active

答:
The change is straightforward:

// requiredPermissionName: PermissionNames.Pages_Tenants,
permissionDependency: new SimplePermissionDependency(PermissionNames.Pages_Tenants),
```

requiredPermissionName was deprecated in version 2.2 in July 2017.

It was removed in version 5.2 that was released yesterday, after 3 major versions and more than 2.5 years.

References:

aspnetboilerplate/aspnetboilerplate#2289 (ABP 2.2)

aspnetboilerplate/aspnetboilerplate#5191 (ABP 5.2)

Body:
There seems to be a breaking change in the latest release (5.2.0)

To replicate:

download the latest stable template for mvc core

Update all nuget packages to latest stable

The property requiredPermissionName is no longer available

Any steps to overcome would be appreciated...

Sample Code from Template (.net core MVC)

public class GpNavigationProvider : NavigationProvider
{
    public override void SetNavigation(INavigationProviderContext context)
    {
        context.Manager.MainMenu
            .AddItem(
                new MenuItemDefinition(
                    PageNames.Home,
                    L("HomePage"),
                    url: "",
                    icon: "home",
                    requiresAuthentication: true
                )
            ).AddItem(
                new MenuItemDefinition(
                    PageNames.Tenants,
                    L("Tenants"),
                    url: "Tenants",
                    icon: "business",
                    requiredPermissionName: PermissionNames.Pages_Tenants
                )

Compile Error:

Severity   Code    Description Project File    Line    Suppression State
  Error   CS1739

  The best overload for 'MenuItemDefinition' does not have a parameter named 'requiredPermissionName'

  ...\5.1.1\aspnet-core\src\Gp.Web.Mvc\Startup\GpNavigationProvider.cs   29  Active

Body:
The change is straightforward:

// requiredPermissionName: PermissionNames.Pages_Tenants,
permissionDependency: new SimplePermissionDependency(PermissionNames.Pages_Tenants),

requiredPermissionName was deprecated in version 2.2 in July 2017.

It was removed in version 5.2 that was released yesterday, after 3 major versions and more than 2.5 years.

References:

aspnetboilerplate/aspnetboilerplate#2289 (ABP 2.2)

aspnetboilerplate/aspnetboilerplate#5191 (ABP 5.2)


问:
Change global variable from event function
I am trying to learn Javascript.

I watched some Javascript course on Youtube and am trying to create my first project.

Project should be simple tic-tac-toe game.

Functionality:
First click on box should fill with "X"
Second click on another box should fill with "Y"
Third click on another box should fill with "X" again and so on until all boxes will be filled with character.

there is my codes
HTML

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
<div class="main">
<table>
    <tr>
        <td class="b1-1"></td>
        <td class="b1-2"></td>
        <td class="b1-3"></td>
    </tr>
    <tr>
        <td class="b2-1"></td>
        <td class="b2-2"></td>
        <td class="b2-3"></td>
    </tr>
    <tr>
        <td class="b3-1"></td>
        <td class="b3-2"></td>
        <td class="b3-3"></td>
    </tr>
</table>
</div>
<script src="script.js" type="text/javascript"></script>
</body>
</html>
</code>```

CSS

```<code>.main {
    padding: 100px 0;
    width: 360px;
    margin: 0 auto;
}

table, tbody {
    margin: 0;
    padding: 0;
    width: 360px;
    height: 360px;
}

tr {
    width:360px;
    height: 120px;
    margin: 0;
    padding: 0;
}

td {
    text-align: center;
    width:120px;
    height: 120px;
    border: 1px solid #333;
    margin: 0;
    padding: 0;
    font-size: 50px;
}
</code>```

Javascript

```<code>var action = document.querySelectorAll('td');
var gameState = 0;
for (var i = 0; i <= action.length - 1; i++) {
    getClassName = "." + action[i].classList.value;
        if (gameState === 0) {
            document.querySelector(getClassName).addEventListener("click", chasviX(i));
        } else {
            document.querySelector(getClassName).addEventListener("click", chasviO(i));
        }
}

function chasviX(cord) {
        document.querySelector("." + action[cord].classList.value).addEventListener("click", event => {
            document.querySelector("." + action[cord].classList.value).textContent = "X";
            gameState = 1;
        });
};

function chasviO(cord) {
        document.querySelector("." + action[cord].classList.value).addEventListener("click", event => {
            document.querySelector("." + action[cord].classList.value).textContent = "O";
            gameState = 0;
        });
};
</code>```

There is project link also - https://jsfiddle.net/qwy2k571/

At the moment each box is filling with "X".
I know i didn't understand closures and scope chains exactly but please give me an correct code to understand it by example.

Thanks in advance and best regards.

答:
Here I made a working jsfiddle: https://jsfiddle.net/1jnkepLg/1/

I simplified the JS part to:

```<code>var gameState = 0; // Holds the current game state
var cells = document.getElementsByTagName("td"); // list of cells of the game board

// attach an event listener at each cell.
for (var i=0;i<cells.length;i++)
{
    cells[i].addEventListener("click", chasvi);
}

function chasvi()
{
       // in event callbacks "this" refers to the element that triggered the event. In this case, it is the TD element.
       this.textContent = gameState ? "X" : "0";

       // switch the game state
       gameState = !gameState;

}
</code>```

In this case, one event listener is enough, you can determine what X|0 to draw at the callback function.

Body:
I am trying to learn Javascript.

I watched some Javascript course on Youtube and am trying to create my first project.

Project should be simple tic-tac-toe game.

Functionality:
First click on box should fill with "X"
Second click on another box should fill with "Y"
Third click on another box should fill with "X" again and so on until all boxes will be filled with character.

there is my codes
HTML

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="style.css">

CSS

.main {
    padding: 100px 0;
    width: 360px;
    margin: 0 auto;
}

table, tbody {
    margin: 0;
    padding: 0;
    width: 360px;
    height: 360px;
}

tr {
    width:360px;
    height: 120px;
    margin: 0;
    padding: 0;
}

td {
    text-align: center;
    width:120px;
    height: 120px;
    border: 1px solid #333;
    margin: 0;
    padding: 0;
    font-size: 50px;
}

Javascript

var action = document.querySelectorAll('td');
var gameState = 0;
for (var i = 0; i <= action.length - 1; i++) {
    getClassName = "." + action[i].classList.value;
        if (gameState === 0) {
            document.querySelector(getClassName).addEventListener("click", chasviX(i));
        } else {
            document.querySelector(getClassName).addEventListener("click", chasviO(i));
        }
}

function chasviX(cord) {
        document.querySelector("." + action[cord].classList.value).addEventListener("click", event => {
            document.querySelector("." + action[cord].classList.value).textContent = "X";
            gameState = 1;
        });
};

function chasviO(cord) {
        document.querySelector("." + action[cord].classList.value).addEventListener("click", event => {
            document.querySelector("." + action[cord].classList.value).textContent = "O";
            gameState = 0;
        });
};

There is project link also - https://jsfiddle.net/qwy2k571/

At the moment each box is filling with "X".
I know i didn't understand closures and scope chains exactly but please give me an correct code to understand it by example.

Thanks in advance and best regards.

Body:
Here I made a working jsfiddle: https://jsfiddle.net/1jnkepLg/1/

I simplified the JS part to:

var gameState = 0; // Holds the current game state
var cells = document.getElementsByTagName("td"); // list of cells of the game board

// attach an event listener at each cell.
for (var i=0;i<cells.length;i++)
{
    cells[i].addEventListener("click", chasvi);
}

function chasvi()
{
       // in event callbacks "this" refers to the element that triggered the event. In this case, it is the TD element.
       this.textContent = gameState ? "X" : "0";

       // switch the game state
       gameState = !gameState;

}

In this case, one event listener is enough, you can determine what X|0 to draw at the callback function.


问:
conda update conda won't work
I would like to update conda to get the later version of python and its extensions but it keeps telling me this :

```<code>(base) C:\Users\pierr>conda update conda
Solving environment: done

==> WARNING: A newer version of conda exists. <==
  current version: 4.5.2
  latest version: 4.5.4

Please update conda by running

    $ conda update -n base conda

# All requested packages already installed.

(base) C:\Users\pierr>conda update -n base conda
Solving environment: done

==> WARNING: A newer version of conda exists. <==
  current version: 4.5.2
  latest version: 4.5.4

Please update conda by running

    $ conda update -n base conda

# All requested packages already installed.
</code>```

Any help here please ?

答:
There seems to be some documentation issue here. Apparently, 'conda update -n base conda' does not work any longer.
It seems that no one has fixed the documentation.

conda update --all

seems to work for me.

Title: conda update conda won't work

Body:
I would like to update conda to get the later version of python and its extensions but it keeps telling me this :

(base) C:\Users\pierr>conda update conda
Solving environment: done

==> WARNING: A newer version of conda exists. <==
  current version: 4.5.2
  latest version: 4.5.4

Please update conda by running

    $ conda update -n base conda

# All requested packages already installed.

(base) C:\Users\pierr>conda update -n base conda
Solving environment: done

==> WARNING: A newer version of conda exists. <==
  current version: 4.5.2
  latest version: 4.5.4

Please update conda by running

    $ conda update -n base conda

# All requested packages already installed.

Any help here please ?


问:
I want to send encrypted password and decrypted password from react js to WSO2 IS 5.9.0?
I am using react JS as frontend and I want to send encrypted password to WSO2 IS 5.9.0 while using

```<code>curl --location --request POST 'https://x.x.x.x/oauth2/token' \
--header 'Content-Type: text/plain' \
--header 'Authorization: Basic xxxx' \
--data-urlencode 'grant_type=password' \
--data-urlencode 'username=xxxxxxxxx' \
--data-urlencode 'password=abc12345' \
--data-urlencode 'scope=openid'

</code>```

I want to send the password in encrypted form and decrypt the password at WSO2 IS end.
How do I perform this.....?

答:
According to the OAuth spec, password grant can be used only if there is trust between the client and server.

The spec says as below:

The resource owner password credentials (i.e., username and password)
can be used directly as an authorization grant to obtain an access

token.  The credentials should only be used when there is a high

degree of trust between the resource owner and the client (e.g., the

client is part of the device operating system or a highly privileged

application), and when other authorization grant types are not

available (such as an authorization code).

So it is not recommended using password grant flow in a browser client.

Body:
I am using react JS as frontend and I want to send encrypted password to WSO2 IS 5.9.0 while using

curl --location --request POST 'https://x.x.x.x/oauth2/token' \
--header 'Content-Type: text/plain' \
--header 'Authorization: Basic xxxx' \
--data-urlencode 'grant_type=password' \
--data-urlencode 'username=xxxxxxxxx' \
--data-urlencode 'password=abc12345' \
--data-urlencode 'scope=openid'

I want to send the password in encrypted form and decrypt the password at WSO2 IS end.
How do I perform this.....?


问:
ODOO 10 custom report pdf name
I am developing a custom report in ODOO10 CE and I have a problem naming the generated PDF. It always names the "string" field in the report definition. It ignores the print_report_name field.

Here is the report definition:

```<code><report
    id="action_report_as"
    model="report_as"
    string="Report AS_EE"
    report_type="qweb-pdf"
    name="report_as_ee.report_as"
    paperformat="report.vertical_1"
/>
<record
    id="action_report_as"
    model="ir.actions.report.xml">
    <field name="print_report_name">mycorrectreportname.pdf</field>
</record>
</code>```

And here is the .py:

```<code>class ReportAs(models.AbstractModel):
_name = 'report.report_as_ee.report_as'

@api.model
def render_html(self, docids, data=None):
    self.model = self.env.context.get('active_model')
    docs = self.env[self.model].browse(self.env.context.get('active_id'))
    as_records = []
    #
    # code that puts records in as_records array
    #
    docargs = {
        'doc_ids': self.ids,
        'doc_model': self.model,
        'docs': docs,
        'time': time,
        'as': as_records
    }
    return self.env['report'].render('report_as_ee.report_as', docargs)
</code>```

Maybe I need to put the name from the .py? How?

Thanks.

答:
you  can do it like this, go to Settings -> Technical ->reports ->reports, select the report of the sales,

Example, Report Quotation / Order. Then open the report and add
 "((object.name or '').replace('/','')+'.pdf')" this to field Printed Report Name.

Check with Quotation/Sale Order Print.

Thanks

Title: ODOO 10 custom report pdf name

Body:
I am developing a custom report in ODOO10 CE and I have a problem naming the generated PDF. It always names the "string" field in the report definition. It ignores the print_report_name field.

Here is the report definition:

<report
    id="action_report_as"
    model="report_as"
    string="Report AS_EE"
    report_type="qweb-pdf"
    name="report_as_ee.report_as"
    paperformat="report.vertical_1"
/>
<record
    id="action_report_as"
    model="ir.actions.report.xml">
    <field name="print_report_name">mycorrectreportname.pdf</field>
</record>

And here is the .py:

class ReportAs(models.AbstractModel):
_name = 'report.report_as_ee.report_as'

@api.model
def render_html(self, docids, data=None):
    self.model = self.env.context.get('active_model')
    docs = self.env[self.model].browse(self.env.context.get('active_id'))
    as_records = []
    #
    # code that puts records in as_records array
    #
    docargs = {
        'doc_ids': self.ids,
        'doc_model': self.model,
        'docs': docs,
        'time': time,
        'as': as_records
    }
    return self.env['report'].render('report_as_ee.report_as', docargs)

Maybe I need to put the name from the .py? How?

Thanks.


问:
How to prevent CSS from displaying the ::after content on a new line?
I'm trying to display a list of names, separated by a comma, using CSS:

a:after {
  content: ', \00a0';
  display: inline-block;
  text-decoration: none;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>Foo
Bar</code>```

The problem is that the result looks something like this:

```<code>Foo, Baz
, Bar
</code>```

答:
You need to add white-space: nowrap; to your a element into the css in order to prevent the comma displaying alone in the next line.

a {
 white-space: nowrap;
}

a:after {
  content: ', \00a0';
  display: inline-block;
  text-decoration: none;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>Foo
Bar
Foo
Bar
Foo
Bar
Foo
Bar
Foo
Bar
Foo
Bar
Foo
Bar
Foo
Bar
Foo
Bar
Foo
Bar</code>```

Body:
I'm trying to display a list of names, separated by a comma, using CSS:

a:after {
  content: ', \00a0';
  display: inline-block;
  text-decoration: none;
}

Foo
Bar

The problem is that the result looks something like this:

Foo, Baz
, Bar

Body:
You need to add white-space: nowrap; to your a element into the css in order to prevent the comma displaying alone in the next line.

a {
 white-space: nowrap;
}

a:after {
  content: ', \00a0';
  display: inline-block;
  text-decoration: none;
}

<a href="foo.com">Foo</a>
<a href="bar.com">Bar</a>
<a href="foo.com">Foo</a>
<a href="bar.com">Bar</a>
<a href="foo.com">Foo</a>
<a href="bar.com">Bar</a>
<a href="foo.com">Foo</a>
<a href="bar.com">Bar</a>
<a href="foo.com">Foo</a>
<a href="bar.com">Bar</a>
<a href="foo.com">Foo</a>
<a href="bar.com">Bar</a>
<a href="foo.com">Foo</a>
<a href="bar.com">Bar</a>
<a href="foo.com">Foo</a>
<a href="bar.com">Bar</a>
<a href="foo.com">Foo</a>
<a href="bar.com">Bar</a>
<a href="foo.com">Foo</a>
<a href="bar.com">Bar</a>


问:
Are there any ways to avoid downtime when NPM goes down? (in this case related to GC App Engine Deployment)
Like many people, I was recently hit by the NPM servers breaking with 429 errors. In my case, Google's App Engine depends on an NPM install for server deployment. As a result of NPM going down, this failed and I was left unable to deploy updates even to our dev environment for several hours.

Whilst GC is very robust, given they can provide no guaruntees (and currently no protection) against this sort of situation, it means very little if the whole system can be taken down by a third party.

I've obviously directed a question towards google about this as well, but I was wondering if anybody else using App Engine or similar products has thoughts on how to mitigate this issue? I don't believe I can simply check in the node modules (and I suspect many would recommend against that) but my knowledge of npm and deployment isn't huge.

I can see there's several other questions related to similar issues, but I haven't been able to find any questions/answers that would help me on the Google App Engine front - at least with my limited understanding of NPM package management.

Thanks

Chris

答:
This is a normal behaviour for App Engine on Node, it has to install the dependencies you specify with the npm install command as mentioned in the documentation here.

As mentioned there, the only "workaround" that comes to mind, would be to specify a yarn.lock so that yarn is used instead of npm.

Hope you find this useful.


问:
Docker - Container cannot be connected to network endpoints
I am getting the following error when running a contaner by attaching to network interfaces test-net, sample-net,bridge0 .
My requirement is to have a container that connects to different containers those are in different networks.

```<code>    docker network create --driver bridge sample-net
    docker container run --name c3 -d --network test-net alpine:latest ping 127.0.0.1
    docker network create --driver bridge --subnet "10.1.0.0/16" test-net
    docker container run --name c4 -d --network test-net alpine:latest ping 127.0.0.1

    docker container run --name c1 -it --rm alpine:latest sh
    docker container run --name c5 -d --network sample-net --network test-net --network docker0 alpine:latest ping 127.0.0.1
</code>```

My intention is to connect "c5" with all other containers by connecting to their interfaces. However , I am facing the error while executing the command

```<code>docker container run --name c5 -d --network sample-net --network test-net --network docker0 alpine:latest ping 127.0.0.1

   docker: Error response from daemon: Container cannot be connected to network endpoints: sample-net, test-net, docker0.
</code>```

答:
It doesnt seem possible to start a container by connecting to multiple networks at once.

From the page https://success.docker.com/article/multiple-docker-networks

Docker only allows a single network to be specified with the docker
run command. To connect multiple networks "docker network connect" is
used to connect additional networks. If a container needs to be
connected to multiple networks before it runs then it is possible to
attach networks to a created container that has not started yet.

And to connect to the default network - in the following example , alpine4 is connected to the default network (along with apline-net) - https://docs.docker.com/network/network-tutorial-standalone/

```<code>docker run -dit --name alpine4 --network alpine-net alpine ash
docker network connect bridge alpine4
</code>```

Body:
I am getting the following error when running a contaner by attaching to network interfaces test-net, sample-net,bridge0 .
My requirement is to have a container that connects to different containers those are in different networks.

    docker network create --driver bridge sample-net
    docker container run --name c3 -d --network test-net alpine:latest ping 127.0.0.1
    docker network create --driver bridge --subnet "10.1.0.0/16" test-net
    docker container run --name c4 -d --network test-net alpine:latest ping 127.0.0.1

    docker container run --name c1 -it --rm alpine:latest sh
    docker container run --name c5 -d --network sample-net --network test-net --network docker0 alpine:latest ping 127.0.0.1

My intention is to connect "c5" with all other containers by connecting to their interfaces. However , I am facing the error while executing the command

docker container run --name c5 -d --network sample-net --network test-net --network docker0 alpine:latest ping 127.0.0.1

   docker: Error response from daemon: Container cannot be connected to network endpoints: sample-net, test-net, docker0.

Body:
It doesnt seem possible to start a container by connecting to multiple networks at once.

From the page https://success.docker.com/article/multiple-docker-networks

Docker only allows a single network to be specified with the docker
run command. To connect multiple networks "docker network connect" is
used to connect additional networks. If a container needs to be
connected to multiple networks before it runs then it is possible to
attach networks to a created container that has not started yet.

And to connect to the default network - in the following example , alpine4 is connected to the default network (along with apline-net) - https://docs.docker.com/network/network-tutorial-standalone/

docker run -dit --name alpine4 --network alpine-net alpine ash
docker network connect bridge alpine4


问:
Create Tensors from Image for ONNX.js
I am trying to use ONNX.js to run a ONNX object detection model in browser. I know that in Tensorflow.js you have to pass only an Image Object to model and Tensorflow automatically create Tensor required by the model, but in ONNX we have to create Tensors from image and then pass it to model.

I read the offical Repository - https://github.com/Microsoft/onnxjs but i can't find any resource on how to create Tensors from image in Javascript.

If anyone knows anything please help ?

I am using following code to run Object Detection in Browser using ONNX.js

```<code><html>

<head> </head>

<body>
    <div onclick="runOD()">
        Run Model
    </div>
    <img src="box.jpg" id="image">

    <!-- Load ONNX.js -->
    <script src="https://cdn.jsdelivr.net/npm/onnxjs/dist/onnx.min.js"></script>
    <!-- Code that consume ONNX.js -->
    <script>
        async function runOD() {
            // Creat the session and load the pre-trained model
            const session = new onnx.InferenceSession({
                backendHint: 'webgl'
            });

            await session.loadModel("./model.onnx");

            //Function to load image to Canvas and Convert it to Tensor
            const preprocessedData = loadImage();

            const inputTensor = new onnx.Tensor(preprocessedData, 'float32', [1, 3, 244, 244]);

            // Run model with Tensor inputs and get the result.
            const outputMap = await session.run([inputTensor]);
            const outputData = outputMap.values().next().value.data;
            console.log(`model output tensor: ${outputData.data}.`);
        }
    </script>
</body>

</html>
</code>```

答:
Following code worked for me

```<code><script>
const imageSize = 416;
var count = 0;

async function runOD() {
    // Creat the session and load the pre-trained model
    const session = new onnx.InferenceSession({
        backendHint: 'webgl'
    });

    await session.loadModel("./model.onnx");

    // Run model with Tensor inputs and get the result.

        // Load image.
        const imageLoader = new ImageLoader(imageSize, imageSize);
        const imageData = await imageLoader.getImageData('./box.jpg');

        // Preprocess the image data to match input dimension requirement
        const width = imageSize;
        const height = imageSize;
        const preprocessedData = preprocess(imageData.data, width, height);

        const inputTensor = new onnx.Tensor(preprocessedData, 'float32', [1, 3, width, height]);
        const outputMap = await session.run([inputTensor]);
        const outputData = outputMap.values().next().value.data;
        var x = outputData.toString();
        var blob = new Blob([x], { type: "text/plain;charset=utf-8" });
        saveAs(blob, "data.txt");

        console.log(outputData);
        count = count+1;
        document.getElementById('count').innerHTML = count;
}
/**
 * Preprocess raw image data to match Resnet50 requirement.
 */
function preprocess(data, width, height) {
    const dataFromImage = ndarray(new Float32Array(data), [width, height, 4]);
    const dataProcessed = ndarray(new Float32Array(width * height * 3), [1, 3, height, width]);

    // Normalize 0-255 to (-1)-1
    ndarray.ops.divseq(dataFromImage, 128.0);
    ndarray.ops.subseq(dataFromImage, 1.0);

    // Realign imageData from [224*224*4] to the correct dimension [1*3*224*224].
    ndarray.ops.assign(dataProcessed.pick(0, 0, null, null), dataFromImage.pick(null, null, 2));
    ndarray.ops.assign(dataProcessed.pick(0, 1, null, null), dataFromImage.pick(null, null, 1));
    ndarray.ops.assign(dataProcessed.pick(0, 2, null, null), dataFromImage.pick(null, null, 0));

    return dataProcessed.data;
}
</code>```

Title: Create Tensors from Image for ONNX.js

Body:
I am trying to use ONNX.js to run a ONNX object detection model in browser. I know that in Tensorflow.js you have to pass only an Image Object to model and Tensorflow automatically create Tensor required by the model, but in ONNX we have to create Tensors from image and then pass it to model.

I read the offical Repository - https://github.com/Microsoft/onnxjs but i can't find any resource on how to create Tensors from image in Javascript.

If anyone knows anything please help ?

I am using following code to run Object Detection in Browser using ONNX.js

        Run Model

Body:
Following code worked for me

<script>
const imageSize = 416;
var count = 0;

async function runOD() {
    // Creat the session and load the pre-trained model
    const session = new onnx.InferenceSession({
        backendHint: 'webgl'
    });

    await session.loadModel("./model.onnx");

    // Run model with Tensor inputs and get the result.

        // Load image.
        const imageLoader = new ImageLoader(imageSize, imageSize);
        const imageData = await imageLoader.getImageData('./box.jpg');

        // Preprocess the image data to match input dimension requirement
        const width = imageSize;
        const height = imageSize;
        const preprocessedData = preprocess(imageData.data, width, height);

        const inputTensor = new onnx.Tensor(preprocessedData, 'float32', [1, 3, width, height]);
        const outputMap = await session.run([inputTensor]);
        const outputData = outputMap.values().next().value.data;
        var x = outputData.toString();
        var blob = new Blob([x], { type: "text/plain;charset=utf-8" });
        saveAs(blob, "data.txt");

        console.log(outputData);
        count = count+1;
        document.getElementById('count').innerHTML = count;
}
/**
 * Preprocess raw image data to match Resnet50 requirement.
 */
function preprocess(data, width, height) {
    const dataFromImage = ndarray(new Float32Array(data), [width, height, 4]);
    const dataProcessed = ndarray(new Float32Array(width * height * 3), [1, 3, height, width]);

    // Normalize 0-255 to (-1)-1
    ndarray.ops.divseq(dataFromImage, 128.0);
    ndarray.ops.subseq(dataFromImage, 1.0);

    // Realign imageData from [224*224*4] to the correct dimension [1*3*224*224].
    ndarray.ops.assign(dataProcessed.pick(0, 0, null, null), dataFromImage.pick(null, null, 2));
    ndarray.ops.assign(dataProcessed.pick(0, 1, null, null), dataFromImage.pick(null, null, 1));
    ndarray.ops.assign(dataProcessed.pick(0, 2, null, null), dataFromImage.pick(null, null, 0));

    return dataProcessed.data;
}


问:
Is it possible to make shared_ptr covariant?
I tried to make the following example.

```<code>struct BaseSPtr{};
struct DerivedSPtr : public BaseSPtr{};

class Base{
    public:
    //virtual shared_ptr<BaseSPtr> function();
    virtual BaseSPtr* function();
};

class Derived : public Base
{
    public:
    //shared_ptr<DerivedSPtr> function() override;
    DerivedSPtr* function() override;
};
</code>```

Can someone tell me if is it possible to make the example with shared_ptr valid?

答:
Now question is how do you use Derived class?

do you use it explicitly and polymorphic call function() is not performed?

or do you keep this factory in some storage and function() is called in polymorphic way

or do you use this in some templates

In first case just provide function with different name, then you can invoke this function when pointer to derived class is needed.

In second case you should not try convince compiler that you return derived class since polymorphic call will hide this anyway.

In last case just use CRTP as other answer suggested (some call this static polymorphism) and drop virtual keyword.

Body:
I tried to make the following example.

struct BaseSPtr{};
struct DerivedSPtr : public BaseSPtr{};

class Base{
    public:
    //virtual shared_ptr<BaseSPtr> function();
    virtual BaseSPtr* function();
};

class Derived : public Base
{
    public:
    //shared_ptr<DerivedSPtr> function() override;
    DerivedSPtr* function() override;
};

Can someone tell me if is it possible to make the example with shared_ptr valid?


问:
Sorting photos exactly like native photoapp using PhotoKit
I am trying to reproduce the native iOS8 photopicker using Photos framework. I got a problem with the sorting.

Lets say I do following:

I edit a photo in Camera+ app and save it back to gallery.

I favourite another photo.

In the native photopicker:

All photos (even the one I favourited) will be sorted by creationDate

The photo I edited and saved will be down at the bottom since it was the last one I changed. The original will be at its original place according to its creation date.

In my app I do following:

```<code>PHFetchOptions *options = [PHFetchOptions new];
options.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"creationDate" ascending:YES]];
options.predicate = [NSPredicate predicateWithFormat:@"mediaType == %ld", PHAssetMediaTypeImage];
PHFetchResult *fetchResult = [PHAsset fetchAssetsInAssetCollection:self.assetCollection options:options];
</code>```

I sort in creationDate and get following result:

All photos (even the one I favourited) will be sorted by creationDate

The photo I edited will be just after at it's original according to it's original creation date.

Then I change my query so instead of sorting on creationDate, I sort on modificationDate. I get following result:

All photos are in general in order almost same as creationDate

The photo I edited will be at the bottom. This is what I want and like in the native app.

The favourited photo will also be at the bottom :-(

So it seeme Apple change modificationDate on favourite action and probably also on other kind of actions and this mess up the sorting of the photos.

How is it possible to get exactly the sorting Apple use in its native app? Maybe some clever use of NSSortDescriptor?

答:
Dont ask me why and how, but when I set that sort description. It works like Photos application (Recents).

```<code>        [options setSortDescriptors:@[[NSSortDescriptor sortDescriptorWithKey:@"burstIdentifier" ascending:NO]]];
</code>```

Try it.

Body:
I am trying to reproduce the native iOS8 photopicker using Photos framework. I got a problem with the sorting.

Lets say I do following:

I edit a photo in Camera+ app and save it back to gallery.

I favourite another photo.

In the native photopicker:

All photos (even the one I favourited) will be sorted by creationDate

The photo I edited and saved will be down at the bottom since it was the last one I changed. The original will be at its original place according to its creation date.

In my app I do following:

PHFetchOptions *options = [PHFetchOptions new];
options.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"creationDate" ascending:YES]];
options.predicate = [NSPredicate predicateWithFormat:@"mediaType == %ld", PHAssetMediaTypeImage];
PHFetchResult *fetchResult = [PHAsset fetchAssetsInAssetCollection:self.assetCollection options:options];

I sort in creationDate and get following result:

All photos (even the one I favourited) will be sorted by creationDate

The photo I edited will be just after at it's original according to it's original creation date.

Then I change my query so instead of sorting on creationDate, I sort on modificationDate. I get following result:

All photos are in general in order almost same as creationDate

The photo I edited will be at the bottom. This is what I want and like in the native app.

The favourited photo will also be at the bottom :-(

So it seeme Apple change modificationDate on favourite action and probably also on other kind of actions and this mess up the sorting of the photos.

How is it possible to get exactly the sorting Apple use in its native app? Maybe some clever use of NSSortDescriptor?

Body:
Dont ask me why and how, but when I set that sort description. It works like Photos application (Recents).

        [options setSortDescriptors:@[[NSSortDescriptor sortDescriptorWithKey:@"burstIdentifier" ascending:NO]]];

Try it.


问:
Background image repeate full height of page?
How can I have a background image repeat the full length of the page?

Ive applied a repeating background image to the body but by default it only extends down as far as the page's content.

If I set the body and html to be height 100% with 0 margin and padding, then the background repeats the full height but now scroll bars appear. I can fix this with overflow: hidden; set to body, but im worried about unintended conciseness of this cross device, etc.

Thanks

答:
Have you tried using overflow auto?

http://jsfiddle.net/easwee/hJsnW/4/

```<code>html, body {margin:0;padding:0;height:100%;background:url(http://jsfiddle.net/img/top-bg.png) repeat-y 0 0;overflow:auto;}
</code>```

Body:
Have you tried using overflow auto?

http://jsfiddle.net/easwee/hJsnW/4/

html, body {margin:0;padding:0;height:100%;background:url(http://jsfiddle.net/img/top-bg.png) repeat-y 0 0;overflow:auto;}


问:
Switch Between Bootstrap Modals
I have setup my rails 4 app to run with bootstrap 3 and devise.

I have customised the devise sign up and sign in views so that they are now inside bootstrap modals. However, despite using the shared items, which includes a "Not a member? sign up here" link, it doesn't appear in the login modal.

When I copy and paste that code directly in the modal, the register modal is displayed within the login modal. The buttons don't work and it looks awful.

Does anyone know how to create a link, for example "Not a member? sign up here" that will cause the login modal to close and the register modal to open?

Thank you.

答:
Modal Switch Bootstrap 4 without Script

FIX: Does anyone know how to create a link, for example "forgot
  password?" that will cause the login modal to close and the forgot
  password modal to open?

You can simply switch modal using bootstrap attribute.

You just have add this code in button or any element which you want, data-dismiss will close your modal and the data-target will open your second modal, also you can check demo which link i have shared below.

```<code><button type="button" class="btn btn-danger" data-dismiss="modal" data-toggle="modal" data-target="#Second_modal">Switch Modal</button>
</code>```

https://codepen.io/shabbirvaghela/pen/rNVMBNJ

Title: Switch Between Bootstrap Modals

Body:
Modal Switch Bootstrap 4 without Script

FIX: Does anyone know how to create a link, for example "forgot
  password?" that will cause the login modal to close and the forgot
  password modal to open?

You can simply switch modal using bootstrap attribute.

You just have add this code in button or any element which you want, data-dismiss will close your modal and the data-target will open your second modal, also you can check demo which link i have shared below.

<button type="button" class="btn btn-danger" data-dismiss="modal" data-toggle="modal" data-target="#Second_modal">Switch Modal</button>

https://codepen.io/shabbirvaghela/pen/rNVMBNJ


问:
Performance for pixel point transformations
So I'm using numpy and OpenCV to process a few videos. The problem I'm having is using a lookup table to do a point transformation on the pixel values:

```<code>def sig(x,factor):
    if x == 255:
        return 255
    elif x!=0:
        return int(255*(1- 1/(1+(255/x -1)**(-factor))))
    else:
        return 0

def Constrast(img):
    global LUT
    for x in range(len(img)):
        for y in range(len(img[0])):
            img[x,y] = LUT[img[x,y]]
    return img

 def Enhance(img):
    img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    #Some other functions here
    img = Constrast(img) # This one thing takes 0.3 seconds
    #Do more stuff here

factor = .8
LUT = []
for i in range(256):
    LUT.append(sig(i,factor))
Enhance(img) # Enhancing a greyscale image
</code>```

The reason I am using a global variable is because my contrast function is nested in other functions. I have tested using LUT as an argument to these functions and it turned out slower. I have used numpy arrays, dictionaries, arrays from the array module and lists, with the latter being the fastest. So far I'm managing 0.3s on every image. Is there an obvious way of making the process of looping through pixels  quicker?

Thanks in advance.

答:
Do not loop over the pixels. Use OpenCV functionality to perform the transformation in one call. As a general rule-of-thumb, always try to avoid looping over pixels with OpenCV, and with Python, and especially with both.

An example how your code could be adapted:

```<code>def Constrat(img):
    global LUT
    img = cv2.LUT(img, LUT)
    return img
</code>```

See the answer here and relevant documentation.

Body:
So I'm using numpy and OpenCV to process a few videos. The problem I'm having is using a lookup table to do a point transformation on the pixel values:

def sig(x,factor):
    if x == 255:
        return 255
    elif x!=0:
        return int(255*(1- 1/(1+(255/x -1)**(-factor))))
    else:
        return 0

def Constrast(img):
    global LUT
    for x in range(len(img)):
        for y in range(len(img[0])):
            img[x,y] = LUT[img[x,y]]
    return img

 def Enhance(img):
    img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    #Some other functions here
    img = Constrast(img) # This one thing takes 0.3 seconds
    #Do more stuff here

factor = .8
LUT = []
for i in range(256):
    LUT.append(sig(i,factor))
Enhance(img) # Enhancing a greyscale image

The reason I am using a global variable is because my contrast function is nested in other functions. I have tested using LUT as an argument to these functions and it turned out slower. I have used numpy arrays, dictionaries, arrays from the array module and lists, with the latter being the fastest. So far I'm managing 0.3s on every image. Is there an obvious way of making the process of looping through pixels  quicker?

Thanks in advance.

Body:
Do not loop over the pixels. Use OpenCV functionality to perform the transformation in one call. As a general rule-of-thumb, always try to avoid looping over pixels with OpenCV, and with Python, and especially with both.

An example how your code could be adapted:

def Constrat(img):
    global LUT
    img = cv2.LUT(img, LUT)
    return img

See the answer here and relevant documentation.