问:
Editing a module seems to have no effect
I am using a module which calculates the shipping method based on item weight. The module appears to install but if I make an edit to the main class, nothing seems to be reflected on the front end.

The main class extends the Mage_Shipping_Model_Carrier_Abstract see below:

```<code><?php
class Laurensmedia_Advancedshipping_Model_Carrier_Advancedshipping
extends Mage_Shipping_Model_Carrier_Abstract
implements Mage_Shipping_Model_Carrier_Interface
{

    protected $_code = 'advancedshipping';
</code>```

The config.xml file looks like this:

```<code><?xml version="1.0"?>
<config>
  <modules>
    <Laurensmedia_Advancedshipping>
      <version>0.1.0</version>
    </Laurensmedia_Advancedshipping>
  </modules>
  <global>
    <helpers>
      <advancedshipping>
        <class>Laurensmedia_Advancedshipping_Helper</class>
      </advancedshipping>
    </helpers>
    <blocks>
      <advancedshipping>
        <class>Laurensmedia_Advancedshipping_Block</class>
      </advancedshipping>
    </blocks>
    <models>
      <advancedshipping>
        <class>Laurensmedia_Advancedshipping_Model</class>
        <resourceModel>advancedshipping_mysql4</resourceModel>
      </advancedshipping>
      <advancedshipping_mysql4>
        <class>Laurensmedia_Advancedshipping_Model_Mysql4</class>
        <entities>
              <matrix>
                <table>advancedshipping_matrix</table>
              </matrix>
        </entities>
      </advancedshipping_mysql4>
            <shipping>
                <rewrite>
                    <shipping>Laurensmedia_Advancedshipping_Model_Shipping_Shipping</shipping>
                </rewrite>
            </shipping>
    </models>
    <resources>
      <advancedshipping_setup>
        <setup>
          <module>Laurensmedia_Advancedshipping</module>
        </setup>
        <connection>
          <use>core_setup</use>
        </connection>
      </advancedshipping_setup>
      <advancedshipping_write>
        <connection>
          <use>core_write</use>
        </connection>
      </advancedshipping_write>
      <advancedshipping_read>
        <connection>
          <use>core_read</use>
        </connection>
      </advancedshipping_read>
    </resources>
  </global>
  <admin>
    <routers>
      <advancedshipping>
        <use>admin</use>
        <args>
          <module>Laurensmedia_Advancedshipping</module>
          <frontName>advancedshipping</frontName>
        </args>
      </advancedshipping>
    </routers>
  </admin>
  <adminhtml>
    <menu>
      <advancedshipping module="advancedshipping">
        <title>Advancedshipping</title>
        <sort_order>100</sort_order>
        <children>
          <matrix module="advancedshipping">
            <title>Manage Matrix</title>
            <sort_order>0</sort_order>
            <action>advancedshipping/adminhtml_matrix</action>
          </matrix>
          <import module="advancedshipping">
            <title>Import from CSV</title>
            <sort_order>1</sort_order>
            <action>advancedshipping/adminhtml_matrix/import</action>
          </import>
          <settings>
            <title>Manage Settings</title>
            <sort_order>999</sort_order>
            <action>adminhtml/system_config/edit/section/lm_advancedshipping</action>
          </settings>
        </children>
      </advancedshipping>
    </menu>
    <acl>
      <resources>
        <all>
          <title>Allow Everything</title>
        </all>
        <admin>
          <children>
            <advancedshipping translate="title" module="advancedshipping">
              <title>Advancedshipping</title>
              <sort_order>1000</sort_order>
              <children>
                  <matrix translate="title">
                    <title>Manage Matrix</title>
                    <sort_order>0</sort_order>
                  </matrix>
                  <import translate="title">
                    <title>Import from CSV</title>
                    <sort_order>1</sort_order>
                  </import>
                  <settings translate="title">
                    <title>Manage Settings</title>
                    <sort_order>999</sort_order>
                  </settings>
              </children>
            </advancedshipping>
          </children>
        </admin>
      </resources>
    </acl>
    <layout>
      <updates>
        <advancedshipping>
          <file>advancedshipping.xml</file>
        </advancedshipping>
      </updates>
    </layout>
  </adminhtml>
    <default>
        <carriers>
            <advancedshipping>
                <active>1</active>
                <model>advancedshipping/carrier_advancedshipping</model>
                <name>Advanced Shipping</name>
                <title>Laurensmedia</title>
                <description>Laurensmedia Advanced Shipping description</description>
                <sort_order>0</sort_order>
            </advancedshipping>
        </carriers>
    </default>
</config>
</code>```

I have tried the following:

Clearing the Magneto cache

Manually deleting the contents of /var/cache/

Copying all of the other modules to ../disabled/ (Effectively
      disabling them)

None of the above seems to have worked. Can anyone offer any suggestions as to why when I edit the main class file nothing happens? Even if I deliberately break the file (i.e - delete half the code) I don't even see any errors.

答:
I don't see a <rewrite> declared for Laurensmedia_Advancedshipping_Model_Carrier_Advancedshipping in the config.

That would explain why it's not being picked up, since it appears to want to rewrite a standard Magento class.

If it's not intended as a rewrite, how is that class being called?

Body:
I am using a module which calculates the shipping method based on item weight. The module appears to install but if I make an edit to the main class, nothing seems to be reflected on the front end.

The main class extends the Mage_Shipping_Model_Carrier_Abstract see below:

<?php
class Laurensmedia_Advancedshipping_Model_Carrier_Advancedshipping
extends Mage_Shipping_Model_Carrier_Abstract
implements Mage_Shipping_Model_Carrier_Interface
{

    protected $_code = 'advancedshipping';

The config.xml file looks like this:

<?xml version="1.0"?>
<config>
  <modules>
    <Laurensmedia_Advancedshipping>
      <version>0.1.0</version>
    </Laurensmedia_Advancedshipping>
  </modules>
  <global>
    <helpers>
      <advancedshipping>
        <class>Laurensmedia_Advancedshipping_Helper</class>
      </advancedshipping>
    </helpers>
    <blocks>
      <advancedshipping>
        <class>Laurensmedia_Advancedshipping_Block</class>
      </advancedshipping>
    </blocks>
    <models>
      <advancedshipping>
        <class>Laurensmedia_Advancedshipping_Model</class>
        <resourceModel>advancedshipping_mysql4</resourceModel>
      </advancedshipping>
      <advancedshipping_mysql4>
        <class>Laurensmedia_Advancedshipping_Model_Mysql4</class>
        <entities>
              <matrix>

advancedshipping_matrix

              </matrix>
        </entities>
      </advancedshipping_mysql4>
            <shipping>
                <rewrite>
                    <shipping>Laurensmedia_Advancedshipping_Model_Shipping_Shipping</shipping>
                </rewrite>
            </shipping>
    </models>
    <resources>
      <advancedshipping_setup>
        <setup>
          <module>Laurensmedia_Advancedshipping</module>
        </setup>
        <connection>
          <use>core_setup</use>
        </connection>
      </advancedshipping_setup>
      <advancedshipping_write>
        <connection>
          <use>core_write</use>
        </connection>
      </advancedshipping_write>
      <advancedshipping_read>
        <connection>
          <use>core_read</use>
        </connection>
      </advancedshipping_read>
    </resources>
  </global>
  <admin>
    <routers>
      <advancedshipping>
        <use>admin</use>
        <args>
          <module>Laurensmedia_Advancedshipping</module>
          <frontName>advancedshipping</frontName>
        </args>
      </advancedshipping>
    </routers>
  </admin>
  <adminhtml>
    <menu>
      <advancedshipping module="advancedshipping">
        <title>Advancedshipping</title>
        <sort_order>100</sort_order>
        <children>
          <matrix module="advancedshipping">
            <title>Manage Matrix</title>
            <sort_order>0</sort_order>
            <action>advancedshipping/adminhtml_matrix</action>
          </matrix>
          <import module="advancedshipping">
            <title>Import from CSV</title>
            <sort_order>1</sort_order>
            <action>advancedshipping/adminhtml_matrix/import</action>
          </import>
          <settings>
            <title>Manage Settings</title>
            <sort_order>999</sort_order>
            <action>adminhtml/system_config/edit/section/lm_advancedshipping</action>
          </settings>
        </children>
      </advancedshipping>
    </menu>
    <acl>
      <resources>
        <all>
          <title>Allow Everything</title>
        </all>
        <admin>
          <children>
            <advancedshipping translate="title" module="advancedshipping">
              <title>Advancedshipping</title>
              <sort_order>1000</sort_order>
              <children>
                  <matrix translate="title">
                    <title>Manage Matrix</title>
                    <sort_order>0</sort_order>
                  </matrix>
                  <import translate="title">
                    <title>Import from CSV</title>
                    <sort_order>1</sort_order>
                  </import>
                  <settings translate="title">
                    <title>Manage Settings</title>
                    <sort_order>999</sort_order>
                  </settings>
              </children>
            </advancedshipping>
          </children>
        </admin>
      </resources>
    </acl>
    <layout>
      <updates>
        <advancedshipping>
          <file>advancedshipping.xml</file>
        </advancedshipping>
      </updates>
    </layout>
  </adminhtml>
    <default>
        <carriers>
            <advancedshipping>
                <active>1</active>
                <model>advancedshipping/carrier_advancedshipping</model>
                <name>Advanced Shipping</name>
                <title>Laurensmedia</title>
                <description>Laurensmedia Advanced Shipping description</description>
                <sort_order>0</sort_order>
            </advancedshipping>
        </carriers>
    </default>
</config>

I have tried the following:

Clearing the Magneto cache

Manually deleting the contents of /var/cache/

Copying all of the other modules to ../disabled/ (Effectively
      disabling them)

None of the above seems to have worked. Can anyone offer any suggestions as to why when I edit the main class file nothing happens? Even if I deliberately break the file (i.e - delete half the code) I don't even see any errors.


来源: stackexchange

问:
How to get version differences between a tag and the latest code in a branch?
We need to validate if a particular file is being used by the development team for other user stories. So every time a developer finishes his changes, he will check the code and create a Tag. now the RM team will checkout the code based on this tag from the branch and need to compare with the latest version of the files in that branch to see if any files are changed post the creation of tag. So how do we compare file versions between a tag and the latest code in the branch.

Any help is highly appreciated. thanks in advance

答:
The git diff command can be used to compare any two versions, not just the HEAD and working tree.

In this case, if you want the changes between the tag <tag> and the branch <branch>, you can run git diff <tag> <branch>. If you only want a list of which files changed, you can add the --name-only parameter.

ContentLicense: CC BY-SA 3.0


问:
validation for php

Possible Duplicate:

  Is there a php library for email address validation?

How can I create a validation for email address?

答:
If you're looking for full control, you can test the email against a regular expression of your own requirements. You can accomplish this using PHP's preg_match() method.

Example:

```<code><?php
   echo preg_match('/^([a-zA-Z0-9_.-])+@([a-zA-Z0-9_.-])+\\.([a-zA-Z])+([a-zA-Z])+$/', 'bob@example.com');
?>
</code>```

If the email address is valid, preg_match will return 1. Otherwise, preg_match will return a value of 0.

-OR-
Use PHP's built in filter:

```<code><?php
   echo filter_var('bob@example.com', FILTER_VALIDATE_EMAIL);
?>
</code>```

Of'course, I've seen many people state that FILTER_VALIDATE_EMAIL is not enough, and return to regular expressions.

You can learn more about PHP regular expressions here:
http://php.net/manual/en/book.regex.php

ContentLicense: CC BY-SA 2.5

Title: validation for php

Body:
If you're looking for full control, you can test the email against a regular expression of your own requirements. You can accomplish this using PHP's preg_match() method.

Example:

<?php
   echo preg_match('/^([a-zA-Z0-9_.-])+@([a-zA-Z0-9_.-])+\\.([a-zA-Z])+([a-zA-Z])+$/', 'bob@example.com');
?>

If the email address is valid, preg_match will return 1. Otherwise, preg_match will return a value of 0.

-OR-
Use PHP's built in filter:

<?php
   echo filter_var('bob@example.com', FILTER_VALIDATE_EMAIL);
?>

Of'course, I've seen many people state that FILTER_VALIDATE_EMAIL is not enough, and return to regular expressions.

You can learn more about PHP regular expressions here:
http://php.net/manual/en/book.regex.php


问:
Error : java.util.ArrayList cannot be cast to java.lang.String
when am running my action i faced Error :
" java.util.ArrayList cannot be cast to java.lang.String "

and this is my code :

```<code> textField_1 = new JTextField();
       textField_1.addActionListener(new ActionListener() {
           public void actionPerformed(ActionEvent e) {
           Object selected = list_1.getSelectedValue();
            Connection conn = null;
            PreparedStatement stmt = null;
            String a =null;
         try{

   conn=DriverManager.getConnection("jdbc:mysql://localhost/flyer","root","000");
   String query= " INSERT INTO flyer_item (discount)  SELECT price * ? FROM `item` WHERE item_name = `?` ";
   Statement st= conn.createStatement();

   java.sql.PreparedStatement ps = conn.prepareStatement(query);
                        ps.setString(1,a);
                        ps.setString(2,(String) selected);
                        ps.executeUpdate();
                        st.executeUpdate(query);

                    } catch (SQLException se){
                        System.out.println(se.getMessage());

                    } }} );
</code>```

Any help please ?

答:
Are you sure about this line ?

```<code>       Object selected = list_1.getSelectedValue();
</code>```

Make sure selected is a String before casting . You can use instanceof operator to check the Object type.

Body:
when am running my action i faced Error :
" java.util.ArrayList cannot be cast to java.lang.String "

and this is my code :

 textField_1 = new JTextField();
       textField_1.addActionListener(new ActionListener() {
           public void actionPerformed(ActionEvent e) {
           Object selected = list_1.getSelectedValue();
            Connection conn = null;
            PreparedStatement stmt = null;
            String a =null;
         try{

   conn=DriverManager.getConnection("jdbc:mysql://localhost/flyer","root","000");
   String query= " INSERT INTO flyer_item (discount)  SELECT price * ? FROM `item` WHERE item_name = `?` ";
   Statement st= conn.createStatement();

   java.sql.PreparedStatement ps = conn.prepareStatement(query);
                        ps.setString(1,a);
                        ps.setString(2,(String) selected);
                        ps.executeUpdate();
                        st.executeUpdate(query);

                    } catch (SQLException se){
                        System.out.println(se.getMessage());

                    } }} );

Any help please ?

Body:
Are you sure about this line ?

       Object selected = list_1.getSelectedValue();

Make sure selected is a String before casting . You can use instanceof operator to check the Object type.


问:
Passing a shell variable into an awk command
I have a loop that processes a bunch of files within a dir. I would like to input the filename into the file it processes, but I'm getting an error. It works perfectly with the myvar syntax but I need that for obvious reasons.

Error

```<code>awk: cmd. line:1: RS=
awk: cmd. line:1:    ^ unexpected newline or end of string
</code>```

Command

```<code>for filename in $files
do
    awk -v "myvar=${filename}"
      RS= '/-- Ticket/{++i; print "PROMPT myvar Line ",
      i ORS $0 ORS; i+=split($0, a, /\n/)+1}' ${filename}.txt
done
</code>```

答:
Couple of issues here, use the -v syntax for each of the variables that you are trying to pass to awk,

```<code>awk -v myvar="${filename}" -v RS= '/-- Ticket/{++i; print "PROMPT " myvar " Line ", i ORS $0 ORS; i+=split($0, a, /\n/)+1}' ${filename}.txt
#  ^^^ variable1           ^^^^^ variable2 --> using separate -v for each
</code>```

should be right approach.

For a shell variable import to awk do it as in my example above, not as "myvar=${filename}" but just myvar="${filename}"

Body:
I have a loop that processes a bunch of files within a dir. I would like to input the filename into the file it processes, but I'm getting an error. It works perfectly with the myvar syntax but I need that for obvious reasons.

Error

awk: cmd. line:1: RS=
awk: cmd. line:1:    ^ unexpected newline or end of string

Command

for filename in $files
do
    awk -v "myvar=${filename}"
      RS= '/-- Ticket/{++i; print "PROMPT myvar Line ",
      i ORS $0 ORS; i+=split($0, a, /\n/)+1}' ${filename}.txt
