问:
More efficient algorithm to find OR of two sets
Given a matrix of n rows and m columns of 1's and 0's, it is required to find out the number of pairs of rows that can be selected so that their OR is 11111....m times.

Example:

```<code>1 0 1 0 1
0 1 0 0 1
1 1 1 1 0
</code>```

Answer:

```<code>2 ---> OR of row number [1,3] and [2,3]
</code>```

Given n and m can be an order upto <= 3000, how efficiently can this problem be solved?

PS: I already tried with a naive O(n*n*m) method. I was thinking of a better solution.

答:
If I'm not mistaken, the following should be O(n*m):

For each column, compute the set of indices of rows that have a "1" at this column, and store this as a mapping from the column index to the set of row indices

For each row, compute the set of row indices that could "complete" the row (by adding "1"s in the columns where the row has a "0"). This can be done by computing the intersection of the sets that have been computed in step 1 for the respective column

Count the completing row indices

For your example:

```<code>1 0 1 0 1
0 1 0 0 1
1 1 1 1 0
</code>```

The indices of the rows that have a "1" at each column are

Column 0: [0, 2]

Column 1: [1, 2]

Column 2: [0, 2]

Column 3: [2]

Column 4: [0, 1]

The unions of all sets of indices that are used for "filling" each row are

Row 0: [2]

Row 1: [2]

Row 2: []

Which is 2 in total.

The main reason of why one could argue about the running time is that the computation of the intersections of m sets with a size of at most n could be considered to be O(m*n), but I think that the sizes of these sets will be limited: The entries are either are 1's or 0's, and when there are many 1s (and the sizes are large), then there are fewer sets to intersect, and vice versa - but I didn't do a rigorous proof here...

A Java-based implementation that I used for playing around with this (and for some basic "tests") :

```<code>import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;

public class SetOrCombinations
{
    public static void main(String[] args)
    {
        List<Integer> row0 = Arrays.asList(1, 0, 1, 0, 1);
        List<Integer> row1 = Arrays.asList(1, 1, 0, 0, 1);
        List<Integer> row2 = Arrays.asList(1, 1, 1, 1, 0);
        List<Integer> row3 = Arrays.asList(0, 0, 1, 1, 1);
        List<List<Integer>> rows = Arrays.asList(row0, row1, row2, row3);
        run(rows);

        for (int m = 2; m < 10; m++)
        {
            for (int n = 2; n < 10; n++)
            {
                run(generateRandomInput(m, n));
            }
        }
    }

    private static void run(List<List<Integer>> rows)
    {
        int m = rows.get(0).size();
        int n = rows.size();

        // For each column i:
        // Compute the set of rows that "fill" this column with a "1"
        Map<Integer, List<Integer>> fillers =
            new LinkedHashMap<Integer, List<Integer>>();
        for (int i = 0; i < m; i++)
        {
            for (int j = 0; j < n; j++)
            {
                List<Integer> row = rows.get(j);
                List<Integer> list =
                    fillers.computeIfAbsent(i, k -> new ArrayList<Integer>());
                if (row.get(i) == 1)
                {
                    list.add(j);
                }
            }
        }

        // For each row, compute the set of rows that could "complete"
        // the row (by adding "1"s in the columns where the row has
        // a "0").
        int count = 0;
        Set<Integer> processedRows = new LinkedHashSet<Integer>();
        for (int j = 0; j < n; j++)
        {
            processedRows.add(j);
            List<Integer> row = rows.get(j);
            Set<Integer> completers = new LinkedHashSet<Integer>();
            for (int i = 0; i < n; i++)
            {
                completers.add(i);
            }
            for (int i = 0; i < m; i++)
            {
                if (row.get(i) == 0)
                {
                    completers.retainAll(fillers.get(i));
                }
            }
            completers.removeAll(processedRows);
            count += completers.size();
        }

        System.out.println("Count "+count);
        System.out.println("Ref.  "+bruteForceCount(rows));
    }

    // Brute force
    private static int bruteForceCount(List<List<Integer>> lists)
    {
        int count = 0;
        int n = lists.size();
        for (int i = 0; i < n; i++)
        {
            for (int j = i + 1; j < n; j++)
            {
                List<Integer> list0 = lists.get(i);
                List<Integer> list1 = lists.get(j);
                if (areOne(list0, list1))
                {
                    count++;
                }
            }
        }
        return count;
    }

    private static boolean areOne(List<Integer> list0, List<Integer> list1)
    {
        int n = list0.size();
        for (int i=0; i<n; i++)
        {
            int v0 = list0.get(i);
            int v1 = list1.get(i);
            if (v0 == 0 && v1 == 0)
            {
                return false;
            }
        }
        return true;
    }

    // For testing
    private static Random random = new Random(0);
    private static List<List<Integer>> generateRandomInput(int m, int n)
    {
        List<List<Integer>> rows = new ArrayList<List<Integer>>();
        for (int i=0; i<n; i++)
        {
            List<Integer> row = new ArrayList<Integer>();
            for (int j=0; j<m; j++)
            {
                row.add(random.nextInt(2));
            }
            rows.add(row);
        }
        return rows;
    }

}
</code>```

Body:
Given a matrix of n rows and m columns of 1's and 0's, it is required to find out the number of pairs of rows that can be selected so that their OR is 11111....m times.

Example:

1 0 1 0 1
0 1 0 0 1
1 1 1 1 0

Answer:

2 ---> OR of row number [1,3] and [2,3]

Given n and m can be an order upto <= 3000, how efficiently can this problem be solved?

PS: I already tried with a naive O(n*n*m) method. I was thinking of a better solution.

Body:
If I'm not mistaken, the following should be O(n*m):

For each column, compute the set of indices of rows that have a "1" at this column, and store this as a mapping from the column index to the set of row indices

For each row, compute the set of row indices that could "complete" the row (by adding "1"s in the columns where the row has a "0"). This can be done by computing the intersection of the sets that have been computed in step 1 for the respective column

Count the completing row indices

For your example:

1 0 1 0 1
0 1 0 0 1
1 1 1 1 0

The indices of the rows that have a "1" at each column are

Column 0: [0, 2]

Column 1: [1, 2]

Column 2: [0, 2]

Column 3: [2]

Column 4: [0, 1]

The unions of all sets of indices that are used for "filling" each row are

Row 0: [2]

Row 1: [2]

Row 2: []

Which is 2 in total.

The main reason of why one could argue about the running time is that the computation of the intersections of m sets with a size of at most n could be considered to be O(m*n), but I think that the sizes of these sets will be limited: The entries are either are 1's or 0's, and when there are many 1s (and the sizes are large), then there are fewer sets to intersect, and vice versa - but I didn't do a rigorous proof here...

A Java-based implementation that I used for playing around with this (and for some basic "tests") :

import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;

public class SetOrCombinations
{
    public static void main(String[] args)
    {
        List<Integer> row0 = Arrays.asList(1, 0, 1, 0, 1);
        List<Integer> row1 = Arrays.asList(1, 1, 0, 0, 1);
        List<Integer> row2 = Arrays.asList(1, 1, 1, 1, 0);
        List<Integer> row3 = Arrays.asList(0, 0, 1, 1, 1);
        List<List<Integer>> rows = Arrays.asList(row0, row1, row2, row3);
        run(rows);

        for (int m = 2; m < 10; m++)
        {
            for (int n = 2; n < 10; n++)
            {
                run(generateRandomInput(m, n));
            }
        }
    }

    private static void run(List<List<Integer>> rows)
    {
        int m = rows.get(0).size();
        int n = rows.size();

        // For each column i:
        // Compute the set of rows that "fill" this column with a "1"
        Map<Integer, List<Integer>> fillers =
            new LinkedHashMap<Integer, List<Integer>>();
        for (int i = 0; i < m; i++)
        {
            for (int j = 0; j < n; j++)
            {
                List<Integer> row = rows.get(j);
                List<Integer> list =
                    fillers.computeIfAbsent(i, k -> new ArrayList<Integer>());
                if (row.get(i) == 1)
                {
                    list.add(j);
                }
            }
        }

        // For each row, compute the set of rows that could "complete"
        // the row (by adding "1"s in the columns where the row has
        // a "0").
        int count = 0;
        Set<Integer> processedRows = new LinkedHashSet<Integer>();
        for (int j = 0; j < n; j++)
        {
            processedRows.add(j);
            List<Integer> row = rows.get(j);
            Set<Integer> completers = new LinkedHashSet<Integer>();
            for (int i = 0; i < n; i++)
            {
                completers.add(i);
            }
            for (int i = 0; i < m; i++)
            {
                if (row.get(i) == 0)
                {
                    completers.retainAll(fillers.get(i));
                }
            }
            completers.removeAll(processedRows);
            count += completers.size();
        }

        System.out.println("Count "+count);
        System.out.println("Ref.  "+bruteForceCount(rows));
    }

    // Brute force
    private static int bruteForceCount(List<List<Integer>> lists)
    {
        int count = 0;
        int n = lists.size();
        for (int i = 0; i < n; i++)
        {
            for (int j = i + 1; j < n; j++)
            {
                List<Integer> list0 = lists.get(i);
                List<Integer> list1 = lists.get(j);
                if (areOne(list0, list1))
                {
                    count++;
                }
            }
        }
        return count;
    }

    private static boolean areOne(List<Integer> list0, List<Integer> list1)
    {
        int n = list0.size();
        for (int i=0; i<n; i++)
        {
            int v0 = list0.get(i);
            int v1 = list1.get(i);
            if (v0 == 0 && v1 == 0)
            {
                return false;
            }
        }
        return true;
    }

    // For testing
    private static Random random = new Random(0);
    private static List<List<Integer>> generateRandomInput(int m, int n)
    {
        List<List<Integer>> rows = new ArrayList<List<Integer>>();
        for (int i=0; i<n; i++)
        {
            List<Integer> row = new ArrayList<Integer>();
            for (int j=0; j<m; j++)
            {
                row.add(random.nextInt(2));
            }
            rows.add(row);
        }
        return rows;
    }

}


来源: stackexchange

问:
how to deal with the war name when deploy eureka client in tomcat
when we deploy a eureka client web server in tomcat,it's path may be hostname:port/project_name/**

but when route by zuul with eureka service-id , zuul always ignore the project_name

and how can I config this this project_name in eureka client or zuul?

答:
In zuul configuration, you can preserve the prefix in url with stripPrefix option. Its default value is true, namely it will remove your project_name in url. If you change stripPrefix to false like below example, your eureka client will receive the full url that was passed to zuul server.

```<code>zuul:
  routes:
    service-a:
      path: /service-a/**
      stripPrefix: false
</code>```

ContentLicense: CC BY-SA 3.0

Body:
In zuul configuration, you can preserve the prefix in url with stripPrefix option. Its default value is true, namely it will remove your project_name in url. If you change stripPrefix to false like below example, your eureka client will receive the full url that was passed to zuul server.

