问:
Swift UITableViewCell - Cell Image changes if I scroll down too fast, but only on the first attempt
I am parsing a JSON within my viewDidLoad method. One of the keys within this JSON is the image URL, which goes into a a string array called "allCImages"

This is just a string. Therefore to populate the image into the cell, in my cellForRowAt method, I have the following:

```<code>cell.vcCellImage.downloadImage(from: allCImages[indexPath.section])
</code>```

Note: vcCellImage is the IBOutlet of my cell image view.

The "downloadImage" method is part of the following extension:

```<code>extension UIImageView {
    func downloadImage(from imgURL: String!) {
        let theUrl = URLRequest(url: URL(string: imgURL)!)

        // set initial image to nil so it doesn't use the image from a reused cell
        image = nil

        // check if the image is already in the cache
        if let imageToCache = vc1ImageCache.object(forKey: imgURL! as NSString) {
            self.image = imageToCache
            print("Image is in Cache")
            return
        }

        // download the image asynchronously
        let task = URLSession.shared.dataTask(with: theUrl) { (data, response, error) in
            if error != nil {
                print(error!)
                return
            }

            DispatchQueue.main.async {
                // create UIImage
                let imageToCache = UIImage(data: data!)
                // add image to cache
                vc1ImageCache.setObject(imageToCache!, forKey: imgURL! as NSString)
                self.image = imageToCache
            }
        }

        task.resume()
    }
</code>```

This is working almost perfectly. For example:

1) If I scroll down my tableview slowly, all the cells contain the correct image

2) If I scroll up my tableview, slowly or quickly, all the cells contain the correct image. This is proven by the fact that my console is printing the following:

Image is in Cache

Image is in Cache

Image is in Cache

I.e, the tableview is getting my image from the cache (since to scroll up, I must have scrolled down before)

3) The issue is if I scroll down my tableview really quickly, on the first attempt. Since the image has not cached yet, the cell will display the wrong image, before changing to the correct image. Classic problem

Therefore I am missing this small piece of logic. How to resolve this?

EDIT: I tried this but the issue remains:

class VCTableViewCell: UITableViewCell {

override func prepareForReuse() {
    super.prepareForReuse()
    vcCellImage.image = nil
}

答:
I have faced the similar issue.
I have fixed this issue by cancelling the image request in the prepareForReuse method.
Can you try the same?

Body:
I am parsing a JSON within my viewDidLoad method. One of the keys within this JSON is the image URL, which goes into a a string array called "allCImages"

This is just a string. Therefore to populate the image into the cell, in my cellForRowAt method, I have the following:

cell.vcCellImage.downloadImage(from: allCImages[indexPath.section])

Note: vcCellImage is the IBOutlet of my cell image view.

The "downloadImage" method is part of the following extension:

extension UIImageView {
    func downloadImage(from imgURL: String!) {
        let theUrl = URLRequest(url: URL(string: imgURL)!)

        // set initial image to nil so it doesn't use the image from a reused cell
        image = nil

        // check if the image is already in the cache
        if let imageToCache = vc1ImageCache.object(forKey: imgURL! as NSString) {
            self.image = imageToCache
            print("Image is in Cache")
            return
        }

        // download the image asynchronously
        let task = URLSession.shared.dataTask(with: theUrl) { (data, response, error) in
            if error != nil {
                print(error!)
                return
            }

            DispatchQueue.main.async {
                // create UIImage
                let imageToCache = UIImage(data: data!)
                // add image to cache
                vc1ImageCache.setObject(imageToCache!, forKey: imgURL! as NSString)
                self.image = imageToCache
            }
        }

        task.resume()
    }

This is working almost perfectly. For example:

1) If I scroll down my tableview slowly, all the cells contain the correct image

2) If I scroll up my tableview, slowly or quickly, all the cells contain the correct image. This is proven by the fact that my console is printing the following:

Image is in Cache

Image is in Cache

Image is in Cache

I.e, the tableview is getting my image from the cache (since to scroll up, I must have scrolled down before)

3) The issue is if I scroll down my tableview really quickly, on the first attempt. Since the image has not cached yet, the cell will display the wrong image, before changing to the correct image. Classic problem

Therefore I am missing this small piece of logic. How to resolve this?

EDIT: I tried this but the issue remains:

class VCTableViewCell: UITableViewCell {

override func prepareForReuse() {
    super.prepareForReuse()
    vcCellImage.image = nil
}


来源: stackexchange

问:
SimpleXML returns combined XML content
I have following code

public function returnArrayOfXmlElements(string $xml_path, string $element_key)
        {

```<code>        // Variables
        $this->simplexml_array    = (array)$this->returnSimpleXmlObject($xml_path);

        // Variables With Dependencies
        $this->xml_elements       = $this->simplexml_array[$element_key];

        foreach ($this->xml_elements as $this->array_key => $this->array_value) {

            $this->xml_elements_rectified[] = (array)$this->array_value;

        }

        return $this->xml_elements_rectified;

    }
</code>```

When I try this,

```<code>switch ($menu_name) {

            case 'secondary':

                    // Variables
                    $this->menu_directory    = constant('ENVIRONMENT_DIRECTORY_FRONTEND_MENU_SECONDARY');
                    $this->request_uri       = (empty($_GET['request']) !== TRUE ? $_GET['request'] : constant('SETTING_TEMPLATE_DEFAULT'));

                    // Variables With Dependencies
                    $this->section_name      = strtolower(substr($this->request_uri, 0, strpos($this->request_uri, '/')));
                    $this->menu_file         = $this->section_name.'.xml';
                    $this->menu_data         = $this->library_xml->returnArrayOfXmlElements($this->menu_directory.$this->menu_file, 'item');

                    echo '
                        <ul menu-secondary>
                            <li class="icon"><icon id="section-'.$this->section_name.'"></icon></li>
                    ';

                        foreach ($this->menu_data as $this->array_key => $this->menu_information) {

                            // Variables
                            $this->item_hook    = $this->menu_information['hook'];
                            $this->item_name    = $this->menu_information['name'];

                            echo '<li><a href="'.$this->item_hook.'">'.$this->item_name.'</a></li>';

                        }

                    echo '
                        </ul>
                    ';

                break;

            default:

                    // Variables
                    $this->menu_directory      = constant('ENVIRONMENT_DIRECTORY_FRONTEND_MENU');
                    $this->menu_file           = 'main.xml';

                    // Variables With Dependencies
                    $this->menu_data           = $this->library_xml->returnArrayOfXmlElements($this->menu_directory.$this->menu_file, 'item');

                    echo '
                        <ul menu-main>
                            <li>polybotes</li>
                    ';

                        foreach ($this->menu_data as $this->array_key => $this->menu_information) {

                            // Variables
                            $this->item_hook    = $this->menu_information['hook'];
                            $this->item_name    = $this->menu_information['name'];

                            echo '<li><a href="'.$this->item_hook.'">'.$this->item_name.'</a></li>';

                        }

                    echo '
                        </ul>
                    ';

                break;
        }

    }
</code>```

$this->menu_data from the secondary switch contains data of both $xml1 and $xml2. How can I prevent this?Unsetting $xml1 does not solve the problem.

The XML files look like this:

$xml1:

```<code><?xml version="1.0" encoding="ISO-8859-1" ?>
<menu>

    <item>

        <name>Dashboard</name>
        <hook>/dashboard/view</hook>

    </item>

    <item>

        <name>Location</name>
        <hook>/location/list</hook>

    </item>

    <item>

        <name>Networks</name>
        <hook>/network/list</hook>

    </item>

    <item>

        <name>Devices</name>
        <hook>/device/list</hook>

    </item>

    <item>

        <name>Alarms & Events</name>
        <hook>/alarm/list</hook>

    </item>

</menu>
</code>```

$xml2:

```<code><?xml version="1.0" encoding="ISO-8859-1" ?>
<menu>

    <item>

        <name>Network List</name>
        <hook>/network/list</hook>

    </item>

    <item>

        <name>Add Network</name>
        <hook>/network/add</hook>

    </item>

</menu>
</code>```

Could you please help me or point me in the right direction? Thanks in advance.

答:
In your method returnArrayOfXmlElements you always seem to use $this->variableName, this can cause problems as it will retain data across method calls.

Unless you really need to retain this data, try removing the $this-> from each of the variables...

```<code>public function returnArrayOfXmlElements(string $xml_path, string $element_key) {

        // Variables
        $simplexml_array    = (array)$this->returnSimpleXmlObject($xml_path);

        // Variables With Dependencies
        $xml_elements       = $this->simplexml_array[$element_key];

        $xml_elements_rectified = [];

        foreach ($xml_elements as $this->array_key => $this->array_value) {

            $xml_elements_rectified[] = (array)$this->array_value;

        }

        return $xml_elements_rectified;

    }
</code>```

ContentLicense: CC BY-SA 4.0

Title: SimpleXML returns combined XML content

Body:
I have following code

public function returnArrayOfXmlElements(string $xml_path, string $element_key)
        {

        // Variables
        $this->simplexml_array    = (array)$this->returnSimpleXmlObject($xml_path);

        // Variables With Dependencies
        $this->xml_elements       = $this->simplexml_array[$element_key];

        foreach ($this->xml_elements as $this->array_key => $this->array_value) {

            $this->xml_elements_rectified[] = (array)$this->array_value;

        }

        return $this->xml_elements_rectified;

    }

When I try this,

switch ($menu_name) {

            case 'secondary':

                    // Variables
                    $this->menu_directory    = constant('ENVIRONMENT_DIRECTORY_FRONTEND_MENU_SECONDARY');
                    $this->request_uri       = (empty($_GET['request']) !== TRUE ? $_GET['request'] : constant('SETTING_TEMPLATE_DEFAULT'));

                    // Variables With Dependencies
                    $this->section_name      = strtolower(substr($this->request_uri, 0, strpos($this->request_uri, '/')));
                    $this->menu_file         = $this->section_name.'.xml';
                    $this->menu_data         = $this->library_xml->returnArrayOfXmlElements($this->menu_directory.$this->menu_file, 'item');

                    echo '

<icon id="section-'.$this->section_name.'"></icon>

                    ';

                        foreach ($this->menu_data as $this->array_key => $this->menu_information) {

                            // Variables
                            $this->item_hook    = $this->menu_information['hook'];
                            $this->item_name    = $this->menu_information['name'];

                            echo '
item_hook.'">'.$this->item_name.'
';

                        }

                    echo '

                    ';

                break;

            default:

                    // Variables
                    $this->menu_directory      = constant('ENVIRONMENT_DIRECTORY_FRONTEND_MENU');
                    $this->menu_file           = 'main.xml';

                    // Variables With Dependencies
                    $this->menu_data           = $this->library_xml->returnArrayOfXmlElements($this->menu_directory.$this->menu_file, 'item');

                    echo '

polybotes

                    ';

                        foreach ($this->menu_data as $this->array_key => $this->menu_information) {

                            // Variables
                            $this->item_hook    = $this->menu_information['hook'];
                            $this->item_name    = $this->menu_information['name'];

                            echo '
item_hook.'">'.$this->item_name.'
';

                        }

                    echo '

                    ';

                break;
        }

    }

$this->menu_data from the secondary switch contains data of both $xml1 and $xml2. How can I prevent this?Unsetting $xml1 does not solve the problem.

The XML files look like this:

$xml1:

<?xml version="1.0" encoding="ISO-8859-1" ?>
<menu>

