问:
how to enable a user to select a single row from data set and send that data row to backend for processing using R shiny
is it possible in shiny to display a dataset (table) to the user(frontend) and select a "single" row from that dataset to process in the backend.

scenario:

i am developing a simple human activity(sitting, running,walking etc) recognition using sensor data app in R using UCI dataset "https://archive.ics.uci.edu/ml/datasets/Human+Activity+Recognition+Using+Smartphones"
.I will be training a certain classification model say naive bayes using dataset and then out of that dataset I want to give my trained model a single row of that dataset and find(recognize) to what class of activity that row belongs. Each row consists of values for various attributes of sensors for a particular instance.

I'll be developing it as a user interactive app "therefore using shiny" and want my entire dataset to be visible in front end(csv form) along with some option (say checkbox) to select a single row and provide my model in the backend that row to process.

I know this may not appear to be very interactive app but I want to "control from frontend" which row gets processed so that I could predict activity for that particular sensor data.Is it possible somehow??

note:from dataset(visible in frontend) I mean only that csv file which contains some 560 attributes, I have no interest in recognizing person(i.e 1-30)I just want activity.

答:
Yes, this is definitely possible. As @s.brunel mentions, it is made exceptionally easy by the DT package.

Below is a toy example where we run the rows that are clicked through the model.

```<code>library("shiny")
library("dplyr")
library("DT")
library("rpart")

set.seed(1)

# set an id variable
iris <- iris %>% mutate(id = row_number())

# select a training set
train_iris <- iris %>%
  group_by(Species) %>%
  sample_frac(0.75)

# select the testing rows
test_iris  <- anti_join(iris, train_iris, by = 'id')

# build the model
fit <- rpart(Species ~ Sepal.Length + Sepal.Width + Petal.Length + Petal.Width, data = test_iris)

ui <- fluidPage(
  DT::dataTableOutput('unscored'),
  DT::dataTableOutput('scored')
  )

server <- function(input, output) {

  # display the data that is available to be scored
  output$unscored <- DT::renderDataTable(test_iris)

  scored_data <- reactive({
    # make sure there are rows to score
    shiny::validate(
      need(length(input$unscored_rows_selected) > 0, "Select rows to score!")
    )

    score_dat <- test_iris[input$unscored_rows_selected, ]
    # return the data with the prediction
    data.table(
      score_dat,
      predicted = predict(fit, score_dat, type = "class")
    )
  })

  # display the scored data once processed by the model
  output$scored <- DT::renderDataTable(scored_data())
}

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

Body:
Yes, this is definitely possible. As @s.brunel mentions, it is made exceptionally easy by the DT package.

Below is a toy example where we run the rows that are clicked through the model.

library("shiny")
library("dplyr")
library("DT")
library("rpart")

set.seed(1)

# set an id variable
iris <- iris %>% mutate(id = row_number())

# select a training set
train_iris <- iris %>%
  group_by(Species) %>%
  sample_frac(0.75)

# select the testing rows
test_iris  <- anti_join(iris, train_iris, by = 'id')

# build the model
fit <- rpart(Species ~ Sepal.Length + Sepal.Width + Petal.Length + Petal.Width, data = test_iris)

ui <- fluidPage(
  DT::dataTableOutput('unscored'),
  DT::dataTableOutput('scored')
  )

server <- function(input, output) {

  # display the data that is available to be scored
  output$unscored <- DT::renderDataTable(test_iris)

  scored_data <- reactive({
    # make sure there are rows to score
    shiny::validate(
      need(length(input$unscored_rows_selected) > 0, "Select rows to score!")
    )

    score_dat <- test_iris[input$unscored_rows_selected, ]
    # return the data with the prediction
    data.table(
      score_dat,
      predicted = predict(fit, score_dat, type = "class")
    )
  })

  # display the scored data once processed by the model
  output$scored <- DT::renderDataTable(scored_data())
}

shinyApp(ui, server)


来源: stackexchange

问:
Is a platform mandatory for cuDNN?
I am using Cuda in C++ for some time now and I would like to try cuDNN. I would like to go straight in C++ but I can mostly only find examples and tutorials that are based on different platforms like Caffè or TensorFlow. Does it mean that I cannot use cuDNN in plain C++?
I need to have the highest possible performance.
Thanks for your help </p>

答:
You can use cuDNN in plain C++.

As a library, it is targeted at Deep Neural Networks/Deep Learning, so many DL Frameworks use it for acceleration of their workloads.

But there is nothing that prevents you from using the library directly, and there should be sufficient API level documentation for you to do so.

If you're unfamiliar with some of the concepts (e.g. tensors), you may find the library more difficult to comprehend, so certainly general familiarity with current common DL concepts will be beneficial in understanding how to use it.

ContentLicense: CC BY-SA 3.0

Title: Is a platform mandatory for cuDNN?


问:
Dask; using apply to update variable
In pandas you can use the apply or map methods in a way that instead up returning an updated view of the DataFrame or Series updates a numpy array passed in with the function. For example:

```<code>In[1]: df = pd.DataFrame({'x': [1,2,3,4,5]})
In[2]: count = np.array([0])
In[3]: def increment(row, count):
           count[0] += row
In[4]: df.x.map(lambda row: increment(row, count))
Out[4]:
    x
0   None
1   None
2   None
3   None
4   None
Name: x, dtype: object
In[5]: count
Out[5]: array([15])
</code>```

I would like to be able to replicate this behavior usins Dask, but so far my only luck has been with the map_partitions method and a bit of a workaround. Is this an issue with the memory space in which the data resides, as my example only uses the one while Dask will be using multiple memory spaces for parallel processing? Or is there a way to force the pandas or Dask apply method to return something that is not shaped like the input DataFrame/Series?

答:
Generally speaking depending on tasks that mutate global state is not supported within Dask.

If your goal is a custom aggregation then the .reduction method may be of use.  This works well if you can write your reduction as a function applied to each partition and then subsequent combination operations.

If your goal is more custom than this then I recommend switching to dask.delayed (see also these docs).

Title: Dask; using apply to update variable

Body:
In pandas you can use the apply or map methods in a way that instead up returning an updated view of the DataFrame or Series updates a numpy array passed in with the function. For example:

In[1]: df = pd.DataFrame({'x': [1,2,3,4,5]})
In[2]: count = np.array([0])
In[3]: def increment(row, count):
           count[0] += row
In[4]: df.x.map(lambda row: increment(row, count))
Out[4]:
    x
0   None
1   None
2   None
3   None
4   None
Name: x, dtype: object
In[5]: count
Out[5]: array([15])

I would like to be able to replicate this behavior usins Dask, but so far my only luck has been with the map_partitions method and a bit of a workaround. Is this an issue with the memory space in which the data resides, as my example only uses the one while Dask will be using multiple memory spaces for parallel processing? Or is there a way to force the pandas or Dask apply method to return something that is not shaped like the input DataFrame/Series?


问:
debugging issue with iphone simulator 4.0
Friends,

I am building and debugging my xproj. Now the control is not stopping at the breakpoint i kept in the program but it is stopping at the return statement of operator++() in the stl_iterator.h file. After I press Continue the code is giving expected results but the thing is I cannot see the step by step debugging. Can any one give me clue why it is happening so, always i see the control at same position. I cleaned all targets and tried but no luck.

Active SDK = iphonesimulator4.0, Active Configuration = Build.  (I used C++ in the code).

With iphoneSImulator3.1.2, i can able to debug step-by-step for the same code.

Thanks in Advance,
Anil

答: Sometimes the compiler will optimize your code and make breakpoints move around. Be sure to turn off all optimizations when building for debugging purposes; this should already be set in the “Debug” build setting.</p>

ContentLicense: CC BY-SA 2.5


问:
Deserialize nested xml in c# (Unity-script)
I am currently making a game in unity3D. I have a xml document which contains a number of decks which are populated with various playing cards. The xml-file looks something like this:

```<code><?xml version="1.0" encoding="utf-8" ?>
<CardCollection>
  <Cards>
    <Deck DeckId="1">
      <Card Id="1">
        <CardElement1></CardElement1>
        <CardElement2></CardElement2>
      </Card>
      <Card Id="2">
        <CardElement1></CardElement1>
        <CardElement2></CardElement2>
      </Card>
      <Card Id="3">
        <CardElement1></CardElement1>
        <CardElement2></CardElement2>
      </Card>
    </Deck>
    <Deck DeckId="2">
      <Card Id="1">
        <CardElement1></CardElement1>
        <CardElement2></CardElement2>
      </Card>
    </Deck>
  </Cards>
</CardCollection>
</code>```

I have a class Card.cs which looks like the following:

```<code>using System.Xml.Serialization;

public class Card {

    [XmlAttribute("Id")]
    public int id;

    [XmlElement("CardElement1")]
    public string cardElement1;

    [XmlElement("CardElement2")]
    public string cardElement2;
}
</code>```

And a class Deck.cs :

using System.Xml.Serialization;

```<code>public class Deck {

    [XmlAttribute("DeckId")]
    public int deckId;

    [XmlArray("Card")]
    public Card[] cards;
}
</code>```

I'm using a class called CardContainer to populate a List decks with this information:

```<code>using System.Collections.Generic;
using System.Xml.Serialization;
using System.IO;
using UnityEngine;

[XmlRoot("CardCollection")]
public class CardContainer {

    [XmlArray("Cards")]
    [XmlArrayItem("Deck")]
    public List<Deck> decks = new List<Deck>();

    public static CardContainer Load(string path)
    {
        TextAsset xml = Resources.Load<TextAsset>(path);

        XmlSerializer serializer = new XmlSerializer(typeof(CardContainer));

        StringReader reader = new StringReader(xml.text);

        CardContainer cards = serializer.Deserialize(reader) as CardContainer;

        reader.Close();

        return cards;
    }

}
</code>```

I can get hold of the Id's of the decks using this snippet of code:

```<code>CardContainer cardContainer = CardContainer.Load(path);
foreach(Deck deck in cardContainer.decks){
       Debug.Log(deck.deckId);
}
</code>```

However I have no idea how to deserialize and populate the Card-array in Deck objects.

答:
I solved it by changing the Deck class to the following:</p>

```<code>using System.Collections.Generic;
using System.Xml.Serialization;

public class Deck {

    [XmlAttribute("DeckId")]
    public int deckId;

