问:
How to backup database mongodb using laradock
I cannot backup the database.

Framework: Laravel

Database: Mongodb

Environment: Laradock

Package: spatie/laravel backup

config/backup.php

```<code>
'databases' => [ 'mongodb' ],

</code>```

Run command: php artisan backup:run

```<code>
Backup failed because The dump process failed with exitcode 127 : Command not found : sh: 1: mongodump: not found
.
#0 /var/www/vendor/spatie/db-dumper/src/DbDumper.php(246): Spatie\DbDumper\Exceptions\DumpFailed::processDidNotEndSuccessfully(Object(Symfony\Component\Process\Process))
#1 /var/www/vendor/spatie/db-dumper/src/Databases/MongoDb.php(37): Spatie\DbDumper\DbDumper->checkIfDumpWasSuccessFul(Object(Symfony\Component\Process\Process), '/var/www/storag...')
#2 /var/www/vendor/spatie/laravel-backup/src/Tasks/Backup/BackupJob.php(250): Spatie\DbDumper\Databases\MongoDb->dumpToFile('/var/www/storag...')
#3 [internal function]: Spatie\Backup\Tasks\Backup\BackupJob->Spatie\Backup\Tasks\Backup\{closure}(Object(Spatie\DbDumper\Databases\MongoDb), 'mongodb')
#4 /var/www/vendor/laravel/framework/src/Illuminate/Support/Collection.php(1122): array_map(Object(Closure), Array, Array)
#5 /var/www/vendor/spatie/laravel-backup/src/Tasks/Backup/BackupJob.php(253): Illuminate\Support\Collection->map(Object(Closure))
#6 /var/www/vendor/spatie/laravel-backup/src/Tasks/Backup/BackupJob.php(167): Spatie\Backup\Tasks\Backup\BackupJob->dumpDatabases()
#7 /var/www/vendor/spatie/laravel-backup/src/Tasks/Backup/BackupJob.php(143): Spatie\Backup\Tasks\Backup\BackupJob->createBackupManifest()
#8 /var/www/vendor/spatie/laravel-backup/src/Commands/BackupCommand.php(52): Spatie\Backup\Tasks\Backup\BackupJob->run()

#9 [internal function]: Spatie\Backup\Commands\BackupCommand->handle()
#10 /var/www/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php(32): call_user_func_array(Array, Array)
#11 /var/www/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php(90): Illuminate\Container\BoundMethod::Illuminate\Container\{closure}()
#12 /var/www/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php(34): Illuminate\Container\BoundMethod::callBoundMethod(Object(Illuminate\Foundation\Application), Array
, Object(Closure))
#13 /var/www/vendor/laravel/framework/src/Illuminate/Container/Container.php(580): Illuminate\Container\BoundMethod::call(Object(Illuminate\Foundation\Application), Array, Array, NUL
L)
#14 /var/www/vendor/laravel/framework/src/Illuminate/Console/Command.php(183): Illuminate\Container\Container->call(Array)
#15 /var/www/vendor/symfony/console/Command/Command.php(255): Illuminate\Console\Command->execute(Object(Symfony\Component\Console\Input\ArgvInput), Object(Illuminate\Console\OutputS
tyle))
#16 /var/www/vendor/laravel/framework/src/Illuminate/Console/Command.php(170): Symfony\Component\Console\Command\Command->run(Object(Symfony\Component\Console\Input\ArgvInput), Objec
t(Illuminate\Console\OutputStyle))
#17 /var/www/vendor/spatie/laravel-backup/src/Commands/BaseCommand.php(16): Illuminate\Console\Command->run(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Componen
t\Console\Output\ConsoleOutput))
#18 /var/www/vendor/symfony/console/Application.php(908): Spatie\Backup\Commands\BaseCommand->run(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\
Output\ConsoleOutput))
#19 /var/www/vendor/symfony/console/Application.php(269): Symfony\Component\Console\Application->doRunCommand(Object(Spatie\Backup\Commands\BackupCommand), Object(Symfony\Component\C
onsole\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#20 /var/www/vendor/symfony/console/Application.php(145): Symfony\Component\Console\Application->doRun(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Con
sole\Output\ConsoleOutput))
#21 /var/www/vendor/laravel/framework/src/Illuminate/Console/Application.php(90): Symfony\Component\Console\Application->run(Object(Symfony\Component\Console\Input\ArgvInput), Object
(Symfony\Component\Console\Output\ConsoleOutput))
#22 /var/www/vendor/laravel/framework/src/Illuminate/Foundation/Console/Kernel.php(122): Illuminate\Console\Application->run(Object(Symfony\Component\Console\Input\ArgvInput), Object
(Symfony\Component\Console\Output\ConsoleOutput))
#23 /var/www/artisan(37): Illuminate\Foundation\Console\Kernel->handle(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#24 {main}
Backup failed because: The dump process failed with exitcode 127 : Command not found : sh: 1: mongodump: not found

</code>```

I tried installing mongo, mongo tools ... to execute mongodump but failed, I found the problem here is that the workspace container cannot call a mongodump but doesn't know how to fix it.

答:
mongodump is not available in the workspace container in Laradock, but it is in mongo container.

Anyway mongo container cannot run php so it doesn't help.

Maybe you can change your strategy create a new container called backup that will make backups of your app, once started.

You can start from the Dockerfile in the laradock/workspace directory (and the definition of the container in docker-compose.yml file.

Body:
I cannot backup the database.

Framework: Laravel

Database: Mongodb

Environment: Laradock

Package: spatie/laravel backup

config/backup.php

'databases' => [ 'mongodb' ],

Run command: php artisan backup:run

Backup failed because The dump process failed with exitcode 127 : Command not found : sh: 1: mongodump: not found
.
#0 /var/www/vendor/spatie/db-dumper/src/DbDumper.php(246): Spatie\DbDumper\Exceptions\DumpFailed::processDidNotEndSuccessfully(Object(Symfony\Component\Process\Process))
#1 /var/www/vendor/spatie/db-dumper/src/Databases/MongoDb.php(37): Spatie\DbDumper\DbDumper->checkIfDumpWasSuccessFul(Object(Symfony\Component\Process\Process), '/var/www/storag...')
#2 /var/www/vendor/spatie/laravel-backup/src/Tasks/Backup/BackupJob.php(250): Spatie\DbDumper\Databases\MongoDb->dumpToFile('/var/www/storag...')
#3 [internal function]: Spatie\Backup\Tasks\Backup\BackupJob->Spatie\Backup\Tasks\Backup\{closure}(Object(Spatie\DbDumper\Databases\MongoDb), 'mongodb')
#4 /var/www/vendor/laravel/framework/src/Illuminate/Support/Collection.php(1122): array_map(Object(Closure), Array, Array)
#5 /var/www/vendor/spatie/laravel-backup/src/Tasks/Backup/BackupJob.php(253): Illuminate\Support\Collection->map(Object(Closure))
#6 /var/www/vendor/spatie/laravel-backup/src/Tasks/Backup/BackupJob.php(167): Spatie\Backup\Tasks\Backup\BackupJob->dumpDatabases()
#7 /var/www/vendor/spatie/laravel-backup/src/Tasks/Backup/BackupJob.php(143): Spatie\Backup\Tasks\Backup\BackupJob->createBackupManifest()
#8 /var/www/vendor/spatie/laravel-backup/src/Commands/BackupCommand.php(52): Spatie\Backup\Tasks\Backup\BackupJob->run()

#9 [internal function]: Spatie\Backup\Commands\BackupCommand->handle()
#10 /var/www/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php(32): call_user_func_array(Array, Array)
#11 /var/www/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php(90): Illuminate\Container\BoundMethod::Illuminate\Container\{closure}()
#12 /var/www/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php(34): Illuminate\Container\BoundMethod::callBoundMethod(Object(Illuminate\Foundation\Application), Array
, Object(Closure))
#13 /var/www/vendor/laravel/framework/src/Illuminate/Container/Container.php(580): Illuminate\Container\BoundMethod::call(Object(Illuminate\Foundation\Application), Array, Array, NUL
L)
#14 /var/www/vendor/laravel/framework/src/Illuminate/Console/Command.php(183): Illuminate\Container\Container->call(Array)
#15 /var/www/vendor/symfony/console/Command/Command.php(255): Illuminate\Console\Command->execute(Object(Symfony\Component\Console\Input\ArgvInput), Object(Illuminate\Console\OutputS
tyle))
#16 /var/www/vendor/laravel/framework/src/Illuminate/Console/Command.php(170): Symfony\Component\Console\Command\Command->run(Object(Symfony\Component\Console\Input\ArgvInput), Objec
t(Illuminate\Console\OutputStyle))
#17 /var/www/vendor/spatie/laravel-backup/src/Commands/BaseCommand.php(16): Illuminate\Console\Command->run(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Componen
t\Console\Output\ConsoleOutput))
#18 /var/www/vendor/symfony/console/Application.php(908): Spatie\Backup\Commands\BaseCommand->run(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\
Output\ConsoleOutput))
#19 /var/www/vendor/symfony/console/Application.php(269): Symfony\Component\Console\Application->doRunCommand(Object(Spatie\Backup\Commands\BackupCommand), Object(Symfony\Component\C
onsole\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#20 /var/www/vendor/symfony/console/Application.php(145): Symfony\Component\Console\Application->doRun(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Con
sole\Output\ConsoleOutput))
#21 /var/www/vendor/laravel/framework/src/Illuminate/Console/Application.php(90): Symfony\Component\Console\Application->run(Object(Symfony\Component\Console\Input\ArgvInput), Object
(Symfony\Component\Console\Output\ConsoleOutput))
#22 /var/www/vendor/laravel/framework/src/Illuminate/Foundation/Console/Kernel.php(122): Illuminate\Console\Application->run(Object(Symfony\Component\Console\Input\ArgvInput), Object
(Symfony\Component\Console\Output\ConsoleOutput))
#23 /var/www/artisan(37): Illuminate\Foundation\Console\Kernel->handle(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#24 {main}
Backup failed because: The dump process failed with exitcode 127 : Command not found : sh: 1: mongodump: not found

I tried installing mongo, mongo tools ... to execute mongodump but failed, I found the problem here is that the workspace container cannot call a mongodump but doesn't know how to fix it.


来源: stackexchange

问:
How to log nuxt server side network requests?
Is there some way how to log all network requests which are done by nuxtjs on server side?

I'm already using node --inspect to enable chrome console, but network tab is missing there.

Thanks a lot for any tip.

答:
Adding on to Nicolas' solution.

Once you created the axios plugin in your Nuxt app, you could add it to your Nuxt config file and set the mode to server as you want to run it on server-side.

More on Nuxt plugin here.