    <item>

        <name>Dashboard</name>
        <hook>/dashboard/view</hook>

    </item>

    <item>

        <name>Location</name>
        <hook>/location/list</hook>

    </item>

    <item>

        <name>Networks</name>
        <hook>/network/list</hook>

    </item>

    <item>

        <name>Devices</name>
        <hook>/device/list</hook>

    </item>

    <item>

        <name>Alarms & Events</name>
        <hook>/alarm/list</hook>

    </item>

</menu>

$xml2:

<?xml version="1.0" encoding="ISO-8859-1" ?>
<menu>

    <item>

        <name>Network List</name>
        <hook>/network/list</hook>

    </item>

    <item>

        <name>Add Network</name>
        <hook>/network/add</hook>

    </item>

</menu>

Could you please help me or point me in the right direction? Thanks in advance.

Body:
In your method returnArrayOfXmlElements you always seem to use $this->variableName, this can cause problems as it will retain data across method calls.

Unless you really need to retain this data, try removing the $this-> from each of the variables...

public function returnArrayOfXmlElements(string $xml_path, string $element_key) {

        // Variables
        $simplexml_array    = (array)$this->returnSimpleXmlObject($xml_path);

        // Variables With Dependencies
        $xml_elements       = $this->simplexml_array[$element_key];

        $xml_elements_rectified = [];

        foreach ($xml_elements as $this->array_key => $this->array_value) {

            $xml_elements_rectified[] = (array)$this->array_value;

        }

        return $xml_elements_rectified;

    }


问:
How to convert rds mysql latin1 to utf8
I want to convert our production database from latin1 to utf8.
we are using amazon rds mysql.
Please provide step by step. Will there be any downtime?

```<code>ALTER DATABASE database_name CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci;

ALTER TABLE table_name CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
</code>```

i use above query to convert each table.

Is it good a way? I need to do one by one or is there any other way to do in one step?

答:
Change in PRODUCT server is always crucial. Lot of consideration need to take in concern before taking the final decision. The first question is -
is this really a show-stopper? or A dead lock situation? or Performance issue? If with all consideration you are decided that this is a must, some caution need to
perform to achieve the changes-

Step-1: Take a full database backup.

Step-2: Make sure the backup is restore-able. Make several copy of backup and preserve in different Server. This will help restore your OLD data in case of any accidental data lose.

Step-3: Make necessary changes to Development server first. Check your application performing as before without any issue specially where there are data access exist for the changed area.

Step-4: Check all database objects like (SP,FUNCTION) are using that table are still performing as expected.

Step-5: Better if you can engage some QA resource before make changes in LIVE environment.

Step-6: If all above steps goes fine, you can go for LIVE changes.

Step-7: Engage QA resource again to make sure LIVE changes are also applied without any issue.

Note: No significant downtime is required. But always it is best if you can keep stop database access from your application during the database changes. This make sure no data will hamper during insert/edit/delete data from application.

Title: How to convert rds mysql latin1 to utf8

Body:
I want to convert our production database from latin1 to utf8.
we are using amazon rds mysql.
Please provide step by step. Will there be any downtime?

ALTER DATABASE database_name CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci;

ALTER TABLE table_name CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;

i use above query to convert each table.

Is it good a way? I need to do one by one or is there any other way to do in one step?


问:
How to write to an Excel spreadsheet using Python?
I need to write some data from my program to an Excel spreadsheet. I've searched online and there seem to be many packages available (xlwt, XlsXcessive, openpyxl). Others suggest writing to a .csv file (never used CSV and don't really understand what it is).

The program is very simple. I have two lists (float) and three variables (strings). I don't know the lengths of the two lists and they probably won't be the same length.

I want the layout to be as in the picture below:

The pink column will have the values of the first list and the green column will have the values of the second list.

So what's the best way to do this?

I am running Windows 7 but I won't necessarily have Office installed on the computers running this program.

import xlwt

x=1
y=2
z=3

list1=[2.34,4.346,4.234]

book = xlwt.Workbook(encoding="utf-8")

sheet1 = book.add_sheet("Sheet 1")

sheet1.write(0, 0, "Display")
sheet1.write(1, 0, "Dominance")
sheet1.write(2, 0, "Test")

sheet1.write(0, 1, x)
sheet1.write(1, 1, y)
sheet1.write(2, 1, z)

sheet1.write(4, 0, "Stimulus Time")
sheet1.write(4, 1, "Reaction Time")

i=4

for n in list1:
    i = i+1
    sheet1.write(i, 0, n)

book.save("trial.xls")
```

I wrote this using all your suggestions. It gets the job done but it can be slightly improved.

How do I format the cells created in the for loop (list1 values) as scientific or number?

I do not want to truncate the values. The actual values used in the program would have around 10 digits after the decimal.

答:
You can try hfexcel Human Friendly object-oriented python library based on XlsxWriter:</p>

```<code>from hfexcel import HFExcel

hf_workbook = HFExcel.hf_workbook('example.xlsx', set_default_styles=False)

hf_workbook.add_style(
    "headline",
    {
       "bold": 1,
        "font_size": 14,
        "font": "Arial",
        "align": "center"
    }
)

sheet1 = hf_workbook.add_sheet("sheet1", name="Example Sheet 1")

column1, _ = sheet1.add_column('headline', name='Column 1', width=2)
column1.add_row(data='Column 1 Row 1')
column1.add_row(data='Column 1 Row 2')

column2, _ = sheet1.add_column(name='Column 2')
column2.add_row(data='Column 2 Row 1')
column2.add_row(data='Column 2 Row 2')

column3, _ = sheet1.add_column(name='Column 3')
column3.add_row(data='Column 3 Row 1')
column3.add_row(data='Column 3 Row 2')

# In order to get a row with coordinates:
# sheet[column_index][row_index] => row
print(sheet1[1][1].data)
assert(sheet1[1][1].data == 'Column 2 Row 2')

hf_workbook.save()
</code>```

Body:
I need to write some data from my program to an Excel spreadsheet. I've searched online and there seem to be many packages available (xlwt, XlsXcessive, openpyxl). Others suggest writing to a .csv file (never used CSV and don't really understand what it is).

The program is very simple. I have two lists (float) and three variables (strings). I don't know the lengths of the two lists and they probably won't be the same length.

I want the layout to be as in the picture below:

The pink column will have the values of the first list and the green column will have the values of the second list.

So what's the best way to do this?

I am running Windows 7 but I won't necessarily have Office installed on the computers running this program.

import xlwt

x=1
y=2
z=3

list1=[2.34,4.346,4.234]

book = xlwt.Workbook(encoding="utf-8")

sheet1 = book.add_sheet("Sheet 1")

sheet1.write(0, 0, "Display")
sheet1.write(1, 0, "Dominance")
sheet1.write(2, 0, "Test")

sheet1.write(0, 1, x)
sheet1.write(1, 1, y)
sheet1.write(2, 1, z)

sheet1.write(4, 0, "Stimulus Time")
sheet1.write(4, 1, "Reaction Time")

i=4

for n in list1:
    i = i+1
    sheet1.write(i, 0, n)

book.save("trial.xls")

I wrote this using all your suggestions. It gets the job done but it can be slightly improved.

How do I format the cells created in the for loop (list1 values) as scientific or number?

I do not want to truncate the values. The actual values used in the program would have around 10 digits after the decimal.

Body:
You can try hfexcel Human Friendly object-oriented python library based on XlsxWriter:

from hfexcel import HFExcel

hf_workbook = HFExcel.hf_workbook('example.xlsx', set_default_styles=False)

hf_workbook.add_style(
    "headline",
    {
       "bold": 1,
        "font_size": 14,
        "font": "Arial",
        "align": "center"
    }
)

sheet1 = hf_workbook.add_sheet("sheet1", name="Example Sheet 1")

column1, _ = sheet1.add_column('headline', name='Column 1', width=2)
column1.add_row(data='Column 1 Row 1')
column1.add_row(data='Column 1 Row 2')

column2, _ = sheet1.add_column(name='Column 2')
column2.add_row(data='Column 2 Row 1')
column2.add_row(data='Column 2 Row 2')

column3, _ = sheet1.add_column(name='Column 3')
column3.add_row(data='Column 3 Row 1')
column3.add_row(data='Column 3 Row 2')

# In order to get a row with coordinates:
# sheet[column_index][row_index] => row
print(sheet1[1][1].data)
assert(sheet1[1][1].data == 'Column 2 Row 2')

hf_workbook.save()


问:
How can I limit a html input box so that it only accepts numeric input?
I have an html input box, but only numeric data is data. How can I enforce that?</p>

答: Use java script function as a validator. Or you can get the jquery funcations as well.</p>

ContentLicense: CC BY-SA 3.0


问:
Web Form Fill via EXCEL VBA-Can't find ID or anything to fill form

Reference

<div class="GHNF1GMDGI"

Reference
```
</div>
</div>
</p>

<p>adress    date  html codes</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="text" class="GHNF1GMDGM" maxlength="64" style="width: 350px;"></code>```

I was trying to fill a web form using different class tag  etc.. but it could not fill the form and an error occurred object dosen't support this property or method.

I tried many different ways:

```<code>  Sub automaticformfilling()

    Dim ie As InternetExplorer
    Dim doc As MSHTML.HTMLDocument
    Set ie = CreateObject("internetexplorer.application")

    With ie
        .Visible = True
        .navigate "xxxxxx"

        'Wait for loading
        Do While .Busy
            DoEvents
        Loop

        Do While .readyState <> 4
            DoEvents
        Loop
    End With

    Set doc = ie.document
    Set fname = doc.getElementById("j_username")
    fname.Value = "xxxx"

    Set lastName = doc.getElementById("j_password")
    lastName.Value = "xxxx"

    doc.getElementsByName("btn_submit")(0).Click
    'Set doc = ie.document
    'Set invdate = doc.getElementsByClassName("GHNF1GMDEI")
    'invdate.Value = "25"
    Set refname = doc.getElementsByName("GHNF1GMDGM")
    '.doc.getElementsByClassName ("GHNF1GMDGM")
    refname.Value = "923456"

