问:
Django custom ordering causes error for related model?
I have two models as follows:

class A(models.Model):
    # more fields here
    finished_at = models.DateTimeField(db_index=True, null=True, blank=True)

    class Meta:
        ordering = [
            models.F("finished_at").desc(nulls_first=True),
            "other_field",
        ]

class B(models.Model):
    a = models.ForeignKey(A, on_delete=models.CASCADE)

    class Meta:
        ordering = [
            "a"
        ]
```
<p>And then when I try to delete <code>A</code> instances through the admin site, or when accessing <code>B</code> instances either through admin or command line it gives error: <code>Cannot resolve keyword into field </code><strong><code>finished_at</code></strong>.</p>
<p>But if I remove the ordering on model <code>A</code> it works fine.</p>
<p><strong>I could narrow down the issue, removing either "a" from <code>B</code> ordering or not using the <code>models.F</code> expression from <code>A</code> ordering will solve the issue.</strong></p>
<p>Full stacktrace:</p>
```
Django Version: 3.2.11
Python Version: 3.8.12
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'rest_framework',
 'corsheaders',
 'my-apps',
]
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'corsheaders.middleware.CorsMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware']

Traceback (most recent call last):
  File "BASE_DIR/.venv/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner
    response = get_response(request)
  File "BASE_DIR/.venv/lib/python3.8/site-packages/django/core/handlers/base.py", line 181, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "BASE_DIR/.venv/lib/python3.8/site-packages/django/contrib/admin/options.py", line 616, in wrapper
    return self.admin_site.admin_view(view)(*args, **kwargs)
  File "BASE_DIR/.venv/lib/python3.8/site-packages/django/utils/decorators.py", line 130, in _wrapped_view
    response = view_func(request, *args, **kwargs)
  File "BASE_DIR/.venv/lib/python3.8/site-packages/django/views/decorators/cache.py", line 44, in _wrapped_view_func
    response = view_func(request, *args, **kwargs)
  File "BASE_DIR/.venv/lib/python3.8/site-packages/django/contrib/admin/sites.py", line 232, in inner
    return view(request, *args, **kwargs)
  File "BASE_DIR/.venv/lib/python3.8/site-packages/django/utils/decorators.py", line 43, in _wrapper
    return bound_method(*args, **kwargs)
  File "BASE_DIR/.venv/lib/python3.8/site-packages/django/utils/decorators.py", line 130, in _wrapped_view
    response = view_func(request, *args, **kwargs)
  File "BASE_DIR/.venv/lib/python3.8/site-packages/django/contrib/admin/options.py", line 1815, in changelist_view
    'selection_note': _('0 of %(cnt)s selected') % {'cnt': len(cl.result_list)},
  File "BASE_DIR/.venv/lib/python3.8/site-packages/django/db/models/query.py", line 262, in __len__
    self._fetch_all()
  File "BASE_DIR/.venv/lib/python3.8/site-packages/django/db/models/query.py", line 1324, in _fetch_all
    self._result_cache = list(self._iterable_class(self))
  File "BASE_DIR/.venv/lib/python3.8/site-packages/django/db/models/query.py", line 51, in __iter__
    results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size)
  File "BASE_DIR/.venv/lib/python3.8/site-packages/django/db/models/sql/compiler.py", line 1162, in execute_sql
    sql, params = self.as_sql()
  File "BASE_DIR/.venv/lib/python3.8/site-packages/django/db/models/sql/compiler.py", line 513, in as_sql
    extra_select, order_by, group_by = self.pre_sql_setup()
  File "BASE_DIR/.venv/lib/python3.8/site-packages/django/db/models/sql/compiler.py", line 56, in pre_sql_setup
    order_by = self.get_order_by()
  File "BASE_DIR/.venv/lib/python3.8/site-packages/django/db/models/sql/compiler.py", line 372, in get_order_by
    resolved = expr.resolve_expression(self.query, allow_joins=True, reuse=None)
  File "BASE_DIR/.venv/lib/python3.8/site-packages/django/db/models/expressions.py", line 247, in resolve_expression
    c.set_source_expressions([
  File "BASE_DIR/.venv/lib/python3.8/site-packages/django/db/models/expressions.py", line 248, in <listcomp>
    expr.resolve_expression(query, allow_joins, reuse, summarize)
  File "BASE_DIR/.venv/lib/python3.8/site-packages/django/db/models/expressions.py", line 578, in resolve_expression
    return query.resolve_ref(self.name, allow_joins, reuse, summarize)
  File "BASE_DIR/.venv/lib/python3.8/site-packages/django/db/models/sql/query.py", line 1756, in resolve_ref
    join_info = self.setup_joins(field_list, self.get_meta(), self.get_initial_alias(), can_reuse=reuse)
  File "BASE_DIR/.venv/lib/python3.8/site-packages/django/db/models/sql/query.py", line 1625, in setup_joins
    path, final_field, targets, rest = self.names_to_path(
  File "BASE_DIR/.venv/lib/python3.8/site-packages/django/db/models/sql/query.py", line 1539, in names_to_path
    raise FieldError("Cannot resolve keyword '%s' into field. "

Exception Type: FieldError at /admin/some/path/
Exception Value: Cannot resolve keyword 'finished_at' into field. Choices are
```

答:
It's a known bug: #29538 (Query Expression in ordering of a related object fails) – Django

This occurs because:

B has on_delete=models.CASCADE on A.

B has ordering on A.

A has ordering on an F object.

SQLCompiler find_ordering_name doesn't properly convert F objects of relations.

There's a stale PR (closed due to inactivity) that attempted to fix this: django/django#10146

Here's a patch that works for simple cases, such as those in the question and the bug report:

from django.db.models.constants import LOOKUP_SEP
from django.db.models.expressions import F
from django.db.models.sql.datastructures import Join
from django.db.models.sql.query import get_field_names_from_opts

def resolve_expression(self, query=None, allow_joins=True, reuse=None, summarize=False, for_save=False):
    name = self.name
    if self.name not in get_field_names_from_opts(query.get_meta()):
        for datastructure in query.alias_map.values():
            if (
                    isinstance(datastructure, Join) and
                    datastructure.join_field.opts == query.get_meta() and
                    self.name in get_field_names_from_opts(datastructure.join_field.related_model._meta)
            ):
                name = datastructure.join_field.name + LOOKUP_SEP + self.name
                break
    return query.resolve_ref(name, allow_joins, reuse, summarize)

F.resolve_expression = resolve_expression
```

Example case where this doesn't work: In addition to the above, A has ordering on another model C, which has ordering on an F object.

The proper fix (determining the full path) needs to be done in SQLCompiler find_ordering_name.

Body:
I have two models as follows:

class A(models.Model):
    # more fields here
    finished_at = models.DateTimeField(db_index=True, null=True, blank=True)

    class Meta:
        ordering = [
            models.F("finished_at").desc(nulls_first=True),
            "other_field",
        ]

class B(models.Model):
    a = models.ForeignKey(A, on_delete=models.CASCADE)

    class Meta:
        ordering = [
            "a"
        ]

And then when I try to delete A instances through the admin site, or when accessing B instances either through admin or command line it gives error: Cannot resolve keyword into field finished_at.

But if I remove the ordering on model A it works fine.

I could narrow down the issue, removing either "a" from B ordering or not using the models.F expression from A ordering will solve the issue.

Full stacktrace:

Django Version: 3.2.11
Python Version: 3.8.12
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'rest_framework',
 'corsheaders',
 'my-apps',
]
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'corsheaders.middleware.CorsMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware']

Traceback (most recent call last):
  File "BASE_DIR/.venv/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner
    response = get_response(request)
  File "BASE_DIR/.venv/lib/python3.8/site-packages/django/core/handlers/base.py", line 181, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "BASE_DIR/.venv/lib/python3.8/site-packages/django/contrib/admin/options.py", line 616, in wrapper
    return self.admin_site.admin_view(view)(*args, **kwargs)
  File "BASE_DIR/.venv/lib/python3.8/site-packages/django/utils/decorators.py", line 130, in _wrapped_view
    response = view_func(request, *args, **kwargs)
  File "BASE_DIR/.venv/lib/python3.8/site-packages/django/views/decorators/cache.py", line 44, in _wrapped_view_func
    response = view_func(request, *args, **kwargs)
  File "BASE_DIR/.venv/lib/python3.8/site-packages/django/contrib/admin/sites.py", line 232, in inner
    return view(request, *args, **kwargs)
  File "BASE_DIR/.venv/lib/python3.8/site-packages/django/utils/decorators.py", line 43, in _wrapper
    return bound_method(*args, **kwargs)
  File "BASE_DIR/.venv/lib/python3.8/site-packages/django/utils/decorators.py", line 130, in _wrapped_view
    response = view_func(request, *args, **kwargs)
  File "BASE_DIR/.venv/lib/python3.8/site-packages/django/contrib/admin/options.py", line 1815, in changelist_view
    'selection_note': _('0 of %(cnt)s selected') % {'cnt': len(cl.result_list)},
  File "BASE_DIR/.venv/lib/python3.8/site-packages/django/db/models/query.py", line 262, in __len__
    self._fetch_all()
  File "BASE_DIR/.venv/lib/python3.8/site-packages/django/db/models/query.py", line 1324, in _fetch_all
    self._result_cache = list(self._iterable_class(self))
  File "BASE_DIR/.venv/lib/python3.8/site-packages/django/db/models/query.py", line 51, in __iter__
    results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size)
  File "BASE_DIR/.venv/lib/python3.8/site-packages/django/db/models/sql/compiler.py", line 1162, in execute_sql
    sql, params = self.as_sql()
  File "BASE_DIR/.venv/lib/python3.8/site-packages/django/db/models/sql/compiler.py", line 513, in as_sql
    extra_select, order_by, group_by = self.pre_sql_setup()
  File "BASE_DIR/.venv/lib/python3.8/site-packages/django/db/models/sql/compiler.py", line 56, in pre_sql_setup
    order_by = self.get_order_by()
  File "BASE_DIR/.venv/lib/python3.8/site-packages/django/db/models/sql/compiler.py", line 372, in get_order_by
    resolved = expr.resolve_expression(self.query, allow_joins=True, reuse=None)
  File "BASE_DIR/.venv/lib/python3.8/site-packages/django/db/models/expressions.py", line 247, in resolve_expression
    c.set_source_expressions([
  File "BASE_DIR/.venv/lib/python3.8/site-packages/django/db/models/expressions.py", line 248, in <listcomp>
    expr.resolve_expression(query, allow_joins, reuse, summarize)
  File "BASE_DIR/.venv/lib/python3.8/site-packages/django/db/models/expressions.py", line 578, in resolve_expression
    return query.resolve_ref(self.name, allow_joins, reuse, summarize)
  File "BASE_DIR/.venv/lib/python3.8/site-packages/django/db/models/sql/query.py", line 1756, in resolve_ref
    join_info = self.setup_joins(field_list, self.get_meta(), self.get_initial_alias(), can_reuse=reuse)
  File "BASE_DIR/.venv/lib/python3.8/site-packages/django/db/models/sql/query.py", line 1625, in setup_joins
    path, final_field, targets, rest = self.names_to_path(
  File "BASE_DIR/.venv/lib/python3.8/site-packages/django/db/models/sql/query.py", line 1539, in names_to_path
    raise FieldError("Cannot resolve keyword '%s' into field. "

Exception Type: FieldError at /admin/some/path/
Exception Value: Cannot resolve keyword 'finished_at' into field. Choices are

Body:
It's a known bug: #29538 (Query Expression in ordering of a related object fails) – Django

This occurs because:

B has on_delete=models.CASCADE on A.

B has ordering on A.

A has ordering on an F object.

SQLCompiler find_ordering_name doesn't properly convert F objects of relations.

There's a stale PR (closed due to inactivity) that attempted to fix this: django/django#10146

Here's a patch that works for simple cases, such as those in the question and the bug report:

from django.db.models.constants import LOOKUP_SEP
from django.db.models.expressions import F
from django.db.models.sql.datastructures import Join
from django.db.models.sql.query import get_field_names_from_opts

def resolve_expression(self, query=None, allow_joins=True, reuse=None, summarize=False, for_save=False):
    name = self.name
    if self.name not in get_field_names_from_opts(query.get_meta()):
        for datastructure in query.alias_map.values():
            if (
                    isinstance(datastructure, Join) and
                    datastructure.join_field.opts == query.get_meta() and
                    self.name in get_field_names_from_opts(datastructure.join_field.related_model._meta)
            ):
                name = datastructure.join_field.name + LOOKUP_SEP + self.name
                break
    return query.resolve_ref(name, allow_joins, reuse, summarize)

F.resolve_expression = resolve_expression

Example case where this doesn't work: In addition to the above, A has ordering on another model C, which has ordering on an F object.

The proper fix (determining the full path) needs to be done in SQLCompiler find_ordering_name.


来源: stackexchange

问:
laravel 6 csrf token expired in every 60 seconds?
I am using laravel 6.I Want my laravel CSRF Token expire in every 60 seconds.

config/session

'lifetime' => 60,

答:
After long testing I end up something, that you put in the lifetime option in session not allow to set expire time in seconds, it'll allow to minutes.

So, when you set up liftime = "60", it's means it will expire in 1 hour.

Hence, You have to set liftime = "1" in your config/session.pph file. Also, default value in .env file SESSION_LIFETIME=120 you have to replace that with 1 SESSION_LIFETIME = 1.

After that you have to clear the cache by command:-

php artisan config:cache

Now, your session will expire after 1 minute / 60 seconds.

To see more check this question.

ContentLicense: CC BY-SA 4.0


问:
How would you solve this tricky SQL problem?
Say you have a table layout like the following:

couses:

```<code>id (INT),
courseName (VARCHAR)
</code>```

instructors:

```<code>id (INT),
courseId(INT),
instructor(VARCHAR)
</code>```

Create a query which will print the all the courses and if one instructor is present display their name, if two instructors are present print both of their names on the row in sorted order, if more than two instructors are present instead of the instructors names display “committee“.

For instance your output would look something like this

```
    courseId    instructor1        instructor2
    0           Edward Yourdon
    1           Edward Dijkstra    Nicholas Wirth
    2           Comittee
```

Note: Taken from a questionnaire on TheDailyWtf. Not a homework question.

答:
In SQL Anywhere, here's how you could do it:

```<code>select courseid as cid,
if ( select count(*) from instructor where courseid = cid ) > 2
   then 'Committee'
else
   list(name order by name)
endif as profs
from instructor
group by courseid
order by cid
</code>```

Note that this selects 'profs' as the list of professors (as stated in the question) as a single column.

I'm not familiar enough with MySQL to know if there is an equivalent to the list() function.

OwnerDisplayName: Click Upvote

ContentLicense: CC BY-SA 2.5

Body:
Say you have a table layout like the following:

couses:

id (INT),
courseName (VARCHAR)

instructors:

id (INT),
courseId(INT),
instructor(VARCHAR)

Create a query which will print the all the courses and if one instructor is present display their name, if two instructors are present print both of their names on the row in sorted order, if more than two instructors are present instead of the instructors names display “committee“.

For instance your output would look something like this

    courseId    instructor1        instructor2
    0           Edward Yourdon
    1           Edward Dijkstra    Nicholas Wirth
    2           Comittee

Note: Taken from a questionnaire on TheDailyWtf. Not a homework question.

Body:
In SQL Anywhere, here's how you could do it:

select courseid as cid,
if ( select count(*) from instructor where courseid = cid ) > 2
   then 'Committee'
else
   list(name order by name)
endif as profs
from instructor
group by courseid
order by cid

Note that this selects 'profs' as the list of professors (as stated in the question) as a single column.

I'm not familiar enough with MySQL to know if there is an equivalent to the list() function.

OwnerDisplayName: Graeme Perrow


问:
Remove traceback in Python on Ctrl-C
Is there a way to keep tracebacks from coming up when you hit Ctrl+c,
 i.e. raise KeyboardInterrupt in a Python script?

答:
suppress exception using context manager:

from contextlib import suppress

def output_forever():
    while True:
        print('endless script output. Press ctrl + C to exit')

if __name__ == '__main__':
    with suppress(KeyboardInterrupt):
        output_forever()
```

ContentLicense: CC BY-SA 3.0

Title: Remove traceback in Python on Ctrl-C


问:
How to scaffold EF core to existing DB?
I am trying to reverse engineer an existing database using Entity Framework Core. I tried to follow the directions from Microsoft but I am presented with the error:

Unable to find provider assembly with name EntityFramework. Ensure the specified name is correct and is referenced by the project.

I am running the following command from the project directory:

```<code>dnx ef dbcontext scaffold "Server=REMOVED;Database=REMOVED;User ID=REMOVED;Password=REMOVED" EntityFramework
</code>```

What am I doing wrong?

答:
Install Microsoft.EntityFrameworkCore.SqlServer from Nuget

In PM set the default project to the project that will contain the Models folder, then in PM...

```<code>PM> Scaffold-DbContext "Server=YOURSERVER;database=YOURDB;Trusted_Connection=True;" MicrosoftEntityFrameworkCore.SqlServer -OutputDir Models -force
</code>```

Title: How to scaffold EF core to existing DB?

Body:
I am trying to reverse engineer an existing database using Entity Framework Core. I tried to follow the directions from Microsoft but I am presented with the error:

Unable to find provider assembly with name EntityFramework. Ensure the specified name is correct and is referenced by the project.

I am running the following command from the project directory:

dnx ef dbcontext scaffold "Server=REMOVED;Database=REMOVED;User ID=REMOVED;Password=REMOVED" EntityFramework

What am I doing wrong?

Body:
Install Microsoft.EntityFrameworkCore.SqlServer from Nuget

In PM set the default project to the project that will contain the Models folder, then in PM...

PM> Scaffold-DbContext "Server=YOURSERVER;database=YOURDB;Trusted_Connection=True;" MicrosoftEntityFrameworkCore.SqlServer -OutputDir Models -force


问:
syntax error near unexpected token `'../lib/cli.js''
The file in question:

```<code>#!/root/.nvm/versions/node/v17.5.0/bin/node
require('../lib/cli.js')(process)
</code>```

Node -v 17.5.0

NPM -v 8.4.1

PM2 -v 5.1.2

Next.js v11.1.3

Trying to run in an Amazon EC2 instance on the default Linux AMI. Any thoughts?

答: No idea what fixed it. But the ancient artform of nuke everything and start from scratch fixed it.</p>

Body:
The file in question:

#!/root/.nvm/versions/node/v17.5.0/bin/node
require('../lib/cli.js')(process)

Node -v 17.5.0

NPM -v 8.4.1

PM2 -v 5.1.2

Next.js v11.1.3

Trying to run in an Amazon EC2 instance on the default Linux AMI. Any thoughts?


问:
how to pass values from multiple textfields with same name attributes to a variable in form of an array
I am building a form that passes a set of numbers in form of an array to a variable as seen below

```<code>  var users=["1","2"];
</code>```

the main purpose of this is to then make an Ajax request with these numbers and get their corresponding content in my database which I then pass to their respective divs, please see below

```<code> var users=["1","2"];

var async_request=[];
var responses=[];
for(i in users)
{
    // you can push  any aysnc method handler
    async_request.push($.ajax({
        url:'back.php', // your url
        method:'post', // method GET or POST
        data:{user_name: users[i]},
        success: function(data){
            console.log('success of ajax response')
            responses.push(data);

        }
    }));
}

$.when.apply(null, async_request).done( function(){
    // all done
    console.log('all request completed')
    console.log(responses);
      $( '#responses' ).html(responses[1]);
      $( '#responses1' ).html(responses[0]);

});
</code>```

This works perfectly.

But now I want to make some adjustments to my solution specifically

Im looking to replace the method of passing the numbers to the variable users

from

```<code>  var users=["1","2"];   // Im looking to replace the method
</code>```

to this

```<code>var users = $('[name="tom[]"]').val(attachArray);

 <input type="text" name="tom[]" value="1" /><br>
        <input type="text" name="tom[]" value="2" /><br>
</code>```

but I am unable to get the the ids from the two textfields and then pass to my database using my Ajax script as I did before with this

```<code>  var users=["1","2"];
</code>```

答:
You forgot to use input key value :

```<code>var users = $('input[name="tom[]"]').val();
</code>```

Body:
I am building a form that passes a set of numbers in form of an array to a variable as seen below

  var users=["1","2"];

the main purpose of this is to then make an Ajax request with these numbers and get their corresponding content in my database which I then pass to their respective divs, please see below

 var users=["1","2"];

var async_request=[];
var responses=[];
for(i in users)
{
    // you can push  any aysnc method handler
    async_request.push($.ajax({
        url:'back.php', // your url
        method:'post', // method GET or POST
        data:{user_name: users[i]},
        success: function(data){
            console.log('success of ajax response')
            responses.push(data);

        }
    }));
}

$.when.apply(null, async_request).done( function(){
    // all done
    console.log('all request completed')
    console.log(responses);
      $( '#responses' ).html(responses[1]);
      $( '#responses1' ).html(responses[0]);

});

This works perfectly.

But now I want to make some adjustments to my solution specifically

Im looking to replace the method of passing the numbers to the variable users

from

  var users=["1","2"];   // Im looking to replace the method

to this

var users = $('[name="tom[]"]').val(attachArray);

 <input type="text" name="tom[]" value="1" />

        <input type="text" name="tom[]" value="2" />

but I am unable to get the the ids from the two textfields and then pass to my database using my Ajax script as I did before with this

  var users=["1","2"];

Body:
You forgot to use input key value :

var users = $('input[name="tom[]"]').val();


问:
How to map `Object.values()` over an array of objects nesting objects?
I'm trying to map Object.values() to extract just the values from an array of objects:

const countries = [
    {
        "austria": { value: 1},
        "canada": {value: 2},
        "nepal": { value: 3},
        "india": { value: 4}
    },
    {
        "australia": { value: 10},
        "france": { value: 20},
        "egypt": { value: 40},
        "usa": { value: 20}
    },
    {
        "mexico": { value: 3},
        "germany": { value: 100},
        "southAfrica": { value: 1},
        "china": { value: 10}
    }
]
```
<p>To get:</p>
<pre class="lang-js prettyprint-override"><code>// expected output
[
    {
        "austria": [ 1 ],
        "canada": [ 2 ],
        "nepal": [ 3 ],
        "india": [ 4 ]
    },
    {
        "australia": [ 10 ] ,
        "france": [ 20 ],
        "egypt": [ 40 ],
        "usa": [ 20 ]
    },
    {
        "mexico": [ 3 ],
        "germany": [ 100 ],
        "southAfrica": [ 1 ],
        "china": [ 10 ]
    }
]
</code>```

I tried

Object.values(countries) // returns the same as `countries`
```
<p>and also tried mapping using <code>ramda</code>'s <code>map()</code> to map <code>Object.values()</code> over <code>countries</code></p>
<pre class="lang-js prettyprint-override"><code>const R = require("ramda")

R.map(Object.values, countries)
// gives:
// [
//   [ { value: 1 }, { value: 2 }, { value: 3 }, { value: 4 } ],
//   [ { value: 10 }, { value: 20 }, { value: 40 }, { value: 20 } ],
//   [ { value: 3 }, { value: 100 }, { value: 1 }, { value: 10 } ]
// ]
</code>```

But I don't want to lose the countries names! How can I utilize either vanilla map or ramda's version to get the expected output?

答:
You need to map the entries and the nested objects values.

const
    countries = [{ austria: { value: 1 }, canada: { value: 2 }, nepal: { value: 3 }, india: { value: 4 } }, { australia: { value: 10 }, france: { value: 20 }, egypt: { value: 40 }, usa: { value: 20 } }, { mexico: { value: 3 }, germany: { value: 100 }, southAfrica: { value: 1 }, china: { value: 10 } }],
    result = countries.map(o => Object.fromEntries(Object
        .entries(o)
        .map(([k, v]) => [k, Object.values(v)]))
    );

console.log(result);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

Body:
I'm trying to map Object.values() to extract just the values from an array of objects:

const countries = [
    {
        "austria": { value: 1},
        "canada": {value: 2},
        "nepal": { value: 3},
        "india": { value: 4}
    },
    {
        "australia": { value: 10},
        "france": { value: 20},
        "egypt": { value: 40},
        "usa": { value: 20}
    },
    {
        "mexico": { value: 3},
        "germany": { value: 100},
        "southAfrica": { value: 1},
        "china": { value: 10}
    }
]

To get:

// expected output
[
    {
        "austria": [ 1 ],
        "canada": [ 2 ],
        "nepal": [ 3 ],
        "india": [ 4 ]
    },
    {
        "australia": [ 10 ] ,
        "france": [ 20 ],
        "egypt": [ 40 ],
        "usa": [ 20 ]
    },
    {
        "mexico": [ 3 ],
        "germany": [ 100 ],
        "southAfrica": [ 1 ],
        "china": [ 10 ]
    }
]

I tried

Object.values(countries) // returns the same as `countries`

and also tried mapping using ramda's map() to map Object.values() over countries

const R = require("ramda")

R.map(Object.values, countries)
// gives:
// [
//   [ { value: 1 }, { value: 2 }, { value: 3 }, { value: 4 } ],
//   [ { value: 10 }, { value: 20 }, { value: 40 }, { value: 20 } ],
//   [ { value: 3 }, { value: 100 }, { value: 1 }, { value: 10 } ]
// ]

But I don't want to lose the countries names! How can I utilize either vanilla map or ramda's version to get the expected output?

Body:
You need to map the entries and the nested objects values.

const
    countries = [{ austria: { value: 1 }, canada: { value: 2 }, nepal: { value: 3 }, india: { value: 4 } }, { australia: { value: 10 }, france: { value: 20 }, egypt: { value: 40 }, usa: { value: 20 } }, { mexico: { value: 3 }, germany: { value: 100 }, southAfrica: { value: 1 }, china: { value: 10 } }],
    result = countries.map(o => Object.fromEntries(Object
        .entries(o)
        .map(([k, v]) => [k, Object.values(v)]))
    );

console.log(result);

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


问:
Docx - Replace element and set font-style?
i want to replace some paragraph-text in this docx-file:

This works generally fine using this code:

```<code>from docx import Document
from docx.shared import Pt
file = "template.docx"
doc = Document(file)
for idxPara, elemPara in enumerate(doc.paragraphs):
  if "«Kunde»" in elemPara.text:
    doc.paragraphs[idxPara].text = "Anderer Text für Kunde"
doc.save('TEST.docx')
</code>```

The output looks now like this:
(everything is ok but i want to change the font-style)

So i tried this code:

```<code>from docx import Document
from docx.shared import Pt

file = "template.docx"
doc = Document(file)

style = doc.styles['Normal']
font = style.font
font.name = 'Corbel'
font.size = Pt(10)

for idxPara, elemPara in enumerate(doc.paragraphs):
  if "«Kunde»" in elemPara.text:
    doc.paragraphs[idxPara].style = doc.styles['Normal']
    doc.paragraphs[idxPara].text = "Anderer Text für Kunde"

doc.save('TEST.docx')
</code>```

but unfortunately with this the style seems to work now - but the text in the paragraph is for whatevery reason on another position

How can i change the paragraph and also set the style of this paragraph?

答:
I think i found a solution for that - iterrating over the runs in the paragraph it seems that after replacement the style keeps the same:</p>
```<code>from docx import Document
    for idxPara, elemPara in enumerate(doc.paragraphs):
      for run in elemPara.runs:
        if "«Kunde»" in run.text:
          run.text = "Anderer Text"
</code>```

Body:
i want to replace some paragraph-text in this docx-file:

This works generally fine using this code:

from docx import Document
from docx.shared import Pt
file = "template.docx"
doc = Document(file)
for idxPara, elemPara in enumerate(doc.paragraphs):
  if "«Kunde»" in elemPara.text:
    doc.paragraphs[idxPara].text = "Anderer Text für Kunde"
doc.save('TEST.docx')

The output looks now like this:
(everything is ok but i want to change the font-style)

So i tried this code:

from docx import Document
from docx.shared import Pt

file = "template.docx"
doc = Document(file)

style = doc.styles['Normal']
font = style.font
font.name = 'Corbel'
font.size = Pt(10)

for idxPara, elemPara in enumerate(doc.paragraphs):
  if "«Kunde»" in elemPara.text:
    doc.paragraphs[idxPara].style = doc.styles['Normal']
    doc.paragraphs[idxPara].text = "Anderer Text für Kunde"

doc.save('TEST.docx')

but unfortunately with this the style seems to work now - but the text in the paragraph is for whatevery reason on another position

How can i change the paragraph and also set the style of this paragraph?

Body:
I think i found a solution for that - iterrating over the runs in the paragraph it seems that after replacement the style keeps the same:

from docx import Document
    for idxPara, elemPara in enumerate(doc.paragraphs):
      for run in elemPara.runs:
        if "«Kunde»" in run.text:
          run.text = "Anderer Text"


问:
Django Rest Framework - AttriubuteError: 'AutoSchema' object has no attribute 'get_link'
The following code is throwing me error when i run (http://127.0.0.1:8000/docs/):

```<code>from django.contrib import admin
from django.urls import path, include
from rest_framework.schemas import get_schema_view
from rest_framework.documentation import include_docs_urls

schema_view = get_schema_view(title='Blog API')

urlpatterns = [
    path('admin/', admin.site.urls),
    path('api/v1/', include('posts.urls')),
    path('api-auth/', include('rest_framework.urls')),  # Peculiar to rest_framework
    path('api/v1/rest-auth/', include('rest_auth.urls')),  # Peculiar to django-rest-auth package
    path('api/v1/rest-auth/registration/', include('rest_auth.registration.urls')),  # Peculiar to rest_auth app
    path('docs/', include_docs_urls(title='Blog API')),
    path('schema/', schema_view),
]
</code>```

Here is the error:

```<code>AttributeError: 'AutoSchema' object has no attribute 'get_link'
</code>```

Please Help suggest a potential solution

答:
add this to your settings.py</p>
```<code>REST_FRAMEWORK = {
  ...
  'DEFAULT_SCHEMA_CLASS': 'rest_framework.schemas.coreapi.AutoSchema'
}
</code>```

Body:
The following code is throwing me error when i run (http://127.0.0.1:8000/docs/):

from django.contrib import admin
from django.urls import path, include
from rest_framework.schemas import get_schema_view
from rest_framework.documentation import include_docs_urls

schema_view = get_schema_view(title='Blog API')

urlpatterns = [
    path('admin/', admin.site.urls),
    path('api/v1/', include('posts.urls')),
    path('api-auth/', include('rest_framework.urls')),  # Peculiar to rest_framework
    path('api/v1/rest-auth/', include('rest_auth.urls')),  # Peculiar to django-rest-auth package
    path('api/v1/rest-auth/registration/', include('rest_auth.registration.urls')),  # Peculiar to rest_auth app
    path('docs/', include_docs_urls(title='Blog API')),
    path('schema/', schema_view),
]

Here is the error:

AttributeError: 'AutoSchema' object has no attribute 'get_link'

Please Help suggest a potential solution

Body:
add this to your settings.py

REST_FRAMEWORK = {
  ...
  'DEFAULT_SCHEMA_CLASS': 'rest_framework.schemas.coreapi.AutoSchema'
}


问:
How to add one component in another based on event in React?
I have two components. A SearchBar and a NavBar. In the homepage I have the searchBar in the middle but when I input something for the first time, I have redirected the user to another page where the SearchBar component gets nested into the Navbar and the suits get displayed.

What is a good/best way to achieve this for a beginner in React? And how would I go about it?

```<code>const Search = () => {

    let location = useLocation();
    let navigate = useNavigate();
    const handleKeyDown = (event) => {
        if (event.key === 'Enter') {
            if (location.pathname === '/') {
                navigate('./List');
            }
        }
    }

    return (
        <div className="searchbar-container">
            <input className="searchbar" placeholder="get" onKeyDown={handleKeyDown}></input>
        </div>
    )
}
</code>```
```<code>const Navbar = () => {
        return (
        <nav className='navigation'>
            <div className='left-slot'>
                <button>TITLE</button>
            </div>
            <div className='right-slot'>
                <button>LINK</button>
                <button>LINK</button>
            </div>
        </nav>
    )
}
</code>```
```<code>const Home = () => {
    return (
        <Search></Search>
    )
}
</code>```
```<code>function App() {

  return (
    <Router>
        <Navbar></Navbar>
        <Routes>
        <Route exact path='/' element={<Home />} />
        <Route path='/List' element={<List />} />
        </Routes>
    </Router>
  );
}

</code>```

答:
You can call the component  on your NavBar and push the search string on the url (like params) or with the location state (but the first is better).

something like that :

```<code>if (event.key === 'Enter') {
 if (location.pathname === '/') {
  navigate(`./List/${searchValue}`);
 }
}
</code>```

and for the List page :

```<code>const {search} = useParams() // from router
</code>```

also you need to add on your list route :

```<code><Route path='/list/:search' element={<List />} />
</code>```

Say me if it's good for you

Body:
I have two components. A SearchBar and a NavBar. In the homepage I have the searchBar in the middle but when I input something for the first time, I have redirected the user to another page where the SearchBar component gets nested into the Navbar and the suits get displayed.

What is a good/best way to achieve this for a beginner in React? And how would I go about it?

const Search = () => {

    let location = useLocation();
    let navigate = useNavigate();
    const handleKeyDown = (event) => {
        if (event.key === 'Enter') {
            if (location.pathname === '/') {
                navigate('./List');
            }
        }
    }

    return (

            <input className="searchbar" placeholder="get" onKeyDown={handleKeyDown}></input>

    )
}

const Navbar = () => {
        return (

                <button>TITLE</button>

                <button>LINK</button>
                <button>LINK</button>

    )
}

const Home = () => {
    return (
        <Search></Search>
    )
}

function App() {

  return (
    <Router>
        <Navbar></Navbar>
        <Routes>
        <Route exact path='/' element={<Home />} />
        <Route path='/List' element={<List />} />
        </Routes>
    </Router>
  );
}

Body:
You can call the component  on your NavBar and push the search string on the url (like params) or with the location state (but the first is better).

something like that :

if (event.key === 'Enter') {
 if (location.pathname === '/') {
  navigate(`./List/${searchValue}`);
 }
}

and for the List page :

const {search} = useParams() // from router

also you need to add on your list route :

<Route path='/list/:search' element={<List />} />

Say me if it's good for you


问:
hvplot points with geo true does not show the map
```<code>all_neighborhoods_df.hvplot.points('Lon', 'Lat', geo=True, color="gross_rent",
                               size="sale_price_sqr_foot", frame_height=500,
                               frame_width=700, title="Neighborhood Map")
</code>```

When I looked through the documentation it said that having geo=True will bring the map but the result I received is this:

The result I should get is something like this:

答: The geo parameter just makes hvplot aware of your intention to display geographic data and as such it will handle projecting the data. You need to define tiles (e g. 'ESRI') to get a basemap (this is shown in the first example of the geographic user guide of the documentation).

Body:
all_neighborhoods_df.hvplot.points('Lon', 'Lat', geo=True, color="gross_rent",
                               size="sale_price_sqr_foot", frame_height=500,
                               frame_width=700, title="Neighborhood Map")

When I looked through the documentation it said that having geo=True will bring the map but the result I received is this:

The result I should get is something like this:


问:
Having trouble with check = True using on_raw_reaction_add
I'm having trouble with my check = True. I can't seem to get identify the member making the reaction. Here is the code:</p>
```<code>@bot.command()
async def buy(ctx):
    reaction = await ctx.reply('Pick \U0001f44d')

@bot.event
async def on_raw_reaction_add(payload: discord.RawReactionActionEvent):
    def check(pl):
        return pl == payload.member and str(payload.emoji) == '\U0001f44d'
    try:
        pl = await bot.wait_for('raw_reaction_add', timeout=3.0, check=check)
    except asyncio.TimeoutError:
            await channel.send("no one picked")
            await payload.member.send("you")
    else:
        if payload.emoji == '\U0001f44d':
            await channel.send("you picked 1")```

My I idea is to have someone call the command and then allowing more than one member to be able to react thus the bot.event. What am I doing wrong for my check to not = True?
</code>```

答:
Maybe you have an issue with the check
I suggest to replace your check with this:

check = lambda payload: payload.message_id == msg.id and payload.channel_id == ctx.channel.id and str(payload.emoji) == '\U0001f44d'

payload = await client.wait_for('raw_reaction_add', check=check, timeout=30)

```

Body:
I'm having trouble with my check = True. I can't seem to get identify the member making the reaction. Here is the code:

@bot.command()
async def buy(ctx):
    reaction = await ctx.reply('Pick \U0001f44d')

@bot.event
async def on_raw_reaction_add(payload: discord.RawReactionActionEvent):
    def check(pl):
        return pl == payload.member and str(payload.emoji) == '\U0001f44d'
    try:
        pl = await bot.wait_for('raw_reaction_add', timeout=3.0, check=check)
    except asyncio.TimeoutError:
            await channel.send("no one picked")
            await payload.member.send("you")
    else:
        if payload.emoji == '\U0001f44d':
            await channel.send("you picked 1")```

My I idea is to have someone call the command and then allowing more than one member to be able to react thus the bot.event. What am I doing wrong for my check to not = True?


答:
You mean

const arr = ["1", "2"]
$('[name^=tom]').val(function(i) {
  return arr[i]
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" name="tom[]" value="" /><br>
<input type="text" name="tom[]" value="" /><br></code>```

or

```<code>$('[name^=tom]').each(function() {
  async_request.push($.ajax({
    url:'back.php',
    method:'post',
    data:{user_name: this.value },
</code>```

Title: how to pass values from multiple textfields with same name attributes to a variable in form of an array

Body:
You mean

const arr = ["1", "2"]
$('[name^=tom]').val(function(i) {
  return arr[i]
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" name="tom[]" value="" /><br>
<input type="text" name="tom[]" value="" /><br>

or

$('[name^=tom]').each(function() {
  async_request.push($.ajax({
    url:'back.php',
    method:'post',
    data:{user_name: this.value },


问:
SQL: how to use split_part in a multi table query?
I am using PostgreSQL and Windows.

I have a diagram of the tables and their relationships:

I am trying to produce a result that has firstname, lastname and country.

firstname = because I only have "givenname" which includes first+middle names, I need to use "split_part" function to extract only the first name.

However, I cannot produce the results:

```<code>SELECT a.split_part(givenname, ' ', 1) AS "First Name", a.lastname AS "Last Name", b."Name" AS "Country" FROM employee as a, country as b
WHERE a.countryoforigin = b.countryID
ORDER BY givenname;
</code>```

this shows error:

Now, if I don't use split_part, and directly use "givenname":

```<code>SELECT "givenname" AS "First Name", a.lastname AS "Last Name", b."Name" AS "Country" FROM employee as a, country as b
WHERE a.countryoforigin = b.countryID
ORDER BY givenname;
</code>```

Is there a way to produce the result using split_part function? What would be the query?

答:
You seem to be using “a.split_part” for some reason, the function is just “split_part”. Table aliases are used with columns, not functions.
Therefore, the syntax should be: split_part(a.givenname.....

By the way, the Oracle-style join syntax you are using was superseded by ANSI join syntax about 30 years ago; you really ought to stop using it.

Here is one article about this:

https://oracle-base.com/articles/misc/sql-for-beginners-joins

Body:
I am using PostgreSQL and Windows.

I have a diagram of the tables and their relationships:

I am trying to produce a result that has firstname, lastname and country.

firstname = because I only have "givenname" which includes first+middle names, I need to use "split_part" function to extract only the first name.

However, I cannot produce the results:

SELECT a.split_part(givenname, ' ', 1) AS "First Name", a.lastname AS "Last Name", b."Name" AS "Country" FROM employee as a, country as b
WHERE a.countryoforigin = b.countryID
ORDER BY givenname;

this shows error:

Now, if I don't use split_part, and directly use "givenname":

SELECT "givenname" AS "First Name", a.lastname AS "Last Name", b."Name" AS "Country" FROM employee as a, country as b
WHERE a.countryoforigin = b.countryID
ORDER BY givenname;

Is there a way to produce the result using split_part function? What would be the query?


问:
type 'double' is not a subtype of type 'int' when decoding data from json + returns null
Every time the data has to be decoded it returns null and the exception type 'double' is not a subtype of type 'int'. The problem is the method attached below.

```<code>Future<void> fetchProducts() async {
    final url = Uri.parse(
        'https://recipier-e1139-default-rtdb.europe-west1.firebasedatabase.app/recipes.json');
    final response = await http.get(url);
    final extractedData = json.decode(response.body) as Map<String, dynamic>;
    print(extractedData['title']);
    if (extractedData.isEmpty || extractedData['error'] != null) {
      return;
    }
    List<Recipe> loadedRecipes = [];
    extractedData.forEach(
      (id, data) {
        loadedRecipes.add(
          Recipe(
            title: data['title'],
            description: data['description'],
            id: id,
            ingredients: data['ingredients'].cast<String>(),
            steps: data['steps'].cast<String>(),
            kcal: data['kcal'],
            p: data['p'],
            c: data['c'],
            f: data['f'],
            servings: data['servings'],
          ),
        );
      },
    );
    _recipes = loadedRecipes;
    notifyListeners();
  }
</code>```

Here is my recipe model

```<code>class Recipe with ChangeNotifier {
  String title;
  String id;
  String description;
  File? image;
  bool favorite;
  List<String> ingredients;
  List<String> steps;
  int servings;
  int kcal;
  int p;
  int c;
  int f;

  Recipe({
    required this.title,
    required this.description,
    this.favorite = false,
    required this.id,
    this.image,
    required this.ingredients,
    required this.steps,
    required this.c,
    required this.kcal,
    required this.f,
    required this.p,
    required this.servings,
  });
</code>```

I/flutter (31885): null E/flutter (31885):
[ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: type
'double' is not a subtype of type 'int' E/flutter (31885): #0

RecipeProvider.fetchProducts.
package:recipier/providers/recipes_provider.dart:39 E/flutter (31885):
#1      _LinkedHashMapMixin.forEach (dart:collection-patch/compact_hash.dart:539:8) E/flutter (31885): #2
RecipeProvider.fetchProducts
package:recipier/providers/recipes_provider.dart:30 E/flutter (31885):

答: Use num type if you're not sure if the expected data is int or double. Also, if your app is null-safety aware and expected data can be null, use num? type.

Body:
Every time the data has to be decoded it returns null and the exception type 'double' is not a subtype of type 'int'. The problem is the method attached below.

Future<void> fetchProducts() async {
    final url = Uri.parse(
        'https://recipier-e1139-default-rtdb.europe-west1.firebasedatabase.app/recipes.json');
    final response = await http.get(url);
    final extractedData = json.decode(response.body) as Map<String, dynamic>;
    print(extractedData['title']);
    if (extractedData.isEmpty || extractedData['error'] != null) {
      return;
    }
    List<Recipe> loadedRecipes = [];
    extractedData.forEach(
      (id, data) {
        loadedRecipes.add(
          Recipe(
            title: data['title'],
            description: data['description'],
            id: id,
            ingredients: data['ingredients'].cast<String>(),
            steps: data['steps'].cast<String>(),
            kcal: data['kcal'],
            p: data['p'],
            c: data['c'],
            f: data['f'],
            servings: data['servings'],
          ),
        );
      },
    );
    _recipes = loadedRecipes;
    notifyListeners();
  }

Here is my recipe model

class Recipe with ChangeNotifier {
  String title;
  String id;
  String description;
  File? image;
  bool favorite;
  List<String> ingredients;
  List<String> steps;
  int servings;
  int kcal;
  int p;
  int c;
  int f;

  Recipe({
    required this.title,
    required this.description,
    this.favorite = false,
    required this.id,
    this.image,
    required this.ingredients,
    required this.steps,
    required this.c,
    required this.kcal,
    required this.f,
    required this.p,
    required this.servings,
  });

I/flutter (31885): null E/flutter (31885):
[ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: type
'double' is not a subtype of type 'int' E/flutter (31885): #0

RecipeProvider.fetchProducts.
package:recipier/providers/recipes_provider.dart:39 E/flutter (31885):
#1      _LinkedHashMapMixin.forEach (dart:collection-patch/compact_hash.dart:539:8) E/flutter (31885): #2
RecipeProvider.fetchProducts
package:recipier/providers/recipes_provider.dart:30 E/flutter (31885):


问:
My scene gets duplicated when I try to access it more than once at runtime
Current situation - On pressing 1,2,3 on the keyboard, it toggles through 3 different scenes.

The problem:

For instance, during the runtime, I press: 1 -> (Scene 1), 2 -> (Scene 2), 3 -> (Scene 3) and then again: 1 -> (Scene 1), its loading the scene but also makes a copy of that scene.

A screenshot of the Hierarchy

My Scene Loading code:

```<code>    private IEnumerator SceneLoader(string sceneName)
{
    if (!SceneManager.GetSceneByName(sceneName).isLoaded)
    {
        currentScene = SceneManager.GetActiveScene();
        AsyncOperation loadScene = SceneManager.LoadSceneAsync(sceneName, LoadSceneMode.Additive);

        asyncScene = loadScene;

        while (!asyncScene.isDone)
        {
            Debug.Log("Scene Loading: " + loadScene.progress);
            yield return null;
        }

        Scene getScene = SceneManager.GetSceneByName(sceneName);

        while (!getScene.isLoaded)
        {
            Debug.Log("Scene loading!!");
            yield return null;
        }

        Debug.Log("Scene name: " + getScene.name);
        if (getScene.IsValid())
        {
            SceneManager.MoveGameObjectToScene(this.gameObject, getScene);
            SceneManager.SetActiveScene(getScene);
            ShiftItems(getScene);
        }

        Debug.Log("Scene name to unload: " + currentScene.name);
        SceneManager.UnloadSceneAsync(currentScene);
    }
    yield return null;
}
</code>```

Update:
After debugging more into this issue, I realized this:
For instance, you have 3 scenes: Main Menu (Scene 1), Settings (Scene 2) and Pause Menu (Scene 3).
Now what I was doing is that I was having all the Game Objects (which were to be moved to the other scenes) in the Main Menu. Now when I toggled through the scenes and go from Scene 3 to Scene 1 again...
It seemed like it was taking inputs from 2 duplicated objects which had the input script attached and the starting scene was never unloaded for some reason I dunno yet. There is something fishy about the start point.

Fix:
What I did?

Create an empty scene.

Get all the Game Objects you want to keep throughout the different scenes in there.

Attach a script to a game object which in my case its the scene manager where you change the scene: Empty Scene -> Scene 1 (In my case its the main menu scene)

So, since the issue was something related to the starting scene, with this approach you won't have to return to the starting scene since that's the empty scene

Hope this helps

答:
You load your scene additive. Therefore having never tried it it probably can be loaded multiple times.

Remember to hide and show the scene not keep reloading it

Body:
Current situation - On pressing 1,2,3 on the keyboard, it toggles through 3 different scenes.

The problem:

For instance, during the runtime, I press: 1 -> (Scene 1), 2 -> (Scene 2), 3 -> (Scene 3) and then again: 1 -> (Scene 1), its loading the scene but also makes a copy of that scene.

A screenshot of the Hierarchy

My Scene Loading code:

    private IEnumerator SceneLoader(string sceneName)
{
    if (!SceneManager.GetSceneByName(sceneName).isLoaded)
    {
        currentScene = SceneManager.GetActiveScene();
        AsyncOperation loadScene = SceneManager.LoadSceneAsync(sceneName, LoadSceneMode.Additive);

        asyncScene = loadScene;

        while (!asyncScene.isDone)
        {
            Debug.Log("Scene Loading: " + loadScene.progress);
            yield return null;
        }

        Scene getScene = SceneManager.GetSceneByName(sceneName);

        while (!getScene.isLoaded)
        {
            Debug.Log("Scene loading!!");
            yield return null;
        }

        Debug.Log("Scene name: " + getScene.name);
        if (getScene.IsValid())
        {
            SceneManager.MoveGameObjectToScene(this.gameObject, getScene);
            SceneManager.SetActiveScene(getScene);
            ShiftItems(getScene);
        }

        Debug.Log("Scene name to unload: " + currentScene.name);
        SceneManager.UnloadSceneAsync(currentScene);
    }
    yield return null;
}

Update:
After debugging more into this issue, I realized this:
For instance, you have 3 scenes: Main Menu (Scene 1), Settings (Scene 2) and Pause Menu (Scene 3).
Now what I was doing is that I was having all the Game Objects (which were to be moved to the other scenes) in the Main Menu. Now when I toggled through the scenes and go from Scene 3 to Scene 1 again...
It seemed like it was taking inputs from 2 duplicated objects which had the input script attached and the starting scene was never unloaded for some reason I dunno yet. There is something fishy about the start point.

Fix:
What I did?

Create an empty scene.

Get all the Game Objects you want to keep throughout the different scenes in there.

Attach a script to a game object which in my case its the scene manager where you change the scene: Empty Scene -> Scene 1 (In my case its the main menu scene)

So, since the issue was something related to the starting scene, with this approach you won't have to return to the starting scene since that's the empty scene

Hope this helps


问:
Unable to start activity: SQLITE_ERROR (no such table: TABLE_NAME)
Background:
I'm new to Android, I've a database in the assets folder and the user is supposed to be able to search that database from the action bar.
I don't create that database from the code itself, instead, when the app is launched for the first time, an empty database is created and my database gets copied to that empty database.
Right now, when I try to search the app craches due to the below error.
I've copied/edited the code from this link.

Solutions tried

I've went through answers on stackoverflow.com and from the comments
section in the above link. it seems that most of those who managed
to solve that error closed the database in different places in the
code (db.close). I've tried placing a closing statement as commented
in my code but in vain.

I know that one of the raised points is never to hardcode the path of the db, so I Checked that the table does exist!

Uninstalled, cleared cache, changed db version number. Still the same

Error:

java.lang.RuntimeException: Unable to start activity
ComponentInfo{com.amgad.hayy/com.amgad.hayy.SearchableActivity}:
android.database.sqlite.SQLiteException: no such table: places (code
1): , while compiling: SELECT type, name FROM places WHERE _id=?

Error Code : 1 (SQLITE_ERROR) Caused By : SQL(query) error or missing
database. (no such table: places (code 1): , while compiling: SELECT
type, name FROM places WHERE _id=?)

Complete LogCat

11-20 10:52:35.231 28023-28023/com.amgad.hayy E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.amgad.hayy, PID: 28023
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.amgad.hayy/com.amgad.hayy.SearchableActivity}: android.database.sqlite.SQLiteException: no such table: places (code 1): , while compiling: SELECT type, name FROM places WHERE _id=?
#################################################################
Error Code : 1 (SQLITE_ERROR)
Caused By : SQL(query) error or missing database.
(no such table: places (code 1): , while compiling: SELECT type, name FROM places WHERE _id=?)
at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3319)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3415)
at android.app.ActivityThread.access$1100(ActivityThread.java:229)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1821)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:7331)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
Caused by: android.database.sqlite.SQLiteException: no such table:
places (code 1): , while compiling: SELECT type, name FROM places
WHERE _id=?
#################################################################
Error Code : 1 (SQLITE_ERROR)
Caused By : SQL(query) error or missing database.
(no such table: places (code 1): , while compiling: SELECT type, name FROM
places WHERE _id=?)
#################################################################
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native
Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:1000)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:565)
at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
at android.database.sqlite.SQLiteProgram.(SQLiteProgram.java:59)
at android.database.sqlite.SQLiteQuery.(SQLiteQuery.java:37)
at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:44)
at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1476)
at android.database.sqlite.SQLiteDatabase.queryWithFactory(SQLiteDatabase.java:1323)
at android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1194)
at android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1362)
at com.amgad.hayy.data.HayyDbHelper.getAllEmployeesDescription(HayyDbHelper.java:228)
at com.amgad.hayy.SearchableActivity.showPlaceName(SearchableActivity.java:52)
at com.amgad.hayy.SearchableActivity.onCreate(SearchableActivity.java:44)
at android.app.Activity.performCreate(Activity.java:6904)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1136)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3266)
... 9 more

Code

public class HayyDbHelper extends SQLiteOpenHelper

```<code>private static String DB_PATH = "/data/data/com.amgad.hayy/databases/";
static final String DB_NAME = "hayy.db";
private SQLiteDatabase myDataBase;
private final Context myContext;
private static final int DB_VERSION = 1;

public static final String TABLE_NAME = "places";
public static final String COLUMN_PLACE_ID = "_id";
public static final String COLUMN_MONUMENT_NUMBER = "monument_number";
public static final String COLUMN_TYPE = "type";
public static final String COLUMN_NAME = "name";

public HayyDbHelper(Context context) {
    super(context, DB_NAME, null, DB_VERSION);
    this.myContext = context;
}

public void createDb() throws IOException{
    boolean dbExists = checkDb();
    //SQLiteDatabase db_Read = null;
    if(dbExists){
        //do nothing, db already exists
    }else{

        //By calling this method an empty database will be created into the default system path
        //of the application so we are gonna be able to overwrite that database with our database.
        //db_Read = this.getReadableDatabase();
        //db_Read.close();
        this.getReadableDatabase();
        try{
           // this.close();
            copyDb();

        }catch(IOException e){
            throw new Error("Error copying database");
        }
    }
    //this.close();
}

private boolean checkDb(){

    File databasePath = myContext.getDatabasePath(DB_NAME);
    return databasePath.exists();

}

private void copyDb() throws IOException{

    //Open your local db as the input stream
    InputStream myInput = myContext.getAssets().open(DB_NAME);

    //Path to the just created empty db
    String outFileName = DB_PATH + DB_NAME;

    //Open the empty db as the output stream
    OutputStream myOutput = new FileOutputStream(outFileName);

    //transfer bytes from the inputfile to the outputfile
    byte[] buffer = new byte[1024];
    int length;
    while ((length = myInput.read(buffer))>0){
        myOutput.write(buffer, 0, length);
    }

    //Close the streams
    myOutput.flush();
    myOutput.close();
    myInput.close();
}

public void openDb() throws SQLException {

    //Open the database
    String myPath = DB_PATH + DB_NAME;
    myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
}

@Override
public synchronized void close() {

    if(myDataBase != null)
        myDataBase.close();

    super.close();
}

@Override
public void onCreate(SQLiteDatabase db) {

}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion){
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
    onCreate(db);
}

public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    onUpgrade(db, oldVersion, newVersion);
}

public ArrayList<String> getAllName() {
    SQLiteDatabase db = this.getReadableDatabase();
    ArrayList<String> pNames = new ArrayList<String>();
    Cursor cursor = db.query(TABLE_NAME, null, null, null, null, null, null);

    if (cursor != null && cursor.getCount() > 0) {
        cursor.moveToFirst();

        do {
            String name = cursor.getString(cursor.getColumnIndex(COLUMN_NAME));

            pNames.add(name);

        } while (cursor.moveToNext());

    }

    cursor.close();
    db.close();

    return pNames;
}

public Cursor getAllEmployeesDescription(int id) {
    SQLiteDatabase db = this.getReadableDatabase();
    String[] selections = {String.valueOf(id)};
    String columns[] = {COLUMN_TYPE, COLUMN_NAME};

    Cursor cursor = db.query(TABLE_NAME, columns, COLUMN_PLACE_ID + "=?",
            selections, null, null, null);
    //db.close();
    return cursor;
}
</code>```

Main Method

```<code>protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    myDatabaseHelper = new HayyDbHelper(MainActivity.this);

    try {
        myDatabaseHelper.createDb();

    } catch (IOException ioe) {

        throw new Error("Unable to create database");

    }

    try {
        myDatabaseHelper.openDb();

    }catch(SQLException sqle){

        throw sqle;
    }
}
</code>```

答:
Try this

```<code>public class DatabaseHelper extends SQLiteOpenHelper {

    public final static String DATABASE_NAME = "GroceryCart.db";

    public DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, 4);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        //db.execSQL("CREATE TABLE IF NOT EXISTS "+TABLE_NAME+"(ID INTEGER PRIMARY KEY AUTOINCREMENT,NAME TEXT,WEIGHT TEXT,COST TEXT,QUANTITY TEXT,IMAGE TEXT,USER_ID TEXT)");

        final String SQL_CREATE_GROCERYLIST_TABLE = "CREATE TABLE "+
                <Table Name>+" ("+
                <Column Name>+" INTEGER PRIMARY KEY AUTOINCREMENT, "+
               <Column Name>+" TEXT NOT NULL, "+
                <Column Name>+" TEXT NOT NULL, "+
                ");";

        db.execSQL(SQL_CREATE_GROCERYLIST_TABLE);

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS "+GroceryEntry.TABLE_NAME);
        onCreate(db);
    }
}

</code>```

Then intialize it in your class like

```<code>        SQLiteDatabase mDatabase;
        DatabaseHelper dbHelper = new DatabaseHelper(getApplicationContext());
        mDatabase = dbHelper.getWritableDatabase();
</code>```

Now do the required operations using the mDatabase object.

Body:
Background:
I'm new to Android, I've a database in the assets folder and the user is supposed to be able to search that database from the action bar.
I don't create that database from the code itself, instead, when the app is launched for the first time, an empty database is created and my database gets copied to that empty database.
Right now, when I try to search the app craches due to the below error.
I've copied/edited the code from this link.

Solutions tried

I've went through answers on stackoverflow.com and from the comments
section in the above link. it seems that most of those who managed
to solve that error closed the database in different places in the
code (db.close). I've tried placing a closing statement as commented
in my code but in vain.

I know that one of the raised points is never to hardcode the path of the db, so I Checked that the table does exist!

Uninstalled, cleared cache, changed db version number. Still the same

Error:

java.lang.RuntimeException: Unable to start activity
ComponentInfo{com.amgad.hayy/com.amgad.hayy.SearchableActivity}:
android.database.sqlite.SQLiteException: no such table: places (code
1): , while compiling: SELECT type, name FROM places WHERE _id=?

Error Code : 1 (SQLITE_ERROR) Caused By : SQL(query) error or missing
database. (no such table: places (code 1): , while compiling: SELECT
type, name FROM places WHERE _id=?)

Complete LogCat

11-20 10:52:35.231 28023-28023/com.amgad.hayy E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.amgad.hayy, PID: 28023
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.amgad.hayy/com.amgad.hayy.SearchableActivity}: android.database.sqlite.SQLiteException: no such table: places (code 1): , while compiling: SELECT type, name FROM places WHERE _id=?
#################################################################
Error Code : 1 (SQLITE_ERROR)
Caused By : SQL(query) error or missing database.
(no such table: places (code 1): , while compiling: SELECT type, name FROM places WHERE _id=?)
at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3319)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3415)
at android.app.ActivityThread.access$1100(ActivityThread.java:229)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1821)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:7331)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
Caused by: android.database.sqlite.SQLiteException: no such table:
places (code 1): , while compiling: SELECT type, name FROM places
WHERE _id=?
#################################################################
Error Code : 1 (SQLITE_ERROR)
Caused By : SQL(query) error or missing database.
(no such table: places (code 1): , while compiling: SELECT type, name FROM
places WHERE _id=?)
#################################################################
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native
Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:1000)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:565)
at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
at android.database.sqlite.SQLiteProgram.(SQLiteProgram.java:59)
at android.database.sqlite.SQLiteQuery.(SQLiteQuery.java:37)
at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:44)
at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1476)
at android.database.sqlite.SQLiteDatabase.queryWithFactory(SQLiteDatabase.java:1323)
at android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1194)
at android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1362)
at com.amgad.hayy.data.HayyDbHelper.getAllEmployeesDescription(HayyDbHelper.java:228)
at com.amgad.hayy.SearchableActivity.showPlaceName(SearchableActivity.java:52)
at com.amgad.hayy.SearchableActivity.onCreate(SearchableActivity.java:44)
at android.app.Activity.performCreate(Activity.java:6904)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1136)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3266)
... 9 more