```<code>plugins: [
    { src: '~/plugins/axios', mode: 'server' },
]
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Adding on to Nicolas' solution.

Once you created the axios plugin in your Nuxt app, you could add it to your Nuxt config file and set the mode to server as you want to run it on server-side.

More on Nuxt plugin here.

plugins: [
    { src: '~/plugins/axios', mode: 'server' },
]


问:
Android - relationship between Fragment and Activity

my question is really simple: can I create/start a Fragment from an Activity, and vice versa? And how can I do that?

I need to implement this for my app, and I read discordant opinions on the web. Some say that you can only open fragments from other fragments, other say that it's possible but you shouldn't do that, instead you should open fragments only from activities. I'm a bit confused.

I found different ways to do one thing or another, but none worked. The only thing that worked for me was create an Activity from an Activity. What I need to do is to start an Activity from a Fragment, or a Fragment from a Fragment.

Before doing any kind of re-implementation I'd like to understand what of this can actually work, and why the other not.

Thanks everyone, any hint is welcome.

答:
Fragment: typically represents a reusable portion of an activity's user interface, but may also represent reusable program logic. You can combine several fragment to create the user interface that make better use of your phone or tablet.
you can easily interchange fragments to make your GUI'S more dynamic.
Fragment must be hosted by an activity  and they can not execute independently.
Fragment they have their own life cycle which mean they can start an app.
for example: they have onCreate() method so the fragment can add their own menu items to host an activity menu.</p>

ContentLicense: CC BY-SA 3.0


问:
How can we generate a conformation prompt before deleting a comment in Django?
I am trying to link java script and Django views, I have a comments delete view, where its functionality is good but, i need some conformation using javascript before deleting them.

I don't have knowledge regarding the Mapping Javascript and Django views. Can any one help me in writing the code?

```<code>@login_required
def delete_my_comment(request, pk):
    comment = get_object_or_404(Comment, pk=pk)
    if comment.user == request.user.username:
        comment.delete()
        messages.success(request, f' Your comment is deleted')
    return redirect('post-detail', pk=comment.post.id)

 <a class="btn btn-danger btn-sm mt-1 mb-1" href="{% url 'post-delete' object.id %}">Delete Post</a>
</code>```

Can some help me in writing javascript logic for the delete conformation based on above code?
Thank you all

答:
why dont you try out django generic views, use class based views such as

class DeleteComment(LoginRequiredMixin, DeleteView):

```<code>model =  Comment
template_name = "delete_comment.html"
success_url = "post"
</code>```

create a delete_comment.html with a confirmation sentence as well as a button for submit and anchor for cancel , this should do fine

Body:
I am trying to link java script and Django views, I have a comments delete view, where its functionality is good but, i need some conformation using javascript before deleting them.

I don't have knowledge regarding the Mapping Javascript and Django views. Can any one help me in writing the code?

@login_required
def delete_my_comment(request, pk):
    comment = get_object_or_404(Comment, pk=pk)
    if comment.user == request.user.username:
        comment.delete()
        messages.success(request, f' Your comment is deleted')
    return redirect('post-detail', pk=comment.post.id)

 Delete Post

Can some help me in writing javascript logic for the delete conformation based on above code?
Thank you all

Body:
why dont you try out django generic views, use class based views such as

class DeleteComment(LoginRequiredMixin, DeleteView):

model =  Comment
template_name = "delete_comment.html"
success_url = "post"

create a delete_comment.html with a confirmation sentence as well as a button for submit and anchor for cancel , this should do fine


问:
Why does 'dispatch' method only instantiate and return of PendingDispatch without scheduling it?
I am an PHP/Laravel newbie. I am working with Laravel job and everything works fine.
However, when I have a look at the implementation of dispatch method, it looks weird to me.

```<code>if (! function_exists('dispatch')) {
    /**
     * Dispatch a job to its appropriate handler.
     *
     * @param  mixed  $job
     * @return \Illuminate\Foundation\Bus\PendingDispatch
     */
    function dispatch($job)
    {
        return new PendingDispatch($job);
    }
}
</code>```

I would expect some code that enqueues the job or at least triggers something to schedule the job to be executed later on. However, the method only creates an instance of PendingDispatch and returns it. I also checked the PendingDispatch constructor and found nothing relevant.

Could anyone please help me to understand how the job is scheduled?

答:
Whenever we dispatch a job in laravel, i call the helper that you have mentioned in question, afterwards PendingDispatch($job) is called where job is assigned in constructor, if you can look at the destructor  in same file you will find the below code

```<code>public function __destruct()
{
    app(Dispatcher::class)->dispatch($this->job);
}
</code>```

This method, when called, will resolve an instance of Dispatcher from the container and call the dispatch() method on it. A __destruct() is a PHP magic method that's called when all references to the object no longer exist or when the script terminates, and since we don't store a reference to the PendingDispatch instance anywhere the __destruct method will be called immediately

Body:
I am an PHP/Laravel newbie. I am working with Laravel job and everything works fine.
However, when I have a look at the implementation of dispatch method, it looks weird to me.

if (! function_exists('dispatch')) {
    /**
     * Dispatch a job to its appropriate handler.
     *
     * @param  mixed  $job
     * @return \Illuminate\Foundation\Bus\PendingDispatch
     */
    function dispatch($job)
    {
        return new PendingDispatch($job);
    }
}

I would expect some code that enqueues the job or at least triggers something to schedule the job to be executed later on. However, the method only creates an instance of PendingDispatch and returns it. I also checked the PendingDispatch constructor and found nothing relevant.

Could anyone please help me to understand how the job is scheduled?

Body:
Whenever we dispatch a job in laravel, i call the helper that you have mentioned in question, afterwards PendingDispatch($job) is called where job is assigned in constructor, if you can look at the destructor  in same file you will find the below code

public function __destruct()
{
    app(Dispatcher::class)->dispatch($this->job);
}

This method, when called, will resolve an instance of Dispatcher from the container and call the dispatch() method on it. A __destruct() is a PHP magic method that's called when all references to the object no longer exist or when the script terminates, and since we don't store a reference to the PendingDispatch instance anywhere the __destruct method will be called immediately


答:
Set plotly.graph_objs.Layout.xaxis.tickangle = 90.

Detail: https://plot.ly/python/axes/#set-and-style-axes-title-labels-and-ticks

Title: Changing the orientation of pyplot graph's x values

Body:
I have the following data:

stage_summary = {'Day1': {'1': 100.0, '2': 0.0, '3': 0.0, '4': 0.0, '5': 0.0, '6': 0.0, '7': 0.0, '8': 0.0}, 'Day2': {'1': 100.0, '2': 0.0, '3': 0.0, '4': 0.0, '5': 0.0, '6': 0.0, '7': 0.0, '8': 0.0}, 'Day3': {'1': 89.8, '2': 10.2, '3': 0.0, '4': 0.0, '5': 0.0, '6': 0.0, '7': 0.0, '8': 0.0}, 'Day4': {'1': 58.6, '2': 41.4, '3': 0.0, '4': 0.0, '5': 0.0, '6': 0.0, '7': 0.0, '8': 0.0}, 'Day5': {'1': 52.71, '2': 47.06, '3': 0.0, '4': 0.0, '5': 0.0, '6': 0.23, '7': 0.0, '8': 0.0}, 'Day6': {'1': 47.89, '2': 50.65, '3': 0.0, '4': 0.0, '5': 0.0, '6': 1.46, '7': 0.0, '8': 0.0}, 'Day7': {'1': 49.72, '2': 46.95, '3': 0.0, '4': 0.0, '5': 0.0, '6': 3.33, '7': 0.0, '8': 0.0}, 'Day8': {'1': 52.59, '2': 39.35, '3': 0.0, '4': 0.0, '5': 0.0, '6': 8.05, '7': 0.0, '8': 0.01}, 'Day9': {'1': 55.45, '2': 30.73, '3': 0.0, '4': 0.0, '5': 0.0, '6': 13.74, '7': 0.0, '8': 0.08}}

date_list = ['2019-05-28',
 '2019-05-29',
 '2019-05-30',
 '2019-05-31',
 '2019-06-03',
 '2019-06-04',
 '2019-06-05',
 '2019-06-06',
 '2019-06-07']

And I plot the data in this way, as a line graph:

for each_state in list(range(1,9)):
    tmp = []
    for each_day in stage_summary:
        tmp.append(stage_summary[each_day][str(each_state)])
    plt.plot(date_list, tmp, label=str('State ' + str(each_state)))
plt.ylabel('Probability')
plt.xlabel('Days')
plt.legend(loc='best')

which results in the following graph,

However, as you can see, the x labels are dates, which are long strings. And therefore, it has to be rotated and be presented vertically to make it readable. But I am not sure how I can change the orientation of x values in a plotly graph. How can I do so?


问:
android studio share CSV file request contain no data
I want to share my csv file to any action like Bluetooth, send to email ,etc

```<code> final String filename = Environment.getExternalStorageDirectory() + "/Folder" + "/" + "mycsv.csv";

  Intent sharingIntent = new Intent();
                        sharingIntent.setAction(Intent.ACTION_SEND);
                        sharingIntent.putExtra(Intent.EXTRA_STREAM, filename);
                        sharingIntent.setType("text/comma_separated_values/csv");
                        startActivity(Intent.createChooser(sharingIntent, "share file with"));
</code>```

the output will be no request containt no data

答:
I think that the filename requires a file:// prefix. Android, for sharing any types of file requires a universal identifier or a Uri.

```<code>final String fileUriString = "file://" + Environment.getExternalStorageDirectory() + "/Folder" + "/" + "mycsv.csv";
</code>```

Also, change the type to text/csv.

```<code>Intent sharingIntent = new Intent();
sharingIntent.setAction(Intent.ACTION_SEND);
sharingIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse( fileUriString ) ) ;
sharingIntent.setType("text/csv");
startActivity(Intent.createChooser(sharingIntent, "share file with"));
</code>```

See this answer for more.

Body:
I want to share my csv file to any action like Bluetooth, send to email ,etc

 final String filename = Environment.getExternalStorageDirectory() + "/Folder" + "/" + "mycsv.csv";

  Intent sharingIntent = new Intent();
                        sharingIntent.setAction(Intent.ACTION_SEND);
                        sharingIntent.putExtra(Intent.EXTRA_STREAM, filename);
                        sharingIntent.setType("text/comma_separated_values/csv");
                        startActivity(Intent.createChooser(sharingIntent, "share file with"));

the output will be no request containt no data

Body:
I think that the filename requires a file:// prefix. Android, for sharing any types of file requires a universal identifier or a Uri.

final String fileUriString = "file://" + Environment.getExternalStorageDirectory() + "/Folder" + "/" + "mycsv.csv";

Also, change the type to text/csv.

Intent sharingIntent = new Intent();
sharingIntent.setAction(Intent.ACTION_SEND);
sharingIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse( fileUriString ) ) ;
sharingIntent.setType("text/csv");
startActivity(Intent.createChooser(sharingIntent, "share file with"));

See this answer for more.


问:
Is there any way to match file with number in its name in apache Ant build.xml
I am trying to match file which has number in its name. And looks like Ant supports only * ? c these characters for regex. Anyone tried ANT regex.
I want to match the file with name TEST-3000-6564345.zip</p>

```<code><target name="demo">
    <mkdir dir="/dem"/>
    <unzip dest="src/main/resources/dem">
        <fileset dir="src/main/resources">
            <filename regex=".*[0-9]\d.*"/>
        </fileset>
    </unzip>