End Sub
</code>```

Please help me with this issue.

答:
Your current error is due to the fact:

```<code>Set refname = doc.getElementsByName("GHNF1GMDGM")
</code>```

is a collection, not a single element, so you can't then do:

```<code>refname.Value = "923456"
</code>```

You need to use an index e.g.

```<code>refname(0).Value = "923456"
</code>```

Beyond that, without url or html, can't say much about anything else that might be wrong.

Side note:

I would compress your two loops for page load into one:

```<code>While .Busy Or .readyState < 4: DoEvents: Wend
</code>```

Body:
Reference

<div class="GHNF1GMDGI"

Reference

adress    date  html codes

<input type="text" class="GHNF1GMDGM" maxlength="64" style="width: 350px;">

I was trying to fill a web form using different class tag  etc.. but it could not fill the form and an error occurred object dosen't support this property or method.

I tried many different ways:

  Sub automaticformfilling()

    Dim ie As InternetExplorer
    Dim doc As MSHTML.HTMLDocument
    Set ie = CreateObject("internetexplorer.application")

    With ie
        .Visible = True
        .navigate "xxxxxx"

        'Wait for loading
        Do While .Busy
            DoEvents
        Loop

        Do While .readyState <> 4
            DoEvents
        Loop
    End With

    Set doc = ie.document
    Set fname = doc.getElementById("j_username")
    fname.Value = "xxxx"

    Set lastName = doc.getElementById("j_password")
    lastName.Value = "xxxx"

    doc.getElementsByName("btn_submit")(0).Click
    'Set doc = ie.document
    'Set invdate = doc.getElementsByClassName("GHNF1GMDEI")
    'invdate.Value = "25"
    Set refname = doc.getElementsByName("GHNF1GMDGM")
    '.doc.getElementsByClassName ("GHNF1GMDGM")
    refname.Value = "923456"

End Sub

Please help me with this issue.

Body:
Your current error is due to the fact:

Set refname = doc.getElementsByName("GHNF1GMDGM")

is a collection, not a single element, so you can't then do:

refname.Value = "923456"

You need to use an index e.g.

refname(0).Value = "923456"

Beyond that, without url or html, can't say much about anything else that might be wrong.

Side note:

I would compress your two loops for page load into one:

While .Busy Or .readyState < 4: DoEvents: Wend


问:
Typescript: import express unexpected idenfitier with ts-node-dev
I am starting a new project with Typescript and i would like to make the node server with typescript using express. I've been following a tutorial about how to run a Typescript file without having to compile files in this link: https://medium.com/javascript-in-plain-english/typescript-with-node-and-express-js-why-when-and-how-eb6bc73edd5d.

The problem i am facing now is that when executing the script that runs ts-node-dev, it throws an error:

```<code>> vidursyn@0.0.0 server:start /home/oscar/Documents/vidursyn
> ts-node-dev --respawn --transpileOnly ./src/server/app.ts