zuul:
  routes:
    service-a:
      path: /service-a/**
      stripPrefix: false


问:
Click: Is it possible to pass multiple inputs to CliRunner.invoke?
I have a click command called download which prompts the user for a username and password before downloading a series of files:

```<code>$ python download.py
Username: jkarimi91
Password: 1234
Download complete!
</code>```

To test this command, I need to be able to pass both a username and a password, separately, to stdin. The CliRunner.invoke() method has an input argument but it does not accept lists. Is it possible to pass multiple inputs to CliRunner.invoke()?

答:
You can pass multiple inputs by passing string joined by newline (\n):

```<code>import click
from click.testing import CliRunner

def test_prompts():
    @click.command()
    @click.option('--username', prompt=True)
    @click.option('--password', prompt=True)
    def test(username, password):
        # download ..
        click.echo('Download complete!')

    # OR
    #
    # @click.command()
    # def test():
    #     username = click.prompt('Username')
    #     password = click.prompt('Password', hide_input=True)
    #     # download ..
    #     click.echo('Download complete!')

    runner = CliRunner()
    result = runner.invoke(test, input='username\npassword\n') # <---
    assert not result.exception
    assert result.output.endswith('Download complete!\n')

if __name__ == '__main__':
    test_prompts()
</code>```

Body:
I have a click command called download which prompts the user for a username and password before downloading a series of files:

$ python download.py
Username: jkarimi91
Password: 1234
Download complete!

To test this command, I need to be able to pass both a username and a password, separately, to stdin. The CliRunner.invoke() method has an input argument but it does not accept lists. Is it possible to pass multiple inputs to CliRunner.invoke()?

Body:
You can pass multiple inputs by passing string joined by newline (\n):

import click
from click.testing import CliRunner

def test_prompts():
    @click.command()
    @click.option('--username', prompt=True)
    @click.option('--password', prompt=True)
    def test(username, password):
        # download ..
        click.echo('Download complete!')

    # OR
    #
    # @click.command()
    # def test():
    #     username = click.prompt('Username')
    #     password = click.prompt('Password', hide_input=True)
    #     # download ..
    #     click.echo('Download complete!')

    runner = CliRunner()
    result = runner.invoke(test, input='username\npassword\n') # <---
    assert not result.exception
    assert result.output.endswith('Download complete!\n')

if __name__ == '__main__':
    test_prompts()


问:
Admin form with "extra" fields
I have a form for an object called AccountImport. This form lives in an admin-generated module. In addition to the fields that map directly to this object's attributes, I need a couple extra fields.

If I just add the fields to the AccountImport form, it won't save correctly because the form will no longer match the AccountImport object.

If I create a template manually and splice the extra fields in that way, I'm throwing away all the stuff the admin generator gives me for free (i.e. formatting, "Back to list" button, save buttons).

What's a "good" way to do what I'm trying to do?

答:
If you define additional fields in generator.yml, you can override one of the admin generator actions to handle the fields however you want.

Look at the generated actions.class.php in cache/YOURAPP/YOURENV/modules/autoYOURMODULE/actions/actions.class.php .  You can override any of those functions with your own in apps/YOURAPP/modules/YOURMODULE/actions/actions.class.php, because it inherits from that cached file.  When you make changes to generator.conf, the cached file is updated but your code will still override it.  You probably want to override processForm().

I have an example of this in step 5 at this blog post:

```<code>protected function processForm(sfWebRequest $request, sfForm $form)
{
  $form->bind($request->getParameter($form->getName()), $request->getFiles($form->getName()));

  if ($form->isValid())
  {
$notice = $form->getObject()->isNew() ? 'The item was created successfully.' : 'The item was updated successfully.';

// NEW: deal with tags
if ($form->getValue('remove_tags')) {
  foreach (preg_split('/\s*,\s*/', $form->getValue('remove_tags')) as $tag) {
    $form->getObject()->removeTag($tag);
  }
}
if ($form->getValue('new_tags')) {
  foreach (preg_split('/\s*,\s*/', $form->getValue('new_tags')) as $tag) {
    // sorry, it would be better to not hard-code this string
    if ($tag == 'Add tags with commas') continue;
    $form->getObject()->addTag($tag);
  }
}