</target>
</code>```

答:
You can use regular expressions, but they’re not supported by ordinary patternsets.  Instead, you need to use a selector, like <filename>:

<fileset dir="${files.root}">
    <filename regex=".*\d.*"/>
</fileset>
```

Body:
I am trying to match file which has number in its name. And looks like Ant supports only * ? c these characters for regex. Anyone tried ANT regex.
I want to match the file with name TEST-3000-6564345.zip

<target name="demo">
    <mkdir dir="/dem"/>
    <unzip dest="src/main/resources/dem">
        <fileset dir="src/main/resources">
            <filename regex=".*[0-9]\d.*"/>
        </fileset>
    </unzip>
</target>


答:
You are using matplotlib and not plotly, right?

If yes, try:

```<code>for each_state in list(range(1,9)):
    tmp = []
    for each_day in stage_summary:
        tmp.append(stage_summary[each_day][str(each_state)])
    plt.plot(date_list, tmp, label=str('State ' + str(each_state)))
plt.ylabel('Probability')
plt.xlabel('Days')
plt.xticks(rotation=45)
plt.legend(loc='best')
</code>```

Body:
You are using matplotlib and not plotly, right?

If yes, try:

for each_state in list(range(1,9)):
    tmp = []
    for each_day in stage_summary:
        tmp.append(stage_summary[each_day][str(each_state)])
    plt.plot(date_list, tmp, label=str('State ' + str(each_state)))
plt.ylabel('Probability')
plt.xlabel('Days')
plt.xticks(rotation=45)
plt.legend(loc='best')


问:
Multiple arguments in a function. Passing info through functions. - ''<function save_snapshots at "###"> not found'
# Error: RuntimeError: file <maya console> line 13: Object '<function save_snapshots at 0x000001757D101EB8>' not found. #

I am working on a script to create uv snapshots. Currently, I'm stuck on getting "save_snapshots" to get the integer that "uv_snap_res" is supposed to give.

In my UI, the 'save' button is using partial and I don't fully understand how that works. If I move save_snapshots behind 'texSizeControl' in the order of commands, it just simply doesn't run (I think?).

Was hoping to have a little help explaining how passing arguments works when using functions, and the order of operations when it comes to the "partial" thing...
The only reason I'm this far is because of this site and finding examples in other areas. The whole radio buttons thing is a total challenge and I don't know if I fully have it working correctly :/ sorry.

any help or advice you have to offer I am all ears!!

```<code>## UV SNAPSHOTS
## PYTHON
import maya.cmds as mc

def get_snapshot_res(label, *args):
    uv_snap_res = label

def save_snapshots(get_snapshot_res, uv_snap_res, *args):
    get_snapshot_res(uv_snap_res)
    print get_snapshot_res

def passValue(texSizeControl, *args):
    radioCol = mc.radioCollection(texSizeControl, query=True, sl=True)
    getSelectRadioVal = mc.radioButton(radioCol, query=True, label=True)
    get_snapshot_res(getSelectRadioVal)

def save_snapshots_ui(*args):
    myWindow = 'Create UV Snapshots'
    if mc.window(myWindow, exists=True):
        mc.deleteUI(myWindow)
    mc.window(myWindow, title = myWindow)
    mc.columnLayout(adjustableColumn=True)
    mc.text(label='Choose your resolution for UV Snapshots', font='obliqueLabelFont')
    texSizeControl = mc.radioCollection()
    saveRadio1k = mc.radioButton(label='1024')
    saveRadio2k = mc.radioButton(label='2048')
    saveRadio4k = mc.radioButton(label='4096')
    saveRadio8k = mc.radioButton(label='8192')
    texSizeControl = mc.radioCollection(texSizeControl, edit=True, select=saveRadio2k )
    mc.button(label='save', command= partial(passValue, save_snapshots, texSizeControl))
    mc.setParent( '..' )
    mc.showWindow()

save_snapshots_ui()
</code>```

答:
Try to remove the *args where there is no need, you should write your script like this :

cmd SNAPSHOT need(FULLPATH, RES, UVRANGE)

ui set resolution

ui set png name

ui set path

ui select the uvRange

snapshot button send -> res, name, path, uvRange

get ui RES

get ui name and get ui path to create FULLPATH

get ui UVRANGE

gather all this get into one cmd to launch SNAPSHOT

====================================

```<code>import maya.cmds as mc
# GATHER
def ui_save_snapshots(texSizeControl, *args):
    # *args is only used when the def is inside ui
    # here it is gathering information to launch the maya command
    RATIO = get_snapshot_res(texSizeControl)
    path = 'something to get the path'
    save_snapshots(path, RATIO)
# GET RES
def ui_get_snapshot_res(label):
    radioCol = mc.radioCollection(texSizeControl, query=True, sl=True)
    RATIO = mc.radioButton(radioCol, query=True, label=True)
    return RATIO
SNAPSHOT
def save_snapshots(path, resolution, uvRange=[0,1,0,1]):
    # this def is a without any ui
    # path = "/marza/proj/fuji2019/work/Prop/trap/sim/everyone/simRig/images/outUV.jpg"
    uMin, uMax, vMin, vMax = uvRange
    cmds.uvSnapshot(o=True,ff='jpg', xr=resolution, yr=4096, aa=True, r=255, g=255, b=255, n=path, uMin=uMin, uMax=uMax, vMin=vMin, vMax=vMax)

def save_snapshots_ui():
    myWindow = 'Create UV Snapshots'
    if mc.window(myWindow, exists=True):
        mc.deleteUI(myWindow)
    mc.window(myWindow, title = myWindow)
    mc.columnLayout(adjustableColumn=True)
    mc.text(label='Choose your resolution for UV Snapshots', font='obliqueLabelFont')
    texSizeControl = mc.radioCollection()
    saveRadio1k = mc.radioButton(label='1024')
    saveRadio2k = mc.radioButton(label='2048')
    saveRadio4k = mc.radioButton(label='4096')
    saveRadio8k = mc.radioButton(label='8192')
    texSizeControl = mc.radioCollection(texSizeControl, edit=True, select=saveRadio2k )
    # send textSiZeControl to passValue
    mc.button(label='save', command= partial(passValue, texSizeControl))
    mc.setParent( '..' )
    mc.showWindow()

save_snapshots_ui()
</code>```

Body:
# Error: RuntimeError: file <maya console> line 13: Object '<function save_snapshots at 0x000001757D101EB8>' not found. #

I am working on a script to create uv snapshots. Currently, I'm stuck on getting "save_snapshots" to get the integer that "uv_snap_res" is supposed to give.

In my UI, the 'save' button is using partial and I don't fully understand how that works. If I move save_snapshots behind 'texSizeControl' in the order of commands, it just simply doesn't run (I think?).

Was hoping to have a little help explaining how passing arguments works when using functions, and the order of operations when it comes to the "partial" thing...
The only reason I'm this far is because of this site and finding examples in other areas. The whole radio buttons thing is a total challenge and I don't know if I fully have it working correctly :/ sorry.

any help or advice you have to offer I am all ears!!

## UV SNAPSHOTS
## PYTHON
import maya.cmds as mc

def get_snapshot_res(label, *args):
    uv_snap_res = label

def save_snapshots(get_snapshot_res, uv_snap_res, *args):
    get_snapshot_res(uv_snap_res)
    print get_snapshot_res

def passValue(texSizeControl, *args):
    radioCol = mc.radioCollection(texSizeControl, query=True, sl=True)
    getSelectRadioVal = mc.radioButton(radioCol, query=True, label=True)
    get_snapshot_res(getSelectRadioVal)

def save_snapshots_ui(*args):
    myWindow = 'Create UV Snapshots'
    if mc.window(myWindow, exists=True):
        mc.deleteUI(myWindow)
    mc.window(myWindow, title = myWindow)
    mc.columnLayout(adjustableColumn=True)
    mc.text(label='Choose your resolution for UV Snapshots', font='obliqueLabelFont')
    texSizeControl = mc.radioCollection()
    saveRadio1k = mc.radioButton(label='1024')
    saveRadio2k = mc.radioButton(label='2048')
    saveRadio4k = mc.radioButton(label='4096')
    saveRadio8k = mc.radioButton(label='8192')
    texSizeControl = mc.radioCollection(texSizeControl, edit=True, select=saveRadio2k )
    mc.button(label='save', command= partial(passValue, save_snapshots, texSizeControl))
    mc.setParent( '..' )
    mc.showWindow()

save_snapshots_ui()

Body:
Try to remove the *args where there is no need, you should write your script like this :

cmd SNAPSHOT need(FULLPATH, RES, UVRANGE)

ui set resolution

ui set png name

ui set path

ui select the uvRange

snapshot button send -> res, name, path, uvRange

get ui RES

get ui name and get ui path to create FULLPATH

get ui UVRANGE

gather all this get into one cmd to launch SNAPSHOT

====================================

import maya.cmds as mc
# GATHER
def ui_save_snapshots(texSizeControl, *args):
    # *args is only used when the def is inside ui
    # here it is gathering information to launch the maya command
    RATIO = get_snapshot_res(texSizeControl)
    path = 'something to get the path'
    save_snapshots(path, RATIO)
# GET RES
def ui_get_snapshot_res(label):
    radioCol = mc.radioCollection(texSizeControl, query=True, sl=True)
    RATIO = mc.radioButton(radioCol, query=True, label=True)
    return RATIO
SNAPSHOT
def save_snapshots(path, resolution, uvRange=[0,1,0,1]):
    # this def is a without any ui
    # path = "/marza/proj/fuji2019/work/Prop/trap/sim/everyone/simRig/images/outUV.jpg"
    uMin, uMax, vMin, vMax = uvRange
    cmds.uvSnapshot(o=True,ff='jpg', xr=resolution, yr=4096, aa=True, r=255, g=255, b=255, n=path, uMin=uMin, uMax=uMax, vMin=vMin, vMax=vMax)

def save_snapshots_ui():
    myWindow = 'Create UV Snapshots'
    if mc.window(myWindow, exists=True):
        mc.deleteUI(myWindow)
    mc.window(myWindow, title = myWindow)
    mc.columnLayout(adjustableColumn=True)
    mc.text(label='Choose your resolution for UV Snapshots', font='obliqueLabelFont')
    texSizeControl = mc.radioCollection()
    saveRadio1k = mc.radioButton(label='1024')
    saveRadio2k = mc.radioButton(label='2048')
    saveRadio4k = mc.radioButton(label='4096')
    saveRadio8k = mc.radioButton(label='8192')
    texSizeControl = mc.radioCollection(texSizeControl, edit=True, select=saveRadio2k )
    # send textSiZeControl to passValue
    mc.button(label='save', command= partial(passValue, texSizeControl))
    mc.setParent( '..' )
    mc.showWindow()

