问:
Prestashop - Add additional fields on product combination
I'm trying to add additional fields on my product combinations in order to have custom meta titles for the combinations.
So I created this module:

My module definition:

class CombinationCustomFields extends Module
{

    public function __construct()
    {
        $this->name = 'combinationcustomfields';
        $this->tab = 'administration';
        $this->author = '';
        $this->version = '1.0';
        $this->need_instance = 0;
        $this->bootstrap = true;

        parent::__construct();

        $this->displayName = $this->l('Combination Custom Fields');
        $this->description = $this->l('Add additional fields on combinations');
        $this->ps_versions_compliancy = array('min' => '1.7.1', 'max' => _PS_VERSION_);
    }

    public function install()
    {
        if (!parent::install() || !$this->_installSql()
            || !$this->registerHook('displayAdminProductsCombinationBottom')
            || !$this->registerHook('actionAttributeCombinationSave')
        ) {
            return false;
        }

        return true;
    }

    public function uninstall()
    {
        return parent::uninstall() && $this->_unInstallSql();
    }

    /**
     * Add database fields
     * @return boolean
     */
    protected function _installSql()
    {
        $sqlInstall = "ALTER TABLE " . _DB_PREFIX_ . "product_attribute "
            . "ADD meta_title_fr VARCHAR(255) NULL, "
            . "ADD meta_title_en VARCHAR(255) NULL;";

        $returnSql = Db::getInstance()->execute($sqlInstall);

        return $returnSql;
    }

    /**
     * Remove database fields
     * @return boolean
     */
    protected function _unInstallSql()
    {
        $sqlInstall = "ALTER TABLE " . _DB_PREFIX_ . "product_attribute "
            . "DROP meta_title_fr, "
            . "DROP meta_title_en";

        $returnSql = Db::getInstance()->execute($sqlInstall);

        return $returnSql;
    }

    public function hookDisplayAdminProductsCombinationBottom($params)
    {
        $combination = new Combination($params['id_product_attribute']);
        $this->context->smarty->assign(array(
                'id_product_attribute' => $params['id_product_attribute'],
                'meta_title_fr' => $combination->meta_title_fr,
                'meta_title_en' => $combination->meta_title_en,
            )
        );

        return $this->display(__FILE__, 'views/templates/hook/combinationfields.tpl');
    }

    public function hookActionAttributeCombinationSave($params)
    {
        $combination = new Combination($params['id_product_attribute']);
        $this->context->smarty->assign(array(
                'id_product_attribute' => $params['id_product_attribute'],
                'meta_title_fr' => $combination->meta_title_fr,
                'meta_title_en' => $combination->meta_title_en,
            )
        );

        $combination->meta_title_fr = Tools::getValue('meta_title_fr');
        $combination->meta_title_en = Tools::getValue('meta_title_en');

        $combination->save();

        return $this->display(__FILE__, 'views/templates/hook/combinationfields.tpl');

    }
}
```
<p><strong>My HTML for the admin hook:</strong></p>
<pre class="lang-html prettyprint-override"><code><div class="m-b-1 m-t-1">
    <h2>{l s='Combination Custom Fields' mod='combinationcustomfields'}</h2>
    <fieldset class="form-group">
        <div class="col-lg-12 col-xl-4">
            <label class="form-control-label" for="combination_{$id_product_attribute}_attribute_meta_title_fr">{l s='Meta title FR' mod='combinationcustomfields'}</label>
            <input class="form-control" name="combination_{$id_product_attribute}[attribute_meta_title_fr]" id="combination_{$id_product_attribute}_attribute_meta_title_fr" type="text" value="{if $meta_title_fr != ''}{$meta_title_fr}{/if}">
            <br />
        </div>
        <div class="col-lg-12 col-xl-4">
            <label class="form-control-label" for="combination_{$id_product_attribute}_attribute_meta_title_en">{l s='Meta title EN' mod='cmp_combination_customfields'}</label>
            <input class="form-control" name="combination_{$id_product_attribute}[attribute_meta_title_en]" id="combination_{$id_product_attribute}_attribute_meta_title_en" type="text" value="{if $meta_title_en != ''}{$meta_title_en}{/if}">
            <br />
        </div>
    </fieldset>
    <div class="clearfix"></div>
</div>
</code>```

My override of the combination class:

class Combination extends CombinationCore
{
    public $meta_title_fr;
    public $meta_title_en;
    /**
     * @see ObjectModel::$definition
     */
    public static $definition = [
        'table' => 'product_attribute',
        'primary' => 'id_product_attribute',
        'fields' => [
            'id_product' => ['type' => self::TYPE_INT, 'shop' => 'both', 'validate' => 'isUnsignedId', 'required' => true],
            'location' => ['type' => self::TYPE_STRING, 'validate' => 'isGenericName', 'size' => 64],
            'ean13' => ['type' => self::TYPE_STRING, 'validate' => 'isEan13', 'size' => 13],
            'isbn' => ['type' => self::TYPE_STRING, 'validate' => 'isIsbn', 'size' => 32],
            'upc' => ['type' => self::TYPE_STRING, 'validate' => 'isUpc', 'size' => 12],
            'mpn' => ['type' => self::TYPE_STRING, 'validate' => 'isMpn', 'size' => 40],
            'quantity' => ['type' => self::TYPE_INT, 'validate' => 'isInt', 'size' => 10],
            'reference' => ['type' => self::TYPE_STRING, 'size' => 64],
            'supplier_reference' => ['type' => self::TYPE_STRING, 'size' => 64],
            'meta_title_fr' => ['type' => self::TYPE_STRING, 'size' => 64],
            'meta_title_en' => ['type' => self::TYPE_STRING, 'size' => 64],

            /* Shop fields */
            'wholesale_price' => ['type' => self::TYPE_FLOAT, 'shop' => true, 'validate' => 'isPrice', 'size' => 27],
            'price' => ['type' => self::TYPE_FLOAT, 'shop' => true, 'validate' => 'isNegativePrice', 'size' => 20],
            'ecotax' => ['type' => self::TYPE_FLOAT, 'shop' => true, 'validate' => 'isPrice', 'size' => 20],
            'weight' => ['type' => self::TYPE_FLOAT, 'shop' => true, 'validate' => 'isFloat'],
            'unit_price_impact' => ['type' => self::TYPE_FLOAT, 'shop' => true, 'validate' => 'isNegativePrice', 'size' => 20],
            'minimal_quantity' => ['type' => self::TYPE_INT, 'shop' => true, 'validate' => 'isUnsignedId', 'required' => true],
            'low_stock_threshold' => ['type' => self::TYPE_INT, 'shop' => true, 'allow_null' => true, 'validate' => 'isInt'],
            'low_stock_alert' => ['type' => self::TYPE_BOOL, 'shop' => true, 'validate' => 'isBool'],
            'default_on' => ['type' => self::TYPE_BOOL, 'allow_null' => true, 'shop' => true, 'validate' => 'isBool'],
            'available_date' => ['type' => self::TYPE_DATE, 'shop' => true, 'validate' => 'isDateFormat'],
        ],
    ];

}
```

But when I save the product, the fields are in the request:

But I have a 400 Error:

Any idea of my mistake here ?

All the best and thanks in advance for you help :)

答:
I would do so:

HTML:
Change all attributes combination_ to custom_

```<code><div class="m-b-1 m-t-1">
<h2>{l s='Combination Custom Fields' mod='combinationcustomfields'}</h2>
<fieldset class="form-group">
    <div class="col-lg-12 col-xl-4">
        <label class="form-control-label" for="custom_{$id_product_attribute}_attribute_meta_title_fr">{l s='Meta title FR' mod='combinationcustomfields'}</label>
        <input class="form-control" name="custom_{$id_product_attribute}[attribute_meta_title_fr]" id="custom_{$id_product_attribute}_attribute_meta_title_fr" type="text" value="{if $meta_title_fr != ''}{$meta_title_fr}{/if}">
        <br />
    </div>
    <div class="col-lg-12 col-xl-4">
        <label class="form-control-label" for="custom_{$id_product_attribute}_attribute_meta_title_en">{l s='Meta title EN' mod='cmp_combination_customfields'}</label>
        <input class="form-control" name="custom_{$id_product_attribute}[attribute_meta_title_en]" id="custom_{$id_product_attribute}_attribute_meta_title_en" type="text" value="{if $meta_title_en != ''}{$meta_title_en}{/if}">
        <br />
    </div>