try {
  $complaint = $form->save();
  // and the remainder is just pasted from the generated actions file
</code>```

When I realized I could read the generated files in the cache to see exactly what the admin generator was doing, and that I could override any part of them, it made me a lot more productive with the admin generator.

ContentLicense: CC BY-SA 2.5

Title: Admin form with "extra" fields

Body:
If you define additional fields in generator.yml, you can override one of the admin generator actions to handle the fields however you want.

Look at the generated actions.class.php in cache/YOURAPP/YOURENV/modules/autoYOURMODULE/actions/actions.class.php .  You can override any of those functions with your own in apps/YOURAPP/modules/YOURMODULE/actions/actions.class.php, because it inherits from that cached file.  When you make changes to generator.conf, the cached file is updated but your code will still override it.  You probably want to override processForm().

I have an example of this in step 5 at this blog post:

protected function processForm(sfWebRequest $request, sfForm $form)
{
  $form->bind($request->getParameter($form->getName()), $request->getFiles($form->getName()));

  if ($form->isValid())
  {
$notice = $form->getObject()->isNew() ? 'The item was created successfully.' : 'The item was updated successfully.';

// NEW: deal with tags
if ($form->getValue('remove_tags')) {
  foreach (preg_split('/\s*,\s*/', $form->getValue('remove_tags')) as $tag) {
    $form->getObject()->removeTag($tag);
  }
}
if ($form->getValue('new_tags')) {
  foreach (preg_split('/\s*,\s*/', $form->getValue('new_tags')) as $tag) {
    // sorry, it would be better to not hard-code this string
    if ($tag == 'Add tags with commas') continue;
    $form->getObject()->addTag($tag);
  }
}

try {
  $complaint = $form->save();
  // and the remainder is just pasted from the generated actions file

When I realized I could read the generated files in the cache to see exactly what the admin generator was doing, and that I could override any part of them, it made me a lot more productive with the admin generator.


问:
Laravel 5.4: Storing the 'Where' clause in a variable
I want to write a dynamic update query in Laravel which accepts arguments and can be used in whole project.

Following is my Controller function:

```<code>public function editquery(Request $request)
    {

    $city_id   = $request->input('city_id');
    $city_name = $request->input('city_name');

    $tbl  = 'city';
    $data = ['city_name'=>$city_name];
    $wher = ('city_id',1);

    General_model::editrecord($data,$wher,$tbl);

    return redirect()->action('Admin_controller@cities_page')->with('status','Record Updated Successfully!');;

    }
</code>```

Below is my Model function:

```<code>public static function editrecord($data,$wher,$tbl)
    {
      return DB::table($tbl)->where($wher)->update($data);
    }
</code>```

The only problem here is that I cannot store the value ('city_id',1) in the $wher variable. This is the screenshot of the error:
link to the image file

Is there any other way to do this. Please Help.

答:
Your code is not exactly in the style of Laravel, why would you want to create a separate static function, if such tasks are easily solved by the standard features of Eloquent / Query Builder?

Eloquent example:

app/City.php

```<code><?php
class City extends Model {
    protected $table = 'city';
    protected $primaryKey = 'city_id';
    protected $fillable = ['city_name'];
}
</code>```

In your controller:

```<code>City::findOrFail($city_id)->update([
    'city_name' => $city_name
]);
</code>```

Query Builder example:

```<code>DB::table('city')->where(['city_id' => $city_id])->update([
    'city_name' => $city_name
]);
</code>```

This is much easier to read, understand and support than functions that do similar things in an incomprehensible way.

Body:
I want to write a dynamic update query in Laravel which accepts arguments and can be used in whole project.

Following is my Controller function:

public function editquery(Request $request)
    {

    $city_id   = $request->input('city_id');
    $city_name = $request->input('city_name');

    $tbl  = 'city';
    $data = ['city_name'=>$city_name];
    $wher = ('city_id',1);

    General_model::editrecord($data,$wher,$tbl);

    return redirect()->action('Admin_controller@cities_page')->with('status','Record Updated Successfully!');;

    }

Below is my Model function:

public static function editrecord($data,$wher,$tbl)
    {
      return DB::table($tbl)->where($wher)->update($data);
    }

The only problem here is that I cannot store the value ('city_id',1) in the $wher variable. This is the screenshot of the error:
link to the image file

Is there any other way to do this. Please Help.

Body:
Your code is not exactly in the style of Laravel, why would you want to create a separate static function, if such tasks are easily solved by the standard features of Eloquent / Query Builder?

Eloquent example:

app/City.php

<?php
class City extends Model {
    protected $table = 'city';
    protected $primaryKey = 'city_id';
    protected $fillable = ['city_name'];
}

In your controller:

City::findOrFail($city_id)->update([
    'city_name' => $city_name
]);

Query Builder example:

DB::table('city')->where(['city_id' => $city_id])->update([
    'city_name' => $city_name
]);

This is much easier to read, understand and support than functions that do similar things in an incomprehensible way.


问:
RDTSC equivalent for iOS
I'm looking to do high-precision timing in an iOS app. On an Intel x86 chip, I'd use RDTSC to get timestamps, but I can't do that on an ARM device. Is there an equivalent of RDTSC that can be used from an iOS app?</p>

答:
For high-precision timing, perhaps you could use mach_absolute_time()

Technical Q&A QA1398 Mach Absolute Time Units

Title: RDTSC equivalent for iOS


问:
How to fix 500.1002 error in Azure?
We have 500.1001 or 500.1002 errors after success building our app. We tried to bundle our app to root and to public - error 500. We tried to correct iisnode.yml parameters (maxNamedPipeConnectionRetry and namedPipeConnectionRetryDelay). Our app always on in server.

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

```<code><webSocket enabled="false" />

<handlers>
  <add name="iisnode" path="/public/server.bundle.js" verb="*" modules="iisnode"/>
</handlers>

<rewrite>
  <rules>
    <rule name="NodeInspector" patternSyntax="ECMAScript" stopProcessing="true">
      <match url="^server.bundle.js\/debug[\/]?" />
    </rule>

    <rule name="StaticContent">
      <action type="Rewrite" url="public{REQUEST_URI}"/>
    </rule>

    <rule name="DynamicContent">
      <conditions>
        <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="True"/>
      </conditions>
      <action type="Rewrite" url="/public/server.bundle.js"/>
    </rule>
  </rules>
</rewrite>

<security>
  <requestFiltering>
    <hiddenSegments>
      <remove segment="bin"/>
    </hiddenSegments>
  </requestFiltering>
</security>

<httpErrors existingResponse="PassThrough" />
</code>```

答: We found the solution. Just migrated to VM with Linux.</p>

Title: How to fix 500.1002 error in Azure?

Body:
We have 500.1001 or 500.1002 errors after success building our app. We tried to bundle our app to root and to public - error 500. We tried to correct iisnode.yml parameters (maxNamedPipeConnectionRetry and namedPipeConnectionRetryDelay). Our app always on in server.

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

<webSocket enabled="false" />

<handlers>
  <add name="iisnode" path="/public/server.bundle.js" verb="*" modules="iisnode"/>
</handlers>

<rewrite>
  <rules>
    <rule name="NodeInspector" patternSyntax="ECMAScript" stopProcessing="true">
      <match url="^server.bundle.js\/debug[\/]?" />
    </rule>

    <rule name="StaticContent">
      <action type="Rewrite" url="public{REQUEST_URI}"/>
    </rule>

    <rule name="DynamicContent">
      <conditions>
        <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="True"/>
      </conditions>
      <action type="Rewrite" url="/public/server.bundle.js"/>
    </rule>
  </rules>
</rewrite>

<security>
  <requestFiltering>
    <hiddenSegments>
      <remove segment="bin"/>
    </hiddenSegments>
  </requestFiltering>
</security>

<httpErrors existingResponse="PassThrough" />


问:
Bootstrap tooltips in eex templates
I have a bootstrap tooltip. A test link works OK here:

```<code><a data-tooltip="I am tooltip text" data-placement="left">Clickame</a>
</code>```

I have an eex link:

```<code> <span><%= link "  ", to: post_path(@conn, :show, post), class: "btn btn-default btn-md btn-read-post unicode-lg" %></span>
</code>```

I tried to wrap anchor tags around the link:

```<code>    <a data-tooltip="edit" data-placement="left"><span><%= link "    ", to: post_path(@conn, :show, post), class: "btn btn-default btn-md btn-read-post unicode-lg" %></span></a>
</code>```

... didn't work.

There are some ideas in this Ruby on Rails tooltip question:

Using Tooltips with link_to (Ruby on Rails 3.2.3)

rel: "data-tooltip" does not raise an error:

```<code><span><%= link "  ", to: post_path(@conn, :show, post), class: "btn btn-default btn-md btn-read-post unicode-lg", rel: "data-tooltip" %></span>
</code>```

but how do I add the data-placement="left" class?

Full tooltip here:

https://codepen.io/peiche/pen/JaftA

```<code>a[data-tooltip] {
  position: relative;
}

a[data-tooltip]::before,
a[data-tooltip]::after {
  position: absolute;
  display: none;
  opacity: 0.85;
}
</code>```

答:
The correct tooltip syntax for the link, including classes, would be:

```<code><%= link("   ", to: post_path(@conn, :show, post), "data-tooltip": "I am tooltip text", "data-placement": "left", class: "btn btn-default btn-md btn-read-post unicode-lg") %>
</code>```

original:

```<code><span><%= link "  ", to: post_path(@conn, :show, post), class: "btn btn-default btn-md btn-read-post unicode-lg" %></span>
</code>```

Title: Bootstrap tooltips in eex templates

Body:
I have a bootstrap tooltip. A test link works OK here:

Clickame

I have an eex link:

 <%= link "  ", to: post_path(@conn, :show, post), class: "btn btn-default btn-md btn-read-post unicode-lg" %>

I tried to wrap anchor tags around the link:

    <%= link "    ", to: post_path(@conn, :show, post), class: "btn btn-default btn-md btn-read-post unicode-lg" %>

... didn't work.

There are some ideas in this Ruby on Rails tooltip question:

Using Tooltips with link_to (Ruby on Rails 3.2.3)

rel: "data-tooltip" does not raise an error:

<%= link "  ", to: post_path(@conn, :show, post), class: "btn btn-default btn-md btn-read-post unicode-lg", rel: "data-tooltip" %>

but how do I add the data-placement="left" class?

Full tooltip here:

https://codepen.io/peiche/pen/JaftA

a[data-tooltip] {
  position: relative;
}

a[data-tooltip]::before,
a[data-tooltip]::after {
  position: absolute;
  display: none;
  opacity: 0.85;
}

Body:
The correct tooltip syntax for the link, including classes, would be:

<%= link("   ", to: post_path(@conn, :show, post), "data-tooltip": "I am tooltip text", "data-placement": "left", class: "btn btn-default btn-md btn-read-post unicode-lg") %>

original:

<span><%= link "  ", to: post_path(@conn, :show, post), class: "btn btn-default btn-md btn-read-post unicode-lg" %></span>


问:
How to draw objects that can be dragged and droped on the screen using pygame?
I am trying to draw 5 rectangles all of which I can drag and drop across the screen. I am using pygame. I managed to draw 1 rectangle that I can drag and drop but I can't do it with 5. This is my code:

```<code>import pygame
from pygame.locals import *
from random import randint

SCREEN_WIDTH = 1024
SCREEN_HEIGHT = 768

BLACK = (  0,   0,   0)
WHITE = (255, 255, 255)
RED   = (255,   0,   0)
pygame.init()

screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
screen_rect = screen.get_rect()

pygame.display.set_caption("Moving circles")

rectangle = pygame.rect.Rect(20,20, 17, 17)
rectangle_draging = False

clock = pygame.time.Clock()

running = True

while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

        elif event.type == pygame.MOUSEBUTTONDOWN:
            if event.button == 1:
                if rectangle.collidepoint(event.pos):
                    rectangle_draging = True
                    mouse_x, mouse_y = event.pos
                    offset_x = rectangle.x - mouse_x
                    offset_y = rectangle.y - mouse_y

        elif event.type == pygame.MOUSEBUTTONUP:
            if event.button == 1:
                rectangle_draging = False

        elif event.type == pygame.MOUSEMOTION:
            if rectangle_draging:
                mouse_x, mouse_y = event.pos
                rectangle.x = mouse_x + offset_x
                rectangle.y = mouse_y + offset_y

    screen.fill(WHITE)
    pygame.draw.rect(screen, RED, rectangle)

    pygame.display.flip()

clock.tick(FPS)

pygame.quit()
</code>```

I guess this is the most important part:

```<code>  pygame.draw.rect(screen, RED, rectangle)
</code>```

Every time I try drawing 5 of them I can't drag any of them. Does anyone have a solution for this?

答:
You can create a list of rectangles and a selected_rect variable which points to the currently selected rect. In the event loop check if one of the rects collides with the event.pos, then set the selected_rect to the rect under the mouse cursor and move it.

I'm using a pygame.math.Vector2 for the offset to save a few lines in the example.

```<code>import sys
import pygame as pg
from pygame.math import Vector2

pg.init()

WHITE = (255, 255, 255)
RED   = (255,   0,   0)

screen = pg.display.set_mode((1024, 768))

selected_rect = None  # Currently selected rectangle.
rectangles = []
for y in range(5):
    rectangles.append(pg.Rect(20, 30*y, 17, 17))
# As a list comprehension.
# rectangles = [pg.Rect(20, 30*y, 17, 17) for y in range(5)]

clock = pg.time.Clock()
running = True

while running:
    for event in pg.event.get():
        if event.type == pg.QUIT:
            running = False
        elif event.type == pg.MOUSEBUTTONDOWN:
            if event.button == 1:
                for rectangle in rectangles:
                    if rectangle.collidepoint(event.pos):
                        offset = Vector2(rectangle.topleft) - event.pos
                        selected_rect = rectangle
        elif event.type == pg.MOUSEBUTTONUP:
            if event.button == 1:
                selected_rect = None
        elif event.type == pg.MOUSEMOTION:
            if selected_rect:
                selected_rect.topleft = event.pos + offset

    screen.fill(WHITE)
    for rectangle in rectangles:
        pg.draw.rect(screen, RED, rectangle)

    pg.display.flip()
    clock.tick(30)

pg.quit()
sys.exit()
</code>```

Body:
I am trying to draw 5 rectangles all of which I can drag and drop across the screen. I am using pygame. I managed to draw 1 rectangle that I can drag and drop but I can't do it with 5. This is my code:

import pygame
from pygame.locals import *
from random import randint

SCREEN_WIDTH = 1024
SCREEN_HEIGHT = 768

BLACK = (  0,   0,   0)
WHITE = (255, 255, 255)
RED   = (255,   0,   0)
pygame.init()

screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
screen_rect = screen.get_rect()

pygame.display.set_caption("Moving circles")

rectangle = pygame.rect.Rect(20,20, 17, 17)
rectangle_draging = False

clock = pygame.time.Clock()

running = True

while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

        elif event.type == pygame.MOUSEBUTTONDOWN:
            if event.button == 1:
                if rectangle.collidepoint(event.pos):
                    rectangle_draging = True
                    mouse_x, mouse_y = event.pos
                    offset_x = rectangle.x - mouse_x
                    offset_y = rectangle.y - mouse_y

        elif event.type == pygame.MOUSEBUTTONUP:
            if event.button == 1:
                rectangle_draging = False

        elif event.type == pygame.MOUSEMOTION:
            if rectangle_draging:
                mouse_x, mouse_y = event.pos
                rectangle.x = mouse_x + offset_x
                rectangle.y = mouse_y + offset_y

    screen.fill(WHITE)
    pygame.draw.rect(screen, RED, rectangle)

    pygame.display.flip()

clock.tick(FPS)

pygame.quit()

I guess this is the most important part:

  pygame.draw.rect(screen, RED, rectangle)

Every time I try drawing 5 of them I can't drag any of them. Does anyone have a solution for this?

Body:
You can create a list of rectangles and a selected_rect variable which points to the currently selected rect. In the event loop check if one of the rects collides with the event.pos, then set the selected_rect to the rect under the mouse cursor and move it.

I'm using a pygame.math.Vector2 for the offset to save a few lines in the example.

import sys
import pygame as pg
from pygame.math import Vector2

pg.init()

WHITE = (255, 255, 255)
RED   = (255,   0,   0)

screen = pg.display.set_mode((1024, 768))

selected_rect = None  # Currently selected rectangle.
rectangles = []
for y in range(5):
    rectangles.append(pg.Rect(20, 30*y, 17, 17))
# As a list comprehension.
# rectangles = [pg.Rect(20, 30*y, 17, 17) for y in range(5)]

clock = pg.time.Clock()
running = True

while running:
    for event in pg.event.get():
        if event.type == pg.QUIT:
            running = False
        elif event.type == pg.MOUSEBUTTONDOWN:
            if event.button == 1:
                for rectangle in rectangles:
                    if rectangle.collidepoint(event.pos):
                        offset = Vector2(rectangle.topleft) - event.pos
                        selected_rect = rectangle
        elif event.type == pg.MOUSEBUTTONUP:
            if event.button == 1:
                selected_rect = None
        elif event.type == pg.MOUSEMOTION:
            if selected_rect:
                selected_rect.topleft = event.pos + offset

    screen.fill(WHITE)
    for rectangle in rectangles:
        pg.draw.rect(screen, RED, rectangle)

    pg.display.flip()
    clock.tick(30)

pg.quit()
sys.exit()


问:
Pandas - Cumsum over time periods + groupby time
I currently have a dataframe that looks like:

I am trying to figure out how to do the following, and just don't know how to start....

For each DAY, cumsum the volume..

After this, group the data by time
of day (ie, 10min intervals). If a day doesn't have that interval
(sometimes gaps), then it should just be treated as 0.

Any help would really be appreciated!

答:
For number 1:

Let's use resample with D:

```<code>df.resample('D')['volume'].cumsum()
</code>```

For Number 2:

Let's use resample('10T') with asfreq and replace:

```<code>df.resample('10T').asfreq().replace(np.nan,0)
</code>```

Body:
For number 1:

Let's use resample with D:

df.resample('D')['volume'].cumsum()

For Number 2:

Let's use resample('10T') with asfreq and replace:

df.resample('10T').asfreq().replace(np.nan,0)


问:
python gcc and setuptools error during lxml installation
I am trying to install LXML on centos (amazon linux AMI).

I have installed the following prereqs:

```<code>sudo yum install libxml2-devel libxslt-devel
sudo yum install zlib-devel
sudo pip install setuptools
sudo yum install python-devel
</code>```

I then install lxml with:

```<code>sudo pip install lxml
</code>```

I get the following gcc error:

creating build/temp.linux-x86_64-2.7/src/lxml
      gcc -pthread -fno-strict-aliasing -O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector --param=ssp-buffer-size=4 -m64 -mtune=generic -D_GNU_SOURCE -fPIC -fwrapv -DNDEBUG -O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector --param=ssp-buffer-size=4 -m64 -mtune=generic -D_GNU_SOURCE -fPIC -fwrapv -fPIC -I/usr/include/libxml2 -Isrc/lxml/includes -I/usr/include/python2.7 -c src/lxml/lxml.etree.c -o
  build/temp.linux-x86_64-2.7/src/lxml/lxml.etree.o -w
      {standard input}: Assembler messages:
      {standard input}:593226: Error: unknown pseudo-op: `.lc1'
      gcc: internal compiler error: Killed (program cc1)
      Please submit a full bug report,
      with preprocessed source if appropriate.
      See http://bugzilla.redhat.com/bugzilla for instructions.
      Compile failed: command 'gcc' failed with exit status 4
      creating tmp
      cc -I/usr/include/libxml2 -I/usr/include/libxml2 -c /tmp/xmlXPathInit0HczkK.c -o tmp/xmlXPathInit0HczkK.o
      cc tmp/xmlXPathInit0HczkK.o -L/usr/lib64 -lxml2 -o a.out
      error: command 'gcc' failed with exit status 4

```<code>----------------------------------------
</code>```

Command "/usr/bin/python2.7 -c "import setuptools,
  tokenize;file='/tmp/pip-build-TmaL5z/lxml/setup.py';exec(compile(getattr(tokenize, 'open', open)(file).read().replace('\r\n', '\n'), file,
  'exec'))" install --record /tmp/pip-OD8Xpx-record/install-record.txt
  --single-version-externally-managed --compile" failed with error code 1 in /tmp/pip-build-TmaL5z/lxml

My gcc version is:
gcc (GCC) 4.8.3 20140911 (Red Hat 4.8.3-9)

My python version is:
Python 2.7.12

How can I get past this error to install LXML ?

答:
I installed those I mentioned above:

```<code>sudo yum install libxml2-devel libxslt-devel
sudo yum install zlib-devel
sudo pip install setuptools
sudo yum install python-devel
</code>```

And these two did the trick:

```<code>sudo yum install glibc-devel glibc-headers
Sudo yum groupinstall "Development tools”

sudo pip install lxml
</code>```

Body:
I am trying to install LXML on centos (amazon linux AMI).

I have installed the following prereqs:

sudo yum install libxml2-devel libxslt-devel
sudo yum install zlib-devel
sudo pip install setuptools
sudo yum install python-devel

I then install lxml with:

sudo pip install lxml

I get the following gcc error:

creating build/temp.linux-x86_64-2.7/src/lxml
      gcc -pthread -fno-strict-aliasing -O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector --param=ssp-buffer-size=4 -m64 -mtune=generic -D_GNU_SOURCE -fPIC -fwrapv -DNDEBUG -O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector --param=ssp-buffer-size=4 -m64 -mtune=generic -D_GNU_SOURCE -fPIC -fwrapv -fPIC -I/usr/include/libxml2 -Isrc/lxml/includes -I/usr/include/python2.7 -c src/lxml/lxml.etree.c -o
  build/temp.linux-x86_64-2.7/src/lxml/lxml.etree.o -w
      {standard input}: Assembler messages:
      {standard input}:593226: Error: unknown pseudo-op: `.lc1'
      gcc: internal compiler error: Killed (program cc1)
      Please submit a full bug report,
      with preprocessed source if appropriate.
      See http://bugzilla.redhat.com/bugzilla for instructions.
      Compile failed: command 'gcc' failed with exit status 4
      creating tmp
      cc -I/usr/include/libxml2 -I/usr/include/libxml2 -c /tmp/xmlXPathInit0HczkK.c -o tmp/xmlXPathInit0HczkK.o
      cc tmp/xmlXPathInit0HczkK.o -L/usr/lib64 -lxml2 -o a.out
      error: command 'gcc' failed with exit status 4

----------------------------------------

Command "/usr/bin/python2.7 -c "import setuptools,
  tokenize;file='/tmp/pip-build-TmaL5z/lxml/setup.py';exec(compile(getattr(tokenize, 'open', open)(file).read().replace('\r\n', '\n'), file,
  'exec'))" install --record /tmp/pip-OD8Xpx-record/install-record.txt
  --single-version-externally-managed --compile" failed with error code 1 in /tmp/pip-build-TmaL5z/lxml

My gcc version is:
gcc (GCC) 4.8.3 20140911 (Red Hat 4.8.3-9)

My python version is:
Python 2.7.12

How can I get past this error to install LXML ?

Body:
I installed those I mentioned above:

sudo yum install libxml2-devel libxslt-devel
sudo yum install zlib-devel
sudo pip install setuptools
sudo yum install python-devel

And these two did the trick:

sudo yum install glibc-devel glibc-headers
Sudo yum groupinstall "Development tools”

sudo pip install lxml


问:
SQL: order by calculated rate between two tables
I might be confusing syntax from other languages with SQL and that's why this isn't working, my subquery is definitely incorrect.

Having the following 2 tables:

```<code>TEST_RESULTS
Student_ID Test_ID Test_Result
    A1       234       90
    B2       234       80
    C3       345       85
    D4       234       95
    A1       345       95
    C3       456       95

TEST_DESCRIPTION
Test_ID  Test_Description Passing_Score
  234         Test A            85
  345         Test B            90
  456         Test C            95
</code>```

I want to calculate the rate of passing for each test and sort by it.

The output I am looking for:

```<code>Test_ID   Test_Description  students_taking students_passing   rate
456             Test C         1                1               1
234             Test A         3                2               0.666666667
345             Test B         2                1               0.5
</code>```

This is my query

```<code>SELECT td.Test_ID, td.Test_Description, COUNT(tr.Student_ID) as
students_taking, students_passing, students_passing/students_taking as rate
FROM
(SELECT td.Test_ID, td.Test_Description, COUNT(tr.Student_ID) as
students_passing
FROM TEST_RESULTS tr
JOIN TEST_DESCRIPTION td
on tr.Test_ID = td.Test_ID
WHERE tr.Test_Result > td.)
GROUP BY td.Test_ID, td.Test_Description
ORDER BY rate DESC, td.Test_ID, td.Test_Description
</code>```

My select from select is wrong, because I am getting no results for this query.

答:
```<code>SELECT td.Test_ID, td.Test_Description,
    students_taking  = counts.students_taking,
    students_passing = counts.students_passing,
    rate             = counts.rate
FROM TEST_DESCRIPTION td
OUTER APPLY (
    SELECT
        students_taking    = COUNT(1),
        students_passing   = COUNT(CASE WHEN tr.Test_Result > td.Passing_score THEN 1 ELSE NULL END),
        rate               = IIF(COUNT(1) <> 0, COUNT(CASE WHEN tr.Test_Result > td.Passing_score THEN 1 ELSE NULL END) / CAST(COUNT(1) AS FLOAT), 0)
    FROM TEST_RESULTS tr
    WHERE tr.Test_ID = td.Test_ID
) counts
ORDER BY counts.rate DESC, td.Test_ID
</code>```

Body:
I might be confusing syntax from other languages with SQL and that's why this isn't working, my subquery is definitely incorrect.

Having the following 2 tables:

TEST_RESULTS
Student_ID Test_ID Test_Result
    A1       234       90
    B2       234       80
    C3       345       85
    D4       234       95
    A1       345       95
    C3       456       95

TEST_DESCRIPTION
Test_ID  Test_Description Passing_Score
  234         Test A            85
  345         Test B            90
  456         Test C            95

I want to calculate the rate of passing for each test and sort by it.

The output I am looking for:

Test_ID   Test_Description  students_taking students_passing   rate
456             Test C         1                1               1
234             Test A         3                2               0.666666667
345             Test B         2                1               0.5

This is my query

SELECT td.Test_ID, td.Test_Description, COUNT(tr.Student_ID) as
students_taking, students_passing, students_passing/students_taking as rate
FROM
(SELECT td.Test_ID, td.Test_Description, COUNT(tr.Student_ID) as
students_passing
FROM TEST_RESULTS tr
JOIN TEST_DESCRIPTION td
on tr.Test_ID = td.Test_ID
WHERE tr.Test_Result > td.)
GROUP BY td.Test_ID, td.Test_Description
ORDER BY rate DESC, td.Test_ID, td.Test_Description

My select from select is wrong, because I am getting no results for this query.


问:
asp.net mvc c# dynamic checkboxes getting controller value
i have the dynamic multiple  checkbox controls generated in the view. what is the best way to get their value in the controller?.There can be multiple values for multiple checkboxes.

Did any one notice that using html.checkbox there is a hidden field added with the already created checkbox? i notice it with firebug ,wonder why

答:
Assuming you have a list of names of the dynamically generated checkboxes, you can extract the values like this:

View:

```<code><%foreach (string checkBoxName in Model.dynamicCheckboxList)
{%>
    <%=Html.CheckBox(checkBoxName)%>
<%}%>
</code>```

Controller:

```<code>public ActionResult controllername(FormCollection form)
{
     foreach(string checkBoxName in dynamicCheckboxList)
     {
           var value = form[checkBoxName];
           //process value here
     }
}
</code>```

Body:
Assuming you have a list of names of the dynamically generated checkboxes, you can extract the values like this:

View:

<%foreach (string checkBoxName in Model.dynamicCheckboxList)
{%>
    <%=Html.CheckBox(checkBoxName)%>
<%}%>

Controller:

public ActionResult controllername(FormCollection form)
{
     foreach(string checkBoxName in dynamicCheckboxList)
     {
           var value = form[checkBoxName];
           //process value here
     }
}


问:
How to get the last part of dirname in Bash
Suppose I have a file /from/here/to/there.txt, and want to get only the last part of its dirname to instead of /from/here/to, what should I do?

答:
Using Bash parameter expansion, you could do this:

```<code>path="/from/here/to/there.txt"
dir="${path%/*}"       # sets dir      to '/from/here/to' (equivalent of dirname)
last_dir="${dir##*/}"  # sets last_dir to 'to' (equivalent of basename)
</code>```

This is more efficient since no external commands are used.

Body:
Using Bash parameter expansion, you could do this:

path="/from/here/to/there.txt"
dir="${path%/*}"       # sets dir      to '/from/here/to' (equivalent of dirname)
last_dir="${dir##*/}"  # sets last_dir to 'to' (equivalent of basename)

This is more efficient since no external commands are used.


问:
R Code : Error in (function: arguments imply differing number of rows: 1, 2
The following part of the code works fine for me. assessments_jobSmart is an imported csv file. I'm trying to reshape data of multiple column but i couldn't make it by using tapply. So i attempted to bind the matrices by matching user_id, and add row id the id hasn't existed.

```<code>individual_assess <- filter(assessments_jobSmart, !is.na(assessments_jobSmart$submitted))
quiz_i = filter(individual_assess, assessment_type == 'quiz')
checkin_i = filter(individual_assess, assessment_type == 'checkin')

groupQuiz_i <- group_by(quiz_i, user_id, program_id, name)
summaryQuiz_i <- summarize(groupQuiz_i, maxQuiz = max(moderated_score))
q1 <- with(summaryQuiz_i, tapply(maxQuiz, list(user_id, name) , I))
q2=matrix(NA, nrow = nrow(q1), ncol = ncol(q1)+1)
colnames(q2) = c("user_id", paste("assess_q", colnames(q1)))
q2[1:nrow(q2),1] = rownames(q1)
q2[1:nrow(q2),2:ncol(q2)] = q1[1:nrow(q1),1:ncol(q1)]
lla = merge(lla, q2, by = 'user_id', all=TRUE)
</code>```

But for the next part, it gives me error at the end of my last line. I reffered to many links but still can't figure out why. c1 and c2 both have same number of rows.

```<code>Error in (function (..., row.names = NULL, check.rows = FALSE, check.names =
TRUE, : arguments imply differing number of rows: 1, 2
</code>```

faulty code:

```<code>groupCheckin_i <- group_by(checkin_i, user_id, program_id, name)
summaryCheckin_i <- summarize(groupCheckin_i, countCheckin = n())
c1 <- with(summaryCheckin_i, tapply(countCheckin, list(user_id, name) , I))
c1[c1=="NULL"]=NA
c2=matrix(NA, nrow = nrow(c1), ncol = ncol(c1)+1)
colnames(c2) = c("user_id", paste("assess_c", colnames(c1)))
c2[1:nrow(c2),1] = rownames(c1)
c2[1:nrow(c2),2:ncol(c2)] = c1[1:nrow(c1),1:ncol(c1)]
lla = merge(lla, c2, by = 'user_id', all=TRUE)
</code>```

Reproducible example, not sure if i replicate it correctly tho. I'll start from the dataframe imported, grouped, and summarized.

```<code>install.packages("dplyr")
install.packages("reshape2")
install.packages('ggplot2', dep = TRUE)
library("dplyr")
library(reshape2)
library(ggplot2)

head = c("user_id", "program", "assessment", "type", "marks")
content = c("111", "program A", "quiz 1", "quiz", "1", "112", "program A", "quiz 1", "quiz", "0.5", "112", "program A", "quiz 2", "quiz", "0.75", "113", "program B", "quiz 2", "quiz", "0.8", "110", "program B", "survey 1", "survey", "1", "113", "program B", "survey 1", "survey", "1")
M = as.dataframe(matrix(content, nrow=5, ncol=5)) #kinda replicate my imported csv file.
s = filter(M, type == 'survey')
q = filter(M, type == 'quiz')
groupS = group_by(s, user_id, program, assessment)
groupQ = group_by(q, user_id, program, assessment)

summaryS <- summarize(groupS, maxMarks = max(marks)) # take only maximum marks if there are duplicate entries
s1 <- with(summaryS, tapply(maxMarks, list(user_id, assessment) , I))
s2 = matrix(NA, nrow=nrow(s1), ncol=ncol(s1)+1)
colnames(s2) = c("user_id", colnames(s1))
s2[q:nrow(s2), 1] = rownames(s1)      # everything works alright till here
s2[1:nrow(s2),2:ncol(s2)] = s1[1:nrow(s1),1:nrow(s1)]

summaryQ <- summarize(groupQ, count = n()) # it makes more sense to count survey done
q1 <- with(summaryQ, tapply(count, list(user_id, assessment) , I))
q2 = matrix(NA, nrow=nrow(q1), ncol=ncol(q1)+1)
colnames(q2) = c("user_id", colnames(q1))
q2[q:nrow(q2), 1] = rownames(q1)      # everything works alright till here
q2[1:nrow(q2),2:ncol(q2)] = q1[1:nrow(q1),1:nrow(q1)]  #q2 becomes a list :(
b = merge(b, a2, by = 'user_id', all+TRUE)

#     | program   | assessment   | marks
# ---------------------------------------
# 111 | program A | quiz 1       | 1
# 112 | program A | quiz 1       | 0.5
# 112 | program A | quiz 2       | 0.75
# 113 | program B | quiz 2       | 0.8

# Then I used tapply to reshape data to get something like:

#     | assessment 1 | assessment 2
# -------------------------------------
# 111 | 1            | NA
# 112 | 0.5          | 0.75
# 113 | NA           | 0.8
</code>```

There are many of these tables because the results are extracted differently, so I want to merge them at the end to combine all the results. I don't want user_id to appear twice, each for separate table. I want to compare results with user_id but heading for that column is missing as user_id was treated as rownames. So I create a larger matrix to copy everything and include the user_id column name:

```<code># Let's say a1 is the matrix after tapply, a2 is the new dataframe I want to create, b is the successful new dataframe created using the exact same method on same csv file exported.
</code>```

I want to get something like this after merging:

```<code>user_id | survey 1 | survey 2 | assessment 1 | assessment 2
-------------------------------------------------------------
110     | 1        | NA       | NA           | NA
111     | NA       | NA       | 1            | NA
112     | NA       | NA       | 0.5          | 0.75
113     | 1        | NA       | NA           | 0.8
</code>```

答:
I'm still having a hard time understanding exactly what you are starting with and what you want. And some parts of your reproducible example do not work. I tried to fill in the blanks and so here's my attempt at answering.

Instead of all the apply functions, you might want to try tidyr functions for reshaping dataframes (gather/ spread and unite/separate).

library(dplyr)
library(tidyr)
library(stringr)

df1 <- data_frame(
           V1 = c("111", "program A", "quiz 1", "quiz", "1"),
           V2 = c("112", "program A", "quiz 1", "quiz", "0.5"),
           V3 = c("112", "program A", "quiz 2", "quiz", "0.75"),
           V4 = c("113", "program B", "quiz 2", "quiz", "0.8"),
           V5 = c("110", "program B", "survey 1", "survey", "1")
)

df1
#> # A tibble: 5 x 5
#>          V1        V2        V3        V4        V5
#>       <chr>     <chr>     <chr>     <chr>     <chr>
#> 1       111       112       112       113       110
#> 2 program A program A program A program B program B
#> 3    quiz 1    quiz 1    quiz 2    quiz 2  survey 1
#> 4      quiz      quiz      quiz      quiz    survey
#> 5         1       0.5      0.75       0.8         1

col_names <- c("user_id", "program", "assessment", "type", "marks")

df2 <- df1 %>%
  summarise_all(paste, collapse = ",") %>%
  gather("key", "val") %>%
  separate(val, col_names, ",", convert = TRUE) %>%
  mutate(assessment = assessment %>% str_extract("\\d") %>% as.integer(),
         program = str_extract(program, ".{1}$")) %>%
  select(-key)

df2
#> # A tibble: 5 x 5
#>   user_id program assessment   type marks
#>     <int>   <chr>      <int>  <chr> <dbl>
#> 1     111       A          1   quiz  1.00
#> 2     112       A          1   quiz  0.50
#> 3     112       A          2   quiz  0.75
#> 4     113       B          2   quiz  0.80
#> 5     110       B          1 survey  1.00

df3 <- df2 %>%
  group_by(user_id, program, type, assessment) %>%
  summarise(marks = max(marks)) %>%
  unite(key, program, type, assessment) %>%
  spread(key, marks)

df3
#> Source: local data frame [4 x 5]
#> Groups: user_id [4]
#>
#> # A tibble: 4 x 5
#>   user_id A_quiz_1 A_quiz_2 B_quiz_2 B_survey_1
#> *   <int>    <dbl>    <dbl>    <dbl>      <dbl>
#> 1     110       NA       NA       NA          1
#> 2     111      1.0       NA       NA         NA
#> 3     112      0.5     0.75       NA         NA
#> 4     113       NA       NA      0.8         NA
```

<p>You also mention something about having trouble with <code>user_id</code> being stuck as the rownames for some data. <code>tibble::rownames_to_column()</code> is helpful for this.</p>

<pre class="lang-r prettyprint-override"><code>library(tibble)

head(mtcars)
#>                    mpg cyl disp  hp drat    wt  qsec vs am gear carb
#> Mazda RX4         21.0   6  160 110 3.90 2.620 16.46  0  1    4    4
#> Mazda RX4 Wag     21.0   6  160 110 3.90 2.875 17.02  0  1    4    4
#> Datsun 710        22.8   4  108  93 3.85 2.320 18.61  1  1    4    1
#> Hornet 4 Drive    21.4   6  258 110 3.08 3.215 19.44  1  0    3    1
#> Hornet Sportabout 18.7   8  360 175 3.15 3.440 17.02  0  0    3    2
#> Valiant           18.1   6  225 105 2.76 3.460 20.22  1  0    3    1

mtcars %>%
  rownames_to_column("model") %>%
  head()
#>               model  mpg cyl disp  hp drat    wt  qsec vs am gear carb
#> 1         Mazda RX4 21.0   6  160 110 3.90 2.620 16.46  0  1    4    4
#> 2     Mazda RX4 Wag 21.0   6  160 110 3.90 2.875 17.02  0  1    4    4
#> 3        Datsun 710 22.8   4  108  93 3.85 2.320 18.61  1  1    4    1
#> 4    Hornet 4 Drive 21.4   6  258 110 3.08 3.215 19.44  1  0    3    1
#> 5 Hornet Sportabout 18.7   8  360 175 3.15 3.440 17.02  0  0    3    2
#> 6           Valiant 18.1   6  225 105 2.76 3.460 20.22  1  0    3    1
</code>```

Also, since you are using a lot of tidyverse functions, you might want to check out dplyr::*_join functions instead of merge.

Body:
The following part of the code works fine for me. assessments_jobSmart is an imported csv file. I'm trying to reshape data of multiple column but i couldn't make it by using tapply. So i attempted to bind the matrices by matching user_id, and add row id the id hasn't existed.

individual_assess <- filter(assessments_jobSmart, !is.na(assessments_jobSmart$submitted))
quiz_i = filter(individual_assess, assessment_type == 'quiz')
checkin_i = filter(individual_assess, assessment_type == 'checkin')

groupQuiz_i <- group_by(quiz_i, user_id, program_id, name)
summaryQuiz_i <- summarize(groupQuiz_i, maxQuiz = max(moderated_score))
q1 <- with(summaryQuiz_i, tapply(maxQuiz, list(user_id, name) , I))
q2=matrix(NA, nrow = nrow(q1), ncol = ncol(q1)+1)
colnames(q2) = c("user_id", paste("assess_q", colnames(q1)))
q2[1:nrow(q2),1] = rownames(q1)
q2[1:nrow(q2),2:ncol(q2)] = q1[1:nrow(q1),1:ncol(q1)]
lla = merge(lla, q2, by = 'user_id', all=TRUE)

But for the next part, it gives me error at the end of my last line. I reffered to many links but still can't figure out why. c1 and c2 both have same number of rows.

Error in (function (..., row.names = NULL, check.rows = FALSE, check.names =
TRUE, : arguments imply differing number of rows: 1, 2

faulty code:

groupCheckin_i <- group_by(checkin_i, user_id, program_id, name)
summaryCheckin_i <- summarize(groupCheckin_i, countCheckin = n())
c1 <- with(summaryCheckin_i, tapply(countCheckin, list(user_id, name) , I))
c1[c1=="NULL"]=NA
c2=matrix(NA, nrow = nrow(c1), ncol = ncol(c1)+1)
colnames(c2) = c("user_id", paste("assess_c", colnames(c1)))
c2[1:nrow(c2),1] = rownames(c1)
c2[1:nrow(c2),2:ncol(c2)] = c1[1:nrow(c1),1:ncol(c1)]
lla = merge(lla, c2, by = 'user_id', all=TRUE)

Reproducible example, not sure if i replicate it correctly tho. I'll start from the dataframe imported, grouped, and summarized.

install.packages("dplyr")
install.packages("reshape2")
install.packages('ggplot2', dep = TRUE)
library("dplyr")
library(reshape2)
library(ggplot2)

head = c("user_id", "program", "assessment", "type", "marks")
content = c("111", "program A", "quiz 1", "quiz", "1", "112", "program A", "quiz 1", "quiz", "0.5", "112", "program A", "quiz 2", "quiz", "0.75", "113", "program B", "quiz 2", "quiz", "0.8", "110", "program B", "survey 1", "survey", "1", "113", "program B", "survey 1", "survey", "1")
M = as.dataframe(matrix(content, nrow=5, ncol=5)) #kinda replicate my imported csv file.
s = filter(M, type == 'survey')
q = filter(M, type == 'quiz')
groupS = group_by(s, user_id, program, assessment)
groupQ = group_by(q, user_id, program, assessment)

summaryS <- summarize(groupS, maxMarks = max(marks)) # take only maximum marks if there are duplicate entries
s1 <- with(summaryS, tapply(maxMarks, list(user_id, assessment) , I))
s2 = matrix(NA, nrow=nrow(s1), ncol=ncol(s1)+1)
colnames(s2) = c("user_id", colnames(s1))
s2[q:nrow(s2), 1] = rownames(s1)      # everything works alright till here
s2[1:nrow(s2),2:ncol(s2)] = s1[1:nrow(s1),1:nrow(s1)]

summaryQ <- summarize(groupQ, count = n()) # it makes more sense to count survey done
q1 <- with(summaryQ, tapply(count, list(user_id, assessment) , I))
q2 = matrix(NA, nrow=nrow(q1), ncol=ncol(q1)+1)
colnames(q2) = c("user_id", colnames(q1))
q2[q:nrow(q2), 1] = rownames(q1)      # everything works alright till here
q2[1:nrow(q2),2:ncol(q2)] = q1[1:nrow(q1),1:nrow(q1)]  #q2 becomes a list :(
b = merge(b, a2, by = 'user_id', all+TRUE)

#     | program   | assessment   | marks
# ---------------------------------------
# 111 | program A | quiz 1       | 1
# 112 | program A | quiz 1       | 0.5
# 112 | program A | quiz 2       | 0.75
# 113 | program B | quiz 2       | 0.8

# Then I used tapply to reshape data to get something like:

#     | assessment 1 | assessment 2
# -------------------------------------
# 111 | 1            | NA
# 112 | 0.5          | 0.75
# 113 | NA           | 0.8

There are many of these tables because the results are extracted differently, so I want to merge them at the end to combine all the results. I don't want user_id to appear twice, each for separate table. I want to compare results with user_id but heading for that column is missing as user_id was treated as rownames. So I create a larger matrix to copy everything and include the user_id column name:

# Let's say a1 is the matrix after tapply, a2 is the new dataframe I want to create, b is the successful new dataframe created using the exact same method on same csv file exported.

I want to get something like this after merging:

user_id | survey 1 | survey 2 | assessment 1 | assessment 2
-------------------------------------------------------------
110     | 1        | NA       | NA           | NA
111     | NA       | NA       | 1            | NA
112     | NA       | NA       | 0.5          | 0.75
113     | 1        | NA       | NA           | 0.8

Body:
I'm still having a hard time understanding exactly what you are starting with and what you want. And some parts of your reproducible example do not work. I tried to fill in the blanks and so here's my attempt at answering.

Instead of all the apply functions, you might want to try tidyr functions for reshaping dataframes (gather/ spread and unite/separate).

library(dplyr)
library(tidyr)
library(stringr)

df1 <- data_frame(
           V1 = c("111", "program A", "quiz 1", "quiz", "1"),
           V2 = c("112", "program A", "quiz 1", "quiz", "0.5"),
           V3 = c("112", "program A", "quiz 2", "quiz", "0.75"),
           V4 = c("113", "program B", "quiz 2", "quiz", "0.8"),
           V5 = c("110", "program B", "survey 1", "survey", "1")
)

df1
#> # A tibble: 5 x 5
#>          V1        V2        V3        V4        V5
#>       <chr>     <chr>     <chr>     <chr>     <chr>
#> 1       111       112       112       113       110
#> 2 program A program A program A program B program B
#> 3    quiz 1    quiz 1    quiz 2    quiz 2  survey 1
#> 4      quiz      quiz      quiz      quiz    survey
#> 5         1       0.5      0.75       0.8         1

col_names <- c("user_id", "program", "assessment", "type", "marks")

df2 <- df1 %>%
  summarise_all(paste, collapse = ",") %>%
  gather("key", "val") %>%
  separate(val, col_names, ",", convert = TRUE) %>%
  mutate(assessment = assessment %>% str_extract("\\d") %>% as.integer(),
         program = str_extract(program, ".{1}$")) %>%
  select(-key)

df2
#> # A tibble: 5 x 5
#>   user_id program assessment   type marks
#>     <int>   <chr>      <int>  <chr> <dbl>
#> 1     111       A          1   quiz  1.00
#> 2     112       A          1   quiz  0.50
#> 3     112       A          2   quiz  0.75
#> 4     113       B          2   quiz  0.80
#> 5     110       B          1 survey  1.00

df3 <- df2 %>%
  group_by(user_id, program, type, assessment) %>%
  summarise(marks = max(marks)) %>%
  unite(key, program, type, assessment) %>%
  spread(key, marks)

df3
#> Source: local data frame [4 x 5]
#> Groups: user_id [4]
#>
#> # A tibble: 4 x 5
#>   user_id A_quiz_1 A_quiz_2 B_quiz_2 B_survey_1
#> *   <int>    <dbl>    <dbl>    <dbl>      <dbl>
#> 1     110       NA       NA       NA          1
#> 2     111      1.0       NA       NA         NA
#> 3     112      0.5     0.75       NA         NA
#> 4     113       NA       NA      0.8         NA

You also mention something about having trouble with user_id being stuck as the rownames for some data. tibble::rownames_to_column() is helpful for this.

library(tibble)

head(mtcars)
#>                    mpg cyl disp  hp drat    wt  qsec vs am gear carb
#> Mazda RX4         21.0   6  160 110 3.90 2.620 16.46  0  1    4    4
#> Mazda RX4 Wag     21.0   6  160 110 3.90 2.875 17.02  0  1    4    4
#> Datsun 710        22.8   4  108  93 3.85 2.320 18.61  1  1    4    1
#> Hornet 4 Drive    21.4   6  258 110 3.08 3.215 19.44  1  0    3    1
#> Hornet Sportabout 18.7   8  360 175 3.15 3.440 17.02  0  0    3    2
#> Valiant           18.1   6  225 105 2.76 3.460 20.22  1  0    3    1

mtcars %>%
  rownames_to_column("model") %>%
  head()
#>               model  mpg cyl disp  hp drat    wt  qsec vs am gear carb
#> 1         Mazda RX4 21.0   6  160 110 3.90 2.620 16.46  0  1    4    4
#> 2     Mazda RX4 Wag 21.0   6  160 110 3.90 2.875 17.02  0  1    4    4
#> 3        Datsun 710 22.8   4  108  93 3.85 2.320 18.61  1  1    4    1
#> 4    Hornet 4 Drive 21.4   6  258 110 3.08 3.215 19.44  1  0    3    1
#> 5 Hornet Sportabout 18.7   8  360 175 3.15 3.440 17.02  0  0    3    2
#> 6           Valiant 18.1   6  225 105 2.76 3.460 20.22  1  0    3    1

Also, since you are using a lot of tidyverse functions, you might want to check out dplyr::*_join functions instead of merge.


问:
Is (Document) an object in javascript?
In this code :

```<code>document.getElementById()
</code>```

Is document an object that has properties and methods?

If yes, is getElementById() a method on this object?

If no, What are document and getElementById considered?

答:
In browser, document is a instance of Document.
document instanceof Document =>true.

It represents the whole HTML page.
And document is a property of window.
window.document === document => true.

So it can used as global object.

Title: Is (Document) an object in javascript?

Body:
In this code :

document.getElementById()

Is document an object that has properties and methods?

If yes, is getElementById() a method on this object?

If no, What are document and getElementById considered?


问:
Confusion with valueError vs ValueType try/exception
I have a follow up question to a post I saw on converting a str() input to a int() type. Based on the definitions of valueError and valueType I would expect the valueType exception to have been used however, it doesn't work (when i tried it). ValueError works but I'm not sure why, isn't int('some string') an example of a wrong type?

Link to original post i'm referring to: Converting String to Int using try/except in Python

答:
From the docs:

class int(x, base=10) Return an integer object constructed from a
  number or string x, or return 0 if no arguments are given. If x is a
  number, return x.int(). For floating point numbers, this truncates
  towards zero.

If x is not a number or if base is given, then x must be a string,
  bytes, or bytearray instance representing an integer literal in radix
  base. Optionally, the literal can be preceded by + or - (with no space
  in between) and surrounded by whitespace. A base-n literal consists of
  the digits 0 to n-1, with a to z (or A to Z) having values 10 to 35.
  The default base is 10. The allowed values are 0 and 2–36. Base-2, -8,
  and -16 literals can be optionally prefixed with 0b/0B, 0o/0O, or
  0x/0X, as with integer literals in code. Base 0 means to interpret
  exactly as a code literal, so that the actual base is 2, 8, 10, or 16,
  and so that int('010', 0) is not legal, while int('010') is, as well
  as int('010', 8).

When you call the int() function on a string it will try to convert it to the specified base in the arguments (by default base-10) by iterating over the string and converting the string object over to an int object in the desired base. If it reaches a point where the conversion can not be made due to illegal syntax , it will raise a ValueError so terminate the program early. If for some reason you want to go forward you can but a try: except block in the code to catch the exception.

From the Docs:

exception ValueError Raised when a built-in operation or function
  receives an argument that has the right type but an inappropriate
  value, and the situation is not described by a more precise exception
  such as IndexError.


问:
OOP best design practices for nested classes and helper functions
I'm programming a project in C# and I have two questions in regards to OOP best practices. To keep my questions simple I have simplified the code examples.

I have a class Map which holds the information to the 2D tile map. There will be only one instance of the Map class:

```<code>class Map {
    int height
    int width
    InventoryGrid iGrid
    TileGrid tGrid

    public Map(int height, int width) { ... }
}
</code>```

The Map class contains 2 grids that are related to the items and tiles on the map. These are technically nested classes since they do not get initialized anywhere else in the code. For example the InventoryGrid class might look like this:

```<code>class InventoryGrid {
    Dictionary<int, Item> inventory

    public function SetInventory(int index, item) { ... }
    public function GetInventory(int index) { ... }
}
</code>```

Let's assume we have a Job class which in case an action is completed needs to update the inventory.

```<code>class Job {
    public void FinishedJob()
    {
        // I need to update the inventory.
    }
}
</code>```

Let's assume the Job class makes an event call or has access to the Map instance.

The first question is, what is the best OO way to call the InventoryGrid.SetInventory() function on the inner class:

Create a getter function in the Map class and call map.iGrid.SetInventory() directly.

Create a new function inside the Map class, map.SetInventoryAt() for example, which in turn calls the iGrid.SetInventory() function.

Other solution?

Now in our example the map takes x and y coordinates. However the "grids" take a single unique deterministic index to store their information. A function to convert the coords to index is required.

```<code>public int CoordsToIndex(int x, int y) {...}
</code>```

This function will be used by all Grids (InventoryGrid, TileGrid, etc...)

My second question is where should the function reside according to best practise OO design? Who's responsibility is it?

Do I make a super class Grid containing the function from which all "grids" inherit to avoid duplication? C# specific: use an interface instead of super class?

Do I put it in the Map class and argue that the "Grids" should not be aware of the coords to index conversion. Would this affect the first question?

Do I make a separate (static) class called GridTools which holds helper methods?

Other solution?

答:
To answer your first question, Google "The Law of Demeter". That will give you good OOP guidelines for exactly this sort of thing. And remember, it's a guideline, not a hard rule.

To answer your second question, put the translation code on the Map class because that's the simplest solution and you can easily refactor later. If you find that you need a bunch of related helpers, make a new Helpers class and move the logic there. If you find that other components need to access the Maps then create a base map class and move the logic there. Always choose the most basic solution because it's the easiest one to change when a better solution becomes more clear (Google YAGNI).

That being said, consider using multidimensional arrays or jagged arrays instead of Dictionary. For me they are much easier to comprehend for tile maps and the translation problem goes away. Making problems go away is better than an elegant solution to a problem.

Body:
I'm programming a project in C# and I have two questions in regards to OOP best practices. To keep my questions simple I have simplified the code examples.

I have a class Map which holds the information to the 2D tile map. There will be only one instance of the Map class:

class Map {
    int height
    int width
    InventoryGrid iGrid
    TileGrid tGrid

    public Map(int height, int width) { ... }
}

The Map class contains 2 grids that are related to the items and tiles on the map. These are technically nested classes since they do not get initialized anywhere else in the code. For example the InventoryGrid class might look like this:

class InventoryGrid {
    Dictionary<int, Item> inventory

    public function SetInventory(int index, item) { ... }
    public function GetInventory(int index) { ... }
}

Let's assume we have a Job class which in case an action is completed needs to update the inventory.

class Job {
    public void FinishedJob()
    {
        // I need to update the inventory.
    }
}

Let's assume the Job class makes an event call or has access to the Map instance.

The first question is, what is the best OO way to call the InventoryGrid.SetInventory() function on the inner class:

Create a getter function in the Map class and call map.iGrid.SetInventory() directly.

Create a new function inside the Map class, map.SetInventoryAt() for example, which in turn calls the iGrid.SetInventory() function.

Other solution?

Now in our example the map takes x and y coordinates. However the "grids" take a single unique deterministic index to store their information. A function to convert the coords to index is required.

public int CoordsToIndex(int x, int y) {...}

This function will be used by all Grids (InventoryGrid, TileGrid, etc...)

My second question is where should the function reside according to best practise OO design? Who's responsibility is it?

Do I make a super class Grid containing the function from which all "grids" inherit to avoid duplication? C# specific: use an interface instead of super class?

Do I put it in the Map class and argue that the "Grids" should not be aware of the coords to index conversion. Would this affect the first question?

Do I make a separate (static) class called GridTools which holds helper methods?

Other solution?


问:
Why can't the signal handler in the child process be triggered?
My intention is to create a time out of 1 sec for fgets. If no input is received in 1 sec, then the program terminates.

The design I come up with is:
the parent registers a signal handler for SIGALRM. Then it forks a child which will trigger SIGALRM and it goes ahead and call fgets. The SIGALRM will trigger the handler which kills the parent process. But when I execute this on a ubuntu 14.04 64-bit, the handler is not triggered and the program just waits for user to input for fgets forever.

Why would this happen and how can I fix this?

```<code>#include "csapp.h"

void handler() {
  printf("lazy man\n");
  kill(SIGKILL, getppid());
  exit(0);
}

int main() {
  char buf[100];
  signal(SIGALRM, handler);
  pid_t pid;
  if ((pid = fork()) == 0) {
    alarm(1);
  } else {
    fgets(buf, 100, stdin);
    printf("%s", buf);
  }
  return 0;
}
</code>```

~

答:
If you will take time to read the manual of kill(), you will see that you miss the order of the arguments.

int kill(pid_t pid, int sig);

Fix:

```<code>kill(getppid(), SIGKILL);
</code>```

Plus, your child terminate his execution before that the signal is raise you must add a sleep() after your call to alarm() to make it wait:

```<code>alarm(1);
sleep(2);
</code>```

Finally, printf() is not safe in a signal handler, list of safe function.

Body:
My intention is to create a time out of 1 sec for fgets. If no input is received in 1 sec, then the program terminates.

The design I come up with is:
the parent registers a signal handler for SIGALRM. Then it forks a child which will trigger SIGALRM and it goes ahead and call fgets. The SIGALRM will trigger the handler which kills the parent process. But when I execute this on a ubuntu 14.04 64-bit, the handler is not triggered and the program just waits for user to input for fgets forever.

Why would this happen and how can I fix this?

#include "csapp.h"

void handler() {
  printf("lazy man\n");
  kill(SIGKILL, getppid());
  exit(0);
}

int main() {
  char buf[100];
  signal(SIGALRM, handler);
  pid_t pid;
  if ((pid = fork()) == 0) {
    alarm(1);
  } else {
    fgets(buf, 100, stdin);
    printf("%s", buf);
  }
  return 0;
}

~

Body:
If you will take time to read the manual of kill(), you will see that you miss the order of the arguments.

int kill(pid_t pid, int sig);

Fix:

kill(getppid(), SIGKILL);

Plus, your child terminate his execution before that the signal is raise you must add a sleep() after your call to alarm() to make it wait:

alarm(1);
sleep(2);

Finally, printf() is not safe in a signal handler, list of safe function.


问:
Creating lists of variable length from one list
I want to create a number of lists from a single list.  The lists will either have 1 value or 3 based on if there is data from a user.  However, since the data is attached to a specific user, the order must be maintained.

For example:

```<code>data = ['no data', 'choice 1', 'choice 4', 'choice 2', 'no data', 'choice 1', ...etc]
</code>```

I want the output to be:

```<code>list1 = ['no data']
list2 = ['choice 1', 'choice4', 'choice 2']
list3 = ['no data']
list4 = ['choice 1'...]
</code>```

How would I achieve this?

答:
This seems to work and is fairly easy to understand. It doesn't create separate variables, but instead creates a list-of-lists named lists.

```<code>data = ['no data', 'choice 1', 'choice 4', 'choice 2', 'no data', 'choice 1', '...etc']

lists = []
tmp = []
for elem in data:
    if elem != 'no data':
        tmp.append(elem)
    else:
        if tmp:
            lists.append(tmp)
        lists.append([elem])
        tmp = []

if tmp:
    lists.append(tmp)

for i, sublist in enumerate(lists, start=1):
    print('list{}: {}'.format(i, sublist))
</code>```

Output:

list1: ['no data']
list2: ['choice 1', 'choice 4', 'choice 2']
list3: ['no data']
list4: ['choice 1', '...etc']
```

Body:
I want to create a number of lists from a single list.  The lists will either have 1 value or 3 based on if there is data from a user.  However, since the data is attached to a specific user, the order must be maintained.

For example:

data = ['no data', 'choice 1', 'choice 4', 'choice 2', 'no data', 'choice 1', ...etc]

I want the output to be:

list1 = ['no data']
list2 = ['choice 1', 'choice4', 'choice 2']
list3 = ['no data']
list4 = ['choice 1'...]

How would I achieve this?

Body:
This seems to work and is fairly easy to understand. It doesn't create separate variables, but instead creates a list-of-lists named lists.

data = ['no data', 'choice 1', 'choice 4', 'choice 2', 'no data', 'choice 1', '...etc']

lists = []
tmp = []
for elem in data:
    if elem != 'no data':
        tmp.append(elem)
    else:
        if tmp:
            lists.append(tmp)
        lists.append([elem])
        tmp = []

if tmp:
    lists.append(tmp)

for i, sublist in enumerate(lists, start=1):
    print('list{}: {}'.format(i, sublist))

Output:

list1: ['no data']
list2: ['choice 1', 'choice 4', 'choice 2']
list3: ['no data']
list4: ['choice 1', '...etc']


问:
How to remove th COPY UIMenuItem in UIMenuController
I am developing an iPhone application and worked with UIWebViews. I planned to customize the UIMenuItems thats popped up when i highlight strings in UiWebView (Copy, Select All, Cut, etc.). I tried removing those menuItems but i cannot remove the COPY menu item.

I need your help guys.

Thanks,
ZaldzBugz

答: I used the technique in this answer to a similar question and it works for ridding of the Copy menu item. That is, override UIWebView instead of UITextView in their example. Also wrote a canPerformAction:withSender: in the view controller that returns YES for my custom selectors and NO for the copy: selector, then returns the value of the super implementation if the selector is none of those. Remember to set the custom UIWebView subclass name in your xib.</p>


问:
Upload image and store to database
I'm getting back into programming once again and I'm currently stuck as I'm unable to upload an image to my database.
  I  was reading some codes and answers last night and I'm still stuck here..It returns "New record created successfully" but nothing is being stored on my database. Hoping someone will help me to make a workaround on this one :) Thanks!

```<code><form method="post" action="" enctype="multipart/form-data">

    Upload File:
    <input type="file" name="upload" /><br>
    <input type="submit" name="submit" value="Submit"/>
</form>
</body>
</html>

<?php
    $servername ="localhost";
    $username = "root";
    $password = "";
    $dbname = "produ_db";

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}
if(isset($_POST['submit'])  ){

$filename = $conn->real_escape_string($_FILES['upload']['name']);
$filedata= $conn->real_escape_string(file_get_contents($_FILES['upload']['tmp_name']));

if ($_FILES['upload']['name'] == 0 ){

echo "<br><br> New record created successfully";

}

else {
    /*where acc_cap is the image caption && acc_img is a blob type to store images*/
    $query = "INSERT INTO accessories(`acc_cap`,`acc_img`) VALUES ('$filename','$filedata')" ;
    if ($conn->query($query) === TRUE) {
    echo "<br><br> New record created successfully";
    } else {
    echo "Error:<br>" . $conn->error;
    }

}
$conn->close();
}

?>
</code>```

答:
1 - You have:

```<code>echo "<br><br> New record created successfully";
</code>```

twice - both in success (after INSERT) and failure ($_FILES['upload']['name'] == 0). Change the failure message so you can tell what is happening.

2 - Move:

```<code>$filename = $conn->real_escape_string($_FILES['upload']['name']);
$filedata= $conn->real_escape_string(file_get_contents($_FILES['upload']['tmp_name']));
</code>```

to following the test for $_FILES['upload']['name'] as the file_get_contents function will fail if there is no file name.

3 - Checking my own code, it looks like I normally use $_FILES['upload']['name'] == '' rather than == 0. PHP often treats 0 and the empty string similarly but in this case I believe the empty string is the correct comparison as this is a string field when it has an actual filename.

4 - Generally considered bad form to store full image (or other) files inside the database - better to store in the file system (see http://php.net/manual/en/function.move-uploaded-file.php ) with just the filename in the database. That being said, sometimes it makes sense and I have stored full files in databases at times.

Title: Upload image and store to database

Body:
I'm getting back into programming once again and I'm currently stuck as I'm unable to upload an image to my database.
  I  was reading some codes and answers last night and I'm still stuck here..It returns "New record created successfully" but nothing is being stored on my database. Hoping someone will help me to make a workaround on this one :) Thanks!

<form method="post" action="" enctype="multipart/form-data">

    Upload File:
    <input type="file" name="upload" />

    <input type="submit" name="submit" value="Submit"/>
</form>

<?php
    $servername ="localhost";
    $username = "root";
    $password = "";
    $dbname = "produ_db";

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}
if(isset($_POST['submit'])  ){

$filename = $conn->real_escape_string($_FILES['upload']['name']);
$filedata= $conn->real_escape_string(file_get_contents($_FILES['upload']['tmp_name']));

if ($_FILES['upload']['name'] == 0 ){

echo "

 New record created successfully";

}

else {
    /*where acc_cap is the image caption && acc_img is a blob type to store images*/
    $query = "INSERT INTO accessories(`acc_cap`,`acc_img`) VALUES ('$filename','$filedata')" ;
    if ($conn->query($query) === TRUE) {
    echo "

 New record created successfully";
    } else {
    echo "Error:
" . $conn->error;
    }

}
$conn->close();
}

?>

Body:
1 - You have:

echo "<br><br> New record created successfully";

twice - both in success (after INSERT) and failure ($_FILES['upload']['name'] == 0). Change the failure message so you can tell what is happening.

2 - Move:

$filename = $conn->real_escape_string($_FILES['upload']['name']);
$filedata= $conn->real_escape_string(file_get_contents($_FILES['upload']['tmp_name']));

to following the test for $_FILES['upload']['name'] as the file_get_contents function will fail if there is no file name.

3 - Checking my own code, it looks like I normally use $_FILES['upload']['name'] == '' rather than == 0. PHP often treats 0 and the empty string similarly but in this case I believe the empty string is the correct comparison as this is a string field when it has an actual filename.

4 - Generally considered bad form to store full image (or other) files inside the database - better to store in the file system (see http://php.net/manual/en/function.move-uploaded-file.php ) with just the filename in the database. That being said, sometimes it makes sense and I have stored full files in databases at times.


问:
Tumblr Theme - Different Style for each post type
I'm creating a Tumblr theme, and I've run into a problem, of sorts. I like all of my posts to be these big circles with a different coloured border per post type. I don't know how to do this. Right now I can put ALL post to have a border and be rounded to the size I want, but, for example, I'd like text posts to have a red border, and photo posts to have an orange border. I've tried putting a div around text posts in the coding and adding the border that way, but it creates a secondary border (around the one I already set for ALL posts) and doesn't include the post's info (i.e the date and tags and such).

Does anyone know how to add different borders around each post type that includes the WHOLE post?

Here's the theme live for reference https://rainbowdotsinspiredthemetestblog.tumblr.com/

Heres the coding I have so far (my posts are labeled as stuff)

```<code>#stuff {
                float:left;
                width:400px;
                height:400px;
                margin-top:25px;
                margin-left:25px;
                text-align:justify;
                font-size:11px;
                line-height:90%;
                padding:5px;
                letter-spacing:0px;
                border:5px #24E4D8 solid;
                border-radius:200px;
                overflow:scroll;
                overflow-x:hidden;
                }
<!--TEXT POSTS-->
<div class="testingtext">
{block:Text}{block:Title}<h3>{Title}</h3>{/block:Title}{Body}{/block:Text}</div>
</code>```

This is what I tired and does NOT work

```<code>#stuff .testingtext{
        border:5px red solid;
    }
#stuff>.testingtext{
            border:5px red solid;
        }
#stuff:.testingtext{
            border:5px red solid;
        }
</code>```

答:
You can create classes for each color in your CSS.

```<code>.red { border: 5px red solid }
.orange { border: 5px orange solid }
/* and so on */
</code>```

Then assign the classes to the post types in your HTML.

```<code>{block:Text}
<div class="post red">
    {block:Title}<h3>{Title}</h3>{/block:Title}
    {Body}
</div>
{/block:Text}

{block:Photo}
<div class="post orange">
    {LinkOpenTag}<img src="{PhotoURL-500}" border="0" alt="{PhotoAlt}">{LinkCloseTag}
    {block:Caption}{Caption}{/block:Caption}
</div>
{/block:Photo}
</code>```

and so on, for all post types. Hope this helps!

Body:
I'm creating a Tumblr theme, and I've run into a problem, of sorts. I like all of my posts to be these big circles with a different coloured border per post type. I don't know how to do this. Right now I can put ALL post to have a border and be rounded to the size I want, but, for example, I'd like text posts to have a red border, and photo posts to have an orange border. I've tried putting a div around text posts in the coding and adding the border that way, but it creates a secondary border (around the one I already set for ALL posts) and doesn't include the post's info (i.e the date and tags and such).

Does anyone know how to add different borders around each post type that includes the WHOLE post?

Here's the theme live for reference https://rainbowdotsinspiredthemetestblog.tumblr.com/

Heres the coding I have so far (my posts are labeled as stuff)

#stuff {
                float:left;
                width:400px;
                height:400px;
                margin-top:25px;
                margin-left:25px;
                text-align:justify;
                font-size:11px;
                line-height:90%;
                padding:5px;
                letter-spacing:0px;
                border:5px #24E4D8 solid;
                border-radius:200px;
                overflow:scroll;
                overflow-x:hidden;
                }

{block:Text}{block:Title}
{Title}
{/block:Title}{Body}{/block:Text}

This is what I tired and does NOT work

#stuff .testingtext{
        border:5px red solid;
    }
#stuff>.testingtext{
            border:5px red solid;
        }
#stuff:.testingtext{
            border:5px red solid;
        }