save_snapshots_ui()


问:
Validation errors: how to get rid of "Validation failed: "?
whenever I do

```<code>        rescue Exception => e
        flash[:error] = e.message
</code>```

the e.message will always contain the "Validation error:" string and
the Object

Example:

Validation failed: Price "message:", Price "message"

How do I tell rails that I just want the message? and not the other
parts of the validation error to be displayed?

答:
You can get the data you want from the #errors attribute of the model you were trying to save.  There could potentially be multiple validation errors (not just one).

See http://api.rubyonrails.org/classes/ActiveModel/Errors.html

Body:
whenever I do

        rescue Exception => e
        flash[:error] = e.message

the e.message will always contain the "Validation error:" string and
the Object

Example:

Validation failed: Price "message:", Price "message"

How do I tell rails that I just want the message? and not the other
parts of the validation error to be displayed?


问:
Requiring button press before calculations carried out and plot drawn in Shiny
I have some code I am trying to write in Shiny.  This involves the following steps:
- choosing a date
- checking whether a valid input file exists for the date
- if a valid input file exists, pulling down remote time series ending on that date
- carrying out calculations
- plotting the result of the calculations

The date checking should be done reactively. However, the dime series pull down and calculations take some time.  I therefore want this to be done only with a button press.

I have most of this working.  However, whilst I can put the first instance of the calculation off until a button press using

```<code>    "if(input$run_shiny_risk==0){
    } else {
    #some code
    }
</code>```

I can't stop it from calculating automatically on subsequent instances.  In other words, as soon as a valid date is chosen, calculations start automatically.  I have tried to isolate the calculations without success. I have also tried to isolate a dummy variable that is driven by the button value, but again no luck.  Here is what I have in terms of code:

```<code>library(shiny)

ui <- fluidPage(

titlePanel("Risk Dashboard"),
sidebarLayout(

sidebarPanel(

  helpText("Effective date"),

  dateInput("shiny_end_date",
            label = "Date (yyyy-mm-dd):",
            value = "2018-12-31"),

  actionButton("run_shiny_risk",
               label = "Run risk report:"),

  textOutput("selected_var")

),

mainPanel(

  plotOutput("selected_var1")

)
)
)

server <- function(input, output) {

shiny_risk_test <- 0

output$selected_var <- renderText({

holdings_data_file <-paste(substr(input$shiny_end_date,3,4),substr(input$shiny_end_date,6,7),substr(input$shiny_end_date,9,10),"_Data.csv",sep="")
if(file.exists(holdings_data_file)){

  end_date <- input$shiny_end_date

  paste("You have selected", end_date)

} else {
  "No such file"
}
})

output$selected_var1 <- renderPlot({

holdings_data_file <-paste(substr(input$shiny_end_date,3,4),substr(input$shiny_end_date,6,7),substr(input$shiny_end_date,9,10),"_Data.csv",sep="")

if(file.exists(holdings_data_file)){

 if(input$run_shiny_risk==0){

   #this stops the chart from being drawn initially...

    } else {

    plot_data <- cbind(c(1,2,3,4),c(1,2,3,4))
    p<-plot(plot_data)

    p
    }

} else {

}
})
}

shinyApp(ui = ui, server = server)
</code>```

So, this works until the first click.  I can change dates between valid and invalid ones, and no chart is drawn until I hit the button.  Then, if I move to an invalid date, the chart vanishes, which is right.  But if I go back to a valid date, the chart appears again (and would be recalculated if I had the actual, lengthy code enclosed).  And code that just stops calculations until the button is pressed, not only the first time but in subsequent case, would be great.  Thank you!

答:
I solved this problem in a previous application via the use of reactive values. Consider the following example:

```<code>server <- function(input, output, session) {

  output_staging <- reactiveValues()
  output_staging$title <- NA

  observeEvent(input$updateButton,{  update_title()  })

  update_title <- function(){
    output_staging$title <- paste0("random number ",runif(1))
  }

  output$title <- renderText(output_staging$title)

}
</code>```

The renderText output looks at the reactive value stored in output_staging$title. Each time the button is clicked, an update function is called that replaces the reactive value.

Note that I could merge the function update_title and the observeEvent command. But having them separate gives me more flexibility.

In your context, I would recommend separating the data prep and the plot generation in order to use this method. You can use the reactive values at either place:

Button sends data to reactiveValue: data --> reactive --> make plot --> display plot

Button sends plot to reactiveValue: data --> make plot --> reactive --> display plot

But you don't need to use it at both.

Body:
I have some code I am trying to write in Shiny.  This involves the following steps:
- choosing a date
- checking whether a valid input file exists for the date
- if a valid input file exists, pulling down remote time series ending on that date
- carrying out calculations
- plotting the result of the calculations

The date checking should be done reactively. However, the dime series pull down and calculations take some time.  I therefore want this to be done only with a button press.

I have most of this working.  However, whilst I can put the first instance of the calculation off until a button press using

    "if(input$run_shiny_risk==0){
    } else {
    #some code
    }

I can't stop it from calculating automatically on subsequent instances.  In other words, as soon as a valid date is chosen, calculations start automatically.  I have tried to isolate the calculations without success. I have also tried to isolate a dummy variable that is driven by the button value, but again no luck.  Here is what I have in terms of code:

library(shiny)

ui <- fluidPage(

titlePanel("Risk Dashboard"),
sidebarLayout(

sidebarPanel(

  helpText("Effective date"),

  dateInput("shiny_end_date",
            label = "Date (yyyy-mm-dd):",
            value = "2018-12-31"),

  actionButton("run_shiny_risk",
               label = "Run risk report:"),

  textOutput("selected_var")

),

mainPanel(

  plotOutput("selected_var1")

)
)
)

server <- function(input, output) {

shiny_risk_test <- 0

output$selected_var <- renderText({

holdings_data_file <-paste(substr(input$shiny_end_date,3,4),substr(input$shiny_end_date,6,7),substr(input$shiny_end_date,9,10),"_Data.csv",sep="")
if(file.exists(holdings_data_file)){

  end_date <- input$shiny_end_date

  paste("You have selected", end_date)

} else {
  "No such file"
}
})

output$selected_var1 <- renderPlot({

holdings_data_file <-paste(substr(input$shiny_end_date,3,4),substr(input$shiny_end_date,6,7),substr(input$shiny_end_date,9,10),"_Data.csv",sep="")

if(file.exists(holdings_data_file)){

 if(input$run_shiny_risk==0){

   #this stops the chart from being drawn initially...

    } else {

    plot_data <- cbind(c(1,2,3,4),c(1,2,3,4))
    p<-plot(plot_data)

    p
    }

} else {

}
})
}

shinyApp(ui = ui, server = server)

So, this works until the first click.  I can change dates between valid and invalid ones, and no chart is drawn until I hit the button.  Then, if I move to an invalid date, the chart vanishes, which is right.  But if I go back to a valid date, the chart appears again (and would be recalculated if I had the actual, lengthy code enclosed).  And code that just stops calculations until the button is pressed, not only the first time but in subsequent case, would be great.  Thank you!

Body:
I solved this problem in a previous application via the use of reactive values. Consider the following example:

server <- function(input, output, session) {

  output_staging <- reactiveValues()
  output_staging$title <- NA

  observeEvent(input$updateButton,{  update_title()  })

  update_title <- function(){
    output_staging$title <- paste0("random number ",runif(1))
  }

  output$title <- renderText(output_staging$title)

}

The renderText output looks at the reactive value stored in output_staging$title. Each time the button is clicked, an update function is called that replaces the reactive value.

Note that I could merge the function update_title and the observeEvent command. But having them separate gives me more flexibility.

In your context, I would recommend separating the data prep and the plot generation in order to use this method. You can use the reactive values at either place:

Button sends data to reactiveValue: data --> reactive --> make plot --> display plot

Button sends plot to reactiveValue: data --> make plot --> reactive --> display plot

But you don't need to use it at both.