</fieldset>
<div class="clearfix"></div>
</code>```

Next step:

```<code>public function hookActionAttributeCombinationSave($params)
{
    $id_product_attribute = $params['id_product_attribute'];
    $custom = $_POST['custom_' . $id_product_attribute];

    ....
}
</code>```

Body:
I'm trying to add additional fields on my product combinations in order to have custom meta titles for the combinations.
So I created this module:

My module definition:

class CombinationCustomFields extends Module
{

    public function __construct()
    {
        $this->name = 'combinationcustomfields';
        $this->tab = 'administration';
        $this->author = '';
        $this->version = '1.0';
        $this->need_instance = 0;
        $this->bootstrap = true;

        parent::__construct();

        $this->displayName = $this->l('Combination Custom Fields');
        $this->description = $this->l('Add additional fields on combinations');
        $this->ps_versions_compliancy = array('min' => '1.7.1', 'max' => _PS_VERSION_);
    }

    public function install()
    {
        if (!parent::install() || !$this->_installSql()
            || !$this->registerHook('displayAdminProductsCombinationBottom')
            || !$this->registerHook('actionAttributeCombinationSave')
        ) {
            return false;
        }

        return true;
    }

    public function uninstall()
    {
        return parent::uninstall() && $this->_unInstallSql();
    }

    /**
     * Add database fields
     * @return boolean
     */
    protected function _installSql()
    {
        $sqlInstall = "ALTER TABLE " . _DB_PREFIX_ . "product_attribute "
            . "ADD meta_title_fr VARCHAR(255) NULL, "
            . "ADD meta_title_en VARCHAR(255) NULL;";

        $returnSql = Db::getInstance()->execute($sqlInstall);

        return $returnSql;
    }

    /**
     * Remove database fields
     * @return boolean
     */
    protected function _unInstallSql()
    {
        $sqlInstall = "ALTER TABLE " . _DB_PREFIX_ . "product_attribute "
            . "DROP meta_title_fr, "
            . "DROP meta_title_en";

        $returnSql = Db::getInstance()->execute($sqlInstall);

        return $returnSql;
    }

    public function hookDisplayAdminProductsCombinationBottom($params)
    {
        $combination = new Combination($params['id_product_attribute']);
        $this->context->smarty->assign(array(
                'id_product_attribute' => $params['id_product_attribute'],
                'meta_title_fr' => $combination->meta_title_fr,
                'meta_title_en' => $combination->meta_title_en,
            )
        );

        return $this->display(__FILE__, 'views/templates/hook/combinationfields.tpl');
    }

    public function hookActionAttributeCombinationSave($params)
    {
        $combination = new Combination($params['id_product_attribute']);
        $this->context->smarty->assign(array(
                'id_product_attribute' => $params['id_product_attribute'],
                'meta_title_fr' => $combination->meta_title_fr,
                'meta_title_en' => $combination->meta_title_en,
            )
        );

        $combination->meta_title_fr = Tools::getValue('meta_title_fr');
        $combination->meta_title_en = Tools::getValue('meta_title_en');

        $combination->save();

        return $this->display(__FILE__, 'views/templates/hook/combinationfields.tpl');

    }
}

My HTML for the admin hook:

{l s='Combination Custom Fields' mod='combinationcustomfields'}

    <fieldset class="form-group">

            {l s='Meta title FR' mod='combinationcustomfields'}
            <input class="form-control" name="combination_{$id_product_attribute}[attribute_meta_title_fr]" id="combination_{$id_product_attribute}_attribute_meta_title_fr" type="text" value="{if $meta_title_fr != ''}{$meta_title_fr}{/if}">

            {l s='Meta title EN' mod='cmp_combination_customfields'}
            <input class="form-control" name="combination_{$id_product_attribute}[attribute_meta_title_en]" id="combination_{$id_product_attribute}_attribute_meta_title_en" type="text" value="{if $meta_title_en != ''}{$meta_title_en}{/if}">

    </fieldset>

My override of the combination class:

class Combination extends CombinationCore
{
    public $meta_title_fr;
    public $meta_title_en;
    /**
     * @see ObjectModel::$definition
     */
    public static $definition = [
        'table' => 'product_attribute',
        'primary' => 'id_product_attribute',
        'fields' => [
            'id_product' => ['type' => self::TYPE_INT, 'shop' => 'both', 'validate' => 'isUnsignedId', 'required' => true],
            'location' => ['type' => self::TYPE_STRING, 'validate' => 'isGenericName', 'size' => 64],
            'ean13' => ['type' => self::TYPE_STRING, 'validate' => 'isEan13', 'size' => 13],
            'isbn' => ['type' => self::TYPE_STRING, 'validate' => 'isIsbn', 'size' => 32],
            'upc' => ['type' => self::TYPE_STRING, 'validate' => 'isUpc', 'size' => 12],
            'mpn' => ['type' => self::TYPE_STRING, 'validate' => 'isMpn', 'size' => 40],
            'quantity' => ['type' => self::TYPE_INT, 'validate' => 'isInt', 'size' => 10],
            'reference' => ['type' => self::TYPE_STRING, 'size' => 64],
            'supplier_reference' => ['type' => self::TYPE_STRING, 'size' => 64],
            'meta_title_fr' => ['type' => self::TYPE_STRING, 'size' => 64],
            'meta_title_en' => ['type' => self::TYPE_STRING, 'size' => 64],

            /* Shop fields */
            'wholesale_price' => ['type' => self::TYPE_FLOAT, 'shop' => true, 'validate' => 'isPrice', 'size' => 27],
            'price' => ['type' => self::TYPE_FLOAT, 'shop' => true, 'validate' => 'isNegativePrice', 'size' => 20],
            'ecotax' => ['type' => self::TYPE_FLOAT, 'shop' => true, 'validate' => 'isPrice', 'size' => 20],
            'weight' => ['type' => self::TYPE_FLOAT, 'shop' => true, 'validate' => 'isFloat'],
            'unit_price_impact' => ['type' => self::TYPE_FLOAT, 'shop' => true, 'validate' => 'isNegativePrice', 'size' => 20],
            'minimal_quantity' => ['type' => self::TYPE_INT, 'shop' => true, 'validate' => 'isUnsignedId', 'required' => true],
            'low_stock_threshold' => ['type' => self::TYPE_INT, 'shop' => true, 'allow_null' => true, 'validate' => 'isInt'],
            'low_stock_alert' => ['type' => self::TYPE_BOOL, 'shop' => true, 'validate' => 'isBool'],
            'default_on' => ['type' => self::TYPE_BOOL, 'allow_null' => true, 'shop' => true, 'validate' => 'isBool'],
            'available_date' => ['type' => self::TYPE_DATE, 'shop' => true, 'validate' => 'isDateFormat'],
        ],
    ];

}

But when I save the product, the fields are in the request:

But I have a 400 Error:

Any idea of my mistake here ?

All the best and thanks in advance for you help :)

Body:
I would do so:

HTML:
Change all attributes combination_ to custom_

<div class="m-b-1 m-t-1">
<h2>{l s='Combination Custom Fields' mod='combinationcustomfields'}</h2>
<fieldset class="form-group">
    <div class="col-lg-12 col-xl-4">
        <label class="form-control-label" for="custom_{$id_product_attribute}_attribute_meta_title_fr">{l s='Meta title FR' mod='combinationcustomfields'}</label>
        <input class="form-control" name="custom_{$id_product_attribute}[attribute_meta_title_fr]" id="custom_{$id_product_attribute}_attribute_meta_title_fr" type="text" value="{if $meta_title_fr != ''}{$meta_title_fr}{/if}">
        <br />
    </div>
    <div class="col-lg-12 col-xl-4">
        <label class="form-control-label" for="custom_{$id_product_attribute}_attribute_meta_title_en">{l s='Meta title EN' mod='cmp_combination_customfields'}</label>
        <input class="form-control" name="custom_{$id_product_attribute}[attribute_meta_title_en]" id="custom_{$id_product_attribute}_attribute_meta_title_en" type="text" value="{if $meta_title_en != ''}{$meta_title_en}{/if}">
        <br />
    </div>
</fieldset>
<div class="clearfix"></div>

Next step:

public function hookActionAttributeCombinationSave($params)
{
    $id_product_attribute = $params['id_product_attribute'];
    $custom = $_POST['custom_' . $id_product_attribute];

    ....
}


来源: stackexchange

问:
Parsing specific column's using inputs
I've been trying to wrap my head around a method of parsing a text file and specifying the specific columns you want. So for example I ask them to input what columns they want to parse out of the text file.

```<code>Names.txt
Joe,Smith,19,15,17
Jake,Jones,19,15,17
Bob,Martin,19,15,17
</code>```

So the person will input the txt file and then inputs that they want Column 0 and 2 it will give them a result of

```<code>Joe,19
Jake,19
Bob,19
</code>```

I know I can do the .split()[0] but I dont want to hard code it I want it to work off the input. Im pretty sure its easy but for some reason I just cant get my head around the way to do it.

To make it a bit more in depth I want to make a program that you input a txt file and it asks you for what sections you would like then it prints out the seconds you wanted.

InputFileName = input("Please enter the name of file you would like to parse: ")
ParseSelection = input("Please enter the section's you want to parse: ")
```
<p>and then from that it will open the txt file see that the user asked for Section 0 and 2 and just print them out as "Section 0 | Section 2"</p>
```Names.txt
Joe,Smith,19,15,17
Jake,Jones,19,15,17
Bob,Martin,19,15,17
```
<p>open Names.txt it see that the person asked for Section 0 and 2 So it prints out</p>
```Joe | 19
Jake | 19
Bob | 19
```

答:
You could use the following:

```<code>columns = list('02')
</code>```

where the input, '02', would indicate the user wants columns 0 and 2.
Then you iterate over the file's lines and columns:

```<code>for lines in file:
    for column in columns:
        print(lines[int(column)], end=',')
    print()
</code>```

With your example, that'd return

```<code>Joe,19,
Jake,19,
Bob,19,
</code>```

Also, if you're wondering how to read the input file, you may want to use the csv library.

ContentLicense: CC BY-SA 4.0

Title: Parsing specific column's using inputs

Body:
I've been trying to wrap my head around a method of parsing a text file and specifying the specific columns you want. So for example I ask them to input what columns they want to parse out of the text file.

Names.txt
Joe,Smith,19,15,17
Jake,Jones,19,15,17
Bob,Martin,19,15,17

So the person will input the txt file and then inputs that they want Column 0 and 2 it will give them a result of

Joe,19
Jake,19
Bob,19

I know I can do the .split()[0] but I dont want to hard code it I want it to work off the input. Im pretty sure its easy but for some reason I just cant get my head around the way to do it.

To make it a bit more in depth I want to make a program that you input a txt file and it asks you for what sections you would like then it prints out the seconds you wanted.

InputFileName = input("Please enter the name of file you would like to parse: ")
ParseSelection = input("Please enter the section's you want to parse: ")

and then from that it will open the txt file see that the user asked for Section 0 and 2 and just print them out as "Section 0 | Section 2"

Names.txt
Joe,Smith,19,15,17
Jake,Jones,19,15,17
Bob,Martin,19,15,17

open Names.txt it see that the person asked for Section 0 and 2 So it prints out

Joe | 19
Jake | 19
Bob | 19

Body:
You could use the following:

columns = list('02')

where the input, '02', would indicate the user wants columns 0 and 2.
Then you iterate over the file's lines and columns:

for lines in file:
    for column in columns:
        print(lines[int(column)], end=',')
    print()

With your example, that'd return

Joe,19,
Jake,19,
Bob,19,

Also, if you're wondering how to read the input file, you may want to use the csv library.


问:
Vue 3: Setup Script, TS Problem: "An import declaration can only be used in a namespace or module."
when using in Vue 3 the setup script with typescript, I get an error in vscode saying:
"An import declaration can only be used in a namespace or module."

That happens for external libs and own vue components.

i. e.:

```<code><script setup lang="ts">
  // ...

  // ASSETS
  import SvgCircle from '@/assets/img/IconsSvg/SvgCircle.vue';

  // MODELS
  import { IApiParams } from '@/models/api/apiparams.interface
  //  import { EBp } from '@/models/enum/baseParams.enum';

  // LIBS
  import justSafeGet from 'just-safe-get';

  // ...
</script>
</code>```

All these are getting red lines in vscode. Others like import from vue or vue-router or own composables do not get red line.
I do not find something helpful to fix it.

Anybody understands that and has a clue?

答:
As a rule you should only import first.</p>
```<code><script setup lang="ts">
  import SvgCircle from '@/assets/img/IconsSvg/SvgCircle.vue'; // ASSETS
  import { EBp } from '@/models/enum/baseParams.enum'; // MODELS
  import justSafeGet from 'just-safe-get'; // LIBS
  ... // Any code here
</script>
</code>```

