问:
Legend order in barplot
I hope you are doing well.

I am using barplot()

```<code>allvax <- table(data$vaxtype, data$vaxdate)

barplot(allvax,
    ylim = c(0,18000),
    main = "Vaccination January 2021 to February 2022", xlab = "Mois", ylab = "Patients",
    col = c("red","indianred1","indianred2","indianred3","blue", "cyan", "cyan3","lightcyan1"),
    legend.text = TRUE,
    args.legend = list(x = "topright", bty="n", cex = 0.8, ncol = 2),

    )
</code>```

I would like to change the order of the legend for esthetic purpose. How can I change the order changing the order from 8-7-6-5-4-3-2-1 to 1-2-3-4-5-6-7.

答:
Given you didn't posted an example data, here is an overall solution:

```<code>barplot(df)
legend("topright", legend = df[,1])
</code>```

With df being your dataframe, and df[,1] being the column you want to base the legend on.

ps: you can alter the colors with the argument fill inside legend()

Title: Legend order in barplot

Body:
I hope you are doing well.

I am using barplot()

allvax <- table(data$vaxtype, data$vaxdate)

barplot(allvax,
    ylim = c(0,18000),
    main = "Vaccination January 2021 to February 2022", xlab = "Mois", ylab = "Patients",
    col = c("red","indianred1","indianred2","indianred3","blue", "cyan", "cyan3","lightcyan1"),
    legend.text = TRUE,
    args.legend = list(x = "topright", bty="n", cex = 0.8, ncol = 2),

    )

I would like to change the order of the legend for esthetic purpose. How can I change the order changing the order from 8-7-6-5-4-3-2-1 to 1-2-3-4-5-6-7.

Body:
Given you didn't posted an example data, here is an overall solution:

barplot(df)
legend("topright", legend = df[,1])

With df being your dataframe, and df[,1] being the column you want to base the legend on.

ps: you can alter the colors with the argument fill inside legend()


来源: stackexchange

问:
NoReverseMatch at reset_password_complete: Django PasswordResetConfirmView
I am using Django's default password reset views and forms to send an email to the user for them to reset their password via a link in the email. I have most of the development complete but am stuck on one issue. When I receive the email from the local host, I click the link, enter my new password 2 times, hit 'submit' and get this error: Error Message.

Below is my code.
urls.py

```<code>
"""defines URL patterns for users"""

from django.urls import path, include, reverse_lazy
from django.contrib.auth import views as auth_views
from . import views
app_name = 'users'

urlpatterns = [
    # include all default auth urls
    path('', include('django.contrib.auth.urls')),
    path('register/', views.register, name='register'),
    path(
        'reset_password/',
        auth_views.PasswordResetView.as_view(
            template_name='registration/password_reset.html',
            success_url=reverse_lazy('users:password_reset_done')
            ) ,
            name='reset_password'
    ),
    path(
        'reset/<uidb64>/<token>/',
        auth_views.PasswordResetConfirmView.as_view(
            template_name='registration/password_reset_form.html',
            success_url=reverse_lazy('users:password_reset_complete')
            ),
            name='password_reset_confirm'
    ),
    path(
        'password_reset_done/',
        auth_views.PasswordResetDoneView.as_view(
            template_name="registration/password_reset_sent.html"),
            name='password_reset_done'
    ),
    path(
        'password_reset_complete/',
        auth_views.PasswordResetCompleteView.as_view(
            template_name='registration/password_reset_done.html'),
            name='password_reset_complete'
    ),
    path('forgot_username/', views.forgot_username, name="forgot_username"),
    path('username_retrieval/', views.username_retrieval, name="username_retrieval"),
]

</code>```

As you can see, I am using the namespace 'users' in the success_url variable, however, it seems to work on the reset_password path, but it does not seem to work on the reset/<uidb64>/<token> path.

One thing to be aware of is that I have a custom user model in my application. Would that affect my ability to use this default Django password reset method?

In addition, here are my templates under the users/templates/registration/ folder: User App Templates

Some other things to mention:
When I click on the link from my email, I am directed to password_reset_confirm and not password_reset_form so that tells me that the template name is not being overwritten as well.

When I change
success_url=reverse_lazy('users:password_reset_complete')
to
success_url=reverse_lazy('users:password_reset_completed')
the app doesn't look for users:password_reset_completed so that implies that the success_url is not being overwritten.

Any help would be appreciated and I can post more code and answer questions if necessary.

Thanks in advance!

答:
this line is overwriting all your paths:

```<code>    path('', include('django.contrib.auth.urls')),
</code>```

just remove it or if you want to keep some of them place it at the end after your paths

ContentLicense: CC BY-SA 4.0

Body:
I am using Django's default password reset views and forms to send an email to the user for them to reset their password via a link in the email. I have most of the development complete but am stuck on one issue. When I receive the email from the local host, I click the link, enter my new password 2 times, hit 'submit' and get this error: Error Message.

Below is my code.
urls.py

"""defines URL patterns for users"""

from django.urls import path, include, reverse_lazy
from django.contrib.auth import views as auth_views
from . import views
app_name = 'users'

urlpatterns = [
    # include all default auth urls
    path('', include('django.contrib.auth.urls')),
    path('register/', views.register, name='register'),
    path(
        'reset_password/',
        auth_views.PasswordResetView.as_view(
            template_name='registration/password_reset.html',
            success_url=reverse_lazy('users:password_reset_done')
            ) ,
            name='reset_password'
    ),
    path(
        'reset/<uidb64>/<token>/',
        auth_views.PasswordResetConfirmView.as_view(
            template_name='registration/password_reset_form.html',
            success_url=reverse_lazy('users:password_reset_complete')
            ),
            name='password_reset_confirm'
    ),
    path(
        'password_reset_done/',
        auth_views.PasswordResetDoneView.as_view(
            template_name="registration/password_reset_sent.html"),
            name='password_reset_done'
    ),
    path(
        'password_reset_complete/',
        auth_views.PasswordResetCompleteView.as_view(
            template_name='registration/password_reset_done.html'),
            name='password_reset_complete'
    ),
    path('forgot_username/', views.forgot_username, name="forgot_username"),
    path('username_retrieval/', views.username_retrieval, name="username_retrieval"),
]

As you can see, I am using the namespace 'users' in the success_url variable, however, it seems to work on the reset_password path, but it does not seem to work on the reset/<uidb64>/<token> path.

One thing to be aware of is that I have a custom user model in my application. Would that affect my ability to use this default Django password reset method?

In addition, here are my templates under the users/templates/registration/ folder: User App Templates

Some other things to mention:
When I click on the link from my email, I am directed to password_reset_confirm and not password_reset_form so that tells me that the template name is not being overwritten as well.

When I change
success_url=reverse_lazy('users:password_reset_complete')
to
success_url=reverse_lazy('users:password_reset_completed')
the app doesn't look for users:password_reset_completed so that implies that the success_url is not being overwritten.

Any help would be appreciated and I can post more code and answer questions if necessary.

Thanks in advance!

Body:
this line is overwriting all your paths:

    path('', include('django.contrib.auth.urls')),

just remove it or if you want to keep some of them place it at the end after your paths


问:
Change color of the IconComponent of Material UI's Select Component
For my project, I'm using MUI's Select Component with the LanguageIcon as the IconComponent.

What I'm trying to do is turn this icon white (it's black per default), but I can't get it to work.

I tried to follow this solution, but it won't work for me.

import { makeStyles } from '@mui/styles'; throws "Module not found: Can't resolve '@mui/styles'" and on their website it says @mui/styles is deprecated.

This is what I currently have:

import * as React from 'react';
import { FunctionComponent } from 'react';
import MenuItem from "@mui/material/MenuItem";
import FormControl from "@mui/material/FormControl";
import Select, {SelectChangeEvent} from "@mui/material/Select";
import { useRouter } from 'next/dist/client/router';
import LanguageIcon from '@mui/icons-material/Language';

const LocaleSelect: FunctionComponent = () => {

  const router = useRouter()
  const {locale, locales, pathname, asPath, query} = router;

  const handleLocaleChange = (event: SelectChangeEvent<string>) => {
    router.push({ pathname, query }, asPath, { locale: event.target.value})
  }

  return(
    <FormControl
      variant='standard'
      sx={{ m: 1, maxWidth: 32 }}
      color="primary" >

      <Select
        disableUnderline
        labelId="demo-simple-select-autowidth-label"
        id="demo-simple-select-autowidth"
        value={locale?.toLocaleUpperCase()}
        onChange={handleLocaleChange}
        autoWidth
        IconComponent={LanguageIcon} >
        {locales?.map((l) => {
          return <MenuItem key={l} value={l}>
            {l.toLocaleUpperCase()}</MenuItem>;
        })}
      </Select>
    </FormControl>
  )
}

export default LocaleSelect
```
<p>This makes it look like this.</p>
<p>I managed to make the globe white by using</p>
<pre class="lang-ts prettyprint-override"><code>IconComponent={() => <LanguageIcon htmlColor='white'/>}
</code>```

but that moves the globe to the right.

Any help would be fantastic; either by making the globe white or by moving it to the left.

答:
You can do something like this.

```<code> <LanguageIcon
      htmlColor="white"
      sx={{ position: "absolute", left: ".5rem",cursor:'pointer',zIndex:-1 }}
 />
</code>```

Position absolute makes it easy to align the icon where you want but the icon becomes un-clickable. To solve this I added cursor:pointer which partially solved the issue but wasn't able to click yet. Hence I reduced the z-index.

Reducing the z-index works because, clicking on icon actually clicks the parent and then displays the options.

Body:
For my project, I'm using MUI's Select Component with the LanguageIcon as the IconComponent.

