问:
For Loop Filter on Pandas DataFrame not Working
I have a very simple for loop :

```<code>## Keep or Drop Rows from Ad Servers

dataframes = [atlas_df, flashtalking_df, innovid_df, ias_viewability_df, ias_fraud_df]

for df in dataframes:
    df = df[df['Placement Name'].str.contains("»")]
</code>```

when I run the for loop though, nothing filters.

However, if I write it down manually as:

```<code>ias_fraud_df = ias_fraud_df[ias_fraud_df['Placement Name'].str.contains("»")]
</code>```

The filter works.

Any ideas on what I am missing?

答:
You're working on the iterator, you need to reference the original df by using an index into the list:

```<code>for i in range(len(dataframes)):
    df = dataframes[i]
    dataframes[i] = df[df['Placement Name'].str.contains("»")]
</code>```

This is so the original df in the list is modified

Example:

```<code>In [108]:
l = list('abcd')
for i in range(len(l)):
    l[i] = 'new_' + l[i]

Out[108]:
['new_a', 'new_b', 'new_c', 'new_d']
</code>```

Versus:

```<code>In [110]:
l = list('abcd')
for x in l:
    x = 'new_' + x
l

Out[110]:
['a', 'b', 'c', 'd']
</code>```

So you see that the latter which is semantically the same as your code never modifies the original elements in the list whilst the other does

Body:
I have a very simple for loop :

## Keep or Drop Rows from Ad Servers

dataframes = [atlas_df, flashtalking_df, innovid_df, ias_viewability_df, ias_fraud_df]

for df in dataframes:
    df = df[df['Placement Name'].str.contains("»")]

when I run the for loop though, nothing filters.

However, if I write it down manually as:

ias_fraud_df = ias_fraud_df[ias_fraud_df['Placement Name'].str.contains("»")]

The filter works.

Any ideas on what I am missing?

Body:
You're working on the iterator, you need to reference the original df by using an index into the list:

for i in range(len(dataframes)):
    df = dataframes[i]
    dataframes[i] = df[df['Placement Name'].str.contains("»")]

This is so the original df in the list is modified

Example:

In [108]:
l = list('abcd')
for i in range(len(l)):
    l[i] = 'new_' + l[i]

Out[108]:
['new_a', 'new_b', 'new_c', 'new_d']

Versus:

In [110]:
l = list('abcd')
for x in l:
    x = 'new_' + x
l

Out[110]:
['a', 'b', 'c', 'd']

So you see that the latter which is semantically the same as your code never modifies the original elements in the list whilst the other does


来源: stackexchange

问:
Execution hangs after Running telnet command on remote SSH session using JSch
I was looking for a solution to take SSH connection followed by Telnet connection to remote system via java. As using telnet connection only I can execute that particular command on remote machine.

After browsing a lot I found this answer "https://stackoverflow.com/questions/27146991/running-telnet-command-on-remote-ssh-session-using-jsch" But after Executing the "telnet localhost 4444" the program executions hangs & never come out from while loop . Because of that I'm not able to execute other commands after taking telnet connection.

My code is :-

```<code>    public static void main(String[] arg) {
    try {
        System.out.println(telnetConnection(command, puttyUserName,
    puttyPassword, puttyHostName));
    } catch (Exception e) {
        e.printStackTrace();
    }
}

public static String telnetConnection(String command, String user, String password, String host)
        throws JSchException, Exception {
    JSch jsch = new JSch();
    jsch.addIdentity(puttyPublicKey, puttyPassword);
    Session session = jsch.getSession(user, host, 22);

    session.setConfig("StrictHostKeyChecking", "no");

    session.connect(500);//This timeout is not working as mentioned in the example. Program execution never stops.

    Channel channel = session.openChannel("shell");

    channel.connect(500);

    DataInputStream dataIn = new DataInputStream(channel.getInputStream());
    BufferedReader reader = new BufferedReader(new InputStreamReader(dataIn));
    DataOutputStream dataOut = new DataOutputStream(channel.getOutputStream());
    System.out.println("Starting telnet connection...");
    dataOut.writeBytes("telnet localhost 4444\r\n"); after this no commands executes
    dataOut.writeBytes(command + "\r\n");

    dataOut.writeBytes("quit\r\n");
</code>```

// using quit I'm able to exit from telnet session while doing manually via putty as exit doesn't work

```<code>    dataOut.writeBytes("exit\r\n"); // exit from shell
    dataOut.flush();
    String line = reader.readLine();
    String result = line + "\n";
    while (!(line = reader.readLine()).equals("Connection closed by foreign host"))
    {
        result += line + "\n";

        System.out.println("heart beat" + result);
    }

    System.out.println("after while done");
    dataIn.close();
    dataOut.close();
    channel.disconnect();
    session.disconnect();
    System.out.println("done");
    return result;
}
</code>```

}

output//

heart beat telnet localhost 4444

START TRANSLATOR ABCLOC HIGH

quit

exit

[XYZ]$ telnet localhost 4444
Trying x.x.x.1...

Connected to localhost.localdomain (x.x.x.1).

Escape character is '^]'.

Connection to INTERFACE LAYER
heart beat telnet localhost 4444

START TRANSLATOR ABCLOC HIGH

quit

exit

[XYZ]$ telnet localhost 4444
Trying x.x.x.1...

Connected to localhost.localdomain (x.x.x.1).

Escape character is '^]'.

Connection to INTERFACE LAYER
Type "help" for a list of commands

////after this programs hangs & no actions are performed

答:
I don't have the same server running on port 4444 as you do, but I got similar behaviour in a local test issuing "telnet localhost 80" and "GET /" within JSch. The fix in my case was to be careful about the exactness of the "Connection closed" message. In my case the server sending:

Connection closed by foreign host.

whereas your code is checking for

Connection closed by foreign host

(no full stop) and so that loop never terminates. You can find my test code at https://github.com/pgleghorn/JSchTest

ContentLicense: CC BY-SA 3.0

Body:
I was looking for a solution to take SSH connection followed by Telnet connection to remote system via java. As using telnet connection only I can execute that particular command on remote machine.

After browsing a lot I found this answer "https://stackoverflow.com/questions/27146991/running-telnet-command-on-remote-ssh-session-using-jsch" But after Executing the "telnet localhost 4444" the program executions hangs & never come out from while loop . Because of that I'm not able to execute other commands after taking telnet connection.

My code is :-

    public static void main(String[] arg) {
    try {
        System.out.println(telnetConnection(command, puttyUserName,
    puttyPassword, puttyHostName));
    } catch (Exception e) {
        e.printStackTrace();
    }
}

public static String telnetConnection(String command, String user, String password, String host)
        throws JSchException, Exception {
    JSch jsch = new JSch();
    jsch.addIdentity(puttyPublicKey, puttyPassword);
    Session session = jsch.getSession(user, host, 22);

    session.setConfig("StrictHostKeyChecking", "no");

    session.connect(500);//This timeout is not working as mentioned in the example. Program execution never stops.

    Channel channel = session.openChannel("shell");

    channel.connect(500);

    DataInputStream dataIn = new DataInputStream(channel.getInputStream());
    BufferedReader reader = new BufferedReader(new InputStreamReader(dataIn));
    DataOutputStream dataOut = new DataOutputStream(channel.getOutputStream());
    System.out.println("Starting telnet connection...");
    dataOut.writeBytes("telnet localhost 4444\r\n"); after this no commands executes
    dataOut.writeBytes(command + "\r\n");

    dataOut.writeBytes("quit\r\n");

// using quit I'm able to exit from telnet session while doing manually via putty as exit doesn't work

    dataOut.writeBytes("exit\r\n"); // exit from shell
    dataOut.flush();
    String line = reader.readLine();
    String result = line + "\n";
    while (!(line = reader.readLine()).equals("Connection closed by foreign host"))
    {
        result += line + "\n";

        System.out.println("heart beat" + result);
    }

    System.out.println("after while done");
    dataIn.close();
    dataOut.close();
    channel.disconnect();
    session.disconnect();
    System.out.println("done");
    return result;
}

}

output//

heart beat telnet localhost 4444

START TRANSLATOR ABCLOC HIGH

quit

exit

[XYZ]$ telnet localhost 4444
Trying x.x.x.1...

Connected to localhost.localdomain (x.x.x.1).

Escape character is '^]'.

Connection to INTERFACE LAYER
heart beat telnet localhost 4444

START TRANSLATOR ABCLOC HIGH

quit

exit

[XYZ]$ telnet localhost 4444
Trying x.x.x.1...

Connected to localhost.localdomain (x.x.x.1).

Escape character is '^]'.

Connection to INTERFACE LAYER
Type "help" for a list of commands

////after this programs hangs & no actions are performed


问:
Bootstrap to hide popover need press button twice
I'm using Bootstrap v3.3.7

I need to click twice to hide a popover.

I have problem like this https://jsfiddle.net/hik200/ejxkv8hb/1/

```<code>$('body').on('hidden.bs.popover', function (e) {
$(e.target).data("bs.popover").inState.click = false; });
</code>```

答:
I edited your fiddle, you were adding the click listener once on your button click, which did not actually trigger the close function :

```<code>    function ClosePopover() {
$("#destroy").click(function(){
    $("[data-toggle='popover']").popover('hide');

});
console.log('asd');
}
</code>```

this is good :

```<code>function ClosePopover() {
    $("[data-toggle='popover']").popover('hide');
    console.log('asd')
}
</code>```

Body:
I'm using Bootstrap v3.3.7

I need to click twice to hide a popover.

I have problem like this https://jsfiddle.net/hik200/ejxkv8hb/1/

$('body').on('hidden.bs.popover', function (e) {
$(e.target).data("bs.popover").inState.click = false; });

Body:
I edited your fiddle, you were adding the click listener once on your button click, which did not actually trigger the close function :

    function ClosePopover() {
$("#destroy").click(function(){
    $("[data-toggle='popover']").popover('hide');

});
console.log('asd');
}

this is good :

function ClosePopover() {
    $("[data-toggle='popover']").popover('hide');
    console.log('asd')
}


问:
How to make a button expand the length of an html table header?
I am trying to get a button that I put in a table  to expand the full width and height of the header column, even when a table cell in the same column is larger than the text. If I do, width 100% in css, then the button will just match the cell size, and then the title will extend beyond the button and header.

I am using the button so when the user click on it the column will sort.

This is my code just trying to do with width:

```<code><th><button onclick="tableColumnSort(this)" style="width:100%">@descriptor.Name</button></th>
</code>```

And this is how it looks without using width:

```<code><th><button onclick="tableColumnSort(this)">@descriptor.Name</button></th>
</code>```

答:
Make your buttons display: block.