Body:
when using in Vue 3 the setup script with typescript, I get an error in vscode saying:
"An import declaration can only be used in a namespace or module."

That happens for external libs and own vue components.

i. e.:

All these are getting red lines in vscode. Others like import from vue or vue-router or own composables do not get red line.
I do not find something helpful to fix it.

Anybody understands that and has a clue?

Body:
As a rule you should only import first.

<script setup lang="ts">
  import SvgCircle from '@/assets/img/IconsSvg/SvgCircle.vue'; // ASSETS
  import { EBp } from '@/models/enum/baseParams.enum'; // MODELS
  import justSafeGet from 'just-safe-get'; // LIBS
  ... // Any code here
</script>


问:
How to redirect with match params in React Router v6?
I used to do this in react router v5:

```<code><Redirect exact from="/:org" to="/:org/users" />
</code>```

translating it into this doesn't work:

```<code><Route path="/:org" element={<Navigate replace to="/:org/users" />} />
</code>```

What is the correct way to perform this kind of a redirect?

UPD: To clarify – I don't have a separate route for /:org/users at the same routes level but I have /:org/* route that handles /:org/users and others:

```<code><Route path="/:org/*" element={<OrgPagesComponent />} />
</code>```

答:
Use relative navigation for the redirect.

```<code><Route path="/:org/*" element={<OrgPagesComponent />} />
<Route path="/:org" element={<Navigate to="users" replace />} />
</code>```

When the path matches exactly "/:org" the second Route will be matched and render the Navigate which will relatively navigate to "/:org/users" which is matched by the first Route on path "/:org/*".

Here is a running codesandbox demo.

Body:
I used to do this in react router v5:

<Redirect exact from="/:org" to="/:org/users" />

translating it into this doesn't work:

<Route path="/:org" element={<Navigate replace to="/:org/users" />} />

What is the correct way to perform this kind of a redirect?

UPD: To clarify – I don't have a separate route for /:org/users at the same routes level but I have /:org/* route that handles /:org/users and others:

<Route path="/:org/*" element={<OrgPagesComponent />} />

Body:
Use relative navigation for the redirect.

<Route path="/:org/*" element={<OrgPagesComponent />} />
<Route path="/:org" element={<Navigate to="users" replace />} />

When the path matches exactly "/:org" the second Route will be matched and render the Navigate which will relatively navigate to "/:org/users" which is matched by the first Route on path "/:org/*".

Here is a running codesandbox demo.


问:
XCode file paths point to nonexistent directories
Right now I'm running XCode 3.2.6. I'm working off of someone else's code, and when I open the project it around 150 files have the wrong path (even when set to "relative to enclosing group."

Instead of using /appname/folder the point to /../../Documents/appname/folder.

I'm aware that some other people have had similar issues with XCode 3.2 in the past, which is why I'm upgrading to Lion now so I can use 4.0. However, has anyone found a fix for this in 3.2?

Also, I was wondering if there was a file that held all of the paths so  I could run a script through it?

Thanks

答: You will notice that the .xcodeproj file itself is actually a Bundle (a.k.a. a directory).  If you cd to this directory in Terminal, you can use grep to figure out which files contain the paths using grep -r -i "path here".  These files are formatted in XML and some other similar format, so it should be pretty easy to use sed or something to fix some of the paths.  And of course, I ALWAYS suggest backing up any files before you autonomously replace stuff in them.

ContentLicense: CC BY-SA 3.0


问:
How to get a function name as a string?
How do I get a function's name as a string?</p>
```<code>def foo():
    pass

>>> name_of(foo)
"foo"
</code>```

答:
You can get a function's name as a string by using the special __name__ variable.

def my_function():
    pass

print(my_function.__name__) # prints "my_function"
```

OwnerDisplayName: Ingenutrix

Title: How to get a function name as a string?

Body:
How do I get a function's name as a string?

def foo():
    pass

>>> name_of(foo)
"foo"


问:
My custom django-admin command won't call celery task
I am trying to write a custom django-admin command that executes a celery task, however the task doesn't execute and django just hangs when I try.

```<code>from django.core.management.base import BaseCommand
from myapp.tasks import my_celery_task

class Command(BaseCommand):
    def handle(self, *args, **options):
        print "starting task"
        my_celery_task.delay()
        print "task has been sent"
</code>```

The output I receive when calling the command is:

```<code>starting task
</code>```

I never reach the "task has been sent" line. It just hangs. I'm not sure why the task isn't running. Celery tasks are called perfectly when called by a view.

答:
This seems to work for me with celery 5.1.2, but not if it is a shared_task

====== tasks.py

```<code>from celery import current_app
from celery.schedules import crontab
app = current_app._get_current_object()

@app.task
def my_celery_task():
    # Do something interesting
    return 0 # Return the result of this operation
</code>```

====== my_command.py

```<code>from accounts.tasks import my_celery_task
...
    def handle(self, *args, **options):
        self.stdout.write("Queing request")
        result = my_celery_task.delay()
        self.stdout.write("Waiting for task to end")
        updated = result.wait(timeout=120.0)

        self.stdout.write(f"Returned {updated}")
</code>```

And, if I put the task in the celery.py file I ended up with a deadlock which was a PITA to debug

Body:
I am trying to write a custom django-admin command that executes a celery task, however the task doesn't execute and django just hangs when I try.

from django.core.management.base import BaseCommand
from myapp.tasks import my_celery_task

class Command(BaseCommand):
    def handle(self, *args, **options):
        print "starting task"
        my_celery_task.delay()
        print "task has been sent"

The output I receive when calling the command is:

starting task

I never reach the "task has been sent" line. It just hangs. I'm not sure why the task isn't running. Celery tasks are called perfectly when called by a view.

Body:
This seems to work for me with celery 5.1.2, but not if it is a shared_task

====== tasks.py

from celery import current_app
from celery.schedules import crontab
app = current_app._get_current_object()

@app.task
def my_celery_task():
    # Do something interesting
    return 0 # Return the result of this operation

====== my_command.py

from accounts.tasks import my_celery_task
...
    def handle(self, *args, **options):
        self.stdout.write("Queing request")
        result = my_celery_task.delay()
        self.stdout.write("Waiting for task to end")
        updated = result.wait(timeout=120.0)

        self.stdout.write(f"Returned {updated}")

And, if I put the task in the celery.py file I ended up with a deadlock which was a PITA to debug


问:
trying to convert cartesian coordinates to polar coordinates but NOT WORKING
**this is what I have so far. I'm supposed to get the quadrant for (x,y), the radius, and the angle.  I don't have any errors but when i put 1 in for x and 1 in for y it gives me

```<code>quadrant:0.000000 radius:.785398 angle:0.0000000**
</code>```

If you see any errors please let me know. I would greatly appreciate it!

```<code>#include<stdio.h>
#include<math.h>

int get_quadrant(double, double);
double get_radius(double, double);
double get_angle(double, double);
void show_info(int, double, double);

int main() {
  double X, Y, rad, theta;
  int quad;
  printf("input the value for the x coordinate: \n");
  scanf("%f", &X);
  printf("input the value for the y coordinate: \n");
  scanf("%f", &Y);
  quad = get_quadrant(X, Y);
  rad = get_radius(X, Y);
  theta = get_angle(X, Y);
  show_info(quad, rad, theta);
  return 0;
}

int get_quadrant(double X, double Y) {
  int quadrant;
  if (X > 0 && Y > 0) {
    quadrant == 1;
    return quadrant;
  }

  else if (X < 0 && Y > 0) {
    quadrant == 2;
    return quadrant;
  }

  else if (X < 0 && Y < 0) {
    quadrant = 3;
    return quadrant;
  }

  else if (X > 0 && Y < 0) {
    quadrant = 4;
    return quadrant;
  }
}

double get_radius(double X, double Y) {
  double r;
  r = sqrt((X) * (X) + (Y) * (Y));
}

double get_angle(double X, double Y) {
  double angle;
  angle = atan(Y / X);
}

void show_info(int quad, double rad, double theta) {
  printf("quadrant: %f  radius:  %f    angle:  %f.\n", quad, rad, theta);
}
</code>```

答:
You actually are comparing values instead of assigning them in the get_quadrant functions, you can replace == by = in the first and second sections. Also, in the get_radius function, r is the squared value of the real radius.
Don't forget to add the return values of non-void functions

Body:
**this is what I have so far. I'm supposed to get the quadrant for (x,y), the radius, and the angle.  I don't have any errors but when i put 1 in for x and 1 in for y it gives me

quadrant:0.000000 radius:.785398 angle:0.0000000**

If you see any errors please let me know. I would greatly appreciate it!

#include<stdio.h>
#include<math.h>

int get_quadrant(double, double);
double get_radius(double, double);
double get_angle(double, double);
void show_info(int, double, double);

int main() {
  double X, Y, rad, theta;
  int quad;
  printf("input the value for the x coordinate: \n");
  scanf("%f", &X);
  printf("input the value for the y coordinate: \n");
  scanf("%f", &Y);
  quad = get_quadrant(X, Y);
  rad = get_radius(X, Y);
  theta = get_angle(X, Y);
  show_info(quad, rad, theta);
  return 0;
}

int get_quadrant(double X, double Y) {
  int quadrant;
  if (X > 0 && Y > 0) {
    quadrant == 1;
    return quadrant;
  }

  else if (X < 0 && Y > 0) {
    quadrant == 2;
    return quadrant;
  }

  else if (X < 0 && Y < 0) {
    quadrant = 3;
    return quadrant;
  }

  else if (X > 0 && Y < 0) {
    quadrant = 4;
    return quadrant;
  }
}

double get_radius(double X, double Y) {
  double r;
  r = sqrt((X) * (X) + (Y) * (Y));
}

double get_angle(double X, double Y) {
  double angle;
  angle = atan(Y / X);
}

void show_info(int quad, double rad, double theta) {
  printf("quadrant: %f  radius:  %f    angle:  %f.\n", quad, rad, theta);
}


问:
Creating Classes to find the Side length and area of a figure
The question is: Create a class Shape that takes a list of two dimensional vertices as an input. For example:

```<code>tri = Shape([[0,0],[0,1],[1,0]])
# or
sqr = Shape([[0,0],[0,1],[1,1], [1,0]])
</code>```

The class should store two attributes, the vertices themselves in self.verts and the number of vertices in self.n. Then class should have a method calcSideLength() that takes an integer argument between 0 and the number of sides of the shape and returns the length of the side. For example the shape:

```<code>tri = Shape([[0,0],[0,1],[1,0]])
</code>```

has three sides SIDE0: [0,0] --- [0,1] SIDE1: [0,1] --- [1,0] and SIDE2: [1,0] --- [0,0].

The length of each side is given by the Euclidean distance:

```<code>sqrt((1−′1)^2+(2−′2)^2)
</code>```

so the lengths of the three sides would be 1, 1.414, and 1.

Then create a new class Triangle which is a child class of Shape. It should include a new method calculateArea() that returns the area of the triangle. This is, of course, 1/2×ℎ×ℎℎ . The length and height are the shorter two sides of the triangle.

This is what I got:

```<code>import math
class Shape:
    def __init__(self, verts):
        self.verts = verts
        self.n = len(self.verts)

    def calcSideLength(self,side):
        if(0 <= side < self.n):
            x1 = self.verts[side]
            x2 = self.verts[side+1]
        return math.sqrt((x1[0]-x2[0])**2 + (x1[1]-x2[1])**2)