What I'm trying to do is turn this icon white (it's black per default), but I can't get it to work.

I tried to follow this solution, but it won't work for me.

import { makeStyles } from '@mui/styles'; throws "Module not found: Can't resolve '@mui/styles'" and on their website it says @mui/styles is deprecated.

This is what I currently have:

import * as React from 'react';
import { FunctionComponent } from 'react';
import MenuItem from "@mui/material/MenuItem";
import FormControl from "@mui/material/FormControl";
import Select, {SelectChangeEvent} from "@mui/material/Select";
import { useRouter } from 'next/dist/client/router';
import LanguageIcon from '@mui/icons-material/Language';

const LocaleSelect: FunctionComponent = () => {

  const router = useRouter()
  const {locale, locales, pathname, asPath, query} = router;

  const handleLocaleChange = (event: SelectChangeEvent<string>) => {
    router.push({ pathname, query }, asPath, { locale: event.target.value})
  }

  return(
    <FormControl
      variant='standard'
      sx={{ m: 1, maxWidth: 32 }}
      color="primary" >

      <Select
        disableUnderline
        labelId="demo-simple-select-autowidth-label"
        id="demo-simple-select-autowidth"
        value={locale?.toLocaleUpperCase()}
        onChange={handleLocaleChange}
        autoWidth
        IconComponent={LanguageIcon} >
        {locales?.map((l) => {
          return <MenuItem key={l} value={l}>
            {l.toLocaleUpperCase()}</MenuItem>;
        })}
      </Select>
    </FormControl>
  )
}

export default LocaleSelect

This makes it look like this.

I managed to make the globe white by using

IconComponent={() => <LanguageIcon htmlColor='white'/>}

but that moves the globe to the right.

Any help would be fantastic; either by making the globe white or by moving it to the left.

Body:
You can do something like this.

 <LanguageIcon
      htmlColor="white"
      sx={{ position: "absolute", left: ".5rem",cursor:'pointer',zIndex:-1 }}
 />

Position absolute makes it easy to align the icon where you want but the icon becomes un-clickable. To solve this I added cursor:pointer which partially solved the issue but wasn't able to click yet. Hence I reduced the z-index.

Reducing the z-index works because, clicking on icon actually clicks the parent and then displays the options.


问:
Why do I get: "Error: cannot find module sass" when I run "gulp" in terminal?
I'm trying to run a gulp task but when I go to Terminal > Run Task... > gulp it says No gulp task found. I run gulp in the terminal and I get the title's error.

which sass: /home/username/.nvm/versions/node/v17.4.0/bin/sass.

which node: /home/username/.nvm/versions/node/v17.4.0/bin/node.

which gulp: /home/username/.nvm/versions/node/v17.4.0/bin/gulp.

Gulp version:

```<code>CLI version: 2.3.0
Local version: 4.0.2
</code>```

Gulp sass version: ^5.1.0.

My gulpfile.js; is in the root folder (as my styles.scss, styles.css, styles.min.css, package.json, package-lock.json and node_modules/), with the code:

```<code>// Sass configuration
var gulp = require('gulp');
var sass = require('gulp-sass')(require('sass'));

gulp.task('sass', function(cb) {
  gulp
    .src('*.scss')
    .pipe(sass())
    .pipe(
      gulp.dest(function(f) {
        return f.base;
      })
    );
  cb();
});

gulp.task(
  'default',
  gulp.series('sass', function(cb) {
    gulp.watch('*.scss', gulp.series('sass'));
    cb();
  })
);
</code>```

I removed and re-installed gulp and gulp-sass but the result is the same.

I'm following these steps.

答: I fixed the problem by adding npm i --save-dev sass.

Body:
I'm trying to run a gulp task but when I go to Terminal > Run Task... > gulp it says No gulp task found. I run gulp in the terminal and I get the title's error.

which sass: /home/username/.nvm/versions/node/v17.4.0/bin/sass.

which node: /home/username/.nvm/versions/node/v17.4.0/bin/node.

which gulp: /home/username/.nvm/versions/node/v17.4.0/bin/gulp.

Gulp version:

CLI version: 2.3.0
Local version: 4.0.2

Gulp sass version: ^5.1.0.

My gulpfile.js; is in the root folder (as my styles.scss, styles.css, styles.min.css, package.json, package-lock.json and node_modules/), with the code:

// Sass configuration
var gulp = require('gulp');
var sass = require('gulp-sass')(require('sass'));

gulp.task('sass', function(cb) {
  gulp
    .src('*.scss')
    .pipe(sass())
    .pipe(
      gulp.dest(function(f) {
        return f.base;
      })
    );
  cb();
});

gulp.task(
  'default',
  gulp.series('sass', function(cb) {
    gulp.watch('*.scss', gulp.series('sass'));
    cb();
  })
);

I removed and re-installed gulp and gulp-sass but the result is the same.

I'm following these steps.


问:
UILocalizedIndexedCollation only returns an English collation
I'm trying to get a localized index like Contacts by using UILocalizedIndexedCollation. In Contacts when I change the language the index changes to match the language. However sectionIndexTitles always returns an english index.

I have tried this with a demo app I created and with 3_SimpleIndexedTableView, which is a demo app from Apple and neither app have a localized index.

I have tried creating a localization folder for the current locale (I used [[NSLocale autoupdatingCurrentLocale] localeIdentifier] to determine the current locale). This does not affect the index.

I've had a look for relevant plist settings by found nothing.

Am I missing something or does UILocalizedIndexedCollation only return an English collation?

答:
You can also set Localized resources can be mixed = YES in Info.plist.
If the key is missing right click and choose Add Row.

ContentLicense: CC BY-SA 3.0


问:
SwiftUI Core Data: Best way to access children array?
What is the best / most efficient way to access core data children in a multilevel one-to-many model?

I have a model with Board > List > Card > ..., always in a one-to-many relation.
At the start view all Boards are fetched.

Let's say we are in the SingleListView, looking at all cards from one List, that has been passed in. Now I can either directly use the Core Data class accessor from the list (NSSet transformed to Array):

```<code>@ObservedObject var list: ListEntity
...
ForEach(list.cardsArray) {
    ....
</code>```

or I can fetch the cards with predicate

```<code>@FetchRequest
private var cards: FetchedResults<CardEntity>

init(list: ListEntity) {
    _cards = FetchRequest<CardEntity>(
        sortDescriptors: [ ... ],
        predicate: NSPredicate(format: "ofList == %@", list),
        animation: .default)
}
</code>```

Is any of these better, more appropriate, more efficient towards view updates ... ?

Especially when I go deeper into the tree structure, it feels strange that all is relying on one first FetchRequest up the chain.

答: Overall it is best to use another @FetchRequest to fetch the child objects using the parent in the predicate, that is why we have inverse relations and means you can benefit to change tracking of the relation objects. However you will also need to wrap this child View inside an intermediate View so that when the parent View's body runs and inits all the child Views it doesn't needlessly re-fetch all the child fetch requests. This is because although @FetchRequest is a property wrapper, unlike @State it causes body to run every time its View is init, so you want to avoid that with the wrapper view that will not re-run the body when its the same parent object passed in. You can turn on SQL debugging to check what queries are hitting the database.

Body:
What is the best / most efficient way to access core data children in a multilevel one-to-many model?

I have a model with Board > List > Card > ..., always in a one-to-many relation.
At the start view all Boards are fetched.

Let's say we are in the SingleListView, looking at all cards from one List, that has been passed in. Now I can either directly use the Core Data class accessor from the list (NSSet transformed to Array):