Using ts-node version 7.0.1, typescript version 3.2.4
/home/oscar/Documents/vidursyn/src/server/app.ts:1
(function (exports, require, module, __filename, __dirname) { import express from "express";
                                                                     ^^^^^^^

SyntaxError: Unexpected identifier
    at new Script (vm.js:80:7)
    at createScript (vm.js:274:10)
    at Object.runInThisContext (vm.js:326:10)
    at Object.obj.(anonymous function) [as runInThisContext] (/home/oscar/Documents/vidursyn/node_modules/ts-node-dev/lib/hook.js:30:19)
    at Module._compile (internal/modules/cjs/loader.js:664:28)
    at Module._compile (/home/oscar/Documents/vidursyn/node_modules/source-map-support/source-map-support.js:517:25)
    at Module.m._compile (/tmp/ts-node-dev-hook-9240179406846312.js:56:25)
    at Module._extensions..js (internal/modules/cjs/loader.js:712:10)
    at require.extensions.(anonymous function) (/tmp/ts-node-dev-hook-9240179406846312.js:58:14)
    at Object.nodeDevHook [as .ts] (/home/oscar/Documents/vidursyn/node_modules/ts-node-dev/lib/hook.js:61:7)
[ERROR] 13:18:43 SyntaxError: Unexpected identifier
</code>```

The file's content is too simple, it goes like this:

```<code>import express         from "express";
import { environment } from "../../lib/environment";
import * as config     from "../../config.json";

const configServer = config[environment].server;
const app = express();

app.get("/", (request: express.Request, response: express.Response) => {
  response.end("Hello World");
});

app.listen(configServer.port, () => {
  console.log(`Server listening at port ${configServer.port}`);
});
</code>```

I've searched around stackoverflow and some other posts in the internet and they all suggest to add --module-experimental as a flag in the command, but even with that flag it still throws the same error, which is why i am making this question.

Just in case to see how the tsconfig.json looks like:

```<code>{
  "compileOnSave": false,
  "compilerOptions": {
    "allowSyntheticDefaultImports": true,
    "baseUrl": "./",
    "outDir": "./dist/out-tsc",
    "sourceMap": true,
    "declaration": false,
    "module": "es6",
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "importHelpers": true,
    "resolveJsonModule": true,
    "target": "es5",
    "typeRoots": [
      "node_modules/@types"
    ],
    "lib": [
      "es2018",
      "dom"
    ]
  }
}
</code>```

and package.json:

```<code>{
  "name": "ng-app",
  "version": "0.0.0",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng test/e2e",
    "server:start": "ts-node-dev --respawn --transpileOnly ./src/server/app.ts"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "~7.2.0",
    "@angular/common": "~7.2.0",
    "@angular/compiler": "~7.2.0",
    "@angular/core": "~7.2.0",
    "@angular/forms": "~7.2.0",
    "@angular/platform-browser": "~7.2.0",
    "@angular/platform-browser-dynamic": "~7.2.0",
    "@angular/router": "~7.2.0",
    "core-js": "^2.5.4",
    "rxjs": "~6.3.3",
    "tslib": "^1.9.0",
    "zone.js": "~0.8.26"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "~0.13.0",
    "@angular/cli": "~7.3.9",
    "@angular/compiler-cli": "~7.2.0",
    "@angular/language-service": "~7.2.0",
    "@types/express": "4.16.1",
    "@types/jasmine": "~2.8.8",
    "@types/jasminewd2": "~2.0.3",
    "@types/node": "~8.9.4",
    "codelyzer": "~4.5.0",
    "express": "4.17.0",
    "jasmine-core": "~2.99.1",
    "jasmine-spec-reporter": "~4.2.1",
    "karma": "~4.0.0",
    "karma-chrome-launcher": "~2.2.0",
    "karma-coverage-istanbul-reporter": "~2.0.1",
    "karma-jasmine": "~1.1.2",
    "karma-jasmine-html-reporter": "^0.2.2",
    "protractor": "~5.4.0",
    "ts-node": "~7.0.0",
    "ts-node-dev": "1.0.0-pre.39",
    "tslint": "~5.11.0",
    "typescript": "~3.2.2"
  }
}
</code>```

答: Set 'module' to 'commonjs' in your tsconfig.</p>

Body:
I am starting a new project with Typescript and i would like to make the node server with typescript using express. I've been following a tutorial about how to run a Typescript file without having to compile files in this link: https://medium.com/javascript-in-plain-english/typescript-with-node-and-express-js-why-when-and-how-eb6bc73edd5d.

The problem i am facing now is that when executing the script that runs ts-node-dev, it throws an error:

> vidursyn@0.0.0 server:start /home/oscar/Documents/vidursyn
> ts-node-dev --respawn --transpileOnly ./src/server/app.ts

Using ts-node version 7.0.1, typescript version 3.2.4
/home/oscar/Documents/vidursyn/src/server/app.ts:1
(function (exports, require, module, __filename, __dirname) { import express from "express";
                                                                     ^^^^^^^

SyntaxError: Unexpected identifier
    at new Script (vm.js:80:7)
    at createScript (vm.js:274:10)
    at Object.runInThisContext (vm.js:326:10)
    at Object.obj.(anonymous function) [as runInThisContext] (/home/oscar/Documents/vidursyn/node_modules/ts-node-dev/lib/hook.js:30:19)
    at Module._compile (internal/modules/cjs/loader.js:664:28)
    at Module._compile (/home/oscar/Documents/vidursyn/node_modules/source-map-support/source-map-support.js:517:25)
    at Module.m._compile (/tmp/ts-node-dev-hook-9240179406846312.js:56:25)
    at Module._extensions..js (internal/modules/cjs/loader.js:712:10)
    at require.extensions.(anonymous function) (/tmp/ts-node-dev-hook-9240179406846312.js:58:14)
    at Object.nodeDevHook [as .ts] (/home/oscar/Documents/vidursyn/node_modules/ts-node-dev/lib/hook.js:61:7)
[ERROR] 13:18:43 SyntaxError: Unexpected identifier

The file's content is too simple, it goes like this:

import express         from "express";
import { environment } from "../../lib/environment";
import * as config     from "../../config.json";

const configServer = config[environment].server;
const app = express();

app.get("/", (request: express.Request, response: express.Response) => {
  response.end("Hello World");
});

app.listen(configServer.port, () => {
  console.log(`Server listening at port ${configServer.port}`);
});

I've searched around stackoverflow and some other posts in the internet and they all suggest to add --module-experimental as a flag in the command, but even with that flag it still throws the same error, which is why i am making this question.

Just in case to see how the tsconfig.json looks like:

{
  "compileOnSave": false,
  "compilerOptions": {
    "allowSyntheticDefaultImports": true,
    "baseUrl": "./",
    "outDir": "./dist/out-tsc",
    "sourceMap": true,
    "declaration": false,
    "module": "es6",
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "importHelpers": true,
    "resolveJsonModule": true,
    "target": "es5",
    "typeRoots": [
      "node_modules/@types"
    ],
    "lib": [
      "es2018",
      "dom"
    ]
  }
}

and package.json:

{
  "name": "ng-app",
  "version": "0.0.0",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng test/e2e",
    "server:start": "ts-node-dev --respawn --transpileOnly ./src/server/app.ts"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "~7.2.0",
    "@angular/common": "~7.2.0",
    "@angular/compiler": "~7.2.0",
    "@angular/core": "~7.2.0",
    "@angular/forms": "~7.2.0",
    "@angular/platform-browser": "~7.2.0",
    "@angular/platform-browser-dynamic": "~7.2.0",
    "@angular/router": "~7.2.0",
    "core-js": "^2.5.4",
    "rxjs": "~6.3.3",
    "tslib": "^1.9.0",
    "zone.js": "~0.8.26"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "~0.13.0",
    "@angular/cli": "~7.3.9",
    "@angular/compiler-cli": "~7.2.0",
    "@angular/language-service": "~7.2.0",
    "@types/express": "4.16.1",
    "@types/jasmine": "~2.8.8",
    "@types/jasminewd2": "~2.0.3",
    "@types/node": "~8.9.4",
    "codelyzer": "~4.5.0",
    "express": "4.17.0",
    "jasmine-core": "~2.99.1",
    "jasmine-spec-reporter": "~4.2.1",
    "karma": "~4.0.0",
    "karma-chrome-launcher": "~2.2.0",
    "karma-coverage-istanbul-reporter": "~2.0.1",
    "karma-jasmine": "~1.1.2",
    "karma-jasmine-html-reporter": "^0.2.2",
    "protractor": "~5.4.0",
    "ts-node": "~7.0.0",
    "ts-node-dev": "1.0.0-pre.39",
    "tslint": "~5.11.0",
    "typescript": "~3.2.2"
  }
}


问:
How brush convert to color (UWP)?
I have convert "Windows.UI.Xaml.Media.Brush" to "Windows.UI.Color". But VS return error. Tell me please how can I do this conversion correctly?</p>

答:
You can convert Brush to color, but you have to write it explicitly.
To do so just do this:

```<code>StackPanel pane = new StackPanel()
{
Background = Background = new SolidColorBrush(new Windows.UI.Color() { A = 255, R = 25, B = 0, G = 0})
}
</code>```

This works for EVERY single UIElement as long as you assign the Background property properly.

Title: How brush convert to color (UWP)?

Body:
You can convert Brush to color, but you have to write it explicitly.
To do so just do this:

StackPanel pane = new StackPanel()
{
Background = Background = new SolidColorBrush(new Windows.UI.Color() { A = 255, R = 25, B = 0, G = 0})
}

This works for EVERY single UIElement as long as you assign the Background property properly.


问:
Clipping UIImageView if is moved out of CGRect
I want to clip an UIImageView if it moves out of given rect.

The image is moving across the screen by setting the frame, but I need to clip it when it moves out of a given fixed rect (say (0,0,650,650)).

答:
Did you try using the property clipsToBounds of UIView and setting it to YES as it says in Reference that

```<code> Setting this value to YES causes subviews to be clipped to the bounds of the receiver
</code>```

UPDATE

See if this SO question helps you

Proper use of UIRectClip to scale a UIImage down to icon size

Body:
Did you try using the property clipsToBounds of UIView and setting it to YES as it says in Reference that

 Setting this value to YES causes subviews to be clipped to the bounds of the receiver

UPDATE

See if this SO question helps you

Proper use of UIRectClip to scale a UIImage down to icon size


问:
Modifying class in Python using __eq__
I need to Add an eq method that returns True if coordinates refer to same point in the plane (i.e., have the same x and y coordinate) and am confused on how to do that.

I have tried some code using eq and I am still getting errors and I am not quite sure why.

```<code>class Coordinate(object):
        def __init__(self, x, y):
            self.x = x
            self.y = y
    def getX(self):
        # Getter method for a Coordinate object's x coordinate.
        # Getter methods are better practice than just
        # accessing an attribute directly
        return self.x
    def getY(self):
        # Getter method for a Coordinate object's y coordinate
        return self.y
    def __str__(self):
        return '<' + str(self.getX()) + ',' + str(self.getY()) + '>'
    def __eq__(Coordinate, otherPoint):
        if self.GetX() == otherPoint.getX()&& self.GetY() == otherPoint.getY()
            return True

x=5
y=5
</code>```

The expected output would return true if both coordinates were the same number and false if x and y were not the same numbers.

答:
Some issues/fixes in your code

You actually don't need GetX and GetY, you can refer the attributes x and y directly.

&& is not valid syntax in Python, instead you use and

The first argument of __eq__ will be self

You can use f-strings to format your string if you are using python3.6+, else you can use format strings

You can optionally raise a TypeError to ensure other is of type Coordinate

Hence the updated code will look like

```<code>class Coordinate(object):
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __str__(self):
        #Use a f-string to format your string representation
        return f'<{self.x},{self.x}>'

        #If python3.5 and below, you can use format string as below
        #return '<{},{}>'.format(self.x, self.y)

    def __eq__(self, other):
        #If other is not an instance of Coordinate, raise TypeError
        if not isinstance(other, Coordinate):
            raise TypeError('An instance of class Coordinate is expected')
        #Compare both coordinates and return True or False
        return self.x == other.x and self.y == other.y
</code>```

Then you can use the class like as follows

```<code>c1 = Coordinate(5,5)
c2 = Coordinate(6,6)

print(c1)
#<5,5>
print(c2)
#<6,6>
print(c1 == c1)
#True
print(c1 == c2)
#False
print(c1 == 1)
#TypeError: An instance of class Coordinate is expected
</code>```

Title: Modifying class in Python using __eq__

Body:
I need to Add an eq method that returns True if coordinates refer to same point in the plane (i.e., have the same x and y coordinate) and am confused on how to do that.

I have tried some code using eq and I am still getting errors and I am not quite sure why.

class Coordinate(object):
        def __init__(self, x, y):
            self.x = x
            self.y = y
    def getX(self):
        # Getter method for a Coordinate object's x coordinate.
        # Getter methods are better practice than just
        # accessing an attribute directly
        return self.x
    def getY(self):
        # Getter method for a Coordinate object's y coordinate
        return self.y
    def __str__(self):
        return '<' + str(self.getX()) + ',' + str(self.getY()) + '>'
    def __eq__(Coordinate, otherPoint):
        if self.GetX() == otherPoint.getX()&& self.GetY() == otherPoint.getY()
            return True

x=5
y=5

The expected output would return true if both coordinates were the same number and false if x and y were not the same numbers.

Body:
Some issues/fixes in your code

You actually don't need GetX and GetY, you can refer the attributes x and y directly.

&& is not valid syntax in Python, instead you use and

The first argument of __eq__ will be self

You can use f-strings to format your string if you are using python3.6+, else you can use format strings

You can optionally raise a TypeError to ensure other is of type Coordinate

Hence the updated code will look like

class Coordinate(object):
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __str__(self):
        #Use a f-string to format your string representation
        return f'<{self.x},{self.x}>'

        #If python3.5 and below, you can use format string as below
        #return '<{},{}>'.format(self.x, self.y)

    def __eq__(self, other):
        #If other is not an instance of Coordinate, raise TypeError
        if not isinstance(other, Coordinate):
            raise TypeError('An instance of class Coordinate is expected')
        #Compare both coordinates and return True or False
        return self.x == other.x and self.y == other.y

Then you can use the class like as follows

c1 = Coordinate(5,5)
c2 = Coordinate(6,6)

print(c1)
#<5,5>
print(c2)
#<6,6>
print(c1 == c1)
#True
print(c1 == c2)
#False
print(c1 == 1)
#TypeError: An instance of class Coordinate is expected


答:
```<code>>>> class Coordinate:
...     def __init__(self, x, y):
...         self.x = x
...         self.y = y
...     def __eq__(self, other):
...         if not isinstance(other, Coordinate):
...             raise TypeError('You can compare a Coordinate with only another Coordinate')
...         return self.x == other.x and self.y == other.y
...
>>> Coordinate(1,2) == Coordinate(1,2)
True
>>> Coordinate(1,2) == Coordinate(1,3)
False
>>> Coordinate(1,2) == 'Hello'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 7, in __eq__
TypeError: You can compare a Coordinate with only another Coordinate
>>>
</code>```

Title: Modifying class in Python using __eq__


问:
CRTP - Is it possible to make an abstract base class?
I'm implementing a static polymorphism:

```<code>template<typename T>
class Base {
public:
    void method() {
         // do something
         impl();
         // do something else
    }
    void impl() { // intended to be private
        static_cast<T*>(this)->impl();
    }
};

class Derived : public Base<Derived> {
public:
     void impl() { // intended to be private
     }
};
</code>```

This code is a static implementation of a dynamic polymorphic classes where void impl() was pure virtual. So the base class was abstract.

Now these classes implement static polymorphism and therefore don't have pure virtual functions.

Is it possible to make Base class abstract, so that objects of this class can't be created?

答:
You can use a protected destructor and constructors:

```<code>template<typename T>
class Base {
public:
    void method() {
         // do something
         impl();
         // do something else
    }
    void impl() { // intended to be private
        static_cast<T*>(this)->impl();
    }

protected:
    Base() = default;
    ~Base() = default;

    // If you don't want to implement proper copying/moving:
    // Base(const Base&) = delete;
    // Base(Base&&) = delete;
    // Base& operator=(const Base&) = delete;
    // Base& operator=(Base&&) = delete;
};
</code>```

This will even disallow a derived class's member functions to create base class objects, as well as trying to delete a pointer whose static type is Base<T>.

Body:
I'm implementing a static polymorphism:

template<typename T>
class Base {
public:
    void method() {
         // do something
         impl();
         // do something else
    }
    void impl() { // intended to be private
        static_cast<T*>(this)->impl();
    }
};

class Derived : public Base<Derived> {
public:
     void impl() { // intended to be private
     }
};

This code is a static implementation of a dynamic polymorphic classes where void impl() was pure virtual. So the base class was abstract.

Now these classes implement static polymorphism and therefore don't have pure virtual functions.

Is it possible to make Base class abstract, so that objects of this class can't be created?

Body:
You can use a protected destructor and constructors:

template<typename T>
class Base {
public:
    void method() {
         // do something
         impl();
         // do something else
    }
    void impl() { // intended to be private
        static_cast<T*>(this)->impl();
    }

protected:
    Base() = default;
    ~Base() = default;

    // If you don't want to implement proper copying/moving:
    // Base(const Base&) = delete;
    // Base(Base&&) = delete;
    // Base& operator=(const Base&) = delete;
    // Base& operator=(Base&&) = delete;
};

This will even disallow a derived class's member functions to create base class objects, as well as trying to delete a pointer whose static type is Base<T>.


问:
Find duplicate files selected in FileDialog
I am creating a function that finds for duplicate files selected with FileDialog, this is what I did:

Since the Collection FileDialogSelectedItems is read-only I search for a function to get a hash and converted the collection to an Array

```<code>Dim FilesArray(), ArraySHA(), FilteredArray() as String
set fdg = Application.FileDialog(3)

With fdg
.....
If .show = -1 then
   ReDim ArraySHA(fdg.SelectedItems.Count)
   For i = 1 to fdg.SelectedItems.Count
      ArraySHA(i) = FileToSHA256(fdg.SelectedItems.Item(i)) '' New array with hashes
   Next i
</code>```

Then I used another function to filter duplicates in the ArraySHA

```<code>   FilteredArray = FilterWords(ArraySHA)
</code>```

Now I have an array with the unique hashes, but I need to have the selectedItems (filepaths) so I can import them without duplicates.

Thank you very much

Edit: I created a dictionary based on the SelectedItems Collection, adding each item only if it is not already there

```<code>    For i = 1 To fdg.SelectedItems.Count
        SHA = FileToSHA256(fdg.SelectedItems.Item(i))
        If Not dict.Exists(SHA) Then
                dict.Add SHA, fdg.SelectedItems.Item(i)
        End if
    Next i
</code>```

Now I have the hashes that correspond to only one file, which is its key value

```<code>   For Each key In dict.keys
        UniqueValue = dict(key)
        '
        'do something with each unique value (which is the filepath)
        '
   Next key
</code>```

Body:
I am creating a function that finds for duplicate files selected with FileDialog, this is what I did:

Since the Collection FileDialogSelectedItems is read-only I search for a function to get a hash and converted the collection to an Array

Dim FilesArray(), ArraySHA(), FilteredArray() as String
set fdg = Application.FileDialog(3)

With fdg
.....
If .show = -1 then
   ReDim ArraySHA(fdg.SelectedItems.Count)
   For i = 1 to fdg.SelectedItems.Count
      ArraySHA(i) = FileToSHA256(fdg.SelectedItems.Item(i)) '' New array with hashes
   Next i

Then I used another function to filter duplicates in the ArraySHA

   FilteredArray = FilterWords(ArraySHA)

Now I have an array with the unique hashes, but I need to have the selectedItems (filepaths) so I can import them without duplicates.

Thank you very much

Edit: I created a dictionary based on the SelectedItems Collection, adding each item only if it is not already there

    For i = 1 To fdg.SelectedItems.Count
        SHA = FileToSHA256(fdg.SelectedItems.Item(i))
        If Not dict.Exists(SHA) Then
                dict.Add SHA, fdg.SelectedItems.Item(i)
        End if
    Next i

Now I have the hashes that correspond to only one file, which is its key value

   For Each key In dict.keys
        UniqueValue = dict(key)
        '
        'do something with each unique value (which is the filepath)
        '
   Next key


问:
Can I run Xtrabackup directly on one of the members in a Galera cluster?
I have a Galera cluster (MySQL) consisting of three nodes and am currently relying on mysqldump for backup. This is cumbersome, to say the least, as the database has grown over the years and is now approaching 20 GiB and mysqldump takes roughly half an hour to do its thing.

Percona xtrabackup seems to be promising and I have tried it out on a copy of the database on a single node with very positive results, where backup time is radically reduced.

What I have not been able to find out is if it is OK to install xtrabackup on one of the nodes (preferably the one running mysqldump today) and run that on the cluster database? I have read quite a lot on xtrabackup but nowhere have I found any information about any risks with running it on one of the cluster members.

答:
I can't think of any risk.

However, there may be an even faster way...

Plan A:

Use a 4th machine to run the backup script.  Or, at least, write the dump to a 4th machine.  Any dump program is I/O-heavy, probably even I/O-bound.  By writing the dump on another machine, you offload the Galera node's I/O.

I assume you take the node out of the cluster during the backup?  And have gcache big enough so that it does an IST, not an SST, to resync?

Plan B:

Carrying things a step further, use 4 nodes instead of 3.  That way, having a node offline has less impact and less exposure.

Plan C:

Use a 4th machine as a Slave to one of the nodes.

Questions... What is the geographical distribution of the nodes?  If all three are currently sitting together, think about tornados, earthquakes, floods, etc.

What is the purpose of the backup?  Will the backup data be geographically remote?  (Note: that will add some delay to the backup method.)


问:
How to Insert an array of input field that is type text into database
I am currently working in a Evaluation system. I have a problem about the comment feature. The input field is dynamically created on how many personnel you will rate. I have an error when it comes in inserting an array of comment into may database and its type is text and in my database is varchar. when Im inserting my comment to database it is empty.

I already check if its under my form and I already check the name that I post and its all correct.

my input field

<input type="text" class="form-control" name="nComment[]">
```

<p>php code who process</p>

<pre class="lang-php prettyprint-override"><code>foreach($_POST['nPersonnelId'] as $i => $personnelId ){
        $rComment = $_POST['nComment'][$i];
        mysqli_query($conn,"INSERT INTO comment
                (personnelId,comment)
                VALUES ('$personnelId','$rComment')");
    }
</code>```

答:
You can serialize comment and save in database with:

```<code>$rComment = serialize($_POST['nComment'][$i]);
</code>```

https://www.php.net/manual/en/function.serialize.php

and then when you read from database use unserialize to back to array.

https://www.php.net/manual/en/function.unserialize.php

Body:
I am currently working in a Evaluation system. I have a problem about the comment feature. The input field is dynamically created on how many personnel you will rate. I have an error when it comes in inserting an array of comment into may database and its type is text and in my database is varchar. when Im inserting my comment to database it is empty.

I already check if its under my form and I already check the name that I post and its all correct.

my input field

<input type="text" class="form-control" name="nComment[]">

php code who process

foreach($_POST['nPersonnelId'] as $i => $personnelId ){
        $rComment = $_POST['nComment'][$i];
        mysqli_query($conn,"INSERT INTO comment
                (personnelId,comment)
                VALUES ('$personnelId','$rComment')");
    }

Body:
You can serialize comment and save in database with:

$rComment = serialize($_POST['nComment'][$i]);

https://www.php.net/manual/en/function.serialize.php

and then when you read from database use unserialize to back to array.

https://www.php.net/manual/en/function.unserialize.php


问:
Simplest way to separate reusable code in XCode 4 for iOS? (library, project, etc)
I'd like to separate reusable code in Xcode 4 as a separate project/library/something else. The reusable code in this case is a game engine, and the main project is a game itself. Idea is to make the game engine code easy to use in the future projects.

Xcode 4 lets me create a blank project or a static library for iOS. Which one would be preferred (or would something else work better?) under KISS principle? I just want to separate two logical set of files into two projects (it's ok if one is a child of another), and to be able to compile them at the same time. I don't have a need for obfuscation and I've heard that with a static library one has to worry for which architecture it was built for, which sounds like an overkill.

I feel that a blank project might be better way to go than the static library, but I don't have any practical experience with this. Any preferences and why?

答: Just create two projects. Add the dependent project into the main project. The Click on the Main XCode Project, Go to the Build Phases Tab, Under the "Target Dependencies" section click + sign and add the second project. </p>


问:
How can I refactor this ASYNC call in my react component to make it more readable?
I want my component to fetch an array of objects from the server. Each object is a message with author, body and date. I then want to render these messages in my react component.

My react component currently fetches data from the server before mounting. It will then store this message list in the redux state.|

I'm sure there's a better way of writing this code.
1. Can I place the fetch request in either the Action or Reducer file?
2. Can I write a function in the component to make the async call?

```<code>import React, { Component } from 'react';
import Message from '../components/message.jsx';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
// Actions
import { fetchMessages } from '../actions/actions_index.js';

class MessageList extends Component {
  constructor(props) {
    super(props)
  }

  componentWillMount() {
    fetch('https://wagon-chat.herokuapp.com/general/messages')
        .then(response => response.json(),
          error => console.log('An error occured receiving messages', error))
        .then((data) => {
          this.props.fetchMessages(data.messages);
        });
  }

  render() {
    return (
      <div className="message-list">
        {this.props.messageList.map( (message, index) => { return <Message key={index} message={message}/> })}
      </div>
    )
  }
}

function mapStateToProps(state) {
  return {
    messageList: state.messageList
  }
}

function mapDispatchToProps(dispatch) {
  return bindActionCreators(
    { fetchMessages: fetchMessages },
    dispatch
  )
}

export default connect(mapStateToProps, mapDispatchToProps)(MessageList);

</code>```

答:
Can I place the fetch request in either the Action or Reducer file?

The fetch request should be placed in action creator. Where the retrieved data will be dispatched to reducer later to manipulate the data, and lastly update the store to show on UI. Here's simple flow for most of react-redux app.

UI -> Action creator (calling request, saga etc..) -> reducer -> store -> UI

Can I write a function in the component to make the async call?

Yes, this should be called action creator, and you can see actions.js below for more reference.

I think you can safely follow this sample pattern where most tutorials out there apply. I'm assuming all files listed here are in the same directory.

constant.js

```<code>const MESSAGE_FETCH__SUCCESS = 'MESSAGE/FETCH__SUCCESS'
const MESSAGE_FETCH__ERROR = 'MESSAGE/FETCH__ERROR'
export {
  MESSAGE_FETCH__SUCCESS,
  MESSAGE_FETCH__ERROR
}
</code>```

actions.js

```<code>import {
  MESSAGE_FETCH__SUCCESS,
  MESSAGE_FETCH__ERROR
} from './constant';

const fetchMessageError = () => ({
  type: MESSAGE_FETCH__ERROR
})

const fetchMessageSuccess = data => ({
  type: MESSAGE_FETCH__SUCCESS,
  payload: data
})

const fetchMessages = () => {
  const data = fetch(...);

  // if error
  if (data.error)
    fetchMessageError();
  else fetchMessageSuccess(data.data);
}

export {
  fetchMessages
}
</code>```

reducers.js

```<code>import {
  MESSAGE_FETCH__SUCCESS,
  MESSAGE_FETCH__ERROR
} from './constant';

const INIT_STATE = {
  messageList: []
}

export default function( state = INIT_STATE, action ) {
  switch(action.type) {
    case MESSAGE_FETCH__SUCCESS:
      return {
        ...state,
        messageList: action.payload
      }
    case MESSAGE_FETCH__ERROR:
      // Do whatever you want here for an error case
      return {
        ...state
      }
    default:
      return state;
  }
}
</code>```

index.js

Please read the comment I noted

```<code>import React, { Component } from 'react';
import Message from '../components/message.jsx';
import { connect } from 'react-redux';

// Actions
import { fetchMessages } from './actions';

class MessageList extends Component {
  /* If you don't do anything in the constructor, it's okay to remove calling `constructor(props)`
  */
  //constructor(props) {
  //    super(props)
  //}

  // I usually put this async call in `componentDidMount` method
  componentWillMount() {
    this.props.fetchMessage();
  }

  render() {
    return (
      <div className="message-list">
        {
          /* Each message should have an unique id so they can be used
          for `key` index. Do not use `index` as an value to `key`.
See this useful link for more reference: https://stackoverflow.com/questions/28329382/understanding-unique-keys-for-array-children-in-react-js
          */
          this.props.messageList.map( message => <Message key={message.id} message={message}/> )
        }
      </div>
    )
  }
}

function mapStateToProps(state) {
  return {
    messageList: state.messageList
  }
}

export default connect(mapStateToProps, {
  fetchMessages
})(MessageList);
</code>```

Body:
I want my component to fetch an array of objects from the server. Each object is a message with author, body and date. I then want to render these messages in my react component.

My react component currently fetches data from the server before mounting. It will then store this message list in the redux state.|

I'm sure there's a better way of writing this code.
1. Can I place the fetch request in either the Action or Reducer file?
2. Can I write a function in the component to make the async call?

import React, { Component } from 'react';
import Message from '../components/message.jsx';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
// Actions
import { fetchMessages } from '../actions/actions_index.js';

class MessageList extends Component {
  constructor(props) {
    super(props)
  }

  componentWillMount() {
    fetch('https://wagon-chat.herokuapp.com/general/messages')
        .then(response => response.json(),
          error => console.log('An error occured receiving messages', error))
        .then((data) => {
          this.props.fetchMessages(data.messages);
        });
  }

  render() {
    return (

        {this.props.messageList.map( (message, index) => { return <Message key={index} message={message}/> })}

    )
  }
}

function mapStateToProps(state) {
  return {
    messageList: state.messageList
  }
}

function mapDispatchToProps(dispatch) {
  return bindActionCreators(
    { fetchMessages: fetchMessages },
    dispatch
  )
}

export default connect(mapStateToProps, mapDispatchToProps)(MessageList);

Body:
Can I place the fetch request in either the Action or Reducer file?

The fetch request should be placed in action creator. Where the retrieved data will be dispatched to reducer later to manipulate the data, and lastly update the store to show on UI. Here's simple flow for most of react-redux app.

UI -> Action creator (calling request, saga etc..) -> reducer -> store -> UI

Can I write a function in the component to make the async call?

Yes, this should be called action creator, and you can see actions.js below for more reference.

I think you can safely follow this sample pattern where most tutorials out there apply. I'm assuming all files listed here are in the same directory.

constant.js

const MESSAGE_FETCH__SUCCESS = 'MESSAGE/FETCH__SUCCESS'
const MESSAGE_FETCH__ERROR = 'MESSAGE/FETCH__ERROR'
export {
  MESSAGE_FETCH__SUCCESS,
  MESSAGE_FETCH__ERROR
}

actions.js

import {
  MESSAGE_FETCH__SUCCESS,
  MESSAGE_FETCH__ERROR
} from './constant';

const fetchMessageError = () => ({
  type: MESSAGE_FETCH__ERROR
})

const fetchMessageSuccess = data => ({
  type: MESSAGE_FETCH__SUCCESS,
  payload: data
})

const fetchMessages = () => {
  const data = fetch(...);

  // if error
  if (data.error)
    fetchMessageError();
  else fetchMessageSuccess(data.data);
}

export {
  fetchMessages
}

reducers.js

import {
  MESSAGE_FETCH__SUCCESS,
  MESSAGE_FETCH__ERROR
} from './constant';

const INIT_STATE = {
  messageList: []
}

export default function( state = INIT_STATE, action ) {
  switch(action.type) {
    case MESSAGE_FETCH__SUCCESS:
      return {
        ...state,
        messageList: action.payload
      }
    case MESSAGE_FETCH__ERROR:
      // Do whatever you want here for an error case
      return {
        ...state
      }
    default:
      return state;
  }
}

index.js

Please read the comment I noted

import React, { Component } from 'react';
import Message from '../components/message.jsx';
import { connect } from 'react-redux';

// Actions
import { fetchMessages } from './actions';

class MessageList extends Component {
  /* If you don't do anything in the constructor, it's okay to remove calling `constructor(props)`
  */
  //constructor(props) {
  //    super(props)
  //}

  // I usually put this async call in `componentDidMount` method
  componentWillMount() {
    this.props.fetchMessage();
  }

  render() {
    return (
      <div className="message-list">
        {
          /* Each message should have an unique id so they can be used
          for `key` index. Do not use `index` as an value to `key`.
See this useful link for more reference: https://stackoverflow.com/questions/28329382/understanding-unique-keys-for-array-children-in-react-js
          */
          this.props.messageList.map( message => <Message key={message.id} message={message}/> )
        }
      </div>
    )
  }
}

function mapStateToProps(state) {
  return {
    messageList: state.messageList
  }
}

export default connect(mapStateToProps, {
  fetchMessages
})(MessageList);


问:
Can you only have one string after !=
I'm just writing some small code and I'm not able to make this work, I am only able to have one string which is e.g boy or girl but I would like to have both, do I have to make a separate elif statement or can I somehow put girl in there as well

    gender = input("Are you a boy or a girl? : ")

    if (gender != "boy"):

    print("Get out of here you mutant")

    exit()
```

答:
You would need to have 3 conditions:

```<code>if gender == 'boy':
    print ('You are a boy')
elif gender == 'girl':
    print ('You are a girl')
else:
    print("Get out of here you mutant")
</code>```

Or you can do like that:

```<code>if gender in ('boy', 'girl'):
    print('You are a {}'.format(gender)
else:
    print("Get out of here you mutant")
</code>```

In the second script you check if gender is a girl or a boy and if so it puts gender variable in the print output string.

Title: Can you only have one string after !=

Body:
You would need to have 3 conditions:

if gender == 'boy':
    print ('You are a boy')
elif gender == 'girl':
    print ('You are a girl')
else:
    print("Get out of here you mutant")

Or you can do like that:

if gender in ('boy', 'girl'):
    print('You are a {}'.format(gender)
else:
    print("Get out of here you mutant")

In the second script you check if gender is a girl or a boy and if so it puts gender variable in the print output string.


答:
So many small mistakes ...

GetX is not the same as getX

an if statements needs a : at the end

the indentation of __init__ clause is wrong

&& does not exist in python, it's called and

the __eq__ function does not always return, it needs an else clause, or just return the boolean expression directly

the first argument of __eq__ needs to be self

class Coordinate(object):
    def __init__(self, x, y):
        self.x = x
        self.y = y
    def getX(self):
        # Getter method for a Coordinate object's x coordinate.
        # Getter methods are better practice than just
        # accessing an attribute directly
        return self.x
    def getY(self):
        # Getter method for a Coordinate object's y coordinate
        return self.y
    def __str__(self):
        return '<' + str(self.getX()) + ',' + str(self.getY()) + '>'
    def __eq__(self, otherPoint):
        return self.getX() == otherPoint.getX() and self.getY() == otherPoint.getY()
```

Title: Modifying class in Python using __eq__


问:
How to send email using Angular 7
How do I create an email service in Angular 7 that contains a method for sending out emails?

For example:

```<code>// email.service.ts
import { Injectable } from ‘@angular/core’;

@Injectable()

export class EmailService {

    constructor() { }

    // method to fetch data from server
    public sendEmail(): void {
       // logic to send email
      ...
    }
}
</code>```

I'm new to developing with Angular so any examples, use cases, and/or code snippets are greatly appreciated.

答:
You need to understand the nature of angular in the first place. But assuming that you're new to angular - you must understand that Angular is just a view front-end framework. So it has no capabilities to send emails on its own. To make angular transaction-capable, you need a backend system that angular can tell to send emails on its behalf.

This is achieved through Web API's. So you must create an API  where angular can inform the API to send emails. As far as my knowledge is concerned, this is the method I am aware is most widely used.

Title: How to send email using Angular 7

Body:
How do I create an email service in Angular 7 that contains a method for sending out emails?

For example:

// email.service.ts
import { Injectable } from ‘@angular/core’;

@Injectable()

export class EmailService {

    constructor() { }

    // method to fetch data from server
    public sendEmail(): void {
       // logic to send email
      ...
    }
}

I'm new to developing with Angular so any examples, use cases, and/or code snippets are greatly appreciated.


问:
A table's
 cannot have border, it seems, for IE 7, but I don't see in books that talks about
 border either?
This one will show border for Chrome, FF, IE 8 and 9, but it won't show a border for IE 7.

http://jsfiddle.net/y7HWr/10/

(which is to have a border for
).  So I think probably IE 7 is at fault?  Even though I don't see books talking about borders for
 elements (they talk about for
 elements usually), but really it should apply to most any elements?  (maybe except elements that doesn't make sense to have borders, such as <meta> or

答:
```<code>.end-of-category td { border: 6px solid #000 }
</code>```

Works in IE7 and IE6.

Title: A table's <tr> cannot have border, it seems, for IE 7, but I don't see in books that talks about <tr> border either?

Body:
.end-of-category td { border: 6px solid #000 }

Works in IE7 and IE6.


问:
Swift UITableViewCell - Cell Image changes if I scroll down too fast, but only on the first attempt
I am parsing a JSON within my viewDidLoad method. One of the keys within this JSON is the image URL, which goes into a a string array called "allCImages"

This is just a string. Therefore to populate the image into the cell, in my cellForRowAt method, I have the following:

```<code>cell.vcCellImage.downloadImage(from: allCImages[indexPath.section])
</code>```

Note: vcCellImage is the IBOutlet of my cell image view.

The "downloadImage" method is part of the following extension:

```<code>extension UIImageView {
    func downloadImage(from imgURL: String!) {
        let theUrl = URLRequest(url: URL(string: imgURL)!)

        // set initial image to nil so it doesn't use the image from a reused cell
        image = nil

        // check if the image is already in the cache
        if let imageToCache = vc1ImageCache.object(forKey: imgURL! as NSString) {
            self.image = imageToCache
            print("Image is in Cache")
            return
        }

        // download the image asynchronously
        let task = URLSession.shared.dataTask(with: theUrl) { (data, response, error) in
            if error != nil {
                print(error!)
                return
            }

            DispatchQueue.main.async {
                // create UIImage
                let imageToCache = UIImage(data: data!)
                // add image to cache
                vc1ImageCache.setObject(imageToCache!, forKey: imgURL! as NSString)
                self.image = imageToCache
            }
        }

        task.resume()
    }
</code>```

This is working almost perfectly. For example:

1) If I scroll down my tableview slowly, all the cells contain the correct image

2) If I scroll up my tableview, slowly or quickly, all the cells contain the correct image. This is proven by the fact that my console is printing the following:

Image is in Cache

Image is in Cache

Image is in Cache

I.e, the tableview is getting my image from the cache (since to scroll up, I must have scrolled down before)

3) The issue is if I scroll down my tableview really quickly, on the first attempt. Since the image has not cached yet, the cell will display the wrong image, before changing to the correct image. Classic problem

Therefore I am missing this small piece of logic. How to resolve this?

EDIT: I tried this but the issue remains:

class VCTableViewCell: UITableViewCell {

override func prepareForReuse() {
    super.prepareForReuse()
    vcCellImage.image = nil
}

答:
This occurs because of

1- cell dequeueing : cells are re-used inside the tableView

2- when you scroll before a request happens it may cause a new 1 with same url

Best option is using SDWebImage

Body:
I am parsing a JSON within my viewDidLoad method. One of the keys within this JSON is the image URL, which goes into a a string array called "allCImages"

This is just a string. Therefore to populate the image into the cell, in my cellForRowAt method, I have the following:

cell.vcCellImage.downloadImage(from: allCImages[indexPath.section])

Note: vcCellImage is the IBOutlet of my cell image view.

The "downloadImage" method is part of the following extension:

extension UIImageView {
    func downloadImage(from imgURL: String!) {
        let theUrl = URLRequest(url: URL(string: imgURL)!)

        // set initial image to nil so it doesn't use the image from a reused cell
        image = nil

        // check if the image is already in the cache
        if let imageToCache = vc1ImageCache.object(forKey: imgURL! as NSString) {
            self.image = imageToCache
            print("Image is in Cache")
            return
        }

        // download the image asynchronously
        let task = URLSession.shared.dataTask(with: theUrl) { (data, response, error) in
            if error != nil {
                print(error!)
                return
            }

            DispatchQueue.main.async {
                // create UIImage
                let imageToCache = UIImage(data: data!)
                // add image to cache
                vc1ImageCache.setObject(imageToCache!, forKey: imgURL! as NSString)
                self.image = imageToCache
            }
        }

        task.resume()
    }

This is working almost perfectly. For example:

1) If I scroll down my tableview slowly, all the cells contain the correct image

2) If I scroll up my tableview, slowly or quickly, all the cells contain the correct image. This is proven by the fact that my console is printing the following:

Image is in Cache

Image is in Cache

Image is in Cache

I.e, the tableview is getting my image from the cache (since to scroll up, I must have scrolled down before)

3) The issue is if I scroll down my tableview really quickly, on the first attempt. Since the image has not cached yet, the cell will display the wrong image, before changing to the correct image. Classic problem

Therefore I am missing this small piece of logic. How to resolve this?

EDIT: I tried this but the issue remains:

class VCTableViewCell: UITableViewCell {

override func prepareForReuse() {
    super.prepareForReuse()
    vcCellImage.image = nil
}


问:
Some text missing in jar executed file
After run my jar file some text are missing its appear,

Eg: in my gui have "admin" but in jar file its appear only "admi"

What is the reason for that?
Thank you for answer

答: JAR actually is a ZIP file. So it content can not match original code.</p>

Title: Some text missing in jar executed file


问:
Simple Serilog + ElasticSearch
This program doesn't post anything to ElasticSearch as seen from Kibana. Am I missing something?

```<code>using System;

using Serilog;
using Serilog.Sinks.Elasticsearch;

namespace DemoService
{
    class Program
    {
        static void Main(string[] args)
        {
            var loggerConfig = new LoggerConfiguration()
            .WriteTo.Elasticsearch(new ElasticsearchSinkOptions(new Uri("http://ipaddress:9200"))
            {
                AutoRegisterTemplate = true,
                AutoRegisterTemplateVersion = AutoRegisterTemplateVersion.ESv6
            });

            Log.Information("The time is {Now}", DateTime.Now);
        }
    }
}
</code>```

答:
I got it to work thus. </p>

```<code>       var log = new LoggerConfiguration()
        .WriteTo.Elasticsearch(new ElasticsearchSinkOptions(new Uri("http://ipaddress"))
        {
            AutoRegisterTemplate = true,
            //AutoRegisterTemplateVersion = AutoRegisterTemplateVersion.ESv6,
            FailureCallback = e => Console.WriteLine("Unable to submit event " + e.MessageTemplate),
            EmitEventFailure = EmitEventFailureHandling.WriteToSelfLog |
                                   EmitEventFailureHandling.WriteToFailureSink |
                                   EmitEventFailureHandling.RaiseCallback,
            FailureSink = new FileSink("./failures.txt", new JsonFormatter(),
            null)
        }
        ).CreateLogger();

        log.Information(new ApplicationException("This is working!").ToString());
</code>```

Title: Simple Serilog + ElasticSearch

Body:
This program doesn't post anything to ElasticSearch as seen from Kibana. Am I missing something?

using System;

using Serilog;
using Serilog.Sinks.Elasticsearch;

namespace DemoService
{
    class Program
    {
        static void Main(string[] args)
        {
            var loggerConfig = new LoggerConfiguration()
            .WriteTo.Elasticsearch(new ElasticsearchSinkOptions(new Uri("http://ipaddress:9200"))
            {
                AutoRegisterTemplate = true,
                AutoRegisterTemplateVersion = AutoRegisterTemplateVersion.ESv6
            });

            Log.Information("The time is {Now}", DateTime.Now);
        }
    }
}

Body:
I got it to work thus.

       var log = new LoggerConfiguration()
        .WriteTo.Elasticsearch(new ElasticsearchSinkOptions(new Uri("http://ipaddress"))
        {
            AutoRegisterTemplate = true,
            //AutoRegisterTemplateVersion = AutoRegisterTemplateVersion.ESv6,
            FailureCallback = e => Console.WriteLine("Unable to submit event " + e.MessageTemplate),
            EmitEventFailure = EmitEventFailureHandling.WriteToSelfLog |
                                   EmitEventFailureHandling.WriteToFailureSink |
                                   EmitEventFailureHandling.RaiseCallback,
            FailureSink = new FileSink("./failures.txt", new JsonFormatter(),
            null)
        }
        ).CreateLogger();

        log.Information(new ApplicationException("This is working!").ToString());


问:
SQL Join 2 tables with date difference
I have 2 tables, one of which is orders and the other one is receipts. The problem i am facing is that they dont have UID, the only thing they can be joined with is the date. Problem with that is, the date is the same, but the time difference between them is approx 30 seconds. My question is, is there any way i can join these 2 tables?

So, the 1st table is in the following format

```<code>|   date        | order | price |
|1/1/13 06:05:32|  tea  |   3   |
|1/2/13 07:04:24| coffee|   2   |
|4/3/13 13:31:23|  tea  |   3   |

</code>```

And the second table has this format

```<code>|   date        | order | quantity |
|1/1/13 06:05:42|  tea  |   3      |
|1/2/13 07:04:54| coffee|   2      |
|4/3/13 13:31:56|  tea  |   3      |

</code>```

My desired output is

```<code>|   date        | order | quantity |  price |
|1/1/13 06:05:42|  tea  |   3      |    3   |
|1/2/13 07:04:54| coffee|   2      |    2   |
|4/3/13 13:31:56|  tea  |   3      |    3   |

</code>```

Basically, my goal here is to combine these 2 tables so i can see the differences between them, but i dont have an idea how to join them without unique ID's, please help guys

答:
in sql server you can do something like this:

```<code>select *
from ( select *, convert(date, getdate()) as d1 from t1) as t1,
( select *, convert(date, getdate()) as d2 from t2) as t2
where t1.d1 = t2.d2
and t1.order = t2.order
</code>```

the point here is to convert date and time to only date and join the two tables

Title: SQL Join 2 tables with date difference

Body:
I have 2 tables, one of which is orders and the other one is receipts. The problem i am facing is that they dont have UID, the only thing they can be joined with is the date. Problem with that is, the date is the same, but the time difference between them is approx 30 seconds. My question is, is there any way i can join these 2 tables?

So, the 1st table is in the following format

|   date        | order | price |
|1/1/13 06:05:32|  tea  |   3   |
|1/2/13 07:04:24| coffee|   2   |
|4/3/13 13:31:23|  tea  |   3   |

And the second table has this format

|   date        | order | quantity |
|1/1/13 06:05:42|  tea  |   3      |
|1/2/13 07:04:54| coffee|   2      |
|4/3/13 13:31:56|  tea  |   3      |

My desired output is

|   date        | order | quantity |  price |
|1/1/13 06:05:42|  tea  |   3      |    3   |
|1/2/13 07:04:54| coffee|   2      |    2   |
|4/3/13 13:31:56|  tea  |   3      |    3   |

Basically, my goal here is to combine these 2 tables so i can see the differences between them, but i dont have an idea how to join them without unique ID's, please help guys

Body:
in sql server you can do something like this:

select *
from ( select *, convert(date, getdate()) as d1 from t1) as t1,
( select *, convert(date, getdate()) as d2 from t2) as t2
where t1.d1 = t2.d2
and t1.order = t2.order

the point here is to convert date and time to only date and join the two tables


问:
How can I get ambethia's captcha plugin to work in rails 3?
I have installed ambethia's captcha plugin as a plugin in my rails 3 app. When I put the <%= recaptcha_tags %> in my view, it prints this on the page:

```<code><script type="text/javascript" src="http://api.recaptcha.net/challenge?k=my_key&error=expression"></script> <noscript> <iframe src="http://api.recaptcha.net/noscript?k=my_other_key" height="300" width="500" frameborder="0"></iframe><br/> <textarea name="recaptcha_challenge_field" rows="3" cols="40"></textarea> <input type="hidden" name="recaptcha_response_field" value="manual_challenge"></noscript>
</code>```

Is there a way that I can make this work in rails 3? I'd appreciate any help.

答:
You already accepted an answer, however, I used this together with Devise and did not need to use raw - and yes, I am on Rails 3:

app/views/users/registrations/new.html.erb

```<code><h2>Sign up</h2>

<%= form_for(resource, :as => resource_name, :url => registration_path(resource_name)) do |f| %>
  <%= devise_error_messages! %>

  <p><%= f.label :email %><br />
  <%= f.text_field :email %></p>

  <p><%= f.label :password %><br />
  <%= f.password_field :password %></p>

  <p><%= f.label :password_confirmation %><br />
  <%= f.password_field :password_confirmation %></p>

  <p><%= recaptcha_tags %></p>

  <p><%= f.submit "Sign up" %></p>
<% end %>

<%= render :partial => "devise/shared/links" %>
</code>```

Rest of the code is here in an article: http://www.communityguides.eu/articles/10

ContentLicense: CC BY-SA 2.5

Body:
I have installed ambethia's captcha plugin as a plugin in my rails 3 app. When I put the <%= recaptcha_tags %> in my view, it prints this on the page:

 <textarea name="recaptcha_challenge_field" rows="3" cols="40"></textarea> <input type="hidden" name="recaptcha_response_field" value="manual_challenge">

Is there a way that I can make this work in rails 3? I'd appreciate any help.

Body:
You already accepted an answer, however, I used this together with Devise and did not need to use raw - and yes, I am on Rails 3:

app/views/users/registrations/new.html.erb

<h2>Sign up</h2>

<%= form_for(resource, :as => resource_name, :url => registration_path(resource_name)) do |f| %>
  <%= devise_error_messages! %>

  <p><%= f.label :email %><br />
  <%= f.text_field :email %></p>

  <p><%= f.label :password %><br />
  <%= f.password_field :password %></p>

  <p><%= f.label :password_confirmation %><br />
  <%= f.password_field :password_confirmation %></p>

  <p><%= recaptcha_tags %></p>

  <p><%= f.submit "Sign up" %></p>
<% end %>

<%= render :partial => "devise/shared/links" %>

Rest of the code is here in an article: http://www.communityguides.eu/articles/10


问:
Chromium hangs using the TestCafe Docker image
Attempting to run Chromium headless inside the testcafe/testcafe Docker image causes the browser to hang, no matter what options I've used. Here's what I have at the moment:

```<code>"browsers": {
    "path": "/usr/bin/chromium-browser",
    "cmd": "--headless --disable-gpu --no-sandbox"
}
</code>```

And the output after a few minutes:

```<code>e2e_1  | Using locally installed version of TestCafe.
e2e_1  | ERROR The HeadlessChrome 71.0.3578 / Linux 0.0.0 browser disconnected. This problem may appear when a browser hangs or is closed, or due to network issues.
e2e_1  |
e2e_1  | Type "testcafe -h" for help.
</code>```

This works fine if I remove the --headless, but then the browser is rendering into Xvfb instead of running headlessly.

Dockerfile:

```<code>FROM testcafe/testcafe

USER root

RUN apk --no-cache add \
    ffmpeg

RUN mkdir /home/e2e
WORKDIR /home/e2e
COPY . .
RUN chmod -R 757 /home/e2e

USER user

RUN npm install

EXPOSE 1337 1338

ENTRYPOINT ["/home/e2e/testcafe-docker.sh"]
</code>```

testcafe-docker.sh:

```<code>#!/bin/sh
XVFB_SCREEN_WIDTH=${SCREEN_WIDTH-1280}
XVFB_SCREEN_HEIGHT=${SCREEN_HEIGHT-720}

dbus-daemon --session --fork
Xvfb :1 -screen 0 "${XVFB_SCREEN_WIDTH}x${XVFB_SCREEN_HEIGHT}x24" >/dev/null 2>&1 &
export DISPLAY=:1.0
fluxbox >/dev/null 2>&1 &
testcafe --ports 1337,1338 "$@"
</code>```

.testcaferc.json:

```<code>{
    "browsers": "chromium --no-sandbox",
    "src": ["tests/*"],
    "reporter": "spec",
    "screenshotPath": "tmp/screenshots/",
    "screenshotPathPattern": "${DATE}_${TIME}/test-${TEST_INDEX}/${USERAGENT}/${FILE_INDEX}.png",
    "takeScreenshotsOnFails": true,
    "videoPath": "tmp/reports/screen-captures",
    "videoOptions": {
        "singleFile": true,
        "failedOnly": true,
        "pathPattern": "${TEST_INDEX}/${USERAGENT}/${FILE_INDEX}.mp4"
    },
    "videoEncodingOptions": {
        "r": 20,
        "aspect": "16:9"
    },
    "skipJsErrors": true,
    "concurrency": 1,
    "port1": 1337,
    "port2": 1338
}
</code>```

EDIT: I should correct myself that this does not work 100% of the time when I remove --headless, nor does it fail 100% of the time when it's headless. Either way, it intermittently passes one or two tests, and then fails. Firefox does pass 100% of the time. I've also been trying docker-compose a bit, but there's nothing too special in my docker-compose.yml, and the behavior seems the same.

答:
Created an issue on the TestCafe GitHub about this. It ended up being resolved by using the --disable-dev-shm-usage flag on Chromium.

Issue: https://github.com/DevExpress/testcafe/issues/3524

PR where this was made a default for running in Docker: https://github.com/DevExpress/testcafe/pull/3557

Body:
Attempting to run Chromium headless inside the testcafe/testcafe Docker image causes the browser to hang, no matter what options I've used. Here's what I have at the moment:

"browsers": {
    "path": "/usr/bin/chromium-browser",
    "cmd": "--headless --disable-gpu --no-sandbox"
}

And the output after a few minutes:

e2e_1  | Using locally installed version of TestCafe.
e2e_1  | ERROR The HeadlessChrome 71.0.3578 / Linux 0.0.0 browser disconnected. This problem may appear when a browser hangs or is closed, or due to network issues.
e2e_1  |
e2e_1  | Type "testcafe -h" for help.

This works fine if I remove the --headless, but then the browser is rendering into Xvfb instead of running headlessly.

Dockerfile:

FROM testcafe/testcafe

USER root

RUN apk --no-cache add \
    ffmpeg

RUN mkdir /home/e2e
WORKDIR /home/e2e
COPY . .
RUN chmod -R 757 /home/e2e

USER user

RUN npm install

EXPOSE 1337 1338

ENTRYPOINT ["/home/e2e/testcafe-docker.sh"]

testcafe-docker.sh:

#!/bin/sh
XVFB_SCREEN_WIDTH=${SCREEN_WIDTH-1280}
XVFB_SCREEN_HEIGHT=${SCREEN_HEIGHT-720}

dbus-daemon --session --fork
Xvfb :1 -screen 0 "${XVFB_SCREEN_WIDTH}x${XVFB_SCREEN_HEIGHT}x24" >/dev/null 2>&1 &
export DISPLAY=:1.0
fluxbox >/dev/null 2>&1 &
testcafe --ports 1337,1338 "$@"

.testcaferc.json:

{
    "browsers": "chromium --no-sandbox",
    "src": ["tests/*"],
    "reporter": "spec",
    "screenshotPath": "tmp/screenshots/",
    "screenshotPathPattern": "${DATE}_${TIME}/test-${TEST_INDEX}/${USERAGENT}/${FILE_INDEX}.png",
    "takeScreenshotsOnFails": true,
    "videoPath": "tmp/reports/screen-captures",
    "videoOptions": {
        "singleFile": true,
        "failedOnly": true,
        "pathPattern": "${TEST_INDEX}/${USERAGENT}/${FILE_INDEX}.mp4"
    },
    "videoEncodingOptions": {
        "r": 20,
        "aspect": "16:9"
    },
    "skipJsErrors": true,
    "concurrency": 1,
    "port1": 1337,
    "port2": 1338
}

EDIT: I should correct myself that this does not work 100% of the time when I remove --headless, nor does it fail 100% of the time when it's headless. Either way, it intermittently passes one or two tests, and then fails. Firefox does pass 100% of the time. I've also been trying docker-compose a bit, but there's nothing too special in my docker-compose.yml, and the behavior seems the same.


问:
How does the @property decorator work in Python?
I would like to understand how the built-in function property works. What confuses me is that property can also be used as a decorator, but it only takes arguments when used as a built-in function and not when used as a decorator.

This example is from the documentation:

```<code>class C:
    def __init__(self):
        self._x = None

    def getx(self):
        return self._x
    def setx(self, value):
        self._x = value
    def delx(self):
        del self._x
    x = property(getx, setx, delx, "I'm the 'x' property.")
</code>```

property's arguments are getx, setx, delx and a doc string.

In the code below property is used as a decorator. The object of it is the x function, but in the code above there is no place for an object function in the arguments.

```<code>class C:
    def __init__(self):
        self._x = None

    @property
    def x(self):
        """I'm the 'x' property."""
        return self._x

    @x.setter
    def x(self, value):
        self._x = value

    @x.deleter
    def x(self):
        del self._x
</code>```

How are the x.setter and x.deleter decorators created in this case?

答:
property is a class behind @property decorator.

You can always check this:

```<code>print(property) #<class 'property'>
</code>```

I rewrote the example from help(property) to show that the @property syntax

```<code>class C:
    def __init__(self):
        self._x=None

    @property
    def x(self):
        return self._x

    @x.setter
    def x(self, value):
        self._x = value

    @x.deleter
    def x(self):
        del self._x

c = C()
c.x="a"
print(c.x)
</code>```

is functionally identical to property() syntax:

```<code>class C:
    def __init__(self):
        self._x=None

    def g(self):
        return self._x

    def s(self, v):
        self._x = v

    def d(self):
        del self._x

    prop = property(g,s,d)

c = C()
c.x="a"
print(c.x)
</code>```

There is no difference how we use the property as you can see.

To answer the question @property decorator is implemented via property class.

So, the question is to explain the property class a bit.
This line:

```<code>prop = property(g,s,d)
</code>```

Was the initialization. We can rewrite it like this:

```<code>prop = property(fget=g,fset=s,fdel=d)
</code>```

The meaning of fget, fset and fdel:

```<code> |    fget
 |      function to be used for getting an attribute value
 |    fset
 |      function to be used for setting an attribute value
 |    fdel
 |      function to be used for del'ing an attribute
 |    doc
 |      docstring
</code>```

The next image shows the triplets we have, from the class property:

__get__, __set__, and __delete__ are there to be overridden. This is the implementation of the descriptor pattern in Python.

In general, a descriptor is an object attribute with “binding behavior”, one whose attribute access has been overridden by methods in the descriptor protocol.

We can also use property setter, getter and deleter methods to bind the function to property. Check the next example. The method s2 of the class C will set the property doubled.

```<code>class C:
    def __init__(self):
        self._x=None

    def g(self):
        return self._x

    def s(self, x):
        self._x = x

    def d(self):
        del self._x

    def s2(self,x):
        self._x=x+x

    x=property(g)
    x=x.setter(s)
    x=x.deleter(d)

c = C()
c.x="a"
print(c.x) # outputs "a"

C.x=property(C.g, C.s2)
C.x=C.x.deleter(C.d)
c2 = C()
c2.x="a"
print(c2.x) # outputs "aa"
</code>```

Body:
I would like to understand how the built-in function property works. What confuses me is that property can also be used as a decorator, but it only takes arguments when used as a built-in function and not when used as a decorator.

This example is from the documentation:

class C:
    def __init__(self):
        self._x = None

    def getx(self):
        return self._x
    def setx(self, value):
        self._x = value
    def delx(self):
        del self._x
    x = property(getx, setx, delx, "I'm the 'x' property.")

property's arguments are getx, setx, delx and a doc string.

In the code below property is used as a decorator. The object of it is the x function, but in the code above there is no place for an object function in the arguments.

class C:
    def __init__(self):
        self._x = None

    @property
    def x(self):
        """I'm the 'x' property."""
        return self._x

    @x.setter
    def x(self, value):
        self._x = value

    @x.deleter
    def x(self):
        del self._x

How are the x.setter and x.deleter decorators created in this case?

Body:
property is a class behind @property decorator.

You can always check this:

print(property) #<class 'property'>

I rewrote the example from help(property) to show that the @property syntax

class C:
    def __init__(self):
        self._x=None

    @property
    def x(self):
        return self._x

    @x.setter
    def x(self, value):
        self._x = value

    @x.deleter
    def x(self):
        del self._x

c = C()
c.x="a"
print(c.x)

is functionally identical to property() syntax:

class C:
    def __init__(self):
        self._x=None

    def g(self):
        return self._x

    def s(self, v):
        self._x = v

    def d(self):
        del self._x

    prop = property(g,s,d)

c = C()
c.x="a"
print(c.x)

There is no difference how we use the property as you can see.

To answer the question @property decorator is implemented via property class.

So, the question is to explain the property class a bit.
This line:

prop = property(g,s,d)

Was the initialization. We can rewrite it like this:

prop = property(fget=g,fset=s,fdel=d)

The meaning of fget, fset and fdel:

 |    fget
 |      function to be used for getting an attribute value
 |    fset
 |      function to be used for setting an attribute value
 |    fdel
 |      function to be used for del'ing an attribute
 |    doc
 |      docstring

The next image shows the triplets we have, from the class property:

__get__, __set__, and __delete__ are there to be overridden. This is the implementation of the descriptor pattern in Python.

In general, a descriptor is an object attribute with “binding behavior”, one whose attribute access has been overridden by methods in the descriptor protocol.

We can also use property setter, getter and deleter methods to bind the function to property. Check the next example. The method s2 of the class C will set the property doubled.

class C:
    def __init__(self):
        self._x=None

    def g(self):
        return self._x

    def s(self, x):
        self._x = x

    def d(self):
        del self._x

    def s2(self,x):
        self._x=x+x

    x=property(g)
    x=x.setter(s)
    x=x.deleter(d)

c = C()
c.x="a"
print(c.x) # outputs "a"

C.x=property(C.g, C.s2)
C.x=C.x.deleter(C.d)
c2 = C()
c2.x="a"
print(c2.x) # outputs "aa"