class Triangle(Shape):
    def __init__(self, verts):
        Shape.__init__(self, verts)

    def calculateArea(self):
        side = []
        for i in range(self.n):
            side.append(self.calcSideLength(i))
            side.sort()
            area = 1/2 * side[1]* side[0]
            return area
</code>```

THe code is not working, I do not know what went wrong, can anyone help with it please

答:
First things first, you name methods using not CamelCase but snake_case. Read PEP8 before writing a code.

Also you do not have to override your parent's init with super call as it's redundant

At third, you will have a problem when you will try to calculate last side length, because you have to x1 to be last vertice and x2 the first (this logic does not appear in your code)

At fourth, you are calculating area with a 1/2 * side * heigth, but your none of your sides do represent a height, so instead you must use Heron's formula

```<code>S = sqrt(p * (p - a) * (p - b) * (p - c))
</code>```

where a, b, c are sides length and p = (a + b + c) / 2

Considering everything above, your code must look something like this

```<code>import math

class Shape:
    def __init__(self, verts):
        self.verts = verts
        self.n = len(self.verts)

    def calc_side_length(self, side):
        if 0 <= side < self.n - 1:
            x1 = self.verts[side]
            x2 = self.verts[side + 1]

        elif side == self.n - 1:
            x1 = self.verts[side]
            x2 = self.verts[0]

        else:
            raise

        return math.sqrt((x1[0] - x2[0]) ** 2 + (x1[1] - x2[1]) ** 2)

class Triangle(Shape):

    def calculate_area(self):
        sides = []
        for i in range(self.n):
            sides.append(self.calc_side_length(i))

        p = sum(sides) / 2  # p = (a + b + c) / 2

        return math.sqrt(p * (p - sides[0]) * (p - sides[1]) * (p - sides[2]))
</code>```

Body:
The question is: Create a class Shape that takes a list of two dimensional vertices as an input. For example:

tri = Shape([[0,0],[0,1],[1,0]])
# or
sqr = Shape([[0,0],[0,1],[1,1], [1,0]])

The class should store two attributes, the vertices themselves in self.verts and the number of vertices in self.n. Then class should have a method calcSideLength() that takes an integer argument between 0 and the number of sides of the shape and returns the length of the side. For example the shape:

tri = Shape([[0,0],[0,1],[1,0]])

has three sides SIDE0: [0,0] --- [0,1] SIDE1: [0,1] --- [1,0] and SIDE2: [1,0] --- [0,0].

The length of each side is given by the Euclidean distance:

sqrt((1−′1)^2+(2−′2)^2)

so the lengths of the three sides would be 1, 1.414, and 1.

Then create a new class Triangle which is a child class of Shape. It should include a new method calculateArea() that returns the area of the triangle. This is, of course, 1/2×ℎ×ℎℎ . The length and height are the shorter two sides of the triangle.

This is what I got:

import math
class Shape:
    def __init__(self, verts):
        self.verts = verts
        self.n = len(self.verts)

    def calcSideLength(self,side):
        if(0 <= side < self.n):
            x1 = self.verts[side]
            x2 = self.verts[side+1]
        return math.sqrt((x1[0]-x2[0])**2 + (x1[1]-x2[1])**2)

class Triangle(Shape):
    def __init__(self, verts):
        Shape.__init__(self, verts)

    def calculateArea(self):
        side = []
        for i in range(self.n):
            side.append(self.calcSideLength(i))
            side.sort()
            area = 1/2 * side[1]* side[0]
            return area

THe code is not working, I do not know what went wrong, can anyone help with it please

Body:
First things first, you name methods using not CamelCase but snake_case. Read PEP8 before writing a code.

Also you do not have to override your parent's init with super call as it's redundant

At third, you will have a problem when you will try to calculate last side length, because you have to x1 to be last vertice and x2 the first (this logic does not appear in your code)

At fourth, you are calculating area with a 1/2 * side * heigth, but your none of your sides do represent a height, so instead you must use Heron's formula

S = sqrt(p * (p - a) * (p - b) * (p - c))

where a, b, c are sides length and p = (a + b + c) / 2

Considering everything above, your code must look something like this

import math

class Shape:
    def __init__(self, verts):
        self.verts = verts
        self.n = len(self.verts)

    def calc_side_length(self, side):
        if 0 <= side < self.n - 1:
            x1 = self.verts[side]
            x2 = self.verts[side + 1]

        elif side == self.n - 1:
            x1 = self.verts[side]
            x2 = self.verts[0]

        else:
            raise

        return math.sqrt((x1[0] - x2[0]) ** 2 + (x1[1] - x2[1]) ** 2)

class Triangle(Shape):

    def calculate_area(self):
        sides = []
        for i in range(self.n):
            sides.append(self.calc_side_length(i))

        p = sum(sides) / 2  # p = (a + b + c) / 2

        return math.sqrt(p * (p - sides[0]) * (p - sides[1]) * (p - sides[2]))


问:
Overflow-x scroll not working on chrome and working on Firefox
I'm trying to make nav tabs on one line on mobile and allow the user to stroll
it works well on firefox or any browser with -Moz- engine, but it not working at all on chrome or any browser with -WebKit- engine.

screenshots on chrome and firefox

scrollbar not showing on chrome
scrollbar appears on firefox

Here is the element with the problem

I'm using bootstrap 3.3.7

Here is the used CSS to make it on one line and scrollable

```<code>.d-box {
  display: -webkit-box;
  display: -moz-box;
}
.overflow-x-scroll {
  overflow-x: scroll;
  overflow-y: hidden;
}
.cl-light-black {
  color: #2c3f58;
}
</code>```

答: If anyone still has this problem, I found another solution. If you have not set background color prop in parent element, maybe that's the problem like mine. When I add that prop, the scrollbar is working now.

Body:
I'm trying to make nav tabs on one line on mobile and allow the user to stroll
it works well on firefox or any browser with -Moz- engine, but it not working at all on chrome or any browser with -WebKit- engine.

screenshots on chrome and firefox

scrollbar not showing on chrome
scrollbar appears on firefox

Here is the element with the problem

I'm using bootstrap 3.3.7

Here is the used CSS to make it on one line and scrollable

.d-box {
  display: -webkit-box;
  display: -moz-box;
}
.overflow-x-scroll {
  overflow-x: scroll;
  overflow-y: hidden;
}
.cl-light-black {
  color: #2c3f58;
}


问:
Firestore how to display an array of items in a collection
I want to display the user's order history in user profile. Thus, I'm trying to fetch the order (which has an array of items) that matches with a userId and show it in their profile. Below is a screenshot of my firestore db.

*FB version 9, on react native

enter image description here

答:
You can get array of orders by calling getDoc from firebase

For example; const ordersRef = doc("configured firestore db", "name of your collection", "user id");

For more information you can read the firestore documentation
https://firebase.google.com/docs/firestore/query-data/get-data


问:
Programmatically determine if a COM library (.DLL) is installed
Is there a programmatic way in C# to determine whether a particular COM DLL has been installed? Or is this a matter of scanning the registry for the classId?</p>

答:
Try and create it, and handle the error if not.

Under Win32 CoCreateInstance will return REGDB_E_CLASSNOTREG if not installed (including, IIRC, if registered but the dll/exe implementing it is then deleted).

Under .NET the generated COM interop assembly will throw some error (need to check this, don't have convenient code to test for which exception type). Note. if the interop assembly is missing then that will be treated as missing assembly possibly leading to an application load error.

OwnerDisplayName: dthrasher

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Richard


问:
Is there a way to run pip inside a virtual environment from a python script?
```<code>python_bin = 'venv\Scripts\python.exe'
subprocess.run([python_bin, 'pip', 'install', '-r', 'requirements.txt'])
</code>```

This is what I am trying to do but it doesn't recognize pip

答:
You're missing the -m:

subprocess.run([python_bin, '-m', 'pip', 'install', '-r', 'requirements.txt'])
```

Body:
python_bin = 'venv\Scripts\python.exe'
subprocess.run([python_bin, 'pip', 'install', '-r', 'requirements.txt'])

This is what I am trying to do but it doesn't recognize pip


问:
Use existing Static library in C++ WinRT UWP app
I have an existing third-party static library that I want to use in my project C++WinRT UWP app. Can I do that?

I have read the documentation. But it has me confused.

Documentation talk about "Using a native C++ static library in a UWP App" what is a native c++ library?.

Also, I do not have the source code for this library.

答:
The primary limitation for UWP is that the library:

(a) Must use the subset of Win32 imports that are supported for use in WINAPI_PARTITION_APP

(b) It needs to have been built with VS 2015 Update 3 or later in order to be 'binary compatible' with modern Visual C++ tooling used for UWP.