@ObservedObject var list: ListEntity
...
ForEach(list.cardsArray) {
    ....

or I can fetch the cards with predicate

@FetchRequest
private var cards: FetchedResults<CardEntity>

init(list: ListEntity) {
    _cards = FetchRequest<CardEntity>(
        sortDescriptors: [ ... ],
        predicate: NSPredicate(format: "ofList == %@", list),
        animation: .default)
}

Is any of these better, more appropriate, more efficient towards view updates ... ?

Especially when I go deeper into the tree structure, it feels strange that all is relying on one first FetchRequest up the chain.


问:
Inserting PHP variables into MySQL query
I have some source code for a Payroll Management System that I am altering to use for an Overtime management system. I altered a MySQL select query to filter the employees based on the selected department. Now I am trying to pass the value of the "Department" drop down list into the SELECT query that is being ran (WHERE department_id = ?). I tried following some tips and code from other posts, but they have not worked so far. I try running the code, but get an error that says "Commands out of sync..." on line 27 ($result = $employee->get_result();). I am not sure if my code is wrong, or if it is trying to execute before the department drop down list has been selected?

This is how I am wanting the code to work:

Select a department from the Department drop down list. (Starting line 6 in the code)

The value of the department drop down list is passed into the Employee drop down list SELECT query, which shows the user only employees for the selected department. (Around line 24 of the code)

<?php include 'db_connect.php' ?>
<?php ?>

<form action="" id="employee-overtime">

            Department
            <select id="department" class="borwser-default select2">
                <option value=""></option>
                <?php
                $department = $conn->query("SELECT department_id, name FROM employee INNER
JOIN department on department.id = employee.department_id");
                while($row = $department->fetch_assoc()):
                ?>
                    <option value="<?php echo $row['department_id'] ?>"><?php echo
$row['name'] ?></option>
                <?php endwhile; ?>
            </select>

            Employee
            <select id="employee_id" class="borwser-default select2">
                <option value=""></option>
                <?php
                $employee = $conn->prepare("SELECT *,concat(lastname,', ',firstname,'
',middlename) as ename FROM employee WHERE department_id = ? order by concat(lastname,',
',firstname,' ',middlename) asc");
                $result = $employee->get_result();
                while($row = $result->fetch_assoc()):
                ?>
                    <option value="<?php echo $row['id'] ?>"><?php echo $row['ename'] . ' | '.
$row['employee_no'] ?></option>
                <?php endwhile; ?>
            </select>

```

答:
You're getting the error because you're missing a bind_param() statement that provides a value for the ? in $conn->prepare(...).

```<code>$employee->bind_param('s', $selectedDepartment);
</code>```

Which brings up the question where you're going to get $selectedDepartment.

Your script doesn't seem to reflect the fact that when the page loads for the first time, there is no selected department. So there can be no select box listing employees of that department.
Also, the user may submit the form with no department selected because the first option is <option value=""></option>.

Only after you submit the form with your department choice, can you read it on the server in $_GET[] array. For that, add some name to the department SELECT box. (attribute id is not used for this.)

```<code><select name="department" id="department" class="borwser-default select2">
</code>```

Then you'll be able to read the selected department in $_GET['department'].

So to put all this together, first add if (!empty($_GET['department'])) {} statement around the area that shows employee select box:

```<code><?php
if (!empty($_GET['department'])) {
?>
<div class="col-md-4">
       <label for="" class="control-label">Employee</label>
...
</div>
<?php
}
?>
</code>```

Then add bind_param() after the employee query:

```<code>$employee = $conn->prepare("SELECT ... FROM ... WHERE department_id = ? order by ...");
$employee->bind_param('s', $_GET['department']);
$result = $employee->get_result();
</code>```

Body:
You're getting the error because you're missing a bind_param() statement that provides a value for the ? in $conn->prepare(...).

$employee->bind_param('s', $selectedDepartment);

Which brings up the question where you're going to get $selectedDepartment.

Your script doesn't seem to reflect the fact that when the page loads for the first time, there is no selected department. So there can be no select box listing employees of that department.
Also, the user may submit the form with no department selected because the first option is <option value=""></option>.

Only after you submit the form with your department choice, can you read it on the server in $_GET[] array. For that, add some name to the department SELECT box. (attribute id is not used for this.)

<select name="department" id="department" class="borwser-default select2">

Then you'll be able to read the selected department in $_GET['department'].

So to put all this together, first add if (!empty($_GET['department'])) {} statement around the area that shows employee select box:

<?php
if (!empty($_GET['department'])) {
?>
<div class="col-md-4">
       <label for="" class="control-label">Employee</label>
...
</div>
<?php
}
?>

Then add bind_param() after the employee query:

$employee = $conn->prepare("SELECT ... FROM ... WHERE department_id = ? order by ...");
$employee->bind_param('s', $_GET['department']);
$result = $employee->get_result();


问:
What is the use of of_device_id and i2c_device_id?
I was understanding an I2C driver for adxl34x sensor.
If I only keep of_device_id, my probe does not gets called, but if I include i2c_device_id probe gets called.
I checked for some explanation but I get to know that i2c_device_id is used for legacy purpose or board file matching.
Here I am using device tree.
How is it possible that i2c_device_id is making the device recognised?
Is there a dependency in I2C drivers to use both i2c_Device_id and of_device_id??
here is my understanding on this top
 id_table is used for legacy i2c devices. See in this code

```<code>static const struct i2c_device_id *i2c_match_id(const struct i2c_device_id *id,
                        const struct i2c_client *client)
{
    while (id->name[0]) {
        if (strcmp(client->name, id->name) == 0)
            return id;
        id++;
    }
    return NULL;
}
</code>```

There is no device id table reference, while of_device_id

```<code>/**
 * of_match_device - Tell if a struct device matches an of_device_id list
 * @ids: array of of device match structures to search in
 * @dev: the of device structure to match against
 *
 * Used by a driver to check whether an platform_device present in the
 * system is in its list of supported devices.
 */
const struct of_device_id *of_match_device(const struct of_device_id *matches,
                       const struct device *dev)
{
    if ((!matches) || (!dev->of_node))
        return NULL;
    return of_match_node(matches, dev->of_node);
}
</code>```

Uses dev->of_node

So its safe to say both mechanism are isolated and does not depend on each other.
Then why my driver is not getting probed by only using this,

```<code>/*
 static const struct i2c_device_id adxl34x_id[] = {
    { "adxl345", 0 },
    { }
};

MODULE_DEVICE_TABLE(i2c, adxl34x_id);
*/

#ifdef CONFIG_OF
static const struct of_device_id adxl34x_of_id[] = {
    /*
     * The ADXL346 is backward-compatible with the ADXL345. Differences are
     * handled by runtime detection of the device model, there's thus no
     * need for listing the "adi,adxl346" compatible value explicitly.
     */
    { .compatible = "adi,adxl345", },
    /*
     * Deprecated, DT nodes should use one or more of the device-specific
     * compatible values "adi,adxl345" and "adi,adxl346".
     */
    { .compatible = "adi,adxl34x", },
    { }
};

MODULE_DEVICE_TABLE(of, adxl34x_of_id);
#endif

static struct i2c_driver adxl34x_driver = {
    .driver = {
        .name = "adxl34x",
        //.pm = &adxl34x_i2c_pm,
        .of_match_table = of_match_ptr(adxl34x_of_id),
    },
    .probe    = adxl34x_i2c_probe,
    .remove   = adxl34x_i2c_remove,
    //.id_table = adxl34x_id, /*commented i2c_device_id*/
};
</code>```

Here are some links that I have gone through in order to get some understanding

https://patches.linaro.org/patch/16873/

https://lists.ozlabs.org/pipermail/linuxppc-dev/2015-July/131965.html

https://i2c.wiki.kernel.org/index.php/OF_Modalias

I understood that first of_* style match will happen, then i2c_device_id type match.

In my case, then how of_* is not able to bind then?

Why i2c_device_table is needed if its legacy thing?

答:
You are right. It is true that you need to pass id_table along with the driver structure for I2C if you are using probe callback.

This is because the earlier I2C driver framework used older style of probe function signature that required i2c_device_id to be passed as the second parameter. However, this has now been replaced with i2c_probe_new callback whose function signature shows that it no more needs i2c_device_id parameter anymore.

Here is a link to this code change for reference:
https://elixir.bootlin.com/linux/v5.16.9/source/include/linux/i2c.h#L281

Body:
I was understanding an I2C driver for adxl34x sensor.
If I only keep of_device_id, my probe does not gets called, but if I include i2c_device_id probe gets called.
I checked for some explanation but I get to know that i2c_device_id is used for legacy purpose or board file matching.
Here I am using device tree.
How is it possible that i2c_device_id is making the device recognised?
Is there a dependency in I2C drivers to use both i2c_Device_id and of_device_id??
here is my understanding on this top
 id_table is used for legacy i2c devices. See in this code

static const struct i2c_device_id *i2c_match_id(const struct i2c_device_id *id,
                        const struct i2c_client *client)
{
    while (id->name[0]) {
        if (strcmp(client->name, id->name) == 0)
            return id;
        id++;
    }
    return NULL;
}

There is no device id table reference, while of_device_id

/**
 * of_match_device - Tell if a struct device matches an of_device_id list
 * @ids: array of of device match structures to search in
 * @dev: the of device structure to match against
 *
 * Used by a driver to check whether an platform_device present in the
 * system is in its list of supported devices.
 */
const struct of_device_id *of_match_device(const struct of_device_id *matches,
                       const struct device *dev)
{
    if ((!matches) || (!dev->of_node))
        return NULL;
    return of_match_node(matches, dev->of_node);
}

Uses dev->of_node

So its safe to say both mechanism are isolated and does not depend on each other.
Then why my driver is not getting probed by only using this,

/*
 static const struct i2c_device_id adxl34x_id[] = {
    { "adxl345", 0 },
    { }
};

MODULE_DEVICE_TABLE(i2c, adxl34x_id);
*/

#ifdef CONFIG_OF
static const struct of_device_id adxl34x_of_id[] = {
    /*
     * The ADXL346 is backward-compatible with the ADXL345. Differences are
     * handled by runtime detection of the device model, there's thus no
     * need for listing the "adi,adxl346" compatible value explicitly.
     */
    { .compatible = "adi,adxl345", },
    /*
     * Deprecated, DT nodes should use one or more of the device-specific
     * compatible values "adi,adxl345" and "adi,adxl346".
     */
    { .compatible = "adi,adxl34x", },
    { }
};

MODULE_DEVICE_TABLE(of, adxl34x_of_id);
#endif

static struct i2c_driver adxl34x_driver = {
    .driver = {
        .name = "adxl34x",
        //.pm = &adxl34x_i2c_pm,
        .of_match_table = of_match_ptr(adxl34x_of_id),
    },
    .probe    = adxl34x_i2c_probe,
    .remove   = adxl34x_i2c_remove,
    //.id_table = adxl34x_id, /*commented i2c_device_id*/
};

Here are some links that I have gone through in order to get some understanding

https://patches.linaro.org/patch/16873/

https://lists.ozlabs.org/pipermail/linuxppc-dev/2015-July/131965.html

https://i2c.wiki.kernel.org/index.php/OF_Modalias

I understood that first of_* style match will happen, then i2c_device_id type match.

In my case, then how of_* is not able to bind then?

Why i2c_device_table is needed if its legacy thing?


问:
Android Studio. Building signed APK. Get Key Failed
I've been building release versions of my app for months, and now all of a sudden I get this error.

Failed to read key ********  from store ***** Get Key Failed. Given final block not properly padded. Such issues can arise if a bad key is used during decryption.

This is beyond frustrating.

What I've done so far

Read every post on this error and tried every solution

Verified my passwords are correct

Checked and unchecked "save passwords"

Verified my keystore location is correct

答:
Recently, Android Studio started to show a message: "Warning: Different store and key passwords not supported for PKCS12 KeyStores. Ignoring user-specified -keypass value. in Android Studio" - so, first of all, store and key passwords should be the same, like other people said.

Besides, after getting this error even using the same password, I realized that we can't use characters like @ or $ on the passwords.


问:
How to build a custom loop activity in Elsa workflows
I'm trying to make a custom activity that will eventually do a complicated database query or API call to get a bunch of records and loop over them.  I'm sure it could be done with the built in flow control activities, but I want to make this usable by non-programmers who don't know or care what a foreach loop is, so putting a lot of functionality into one box is good.

My first attempt was to inherit from ForEach and do some initialization before letting OnExecute do its thing, but the result feels somewhat hacky.

```<code>public class FancyForEach : ForEach
{
    private bool? Initialized
    {
        get
        {
            return GetState<bool?>("Initialized");
        }
        set
        {
            SetState(value, "Initialized");
        }
    }

    protected override IActivityExecutionResult OnExecute(ActivityExecutionContext context)
    {
        if (Initialized != true)
        {
            Items = GetThingsFromDatabase();
            Initialized = true;
        }

        return base.OnExecute(context);
    }

    protected List<DatabaseThings> GetThingsFromDatabase()
    {
        // Fancy stuff here, including paging eventually.
    }
}
</code>```

It seems like it would be a little cleaner to instantiate a ForEach somewhere within the activity rather than inherit from it, but I can't puzzle out a way to make that work.  I imagine a decent solution would be to trigger another workflow for each record, but I'd rather not do that, again to make this easy to digest for people who aren't programmers.

Can anyone offer a suggestion on the best way to make this work?  This is my first project using Elsa, so maybe I'm approaching it from an entirely wrong direction!

答:
If I understand correctly, your activity is responsible for loading in the data and looping over it, while the user of the activity should be able to specify what happens in each iteration.

If so, then you might implement something like this:

[Activity(
    Category = "Control Flow",
    Description = "Iterate over a collection.",
    Outcomes = new[] { OutcomeNames.Iterate, OutcomeNames.Done }
)]
public class FancyForEach : Activity
{
    private bool? Initialized
    {
        get => GetState<bool?>();
        set => SetState(value);
    }

    private IList<DatabaseThings>? Items
    {
        get => GetState<IList<DatabaseThings>?>();
        set => SetState(value);
    }

    private int? CurrentIndex
    {
        get => GetState<int?>();
        set => SetState(value);
    }

    protected override IActivityExecutionResult OnExecute(ActivityExecutionContext context)
    {
        if (Initialized != true)
        {
            Items = GetThingsFromDatabase();
            Initialized = true;
        }

        var collection = Items.ToList();
        var currentIndex = CurrentIndex ?? 0;

        if (currentIndex < collection.Count)
        {
            var currentValue = collection[currentIndex];
            var scope = context.CreateScope();

            scope.Variables.Set("CurrentIndex", currentIndex);
            scope.Variables.Set("CurrentValue", currentValue);

            CurrentIndex = currentIndex + 1;
            context.JournalData.Add("Current Index", currentIndex);

            // For each iteration, return an outcome to which the user can connect activities to.
            return Outcome(OutcomeNames.Iterate, currentValue);
        }

        CurrentIndex = null;
        return Done();
    }

    protected List<DatabaseThings> GetThingsFromDatabase()
    {
        // Fancy stuff here, including paging eventually.
    }
}
```

This example loads the database items into memory once and then stores this list in workflow state (via Items) - which may or may not be desirable, since this has the potential of increasing the size of the workflow instance significantly depending on the size of each record and number of records.

A more scalable approach would be to load just one item per iteration, keeping track of the current index that was loaded, incrementing it (i.e. pagination with a page size of 1).

Body:
I'm trying to make a custom activity that will eventually do a complicated database query or API call to get a bunch of records and loop over them.  I'm sure it could be done with the built in flow control activities, but I want to make this usable by non-programmers who don't know or care what a foreach loop is, so putting a lot of functionality into one box is good.

My first attempt was to inherit from ForEach and do some initialization before letting OnExecute do its thing, but the result feels somewhat hacky.

public class FancyForEach : ForEach
{
    private bool? Initialized
    {
        get
        {
            return GetState<bool?>("Initialized");
        }
        set
        {
            SetState(value, "Initialized");
        }
    }

    protected override IActivityExecutionResult OnExecute(ActivityExecutionContext context)
    {
        if (Initialized != true)
        {
            Items = GetThingsFromDatabase();
            Initialized = true;
        }

        return base.OnExecute(context);
    }

    protected List<DatabaseThings> GetThingsFromDatabase()
    {
        // Fancy stuff here, including paging eventually.
    }
}

It seems like it would be a little cleaner to instantiate a ForEach somewhere within the activity rather than inherit from it, but I can't puzzle out a way to make that work.  I imagine a decent solution would be to trigger another workflow for each record, but I'd rather not do that, again to make this easy to digest for people who aren't programmers.

Can anyone offer a suggestion on the best way to make this work?  This is my first project using Elsa, so maybe I'm approaching it from an entirely wrong direction!

Body:
If I understand correctly, your activity is responsible for loading in the data and looping over it, while the user of the activity should be able to specify what happens in each iteration.

If so, then you might implement something like this:

[Activity(
    Category = "Control Flow",
    Description = "Iterate over a collection.",
    Outcomes = new[] { OutcomeNames.Iterate, OutcomeNames.Done }
)]
public class FancyForEach : Activity
{
    private bool? Initialized
    {
        get => GetState<bool?>();
        set => SetState(value);
    }

    private IList<DatabaseThings>? Items
    {
        get => GetState<IList<DatabaseThings>?>();
        set => SetState(value);
    }

    private int? CurrentIndex
    {
        get => GetState<int?>();
        set => SetState(value);
    }

    protected override IActivityExecutionResult OnExecute(ActivityExecutionContext context)
    {
        if (Initialized != true)
        {
            Items = GetThingsFromDatabase();
            Initialized = true;
        }

        var collection = Items.ToList();
        var currentIndex = CurrentIndex ?? 0;

        if (currentIndex < collection.Count)
        {
            var currentValue = collection[currentIndex];
            var scope = context.CreateScope();

            scope.Variables.Set("CurrentIndex", currentIndex);
            scope.Variables.Set("CurrentValue", currentValue);

            CurrentIndex = currentIndex + 1;
            context.JournalData.Add("Current Index", currentIndex);

            // For each iteration, return an outcome to which the user can connect activities to.
            return Outcome(OutcomeNames.Iterate, currentValue);
        }

        CurrentIndex = null;
        return Done();
    }

    protected List<DatabaseThings> GetThingsFromDatabase()
    {
        // Fancy stuff here, including paging eventually.
    }
}

This example loads the database items into memory once and then stores this list in workflow state (via Items) - which may or may not be desirable, since this has the potential of increasing the size of the workflow instance significantly depending on the size of each record and number of records.

A more scalable approach would be to load just one item per iteration, keeping track of the current index that was loaded, incrementing it (i.e. pagination with a page size of 1).


问:
Can not login with firebase in react redux, console says: firebase.auth is not a function
In my react-redux application I want to login through firebase. I tried with the code showed below, but this error appears "firebase.auth is not a function"

import React, {useRef} from 'react';
import { getFirebase } from 'react-redux-firebase';
const Auth = () => {

    const emailRef = useRef('')
    const passwordRef = useRef('')

    const handleSubmit = e => {
        e.preventDefault()
        const firebase = getFirebase();
        firebase.login({
            email : emailRef.current.value,
            password : passwordRef.current.value
        }).then(res => console.log('se autentifico correctamente')).catch(error => console.log(error))

    }```
</div>
</div>
</p>

<p><img src="https://i.stack.imgur.com/cUL6A.png" alt="Error captured from the console"></p>

<p>I tried this one and shows me exactly the same error</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>import React, {useRef} from 'react';
import { getFirebase } from 'react-redux-firebase';

const Auth = () => {

    const emailRef = useRef('')
    const passwordRef = useRef('')

    const handleSubmit = e => {
        e.preventDefault()
        const firebase = getFirebase();
        firebase.auth().createUserWithEmailAndPassword(emailRef.current.value, passwordRef.current.value)
        .catch(error => console.log(error))

    }</code>```

Im just learning to use firebase and firestore, Im blocked in this point, I dont know how to login whit firebase

I tried using 'firebaseConnect' but is now deprecated

答:
I ran into this same problem.
You need to change the imports to the v9 compatibility versions, i.e:</p>
```<code>import firebase from 'firebase/compat/app'
import 'firebase/compat/auth'
import 'firebase/compat/database'
import 'firebase/compat/firestore'
</code>```

Body:
In my react-redux application I want to login through firebase. I tried with the code showed below, but this error appears "firebase.auth is not a function"

import React, {useRef} from 'react';
import { getFirebase } from 'react-redux-firebase';
const Auth = () => {

    const emailRef = useRef('')
    const passwordRef = useRef('')

    const handleSubmit = e => {
        e.preventDefault()
        const firebase = getFirebase();
        firebase.login({
            email : emailRef.current.value,
            password : passwordRef.current.value
        }).then(res => console.log('se autentifico correctamente')).catch(error => console.log(error))

    }

I tried this one and shows me exactly the same error

import React, {useRef} from 'react';
import { getFirebase } from 'react-redux-firebase';

const Auth = () => {

    const emailRef = useRef('')
    const passwordRef = useRef('')

    const handleSubmit = e => {
        e.preventDefault()
        const firebase = getFirebase();
        firebase.auth().createUserWithEmailAndPassword(emailRef.current.value, passwordRef.current.value)
        .catch(error => console.log(error))

    }

Im just learning to use firebase and firestore, Im blocked in this point, I dont know how to login whit firebase

I tried using 'firebaseConnect' but is now deprecated

Body:
I ran into this same problem.
You need to change the imports to the v9 compatibility versions, i.e:

import firebase from 'firebase/compat/app'
import 'firebase/compat/auth'
import 'firebase/compat/database'
import 'firebase/compat/firestore'


问:
Is is legal to have relativePath to parent pom in a repository?
I found this artifact pom in the maven 2 central repository:

http://search.maven.org/remotecontent?filepath=javax/servlet/jsp/jsp-api/2.1.2/jsp-api-2.1.2.pom

It includes:

```<code>...
<parent>
  <groupId>org.glassfish.web</groupId>
  <artifactId>jsp</artifactId>
  <version>2.2</version>
  <relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<packaging>jar</packaging>
<version>${jsp-api.version}</version>
<name>JavaServer Pages(TM) API v${jsp-api.version}</name>
....
</code>```

I encountered a problem when I tried to resolve with Ivy the dependency:

```<code><dependency org="javax.servlet.jsp" name="jsp-api" rev="2.1.2" />
</code>```

Ivy could not resolve the dependency and printed out this error:

```<code>[ivy:resolve]       nexus: bad revision found in http://XXX/nexus/content/groups/public/javax/servlet/jsp/jsp-api/2.1.2/jsp-api-2.1.2.pom: expected='2.1.2 found='${jsp-api.version}'
</code>```

Now wonder if it is ok that a pom file in a repository references relatively to a parent pom?

答:
From the POM Reference: "Notice the relativePath element. It is not required, but may be used as a signifier to Maven to first search the path given for this project's parent, before searching the local and then remote repositories."

That effectively means that the relativePath is only used if it's found, and then Maven falls back to normal repository lookup. In this case, repository lookup should work fine, as the referenced artifact is available in central. Are you using a local repo or proxy? It could be that your proxy settings are preventing Ivy from finding the parent pom.

Body:
I found this artifact pom in the maven 2 central repository:

http://search.maven.org/remotecontent?filepath=javax/servlet/jsp/jsp-api/2.1.2/jsp-api-2.1.2.pom

It includes:

...
<parent>
  <groupId>org.glassfish.web</groupId>
  <artifactId>jsp</artifactId>
  <version>2.2</version>
  <relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<packaging>jar</packaging>
<version>${jsp-api.version}</version>
<name>JavaServer Pages(TM) API v${jsp-api.version}</name>
....

I encountered a problem when I tried to resolve with Ivy the dependency:

<dependency org="javax.servlet.jsp" name="jsp-api" rev="2.1.2" />

Ivy could not resolve the dependency and printed out this error:

[ivy:resolve]       nexus: bad revision found in http://XXX/nexus/content/groups/public/javax/servlet/jsp/jsp-api/2.1.2/jsp-api-2.1.2.pom: expected='2.1.2 found='${jsp-api.version}'

Now wonder if it is ok that a pom file in a repository references relatively to a parent pom?


问:
Greyscale image transformation as a function g(x,y) = f(a*x,b*y)
I have the following code. I'm reading a greyscale image into f and simply need to treat it as a function f(x,y) and transform it into g(x,y)=f(-x,y) and g(x,y)=f(kx,ky). In general, I need to be able to transform the image as g(x,y)=f(ax,bx). It should be very straightforward, but I have tried various approaches (all ultimately wrong so not shown) but can't properly access the pixel values to multiply them - there is always some kind of error I can't solve.

My question is: how do I transform f in the mathematical way shown (commented as #####... in the code) correctly?

Note: f becomes a 3D numpy array when "filename" is read.

Thank you for any assistance.

```<code>import matplotlib.pyplot as plt
import numpy as np

rows = 2
cols = 2
axes=[]
fig=plt.figure()

f = np.array(plt.imread(r"filename", format = None)

b = 3
g1 = b*f
##### g2 = f(-x,y)
##### g3 = f(k*x,k*y)

masterfx =[f, g1, g2, g3]

for i in range(rows*cols):
    axes.append( fig.add_subplot(rows, cols, i+1) )
    subplot_title=("Image "+str(i+1))
    axes[-1].set_title(subplot_title)
    plt.imshow(masterfx[i])
fig.tight_layout()
plt.show()
</code>```

答:
I was able to "solve" the problem, I think. But, if this is right, it's certainly not very elegant: (the multiple versions of f as f0, f1, f2, allow different results to be displayed upon showing the 4 images - otherwise, all functions looked the same if just using f - somehow effecting each other from right to left.

```<code>import matplotlib.pyplot as plt
import numpy as np

rows = 2
cols = 2
axes=[]
fig=plt.figure()

b = 3
K = 5

f0 = np.array(plt.imread(r"filename", format = None))

x, y, z = f0.shape

f1 = np.array(plt.imread(r"filename", format = None))
f2 = np.array(plt.imread(r"filename", format = None))
f3 = np.array(plt.imread(r"filename", format = None))

g1 = b*f1
g2 = f2
g3 = f3

for i in range(x):
    g2[i,:,:] = -1*g2[i,:,:]

for i in range(x):
    for j in range(y):
        g3[i,j,:] = K*g2[i,j,:]

masterfx =[f0, g1, g2, g3]

for i in range(rows*cols):
    axes.append( fig.add_subplot(rows, cols, i+1) )
    subplot_title=("Image "+str(i+1))
    axes[-1].set_title(subplot_title)
    plt.imshow(masterfx[i])
fig.tight_layout()
plt.show()
</code>```

Body:
I have the following code. I'm reading a greyscale image into f and simply need to treat it as a function f(x,y) and transform it into g(x,y)=f(-x,y) and g(x,y)=f(kx,ky). In general, I need to be able to transform the image as g(x,y)=f(ax,bx). It should be very straightforward, but I have tried various approaches (all ultimately wrong so not shown) but can't properly access the pixel values to multiply them - there is always some kind of error I can't solve.

My question is: how do I transform f in the mathematical way shown (commented as #####... in the code) correctly?

Note: f becomes a 3D numpy array when "filename" is read.

Thank you for any assistance.

import matplotlib.pyplot as plt
import numpy as np

rows = 2
cols = 2
axes=[]
fig=plt.figure()

f = np.array(plt.imread(r"filename", format = None)

b = 3
g1 = b*f
##### g2 = f(-x,y)
##### g3 = f(k*x,k*y)

masterfx =[f, g1, g2, g3]

for i in range(rows*cols):
    axes.append( fig.add_subplot(rows, cols, i+1) )
    subplot_title=("Image "+str(i+1))
    axes[-1].set_title(subplot_title)
    plt.imshow(masterfx[i])
fig.tight_layout()
plt.show()

Body:
I was able to "solve" the problem, I think. But, if this is right, it's certainly not very elegant: (the multiple versions of f as f0, f1, f2, allow different results to be displayed upon showing the 4 images - otherwise, all functions looked the same if just using f - somehow effecting each other from right to left.

import matplotlib.pyplot as plt
import numpy as np

rows = 2
cols = 2
axes=[]
fig=plt.figure()

b = 3
K = 5

f0 = np.array(plt.imread(r"filename", format = None))

x, y, z = f0.shape

f1 = np.array(plt.imread(r"filename", format = None))
f2 = np.array(plt.imread(r"filename", format = None))
f3 = np.array(plt.imread(r"filename", format = None))

g1 = b*f1
g2 = f2
g3 = f3

for i in range(x):
    g2[i,:,:] = -1*g2[i,:,:]

for i in range(x):
    for j in range(y):
        g3[i,j,:] = K*g2[i,j,:]

masterfx =[f0, g1, g2, g3]

for i in range(rows*cols):
    axes.append( fig.add_subplot(rows, cols, i+1) )
    subplot_title=("Image "+str(i+1))
    axes[-1].set_title(subplot_title)
    plt.imshow(masterfx[i])
fig.tight_layout()
plt.show()


问:
IllegalStateException: Error processing condition on org.springframework.boot.actuate.autoconfigure.audit.AuditEventsEndpointAutoConfiguration
I am facing "Failed to load Application context" while executing test cases and couldn't able to figure to the reason behind that. Below is the stacktrace that I got.

```<code>java.lang.IllegalStateException: Failed to load ApplicationContext
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:132)
    at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:124)
    at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:118)
    at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:83)
    at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:244)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:227)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:289)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:291)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:246)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97)
    at org.junit.runners.ParentRunner$4.run(ParentRunner.java:331)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:79)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:329)
    at org.junit.runners.ParentRunner.access$100(ParentRunner.java:66)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:293)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
    at org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:413)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:190)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:69)
    at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33)
    at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:235)
    at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:54)
Caused by: org.springframework.beans.factory.BeanDefinitionStoreException: Failed to process import candidates for configuration class [com.ntrs.tct.external.model.AdapterTradecaptureModelApplication]; nested exception is java.lang.IllegalStateException: Error processing condition on org.springframework.boot.actuate.autoconfigure.audit.AuditEventsEndpointAutoConfiguration
    at org.springframework.context.annotation.ConfigurationClassParser.processImports(ConfigurationClassParser.java:610)
    at org.springframework.context.annotation.ConfigurationClassParser.access$800(ConfigurationClassParser.java:111)
    at org.springframework.context.annotation.ConfigurationClassParser$DeferredImportSelectorGroupingHandler.lambda$processGroupImports$1(ConfigurationClassParser.java:812)
    at java.util.ArrayList.forEach(ArrayList.java:1257)
    at org.springframework.context.annotation.ConfigurationClassParser$DeferredImportSelectorGroupingHandler.processGroupImports(ConfigurationClassParser.java:809)
    at org.springframework.context.annotation.ConfigurationClassParser$DeferredImportSelectorHandler.process(ConfigurationClassParser.java:780)
    at org.springframework.context.annotation.ConfigurationClassParser.parse(ConfigurationClassParser.java:193)
    at org.springframework.context.annotation.ConfigurationClassPostProcessor.processConfigBeanDefinitions(ConfigurationClassPostProcessor.java:331)
    at org.springframework.context.annotation.ConfigurationClassPostProcessor.postProcessBeanDefinitionRegistry(ConfigurationClassPostProcessor.java:247)
    at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanDefinitionRegistryPostProcessors(PostProcessorRegistrationDelegate.java:311)
    at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(PostProcessorRegistrationDelegate.java:112)
    at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:746)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:564)
    at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:144)
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:771)
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:763)
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:438)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:339)
    at org.springframework.boot.test.context.SpringBootContextLoader.loadContext(SpringBootContextLoader.java:123)
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:99)
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:124)
    ... 25 more
Caused by: java.lang.IllegalStateException: Error processing condition on org.springframework.boot.actuate.autoconfigure.audit.AuditEventsEndpointAutoConfiguration
    at org.springframework.boot.autoconfigure.condition.SpringBootCondition.matches(SpringBootCondition.java:60)
    at org.springframework.context.annotation.ConditionEvaluator.shouldSkip(ConditionEvaluator.java:108)
    at org.springframework.context.annotation.ConfigurationClassParser.processConfigurationClass(ConfigurationClassParser.java:226)
    at org.springframework.context.annotation.ConfigurationClassParser.processImports(ConfigurationClassParser.java:600)
    ... 45 more
Caused by: java.lang.IllegalArgumentException: Value must only contain valid chars
    at org.springframework.util.Assert.isTrue(Assert.java:121)
    at org.springframework.boot.actuate.endpoint.EndpointId.<init>(EndpointId.java:58)
    at org.springframework.boot.actuate.endpoint.EndpointId.fromPropertyValue(EndpointId.java:146)
    at org.springframework.boot.actuate.autoconfigure.endpoint.expose.IncludeExcludeEndpointFilter$EndpointPatterns.<init>(IncludeExcludeEndpointFilter.java:219)
    at org.springframework.boot.actuate.autoconfigure.endpoint.expose.IncludeExcludeEndpointFilter.<init>(IncludeExcludeEndpointFilter.java:89)
    at org.springframework.boot.actuate.autoconfigure.endpoint.expose.IncludeExcludeEndpointFilter.<init>(IncludeExcludeEndpointFilter.java:78)
    at org.springframework.boot.actuate.autoconfigure.endpoint.condition.OnAvailableEndpointCondition$Exposure.<init>(OnAvailableEndpointCondition.java:96)
    at org.springframework.boot.actuate.autoconfigure.endpoint.condition.OnAvailableEndpointCondition.getExposures(OnAvailableEndpointCondition.java:84)
    at org.springframework.boot.actuate.autoconfigure.endpoint.condition.OnAvailableEndpointCondition.getMatchOutcome(OnAvailableEndpointCondition.java:64)
    at org.springframework.boot.autoconfigure.condition.SpringBootCondition.matches(SpringBootCondition.java:47)
    ... 48 more
</code>```

Here is the code for my test case

```<code>@RunWith(SpringRunner.class)
@TestPropertySource(locations = { "classpath:application.yml" , "classpath:contract-test.properties"})
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT, classes = {
        TradeCaptureServiceApplication.class })
@ActiveProfiles({ "local" })
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
@Slf4j
public class AgentContractTest extends AbstractTestNGSpringContextTests {

    @Test
    public void verifyAuthFail() {

    }

}
</code>```

Could you direct me on what could be the reason behind the issue as I didn't write anything under testcase

答:
I'm not sure what you're trying to accomplish.  But it is quite possible you should replace: @RunWith(SpringRunner.class) with @RunWith(MockitoJUnitRunner.class)

What are you using: AbstractTestNGSpringContextTests for?  I'm not sure what you're attempting to do.

Also, (without knowing context), you might not need:

```<code>@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT, classes = {
            TradeCaptureServiceApplication.class })
    @ActiveProfiles({ "local" })
    @TestInstance(TestInstance.Lifecycle.PER_CLASS)
</code>```

Body:
I am facing "Failed to load Application context" while executing test cases and couldn't able to figure to the reason behind that. Below is the stacktrace that I got.

java.lang.IllegalStateException: Failed to load ApplicationContext
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:132)
    at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:124)
    at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:118)
    at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:83)
    at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:244)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:227)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:289)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:291)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:246)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97)
    at org.junit.runners.ParentRunner$4.run(ParentRunner.java:331)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:79)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:329)
    at org.junit.runners.ParentRunner.access$100(ParentRunner.java:66)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:293)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
    at org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:413)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:190)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:69)
    at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33)
    at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:235)
    at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:54)