Code

public class HayyDbHelper extends SQLiteOpenHelper

private static String DB_PATH = "/data/data/com.amgad.hayy/databases/";
static final String DB_NAME = "hayy.db";
private SQLiteDatabase myDataBase;
private final Context myContext;
private static final int DB_VERSION = 1;

public static final String TABLE_NAME = "places";
public static final String COLUMN_PLACE_ID = "_id";
public static final String COLUMN_MONUMENT_NUMBER = "monument_number";
public static final String COLUMN_TYPE = "type";
public static final String COLUMN_NAME = "name";

public HayyDbHelper(Context context) {
    super(context, DB_NAME, null, DB_VERSION);
    this.myContext = context;
}

public void createDb() throws IOException{
    boolean dbExists = checkDb();
    //SQLiteDatabase db_Read = null;
    if(dbExists){
        //do nothing, db already exists
    }else{

        //By calling this method an empty database will be created into the default system path
        //of the application so we are gonna be able to overwrite that database with our database.
        //db_Read = this.getReadableDatabase();
        //db_Read.close();
        this.getReadableDatabase();
        try{
           // this.close();
            copyDb();

        }catch(IOException e){
            throw new Error("Error copying database");
        }
    }
    //this.close();
}

private boolean checkDb(){

    File databasePath = myContext.getDatabasePath(DB_NAME);
    return databasePath.exists();

}