done

Body:
Couple of issues here, use the -v syntax for each of the variables that you are trying to pass to awk,

awk -v myvar="${filename}" -v RS= '/-- Ticket/{++i; print "PROMPT " myvar " Line ", i ORS $0 ORS; i+=split($0, a, /\n/)+1}' ${filename}.txt
#  ^^^ variable1           ^^^^^ variable2 --> using separate -v for each

should be right approach.

For a shell variable import to awk do it as in my example above, not as "myvar=${filename}" but just myvar="${filename}"


问:
How to determine distance to a point on arc perpendicular from tangent?
Given the following from the image below:

The green circle has a radius equal to B

The yellow line is tangent to the green circle

The vertical purple line is parallel to the green line and perpendicular to the yellow line.

The yellow line is perpendicular to both the green line and the vertical purple line

The purple point is centered on the green circle's edge

A and B are known values

I realize several of these constraints overlap, just trying to be thorough.
Pythagorean's theorem can provide the value of C, just to illustrate what I know we can determine already.

What is the formula/equation to determine D, where D is the perpendicular distance from the tangent yellow line to the arc/circle (at the purple point)?

Update

Replacing previous attempts to illustrate solution now with one that I can now visualize as the correct representation of the answer and comments provided by John

答:
The distance D can be found by computing the lowest intersection between the vertical ray from the right endpoint of the yellow segment and the circle.

Some notations (x axis to the right, y axis to the bottom, origin at the center of the circle):

center of the circle: P_C = (0, 0)

origin of the vertical ray: P_O = (A, B)

direction of the vertical ray: v_d = (0, -1)

Points on the ray satisfy: P = P_O + t v_d = (A, B - t)

Points on the circle satisfy: |P P_O|^2 = B^2

Expanding the first equation into the second gives: A^2 + (B - t)^2 = B^2 = A^2 + B^2 - 2 B t + t^2

Solving t^2 - 2 B t + A^2 = 0 for t yields d = B^2 - A^2 > 0, so two solutions t_1 = B - sqrt(d), t_2 = B + sqrt(d) (one near the bottom of the circle, the other near the top as expected). But t actually gives the distance along the ray (since v_d is a unit vector), so what we are looking for is the smallest solution t_1. Hence D = B - sqrt(B^2 - A^2).

The final result can also be derived and / or verified geometrically (courtesy of John, see all the corresponding comments): D = B - B' and B'^2 + A^2 = B^2 (Pythagorus on the right triangle with the center of the circle and the purple point as two of its vertices and an edge sitting on the purple line).


问:
How to make sure that the font size is correct when copied from an HTML page?
I've got the following page: http://pogopixels.com/test/generated.html

In this page, the title "Massachusetts Personal Auto" is simply:

```<code><h1>Massachusetts Personal Auto</h1>
</code>```

With the following CSS:

```<code>@font-face {
    font-family: MyriadPro-Bold;
    src: url(https://pogopixels.com/clients/widgetworld/fonts/get.php?name=MYRIADPRO-BOLD.OTF);
}

h1 {
    font-family: MyriadPro-Bold;
    font-size: 16px;
    text-align: center;
}
</code>```

The font size is 16px and when I check the element in the Chrome console, I see it's indeed 16px. However, when I copy and paste it in LibreOffice (or any other rich text editor), the font comes out as 12px. On the HTML page it's true that it looks more like 12px than 16px.

I'm not sure what I'm missing. How can I make sure that it looks like 16px and that it's still 16px when I copy and paste it somewhere?

答:
When you copy from a web page, the actual data that gets copied depends on the browser. And when you paste to an application, different applications will have different abilities to interpret the web page data it reads from the clipboard.

For example, when using Chrome to copy from your example page, the clipboard contains HTML with a bunch of inline styles, including font-weight: 16px. LibreOffice Writer seems to be able to pick up some of the font information along with HTML structure such as heading levels, but it changes the font size to 12 despite the inline style info.

When copying from Firefox, the clipboard only contains basic HTML without any inline styles. In this case, LibreOffice Writer doesn't do any special formatting beyond translating some of the HTML to its own concepts of structure (such as heading levels). At least this would allow you to customize the styles that LibreOffice is applying. But obviously you can't do that on behalf of other users.

I don't think there is a way to get consistent results across a variety of sources and destinations.

Body:
I've got the following page: http://pogopixels.com/test/generated.html

In this page, the title "Massachusetts Personal Auto" is simply:

Massachusetts Personal Auto

With the following CSS:

@font-face {
    font-family: MyriadPro-Bold;
    src: url(https://pogopixels.com/clients/widgetworld/fonts/get.php?name=MYRIADPRO-BOLD.OTF);
}

h1 {
    font-family: MyriadPro-Bold;
    font-size: 16px;
    text-align: center;
}

The font size is 16px and when I check the element in the Chrome console, I see it's indeed 16px. However, when I copy and paste it in LibreOffice (or any other rich text editor), the font comes out as 12px. On the HTML page it's true that it looks more like 12px than 16px.

I'm not sure what I'm missing. How can I make sure that it looks like 16px and that it's still 16px when I copy and paste it somewhere?


问:
Using COUNTIFS to find only unique values
I currently have a table with five columns:

```<code>A = Campaign
B = Person
C = Opportunity Name
D = Total Cost of Campaign
E = Date
</code>```

I'm trying to use COUNTIFS to count the number of rows that match the exact value in cell H2 to column A and has a date range, in column E, that is greater than the value in cell I2.

I have something like this so far:

```<code>=countifs($A$2:$A, $H$2, $E$2:$E, ">"&$I$2).
</code>```

However, I'm having a tough time to trying to dedupe this - it should only count unique rows based on the data in column C, where duplicate names exist. Please refer to my data table as reference:

```<code>Campaign    Person  Opportunity Name    Total Cost of Campaign  Date
A           Bob     Airbnb              5000                   3/2/2017
B           Jim     Sony                10000                  3/2/2017
B           Jane    Coca-Cola           10000                  3/2/2017
C           Jim     Sony                200                    3/2/2017
B           Daniel  Sony                10000                  3/2/2017
B           April   Coca-Cola           10000                  3/5/2017
</code>```

For example:

```<code>=countifs($A$2:$A, $H$2, $E$2:$E, ">"&$I$2)
</code>```

with B in H2 and 3/1/2017 in I2 will give me a result of 4 but I'm really trying to extract a value of 2, given that there are only two unique names in Column C (Sony and Coca-Cola).

How could I do this?

答:
Use COUNTUNIQUE with QUERY

```<code>=countunique(QUERY(A:E,"Select C where A = '"&H2&"' and E > date '" & text(I2,"yyyy-mm-dd") & "'",0))
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I currently have a table with five columns:

A = Campaign
B = Person
C = Opportunity Name
D = Total Cost of Campaign
E = Date

I'm trying to use COUNTIFS to count the number of rows that match the exact value in cell H2 to column A and has a date range, in column E, that is greater than the value in cell I2.

I have something like this so far:

=countifs($A$2:$A, $H$2, $E$2:$E, ">"&$I$2).

However, I'm having a tough time to trying to dedupe this - it should only count unique rows based on the data in column C, where duplicate names exist. Please refer to my data table as reference:

Campaign    Person  Opportunity Name    Total Cost of Campaign  Date
A           Bob     Airbnb              5000                   3/2/2017
B           Jim     Sony                10000                  3/2/2017
B           Jane    Coca-Cola           10000                  3/2/2017
C           Jim     Sony                200                    3/2/2017
B           Daniel  Sony                10000                  3/2/2017
B           April   Coca-Cola           10000                  3/5/2017

For example:

=countifs($A$2:$A, $H$2, $E$2:$E, ">"&$I$2)

with B in H2 and 3/1/2017 in I2 will give me a result of 4 but I'm really trying to extract a value of 2, given that there are only two unique names in Column C (Sony and Coca-Cola).

How could I do this?

Body:
Use COUNTUNIQUE with QUERY

=countunique(QUERY(A:E,"Select C where A = '"&H2&"' and E > date '" & text(I2,"yyyy-mm-dd") & "'",0))


问:
Fastest Way To Calculate Directory Sizes
what is the best and fastest way to calculate directory sizes? For example we will have the following structure:

```<code>/users
      /a
      /b
      /c
      /...
</code>```

We need the output to be per user directory:

```<code>a = 1224KB
b = 3533KB
c = 3324KB
...
</code>```

We plan on having tens maybe even hundred of thousands of directories under /users. The following shell command works:

```<code>du -cms /users/a | grep total | awk '{print $1}'
</code>```

But, we will have to call it N number of times. The entire point, is that the output; each users directory size will be stored in our database. Also, we would love to have it update as frequently as possible, but without blocking all the resources on the server. Is it even possible to have it calculate users directory size every minute? How about every 5 minutes?

Now that I am thinking about it some more, would it make sense to use node.js? That way, we can calculate directory sizes, and even insert into the database all in one transaction. We could do that as well in PHP and Python, but not sure it is as fast.

Thanks.

答:
Why not just:

```<code>du -sm /users/*
</code>```

(The slowest part is still likely to be du traversing the filesystem to calculate the size, though).

Body:
what is the best and fastest way to calculate directory sizes? For example we will have the following structure:

/users
      /a
      /b
      /c
      /...

We need the output to be per user directory:

a = 1224KB
b = 3533KB
c = 3324KB
...

We plan on having tens maybe even hundred of thousands of directories under /users. The following shell command works:

du -cms /users/a | grep total | awk '{print $1}'

But, we will have to call it N number of times. The entire point, is that the output; each users directory size will be stored in our database. Also, we would love to have it update as frequently as possible, but without blocking all the resources on the server. Is it even possible to have it calculate users directory size every minute? How about every 5 minutes?

Now that I am thinking about it some more, would it make sense to use node.js? That way, we can calculate directory sizes, and even insert into the database all in one transaction. We could do that as well in PHP and Python, but not sure it is as fast.

Thanks.

Body:
Why not just:

du -sm /users/*

(The slowest part is still likely to be du traversing the filesystem to calculate the size, though).


问:
Get Query Binding array result in codeigniter
I want to prevent injection on my codeigniter script. I used Query Binding array, but It's not fetching out the result... I get this error

Fatal error: Call to a member function result() on a non-object in C:\xampp\htdocs

code bellow

```<code><php
$my = "Select * from gw_marge where amount != ? AND is_activated= ? ORDER BY RAND()";
$this->db->query($my, array(0, 1));
      foreach ($my->result() as $roww)
    {
    $pay = $roww->amount;
    $idd = $roww->id;
  }
 ?>
<p><?php echo $pay.' &'.$idd; ?></p>
</code>```

Where did i get it wrong.

答:
Change

```<code>$this->db->query($my, array(0, 1));
foreach ($my->result() as $roww)
</code>```

to

```<code>$query = $this->db->query($my, array(0, 1));
foreach ($query->result() as $roww)
</code>```

Body:
I want to prevent injection on my codeigniter script. I used Query Binding array, but It's not fetching out the result... I get this error

Fatal error: Call to a member function result() on a non-object in C:\xampp\htdocs

code bellow

<php
$my = "Select * from gw_marge where amount != ? AND is_activated= ? ORDER BY RAND()";
$this->db->query($my, array(0, 1));
      foreach ($my->result() as $roww)
    {
    $pay = $roww->amount;
    $idd = $roww->id;
  }
 ?>

<?php echo $pay.' &'.$idd; ?>

Where did i get it wrong.

Body:
Change

$this->db->query($my, array(0, 1));
foreach ($my->result() as $roww)

to

$query = $this->db->query($my, array(0, 1));
foreach ($query->result() as $roww)


问:
How to save/backup amazon instance local
I would like to lower the cost paying to Amazon.
There are stopped instances that I want to backup and save on my local server, on-prem.

After creating an image from the instance, is there any way I can copy AMI to my local server and remove it from Amazon. So in a day, I will need back, it can transfer back from my local server to Amazon to use it again?

The instance first created on Amazon.
I rather a way to save instance on-premise as a file and not as a virtual server.

The main issue is: How can I transfer and save the image of an instance, that created on Amazon, as a file to the local server and how I can return it back to be in  Amazon, in case I need to build the instance again.

Is there any way to do it?

Thanks a lot!

答:
You can create an image file from your current drive but it will be quite expensive:

create another instance

attach your volume there as the second drive

use something like dd if=/dev/xvd0 of=drive.img ... to copy volume to a file

rsync / ftp / etc  the file to your local drive.

You will be billed for the second instance and for the transfer. When you want to restore the machine - you'll be billed too.

Have you checked free tier? You have a year of free access to AWS for small instances and volumes.


问:
What is the meaning of 'self.diff' in 'forward' of a custom python loss layer for Caffe training?
I try to use a custom python loss layer. When I checked several examples online, such as:

Euclidean loss layer, Dice loss layer,

I notice a variable 'self.diff' is always assigned in 'forward'. Especially for the Dice loss layer,

self.diff[...] = bottom[1].data

I wonder if there is any reason that this variable has to be introduced in forward or I can just use bottom[1].data to access ground truth label?

In addition, what is the point of top[0].reshape(1) in reshape, since by definition in forward, the loss output is a scalar itself.

答:
You need to set the diff attribute of the layer for overall consistency and data communication protocol; it's available other places in the class, and anywhere the loss layer object appears.  bottom is a local parameter, and is not available elsewhere in the same form.

In general, the code is expandable for a variety of applications and more complex computations; the reshaping is part of this, ensuring that the returned value is scalar, even if someone expands the inputs to work with vectors or matrices.


问:
How to send notifications to all devices using Firebase Cloud Messaging
On the Firebase doc, it always has a "to" field with a device/token id... but how can I get it to send the notification to all devices. What do I replace the to field with, or what value do I put in there. I'd removed it altogether but it comes back with an error asking for it. Any ideas?</p>

```<code>{
   "to" : "bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...",
   "data" : {
     "Nick" : "Mario",
     "body" : "great match!",
     "Room" : "PortugalVSDenmark"
   },
 }
</code>```

答:
As Frank van Puffelen said there isn't a way to send to all devices.
What you could do is to subscribe everyone to a single topic in the app side using:

```<code>FirebaseMessaging.getInstance().subscribeToTopic("TopicName");
</code>```

So your message would look like this:

```<code>  {
   "to"   : "/topics/TopicName",
   "data" : {
     "Nick" : "Mario",
     "body" : "great match!",
     "Room" : "PortugalVSDenmark"
   },
 }
</code>```

The topic is automatically created in the Firebase server side, but sometimes it takes a while to show up in the Firebase drop down list.

The number of users in a single topic are unlimited.

Body:
On the Firebase doc, it always has a "to" field with a device/token id... but how can I get it to send the notification to all devices. What do I replace the to field with, or what value do I put in there. I'd removed it altogether but it comes back with an error asking for it. Any ideas?

{
   "to" : "bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...",
   "data" : {
     "Nick" : "Mario",
     "body" : "great match!",
     "Room" : "PortugalVSDenmark"
   },
 }

Body:
As Frank van Puffelen said there isn't a way to send to all devices.
What you could do is to subscribe everyone to a single topic in the app side using:

FirebaseMessaging.getInstance().subscribeToTopic("TopicName");

So your message would look like this:

  {
   "to"   : "/topics/TopicName",
   "data" : {
     "Nick" : "Mario",
     "body" : "great match!",
     "Room" : "PortugalVSDenmark"
   },
 }

The topic is automatically created in the Firebase server side, but sometimes it takes a while to show up in the Firebase drop down list.

The number of users in a single topic are unlimited.


问:
Do md5sum on files inside a directory and check if there are identical files
I'm studying shell script and there is an exercise asking to calculate the md5 hash of all files of a folder. It also asks to, in case there's two files with the same hash, print their names in the terminal. My code can do that, but once it finds a match, it's printed twice. I can't figure out how to exclude the first file name from the next iterations.
Another thing: It's forbidden to create any temporary files to help with the task.

```<code>#!/bin/bash

ifs=$IFS
IFS=$'\n'

echo "Verifying the files inside the directory..."

for file1 in $(find . -maxdepth 1 -type f | cut -d "/" -f2); do
  md51=$(md5sum $file1  | cut -d " " -f1)
  for file2 in $(find . -maxdepth 1 -type f | cut -d "/" -f2 | grep -v "$file1"); do
    md52=$(md5sum $file2 | cut -d " " -f1)
    if [ "$md51" == "$md52" ]; then
      echo "Files $file1 e $file2 are the same."
    fi
  done
done
</code>```

I also would like to know if there is a more efficient way to do this task.

答:
Here is a more efficient way to do this and it doesn't use any temporary files:

```<code>#!/bin/bash

# get the sorted md5sum list of all files into an array in one shot
readarray -t arr < <(find . -maxdepth 1 -type f -exec md5sum {} + | sort)
# loop through the array and compare md5sum of contiguous items
for i in "${arr[@]}"; do
  md5="${i/ */}" # extract md5sum part
  [[ "$md5" = "$prev_md5" ]] && printf '%s\n' "$prev_i" "$i"
  prev_md5="$md5"
  prev_i="$i"