Caused by: org.springframework.beans.factory.BeanDefinitionStoreException: Failed to process import candidates for configuration class [com.ntrs.tct.external.model.AdapterTradecaptureModelApplication]; nested exception is java.lang.IllegalStateException: Error processing condition on org.springframework.boot.actuate.autoconfigure.audit.AuditEventsEndpointAutoConfiguration
    at org.springframework.context.annotation.ConfigurationClassParser.processImports(ConfigurationClassParser.java:610)
    at org.springframework.context.annotation.ConfigurationClassParser.access$800(ConfigurationClassParser.java:111)
    at org.springframework.context.annotation.ConfigurationClassParser$DeferredImportSelectorGroupingHandler.lambda$processGroupImports$1(ConfigurationClassParser.java:812)
    at java.util.ArrayList.forEach(ArrayList.java:1257)
    at org.springframework.context.annotation.ConfigurationClassParser$DeferredImportSelectorGroupingHandler.processGroupImports(ConfigurationClassParser.java:809)
    at org.springframework.context.annotation.ConfigurationClassParser$DeferredImportSelectorHandler.process(ConfigurationClassParser.java:780)
    at org.springframework.context.annotation.ConfigurationClassParser.parse(ConfigurationClassParser.java:193)
    at org.springframework.context.annotation.ConfigurationClassPostProcessor.processConfigBeanDefinitions(ConfigurationClassPostProcessor.java:331)
    at org.springframework.context.annotation.ConfigurationClassPostProcessor.postProcessBeanDefinitionRegistry(ConfigurationClassPostProcessor.java:247)
    at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanDefinitionRegistryPostProcessors(PostProcessorRegistrationDelegate.java:311)
    at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(PostProcessorRegistrationDelegate.java:112)
    at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:746)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:564)
    at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:144)
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:771)
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:763)
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:438)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:339)
    at org.springframework.boot.test.context.SpringBootContextLoader.loadContext(SpringBootContextLoader.java:123)
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:99)
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:124)
    ... 25 more