private void copyDb() throws IOException{

    //Open your local db as the input stream
    InputStream myInput = myContext.getAssets().open(DB_NAME);

    //Path to the just created empty db
    String outFileName = DB_PATH + DB_NAME;

    //Open the empty db as the output stream
    OutputStream myOutput = new FileOutputStream(outFileName);

    //transfer bytes from the inputfile to the outputfile
    byte[] buffer = new byte[1024];
    int length;
    while ((length = myInput.read(buffer))>0){
        myOutput.write(buffer, 0, length);
    }

    //Close the streams
    myOutput.flush();
    myOutput.close();
    myInput.close();
}

public void openDb() throws SQLException {

    //Open the database
    String myPath = DB_PATH + DB_NAME;
    myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
}

@Override
public synchronized void close() {

    if(myDataBase != null)
        myDataBase.close();

    super.close();
}

@Override
public void onCreate(SQLiteDatabase db) {

}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion){
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
    onCreate(db);
}

public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    onUpgrade(db, oldVersion, newVersion);
}

public ArrayList<String> getAllName() {
    SQLiteDatabase db = this.getReadableDatabase();
    ArrayList<String> pNames = new ArrayList<String>();
    Cursor cursor = db.query(TABLE_NAME, null, null, null, null, null, null);

    if (cursor != null && cursor.getCount() > 0) {
        cursor.moveToFirst();

        do {
            String name = cursor.getString(cursor.getColumnIndex(COLUMN_NAME));

            pNames.add(name);

        } while (cursor.moveToNext());

    }

    cursor.close();
    db.close();

    return pNames;
}