    [XmlElement("Card")]
    public List<Card> cards = new List<Card>();
}
</code>```

Body:
I am currently making a game in unity3D. I have a xml document which contains a number of decks which are populated with various playing cards. The xml-file looks something like this:

<?xml version="1.0" encoding="utf-8" ?>
<CardCollection>
  <Cards>
    <Deck DeckId="1">
      <Card Id="1">
        <CardElement1></CardElement1>
        <CardElement2></CardElement2>
      </Card>
      <Card Id="2">
        <CardElement1></CardElement1>
        <CardElement2></CardElement2>
      </Card>
      <Card Id="3">
        <CardElement1></CardElement1>
        <CardElement2></CardElement2>
      </Card>
    </Deck>
    <Deck DeckId="2">
      <Card Id="1">
        <CardElement1></CardElement1>
        <CardElement2></CardElement2>
      </Card>
    </Deck>
  </Cards>
</CardCollection>

I have a class Card.cs which looks like the following:

using System.Xml.Serialization;

public class Card {

    [XmlAttribute("Id")]
    public int id;

    [XmlElement("CardElement1")]
    public string cardElement1;

    [XmlElement("CardElement2")]
    public string cardElement2;
}

And a class Deck.cs :

using System.Xml.Serialization;

public class Deck {

    [XmlAttribute("DeckId")]
    public int deckId;

    [XmlArray("Card")]
    public Card[] cards;
}

I'm using a class called CardContainer to populate a List decks with this information:

using System.Collections.Generic;
using System.Xml.Serialization;
using System.IO;
using UnityEngine;

[XmlRoot("CardCollection")]
public class CardContainer {

    [XmlArray("Cards")]
    [XmlArrayItem("Deck")]
    public List<Deck> decks = new List<Deck>();

    public static CardContainer Load(string path)
    {
        TextAsset xml = Resources.Load<TextAsset>(path);

        XmlSerializer serializer = new XmlSerializer(typeof(CardContainer));

        StringReader reader = new StringReader(xml.text);

        CardContainer cards = serializer.Deserialize(reader) as CardContainer;

        reader.Close();

        return cards;
    }

}

I can get hold of the Id's of the decks using this snippet of code:

CardContainer cardContainer = CardContainer.Load(path);
foreach(Deck deck in cardContainer.decks){
       Debug.Log(deck.deckId);
}

However I have no idea how to deserialize and populate the Card-array in Deck objects.

Body:
I solved it by changing the Deck class to the following:

using System.Collections.Generic;
using System.Xml.Serialization;

public class Deck {

    [XmlAttribute("DeckId")]
    public int deckId;

    [XmlElement("Card")]
    public List<Card> cards = new List<Card>();
}


问:
awk - How to print two parts of one record
I got fields like this one:

```<code>Dagmar Schlecht(ID: 1233), Taubenstr- 246, 71108 Germany, dr_schlecht@t-online-de 1233 Shopping cart #3664 - Grüne Pillen;
</code>```

How Can I print the characters until the first ")" appears in, e.g., $1 and the characters from ~/"Shopping" and 19 chars onward ( so the part "- Grüne Pillen" is being skipped) ?

The outcome shall be written to and new field, e.g. $2:

```<code>Dagmar Schlecht(ID: 1233) Shopping cart #3664
</code>```

答:
sed approach:

```<code>sed -En 's/^([^,]+),.+(Shopping.{11}).*/\1 \2/p' testfile

Dagmar Schlecht(ID: 1233) Shopping cart #3664
</code>```

Body:
I got fields like this one:

Dagmar Schlecht(ID: 1233), Taubenstr- 246, 71108 Germany, dr_schlecht@t-online-de 1233 Shopping cart #3664 - Grüne Pillen;

How Can I print the characters until the first ")" appears in, e.g., $1 and the characters from ~/"Shopping" and 19 chars onward ( so the part "- Grüne Pillen" is being skipped) ?

The outcome shall be written to and new field, e.g. $2:

Dagmar Schlecht(ID: 1233) Shopping cart #3664

Body:
sed approach:

sed -En 's/^([^,]+),.+(Shopping.{11}).*/\1 \2/p' testfile

Dagmar Schlecht(ID: 1233) Shopping cart #3664


问:
Webpage displays differently on different screens
I'm trying to get my website to be display the way that it was designed. I have an iMac but when I view it on a MacBook Pro and my phone, the divs on one of my pages lose their proportions and it's not looking the way it should. Here's the link to my page:http://www.wintonbrownmusic.online/Music%20Site%20Beat%20Making.html

Here's the CSS for my page:

```<code>header, section, footer, aside, nav, main, article, figure {
display: block;
}

ul {
list-style-type: none;
margin: 0;
padding: 0;
text-align: center;
}

a {
display: inline-block;
width: 90px;
text-align: center;
text-decoration: none;
font-family: Gagalin;
color: #404040;
font-size: 20px;
}

li {
width: 100px;
margin: auto;
display: inline;
}

p {
font-family: Arial;
padding-left: 10px;

}

a:hover, a:active {
padding-bottom:8px;
background: transparent;
border-bottom: 3px solid #FA8440;
}

a:active {
color: #FA8440;
}

.newspaper {
-webkit-columns: 100px 3; /* Chrome, Safari, Opera */
-moz-columns: 100px 3; /* Firefox */
columns: 100px 3;
font-family: Arial;
}

h2 {
font-family: Gagalin;
padding-left: 10px;
}

footer {
background-color:black;
color:white;
clear:both;
text-align:center;
padding:5px;
}

.blurb {
margin:5px 0 10px 10px;
width:425px;
height: 230px;
background:#1a1a1a;
border: 6px solid #4d4d4d;
padding: 30px;
float: right;
font-family: Arial;
color: White;
padding-right:50px;
}