Body:
You can create classes for each color in your CSS.

.red { border: 5px red solid }
.orange { border: 5px orange solid }
/* and so on */

Then assign the classes to the post types in your HTML.

{block:Text}
<div class="post red">
    {block:Title}<h3>{Title}</h3>{/block:Title}
    {Body}
</div>
{/block:Text}

{block:Photo}
<div class="post orange">
    {LinkOpenTag}<img src="{PhotoURL-500}" border="0" alt="{PhotoAlt}">{LinkCloseTag}
    {block:Caption}{Caption}{/block:Caption}
</div>
{/block:Photo}

and so on, for all post types. Hope this helps!


问:
second element(contenttab) is too height/Exceeded of container(outer) after add padding to header tag
My html is :

```<code><div id="outer">
    <header><h1>The Header</h1></header>
    <div id="contenttab">
        <table>
            blablabla
        </table>
    </div>
</div>
</code>```

My CSS :

```<code>#outer{
height:70%;
width:900px;
left:50%;
margin:0 auto;
position:absolute;
top:20px;
z-index:1001;
transform:translate(-50%, 0);
-webkit-transform:translate(-50%, 0);
    -webkit-box-sizing:border-box;
       -moz-box-sizing:border-box;
            box-sizing:border-box;
}
header{
    background-color:#f6f7f9;
    padding:10px;
    font-size:15px !important;
    font-weight:bold !important;
    text-align:center;
    width:100%;
}
#contenttab{
    height:100%;
    overflow-y:auto;
}
</code>```