public Cursor getAllEmployeesDescription(int id) {
    SQLiteDatabase db = this.getReadableDatabase();
    String[] selections = {String.valueOf(id)};
    String columns[] = {COLUMN_TYPE, COLUMN_NAME};

    Cursor cursor = db.query(TABLE_NAME, columns, COLUMN_PLACE_ID + "=?",
            selections, null, null, null);
    //db.close();
    return cursor;
}

Main Method

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    myDatabaseHelper = new HayyDbHelper(MainActivity.this);

    try {
        myDatabaseHelper.createDb();

    } catch (IOException ioe) {

        throw new Error("Unable to create database");

    }

    try {
        myDatabaseHelper.openDb();

    }catch(SQLException sqle){

        throw sqle;
    }
}

Body:
Try this

public class DatabaseHelper extends SQLiteOpenHelper {

    public final static String DATABASE_NAME = "GroceryCart.db";

    public DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, 4);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        //db.execSQL("CREATE TABLE IF NOT EXISTS "+TABLE_NAME+"(ID INTEGER PRIMARY KEY AUTOINCREMENT,NAME TEXT,WEIGHT TEXT,COST TEXT,QUANTITY TEXT,IMAGE TEXT,USER_ID TEXT)");

        final String SQL_CREATE_GROCERYLIST_TABLE = "CREATE TABLE "+
                <Table Name>+" ("+
                <Column Name>+" INTEGER PRIMARY KEY AUTOINCREMENT, "+
               <Column Name>+" TEXT NOT NULL, "+
                <Column Name>+" TEXT NOT NULL, "+
                ");";

        db.execSQL(SQL_CREATE_GROCERYLIST_TABLE);

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS "+GroceryEntry.TABLE_NAME);
        onCreate(db);
    }
}