(c) Some APIs that are used by the static library may not be supported in the "AppContainer" security context (i.e. they may fail in ways the code doesn't handle gracefully).

You should also use /NODEFAULTLIB:kernel32.lib to avoid having your static library force the import of non-supported APIs. The "WindowsApp.lib" umbrella library provides everything that's supported.

More than likely, you'll need the static library built with some modification to actually link successfully and eventually pass WACK.


问:
Get the caret position (x, y) from NSTextView
The NSTextView will send -textViewDidChangeSelection: when the selection changes.

How do I get the caret line and position inside this notification?

TIA!!

EDIT:

Here is my code:

```<code>        NSRange selectedRange = [self selectedRange];
        NSRange newRange = [[self layoutManager] glyphRangeForCharacterRange:selectedRange actualCharacterRange:NULL];
        NSRect rect = [[self layoutManager] boundingRectForGlyphRange:newRange inTextContainer:[self textContainer]];
        NSInteger insertionPoint = [[[self selectedRanges] objectAtIndex:0] rangeValue].location;
</code>```

And those are the values from lldb (when I click on line 3 position 3 of the text control):

```<code>Target 0: (text) stopped.
(lldb) p selectedRange
(NSRange) $0 = location=65, length=0
(lldb) p newRange
(NSRange) $1 = location=65, length=0
(lldb) p rect
(NSRect) $2 = (origin = (x = 60.73876953125, y = 32), size = (width = 0, height = 16))
(lldb) p insertionPoint
(NSInteger) $3 = 65
(lldb)
</code>```

Now, line 3 is actually a big line 1 with couple of soft "carriage return" symbols inserted. Meaning that I didn't press Enter - line was wrapped at the end.

Oh, and what I expect to get is (3,3 - line 3, position 3) instead of (65 - position relative to the beginning of the text).

EDIT1:

I tried to put the code you provided in the handler and run the test program I have.

I got the wrong results - please see the screenshot.

I was expecting to have the following:

```<code>x = 3 and y = 3
</code>```

Now if from here I press an "UP ARROW" key, I will get:

```<code>Cursor position changes. New position: x - 4, y - 1
</code>```

which bring both numbers to be incorrect, because x position shouldn't be changing.

I'm trying to place this inside the

```<code>- (void)textViewDidChangeSelection:(NSNotification *)aNotification
</code>```

答:
NSLayoutManager's method lineFragmentRectForGlyphAtIndex:effectiveRange: returns the rectangle for the line fragment where the glyph lies and (optionally), by reference, the entire range of glyphs in that fragment. With the range of glyphs on the line it is possible to calculate the character index on the line. The line index can be calculated by repeatedly calling this method for a glyph on the previous line. When the insertion point is at the end of the text then there is no glyph so the last glyph is used and the line and character index are adjusted.

```<code>NSUInteger lineNr = 0;
NSUInteger characterNr = 0;
BOOL extraCharacter = NO;
if (textView.textStorage.length > 0) {
    NSUInteger characterIndex = [textView selectedRange].location; // character index in text
    if (characterIndex >= textView.textStorage.length) {
         //  there is no glyph after the insertion point, use the last glyph and add a character later
        characterIndex--;
        extraCharacter = YES;
    }
    NSLayoutManager *layoutManager = textView.layoutManager;
    NSUInteger glyphIndex = [layoutManager glyphIndexForCharacterAtIndex:characterIndex];
    NSRange effectiveRange;
    NSRect lineRect = [layoutManager lineFragmentRectForGlyphAtIndex:glyphIndex effectiveRange:&effectiveRange];
    // effectiveRange is the glyph range of the line
    NSUInteger lineStart = [layoutManager characterIndexForGlyphAtIndex:effectiveRange.location];
    characterNr = characterIndex - lineStart;
    if (extraCharacter) {
        // extraLineFragmentRect is not equal to NSZeroRect if the last character in the text causes a line or paragraph break
        if (NSEqualRects(layoutManager.extraLineFragmentRect, NSZeroRect)) {
            characterNr++;
        }
        else {
            characterNr = 0;
            lineNr++;
        }
    }
    // count lines until effectiveRange is at the start of the text
    while (effectiveRange.location > 0 && effectiveRange.location != NSNotFound) {
        lineNr++;
        glyphIndex = effectiveRange.location - 1;
        lineRect = [layoutManager lineFragmentRectForGlyphAtIndex:glyphIndex effectiveRange:&effectiveRange];
    }
}
NSLog(@"Line: %li, character: %li", (long)lineNr, (long)characterNr);
</code>```

Body:
The NSTextView will send -textViewDidChangeSelection: when the selection changes.

How do I get the caret line and position inside this notification?

TIA!!

EDIT:

Here is my code:

        NSRange selectedRange = [self selectedRange];
        NSRange newRange = [[self layoutManager] glyphRangeForCharacterRange:selectedRange actualCharacterRange:NULL];
        NSRect rect = [[self layoutManager] boundingRectForGlyphRange:newRange inTextContainer:[self textContainer]];
        NSInteger insertionPoint = [[[self selectedRanges] objectAtIndex:0] rangeValue].location;

And those are the values from lldb (when I click on line 3 position 3 of the text control):

Target 0: (text) stopped.
(lldb) p selectedRange
(NSRange) $0 = location=65, length=0
(lldb) p newRange
(NSRange) $1 = location=65, length=0
(lldb) p rect
(NSRect) $2 = (origin = (x = 60.73876953125, y = 32), size = (width = 0, height = 16))
(lldb) p insertionPoint
(NSInteger) $3 = 65
(lldb)

Now, line 3 is actually a big line 1 with couple of soft "carriage return" symbols inserted. Meaning that I didn't press Enter - line was wrapped at the end.

Oh, and what I expect to get is (3,3 - line 3, position 3) instead of (65 - position relative to the beginning of the text).

EDIT1:

I tried to put the code you provided in the handler and run the test program I have.

I got the wrong results - please see the screenshot.

I was expecting to have the following:

x = 3 and y = 3

Now if from here I press an "UP ARROW" key, I will get:

Cursor position changes. New position: x - 4, y - 1

which bring both numbers to be incorrect, because x position shouldn't be changing.

I'm trying to place this inside the

- (void)textViewDidChangeSelection:(NSNotification *)aNotification

Body:
NSLayoutManager's method lineFragmentRectForGlyphAtIndex:effectiveRange: returns the rectangle for the line fragment where the glyph lies and (optionally), by reference, the entire range of glyphs in that fragment. With the range of glyphs on the line it is possible to calculate the character index on the line. The line index can be calculated by repeatedly calling this method for a glyph on the previous line. When the insertion point is at the end of the text then there is no glyph so the last glyph is used and the line and character index are adjusted.

NSUInteger lineNr = 0;
NSUInteger characterNr = 0;
BOOL extraCharacter = NO;
if (textView.textStorage.length > 0) {
    NSUInteger characterIndex = [textView selectedRange].location; // character index in text
    if (characterIndex >= textView.textStorage.length) {
         //  there is no glyph after the insertion point, use the last glyph and add a character later
        characterIndex--;
        extraCharacter = YES;
    }
    NSLayoutManager *layoutManager = textView.layoutManager;
    NSUInteger glyphIndex = [layoutManager glyphIndexForCharacterAtIndex:characterIndex];
    NSRange effectiveRange;
    NSRect lineRect = [layoutManager lineFragmentRectForGlyphAtIndex:glyphIndex effectiveRange:&effectiveRange];
    // effectiveRange is the glyph range of the line
    NSUInteger lineStart = [layoutManager characterIndexForGlyphAtIndex:effectiveRange.location];
    characterNr = characterIndex - lineStart;
    if (extraCharacter) {
        // extraLineFragmentRect is not equal to NSZeroRect if the last character in the text causes a line or paragraph break
        if (NSEqualRects(layoutManager.extraLineFragmentRect, NSZeroRect)) {
            characterNr++;
        }
        else {
            characterNr = 0;
            lineNr++;
        }
    }
    // count lines until effectiveRange is at the start of the text
    while (effectiveRange.location > 0 && effectiveRange.location != NSNotFound) {
        lineNr++;
        glyphIndex = effectiveRange.location - 1;
        lineRect = [layoutManager lineFragmentRectForGlyphAtIndex:glyphIndex effectiveRange:&effectiveRange];
    }
}
NSLog(@"Line: %li, character: %li", (long)lineNr, (long)characterNr);


问:
Accept Google Cookies
I want to use Python's Selenium to accept the cookies of Google. But the ids and everything are at random values. So, how do I do for example

```<code>driver.find_element(By.XPATH, '//*[@id="L2AGLb"]').click()
</code>```

?

答:
You can click a particular location in x,y (that is if x,y, is known), but in your case x & y will a be constant unless you are resizing windows.

```<code>driver = webdriver.Firefox()
driver.get("http://www.google.com")
el=driver.find_elements_by_xpath("//button[contains(string(), 'Lucky')]")[0]

action = webdriver.common.action_chains.ActionChains(driver)
action.move_to_element_with_offset(el, 5, 5)
</code>```

use this line from a id that doesnt change within the page

```<code>action.click()
action.perform()
</code>```

You wouldn't have a problem if the click is offset with respect to an element that doesn't alter its ID.

Title: Accept Google Cookies

Body:
I want to use Python's Selenium to accept the cookies of Google. But the ids and everything are at random values. So, how do I do for example

driver.find_element(By.XPATH, '//*[@id="L2AGLb"]').click()

?

Body:
You can click a particular location in x,y (that is if x,y, is known), but in your case x & y will a be constant unless you are resizing windows.

driver = webdriver.Firefox()
driver.get("http://www.google.com")
el=driver.find_elements_by_xpath("//button[contains(string(), 'Lucky')]")[0]

action = webdriver.common.action_chains.ActionChains(driver)
action.move_to_element_with_offset(el, 5, 5)

use this line from a id that doesnt change within the page

action.click()
action.perform()

You wouldn't have a problem if the click is offset with respect to an element that doesn't alter its ID.


问:
Upgrading Visual Studio 2017 to 2022, getting build errors LNK2038

These build errors are only happening on Release build.  Debug build is fine.  I have 2 projects.  One Solution is an .exe with some supporting .dll projects.  All of them are dependent on a project that produces a .lib

One of the projects:

The .lib project:

The other update was to the boost library.  I went from 67 to 78 . . .

It appeared that boost 78 could handle project builds from the v143 toolset.

答: Edit the .vcxproj and change the occurrences of v143 to be v142</p>


问:
Very slow join query on large table (machine = Xeon 2.4 GHz, 16 core, 64 GB RAM)
Here is my query :

```<code>SELECT  email_data.id, email_data.source_file, email_data.report_id,
        email_data.filePath, email_data.fileName, email_data.size,
        email_data.emailID, email_data.msgID, email_data.cus, email_data.subject,
        email_data.sentto, email_data.emailFrom, email_data.hdrs, email_data.cc,
        email_data.bcc, email_data.extracted, email_data.DateTime,
        email_data.TimeStamp, email_data.OriginalDateTime, email_data.ParentID,
        email_data.reply_to, email_data.MD5Hash, email_data.duplicated,
        email_data.TimeZone, email_data.AttachName, email_data.fqdn,
        attach_data.id, attach_data.source_file, attach_data.report_id,
        attach_data.filePath, attach_data.fileName, attach_data.size, attach_data.ext,
        attach_data.emailID, attach_data.cus, attach_data.extracted,
        attach_data.MD5Hash, attach_data.duplicated
FROM email_data
LEFT JOIN attach_data
ON (email_data.emailID = attach_data.emailID);
</code>```

Combination of both of the table has 50k + records (email_data have 22k records and other have 30K + records).

Above query takes over 90 mins and still not finished.

This one :

```<code>SELECT email_data.id, attach_data.id
FROM email_data
LEFT JOIN attach_data
ON (email_data.emailID = attach_data.emailID);
</code>```

takes 2 mins 22 sec:

What am I doing wrong? It seems that MySQL do not using enough memory to speed things up, and it only uses 1 core out of 16 cores.

How can I configure it to use all available resources?

Or should I query IDs (as in 2nd query) and loop + select each of them back in my code? Will it cause same result?

I needs all those fields and all the row, I am converting them into Custom CSV-Like format so it can be exported to other software.

Columns :

```<code>mysql> show columns from email_data;
+------------------+----------+------+-----+---------+----------------+
| Field            | Type     | Null | Key | Default | Extra          |
+------------------+----------+------+-----+---------+----------------+
| id               | int(11)  | NO   | PRI | NULL    | auto_increment |
| source_file      | longtext | YES  |     | NULL    |                |
| report_id        | int(11)  | YES  |     | NULL    |                |
| filePath         | longtext | YES  |     | NULL    |                |
| fileName         | longtext | YES  |     | NULL    |                |
| size             | int(11)  | YES  |     | NULL    |                |
| emailID          | longtext | YES  |     | NULL    |                |
| msgID            | longtext | YES  |     | NULL    |                |
| cus              | longtext | YES  |     | NULL    |                |
| subject          | longtext | YES  |     | NULL    |                |
| sentto           | longtext | YES  |     | NULL    |                |
| emailFrom        | longtext | YES  |     | NULL    |                |
| hdrs             | longtext | YES  |     | NULL    |                |
| cc               | longtext | YES  |     | NULL    |                |
| bcc              | longtext | YES  |     | NULL    |                |
| extracted        | longtext | YES  |     | NULL    |                |
| DateTime         | char(1)  | YES  |     | NULL    |                |
| TimeStamp        | int(11)  | YES  |     | NULL    |                |
| OriginalDateTime | char(1)  | YES  |     | NULL    |                |
| ParentID         | longtext | YES  |     | NULL    |                |
| reply_to         | longtext | YES  |     | NULL    |                |
| MD5Hash          | longtext | YES  |     | NULL    |                |
| duplicated       | char(1)  | YES  |     | NULL    |                |
| TimeZone         | char(1)  | YES  |     | NULL    |                |
| AttachName       | longtext | YES  |     | NULL    |                |
| fqdn             | longtext | YES  |     | NULL    |                |
+------------------+----------+------+-----+---------+----------------+
</code>```

Almost same for attach_data

答:
Not sure what you did to have a query to run 90mins and not timeout...

Check the field you are joining on.  Specifically, take a look at the execution plan for the query (or estimated execution plan) to see what's the most costly operation.

Are you joining on fields that are varchar(255). varchar(max) or similar?  Comparing large varchars is an expensive operation.  If you can shortern the field that would help.

Regarding all those fields:

Return a smaller subset of fields.  If you are recalling actual attachment data from the sql server, then you may want to first perform a query to identify just which attachments (attach_data.PrimaryKey) are needed, instead of the entire row (which must then be pulled into memory).
Then, once you have the PKs of the required attach_data records, you can recall only the data needed for those rows

Are you joining on non-indexed fields (as in you're not joining on a primary key)? Adding indexes to the columns will speed retrieval the process, but learn about indexes before doing so (For example, adding indexes to a column will actually slow data updates/inserts and indexes on int fields are better than indexes on large-range varchars).

Body:
Here is my query :

SELECT  email_data.id, email_data.source_file, email_data.report_id,
        email_data.filePath, email_data.fileName, email_data.size,
        email_data.emailID, email_data.msgID, email_data.cus, email_data.subject,
        email_data.sentto, email_data.emailFrom, email_data.hdrs, email_data.cc,
        email_data.bcc, email_data.extracted, email_data.DateTime,
        email_data.TimeStamp, email_data.OriginalDateTime, email_data.ParentID,
        email_data.reply_to, email_data.MD5Hash, email_data.duplicated,
        email_data.TimeZone, email_data.AttachName, email_data.fqdn,
        attach_data.id, attach_data.source_file, attach_data.report_id,
        attach_data.filePath, attach_data.fileName, attach_data.size, attach_data.ext,
        attach_data.emailID, attach_data.cus, attach_data.extracted,
        attach_data.MD5Hash, attach_data.duplicated
FROM email_data
LEFT JOIN attach_data
ON (email_data.emailID = attach_data.emailID);

Combination of both of the table has 50k + records (email_data have 22k records and other have 30K + records).

Above query takes over 90 mins and still not finished.

This one :

SELECT email_data.id, attach_data.id
FROM email_data
LEFT JOIN attach_data
ON (email_data.emailID = attach_data.emailID);

takes 2 mins 22 sec:

What am I doing wrong? It seems that MySQL do not using enough memory to speed things up, and it only uses 1 core out of 16 cores.

How can I configure it to use all available resources?

Or should I query IDs (as in 2nd query) and loop + select each of them back in my code? Will it cause same result?

I needs all those fields and all the row, I am converting them into Custom CSV-Like format so it can be exported to other software.

Columns :

mysql> show columns from email_data;
+------------------+----------+------+-----+---------+----------------+
| Field            | Type     | Null | Key | Default | Extra          |
+------------------+----------+------+-----+---------+----------------+
| id               | int(11)  | NO   | PRI | NULL    | auto_increment |
| source_file      | longtext | YES  |     | NULL    |                |
| report_id        | int(11)  | YES  |     | NULL    |                |
| filePath         | longtext | YES  |     | NULL    |                |
| fileName         | longtext | YES  |     | NULL    |                |
| size             | int(11)  | YES  |     | NULL    |                |
| emailID          | longtext | YES  |     | NULL    |                |
| msgID            | longtext | YES  |     | NULL    |                |
| cus              | longtext | YES  |     | NULL    |                |
| subject          | longtext | YES  |     | NULL    |                |
| sentto           | longtext | YES  |     | NULL    |                |
| emailFrom        | longtext | YES  |     | NULL    |                |
| hdrs             | longtext | YES  |     | NULL    |                |
| cc               | longtext | YES  |     | NULL    |                |
| bcc              | longtext | YES  |     | NULL    |                |
| extracted        | longtext | YES  |     | NULL    |                |
| DateTime         | char(1)  | YES  |     | NULL    |                |
| TimeStamp        | int(11)  | YES  |     | NULL    |                |
| OriginalDateTime | char(1)  | YES  |     | NULL    |                |
| ParentID         | longtext | YES  |     | NULL    |                |
| reply_to         | longtext | YES  |     | NULL    |                |
| MD5Hash          | longtext | YES  |     | NULL    |                |
| duplicated       | char(1)  | YES  |     | NULL    |                |
| TimeZone         | char(1)  | YES  |     | NULL    |                |
| AttachName       | longtext | YES  |     | NULL    |                |
| fqdn             | longtext | YES  |     | NULL    |                |
+------------------+----------+------+-----+---------+----------------+

Almost same for attach_data


问:
play sound in xylophone project
I try to make a Xylophone. I added my Sound file by dragging the file into my XCode project and i made sure 'Copy items if needed' is checked. I wrote the code. I connected 7 buttons to the keyPressed function. I set the names of the sound files and the names of the buttons to be the same. When I run the code and press any key, it gives this error and no sound is playing. I'm sure the sound files are also included because when I click on show in Finder, the audio files are in the project. I don't know what I did wrong.

this is the code in ViewController and below it the error

this is the Main.storyboard with assistant

答:
I found the cause of the error. When I change Button's style Plain to Default in Inspector, it works without any problem.

When you wanna add sounds to XCode the safest way is to do, first you should create a new group by right clickin to ViewController. This will create a new file then you can drag your sounds (.wav / .mp3) into that file. While you doing that you need to target them.

After you drag and target them, you should see like this in the inspector when you click each of the sounds:

If you wont change the button style plain to default it wont work whatever you carefully drag the sounds into XCode. I know it's stupid but it should be like this. Otherwise when you run the project and click on any button it would give an error like that:

Title: play sound in xylophone project


问:
Pinata IPFS's pinFileToIPFS method not accepting a user uploaded file
I am working on a project (using React.js Express.js and Node.js) to convert a user uploaded image into and NFT on Ethereum blockchain and for that, I need to upload the image on an IPFS (I am using Pinata) and then use the pinata URI in the metadata to mint a new NFT. (Do let me know if I am wrong here, I am still newbie to web3)

For uploading my image onto the Pinata IPFS, I am sending the base64 string of the image from the client side to the server side and then calling the pinFileToIPFS method. This is the code of my server side file

```<code>const axios = require('axios');
const fs = require('fs');
const FormData = require('form-data');
const router = require('express').Router();
const { Readable } = require('stream');

const pinFileToIPFS = (image) => {
    const url = `https://api.pinata.cloud/pinning/pinJSONToIPFS`;
    const buffer = Buffer.from(image);
    const stream = Readable.from(buffer);
    const filename = `an-awesome-nft_${Date.now()}.png`;
    stream.path = filename;

    const formData = new FormData();
    formData.append("file", stream);

return axios.post(url,
        formData,
        {
            headers: {
                'Content-Type': `multipart/form-data; boundary= ${formData._boundary}`,
                'pinata_api_key': "*******************",
                'pinata_secret_api_key': "**********************************",
            }
        }
    ).then(function (response) {
        console.log("Success: ", response);
    }).catch(function (error) {
        console.log("Fail! ", error.response.data);
    });
};

router.route('/').post((req, res) => {
    const image = req.body.image;
    pinFileToIPFS(image);
});

module.exports = router;
</code>```

Here req.body.image contains the base64 string of the user uploaded file.
I have tried to convert the base64 string into a buffer and then convert the buffer into a readable stream (as done in the official Pianata documentation but for a localy file) and then wrap it up in FormData(), but I keep getting the following error.

```<code>data: {
  error: 'This API endpoint requires valid JSON, and a JSON content-type'
}
</code>```

I know the problem is with the format my image/file is being sent to the API but I can't figure out. I am still a newbie to web3 and blockchains so please help!

答:
You may want to consider changing the following two lines and using the https://api.pinata.cloud/pinning/pinFileToIPFS endpoint instead:

const buffer = Buffer.from(image); -> const buffer = Buffer.from(image, "base64");

and

formData.append("file", stream); -> formData.append("file", stream, "fileNameOfChoiche.png);

Body:
I am working on a project (using React.js Express.js and Node.js) to convert a user uploaded image into and NFT on Ethereum blockchain and for that, I need to upload the image on an IPFS (I am using Pinata) and then use the pinata URI in the metadata to mint a new NFT. (Do let me know if I am wrong here, I am still newbie to web3)

For uploading my image onto the Pinata IPFS, I am sending the base64 string of the image from the client side to the server side and then calling the pinFileToIPFS method. This is the code of my server side file

const axios = require('axios');
const fs = require('fs');
const FormData = require('form-data');
const router = require('express').Router();
const { Readable } = require('stream');

const pinFileToIPFS = (image) => {
    const url = `https://api.pinata.cloud/pinning/pinJSONToIPFS`;
    const buffer = Buffer.from(image);
    const stream = Readable.from(buffer);
    const filename = `an-awesome-nft_${Date.now()}.png`;
    stream.path = filename;

    const formData = new FormData();
    formData.append("file", stream);

return axios.post(url,
        formData,
        {
            headers: {
                'Content-Type': `multipart/form-data; boundary= ${formData._boundary}`,
                'pinata_api_key': "*******************",
                'pinata_secret_api_key': "**********************************",
            }
        }
    ).then(function (response) {
        console.log("Success: ", response);
    }).catch(function (error) {
        console.log("Fail! ", error.response.data);
    });
};