why my contenttab exceeded the height of #outer div ? how to fix that? I have try adding border-box css to parent div but not solve my problem . . .

答:
I just tried out your posted html/css and your #contenttab div is exceeding the height of it's container because of your css rule of height: 100% on the #contenttab;

It's a lot easier to see/debug the issue using borders on your elements, add the following:

```<code>#outer {
  border: 1px solid #000;
}

#contenttab {
    height: 100%;
    overflow-y: auto;
    border: 1px solid #ffa500;
}
</code>```

You are telling the #contenttab to have 100% full height of it's container, however then you are also adding additional content(the header element) which causes the internal elements to have more than 100% height than it's container can hold.

Either change the height rule on the #contenttab to auto or less than 100%. Or add css rule overflow: hidden(or auto) to your #outer css rule.

Body:
My html is :

The Header

            blablabla

My CSS :

#outer{
height:70%;
width:900px;
left:50%;
margin:0 auto;
position:absolute;
top:20px;
z-index:1001;
transform:translate(-50%, 0);
-webkit-transform:translate(-50%, 0);
    -webkit-box-sizing:border-box;
       -moz-box-sizing:border-box;
            box-sizing:border-box;
}
header{
    background-color:#f6f7f9;
    padding:10px;
    font-size:15px !important;
    font-weight:bold !important;
    text-align:center;
    width:100%;
}
#contenttab{
    height:100%;
    overflow-y:auto;
}