问:
chrome.downloads.download ignoring parameters after 'url'
I am trying to write a simple extension that will automatically download an image from our company website to a directory.  The problem is that chrome.downloads.download seems to ignore every parameter after 'url'.
It downloads the file.  But keeps the original name, and ignores sub-directories.  It will append a (#) if the file already exits instead of overwriting as specified in the code.

I have tried various ways of implementing the object passed to chrome.downloads.download, including creating a object with all the parameters and passing that object.  I've tried using quotes even where it didn't make sense.
I have tried reformatting the filename parameter, even giving it a fixed value of "foo.jpg".  I have tried doing this in both the content.js and bs.js.
I have confirmed that the filename is passed to the background script and the value is accessible by displaying it with an alert() in the background script

```<code>//Manifest.js (important parts)
"permissions": ["downloads","webNavigation"],
"background": {
    "scripts": ["bs.js"],
    "Persistent": false
    },
"content_scripts": [
    {
        "matches": ["<all_urls>"],
        "js": ["jquery-3.4.1.min.js"]
    },
    {
        "matches": ["https://mycompany.com/*"],
        "js": ["content.js"]
    }

    ]

//Content.js (important parts)
var $imgs = $('#spec_jpg img');
var url = "https:" + $imgs.attr('src');
var filename ="specificationArchive/" +  url.substring(url.lastIndexOf('/')+1); //edited
chrome.runtime.sendMessage({url: url, filename: filename});

//bs.js (whole thing)
chrome.runtime.onMessage.addListener(
    function(request, sender){
      chrome.downloads.download ( { url: request.url,
      filename: request.filename,
      conflictAction: "overwrite",
      saveAs: false }
      )
    }
);
</code>```

The extension does download the file, but I expected it to save it into a sub-directorycalled specificationArchive.  I also expected it to overwrite an existing file instead of appending a (#) to the end of the name.  Even when passing an absolute string for the filename, I get the file's original name

答:
The solution provided by wOxxOm is to add an additional listener.  Here's the code that was added to bs.js

```<code>//bs.js
chrome.downloads.onDeterminingFilename.addListener(function(item, suggest) {
suggest({filename: "specificationArchive/" + item.filename, conflictAction: 'overwrite'});
});
</code>```

Once this was included it saved to the directory listed.
Thanks again.

Body:
I am trying to write a simple extension that will automatically download an image from our company website to a directory.  The problem is that chrome.downloads.download seems to ignore every parameter after 'url'.
It downloads the file.  But keeps the original name, and ignores sub-directories.  It will append a (#) if the file already exits instead of overwriting as specified in the code.

I have tried various ways of implementing the object passed to chrome.downloads.download, including creating a object with all the parameters and passing that object.  I've tried using quotes even where it didn't make sense.
I have tried reformatting the filename parameter, even giving it a fixed value of "foo.jpg".  I have tried doing this in both the content.js and bs.js.
I have confirmed that the filename is passed to the background script and the value is accessible by displaying it with an alert() in the background script

//Manifest.js (important parts)
"permissions": ["downloads","webNavigation"],
"background": {
    "scripts": ["bs.js"],
    "Persistent": false
    },
"content_scripts": [
    {
        "matches": ["<all_urls>"],
        "js": ["jquery-3.4.1.min.js"]
    },
    {
        "matches": ["https://mycompany.com/*"],
        "js": ["content.js"]
    }

    ]

//Content.js (important parts)
var $imgs = $('#spec_jpg img');
var url = "https:" + $imgs.attr('src');
var filename ="specificationArchive/" +  url.substring(url.lastIndexOf('/')+1); //edited
chrome.runtime.sendMessage({url: url, filename: filename});

//bs.js (whole thing)
chrome.runtime.onMessage.addListener(
    function(request, sender){
      chrome.downloads.download ( { url: request.url,
      filename: request.filename,
      conflictAction: "overwrite",
      saveAs: false }
      )
    }
);

The extension does download the file, but I expected it to save it into a sub-directorycalled specificationArchive.  I also expected it to overwrite an existing file instead of appending a (#) to the end of the name.  Even when passing an absolute string for the filename, I get the file's original name

Body:
The solution provided by wOxxOm is to add an additional listener.  Here's the code that was added to bs.js

//bs.js
chrome.downloads.onDeterminingFilename.addListener(function(item, suggest) {
suggest({filename: "specificationArchive/" + item.filename, conflictAction: 'overwrite'});
});

Once this was included it saved to the directory listed.
Thanks again.


问:
How to fix: "EPROTO" Error after upgrading Node's version
The following code works on Node's v10.15.3 version:

```<code>const { post } = require('request');

post({
  url: 'https://cidadao.sinesp.gov.br/sinesp-cidadao/mobile/consultar-placa/v4',
  body: '<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n<v:Envelope xmlns:v=\"http://schemas.xmlsoap.org/soap/envelope/\">\n  <v:Header>\n    <b>LGE Nexus 5</b>\n    <c>ANDROID</c>\n    <d>v4</d>\n    <e>4.3.2</e>\n    <f>98.193.54.223</f>\n    <g>514650d8dba4784ed08b5a029583576361a50bc5</g>\n    <h>-3272.3179572637086</h>\n    <i>940.839492700698</i>\n    <j/>\n    <k/>\n    <l>2019-05-24 10:24:35</l>\n    <m>8797e74f0d6eb7b1ff3dc114d4aa12d3</m>\n  </v:Header>\n  <v:Body xmlns:n0=\"http://soap.ws.placa.service.sinesp.serpro.gov.br/\">\n    <n0:getStatus>\n      <a>LSU3J43</a>\n    </n0:getStatus>\n  </v:Body>\n</v:Envelope>',
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
    'User-Agent': 'SinespCidadao / 3.0.2.1 CFNetwork / 758.2.8 Darwin / 15.0.0',
    Host: 'cidadao.sinesp.gov.br'
  },
}, (err, httpResponse, body) => {
  if (err) return console.error(err);
  console.log(JSON.stringify(httpResponse));
});
</code>```

But after upgrading to v12.2.0 or above I got the following error:

```<code>Error: write EPROTO 17432:error:1425F102:SSL routines:ssl_choose_client_version:unsupported protocol:c:\ws\deps\openssl\openssl\ssl\statem\statem_lib.c:1922:

    at WriteWrap.onWriteComplete [as oncomplete] (internal/stream_base_commons.js:83:16) {
  errno: 'EPROTO',
  code: 'EPROTO',
  syscall: 'write'
}
</code>```

How can I fix it?

答:
As the same code works on Node.js v10.15.3, but not work on v12.2.0, and the error message indicates "unsupported protocol", the most possible root cause of this issue is: the minimal supported TLS version in Node.js 10 is TLSv1.0, but since v11.4.0, it is raised to TLSv1.2 (tls.DEFAULT_MIN_VERSION). I suspect the certificate of cidadao.sinesp.gov.br is signed with TLSv1.0, which works on Node.js v10.15.3, but not on v12.2.0.

To make Node.js accept TLSv1.0, you can lauch Node.js process with --tls-min-v1.0 option.

I made an experiment and it works well:

BTW, the certificate of cidadao.sinesp.gov.br is invalid now. It has been expired since May 2018 -- as the OP mentioned, the request should be sent from Brazil (or through proxy node in Brazil).

Body:
The following code works on Node's v10.15.3 version:

const { post } = require('request');

post({
  url: 'https://cidadao.sinesp.gov.br/sinesp-cidadao/mobile/consultar-placa/v4',
  body: '<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n<v:Envelope xmlns:v=\"http://schemas.xmlsoap.org/soap/envelope/\">\n  <v:Header>\n    LGE Nexus 5\n    <c>ANDROID</c>\n    <d>v4</d>\n    <e>4.3.2</e>\n    <f>98.193.54.223</f>\n    <g>514650d8dba4784ed08b5a029583576361a50bc5</g>\n    <h>-3272.3179572637086</h>\n    940.839492700698\n    <j/>\n    <k/>\n    <l>2019-05-24 10:24:35</l>\n    <m>8797e74f0d6eb7b1ff3dc114d4aa12d3</m>\n  </v:Header>\n  <v:Body xmlns:n0=\"http://soap.ws.placa.service.sinesp.serpro.gov.br/\">\n    <n0:getStatus>\n      LSU3J43\n    </n0:getStatus>\n  </v:Body>\n</v:Envelope>',
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
    'User-Agent': 'SinespCidadao / 3.0.2.1 CFNetwork / 758.2.8 Darwin / 15.0.0',
    Host: 'cidadao.sinesp.gov.br'
  },
}, (err, httpResponse, body) => {
  if (err) return console.error(err);
  console.log(JSON.stringify(httpResponse));
});

But after upgrading to v12.2.0 or above I got the following error:

Error: write EPROTO 17432:error:1425F102:SSL routines:ssl_choose_client_version:unsupported protocol:c:\ws\deps\openssl\openssl\ssl\statem\statem_lib.c:1922:

    at WriteWrap.onWriteComplete [as oncomplete] (internal/stream_base_commons.js:83:16) {
  errno: 'EPROTO',
  code: 'EPROTO',
  syscall: 'write'
}

How can I fix it?


问:
Custom camel component using in spring-boot application
I'm a beginner with Camel Integration and I need to create my custom camel component and use it in a Spring Boot application.

I've tried to generate my component using   maven archetype .

So the command is like that:

mvn archetype:generate -DarchetypeGroupId=org.apache.camel.archetypes
  -DarchetypeArtifactId=camel-archetype-component -DarchetypeVersion=2.12.1 -DgroupId=my.tcp.camel.component -DartifactId=my-tcp -Dname=MyTCP -Dscheme=my-tcp

The generated code looks like that

```<code>public class MyTCPComponent extends DefaultComponent {

    protected Endpoint createEndpoint(String uri, String remaining, Map<String, Object> parameters) throws Exception {
        Endpoint endpoint = new MyTCPEndpoint(uri, this);
        setProperties(endpoint, parameters);
        return endpoint;
    }
}

public class MyTCPEndpoint extends DefaultEndpoint {

    public MyTCPEndpoint() {}

    public MyTCPEndpoint(String uri, PtTCPComponent component) {
        super(uri, component);
    }

    public MyTCPEndpoint(String endpointUri) {
        super(endpointUri);
    }

    public Producer createProducer() throws Exception {
        return new MyTCPProducer(this);
    }

    public Consumer createConsumer(Processor processor) throws Exception {
        return new MyTCPConsumer(this, processor);
    }

    public boolean isSingleton() {
        return true;
    }
}

public class MyTCPConsumer extends ScheduledPollConsumer {
    private final MyTCPEndpoint endpoint;

    public MyTCPConsumer(MyTCPEndpoint endpoint, Processor processor) {
        super(endpoint, processor);
        this.endpoint = endpoint;
    }

    @Override
    protected int poll() throws Exception {
        Exchange exchange = endpoint.createExchange();

        // create a message body
        Date now = new Date();
        exchange.getIn().setBody("Hello World! The time is " + now);

        try {
            // send message to next processor in the route
            getProcessor().process(exchange);
            return 1; // number of messages polled
        } finally {
            // log exception if an exception occurred and was not handled
            if (exchange.getException() != null) {
                getExceptionHandler().handleException("Error processing exchange", exchange, exchange.getException());
            }
        }
    }
}

public class MyTCPProducer extends DefaultProducer {
    private static final Logger LOG = LoggerFactory.getLogger(MyTCPProducer.class);
    private MyTCPEndpoint endpoint;

    public MyTCPProducer(MyTCPEndpoint endpoint) {
        super(endpoint);
        this.endpoint = endpoint;
    }

    public void process(Exchange exchange) throws Exception {
        System.out.println(exchange.getIn().getBody());
    }

}
</code>```

and the manifest file created in resources.

I've found out that you can initialize springBoot with FatJar

```<code>@SpringBootApplication
public class MySpringBootRouter extends FatJarRouter {

    @Override
    public void configure() {
        from("timer://trigger").
                transform().simple("ref:myBean").
                to("log:out", "mock:test");
    }

    @Bean
    String myBean() {
        return "I'm Spring bean!";
    }

}
</code>```

Have somebody integrated their custom component within a SpringBoot Application.

I would prefer to make springboot working with camel auto-discovery component.

Thank you.

答:
The issue was that I was trying to add a Custom camel component in a camel spring boot.

I've decided to use only as a reference bean instead of component.

```<code>  @Component("my-tcp")
    @Slf4j
    public class MyTCPComponent {

           public String messageProcess(Exchange msg){
             // do your logic here
           }
  }

@Configuration
public class MyTCPCamelRouter extends RouteBuilder {

    @Override
    public void configure() throws Exception {

        from("direct:my-tcp")
                .to("bean:my-tcp")
                .to("log:foo");
    }
}
</code>```

and in pom.xml

```<code> <dependency>
        <groupId>org.apache.camel</groupId>
        <artifactId>camel-spring-boot-starter</artifactId>
        <version>3.0.0-SNAPSHOT</version>
 </dependency>
</code>```

Another solution I was thinking about is to generate camel custom component with maven archetype, and after that to import this as a jar in a spring-boot application.

Body:
I'm a beginner with Camel Integration and I need to create my custom camel component and use it in a Spring Boot application.

I've tried to generate my component using   maven archetype .

So the command is like that:

mvn archetype:generate -DarchetypeGroupId=org.apache.camel.archetypes
  -DarchetypeArtifactId=camel-archetype-component -DarchetypeVersion=2.12.1 -DgroupId=my.tcp.camel.component -DartifactId=my-tcp -Dname=MyTCP -Dscheme=my-tcp

The generated code looks like that

public class MyTCPComponent extends DefaultComponent {

    protected Endpoint createEndpoint(String uri, String remaining, Map<String, Object> parameters) throws Exception {
        Endpoint endpoint = new MyTCPEndpoint(uri, this);
        setProperties(endpoint, parameters);
        return endpoint;
    }
}

public class MyTCPEndpoint extends DefaultEndpoint {

    public MyTCPEndpoint() {}

    public MyTCPEndpoint(String uri, PtTCPComponent component) {
        super(uri, component);
    }

    public MyTCPEndpoint(String endpointUri) {
        super(endpointUri);
    }

    public Producer createProducer() throws Exception {
        return new MyTCPProducer(this);
    }

    public Consumer createConsumer(Processor processor) throws Exception {
        return new MyTCPConsumer(this, processor);
    }

    public boolean isSingleton() {
        return true;
    }
}

public class MyTCPConsumer extends ScheduledPollConsumer {
    private final MyTCPEndpoint endpoint;

    public MyTCPConsumer(MyTCPEndpoint endpoint, Processor processor) {
        super(endpoint, processor);
        this.endpoint = endpoint;
    }

    @Override
    protected int poll() throws Exception {
        Exchange exchange = endpoint.createExchange();

        // create a message body
        Date now = new Date();
        exchange.getIn().setBody("Hello World! The time is " + now);

        try {
            // send message to next processor in the route
            getProcessor().process(exchange);
            return 1; // number of messages polled
        } finally {
            // log exception if an exception occurred and was not handled
            if (exchange.getException() != null) {
                getExceptionHandler().handleException("Error processing exchange", exchange, exchange.getException());
            }
        }
    }
}

public class MyTCPProducer extends DefaultProducer {
    private static final Logger LOG = LoggerFactory.getLogger(MyTCPProducer.class);
    private MyTCPEndpoint endpoint;

    public MyTCPProducer(MyTCPEndpoint endpoint) {
        super(endpoint);
        this.endpoint = endpoint;
    }

    public void process(Exchange exchange) throws Exception {
        System.out.println(exchange.getIn().getBody());
    }

}

and the manifest file created in resources.

I've found out that you can initialize springBoot with FatJar

@SpringBootApplication
public class MySpringBootRouter extends FatJarRouter {

    @Override
    public void configure() {
        from("timer://trigger").
                transform().simple("ref:myBean").
                to("log:out", "mock:test");
    }

    @Bean
    String myBean() {
        return "I'm Spring bean!";
    }

}

Have somebody integrated their custom component within a SpringBoot Application.

I would prefer to make springboot working with camel auto-discovery component.

Thank you.

Body:
The issue was that I was trying to add a Custom camel component in a camel spring boot.

I've decided to use only as a reference bean instead of component.

  @Component("my-tcp")
    @Slf4j
    public class MyTCPComponent {

           public String messageProcess(Exchange msg){
             // do your logic here
           }
  }

@Configuration
public class MyTCPCamelRouter extends RouteBuilder {

    @Override
    public void configure() throws Exception {

        from("direct:my-tcp")
                .to("bean:my-tcp")
                .to("log:foo");
    }
}

and in pom.xml

 <dependency>
        <groupId>org.apache.camel</groupId>
        <artifactId>camel-spring-boot-starter</artifactId>
        <version>3.0.0-SNAPSHOT</version>
 </dependency>

Another solution I was thinking about is to generate camel custom component with maven archetype, and after that to import this as a jar in a spring-boot application.


问:
How do I seed data of a class which requires the user_id of the current user?
I am making a fitness web application as part of a project. This project has 5 models. User, Muscle_Groups, Diet, Workout and Meal. The associations are on the code below. As of now, I have a new page and a show page for the User. I want to redirect the user from the show page to the muscle_group index page where it will list all the muscles in a persons body. The User obviously has many Muscle_Groups, I want to seed the muscle_group index page with all muscle groups (biceps, back, legs, chest). The issue is, I need to create these instances with the user_id of the current user using the app and I have no idea how to do it at this point. I hope my brief explanation helps, my code is below.</p>

```<code>
class User < ApplicationRecord
    has_many :diets
    has_many :muscle_groups

    before_save { self.email = email.downcase }
    #before saving, the email is lowercased
    validates :name, presence: true, length: { maximum: 50 }
    #validates the names presence, max char length is 50

    validates :weight, presence: true, numericality: true
    validates :height, presence: true, numericality: true

    validates_inclusion_of :gender, :in => %w( m f male Male female Female)
    validates :age, presence: true, numericality: {only_integer: true }

    VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
    validates :email, presence: true, length: { maximum: 255 },
                      format: { with: VALID_EMAIL_REGEX },
                      uniqueness: { case_sensitive: false }

    has_secure_password
end

class Muscle_Group < ApplicationRecord
    has_many :workouts
    belongs_to :user
end

class Diet < ApplicationRecord
    belongs_to :user
    has_many :meals
end

class Meal < ApplicationRecord
    belongs_to :diet
end

class Workout < ApplicationRecord
    belongs_to :muscle_group
end

class UsersController < ApplicationController

    def new #render's the sign up page for a new user
        @user = User.new
    end

    def create #action to create the user
        @user = User.create(user_params)

        if @user.save
            log_in @user
            flash[:success] = "Are you ready to GitFit?!"
            redirect_to @user #redirects to the user's show page, which is the main menu
        else
            render 'new'
        end
    end

    def show
        @user = User.find(params[:id])
    end

    private
        def user_params
            params.require(:user).permit(:name,
            :email,
            :weight,
            :height,
            :gender,
            :age,
            :password,
            :password_confirmation)
        end

end

class Muscle_GroupsController < ApplicationController

    def index
        @muscle_groups = Muscle_Group.all
    end
end

</code>```

答:
Just create one sample user in the seed file and associate the muscle groups to him. Then login with this account and you will have the results.
For instance like this

```<code># seed.rb

sample_user = User.create(name: "Joe", weight: 100, height: 180,
                          age: 23, email: "test@mail.com",
                          password: "123456")

MuscleGroup.create(user: sample_user, ...)
Diet.create(user: sample_user)
...
</code>```

I don't know the exact fields and the measuring system you use, but it could look like that.

Another way in production would be to sign up as a user of the website. And then find yourself in the console (rails c) and add the muscle_group and diet and so on and connect it manually to your user.

Body:
I am making a fitness web application as part of a project. This project has 5 models. User, Muscle_Groups, Diet, Workout and Meal. The associations are on the code below. As of now, I have a new page and a show page for the User. I want to redirect the user from the show page to the muscle_group index page where it will list all the muscles in a persons body. The User obviously has many Muscle_Groups, I want to seed the muscle_group index page with all muscle groups (biceps, back, legs, chest). The issue is, I need to create these instances with the user_id of the current user using the app and I have no idea how to do it at this point. I hope my brief explanation helps, my code is below.

class User < ApplicationRecord
    has_many :diets
    has_many :muscle_groups

    before_save { self.email = email.downcase }
    #before saving, the email is lowercased
    validates :name, presence: true, length: { maximum: 50 }
    #validates the names presence, max char length is 50

    validates :weight, presence: true, numericality: true
    validates :height, presence: true, numericality: true

    validates_inclusion_of :gender, :in => %w( m f male Male female Female)
    validates :age, presence: true, numericality: {only_integer: true }

    VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
    validates :email, presence: true, length: { maximum: 255 },
                      format: { with: VALID_EMAIL_REGEX },
                      uniqueness: { case_sensitive: false }

    has_secure_password
end

class Muscle_Group < ApplicationRecord
    has_many :workouts
    belongs_to :user
end

class Diet < ApplicationRecord
    belongs_to :user
    has_many :meals
end

class Meal < ApplicationRecord
    belongs_to :diet
end

class Workout < ApplicationRecord
    belongs_to :muscle_group
end

class UsersController < ApplicationController

    def new #render's the sign up page for a new user
        @user = User.new
    end

    def create #action to create the user
        @user = User.create(user_params)

        if @user.save
            log_in @user
            flash[:success] = "Are you ready to GitFit?!"
            redirect_to @user #redirects to the user's show page, which is the main menu
        else
            render 'new'
        end
    end

    def show
        @user = User.find(params[:id])
    end

    private
        def user_params
            params.require(:user).permit(:name,
            :email,
            :weight,
            :height,
            :gender,
            :age,
            :password,
            :password_confirmation)
        end

end

class Muscle_GroupsController < ApplicationController

    def index
        @muscle_groups = Muscle_Group.all
    end
end

Body:
Just create one sample user in the seed file and associate the muscle groups to him. Then login with this account and you will have the results.
For instance like this

# seed.rb

sample_user = User.create(name: "Joe", weight: 100, height: 180,
                          age: 23, email: "test@mail.com",
                          password: "123456")

MuscleGroup.create(user: sample_user, ...)
Diet.create(user: sample_user)
...

I don't know the exact fields and the measuring system you use, but it could look like that.

Another way in production would be to sign up as a user of the website. And then find yourself in the console (rails c) and add the muscle_group and diet and so on and connect it manually to your user.


问:
Using aws_secret in ansible
I'm trying to retrieve password from aws secret manager using ansible 2.8 using lookup.

Below things are not working for me:

In .bashrc, I have exported region

Ansible Environment Variables in task

Setting up ansible variables in pre_tasks

- hosts: StagingApps
  remote_user: staging
  gather_facts: false

  tasks:
  - debug:
      var: "{{ lookup('aws_secret', 'staging_mongodb_pass', region='us-east-1') }}"
      msg: "{{ query('aws_secret', 'staging_mongodb_pass', region='us-east-1') }}"
      environment:
        region: 'us-east-1'
```

Error Message:

FAILED! => {"msg": "An unhandled exception occurred while running the lookup plugin 'aws_secret'. Error was a , original message: 'Requested entry (plugin_type: lookup plugin: aws_secret setting: region ) was not defined in configuration.'"}

答:
below playbook has worked for me </p>

```<code>  - name: "register mongodb from secretsmanager"
    shell: "aws secretsmanager get-secret-value --secret-id staging_mongodb"
    register: mongodb_pass
    delegate_to: 127.0.0.1

  - set_fact:
      mongodb_pass_dict: "{{ mongodb_pass.stdout | from_json | json_query('SecretString')  }}"

  - set_fact:
      mongodb_pass_list: "{{ ['staging_mongodb'] | map('extract', mongodb_pass_dict) | list  }}"

  - set_fact:
      mongodb_pass: "{{ mongodb_pass_list[0] }}"

    - template:
      src: application.properties.j2
      dest: application.properties
      mode: 0644
      backup: yes
</code>```

Title: Using aws_secret in ansible

Body:
I'm trying to retrieve password from aws secret manager using ansible 2.8 using lookup.

Below things are not working for me:

In .bashrc, I have exported region

Ansible Environment Variables in task

Setting up ansible variables in pre_tasks

- hosts: StagingApps
  remote_user: staging
  gather_facts: false

  tasks:
  - debug:
      var: "{{ lookup('aws_secret', 'staging_mongodb_pass', region='us-east-1') }}"
      msg: "{{ query('aws_secret', 'staging_mongodb_pass', region='us-east-1') }}"
      environment:
        region: 'us-east-1'

Error Message:

FAILED! => {"msg": "An unhandled exception occurred while running the lookup plugin 'aws_secret'. Error was a , original message: 'Requested entry (plugin_type: lookup plugin: aws_secret setting: region ) was not defined in configuration.'"}

Body:
below playbook has worked for me

  - name: "register mongodb from secretsmanager"
    shell: "aws secretsmanager get-secret-value --secret-id staging_mongodb"
    register: mongodb_pass
    delegate_to: 127.0.0.1

  - set_fact:
      mongodb_pass_dict: "{{ mongodb_pass.stdout | from_json | json_query('SecretString')  }}"

  - set_fact:
      mongodb_pass_list: "{{ ['staging_mongodb'] | map('extract', mongodb_pass_dict) | list  }}"

  - set_fact:
      mongodb_pass: "{{ mongodb_pass_list[0] }}"

    - template:
      src: application.properties.j2
      dest: application.properties
      mode: 0644
      backup: yes


问:
Angular 5 custom pipe
I am new to Angular and facing this issue.

I want to create a custom pipe for convert decimal codes into the base64 image then displaying them in views. I have complete code for this issue but don't know how to use it for the custom pipe.

This is my code:

my-component.ts

```<code>this.imgIn = "";
var chars1 = dataParkir.pictstart.data; // array of decimal codes
for (var k = 0; k < chars1.length; k++) {
  var convert = String.fromCharCode(chars1[k]); // convert into base64
  this.imgIn = this.imgIn + convert;
}

this.base64ImageIn = this.sanitizer.bypassSecurityTrustResourceUrl('data:image/png;base64,' + this.imgIn);
</code>```

Has anyone else experienced this, please help me?

答:
If your snippet of code already does what you want, then moving to a custom pipe is pretty straight forward. You just need to bind your array of decimal and use a pipe that converts it exactly like you do now. Something like:

Pipe:

```<code>import { Pipe, PipeTransform } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';
@Pipe({
  name: 'base64'
})
export class Base64Pipe implements PipeTransform {
  constructor(private sanitizer: DomSanitizer){}

  transform(value: any,){
    let imgIn="";
    for (var k = 0; k < value.length; k++) {
        var convert = String.fromCharCode(value[k]); // convert into base64
        imgIn += convert;
      }
      let base64Url =this.sanitizer.bypassSecurityTrustResourceUrl('data:image/png;base64,' + imgIn);
      return base64Url;
  }
}
</code>```

And you'd use it like so: [src]="yourDecimalCodeArray | base64"

Here's a Stackblitz to illustrate.

Keep in mind that using this.sanitizer.bypassSecurityTrustResourceUrl mean you have to bind safely (Safe value must use [property]=binding after bypass security with DomSanitizer).

Hope this helps.

Title: Angular 5 custom pipe

Body:
I am new to Angular and facing this issue.

I want to create a custom pipe for convert decimal codes into the base64 image then displaying them in views. I have complete code for this issue but don't know how to use it for the custom pipe.

This is my code:

my-component.ts

this.imgIn = "";
var chars1 = dataParkir.pictstart.data; // array of decimal codes
for (var k = 0; k < chars1.length; k++) {
  var convert = String.fromCharCode(chars1[k]); // convert into base64
  this.imgIn = this.imgIn + convert;
}

this.base64ImageIn = this.sanitizer.bypassSecurityTrustResourceUrl('data:image/png;base64,' + this.imgIn);

Has anyone else experienced this, please help me?

Body:
If your snippet of code already does what you want, then moving to a custom pipe is pretty straight forward. You just need to bind your array of decimal and use a pipe that converts it exactly like you do now. Something like:

Pipe:

import { Pipe, PipeTransform } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';
@Pipe({
  name: 'base64'
})
export class Base64Pipe implements PipeTransform {
  constructor(private sanitizer: DomSanitizer){}

  transform(value: any,){
    let imgIn="";
    for (var k = 0; k < value.length; k++) {
        var convert = String.fromCharCode(value[k]); // convert into base64
        imgIn += convert;
      }
      let base64Url =this.sanitizer.bypassSecurityTrustResourceUrl('data:image/png;base64,' + imgIn);
      return base64Url;
  }
}

And you'd use it like so: [src]="yourDecimalCodeArray | base64"

Here's a Stackblitz to illustrate.

Keep in mind that using this.sanitizer.bypassSecurityTrustResourceUrl mean you have to bind safely (Safe value must use [property]=binding after bypass security with DomSanitizer).

Hope this helps.


问:
How to make search based on pickup date and return date?
In the car page,i already input all the data into mysql database(car table).So i want to ease the user to find the car that available on pickup date and return date.So,I made search pickup date and return date in search page.But the error is "could not be execute".

This is using mysql and php.

car.php

```<code></body>
        <table align='center' width='40%' border='0' cellpadding='0' cellspacing='0'>
            <tr>
                <form action="search.php" method="post" enctype="multipart/form-data">
                <td><input type="date" name="Pickup_date" placeholder="Pickup_date" style='height:38px' required /></td>
                <td><input type="date" name="Return_date" placeholder="Return_date" style='height:38px' required    /></td>
                <td><input type="submit" name="submitbook" value="Search" style='background-color: blue; border: none; color: white; padding: 10px 10px; text-align: center; text-decoration: none; display: inline-block; font-size: 14px;'/></td>
    </div>
                </form>
            </table>

 <?php

 $link = mysqli_connect("localhost", "root", "", "online_car_rental");

 // Check connection
 if($link === false){
  die("ERROR: Could not connect. " . mysqli_connect_error());
}

 // Attempt select query execution
 $sql = "SELECT * FROM car";
 if($result = mysqli_query($link, $sql)){
 if(mysqli_num_rows($result) > 0){
 echo "<table>";
echo "<tr>";
    echo "<th>Id</th>";
    echo "<th>Name</th>";
    echo "<th>Price(RM)</th>";
    echo "<th>Colour</th>";
    echo "<th>Mode</th>";
    echo "<th>Image</th>";
    echo "<th>Status</th>";
    echo "<th>Add to Booking</th>";
    echo "</tr>";

 while($row = mysqli_fetch_array($result)){
 echo "<tr>";
    echo "<td>" . $row['car_id'] . "</td>";
    echo "<td>" . $row['car_name'] . "</td>";
    echo "<td>" . $row['car_price'] . "</td>";
    echo "<td>" . $row['car_colour'] . "</td>";
    echo "<td>" . $row['car_mode'] . "</td>";
    echo "<td><img src='" . $row['car_image'] . "' height='100'
    width='100'></td>";
    echo "<td>" . $row['car_status'] . "</td>";
    echo '<input type="hidden" name="pickup_date"
  value="'.$pickup_date.'">';
    echo '<input type="hidden" name="return_date"
  value="'.$return_date.'">';
    echo "<td><button onclick=\"booking_car('" . $row['car_id'] .
    "')\">Book</button>
    </td>";

  echo "</tr>";
}
    echo "</table>";
    // Free result set
    mysqli_free_result($result);
} else{
    echo "No records matching your query were found.";
}
 } else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
 }

 mysqli_close($link);
?>

 </html>
</code>```

search.php

```<code> <?php

 $link = mysqli_connect("localhost", "root", "", "online_car_rental");

 if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}

$search=$_GET['s'];
$query="SELECT * FROM car WHERE date BETWEEN 'pickup_date' AND
 'return_date'";
if($result = mysqli_query($link, $sql)){
if(mysqli_num_rows($result) > 0){
    echo "<table>";
        echo "<tr>";
            echo "<th>Id</th>";
            echo "<th>Name</th>";
            echo "<th>Price(RM)</th>";
            echo "<th>Colour</th>";
            echo "<th>Mode</th>";
            echo "<th>Image</th>";
            echo "<th>Status</th>";
            echo "<th>Add to Booking</th>";

        echo "</tr>";
    while($row = mysqli_fetch_array($result)){
        echo "<tr>";
            echo "<td>" . $row['car_id'] . "</td>";
            echo "<td>" . $row['car_name'] . "</td>";
            echo "<td>" . $row['car_price'] . "</td>";
            echo "<td>" . $row['car_colour'] . "</td>";
            echo "<td>" . $row['car_mode'] . "</td>";
            echo "<td><img src='" . $row['car_image'] . "' height='100' width='100'></td>";
            echo "<td>" . $row['car_status'] . "</td>";
            echo "<td>" . $row['pickup_date'] . "</td>";
            echo "<td>" . $row['return_date'] . "</td>";
            echo "<td><button onclick=\"booking_car('" . $row['car_id'] .
    "')\">Book</button>

    </td>";

        echo "</tr>";
    }
    echo "</table>";
    // Free result set
    mysqli_free_result($result);
} else{
    echo "No records matching your query were found.";
}
 } else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}