router.route('/').post((req, res) => {
    const image = req.body.image;
    pinFileToIPFS(image);
});

module.exports = router;

Here req.body.image contains the base64 string of the user uploaded file.
I have tried to convert the base64 string into a buffer and then convert the buffer into a readable stream (as done in the official Pianata documentation but for a localy file) and then wrap it up in FormData(), but I keep getting the following error.

data: {
  error: 'This API endpoint requires valid JSON, and a JSON content-type'
}

I know the problem is with the format my image/file is being sent to the API but I can't figure out. I am still a newbie to web3 and blockchains so please help!


问:
Sort array outside method
I have this method:

```<code>public static IEnumerable<string> GetWords(string path, Func<string,Boolean> s)
        {
            string Text = "";
            try
            {
                Text = File.ReadAllText(path).ToLower();
            }
            catch
            {
                Console.Write("File not found");
            }
            Char[] characters = { ' ',',','.','_', '\n' };

            string[] array = Text.Split(characters);
            Array.Sort(array, (first, last) => first.Length.CompareTo(last.Length));

            foreach (string word in array)
            {
                if (s(word) == true)
                    yield return word;

            }

</code>```

I want to get the Array.Sort outside the GetWords method. Is there a simple way to do this?

答:
I assume you mean, "I want to sort the result of GetWords, but thats not an Array, its an IEnumerable so I cant use Array.Sort - how do I do that?"