done | sort -u
</code>```

sort -u is required to remove duplicates which get printed when there are more than two identical files

Body:
I'm studying shell script and there is an exercise asking to calculate the md5 hash of all files of a folder. It also asks to, in case there's two files with the same hash, print their names in the terminal. My code can do that, but once it finds a match, it's printed twice. I can't figure out how to exclude the first file name from the next iterations.
Another thing: It's forbidden to create any temporary files to help with the task.

#!/bin/bash

ifs=$IFS
IFS=$'\n'

echo "Verifying the files inside the directory..."

for file1 in $(find . -maxdepth 1 -type f | cut -d "/" -f2); do
  md51=$(md5sum $file1  | cut -d " " -f1)
  for file2 in $(find . -maxdepth 1 -type f | cut -d "/" -f2 | grep -v "$file1"); do
    md52=$(md5sum $file2 | cut -d " " -f1)
    if [ "$md51" == "$md52" ]; then
      echo "Files $file1 e $file2 are the same."
    fi
  done
done

I also would like to know if there is a more efficient way to do this task.

Body:
Here is a more efficient way to do this and it doesn't use any temporary files:

#!/bin/bash

# get the sorted md5sum list of all files into an array in one shot
readarray -t arr < <(find . -maxdepth 1 -type f -exec md5sum {} + | sort)
# loop through the array and compare md5sum of contiguous items
for i in "${arr[@]}"; do
  md5="${i/ */}" # extract md5sum part
  [[ "$md5" = "$prev_md5" ]] && printf '%s\n' "$prev_i" "$i"
  prev_md5="$md5"
  prev_i="$i"
done | sort -u

sort -u is required to remove duplicates which get printed when there are more than two identical files


问:
enterprise library data blocks throwing an exception
I am working on a new application and just downloaded enterprise library through nuget using the below command:

Install-Package EnterpriseLibrary.Data

whenever I tried calling the below statement, I am getting the following error:

```<code> Database objDB = DatabaseFactory.CreateDatabase();
</code>```

The exception is

Server Error in '/' Application.

```<code>Database provider factory not set for the static DatabaseFactory. Set a provider factory invoking the DatabaseFactory.SetProviderFactory method or by specifying custom mappings by calling the DatabaseFactory.SetDatabases method.
</code>```

My config file looks like this:

```<code> <configSections>

<!--<section name="dataConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSettings, Microsoft.Practices.EnterpriseLibrary.Data, Version=6.0.1304.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="true" ></section>-->
<section name="dataConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSettings, Microsoft.Practices.EnterpriseLibrary.Data"/>
</code>```

and my connection string is like below:

```<code>  <connectionStrings>
<add name="Dbconnection"
   connectionString="Server=SQL100; Database=Test_db ; Trusted_Connection=Yes; "
   providerName="System.Data.SqlClient"   />
</code>```

The method that I created to call the stored procedure is below:

```<code> string connStr = ConfigurationManager.AppSettings["ConnString"].ToString();
 DataSet ds = new DataSet();

        Database objDB = DatabaseFactory.CreateDatabase();

        DbCommand cmd;

        try

        {

            cmd = objDB.GetStoredProcCommand("sp_PubTables");

            ds = objDB.ExecuteDataSet(cmd);

            return ds;

        }

        catch (Exception ex)

        {

            throw ex;

        }
</code>```

any help will be appreciated. I am using Visual studio 2015. My entire config file is below

```<code>     <?xml version="1.0" encoding="utf-8"?>
<!--
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=169433
  -->
<configuration>
  <configSections>

    <section name="dataConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSettings, Microsoft.Practices.EnterpriseLibrary.Data, Version=6.0.1304.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="true" ></section>
    <!--<section name="dataConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSettings, Microsoft.Practices.EnterpriseLibrary.Data"/>-->
  </configSections>
  <system.web>
    <compilation debug="true" targetFramework="4.5.2" />
    <httpRuntime targetFramework="4.5.2" />
    <httpModules>
      <add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" />
    </httpModules>

  <pages>
      <controls>
        <add tagPrefix="ajaxToolkit" assembly="AjaxControlToolkit" namespace="AjaxControlToolkit" />
      </controls>
    </pages></system.web>
  <connectionStrings>
    <add name="Dbconnection"
       connectionString="Server=SQL100; Database=test_db ; Trusted_Connection=Yes; "
       providerName="System.Data.SqlClient"   />

  </connectionStrings>

  <system.codedom>
    <compilers>
      <compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:6 /nowarn:1659;1699;1701" />
      <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:14 /nowarn:41008 /define:_MYTYPE=\"Web\" /optionInfer+" />
    </compilers>
  </system.codedom>
  <system.webServer>
    <validation validateIntegratedModeConfiguration="false" />
    <modules>
      <remove name="ApplicationInsightsWebTracking" />
      <add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" preCondition="managedHandler" />
    </modules>

  </system.webServer>
</configuration>
</code>```

答:
Try adding this to your config in the <configuration> node:

```<code><dataConfiguration defaultDatabase="Dbconnection" />
</code>```

Body:
I am working on a new application and just downloaded enterprise library through nuget using the below command:

Install-Package EnterpriseLibrary.Data

whenever I tried calling the below statement, I am getting the following error:

 Database objDB = DatabaseFactory.CreateDatabase();

The exception is

Server Error in '/' Application.

Database provider factory not set for the static DatabaseFactory. Set a provider factory invoking the DatabaseFactory.SetProviderFactory method or by specifying custom mappings by calling the DatabaseFactory.SetDatabases method.

My config file looks like this:

 <configSections>

and my connection string is like below:

  <connectionStrings>
<add name="Dbconnection"
   connectionString="Server=SQL100; Database=Test_db ; Trusted_Connection=Yes; "
   providerName="System.Data.SqlClient"   />

The method that I created to call the stored procedure is below:

 string connStr = ConfigurationManager.AppSettings["ConnString"].ToString();
 DataSet ds = new DataSet();

        Database objDB = DatabaseFactory.CreateDatabase();

        DbCommand cmd;

        try

        {

            cmd = objDB.GetStoredProcCommand("sp_PubTables");

            ds = objDB.ExecuteDataSet(cmd);

            return ds;

        }

        catch (Exception ex)

        {

            throw ex;

        }

any help will be appreciated. I am using Visual studio 2015. My entire config file is below

     <?xml version="1.0" encoding="utf-8"?>

<configuration>
  <configSections>

  </configSections>
  <system.web>
    <compilation debug="true" targetFramework="4.5.2" />
    <httpRuntime targetFramework="4.5.2" />
    <httpModules>
      <add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" />
    </httpModules>

  <pages>
      <controls>
        <add tagPrefix="ajaxToolkit" assembly="AjaxControlToolkit" namespace="AjaxControlToolkit" />
      </controls>
    </pages></system.web>
  <connectionStrings>
    <add name="Dbconnection"
       connectionString="Server=SQL100; Database=test_db ; Trusted_Connection=Yes; "
       providerName="System.Data.SqlClient"   />

  </connectionStrings>

  <system.codedom>
    <compilers>
      <compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:6 /nowarn:1659;1699;1701" />
      <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:14 /nowarn:41008 /define:_MYTYPE=\"Web\" /optionInfer+" />
    </compilers>
  </system.codedom>
  <system.webServer>
    <validation validateIntegratedModeConfiguration="false" />
    <modules>
      <remove name="ApplicationInsightsWebTracking" />
      <add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" preCondition="managedHandler" />
    </modules>

  </system.webServer>
</configuration>

Body:
Try adding this to your config in the <configuration> node:

<dataConfiguration defaultDatabase="Dbconnection" />


问:
CSS overlay with scrolling content
I am trying to get a content panel inside a fixed-position overlay to scroll vertically, but it does not scroll, it is forced into its container.

Can you spot the mistake?
fiddle

Only the green bottom should scroll the header should stay where it is.

```<code><html>
<head>
    <style>
        * {
            box-sizing: border-box;
        }
    </style>
</head>
<body style="background-color: #502074;">
    <div style="position: fixed; width:100%; height: 100%;">
        <div style="height: 80px; width: 100%; background-color: yellow;">Top</div>
        <div style="height: 10000px; width: 100%; background-color: green; overflow: scroll;">Bottom</div>
    </div>

</body>
</html>
</code>```

答:
You can avoid adding a container to your Bottom element by moving its height to an ::after pseudo-element:

```<code>.bottom {
  overflow-y: scroll;
  height: calc(100% - 80px);
}

.bottom::after {
  content: '';
  display: block;
  height: 10000px;
}
</code>```

Updated Fiddle

Title: CSS overlay with scrolling content

Body:
I am trying to get a content panel inside a fixed-position overlay to scroll vertically, but it does not scroll, it is forced into its container.

Can you spot the mistake?
fiddle

Only the green bottom should scroll the header should stay where it is.

Top

Bottom

Body:
You can avoid adding a container to your Bottom element by moving its height to an ::after pseudo-element:

.bottom {
  overflow-y: scroll;
  height: calc(100% - 80px);
}

.bottom::after {
  content: '';
  display: block;
  height: 10000px;
}

Updated Fiddle


问:
UIStackView : Is it really necessary to call both removeFromSuperView and removeArrangedSubview to remove a subview?
From the UIStackView Class Reference

In removeArrangedSubview:

To prevent the view from appearing on screen after calling the stack’s removeArrangedSubview: method, explicitly remove the view from the subviews array by calling the view’s removeFromSuperview method.

In arrangedSubview:

Whenever an arranged view’s removeFromSuperview method is called, the stack view removes the view from its arrangedSubview array

From these, it seems that calling just removeFromSuperview is enough to remove a subview and I've been using it like that without problems. I also confirmed the behavior by logging the count of the arrangedSubviews array when removeFromSuperview is called.

A lot of tutorials and comments here on S/O however, say to call both. Is there a reason for this? Or do people just do it because the documentation says so?

答:
You're right, just the call to removeFromSuperview is sufficient to have the view fully removed.

I suspect the reason for people putting both is because they run across the removeArrangedSubview documentation which seems to say both are needed. (And indeed, they are, if you call removeArrangedSubview and want the view really gone.)

The additional doc in arrangedSubviews is not seen by so many, so they don't realize removeArrangedSubview is, in this case, optional.


答:
You need to include column C in your formula and use COUNTUNIQUE function as @Jeeped have suggested. Here is the final formula that you can use:

```<code>=COUNTUNIQUE(IFERROR(FILTER(C:C,A:A=H2,E:E>I2)))
</code>```

Title: Using COUNTIFS to find only unique values

Body:
You need to include column C in your formula and use COUNTUNIQUE function as @Jeeped have suggested. Here is the final formula that you can use:

=COUNTUNIQUE(IFERROR(FILTER(C:C,A:A=H2,E:E>I2)))


问:
System.Management Implementation in Windows Form Won't Work
Using Visual Studios RC 2017, using their template for a .NET Windows Form Application

Trying to get a list of usb devices from my computer, and stick it crudely into a rTextbox for a school project, using a function in System.Management called "GetUSBDevices()".

Attempting to do this using a function I know System.Management has, and that works while using in a Visual Studios C# Console Application Template,and for some reason It won't recognize the reference...

I've tried:

Adding System.Management as a reference through the solution explorer

reinstalling the System.Management Reference

calling the function directly from the library [ System.Management.GetUSBDevices(); ]

And nothing has worked so far...

Code That Doesn't Work:

```<code>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Management; //ISSUE HERE!
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Manager
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        public void DisplayProcess()
        {
            richTextBox1.Clear();
            Process[] plist = Process.GetProcesses();

            foreach (Process p in plist)
            {
                richTextBox1.Text += "Process " + p.Id.ToString() + " : " + p.ProcessName.ToString() + "\n";
            }

        }