mysqli_close($link);
?>

</html>
</code>```

i expect the output is based on pickup_date and return_date.But the output is "ERROR:Could not able to execute".

答:
Without knowing your schema, it's difficult to provide a detailed solution, but an example of a plausible query might be as follows:</p>

```<code>"
SELECT c.olumns
     , y.ou
     , a.ctually
     , w.ant
  FROM car c
 WHERE pickup_date < :return_date
   AND return_date >= :pickup_date
 ORDER
    BY pickup_date
     , car_id;
"
</code>```

Body:
In the car page,i already input all the data into mysql database(car table).So i want to ease the user to find the car that available on pickup date and return date.So,I made search pickup date and return date in search page.But the error is "could not be execute".

This is using mysql and php.

car.php

                <form action="search.php" method="post" enctype="multipart/form-data">
                <input type="date" name="Pickup_date" placeholder="Pickup_date" style='height:38px' required />
                <input type="date" name="Return_date" placeholder="Return_date" style='height:38px' required    />
                <input type="submit" name="submitbook" value="Search" style='background-color: blue; border: none; color: white; padding: 10px 10px; text-align: center; text-decoration: none; display: inline-block; font-size: 14px;'/>

                </form>

 <?php

 $link = mysqli_connect("localhost", "root", "", "online_car_rental");

 // Check connection
 if($link === false){
  die("ERROR: Could not connect. " . mysqli_connect_error());
}

 // Attempt select query execution
 $sql = "SELECT * FROM car";
 if($result = mysqli_query($link, $sql)){
 if(mysqli_num_rows($result) > 0){
 echo "
";
echo "
";
    echo "Id	";
    echo "Name	";
    echo "Price(RM)	";
    echo "Colour	";
    echo "Mode	";
    echo "Image	";
    echo "Status	";
    echo "Add to Booking	";
    echo "
";

 while($row = mysqli_fetch_array($result)){
 echo "
";
    echo "" . $row['car_id'] . "	";
    echo "" . $row['car_name'] . "	";
    echo "" . $row['car_price'] . "	";
    echo "" . $row['car_colour'] . "	";
    echo "" . $row['car_mode'] . "	";
    echo "	";
    echo "" . $row['car_status'] . "	";
    echo '<input type="hidden" name="pickup_date"
  value="'.$pickup_date.'">';
    echo '<input type="hidden" name="return_date"
  value="'.$return_date.'">';
    echo "<button onclick=\"booking_car('" . $row['car_id'] .
    "')\">Book</button>
    	";

  echo "
";
}
    echo "
";
    // Free result set
    mysqli_free_result($result);
} else{
    echo "No records matching your query were found.";
}
 } else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
 }

 mysqli_close($link);
?>

search.php

 <?php

 $link = mysqli_connect("localhost", "root", "", "online_car_rental");

 if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}

$search=$_GET['s'];
$query="SELECT * FROM car WHERE date BETWEEN 'pickup_date' AND
 'return_date'";
if($result = mysqli_query($link, $sql)){
if(mysqli_num_rows($result) > 0){
    echo "
";
        echo "
";
            echo "Id	";
            echo "Name	";
            echo "Price(RM)	";
            echo "Colour	";
            echo "Mode	";
            echo "Image	";
            echo "Status	";
            echo "Add to Booking	";

        echo "
";
    while($row = mysqli_fetch_array($result)){
        echo "
";
            echo "" . $row['car_id'] . "	";
            echo "" . $row['car_name'] . "	";
            echo "" . $row['car_price'] . "	";
            echo "" . $row['car_colour'] . "	";
            echo "" . $row['car_mode'] . "	";
            echo "	";
            echo "" . $row['car_status'] . "	";
            echo "" . $row['pickup_date'] . "	";
            echo "" . $row['return_date'] . "	";
            echo "<button onclick=\"booking_car('" . $row['car_id'] .
    "')\">Book</button>

    	";

        echo "
";
    }
    echo "
";
    // Free result set
    mysqli_free_result($result);
} else{
    echo "No records matching your query were found.";
}
 } else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}

mysqli_close($link);
?>

i expect the output is based on pickup_date and return_date.But the output is "ERROR:Could not able to execute".

Body:
Without knowing your schema, it's difficult to provide a detailed solution, but an example of a plausible query might be as follows:

"
SELECT c.olumns
     , y.ou
     , a.ctually
     , w.ant
  FROM car c
 WHERE pickup_date < :return_date
   AND return_date >= :pickup_date
 ORDER
    BY pickup_date
     , car_id;
"


问:
Regex to find words with specific character
How to find all words which contain a specific letter in it?

For example, if my string is

```<code>This is a Station called South Yarra
</code>```

then I want to extract all words with the letter 'a' in them. The matches will be

```<code>"a", "Station", "called", "Yarra"
</code>```

So far I have tried

```<code>Regex regex = new Regex(@"\w[a]\w");