.container-fluid {
margin: 0 auto;
margin-left: 0 auto;
width: 65%;
}
</code>```

I could use some assistance on what code I can use to make this page appear the same in all browsers, all pages and even phones.

答:
Its a resolution problem(or cross browser issue) since I see your fixing width and height in ur css.

There are 2 Solutions to ur problem:

make your containers/divs by percentage, even after doing that you may still face some issues.

What I would recommend is scrap existing html and redo it using a styling framework like bootstrap(http://getbootstrap.com/) this would allow you to make your website responsive and it wont break on different browsers.

Body:
I'm trying to get my website to be display the way that it was designed. I have an iMac but when I view it on a MacBook Pro and my phone, the divs on one of my pages lose their proportions and it's not looking the way it should. Here's the link to my page:http://www.wintonbrownmusic.online/Music%20Site%20Beat%20Making.html

Here's the CSS for my page:

header, section, footer, aside, nav, main, article, figure {
display: block;
}

ul {
list-style-type: none;
margin: 0;
padding: 0;
text-align: center;
}

a {
display: inline-block;
width: 90px;
text-align: center;
text-decoration: none;
font-family: Gagalin;
color: #404040;
font-size: 20px;
}

li {
width: 100px;
margin: auto;
display: inline;
}

p {
font-family: Arial;
padding-left: 10px;

}

a:hover, a:active {
padding-bottom:8px;
background: transparent;
border-bottom: 3px solid #FA8440;
}

a:active {
color: #FA8440;
}

.newspaper {
-webkit-columns: 100px 3; /* Chrome, Safari, Opera */
-moz-columns: 100px 3; /* Firefox */
columns: 100px 3;
font-family: Arial;
}

h2 {
font-family: Gagalin;
padding-left: 10px;
}

footer {
background-color:black;
color:white;
clear:both;
text-align:center;
padding:5px;
}

.blurb {
margin:5px 0 10px 10px;
width:425px;
height: 230px;
background:#1a1a1a;
border: 6px solid #4d4d4d;
padding: 30px;
float: right;
font-family: Arial;
color: White;
padding-right:50px;
}

.container-fluid {
margin: 0 auto;
margin-left: 0 auto;
width: 65%;
}

I could use some assistance on what code I can use to make this page appear the same in all browsers, all pages and even phones.


问:
Python Dict Transform
I've been having some strange difficulty trying to transform a dataset that I have.

I currently have a dictionary coming from a form as follows:

```<code>data['content']['answers']
</code>```

I would like to have the ['answers'] appended to the first element of a list like so:

```<code>data['content'][0]['answers']
</code>```

However when I try to create it as so, I get an empty dataset.

```<code>data['content'] = [data['content']['answers']]
</code>```

I can't for the life of me figure out what I am doing wrong.

EDIT: Here is the opening JSON

I have:

```<code>{
"content" : {
              "answers" : {
                "3" : {
</code>```

But I need it to be:

```<code>    {
"content" : [
              {
                 "answers" : {
                  "3" : {
</code>```

thanks

答:
You can do what you want by using a dictionary comprehension (which is one of the most elegant and powerful features in Python.)

In your case, the following should work:

```<code>d = {k:[v] for k,v in d.items()}
</code>```

You mentioned JSON in your question. Rather than rolling your own parser (which it seems like you might be trying to do), consider using the json module.

Title: Python Dict Transform

Body:
I've been having some strange difficulty trying to transform a dataset that I have.

I currently have a dictionary coming from a form as follows:

data['content']['answers']

I would like to have the ['answers'] appended to the first element of a list like so:

data['content'][0]['answers']

However when I try to create it as so, I get an empty dataset.

data['content'] = [data['content']['answers']]

I can't for the life of me figure out what I am doing wrong.

EDIT: Here is the opening JSON

I have:

{
"content" : {
              "answers" : {
                "3" : {

But I need it to be:

    {
"content" : [
              {
                 "answers" : {
                  "3" : {

thanks

Body:
You can do what you want by using a dictionary comprehension (which is one of the most elegant and powerful features in Python.)

In your case, the following should work:

d = {k:[v] for k,v in d.items()}

You mentioned JSON in your question. Rather than rolling your own parser (which it seems like you might be trying to do), consider using the json module.


问:
UNION ALL vs UNPIVOT to change column values into rows
Why would one want to use one method over the other for taking several column values and moving them into rows with a label classifier and a value column?</p>

答:
UNPIVOT is better from a performance perspective because it only scans the rows once.  UNION ALL is going to scan the rows once for every subquery.  In theory, this doesn't have to happen, but I don't know of an optimizer that would only do one scan.

This is particularly important for large tables or if the "table" is really a complex SQL expression or view.


问:
Query temp space limit in Oracle
I want to run a query which takes a lot of temp space. However, I don't want the query to exhaust all the available temp space. How can this be achieved?</p>

答: You can add a resource plan that limits it.</p>

Title: Query temp space limit in Oracle


问:
jquery validate radio buttons
I am not able to get the radio buttons for Gender to register an error.
I have tried several options:

Put the word required inside the <input > tag

Put the class="required" in the input tag

added rule in the validate({rule:{'fb[15]':{required:true}}}

None of these options give an error in the js console, but none trigger an validation error,

if I leave the gender option unselected upon submit.

I have jQuery in the header of the page. I know it is functioning.

```<code><form action="https://example.com" method="post" id="formBuilder" class="formBuilder">
  <p>
    <label for="form-1"><span class="red">*</span> E-Mail Address</label>< br/>
    <input maxlength="255" name="fb[1]" size="50" type="email" id="form-1" required/> <br/>

    <label for="form-2"><span class="red">*</span> Full Name</label> <br/>
    <input maxlength="255" name="fb[2]" size="50" type="text" required id="form-2"/> <br/>

    <label><span class="red">*</span> Gender</label> <br/>
    <input name="fb[15]" type="radio" value="0"  id="form-15-0"/>

    <label for="form-15-0">Male</label>
       <input class="required" name="fb[15]" type="radio" value="1" id="form-15-1"/>

    <label for="form-15-1">Female</label>

    <label for="form-8"><span class="red">*</span> Request</label> <br/>
    <textarea cols="40" name="fb[8]" rows="3" id="form-8" required></textarea> <br/>

    <span><span class="red">*</span>= required information </span>
  </p>

  <span class="buttons">
    <input name="submit" type="submit" value="Submit" id="form-submit"/>
  </p>
</form>

<script src="/wp-includes/js/jquery.validate.min.js"></script>
<script>
$('#formBuilder').validate( );
</script>
</code>```

答:
Try to change your name attribute for radio input to different name for example test without [] so it will be name="test":

and your rules will be :

```<code>$('#formBuilder').validate({
    rules: {
        test: {
            required: true
        }
    }
});
</code>```

Title: jquery validate radio buttons

Body:
I am not able to get the radio buttons for Gender to register an error.
I have tried several options:

Put the word required inside the <input > tag

Put the class="required" in the input tag

added rule in the validate({rule:{'fb[15]':{required:true}}}

None of these options give an error in the js console, but none trigger an validation error,

if I leave the gender option unselected upon submit.

I have jQuery in the header of the page. I know it is functioning.

<form action="https://example.com" method="post" id="formBuilder" class="formBuilder">

    * E-Mail Address

    <input maxlength="255" name="fb[1]" size="50" type="email" id="form-1" required/>

    * Full Name

    <input maxlength="255" name="fb[2]" size="50" type="text" required id="form-2"/>

    * Gender

    <input name="fb[15]" type="radio" value="0"  id="form-15-0"/>

    Male
       <input class="required" name="fb[15]" type="radio" value="1" id="form-15-1"/>

    Female

    * Request

    <textarea cols="40" name="fb[8]" rows="3" id="form-8" required></textarea>

    *= required information

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

</form>

Body:
Try to change your name attribute for radio input to different name for example test without [] so it will be name="test":

and your rules will be :

$('#formBuilder').validate({
    rules: {
        test: {
            required: true
        }
    }
});


问:
How in angular 2 put [attr.ref] dynamically?
Example:

```<code> <app-component *ngFor="let item of list; let i = index" [attr.ref]="i">
 </app-component>
</code>```

How put

```<code><app #idModal></app>
</code>```

where idModal is dynamic and not name static.

答:
You can use a function do to this

```<code><app-component *ngFor="let item of list; let i = index" [attr.ref]="concatenate(i)">
 </app-component>

concatenate(i){
    return '#' + i;
}
</code>```

If you want to have #idModal just modify your function as

```<code>concatenate(i){
        return '#' + i+ 'Modal';
    }
</code>```

Body:
Example:

 <app-component *ngFor="let item of list; let i = index" [attr.ref]="i">
 </app-component>

How put

<app #idModal></app>

where idModal is dynamic and not name static.

Body:
You can use a function do to this

<app-component *ngFor="let item of list; let i = index" [attr.ref]="concatenate(i)">
 </app-component>

concatenate(i){
    return '#' + i;
}

If you want to have #idModal just modify your function as

concatenate(i){
        return '#' + i+ 'Modal';
    }


问:
Is it normal to have a list of objects in an object?
I'm new to OO design, and I wondering whether it is typical to have designs where objects contain lists of other objects. An example is below:

```<code>// Person object containing a list of phone numbers
public class Person
{
    public Guid Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public List<Phone> Contacts { get; set; }

    public void AddPhoneNumber(Phone phone)
    {
        Contacts.Add(phoneNumber);
    }
}

// Phone object
public class Phone
{
    public Guid Id { get; set; }
    public string Name { get; set; }
    public string Number { get; set; }
}

// Example code to establish an object:
Person p1 = new Person();
p1.FirstName = "John";
p1.LastName = "Smith";
p1.AddPhoneNumber(new Phone() { Number = "555957000" });
p1.AddPhoneNumber(new Phone() { Number = "555579561" });
</code>```

Is there a better way to structure this that simplifies the design and allows easier access to the data? Thanks!

答:
I wondering whether it is typical to have designs where objects
  contain lists of other objects.

Absolutely, this is normal as an object can contain lists that belong to only that particular object. One of many examples is when you're traversing a binary tree or such you could have each node have their own list which identifies their children. There are many more cases in which an object should/could contain their own list.

Going back to your code, you seem to have an error because the code below states that the list will contain Phone objects.

```<code>public List<Phone> Contacts { get; set; }
</code>```

but yet you're passing in a string object rather than a phone object.

```<code>public void AddPhoneNumber(string phoneNumber)
{
     Contacts.Add(phoneNumber); // this code shouldnt compile
}
</code>```

rather what you can do is this:

```<code>public void AddPhoneNumber(string phoneNumber)
{
    Contacts.Add(new Phone() { Number = phoneNumber });
}
</code>```

Body:
I'm new to OO design, and I wondering whether it is typical to have designs where objects contain lists of other objects. An example is below:

// Person object containing a list of phone numbers
public class Person
{
    public Guid Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public List<Phone> Contacts { get; set; }

    public void AddPhoneNumber(Phone phone)
    {
        Contacts.Add(phoneNumber);
    }
}

// Phone object
public class Phone
{
    public Guid Id { get; set; }
    public string Name { get; set; }
    public string Number { get; set; }
}

// Example code to establish an object:
Person p1 = new Person();
p1.FirstName = "John";
p1.LastName = "Smith";
p1.AddPhoneNumber(new Phone() { Number = "555957000" });
p1.AddPhoneNumber(new Phone() { Number = "555579561" });

Is there a better way to structure this that simplifies the design and allows easier access to the data? Thanks!

Body:
I wondering whether it is typical to have designs where objects
  contain lists of other objects.

Absolutely, this is normal as an object can contain lists that belong to only that particular object. One of many examples is when you're traversing a binary tree or such you could have each node have their own list which identifies their children. There are many more cases in which an object should/could contain their own list.

Going back to your code, you seem to have an error because the code below states that the list will contain Phone objects.

public List<Phone> Contacts { get; set; }

but yet you're passing in a string object rather than a phone object.

public void AddPhoneNumber(string phoneNumber)
{
     Contacts.Add(phoneNumber); // this code shouldnt compile
}

rather what you can do is this:

public void AddPhoneNumber(string phoneNumber)
{
    Contacts.Add(new Phone() { Number = phoneNumber });
}


问:
Checking properties on different classes
I have multiple classes that all contain the same property along with a whole of different other properties. The classes don't use any kind of Interface. What I would like to do is pass an instance of each class to a method that can check for the property.

Can generics be used for this? If so, how can I construct a method to perform this task?

答:
Well, you could use reflection... but it would be better to use an interface which specified the property, then you could make each class implement the interface. Generics won't help you here - there's no way of specifying "T must be a type which has property X" for example.

If you're using C# 4 you could use dynamic typing:

```<code>public void Foo(dynamic d)
{
    Console.WriteLine(d.MyProperty);
}
</code>```

However, I would advise you to try to use static typing (via interfaces) if at all possible.

Body:
Well, you could use reflection... but it would be better to use an interface which specified the property, then you could make each class implement the interface. Generics won't help you here - there's no way of specifying "T must be a type which has property X" for example.

If you're using C# 4 you could use dynamic typing:

public void Foo(dynamic d)
{
    Console.WriteLine(d.MyProperty);
}

However, I would advise you to try to use static typing (via interfaces) if at all possible.


问:
How to run one-off python script on Heroku
I have a Django app up and running on Heroku. I want to run a simple script called import.py, which imports a CSV file into my models. It works great on my local computer. When I try to run the script on Heroku using this commmand:

```<code>heroku run python manage.py < import.py
</code>```

All it does is read the script back to me, but not execute any of the content. What am I doing wrong?

Edit:

This is the start of the result I get when I run: heroku run python manage.py < import.py

```<code>Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> import csv
>>> from bah_api.models import withDependents, withOutDependents, ZipMHA
>>>
>>> # Populate CSV file into model
>>> def LoadCSV(file_location, my_model, delim):
... f = open(file_location)
  File "<console>", line 2
    f = open(file_location)
    ^
IndentationError: expected an indented block
>>> csv_f = csv.reader(f, delimiter=delim)
Traceback (most recent call last):
  File "<console>", line 1, in <module>
NameError: name 'f' is not defined
>>> for row in csv_f:
...
Display all 182 possibilities? (y or n)
</code>```

答:
You can use the django-extensions runscript command. This command allows you to run python scripts in the Django context via manage.py:

```<code>python manage.py runscript my_script
</code>```

To do this with Heroku:

Install django-extensions and make sure it's in your requirements.txt

pip install django-extensions

pip freeze > requirements.txt

Create a scripts directory as described in the documentation

Deploy to Heroku

Run it on Heroku with heroku run

heroku run python manage.py runscript my_script

Note: don't append a .py to your script name in the above command

And off you go!

Body:
I have a Django app up and running on Heroku. I want to run a simple script called import.py, which imports a CSV file into my models. It works great on my local computer. When I try to run the script on Heroku using this commmand:

heroku run python manage.py < import.py

All it does is read the script back to me, but not execute any of the content. What am I doing wrong?

Edit:

This is the start of the result I get when I run: heroku run python manage.py < import.py

Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> import csv
>>> from bah_api.models import withDependents, withOutDependents, ZipMHA
>>>
>>> # Populate CSV file into model
>>> def LoadCSV(file_location, my_model, delim):
... f = open(file_location)
  File "<console>", line 2
    f = open(file_location)
    ^
IndentationError: expected an indented block
>>> csv_f = csv.reader(f, delimiter=delim)
Traceback (most recent call last):
  File "<console>", line 1, in <module>
NameError: name 'f' is not defined
>>> for row in csv_f:
...
Display all 182 possibilities? (y or n)

Body:
You can use the django-extensions runscript command. This command allows you to run python scripts in the Django context via manage.py:

python manage.py runscript my_script

To do this with Heroku:

Install django-extensions and make sure it's in your requirements.txt

pip install django-extensions

pip freeze > requirements.txt

Create a scripts directory as described in the documentation

Deploy to Heroku

Run it on Heroku with heroku run

heroku run python manage.py runscript my_script

Note: don't append a .py to your script name in the above command

And off you go!


问:
Css Hack Issue In Safari
I tried this below code but still it is working on both Safari & Chrome.

Please let me know a hack only for Safari not Chrome

```<code>.contactDiv img:not(:root:root) {
    margin-top:-75px;
}

@media screen and (-webkit-min-device-pixel-ratio:0) {
    .contactDiv img{
         margin-top:-75px;
    }
}
</code>```

Both are working on Chrome as well as Safari but I want that only on Safari.

答:
This hack is going to work only on Safari:</p>
```<code>_::-webkit-full-page-media, _:future, :root .contactDiv img {   margin-top:-75px; }
</code>```

Title: Css Hack Issue In Safari

Body:
I tried this below code but still it is working on both Safari & Chrome.

Please let me know a hack only for Safari not Chrome

.contactDiv img:not(:root:root) {
    margin-top:-75px;
}

@media screen and (-webkit-min-device-pixel-ratio:0) {
    .contactDiv img{
         margin-top:-75px;
    }
}

Both are working on Chrome as well as Safari but I want that only on Safari.

Body:
This hack is going to work only on Safari:

_::-webkit-full-page-media, _:future, :root .contactDiv img {   margin-top:-75px; }

ContentLicense: CC BY-SA 4.0


问:
Why do properties have to be class attributes in Python?
Recently I have been learning about managed attributes in Python and a common theme with properties and descriptors is, that they have to be assigned as class attributes. But nowhere can I find an explanation of why and especially why they cannot be assigned as instance attributes. So my question has actually two parts:

why do properties / descriptor instances have to be class attributes?

why can properties / descriptor instances not be instance attributes?

答:
why do properties/descriptor instances have to be class attributes?

They don't have to be, they just are. This was a design decision that probably has many more reasons to back it up than I can think (simplifying implementation, separating classes from objects).

why can properties/descriptor instances not be instance attributes?

They could be, you can always override __getattribute__ in order to invoke any descriptors accessed on an instance or forbid them altogether if you desire.

Keep in mind that the fact that Python won't stop you from doing this doesn't mean it's a good idea.


问:
Test API Grails
I try to get JSON from URL at HTTPBuilder, but this code return an Exception, return this erro "Method threw 'groovy.lang.MissingPropertyException' exception."</p>

```<code>static request(String path, boolean isGet){
    def myClient = new HTTPBuilder("${HOST}${path}")
    def jsonResp = [:]

    try{
        if(isGet){
            log.info "[EXAMPLE GET] ${HOST}${path}"
            myClient.get(requestContentType: ContentType.JSON){ resp, json ->
                jsonResp = resp
            }
        }
    }catch(Exception e){
        println "erro: "
        log.info "[EXAMPLE ERROR]: ${e.message}"
        println(e.message)
    }
    jsonResp
}
</code>```

答:
What's the MissingPropertyException on?

I tried your example in a script (with a few mods), this time returning json rather than resp which seems to work.

```<code>import groovy.transform.Field
import groovyx.net.http.ContentType
import groovyx.net.http.HTTPBuilder

@Field final String HOST = 'http://echo.jsontest.com'

def resp = request( "/name/jon", true )
println resp.toString()

def request(String path, boolean isGet){

    def myClient = new HTTPBuilder("${HOST}${path}")
    def jsonResp = [:]

    try{
        if(isGet){
            println  "[EXAMPLE GET] ${HOST}${path}"
            myClient.get(requestContentType: ContentType.JSON){ resp, json ->
            jsonResp = json
        }
    }
}
catch(Exception e) {
      println(e.message)
    }
    jsonResp
</code>```

}

Output is:

```<code>{"name":"jon"}
</code>```

Title: Test API Grails

Body:
I try to get JSON from URL at HTTPBuilder, but this code return an Exception, return this erro "Method threw 'groovy.lang.MissingPropertyException' exception."

static request(String path, boolean isGet){
    def myClient = new HTTPBuilder("${HOST}${path}")
    def jsonResp = [:]

    try{
        if(isGet){
            log.info "[EXAMPLE GET] ${HOST}${path}"
            myClient.get(requestContentType: ContentType.JSON){ resp, json ->
                jsonResp = resp
            }
        }
    }catch(Exception e){
        println "erro: "
        log.info "[EXAMPLE ERROR]: ${e.message}"
        println(e.message)
    }
    jsonResp
}

Body:
What's the MissingPropertyException on?

I tried your example in a script (with a few mods), this time returning json rather than resp which seems to work.

import groovy.transform.Field
import groovyx.net.http.ContentType
import groovyx.net.http.HTTPBuilder

@Field final String HOST = 'http://echo.jsontest.com'

def resp = request( "/name/jon", true )
println resp.toString()

def request(String path, boolean isGet){

    def myClient = new HTTPBuilder("${HOST}${path}")
    def jsonResp = [:]

    try{
        if(isGet){
            println  "[EXAMPLE GET] ${HOST}${path}"
            myClient.get(requestContentType: ContentType.JSON){ resp, json ->
            jsonResp = json
        }
    }
}
catch(Exception e) {
      println(e.message)
    }
    jsonResp

}

Output is:

{"name":"jon"}


问:
PHP array search
I'm trying to add some quick and simple search functionality to a site. The site has an XML file with all their stores, and I want to create a search box to search for the closest store to the user by town or postcode.

I have put all the data into an array, but as far as I can tell, there is no way to 'search' an array (NOT array_search) to retrieve results like using a MySQL LIKE query.

Surely there must be a way? Using MySQL isn't an option in this case.

答:
You could try something like this:</p>

```<code>$q = $_GET['search'];

$file = new DOMDocument();
$file->load("filename.xml");

$xml = simplexml_import_dom($file);
foreach($xml->store as $store)
{
  $store_name = $store->name;
  if($q == $store_name)
  {
    //query in your database
  }
}
</code>```

Title: PHP array search

Body:
You could try something like this:

$q = $_GET['search'];

$file = new DOMDocument();
$file->load("filename.xml");

$xml = simplexml_import_dom($file);
foreach($xml->store as $store)
{
  $store_name = $store->name;
  if($q == $store_name)
  {
    //query in your database
  }
}


问:
Getting a variable from a class
So I have a class called Buildings which  creates 7 building objects and adds them to an ArrayList of type building:

```<code>package model;

import java.util.ArrayList;

/**
 *
 * @author dominic
 */
public class Buildings {
    private ArrayList<Building> buildingList = new ArrayList<Building>();

    public ArrayList<Building> getBuildingList() {
        return buildingList;
    }

    public void setBuildingList(ArrayList<Building> buildingList) {
        this.buildingList = buildingList;
    }

    public Buildings(){
        Building building1 = new Building("Kingston University","Penrhyn Road","KT1 2EE");
        buildingList.add(building1);
          Building building2 = new Building("Guild of Students","Penrhyn Road","KT1 2EE");
        buildingList.add(building2);
          Building building3 = new Building("Kingston University Health Centre","Penrhyn Road","KT1 2EE");
        buildingList.add(building3);
          Building building4 = new Building("Knights Park Centre","Grange Road","KT1 2QJ");
        buildingList.add(building4);
          Building building5 = new Building("Roehampton Vale","Friars Avenue","SW15 5DW");
        buildingList.add(building5);
          Building building6 = new Building("Kingston Law School","Kingston Hill","KT2 7LB");
        buildingList.add(building6);
          Building building7 = new Building("Kingston Business School","Kingston Hill","KT2 7LB");
        buildingList.add(building7);
    }

}
</code>```

The building class looks like this on the inside:

```<code>package model;

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author dominic
 */
public class Building {
    private String buildingName;
    private String streetName;
    private String postcode;

    public Building(String buildingName, String streetName, String postcode){
    this.buildingName = buildingName;
    this.streetName = streetName;
    this.postcode = postcode;
    }
    public String getBuildingName() {
        return buildingName;
    }

    public void setBuildingName(String buildingName) {
        this.buildingName = buildingName;
    }

    public String getStreetName() {
        return streetName;
    }

    public void setStreetName(String streetName) {
        this.streetName = streetName;
    }

    public String getPostcode() {
        return postcode;
    }

    public void setPostcode(String postcode) {
        this.postcode = postcode;
    }

}
</code>```

And I have a for loop elsewhere in my project (in a servlet) that creates the object buildings and loops through each object and compares them to user input. I have tested to make sure the program was actually getting user input and it is. However, the string streetName and postCode are still empty. Thank you.

```<code>  HttpSession session = request.getSession();
    Integer id = (Integer)session.getAttribute("id");
     Buildings buildings = new Buildings();
       String streetName = "";
   String postCode = "";
   String postCodeInput = request.getParameter("postCodeInput");
    for(int i = 0; i > 6; i++)
    {

        if (postCodeInput == buildings.getBuildingList().get(i).getPostcode())
        {
            streetName = buildings.getBuildingList().get(i).getStreetName();
            postCode = buildings.getBuildingList().get(i).getPostcode();

        }

    }

          request.setAttribute("streetName", streetName);
    request.setAttribute("postCode", postCode);
          request.setAttribute("postCodeInput", postCodeInput);
    request.getRequestDispatcher("StreetNameView.jsp").forward(request, response);
</code>```

答:
```<code>for(int i = 0; i > 6; i++)
</code>```

That should be <.

```<code>for(int i = 0; i < 6; i++)
</code>```

Better yet, iterate over the list items directly, instead of by index.

```<code>for (Building building: buildings.getBuildingList())
{
    if (postCodeInput == building.getPostcode())
    {
        streetName = building.getStreetName();
        postCode   = building.getPostcode();

        break;
    }
}
</code>```

You could even use Java 8 streams to do the matching.

```<code>Building building = buildings.getBuildingList().stream()
    .filter(b -> b.getPostcode() == postCodeInput)
    .findAny()
    .orElseThrow(NoSuchElementException::new);

request.setAttribute("streetName", building.getStreetName());
request.setAttribute("postCode",   building.getPostcode());
</code>```

Title: Getting a variable from a class

Body:
So I have a class called Buildings which  creates 7 building objects and adds them to an ArrayList of type building:

package model;

import java.util.ArrayList;

/**
 *
 * @author dominic
 */
public class Buildings {
    private ArrayList<Building> buildingList = new ArrayList<Building>();

    public ArrayList<Building> getBuildingList() {
        return buildingList;
    }

    public void setBuildingList(ArrayList<Building> buildingList) {
        this.buildingList = buildingList;
    }

    public Buildings(){
        Building building1 = new Building("Kingston University","Penrhyn Road","KT1 2EE");
        buildingList.add(building1);
          Building building2 = new Building("Guild of Students","Penrhyn Road","KT1 2EE");
        buildingList.add(building2);
          Building building3 = new Building("Kingston University Health Centre","Penrhyn Road","KT1 2EE");
        buildingList.add(building3);
          Building building4 = new Building("Knights Park Centre","Grange Road","KT1 2QJ");
        buildingList.add(building4);
          Building building5 = new Building("Roehampton Vale","Friars Avenue","SW15 5DW");
        buildingList.add(building5);
          Building building6 = new Building("Kingston Law School","Kingston Hill","KT2 7LB");
        buildingList.add(building6);
          Building building7 = new Building("Kingston Business School","Kingston Hill","KT2 7LB");
        buildingList.add(building7);
    }

}

The building class looks like this on the inside:

package model;

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author dominic
 */
public class Building {
    private String buildingName;
    private String streetName;
    private String postcode;

    public Building(String buildingName, String streetName, String postcode){
    this.buildingName = buildingName;
    this.streetName = streetName;
    this.postcode = postcode;
    }
    public String getBuildingName() {
        return buildingName;
    }

    public void setBuildingName(String buildingName) {
        this.buildingName = buildingName;
    }

    public String getStreetName() {
        return streetName;
    }

    public void setStreetName(String streetName) {
        this.streetName = streetName;
    }

    public String getPostcode() {
        return postcode;
    }

    public void setPostcode(String postcode) {
        this.postcode = postcode;
    }

}

And I have a for loop elsewhere in my project (in a servlet) that creates the object buildings and loops through each object and compares them to user input. I have tested to make sure the program was actually getting user input and it is. However, the string streetName and postCode are still empty. Thank you.

  HttpSession session = request.getSession();
    Integer id = (Integer)session.getAttribute("id");
     Buildings buildings = new Buildings();
       String streetName = "";
   String postCode = "";
   String postCodeInput = request.getParameter("postCodeInput");
    for(int i = 0; i > 6; i++)
    {

        if (postCodeInput == buildings.getBuildingList().get(i).getPostcode())
        {
            streetName = buildings.getBuildingList().get(i).getStreetName();
            postCode = buildings.getBuildingList().get(i).getPostcode();

        }

    }

          request.setAttribute("streetName", streetName);
    request.setAttribute("postCode", postCode);
          request.setAttribute("postCodeInput", postCodeInput);
    request.getRequestDispatcher("StreetNameView.jsp").forward(request, response);

Body:
for(int i = 0; i > 6; i++)

That should be <.

for(int i = 0; i < 6; i++)

Better yet, iterate over the list items directly, instead of by index.

for (Building building: buildings.getBuildingList())
{
    if (postCodeInput == building.getPostcode())
    {
        streetName = building.getStreetName();
        postCode   = building.getPostcode();

        break;
    }
}

You could even use Java 8 streams to do the matching.

Building building = buildings.getBuildingList().stream()
    .filter(b -> b.getPostcode() == postCodeInput)
    .findAny()
    .orElseThrow(NoSuchElementException::new);

request.setAttribute("streetName", building.getStreetName());
request.setAttribute("postCode",   building.getPostcode());


问:
primefaces inputMask for ip address
I'm looking to do an inputMask for an ip address.

Currently I have this code:

```<code><p:inputMask value="#{newNode.ipv4}" mask="999.999.999.999">
       <p:keyFilter mask="num" />
</p:inputMask>
</code>```

So I can enter un num value between 000.000.000.000 to 999.999.999.999 but I would like to restrict the input to 255.255.255.255, do you know a way to do this?

Thanks,
Ersch

答:
Here you go:</p>

```<code><p:inputMask value="#{newNode.ipv4}"
        mask="999.999.999.999"
        validatorMessage="Invalid IPv4 Address">
    <f:validateRegex pattern="\b((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\.|$)){4}\b"/>
</p:inputMask>
</code>```

Title: primefaces inputMask for ip address

Body:
I'm looking to do an inputMask for an ip address.

Currently I have this code:

So I can enter un num value between 000.000.000.000 to 999.999.999.999 but I would like to restrict the input to 255.255.255.255, do you know a way to do this?

Thanks,
Ersch

Body:
Here you go:

<p:inputMask value="#{newNode.ipv4}"
        mask="999.999.999.999"
        validatorMessage="Invalid IPv4 Address">
    <f:validateRegex pattern="\b((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\.|$)){4}\b"/>
</p:inputMask>


问:
wordpress template layout single.php
I need to custom single.php template in my wordpress template.
In my single.php I have this line

My new template need to show post image, post date, post text.

How I can do it?

Thanks

答:
Google could have easily told you how this is done, but because I'm here I will help.

First, learn the WordPress Loop.

Open your single.php template and paste the following:

```<code><?php
    if ( have_posts() ) {
        while ( have_posts() ) {
            the_post();

            // Post Image
            the_post_thumbnail();

            // Post Date
            the_date();

            // The Post Content
            the_content();

        } // end while
    } // end if
?>
</code>```

Then read up on the functions used:

the_post_thumbnail()

the_date()

the_content()

Title: wordpress template layout single.php

Body:
Google could have easily told you how this is done, but because I'm here I will help.

First, learn the WordPress Loop.

Open your single.php template and paste the following:

<?php
    if ( have_posts() ) {
        while ( have_posts() ) {
            the_post();

            // Post Image
            the_post_thumbnail();

            // Post Date
            the_date();

            // The Post Content
            the_content();

        } // end while
    } // end if
?>

Then read up on the functions used:

the_post_thumbnail()

the_date()

the_content()


问:
how to 3-way outer product in numpy?
About the numpy.outer [link] .

Given two vectors, a = [a0, a1, ..., aM] and b = [b0, b1, ..., bN], the outer product will be M*N matrix.

But how to implement a 3-array outer product, which means : given
third vector c = [c0, c1, ..., cP], how to get the outer product
between the 3 numpy arrays.

and how to get n-way outer product for n-array in numpy, for the method of einsum, how to change 'i,j,k->ijk'  to process "n" .

答:
The direct way of doing this, taking full advantage of broadcasting is:

```<code>a[:,None,None] * b[None,:,None] * c[None,None,:]
</code>```

np.ix_ does this reshaping for you, at a modest cost in speed

```<code>In [919]: np.ix_(a,b,c)
Out[919]:
(array([[[0]],

        [[1]],

        [[2]],

        [[3]],

        [[4]]]), array([[[10],
         [11],
         [12],
         [13]]]), array([[[20, 21, 22]]]))
</code>```

and the resulting arrays can be multiplied with

```<code>np.prod(np.ix_(a,b,c))
</code>```

The einsum version is simple, and fast

```<code>np.einsum('i,j,k',a,b,c)
</code>```

It's a good idea to learn all 3 methods.

The problem with nesting outer is that expects the inputs to be 1d, or it flattens them.  It can be used, but needs some reshaping

```<code>np.outer(a,np.outer(b,c)).reshape(a.shape[0],b.shape[0],c.shape[0])
</code>```

Title: how to 3-way outer product in numpy?

Body:
The direct way of doing this, taking full advantage of broadcasting is:

a[:,None,None] * b[None,:,None] * c[None,None,:]

np.ix_ does this reshaping for you, at a modest cost in speed

In [919]: np.ix_(a,b,c)
Out[919]:
(array([[[0]],

        [[1]],

        [[2]],

        [[3]],

        [[4]]]), array([[[10],
         [11],
         [12],
         [13]]]), array([[[20, 21, 22]]]))

and the resulting arrays can be multiplied with

np.prod(np.ix_(a,b,c))

The einsum version is simple, and fast

np.einsum('i,j,k',a,b,c)

It's a good idea to learn all 3 methods.

The problem with nesting outer is that expects the inputs to be 1d, or it flattens them.  It can be used, but needs some reshaping

np.outer(a,np.outer(b,c)).reshape(a.shape[0],b.shape[0],c.shape[0])


问:
Put multiple rows of a gridview into edit mode
I have the need to allow a user to "tab through" making edits on a gridview.  There will be one editable column in the row data. The user should be able to hit tab and go to the next row to edit said column.

I have not found any easy method to accomplish this task.  I found a way to programmatically put a gridview into edit mode, but in testing the code below it works for only 1 row at a time.

```<code>        reviewTransferGV.EditIndex = 0;
        reviewTransferGV.Rows[0].RowState = DataControlRowState.Edit;
        reviewTransferGV.EditIndex = 1;
        reviewTransferGV.Rows[1].RowState = DataControlRowState.Edit;
        reviewTransferGV.DataBind();
</code>```

答: I don't believe it is possible for a GridView to have multiple rows in edit mode simultaneously. If you want to edit multiple rows, you will need to roll your own mechanism to do so.</p>

Body:
I have the need to allow a user to "tab through" making edits on a gridview.  There will be one editable column in the row data. The user should be able to hit tab and go to the next row to edit said column.

I have not found any easy method to accomplish this task.  I found a way to programmatically put a gridview into edit mode, but in testing the code below it works for only 1 row at a time.

        reviewTransferGV.EditIndex = 0;
        reviewTransferGV.Rows[0].RowState = DataControlRowState.Edit;
        reviewTransferGV.EditIndex = 1;
        reviewTransferGV.Rows[1].RowState = DataControlRowState.Edit;
        reviewTransferGV.DataBind();


问:
Passing arguments to functions with const parameters: is it faster?
Consider, for example:

```<code>int sum(int a, int b)
{
    return a + b;
}
</code>```

vs.

```<code>int sum(const int a, const int b)
{
    return a + b;
}
</code>```

Is the second approach in general faster?

Function parameters in C are copied and sent to the function, so that changes inside the function do not affect the original values. My reasoning is that in the second sum above, the compiler knows for sure that a and b are not modified inside the function, so it can just pass the original values without copying them first. That's why I think the second sum is faster than the first. But I don't really know. In the particular simple example of sum above, the differences, if any, should be minimal.

Edit: The sum example is just to illustrate my point. I don't expect that in this particular example there should be large differences. But I wonder if in more complicated situations the const modifier inside a function parameter can be exploited by the compiler to make the function faster. I doubt that the compiler can always determine whether a parameter is changed inside a function (hence my 2nd question below); hence I'd expect that when it finds a const modifier, it does something different than when there's no const modifier.

Question: In general, a function will be faster when its arguments are const, than when they are not?

Question 2: In general, can a C compiler (theoretically) always determine whether a function parameter is changed inside the function?

答:
Although late to the party, a compiler could put variables defined as const in a read-only memory segment/block, so that if an attempt was made to write to the address, via some pointer tomfoolery, the write to the memory would trigger an exception at runtime.

-- Jamey

Body:
Consider, for example:

int sum(int a, int b)
{
    return a + b;
}

vs.

int sum(const int a, const int b)
{
    return a + b;
}

Is the second approach in general faster?

Function parameters in C are copied and sent to the function, so that changes inside the function do not affect the original values. My reasoning is that in the second sum above, the compiler knows for sure that a and b are not modified inside the function, so it can just pass the original values without copying them first. That's why I think the second sum is faster than the first. But I don't really know. In the particular simple example of sum above, the differences, if any, should be minimal.

Edit: The sum example is just to illustrate my point. I don't expect that in this particular example there should be large differences. But I wonder if in more complicated situations the const modifier inside a function parameter can be exploited by the compiler to make the function faster. I doubt that the compiler can always determine whether a parameter is changed inside a function (hence my 2nd question below); hence I'd expect that when it finds a const modifier, it does something different than when there's no const modifier.

Question: In general, a function will be faster when its arguments are const, than when they are not?

Question 2: In general, can a C compiler (theoretically) always determine whether a function parameter is changed inside the function?


问:
Select Effectiveness for every user
I have table storing every bet that user makes on a website. According to my question there are only 2 important columns:

```<code>+--------+--------+
| userid | status |
+--------+--------+
|      2 |      0 |
|      2 |      1 |
|      2 |      1 |
|      6 |      1 |
|      6 |      1 |
+--------+--------+
</code>```

I want to calculate percentage of won bets for every user.
0 means lost.
1 means won.

So obviously percentage will be won bets/all bets.

I tried to do it by below query, but it doesn't work like it should be.

```<code>SELECT userid,(
(select count(id) as count_won from bets where status=1)
/
(select count(id) as count_all from bets where status!=-1)) * 100 as percent FROM bets group by userid;
</code>```

I'm getting result:

```<code>+--------+---------+
| userid | percent |
+--------+---------+
|      2 | 80.0000 |
|      6 | 80.0000 |
+--------+---------+
</code>```

It's counting all bets percentage. How i can make calculation for every user?

I know i can add WHERE clause with userid, but i don't want to do this, because after calculations i want to simply order results by percentage.

Does anyone can help me a little bit?

答:
Something like this might be helpful for you,</p>

```<code>SELECT USERID
  , (COALESCE(SUM(CASE WHEN STATUS = 1 THEN 1 END), 0) / COUNT(*)) * 100 STATUS1_PER
  , (COALESCE(SUM(CASE WHEN STATUS = 0 THEN 1 END), 0) / COUNT(*)) * 100 STATUS0_PER
FROM
MY_TABLE1
GROUP BY USERID;
</code>```

Title: Select Effectiveness for every user

Body:
I have table storing every bet that user makes on a website. According to my question there are only 2 important columns:

+--------+--------+
| userid | status |
+--------+--------+
|      2 |      0 |
|      2 |      1 |
|      2 |      1 |
|      6 |      1 |
|      6 |      1 |
+--------+--------+

I want to calculate percentage of won bets for every user.
0 means lost.
1 means won.

So obviously percentage will be won bets/all bets.

I tried to do it by below query, but it doesn't work like it should be.

SELECT userid,(
(select count(id) as count_won from bets where status=1)
/
(select count(id) as count_all from bets where status!=-1)) * 100 as percent FROM bets group by userid;

I'm getting result:

+--------+---------+
| userid | percent |
+--------+---------+
|      2 | 80.0000 |
|      6 | 80.0000 |
+--------+---------+

It's counting all bets percentage. How i can make calculation for every user?

I know i can add WHERE clause with userid, but i don't want to do this, because after calculations i want to simply order results by percentage.

Does anyone can help me a little bit?

Body:
Something like this might be helpful for you,

SELECT USERID
  , (COALESCE(SUM(CASE WHEN STATUS = 1 THEN 1 END), 0) / COUNT(*)) * 100 STATUS1_PER
  , (COALESCE(SUM(CASE WHEN STATUS = 0 THEN 1 END), 0) / COUNT(*)) * 100 STATUS0_PER
FROM
MY_TABLE1
GROUP BY USERID;


问:
Is it possible to make a real function type in C++ which is callable with itself?
I am trying to write recursion without referencing the function name in C++ by means of Y-combinator. However, I can't figure out the type of the Function in the following attempt:

```<code>#include <iostream>

using std::cin;
using std::cout;

template<class Function> unsigned long factorial1(Function self, unsigned long n) {
    return n ? n * self(self, n - 1) : 1;
}

unsigned long factorial(unsigned long n) {
    return factorial1(factorial1, n);
}

int main() {
    unsigned long n;
    cin >> n;
    cout << factorial(n) << '\n';
    return 0;
}
</code>```

The compiler cannot deduce what is Function, neither can me. Then I tried the following:

```<code>#include <iostream>

using std::cin;
using std::cout;

struct Factorial {
    template<class Function> unsigned long operator()(Function self, unsigned long n) const {
        return n ? n * self(self, n - 1) : 1;
    }
};

unsigned long factorial(unsigned long n) {
    return Factorial()(Factorial(), n);
}

int main() {
    unsigned long n;
    cin >> n;
    cout << factorial(n) << '\n';
    return 0;
}
</code>```

This, when compared to the above example, the difference is I changed the work function to a callable object, which Function is deduced easily as Factorial, leading to the following complete implementation of the combinator:

```<code>#include <iostream>

using std::cin;
using std::cout;

struct Factorial {
    template<class Function> unsigned long operator()(Function self, unsigned long n) const {
        return n ? n * self(self, n - 1) : 1;
    }
};

template<class Function> auto y(Function f) {
    return [f](auto n) {
        return f(f, n);
    };
}

int main() {
    unsigned long n;
    cin >> n;
    cout << y(Factorial())(n) << '\n';
    return 0;
}
</code>```

The question is that, is it possible to rewrite the struct Factorial to a plain function?

答:
The case you are describing looks to me as something like an infinite type or recursive type. You can see that it is infinite if you try to deduce the type manually by yourself, which you probably discovered by yourself as well. To show that, I want to simplify your factorial1 function into:

```<code>template <class T> void foobar(T self) {
    self(self);
}
</code>```

and then try to write this function with function pointer instead of templates, to manually deduce its type.

First, we want that foobar takes a function pointer as argument.

```<code>void foobar(void (*self)());
            ^^^^^^^^^^^^^^
</code>```

But that's still not exactly what we want, this function pointer should take as an argument a pointer to itself.

```<code>void foobar(void (*self)(void (*)()));
                         ^^^^^^^^^^
</code>```

But again we are not finished, because we have to add a pointer to itself as an argument again

```<code>void foobar(void (*self)(void (*)(void (*)())));
                                  ^^^^^^^^^^
</code>```

You can see the pattern how it goes on and on.

```<code>void foobar(void (*self)(void (*)(void (*)(void (*)()))));
                                           ^^^^^^^^^^

void foobar(void (*self)(void (*)(void (*)(void (*)(void (*)())))));
                                                    ^^^^^^^^^^
</code>```

The examples you gave, where you managed to do that with a struct, is just something that mimics it through operator(). If you change the name of that function to foobar it looks like that:

```<code>struct Factorial {
    template<class Function> unsigned long foobar(Function self, unsigned long n) const {
        return n ? n * self.foobar(self, n - 1) : 1;
    }
};

unsigned long factorial(unsigned long n) {
    return Factorial().foobar(Factorial(), n);
}
</code>```

So you basically call foobar recursively in foobar, which contradicts your initial statement, that you want to call the function without knowing / referencing its name.

Body:
I am trying to write recursion without referencing the function name in C++ by means of Y-combinator. However, I can't figure out the type of the Function in the following attempt:

#include <iostream>

using std::cin;
using std::cout;

template<class Function> unsigned long factorial1(Function self, unsigned long n) {
    return n ? n * self(self, n - 1) : 1;
}

unsigned long factorial(unsigned long n) {
    return factorial1(factorial1, n);
}

int main() {
    unsigned long n;
    cin >> n;
    cout << factorial(n) << '\n';
    return 0;
}

The compiler cannot deduce what is Function, neither can me. Then I tried the following:

#include <iostream>

using std::cin;
using std::cout;

struct Factorial {
    template<class Function> unsigned long operator()(Function self, unsigned long n) const {
        return n ? n * self(self, n - 1) : 1;
    }
};

unsigned long factorial(unsigned long n) {
    return Factorial()(Factorial(), n);
}

int main() {
    unsigned long n;
    cin >> n;
    cout << factorial(n) << '\n';
    return 0;
}

This, when compared to the above example, the difference is I changed the work function to a callable object, which Function is deduced easily as Factorial, leading to the following complete implementation of the combinator:

#include <iostream>

using std::cin;
using std::cout;

struct Factorial {
    template<class Function> unsigned long operator()(Function self, unsigned long n) const {
        return n ? n * self(self, n - 1) : 1;
    }
};

template<class Function> auto y(Function f) {
    return [f](auto n) {
        return f(f, n);
    };
}

int main() {
    unsigned long n;
    cin >> n;
    cout << y(Factorial())(n) << '\n';
    return 0;
}

The question is that, is it possible to rewrite the struct Factorial to a plain function?

Body:
The case you are describing looks to me as something like an infinite type or recursive type. You can see that it is infinite if you try to deduce the type manually by yourself, which you probably discovered by yourself as well. To show that, I want to simplify your factorial1 function into:

template <class T> void foobar(T self) {
    self(self);
}

and then try to write this function with function pointer instead of templates, to manually deduce its type.

First, we want that foobar takes a function pointer as argument.

void foobar(void (*self)());
            ^^^^^^^^^^^^^^

But that's still not exactly what we want, this function pointer should take as an argument a pointer to itself.

void foobar(void (*self)(void (*)()));
                         ^^^^^^^^^^

But again we are not finished, because we have to add a pointer to itself as an argument again

void foobar(void (*self)(void (*)(void (*)())));
                                  ^^^^^^^^^^

You can see the pattern how it goes on and on.

void foobar(void (*self)(void (*)(void (*)(void (*)()))));
                                           ^^^^^^^^^^

void foobar(void (*self)(void (*)(void (*)(void (*)(void (*)())))));
                                                    ^^^^^^^^^^

The examples you gave, where you managed to do that with a struct, is just something that mimics it through operator(). If you change the name of that function to foobar it looks like that:

struct Factorial {
    template<class Function> unsigned long foobar(Function self, unsigned long n) const {
        return n ? n * self.foobar(self, n - 1) : 1;
    }
};

unsigned long factorial(unsigned long n) {
    return Factorial().foobar(Factorial(), n);
}

So you basically call foobar recursively in foobar, which contradicts your initial statement, that you want to call the function without knowing / referencing its name.


问:
python 3 regex - find all overlapping matches' start and end index in a string
This was my original approach:

```<code>string = '1'*15
result = re.finditer(r'(?=11111)', string)      # overlapped = True
                                                # Doesn't work for me
for i in result:                                # python 3.5
   print(i.start(), i.end())
</code>```

It finds all overlapping matches, but fails to get the right end index.
The output:

```<code>1 <_sre.SRE_Match object; span=(0, 0), match=''>
2 <_sre.SRE_Match object; span=(1, 1), match=''>
3 <_sre.SRE_Match object; span=(2, 2), match=''>
4 <_sre.SRE_Match object; span=(3, 3), match=''>
(and so on..)
</code>```

My Question:
How can I find all overlapping matches, and get all the start and end index right as well?

答:
The problem you get is related to the fact that a lookahead is a zero-width assertion that consumes (i.e. adds to the match result) no text. It is a mere position in the string. Thus, all your matches start and end at the same location in the string.

You need to enclose the lookahead pattern with a capturing group (i.e. (?=(11111))) and access start and end of group 1 (with i.start(1) and i.end(1)):

```<code>import re
s = '1'*15
result = re.finditer(r'(?=(11111))', s)

for i in result:
    print(i.start(1), i.end(1))
</code>```

See the Python demo, its output is

```<code>(0, 5)
(1, 6)
(2, 7)
(3, 8)
(4, 9)
(5, 10)
(6, 11)
(7, 12)
(8, 13)
(9, 14)
(10, 15)
</code>```

Body:
This was my original approach:

string = '1'*15
result = re.finditer(r'(?=11111)', string)      # overlapped = True
                                                # Doesn't work for me
for i in result:                                # python 3.5
   print(i.start(), i.end())

It finds all overlapping matches, but fails to get the right end index.
The output:

1 <_sre.SRE_Match object; span=(0, 0), match=''>
2 <_sre.SRE_Match object; span=(1, 1), match=''>
3 <_sre.SRE_Match object; span=(2, 2), match=''>
4 <_sre.SRE_Match object; span=(3, 3), match=''>
(and so on..)

My Question:
How can I find all overlapping matches, and get all the start and end index right as well?

Body:
The problem you get is related to the fact that a lookahead is a zero-width assertion that consumes (i.e. adds to the match result) no text. It is a mere position in the string. Thus, all your matches start and end at the same location in the string.

You need to enclose the lookahead pattern with a capturing group (i.e. (?=(11111))) and access start and end of group 1 (with i.start(1) and i.end(1)):

import re
s = '1'*15
result = re.finditer(r'(?=(11111))', s)

for i in result:
    print(i.start(1), i.end(1))

See the Python demo, its output is

(0, 5)
(1, 6)
(2, 7)
(3, 8)
(4, 9)
(5, 10)
(6, 11)
(7, 12)
(8, 13)
(9, 14)
(10, 15)


问:
How to stop closing JFrame form?
I want to Stop accidentally closings in my project. I'm using JFrame Form as Home page. When I click Home window's close button I put Exit cord in Yes Option. I want to stop closing when I click No Option. Is there any way. Here is my cord. I'm using netbeans 7.3

```<code> private void formWindowClosing(java.awt.event.WindowEvent evt) {
 int i= JOptionPane.showConfirmDialog(null, "Are you sure to exit?");
    if (i == JOptionPane.YES_OPTION) {
        System.exit(0);
    } else{
        new Home().setVisible(true);

    }
}
</code>```

答:
You can simply do that like this</p>

```<code>Integer opt =  JOptionPane.showConfirmDialog(null, "This application cannot continue without login to the database\n Are you sure you need to exit...?", "Application X", JOptionPane.YES_NO_OPTION);
if(opt== JOptionPane.NO_OPTION){
    this.setVisible(true);
}else{
    System.exit(0);
}
</code>```

Title: How to stop closing JFrame form?

Body:
I want to Stop accidentally closings in my project. I'm using JFrame Form as Home page. When I click Home window's close button I put Exit cord in Yes Option. I want to stop closing when I click No Option. Is there any way. Here is my cord. I'm using netbeans 7.3

 private void formWindowClosing(java.awt.event.WindowEvent evt) {
 int i= JOptionPane.showConfirmDialog(null, "Are you sure to exit?");
    if (i == JOptionPane.YES_OPTION) {
        System.exit(0);
    } else{
        new Home().setVisible(true);

    }
}

Body:
You can simply do that like this

Integer opt =  JOptionPane.showConfirmDialog(null, "This application cannot continue without login to the database\n Are you sure you need to exit...?", "Application X", JOptionPane.YES_NO_OPTION);
if(opt== JOptionPane.NO_OPTION){
    this.setVisible(true);
}else{
    System.exit(0);
}


问:
For loop in R return error 'object not found'
I'm learning R and have written my first for-loop. For 1000 iterations I create 4 vectors, each with the dimensions 10, 100, 1000  and 10000 elements. These so called theta1 values are not recognised. I tried running one theta1 at the time and it works but running all 4 gives the error 'object not found'. It's not obvious to me what's wrong here, can anyone explain?</p>

```<code>k=1000

'Method1'

for(i in 1:k){
  N10=runif(10)
  N100=runif(100)
  N1000=runif(1000)
  N10000=runif(10000)
  theta1_10[i]=(1/10)*4*sum(sqrt(1-N10^2))
  theta1_100[i]=(1/100)*4*sum(sqrt(1-N100^2))
  theta1_1000[i]=(1/1000)*4*sum(sqrt(1-N1000^2))
  theta1_10000[i]=(1/10000)*4*sum(sqrt(1-N10000^2))
}

'Result Method 1'
m_theta1_10 = mean(theta1_10)
sd_theta1_10 = sd(theta1_10)
m_theta1_100 = mean(theta1_100)
sd_theta1_100 = sd(theta1_100)
m_theta1_1000 = mean(theta1_1000)
sd_theta1_1000 = sd(theta1_1000)
m_theta1_10000 = mean(theta1_10000)
sd_theta1_10000 = sd(theta1_10000)
</code>```

Body:
I'm learning R and have written my first for-loop. For 1000 iterations I create 4 vectors, each with the dimensions 10, 100, 1000  and 10000 elements. These so called theta1 values are not recognised. I tried running one theta1 at the time and it works but running all 4 gives the error 'object not found'. It's not obvious to me what's wrong here, can anyone explain?

k=1000

'Method1'

for(i in 1:k){
  N10=runif(10)
  N100=runif(100)
  N1000=runif(1000)
  N10000=runif(10000)
  theta1_10[i]=(1/10)*4*sum(sqrt(1-N10^2))
  theta1_100[i]=(1/100)*4*sum(sqrt(1-N100^2))
  theta1_1000[i]=(1/1000)*4*sum(sqrt(1-N1000^2))
  theta1_10000[i]=(1/10000)*4*sum(sqrt(1-N10000^2))
}

'Result Method 1'
m_theta1_10 = mean(theta1_10)
sd_theta1_10 = sd(theta1_10)
m_theta1_100 = mean(theta1_100)
sd_theta1_100 = sd(theta1_100)
m_theta1_1000 = mean(theta1_1000)
sd_theta1_1000 = sd(theta1_1000)
m_theta1_10000 = mean(theta1_10000)
sd_theta1_10000 = sd(theta1_10000)

Body:
You need to initial a vector before assigning values to it.
For this case it is:

# Initialize
k=1000
theta1_10 = vector(,k)
theta1_100 = vector(,k)
theta1_1000 = vector(,k)
theta1_10000 = vector(,k)

# Method1
for(i in 1:k){
  N10=runif(10)
  N100=runif(100)
  N1000=runif(1000)
  N10000=runif(10000)
  theta1_10[k] = (1/10)*4*sum(sqrt(1-N10^2))
  theta1_100[k] = (1/100)*4*sum(sqrt(1-N100^2))
  theta1_1000[k] = (1/1000)*4*sum(sqrt(1-N1000^2))
  theta1_10000[k] = (1/10000)*4*sum(sqrt(1-N10000^2))
}

# Result Method 1
result = data.frame(mean = c(mean(theta1_10),mean(theta1_100),mean(theta1_1000),mean(theta1_10000)),
                    sd = c(sd(theta1_10),sd(theta1_100),sd(theta1_1000),sd(theta1_10000)))
rownames(result) <- c("theta1_10","theta1_100","theta1_1000","theta1_10000")
result

                 mean          sd
theta1_10    3.145259 0.287263626
theta1_100   3.142640 0.089207786
theta1_1000  3.140476 0.027901399
theta1_10000 3.141695 0.009046627


问:
How to count words and group by hour?
I am working with a large Twitter data-set, I am trying to count the word column and group by hour using the Time column, then display it as a histogram so I can see how the words changed over time (distribution of words over time). I was wondering if anybody knows how I can do this with R?

Sample of the data is accessible via this link: https://docs.google.com/spreadsheets/d/1JhXEyzkjPs59hVgoS3lW7e0Fcumis62QDUvuMP2q5aQ/edit?usp=sharing

Thanks,
James

答:
Read your file into R, (I assumed the variable you set the file data into was x in my code below) then use the following:

```<code>require(dplyr)
x%>%group_by(Time, Word)%>%
  summarise(count=n())
</code>```

It returns output like this:

```<code>                  Time      Word count
                <fctr>    <fctr> <int>
1  2015/04/30 21:59:00         a     1
2  2015/04/30 21:59:00 baltimore     1
3  2015/04/30 21:59:00     check     1
4  2015/04/30 21:59:00    common     1
5  2015/04/30 21:59:00   grabbed     1
6  2015/04/30 21:59:00      have     1
7  2015/04/30 21:59:00       her     1
</code>```

Which you can capture in a data table or data frame

Title: How to count words and group by hour?

Body:
Read your file into R, (I assumed the variable you set the file data into was x in my code below) then use the following:

require(dplyr)
x%>%group_by(Time, Word)%>%
  summarise(count=n())

It returns output like this:

                  Time      Word count
                <fctr>    <fctr> <int>
1  2015/04/30 21:59:00         a     1
2  2015/04/30 21:59:00 baltimore     1
3  2015/04/30 21:59:00     check     1
4  2015/04/30 21:59:00    common     1
5  2015/04/30 21:59:00   grabbed     1
6  2015/04/30 21:59:00      have     1
7  2015/04/30 21:59:00       her     1

Which you can capture in a data table or data frame


问:
Subset around values that follow a pattern
Hopefully, this is a fairly straight forward question. I am using R to help subset some data that I am working with. Below is print() of some of the data that I am currently working with. I am trying to create a subset() of the data based around JobCode. As you can see the JobCode follows a pattern (00 - 0000) where the first 2 numbers are the same for a specific industry.

```<code>          ID   State         StateName JobCode
          1    AL            Alabama   51-9199
          2    AL            Alabama   27-3011
          4    AL            Alabama   49-9043
          5    AL            Alabama   49-2097
</code>```

My current attempt is to use this test <- subset(data, data$State == "AL" & data$JobCode == ("15-####"))(where # is a placeholder for the remaining 4 values) to subset for JobCode beginning with "15-". Is there any way to tell the subset to look for those remaining 4 values?

I'm sorry for the poor formatting as I am new to StackOverflow and I am also quite inexperienced with R. Thank you for your help.

答:
There are no wild card characters in string equality. You need to use a function. You could use substr() to extract the first three charcters

```<code>test <- subset(data, State == "AL" & substr(JobCode,1,3) == ("15-"))
</code>```

Also note that you don't need to use data$ inside the subset() parameter. Variables are evaulated in the context of the data frame for that function.

Body:
Hopefully, this is a fairly straight forward question. I am using R to help subset some data that I am working with. Below is print() of some of the data that I am currently working with. I am trying to create a subset() of the data based around JobCode. As you can see the JobCode follows a pattern (00 - 0000) where the first 2 numbers are the same for a specific industry.

          ID   State         StateName JobCode
          1    AL            Alabama   51-9199
          2    AL            Alabama   27-3011
          4    AL            Alabama   49-9043
          5    AL            Alabama   49-2097

My current attempt is to use this test <- subset(data, data$State == "AL" & data$JobCode == ("15-####"))(where # is a placeholder for the remaining 4 values) to subset for JobCode beginning with "15-". Is there any way to tell the subset to look for those remaining 4 values?

I'm sorry for the poor formatting as I am new to StackOverflow and I am also quite inexperienced with R. Thank you for your help.

Body:
There are no wild card characters in string equality. You need to use a function. You could use substr() to extract the first three charcters

test <- subset(data, State == "AL" & substr(JobCode,1,3) == ("15-"))

Also note that you don't need to use data$ inside the subset() parameter. Variables are evaulated in the context of the data frame for that function.


问:
Checking properties on different classes
I have multiple classes that all contain the same property along with a whole of different other properties. The classes don't use any kind of Interface. What I would like to do is pass an instance of each class to a method that can check for the property.

Can generics be used for this? If so, how can I construct a method to perform this task?

答:
Sounds like a use for dynamic (in C# 4.0)

```<code>public void DoMethodThing (dynamic your_object){
   your_object.ThatThingYouDo();
}
</code>```

http://msdn.microsoft.com/en-us/library/dd264736.aspx

Body:
Sounds like a use for dynamic (in C# 4.0)

public void DoMethodThing (dynamic your_object){
   your_object.ThatThingYouDo();
}

http://msdn.microsoft.com/en-us/library/dd264736.aspx


问:
How to adding space in middle of alphanumeric string?
I have a string like cs123 and I want to add space in the middle alphanumeric values in PHP. Is there any function for doing this specifically in PHP?

I have cs123 and I want cs 123.

Body:
echo preg_replace("/([a-z]+)([0-9]+)/i", "$1 $2", "cs123"); // Outputs: cs 123

in case "123cs" => "123 cs"

echo preg_replace("/([0-9]+)([a-z]+)/i", "$1 $2", "123cs"); // Outputs: 123 cs

we can combine both:

$text = "cs123, 123cs";
$new_text = preg_replace("/([a-z]+)([0-9]+)/i", "$1 $2", $text);
$new_text = preg_replace("/([0-9]+)([a-z]+)/i", "$1 $2", $new_text);
// $new_text = "cs 123, 123 cs"


问:
Can I extend VS Code TextMate Language Grammars?
Is there a way to extend the default csharp.tmLanguage with some additional rule? With references to existing scopes?

答:
You can include a grammar just like:

```<code>{ "include": "source.cs" }
</code>```

But if you replace the grammar with your own (defining your own source.cs scope), then you cannot include the original source.cs scope anymore into it (VS Code reports it failed tokenize the file).

Visual Studio Code supports grammar injection, like:

```<code>"grammars": [
            {
                "scopeName": "source.todo",
                "path": "./syntaxes/todo.json",
                "injectTo": [  "source.js", "source.ts" ]
            },
</code>```

Which is surprisingly under documented. It works, but you can inject into existing scopes, except the top level source scope. Also, it seems to me you can inject additions only, instead override rules. So again, I cannot extend grammar this way.

For now I go with a workaround, where I contribute 2 grammars. One is the original C# grammar with a fake name, the 2nd is the overwriting C# grammar, including all the original rules via the fake scope. I wish there was a way without this.

This way I can add some rules "before" I include the original grammar. But still, these are additions, I cannot really extend existing rules.

Body:
You can include a grammar just like:

{ "include": "source.cs" }

But if you replace the grammar with your own (defining your own source.cs scope), then you cannot include the original source.cs scope anymore into it (VS Code reports it failed tokenize the file).

Visual Studio Code supports grammar injection, like:

"grammars": [
            {
                "scopeName": "source.todo",
                "path": "./syntaxes/todo.json",
                "injectTo": [  "source.js", "source.ts" ]
            },

Which is surprisingly under documented. It works, but you can inject into existing scopes, except the top level source scope. Also, it seems to me you can inject additions only, instead override rules. So again, I cannot extend grammar this way.

For now I go with a workaround, where I contribute 2 grammars. One is the original C# grammar with a fake name, the 2nd is the overwriting C# grammar, including all the original rules via the fake scope. I wish there was a way without this.

This way I can add some rules "before" I include the original grammar. But still, these are additions, I cannot really extend existing rules.


问:
Android can't include linux in C program with Android.mk
I'm trying to compile a C program for Android 6. This is my Android.mk:

```<code>APP_PLATFORM := android-23
LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)
# Enable PIE manually. Will get reset on $(CLEAR_VARS). This
# is what enabling PIE translates to behind the scenes.
LOCAL_CFLAGS += -fPIE -DHAVE_FANOTIFY=1 -DHAVE_SYS_FANOTIFY=0
LOCAL_LDFLAGS += -fPIE -pie
# give module name
LOCAL_MODULE := fsmon
# list your C files to compile
LOCAL_SRC_FILES := inotify.c fanotify.c util.c main.c
# this option will build executables instead of building library for android application.
include $(BUILD_EXECUTABLE)
</code>```

In the fanotify.c following include is written:

```<code>#include <linux/fanotify.h>
</code>```

When I try to use ndk-build, following error appears:

```<code>fsmon/jni/fanotify.c:51:10: fatal error: 'linux/fanotify.h' file not found
#include <linux/fanotify.h>
         ^
</code>```

The header fanotify.h is present in the ndk path /Android/Sdk/ndk-bundle/sysroot/usr/include/linux

Any suggestions?

EDIT: Same error if I try to include sys/fanotify.h

答:
The NDK historically didn't backport headers to old releases, but we've reworked things in r14 so this is possible: https://android.googlesource.com/platform/ndk/+/ndk-r14-release/docs/UnifiedHeaders.md

By default in r14 you still get the old form of the headers. The new "unified headers" have the headers you're looking for. If you want to try unified headers, set APP_UNIFIED_HEADERS := true in your Application.mk (settings for other build systems can be found in the link above).

In r15 (first beta due out soon), the default has changed to the new headers, and the option for disabling them has changed (see the same doc in r15 for changes in options: https://android.googlesource.com/platform/ndk/+/ndk-r15-release/docs/UnifiedHeaders.md).

Body:
I'm trying to compile a C program for Android 6. This is my Android.mk:

APP_PLATFORM := android-23
LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)
# Enable PIE manually. Will get reset on $(CLEAR_VARS). This
# is what enabling PIE translates to behind the scenes.
LOCAL_CFLAGS += -fPIE -DHAVE_FANOTIFY=1 -DHAVE_SYS_FANOTIFY=0
LOCAL_LDFLAGS += -fPIE -pie
# give module name
LOCAL_MODULE := fsmon
# list your C files to compile
LOCAL_SRC_FILES := inotify.c fanotify.c util.c main.c
# this option will build executables instead of building library for android application.
include $(BUILD_EXECUTABLE)

In the fanotify.c following include is written:

#include <linux/fanotify.h>

When I try to use ndk-build, following error appears:

fsmon/jni/fanotify.c:51:10: fatal error: 'linux/fanotify.h' file not found
#include <linux/fanotify.h>
         ^

The header fanotify.h is present in the ndk path /Android/Sdk/ndk-bundle/sysroot/usr/include/linux

Any suggestions?

EDIT: Same error if I try to include sys/fanotify.h


问:
Python Dict Transform
I've been having some strange difficulty trying to transform a dataset that I have.

I currently have a dictionary coming from a form as follows:

```<code>data['content']['answers']
</code>```

I would like to have the ['answers'] appended to the first element of a list like so:

```<code>data['content'][0]['answers']
</code>```

However when I try to create it as so, I get an empty dataset.

```<code>data['content'] = [data['content']['answers']]
</code>```

I can't for the life of me figure out what I am doing wrong.

EDIT: Here is the opening JSON

I have:

```<code>{
"content" : {
              "answers" : {
                "3" : {
</code>```

But I need it to be:

```<code>    {
"content" : [
              {
                 "answers" : {
                  "3" : {
</code>```

thanks

答: It would be best if you give us a concrete example of 'data' (what the dictionary looks like), what code you try to run, what result you get and what you except. I think I have an idea but can't be sure.</p>

Title: Python Dict Transform

Body:
I've been having some strange difficulty trying to transform a dataset that I have.

I currently have a dictionary coming from a form as follows:

data['content']['answers']

I would like to have the ['answers'] appended to the first element of a list like so:

data['content'][0]['answers']

However when I try to create it as so, I get an empty dataset.

data['content'] = [data['content']['answers']]

I can't for the life of me figure out what I am doing wrong.

EDIT: Here is the opening JSON

I have:

{
"content" : {
              "answers" : {
                "3" : {

But I need it to be:

    {
"content" : [
              {
                 "answers" : {
                  "3" : {

thanks


问:
Why Does Every Letter in my String get Replaced Instead of Vowels?
I have the following code:

```<code>def replace_vowel(text):
    text = list(text)
    for i in range(0, len(text)):
        if text[i] == 'A' or 'a' or 'E' or 'e' or 'I' or 'i' or 'O' or 'o' or 'U' or 'u':
            text[i] = ''
    print ''.join(text)
    return ''.join(text)

replace_vowel("HeylookWords!")
</code>```

The code is supposed to replace every vowel, but instead, every letter gets replaced with ''. Why does this happen?

答:
Do range(len(text))

And you need == for each comparison.  You can't just do text[i] == 'A' then a bunch of or statements.

if text[i] == 'A' or text[i] == 'a' or... ect

Note that you can also do replace in python, 'some string'.replace('with something','for something else')

If you had a long list of checks you would put your letters into a list and check against the list.

```<code>l = ['A','B','C','D']
for letter in l:
   if text[i] == letter:
       do_something()
</code>```

Body:
I have the following code:

def replace_vowel(text):
    text = list(text)
    for i in range(0, len(text)):
        if text[i] == 'A' or 'a' or 'E' or 'e' or 'I' or 'i' or 'O' or 'o' or 'U' or 'u':
            text[i] = ''
    print ''.join(text)
    return ''.join(text)

replace_vowel("HeylookWords!")

The code is supposed to replace every vowel, but instead, every letter gets replaced with ''. Why does this happen?

Body:
Do range(len(text))

And you need == for each comparison.  You can't just do text[i] == 'A' then a bunch of or statements.

if text[i] == 'A' or text[i] == 'a' or... ect

Note that you can also do replace in python, 'some string'.replace('with something','for something else')

If you had a long list of checks you would put your letters into a list and check against the list.

l = ['A','B','C','D']
for letter in l:
   if text[i] == letter:
       do_something()


答:
Your question isn't clear and lacks of an explicit example.

Btw, something like this can work for you?

```<code>data_list = list()
for content in data.keys():
    data_list.append(data[content])
</code>```

Title: Python Dict Transform

Body:
Your question isn't clear and lacks of an explicit example.

Btw, something like this can work for you?

data_list = list()
for content in data.keys():
    data_list.append(data[content])


问:
SQL Server - Remove all non-printable ASCII characters
We recently migrated from SQL Server 2012 to SQL Server 2014 and all our FOR XML code started throwing errors about non-printable ASCII characters.
I wrote this horrible function to remove non-printable ASCII characters as a quick fix. I want to replace it with something cleaner. Is there a way to do this?

```<code>ALTER FUNCTION [dbo].[remove_non_printable_chars]
(@input_string nvarchar(max))
RETURNS nvarchar(max)
BEGIN
    RETURN
    REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(
    REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(
    REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(
    REPLACE(REPLACE(@input_string,
        CHAR(1), ''),CHAR(2), ''),CHAR(3), ''),CHAR(4), ''),CHAR(5), ''),CHAR(6), ''),CHAR(7), ''),CHAR(8), ''),CHAR(9), ''),CHAR(10), ''),
        CHAR(11), ''),CHAR(12), ''),CHAR(13), ''),CHAR(14), ''),CHAR(15), ''),CHAR(16), ''),CHAR(17), ''),CHAR(18), ''),CHAR(19), ''),CHAR(20), ''),
        CHAR(21), ''),CHAR(22), ''),CHAR(23), ''),CHAR(24), ''),CHAR(25), ''),CHAR(26), ''),CHAR(27), ''),CHAR(28), ''),CHAR(29), ''),CHAR(30), ''),
        CHAR(31), ''), NCHAR(0) COLLATE Latin1_General_100_BIN2, '')