//-----------------------------------ISSUE HERE-----------------------------
//-----------------------------------ISSUE HERE-----------------------------
//-----------------------------------ISSUE HERE-----------------------------
        private void DisplayUSB()
        {
            richTextBox1.Clear();

            var usbDevices = GetUSBDevices();

            foreach (var usb in usbDevices)
            {
                richTextBox1.Text += "USB Device " + usb.DeviceID;
            }
        }
        private void button1_Click(object sender, EventArgs e)
        {
            switch (button1.Text)
            {
                case "Start":
                    button1.Text = "USB";
                    DisplayProcess();

                    break;

                case "USB":
                    button1.Text = "Manager";
                    // DisplayUSB();
                    break;

                case "Manager":
                    DisplayProcess();
                    button1.Text = "USB";
                    break;

                                }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            switch(button1.Text)
            {
                case "Start":
                    MessageBox.Show("Please Start The Manager!","REFRESH ERROR");
                    break;

                case "USB":
                    DisplayProcess();
                    break;

                //case "Manager":
                //    DisplayUSB();
                //    break;

            }
        }
    }
}
</code>```

Errors given are:

```<code>Error   CS0103  The name 'GetUSBDevices' does not exist in the current context  Manager c:\users\*****\documents\visual studio 2017\Projects\Manager\Manager\Form1.cs   38
</code>```

Error   CS1579  foreach statement cannot operate on variables of type '?' because '?' does not contain a public definition for 'GetEnumerator'  Manager c:\users*****\documents\visual studio 2017\Projects\Manager\Manager\Form1.cs   40

Code That Does Work (taken from Get List of connected USB Devices  and tested personally, works on my PC fine)

```<code>namespace ConsoleApplication1
{
  using System;
  using System.Collections.Generic;
  using System.Management;

  class Program
  {
    static void Main(string[] args)
    {
      var usbDevices = GetUSBDevices();

      foreach (var usbDevice in usbDevices)
      {
        Console.WriteLine("Device ID: {0}, PNP Device ID: {1}, Description: {2}",
            usbDevice.DeviceID, usbDevice.PnpDeviceID, usbDevice.Description);
      }

      Console.Read();
    }

    }
}
</code>```

Will very much appreciate any help i can get in the matter, so it will work!

答: Function GetUSBDevices() is not in System.Management but in the code you copied from the other SO question. So my guess is that you forgot to copy that piece of code ;-).

Body:
Using Visual Studios RC 2017, using their template for a .NET Windows Form Application

Trying to get a list of usb devices from my computer, and stick it crudely into a rTextbox for a school project, using a function in System.Management called "GetUSBDevices()".

Attempting to do this using a function I know System.Management has, and that works while using in a Visual Studios C# Console Application Template,and for some reason It won't recognize the reference...

I've tried:

Adding System.Management as a reference through the solution explorer

reinstalling the System.Management Reference

calling the function directly from the library [ System.Management.GetUSBDevices(); ]

And nothing has worked so far...

Code That Doesn't Work:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Management; //ISSUE HERE!
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Manager
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        public void DisplayProcess()
        {
            richTextBox1.Clear();
            Process[] plist = Process.GetProcesses();

            foreach (Process p in plist)
            {
                richTextBox1.Text += "Process " + p.Id.ToString() + " : " + p.ProcessName.ToString() + "\n";
            }

        }
//-----------------------------------ISSUE HERE-----------------------------
//-----------------------------------ISSUE HERE-----------------------------
//-----------------------------------ISSUE HERE-----------------------------
        private void DisplayUSB()
        {
            richTextBox1.Clear();

            var usbDevices = GetUSBDevices();

            foreach (var usb in usbDevices)
            {
                richTextBox1.Text += "USB Device " + usb.DeviceID;
            }
        }
        private void button1_Click(object sender, EventArgs e)
        {
            switch (button1.Text)
            {
                case "Start":
                    button1.Text = "USB";
                    DisplayProcess();

                    break;

                case "USB":
                    button1.Text = "Manager";
                    // DisplayUSB();
                    break;

                case "Manager":
                    DisplayProcess();
                    button1.Text = "USB";
                    break;

                                }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            switch(button1.Text)
            {
                case "Start":
                    MessageBox.Show("Please Start The Manager!","REFRESH ERROR");
                    break;

                case "USB":
                    DisplayProcess();
                    break;

                //case "Manager":
                //    DisplayUSB();
                //    break;

            }
        }
    }
}

Errors given are:

Error   CS0103  The name 'GetUSBDevices' does not exist in the current context  Manager c:\users\*****\documents\visual studio 2017\Projects\Manager\Manager\Form1.cs   38

Error   CS1579  foreach statement cannot operate on variables of type '?' because '?' does not contain a public definition for 'GetEnumerator'  Manager c:\users*****\documents\visual studio 2017\Projects\Manager\Manager\Form1.cs   40

Code That Does Work (taken from Get List of connected USB Devices  and tested personally, works on my PC fine)

namespace ConsoleApplication1
{
  using System;
  using System.Collections.Generic;
  using System.Management;

  class Program
  {
    static void Main(string[] args)
    {
      var usbDevices = GetUSBDevices();

      foreach (var usbDevice in usbDevices)
      {
        Console.WriteLine("Device ID: {0}, PNP Device ID: {1}, Description: {2}",
            usbDevice.DeviceID, usbDevice.PnpDeviceID, usbDevice.Description);
      }

      Console.Read();
    }

    }
}

Will very much appreciate any help i can get in the matter, so it will work!


问:
Increasing stack not working
How do can i properly increase the stack available for a program using either Bloodshed Dev C++ or Code::Block? Im running simple bubble and quick sort that work, but when i changed the stack in Code::Block (found out how over here) it made my program crash even faster, despite using much more than suggested space. originally, the program was crashing while sorting 64K of random integers (using the rand() function). Now, its crashing at 32K. im getting the error: Process returned -1073741571 (0xC00000FD)

the program actually runs faster without having the stack changed, assuming im doing it right. gcc -Wl,--stack,1099511627776

i cant figure out how to change it at all in Dev C++

What should i do?
is there any way to change the stack within the code itself?
here is the code im using for bubble and quick sort. there are two of each: one is with vectors, the other is with arrays. i think that the bubble sort. should be correct. the quick sort, im not so sure about. sorry if its a bit messy

```<code>vector <int> v_bubble(vector <int> array){
    // Vector Bubble Sort
    if (array.size() < 2){
        return array;
    }
    int s = 1;
    while (s){
        s = 0;
        for (unsigned int x = 0; x < (array.size() - 1); x++){
            if (array[x] > array[x + 1]){
                int t = array[x];
                array[x] = array[x + 1];
                array[x + 1] = t;
                s = 1;
            }
        }
    }
    return array;
}

void a_bubble(int array[], int size){
    // Array Bubble Sort
    int s = 1;
    while (s){
        s = 0;
        for (int x = 0; x < (size - 1); x++){
            if (array[x] > array[x + 1]){
                int t = array[x];
                array[x] = array[x + 1];
                array[x + 1] = t;
                s = 1;
            }
        }
    }
}

vector <int> v_quick(vector <int> array){
    //Vector Quick Sort
    if (array.size() < 2){
        return array;
    }
    vector <int> left;
    vector <int> right;
    int p_location = array.size() / 2 - 1;
    int pivot = array[p_location];
    for(unsigned int x = p_location; x < array.size() - 1; x++){
        array[x] = array[x + 1];
    }
    array.pop_back();
    for(unsigned int x = 0; x < array.size(); x++){
        if (array[x] <= pivot) {
            left.push_back(array[x]);
        }
        else if (array[x] > pivot){
            right.push_back(array[x]);
        }
    }
    vector <int> p;
    p.push_back(pivot);
    return combine(combine(v_quick(left), p), v_quick(right));
}

int a_quick(int array[], int size, int l_index = -1, int r_index = -1){
    //Array Quick Sort
    if (size < 2){
        return array[size];
    }
    array[size] = array[size];
    int left[size];
    int right[size];
    l_index = 0;
    r_index = 0;
    int p_location = size / 2 - 1;
    int pivot = array[p_location];
    for(int x = p_location; x < size - 1; x++){
        array[x] = array[x + 1];
    }
    size--;
    for(unsigned int x = 0; x < size; x++){
        if (array[x] <= pivot) {
            left[l_index] = array[x];
            l_index++;
        }
        else if (array[x] > pivot){
            right[r_index] = array[x];
            r_index++;
        }
    }
    return a_quick(left, l_index, l_index, r_index) + pivot + a_quick(right, r_index, l_index, r_index);
}
</code>```

the rest of the code is simply generating arrays and vectors with 32, 64 and 128 k entries, sorting them using the above code and returning the time. that part im pretty sure i did not screw up

my main is basically just

```<code>    start = clock();
    a_quick(array1, 32000);
    end = clock();
    cout << "\nQuick Sort\tArray\t32000\t" << ((double) end - start)/CLOCKS_PER_SEC << " seconds\n";