Then intialize it in your class like

        SQLiteDatabase mDatabase;
        DatabaseHelper dbHelper = new DatabaseHelper(getApplicationContext());
        mDatabase = dbHelper.getWritableDatabase();

Now do the required operations using the mDatabase object.


问:
Optimization variables of a neural network model with simulated annealing
I implement an MLP neural network model on the data, for optimization 4 variables a function base on the MLP model is defined, and simulated annealing run on this function. I don't know why I get this error (attached below).

Neural network code:

```<code># mlp for regression
from numpy import sqrt
from pandas import read_csv
from sklearn.model_selection import train_test_split
from tensorflow.keras import Sequential
from tensorflow.keras.layers import Dense
import tensorflow
from tensorflow import keras
from matplotlib import pyplot
from keras.layers import Dropout
from tensorflow.keras import regularizers

# determine the number of input features
n_features = X_train.shape[1]
# define model
model = Sequential()
model.add(Dense(150, activation='tanh', kernel_initializer='zero',kernel_regularizer=regularizers.l2(0.001), input_shape=(n_features,))) #relu/softmax/tanh
model.add(Dense(100, activation='tanh', kernel_initializer='zero',kernel_regularizer=regularizers.l2(0.001)))
model.add(Dense(50, activation='tanh', kernel_initializer='zero',kernel_regularizer=regularizers.l2(0.001)))
model.add(Dropout(0.0))
model.add(Dense(1))
# compile the model
opt= keras.optimizers.Adam(learning_rate=0.001)
#opt = tensorflow.keras.optimizers.RMSprop(learning_rate=0.001,rho=0.9,momentum=0.0,epsilon=1e-07,centered=False,name="RMSprop")
model.compile(optimizer=opt, loss='mse')
# fit the model
history=model.fit(X_train, y_train, validation_data = (X_test,y_test), epochs=100, batch_size=10, verbose=0,validation_split=0.3)
# evaluate the model
error = model.evaluate(X_test, y_test, verbose=0)
print('MSE: %.3f, RMSE: %.3f' % (error, sqrt(error)))
# plot learning curves
pyplot.title('Learning Curves')
pyplot.xlabel('Epoch')
pyplot.ylabel('Cross Entropy')
pyplot.plot(history.history['loss'], label='train')
pyplot.plot(history.history['val_loss'], label='val')
pyplot.legend()
pyplot.show()
</code>```