```<code>var list = GetWords(....);
var sorted = list.OrderBy(s=>s);
</code>```

see How to sort an IEnumerable<string>

Title: Sort array outside method

Body:
I have this method:

public static IEnumerable<string> GetWords(string path, Func<string,Boolean> s)
        {
            string Text = "";
            try
            {
                Text = File.ReadAllText(path).ToLower();
            }
            catch
            {
                Console.Write("File not found");
            }
            Char[] characters = { ' ',',','.','_', '\n' };

            string[] array = Text.Split(characters);
            Array.Sort(array, (first, last) => first.Length.CompareTo(last.Length));

            foreach (string word in array)
            {
                if (s(word) == true)
                    yield return word;

            }

I want to get the Array.Sort outside the GetWords method. Is there a simple way to do this?

Body:
I assume you mean, "I want to sort the result of GetWords, but thats not an Array, its an IEnumerable so I cant use Array.Sort - how do I do that?"

var list = GetWords(....);
var sorted = list.OrderBy(s=>s);

see How to sort an IEnumerable<string>


问:
Sqlite3 Python Parameterized Query Error binding parameter 0 - probably unsupported type
I'm getting an error (Error binding parameter 0 - probably unsupported type.) for the query:

```<code>parameterized_query = cur.execute('SELECT courses.dept, courses.course_num, courses.title FROM courses JOIN catalog_index ON catalog_index.course_id = courses.course_id WHERE catalog_index.word IN (?)', arg)
</code>```

where

```<code>arg = (('computer', 'science', 'economics'),)
</code>```

I am confused because I am passing in a tuple, so I expect this should work, but it is not.

答:
How about this:

```<code>arg = ('computer', 'science', 'economics')
sql = '''SELECT courses.dept
, courses.course_num
, courses.title
FROM courses
JOIN catalog_index
ON catalog_index.course_id = courses.course_id
WHERE catalog_index.word IN (?,?,?);'''
parameterized_query = cur.execute(sql, arg)
</code>```

The changes in my suggestion are:

Set arg to be a single tuple (it is a nested tuple in your post)

Use 3 question marks in the prepared sql statement (it is one question mark in your post).

Body:
I'm getting an error (Error binding parameter 0 - probably unsupported type.) for the query:

parameterized_query = cur.execute('SELECT courses.dept, courses.course_num, courses.title FROM courses JOIN catalog_index ON catalog_index.course_id = courses.course_id WHERE catalog_index.word IN (?)', arg)

where

arg = (('computer', 'science', 'economics'),)

I am confused because I am passing in a tuple, so I expect this should work, but it is not.

Body:
How about this:

arg = ('computer', 'science', 'economics')
sql = '''SELECT courses.dept
, courses.course_num
, courses.title
FROM courses
JOIN catalog_index
ON catalog_index.course_id = courses.course_id
WHERE catalog_index.word IN (?,?,?);'''
parameterized_query = cur.execute(sql, arg)

The changes in my suggestion are:

Set arg to be a single tuple (it is a nested tuple in your post)

Use 3 question marks in the prepared sql statement (it is one question mark in your post).


问:
Spring 5.x and CDI 2.x Integration Options
Considering Spring's 5.x baseline and CDI's baseline 2.x, what more viable options should I consider to integrate them into a project with JSF 2.3, since JSF 2.3 is coupled with the CDI? Bridges? Custom Bean Factories? Others?</p>

答:
We use bean producers to access Spring objects in CDI. As in the architecture we used there is an interface layer between the UI and the server/business, this integration was facilitated.
Integration is performed as follows.

Cdi Factory from the view/ui layer.

```<code>public class MainViewClientFactory {

    public MainViewClientFactory() {
    }

    @ApplicationScoped
    @Produces
    public CadastroPaisService cadastroPaisService() {
        return CdiSpringUtils.getSpringBean(CadastroPaisService.class);
    }

}
</code>```

The CdiSpringUtils Class.

```<code>public class CdiSpringUtils {

    private CdiSpringUtils() {
    }

    public static <R, Q extends Annotation> R getSpringBean(Class<R> beanClass) {
        return ApplicationContextProvider.getApplicationContext().getBean(beanClass);
    }

    public static <R, Q extends Annotation> R getSpringBean(Class<R> beanClass, Class<Q> qualifierClass) {
        return ApplicationContextProvider.getQualifiedBeanOfType(beanClass, qualifierClass);
    }

}
</code>```

The ApplicationContextProvider Class.

```<code>public class ApplicationContextProvider implements ApplicationContextAware {

    private static ApplicationContext context;

    public static ApplicationContext getApplicationContext() {
        return context;
    }

    public static <R, Q extends Annotation> R getQualifiedBeanOfType(Class<R> cls, Class<Q> qualifierAnnotationClass) {
        R bean = null;
        Map<String, R> beanMap = getApplicationContext().getBeansOfType(cls);
        for (Map.Entry<String, R> entry : beanMap.entrySet()) {
            Q targetAnnotation = getApplicationContext().findAnnotationOnBean(entry.getKey(), qualifierAnnotationClass);
            if (targetAnnotation != null) {
                bean = entry.getValue();
                break;
            }
        }
        return bean;
    }

    @Override
    public void setApplicationContext(ApplicationContext ctx) {
        context = ctx;
    }
}

</code>```

Body:
We use bean producers to access Spring objects in CDI. As in the architecture we used there is an interface layer between the UI and the server/business, this integration was facilitated.
Integration is performed as follows.

Cdi Factory from the view/ui layer.

public class MainViewClientFactory {

    public MainViewClientFactory() {
    }

    @ApplicationScoped
    @Produces
    public CadastroPaisService cadastroPaisService() {
        return CdiSpringUtils.getSpringBean(CadastroPaisService.class);
    }

}

The CdiSpringUtils Class.

public class CdiSpringUtils {

    private CdiSpringUtils() {
    }

    public static <R, Q extends Annotation> R getSpringBean(Class<R> beanClass) {
        return ApplicationContextProvider.getApplicationContext().getBean(beanClass);
    }

    public static <R, Q extends Annotation> R getSpringBean(Class<R> beanClass, Class<Q> qualifierClass) {
        return ApplicationContextProvider.getQualifiedBeanOfType(beanClass, qualifierClass);
    }

}

The ApplicationContextProvider Class.

public class ApplicationContextProvider implements ApplicationContextAware {

    private static ApplicationContext context;

    public static ApplicationContext getApplicationContext() {
        return context;
    }

    public static <R, Q extends Annotation> R getQualifiedBeanOfType(Class<R> cls, Class<Q> qualifierAnnotationClass) {
        R bean = null;
        Map<String, R> beanMap = getApplicationContext().getBeansOfType(cls);
        for (Map.Entry<String, R> entry : beanMap.entrySet()) {
            Q targetAnnotation = getApplicationContext().findAnnotationOnBean(entry.getKey(), qualifierAnnotationClass);
            if (targetAnnotation != null) {
                bean = entry.getValue();
                break;
            }
        }
        return bean;
    }

    @Override
    public void setApplicationContext(ApplicationContext ctx) {
        context = ctx;
    }
}


问:
Why is jest test not recognizing react native components?
I have a react native app that I am trying to run tests on, I have set up a basic greeting component as shown below called Greetings.js:

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

const Greetings = ({hello}) => {
  return (
    <View>
      <Text>{hello}</Text>
    </View>
  );
};

export default Greetings;
</code>```

This is the test I am running called Greetings.test.js:

```<code>import React from 'react';
import {render, screen} from '@testing-library/react-native';
import Greetings from './Greetings';

describe('Greetings component', () => {
  it('renders hello world as a test', () => {
    render(<Greetings hello="Hello World!" />);

    const helloWorldElement = screen.getByText('Hello World!');
    expect(helloWorldElement).toBeInTheDocument();
  });
});
</code>```

For some reason it doesnt recognise the react native components, this is the error when running the test:

```<code> FAIL  app/__tests__/components/Account/Greetings.test.js
  ● Console

    console.error
      Warning: React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You li
forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.

      Check the render method of `Greetings`.
          at Greetings (C:\Users\meeve\OneDrive\Desktop\Cozify\smartliving-app\app\__tests__\components\Account\Greetings.js:4:21)

       5 |   return (
       6 |     <View>
    >  7 |       <Text>{hello}</Text>
         |       ^
       8 |     </View>
       9 |   );
      10 | };

      at printWarning (node_modules/react/cjs/react.development.js:220:30)
      at error (node_modules/react/cjs/react.development.js:196:5)
      at Object.createElementWithValidation [as createElement] (node_modules/react/cjs/react.development.js:2215:7)
      at Greetings (app/__tests__/components/Account/Greetings.js:7:7)
      at renderWithHooks (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:6016:18)
      at mountIndeterminateComponent (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:8744:13)
      at beginWork (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:9966:16)
      at performUnitOfWork (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:13800:12)