</code>```

over and over again

答:
Unless you're programming for a very memory-constrained embedded environment, I suspect you've got a recursion bug in your sort implementations that is causing stack overflow.  Changing the stack size shouldn't be necessary unless you're dealing with truly enormous (many GB) arrays.

Care to post some code?

Title: Increasing stack not working

Body:
How do can i properly increase the stack available for a program using either Bloodshed Dev C++ or Code::Block? Im running simple bubble and quick sort that work, but when i changed the stack in Code::Block (found out how over here) it made my program crash even faster, despite using much more than suggested space. originally, the program was crashing while sorting 64K of random integers (using the rand() function). Now, its crashing at 32K. im getting the error: Process returned -1073741571 (0xC00000FD)

the program actually runs faster without having the stack changed, assuming im doing it right. gcc -Wl,--stack,1099511627776

i cant figure out how to change it at all in Dev C++

What should i do?
is there any way to change the stack within the code itself?
here is the code im using for bubble and quick sort. there are two of each: one is with vectors, the other is with arrays. i think that the bubble sort. should be correct. the quick sort, im not so sure about. sorry if its a bit messy

vector <int> v_bubble(vector <int> array){
    // Vector Bubble Sort
    if (array.size() < 2){
        return array;
    }
    int s = 1;
    while (s){
        s = 0;
        for (unsigned int x = 0; x < (array.size() - 1); x++){
            if (array[x] > array[x + 1]){
                int t = array[x];
                array[x] = array[x + 1];
                array[x + 1] = t;
                s = 1;
            }
        }
    }
    return array;
}

void a_bubble(int array[], int size){
    // Array Bubble Sort
    int s = 1;
    while (s){
        s = 0;
        for (int x = 0; x < (size - 1); x++){
            if (array[x] > array[x + 1]){
                int t = array[x];
                array[x] = array[x + 1];
                array[x + 1] = t;
                s = 1;
            }
        }
    }
}

vector <int> v_quick(vector <int> array){
    //Vector Quick Sort
    if (array.size() < 2){
        return array;
    }
    vector <int> left;
    vector <int> right;
    int p_location = array.size() / 2 - 1;
    int pivot = array[p_location];
    for(unsigned int x = p_location; x < array.size() - 1; x++){
        array[x] = array[x + 1];
    }
    array.pop_back();
    for(unsigned int x = 0; x < array.size(); x++){
        if (array[x] <= pivot) {
            left.push_back(array[x]);
        }
        else if (array[x] > pivot){
            right.push_back(array[x]);
        }
    }
    vector <int> p;
    p.push_back(pivot);
    return combine(combine(v_quick(left), p), v_quick(right));
}

int a_quick(int array[], int size, int l_index = -1, int r_index = -1){
    //Array Quick Sort
    if (size < 2){
        return array[size];
    }
    array[size] = array[size];
    int left[size];
    int right[size];
    l_index = 0;
    r_index = 0;
    int p_location = size / 2 - 1;
    int pivot = array[p_location];
    for(int x = p_location; x < size - 1; x++){
        array[x] = array[x + 1];
    }
    size--;
    for(unsigned int x = 0; x < size; x++){
        if (array[x] <= pivot) {
            left[l_index] = array[x];
            l_index++;
        }
        else if (array[x] > pivot){
            right[r_index] = array[x];
            r_index++;
        }
    }
    return a_quick(left, l_index, l_index, r_index) + pivot + a_quick(right, r_index, l_index, r_index);
}

the rest of the code is simply generating arrays and vectors with 32, 64 and 128 k entries, sorting them using the above code and returning the time. that part im pretty sure i did not screw up

my main is basically just

    start = clock();
    a_quick(array1, 32000);
    end = clock();
    cout << "\nQuick Sort\tArray\t32000\t" << ((double) end - start)/CLOCKS_PER_SEC << " seconds\n";

over and over again


问:
Getting the third moving date
I need to get the third moving date based on address for each person. Either status change or address change will make DT change. For example, for PERSON_ID:1, the third moving date should be 07/16/2016. Thanks!
The data is as below:</p>

```<code>PERSON_ID      STATUS      DT        ADDRESS
1                12      5/6/2016      3
1                 6      5/8/2016      3
1                 7      6/5/2016      3
1                 1      6/13/2016     3
1                 12    6/20/2016      1
1                 17    7/8/2016       1
1                  1    7/11/2016      1
1                 12    7/16/2016      2
1                  3    12/6/2016      2
2                  5    3/11/2016      5
2                  1    5/15/2016      4
2                  6    7/18/2016      6
2                 12    7/21/2016      6
</code>```

答:
Question is not entirely clear </p>

```<code>select PERSON_ID, STATUS, DT, ADDRESS
from ( select PERSON_ID, STATUS, DT, ADDRESS
            , row_number() over (partition by person order by dt) as rn
         from ( select PERSON_ID, STATUS, DT, ADDRESS
                     , row_number() over ( partition by PERSON_ID, address order by dt) as rn
                 from table
              ) tt
          where tt.rn = 1
     ) rr
 where rr.rn = 3
</code>```

Title: Getting the third moving date

Body:
I need to get the third moving date based on address for each person. Either status change or address change will make DT change. For example, for PERSON_ID:1, the third moving date should be 07/16/2016. Thanks!
The data is as below:

PERSON_ID      STATUS      DT        ADDRESS
1                12      5/6/2016      3
1                 6      5/8/2016      3
1                 7      6/5/2016      3
1                 1      6/13/2016     3
1                 12    6/20/2016      1
1                 17    7/8/2016       1
1                  1    7/11/2016      1
1                 12    7/16/2016      2
1                  3    12/6/2016      2
2                  5    3/11/2016      5
2                  1    5/15/2016      4
2                  6    7/18/2016      6
2                 12    7/21/2016      6

Body:
Question is not entirely clear

select PERSON_ID, STATUS, DT, ADDRESS
from ( select PERSON_ID, STATUS, DT, ADDRESS
            , row_number() over (partition by person order by dt) as rn
         from ( select PERSON_ID, STATUS, DT, ADDRESS
                     , row_number() over ( partition by PERSON_ID, address order by dt) as rn
                 from table
              ) tt
          where tt.rn = 1
     ) rr
 where rr.rn = 3


问:
Expected a colon error issues
Having a hard time figuring out why I am getting a expected a ';' after the function parseString.   </p>

```<code>#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

typedef struct Integer50
{
// a dynamically allocated array to hold a 50
// digit integer, stored in reverse order
int *digits;
} Integer50;

main() {
    Integer50 * parseString(char * str)
    { //error is on this colon
        return NULL;
    }
}
</code>```

答:
This:

```<code>main() {
    Integer50 * parseString(char * str)
    { //error is on this colon
        return NULL;
    }
}
</code>```

Should be replaced by:

```<code>Integer50 * parseString(char * str)
{ //error is on this colon
    return NULL;
}

int main() {
    //If you need to call that `parseString` function call it here
}
</code>```

So, C doesn't support function inside function. main is a function and parseString is another function. That's the problem.

Title: Expected a colon error issues

Body:
Having a hard time figuring out why I am getting a expected a ';' after the function parseString.

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

typedef struct Integer50
{
// a dynamically allocated array to hold a 50
// digit integer, stored in reverse order
int *digits;
} Integer50;

main() {
    Integer50 * parseString(char * str)
    { //error is on this colon
        return NULL;
    }
}

Body:
This:

main() {
    Integer50 * parseString(char * str)
    { //error is on this colon
        return NULL;
    }
}

Should be replaced by:

Integer50 * parseString(char * str)
{ //error is on this colon
    return NULL;
}

int main() {
    //If you need to call that `parseString` function call it here
}

So, C doesn't support function inside function. main is a function and parseString is another function. That's the problem.


问:
SAPUI5 - get model header and items in the controller
I'm working on a simple Master detail SAPUI5 app.
I use V2 Odata Model an TwoWay binding.
When I click on the submit button I want to get all the values entered by the user in the model.

The problem is that I get only header data but not items data.
I need both in order to use the create deep entity method in the backend.

Here is my code:

var sPath = evt.getSource().getBindingContext().getPath();
var myData = evt.getSource().getBindingContext().getObject(sPath);```

In myData I get the header data and the navigation propoerty with no data in it.

How can I get the items data as well ?

I tried with expand but no success !

答:
Have you tried to do it in the following way ?

```<code> var sPath = evt.getSource().getBindingContext().getPath(),
 var myData = yourModel.getProperty(sPath);
</code>```

If you model has a particular name you could do something like this -

```<code>var sPath = evt.getSource().getBindingContext("modelName").getPath(),
var myData = this.getView().getModel("modelName").getProperty(sPath);
</code>```

You always need to get the path, and using it, you get the value in that path for the model

Body:
I'm working on a simple Master detail SAPUI5 app.
I use V2 Odata Model an TwoWay binding.
When I click on the submit button I want to get all the values entered by the user in the model.

The problem is that I get only header data but not items data.
I need both in order to use the create deep entity method in the backend.

Here is my code:

var sPath = evt.getSource().getBindingContext().getPath();
var myData = evt.getSource().getBindingContext().getObject(sPath);

In myData I get the header data and the navigation propoerty with no data in it.

How can I get the items data as well ?

I tried with expand but no success !

Body:
Have you tried to do it in the following way ?

 var sPath = evt.getSource().getBindingContext().getPath(),
 var myData = yourModel.getProperty(sPath);

If you model has a particular name you could do something like this -

var sPath = evt.getSource().getBindingContext("modelName").getPath(),
var myData = this.getView().getModel("modelName").getProperty(sPath);

You always need to get the path, and using it, you get the value in that path for the model


问:
How to pass Mat_<long double> in function?
I have a Mat_<long double> matrix. I need long double to perform multiplication of large matrices (10x4096 both). But the problem is that passing to function in such way: func(Mat first) makes the size of element in function 8 bytes though I need 16. But func(Mat_<long double> first) causes undefined reference to function by linker. So the question is how can I pass Mat_<long double> to function?

答:
You need to change the prototype of the function to pass diferent parameter type:

Prototype:

```<code>func(Mat_<long double> first);
</code>```

Definition:

```<code>func(Mat_<long double> first)
{
..
}
</code>```

Usage:

```<code>Mat_<long double> example;
func(example);
</code>```

Notes:

Be careful with the use of long double, isn't very portable, as different compilers treat it differently

Also consider to pass by reference (Mat_<long double> &) instead of by val for performance reasons, when you use a big matrix.

Body:
You need to change the prototype of the function to pass diferent parameter type:

Prototype:

func(Mat_<long double> first);

Definition:

func(Mat_<long double> first)
{
..
}

Usage:

Mat_<long double> example;
func(example);

Notes:

Be careful with the use of long double, isn't very portable, as different compilers treat it differently

Also consider to pass by reference (Mat_<long double> &) instead of by val for performance reasons, when you use a big matrix.


问:
awk split column into multiple columns in staggered manner
I have a text file containing a single column of data as below :

```<code>1
2
3
4
5
6
</code>```

I want to split this into multiple columns using awk or sed command as follows:

```<code>1 2 3
4 5 6
</code>```

How can I do this? Thanks in advance

答:
With sed:

```<code>sed 'N; N; s/\n/ /g' file
</code>```

Body:
I have a text file containing a single column of data as below :

1
2
3
4
5
6

I want to split this into multiple columns using awk or sed command as follows:

1 2 3
4 5 6

How can I do this? Thanks in advance

Body:
With sed:

sed 'N; N; s/\n/ /g' file


问:
Add Collection as an item within another collection - Class - Excel VBA
I'm currently trying to build a collection of items wherein a collection might contain an another collection as an Item within.

I've set two collections and created a class module for each:
col1 - (linked to Class1); and col2 - (linked to Class2)