function code:

```<code>def objective_function(X):
  wob   = X[0]
  torque= X[1]
  RPM   = X[2]
  pump  = X[3]
  input=[wob,torque,RPM, 0.00017,0.027,pump,0,0.5,0.386,0.026,0.0119,0.33,0.83,0.48]
  input = pd.DataFrame(input)
  obj= model.predict(input)
  return obj
</code>```

simulated annealing for optimization:

```<code>import time
import random
import math
import numpy as np

## custom section
initial_temperature = 100
cooling = 0.8 # cooling coef.
number_variables = 4
upper_bounds = [1,1,1,1]
lower_bounds = [0,0,0,0]
computing_time = 1 # seconds

## simulated Annealing algorithm

## 1. Genertate an initial solution randomly
initial_solution = np.zeros((number_variables))
for v in range(number_variables):
    initial_solution[v] = random.uniform(lower_bounds[v], upper_bounds[v])
current_solution = initial_solution
best_solution = initial_solution
n=1 # no of solutions accepted
best_fitness = objective_function(best_solution)
current_temperature = initial_temperature # current temperature
start = time.time()
no_attemps = 100 # number of attemps in each level of temperature
record_best_fitness = []

for i in range(9999999):
    for j in range(no_attemps):
        for k in range(number_variables):
            ## 2. generate a candidate solution y randomly based on solution x
            current_solution[k] = best_solution[k] + 0.1*(random.uniform(lower_bounds[k], upper_bounds[k]))
            current_solution[k] = max(min(current_solution[k], upper_bounds[k]), lower_bounds[k]) # repaire the solution respecting the bounds

  ## 3. check if y is better than x
        current_fitness = objective_function(current_solution)
        E = abs(current_fitness - best_solution)
        if i==0 and j==0:
            EA = E
        if current_fitness < best_fitness:
            p = math.exp(-E/(EA*current_temperature))
            # make a decision to accept the worse solution or not
            ## 4. make a decision whether r < p
            if random.random()<p:
                accept = True # this worse solution is not accepted
            else:
                accept = False # this worse solution is not accepted
        else:
            accept = True # accept better solution
        ## 5. make a decision whether step comdition of inner loop is met
        if accept == True:
            best_solution = current_solution # update the best solution
            best_fitness = objective_function(best_solution)
            n = n + 1 #count the solutions accepted
            EA = (EA*(n-1)+E)/n # accept EA
    print('interation : {}, best_solution:{}, best_fitness:{}'. format(i, best_solution, best_fitness))
    record_best_fitness.append(best_fitness)
    ## 6. decrease the temperature
    current_temperature = current_temperature * cooling
    ## 7. stop condition of outer loop is met
    end = time.time()
    if end-start >= computing_time:
        break
</code>```