why my contenttab exceeded the height of #outer div ? how to fix that? I have try adding border-box css to parent div but not solve my problem . . .

Body:
I just tried out your posted html/css and your #contenttab div is exceeding the height of it's container because of your css rule of height: 100% on the #contenttab;

It's a lot easier to see/debug the issue using borders on your elements, add the following:

#outer {
  border: 1px solid #000;
}

#contenttab {
    height: 100%;
    overflow-y: auto;
    border: 1px solid #ffa500;
}

You are telling the #contenttab to have 100% full height of it's container, however then you are also adding additional content(the header element) which causes the internal elements to have more than 100% height than it's container can hold.

Either change the height rule on the #contenttab to auto or less than 100%. Or add css rule overflow: hidden(or auto) to your #outer css rule.


问:
Get first item of every sublist of list in Python
I have the following string which is a list of lists:

```<code>"ID":[[310.5,1.1612828],[310.0,15.0],[310.0,2.9755309],[309.5,30.0]]
</code>```

I want to grab all the first values of each list into a variable, so the output should be in this case

```<code>print variable
</code>```

expected output:

```<code>310.5
310.0
310.0
309.5
</code>```

答:
```<code>id = [[310.5,1.1612828],[310.0,15.0],[310.0,2.9755309],[309.5,30.0]]

# If you just want to output to console:
[print(x[0]) for x in id]  #if id a list
# if id is in dict named dict_
[print(x[0] for x in dict_['id']
</code>```