Below are my Class Modules:

Class1:

```<code>Option Explicit
Private pTestC1A As String
Private pTestC1B As Collection

Public Property Let TestC1A(Value As String)
pTestC1A = Value
End Property

Public Property Get TestC1A() As String
TestC1A = pTestC1A
End Property

Property Set TestC1B(col2 As Collection)
Set pTestC1B = col2
End Property

Property Get TestC1BElements(v As Integer) As String
    TestC1B = pTestC1B(v)
End Property
</code>```

Class2:

```<code>Option Explicit
Private pTestC2A  As String

Public Property Let TestC2A(Value As String)
pTestC2A = Value
End Property

Public Property Get TestC2A() As String
TestC2A = pTestC2A
End Property
</code>```

Below is my Module code

```<code>Sub Test()

Set col1 = New Collection
Set col2 = New Collection

Set cV = New Class1
cV.TestC1A = "First Collection"

Set aV = New Class2
aV.TestC2A = "Second Collection"
sKey1 = CStr(aV.TestC2A)
col2.Add aV, sKey1

Set cV.TestC1B = col2

sKey2 = CStr(cV.TestC1A)
col1.Add cV, sKey2
    If Err.Number = 457 Then
      MsgBox "Error Occured"
    ElseIf Err.Number <> 0 Then Stop
    End If
    Err.Clear

Msgbox col1(1).TestC1A ' works fine
Msgbox col2(1).TestC2A ' works file
MsgBox col1(1).TestC1B(1).TestC2A ' does not work - 450 run-time error

End Sub
</code>```

As per the above code, I'm successfully able to get the values of the items if I reference each collection respectively, however I'm getting a "Wrong number of arguments or invalid property assignment" run-time error if I try to get the item value in a nested fashion.

It would be appreciated if someone can help point out where I'm going wrong, and perhaps shed some light on the way the class module handles the Property Set & Get parameters for a collection.

答:
You are missing a Get TestC1B property in your Class1 class module:

```<code>Property Get TestC1B() As Collection
    Set TestC1B = pTestC1B
End Property
</code>```

Once that is present you will be able to make calls to col1(1).TestC1B(1) and access it's .TestC2A property

Background

You did the right thing by using private variables in your classes and using properties to give read/write access to your private variables. You'll get a lot more control this way.

Property Get gives read access to that property (and broadly speaking, the underlying private variable). For example you can use Range.Address to return (read) the address of a range object.

Property Let and Set give write access to the property. Use Set for objects. For example Range.Value = 1 will write the new value to the range.

Consider, Range.Address = $A$1. Since there is no Property Set for the address of a range, this will not change the address of the range. It will consider the Range.Address part a Get call and evaluate something like $A$1 = $A$1 returning TRUE in this example

Body:
I'm currently trying to build a collection of items wherein a collection might contain an another collection as an Item within.

I've set two collections and created a class module for each:
col1 - (linked to Class1); and col2 - (linked to Class2)

Below are my Class Modules:

Class1:

Option Explicit
Private pTestC1A As String
Private pTestC1B As Collection

Public Property Let TestC1A(Value As String)
pTestC1A = Value
End Property

Public Property Get TestC1A() As String
TestC1A = pTestC1A
End Property

Property Set TestC1B(col2 As Collection)
Set pTestC1B = col2
End Property

Property Get TestC1BElements(v As Integer) As String
    TestC1B = pTestC1B(v)
End Property

Class2:

Option Explicit
Private pTestC2A  As String

Public Property Let TestC2A(Value As String)
pTestC2A = Value
End Property

Public Property Get TestC2A() As String
TestC2A = pTestC2A
End Property

Below is my Module code

Sub Test()

Set col1 = New Collection
Set col2 = New Collection

Set cV = New Class1
cV.TestC1A = "First Collection"

Set aV = New Class2
aV.TestC2A = "Second Collection"
sKey1 = CStr(aV.TestC2A)
col2.Add aV, sKey1

Set cV.TestC1B = col2

sKey2 = CStr(cV.TestC1A)
col1.Add cV, sKey2
    If Err.Number = 457 Then
      MsgBox "Error Occured"
    ElseIf Err.Number <> 0 Then Stop
    End If
    Err.Clear

Msgbox col1(1).TestC1A ' works fine
Msgbox col2(1).TestC2A ' works file
MsgBox col1(1).TestC1B(1).TestC2A ' does not work - 450 run-time error

End Sub

As per the above code, I'm successfully able to get the values of the items if I reference each collection respectively, however I'm getting a "Wrong number of arguments or invalid property assignment" run-time error if I try to get the item value in a nested fashion.

It would be appreciated if someone can help point out where I'm going wrong, and perhaps shed some light on the way the class module handles the Property Set & Get parameters for a collection.

Body:
You are missing a Get TestC1B property in your Class1 class module:

Property Get TestC1B() As Collection
    Set TestC1B = pTestC1B
End Property

Once that is present you will be able to make calls to col1(1).TestC1B(1) and access it's .TestC2A property

Background

You did the right thing by using private variables in your classes and using properties to give read/write access to your private variables. You'll get a lot more control this way.

Property Get gives read access to that property (and broadly speaking, the underlying private variable). For example you can use Range.Address to return (read) the address of a range object.

Property Let and Set give write access to the property. Use Set for objects. For example Range.Value = 1 will write the new value to the range.

Consider, Range.Address = $A$1. Since there is no Property Set for the address of a range, this will not change the address of the range. It will consider the Range.Address part a Get call and evaluate something like $A$1 = $A$1 returning TRUE in this example


问:
Hide duplicate post on article page - Wordpress
I'm displaying a article on my page in Wordpress. Then right below that article, Im doing a foreach loop and displaying latest articles. Here is how it looks:

As you can see, "Jeffs Wedding Surprise" displays again in the bottom articles. How can I make it so the same article wont display again in my foreach loop that I'm viewing right now.

Here is how Im looping through the "Similar articles" at the bottom and my featured article:

```<code><?php if( have_posts() ){
            while( have_posts(['posts_per_page'=>100]) ){
                $articles = the_post();
                $thumb_id = get_post_thumbnail_id($articles);
                $thumb_url_array = wp_get_attachment_image_src($thumb_id, 'thumbnail-size', true);
                $thumb_url = $thumb_url_array[0];
        ?>
            <?php } ?>
            <div class="article-heading">
                <h4><?php the_title(); ?></h4>
            </div>
            <div class="article-background">
                <img src="<?=$thumb_url;?>">
                <?php
                $title = get_the_title();
                $content = the_content();
                if(strlen($content)>0){?>
                    <div class="article-details">
                        <?php $content ?>
                    </div>
                <?php } ?>
            </div>
        <?php } ?>

        <div class="similar-section">
            <h3>Similar Articles</h3>
        </div>
        <?php foreach (get_posts(['post_type' => 'add_article', 'posts_per_page'=>3]) as $articles) {
            $thumb_id = get_post_thumbnail_id($articles);
            $thumb_url_array = wp_get_attachment_image_src($thumb_id, 'thumbnail-size', true);
            $thumb_url = $thumb_url_array[0];
            $url_to_project = "/previous_work/".$articles->post_name;
            ?>
                <div class="col-md-4">
                    <a class="article-link" href="<?=$url_to_project;?>">
                        <div class="single-article-photo">
                            <img src="<?=$thumb_url;?>">
                        </div>
                        <div class="single-article">
                            <h6><?= $articles->post_title ?></h6>
                            <p><?= substr($articles->post_content,0,200) ?> <span style="text-transform: uppercase; text-decoration: underline">(Read More)</span>...</p>
                        </div>
                    </a>
                </div>
        <?php } ?>
</code>```

答:
This is what I was supposed to do in the foreach loop:

```<code><?php foreach (get_posts(['post_type' => 'add_article', 'posts_per_page'=>3,'exclude'=>[get_the_ID()]]) as $articles) { ?>
</code>```

That will exclude the current article in the "Similar articles" section on bottom of page.

Body:
I'm displaying a article on my page in Wordpress. Then right below that article, Im doing a foreach loop and displaying latest articles. Here is how it looks:

As you can see, "Jeffs Wedding Surprise" displays again in the bottom articles. How can I make it so the same article wont display again in my foreach loop that I'm viewing right now.

Here is how Im looping through the "Similar articles" at the bottom and my featured article:

<?php if( have_posts() ){
            while( have_posts(['posts_per_page'=>100]) ){
                $articles = the_post();
                $thumb_id = get_post_thumbnail_id($articles);
                $thumb_url_array = wp_get_attachment_image_src($thumb_id, 'thumbnail-size', true);
                $thumb_url = $thumb_url_array[0];
        ?>
            <?php } ?>

<?php the_title(); ?>

                <img src="<?=$thumb_url;?>">
                <?php
                $title = get_the_title();
                $content = the_content();
                if(strlen($content)>0){?>

                        <?php $content ?>

                <?php } ?>

        <?php } ?>

Similar Articles

        <?php foreach (get_posts(['post_type' => 'add_article', 'posts_per_page'=>3]) as $articles) {
            $thumb_id = get_post_thumbnail_id($articles);
            $thumb_url_array = wp_get_attachment_image_src($thumb_id, 'thumbnail-size', true);
            $thumb_url = $thumb_url_array[0];
            $url_to_project = "/previous_work/".$articles->post_name;
            ?>

                    <a class="article-link" href="<?=$url_to_project;?>">

                            <img src="<?=$thumb_url;?>">

<?= $articles->post_title ?>

<?= substr($articles->post_content,0,200) ?> (Read More)...

        <?php } ?>

Body:
This is what I was supposed to do in the foreach loop:

<?php foreach (get_posts(['post_type' => 'add_article', 'posts_per_page'=>3,'exclude'=>[get_the_ID()]]) as $articles) { ?>

That will exclude the current article in the "Similar articles" section on bottom of page.


问:
Train Android app to recognize sensor patterns using machine learning
I'd like my app to be able to detect when the user carrying the phone falls, using only accelerometer data (because it's the only sensor available on all smartphones).

I first tried to implement an algorithm to detect free fall (accelerometer total acceleration nearing zero, followed by high acceleration due to ground hitting, and a short period of motionlessness to ditch false positives when the user is just walking downstairs quickly), but there's a lot of ways to fall, and for my algorithm implementation, I can always find a case where a fall is not detected, or where a fall is wrongly detected.

I think Machine Learning can help me solve this issue, by learning from a lot of sensor values coming from different devices, with different sampling rates, what is a fall and what is not.

Tensorflow seems to be what I need for this as it seems it can run on Android, but while I could find tutorials to use it for offline image classifying (here for example), I didn't find any help to make model that learns patterns from motion sensors values.

I tried to learn how to use Tensorflow using the Getting Started page, but failed to, probably because I'm not fluent in Python, and do not have machine learning background. (I'm fluent in Java and Kotlin, and used to Android APIs).

I'm looking for help from the community to help me use Tensorflow (or something else in machine learning) to train my app to recognize falls and other motion sensors patterns.