table, th, td { border-collapse: collapse; border: 1px solid #333; }
th button { display: block; width: 100%; }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table>
  <thead>
    <tr>
      <th><button>DELETE</button></th>
      <th><button>PARTNO</button></th>
      <th><button>DLT</button></th>
      <th><button>TCOUNT</button></th>
      <th><button>TRANS</button></th>
    </tr>
  </thead>
  <tbody>
    <tr><td></td><td>3</td><td>20170315</td><td>1</td><td>R</td></tr>
    <tr><td></td><td>3</td><td>20170315</td><td>1</td><td>R</td></tr>
    <tr><td></td><td>3</td><td>20170315</td><td>1</td><td>R</td></tr>
    <tr><td></td><td>3</td><td>20170315</td><td>1</td><td>R</td></tr>
  </tbody>
</table></code>```

Body:
I am trying to get a button that I put in a table  to expand the full width and height of the header column, even when a table cell in the same column is larger than the text. If I do, width 100% in css, then the button will just match the cell size, and then the title will extend beyond the button and header.

I am using the button so when the user click on it the column will sort.

This is my code just trying to do with width:

<button onclick="tableColumnSort(this)" style="width:100%">@descriptor.Name</button>

And this is how it looks without using width:

<button onclick="tableColumnSort(this)">@descriptor.Name</button>

Body:
Make your buttons display: block.

table, th, td { border-collapse: collapse; border: 1px solid #333; }
th button { display: block; width: 100%; }

<table>
  <thead>
    <tr>
      <th><button>DELETE</button></th>
      <th><button>PARTNO</button></th>
      <th><button>DLT</button></th>
      <th><button>TCOUNT</button></th>
      <th><button>TRANS</button></th>
    </tr>
  </thead>
  <tbody>
    <tr><td></td><td>3</td><td>20170315</td><td>1</td><td>R</td></tr>
    <tr><td></td><td>3</td><td>20170315</td><td>1</td><td>R</td></tr>
    <tr><td></td><td>3</td><td>20170315</td><td>1</td><td>R</td></tr>
    <tr><td></td><td>3</td><td>20170315</td><td>1</td><td>R</td></tr>
  </tbody>
</table>


问:
C# - LINQ - Sum a field from other table
I need to join two tables (Movimientos and Cuentas), group by CuentasId and make a SUM of Movimientos.Monto

Movimientos has a CuentasId to join this, and I can get the data from Cuentas but can not get the Sum.

This is my best approach, any help will be preciated, I'm a little confused with the syntax. Thanks in advance and kind regards,

```<code>          var cuentas = (from mov in _data.Movimientos
                               join ct in _data.Cuentas
                               on mov.CuentasId equals ct.CuentasId
                               where ct.IsDeleted == 0 && mov.IsDeleted == 0
                               group ct by new
                               {
                                   CuentasId = ct.CuentasId,
                                   Alias = ct.Alias,
                                   Moneda = ct.Monedas.Nombre,
                                   Signo = ct.Monedas.Signo,
                                  Banco = ct.Bancos.Nombre
                               } into ctg
                               select new
                               {
                                   Alias = ctg.Key.Alias,
                                   Moneda = ctg.Key.Moneda,
                                   Signo = ctg.Key.Signo,
                                   Banco = ctg.Key.Banco,
                                   Monto = ctg.Sum(mov.Monto)
                               }
                                ).ToList();
</code>```

答:
You could also try grouping by first and then just summing the items later:</p>

```<code>var cuentas = (from mov in _data.Movimientos.Where(w => w.IsDeleted == 0).GroupBy(g => g.CuentasId)
              join ct in _data.Cuentas.Where(w => w.IsDeleted == 0).GroupBy(g => new { CuentasId = g.CuentasId, Alias = g.Alias, Monedas = g.Monedas.Nombre, Signo = g.Monedas.Signo, Banco = g.Bancos.Nombre })
              on mov.Key.CuentasId equals ct.Key.CuentasId
              select new
              {
                  Alias = ct.Key.Alias,
                  Moneda = ct.Key.Moneda,
                  Signo = ct.Key.Signo,
                  Banco = ct.Key.Banco,
                  Monto = mov.Sum(s => s.Monto)
               }
               ).ToList();
</code>```

Body:
I need to join two tables (Movimientos and Cuentas), group by CuentasId and make a SUM of Movimientos.Monto

Movimientos has a CuentasId to join this, and I can get the data from Cuentas but can not get the Sum.

This is my best approach, any help will be preciated, I'm a little confused with the syntax. Thanks in advance and kind regards,

          var cuentas = (from mov in _data.Movimientos
                               join ct in _data.Cuentas
                               on mov.CuentasId equals ct.CuentasId
                               where ct.IsDeleted == 0 && mov.IsDeleted == 0
                               group ct by new
                               {
                                   CuentasId = ct.CuentasId,
                                   Alias = ct.Alias,
                                   Moneda = ct.Monedas.Nombre,
                                   Signo = ct.Monedas.Signo,
                                  Banco = ct.Bancos.Nombre
                               } into ctg
                               select new
                               {
                                   Alias = ctg.Key.Alias,
                                   Moneda = ctg.Key.Moneda,
                                   Signo = ctg.Key.Signo,
                                   Banco = ctg.Key.Banco,
                                   Monto = ctg.Sum(mov.Monto)
                               }
                                ).ToList();

Body:
You could also try grouping by first and then just summing the items later:

var cuentas = (from mov in _data.Movimientos.Where(w => w.IsDeleted == 0).GroupBy(g => g.CuentasId)
              join ct in _data.Cuentas.Where(w => w.IsDeleted == 0).GroupBy(g => new { CuentasId = g.CuentasId, Alias = g.Alias, Monedas = g.Monedas.Nombre, Signo = g.Monedas.Signo, Banco = g.Bancos.Nombre })
              on mov.Key.CuentasId equals ct.Key.CuentasId
              select new
              {
                  Alias = ct.Key.Alias,
                  Moneda = ct.Key.Moneda,
                  Signo = ct.Key.Signo,
                  Banco = ct.Key.Banco,
                  Monto = mov.Sum(s => s.Monto)
               }
               ).ToList();


问:
Which is the minimum width at which default layout is used
I am creating alternative layouts for my activities, for example sw320dp, etc. I plan to create another for sw480dp, and sw600dp, sw720dp.
In which segment falls the default layout, the one without qualifiers? So I don't duplicate code.</p>

答: you can use a -nodpi qualifier to set the generics layouts.</p>


问:
How to represent types for GUI elements in XSD?
I am working with an application, where some entries need to be filled in in a GUI. Now a customer has requested a configuration file in order to bypass the GUI.

In order to get this done, I'm thinking of the following:

Checkboxes : use a simple integer restriction on the numbers 0 and 1:

```<code><xs:simpleType name="T_Choice">
  <xs:restriction base="xs:integer">
    <xs:minInclusive value="0"/>
    <xs:maxInclusive value="1"/>
  </xs:restriction>
</xs:simpleType>
</code>```

Comboboxes : use a union or a simple integer restriction and an empty string (in order to simulate a combobox with all values from 0 to 10, and an empty first line):

```<code><xs:simpleType name="T_Combo_Choice">
    <xs:union>
        <xs:simpleType>
            <xs:restriction base="xs:string">
                <xs:length value="0"/>
            </xs:restriction>
        </xs:simpleType>
        <xs:simpleType>
            <xs:restriction base="xs:integer">
                <xs:minInclusive value="0"/>
                <xs:maxInclusive value="10"/>
            </xs:restriction>
        </xs:simpleType>
    </xs:union>
</xs:simpleType>
</code>```

But what about radiobuttons? In my XML file, I'm having two adjacent tags:

```<code><use_old_configuration>0</use_old_configuration>
<use_new_configuration>1</use_new_configuration>
</code>```

Now my question: how can I create a restriction in the schema in order to have the possible combinations (0,1) and (1,0), but not (0,0), (1,1) or anything else?

答:
My recommendation for XSD types of your GUI components:

Checkboxes: Use xs:boolean.

Comboboxes: Use a xs:list restricted to length 1 of
xs:enumeration.  The xs:list of 0 would represent no selection.
Name enumerations logically.

Radio buttons: Assuming the traditional model where only 1 of several
buttons must be selected, use an enumeration where where each
enumerated value is associated with one radio button.  Name
enumerations logically.

Body:
I am working with an application, where some entries need to be filled in in a GUI. Now a customer has requested a configuration file in order to bypass the GUI.

In order to get this done, I'm thinking of the following:

Checkboxes : use a simple integer restriction on the numbers 0 and 1:

<xs:simpleType name="T_Choice">
  <xs:restriction base="xs:integer">
    <xs:minInclusive value="0"/>
    <xs:maxInclusive value="1"/>
  </xs:restriction>
</xs:simpleType>

Comboboxes : use a union or a simple integer restriction and an empty string (in order to simulate a combobox with all values from 0 to 10, and an empty first line):

<xs:simpleType name="T_Combo_Choice">
    <xs:union>
        <xs:simpleType>
            <xs:restriction base="xs:string">
                <xs:length value="0"/>
            </xs:restriction>
        </xs:simpleType>
        <xs:simpleType>
            <xs:restriction base="xs:integer">
                <xs:minInclusive value="0"/>
                <xs:maxInclusive value="10"/>
            </xs:restriction>
        </xs:simpleType>
    </xs:union>
</xs:simpleType>

But what about radiobuttons? In my XML file, I'm having two adjacent tags:

<use_old_configuration>0</use_old_configuration>
<use_new_configuration>1</use_new_configuration>

Now my question: how can I create a restriction in the schema in order to have the possible combinations (0,1) and (1,0), but not (0,0), (1,1) or anything else?


问:
Install mysql on centOS always return wrong root credentials
I have installed mysql on CentOS, as described on https://www.linode.com/docs/databases/mysql/how-to-install-mysql-on-centos-7

Always on first installation I got a messagae after the command:

sudo mysql_secure_installation

Error: Access denied for user 'root'@'localhost' (using password: NO)

Here are some informations:
commands + results

cat /etc/*-release

CentOS Linux release 7.3.1611 (Core) NAME="CentOS Linux" VERSION="7
  (Core)" ID="centos" ID_LIKE="rhel fedora" VERSION_ID="7"
  PRETTY_NAME="CentOS Linux 7 (Core)" ANSI_COLOR="0;31"
  CPE_NAME="cpe:/o:centos:centos:7" HOME_URL="https://www.centos.org/"
  BUG_REPORT_URL="https://bugs.centos.org/"

CENTOS_MANTISBT_PROJECT="CentOS-7" CENTOS_MANTISBT_PROJECT_VERSION="7"
  REDHAT_SUPPORT_PRODUCT="centos" REDHAT_SUPPORT_PRODUCT_VERSION="7"

CentOS Linux release 7.3.1611 (Core) CentOS Linux release 7.3.1611
  (Core)

cat /etc/redhat-release

CentOS Linux release 7.3.1611 (Core)

cat /proc/version

Linux version 3.10.0-327.28.2.el7.x86_64
  (builder@kbuilder.dev.centos.org)  (gcc version 4.8.3 20140911 (Red
  Hat 4.8.3-9) (GCC) ) #1 SMP Wed Aug 3 11:11:39 UTC 2016

My host name is not localhost, but root is always configured to 'localhost'.
Also, I have 'root' user for linux (same name for mysql) - I have tried both password of as linux root user and blank password, but still got the same error.

I have re-installed the mysql, but also got the same error.

Please, help.

Thank you.

答:
As I see in MySQL Error: : 'Access denied for user 'root'@'localhost'

The steps:

```<code>1.Add skip-grant-tables under [mysqld] (nano etc/my.cnf)
2.service restart.
3.flush privileges;
4.change root password (root) ALTER USER 'root'@'localhost' IDENTIFIED BY 'NewPassword';
5.Go back to /etc/my.cnf and remove/comment skip-grant-tables
6.Restart Mysql
</code>```

After that, I have checked by command line:
telnet  3306, which seems to be correct.

Body:
As I see in MySQL Error: : 'Access denied for user 'root'@'localhost'

The steps:

1.Add skip-grant-tables under [mysqld] (nano etc/my.cnf)
2.service restart.
3.flush privileges;
4.change root password (root) ALTER USER 'root'@'localhost' IDENTIFIED BY 'NewPassword';
5.Go back to /etc/my.cnf and remove/comment skip-grant-tables
6.Restart Mysql

After that, I have checked by command line:
telnet  3306, which seems to be correct.


问:
how to get content in same div without getting in many boxes?
I have following code

```<code><div class="col-md-9">
                 <div id="statbox">
                       {% for obj in product_type %}
                       {% for obj1 in vastu %}
                        <script type="text/javascript">
                            var product  = "{{ obj.type_product }}";
                            var product1 = "{{ name }}";
                            var vastu    = "{{ obj1.vastu_key.id }}";
                            var type_id  = "{{ obj.id }}";

                            if (vastu == type_id)
                            {
                            var title = "{{ obj1.title }}";
                            var brand = "{{ obj1.brand }}";
                            var img   = "{{ obj1.image }}";
                            var price = "{{ obj1.price }}";

                            $("#statbox").prepend("<div id='box2'>"
                                                + title
                                                + brand
                                                + price
                                                +"</div>");
                            }
                        </script>
                            {% endfor %}
                         {% endfor %}
                 </div>
</code>```

I am using two for loops here and the box2 which is styled in css, by running this code i got box2 multiple times as content contains in child for loop and that title,brand,img,price is displyed in each new box2.
But i want new box2 should be generate only according to content contains in parent for loop not according to content contains in child for loop
and the all contents i.e. title,brand,img,price which are associated with each content of parent for loop should disply in same box2.
Multiple box2 only create according to parent for loop and contents of child for loop in the same box2 created by parent for loop.
Thank you....

答:
Create a JS object and loop that . Also change the ID to class

Something like this:

var boxes = [
  {% for obj in product_type %}
    {
    {% for obj1 in vastu %}
     "product":"{{ obj.type_product }}",
     "product1":"{{ name }}",
     "vastu": "{{ obj1.vastu_key.id }}",
     "type_id":"{{ obj.id }}"
     {% if obj1.vastu_key.id == obj.id %}
     ,
     "title":"{{ obj1.title }}",
     "brand":"{{ obj1.brand }}",
     "img":"{{ obj1.image }}",
     "price":"{{ obj1.price }}"
     {% endif %}
   {% endfor %}
   }
   {% endfor %}
];
$.each(boxes,function(obj) {
  $("#statbox").prepend("
"
   + obj.title || ""
   + obj.brand || ""
   + obj.price || """
   +"
");
});
                         ```

Body:
I have following code

                       {% for obj in product_type %}
                       {% for obj1 in vastu %}

                            {% endfor %}
                         {% endfor %}

I am using two for loops here and the box2 which is styled in css, by running this code i got box2 multiple times as content contains in child for loop and that title,brand,img,price is displyed in each new box2.
But i want new box2 should be generate only according to content contains in parent for loop not according to content contains in child for loop
and the all contents i.e. title,brand,img,price which are associated with each content of parent for loop should disply in same box2.
Multiple box2 only create according to parent for loop and contents of child for loop in the same box2 created by parent for loop.
Thank you....

Body:
Create a JS object and loop that . Also change the ID to class

Something like this:

var boxes = [
  {% for obj in product_type %}
    {
    {% for obj1 in vastu %}
     "product":"{{ obj.type_product }}",
     "product1":"{{ name }}",
     "vastu": "{{ obj1.vastu_key.id }}",
     "type_id":"{{ obj.id }}"
     {% if obj1.vastu_key.id == obj.id %}
     ,
     "title":"{{ obj1.title }}",
     "brand":"{{ obj1.brand }}",
     "img":"{{ obj1.image }}",
     "price":"{{ obj1.price }}"
     {% endif %}
   {% endfor %}
   }
   {% endfor %}
];
$.each(boxes,function(obj) {
  $("#statbox").prepend("<div class='box2'>"
   + obj.title || ""
   + obj.brand || ""
   + obj.price || """
   +"</div>");
});


问:
Normalizr and recursive nested structure
I'm using normalizr to flatten a structure like the following one:

```<code>{
  "fields":[{
    "id":"29",
    "text": "something"
  }, {
    "id":"16",
    "text": "something"
    "fields":[{
      "id":"17",
      "text": "something"
    }]
  }, {
    "id":"18",
    "text": "something"
  }
}
</code>```

My structure has an array of fields and a field may also have nested fields. There's only one level of nesting allowed.

What I'm trying to do is this:

```<code>const block = new schema.Entity('fields')
const blockList = new schema.Array(block)

block.define({
  fields: blockList
})

const normalizedData = normalize(originalData, blockList)
</code>```

After running this snippet, normalizedData has a results property and it only has the first level of field ids, even though entities has all the fields normalized, including the nested ones.

I'd like to have in the results array all the ids, including the nested ones. What am I missing?

答:
You should consider using a normalized form for your data structure in redux.
This is advisable if your application need growth in complexity.

There is an interesting article on redux docs.
http://redux.js.org/docs/recipes/reducers/NormalizingStateShape.html

A normalized form take some ideas from db counterpart and Normalizr works in that way, so your request does not really match with how Normalizr works.

Please consider @Paul Armstrong answer for a work around if you really need get blocks in that way.

Body:
I'm using normalizr to flatten a structure like the following one:

{
  "fields":[{
    "id":"29",
    "text": "something"
  }, {
    "id":"16",
    "text": "something"
    "fields":[{
      "id":"17",
      "text": "something"
    }]
  }, {
    "id":"18",
    "text": "something"
  }
}

My structure has an array of fields and a field may also have nested fields. There's only one level of nesting allowed.

What I'm trying to do is this:

const block = new schema.Entity('fields')
const blockList = new schema.Array(block)

block.define({
  fields: blockList
})

const normalizedData = normalize(originalData, blockList)

After running this snippet, normalizedData has a results property and it only has the first level of field ids, even though entities has all the fields normalized, including the nested ones.

I'd like to have in the results array all the ids, including the nested ones. What am I missing?


问:
How do you select child-or-self (children + self)
In XSL 1.0, descendant-or-self will select ALL descendants and the current node. What if you want to select only the immediate children and the current node (i.e. child-or-self)?

Is that possible with XPATH?

答:
In XPath 1.0 or later use:

```<code>SomeExpression | SomeExpresion/node()
</code>```

In XPath 2.0 or later use:

```<code>SomeExpression/(self::node()|node())
</code>```

An incorrect answer would be:

```<code>SomeExpression | SomeExpression/*
</code>```

because this selects only those children of SomeExpression that are elements, while SomeExpression may have other children too -- as text-nodes, comment nodes, processing-instruction nodes.

Also incorrect is:

```<code>./SomeExpression | ./*/SomeExpression
</code>```

This doesn't select the immediate children of ./SomeExpression and it doesn't select the immidiate children of ./*/SomeExpression.

ContentLicense: CC BY-SA 2.5

Body:
In XPath 1.0 or later use:

SomeExpression | SomeExpresion/node()

In XPath 2.0 or later use:

SomeExpression/(self::node()|node())

An incorrect answer would be:

SomeExpression | SomeExpression/*

because this selects only those children of SomeExpression that are elements, while SomeExpression may have other children too -- as text-nodes, comment nodes, processing-instruction nodes.

Also incorrect is:

./SomeExpression | ./*/SomeExpression

This doesn't select the immediate children of ./SomeExpression and it doesn't select the immidiate children of ./*/SomeExpression.

ContentLicense: CC BY-SA 4.0


问:
How to handle an un-encoded special character in a url query string?
I have a url like this:

```<code>http://www.nearbynursinghomes.com/innerpage.php?state=CA&city=RIVERSIDE&shop=ALTA%20VISTA%20HEALTHCARE%20&%20WELLNESS%20CENTRE
</code>```

I'm currently using this code:

```<code>$category = $_GET["state"];
$city= $_GET["city"];
$shop= $_GET["shop"];
if (isset($_GET["page"])) { $page  = $_GET["page"]; } else { $page=1; };

$start_from = ($page-1) * $results_per_page;
$sql = "SELECT *
    FROM $datatable
    WHERE STATE='$category'
    AND CITY='$city'
    AND PROVNAME='$shop'
    ORDER BY PROVNAME ASC LIMIT $start_from, $results_per_page" ;
$rs_result = $conn->query($sql);
</code>```

However it doesn't return the proper value because of the & in the middle of the value which says shop=ALTA%20VISTA%20HEALTHCARE%20&%20WELLNESS%20CENTRE.

It just gets cut off. How would I fix this?

答:
After a good nights rest i came up with this solution using the tools provided here. </p>

```<code>$shop= $_SERVER['REQUEST_URI'];
$shop= explode("=", $shop,4);
$shop= $shop[3];
$shop= urldecode("$shop");
</code>```

Body:
I have a url like this:

http://www.nearbynursinghomes.com/innerpage.php?state=CA&city=RIVERSIDE&shop=ALTA%20VISTA%20HEALTHCARE%20&%20WELLNESS%20CENTRE

I'm currently using this code:

$category = $_GET["state"];
$city= $_GET["city"];
$shop= $_GET["shop"];
if (isset($_GET["page"])) { $page  = $_GET["page"]; } else { $page=1; };

$start_from = ($page-1) * $results_per_page;
$sql = "SELECT *
    FROM $datatable
    WHERE STATE='$category'
    AND CITY='$city'
    AND PROVNAME='$shop'
    ORDER BY PROVNAME ASC LIMIT $start_from, $results_per_page" ;
$rs_result = $conn->query($sql);

However it doesn't return the proper value because of the & in the middle of the value which says shop=ALTA%20VISTA%20HEALTHCARE%20&%20WELLNESS%20CENTRE.

It just gets cut off. How would I fix this?

Body:
After a good nights rest i came up with this solution using the tools provided here.

$shop= $_SERVER['REQUEST_URI'];
$shop= explode("=", $shop,4);
$shop= $shop[3];
$shop= urldecode("$shop");


问:
Centered content when resizing the browser is going off to the right side of the page
I'm building a random quote generator: http://codepen.io/Kestvir/pen/peqjZZ ,
and while doing the html/css part of things, I've encountered a problem with the content, that is inside the transparent background. When resizing the window, the content is going off to right side, and it no longer looks like it is centered, when it actually is. If I remove the margins of the background (margin:  0 150px;) then this problem no longer exists, but then the transparent background becomes as wide as the entire window. I suspect that this is because my
 is outside of the container, but I did so, because I had no idea, how to center my contents with the mentioned div class being inside the container, as opposed, of how it is now, because it was stuck to the very top of the page. How should I fix the text and buttons going off to the right, and not looking centered ?

答:
I think this is what you wanted. I added the margin inside container and row divs, added the background color and border radius and removed it from your other class.

codepen

```<code>    <body>
      <div class="quote-bckgr">
        <div class="container">
          <div class="row">
            <div class="new-margin">
              <div class="col-sm-12">
                <h1> Welcome to CIV5 random quote generator!</h1>
                <div id="quotation"></div>
                <div id="author"></div>
              </div>

              <div class="row">
                <div class= "col-md-3 col-md-offset-3">
                  <a href="#" id="twitter" class="btn" target="_blank"> <i class="fa fa-twitter" aria-hidden="true"></i>Tweet This Quote</a>
                </div>
                <div class="col-md-3">
                  <a href="#" id="newQuote" class="btn" target="_blank">New Quote</a>
                </div>
              </div>

            </div>
          </div>
        </div>
      </div>
    </body>
</code>```

and css

```<code>.quote-bckgr {
      color: #fff;
      text-align: center;
      position: relative;
      top: 50%;
      margin: 0 auto;
      transform: translatey(-50%);
      overflow: hidden;
    }
    .new-margin{
      margin:0 155px;
      background-color: rgba(25, 0, 0, .45);
      border-radius:5px;
    }
</code>```

Body:
I think this is what you wanted. I added the margin inside container and row divs, added the background color and border radius and removed it from your other class.

codepen

    <body>
      <div class="quote-bckgr">
        <div class="container">
          <div class="row">
            <div class="new-margin">
              <div class="col-sm-12">
                <h1> Welcome to CIV5 random quote generator!</h1>
                <div id="quotation"></div>
                <div id="author"></div>
              </div>

              <div class="row">
                <div class= "col-md-3 col-md-offset-3">
                  <a href="#" id="twitter" class="btn" target="_blank"> <i class="fa fa-twitter" aria-hidden="true"></i>Tweet This Quote</a>
                </div>
                <div class="col-md-3">
                  <a href="#" id="newQuote" class="btn" target="_blank">New Quote</a>
                </div>
              </div>

            </div>
          </div>
        </div>
      </div>
    </body>

and css

.quote-bckgr {
      color: #fff;
      text-align: center;
      position: relative;
      top: 50%;
      margin: 0 auto;
      transform: translatey(-50%);
      overflow: hidden;
    }
    .new-margin{
      margin:0 155px;
      background-color: rgba(25, 0, 0, .45);
      border-radius:5px;
    }


问:
JavaScript window.location.assign() is not working
I am working on an HTML based text-adventure game, where one choice leads to the next, based on which links the user clicks. I am using localStorage to store the HP value of the player, when the HP value hits 0, the game is supposed to end, and the website is supposed to change to a 'Game Over' page. I have two functions that both navigate to a different page, depending on if the HP is above or below a certain number

```<code>function alterHP(value) {
    if (typeof (Storage) !== "undefined") {
        var currentHP = parseInt(localStorage.HP);
        localStorage.HP = currentHP + value;
        hp=parseInt(localStorage.HP);
        if (hp<=0) {
            alert(hp); //For debugging, is showing a negative number, like it should be
            /*If the error is syntactical, it is the next line*/
            window.location.replace('youLose.html');
            /*I used breakpoints and this line IS getting hit*/
            /*It's just not going to the 'youLose' page*/
        }
    }
}

function getResult() {
    var currentHP = parseInt(localStorage.HP);
    if (currentHP > 4) {
        window.location.assign('endAbove4.html');//These both work fine
    } else {
        window.location.assign('endBelow4.html');//These both work fine
    }
}
</code>```

```<code><li><a
    href="../S9/S9.html" onclick="alterHP(-6);"
    class="ghost-button">Go on to the next scene</a></li>
</code>```

I have tried every variation of the path name for youLose.html that i can think of, including ../youLose.html, ../../youLose.html, ..\youLose.html, and even putting the full http://gw.mvctc.com/Class2018/smcintosh/Projects/StMarys (I physically opened the page and copied directly from the URL bar to my code, so I know it was the right address.) I also tried using window.location.href="../youLose.html" "youLose.html" '../youLose.html' and 'youLose.html' and window.location.replace()

The most frustrating part is that if you get to the point where getResult(); is called, and you have -26hp, it acts correctly and redirects to the endBelow4.html page. I just need it to redirect to the youLose page as soon as HP hits 0

I cannot for the life of me figure out why it wont redirect to the youLose page.

答:
Put

```<code>window.close('game');
window.open('../youLose.html');
</code>```

inplace of the window.location.assign(); then  in your index.html page place

```<code><script>window.name("game");</script>
</code>```

and this will close the tab for the game, and then open the youLose.html in a new tab that replaces the original tab.

Body:
I am working on an HTML based text-adventure game, where one choice leads to the next, based on which links the user clicks. I am using localStorage to store the HP value of the player, when the HP value hits 0, the game is supposed to end, and the website is supposed to change to a 'Game Over' page. I have two functions that both navigate to a different page, depending on if the HP is above or below a certain number

function alterHP(value) {
    if (typeof (Storage) !== "undefined") {
        var currentHP = parseInt(localStorage.HP);
        localStorage.HP = currentHP + value;
        hp=parseInt(localStorage.HP);
        if (hp<=0) {
            alert(hp); //For debugging, is showing a negative number, like it should be
            /*If the error is syntactical, it is the next line*/
            window.location.replace('youLose.html');
            /*I used breakpoints and this line IS getting hit*/
            /*It's just not going to the 'youLose' page*/
        }
    }
}

function getResult() {
    var currentHP = parseInt(localStorage.HP);
    if (currentHP > 4) {
        window.location.assign('endAbove4.html');//These both work fine
    } else {
        window.location.assign('endBelow4.html');//These both work fine
    }
}

Go on to the next scene

I have tried every variation of the path name for youLose.html that i can think of, including ../youLose.html, ../../youLose.html, ..\youLose.html, and even putting the full http://gw.mvctc.com/Class2018/smcintosh/Projects/StMarys (I physically opened the page and copied directly from the URL bar to my code, so I know it was the right address.) I also tried using window.location.href="../youLose.html" "youLose.html" '../youLose.html' and 'youLose.html' and window.location.replace()

The most frustrating part is that if you get to the point where getResult(); is called, and you have -26hp, it acts correctly and redirects to the endBelow4.html page. I just need it to redirect to the youLose page as soon as HP hits 0

I cannot for the life of me figure out why it wont redirect to the youLose page.

Body:
Put

window.close('game');
window.open('../youLose.html');

inplace of the window.location.assign(); then  in your index.html page place

<script>window.name("game");</script>

and this will close the tab for the game, and then open the youLose.html in a new tab that replaces the original tab.


答:
It's totally acceptable to create sw320dp,sw480dp,sw600dp and sw720dp.
You don't need to think about the smallest width since it will choose on its own depends on the device size.
So just create those layouts 320-720 and if the device is not in those sizes it will just fall into the default one.</p>

Title: Which is the minimum width at which default layout is used

Body:
I am creating alternative layouts for my activities, for example sw320dp, etc. I plan to create another for sw480dp, and sw600dp, sw720dp.
In which segment falls the default layout, the one without qualifiers? So I don't duplicate code.


问:
Compare columns in 2 files, append data for shared items and print the non shared items of the first file
I have found similar questions as mine but none helped me with my specific problem (and i'm not quite sure whether there actually is such an easy solution..)

I have two files:

file1:

```<code>a b c
d e f
g h i
</code>```

file2:

```<code>a b x y z
d e x
f h i
</code>```

Desired Output:

```<code>a b c x y z
d e f x
g h i
</code>```

So, I want all the rows and columns from file 1 and additionally, if there is a match of the first two columns in file 2, I want to append the rest of those columns (from file 2) to the ones in file 1 and write it in a new file.

I have tried with awk but so far I have only managed to append the columns for those rows that have a match, but the other ones (in my example the "g,h,i" row) is not printed.
Another issue seems to be that the items in file 2 do not always have the same amount of columns.

Does anyone have an idea how to solve this?

Thank you!

答:
here is another awk

```<code> awk        '{k=$1 FS $2}
     NR==FNR {sub(k,"",$0); a[k]=$0; next}
     k in a  {$0 = $0 a[k]}1' file2 file1

a b c x y z
d e f x
g h i
</code>```

note the order of the files.

Body:
I have found similar questions as mine but none helped me with my specific problem (and i'm not quite sure whether there actually is such an easy solution..)

I have two files:

file1:

a b c
d e f
g h i

file2:

a b x y z
d e x
f h i

Desired Output:

a b c x y z
d e f x
g h i

So, I want all the rows and columns from file 1 and additionally, if there is a match of the first two columns in file 2, I want to append the rest of those columns (from file 2) to the ones in file 1 and write it in a new file.

I have tried with awk but so far I have only managed to append the columns for those rows that have a match, but the other ones (in my example the "g,h,i" row) is not printed.
Another issue seems to be that the items in file 2 do not always have the same amount of columns.

Does anyone have an idea how to solve this?

Thank you!

Body:
here is another awk

 awk        '{k=$1 FS $2}
     NR==FNR {sub(k,"",$0); a[k]=$0; next}
     k in a  {$0 = $0 a[k]}1' file2 file1

a b c x y z
d e f x
g h i

note the order of the files.


问:
Extract specific data from text
I have a single column with many rows with following geographical information:

Ø228818, N6575807 Sone 33 (±500m) UTM(WGS 84)

These are all merged in a single column, only separated with "," and " " .
I need to extract the "Sone XX" into an own column, but i haven`t found any suitable commands for this.
Any suggestions?

答:
You can get this with sub and a regular expression.

```<code>NewColumn = sub(".*\\b(Sone\\s+\\d+).*", "\\1", String)
NewColumn
[1] "Sone 33"
</code>```

Some detail on the RegEx

The part in the middle Sone\\s+\\d+ is what you want.

Sone is the literal string. \\s+ matches one or more blanks. \\d+ matches one or more digits, 0-9.  That group is enclosed in parentheses so that the result is stored for later use. The pattern is preceded and followed by \\.* to match everything else.

Title: Extract specific data from text

Body:
You can get this with sub and a regular expression.

NewColumn = sub(".*\\b(Sone\\s+\\d+).*", "\\1", String)
NewColumn
[1] "Sone 33"

Some detail on the RegEx

The part in the middle Sone\\s+\\d+ is what you want.

Sone is the literal string. \\s+ matches one or more blanks. \\d+ matches one or more digits, 0-9.  That group is enclosed in parentheses so that the result is stored for later use. The pattern is preceded and followed by \\.* to match everything else.


问:
what is a good mocking framework to start mocking with in asp.net MVC? (novice and probably not a hardcore mocker)
i want to use mocking in my unit tests.

Till now i more programmed 'tests' and not 'unittests' because i tested whole program flows, but reading discussions i can see the beauty of a mock object, from time to time.

But, looking around, there are a lot of frameworks available, and i want to make sure i start with a good one, because i'd like to invest time in learning a mock framework only once.

So as i said in the title, i'm a novice for mocking, using asp.net mvc, and don't think i'll be a hardcore mocker, investigating the edges of a mocking framework.

To give you an idea of what i like in the IOC frameworks i like unity and structuremap.

Michel

答:
I recommend Moq.

Say you have a class MyClass defined as follows:

```<code>public class MyClass{

    private IMyDependency dependency;

    public MyClass(IMyDependency dependency){
        this.dependency = dependency;
    }

    public void DoSomething(){
        //invoke a method on the dependency
        this.dependency.DoWork();
    }

}
</code>```

IMyDependency is declared like this:

```<code>public interface IMyDependency{
    void DoWork();
}
</code>```

Now using Moq, you could test that the dependency is called like so:

```<code>public void DoSomethingWillInvokeDoWorkCorrectly()
{
    var mock = new Mock<IMyDependency>();
    mock.Setup(imd => imd.DoWork()).Verifiable();
    var sut = new MyClass(mock.Object);
    sut.DoSomething();
    //Verify that the mock was called correctly
    mock.Verify();
}
</code>```

Now that was a very simple example, so lets spice it up a little.

public class MyClass2{

```<code>    private IMyDependency2 dependency;

    public MyClass2(IMyDependency2 dependency){
        this.dependency = dependency;
    }

    public void DoSomething(int i){
        //invoke a method on the dependency
        this.dependency.DoWork(i * 2);
    }

}
</code>```

IMyDependency2 is declared like this:

```<code>public interface IMyDependency2{
    void DoWork(int i);
}
</code>```

A test method that tests that the correct parameter is passed to the dependency could look like this:

```<code>public void DoSomethingV2WillInvokeDoWorkCorrectly()
{
    var mock = new Mock<IMyDependency2>();
    int parameter = 60;
    mock.Setup(imd => imd.DoWork(It.Is<int>(i => i == 2 * parameter)).Verifiable();
    var sut = new MyClass2(mock.Object);
    sut.DoSomething(parameter);
    //Verify that the mock was called correctly
    mock.Verify();
}
</code>```

As you can see, the Setup method now adds a constraint on the parameter passed to DoWork, saying that it is an int the value of which must be twice the value of the parameter variable.

Body:
I recommend Moq.

Say you have a class MyClass defined as follows:

public class MyClass{

    private IMyDependency dependency;

    public MyClass(IMyDependency dependency){
        this.dependency = dependency;
    }

    public void DoSomething(){
        //invoke a method on the dependency
        this.dependency.DoWork();
    }

}

IMyDependency is declared like this:

public interface IMyDependency{
    void DoWork();
}

Now using Moq, you could test that the dependency is called like so:

public void DoSomethingWillInvokeDoWorkCorrectly()
{
    var mock = new Mock<IMyDependency>();
    mock.Setup(imd => imd.DoWork()).Verifiable();
    var sut = new MyClass(mock.Object);
    sut.DoSomething();
    //Verify that the mock was called correctly
    mock.Verify();
}

Now that was a very simple example, so lets spice it up a little.

public class MyClass2{

    private IMyDependency2 dependency;

    public MyClass2(IMyDependency2 dependency){
        this.dependency = dependency;
    }

    public void DoSomething(int i){
        //invoke a method on the dependency
        this.dependency.DoWork(i * 2);
    }

}

IMyDependency2 is declared like this:

public interface IMyDependency2{
    void DoWork(int i);
}

A test method that tests that the correct parameter is passed to the dependency could look like this:

public void DoSomethingV2WillInvokeDoWorkCorrectly()
{
    var mock = new Mock<IMyDependency2>();
    int parameter = 60;
    mock.Setup(imd => imd.DoWork(It.Is<int>(i => i == 2 * parameter)).Verifiable();
    var sut = new MyClass2(mock.Object);
    sut.DoSomething(parameter);
    //Verify that the mock was called correctly
    mock.Verify();
}

As you can see, the Setup method now adds a constraint on the parameter passed to DoWork, saying that it is an int the value of which must be twice the value of the parameter variable.


问:
Replacing an empty cell in one column based on corresponding value from another column?
I have this data frame:

```<code>df <- data.frame(number = c(1,2,3,1,3,4,5,2),
             name = c('dany', 'rand', 'tanya',
                      ' ', ' ', 'bruce', 'tony', ' '),
             grade = c('a', 'b', 'c', ' ', 'c', 'd', 'e', ' '))
</code>```

which looks like this:

```<code> > df
# A tibble: 8 × 3
number  name grade
 <dbl> <chr> <chr>
    1  dany     a
    2  rand     b
    3 tanya     c
    1
    3           c
    4 bruce     d
    5  tony     e
    2
</code>```

what I want is this:

```<code> > df
# A tibble: 8 × 3
number  name grade
 <dbl> <chr> <chr>
    1  dany     a
    2  rand     b
    3 tanya     c
    1  dany     a
    3 tanya     c
    4 bruce     d
    5  tony     e
    2  rand     b
</code>```

How do I accomplish this ?
how do I replace the empty spaces with the values corresponding to number column?

If possible, please explain how can I achieve this with dplyr(tidyverse).

答:
It will be easier to handle if you have NAs,</p>

```<code>library(dplyr)
library(tidyr)

df[df == ' '] <- NA

df %>%
 group_by(number) %>%
 fill(name, grade)

#Source: local data frame [8 x 3]
#Groups: number [5]

#  number  name grade
#   <dbl> <chr> <chr>
#1      1  dany     a
#2      1  dany     a
#3      2  rand     b
#4      2  rand     b
#5      3 tanya     c
#6      3 tanya     c
#7      4 bruce     d
#8      5  tony     e
</code>```

Body:
I have this data frame:

df <- data.frame(number = c(1,2,3,1,3,4,5,2),
             name = c('dany', 'rand', 'tanya',
                      ' ', ' ', 'bruce', 'tony', ' '),
             grade = c('a', 'b', 'c', ' ', 'c', 'd', 'e', ' '))

which looks like this:

 > df
# A tibble: 8 × 3
number  name grade
 <dbl> <chr> <chr>
    1  dany     a
    2  rand     b
    3 tanya     c
    1
    3           c
    4 bruce     d
    5  tony     e
    2

what I want is this:

 > df
# A tibble: 8 × 3
number  name grade
 <dbl> <chr> <chr>
    1  dany     a
    2  rand     b
    3 tanya     c
    1  dany     a
    3 tanya     c
    4 bruce     d
    5  tony     e
    2  rand     b

How do I accomplish this ?
how do I replace the empty spaces with the values corresponding to number column?

If possible, please explain how can I achieve this with dplyr(tidyverse).

Body:
It will be easier to handle if you have NAs,

library(dplyr)
library(tidyr)

df[df == ' '] <- NA

df %>%
 group_by(number) %>%
 fill(name, grade)

#Source: local data frame [8 x 3]
#Groups: number [5]

#  number  name grade
#   <dbl> <chr> <chr>
#1      1  dany     a
#2      1  dany     a
#3      2  rand     b
#4      2  rand     b
#5      3 tanya     c
#6      3 tanya     c
#7      4 bruce     d
#8      5  tony     e


问:
SVN - how to transform individually checked-out sub-folders into sparse checkout
SVN repo looks like this:

top/

top/one

top/two

top/three

  ...etc

You don't want to checkout the entire top folder but you don't know about SVN's sparse checkout feature.

So you check-out repo folder top/one into C:\svn\top\one and then you checkout repo folder top/two into C:\svn\top\two

At this point, both of the checked-out folders have their own .svn folder

Then you discover sparse checkouts.

QUESTION

How do you transform the "standalone" checkout of these two folders into a sparse checkout of the top-level folder with minimal re-checking out?

Is it as simple as initiating a sparse check-out while not overwriting existing items and then simply deleting the pre-existing .svn folders?

答:
SVN works recursively, which means that every folder is mostly independent from its parent. So the issue comes from the .SVN in the parent folder, this is the one you want to recreate from scratch.

Rename your former folder (.old) and create a new one. Do your Sparse Checkout in that folder. It should download the files but you can prevent that with --depth empty.

Then, move your old folders back in the freshly created Sparse Checkout folder and Clean it. SVN will scan and repair the folder recursively.


问:
C# Json.NET Render Flags Enum as String Array
In a .NET Application, I have a set of values that are stored as a [Flags] enum. I want to serialize these to json, but instead of having the result be an integer, I'd like to get an array of string for the flags that are active.

So if I have the following code

```<code>[Flags]
public enum F
{
    Val1 = 1,
    Val2 = 2,
    Val4 = 4,
    Val8 = 8

}

public class C
{
    public F Flags { get; set; }
}

string Serialize() {
    return JsonConvert.SerializeObject(new C { Flags = F.Val1 | F.Val4 });
}
</code>```

I want the Serialize() method to return:

```<code>"{ Flags: [ "Val1", "Val4" ] }"
</code>```

Instead of:

```<code>"{ Flags: 5 }"
</code>```

答:
Decorate your enum

```<code>[Flags]
[JsonConverter(typeof(Newtonsoft.Json.Converters.StringEnumConverter))]
public enum F
{
    Val1 = 1,
    Val2 = 2,
    Val4 = 4,
    Val8 = 8
}
</code>```

Output:

{"Flags":"Val1, Val4"}

I realise the JSON is not an array as in your question, wasn't sure if this was required since this is also valid JSON.

Body:
In a .NET Application, I have a set of values that are stored as a [Flags] enum. I want to serialize these to json, but instead of having the result be an integer, I'd like to get an array of string for the flags that are active.

So if I have the following code

[Flags]
public enum F
{
    Val1 = 1,
    Val2 = 2,
    Val4 = 4,
    Val8 = 8

}

public class C
{
    public F Flags { get; set; }
}

string Serialize() {
    return JsonConvert.SerializeObject(new C { Flags = F.Val1 | F.Val4 });
}

I want the Serialize() method to return:

"{ Flags: [ "Val1", "Val4" ] }"

Instead of:

"{ Flags: 5 }"

Body:
Decorate your enum

[Flags]
[JsonConverter(typeof(Newtonsoft.Json.Converters.StringEnumConverter))]
public enum F
{
    Val1 = 1,
    Val2 = 2,
    Val4 = 4,
    Val8 = 8
}

Output:

{"Flags":"Val1, Val4"}

I realise the JSON is not an array as in your question, wasn't sure if this was required since this is also valid JSON.


问:
matching occurrence of opposite number in a list python
I have a list such has

```<code>results = [100, 100, -100, 100, -100, -100]
</code>```

I would like to figure out the first occurrence of the opposite number. so first 100 would be match with the first -100, the second 100 would be match with the second -100.

I would like to have position as output such has:

```<code>[0, 2], [1, 4], [3, 5]
</code>```

i.e : [0,2] represent the results[0] and  results[2]  where first occurrence of 100 is match with the first occurrence of -100

edit : you can assume there will always be the same amount of positive / negative and that the list will only contain 1 number

any help would be appricated

答:
This would work as well for the general case in which different numbers occur:</p>

```<code>solutions = []
for x in set(abs(x) for x in results):
    solutions += list(zip([i for i, x2 in enumerate(results) if x2 == x],
                          [i for i, x2 in enumerate(results) if x2 == x*-1]))
</code>```

Body:
I have a list such has

results = [100, 100, -100, 100, -100, -100]

I would like to figure out the first occurrence of the opposite number. so first 100 would be match with the first -100, the second 100 would be match with the second -100.

I would like to have position as output such has:

[0, 2], [1, 4], [3, 5]

i.e : [0,2] represent the results[0] and  results[2]  where first occurrence of 100 is match with the first occurrence of -100

edit : you can assume there will always be the same amount of positive / negative and that the list will only contain 1 number

any help would be appricated

Body:
This would work as well for the general case in which different numbers occur:

solutions = []
for x in set(abs(x) for x in results):
    solutions += list(zip([i for i, x2 in enumerate(results) if x2 == x],
                          [i for i, x2 in enumerate(results) if x2 == x*-1]))


问:
Javascript swaps to mm/dd date but the input field is dd/mm
I have an html form with bootstrap with this date fields:

```<code><input type="date" class="form-control" id="from" name="from" placeholder="dd/mm/yyyy">
<input type="date" class="form-control" id="to" name="to" placeholder="dd/mm/yyyy">
</code>```

I need to compare the two to check "to" is a date after "from", but when I compare using this code:

```<code>if(new Date($("#from").val() > new Date($("#to").val()) ....
</code>```

the calculation goes wrong because under the hood it swaps month numbers with the day numbers. How do I force it to take the dd/mm/yyyy format (or convert the input as mm/dd/yyyy) to get the proper calculation?
Thank you.

答:
You can't force the date format with a placeholder. If the browser supports date well it will be overridden depending on local settings, in which case the actual field value should always be in YYYY-MM-DD format. This is how Chrome handles the field.

In this case it will work

```<code>var from = new Date($("#from").val());
var to = new Date($("#to").val());
if (from > to)
</code>```

Other browsers like Firefox for instance do however not support the date field well. It will just work like a normal text input. In this case you will need to do some string manipulation to separate the values and insert them in a way that Date() expects:
new Date(YYYY, MM, DD);

Body:
I have an html form with bootstrap with this date fields:

<input type="date" class="form-control" id="from" name="from" placeholder="dd/mm/yyyy">
<input type="date" class="form-control" id="to" name="to" placeholder="dd/mm/yyyy">

I need to compare the two to check "to" is a date after "from", but when I compare using this code:

if(new Date($("#from").val() > new Date($("#to").val()) ....

the calculation goes wrong because under the hood it swaps month numbers with the day numbers. How do I force it to take the dd/mm/yyyy format (or convert the input as mm/dd/yyyy) to get the proper calculation?
Thank you.

Body:
You can't force the date format with a placeholder. If the browser supports date well it will be overridden depending on local settings, in which case the actual field value should always be in YYYY-MM-DD format. This is how Chrome handles the field.

In this case it will work

var from = new Date($("#from").val());
var to = new Date($("#to").val());
if (from > to)

Other browsers like Firefox for instance do however not support the date field well. It will just work like a normal text input. In this case you will need to do some string manipulation to separate the values and insert them in a way that Date() expects:
new Date(YYYY, MM, DD);


问:
How to get Selected Text from select2 when using <input>
I am using the select2 control, loading data via ajax. This requires the use of the <input type=hidden..> tag.

Now, I want to retrieve the selected text. (The value property in the data-bind expression sotres the id only)

I have tried $(".select2-chosen").text(), but this breaks when I have multiple select2 controls on the page.

答:
The code below also solves otherwise</p>

```<code>.on("change", function(e) {

  var lastValue = e.currentTarget.value;
  var lastText = e.currentTarget.textContent;

 });
</code>```

Body:
The code below also solves otherwise

.on("change", function(e) {

  var lastValue = e.currentTarget.value;
  var lastText = e.currentTarget.textContent;

 });


问:
Remove all punctuation from string, except if it's between digits
I have a text that contains words and numbers. I'll give a representative example of the text:

```<code>string = "This is a 1example of the text. But, it only is 2.5 percent of all data"
</code>```

I'd like to convert it to something like:

```<code>"This is a  1 example of the text But it only is  2.5  percent of all data"
</code>```

So removing punctuation (can be . , or any other in string.punctuation) and also put a space between digits and words when it is concatenated. But keep the floats like 2.5 in my example.

I used the following code:

```<code>item = "This is a 1example of the text. But, it only is 2.5 percent of all data"
item = ' '.join(re.sub( r"([A-Z])", r" \1", item).split())
# This a start but not there yet !
#item = ' '.join([x.strip(string.punctuation) for x in item.split() if x not in string.digits])
item = ' '.join(re.split(r'(\d+)', item) )
print item
</code>```

The result is :

```<code> >> "This is a  1 example of the text. But, it only is  2 . 5  percent of all data"
</code>```

I'm almost there but can't figure out that last peace.

答:
Code:

```<code>from itertools import groupby

s1 = "This is a 1example of the text. But, it only is 2.5 percent of all data"
s2 = [''.join(g) for _, g in groupby(s1, str.isalpha)]
s3 = ' '.join(s2).replace("   ", "  ").replace("  ", " ")

#you can keep adding a replace for each ponctuation
s4 = s3.replace(". ", " ").replace(", "," ").replace("; "," ").replace(", "," ").replace("- "," ").replace("? "," ").replace("! "," ").replace(" ("," ").replace(") "," ").replace('" '," ").replace(' "'," ").replace('... '," ").replace('/ '," ").replace(' “'," ").replace('” '," ").replace('] '," ").replace(' ['," ")

s5 = s4.replace("  ", " ")
print(s5)
</code>```

Output:

```<code>'This is a 1 example of the text But it only is 2.5 percent of all data'
</code>```

P.s.: You can take a look at Punctuation Marks and keep adding them inside the .replace() function.

Body:
I have a text that contains words and numbers. I'll give a representative example of the text:

string = "This is a 1example of the text. But, it only is 2.5 percent of all data"

I'd like to convert it to something like:

"This is a  1 example of the text But it only is  2.5  percent of all data"

So removing punctuation (can be . , or any other in string.punctuation) and also put a space between digits and words when it is concatenated. But keep the floats like 2.5 in my example.

I used the following code:

item = "This is a 1example of the text. But, it only is 2.5 percent of all data"
item = ' '.join(re.sub( r"([A-Z])", r" \1", item).split())
# This a start but not there yet !
#item = ' '.join([x.strip(string.punctuation) for x in item.split() if x not in string.digits])
item = ' '.join(re.split(r'(\d+)', item) )
print item

The result is :

 >> "This is a  1 example of the text. But, it only is  2 . 5  percent of all data"

I'm almost there but can't figure out that last peace.

Body:
Code:

from itertools import groupby

s1 = "This is a 1example of the text. But, it only is 2.5 percent of all data"
s2 = [''.join(g) for _, g in groupby(s1, str.isalpha)]
s3 = ' '.join(s2).replace("   ", "  ").replace("  ", " ")

#you can keep adding a replace for each ponctuation
s4 = s3.replace(". ", " ").replace(", "," ").replace("; "," ").replace(", "," ").replace("- "," ").replace("? "," ").replace("! "," ").replace(" ("," ").replace(") "," ").replace('" '," ").replace(' "'," ").replace('... '," ").replace('/ '," ").replace(' “'," ").replace('” '," ").replace('] '," ").replace(' ['," ")

s5 = s4.replace("  ", " ")
print(s5)

Output:

'This is a 1 example of the text But it only is 2.5 percent of all data'

P.s.: You can take a look at Punctuation Marks and keep adding them inside the .replace() function.


问:
c++ save and load game with pointers in structs
I know I can use:

```<code>MyGame  game; // the game object
//

ofstream out("mygame.bin", ios::binary);
out.write((char *)&game, sizeof(MyGame));
</code>```

to save and load the game, but what if I have pointers inside MyGame structure? will the pointers just be saved but not the data it points to?

and: how to solve this?

答:
Assuming you  have not overridden char * cast, yes this will most probably save only pointer and not data.

What you need is Serialization of your object. You can provide a method to marshal the state of object in a bit stream and write that out. And you also need to have method to restore the state back.

You may read more about serialization on wikipedia

Body:
I know I can use:

MyGame  game; // the game object
//

ofstream out("mygame.bin", ios::binary);
out.write((char *)&game, sizeof(MyGame));

to save and load the game, but what if I have pointers inside MyGame structure? will the pointers just be saved but not the data it points to?

and: how to solve this?

OwnerDisplayName: Rohit J


问:
How to point my compass to Mecca?
I took the code of compass from this link.

http://www.androidcode.ninja/android-compass-code-example/

How to set mecca location on my compass??

What do i need to do to point my compass to Mecca?

答: Well for very few words that's a long question.  The answer is to extend the OnSensorChanged code from the example to calculate the heading to Mecca from the current location and adjust the heading based on the current direction the sensor is facing in.  You'll need the current location co-ordinates from GPS and the fixed co-ordintates for Mecca, Calculate the direction relative to North (the way the compass is designed to point) and then adjust by the current heading.  </p>

Title: How to point my compass to Mecca?


问:
How to check if a List of Lists contains another List
I want to create a list which will hold two int values lets say it arrfirst and another list that will hold lists of arrfirst, lets say it arrsecond then check if arrsecond contains a defined arrfirst . Now i created lists but when i try to use .Contains it doesn't work.

```<code>List<List<int>> Eklenenler = new List<List<int>>();

for (int i = 0; i < YourTable.Rows.Count; i++)
        {
            prjAd = YourTable.Rows[i].Field<string>("F1");
            if (prjAd != "Servis Adresi")
            {
                wesAd = YourTable.Rows[i].Field<string>("F2");
                RowPrj = tbProjeler.AsEnumerable().Where(r => r.Field<string>("prjAd") == prjAd).FirstOrDefault();
                RowWes = tbServisler.AsEnumerable().Where(k => k.Field<string>("wesAd") == wesAd).FirstOrDefault();
                prjId = RowPrj.Field<int>("prjId");
                wesId = RowWes.Field<int>("wesId");
                List<int> temp = new List<int>();
                temp.Add(prjId);
                temp.Add(wesId);
                if (!Eklenenler.Contains(temp))
                {
                    sqlExProjeEkle = "INSERT INTO NLK_PRJ_Webservisler (prjId,wesId) Values (" + prjId + "," + wesId + ")";
                    dco.Execute(sqlExProjeEkle);
                    Eklenenler.Add(temp);

                }
                else
                {

                }
            }
        }
</code>```

This is my code. When i debugging, i can see temp values are right and also at second loop, temp is in Eklenenler list but it always goes in if block. For example, first loop shows temp[0]=36 and temp[1]=42 goes in if block and at second loop again temp[0]=36 and temp[1]=42 also Eklenenler[0][0]=36 and Eklenenler[0][1]=42 so it contains temp but it still goes in. How can i solve this problem and why this returns false and can't find this temp in Eklenenler. Thank you.

答:
Here's an answer using a foreach loop.</p>

```<code>foreach (List<int> list in Eklenenler)
{
    if (list.SequenceEqual(temp))
    {
        //Do work
    }
}
</code>```

Body:
I want to create a list which will hold two int values lets say it arrfirst and another list that will hold lists of arrfirst, lets say it arrsecond then check if arrsecond contains a defined arrfirst . Now i created lists but when i try to use .Contains it doesn't work.

List<List<int>> Eklenenler = new List<List<int>>();

for (int i = 0; i < YourTable.Rows.Count; i++)
        {
            prjAd = YourTable.Rows[i].Field<string>("F1");
            if (prjAd != "Servis Adresi")
            {
                wesAd = YourTable.Rows[i].Field<string>("F2");
                RowPrj = tbProjeler.AsEnumerable().Where(r => r.Field<string>("prjAd") == prjAd).FirstOrDefault();
                RowWes = tbServisler.AsEnumerable().Where(k => k.Field<string>("wesAd") == wesAd).FirstOrDefault();
                prjId = RowPrj.Field<int>("prjId");
                wesId = RowWes.Field<int>("wesId");
                List<int> temp = new List<int>();
                temp.Add(prjId);
                temp.Add(wesId);
                if (!Eklenenler.Contains(temp))
                {
                    sqlExProjeEkle = "INSERT INTO NLK_PRJ_Webservisler (prjId,wesId) Values (" + prjId + "," + wesId + ")";
                    dco.Execute(sqlExProjeEkle);
                    Eklenenler.Add(temp);

                }
                else
                {

                }
            }
        }

This is my code. When i debugging, i can see temp values are right and also at second loop, temp is in Eklenenler list but it always goes in if block. For example, first loop shows temp[0]=36 and temp[1]=42 goes in if block and at second loop again temp[0]=36 and temp[1]=42 also Eklenenler[0][0]=36 and Eklenenler[0][1]=42 so it contains temp but it still goes in. How can i solve this problem and why this returns false and can't find this temp in Eklenenler. Thank you.

Body:
Here's an answer using a foreach loop.

foreach (List<int> list in Eklenenler)
{
    if (list.SequenceEqual(temp))
    {
        //Do work
    }
}


问:
Angular2 - Supplied parameters do not match any signature of call target
```<code>import { Component, Input, OnChanges } from '@angular/core';

@Component({
  selector: 'image-display',
  templateUrl: './image-display.component.html'
})
export class ImageDisplayComponent implements OnChanges {
  @Input() image: File;
  @Input() imagePath?: string;

  private fileReader: FileReader;

  constructor() { }

  ngOnChanges() {
    if (this.image && this.fileReader) {
      this.fileReader.readAsDataURL(this.image);
    }
  }
}
</code>```

On compiling this with AOT getting below error:

```<code>PRINHYLTPAP0592:matata ajays$ ng build --prod --aot
/myApp/src/$$_gendir/app/image-uploader/image-display/image-display.component.ngfactory.ts (61,9):
Supplied parameters do not match any signature of call target.
</code>```

答: please provide code of image-display.component.html file. it might be the variable on the template is not initialized onto the component. Check all the variables you used on the template if they are exists on ImageDisplayComponent.</p>

Body:
import { Component, Input, OnChanges } from '@angular/core';

@Component({
  selector: 'image-display',
  templateUrl: './image-display.component.html'
})
export class ImageDisplayComponent implements OnChanges {
  @Input() image: File;
  @Input() imagePath?: string;

  private fileReader: FileReader;

  constructor() { }

  ngOnChanges() {
    if (this.image && this.fileReader) {
      this.fileReader.readAsDataURL(this.image);
    }
  }
}

On compiling this with AOT getting below error:

PRINHYLTPAP0592:matata ajays$ ng build --prod --aot
/myApp/src/$$_gendir/app/image-uploader/image-display/image-display.component.ngfactory.ts (61,9):
Supplied parameters do not match any signature of call target.


问:
Getting index of dictionary item based on item.key
How can I find the index of an element of a dictionary based on the element key? I'm using the following code to go through the dictionary:

```<code>foreach (var entry in freq)
{
    var word = entry.Key;
    var wordFreq = entry.Value;
    int termIndex = ??????;
}
</code>```

Could anyone help please?

答:
This might work and this is probably not the most efficient way of doing this. Also im not sure why you would want something like this.</p>

```<code>Int termIndex = Array.IndexOf(myDictionary.Keys.ToArray(), someKey);
</code>```

Body:
How can I find the index of an element of a dictionary based on the element key? I'm using the following code to go through the dictionary:

foreach (var entry in freq)
{
    var word = entry.Key;
    var wordFreq = entry.Value;
    int termIndex = ??????;
}

Could anyone help please?

Body:
This might work and this is probably not the most efficient way of doing this. Also im not sure why you would want something like this.

Int termIndex = Array.IndexOf(myDictionary.Keys.ToArray(), someKey);


问:
Is PHP used for quick and easy website where other languages are used in more complex websites?
I just put this question in serverfault.com and I know that this question may be rejected in Stackoverflow.

But I thought programmers know better.

This stat shows that PHP is used by 75.2% of all the websites whose server-side programming language.

http://w3techs.com/technologies/overview/programming_language/all

And this page shows that PHP is the least used server-side language in ranked by usage on top websites

http://w3techs.com/technologies/topsite/programming_language

Q1. Does this mean PHP is used for quick and easy website where other languages are used in more complex websites?

Q2. Why PHP is ranked at the bottom? Or why big company tend to use other language than PHP?

Update: I know that facebook and other biggies uses PHP. But it does not tell why there are more other languages are used in top websites.

答:
PHP

has a very low entry level

is very fast to learn for no experience programmers

it is very forgiving with newbie errors

it has excellent support (including here)

you don't have to do builds, compiling and other complicated stuff

it can accomplish almost everything until you hit a wall and you'll need to retool (facebook style)


问:
Scroll to bottom of DIV element
I’ve seen countless posts on this one and tried them all, but none seem to work and I don't know why.

Basically, I load a SQL generated HTML page into a div, and try to scroll to the bottom of it. Hours later, still I can't figure it out.

```<code><script type="text/javascript">
    $(document).ready(function() {
        $('#chat_grab').load('chat_grab.php');
        $('#chat_grab').stop().animate({ scrollTop: $('#chat_grab')[0].scrollHeight}, 800);
    });
</script>

<div id="chat_grab" style="height: 152px; overflow-y: auto"></div>
</code>```

It doesn't scroll to the bottom of the page. Like I said, I've tried multiple variants of the scroll line found on here.

I tried this, but still no luck;

```<code>$('#chat_grab').load('chat_grab.php', callback);

function callback() {
    $('#chat_grab').scrollTop(0);
}
</code>```

答:
Try this</p>

```<code> $('html, body').stop().animate({
   scrollTop: $('#chat_grab').offset().top - 100
 }, 800);
</code>```

Title: Scroll to bottom of DIV element

Body:
I’ve seen countless posts on this one and tried them all, but none seem to work and I don't know why.

Basically, I load a SQL generated HTML page into a div, and try to scroll to the bottom of it. Hours later, still I can't figure it out.

It doesn't scroll to the bottom of the page. Like I said, I've tried multiple variants of the scroll line found on here.

I tried this, but still no luck;

$('#chat_grab').load('chat_grab.php', callback);

function callback() {
    $('#chat_grab').scrollTop(0);
}

Body:
Try this

 $('html, body').stop().animate({
   scrollTop: $('#chat_grab').offset().top - 100
 }, 800);


问:
obtain a Google OAuth 2.0 Bearer token from a client and secret
I have a client id and client secret for my Google Container Engine app obtained via Credentials and I just want to do some local testing of the JSON API endpoints.

How can I convert this into a Bearer token so that I can just get some work done? Is there a Google page where I provide these things and get a token that I can use in my app?

I don't want to have to write an entire OAuth handling mechanism at this point in time (which would use the flow described in oauthplayground). It's an app to be run only for my account, in headless mode, on a trusted machine, to manage my cluster.

NOTE: must not require any proprietary software installations (e.g. the Google SDK).

答:
Google provides an API Client Library for Java, which itself depends on an OAuth client library.

For the project of 9Cards launcher for Android, within the back-end, we had to use this library to fetch applications usage statistics from Google Analytics. In our code, because it is a case of "server to server" authentication, we use a Service Account's credentials. The code issues a request from Google a short-lived OAuth2 Auth Token. The library may provide similar features if you use a Client-ID and Client-Secret.

Regarding the issue of licenses, the library is published under Apache License v2, so in that regard it is not too proprietary.


问:
Why can we not return a structure to a function?
Why can we not return a structure as a return value? I would also like to print it as well? I want to print the variables of the structure returned.

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

struct distance
{
    int feet;
    float inch;
};

distance add(struct distance d1,struct distance d2);

distance d3;
int main()
{
    struct distance dist1, dist2,dist3;
    printf("first distance\n");
    scanf("%d",&dist1.feet);
    scanf("%f",&dist1.inch);
    printf("second distance\n");
    scanf("%d",&dist2.feet);
    scanf("%f",&dist2.inch);
    dist3 = add(dist1,dist2);
    printf("sum of distances= %d\'-%.1f\"",dist3.feet,dist3.inch);
    return dist3;
}

 distance add(struct distance d1,struct distance d2){
    //Adding distances d1 and d2 and storing it in d3
    d3.feet = d2.feet+d1.feet;
    d3.inch = d2.inch+d1.inch;
    if(d3.inch>12){
        d3.inch-=12;
        ++d3.feet;
    }
}
</code>```

The following error message is displayed
prog.c:7:1: error: unknown type name ‘distance’
 distance add(struct distance d1,struct distance d2);

答:
To address this error message:

prog.c:7:1: error: unknown type name ‘distance’ distance add(struct distance d1,struct distance d2)

you need to realize that there's a difference between the types struct distance and distance.  They are not the same.

Given just:

```<code>struct distance
{
    int feet;
    float inch;
};
</code>```

This is incorrect, as there is no distance type:

```<code>distance add(struct distance d1,struct distance d2);
</code>```

That code assumes distance is a type.  It's not.  The correct type is struct distance:

```<code>struct distance add(struct distance d1,struct distance d2);
</code>```

You can also solve that with a typedef:

```<code>typedef struct distance
{
    int feet;
    float inch;
} distance;
</code>```

Personally, I don't like hiding types that way - I'd rather see something like struct distance and know it's a struct.

Body:
Why can we not return a structure as a return value? I would also like to print it as well? I want to print the variables of the structure returned.

#include <stdio.h>

struct distance
{
    int feet;
    float inch;
};

distance add(struct distance d1,struct distance d2);

distance d3;
int main()
{
    struct distance dist1, dist2,dist3;
    printf("first distance\n");
    scanf("%d",&dist1.feet);
    scanf("%f",&dist1.inch);
    printf("second distance\n");
    scanf("%d",&dist2.feet);
    scanf("%f",&dist2.inch);
    dist3 = add(dist1,dist2);
    printf("sum of distances= %d\'-%.1f\"",dist3.feet,dist3.inch);
    return dist3;
}

 distance add(struct distance d1,struct distance d2){
    //Adding distances d1 and d2 and storing it in d3
    d3.feet = d2.feet+d1.feet;
    d3.inch = d2.inch+d1.inch;
    if(d3.inch>12){
        d3.inch-=12;
        ++d3.feet;
    }
}

The following error message is displayed
prog.c:7:1: error: unknown type name ‘distance’
 distance add(struct distance d1,struct distance d2);

Body:
To address this error message:

prog.c:7:1: error: unknown type name ‘distance’ distance add(struct distance d1,struct distance d2)

you need to realize that there's a difference between the types struct distance and distance.  They are not the same.

Given just:

struct distance
{
    int feet;
    float inch;
};

This is incorrect, as there is no distance type:

distance add(struct distance d1,struct distance d2);

That code assumes distance is a type.  It's not.  The correct type is struct distance:

struct distance add(struct distance d1,struct distance d2);

You can also solve that with a typedef:

typedef struct distance
{
    int feet;
    float inch;
} distance;

Personally, I don't like hiding types that way - I'd rather see something like struct distance and know it's a struct.


问:
Dapper Multimapping complex entity
I want to use dapper to query a complex entity from database.

Ex. Job is top level entity I want to query.

```<code>public class Job
{
    public User User { get; set; }
}
public class Account
{
}

public class Roles
{
    public IList<Schedule> Schedules { get; set; }
}

public class Devices
{
    public IList<Roles> Roles { get; set; }
    public IList<Account> Accounts { get; set; }
}

public class Schedule
{

}
public class User
{
    public IList<Account> Accounts { get; set; }
    public Profile Profile { get; set; }
}
public class Profile
{
    public IList<Account> Accounts { get; set; }
}
</code>```

Is this even possible with dapper, if it is then is it worth using dapper for this or should I use some other ORM (EF, LLBLGen, NH)?

答:
I believe you are asking how to implement MultiMapping in Dapper.

You can pass more than one model like so:

```<code>var sql = @"select * from Product p
            inner join Customer c on p.CustomerId = c.CustomerId
            order by p.ProductName";

var item = connection.Query<ProductItem, Customer, ProductItem>(sql,
        (p, c) => { p.Customer = c; return p; }, splitOn: "CustomerId").First();
</code>```

Reference: Correct use of Multimapping in Dapper

Title: Dapper Multimapping complex entity

Body:
I want to use dapper to query a complex entity from database.

Ex. Job is top level entity I want to query.

public class Job
{
    public User User { get; set; }
}
public class Account
{
}

public class Roles
{
    public IList<Schedule> Schedules { get; set; }
}

public class Devices
{
    public IList<Roles> Roles { get; set; }
    public IList<Account> Accounts { get; set; }
}

public class Schedule
{

}
public class User
{
    public IList<Account> Accounts { get; set; }
    public Profile Profile { get; set; }
}
public class Profile
{
    public IList<Account> Accounts { get; set; }
}

Is this even possible with dapper, if it is then is it worth using dapper for this or should I use some other ORM (EF, LLBLGen, NH)?

Body:
I believe you are asking how to implement MultiMapping in Dapper.

You can pass more than one model like so:

var sql = @"select * from Product p
            inner join Customer c on p.CustomerId = c.CustomerId
            order by p.ProductName";

var item = connection.Query<ProductItem, Customer, ProductItem>(sql,
        (p, c) => { p.Customer = c; return p; }, splitOn: "CustomerId").First();

Reference: Correct use of Multimapping in Dapper


问:
Relatively modify a property's value
I would like to decrease a certain margin's size by 25% in certain cases. I could do this by looking at it's base value and manually entering 75% of the value. However, the margin's base size varies according to client screen resolution.

Therefore I would like to decrease the already defined margin value by 25%.
If one were to be doing an analogous thing in Python programming, the equivalent would thus be:

```<code>margin = some_base_value
...
margin = 0.75*margin
</code>```

Can I do this in CSS, and if so, how?

答:
I recommend you to use Sass or LESS ,
so you can use variables.

Example: (Sass (SCSS))

```<code>$margin: 10px;

#element {
    margin: $margin*.75;
}
</code>```

.. if you don't want to use any css preprocessor, you can use css variables with calc function.

Title: Relatively modify a property's value

Body:
I would like to decrease a certain margin's size by 25% in certain cases. I could do this by looking at it's base value and manually entering 75% of the value. However, the margin's base size varies according to client screen resolution.

Therefore I would like to decrease the already defined margin value by 25%.
If one were to be doing an analogous thing in Python programming, the equivalent would thus be:

margin = some_base_value
...
margin = 0.75*margin

Can I do this in CSS, and if so, how?

Body:
I recommend you to use Sass or LESS ,
so you can use variables.

Example: (Sass (SCSS))

$margin: 10px;

#element {
    margin: $margin*.75;
}

.. if you don't want to use any css preprocessor, you can use css variables with calc function.


问:
Loop for variable value,
I have a variable generated by $_POST called $quantity,

What would be the correct way to run a loop based on the value of this variable?

答:
Well, assuming that $quantity is numerical, you can do this:

```<code>for ($c = 0; $c < $quantity; $c++) {
  //do whatever
}
</code>```

Title: Loop for variable value,

Body:
Well, assuming that $quantity is numerical, you can do this:

for ($c = 0; $c < $quantity; $c++) {
  //do whatever
}


问:
How to make a button expand the length of an html table header?
I am trying to get a button that I put in a table  to expand the full width and height of the header column, even when a table cell in the same column is larger than the text. If I do, width 100% in css, then the button will just match the cell size, and then the title will extend beyond the button and header.

I am using the button so when the user click on it the column will sort.

This is my code just trying to do with width:

```<code><th><button onclick="tableColumnSort(this)" style="width:100%">@descriptor.Name</button></th>
</code>```

And this is how it looks without using width:

```<code><th><button onclick="tableColumnSort(this)">@descriptor.Name</button></th>
</code>```

答:
If you set an element to width: 100% or height: 100%, it's relative to its parent element. So, if you're setting your button width: 100%, and you want it to be 100% of your header width, set a width (that's not in percentage) on the header and it'll respect it. Like this:

HTML:

```<code><table>
  <thead>
    <tr>
      <th>
        <button>shortHeader</button>
      </th>
      <th>
        <button>veryLongLongHeader</button>
      </th>
      <th>
        <button>header</button>
      </th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td> </td>
      <td> </td>
      <td> </td>
    </tr>
  </tbody>
</table><table>
  <thead>
    <tr>
      <th>
        <button>shortHeader</button>
      </th>
      <th>
        <button>veryLongLongHeader</button>
      </th>
      <th>
        <button>header</button>
      </th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td> </td>
      <td> </td>
      <td> </td>
    </tr>
  </tbody>
</table>
</code>```

CSS:

```<code>button {
  width: 100%;
}

th {
  width: 100px;
}

table, th, td {
  border: 1px solid #000;
}
</code>```

Check out this fiddle.

Body:
I am trying to get a button that I put in a table  to expand the full width and height of the header column, even when a table cell in the same column is larger than the text. If I do, width 100% in css, then the button will just match the cell size, and then the title will extend beyond the button and header.

I am using the button so when the user click on it the column will sort.

This is my code just trying to do with width:

<button onclick="tableColumnSort(this)" style="width:100%">@descriptor.Name</button>

And this is how it looks without using width:

<button onclick="tableColumnSort(this)">@descriptor.Name</button>

Body:
If you set an element to width: 100% or height: 100%, it's relative to its parent element. So, if you're setting your button width: 100%, and you want it to be 100% of your header width, set a width (that's not in percentage) on the header and it'll respect it. Like this:

HTML:

<table>
  <thead>
    <tr>
      <th>
        <button>shortHeader</button>
      </th>
      <th>
        <button>veryLongLongHeader</button>
      </th>
      <th>
        <button>header</button>
      </th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>&nbsp;</td>
      <td>&nbsp;</td>
      <td>&nbsp;</td>
    </tr>
  </tbody>
</table><table>
  <thead>
    <tr>
      <th>
        <button>shortHeader</button>
      </th>
      <th>
        <button>veryLongLongHeader</button>
      </th>
      <th>
        <button>header</button>
      </th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>&nbsp;</td>
      <td>&nbsp;</td>
      <td>&nbsp;</td>
    </tr>
  </tbody>
</table>

CSS:

button {
  width: 100%;
}

th {
  width: 100px;
}

table, th, td {
  border: 1px solid #000;
}

Check out this fiddle.


问:
how to put sql data into an html table
I am trying to put my SQL data into an HTML data, this is the code I have so far but it does not work yet. I have tried to put HTML into my PHP code I am wondering whether I should do it the the other way round(put PHP into HTML), any reply greatly appreciated</p>

```<code>  while ($rowObj = $queryResult->fetch_object()) {
echo "<tr>";
echo"<td>" . $AE_events ['eventTitle'] . "</td>;
echo"<td>" . $AE_events ['eventDescription'] . "</td>;
echo"<td;>" . $AE_events ['eventStartDate'] . "</td>;
echo"<td>" . $AE_events ['eventEndDate'] . "</td>;
echo"<td>" . $AE_events ['eventPrice'] . "</td>;

    $AE_eventTitle = $rowObj->eventTitle;
    $AE_eventDescription = $rowObj->eventDescription;
    $AE_eventStartDate = $rowObj->eventStartDate;
    $AE_eventEndDate = $rowObj->eventEndDate;
    $AE_eventPrice = $rowObj->eventPrice;
    echo "<div>  $AE_eventTitle<br> $AE_eventDescription<br>
$AE_eventStartDate<br>
$AE_eventEndDate<br> $AE_eventPrice<br> </div>";

}
</code>```

答:
If you want to draw a table out of data in PHP, you can have to use nested loops. The first loop manages the rows and the nested one manages the columns. Example :

```<code>$data = [
    [1, 3, 5],
    [2, 4, 6]
];
print "<table>";
for ($i = 0; $i < count($data); $i++) {
    $row = $data[$i];
    print "<tr>";
    for ($k = 0; $k < count($row); $k++) {
        print "<td>{$row[$k]}</td>";
    }
    print "</tr>";
}
print "</table>";
</code>```

Outputs:

```<code><table>
    <tr>
        <td>1</td>
        <td>3</td>
        <td>5</td>
    </tr>
    <tr>
        <td>2</td>
        <td>4</td>
        <td>6</td>
    </tr>
</table>
</code>```

Title: how to put sql data into an html table

Body:
I am trying to put my SQL data into an HTML data, this is the code I have so far but it does not work yet. I have tried to put HTML into my PHP code I am wondering whether I should do it the the other way round(put PHP into HTML), any reply greatly appreciated

  while ($rowObj = $queryResult->fetch_object()) {
echo "
";
echo"" . $AE_events ['eventTitle'] . "	;
echo"" . $AE_events ['eventDescription'] . "	;
echo"" . $AE_events ['eventStartDate'] . "	;
echo"" . $AE_events ['eventEndDate'] . "	;
echo"" . $AE_events ['eventPrice'] . "	;

    $AE_eventTitle = $rowObj->eventTitle;
    $AE_eventDescription = $rowObj->eventDescription;
    $AE_eventStartDate = $rowObj->eventStartDate;
    $AE_eventEndDate = $rowObj->eventEndDate;
    $AE_eventPrice = $rowObj->eventPrice;
    echo "
  $AE_eventTitle
 $AE_eventDescription

$AE_eventStartDate

$AE_eventEndDate
 $AE_eventPrice

";

}

Body:
If you want to draw a table out of data in PHP, you can have to use nested loops. The first loop manages the rows and the nested one manages the columns. Example :

$data = [
    [1, 3, 5],
    [2, 4, 6]
];
print "<table>";
for ($i = 0; $i < count($data); $i++) {
    $row = $data[$i];
    print "<tr>";
    for ($k = 0; $k < count($row); $k++) {
        print "<td>{$row[$k]}</td>";
    }
    print "</tr>";
}
print "</table>";

Outputs:

<table>
    <tr>
        <td>1</td>
        <td>3</td>
        <td>5</td>
    </tr>
    <tr>
        <td>2</td>
        <td>4</td>
        <td>6</td>
    </tr>
</table>


问:
Code to run that can help benchmark a new SAS drive?
We just got a new Server at work that will be used only for running SAS code, and I've been asked to run some tests and make sure that it's performing better than our other servers. I'm not an expert at this so I want to make sure I avoid making naive mistakes that don't properly measure the performance of the server. My header looks like this:

```<code>options fullstimer;
%LET BenchStartTime =  %sysfunc(datetime(),22.);
</code>```

Which I use as a check for the "real time" report in the log. I have a vague understanding of the difference between "user cpu time" and "system cpu time", but if anyone wants to offer up additional information on that, that would be helpful.

Anyway, the main point of this post is that I want to know if there are any standard benchmark tests that I should be using in order to see if this new server is better than the old ones. Currently I'm using something I found online which is just appending a bunch of copies of sashelp.class (but I think this might be a bad idea because pulling from the C: and loading it into a different drive might be the same across all servers, right? If the C: is the slowest drive, doesn't that become the bottleneck?), and I'm also using code that basically generates a bunch of random data of a fixed size and comparing runtimes. Is this the correct approach? Is there something else I should be doing? How many times should I be running these benchmark tests to make sure that it isn't a fluke?

Thanks for your help!

答:
I would test by doing the things that you normally do.  If you run larger merges, then you're basically talking I/O; so just make a very large dataset, write it out, read it in, etc., and perform the same test on the other machine.  Perform each test a few times each in a fresh SAS session.

Further, it sounds like you need to make sure the new server can handle multiple concurrent sessions.  You can simulate this in part by submitting many connections from one computer by using SAS/CONNECT; that allows you to start multiple concurrent sessions.  Then do so, perhaps I would create a script that starts a local SAS session, signs on to the server and rsubmits a job of a normal difficulty that takes maybe 5 to 10 minutes, and then run that script 20 times concurrently (you can script this or just double click a .bat file 20 times).  See how it handles it as compared to the other server.

Body:
We just got a new Server at work that will be used only for running SAS code, and I've been asked to run some tests and make sure that it's performing better than our other servers. I'm not an expert at this so I want to make sure I avoid making naive mistakes that don't properly measure the performance of the server. My header looks like this:

options fullstimer;
%LET BenchStartTime =  %sysfunc(datetime(),22.);

Which I use as a check for the "real time" report in the log. I have a vague understanding of the difference between "user cpu time" and "system cpu time", but if anyone wants to offer up additional information on that, that would be helpful.

Anyway, the main point of this post is that I want to know if there are any standard benchmark tests that I should be using in order to see if this new server is better than the old ones. Currently I'm using something I found online which is just appending a bunch of copies of sashelp.class (but I think this might be a bad idea because pulling from the C: and loading it into a different drive might be the same across all servers, right? If the C: is the slowest drive, doesn't that become the bottleneck?), and I'm also using code that basically generates a bunch of random data of a fixed size and comparing runtimes. Is this the correct approach? Is there something else I should be doing? How many times should I be running these benchmark tests to make sure that it isn't a fluke?

Thanks for your help!