The error picture:

答:
it's for your input shape, in MLP neural network your input shape is [none,14], but in your function's input id [14,1], so you need transpose it.</p>
```<code>def objective_function(X):
  wob   = X[0]
  torque= X[1]
  RPM   = X[2]
  pump  = X[3]
  input=[wob,torque,RPM, 0.00017,0.027,pump,0,0.5,0.386,0.026,0.0119,0.33,0.83,0.48]
  input = pd.DataFrame(input)
  input=input.T
  model1.predict(input)
  return obj
</code>```

Body:
I implement an MLP neural network model on the data, for optimization 4 variables a function base on the MLP model is defined, and simulated annealing run on this function. I don't know why I get this error (attached below).

Neural network code:

# mlp for regression
from numpy import sqrt
from pandas import read_csv
from sklearn.model_selection import train_test_split
from tensorflow.keras import Sequential
from tensorflow.keras.layers import Dense
import tensorflow
from tensorflow import keras
from matplotlib import pyplot
from keras.layers import Dropout
from tensorflow.keras import regularizers

# determine the number of input features
n_features = X_train.shape[1]
# define model
model = Sequential()
model.add(Dense(150, activation='tanh', kernel_initializer='zero',kernel_regularizer=regularizers.l2(0.001), input_shape=(n_features,))) #relu/softmax/tanh
model.add(Dense(100, activation='tanh', kernel_initializer='zero',kernel_regularizer=regularizers.l2(0.001)))
model.add(Dense(50, activation='tanh', kernel_initializer='zero',kernel_regularizer=regularizers.l2(0.001)))
model.add(Dropout(0.0))
model.add(Dense(1))
# compile the model
opt= keras.optimizers.Adam(learning_rate=0.001)
#opt = tensorflow.keras.optimizers.RMSprop(learning_rate=0.001,rho=0.9,momentum=0.0,epsilon=1e-07,centered=False,name="RMSprop")
model.compile(optimizer=opt, loss='mse')
# fit the model
history=model.fit(X_train, y_train, validation_data = (X_test,y_test), epochs=100, batch_size=10, verbose=0,validation_split=0.3)
# evaluate the model
error = model.evaluate(X_test, y_test, verbose=0)
print('MSE: %.3f, RMSE: %.3f' % (error, sqrt(error)))
# plot learning curves
pyplot.title('Learning Curves')
pyplot.xlabel('Epoch')
pyplot.ylabel('Cross Entropy')
pyplot.plot(history.history['loss'], label='train')
pyplot.plot(history.history['val_loss'], label='val')
pyplot.legend()
pyplot.show()