END
</code>```

Here's the FOR XML code that broke. (I did not write this. It was already in the code base).

```<code>SELECT @HTMLTableData =
(
    SELECT  HTMLRows
    FROM (
        SELECT N'<tr>' + HTMLRow + N'</tr>' AS HTMLRows
        FROM @HTMLRowData
    ) mi
    FOR XML PATH(''), TYPE
).value('/', 'NVARCHAR(MAX)')
</code>```

答:
Another Option.

This function will replace control characters and correct any residual repeating spaces.  For example Jane Smith{13}was here will not be returned as Jane Smithwas here, but rather Jane Smith was here

```<code>CREATE FUNCTION [dbo].[udf-Str-Strip-Control](@S varchar(max))
Returns varchar(max)
Begin
    ;with  cte1(N) As (Select 1 From (Values(1),(1),(1),(1),(1),(1),(1),(1),(1),(1)) N(N)),
           cte2(C) As (Select Top (32) Char(Row_Number() over (Order By (Select NULL))-1) From cte1 a,cte1 b)
    Select @S = Replace(@S,C,' ')
     From  cte2

    Return ltrim(rtrim(replace(replace(replace(@S,' ','†‡'),'‡†',''),'†‡',' ')))
End
--Select [dbo].[udf-Str-Strip-Control]('Michael        '+char(13)+char(10)+'LastName')  --Returns: Michael LastName
</code>```

Body:
We recently migrated from SQL Server 2012 to SQL Server 2014 and all our FOR XML code started throwing errors about non-printable ASCII characters.
I wrote this horrible function to remove non-printable ASCII characters as a quick fix. I want to replace it with something cleaner. Is there a way to do this?

ALTER FUNCTION [dbo].[remove_non_printable_chars]
(@input_string nvarchar(max))
RETURNS nvarchar(max)
BEGIN
    RETURN
    REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(
    REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(
    REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(
    REPLACE(REPLACE(@input_string,
        CHAR(1), ''),CHAR(2), ''),CHAR(3), ''),CHAR(4), ''),CHAR(5), ''),CHAR(6), ''),CHAR(7), ''),CHAR(8), ''),CHAR(9), ''),CHAR(10), ''),
        CHAR(11), ''),CHAR(12), ''),CHAR(13), ''),CHAR(14), ''),CHAR(15), ''),CHAR(16), ''),CHAR(17), ''),CHAR(18), ''),CHAR(19), ''),CHAR(20), ''),
        CHAR(21), ''),CHAR(22), ''),CHAR(23), ''),CHAR(24), ''),CHAR(25), ''),CHAR(26), ''),CHAR(27), ''),CHAR(28), ''),CHAR(29), ''),CHAR(30), ''),
        CHAR(31), ''), NCHAR(0) COLLATE Latin1_General_100_BIN2, '')
END

Here's the FOR XML code that broke. (I did not write this. It was already in the code base).

SELECT @HTMLTableData =
(
    SELECT  HTMLRows
    FROM (
        SELECT N'
' + HTMLRow + N'
' AS HTMLRows
        FROM @HTMLRowData
    ) mi
    FOR XML PATH(''), TYPE
).value('/', 'NVARCHAR(MAX)')

Body:
Another Option.

This function will replace control characters and correct any residual repeating spaces.  For example Jane Smith{13}was here will not be returned as Jane Smithwas here, but rather Jane Smith was here

CREATE FUNCTION [dbo].[udf-Str-Strip-Control](@S varchar(max))
Returns varchar(max)
Begin
    ;with  cte1(N) As (Select 1 From (Values(1),(1),(1),(1),(1),(1),(1),(1),(1),(1)) N(N)),
           cte2(C) As (Select Top (32) Char(Row_Number() over (Order By (Select NULL))-1) From cte1 a,cte1 b)
    Select @S = Replace(@S,C,' ')
     From  cte2

    Return ltrim(rtrim(replace(replace(replace(@S,' ','†‡'),'‡†',''),'†‡',' ')))
End
--Select [dbo].[udf-Str-Strip-Control]('Michael        '+char(13)+char(10)+'LastName')  --Returns: Michael LastName