Caused by: java.lang.IllegalStateException: Error processing condition on org.springframework.boot.actuate.autoconfigure.audit.AuditEventsEndpointAutoConfiguration
    at org.springframework.boot.autoconfigure.condition.SpringBootCondition.matches(SpringBootCondition.java:60)
    at org.springframework.context.annotation.ConditionEvaluator.shouldSkip(ConditionEvaluator.java:108)
    at org.springframework.context.annotation.ConfigurationClassParser.processConfigurationClass(ConfigurationClassParser.java:226)
    at org.springframework.context.annotation.ConfigurationClassParser.processImports(ConfigurationClassParser.java:600)
    ... 45 more
Caused by: java.lang.IllegalArgumentException: Value must only contain valid chars
    at org.springframework.util.Assert.isTrue(Assert.java:121)
    at org.springframework.boot.actuate.endpoint.EndpointId.<init>(EndpointId.java:58)
    at org.springframework.boot.actuate.endpoint.EndpointId.fromPropertyValue(EndpointId.java:146)
    at org.springframework.boot.actuate.autoconfigure.endpoint.expose.IncludeExcludeEndpointFilter$EndpointPatterns.<init>(IncludeExcludeEndpointFilter.java:219)
    at org.springframework.boot.actuate.autoconfigure.endpoint.expose.IncludeExcludeEndpointFilter.<init>(IncludeExcludeEndpointFilter.java:89)
    at org.springframework.boot.actuate.autoconfigure.endpoint.expose.IncludeExcludeEndpointFilter.<init>(IncludeExcludeEndpointFilter.java:78)
    at org.springframework.boot.actuate.autoconfigure.endpoint.condition.OnAvailableEndpointCondition$Exposure.<init>(OnAvailableEndpointCondition.java:96)
    at org.springframework.boot.actuate.autoconfigure.endpoint.condition.OnAvailableEndpointCondition.getExposures(OnAvailableEndpointCondition.java:84)
    at org.springframework.boot.actuate.autoconfigure.endpoint.condition.OnAvailableEndpointCondition.getMatchOutcome(OnAvailableEndpointCondition.java:64)
    at org.springframework.boot.autoconfigure.condition.SpringBootCondition.matches(SpringBootCondition.java:47)
    ... 48 more