function code:

def objective_function(X):
  wob   = X[0]
  torque= X[1]
  RPM   = X[2]
  pump  = X[3]
  input=[wob,torque,RPM, 0.00017,0.027,pump,0,0.5,0.386,0.026,0.0119,0.33,0.83,0.48]
  input = pd.DataFrame(input)
  obj= model.predict(input)
  return obj

simulated annealing for optimization:

import time
import random
import math
import numpy as np

## custom section
initial_temperature = 100
cooling = 0.8 # cooling coef.
number_variables = 4
upper_bounds = [1,1,1,1]
lower_bounds = [0,0,0,0]
computing_time = 1 # seconds

## simulated Annealing algorithm

## 1. Genertate an initial solution randomly
initial_solution = np.zeros((number_variables))
for v in range(number_variables):
    initial_solution[v] = random.uniform(lower_bounds[v], upper_bounds[v])
current_solution = initial_solution
best_solution = initial_solution
n=1 # no of solutions accepted
best_fitness = objective_function(best_solution)
current_temperature = initial_temperature # current temperature
start = time.time()
no_attemps = 100 # number of attemps in each level of temperature
record_best_fitness = []

for i in range(9999999):
    for j in range(no_attemps):
        for k in range(number_variables):
            ## 2. generate a candidate solution y randomly based on solution x
            current_solution[k] = best_solution[k] + 0.1*(random.uniform(lower_bounds[k], upper_bounds[k]))
            current_solution[k] = max(min(current_solution[k], upper_bounds[k]), lower_bounds[k]) # repaire the solution respecting the bounds

  ## 3. check if y is better than x
        current_fitness = objective_function(current_solution)
        E = abs(current_fitness - best_solution)
        if i==0 and j==0:
            EA = E
        if current_fitness < best_fitness:
            p = math.exp(-E/(EA*current_temperature))
            # make a decision to accept the worse solution or not
            ## 4. make a decision whether r < p
            if random.random()<p:
                accept = True # this worse solution is not accepted
            else:
                accept = False # this worse solution is not accepted
        else:
            accept = True # accept better solution
        ## 5. make a decision whether step comdition of inner loop is met
        if accept == True:
            best_solution = current_solution # update the best solution
            best_fitness = objective_function(best_solution)
            n = n + 1 #count the solutions accepted
            EA = (EA*(n-1)+E)/n # accept EA
    print('interation : {}, best_solution:{}, best_fitness:{}'. format(i, best_solution, best_fitness))
    record_best_fitness.append(best_fitness)
    ## 6. decrease the temperature
    current_temperature = current_temperature * cooling
    ## 7. stop condition of outer loop is met
    end = time.time()
    if end-start >= computing_time:
        break

The error picture:

Body:
it's for your input shape, in MLP neural network your input shape is [none,14], but in your function's input id [14,1], so you need transpose it.

def objective_function(X):
  wob   = X[0]
  torque= X[1]
  RPM   = X[2]
  pump  = X[3]
  input=[wob,torque,RPM, 0.00017,0.027,pump,0,0.5,0.386,0.026,0.0119,0.33,0.83,0.48]
  input = pd.DataFrame(input)
  input=input.T
  model1.predict(input)
  return obj


问:
MS Access - Run Query based on User Choice from Drop Down List
I'm trying to create a Microsoft Access form where a user would pick a value from a drop down list and based on that choice a different query would run. For example if the user picks choice A then Query A would run, if B then Query B would run. I have already written the sql query that chooses which query would run based on what choice and it runs perfectly on its own. The problem occurs when I try to incorporate it within my form and add the criteria as  [Forms]![myform]![myvalue], the query doesn't even run. I've tried to simplify the query where only simple SELECT FROM query should run when a user makes an input but it also doesn't run. I can't seem to make out where the problem is so I'd be very thankful for your help.

答:
Create an unbound form, with the dropdown column/combo box that has the choices e.g A,b,c etc

Create a command button.

On the click event of the command button, add an IF statement.

In the images I attached, the following are the names I used.

Combo box has the name Combo0 and the caption choice

Command button has the name runquery, and the caption Run Query


问:
select code where the price difference is above 8% in the last 3 days
Here is the table:

code
date
price

ETH
2020/1/2
1022

ETH
2020/1/8
2000

EOS
2020/1/4
2.3

EOS
2020/1/9
3.2

I want to pick up codes whose price changed 8% in the last 3 days.

What I can figure out is something like:

```<code>select stockcode,
      LAG(price) over (partition by code order by date) as previous_price
from table
where (price-previous_price)/previous_price
order by date
</code>```

But this doesn't work well, any solutions? thanks.

答:
try like below using lag() with sub query</p>
```<code>with cte as
(
select 'e' as c ,'2020-01-02' as d, 1022 as p
union all
select 'e','2020-01-08', 2000
union all
select 'f','2020-01-04',2.3
union all
select 'f','2020-01-09',3.2
),cte2 as
(select c,p,
lag(p) over (partition by c order by d) as previous_price,
row_number() over(partition by c order by d) as rn
from cte ) select c  from cte2
where rn!=1
and abs(((p-previous_price)*1.0/p)*100.0)>8
</code>```

Body:
Here is the table:

code
date
price

ETH
2020/1/2
1022

ETH
2020/1/8
2000

EOS
2020/1/4
2.3

EOS
2020/1/9
3.2

I want to pick up codes whose price changed 8% in the last 3 days.

What I can figure out is something like:

select stockcode,
      LAG(price) over (partition by code order by date) as previous_price
from table
where (price-previous_price)/previous_price
order by date

But this doesn't work well, any solutions? thanks.

Body:
try like below using lag() with sub query

with cte as
(
select 'e' as c ,'2020-01-02' as d, 1022 as p
union all
select 'e','2020-01-08', 2000
union all
select 'f','2020-01-04',2.3
union all
select 'f','2020-01-09',3.2
),cte2 as
(select c,p,
lag(p) over (partition by c order by d) as previous_price,
row_number() over(partition by c order by d) as rn
from cte ) select c  from cte2
where rn!=1
and abs(((p-previous_price)*1.0/p)*100.0)>8


问:
Image Replacement Script (jQuery)
I'm building an employee bios page where the client wants selected thumbnails to display in color at full opacity and all others at lower opacity in black and white. Which wouldn't be hard - the trouble is, every thumbnail has to have a color state and a black and white state. So my next thought was to swap out the black and white image (which would be resting within the div with a color background image) on mouseover.

```<code>$('.thumbnail').mouseenter(function(){
    var current = $(this); // cache thing
    var thishtml = current.html(); // get contents of thing
    current.html('').mouseleave(function(){ //empty the thing
        current.html(thishtml); //put the variable back in the thing
        });
});
</code>```

My HTML would be as follows:

```<code><div class = "thumbnail" style = "background-image: url(color.jpg);">
<img src="blackandwhite.jpg" />
</div>
</code>```

Obviously, since I'm asking the question, my idea didn't work. The mouseover removes the innerHTML, and the variable is converted successfully, but it doesn't get inserted into the DIV again. What am I missing?

答:
Try using .show() and hide() to make the blackandwhite.jpg image visible and hidden respectively.</p>

```<code>$(".thumbnail").hover(
  function () {
    $(this).children("img").hide(); //hide b and w on mouse in
  },
  function () {
    $(this).children("img").show();  //showb and w on mouse out
  }
);
</code>```

Title: Image Replacement Script (jQuery)

Body:
I'm building an employee bios page where the client wants selected thumbnails to display in color at full opacity and all others at lower opacity in black and white. Which wouldn't be hard - the trouble is, every thumbnail has to have a color state and a black and white state. So my next thought was to swap out the black and white image (which would be resting within the div with a color background image) on mouseover.

$('.thumbnail').mouseenter(function(){
    var current = $(this); // cache thing
    var thishtml = current.html(); // get contents of thing
    current.html('').mouseleave(function(){ //empty the thing
        current.html(thishtml); //put the variable back in the thing
        });
});

My HTML would be as follows:

Obviously, since I'm asking the question, my idea didn't work. The mouseover removes the innerHTML, and the variable is converted successfully, but it doesn't get inserted into the DIV again. What am I missing?

Body:
Try using .show() and hide() to make the blackandwhite.jpg image visible and hidden respectively.

$(".thumbnail").hover(
  function () {
    $(this).children("img").hide(); //hide b and w on mouse in
  },
  function () {
    $(this).children("img").show();  //showb and w on mouse out
  }
);