Regex regex = new Regex(@"\s[a*]\s");
</code>```

答:
Try with below regular expression</p>

```<code>Regex regex = new Regex(@"[^\s]*[a][^\s]*");
</code>```

Body:
How to find all words which contain a specific letter in it?

For example, if my string is

This is a Station called South Yarra

then I want to extract all words with the letter 'a' in them. The matches will be

"a", "Station", "called", "Yarra"

So far I have tried

Regex regex = new Regex(@"\w[a]\w");

Regex regex = new Regex(@"\s[a*]\s");

Body:
Try with below regular expression

Regex regex = new Regex(@"[^\s]*[a][^\s]*");


问:
Using React.memo with hooks for controlled inputs
I'm providing some form functionality from a custom React hook. This hook has some functionality similar to Formik (but this is really basic stuff).

```<code>function useFormValidation(initialState, validate) {
  const [values, setValues] = React.useState(initialState);
  const [errors, setErrors] = React.useState({});
  const [isSubmitting, setSubmitting] = React.useState(false);

  React.useEffect(() => {
    if (isSubmitting) {
      const noErrors = Object.keys(errors).length === 0;
      if (noErrors) {
        console.log("authenticated!", values.email, values.password);
        setSubmitting(false);
      } else {
        setSubmitting(false);
      }
    }
  }, [errors]);

  function handleChange(event) {
    setValues({
      ...values,
      [event.target.name]: event.target.value
    });
  }

  function handleBlur() {
    const validationErrors = validate(values);
    setErrors(validationErrors);
  }

  function handleSubmit(event) {
    event.preventDefault();
    const validationErrors = validate(values);
    setErrors(validationErrors);
    setSubmitting(true);
  }

  return {
    handleSubmit,
    handleChange,
    handleBlur,
    values,
    errors,
    isSubmitting
  };
}