Here is the code for my test case

@RunWith(SpringRunner.class)
@TestPropertySource(locations = { "classpath:application.yml" , "classpath:contract-test.properties"})
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT, classes = {
        TradeCaptureServiceApplication.class })
@ActiveProfiles({ "local" })
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
@Slf4j
public class AgentContractTest extends AbstractTestNGSpringContextTests {

    @Test
    public void verifyAuthFail() {

    }

}

Could you direct me on what could be the reason behind the issue as I didn't write anything under testcase

Body:
I'm not sure what you're trying to accomplish.  But it is quite possible you should replace: @RunWith(SpringRunner.class) with @RunWith(MockitoJUnitRunner.class)

What are you using: AbstractTestNGSpringContextTests for?  I'm not sure what you're attempting to do.

Also, (without knowing context), you might not need:

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT, classes = {
            TradeCaptureServiceApplication.class })
    @ActiveProfiles({ "local" })
    @TestInstance(TestInstance.Lifecycle.PER_CLASS)


问:
Operating on numpy array gives incorrect values for large numbers
I need to operate on some pretty large numbers. Here, I am trying to take the cube of a large number inside an array.

```<code>import numpy as np
array=np.array([149597500000,3,4],dtype=np.int64)
print(array**3)
</code>```

This gives

```<code>[4258029614102052864                  27                  64]
</code>```