</code>```

It shows the same error for the View Component.
Should it not automatically recognize these components after initial setup?
I have installed the following:
yarn add install -dev react-test-renderer@17.0.1 @testing-library/react-native @testing-library/jest-native

The current Jest configuration in the package.json file:

```<code>  "jest": {
    "preset": "react-native",
    "coverageThreshold": {
      "app/**/selectors.{js,ts,tsx}": {
        "_comment": "Let's strive to increase coverage, instead of lowering it!",
        "lines": 57
      }
    },
    "coverageDirectory": ".coverage/",
    "moduleFileExtensions": [
      "ts",
      "tsx",
      "js",
      "jsx",
      "native"
    ],
    "testRegex": "(/__tests__/.*|\\.(test|spec))\\.(ts|tsx|js|jsx)$",
    "testPathIgnorePatterns": [
      "\\.snap$",
      "<rootDir>/node_modules/"
    ],
    "cacheDirectory": ".jest/cache",
    "setupFiles": [
      "./jest.setup.js"
    ]
  }
</code>```

答:
Seems nothing wrong with the component rendering but the test.

You can use getByText query which can be obtained from render.

Please refer to React Native Testing Library for more information.

```<code>import React from 'react';
import {render} from '@testing-library/react-native';
import Greetings from './Greetings';

describe('Greetings component', () => {
  it('renders hello world as a test', () => {

   const {getByText} = render(<Greetings hello="Hello World!" />);

   expect(getByText('Hello World!')).toBeDefined();

  });
});

</code>```

Body:
I have a react native app that I am trying to run tests on, I have set up a basic greeting component as shown below called Greetings.js:

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

const Greetings = ({hello}) => {
  return (
    <View>
      <Text>{hello}</Text>
    </View>
  );
};

export default Greetings;

This is the test I am running called Greetings.test.js:

import React from 'react';
import {render, screen} from '@testing-library/react-native';
import Greetings from './Greetings';

describe('Greetings component', () => {
  it('renders hello world as a test', () => {
    render(<Greetings hello="Hello World!" />);

    const helloWorldElement = screen.getByText('Hello World!');
    expect(helloWorldElement).toBeInTheDocument();
  });
});

For some reason it doesnt recognise the react native components, this is the error when running the test:

 FAIL  app/__tests__/components/Account/Greetings.test.js
  ● Console

    console.error
      Warning: React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You li
forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.

      Check the render method of `Greetings`.
          at Greetings (C:\Users\meeve\OneDrive\Desktop\Cozify\smartliving-app\app\__tests__\components\Account\Greetings.js:4:21)

       5 |   return (
       6 |     <View>
    >  7 |       <Text>{hello}</Text>
         |       ^
       8 |     </View>
       9 |   );
      10 | };

      at printWarning (node_modules/react/cjs/react.development.js:220:30)
      at error (node_modules/react/cjs/react.development.js:196:5)
      at Object.createElementWithValidation [as createElement] (node_modules/react/cjs/react.development.js:2215:7)
      at Greetings (app/__tests__/components/Account/Greetings.js:7:7)
      at renderWithHooks (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:6016:18)
      at mountIndeterminateComponent (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:8744:13)
      at beginWork (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:9966:16)
      at performUnitOfWork (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:13800:12)

It shows the same error for the View Component.
Should it not automatically recognize these components after initial setup?
I have installed the following:
yarn add install -dev react-test-renderer@17.0.1 @testing-library/react-native @testing-library/jest-native

The current Jest configuration in the package.json file:

  "jest": {
    "preset": "react-native",
    "coverageThreshold": {
      "app/**/selectors.{js,ts,tsx}": {
        "_comment": "Let's strive to increase coverage, instead of lowering it!",
        "lines": 57
      }
    },
    "coverageDirectory": ".coverage/",
    "moduleFileExtensions": [
      "ts",
      "tsx",
      "js",
      "jsx",
      "native"
    ],
    "testRegex": "(/__tests__/.*|\\.(test|spec))\\.(ts|tsx|js|jsx)$",
    "testPathIgnorePatterns": [
      "\\.snap$",
      "<rootDir>/node_modules/"
    ],
    "cacheDirectory": ".jest/cache",
    "setupFiles": [
      "./jest.setup.js"
    ]
  }

Body:
Seems nothing wrong with the component rendering but the test.

You can use getByText query which can be obtained from render.

Please refer to React Native Testing Library for more information.

import React from 'react';
import {render} from '@testing-library/react-native';
import Greetings from './Greetings';

describe('Greetings component', () => {
  it('renders hello world as a test', () => {

   const {getByText} = render(<Greetings hello="Hello World!" />);

   expect(getByText('Hello World!')).toBeDefined();

  });
});


问:
What "costs" more, memory space or recursive calls?
Assume we want to implement a data structure, say a binary search tree.

One can implement every method of the tree without using recursion at all, by allocating each node additional space for a pointer to its parent in the tree. In that way, we can traverse the tree however we wish.
The advantage is clear - we do not need to make recursive calls in order to process parents informantion, too much recursive calls may lead to a stack overflow.
On the other hand, using that parent's pointer requires O(n) memory space, which may be serious when dealing with a lot of data.

So my question is - what considered to be more efficient, implementing the tree using recursive calls, or maybe implementing the tree using parent's pointers (the latter may be even more convenient to implement and lead to more readable code) ?

Thanks in advance.

答: There is no possible way for an explicitly recursive function to beat the equivalent stack-based implementation in terms of memory consumption. Any recursive function can be mechanically transformed into a non-recursive function with the same behavior, and its stack will not need to store frame pointers or return addresses. The advantage of the recursive implementation is solely code clarity.</p>


问:
where like - doctrine - symfony
```<code>News:
id | title | sub
1  | one   | sub1
2  | two   | sub2

public function executeSearch(sfWebRequest $request)
{
  $q = Doctrine_Core::getTable('News')
          ->createQuery('a')
          ->where("a.title LIKE %?%", array($request->getParameter('text')));

  if ($request->getParameter('sub')){
           $q->andWhere('a.subtile = sub2');
  }
  $test = $q->execute();
}
</code>```

if i send title = one then show me ok, same as if title = two, but if i entered in input search "one two" then this not working. How change SQL query and code for this? I would like if i entered "one two", then show me title id 1 and title id 2. Now nothing show.

答:
You need to break the search query to words, and add them all to the doctrine query:</p>

```<code>foreach(explode(" ", $request->getParameter("title")) as $v) {
  $q->orWhere("a.title LIKE %?%", $v);
}
</code>```

Title: where like - doctrine - symfony

Body:
News:
id | title | sub
1  | one   | sub1
2  | two   | sub2

public function executeSearch(sfWebRequest $request)
{
  $q = Doctrine_Core::getTable('News')
          ->createQuery('a')
          ->where("a.title LIKE %?%", array($request->getParameter('text')));

  if ($request->getParameter('sub')){
           $q->andWhere('a.subtile = sub2');
  }
  $test = $q->execute();
}

if i send title = one then show me ok, same as if title = two, but if i entered in input search "one two" then this not working. How change SQL query and code for this? I would like if i entered "one two", then show me title id 1 and title id 2. Now nothing show.

Body:
You need to break the search query to words, and add them all to the doctrine query:

foreach(explode(" ", $request->getParameter("title")) as $v) {
  $q->orWhere("a.title LIKE %?%", $v);
}


问:
Why is it necessary to enter the object twice for a class?
I am just getting started with linked lists, and I wrote some basic functions with a linked list class and node objects. When calling a function, it seems that I have to enter in the linked list object twice and I think I'm doing something wrong. To add a new node with value "b" to the tail, I have to call
sample_list.add_tail_node(sample_list, "b"), when I think it is supposed to be sample_list.add_tail_node("b"), because what is the point of specifying sample_list twice</p>
```<code>class LinkedList:

def __init__(self):
    self.head = None

def add_tail_node(self, val: int):
    node = self.head
    while True:
        if node.next is None:
            node.next = Node(val)
            break
        node = node.next

class Node:
def __init__(self, val):
    self.val = val
    self.next = None
sample_list = LinkedList
sample_list.head = Node("a")
sample_list.add_tail_node(sample_list, "b")
</code>```

答:
You are assigning class reference to a variable here

```<code>sample_list = LinkedList
</code>```

When you need to call a class, so it creates a instance

```<code>sample_list = LinkedList()
</code>```

For better undersanding

When you are calling

```<code>sample_list.head = Node("a")
</code>```

You are actualy assigning head to a class itself

And when you are calling object method using class, you need to provide class object instance variable first (self value), which is suited automatically when calling method from instance object

```<code>sample_list.add_tail_node(sample_list, "b")
</code>```

This will actually process add_tail_node method on a class itself, not it's  instance

Body:
I am just getting started with linked lists, and I wrote some basic functions with a linked list class and node objects. When calling a function, it seems that I have to enter in the linked list object twice and I think I'm doing something wrong. To add a new node with value "b" to the tail, I have to call
sample_list.add_tail_node(sample_list, "b"), when I think it is supposed to be sample_list.add_tail_node("b"), because what is the point of specifying sample_list twice

class LinkedList:

def __init__(self):
    self.head = None

def add_tail_node(self, val: int):
    node = self.head
    while True:
        if node.next is None:
            node.next = Node(val)
            break
        node = node.next

class Node:
def __init__(self, val):
    self.val = val
    self.next = None
sample_list = LinkedList
sample_list.head = Node("a")
sample_list.add_tail_node(sample_list, "b")

Body:
You are assigning class reference to a variable here

sample_list = LinkedList

When you need to call a class, so it creates a instance

sample_list = LinkedList()

For better undersanding

When you are calling

sample_list.head = Node("a")

You are actualy assigning head to a class itself

And when you are calling object method using class, you need to provide class object instance variable first (self value), which is suited automatically when calling method from instance object

sample_list.add_tail_node(sample_list, "b")

This will actually process add_tail_node method on a class itself, not it's  instance