</code>```

The form is the following:

```<code>function Register() {
  const {
    handleSubmit,

    handleChange,
    handleBlur,
    values,
    errors,
    isSubmitting
  } = useFormValidation(INITIAL_STATE, validateAuth);
  // const [email, setEmail] = React.useState("");
  // const [password, setPassword] = React.useState("");

  return (
    <div className="container">
      <h1>Register Here</h1>
      <form onSubmit={handleSubmit}>
        <Input
          handleChange={handleChange}
          handleBlur={handleBlur}
          name="email"
          value={values.email}
          className={errors.email && "error-input"}
          autoComplete="off"
          placeholder="Your email address"
        />
        {errors.email && <p className="error-text">{errors.email}</p>}
        <Input
          handleChange={handleChange}
          handleBlur={handleBlur}
          value={values.password}
          className={errors.password && "error-input"}
          name="password"
          // type="password"
          placeholder="Choose a safe password"
        />
        {errors.password && <p className="error-text">{errors.password}</p>}
        <div>
          <button disabled={isSubmitting} type="submit">
            Submit
          </button>
        </div>
      </form>
    </div>
  );
}
</code>```

And the memoized component is the next:

```<code>function Input({
  handleChange,
  handleBlur,
  name,
  value,
  className,
  autoComplete,
  placeholder,
  type
}) {

  return (
    <input
      onChange={handleChange}
      onBlur={handleBlur}
      name={name}
      value={value}
      className={className}
      autoComplete={autoComplete}
      placeholder={placeholder}
      type={type}
    />
  );
}

function areEqual(prevProps, nextProps) {
  console.log(`
    prevProps: ${JSON.stringify(prevProps.value)}
    nextProps: ${JSON.stringify(nextProps.value)}
  `);
  return prevProps.value === nextProps.value;
}
const useMemo = (component, propsAreEqual) => {
  return memo(component, propsAreEqual);
};
export default useMemo(Input, areEqual);
</code>```

I enter some text into the first input. Then, when I switch to the second Input and start typing, the first input loses the value. It's like the form is not rendering the LAST MEMOIZED input, but prior versions instead.
I'm a React beginner and can't figure out the solution. Any help please?

答:
Your areEqual method translates to

Re-render my Input ONLY when the value changes.

But in reality, your handleChange function from the hook is also changing. Also, you use the same handleChange for both the inputs. So, the Input "remembers" only the handleChange from the last time value had changed and since handleChange is tracking values via closure, it in-turn "remembers" the values when it was created.

Changing your areEqual method (or completely omitting it) to verify a change in handleChange, will solve your problem.

```<code>function areEqual(prevProps, nextProps) {
  return (
    prevProps.value === nextProps.value &&
    prevProps.handleChange === nextProps.handleChange
  );
}
</code>```

A codesandbox of the solution here

Body:
I'm providing some form functionality from a custom React hook. This hook has some functionality similar to Formik (but this is really basic stuff).

function useFormValidation(initialState, validate) {
  const [values, setValues] = React.useState(initialState);
  const [errors, setErrors] = React.useState({});
  const [isSubmitting, setSubmitting] = React.useState(false);

  React.useEffect(() => {
    if (isSubmitting) {
      const noErrors = Object.keys(errors).length === 0;
      if (noErrors) {
        console.log("authenticated!", values.email, values.password);
        setSubmitting(false);
      } else {
        setSubmitting(false);
      }
    }
  }, [errors]);

  function handleChange(event) {
    setValues({
      ...values,
      [event.target.name]: event.target.value
    });
  }

  function handleBlur() {
    const validationErrors = validate(values);
    setErrors(validationErrors);
  }

  function handleSubmit(event) {
    event.preventDefault();
    const validationErrors = validate(values);
    setErrors(validationErrors);
    setSubmitting(true);
  }

  return {
    handleSubmit,
    handleChange,
    handleBlur,
    values,
    errors,
    isSubmitting
  };
}

The form is the following:

function Register() {
  const {
    handleSubmit,

    handleChange,
    handleBlur,
    values,
    errors,
    isSubmitting
  } = useFormValidation(INITIAL_STATE, validateAuth);
  // const [email, setEmail] = React.useState("");
  // const [password, setPassword] = React.useState("");

  return (

Register Here

      <form onSubmit={handleSubmit}>
        <Input
          handleChange={handleChange}
          handleBlur={handleBlur}
          name="email"
          value={values.email}
          className={errors.email && "error-input"}
          autoComplete="off"
          placeholder="Your email address"
        />
        {errors.email &&
{errors.email}
}
        <Input
          handleChange={handleChange}
          handleBlur={handleBlur}
          value={values.password}
          className={errors.password && "error-input"}
          name="password"
          // type="password"
          placeholder="Choose a safe password"
        />
        {errors.password &&
{errors.password}
}

          <button disabled={isSubmitting} type="submit">
            Submit
          </button>

      </form>

  );
}

And the memoized component is the next:

function Input({
  handleChange,
  handleBlur,
  name,
  value,
  className,
  autoComplete,
  placeholder,
  type
}) {

  return (
    <input
      onChange={handleChange}
      onBlur={handleBlur}
      name={name}
      value={value}
      className={className}
      autoComplete={autoComplete}
      placeholder={placeholder}
      type={type}
    />
  );
}

function areEqual(prevProps, nextProps) {
  console.log(`
    prevProps: ${JSON.stringify(prevProps.value)}
    nextProps: ${JSON.stringify(nextProps.value)}
  `);
  return prevProps.value === nextProps.value;
}
const useMemo = (component, propsAreEqual) => {
  return memo(component, propsAreEqual);
};
export default useMemo(Input, areEqual);

I enter some text into the first input. Then, when I switch to the second Input and start typing, the first input loses the value. It's like the form is not rendering the LAST MEMOIZED input, but prior versions instead.
I'm a React beginner and can't figure out the solution. Any help please?

Body:
Your areEqual method translates to

Re-render my Input ONLY when the value changes.

But in reality, your handleChange function from the hook is also changing. Also, you use the same handleChange for both the inputs. So, the Input "remembers" only the handleChange from the last time value had changed and since handleChange is tracking values via closure, it in-turn "remembers" the values when it was created.

Changing your areEqual method (or completely omitting it) to verify a change in handleChange, will solve your problem.

function areEqual(prevProps, nextProps) {
  return (
    prevProps.value === nextProps.value &&
    prevProps.handleChange === nextProps.handleChange
  );
}

A codesandbox of the solution here