Here's a longer version.

```<code>dict_ = {'id': [[310.5,1.1612828],
                [310.0,15.0],
                [310.0,2.9755309],
                [309.5,30.0]]
                }

#make a list containing position 0 values of sublists
pos_0 = [x[0] for x in dict_['id']]
print(pos_0)

#output them to a file
for entry in pos_0:
      print(entry)
</code>```

Body:
I have the following string which is a list of lists:

"ID":[[310.5,1.1612828],[310.0,15.0],[310.0,2.9755309],[309.5,30.0]]

I want to grab all the first values of each list into a variable, so the output should be in this case

print variable

expected output:

310.5
310.0
310.0
309.5

Body:
id = [[310.5,1.1612828],[310.0,15.0],[310.0,2.9755309],[309.5,30.0]]

# If you just want to output to console:
[print(x[0]) for x in id]  #if id a list
# if id is in dict named dict_
[print(x[0] for x in dict_['id']

Here's a longer version.

dict_ = {'id': [[310.5,1.1612828],
                [310.0,15.0],
                [310.0,2.9755309],
                [309.5,30.0]]
                }

#make a list containing position 0 values of sublists
pos_0 = [x[0] for x in dict_['id']]
print(pos_0)

#output them to a file
for entry in pos_0:
      print(entry)


问:
React-router v4 showing multiple routes at once
I am having an issue where my routing using react-router-dom is showing all routes at once.  So when I render my App component and the start that contains the Routing, I am seeing the pages for each route on top of each other.  So it looks like this:

Sooo to begin how this is all kicking off, this is my index.jsx that is rendering the App component on the page:

```<code>// Dependencies
import React from 'react';
import ReactDOM from 'react-dom';

// Components
import App from './components/app.jsx';

// Styles
import './index.scss';

const container = document.getElementById('main');

ReactDOM.render(<App />, container);
</code>```

In my App Component, the routing is set up as so:

```<code>// Dependencies
import React from 'react';
import { BrowserRouter as Router, Route, Match, Miss } from 'react-router-dom';

// Components
import Login from './pages/login/login.jsx';
import Home from './pages/home/home.jsx';

// Styles
import './app.scss';

const App = () => {
  return (
    <Router>
      <div>
          <Route exact pattern='/' component={Login}/>
          <Route exact pattern='/home' component={Home}/>
      </div>
    </Router>
  );
};

export default App;
</code>```

This is my Login/Home component (The Home component is the exact same just replacing Login):

```<code>// Dependencies
import React from 'react';

// Styles
import './login.scss';

class Login extends React.Component {
  render() {
    return (
      <div className="content">
        <div className='title'>
            Login Page
        </div>
      </div>
    );
  }
}

export default Login;
</code>```

I also noticed that when I navigate to http://localhost:9999/home I am getting this error also:

Something is apparently wired incorrectly, and I am a little confused by the documentation with the different versions existing.  And advice on how to get this fixed is greatly appreciated!

答:
From the React Training :

Routes without a path always match.

So in your case both will always match because u are using pattern.

Body:
I am having an issue where my routing using react-router-dom is showing all routes at once.  So when I render my App component and the start that contains the Routing, I am seeing the pages for each route on top of each other.  So it looks like this:

Sooo to begin how this is all kicking off, this is my index.jsx that is rendering the App component on the page:

// Dependencies
import React from 'react';
import ReactDOM from 'react-dom';

// Components
import App from './components/app.jsx';

// Styles
import './index.scss';

const container = document.getElementById('main');

ReactDOM.render(<App />, container);

In my App Component, the routing is set up as so:

// Dependencies
import React from 'react';
import { BrowserRouter as Router, Route, Match, Miss } from 'react-router-dom';

// Components
import Login from './pages/login/login.jsx';
import Home from './pages/home/home.jsx';

// Styles
import './app.scss';

const App = () => {
  return (
    <Router>

          <Route exact pattern='/' component={Login}/>
          <Route exact pattern='/home' component={Home}/>

    </Router>
  );
};

export default App;

This is my Login/Home component (The Home component is the exact same just replacing Login):

// Dependencies
import React from 'react';

// Styles
import './login.scss';

class Login extends React.Component {
  render() {
    return (

            Login Page

    );
  }
}

export default Login;

I also noticed that when I navigate to http://localhost:9999/home I am getting this error also:

Something is apparently wired incorrectly, and I am a little confused by the documentation with the different versions existing.  And advice on how to get this fixed is greatly appreciated!