The second 2 values are correct, but the first one is off by many orders of magnitude. By contrast,

```<code>print(149597500000**3)
</code>```

gives

```<code>3347904087604984375000000000000000
</code>```

which is the correct result. Is this related to integer overflow? If so, why doesn't performing the operation outside the array also cause an overflow? How can I work around this problem? Sorry if this is a basic question; I never learned Python in a formal way.

答:
I would say the number of bits in the first number to the cube is at least 3*log2(149597500000)+1=113.
This does not fit in a 64 bits

a = 149597500000
b= a**3
print(a.bit_length(), b.bit_length())
```

returns: 38, 112

you can store that bigs number in numpy using either dtype=object or np.float64, see Stocking large numbers into numpy array

Body:
I need to operate on some pretty large numbers. Here, I am trying to take the cube of a large number inside an array.

import numpy as np
array=np.array([149597500000,3,4],dtype=np.int64)
print(array**3)

This gives

[4258029614102052864                  27                  64]

The second 2 values are correct, but the first one is off by many orders of magnitude. By contrast,

print(149597500000**3)

gives

3347904087604984375000000000000000

which is the correct result. Is this related to integer overflow? If so, why doesn't performing the operation outside the array also cause an overflow? How can I work around this problem? Sorry if this is a basic question; I never learned Python in a formal way.

Body:
I would say the number of bits in the first number to the cube is at least 3*log2(149597500000)+1=113.
This does not fit in a 64 bits

a = 149597500000
b= a**3
print(a.bit_length(), b.bit_length())

returns: 38, 112

you can store that bigs number in numpy using either dtype=object or np.float64, see Stocking large numbers into numpy array


问:
Django E.408, E.409 and E.410 errors on runserver
I am installing a new Django project using virtualenv, all in the normal way. My version of Python is 3.7.3, and django is 2.2.3.

If I do python manage.py runserver, I get the following errors:

```<code>?: (admin.E408)'django.contrib.auth.middleware.AuthenticationMiddleware' must be in MIDDLEWARE in order to use the admin application.
?: (admin.E409) 'django.contrib.messages.middleware.MessageMiddleware' must be in MIDDLEWARE in order to use the admin application.
?: (admin.E410) 'django.contrib.sessions.middleware.SessionMiddleware' must be in MIDDLEWARE in order to use the admin application.
</code>```

Here is my settings.py, and you can see that those middleware are there.

```<code>"""
Django settings for fcc_new project.

Generated by 'django-admin startproject' using Django 1.9.4.

For more information on this file, see
https://docs.djangoproject.com/en/1.9/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.9/ref/settings/
"""

import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.9/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = MY KEY goes here

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []

# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

MIDDLEWARE_CLASSES = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'fcc_new.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'fcc_new.wsgi.application'

# Database
# https://docs.djangoproject.com/en/1.9/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}

# Password validation
# https://docs.djangoproject.com/en/1.9/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]

# Internationalization
# https://docs.djangoproject.com/en/1.9/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.9/howto/static-files/

STATIC_URL = '/static/'
</code>```

I've tried reinstalling, checking versions, and changing 'MIDDLEWARE_CLASSES' to 'MIDDLEWARE'. Nothing is working. Can anyone identify the problem?

答: If you have a custom middleware, try to import it in manage.py shell. Sometimes Django can blame other middlewares when it cannot import yours (because of not installed dependency for example).

Body:
I am installing a new Django project using virtualenv, all in the normal way. My version of Python is 3.7.3, and django is 2.2.3.

If I do python manage.py runserver, I get the following errors:

?: (admin.E408)'django.contrib.auth.middleware.AuthenticationMiddleware' must be in MIDDLEWARE in order to use the admin application.
?: (admin.E409) 'django.contrib.messages.middleware.MessageMiddleware' must be in MIDDLEWARE in order to use the admin application.
?: (admin.E410) 'django.contrib.sessions.middleware.SessionMiddleware' must be in MIDDLEWARE in order to use the admin application.

Here is my settings.py, and you can see that those middleware are there.

"""
Django settings for fcc_new project.

Generated by 'django-admin startproject' using Django 1.9.4.

For more information on this file, see
https://docs.djangoproject.com/en/1.9/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.9/ref/settings/
"""

import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.9/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = MY KEY goes here

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []

# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

MIDDLEWARE_CLASSES = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'fcc_new.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'fcc_new.wsgi.application'

# Database
# https://docs.djangoproject.com/en/1.9/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}

# Password validation
# https://docs.djangoproject.com/en/1.9/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]

# Internationalization
# https://docs.djangoproject.com/en/1.9/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.9/howto/static-files/

STATIC_URL = '/static/'

I've tried reinstalling, checking versions, and changing 'MIDDLEWARE_CLASSES' to 'MIDDLEWARE'. Nothing is working. Can anyone identify the problem?


问:
How to configure -fno-strict-aliasing?
I am trying to use autogen and configure to generate a Makefile in a third-party code.   I want to add –fno-strict-aliasing to the gcc to get around a compiling problem in the code.

I guess this can done in the ./configure stage but not totally sure.  I have tried the following, but none worked:

```<code>./configure –fno-strict-aliasing
./configure –with-no-strict-aliasing
</code>```

How can this be done?

答:
You need to call configure with CFLAGS set to what you want.

```<code>./configure "CFLAGS=-O3 -fno-strict-aliasing"
</code>```

Alternatively call make with the desired options (IMO this is better).

Title: How to configure -fno-strict-aliasing?

Body:
I am trying to use autogen and configure to generate a Makefile in a third-party code.   I want to add –fno-strict-aliasing to the gcc to get around a compiling problem in the code.

I guess this can done in the ./configure stage but not totally sure.  I have tried the following, but none worked:

./configure –fno-strict-aliasing
./configure –with-no-strict-aliasing

How can this be done?

Body:
You need to call configure with CFLAGS set to what you want.

./configure "CFLAGS=-O3 -fno-strict-aliasing"

Alternatively call make with the desired options (IMO this is better).


问:
How to format a UTC date as a `YYYY-MM-DD hh:mm:ss` string using NodeJS?
Using NodeJS, I want to format a Date into the following string format:

```<code>var ts_hms = new Date(UTC);
ts_hms.format("%Y-%m-%d %H:%M:%S");
</code>```

How do I do that?

答:
Here's a handy vanilla one-liner (adapted from this):

var timestamp =
  new Date((dt = new Date()).getTime() - dt.getTimezoneOffset() * 60000)
  .toISOString()
  .replace(/(.*)T(.*)\..*/,'$1 $2')
console.log(timestamp)```

Output: 2022-02-11 11:57:39

Body:
Using NodeJS, I want to format a Date into the following string format:

var ts_hms = new Date(UTC);
ts_hms.format("%Y-%m-%d %H:%M:%S");

How do I do that?

Body:
Here's a handy vanilla one-liner (adapted from this):

var timestamp =
  new Date((dt = new Date()).getTime() - dt.getTimezoneOffset() * 60000)
  .toISOString()
  .replace(/(.*)T(.*)\..*/,'$1 $2')
console.log(timestamp)

Output: 2022-02-11 11:57:39


问:
How to change Image Src(logo) in firefox using Inspect Element
When i did inspect Element on one of the website logo. Image src is as follow.

src="/WSDNPortalTest/Content/themes/images/THP_img.jpg"

Now, I want to try different logo, that i have in my local machine folder.

Is it possible to do that? Advice me. Thanks

答:
It is not possible to inspect and put up your local image. However, you can follow the following steps to achieve the desired result:

Put your image on Google Drive or any other storage server

Generate a sharable link for that image

Inspect the element in your browser

Change image src from src="/WSDNPortalTest/Content/themes/images/THP_img.jpg to src = "sharable-url-here.jpg"

This is how you can achieve the same effect


问:
Create Laravel Relationship through Many-To-One and Many-To-Many
I'm having trouble defining a relationship between several models.
In the Laravel documentation, I was able to find a hasManyThrough() relationship where the relationship was extended down through two many-to-one models, but I'm having issues with mine from a many-to-one then many-to-many relationship. Here are the tables:

```<code>practices
  id
  name

locations
  id
  practice_id
  name

doctors
  id
  name

doctor_location
  doctor_id
  location_id
</code>```

As you can see, practices can have many locations, and locations can only belong to one practice. Doctors can have many locations, and locations can have many doctors. I'm not certain how to drill down to create a $practice->doctors relationship, however. I did attempt the hasManyThrough() relationship in the practices model:

```<code>public function doctors() {
  return $this->hasManyThrough(Doctor::class, Location::class);
}
</code>```

but this simply threw an sqlstate error looking for a location_id in the doctors table. Is it possible to relate these models?

Edit: SQLState error

```<code>Illuminate\Database\QueryException
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'doctors.location_id' in 'on clause' (SQL: select `doctors`.*, `locations`.`practice_id` as `laravel_through_key` from `doctors` inner join `locations` on `locations`.`id` = `doctors`.`location_id` where `locations`.`practice_id` = 1)
</code>```

答:
I think you don't need any relationship between doctors and practice in your case. The following query should work:

```<code>Practice::with('locations.doctors');
</code>```

The output should be an array of locations, and each location will contain doctors.

Body:
I'm having trouble defining a relationship between several models.
In the Laravel documentation, I was able to find a hasManyThrough() relationship where the relationship was extended down through two many-to-one models, but I'm having issues with mine from a many-to-one then many-to-many relationship. Here are the tables:

practices
  id
  name

locations
  id
  practice_id
  name

doctors
  id
  name

doctor_location
  doctor_id
  location_id

As you can see, practices can have many locations, and locations can only belong to one practice. Doctors can have many locations, and locations can have many doctors. I'm not certain how to drill down to create a $practice->doctors relationship, however. I did attempt the hasManyThrough() relationship in the practices model:

public function doctors() {
  return $this->hasManyThrough(Doctor::class, Location::class);
}

but this simply threw an sqlstate error looking for a location_id in the doctors table. Is it possible to relate these models?

Edit: SQLState error

Illuminate\Database\QueryException
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'doctors.location_id' in 'on clause' (SQL: select `doctors`.*, `locations`.`practice_id` as `laravel_through_key` from `doctors` inner join `locations` on `locations`.`id` = `doctors`.`location_id` where `locations`.`practice_id` = 1)

Body:
I think you don't need any relationship between doctors and practice in your case. The following query should work:

Practice::with('locations.doctors');

The output should be an array of locations, and each location will contain doctors.


问:
SwiftUI @StateObject nested @State value not updating
I've run into an issue whilst trying to learn SwiftUI's binding and I'm struggling to understand why a @StateObject value can't be updated from its parent.

Here's what I've put together and I can open and close a SheetView successfully using it the .show enum but $isPresented still outputs as false, as if it's not being sent. $isPresented is being used inside SheetView on a button to close the SheetView from inside. How can I update isPresented from inside ContentView and inside SheetView?

```<code>class Presenter: ObservableObject {
enum Show: Equatable {
    case none, login, register
}

@Published var show: Show = .none
@State var isPresented: Bool = false

@ViewBuilder
func makeView() -> some View {
    switch show {
    case .none:
        EmptyView().onAppear {
            isPresented.toggle()
        }
    case .login:
        SheetView(isOpen: $isPresented) { // SheetView has a button which fails to close using isPresented.toggle() or isPresented = false
            LoginView()
        }
    case .register:
        SheetView(isOpen: $isPresented) {
            RegisterView()
        }
    }
}
}

struct ContentView: View {

@StateObject var presenter = Presenter()

var body: some View {
    ZStack {
        Color("White")
        HomeView().environmentObject(presenter) // Has button which changes presenter to login via presenter.show = .login
        .overlay {
            switch presenter.show {
            case .none:
                EmptyView().onAppear {
                    presenter.isPresented.toggle() // Has no effect
                    presenter.show = .none
                }
            default:
                ZStack {
                    Color("Black").opacity(0.1).onTapGesture {
                        withAnimation(.interactiveSpring()) {
                            presenter.isPresented.toggle() // Has no effect
                            presenter.show = .none
                        }
                    }.transition(.opacity)
                }.edgesIgnoringSafeArea(.all)
            }
        }
    }.overlay {
        presenter.makeView()
    }
}

}
</code>```

To include a MRE would take around 200 lines of code, hence the abridged version above. The main issue is how do you change a @State property from inside view which is already inside the @StateObject. SheetView needs to toggle $isPresented

答:
I managed to solve the issue removing isPresented and passing down a singleton of the same Presenter. So Presenter.shared inside contentView and inside Presenter. Then passed as a param on SheetView like: SheetView(presenter: Presenter.shared) - After this I could close SheetView from inside SheetView. Nice approach to allow multiple ways to close a Sheet both internally and externally.

Hope this helps anyone else on a related issue.

Body:
I've run into an issue whilst trying to learn SwiftUI's binding and I'm struggling to understand why a @StateObject value can't be updated from its parent.

Here's what I've put together and I can open and close a SheetView successfully using it the .show enum but $isPresented still outputs as false, as if it's not being sent. $isPresented is being used inside SheetView on a button to close the SheetView from inside. How can I update isPresented from inside ContentView and inside SheetView?

class Presenter: ObservableObject {
enum Show: Equatable {
    case none, login, register
}

@Published var show: Show = .none
@State var isPresented: Bool = false

@ViewBuilder
func makeView() -> some View {
    switch show {
    case .none:
        EmptyView().onAppear {
            isPresented.toggle()
        }
    case .login:
        SheetView(isOpen: $isPresented) { // SheetView has a button which fails to close using isPresented.toggle() or isPresented = false
            LoginView()
        }
    case .register:
        SheetView(isOpen: $isPresented) {
            RegisterView()
        }
    }
}
}

struct ContentView: View {

@StateObject var presenter = Presenter()

var body: some View {
    ZStack {
        Color("White")
        HomeView().environmentObject(presenter) // Has button which changes presenter to login via presenter.show = .login
        .overlay {
            switch presenter.show {
            case .none:
                EmptyView().onAppear {
                    presenter.isPresented.toggle() // Has no effect
                    presenter.show = .none
                }
            default:
                ZStack {
                    Color("Black").opacity(0.1).onTapGesture {
                        withAnimation(.interactiveSpring()) {
                            presenter.isPresented.toggle() // Has no effect
                            presenter.show = .none
                        }
                    }.transition(.opacity)
                }.edgesIgnoringSafeArea(.all)
            }
        }
    }.overlay {
        presenter.makeView()
    }
}

}

To include a MRE would take around 200 lines of code, hence the abridged version above. The main issue is how do you change a @State property from inside view which is already inside the @StateObject. SheetView needs to toggle $isPresented


问:
converting time to local timezone not working with moment.js in React
I am converting a timestamp on a DB object using moment:

```<code>{moment(comment.created_at).local(true).format('h:mm a')}
</code>```

My time is outputting in UTC time because that is how it gets created in my DB.
So I am seeing '6:45 PM' for example, when I want to see the time in MY timezone (EST) or the user's relative timezone. According to the moment docs local() will convert to your current timezone? Calling the local() method as shown in my code aboven does not change the time zone. Am I using this incorrectly?

My DB object

```<code>{
  client_id: 24
  created_at: "2022-02-11 17:41:39.330443"
  id: 22
  report: "sfsf"
  report_category: "Client Assigned"
  volunteer_id: 23
}
</code>```

答:
Your database is storing the date without an offset indicator. This means that moment cannot automatically determine the timezone. As per the documentation on parsing dates:

moment(...) is local mode. Ambiguous input (without offset) is assumed to be local time. Unambiguous input (with offset) is adjusted to local time. * moment.utc(...) is utc mode. Ambiguous input is assumed to be UTC.

So if you know your input is UTC and you know it won't have an offset indicator, use moment.utc() instead of moment().

Furthermore, you don't want to use local(true), since passing in "true" will only change the timezone on the object without changing the time (see the documentation). So you're left with:

```<code>{moment.utc(comment.created_at).local().format('h:mm a')}
</code>```

Body:
I am converting a timestamp on a DB object using moment:

{moment(comment.created_at).local(true).format('h:mm a')}

My time is outputting in UTC time because that is how it gets created in my DB.
So I am seeing '6:45 PM' for example, when I want to see the time in MY timezone (EST) or the user's relative timezone. According to the moment docs local() will convert to your current timezone? Calling the local() method as shown in my code aboven does not change the time zone. Am I using this incorrectly?

My DB object

{
  client_id: 24
  created_at: "2022-02-11 17:41:39.330443"
  id: 22
  report: "sfsf"
  report_category: "Client Assigned"
  volunteer_id: 23
}

Body:
Your database is storing the date without an offset indicator. This means that moment cannot automatically determine the timezone. As per the documentation on parsing dates:

moment(...) is local mode. Ambiguous input (without offset) is assumed to be local time. Unambiguous input (with offset) is adjusted to local time. * moment.utc(...) is utc mode. Ambiguous input is assumed to be UTC.

So if you know your input is UTC and you know it won't have an offset indicator, use moment.utc() instead of moment().

Furthermore, you don't want to use local(true), since passing in "true" will only change the timezone on the object without changing the time (see the documentation). So you're left with:

{moment.utc(comment.created_at).local().format('h:mm a')}


问:
Generate a series of numbers that go up in two interweaving intervals
Let's say I want to generate a series of numbers that first jump 5 and then 10 all the way to 100 which would be

```<code>0,5,15,20,30,35,45,50,60,65,75,85,90,100
</code>```

I am aware of

```<code>seq 0 10 100
</code>```

but am looking to jump two different intervals intertwined.

答:
Assumptions:

start with 0

generate a sequence of numbers by adding +5, +10, +5, +10 ... until we reach/exceed 100

One idea using a bash loop:

```<code>i=0
sum=0

while [[ "${sum}" -le 100 ]]
do
    echo $sum
    ((sum += (i++%2 + 1) * 5))
done
</code>```

This generates:

```<code>0
5
15
20
30
35
45
50
60
65
75
80
90
95
</code>```

Body:
Let's say I want to generate a series of numbers that first jump 5 and then 10 all the way to 100 which would be

0,5,15,20,30,35,45,50,60,65,75,85,90,100

I am aware of

seq 0 10 100

but am looking to jump two different intervals intertwined.

Body:
Assumptions:

start with 0

generate a sequence of numbers by adding +5, +10, +5, +10 ... until we reach/exceed 100

One idea using a bash loop:

i=0
sum=0

while [[ "${sum}" -le 100 ]]
do
    echo $sum
    ((sum += (i++%2 + 1) * 5))
done

This generates:

0
5
15
20
30
35
45
50
60
65
75
80
90
95