As a reminder, Android reports motion sensors values at a random rate, but provides a timestamp in nanoseconds for each sensor event, which can be used to infer the time elapsed since the previous sensor event, and the sensor readings are provided as a float (32bits) for each axis (x, y, z).

答:
If you have your data well organized, then you might be able to use the Java-based Weka machine learning environment:
http://www.cs.waikato.ac.nz/ml/weka/

You can use Weka to play around with all the different algorithms on your data. Weka uses a ARFF file for the data. It's pretty easy to create that if you have your data in JSON or CSV.
Once you find a algo/model that works, the you can easily put that into your Android app:
http://weka.wikispaces.com/Use+Weka+in+your+Java+code

You really don't need Tensorflow if you dont require deep learning algos, which I don't think you require. If you did need the deep learning algo, then DeepLearning4J is a java based open source solution for Android:
https://deeplearning4j.org/android


问:
How to leave a copy of the original file when we save the file
When modifying and saving a file, how to leave a copy of the original file, say give it *.bak?Is there a built-in support?</p>

答: You can call File.Move to rename the original file, then save the new version with the original name.


问:
Getting SSL23_GET_SERVER_HELLO:unknown protocol
This seems to be a popular question.  I hope to differentiate my version from the others.  Here's what I'm seeing when trying to connect to a Tomcat server, using the -debug option:</p>

```<code># openssl s_client -connect example.com:443 -debug
CONNECTED(00000003)
write to 0x694230 [0x694ef0] (187 bytes => 187 (0xBB))
[...]
read from 0x694230 [0x69a450] (7 bytes => 7 (0x7))
0000 - 15 03 03 00 02 02 28                              ......(
15633:error:140770FC:SSL routines:SSL23_GET_SERVER_HELLO:unknown protocol:s23_clnt.c:610:
</code>```

答:
The first thing to note is that the response does not include visible characters, so I'm unlikely to be connecting to a non-SSL-enabled port.  I'm not certain which SSL library my version of openssl is using, but looking at https://boringssl.googlesource.com/boringssl/+/2214/ssl/s23_clnt.c is helpful, even with the wrong line numbers.  p[1] is 0x03, which is SSL3_VERSION_MAJOR, and p[2] is 0x03, which is TLS1_2_VERSION_MINOR. p[0] is 0x15 (21 decimal), which is SSL3_RT_ALERT, which means that p[3] and p[4] should be 0 and 2 (the code doesn't use symbolic names for these), which they are.  p[5] is also 0x02, which is SSL3_AL_FATAL, which doesn't look good. I'm guessing the server didn't like my initial write.  However, that should give me a different error, so I'm wondering if openssl really doesn't recognize an otherwise valid protocol.  Checking the version:

```<code># openssl version
OpenSSL 0.9.8j-fips 07 Jan 2009
</code>```

Yes, that looks a bit old.  I guess I need to find a more recent version.

Body:
This seems to be a popular question.  I hope to differentiate my version from the others.  Here's what I'm seeing when trying to connect to a Tomcat server, using the -debug option:

# openssl s_client -connect example.com:443 -debug
CONNECTED(00000003)
write to 0x694230 [0x694ef0] (187 bytes => 187 (0xBB))
[...]
read from 0x694230 [0x69a450] (7 bytes => 7 (0x7))
0000 - 15 03 03 00 02 02 28                              ......(
15633:error:140770FC:SSL routines:SSL23_GET_SERVER_HELLO:unknown protocol:s23_clnt.c:610:

Body:
The first thing to note is that the response does not include visible characters, so I'm unlikely to be connecting to a non-SSL-enabled port.  I'm not certain which SSL library my version of openssl is using, but looking at https://boringssl.googlesource.com/boringssl/+/2214/ssl/s23_clnt.c is helpful, even with the wrong line numbers.  p[1] is 0x03, which is SSL3_VERSION_MAJOR, and p[2] is 0x03, which is TLS1_2_VERSION_MINOR. p[0] is 0x15 (21 decimal), which is SSL3_RT_ALERT, which means that p[3] and p[4] should be 0 and 2 (the code doesn't use symbolic names for these), which they are.  p[5] is also 0x02, which is SSL3_AL_FATAL, which doesn't look good. I'm guessing the server didn't like my initial write.  However, that should give me a different error, so I'm wondering if openssl really doesn't recognize an otherwise valid protocol.  Checking the version:

# openssl version
OpenSSL 0.9.8j-fips 07 Jan 2009

Yes, that looks a bit old.  I guess I need to find a more recent version.


问:
SQL Server - PIVOT Grouping
I have this confusing thing on using pivot in grouping per EmployeeID.

```<code>SELECT *
FROM(
    SELECT  LoanAmount, lt.LoanTypeID
    FROM LoanContract lc
        INNER JOIN LoanType lt ON lt.LoanTypeID = lc.LoanTypeID
    GROUP BY EmployeeID, LoanAmount, lt.LoanTypeID
)src
PIVOT(
    SUM(LoanAmount)
    FOR LoanTypeID IN ([1], [2], [3], [4],  [5])
)piv;
</code>```

There are 2 employeeID which is emp=1 has a sum(lt.LoanAmount) that is associated with lt.LoanTypeID = 5 and on the other hand emp2 has a sum(lt.LoanAmount) that is associated with lt.LoanTypeID 1 and 2

The result(1) shows:

```<code>[1]         [2]        [3]     [4]      [5]
2400.00 30000.00    NULL    NULL    105000.00
</code>```

Expected result(2):

```<code>[1]         [2]        [3]     [4]      [5]
NULL         NULL       NULL    NULL     105000.00
2400.00      30000.00   NULL    NULL     NULL
</code>```

Any help would be appreciated.

答:
Try selecting employeeId as well in the subquery:</p>

```<code>select *
from (
    select employeeID, -- here
        LoanAmount,
        lt.LoanTypeID
    from LoanContract lc
    inner join LoanType lt on lt.LoanTypeID = lc.LoanTypeID
    group by EmployeeID,
        LoanAmount,
        lt.LoanTypeID
    ) src
PIVOT(
    SUM(LoanAmount)
    for LoanTypeID in ([1], [2], [3], [4], [5])
    ) piv;
</code>```

Title: SQL Server - PIVOT Grouping

Body:
I have this confusing thing on using pivot in grouping per EmployeeID.

SELECT *
FROM(
    SELECT  LoanAmount, lt.LoanTypeID
    FROM LoanContract lc
        INNER JOIN LoanType lt ON lt.LoanTypeID = lc.LoanTypeID
    GROUP BY EmployeeID, LoanAmount, lt.LoanTypeID
)src
PIVOT(
    SUM(LoanAmount)
    FOR LoanTypeID IN ([1], [2], [3], [4],  [5])
)piv;

There are 2 employeeID which is emp=1 has a sum(lt.LoanAmount) that is associated with lt.LoanTypeID = 5 and on the other hand emp2 has a sum(lt.LoanAmount) that is associated with lt.LoanTypeID 1 and 2

The result(1) shows:

[1]         [2]        [3]     [4]      [5]
2400.00 30000.00    NULL    NULL    105000.00

Expected result(2):

[1]         [2]        [3]     [4]      [5]
NULL         NULL       NULL    NULL     105000.00
2400.00      30000.00   NULL    NULL     NULL

Any help would be appreciated.

Body:
Try selecting employeeId as well in the subquery:

select *
from (
    select employeeID, -- here
        LoanAmount,
        lt.LoanTypeID
    from LoanContract lc
    inner join LoanType lt on lt.LoanTypeID = lc.LoanTypeID
    group by EmployeeID,
        LoanAmount,
        lt.LoanTypeID
    ) src
PIVOT(
    SUM(LoanAmount)
    for LoanTypeID in ([1], [2], [3], [4], [5])
    ) piv;


问:
How does this code (parameters (of Primitive Type)) work?
I am new to java and just learned a little bit about methods and classes, and I am really confused about this whole chapter. This code comes from our review powerpoint and I really don't know how to do it. And I feel like the last section should be in the class? But this is how the powerpoint says. Can someone please explain how does this code work and how to get the printout result specifically step by step?? I really appreciate it, thanks!</p>

```<code>public class MyClass {
    public void swap(int x, int y){
        int temp = x;
        x = y;
        y = temp;
    }
}

int w = 10,
z = 20;
MyClass m = new MyClass();
m.swap(w,z);
System.out.println(w + " " + z);
</code>```

答:
In order to execute Java you need a main method somewhere.

```<code>public static void main(String[] args) {
  // Do stuff
}
</code>```

So you can rewrite the example like so to get it executing:

```<code>public class Main {
  public static void main(String[] args) {
    int w = 10,
    z = 20;
    MyClass m = new MyClass();
    m.swap(w,z);
    System.out.println(w + " " + z);
  }
}

public class MyClass {
    public void swap(int x, int y) {
        int temp = x;
        x = y;
        y = temp;
    }
}
</code>```

The whole point of this code example is that Java passes primitive types by value and not by reference. Look at the main method. You have two integers, w=10 and z=20. After that you pass w and z to the swap method. Since java passes these primitive types as values, the original w and z are not modified by the swap, which is proven by the println where w is still 10 and z is still 20.

Body:
I am new to java and just learned a little bit about methods and classes, and I am really confused about this whole chapter. This code comes from our review powerpoint and I really don't know how to do it. And I feel like the last section should be in the class? But this is how the powerpoint says. Can someone please explain how does this code work and how to get the printout result specifically step by step?? I really appreciate it, thanks!

public class MyClass {
    public void swap(int x, int y){
        int temp = x;
        x = y;
        y = temp;
    }
}

int w = 10,
z = 20;
MyClass m = new MyClass();
m.swap(w,z);
System.out.println(w + " " + z);

Body:
In order to execute Java you need a main method somewhere.

public static void main(String[] args) {
  // Do stuff
}

So you can rewrite the example like so to get it executing:

public class Main {
  public static void main(String[] args) {
    int w = 10,
    z = 20;
    MyClass m = new MyClass();
    m.swap(w,z);
    System.out.println(w + " " + z);
  }
}

public class MyClass {
    public void swap(int x, int y) {
        int temp = x;
        x = y;
        y = temp;
    }
}

The whole point of this code example is that Java passes primitive types by value and not by reference. Look at the main method. You have two integers, w=10 and z=20. After that you pass w and z to the swap method. Since java passes these primitive types as values, the original w and z are not modified by the swap, which is proven by the println where w is still 10 and z is still 20.


问:
Support both AD clients and non-AD clients concurrently
I have Service x I make authentication for the service with membership provider

and I'm the DB and active directory users

some projects need authentication with DB or AD

but we have project need to support both so the clients can be authenticated from the internet (DB) or from the network (AD)

how I can support this ?

thanks

答:
Look at "Claim based authentication (Geneva Framework)" and "Building Claim Based security authentication"

On a high level you create two endpoints with AD and non-AD authenticaiton. Your security layer will populate claims based on user and the core of your service will use the claims for authorizaiton and will not know/care how the user authenticated.