问:
jQuery hide / show content based on common parent
I've this repeated HTML code.

```<code><div id="id1" class="questio">
  <input type="checkbox" class="c1">
  <div class="c2">Content</div>
</div>

<div id="id2" class="questio">
  <input type="checkbox" class="c1">
  <div class="c2">Another Content</div>
</div>

<div id="id3" class="questio">
  <input type="checkbox" class="c1">
  <div class="c2">Another Content</div>
</div>
</code>```

The wanted behaviour is to hide / show div c2 Content for each section independently based on input.c1 checked or not:

```<code>if ($(".c1").is(":checked")) {
  $('.c2').show();
}
</code>```

I tried somethig like this but I can't go on :

```<code>$("input.c1").each(function() {
  var parent1 = $(this).closest('questio');
  if ($(this).is(":checked")) {
        /// ??
  }
});
</code>```

答:
You were pretty close.

```<code>//you can find the c1's that are checked
$(".c1:checked").each(function() {
    //you can then find their parent questio (with the '.' for the selector)
    //then find the related c2 and show it.
    $(this).closest('.questio').find('.c2').show();
});
</code>```

Though given your markup you could do this entirely with css.

.questio .c1:not(:checked) + .c2 {
  display: none;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="id1" class="questio">
  <input type="checkbox" class="c1">
  <div class="c2">Content</div>
</div>

<div id="id2" class="questio">
  <input type="checkbox" class="c1">
  <div class="c2">Another Content</div>
</div>

<div id="id3" class="questio">
  <input type="checkbox" class="c1">
  <div class="c2">Another Content</div>
</div></code>```

Body:
I've this repeated HTML code.

  <input type="checkbox" class="c1">

Content

  <input type="checkbox" class="c1">

Another Content

  <input type="checkbox" class="c1">

Another Content

The wanted behaviour is to hide / show div c2 Content for each section independently based on input.c1 checked or not:

if ($(".c1").is(":checked")) {
  $('.c2').show();
}

I tried somethig like this but I can't go on :

$("input.c1").each(function() {
  var parent1 = $(this).closest('questio');
  if ($(this).is(":checked")) {
        /// ??
  }
});

Body:
You were pretty close.

//you can find the c1's that are checked
$(".c1:checked").each(function() {
    //you can then find their parent questio (with the '.' for the selector)
    //then find the related c2 and show it.
    $(this).closest('.questio').find('.c2').show();
});

Though given your markup you could do this entirely with css.

.questio .c1:not(:checked) + .c2 {
  display: none;
}

<div id="id1" class="questio">
  <input type="checkbox" class="c1">
  <div class="c2">Content</div>
</div>

<div id="id2" class="questio">
  <input type="checkbox" class="c1">
  <div class="c2">Another Content</div>
</div>

<div id="id3" class="questio">
  <input type="checkbox" class="c1">
  <div class="c2">Another Content</div>
</div>


来源: stackexchange

问:
How to use legacy web site and ReactJS both?
I have a React app which is created by create-react-app command.

And I also have the blog system which is based on Wordpress.

Directory structure is like this.

```<code>*/index.html
/service-workder.js
/manifect.json
/index.html
/favicon.ico
/asset-manifest.json
/static/media
       /js
       /css
/blog <--------------------- Wordpress*
</code>```

When I access the URL by http:mydomain/blog/,
Firefox show React page instead of Wordpress page.

Firefox even show React page for     http:mydomain/blog/nonexisting    ,

which I think is supposed to provide 404 not found from web server.

I was struggling to find a way NOT to let React take wildcard paths.

Safari use React only for index.html, which is good.
Chrome, Firefox use React for entire wildcard paths, even for not existing paths.

http://myserver/ ---> should show React app

http://myserver/nonexistence ---> should show 404 from server

Please help me to figure out isolate React app only for exact index.html.

Thanks in advance.

答:
Like I wrote here, the root cause was service worker which seems to be HTML5 feature to make a web site to a web app.

Unregistering service worker was the solution.

ContentLicense: CC BY-SA 3.0

Body:
I have a React app which is created by create-react-app command.

And I also have the blog system which is based on Wordpress.

Directory structure is like this.

*/index.html
/service-workder.js
/manifect.json
/index.html
/favicon.ico
/asset-manifest.json
/static/media
       /js
       /css
/blog <--------------------- Wordpress*

When I access the URL by http:mydomain/blog/,
Firefox show React page instead of Wordpress page.

Firefox even show React page for     http:mydomain/blog/nonexisting    ,

which I think is supposed to provide 404 not found from web server.

I was struggling to find a way NOT to let React take wildcard paths.

Safari use React only for index.html, which is good.
Chrome, Firefox use React for entire wildcard paths, even for not existing paths.

http://myserver/ ---> should show React app

http://myserver/nonexistence ---> should show 404 from server

Please help me to figure out isolate React app only for exact index.html.

Thanks in advance.


问:
formatting numbers in input with ngModel
I've got an input linked to the object that contains relevant data:

```<code>  <input type="text" [(ngModel)]="element.number" name="someName">
</code>```

element is an object with property number. number is of type number and it is always whole number.

I'd like to display a formated value of input (transform seconds into a more human readable format). Lets say element.number is 140, than the displayed value is 00:02:20. If the element.number is 22, than the displayed value is 00:00:22. If element.number is 3670, than the displayed value is  01:01:10 and so on.

If the user than edits 00:00:22 to 00:01:44 than element.number gets updated to 104.

For all the logic the app needs, element.number must be an integer. How should I go around this? Is there some pipe I can use on expressions? Should I split the input into 3 input fields?

答:
Try this out:

```<code>  import { Component } from '@angular/core';

        @Component({
          selector: 'app-root',
          template: '
         <div>
           <p>The number is {{number}}</p>
           <p>
             <input type="number" [(ngModel)]="formattednumbers.hrs"
                name="hrs" (change)="updateNumber()">:
             <input type="number" [(ngModel)]="formattednumbers.mins"
                name="mins" (change)="updateNumber()">:
             <input type="number" [(ngModel)]="formattednumbers.secs"
                name="secs" (change)="updateNumber()">
           </p>
         </div>
         '
        })
        export class AppComponent {
          number = 140;
          formattednumbers: TimeFormatter;

          constructor() {
            this.formattednumbers = this.fancyTimeFormat(this.number);
          }

          fancyTimeFormat(time): TimeFormatter {
            // Hours, minutes and seconds
            const hrs = Math.floor(time / 3600);
            const mins = Math.floor((time % 3600) / 60);
            const secs = Math.floor(time % 60);

            const ret = {
              hrs: hrs,
              mins: mins,
              secs: secs
            };

            return ret;
          }

          updateNumber() {
            const h2s = this.formattednumbers.hrs * 3600;
            const m2s = this.formattednumbers.mins * 60;
            const s = this.formattednumbers.secs;
            this.number = h2s + m2s + s;
            this.formattednumbers = this.fancyTimeFormat(this.number);
          }
        }

        interface TimeFormatter {
          hrs: number;
          mins: number;
          secs: number;
        }
</code>```

you can refactor the code a little bit more but the answer for your question is there i think :)

Body:
I've got an input linked to the object that contains relevant data:

  <input type="text" [(ngModel)]="element.number" name="someName">

element is an object with property number. number is of type number and it is always whole number.

I'd like to display a formated value of input (transform seconds into a more human readable format). Lets say element.number is 140, than the displayed value is 00:02:20. If the element.number is 22, than the displayed value is 00:00:22. If element.number is 3670, than the displayed value is  01:01:10 and so on.

If the user than edits 00:00:22 to 00:01:44 than element.number gets updated to 104.

For all the logic the app needs, element.number must be an integer. How should I go around this? Is there some pipe I can use on expressions? Should I split the input into 3 input fields?

Body:
Try this out:

  import { Component } from '@angular/core';

        @Component({
          selector: 'app-root',
          template: '
         <div>
           <p>The number is {{number}}</p>
           <p>
             <input type="number" [(ngModel)]="formattednumbers.hrs"
                name="hrs" (change)="updateNumber()">:
             <input type="number" [(ngModel)]="formattednumbers.mins"
                name="mins" (change)="updateNumber()">:
             <input type="number" [(ngModel)]="formattednumbers.secs"
                name="secs" (change)="updateNumber()">
           </p>
         </div>
         '
        })
        export class AppComponent {
          number = 140;
          formattednumbers: TimeFormatter;

          constructor() {
            this.formattednumbers = this.fancyTimeFormat(this.number);
          }

          fancyTimeFormat(time): TimeFormatter {
            // Hours, minutes and seconds
            const hrs = Math.floor(time / 3600);
            const mins = Math.floor((time % 3600) / 60);
            const secs = Math.floor(time % 60);

            const ret = {
              hrs: hrs,
              mins: mins,
              secs: secs
            };

            return ret;
          }

          updateNumber() {
            const h2s = this.formattednumbers.hrs * 3600;
            const m2s = this.formattednumbers.mins * 60;
            const s = this.formattednumbers.secs;
            this.number = h2s + m2s + s;
            this.formattednumbers = this.fancyTimeFormat(this.number);
          }
        }

        interface TimeFormatter {
          hrs: number;
          mins: number;
          secs: number;
        }

you can refactor the code a little bit more but the answer for your question is there i think :)


问:
React native modal blur/vibrancy on iOS and Android?
I'm trying to build a modal that looks somewhat like this using React Native for iOS and Android. Are there any libraries that do blurred/vibrancy overlays? I had a look at the react-native-blur, however unfortunately this is only for iOS. React-native-overlay also has some options for such views, however it also appears to be iOS only.

Is there a library that supports both platforms, or is there a way to use a JS library such as vibrancy.js that can be used with React?

答:
Currently react-native-blur supports blur for Android as well. However a little bit of setup is required. Check out the docs here:
https://github.com/react-native-community/react-native-blur.

The library also offers the ability to create vibrancy views. Although, at the present (v 3.2.2), vibrancy will only work fo iOS.


问:
Watson Discovery Service - File size limit
The Watson discovery service documentation says limit of file "The maximum file size that can be uploaded to the Discovery service is 50MB." But it seems there is a character limit as well which is 50000 characters.
The warning message is "Text content exceeds 50000 character limit. Only first 50000 characters processed...".
Can anyone please confirm?</p>

答: The warning about exceeding 50,000 characters is talking about enrichments. The text of entire document is still added to your Discovery collection, but the enrichments only apply to the first 50,000 characters of the document text.</p>


问:
How to print only the product barcode label in Odoo? How to change the default size of the paper?
I am creattng a report to print a barcode label.

My template try to print the whole page, but I need a specia page side: width = 35mm and height = 11mm.

So how and where can I change the default product label report template and make changes? I need to print only the label as pdf.

答:
The report template with the barcode, this example is uses a qrcode, but you can change it to adapt it to your needs. You can add some styles as well:

<template id="report_label_style" inherit_id="website_report.layout">
    <xpath expr="//style" position="after">

    </xpath>
</template>

<template id="report_label">
    <t t-call="report.html_container">
        <t t-foreach="docs" t-as="o">

                        <t t-set="qr_src">/report/barcode/?type=QR&value=<t t-esc="o.qr_string" />&width=600&height=600</t>

        </t>
    </t>
</template>
```

<p>The paperformat definition. You will see the paperformat if you go to: <strong>Settings > Report > Paper forma</strong></p>

<pre class="lang-xml prettyprint-override"><code><record id="paperformat_label_example" model="report.paperformat">
    <field name="name">Paperformat Example</field>
    <field name="default" eval="True"/>
    <field name="format">custom</field>
    <field name="page_height">23</field>
    <field name="page_width">50</field>
    <field name="orientation">Portrait</field>
    <field name="margin_top">0</field>
    <field name="margin_bottom">0</field>
    <field name="margin_left">0</field>
    <field name="margin_right">0</field>
    <field name="header_line" eval="False"/>
    <field name="header_spacing">0</field>
    <field name="dpi">80</field>
</record>
</code>```

The report action, this creates the needed record in the model ir_act_report_xml:

<report id="action_report_label"
        model="model.name"
        report_type="qweb-pdf"
        name="module_name.report_label"
        file="module_name.report_label"
        string="Label" />
```

<p>Here I associate the paperformat to the report:</p>

<pre class="lang-xml prettyprint-override"><code><record id="module_name.action_report_label" model="ir.actions.report.xml">
    <field name="paperformat_id" ref="module_name.paperformat_label_example"/>
</record>
</code>```

Body:
The report template with the barcode, this example is uses a qrcode, but you can change it to adapt it to your needs. You can add some styles as well:

<template id="report_label_style" inherit_id="website_report.layout">
    <xpath expr="//style" position="after">
        <style type="text/css">
            .example_class {
                display: block;
                width: 228px;
                height: 103px;
            }
        </style>
    </xpath>
</template>

<template id="report_label">
    <t t-call="report.html_container">
        <t t-foreach="docs" t-as="o">
            <div class="page">
                <div class="row">
                    <div class="example_class">
                        <t t-set="qr_src">/report/barcode/?type=QR&amp;value=<t t-esc="o.qr_string" />&amp;width=600&amp;height=600</t>
                        <img t-att-src="'%s' % qr_src"/>
                    </div>
                </div>
            </div>
        </t>
    </t>
</template>

The paperformat definition. You will see the paperformat if you go to: Settings > Report > Paper forma

<record id="paperformat_label_example" model="report.paperformat">
    <field name="name">Paperformat Example</field>
    <field name="default" eval="True"/>
    <field name="format">custom</field>
    <field name="page_height">23</field>
    <field name="page_width">50</field>
    <field name="orientation">Portrait</field>
    <field name="margin_top">0</field>
    <field name="margin_bottom">0</field>
    <field name="margin_left">0</field>
    <field name="margin_right">0</field>
    <field name="header_line" eval="False"/>
    <field name="header_spacing">0</field>
    <field name="dpi">80</field>
</record>

The report action, this creates the needed record in the model ir_act_report_xml:

<report id="action_report_label"
        model="model.name"
        report_type="qweb-pdf"
        name="module_name.report_label"
        file="module_name.report_label"
        string="Label" />

Here I associate the paperformat to the report:

<record id="module_name.action_report_label" model="ir.actions.report.xml">
    <field name="paperformat_id" ref="module_name.paperformat_label_example"/>
</record>


问:
problems passing gl with Android
I have a button class thats created from within the onSurfaceCreated method in my glSurfaceView; It takes gl as one of its parameters so it can properly draw. Im having an issue passing gl to an overlay class, which looks like a pin in the google maps app. If i call makeOverlay() in my button's constructor it draws perfectly, if i call it anywhere else all i get is a white square. They are all on the same drawing thread. Anyone know what im missing? Thanks.</p>

答: You could store the GL context inside a static variable to be able to access it from anywhere within your code.</p>

ContentLicense: CC BY-SA 2.5

Title: problems passing gl with Android


答:
You can use the joins to connects the multiple tables

```<code>select s.*,g.* from student as s
inner join GRADE as g on g.student_id=s.student_id
inner join SUBJECT as sj on sj.subject_id = g.subject_id
where g.grade in ('A','B')
</code>```

i hope this will help

Title: how to select records with specific value/condition in another table

Body:
I have 3 tables STUDENT, SUBJECT and GRADE.

STUDENT

+------------+------------+------------+
| student_id | first_name |  last_name |
+------------+------------+------------+
|          0 | Arthur     | Pain       |
|          1 | Richard    | Gordon     |
|          2 | Jennifer   | Adelaide   |
+------------+------------+------------+

SUBJECT

+------------+--------------+
| subject_id | subject_name |
+------------+--------------+
|        001 | Math         |
|        002 | Science      |
|        003 | English      |
+------------+--------------+

GRADE

+-------------+-------------+--------+
| student_id  | subject_id  |  grade |
+-------------+-------------+--------+
| 0           | 001         | A      |
| 0           | 002         | B      |
| 0           | 003         | A      |
| 1           | 001         | B      |
| 1           | 002         | A      |
| 1           | 003         | F      |
| 2           | 001         | A      |
| 2           | 002         | B      |
| 2           | 003         | B      |
+-------------+-------------+--------+

I have tried the query below.

SELECT * FROM student st WHERE EXISTS
       (SELECT 1 FROM grade g WHERE st.student_id = g.student_id AND g.grade IN ('A','B');

I want to select the students with grades only 'A' OR 'B'.

Body:
You can use the joins to connects the multiple tables

select s.*,g.* from student as s
inner join GRADE as g on g.student_id=s.student_id
inner join SUBJECT as sj on sj.subject_id = g.subject_id
where g.grade in ('A','B')

i hope this will help


问:
EXTJS Find the parent of a node
I need to be able to find a parent of a select node in a tree, however, whenever i use ParentNode it always comes up as 'undefined'  (and i am not selecting the root).  Anybody know a good way to find the parent of a node?

Thanks

答:
You can use the below code:</p>

```<code>let parentNode = Ext.getCmp('YourGridId').getRootNode();
</code>```

Title: EXTJS Find the parent of a node

Body:
You can use the below code:

let parentNode = Ext.getCmp('YourGridId').getRootNode();


问:
Select a part of Image in Python(without using imcrop)
I want to select a part of the image and save it as an image file but I don't want to use imcrop() function.There are many answers for this but I don't want to use crop function.Any other methods?</p>

答:
You can convert it to an array and "crop" it by indexing, then convert back to an image.</p>

```<code>from PIL import Image
import numpy as np

# Create an image for example
w, h = 512, 512
data = np.zeros((h, w, 3), dtype=np.uint8)
data[:, :, :] = 100  # Grey image
img = Image.fromarray(data, 'RGB')
img.save('my.png')
img.show()  # View the original image

img_array = np.asarray(img)  # Convert image to an array
cropped = img_array[:100, :100, :]  # Select portion to keep

img = Image.fromarray(cropped, 'RGB')  # Convert back to image
img.save('my.png')
img.show()  # View the cropped image
</code>```

Body:
You can convert it to an array and "crop" it by indexing, then convert back to an image.

from PIL import Image
import numpy as np

# Create an image for example
w, h = 512, 512
data = np.zeros((h, w, 3), dtype=np.uint8)
data[:, :, :] = 100  # Grey image
img = Image.fromarray(data, 'RGB')
img.save('my.png')
img.show()  # View the original image

img_array = np.asarray(img)  # Convert image to an array
cropped = img_array[:100, :100, :]  # Select portion to keep

img = Image.fromarray(cropped, 'RGB')  # Convert back to image
img.save('my.png')
img.show()  # View the cropped image


问:
PHP Echo SUM session value & form select
I have a PHP echo statement of a session value like this:

<?php echo $userinfo['RenewAgreementAmount'] ;?>

I have a form select element like this:

```<code><select id="Lock" name="Lock">
                      <option value="1" selected="selected">1 Year</option>
                      <option value="2">2 Years</option>
                      <option value="3">3 Years</option>
                      <option value="4">4 Years</option>
                    </select>
</code>```

I'm trying to update the <?php echo $userinfo['RenewAgreementAmount'] ;?> output by taking what the user selects in the select value id Lock with this session value while interacting with the form?

I've tried <?php echo ($userinfo['RenewAgreementAmount'] * #Lock) ;?> with no luck.

What is the easiest way to update this value as the user interacts with the select form input in real time?

答:
```<code><script>
renewAmount = <?= $userinfo['RenewAgreementAmount']; ?>
function calc(year){
    var amount = renewAmount*year;
    // here you can perform an ajax request to update the amount on server
}
</script>
<select id="Lock" name="Lock" onchange="calc(this.value)">
  <option value="1" selected="selected">1 Year</option>
  <option value="2">2 Years</option>
  <option value="3">3 Years</option>
  <option value="4">4 Years</option>
</select>
</code>```

Body:
I have a PHP echo statement of a session value like this:

<?php echo $userinfo['RenewAgreementAmount'] ;?>

I have a form select element like this:

<select id="Lock" name="Lock">
                      <option value="1" selected="selected">1 Year</option>
                      <option value="2">2 Years</option>
                      <option value="3">3 Years</option>
                      <option value="4">4 Years</option>
                    </select>

I'm trying to update the <?php echo $userinfo['RenewAgreementAmount'] ;?> output by taking what the user selects in the select value id Lock with this session value while interacting with the form?

I've tried <?php echo ($userinfo['RenewAgreementAmount'] * #Lock) ;?> with no luck.

What is the easiest way to update this value as the user interacts with the select form input in real time?


问:
Swift protocol property check if weak
Is it possible in XCTest to test a class property if it's weak or not.

```<code>class A {
  weak var p: String? = nil
}
</code>```

Result: if p property of a class is weak then assert

答:
You could use an approach like this:

```<code>class TestObject {}

protocol A {
    var a: TestObject? { get set }
}

class B: A {
    var a: TestObject?
}

class C: A {
    weak var a: TestObject?
}

func addVar(to: A) {
    var target = to
    target.a = TestObject()  // Once we leave the scope of this function, the TestObject instance created here will be released unless retained by target
}

let b = B()
let c = C()

addVar(to: b)
addVar(to: c)

print(b.a)  // prints Optional(TestObject) because class C uses a strong var for a
print(c.a)  // prints nil because class B uses a weak var for a
</code>```

Converted to a test case, it might look something like:

```<code>func testNotWeak() {

    func addVar(to: A) {
        var target = to
        target.a = TestObject()  // Once we leave the scope of this function, the TestObject instance created here will be released unless retained by target
    }

    let testClass = B()
    addVar(to: testClass)
    XCTAssertNotNil(testClass.a)
}
</code>```

Title: Swift protocol property check if weak

Body:
Is it possible in XCTest to test a class property if it's weak or not.

class A {
  weak var p: String? = nil
}

Result: if p property of a class is weak then assert

Body:
You could use an approach like this:

class TestObject {}

protocol A {
    var a: TestObject? { get set }
}

class B: A {
    var a: TestObject?
}

class C: A {
    weak var a: TestObject?
}

func addVar(to: A) {
    var target = to
    target.a = TestObject()  // Once we leave the scope of this function, the TestObject instance created here will be released unless retained by target
}

let b = B()
let c = C()

addVar(to: b)
addVar(to: c)

print(b.a)  // prints Optional(TestObject) because class C uses a strong var for a
print(c.a)  // prints nil because class B uses a weak var for a

Converted to a test case, it might look something like:

func testNotWeak() {

    func addVar(to: A) {
        var target = to
        target.a = TestObject()  // Once we leave the scope of this function, the TestObject instance created here will be released unless retained by target
    }

    let testClass = B()
    addVar(to: testClass)
    XCTAssertNotNil(testClass.a)
}


问:
Access to path denied on IIS
I'm trying to get my MVC app to write a simple text file to another server using System.IO.File.WriteAllText.  (A separate process is looking in that folder for text files to grab.)  It works fine when debugging on my local machine, but when deployed to IIS on a test server, I always get this error when trying to write the file:

Access to the path '\\server\C$\folder\subfolder\file.txt' is denied.

The answer to at least half a dozen similar questions here on SO was to give the application pool identity account access to that folder.  However, the app pool on IIS was already running under a service account that had full permissions to the desired folder but was still getting the error.  I even tried changing the app pool to my own account (the one used successfully in debugging) and still get the error.

Anonymous access is turned off, and Windows Authentication is turned on (part of the file.txt is info from the user's AD account).  I have tried accessing the app with several AD accounts, both with and without access to \\server\C$\folder\subfolder\ but they all give the same error.

I don't see how the app can be running under an authorized account, and the user can be logged in to the app with an authorized account, but still get the access denied error.  Is there any way to get more info about specifically what access is denied or which account is actually being denied? Anything else I'm missing here??

答:
First of all, you can try to give write rights to IUSR user on your folder in which you want to write your text file.

There is a way to imitate an user in your asp.net application by using Impersonate tag in your web.config file but I think this can be dangerous.

```<code>  <identity impersonate="true" userName="nomducompte" password="motdepasse" />
</code>```

I hope this helps.

Title: Access to path denied on IIS

Body:
First of all, you can try to give write rights to IUSR user on your folder in which you want to write your text file.

There is a way to imitate an user in your asp.net application by using Impersonate tag in your web.config file but I think this can be dangerous.

  <identity impersonate="true" userName="nomducompte" password="motdepasse" />

I hope this helps.


答:
```<code>SELECT * FROM STUDENT
LEFT JOIN GRADE ON STUDENT.STUDENT_ID = GRADE.STUDENT_ID
LEFT JOIN SUBJECT ON GRADE.SUBJECT_ID = SUBJECT.SUBJECT_ID
WHERE GRADE.GRADE IN ('A','B')
</code>```


问:
Python 3.6 - How to match strings in a for loop?

I'm defining a function that counts the number of times XML tags are present in a string, namely <> and </>. Although I'm able to 'match' the strings, I'm unable to quantify those number of matches to return a numeric count. This is my function:

```<code>def tag_count(the_string):
    count = 0
    for element in the_string:
        if '<>' in the_string:
            count += 1
            return count
        elif '</>' in the_string:
             count += 1
             return count
</code>```

The problem is that for strings that have both <> and </>, count should return the number of times these tags are matched whereas my function is only returning count as 1 because of the elif condition. I tried inserting and in the 3rd line but that gives me an error. How do I sum the number of times these tags are matched?

答:
You return from the function every time you encounter a tag, that's why it's always 1. You can also use the str.count() method:

```<code>def tag_count(source):
    return source.count('<>') + source.count('</>')
</code>```

Example usage:

```<code>>>> tag_count('<> <> </> <> <>')
5
</code>```

Body:
I'm defining a function that counts the number of times XML tags are present in a string, namely <> and </>. Although I'm able to 'match' the strings, I'm unable to quantify those number of matches to return a numeric count. This is my function:

def tag_count(the_string):
    count = 0
    for element in the_string:
        if '<>' in the_string:
            count += 1
            return count
        elif '</>' in the_string:
             count += 1
             return count

The problem is that for strings that have both <> and </>, count should return the number of times these tags are matched whereas my function is only returning count as 1 because of the elif condition. I tried inserting and in the 3rd line but that gives me an error. How do I sum the number of times these tags are matched?

Body:
You return from the function every time you encounter a tag, that's why it's always 1. You can also use the str.count() method:

def tag_count(source):
    return source.count('<>') + source.count('</>')

Example usage:

>>> tag_count('<> <> </> <> <>')
5


问:
QTcpSocket and QTimer for automatic reconnection best practice
we are trying to implement an application which retrieves data from multiple servers, so we need several QTcpSocket instances in order to manage the connections for each host.

We are facing some decisional "design" problems:

should we implement a multi-threading solution to reach the goal? (probably yes)

if Yes, should we use a "worker thread" ( e.g as in the QThread example moveToThread(socket_) ) as best solution or there are better ? We need to manage three or more connections simultaneously, so we cannot use waitingForConnection(...) because is a blocking function (from what we understand)

what is the best practice for QTcpSocket reconnection? Maybe a QTimer, but what is the best way to use it...?

Thank you in advance!

AD

答:
Well, I had some design questions just like these, but in my case the main reason was to avoid my connection timing to be delayed by the heavy GUI processing, also, my communication system is thru serial, but apart from it, I think that my model fits pretty well in your case, here is the way i designed it, my questions, and the answers from UmNyobe:

QT QThread with QTimer and QSerial - parenting

Basically, each new instance of my "CommCore" class creates its own Serial, Timer and Thread, and transfers itself and it's children to this Thread, avoiding that the GUI processing interferes in the communication timing.


问:
React: How to pass width as a prop from the component
I am trying to create a component, whose width can be specified wherever the component can be used

Like:

```<code><Button label="button" width="80%" />

const TestButton = styled.button`
  color: red;
`;

var React = require('react');

var Button = React.createClass({

render: function () {

return (
  <TestButton>{this.props.label}</TestButton>
);
}
});

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

how can I achieve this?

答:
You can pass width as props to button component like,

```<code>export const Button = (props) => { // Your button component in somewhere
    return (
        <button style={{width: `${props.width}`}}>{props.label}</button>
    )
}
</code>```

In your main component import your button and work as what you want like below

```<code>import Button from 'your_button_component_path';

class RenderButton extends React.Component {
    render() {
        return (
            <Button width="80%" label="Save" />
        );
    }
}
</code>```

Body:
I am trying to create a component, whose width can be specified wherever the component can be used

Like:

<Button label="button" width="80%" />

const TestButton = styled.button`
  color: red;
`;

var React = require('react');

var Button = React.createClass({

render: function () {

return (
  <TestButton>{this.props.label}</TestButton>
);
}
});

module.exports = Button;

how can I achieve this?

Body:
You can pass width as props to button component like,

export const Button = (props) => { // Your button component in somewhere
    return (
        <button style={{width: `${props.width}`}}>{props.label}</button>
    )
}

In your main component import your button and work as what you want like below

import Button from 'your_button_component_path';

class RenderButton extends React.Component {
    render() {
        return (
            <Button width="80%" label="Save" />
        );
    }
}


问:
Sql Server print affected rows during while loop
I have a stored procedure running on sql server 2008 looping over a table of ~50 million rows, deleting records one day at a time (approx. 25,000 records a day). I want to be able to watch this occur as the process runs via print statements to the messages window. I'd like to be able to see a message each time a day's worth of deletions is committed. Is there any way to do something like this? The procedure is roughly laid out like this:</p>

```<code>WHILE EXISTS(<query statement>)
BEGIN

BEGIN TRAN

DELETE
FROM  <table>
WHERE <condition>
AND <condition>

--need some sort of "rows affected" statement here

COMMIT

END
</code>```

答:
you could do something like this to iterate over each row</p>

```<code>           declare @ii (id int) table

     -- for batchchunk operations

          declare @numTransactions as int = 0,
            @totalRowsInserted as int = 0,
            @chunksize int = 0,
            @printnow varchar(1000)

      --does the initial insert into the  table
            select * from #table
            SET @numTransactions =@@rowcount
            SET @printnow = 'Should Insert :'+cast(@numTransactions as varchar)+ ' rows into the  table.'
            exec db.printNow @printnow;       -- shortened proc

           BEGIN
           INSERTCHUNKS:

           SET ROWCOUNT @Batchsize

          insert into table
          (
            type_id,
            parent_id,
            created_by_user_id,
            created_at,
            updated_by_user_id,
            updated_at,
            created_by_system_id,
            updated_by_system_id,
            is_deleted
           )
          output inserted.id into @ii(id)

           select
          1,--party_type_id
         NULL,--parent_party_id
         @user_id, --created_by_user_id
         case when created_at is NULL then getdate() else created_at end ,

         NULL , --updated_by_user_id
         case when updated_at is NULL then getdate() else updated_at end, --
         updated_at
         case when created_by_system_id is null then 292 else 0 end, --created_by_system_id
          updated_by_system_id,--updated_by_system_id                   \
           0 --is_deleted
         from
         #table
         order by id asc
         OFFSET
         @TotalRowsInserted ROWS
         FETCH NEXT @batchsize ROWS ONLY
         set @chunksize =@@rowcount
          IF @chunksize > 0
          BEGIN
         set @totalRowsInserted = @totalRowsInserted + @chunksize
          SET @printnow = 'Batch done: ' +
            cast(@chunksize as varchar) + ' rows in Batch ; '
            + cast(@totalRowsInserted as varchar) + ' total inserted so far
             into the table.'             exec db.printnow @printnow;

           waitfor delay '00:00:01'
          GOTO INSERTCHUNKS
          END
          SET ROWCOUNT 0;
          END
</code>```

Body:
I have a stored procedure running on sql server 2008 looping over a table of ~50 million rows, deleting records one day at a time (approx. 25,000 records a day). I want to be able to watch this occur as the process runs via print statements to the messages window. I'd like to be able to see a message each time a day's worth of deletions is committed. Is there any way to do something like this? The procedure is roughly laid out like this:

WHILE EXISTS(<query statement>)
BEGIN

BEGIN TRAN

DELETE
FROM

WHERE <condition>
AND <condition>

--need some sort of "rows affected" statement here

COMMIT

END

Body:
you could do something like this to iterate over each row

           declare @ii (id int) table

     -- for batchchunk operations

          declare @numTransactions as int = 0,
            @totalRowsInserted as int = 0,
            @chunksize int = 0,
            @printnow varchar(1000)

      --does the initial insert into the  table
            select * from #table
            SET @numTransactions =@@rowcount
            SET @printnow = 'Should Insert :'+cast(@numTransactions as varchar)+ ' rows into the  table.'
            exec db.printNow @printnow;       -- shortened proc

           BEGIN
           INSERTCHUNKS:

           SET ROWCOUNT @Batchsize

          insert into table
          (
            type_id,
            parent_id,
            created_by_user_id,
            created_at,
            updated_by_user_id,
            updated_at,
            created_by_system_id,
            updated_by_system_id,
            is_deleted
           )
          output inserted.id into @ii(id)

           select
          1,--party_type_id
         NULL,--parent_party_id
         @user_id, --created_by_user_id
         case when created_at is NULL then getdate() else created_at end ,

         NULL , --updated_by_user_id
         case when updated_at is NULL then getdate() else updated_at end, --
         updated_at
         case when created_by_system_id is null then 292 else 0 end, --created_by_system_id
          updated_by_system_id,--updated_by_system_id                   \
           0 --is_deleted
         from
         #table
         order by id asc
         OFFSET
         @TotalRowsInserted ROWS
         FETCH NEXT @batchsize ROWS ONLY
         set @chunksize =@@rowcount
          IF @chunksize > 0
          BEGIN
         set @totalRowsInserted = @totalRowsInserted + @chunksize
          SET @printnow = 'Batch done: ' +
            cast(@chunksize as varchar) + ' rows in Batch ; '
            + cast(@totalRowsInserted as varchar) + ' total inserted so far
             into the table.'             exec db.printnow @printnow;

           waitfor delay '00:00:01'
          GOTO INSERTCHUNKS
          END
          SET ROWCOUNT 0;
          END


问:
Multiple values with Drupal Embedded Media Field
I am a novice programming and I met this problem which I have not been able to figure out. Hope that you can help me out.

I am currently using Drupal 6.20 with the Embedded media field (http://drupal.org/project/emfield). I have added an Embedded Video field into a content type named Video-Post. I set the value of "Number of Values" as "Unlimited" at .../admin/content/node-type/video-post

When I proceed to create a new node for content type Video Post at .../node/add/video-post, I see 2 "Embed a video" fields (despite me not yet clicking on the "Add another item button") and a "Add another item" button.

I would like it to show only 1 "Embed a video" field even when I set the "Number of Values" as "Unlimited".

Which file and function should I modify to achieve this?

Thanks.

答: Without looking at the module I'm going to say you may be able to use form_alter() to modify the output.</p>


问:
bigger than and lesser than javascript
I am trying to make a simple function that validates an ID.
the ID is supposed to be longer either 2 or 3 letters, so bigger than or equal to 2 and lesser than or equal to 3, heres what im using atm:</p>

```<code>else if (pasientID.length < 2)
{
 lovligPasientID=false;
 feilmelding="Pasient ID'en er ikke lang nok.";
}

else if(pasientID.length > 3)
{
 lovligPasientID=false;
 feilmelding="Pasient ID'en er for lang.";
}
</code>```

答:
This can be made cleaner with .match() and regex.

```<code>/^([a-zA-Z]|[0-9]){2,3}$/g
</code>```

This will match any 2 or 3 character alphanumeric string.

let id = '5', id2 = '23', id3 ='ABC', id4 = 'ABCD';

function validate(patientID) {
  if (patientID.match(/^([a-zA-Z]|[0-9]){2,3}$/g)) {
    console.log('ok');
  }
  else {
    console.log('not ok');
  }
};

validate(id);
validate(id2);
validate(id3);
validate(id4);```

Title: bigger than and lesser than javascript

Body:
I am trying to make a simple function that validates an ID.
the ID is supposed to be longer either 2 or 3 letters, so bigger than or equal to 2 and lesser than or equal to 3, heres what im using atm:

else if (pasientID.length < 2)
{
 lovligPasientID=false;
 feilmelding="Pasient ID'en er ikke lang nok.";
}

else if(pasientID.length > 3)
{
 lovligPasientID=false;
 feilmelding="Pasient ID'en er for lang.";
}

Body:
This can be made cleaner with .match() and regex.

/^([a-zA-Z]|[0-9]){2,3}$/g

This will match any 2 or 3 character alphanumeric string.

let id = '5', id2 = '23', id3 ='ABC', id4 = 'ABCD';

function validate(patientID) {
  if (patientID.match(/^([a-zA-Z]|[0-9]){2,3}$/g)) {
    console.log('ok');
  }
  else {
    console.log('not ok');
  }
};

validate(id);
validate(id2);
validate(id3);
validate(id4);


答:
Using Not In :</p>

```<code>SELECT * FROM student st WHERE student_id not in
       (SELECT student_id FROM grade g WHERE grade = 'F');
</code>```

Body:
Using Not In :

SELECT * FROM student st WHERE student_id not in
       (SELECT student_id FROM grade g WHERE grade = 'F');


问:
How to get an object from a List<typeObject> in a DropDownlistFor?
As a beginner in c#/asp.net/mvc, I can't find how to get an object from a Html.DropDownList in the View.
Here is my ViewModel :

```<code>public class MyViewModel {
   public List<Something> ListOfSomething {get;set;} // A list of Somethings
   public Something TheSomethingToGet {get;set;} // The object I want to get
}
</code>```

The "Something" object is for example :

```<code>public class Something {
   public int Id {get;set;}
   public string Name {get;set;}
   public int AnotherProperty {get;set;}
}
</code>```

I populate my List<> in the controller :

```<code>public ActionResult Index () {
   MyViewModel mvm=new MyViewModel();
   mvm.ListOfSomething=(my code to populate the List);
   return View(vm);
}
</code>```

The View is here :

```<code>@model Project.ViewModels.MyViewModel
@Html.LabelFor(m => m.ListOfSomething)
@Html.DropDownListFor(m => m.ListOfSomething, new SelectList(Model.ListOfSomething, "id", "name"), "-")<br/>
</code>```

And eventually, the [HttpPost] Index of the controller :

```<code>[HttpPost]
public ActionResult Index(MyViewModel mvm) {
    /* Here, how could I get the "Something" object that
       was selected in the dropdownlist and can be identified
       by the "id" property ?
    */

}
</code>```

I'm totally wrong ?
Thanks

答: OK, I understand now that the controller can't instantiate the Something object, it's my job to use the id to find and use the appropriate record or item of the List. Thanks</p>

Body:
As a beginner in c#/asp.net/mvc, I can't find how to get an object from a Html.DropDownList in the View.
Here is my ViewModel :

public class MyViewModel {
   public List<Something> ListOfSomething {get;set;} // A list of Somethings
   public Something TheSomethingToGet {get;set;} // The object I want to get
}

The "Something" object is for example :

public class Something {
   public int Id {get;set;}
   public string Name {get;set;}
   public int AnotherProperty {get;set;}
}

I populate my List<> in the controller :

public ActionResult Index () {
   MyViewModel mvm=new MyViewModel();
   mvm.ListOfSomething=(my code to populate the List);
   return View(vm);
}

The View is here :

@model Project.ViewModels.MyViewModel
@Html.LabelFor(m => m.ListOfSomething)
@Html.DropDownListFor(m => m.ListOfSomething, new SelectList(Model.ListOfSomething, "id", "name"), "-")

And eventually, the [HttpPost] Index of the controller :

[HttpPost]
public ActionResult Index(MyViewModel mvm) {
    /* Here, how could I get the "Something" object that
       was selected in the dropdownlist and can be identified
       by the "id" property ?
    */

}

I'm totally wrong ?
Thanks


问:
Excel VBA - Determining Column or Row Target of Array UDF
I have a simple excel UDF for converting an array of mass values to mol fractions.  Most times, the output will be a column array (n rows by 1 column).

How, from within the VBA environment, do I determine the dimensions of the target cells on the worksheet to ensure that it should be returned as n rows by 1 column versus n columns by 1 row?

```<code>Function molPct(chemsAndMassPctsRng As Range)

Dim chemsRng As Range
Dim massPctsRng As Range
Dim molarMasses()
Dim molPcts()

Set chemsRng = chemsAndMassPctsRng.Columns(1)
Set massPctsRng = chemsAndMassPctsRng.Columns(2)

chems = oneDimArrayZeroBasedFromRange(chemsRng)
massPcts = oneDimArrayZeroBasedFromRange(massPctsRng)

'oneDimArrayZeroBasedFromRange is a UDF to return a zero-based array from a range.

ReDim molarMasses(UBound(chems))
ReDim molPcts(UBound(chems))

totMolarMass = 0

For chemNo = LBound(chems) To UBound(chems)

    molarMasses(chemNo) = massPcts(chemNo) / mw(chems(chemNo))
    totMolarMass = totMolarMass + molarMasses(chemNo)

Next chemNo

For chemNo = LBound(chems) To UBound(chems)

    molPcts(chemNo) = Round(molarMasses(chemNo) / totMolarMass, 2)

Next chemNo

molPct = Application.WorksheetFunction.Transpose(molPcts)

End Function
</code>```

I understand that, if nothing else, I could have an input parameter to flag if return should be as a row array.  I'm hoping to not go that route.

Body:
I have a simple excel UDF for converting an array of mass values to mol fractions.  Most times, the output will be a column array (n rows by 1 column).

How, from within the VBA environment, do I determine the dimensions of the target cells on the worksheet to ensure that it should be returned as n rows by 1 column versus n columns by 1 row?

Function molPct(chemsAndMassPctsRng As Range)

Dim chemsRng As Range
Dim massPctsRng As Range
Dim molarMasses()
Dim molPcts()

Set chemsRng = chemsAndMassPctsRng.Columns(1)
Set massPctsRng = chemsAndMassPctsRng.Columns(2)

chems = oneDimArrayZeroBasedFromRange(chemsRng)
massPcts = oneDimArrayZeroBasedFromRange(massPctsRng)

'oneDimArrayZeroBasedFromRange is a UDF to return a zero-based array from a range.

ReDim molarMasses(UBound(chems))
ReDim molPcts(UBound(chems))

totMolarMass = 0

For chemNo = LBound(chems) To UBound(chems)

    molarMasses(chemNo) = massPcts(chemNo) / mw(chems(chemNo))
    totMolarMass = totMolarMass + molarMasses(chemNo)

Next chemNo

For chemNo = LBound(chems) To UBound(chems)

    molPcts(chemNo) = Round(molarMasses(chemNo) / totMolarMass, 2)

Next chemNo

molPct = Application.WorksheetFunction.Transpose(molPcts)

End Function

I understand that, if nothing else, I could have an input parameter to flag if return should be as a row array.  I'm hoping to not go that route.

Body:
Here is a small example of a UDF() that:

accepts a variable number of input ranges

extracts the unique values in those ranges

creates a suitable output array (column,row, or block)

dumps the unique values to the area

Public Function ExtractUniques(ParamArray Rng()) As Variant
    Dim i As Long, r As Range, c As Collection, OutPut
    Dim rr As Range, k As Long, j As Long

    Set c = New Collection
    '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
    '
    '   First grab all the data and make a Collection of uniques
    '
    '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
    On Error Resume Next
        For i = LBound(Rng) To UBound(Rng)
            Set r = Rng(i)
            For Each rr In r
                c.Add rr.Value, CStr(rr.Value)
            Next rr
        Next i
    On Error GoTo 0
   '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
   '
   '    next create an output array the same size and shape
   '    as the worksheet output area
   '
   ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
    k = 1
    With Application.Caller
        ReDim OutPut(1 To .Rows.Count, 1 To .Columns.Count)
    End With

    For i = LBound(OutPut, 1) To UBound(OutPut, 1)
        For j = LBound(OutPut, 2) To UBound(OutPut, 2)
            If k < c.Count + 1 Then
                OutPut(i, j) = c.Item(k)
                k = k + 1
            Else
                OutPut(i, j) = ""
            End If
        Next j
    Next i
    ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
    '
    '   put the data on the sheet
    '
    ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''

    ExtractUniques = OutPut
End Function


问:
Setting device permission from driver code fails
I want to access I2C device driver nodes from user space in a linux kernel 3.10.14.
I added i2c-dev in the kernel configuration and got the /dev/i2c-* device nodes. However they have permission

```<code>$ ls -l /dev/i2c-*
crw------- root     root      89,   1 2014-08-21 20:00 i2c-1
</code>```

In drivers/i2c/i2c-dev.c I added the callback

```<code>static char *i2c_dev_devnode(struct device *dev, umode_t *mode)
{
    if (!mode)
            return NULL;
    if (MAJOR(dev->devt) == I2C_MAJOR)
            *mode = 0666;
    return NULL;
}
</code>```

and in the same file I added the callback to the device class struct:

```<code>static int __init i2c_dev_init(void)
{
   ...
   i2c_dev_class = class_create(THIS_MODULE, "i2c-dev");
   ...

    /* set access rights */
    i2c_dev_class->devnode = i2c_dev_devnode;
   ...
}
</code>```

However the access rights of the device node remain

```<code>crw------- root     root      89,   1 2014-08-21 20:00 i2c-1
</code>```

There is no /lib/udev/rules.d or /etc/udev/rules.d

I would appreciate any suggestions what might go wrong here.

I am also interested in ideas how to test this issue.

答: Setting up device node is responsibility of udev. So we need to use correct udev rule. Further init.rc approach will fail if driver is loaded after boot time for example in case it is a loadable module. Your distribution might be using another way of supporting hotplug so we need to consult documentation about that distro.</p>

Body:
I want to access I2C device driver nodes from user space in a linux kernel 3.10.14.
I added i2c-dev in the kernel configuration and got the /dev/i2c-* device nodes. However they have permission

$ ls -l /dev/i2c-*
crw------- root     root      89,   1 2014-08-21 20:00 i2c-1

In drivers/i2c/i2c-dev.c I added the callback

static char *i2c_dev_devnode(struct device *dev, umode_t *mode)
{
    if (!mode)
            return NULL;
    if (MAJOR(dev->devt) == I2C_MAJOR)
            *mode = 0666;
    return NULL;
}

and in the same file I added the callback to the device class struct:

static int __init i2c_dev_init(void)
{
   ...
   i2c_dev_class = class_create(THIS_MODULE, "i2c-dev");
   ...

    /* set access rights */
    i2c_dev_class->devnode = i2c_dev_devnode;
   ...
}

However the access rights of the device node remain

crw------- root     root      89,   1 2014-08-21 20:00 i2c-1

There is no /lib/udev/rules.d or /etc/udev/rules.d

I would appreciate any suggestions what might go wrong here.

I am also interested in ideas how to test this issue.


答:
You can pass it as props in this way

```<code><Button label="button" width="80%"/>
</code>```

And create Button component.

```<code>export const Button = (props) => {
return(
    <button
    style={{width: props.width}}   // or you can pass whole style object here
     >
    {props.label}
    </button>
);
}
</code>```

You can pass width in both pixel and percentage.

Title: React: How to pass width as a prop from the component

Body:
You can pass it as props in this way

<Button label="button" width="80%"/>

And create Button component.

export const Button = (props) => {
return(
    <button
    style={{width: props.width}}   // or you can pass whole style object here
     >
    {props.label}
    </button>
);
}

You can pass width in both pixel and percentage.


问:
how to add a class to post_class();
How can I add the bootstrap class md-col-9 to this element when the classes are being pulled through by php?</p>

```<code><li <?php post_class(); ?>>
</li>
</code>```

答:
You can use optional parameter, which can be added to the post_class().

If you need to add only 1 class, then you can make like this <?php post_class( 'class-name' ); ?>

If you need to add more then 1 class, then your code may look like this

```<code><?php

$classes = array(
    'class1',
    'class2',
    'class3',
);
?>

<div <?php post_class( $classes ); ?>>
</code>```

You can read more about it at official documentation here https://codex.wordpress.org/Function_Reference/post_class

Title: how to add a class to post_class();

Body:
How can I add the bootstrap class md-col-9 to this element when the classes are being pulled through by php?

<li <?php post_class(); ?>>

Body:
You can use optional parameter, which can be added to the post_class().

If you need to add only 1 class, then you can make like this <?php post_class( 'class-name' ); ?>

If you need to add more then 1 class, then your code may look like this

<?php

$classes = array(
    'class1',
    'class2',
    'class3',
);
?>

<div <?php post_class( $classes ); ?>>

You can read more about it at official documentation here https://codex.wordpress.org/Function_Reference/post_class


问:
MySQL Slowly changing dimensions SCD2 + ON DUPLICATE KEY UPDATE
Im looking to have MySQL handle Slowly changing dimensions
The table is set up to use 'effective date' as the control - so table structure is similar to here http://en.wikipedia.org/wiki/Slowly_changing_dimension  Type II bottom example.

Is it possible to use this function to update / insert or is it best to seperate the functions eg insert = check for existing then insert, update = update original column, insert new column

Thanks

答:
I have an implementation for such approach without any selects (but with insert/update). MySQL: 5.7
Here is table structure:

```<code>CREATE TABLE UserStatusLog (
  `user_id` int(11) NOT NULL,
  `status_type` tinyint(8) NOT NULL, // we are logging multiple statuses in one table
  `status_value` int(11) NOT NULL, // actual value of the status
  `is_last` tinyint(1) DEFAULT '1', // marking flag
  `start_ts` timestamp NOT NULL DEFAULT '1970-01-01 00:00:01', // when this status_value became actual
  `finish_ts` timestamp NOT NULL DEFAULT '2030-01-01 00:00:00', // end of actuality for this status
  `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, // just for logging
  `updated` timestamp NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP, // just for logging
  PRIMARY KEY (`user_id`,`status_type`,`finish_ts`),
  UNIQUE KEY `uniq` (`user_id`,`status_type`,`is_last`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
</code>```

We are trying to insert new value to log:

```<code>INSERT IGNORE INTO UserStatusLog
(user_id, status_type, status_value, is_last, start_ts, finish_ts)
VALUES ($user_id, $type, $value, NULL, '2017-12-08 15:45:34', '2030-01-01 00:00:00')
ON DUPLICATE KEY UPDATE is_last = IF(start_ts < '2017-12-08 15:45:34' && status_value != VALUES(status_value),
2 /* THIS IS A "SPECIAL VALUE" for is_last */
, is_last);
</code>```

Then, we are comparing result of query via mysql_affected_rows();

0 there is a record with start_ts greater than new one, oe

1 this is a first user's record in log, need to perform update, marking is_last for this record:

UPDATE UserStatusLog
SET is_last = 1
WHERE user_id = $user_id AND status_type = $type AND finish_ts = '2030-01-01 00:00:00' LIMIT 1;

2 there was a record, that is elder than new start_ts, and we've updated it with is_last = 2 (SPECIAL VALUE):

UPDATE test.mock_20171208_47d9ac21808ee65d605ca32205888648
SET is_last = NULL, finish_ts = '2017-12-08 15:45:45'
WHERE user_id = $user_id AND status_type = $type AND is_last = 2 LIMIT 1;
// insert new, really last record
INSERT INTO test.mock_20171208_47d9ac21808ee65d605ca32205888648
(user_id, status_type, status_value, is_last, start_ts, finish_ts)
VALUES
($user_id, $type, $value, $is_last = 1, '2017-12-08 15:45:45', '2030-01-01 00:00:00');

Body:
I have an implementation for such approach without any selects (but with insert/update). MySQL: 5.7
Here is table structure:

CREATE TABLE UserStatusLog (
  `user_id` int(11) NOT NULL,
  `status_type` tinyint(8) NOT NULL, // we are logging multiple statuses in one table
  `status_value` int(11) NOT NULL, // actual value of the status
  `is_last` tinyint(1) DEFAULT '1', // marking flag
  `start_ts` timestamp NOT NULL DEFAULT '1970-01-01 00:00:01', // when this status_value became actual
  `finish_ts` timestamp NOT NULL DEFAULT '2030-01-01 00:00:00', // end of actuality for this status
  `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, // just for logging
  `updated` timestamp NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP, // just for logging
  PRIMARY KEY (`user_id`,`status_type`,`finish_ts`),
  UNIQUE KEY `uniq` (`user_id`,`status_type`,`is_last`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

We are trying to insert new value to log:

INSERT IGNORE INTO UserStatusLog
(user_id, status_type, status_value, is_last, start_ts, finish_ts)
VALUES ($user_id, $type, $value, NULL, '2017-12-08 15:45:34', '2030-01-01 00:00:00')
ON DUPLICATE KEY UPDATE is_last = IF(start_ts < '2017-12-08 15:45:34' && status_value != VALUES(status_value),
2 /* THIS IS A "SPECIAL VALUE" for is_last */
, is_last);

Then, we are comparing result of query via mysql_affected_rows();

0 there is a record with start_ts greater than new one, oe

1 this is a first user's record in log, need to perform update, marking is_last for this record:

UPDATE UserStatusLog
SET is_last = 1
WHERE user_id = $user_id AND status_type = $type AND finish_ts = '2030-01-01 00:00:00' LIMIT 1;

2 there was a record, that is elder than new start_ts, and we've updated it with is_last = 2 (SPECIAL VALUE):

UPDATE test.mock_20171208_47d9ac21808ee65d605ca32205888648
SET is_last = NULL, finish_ts = '2017-12-08 15:45:45'
WHERE user_id = $user_id AND status_type = $type AND is_last = 2 LIMIT 1;
// insert new, really last record
INSERT INTO test.mock_20171208_47d9ac21808ee65d605ca32205888648
(user_id, status_type, status_value, is_last, start_ts, finish_ts)
VALUES
($user_id, $type, $value, $is_last = 1, '2017-12-08 15:45:45', '2030-01-01 00:00:00');


问:
Domain validation using the notification pattern
Historically I have performed validation of my objects within their constructors and thrown an exception when validation fails.  For example:

```<code>class Name
{
    const MIN_LENGTH = 1;

    const MAX_LENGTH = 120;

    private $value;

    public function __construct(string $name)
    {
        if (!$this->isValidNameLength($name)) {
            throw new InvalidArgumentException(
                sprintf('The name must be between %d and %d characters long', self::MIN_LENGTH, self::MAX_LENGTH)
            );
        }
        $this->value = $name;
    }

    public function changeName(string $name)
    {
        return new self($name);
    }

    private function isValidNameLength(string $name)
    {
        return strlen($name) >= self::MIN_LENGTH && strlen($name) <= self::MAX_LENGTH;
    }
}
</code>```

Whilst I like this approach as my object is responsible for enforcing its consistency and ensuring it is always-valid, I've never been overly enthusiastic about the use of exceptions.  Whilst there are people who would argue for and against the use of exceptions as above, it does limit the number of validation messages I can return when performing validation over multiple objects.  For example:

```<code>class Room
{
    private $name;

    private $description;

    public function __construct(Name $name, Description $description)
    {
        $this->name = $name;
        $this->description = $description;
    }
}

class Name
{
    public function __construct(string $name)
    {
        // do some validation
    }
}

class Description
{
    public function __construct(string $description)
    {
        // do some validation
    }
}
</code>```

Should both Name and Description fail validation, I want to be able to return the failure messages for both objects, not just a single exception from whichever object failed first.

Having done some reading on the notification pattern I feel this would be a good fit for my scenario.  Where I become stuck is how I perform validation and prevent my object from entering an invalid state should validation fail.

```<code>class Name
{
    const MIN_LENGTH = 1;

    const MAX_LENGTH = 120;

    private $notification;

    private $value;

    public function __construct(string $name, Notification $notification)
    {
        $this->notification = $notification;
        $this->setName($name);
    }

    private function setName(string $name)
    {
        if ($this->isValidNameLength($name)) {
            $this->value = $name;
        }
    }

    private function isValidNameLength(string $name)
    {
        if (strlen($name) < self::MIN_LENGTH || strlen($name) > self::MAX_LENGTH) {
            $this->notification->addError('NAME_LENGTH_INVALID');
            return false;
        }
        return true;
    }

    public function hasError()
    {
        return $this->notification->hasError();
    }

    public function getError()
    {
        return $this->notification->getError();
    }
}
</code>```

I have a few concerns about the above:

If validation fails, then the object is still constructed but its $value is null which is not a valid state.

After creating a Name, I must remember to call hasError to determine if a validation error has occured.

I am now pebbling my domain objects with hasError/getError functions which I'm not sure is good practice.

Is there a piece of this puzzle I am missing?  How would I got about utilising the notification pattern but ensuring that my object can not enter an invalid state?

答:
How would I got about utilising the notification pattern but ensuring that my object can not enter an invalid state?

Factory pattern - aka "named constructors"

You leave the constructor validation has is -- you never want to create a value that can't preserve its own invariant.

But you take the constructor out of the public API, instead arranging for client code to invoke a method on a factory.  That factory gets to decide how to manage the failure to construct the object - gathering up all of your notifications and then either

throwing an exception that includes the notification collection

returning a failure type that includes the notification collection

depending on whether you prefer handling control flow with exceptions or discriminated unions.

Body:
Historically I have performed validation of my objects within their constructors and thrown an exception when validation fails.  For example:

class Name
{
    const MIN_LENGTH = 1;

    const MAX_LENGTH = 120;

    private $value;

    public function __construct(string $name)
    {
        if (!$this->isValidNameLength($name)) {
            throw new InvalidArgumentException(
                sprintf('The name must be between %d and %d characters long', self::MIN_LENGTH, self::MAX_LENGTH)
            );
        }
        $this->value = $name;
    }

    public function changeName(string $name)
    {
        return new self($name);
    }

    private function isValidNameLength(string $name)
    {
        return strlen($name) >= self::MIN_LENGTH && strlen($name) <= self::MAX_LENGTH;
    }
}

Whilst I like this approach as my object is responsible for enforcing its consistency and ensuring it is always-valid, I've never been overly enthusiastic about the use of exceptions.  Whilst there are people who would argue for and against the use of exceptions as above, it does limit the number of validation messages I can return when performing validation over multiple objects.  For example:

class Room
{
    private $name;

    private $description;

    public function __construct(Name $name, Description $description)
    {
        $this->name = $name;
        $this->description = $description;
    }
}

class Name
{
    public function __construct(string $name)
    {
        // do some validation
    }
}

class Description
{
    public function __construct(string $description)
    {
        // do some validation
    }
}

Should both Name and Description fail validation, I want to be able to return the failure messages for both objects, not just a single exception from whichever object failed first.

Having done some reading on the notification pattern I feel this would be a good fit for my scenario.  Where I become stuck is how I perform validation and prevent my object from entering an invalid state should validation fail.

class Name
{
    const MIN_LENGTH = 1;

    const MAX_LENGTH = 120;

    private $notification;

    private $value;

    public function __construct(string $name, Notification $notification)
    {
        $this->notification = $notification;
        $this->setName($name);
    }

    private function setName(string $name)
    {
        if ($this->isValidNameLength($name)) {
            $this->value = $name;
        }
    }

    private function isValidNameLength(string $name)
    {
        if (strlen($name) < self::MIN_LENGTH || strlen($name) > self::MAX_LENGTH) {
            $this->notification->addError('NAME_LENGTH_INVALID');
            return false;
        }
        return true;
    }

    public function hasError()
    {
        return $this->notification->hasError();
    }

    public function getError()
    {
        return $this->notification->getError();
    }
}

I have a few concerns about the above:

If validation fails, then the object is still constructed but its $value is null which is not a valid state.

After creating a Name, I must remember to call hasError to determine if a validation error has occured.

I am now pebbling my domain objects with hasError/getError functions which I'm not sure is good practice.

Is there a piece of this puzzle I am missing?  How would I got about utilising the notification pattern but ensuring that my object can not enter an invalid state?


问:
Why i got that problems when i run my script?

Hi, is there a solution for this error code ? </p>

```<code>Traceback (most recent call last):
  File "./weevely.py", line 2, in <module>
    from core.terminal import Terminal
  File "/Users/ismailtaibi/Desktop/isdo/scripts/weevely/core/terminal.py", line 6, in <module>
    from core.module import Status
  File "/Users/ismailtaibi/Desktop/isdo/scripts/weevely/core/module.py", line 14, in <module>
    from core.vectorlist import VectorList
  File "/Users/ismailtaibi/Desktop/isdo/scripts/weevely/core/vectorlist.py", line 15, in <module>
    from core.vectors import Os
  File "/Users/ismailtaibi/Desktop/isdo/scripts/weevely/core/vectors.py", line 11, in <module>
    from mako.template import Template
ImportError: No module named mako.template
</code>```

<p>Thanks.
</p>

答:
The answer is pretty self explainatory and with a google search you could have solved everything in seconds.

Here you have a how to install pip if you don`t have it: How do I install pip on macOS or OS X?

After this type in the terminal:
pip install Mako
as stated in the official website: http://www.makotemplates.org/download.html

If this doesn`t work you can manually download the Mako package here:
https://pypi.python.org/pypi/Mako/

Please, also read this carefully:
https://stackoverflow.com/help/how-to-ask

Body:
Hi, is there a solution for this error code ?

Traceback (most recent call last):
  File "./weevely.py", line 2, in <module>
    from core.terminal import Terminal
  File "/Users/ismailtaibi/Desktop/isdo/scripts/weevely/core/terminal.py", line 6, in <module>
    from core.module import Status
  File "/Users/ismailtaibi/Desktop/isdo/scripts/weevely/core/module.py", line 14, in <module>
    from core.vectorlist import VectorList
  File "/Users/ismailtaibi/Desktop/isdo/scripts/weevely/core/vectorlist.py", line 15, in <module>
    from core.vectors import Os
  File "/Users/ismailtaibi/Desktop/isdo/scripts/weevely/core/vectors.py", line 11, in <module>
    from mako.template import Template
ImportError: No module named mako.template

Thanks.


答:
Ok so you have this dropdown and you want to get the real-time options everytime something is selected:

```<code>   $('#Lock').on('change',function() {
       var option
       option = $('#Lock').val()

       $.ajax({
           type: 'post',
           url: "your_php_file.php",
           dataType: 'data',
           data: {
               option: option
           }
       })
   })
</code>```

This code will get the value every time a value is selected from this dropdown and will make an ajax call to your php class that you want to handle. your php class name should be put in the url: field

After that in your php you just retrieve the data like this:

```<code>$option=$_POST['option'];
</code>```

Well this means that you execute an ajax call everytime something is selected. I propose that you put a button and trigger the ajax when the user clicks the button, so setup and onClick event.

Don't forget in your html-head to include the jquery version :

```<code><script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>
</code>```

Title: PHP Echo SUM session value & form select

Body:
I have a PHP echo statement of a session value like this:

<?php echo $userinfo['RenewAgreementAmount'] ;?>

I have a form select element like this:

<select id="Lock" name="Lock">
                      <option value="1" selected="selected">1 Year</option>
                      <option value="2">2 Years</option>
                      <option value="3">3 Years</option>
                      <option value="4">4 Years</option>
                    </select>

I'm trying to update the <?php echo $userinfo['RenewAgreementAmount'] ;?> output by taking what the user selects in the select value id Lock with this session value while interacting with the form?

I've tried <?php echo ($userinfo['RenewAgreementAmount'] * #Lock) ;?> with no luck.

What is the easiest way to update this value as the user interacts with the select form input in real time?

Body:
Ok so you have this dropdown and you want to get the real-time options everytime something is selected:

   $('#Lock').on('change',function() {
       var option
       option = $('#Lock').val()

       $.ajax({
           type: 'post',
           url: "your_php_file.php",
           dataType: 'data',
           data: {
               option: option
           }
       })
   })

This code will get the value every time a value is selected from this dropdown and will make an ajax call to your php class that you want to handle. your php class name should be put in the url: field

After that in your php you just retrieve the data like this:

$option=$_POST['option'];

Well this means that you execute an ajax call everytime something is selected. I propose that you put a button and trigger the ajax when the user clicks the button, so setup and onClick event.

Don't forget in your html-head to include the jquery version :

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>


问:
How to set up an independent progress bar
I'm trying to include a progress bar during the computations in my shiny application. Description of my problem:

My computation takes a while, like 30 seconds

I'm able to evaluate in advance the exact time a computation will take

however, the computation is in one chunk, not splitable in small parts that I could use to manually increment the progress bar, think of it as a large model fitting process.

Currently there are some questions related to the problem but no satisfying answer:
here, here for instance.

Is there a way to implement an bar that progresses on top of a calculation, independently and continuously, for a fixed amount of time (or maybe insert an animation of the bar in a pop-up that mimics the bar?)

Thanks

Edit: I tried to mimic a progress bar with an animated sliderInput, but I couldn't find how programmatically trigger the animation...

答:
Not a complete answer, since my suggestion would be to use progress bars, but I hope it helps a bit.

Here's a way to trigger clicking a slider animate button using some javascript with the shinyjs package:

```<code>library(shiny)
library(shinyjs)

jscode <- "
  shinyjs.play = function() {
    $('.slider-animate-button').trigger('click');
  }
"

ui <- fluidPage(
  useShinyjs(),
  extendShinyjs(text = jscode),
  sliderInput("slider", label = "", width = '600px',
              min = 0,
              max = 20,
              value = 0,
              step = 1,
              animate = animationOptions(
                interval = 100,
                playButton = "Play",
                pauseButton = "Pause"
              )
  )
)

server <- function(input, output,session) {
  observe( {
    js$play()
  })
}

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

Please note that the js code references the slider-animate-button class, so it will trigger every slider animation option in the app.

Body:
Not a complete answer, since my suggestion would be to use progress bars, but I hope it helps a bit.

Here's a way to trigger clicking a slider animate button using some javascript with the shinyjs package:

library(shiny)
library(shinyjs)

jscode <- "
  shinyjs.play = function() {
    $('.slider-animate-button').trigger('click');
  }
"

ui <- fluidPage(
  useShinyjs(),
  extendShinyjs(text = jscode),
  sliderInput("slider", label = "", width = '600px',
              min = 0,
              max = 20,
              value = 0,
              step = 1,
              animate = animationOptions(
                interval = 100,
                playButton = "Play",
                pauseButton = "Pause"
              )
  )
)

server <- function(input, output,session) {
  observe( {
    js$play()
  })
}

shinyApp(ui, server)

Please note that the js code references the slider-animate-button class, so it will trigger every slider animation option in the app.


问:
How can I solve linear equation AX=b for sparse matrix
I have sparse matrix A(120,000*120,000) and a vector b(120,000) and I would like to solve the linear system AX=b using Eigen library. I tried to follow the documentation but I always have an error. I also tried change the matrix to dense and solve the system

```<code>    Eigen::MatrixXd H(N,N);
    HH =Eigen:: MatrixXd(A);
    Eigen::ColPivHouseholderQR<Eigen::MatrixXd> dec(H);
    Eigen::VectorXd RR = dec.solve(b);
</code>```

but I got a memory error.
Please help me find the way to solve this problem.

答:
For sparse systems, we generally use iterative methods. One reason is that direct solvers like LU, QR... factorizations fill your initial matrix (fill in the sense that initially zero components are replaced with nonzero ones). In most of the cases the resulting dense matrix can not fit into the memory anymore (-> your  memory error). In short, iterative solvers do not change your sparsity pattern as they only involve matrix-vector products (no filling).

That said, you must first know if your system is symmetric positive definite (aka SPD) in such case you can use the conjugate gradient method. Otherwise you must use methods for unsymmetric systems like BiCGSTAB or GMRES.

You must know that most of the time we use a preconditioner, especially if your system is ill-conditioned.

Looking at Eigen doc I found(example without preconditioner afaik):

```<code>  int n = 10000;
  VectorXd x(n), b(n);
  SparseMatrix<double> A(n,n);
  /* ... fill A and b ... */
  BiCGSTAB<SparseMatrix<double> > solver;
  solver.compute(A);
  x = solver.solve(b);
  std::cout << "#iterations:     " << solver.iterations() << std::endl;
  std::cout << "estimated error: " << solver.error()      << std::endl;
</code>```

which is maybe a good start (use Conjugate Gradient Method if your matrix is SPD). Note that here, there is no preconditioner, hence convergence will be certainly rather slow.

Recap: big matrix -> iterative method + preconditioner.

This is really a first "basic/naive" explanation, you can found futher information about the theory in Saad's book: Iterative Methods for Sparse Linear Systems. Again this topic is huge you can found plenty of other books on this subject.

I am not an Eigen user, however there are precondtioners here.
-> Incomplete LU (unsymmetric systems) or Incomplete Cholesky (SPD systems) are generally good all purpose preconditioners, there are the firsts to test.

Body:
I have sparse matrix A(120,000*120,000) and a vector b(120,000) and I would like to solve the linear system AX=b using Eigen library. I tried to follow the documentation but I always have an error. I also tried change the matrix to dense and solve the system

    Eigen::MatrixXd H(N,N);
    HH =Eigen:: MatrixXd(A);
    Eigen::ColPivHouseholderQR<Eigen::MatrixXd> dec(H);
    Eigen::VectorXd RR = dec.solve(b);

but I got a memory error.
Please help me find the way to solve this problem.

Body:
For sparse systems, we generally use iterative methods. One reason is that direct solvers like LU, QR... factorizations fill your initial matrix (fill in the sense that initially zero components are replaced with nonzero ones). In most of the cases the resulting dense matrix can not fit into the memory anymore (-> your  memory error). In short, iterative solvers do not change your sparsity pattern as they only involve matrix-vector products (no filling).

That said, you must first know if your system is symmetric positive definite (aka SPD) in such case you can use the conjugate gradient method. Otherwise you must use methods for unsymmetric systems like BiCGSTAB or GMRES.

You must know that most of the time we use a preconditioner, especially if your system is ill-conditioned.

Looking at Eigen doc I found(example without preconditioner afaik):

  int n = 10000;
  VectorXd x(n), b(n);
  SparseMatrix<double> A(n,n);
  /* ... fill A and b ... */
  BiCGSTAB<SparseMatrix<double> > solver;
  solver.compute(A);
  x = solver.solve(b);
  std::cout << "#iterations:     " << solver.iterations() << std::endl;
  std::cout << "estimated error: " << solver.error()      << std::endl;

which is maybe a good start (use Conjugate Gradient Method if your matrix is SPD). Note that here, there is no preconditioner, hence convergence will be certainly rather slow.

Recap: big matrix -> iterative method + preconditioner.

This is really a first "basic/naive" explanation, you can found futher information about the theory in Saad's book: Iterative Methods for Sparse Linear Systems. Again this topic is huge you can found plenty of other books on this subject.

I am not an Eigen user, however there are precondtioners here.
-> Incomplete LU (unsymmetric systems) or Incomplete Cholesky (SPD systems) are generally good all purpose preconditioners, there are the firsts to test.

ContentLicense: CC BY-SA 4.0


问:
jQuery looping checkboxes
I have a page that contains many checkboxes. There are a set of checkboxes that have an ID prefixed with pbfam_ and it is only these I am interested in.

When a user clicks on one of these, I need to get a list of the IDs from that subset of only the ones that are checked, and I need it to be a comma delimited string of the IDs.

The HTML looks like this:

```<code><input type="checkbox" id="pdfam_711131" />
<label for="pdfam_711131" class="VIEWBOX">Temporary Staff</label>
<br />
<input type="checkbox" id="pdfam_711341" />
<label for="pdfam_711341" class="VIEWBOX">Other Contractors</label>
<br />
</code>```

There are about 40 of these checkboxes. What I'm looking for is a string like:

"pdfam_711131, pdfam_711341"

I've tried various things and nothing has worked. I'm quite new to jQuery. This gives me a list of checked ones and returns the checked value in an alert and I was trying to mess around with this but I have got nowhere.

```<code>$('input:checkbox[id^="pdfam_"]:checked').each(function(){alert($(this).attr("id")););
</code>```

答:
You can get all those are selected followed by Join.The get() method returns a specified element from a Map object.

console.log($('input:checkbox[id^="pdfam_"]:checked').map(function() {
   return this.id || null;
}).get().join(','))```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" checked id="pdfam_711131" />
<label for="pdfam_711131" class="VIEWBOX">Temporary Staff</label>
<br />
<input type="checkbox" checked id="pdfam_711341" />
<label for="pdfam_711341" class="VIEWBOX">Other Contractors</label>
<br /></code>```

Title: jQuery looping checkboxes

Body:
I have a page that contains many checkboxes. There are a set of checkboxes that have an ID prefixed with pbfam_ and it is only these I am interested in.

When a user clicks on one of these, I need to get a list of the IDs from that subset of only the ones that are checked, and I need it to be a comma delimited string of the IDs.

The HTML looks like this:

<input type="checkbox" id="pdfam_711131" />
Temporary Staff

<input type="checkbox" id="pdfam_711341" />
Other Contractors

There are about 40 of these checkboxes. What I'm looking for is a string like:

"pdfam_711131, pdfam_711341"

I've tried various things and nothing has worked. I'm quite new to jQuery. This gives me a list of checked ones and returns the checked value in an alert and I was trying to mess around with this but I have got nowhere.

$('input:checkbox[id^="pdfam_"]:checked').each(function(){alert($(this).attr("id")););

Body:
You can get all those are selected followed by Join.The get() method returns a specified element from a Map object.

console.log($('input:checkbox[id^="pdfam_"]:checked').map(function() {
   return this.id || null;
}).get().join(','))

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" checked id="pdfam_711131" />
<label for="pdfam_711131" class="VIEWBOX">Temporary Staff</label>
<br />
<input type="checkbox" checked id="pdfam_711341" />
<label for="pdfam_711341" class="VIEWBOX">Other Contractors</label>
<br />


问:
jQuery hide / show content based on common parent
I've this repeated HTML code.

```<code><div id="id1" class="questio">
  <input type="checkbox" class="c1">
  <div class="c2">Content</div>
</div>

<div id="id2" class="questio">
  <input type="checkbox" class="c1">
  <div class="c2">Another Content</div>
</div>

<div id="id3" class="questio">
  <input type="checkbox" class="c1">
  <div class="c2">Another Content</div>
</div>
</code>```

The wanted behaviour is to hide / show div c2 Content for each section independently based on input.c1 checked or not:

```<code>if ($(".c1").is(":checked")) {
  $('.c2').show();
}
</code>```

I tried somethig like this but I can't go on :

```<code>$("input.c1").each(function() {
  var parent1 = $(this).closest('questio');
  if ($(this).is(":checked")) {
        /// ??
  }
});
</code>```

答:
You can use parent(), like this short-hand:

$(".c1").on('change', function() {
  var parent = $(this).parent().find('.c2');
  parent[$(this).is(":checked") ? "show" : "hide"]();
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.c2 {
  display:none
}</code>```

  <input type="checkbox" class="c1">

Content

  <input type="checkbox" class="c1">

Another Content

  <input type="checkbox" class="c1">

Another Content

```

Body:
I've this repeated HTML code.

  <input type="checkbox" class="c1">

Content

  <input type="checkbox" class="c1">

Another Content

  <input type="checkbox" class="c1">

Another Content

The wanted behaviour is to hide / show div c2 Content for each section independently based on input.c1 checked or not:

if ($(".c1").is(":checked")) {
  $('.c2').show();
}

I tried somethig like this but I can't go on :

$("input.c1").each(function() {
  var parent1 = $(this).closest('questio');
  if ($(this).is(":checked")) {
        /// ??
  }
});

Body:
You can use parent(), like this short-hand:

$(".c1").on('change', function() {
  var parent = $(this).parent().find('.c2');
  parent[$(this).is(":checked") ? "show" : "hide"]();
});

.c2 {
  display:none
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="id1" class="questio">

  <input type="checkbox" class="c1">
  <div class="c2">Content</div>

</div>

<div id="id2" class="questio">

  <input type="checkbox" class="c1">
  <div class="c2">Another Content</div>

</div>

<div id="id3" class="questio">

  <input type="checkbox" class="c1">
  <div class="c2">Another Content</div>

</div>


问:
RequestMethod.PUT = error 403
I'm actually trying to create some REST controllers but each time that I try to use the PUT method I get a 403 error while the GET and DELETE method work fine.

here is my servlet-context.xml :

```<code><?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xmlns:beans="http://www.springframework.org/schema/beans"
             xmlns:context="http://www.springframework.org/schema/context"

             xmlns:mvc="http://www.springframework.org/schema/mvc"
             xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <!-- Anable du model @Controller -->
    <annotation-driven />

    <!-- Résolution des vues utilisées (renvoyées) par les controller - Rendu/Intepretation JSP -->
    <beans:bean id="viewReslover" class="org.springframework.web.servlet.view.InternalResourceViewResolver"></beans:bean>

    <mvc:resources mapping="/resources/**" location="/resources/" />

    <context:component-scan base-package="back_office" />

</beans:beans>
</code>```

here is my web.xml :

```<code><?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/root-context.xml</param-value>
    </context-param>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/servlet-context.xml</param-value>

        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet>
        <servlet-name>LogIn</servlet-name>
        <servlet-class>servlets.LogIn</servlet-class>
    </servlet>
    <servlet>
        <servlet-name>LogOut</servlet-name>
        <servlet-class>servlets.LogOut</servlet-class>
    </servlet>
    <servlet>
        <servlet-name>Registration</servlet-name>
        <servlet-class>servlets.RegistrationServlet</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>LogIn</servlet-name>
        <url-pattern>/log_in</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>LogOut</servlet-name>
        <url-pattern>/log_out</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>Registration</servlet-name>
        <url-pattern>/registration</url-pattern>
    </servlet-mapping>

    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>/back_office</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>/back_office/users</url-pattern>
    </servlet-mapping>
        <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>/back_office/user_update</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>/back_office/user</url-pattern>
    </servlet-mapping>
     <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>/back_office/salon_message</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>/back_office/salon_nbr_message</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>/back_office//addMessage</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>/back_office/message</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>/back_office/delSalon</url-pattern>
    </servlet-mapping>

    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>

    <filter>
        <filter-name>filtre_connexion</filter-name>
        <filter-class>Filtre.Connexion</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>filtre_connexion</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

</web-app>
</code>```

and here is one of my controller :

```<code>@RequestMapping(value = "/back_office/addMessage", method = RequestMethod.PUT)
    public ResponseEntity<String> addMessage(@RequestParam(value = "salon", required = true) String salon,
        @RequestBody String message)
    {
    Tchat t = new Tchat();
    t.add_Message(message, salon, "god");

         return new ResponseEntity<String>("resource saved", HttpStatus.OK);
    }
</code>```

I'm a newbie on java so I may have missed something but I'm stuck on this for a few day now and I have no idea on why it don't work.

答:
Is this correct:

```<code><servlet-mapping>
    <servlet-name>dispatcher</servlet-name>
    <url-pattern>/back_office**//addMessage**</url-pattern>
</servlet-mapping>
</code>```

Looks like it should be:

```<code><servlet-mapping>
    <servlet-name>dispatcher</servlet-name>
    <url-pattern>/back_office/addMessage</url-pattern>
</servlet-mapping>
</code>```

Title: RequestMethod.PUT = error 403

Body:
I'm actually trying to create some REST controllers but each time that I try to use the PUT method I get a 403 error while the GET and DELETE method work fine.

here is my servlet-context.xml :

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xmlns:beans="http://www.springframework.org/schema/beans"
             xmlns:context="http://www.springframework.org/schema/context"

             xmlns:mvc="http://www.springframework.org/schema/mvc"
             xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <annotation-driven />

    <beans:bean id="viewReslover" class="org.springframework.web.servlet.view.InternalResourceViewResolver"></beans:bean>

    <mvc:resources mapping="/resources/**" location="/resources/" />

    <context:component-scan base-package="back_office" />

</beans:beans>

here is my web.xml :

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/root-context.xml</param-value>
    </context-param>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/servlet-context.xml</param-value>

        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet>
        <servlet-name>LogIn</servlet-name>
        <servlet-class>servlets.LogIn</servlet-class>
    </servlet>
    <servlet>
        <servlet-name>LogOut</servlet-name>
        <servlet-class>servlets.LogOut</servlet-class>
    </servlet>
    <servlet>
        <servlet-name>Registration</servlet-name>
        <servlet-class>servlets.RegistrationServlet</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>LogIn</servlet-name>
        <url-pattern>/log_in</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>LogOut</servlet-name>
        <url-pattern>/log_out</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>Registration</servlet-name>
        <url-pattern>/registration</url-pattern>
    </servlet-mapping>

    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>/back_office</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>/back_office/users</url-pattern>
    </servlet-mapping>
        <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>/back_office/user_update</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>/back_office/user</url-pattern>
    </servlet-mapping>
     <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>/back_office/salon_message</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>/back_office/salon_nbr_message</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>/back_office//addMessage</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>/back_office/message</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>/back_office/delSalon</url-pattern>
    </servlet-mapping>

    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>

    <filter>
        <filter-name>filtre_connexion</filter-name>
        <filter-class>Filtre.Connexion</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>filtre_connexion</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

</web-app>

and here is one of my controller :

@RequestMapping(value = "/back_office/addMessage", method = RequestMethod.PUT)
    public ResponseEntity<String> addMessage(@RequestParam(value = "salon", required = true) String salon,
        @RequestBody String message)
    {
    Tchat t = new Tchat();
    t.add_Message(message, salon, "god");

         return new ResponseEntity<String>("resource saved", HttpStatus.OK);
    }

I'm a newbie on java so I may have missed something but I'm stuck on this for a few day now and I have no idea on why it don't work.

Body:
Is this correct:

<servlet-mapping>
    <servlet-name>dispatcher</servlet-name>
    <url-pattern>/back_office**//addMessage**</url-pattern>
</servlet-mapping>

Looks like it should be:

<servlet-mapping>
    <servlet-name>dispatcher</servlet-name>
    <url-pattern>/back_office/addMessage</url-pattern>
</servlet-mapping>


问:
How to reset permission of geolocation in wkwebview
If once user didn't allow location to specific site in WKWebview and again user open same website then WKWebview will not take permission of geolocation access.How will I do it so that WKWebview ask every time for permission of geolocation irrespective of how many times user denied it for same site.

Thanks in advance

答: If its your website in the webview then you do not ask for the location in the webpage.  Instead you have your viewcontroller get the location from the phone and then you inject the location into your webview via javascript with evaluateJavaScript(_:completionHandler:).  This prevents the webpage from ever triggering the permission location popup.</p>