问:
Python: Chi Squared for categorical values in large dataset
I no experience of note with Python, and am trying to use it for a statistical analysis of a very large dataset (10 million cases) because the other options (SPSS and R) are unable to handle the dataset on the authorized hardware.

In this dataset, there are many categorical variables (Diagnosis1, Diagnosis2...Diagnosis30) and an Event variable (the dependent variable).

Cases are listed as rows.

Something like this

```<code>Diagnosis1       Diagnosis2         Diagnosis3   Event
1                0                  0            1
0                1                  0            0
0                1                  0            0
</code>```

....and so on

I can load the data and review it with this -

```<code>    import pandas as pd
    import numpy as np
    NRD_Data = pd.read_csv('NRD_DL.csv')
    NRD_Data.head()
</code>```

but I am stuck on how to build 2x2 tables and perform a Chi Square test on the tables.

```<code>            Diagnosis1=1   Diagnosis1=0
Event=1     100            12
Event=0     80             45
</code>```

Something akin to running cross-tabs on SPSS to compare categorial values is the desired result.

答:
Using pd.crosstab to get the matrix you need , then you can do your Chi Square test

```<code>l=['Diagnosis1',  'Diagnosis2',  'Diagnosis3']
d=[]
for i in l:
    d.append(pd.crosstab(df['Event'],df[i]))
d[0]
Out[569]:
Diagnosis1  0  1
Event
0           2  0
1           0  1
</code>```

Body:
I no experience of note with Python, and am trying to use it for a statistical analysis of a very large dataset (10 million cases) because the other options (SPSS and R) are unable to handle the dataset on the authorized hardware.

In this dataset, there are many categorical variables (Diagnosis1, Diagnosis2...Diagnosis30) and an Event variable (the dependent variable).

Cases are listed as rows.

Something like this

Diagnosis1       Diagnosis2         Diagnosis3   Event
1                0                  0            1
0                1                  0            0
0                1                  0            0

....and so on

I can load the data and review it with this -

    import pandas as pd
    import numpy as np
    NRD_Data = pd.read_csv('NRD_DL.csv')
    NRD_Data.head()

but I am stuck on how to build 2x2 tables and perform a Chi Square test on the tables.

            Diagnosis1=1   Diagnosis1=0
Event=1     100            12
Event=0     80             45

Something akin to running cross-tabs on SPSS to compare categorial values is the desired result.

Body:
Using pd.crosstab to get the matrix you need , then you can do your Chi Square test

l=['Diagnosis1',  'Diagnosis2',  'Diagnosis3']
d=[]
for i in l:
    d.append(pd.crosstab(df['Event'],df[i]))
d[0]
Out[569]:
Diagnosis1  0  1
Event
0           2  0
1           0  1


来源: stackexchange

问:
how to highlight the selected menu in angular 4
I am trying to highlight the selected menu but unable to get an idea.

Below code is menu with sub-menus, menus come from JSON.

HTML

```<code><div *ngFor="let values of val">
    <mat-expansion-panel class="mat-ripple" mat-button routerLink=".">
        <mat-expansion-panel-header expandedHeight="48px" collapsedHeight="48px">
            <mat-panel-title>
                <md-icon class="mat-icon mat-list-icon material-icons">
                    {{values.titleImage}}
                </md-icon>
                <div class="menu-list-text">
                    {{values.titleName}}
                </div>
            </mat-panel-title>
        </mat-expansion-panel-header>
        <a class="sidenav-link mat-list-item mat-ripple"
           mat-button
           routerLink="."
           *ngFor="let subTitleVal of values.subTitle">
            <div class="mat-list-item-content">
                <span md-line="">{{subTitleVal.titleName}}</span>
            </div>
        </a>
    </mat-expansion-panel>
</div>
</code>```

JSON

```<code>val: any;
val = [{
    'titleKey': 'AAA',
    'titleName': ' Menu1',
    'titleImage': 'Icon1',
    'subTitle': [{
        'titleKey': 'AAA',
        'titleName': 'SubMenu1',
        'action': 'ACC',
    }]
}, {
    'titleKey': 'BBB',
    'titleName': 'Menu2',
    'titleImage': 'Icon2',
    'subTitle': [{
        'titleKey': 'BBB',
        'titleName': 'SubMenu2',
        'action': 'FT',
    }]
}, {
    'titleKey': 'CCC',
    'titleName': 'Menu3',
    'titleImage': 'Icon3',
    'subTitle': [{
        'titleKey': 'CCC',
        'titleName': 'SubMenu3',
        'action': 'BP',
    }]
}];
</code>```

How to add the class when user selects a particular sub-menu?

答:
Implement a addClass and removeClass like:

```<code>import { Renderer2, ElementRef } from '@angular/core';

export class changeStyleClass {

  constructor(private renderer: Renderer2, private el: ElementRef) {
  }

  addClass( element: any, className: string) {
  this.renderer.addClass(element, className);
  // or use the host element directly
  // this.renderer.addClass(this.el.nativeElement, className);
  }

  removeClass(className: string, element: any) {
  this.renderer.removeClass(element, className);
  }

}
</code>```

Demo: https://plnkr.co/edit/BpeYpqf378MYDLWRGbjc?p=preview

ContentLicense: CC BY-SA 3.0

Body:
I am trying to highlight the selected menu but unable to get an idea.

Below code is menu with sub-menus, menus come from JSON.

HTML

    <mat-expansion-panel class="mat-ripple" mat-button routerLink=".">
        <mat-expansion-panel-header expandedHeight="48px" collapsedHeight="48px">
            <mat-panel-title>
                <md-icon class="mat-icon mat-list-icon material-icons">
                    {{values.titleImage}}
                </md-icon>

                    {{values.titleName}}

            </mat-panel-title>
        </mat-expansion-panel-header>

                {{subTitleVal.titleName}}

    </mat-expansion-panel>

JSON

val: any;
val = [{
    'titleKey': 'AAA',
    'titleName': ' Menu1',
    'titleImage': 'Icon1',
    'subTitle': [{
        'titleKey': 'AAA',
        'titleName': 'SubMenu1',
        'action': 'ACC',
    }]
}, {
    'titleKey': 'BBB',
    'titleName': 'Menu2',
    'titleImage': 'Icon2',
    'subTitle': [{
        'titleKey': 'BBB',
        'titleName': 'SubMenu2',
        'action': 'FT',
    }]
}, {
    'titleKey': 'CCC',
    'titleName': 'Menu3',
    'titleImage': 'Icon3',
    'subTitle': [{
        'titleKey': 'CCC',
        'titleName': 'SubMenu3',
        'action': 'BP',
    }]
}];

How to add the class when user selects a particular sub-menu?

Body:
Implement a addClass and removeClass like:

import { Renderer2, ElementRef } from '@angular/core';

export class changeStyleClass {

  constructor(private renderer: Renderer2, private el: ElementRef) {
  }

  addClass( element: any, className: string) {
  this.renderer.addClass(element, className);
  // or use the host element directly
  // this.renderer.addClass(this.el.nativeElement, className);
  }

  removeClass(className: string, element: any) {
  this.renderer.removeClass(element, className);
  }

}

Demo: https://plnkr.co/edit/BpeYpqf378MYDLWRGbjc?p=preview


问:
SQL INTERSECT by one field and get another field
I'm trying to do this SQL query:

```<code> SELECT field FROM table
 INTERSECT
 SELECT field FROM table
</code>```

Which return the intersection by the given field, but I want to get another field from the table as a result (intersected by the given field), how do I do that?

答:
something like this should do it:

Look into joins

```<code>select
    t1.AnyField, t2.AnyField
from
    t1
    inner join t2 on t1.intersection_field = t2.intersection_field
</code>```

Per your comment about the same table being involved

```<code>select
    t1.AnyField, t2.AnyField
from
    table as t1
    inner join table as t2 on t1.intersection_field = t2.intersection_field
      and t1.another_field = t2.another_field
</code>```

or

```<code>select
    t1.AnyField, t2.AnyField
from
    table as t1
    inner join table as t2 on t1.intersection_field = t2.intersection_field
where
    t1.filtered_field = 'text'
    and t2.yet_another_field >= 10
</code>```

Body:
I'm trying to do this SQL query:

 SELECT field FROM table
 INTERSECT
 SELECT field FROM table

Which return the intersection by the given field, but I want to get another field from the table as a result (intersected by the given field), how do I do that?

Body:
something like this should do it:

Look into joins

select
    t1.AnyField, t2.AnyField
from
    t1
    inner join t2 on t1.intersection_field = t2.intersection_field

Per your comment about the same table being involved

select
    t1.AnyField, t2.AnyField
from
    table as t1
    inner join table as t2 on t1.intersection_field = t2.intersection_field
      and t1.another_field = t2.another_field

or

select
    t1.AnyField, t2.AnyField
from
    table as t1
    inner join table as t2 on t1.intersection_field = t2.intersection_field
where
    t1.filtered_field = 'text'
    and t2.yet_another_field >= 10


问:
Trouble with Google Vision API key
I am trying to use Google Vision API in my WinForms (.NET) project. I have signed up in Google Cloud Platform and enabled Vision API. Having followed Google Cloud standard steps in authorization process I have created and downloaded service key in JSON format. As far as it is concerned, GOOGLE_APPLICATION_CREDENTIALS also have been set to be pointing to key file (JSON file I have mentioned before). All settings are looking good in Google Cloud Platform, in terms of API.

I am wondering why I am getting exception

Grpc.Core.RpcException: 'Status(StatusCode=Unauthenticated,Detail="Getting metadata from plugin failed with error: Exception occured in metadata credentials plugin.")'

Here is the code of method where exception is thrown:

```<code>        var client = ImageAnnotatorClient.Create();
        var image = Image.FromFile(filePath);
        var response = client.DetectText(image); // <- here exception is thrown
</code>```

P.S. I have made a significant research on this topic. I know it seems something is wrong with authentication, can't figure out what exactly is wrong though.

P.S.S Should you have any references or tutorials, don't hesitate to provide me with them.

答:
The code in your sample should work as long as the environment variable GOOGLE_APPLICATION_CREDENTIALS is set accordingly.

To debug, you may want to add a line like:

```<code>Console.WriteLine($"Using credentials from {Environment.GetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS")}.");
</code>```

Title: Trouble with Google Vision API key

Body:
I am trying to use Google Vision API in my WinForms (.NET) project. I have signed up in Google Cloud Platform and enabled Vision API. Having followed Google Cloud standard steps in authorization process I have created and downloaded service key in JSON format. As far as it is concerned, GOOGLE_APPLICATION_CREDENTIALS also have been set to be pointing to key file (JSON file I have mentioned before). All settings are looking good in Google Cloud Platform, in terms of API.

I am wondering why I am getting exception

Grpc.Core.RpcException: 'Status(StatusCode=Unauthenticated,Detail="Getting metadata from plugin failed with error: Exception occured in metadata credentials plugin.")'

Here is the code of method where exception is thrown:

        var client = ImageAnnotatorClient.Create();
        var image = Image.FromFile(filePath);
        var response = client.DetectText(image); // <- here exception is thrown

P.S. I have made a significant research on this topic. I know it seems something is wrong with authentication, can't figure out what exactly is wrong though.

P.S.S Should you have any references or tutorials, don't hesitate to provide me with them.

Body:
The code in your sample should work as long as the environment variable GOOGLE_APPLICATION_CREDENTIALS is set accordingly.

To debug, you may want to add a line like:

Console.WriteLine($"Using credentials from {Environment.GetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS")}.");


问:
GraphQL query does not update on react router v4 history push
I would like to implement a basic filtering option in my React web app. I have three components

```<code>VideoList
--------------------------

Filter    Result
--------  ----------------
category
</code>```

the Filter component and the Result component are both children of the VideoList component. In the filter component when a user clicks on the category, I am pushing a new url, like this this.props.history.push(/videos/${category.name}). It seems like my react-router settings works correctly and the VideoList component gets new category name and successfully passes it to the Result component.

```<code><Route exact path="/videos" component={VideoList}/>,
<Route exact path="/videos/:category" render={props => <VideoList {...props} />} />,
</code>```

In VideoLIst component

<Result category={category} />

The Result component makes usage of a new category name in its own GraphQL query as follow:

```<code>export default compose(
  graphql(VIDEOS_QUERY, {
    options: props => {
      return {
        variables: {
          filterByCategory: props.category ? props.category : null,
        }
      };
    },
...
</code>```

But, by some unknown to me reasons when pushing new url for the first time props.data.VideoQuery (this is return values from graphql server) in the Result component gets undefined. However, when a user clicks on the category second time, the Result components renders correctly.

答:
Have you tried using Switch instead of Routes with exact?

```<code><Switch>
  <Route path="/videos" component={VideoList} />
  <Route path="/videos/:category" render={props => <VideoList {...props} />} />
</Switch>
</code>```

Body:
I would like to implement a basic filtering option in my React web app. I have three components

VideoList
--------------------------

Filter    Result
--------  ----------------
category

the Filter component and the Result component are both children of the VideoList component. In the filter component when a user clicks on the category, I am pushing a new url, like this this.props.history.push(/videos/${category.name}). It seems like my react-router settings works correctly and the VideoList component gets new category name and successfully passes it to the Result component.

<Route exact path="/videos" component={VideoList}/>,
<Route exact path="/videos/:category" render={props => <VideoList {...props} />} />,

In VideoLIst component

<Result category={category} />

The Result component makes usage of a new category name in its own GraphQL query as follow:

export default compose(
  graphql(VIDEOS_QUERY, {
    options: props => {
      return {
        variables: {
          filterByCategory: props.category ? props.category : null,
        }
      };
    },
...

But, by some unknown to me reasons when pushing new url for the first time props.data.VideoQuery (this is return values from graphql server) in the Result component gets undefined. However, when a user clicks on the category second time, the Result components renders correctly.

Body:
Have you tried using Switch instead of Routes with exact?

<Switch>
  <Route path="/videos" component={VideoList} />
  <Route path="/videos/:category" render={props => <VideoList {...props} />} />
</Switch>


问:
How to position polymer paper-toast element
Created Polymer app using polymer init command and selecting app-drawer-template.

In my-view1.html, linked to paper-toast.html and modified the template and script as follows:

```<code> <template>
   <div class="card">
   <div class="circle">1</div>
   <h1>View One</h1>

   <button on-tap="handleTap">open</button>

   <paper-toast id="toast0" text="This toast auto-closes after 3 seconds"></paper-toast>

</div>

</template>

<script>

 Polymer({

   is: 'my-view1',

    handleTap: function(){
    this.$.toast0.open();
  }

  });
</code>```

When the button is clicked, the toast appears but most of it appears behind the Menu drawer and only part of the toast window is visible.

I tried to center the toast using css but it does not work. Setting z-index did not work either. How can the toast window be positioned so it is not hidden behind the drawer?

答:
Following css also can solve your problem.</p>

```<code>paper-toast {
   width: 300px;
   margin-left: calc(50vw - 150px);
}
</code>```

Body:
Created Polymer app using polymer init command and selecting app-drawer-template.

In my-view1.html, linked to paper-toast.html and modified the template and script as follows:

 <template>

1

View One

   <button on-tap="handleTap">open</button>

   <paper-toast id="toast0" text="This toast auto-closes after 3 seconds"></paper-toast>

</template>

Body:
Following css also can solve your problem.

paper-toast {
   width: 300px;
   margin-left: calc(50vw - 150px);
}


问:
How to handle multiple OR condition in IF
```<code>bool A=false;
bool B=true;

if(!A || !B)
{
.....
}
</code>```

In this condition when A is true, it didn't checks the B but I want to check B instead of A .

In this condition I want to execute if any one is true(A or B), But If A is true I want to check B also. is there any other logic to resolve this apart from using different if conditions?

答:
You may turn off short-circut evaluation in your compiler. If you work with your own types, you may overload || and &&. Overloaded logical operators are not short-circuted.

Both things are really bad. Programmers expect logical operators to behave in certain way and are very likely to get super confused with this unexpected behavior. You should stick to short-circuting.

Body:
bool A=false;
bool B=true;

if(!A || !B)
{
.....
}

In this condition when A is true, it didn't checks the B but I want to check B instead of A .

In this condition I want to execute if any one is true(A or B), But If A is true I want to check B also. is there any other logic to resolve this apart from using different if conditions?


问:
How to pass global CSS/JS to components?
I have components with some styles:

```<code>const styles = () => ({
  rootPaper: {
    marginBottom: '25px',
    paddingTop: 0,
  },
});
...
 render() {
    const { classes } = this.props;
    <Paper className={styles.rootPaper} elevation={4}></Paper>
...
export default withStyles(styles)(...)
</code>```

And it works. This code is repeated in some components so I want to exclude this as a separate JS file:

```<code>const globalCss = {
  rootPaper: {
    marginBottom: '25px',
    paddingTop: 0,
  },
  hidden: {
    display: 'none',
  },
};

export default globalCss;
</code>```

and import that file like that:

```<code>import globalCss from '../../styles/globalCss';
...
<Paper className={globalCss.rootPaper} elevation={4}>
</code>```

But when I want to use this in className it doesn't work(no errors). Used React v16 and Material-ui-next beta 20. How Can I move the same classes to one file and use it in different components?

答:
I'm not sure how your 1st example actually works (as you mentioned).

You are not really invoking the styles function.

You should pass this kind of object to the style prop and not to
the className prop (which accepts a string).

As for your second example, it should work if you will pass it to the style prop instead of the className prop, for reasons I mentioned above.

Running example:

const globalCss = {
  rootPaper: {
    marginBottom: '25px',
    paddingTop: 0,
    color: 'red'
  },
  hidden: {
    display: 'none',
  },
};

const App = () => (

I got some styles!

);

ReactDOM.render(<App />, document.getElementById("root"));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div></code>```

Body:
I have components with some styles:

const styles = () => ({
  rootPaper: {
    marginBottom: '25px',
    paddingTop: 0,
  },
});
...
 render() {
    const { classes } = this.props;
    <Paper className={styles.rootPaper} elevation={4}></Paper>
...
export default withStyles(styles)(...)

And it works. This code is repeated in some components so I want to exclude this as a separate JS file:

const globalCss = {
  rootPaper: {
    marginBottom: '25px',
    paddingTop: 0,
  },
  hidden: {
    display: 'none',
  },
};

export default globalCss;

and import that file like that:

import globalCss from '../../styles/globalCss';
...
<Paper className={globalCss.rootPaper} elevation={4}>

But when I want to use this in className it doesn't work(no errors). Used React v16 and Material-ui-next beta 20. How Can I move the same classes to one file and use it in different components?

Body:
I'm not sure how your 1st example actually works (as you mentioned).

You are not really invoking the styles function.

You should pass this kind of object to the style prop and not to
the className prop (which accepts a string).

As for your second example, it should work if you will pass it to the style prop instead of the className prop, for reasons I mentioned above.

Running example:

const globalCss = {
  rootPaper: {
    marginBottom: '25px',
    paddingTop: 0,
    color: 'red'
  },
  hidden: {
    display: 'none',
  },
};

const App = () => (
  <div style={globalCss.rootPaper}>
    <h2>I got some styles!</h2>
  </div>
);

ReactDOM.render(<App />, document.getElementById("root"));

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>


问:
Choco Solver - Variables association
I'm using choco solver 4.0.5 (latest until now) and the few examples on the web besides not contemplating my need, use older version.

I'm absolutely a begginner on choco solver, and after very hard search on the web, I came here to ask help.

I have the following variables domain:

Days of year: 1 (represents 1-jan), 35 (represents 4-feb), 58, 56, 125, 142, 168, 225, 360, 364...
People Ids: 789111, 789555, 78496, 879...

I need create a constraint in order that people don't be associated on a consecutive days, but alternate them in a balanced way like:

```<code>1 = 789111
35 = 789555
58 = 789496
56 = 879
125 = 789111
142 = 789555
168 = 789496
225 = 879
360 = 789111
364 = 789496 (the 789555 is unavailable here)
</code>```

How can I represent this on choco solver 4.0.5?

Thank you all!!

答:
Distribute events evenly over time is not an easy thing to model. A simple "proxy" is: forbid people to work on days that are close. E.g. at least two days in between. This can be modeled as:

```<code>worker w works at t => w cannot work at t+1 and t+2
</code>```

If you would model this as x[w,t]=1 iff w works at t then this becomes:

```<code>x[w,t]=1 => x[w,t+1]=0 and x[w,t+2]=0
</code>```

Title: Choco Solver - Variables association

Body:
I'm using choco solver 4.0.5 (latest until now) and the few examples on the web besides not contemplating my need, use older version.

I'm absolutely a begginner on choco solver, and after very hard search on the web, I came here to ask help.

I have the following variables domain:

Days of year: 1 (represents 1-jan), 35 (represents 4-feb), 58, 56, 125, 142, 168, 225, 360, 364...
People Ids: 789111, 789555, 78496, 879...

I need create a constraint in order that people don't be associated on a consecutive days, but alternate them in a balanced way like:

1 = 789111
35 = 789555
58 = 789496
56 = 879
125 = 789111
142 = 789555
168 = 789496
225 = 879
360 = 789111
364 = 789496 (the 789555 is unavailable here)

How can I represent this on choco solver 4.0.5?

Thank you all!!

Body:
Distribute events evenly over time is not an easy thing to model. A simple "proxy" is: forbid people to work on days that are close. E.g. at least two days in between. This can be modeled as:

worker w works at t => w cannot work at t+1 and t+2

If you would model this as x[w,t]=1 iff w works at t then this becomes:

x[w,t]=1 => x[w,t+1]=0 and x[w,t+2]=0


问:
.NET, arrows on the right side in MenuStrip
When not all items fit in a ToolStrip, there are arrows on the right side.
Is there the same possibility for MenuStrip?

'LayoutStyle = Flow' is not so good, cause then the menu takes more lines and the user has less space to work.

答:
Thanks for your comment, I found the answer:

Can a MenuStrip control have its LayoutStyle set to StackWithOverflow?

```<code>    Me.MenuStrip1.CanOverflow = True
    Me.FischersToolStripMenuItem.Overflow = ToolStripItemOverflow.AsNeeded
</code>```

Body:
Thanks for your comment, I found the answer:

Can a MenuStrip control have its LayoutStyle set to StackWithOverflow?

    Me.MenuStrip1.CanOverflow = True
    Me.FischersToolStripMenuItem.Overflow = ToolStripItemOverflow.AsNeeded


问:
HTML Tag for grouping content
In HTML, when I use div tag after some content, for example, canvas, div content will be under canvas. Is there a tag, that places its content on right side. Please, see picture below

答:
There are two ways to achieve this first one is using css float property and second one is by bootstrap. I add a demo code for your better understanding.

<!DOCTYPE html>

roundel container

article body

    ```

Title: HTML Tag for grouping content

Body:
There are two ways to achieve this first one is using css float property and second one is by bootstrap. I add a demo code for your better understanding.

<!DOCTYPE html>
    <html>
    <head>
    <style>
    div.container {
        width: 100%;
        border: 1px solid gray;
    }

    header, footer {
        padding: 1em;
        border-top: 1px solid black;
        clear: left;
    }

    nav {
        float: left;
        max-width: 160px;
        margin: 0;
        padding: 1em;
    }

    nav ul {
        list-style-type: none;
        padding: 0;
    }

    nav ul a {
        text-decoration: none;
    }

    article {
        margin-left: 170px;
        border-left: 1px solid gray;

        overflow: hidden;
    }
    </style>
    </head>
    <body>
    <div class="container">
    <nav>
      <p>roundel container</p>
    </nav>
    <article>
      <p>article body</p>
    </article>
    </div>
    </body>
    </html>


问:
Rails inverse of Polymorphic association in concern gives TypeError: can't cast Class
I am trying to use the information in this tutorial to learn concerns with polymorphic associations. I have the following:

concerns/taggable.rb:

```<code>module Taggable
  extend ActiveSupport::Concern

  included do
    has_many :taggings, :as => :taggable
    has_many :tags, :through => :taggings
  end

  def tag_list
    tags.map(&:name).join(', ')
  end

  def tag_list=(names)
    self.tags = names.split(',').map do |name|
      Tag.where(name: name.strip).first_or_create!
    end
  end

  module ClassMethods
    def tag_counts
      Tag.select('tags.*, count(taggings.tag_id) as count').joins(:taggings).group('taggings.tag_id')
    end
  end
end
</code>```

models/article.rb:

```<code>class Article < ApplicationRecord
  include Taggable

  def self.tagged_with(name)
    Tag.find_by!(name: name).articles
  end

end
</code>```

models/tagging.rb:

```<code>class Tagging < ApplicationRecord

  belongs_to :tag
  belongs_to :taggable, :polymorphic => true

end
</code>```

models/tag.rb:

```<code>class Tag < ApplicationRecord
  has_many :taggings
  has_many :articles, through: :taggings, source: :taggable, source_type: Article

end
</code>```

The forward associations work just fine. I can ask:

```<code>Article.first.tags
#=> Article Load (0.2ms)  SELECT  "articles".* FROM "articles" ORDER BY "articles"."id" ASC LIMIT ?  [["LIMIT", 1]]
Tag Load (0.3ms)  SELECT  "tags".* FROM "tags" INNER JOIN "taggings" ON "tags"."id" = "taggings"."tag_id" WHERE "taggings"."taggable_id" = ? AND "taggings"."taggable_type" = ? LIMIT ?  [["taggable_id", 1], ["taggable_type", "Article"], ["LIMIT", 11]]
=> #<ActiveRecord::Associations::CollectionProxy [#<Tag id: 1, name: "Superhero", created_at: "2017-11-12 21:06:33", updated_at: "2017-11-12 21:06:33">, #<Tag id: 2, name: "Bat", created_at: "2017-11-12 21:06:33"...
</code>```

But if I do:

```<code>Tag.first.articles
Tag Load (0.3ms)  SELECT  "tags".* FROM "tags" ORDER BY "tags"."id" ASC LIMIT ?  [["LIMIT", 1]]
TypeError: can't cast Class
</code>```

I've tried several variations on the associations in the tag.rb model but can't seem to find any that works.

答:
The source_type in the Tag's has_many :through association needs to be a string:</p>

```<code>has_many :articles, through: :taggings, source: :taggable, source_type: "Article"
</code>```

Body:
I am trying to use the information in this tutorial to learn concerns with polymorphic associations. I have the following:

concerns/taggable.rb:

module Taggable
  extend ActiveSupport::Concern

  included do
    has_many :taggings, :as => :taggable
    has_many :tags, :through => :taggings
  end

  def tag_list
    tags.map(&:name).join(', ')
  end

  def tag_list=(names)
    self.tags = names.split(',').map do |name|
      Tag.where(name: name.strip).first_or_create!
    end
  end

  module ClassMethods
    def tag_counts
      Tag.select('tags.*, count(taggings.tag_id) as count').joins(:taggings).group('taggings.tag_id')
    end
  end
end

models/article.rb:

class Article < ApplicationRecord
  include Taggable

  def self.tagged_with(name)
    Tag.find_by!(name: name).articles
  end

end

models/tagging.rb:

class Tagging < ApplicationRecord

  belongs_to :tag
  belongs_to :taggable, :polymorphic => true

end

models/tag.rb:

class Tag < ApplicationRecord
  has_many :taggings
  has_many :articles, through: :taggings, source: :taggable, source_type: Article

end

The forward associations work just fine. I can ask:

Article.first.tags
#=> Article Load (0.2ms)  SELECT  "articles".* FROM "articles" ORDER BY "articles"."id" ASC LIMIT ?  [["LIMIT", 1]]
Tag Load (0.3ms)  SELECT  "tags".* FROM "tags" INNER JOIN "taggings" ON "tags"."id" = "taggings"."tag_id" WHERE "taggings"."taggable_id" = ? AND "taggings"."taggable_type" = ? LIMIT ?  [["taggable_id", 1], ["taggable_type", "Article"], ["LIMIT", 11]]
=> #<ActiveRecord::Associations::CollectionProxy [#<Tag id: 1, name: "Superhero", created_at: "2017-11-12 21:06:33", updated_at: "2017-11-12 21:06:33">, #<Tag id: 2, name: "Bat", created_at: "2017-11-12 21:06:33"...

But if I do:

Tag.first.articles
Tag Load (0.3ms)  SELECT  "tags".* FROM "tags" ORDER BY "tags"."id" ASC LIMIT ?  [["LIMIT", 1]]
TypeError: can't cast Class

I've tried several variations on the associations in the tag.rb model but can't seem to find any that works.

Body:
The source_type in the Tag's has_many :through association needs to be a string:

has_many :articles, through: :taggings, source: :taggable, source_type: "Article"


问:
Datetime objects with pandas mean function
I am new to programming so I apologize in advance if this question does not make any sens.
I noticed that when I try to calculate the mean value of a pandas data frame with a date time object formatted like this:  datetime.datetime(2014, 7, 10), it can not calculate the mean value of it however it seems to be able to calculate the minimum and maximum value of that same data frame with out a problem.

```<code>d={'one' : Series([1, 2, 3], index=['a', 'b', 'c']), 'two' :Series([datetime.datetime(2014, 7, 9) , datetime.datetime(2014, 7, 10) , datetime.datetime(2014, 7, 11) ], index=['a', 'b', 'c'])}
df=pd.DataFrame(d)

df
Out[18]:
      one        two
   a    1 2014-07-09
   b    2 2014-07-10
   c    3 2014-07-11

df.min()
Out[19]:
   one             1
   two    2014-07-09
dtype: object

df.mean()
Out[20]:
   one    2
dtype: float64
</code>```

I did notice that the min and the max function converted all the columns to objects, where as the mean function only outputs floats.
Could anyone explain to me why the mean function can only handle floats?
Is there another way I to get the mean values of a data frame with a date time object?
I can work around it by using epoch time (as integer), but it would be very convenient if there was a direct way. I use Python 2.7

I am grateful for any hints.

答:
To simplify Alex's answer (I would have added this as a comment but I don't have sufficient reputation):

```<code>import datetime
import pandas as pd

d={'one': pd.Series([1, 2, 3], index=['a', 'b', 'c']),
   'two': pd.Series([datetime.datetime(2014, 7, 9),
           datetime.datetime(2014, 7, 10),
           datetime.datetime(2014, 7, 11) ],
           index=['a', 'b', 'c'])}
df = pd.DataFrame(d)
</code>```

Which looks like:

```<code>   one   two
a   1   2014-07-09
b   2   2014-07-10
c   3   2014-07-11
</code>```

Then calculate the mean of column "two" by:

```<code>(df.two - df.two.min()).mean() + df.two.min()
</code>```

So, subtract the min of the timeseries, calculate the mean (or median) of the resulting timedeltas, and add back the min.

Body:
I am new to programming so I apologize in advance if this question does not make any sens.
I noticed that when I try to calculate the mean value of a pandas data frame with a date time object formatted like this:  datetime.datetime(2014, 7, 10), it can not calculate the mean value of it however it seems to be able to calculate the minimum and maximum value of that same data frame with out a problem.

d={'one' : Series([1, 2, 3], index=['a', 'b', 'c']), 'two' :Series([datetime.datetime(2014, 7, 9) , datetime.datetime(2014, 7, 10) , datetime.datetime(2014, 7, 11) ], index=['a', 'b', 'c'])}
df=pd.DataFrame(d)

df
Out[18]:
      one        two
   a    1 2014-07-09
   b    2 2014-07-10
   c    3 2014-07-11

df.min()
Out[19]:
   one             1
   two    2014-07-09
dtype: object

df.mean()
Out[20]:
   one    2
dtype: float64

I did notice that the min and the max function converted all the columns to objects, where as the mean function only outputs floats.
Could anyone explain to me why the mean function can only handle floats?
Is there another way I to get the mean values of a data frame with a date time object?
I can work around it by using epoch time (as integer), but it would be very convenient if there was a direct way. I use Python 2.7

I am grateful for any hints.

Body:
To simplify Alex's answer (I would have added this as a comment but I don't have sufficient reputation):

import datetime
import pandas as pd

d={'one': pd.Series([1, 2, 3], index=['a', 'b', 'c']),
   'two': pd.Series([datetime.datetime(2014, 7, 9),
           datetime.datetime(2014, 7, 10),
           datetime.datetime(2014, 7, 11) ],
           index=['a', 'b', 'c'])}
df = pd.DataFrame(d)

Which looks like:

   one   two
a   1   2014-07-09
b   2   2014-07-10
c   3   2014-07-11

Then calculate the mean of column "two" by:

(df.two - df.two.min()).mean() + df.two.min()

So, subtract the min of the timeseries, calculate the mean (or median) of the resulting timedeltas, and add back the min.


问:
parent form containing MenuStrip control
I have a simple desktop app that I've been building.  Currently it is using a bunch of buttons to navigate back and forth between forms.

Now I've decided to add a small MenuStrip control at the top to also help with navigation.

I currently have the same MenuStrip in every form with duplicate code like this:

```<code>Private Sub AddEngineToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles AddEngineToolStripMenuItem.Click
    Dim frmShowEnginesForm = New frmShowEnginesForm()
    frmShowEnginesForm.Show()
    Me.Hide()
End Sub

Private Sub EnterSpecsToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles EnterSpecsToolStripMenuItem.Click
    Dim frmEnterEngineSpecsForm = New frmEnterEngineSpecsForm()
    frmEnterEngineSpecsForm.Show()
    Me.Hide()
End Sub
</code>```

I was hoping to simplify this a bit, so that if I ever want to add another menu item, I don't have to go through all my forms and change them all.

Is there a way to create a sort-of parent control/form that contains the MenuStrip so I don't have to duplicate it across all my forms?

THanks!

答:
add new module to your project and use code bellow :

```<code>Module Module1

    Public Sub CreateMenuStrip(frm As Form)
        'create new MenuStrip control
        Dim ms As New MenuStrip
        ms.Location = New Point(0, 0)
        ms.Dock = DockStyle.Top

        'create new toolstripmenuitem
        Dim itm As New ToolStripMenuItem
        itm.Name = "miAddEngine"
        itm.Text = "Add Engine"
        'add handler what will happen when you click on this item... same for next item
        AddHandler itm.Click, AddressOf AddEngineToolStripMenuItem_Click
        ms.Items.Add(itm)

        itm = New ToolStripMenuItem
        itm.Name = "miEnterSpecs"
        itm.Text = "Enter Specs"
        AddHandler itm.Click, AddressOf EnterSpecsToolStripMenuItem_Click
        ms.Items.Add(itm)

        '...
        'there you can, latter, add new item and bellow sub add subs which will handle click or whatever
        '...

        'add control to the form
        frm.Controls.Add(ms)

    End Sub

    'subroutines which will handle Click
    Private Sub AddEngineToolStripMenuItem_Click(sender As Object, e As EventArgs)
        MsgBox("open add engine form")
    End Sub

    Private Sub EnterSpecsToolStripMenuItem_Click(sender As Object, e As EventArgs)
        MsgBox("open enter specs form")
    End Sub

End Module
</code>```

Now, from every your form(s), on load, call CreateMenuStrip(Me)

for example, in Form1 :

```<code>Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        CreateMenuStrip(Me)
End Sub
</code>```

Of course, You can always create MDI Form and his child's, putting that MenuStrip in the, for example, top of MDIForm.

Body:
I have a simple desktop app that I've been building.  Currently it is using a bunch of buttons to navigate back and forth between forms.

Now I've decided to add a small MenuStrip control at the top to also help with navigation.

I currently have the same MenuStrip in every form with duplicate code like this:

Private Sub AddEngineToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles AddEngineToolStripMenuItem.Click
    Dim frmShowEnginesForm = New frmShowEnginesForm()
    frmShowEnginesForm.Show()
    Me.Hide()
End Sub

Private Sub EnterSpecsToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles EnterSpecsToolStripMenuItem.Click
    Dim frmEnterEngineSpecsForm = New frmEnterEngineSpecsForm()
    frmEnterEngineSpecsForm.Show()
    Me.Hide()
End Sub

I was hoping to simplify this a bit, so that if I ever want to add another menu item, I don't have to go through all my forms and change them all.

Is there a way to create a sort-of parent control/form that contains the MenuStrip so I don't have to duplicate it across all my forms?

THanks!

Body:
add new module to your project and use code bellow :

Module Module1

    Public Sub CreateMenuStrip(frm As Form)
        'create new MenuStrip control
        Dim ms As New MenuStrip
        ms.Location = New Point(0, 0)
        ms.Dock = DockStyle.Top

        'create new toolstripmenuitem
        Dim itm As New ToolStripMenuItem
        itm.Name = "miAddEngine"
        itm.Text = "Add Engine"
        'add handler what will happen when you click on this item... same for next item
        AddHandler itm.Click, AddressOf AddEngineToolStripMenuItem_Click
        ms.Items.Add(itm)

        itm = New ToolStripMenuItem
        itm.Name = "miEnterSpecs"
        itm.Text = "Enter Specs"
        AddHandler itm.Click, AddressOf EnterSpecsToolStripMenuItem_Click
        ms.Items.Add(itm)

        '...
        'there you can, latter, add new item and bellow sub add subs which will handle click or whatever
        '...

        'add control to the form
        frm.Controls.Add(ms)

    End Sub

    'subroutines which will handle Click
    Private Sub AddEngineToolStripMenuItem_Click(sender As Object, e As EventArgs)
        MsgBox("open add engine form")
    End Sub

    Private Sub EnterSpecsToolStripMenuItem_Click(sender As Object, e As EventArgs)
        MsgBox("open enter specs form")
    End Sub

End Module

Now, from every your form(s), on load, call CreateMenuStrip(Me)

for example, in Form1 :

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        CreateMenuStrip(Me)
End Sub

Of course, You can always create MDI Form and his child's, putting that MenuStrip in the, for example, top of MDIForm.


问:
Cannot resolve font-face include using webpack
I am using Aliases in my webpack config to reference my font files. No matter the syntax, I cannot get the font file to resolve correctly. Other similar Stack overflow posts describe similar behavior, but don't offer a solution.

ie: Webpack @font-face relative path issue

What is the proper way to set an alias for fonts and images referenced in SCSS files? What do I need to do to make sure that these supporting assets make it from my src directory to my dist directory?

Here is my Directory structure

```<code>/
/src
    /styles
        base.scss
        fonts.scss
        ...
    /fonts
        myFont.eot
        ...
/dist
   /fonts
   /images
   /styles
       site.css
</code>```

Here is my web.config

```<code>var mainCss = new ExtractTextPlugin(pathToStyles + "main.css");
module.exports = {
    entry: './app.js',
    output: { filename: 'bundle.js'},
    resolve: {
        alias: {
            'fonts': path.resolve(__dirname, "src/fonts"),
            'styles': path.resolve(__dirname, "src/styles")
        }
    },
    module: {
        loaders: [
            {
                test: /\.(eot|svg|ttf|woff|woff2)$/,
                loader: 'file?name=dist/fonts/[name].[ext]'
            },
            {
                test: /\.scss$/,
                loader: mainCss.extract({fallback: "style-loader", use: [{
                    loader: "css-loader"
                }, {
                    loader: "sass-loader"
                }]
                })
            },
            {
                test: /src\/\.css$/,
                loader: ExtractTextPlugin.extract({fallback: "style-loader", use: ["css-loader"]})
            }]
    },
    plugins: [ mainCss ]
};
</code>```

app.js

```<code>require('./src/site.scss');
console.log('hey');
</code>```

fonts.scss

```<code>@font-face {
    font-family: 'myFont';
    src: url('~fonts/myFont.eot');
}
</code>```

site.scss

```<code>@import "~styles/base/_fonts";
body {
    color: red;
}
a {
    font-weight:bold;
    font-family: 'myFont';
}
</code>```

答:
I failed to install 'file-loader' I discovered this as I played around with the file paths to the font. Also helpful was discovering how to trigger debug output.

ie webpack --display-error-details

Body:
I am using Aliases in my webpack config to reference my font files. No matter the syntax, I cannot get the font file to resolve correctly. Other similar Stack overflow posts describe similar behavior, but don't offer a solution.

ie: Webpack @font-face relative path issue

What is the proper way to set an alias for fonts and images referenced in SCSS files? What do I need to do to make sure that these supporting assets make it from my src directory to my dist directory?

Here is my Directory structure

/
/src
    /styles
        base.scss
        fonts.scss
        ...
    /fonts
        myFont.eot
        ...
/dist
   /fonts
   /images
   /styles
       site.css

Here is my web.config

var mainCss = new ExtractTextPlugin(pathToStyles + "main.css");
module.exports = {
    entry: './app.js',
    output: { filename: 'bundle.js'},
    resolve: {
        alias: {
            'fonts': path.resolve(__dirname, "src/fonts"),
            'styles': path.resolve(__dirname, "src/styles")
        }
    },
    module: {
        loaders: [
            {
                test: /\.(eot|svg|ttf|woff|woff2)$/,
                loader: 'file?name=dist/fonts/[name].[ext]'
            },
            {
                test: /\.scss$/,
                loader: mainCss.extract({fallback: "style-loader", use: [{
                    loader: "css-loader"
                }, {
                    loader: "sass-loader"
                }]
                })
            },
            {
                test: /src\/\.css$/,
                loader: ExtractTextPlugin.extract({fallback: "style-loader", use: ["css-loader"]})
            }]
    },
    plugins: [ mainCss ]
};

app.js

require('./src/site.scss');
console.log('hey');

fonts.scss

@font-face {
    font-family: 'myFont';
    src: url('~fonts/myFont.eot');
}

site.scss

@import "~styles/base/_fonts";
body {
    color: red;
}
a {
    font-weight:bold;
    font-family: 'myFont';
}


问:
how to read a specific position in the last line using python
I have a txt file that is too large and has several similar lines, like this:

word1 word2 word3 word4 -553.75

I am interested in the position [4] "the value", that of the last line -553.75

my file text:

```<code>.
.
word1 word2 word3 word4 -553.20
.
.
.
word1 word2 word3 word4 -553.25
.
.
.
word1 word2 word3 word4 -553.75
.
.
.
</code>```

my script :

```<code>def main():
    oTE_list = []
    oTE = []

    with open("file.txt","r") as f:
    text = f.readlines()
    for line in text:
        if line[0] == 'word1' and line[1] == 'word2' and line[2] == 'word3' and line[3] == 'word4':
      oTE_list.append(line[4])

    # Change Lists To Number Format
    for idx, item in enumerate(oTE_list):
        if idx == len(oTE_list) - 1:
            print(item)

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

but I do not know why it does not work with me!

thank you in advance.

答:
The line is string not list of word, to convert it to list of word use split and strip before to get rid of \n

```<code>def main():
    oTE_list = []
    oTE = []

    with open("file.txt","r") as f:
    text = f.readlines()
    for line in text:
        line = line.strip().split()
        if line[0] == 'FINAL' and line[1] == 'SINGLE' and line[2] == 'POINT' and line[3] == 'ENERGY':
            oTE_list.append(line[4])

    # Change Lists To Number Format
    for idx, item in enumerate(oTE_list):
        if idx == len(oTE_list) - 1:
            print(item)

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

Body:
I have a txt file that is too large and has several similar lines, like this:

word1 word2 word3 word4 -553.75

I am interested in the position [4] "the value", that of the last line -553.75

my file text:

.
.
word1 word2 word3 word4 -553.20
.
.
.
word1 word2 word3 word4 -553.25
.
.
.
word1 word2 word3 word4 -553.75
.
.
.

my script :

def main():
    oTE_list = []
    oTE = []

    with open("file.txt","r") as f:
    text = f.readlines()
    for line in text:
        if line[0] == 'word1' and line[1] == 'word2' and line[2] == 'word3' and line[3] == 'word4':
      oTE_list.append(line[4])

    # Change Lists To Number Format
    for idx, item in enumerate(oTE_list):
        if idx == len(oTE_list) - 1:
            print(item)

if __name__ == '__main__':
    main()

but I do not know why it does not work with me!

thank you in advance.

Body:
The line is string not list of word, to convert it to list of word use split and strip before to get rid of \n

def main():
    oTE_list = []
    oTE = []

    with open("file.txt","r") as f:
    text = f.readlines()
    for line in text:
        line = line.strip().split()
        if line[0] == 'FINAL' and line[1] == 'SINGLE' and line[2] == 'POINT' and line[3] == 'ENERGY':
            oTE_list.append(line[4])

    # Change Lists To Number Format
    for idx, item in enumerate(oTE_list):
        if idx == len(oTE_list) - 1:
            print(item)

if __name__ == '__main__':
    main()


问:
NPE when trying to generate a certificate
I'm getting the following error when trying to generate an X509 certificate on android

java.lang.NullPointerException: Attempt to invoke virtual method 'java.security.PublicKey java.security.cert.X509Certificate.getPublicKey()' on a null object reference

Below is the code I use to achieve this:

```<code>            AssetFileDescriptor assetFileDescriptor = this.getAssets().openFd("cert.cer");
        FileDescriptor securityCertificate = assetFileDescriptor.getFileDescriptor();

        FileInputStream fin = new FileInputStream(securityCertificate);
        CertificateFactory cf = CertificateFactory.getInstance("X.509", "BC");
        X509Certificate certificate = (X509Certificate) cf.generateCertificate(fin);
</code>```

The error seem to be happening on cf.generateCertificate(fin)

答:
Managed to solve this by using InputStream instead of FileInputStream, the code below works fine for me:</p>

```<code>        InputStream inputStream = assetManager.open("cert.cer");
        CertificateFactory cf = CertificateFactory.getInstance("X.509", "BC");
        X509Certificate certificate = (X509Certificate) cf.generateCertificate(inputStream);
</code>```

Body:
I'm getting the following error when trying to generate an X509 certificate on android

java.lang.NullPointerException: Attempt to invoke virtual method 'java.security.PublicKey java.security.cert.X509Certificate.getPublicKey()' on a null object reference

Below is the code I use to achieve this:

            AssetFileDescriptor assetFileDescriptor = this.getAssets().openFd("cert.cer");
        FileDescriptor securityCertificate = assetFileDescriptor.getFileDescriptor();

        FileInputStream fin = new FileInputStream(securityCertificate);
        CertificateFactory cf = CertificateFactory.getInstance("X.509", "BC");
        X509Certificate certificate = (X509Certificate) cf.generateCertificate(fin);

The error seem to be happening on cf.generateCertificate(fin)

Body:
Managed to solve this by using InputStream instead of FileInputStream, the code below works fine for me:

        InputStream inputStream = assetManager.open("cert.cer");
        CertificateFactory cf = CertificateFactory.getInstance("X.509", "BC");
        X509Certificate certificate = (X509Certificate) cf.generateCertificate(inputStream);


问:
Selecting MySql table data into an array
I try to catch data from mysql to put them all in array.
Suppose:

```<code>    users table
    -----------------------
    id| name | code
    ----------------------
    1| gorge | 2132
    2| flix | ksd02
    3| jasmen | skaod2

    $sql = mysql_query("select id, name, code from users");
    $userinfo = array()
    while($row_user = mysql_fetch_array($sql)){
    $userinfo = $row_user[name]
    }
-------------------------
foreach($userinfo as $usinfo){
echo $usinfo."<br/>";
}
</code>```

Here is the problem i can only insert user name but cant insert also code & id in userinfo array please help me to insert all data in same array.

[P.S] No object oriented please.

答:
```<code>while($row_user = mysql_fetch_assoc($sql)){
   $userinfo[] = $row_user;
}

foreach($userinfo as $usrinfo){
   echo "Id: ".$usrinfo['id']."<br />";
   echo "Name: ".$usrinfo['name']."<br />";
   echo "Code: ".$usrinfo['code']."<br />";
}
</code>```

Body:
I try to catch data from mysql to put them all in array.
Suppose:

    users table
    -----------------------
    id| name | code
    ----------------------
    1| gorge | 2132
    2| flix | ksd02
    3| jasmen | skaod2

    $sql = mysql_query("select id, name, code from users");
    $userinfo = array()
    while($row_user = mysql_fetch_array($sql)){
    $userinfo = $row_user[name]
    }
-------------------------
foreach($userinfo as $usinfo){
echo $usinfo."
";
}

Here is the problem i can only insert user name but cant insert also code & id in userinfo array please help me to insert all data in same array.

[P.S] No object oriented please.

ContentLicense: CC BY-SA 2.5


问:
Django - How can I prevent access to other users' objects?
Let's assume that I have such URL users/{id}/objects and I am authenticated as a User with ID equals 1. At the moment I can access objects of users with ID equals 2, 3 etc. Does anyone have an idea how can I prevent this?

```<code>class UserObject(GenericAPIView):

    permission_classes = [UserPermission]
    def get(self, request, user_id):

            try:
                object = Object.objects.filter(user=user_id)
            except Object.DoesNotExist:
                return Response(status=status.HTTP_404_NOT_FOUND)
            serializer = ObjectSerializer(object, many=True)
            return Response(serializer.data)

class UserPermission(permissions.BasePermission):

    def has_permission(self, request, view):
        if request.user and request.user.is_authenticated():
            return True
        return False
</code>```

I tried in this way:

```<code>serializer_class = ObjectSerializer
permission_classes = [IsAuthenticated, ]

def get_queryset(self):
    return Object.objects.filter(owner=self.request.user)

def get(self, request, user_id):

        try:
            object = Object.objects.filter(user=user_id)
        except Object.DoesNotExist:
            return Response(status=status.HTTP_404_NOT_FOUND)
        serializer = ObjectSerializer(object, many=True)
        return Response(serializer.data)
</code>```

答:
If you overload the view's get_queryset to only return objects belonging to the current user then Django will handle the appropriate errors and responses on its own.  For example,

```<code>class MyView(GenericAPIView):

    serializer_class = serializers.MySerializer
    permission_classes = (IsAuthenticated,)

    def get_queryset(self):
        return MyModel.objects.filter(owner=self.request.user)
</code>```

See also http://www.django-rest-framework.org/api-guide/generic-views/#attributes

Body:
Let's assume that I have such URL users/{id}/objects and I am authenticated as a User with ID equals 1. At the moment I can access objects of users with ID equals 2, 3 etc. Does anyone have an idea how can I prevent this?

class UserObject(GenericAPIView):

    permission_classes = [UserPermission]
    def get(self, request, user_id):

            try:
                object = Object.objects.filter(user=user_id)
            except Object.DoesNotExist:
                return Response(status=status.HTTP_404_NOT_FOUND)
            serializer = ObjectSerializer(object, many=True)
            return Response(serializer.data)

class UserPermission(permissions.BasePermission):

    def has_permission(self, request, view):
        if request.user and request.user.is_authenticated():
            return True
        return False

I tried in this way:

serializer_class = ObjectSerializer
permission_classes = [IsAuthenticated, ]

def get_queryset(self):
    return Object.objects.filter(owner=self.request.user)

def get(self, request, user_id):

        try:
            object = Object.objects.filter(user=user_id)
        except Object.DoesNotExist:
            return Response(status=status.HTTP_404_NOT_FOUND)
        serializer = ObjectSerializer(object, many=True)
        return Response(serializer.data)

Body:
If you overload the view's get_queryset to only return objects belonging to the current user then Django will handle the appropriate errors and responses on its own.  For example,

class MyView(GenericAPIView):

    serializer_class = serializers.MySerializer
    permission_classes = (IsAuthenticated,)

    def get_queryset(self):
        return MyModel.objects.filter(owner=self.request.user)

See also http://www.django-rest-framework.org/api-guide/generic-views/#attributes


问:
Sort a list by a custom order
I have an array of some types

```<code>private string[] linkTypes = {
    "dog",
    "cat",
    // and so on ..
};
</code>```

Yes, I could use an enum but in this case it has to be an array of
  strings.

So now I have a List of objects called "LinkElement"

```<code>private List<LinkElement> links = new List<LinkElement>();
</code>```

and these objects have a string property called "Type"

```<code>string linkType = links[index].Type;
</code>```

If linkTypes contains the elements "dog" and "cat", my links can only have "dog" or "cat" as their type.

I want to sort the list "links" by the order of linkTypes.

Means the lists order contains the links with having the type "dog" first and after that the links with the type "cat" come up.

```<code>List<LinkElement> sortedLinks = ; // sort links

for (int i = 0; i < sortedLinks.Count; i++)
{
    LinkElement currentLink = sortedLinks[i];
    Console.WriteLine(currentLink.Type);
}

// Write down dogs first, cats after
</code>```

Can someone help me out?

答:
Implement either the IComparer or the IComparable interface. The downside of using the IComparable is that this has to be implemented by the class which is targeted for sorting, which means that in case you want to sort it a different way elsewhere in your code, you will not be able to do so using this mechanism. On the other hand, IComparer can be decoupled from the target class and implemented in multiple ways if you choose to, and depending on the sorting criteria in different parts of your application, you could apply one of these IComparer classes as needed.

https://support.microsoft.com/en-us/help/320727/how-to-use-the-icomparable-and-icomparer-interfaces-in-visual-c

Title: Sort a list by a custom order

Body:
I have an array of some types

private string[] linkTypes = {
    "dog",
    "cat",
    // and so on ..
};

Yes, I could use an enum but in this case it has to be an array of
  strings.

So now I have a List of objects called "LinkElement"

private List<LinkElement> links = new List<LinkElement>();

and these objects have a string property called "Type"

string linkType = links[index].Type;

If linkTypes contains the elements "dog" and "cat", my links can only have "dog" or "cat" as their type.

I want to sort the list "links" by the order of linkTypes.

Means the lists order contains the links with having the type "dog" first and after that the links with the type "cat" come up.

List<LinkElement> sortedLinks = ; // sort links

for (int i = 0; i < sortedLinks.Count; i++)
{
    LinkElement currentLink = sortedLinks[i];
    Console.WriteLine(currentLink.Type);
}

// Write down dogs first, cats after

Can someone help me out?


问:
Removing "NUL" characters
I have got characters like that in my notepad++

When i am trying to copy whole line, i am actually copying everything until "NUL":

```<code>File:1
</code>```

What i want to do, is replace those null, to be nothing, so i can copy my whole line.
Maybe there is any keyword that will tell notepad++(or any other program that might help) to replace those characters?
When i am selecting it, use Right Click and then "clear", its gone - but i dont want to do it one by one.

I don't care about removing the cause of this problem, just the effect(NULs)

答:
Open Notepad++

Select Replace (Ctrl/H)

Find what: \x00

Replace with:

Click on radio button Regular expression

Click on Replace All

Title: Removing "NUL" characters

Body:
I have got characters like that in my notepad++

When i am trying to copy whole line, i am actually copying everything until "NUL":

File:1

What i want to do, is replace those null, to be nothing, so i can copy my whole line.
Maybe there is any keyword that will tell notepad++(or any other program that might help) to replace those characters?
When i am selecting it, use Right Click and then "clear", its gone - but i dont want to do it one by one.

I don't care about removing the cause of this problem, just the effect(NULs)


问:
ColdFusion Hardlink vs SoftLink traversal searching for Application.cfc (Solaris)
Using the following directory structure on a Solaris 11.3 box running ColdFusion 11. Apache is configured to follow Symbolic links. I have tried using all the following ColdFusion configuration options ( Default order,   Until webroot,  In webroot). The test2.cfm wont grab the #DATASOURCE# from the Application.cfm and so it is undefined.

```<code>/webroot
    - Application.cfm
   /dir1
      /dir2
        /dir3
           -test1.cfm
        /dir4 (softlink to random directory)
           -test2.cfm
</code>```

---------Application.cfm-------------

```<code><CFSET DATASOURCE = "bob" >
<CFAPPLICATION NAME = "bob_app" SESSIONMANAGEMENT = "YES" >
<CFSET SESSION.USERID = "0" >
</code>```

---------test1/test2.cfm-------------

```<code><cfoutput>
The data source name is #DATASOURCE#
</cfoutput>
</code>```

Any Suggestions on how to properly add the symbolic link so that search path includes the Application.cfm in the linked directory parent.

答:
I suspect the traversal is getting messed up in the upward recursion because the directory operations are scanning upward from the absolute path of the symlinked directory - which is why symlinks aren't a good pattern for anything traversing up.

I would suggest not using symlinks for any directories which are extensions of the main application - other than static assets.

Alternately, though it's messy and less than ideal, you could just add an Application.cfm to those directories and add <cfinclude template="/Application.cfm"/> ( or include "/Application.cfm"; ) in a <cfscript> block to the beginning of the file.

Body:
Using the following directory structure on a Solaris 11.3 box running ColdFusion 11. Apache is configured to follow Symbolic links. I have tried using all the following ColdFusion configuration options ( Default order,   Until webroot,  In webroot). The test2.cfm wont grab the #DATASOURCE# from the Application.cfm and so it is undefined.

/webroot
    - Application.cfm
   /dir1
      /dir2
        /dir3
           -test1.cfm
        /dir4 (softlink to random directory)
           -test2.cfm

---------Application.cfm-------------

<CFSET DATASOURCE = "bob" >
<CFAPPLICATION NAME = "bob_app" SESSIONMANAGEMENT = "YES" >
<CFSET SESSION.USERID = "0" >

---------test1/test2.cfm-------------

<cfoutput>
The data source name is #DATASOURCE#
</cfoutput>

Any Suggestions on how to properly add the symbolic link so that search path includes the Application.cfm in the linked directory parent.


问:
What file format do we need to upload variables through the admin in airflow?
I'm trying to define a variable file to upload through the airflow UI and I'm struggling to find the correct format to upload.

I've created a file called settings.cfg that looks like:

```<code>my_var=test
</code>```

However when I try to upload this through the Airflow Admin->Variables dialog I get the following message:

```<code>Missing file or syntax error.
</code>```

What am I missing?

答:
It expects JSON.

```<code>{
  "my_var": "test",
  "your_var": "hello"
}
</code>```

Reference: https://github.com/apache/incubator-airflow/blob/1.8.2/airflow/www/views.py#L1766-L1779

Body:
I'm trying to define a variable file to upload through the airflow UI and I'm struggling to find the correct format to upload.

I've created a file called settings.cfg that looks like:

my_var=test

However when I try to upload this through the Airflow Admin->Variables dialog I get the following message:

Missing file or syntax error.

What am I missing?

Body:
It expects JSON.

{
  "my_var": "test",
  "your_var": "hello"
}

Reference: https://github.com/apache/incubator-airflow/blob/1.8.2/airflow/www/views.py#L1766-L1779


问:
Application-scope Variables in Node.js?
Is there a variable scope in Node.js that persists longer than the request, that is available to all application users? I'd like to create a variable that can be read/written to by multiple app users, like so:

```<code>var appScope.appHitCount += 1;
</code>```

The session scope won't work because it is user specific. Looking for application specific. I couldn't find anything in the Node.js docs. Thanks.

答:
If you have a variable scoped to the app module it will be available and shared by everything within the scope. I imagine in a big app you would need to be careful with this, but it's just regular javascript scoping. For example this will continue to append to the array as you hit it:

```<code>const express = require('express')
const app = express()
var input = []

app.get('/:input/', (req, res) => {
    var params = req.params
    input.push(params.input)
    res.send("last input was: " + JSON.stringify(input))
})

app.listen(8080, () => console.log('Example app listening on port 8080!'))
</code>```

Now visiting 'http://localhost:8080/hi' returns:

last input was: ["hi"]

and then 'http://localhost:8080/there' returns:

last input was: ["hi", "there"]

...etc.

If you want something shared by the entire app (i.e. all the modules) you could set up a module that is require()d by all the modules and i=has the responsibility of getting and setting that value.

Title: Application-scope Variables in Node.js?

Body:
Is there a variable scope in Node.js that persists longer than the request, that is available to all application users? I'd like to create a variable that can be read/written to by multiple app users, like so:

var appScope.appHitCount += 1;

The session scope won't work because it is user specific. Looking for application specific. I couldn't find anything in the Node.js docs. Thanks.

Body:
If you have a variable scoped to the app module it will be available and shared by everything within the scope. I imagine in a big app you would need to be careful with this, but it's just regular javascript scoping. For example this will continue to append to the array as you hit it:

const express = require('express')
const app = express()
var input = []

app.get('/:input/', (req, res) => {
    var params = req.params
    input.push(params.input)
    res.send("last input was: " + JSON.stringify(input))
})

app.listen(8080, () => console.log('Example app listening on port 8080!'))

Now visiting 'http://localhost:8080/hi' returns:

last input was: ["hi"]

and then 'http://localhost:8080/there' returns:

last input was: ["hi", "there"]

...etc.

If you want something shared by the entire app (i.e. all the modules) you could set up a module that is require()d by all the modules and i=has the responsibility of getting and setting that value.


问:
How can I see all the data that solr is indexing?
So I have a solr server running as part of a chef server. Some of my nodes just aren't coming up in searches. I can use ?q=*:* to show the documents but most of the chef data is indexed as dynamicFields, so I don't see it in the xml documents.

I'm hoping that if I can find a way to see either:

what's coming into solr as it's indexed or

the full set of indexed documents with their dynamic fields

Thanks in advance!

答:
Luke may help: https://github.com/DmitryKey/luke. You can point it at the Solr index and see what's in there.

Last time I checked, you could run it right from the web and just point it at the index.

ContentLicense: CC BY-SA 4.0


问:
Javascript file not including inside html page
I'm trying to use JQuery inside a ASP.NET MVC practice project but the site.js file not working or including inside html page. If I write JQuery code inside script tag in html then it's working fine, Even I have included some other files like Bootstrap and site.css that also working only problem with site.js file.

Site.js

```<code>$(document).ready(function () {
    alert("Hello 1");
});

$(window).load(function () {
    alert("Hello 2");
});
</code>```

_Layout.cshtml

Including snippet

```<code><script src="~/lib/jquery/dist/jquery.min.js" type="text/javascript"></script>
<script src="~/js/site.js" type="text/javascript"></script>
<script src="~/lib/jquery-validation/dist/jquery.validate.min.js" type="text/javascript"></script>
</code>```

答:
Since we don't want to guess and have no view of your specific project do this:

Open your project.

Find the missing js file in the project

Open your layout file

In Visual Studio, drag the js file and drop it on the layout file

Revise your layout to use the js file location as in the dropped link

Test

Note normally it is a "Scripts" folder by default

Body:
I'm trying to use JQuery inside a ASP.NET MVC practice project but the site.js file not working or including inside html page. If I write JQuery code inside script tag in html then it's working fine, Even I have included some other files like Bootstrap and site.css that also working only problem with site.js file.

Site.js

$(document).ready(function () {
    alert("Hello 1");
});

$(window).load(function () {
    alert("Hello 2");
});

_Layout.cshtml

Including snippet


问:
addRange not working on Chrome version 61
I have been using the following code to handle copy events for quite a while:

```<code>range.selectNodeContents(el);
sel.removeAllRanges();
sel.addRange(range);
</code>```

Some of my users are now reporting that the copy event is not working in Chrome. I've noticed that since the release of version 61, this seems to be happening. Is there an alternative to copying element contents to the clipboard in the newer versions of Chrome?

答:
try this code:

```<code>let sel = window.getSelection();
    sel.removeAllRanges();
    let range = document.createRange();
    range.selectNodeContents(el);
    el.contentEditable = true;
    el.focus();
    sel.addRange(range);
</code>```

if this code don't work , try
use youre code without

```<code>sel.removeAllRanges();
</code>```

because  removeAllranges will be deprecated, and selection could has only one range

I used code (example)

```<code>let range = document.createRange();
let sel = window.getSelection();
range.selectNodeContents(document.body);
sel.addRange(range);
</code>```

and it work(tested in chrome 62).
Maybe el node  do not visible or DOM hasn't this node. Without all code I can't help you.

Body:
I have been using the following code to handle copy events for quite a while:

range.selectNodeContents(el);
sel.removeAllRanges();
sel.addRange(range);

Some of my users are now reporting that the copy event is not working in Chrome. I've noticed that since the release of version 61, this seems to be happening. Is there an alternative to copying element contents to the clipboard in the newer versions of Chrome?

Body:
try this code:

let sel = window.getSelection();
    sel.removeAllRanges();
    let range = document.createRange();
    range.selectNodeContents(el);
    el.contentEditable = true;
    el.focus();
    sel.addRange(range);

if this code don't work , try
use youre code without

sel.removeAllRanges();

because  removeAllranges will be deprecated, and selection could has only one range

I used code (example)

let range = document.createRange();
let sel = window.getSelection();
range.selectNodeContents(document.body);
sel.addRange(range);

and it work(tested in chrome 62).
Maybe el node  do not visible or DOM hasn't this node. Without all code I can't help you.


问:
Recursive function not returning to immediate caller
I have written a recursive implementation for finding some specific path given some n*n matrix using this psuedocode I found on stackoverflow . I have constructed two arrays:

path weight array that holds the edge  value going from one vertex in our graph to another (cell matrix to neighboring cells in matrix)

an adjacency array for each index in our path weight array

For some reason however my when my recursive function returns it doesn't return to the immediate caller?

My implementation:

```<code>        // find paths of specific length from our starting cell 1,1
        // when a path is found print it
        // otherwise return?
        function findPaths(adjMatrix, pathW_array, path, pathWeight, x, y, idx, curpath_idx){
            // set curpath to the current path (an array with storing path weight values)
            var curpath = path;
            // tempArray with store pathW_array (set cell value to -1 if value has been added to curpath)
            var tempArray = pathW_array;

            // curValue retruns sum value of our curpath
            if ( (curValue(curpath) == pathWeight) && (Object.keys(curpath).length !=1)){
                for(i = 0; i < Object.keys(curpath).length; i++){
                    console.log(curpath[i]);
                }
                return;
            }if(tempArray[x][y] == -1){
                return;
            }if(curValue(curpath) > pathWeight){
                return;
            }

            // Did not return, add current cell value to curpath array
            curpath[curpath_idx] = tempArray[x][y];
            curpath_idx = curpath_idx + 1;
            // set current cell value in tempArray to -1 because we've added it to current path (do not want to add same cell value multiple times)
            tempArray[x][y] = -1;

            // iterate until i = pathWeight -1
            for(var i = 0; i < pathWeight; i++){
                if(adjMatrix[idx][i] != -1){
                     // get pathW_array indices for next neighbor cell of current element
                     arrayIndices = neighbor_value(adjMatrix, tempArray, idx);
                     x = arrayIndices[0];
                     y = arrayIndices[1];
                     adjMatrix[idx][i] = -1;
                     idx = adjMatrix_idx(x,y);

                    // findpaths from the next cell in the matrix
                    findPaths(adjMatrix, tempArray, curpath, pathWeight, x, y, idx, curpath_idx);
                    curpath.pop();
                    curpath_idx = curpath -1;
                }
            }
        }
</code>```

答:
Change the following line:

```<code>findPaths(adjMatrix, tempArray, curpath, pathWeight, x, y, idx, curpath_idx)
</code>```

to

```<code>return findPaths(adjMatrix, tempArray, curpath, pathWeight, x, y, idx, curpath_idx)
</code>```

Without understanding the rest of the complexity in the function, this 'should' return the recursive return value up the call stack.

Body:
I have written a recursive implementation for finding some specific path given some n*n matrix using this psuedocode I found on stackoverflow . I have constructed two arrays:

path weight array that holds the edge  value going from one vertex in our graph to another (cell matrix to neighboring cells in matrix)

an adjacency array for each index in our path weight array

For some reason however my when my recursive function returns it doesn't return to the immediate caller?

My implementation:

        // find paths of specific length from our starting cell 1,1
        // when a path is found print it
        // otherwise return?
        function findPaths(adjMatrix, pathW_array, path, pathWeight, x, y, idx, curpath_idx){
            // set curpath to the current path (an array with storing path weight values)
            var curpath = path;
            // tempArray with store pathW_array (set cell value to -1 if value has been added to curpath)
            var tempArray = pathW_array;

            // curValue retruns sum value of our curpath
            if ( (curValue(curpath) == pathWeight) && (Object.keys(curpath).length !=1)){
                for(i = 0; i < Object.keys(curpath).length; i++){
                    console.log(curpath[i]);
                }
                return;
            }if(tempArray[x][y] == -1){
                return;
            }if(curValue(curpath) > pathWeight){
                return;
            }

            // Did not return, add current cell value to curpath array
            curpath[curpath_idx] = tempArray[x][y];
            curpath_idx = curpath_idx + 1;
            // set current cell value in tempArray to -1 because we've added it to current path (do not want to add same cell value multiple times)
            tempArray[x][y] = -1;

            // iterate until i = pathWeight -1
            for(var i = 0; i < pathWeight; i++){
                if(adjMatrix[idx][i] != -1){
                     // get pathW_array indices for next neighbor cell of current element
                     arrayIndices = neighbor_value(adjMatrix, tempArray, idx);
                     x = arrayIndices[0];
                     y = arrayIndices[1];
                     adjMatrix[idx][i] = -1;
                     idx = adjMatrix_idx(x,y);

                    // findpaths from the next cell in the matrix
                    findPaths(adjMatrix, tempArray, curpath, pathWeight, x, y, idx, curpath_idx);
                    curpath.pop();
                    curpath_idx = curpath -1;
                }
            }
        }

Body:
Change the following line:

findPaths(adjMatrix, tempArray, curpath, pathWeight, x, y, idx, curpath_idx)

to

return findPaths(adjMatrix, tempArray, curpath, pathWeight, x, y, idx, curpath_idx)

Without understanding the rest of the complexity in the function, this 'should' return the recursive return value up the call stack.


问:
SQL - UPDATE (Using existing rows in same table)
I have a table (see below:  Current Table) in which I need to UPDATE Row# 5 because a value for ID1 already exist (Row# 4) and a value for ID3 already exist (Row# 3).  There are three (3) use cases on which to UPDATE the table.

Additional context:  In the final state, ID1 will have one and only one ID2, but can have many ID3.  ID3 can have many ID1 and ID2.  ID1 and ID3 are unique values, iff ID1 OR ID3 does not exist in table, then ID2 is assigned the value of ID1.

Use cases for UPDATE

An existing row (smaller row # and TIME value) has the same ID1
value.  Use the ID2 value for that existing ID1 value.

An existing row (smaller row # and TIME value) has the same ID3 value.  Use the ID2 value for that existing ID3 value.

Both ID1 and ID3 values exist (Not the same rows though).  Use the ID2 value from the row with the smallest (oldest) TIME value.

Current Table

```<code>Row    ID1    ID2    ID3    TIME
1      A      A      123    12:01AM
2      A      A      456    12:05AM
3      A      A      789    12:10AM
4      B      A      123    12:15AM
5      B      B      789    12:20AM
6      C      C      987    12:25AM
</code>```

Updated Table

```<code>Row    ID1    ID2    ID3    TIME
1      A      A      123    12:01AM
2      A      A      456    12:05AM
3      A      A      789    12:10AM
4      B      A      123    12:15AM
5      B      A      789    12:20AM
6      C      C      987    12:25AM
</code>```

答:
I think your conditions simplify to getting the earliest id2 from a matching id1 or id3:

```<code>update t
    set id2 = tt.new_id
    from (select t.*,
                 (select t2.id2
                  from t t2
                  where t2.id1 = t.id1 or t2.id3 = t.id3
                 ) as new_id
          from t
         ) tt
    where t.id1 = tt.id1;
</code>```

Body:
I have a table (see below:  Current Table) in which I need to UPDATE Row# 5 because a value for ID1 already exist (Row# 4) and a value for ID3 already exist (Row# 3).  There are three (3) use cases on which to UPDATE the table.

Additional context:  In the final state, ID1 will have one and only one ID2, but can have many ID3.  ID3 can have many ID1 and ID2.  ID1 and ID3 are unique values, iff ID1 OR ID3 does not exist in table, then ID2 is assigned the value of ID1.

Use cases for UPDATE

An existing row (smaller row # and TIME value) has the same ID1
value.  Use the ID2 value for that existing ID1 value.

An existing row (smaller row # and TIME value) has the same ID3 value.  Use the ID2 value for that existing ID3 value.

Both ID1 and ID3 values exist (Not the same rows though).  Use the ID2 value from the row with the smallest (oldest) TIME value.

Current Table

Row    ID1    ID2    ID3    TIME
1      A      A      123    12:01AM
2      A      A      456    12:05AM
3      A      A      789    12:10AM
4      B      A      123    12:15AM
5      B      B      789    12:20AM
6      C      C      987    12:25AM

Updated Table

Row    ID1    ID2    ID3    TIME
1      A      A      123    12:01AM
2      A      A      456    12:05AM
3      A      A      789    12:10AM
4      B      A      123    12:15AM
5      B      A      789    12:20AM
6      C      C      987    12:25AM

Body:
I think your conditions simplify to getting the earliest id2 from a matching id1 or id3:

update t
    set id2 = tt.new_id
    from (select t.*,
                 (select t2.id2
                  from t t2
                  where t2.id1 = t.id1 or t2.id3 = t.id3
                 ) as new_id
          from t
         ) tt
    where t.id1 = tt.id1;


问:
EmbedMany Strings in an MongoDB Document?
I need to have a simple array/collection of strings in my Document, but cannot work out a way to acheive this with Doctrine ODM.

This is an example class/document, with $tags needing to be a simple array of strings:

```<code>namespace Acme\ExampleBundle\Document;
use Doctrine\ODM\MongoDB\Mapping\Annotations as MongoDB;

/** @MongoDB\Document */
class MyDocument {

    /** @MongoDB\Id */
    protected $id;

    /** @MongoDB\String */
    protected $name;

    /** @MongoDB\EmbedMany */
    protected $tags = array();
}
</code>```

I've tried different things like @MongoDB\EmbedMany or @MongoDB\EmbedMany(targetDocument="String") I know there is no reason for the last one to work, but I was just trying anything I could think of.

The end result in the Mongo DB as JSON is as simple as this:

```<code>{
    "_id": ObjectId("a0afa410caeea70de1000000"),
    "name": "Example Name",
    "tags": ["tag1", "example", "test tag"]
}
</code>```

What I need help with is, how to have the @MongoDB\EmbedMany annotation to allow me to add only strings into the Collection, which will then look like the above JSON when persisted to the DB.

I hope someone can help, as I'm really stuck with this now. It feels like it should be so simple!

答:
also type="collection" works same way as hash

```<code> /**
 * @MongoDB\Field(type="collection")
 */

protected $possibleTags;

/**
 * Set tags
 *
 * @param collection $possibleTags
 * @return $this
 */
public function setPossibleTags($possibleTags)
{
    $this->possibleTags = $possibleTags;
    return $this;
}

/**
 * Get tags
 *
 * @return collection $tags
 */
public function getPossibleTags()
{
    return $this->possibleTags;
}
</code>```

Body:
I need to have a simple array/collection of strings in my Document, but cannot work out a way to acheive this with Doctrine ODM.

This is an example class/document, with $tags needing to be a simple array of strings:

namespace Acme\ExampleBundle\Document;
use Doctrine\ODM\MongoDB\Mapping\Annotations as MongoDB;

/** @MongoDB\Document */
class MyDocument {

    /** @MongoDB\Id */
    protected $id;

    /** @MongoDB\String */
    protected $name;

    /** @MongoDB\EmbedMany */
    protected $tags = array();
}

I've tried different things like @MongoDB\EmbedMany or @MongoDB\EmbedMany(targetDocument="String") I know there is no reason for the last one to work, but I was just trying anything I could think of.

The end result in the Mongo DB as JSON is as simple as this:

{
    "_id": ObjectId("a0afa410caeea70de1000000"),
    "name": "Example Name",
    "tags": ["tag1", "example", "test tag"]
}

What I need help with is, how to have the @MongoDB\EmbedMany annotation to allow me to add only strings into the Collection, which will then look like the above JSON when persisted to the DB.

I hope someone can help, as I'm really stuck with this now. It feels like it should be so simple!

Body:
also type="collection" works same way as hash

 /**
 * @MongoDB\Field(type="collection")
 */

protected $possibleTags;

/**
 * Set tags
 *
 * @param collection $possibleTags
 * @return $this
 */
public function setPossibleTags($possibleTags)
{
    $this->possibleTags = $possibleTags;
    return $this;
}

/**
 * Get tags
 *
 * @return collection $tags
 */
public function getPossibleTags()
{
    return $this->possibleTags;
}


问:
Handle too many textures Unity
At present one of my quiz game require, many images of flowers based on questions asked.
I can say total 250+ images with resolution of 512x435 each.
Plus other games textures get loaded at a time.

So when game screen get opened which showing all these images, its on the spot get crashed.
I am testing this on iPhone devices. So how to handle these many textures? I was stuck in this point.

Here is overview of flowers textures.

I was displaying all these in grid view so in one scrollable screen all get displayed.
Now I hope, you understand my side point of view.

答:
Wow. That's a lot of flowers....
Okay if you need all of those textures, and you're only displaying them in the editor, I'd group them into folders.

Even if you sort the blue from the red..... etc just human readable directories it will help out a lot as you won't load ALL of your images at once.

If you are loading all of those textures at runtime, which I don't think you would as unity optimizes your built executable, I would recommend against loading all of the images at once because you will use a lot of RAM, especially if those images are 512px or larger.

Title: Handle too many textures Unity


问:
The compilation of an array of conditions with numba.jit takes a long time
If I try to compile a function, containing an array of conditions, with numba's jit-compiler, it takes very long. The program looks essentially like

```<code>from numba import jit
import numpy as np

@jit(nopython=True)
def foo(a, b):
    valid = [
        (a - 1 >= 0) and (b - 1 >= 0),
        (a - 1 >= 0) and (b - 1 >= 0),
        (a - 1 >= 0) and (b - 1 >= 0),
        (a - 1 >= 0) and (b - 1 >= 0),
        (a - 1 >= 0) and (b - 1 >= 0),
        (a - 1 >= 0) and (b - 1 >= 0),
        (a - 1 >= 0) and (b - 1 >= 0),
        (a - 1 >= 0) and (b - 1 >= 0),
        (a - 1 >= 0) and (b - 1 >= 0),
        (a - 1 >= 0) and (b - 1 >= 0),
        (a - 1 >= 0) and (b - 1 >= 0),
        (a - 1 >= 0) and (b - 1 >= 0),
        (a - 1 >= 0) and (b - 1 >= 0),
        (a - 1 >= 0) and (b - 1 >= 0),
        (a - 1 >= 0) and (b - 1 >= 0),
        (a - 1 >= 0) and (b - 1 >= 0),
        (a - 1 >= 0) and (b - 1 >= 0),
        (a - 1 >= 0) and (b - 1 >= 0),
        (a - 1 >= 0) and (b - 1 >= 0),
        (a - 1 >= 0) and (b - 1 >= 0),
        (a - 1 >= 0) and (b - 1 >= 0),
        (a - 1 >= 0) and (b - 1 >= 0),
        (a - 1 >= 0) and (b - 1 >= 0)
    ]

foo(1, 1)
</code>```

where I have excluded everything that will not alter the compilation time significantly. The problem arises if I use more than 20 elements.

```<code>| elements | time |
-------------------
|    21    | 2.7s |
|    22    | 5.1s |
|    23    |  10s |
|   ...    |  ... |
-------------------
</code>```

Despite that, the function workes well. Does anybody know, why it takes so long, to compile such function with numba? Creating arrays in a similar way with combinations of integers or floats causes no problem.

答:
You may want to report this on the numba issue tracker, feels like something is going awry in the compiler for it to scale so poorly.

You may also consider if you really need a large number of array statements like this and if problem could be more clear refactored.  E.g. instead of array of booleans, could valid be a function called as needed?

That all said, a workaround in the current version of numba is unrolling the conditions.

For your example:

```<code># "codegen"
for i in range(23):
    print(f'    valid[{i}] = (a - 1 >= 0) and (b - 1 >= 0)')

@jit(nopython=True)
def foo(a, b):
    valid = np.empty(23, dtype=np.bool_)
    valid[0] = (a - 1 >= 0) and (b - 1 >= 0)
    valid[1] = (a - 1 >= 0) and (b - 1 >= 0)
    valid[2] = (a - 1 >= 0) and (b - 1 >= 0)
    valid[3] = (a - 1 >= 0) and (b - 1 >= 0)
    valid[4] = (a - 1 >= 0) and (b - 1 >= 0)
    valid[5] = (a - 1 >= 0) and (b - 1 >= 0)
    valid[6] = (a - 1 >= 0) and (b - 1 >= 0)
    valid[7] = (a - 1 >= 0) and (b - 1 >= 0)
    valid[8] = (a - 1 >= 0) and (b - 1 >= 0)
    valid[9] = (a - 1 >= 0) and (b - 1 >= 0)
    valid[10] = (a - 1 >= 0) and (b - 1 >= 0)
    valid[11] = (a - 1 >= 0) and (b - 1 >= 0)
    valid[12] = (a - 1 >= 0) and (b - 1 >= 0)
    valid[13] = (a - 1 >= 0) and (b - 1 >= 0)
    valid[14] = (a - 1 >= 0) and (b - 1 >= 0)
    valid[15] = (a - 1 >= 0) and (b - 1 >= 0)
    valid[16] = (a - 1 >= 0) and (b - 1 >= 0)
    valid[17] = (a - 1 >= 0) and (b - 1 >= 0)
    valid[18] = (a - 1 >= 0) and (b - 1 >= 0)
    valid[19] = (a - 1 >= 0) and (b - 1 >= 0)
    valid[20] = (a - 1 >= 0) and (b - 1 >= 0)
    valid[21] = (a - 1 >= 0) and (b - 1 >= 0)
    valid[22] = (a - 1 >= 0) and (b - 1 >= 0)

%time foo(1,1)
Wall time: 274 ms
</code>```

Body:
If I try to compile a function, containing an array of conditions, with numba's jit-compiler, it takes very long. The program looks essentially like

from numba import jit
import numpy as np

@jit(nopython=True)
def foo(a, b):
    valid = [
        (a - 1 >= 0) and (b - 1 >= 0),
        (a - 1 >= 0) and (b - 1 >= 0),
        (a - 1 >= 0) and (b - 1 >= 0),
        (a - 1 >= 0) and (b - 1 >= 0),
        (a - 1 >= 0) and (b - 1 >= 0),
        (a - 1 >= 0) and (b - 1 >= 0),
        (a - 1 >= 0) and (b - 1 >= 0),
        (a - 1 >= 0) and (b - 1 >= 0),
        (a - 1 >= 0) and (b - 1 >= 0),
        (a - 1 >= 0) and (b - 1 >= 0),
        (a - 1 >= 0) and (b - 1 >= 0),
        (a - 1 >= 0) and (b - 1 >= 0),
        (a - 1 >= 0) and (b - 1 >= 0),
        (a - 1 >= 0) and (b - 1 >= 0),
        (a - 1 >= 0) and (b - 1 >= 0),
        (a - 1 >= 0) and (b - 1 >= 0),
        (a - 1 >= 0) and (b - 1 >= 0),
        (a - 1 >= 0) and (b - 1 >= 0),
        (a - 1 >= 0) and (b - 1 >= 0),
        (a - 1 >= 0) and (b - 1 >= 0),
        (a - 1 >= 0) and (b - 1 >= 0),
        (a - 1 >= 0) and (b - 1 >= 0),
        (a - 1 >= 0) and (b - 1 >= 0)
    ]

foo(1, 1)

where I have excluded everything that will not alter the compilation time significantly. The problem arises if I use more than 20 elements.

| elements | time |
-------------------
|    21    | 2.7s |
|    22    | 5.1s |
|    23    |  10s |
|   ...    |  ... |
-------------------

Despite that, the function workes well. Does anybody know, why it takes so long, to compile such function with numba? Creating arrays in a similar way with combinations of integers or floats causes no problem.

Body:
You may want to report this on the numba issue tracker, feels like something is going awry in the compiler for it to scale so poorly.

You may also consider if you really need a large number of array statements like this and if problem could be more clear refactored.  E.g. instead of array of booleans, could valid be a function called as needed?

That all said, a workaround in the current version of numba is unrolling the conditions.

For your example:

# "codegen"
for i in range(23):
    print(f'    valid[{i}] = (a - 1 >= 0) and (b - 1 >= 0)')

@jit(nopython=True)
def foo(a, b):
    valid = np.empty(23, dtype=np.bool_)
    valid[0] = (a - 1 >= 0) and (b - 1 >= 0)
    valid[1] = (a - 1 >= 0) and (b - 1 >= 0)
    valid[2] = (a - 1 >= 0) and (b - 1 >= 0)
    valid[3] = (a - 1 >= 0) and (b - 1 >= 0)
    valid[4] = (a - 1 >= 0) and (b - 1 >= 0)
    valid[5] = (a - 1 >= 0) and (b - 1 >= 0)
    valid[6] = (a - 1 >= 0) and (b - 1 >= 0)
    valid[7] = (a - 1 >= 0) and (b - 1 >= 0)
    valid[8] = (a - 1 >= 0) and (b - 1 >= 0)
    valid[9] = (a - 1 >= 0) and (b - 1 >= 0)
    valid[10] = (a - 1 >= 0) and (b - 1 >= 0)
    valid[11] = (a - 1 >= 0) and (b - 1 >= 0)
    valid[12] = (a - 1 >= 0) and (b - 1 >= 0)
    valid[13] = (a - 1 >= 0) and (b - 1 >= 0)
    valid[14] = (a - 1 >= 0) and (b - 1 >= 0)
    valid[15] = (a - 1 >= 0) and (b - 1 >= 0)
    valid[16] = (a - 1 >= 0) and (b - 1 >= 0)
    valid[17] = (a - 1 >= 0) and (b - 1 >= 0)
    valid[18] = (a - 1 >= 0) and (b - 1 >= 0)
    valid[19] = (a - 1 >= 0) and (b - 1 >= 0)
    valid[20] = (a - 1 >= 0) and (b - 1 >= 0)
    valid[21] = (a - 1 >= 0) and (b - 1 >= 0)
    valid[22] = (a - 1 >= 0) and (b - 1 >= 0)

%time foo(1,1)
Wall time: 274 ms


问:
NUnit: OneTimeSetUp not being recognized
I just started having this issue today after updating my nuget packages, specifically the NUnit package to 3.9.1. I have always decorated my selenium test files as unit tests through NUnit and have utilized the various different tags to specify the different "parts" of each test fixture.

I use the OneTimeSetUp tag on each fixture to launch my browser and sign into the web app. I use the OneTimeTearDown tag to dispose of my driver and close the browser. I use the Test tag to specify the tests themselves, and I also have a Retry tag that I use on each test to retry based on outcome.

After updating to 3.9.1, it seems as if the OneTimeSetUp and OneTimeTearDown, along with the Retry tags are no longer recognized by visual studio, however the Test tags all are recognized.

Does anyone have any ideas as to why these attributes are no longer being recognized after working over the past few months? Any direction would be appreciated.

Thank you.

答:
Turns out on the update, for some reason it downloaded the dll of NUnit v2.6, and I'm assuming that both OneTimeSetUp and OneTimeTearDown were not present in NUnit 2.6 and my system was reading that dll instead of the new one.

I deleted NUnit 2.6 from my project and it instantly was able to recognize the other tags.


问:
Allocating Array of Pointers on Heap
Does the following create x new objects, or simply allocate space for x objects?:

```<code>Vector3D* binArray = new Vector3D[size];
</code>```

I need to build an array with space for x Vector3D objects on the heap. However, a Vector3D object can only be created when an "add" function is called - this will take the parameters, construct the object on the heap and add its address to the array of Vector3D pointers.

答:
Just to add based on the asker's comments on RayToal's excellent answer. If you don't know the size of the binArray prior to runtime then you must use std::vector. If you want to allocate each item alone, I would recommend using std::vector<Vector3D*>.

This way you can resize the std::vector at runtime and when you do, it will hold a bunch of nullptrs that are not allocated. Then you can allocate each one of them separately.

```<code>std::vector<Vector3D*> binArray;
binArray.resize(x);  // now you have binArray of size x and no allocated elements
binArray[0] = new Vector3D(...);
</code>```

Please keep in mind that you need to delete them after you're not using them in order to not have a memory leak:

```<code>for(size_t i=0;i<binArray.size(); i++)
  if(binArray[i]!=nullptr) delete binArray[i];
</code>```

Title: Allocating Array of Pointers on Heap

Body:
Does the following create x new objects, or simply allocate space for x objects?:

Vector3D* binArray = new Vector3D[size];

I need to build an array with space for x Vector3D objects on the heap. However, a Vector3D object can only be created when an "add" function is called - this will take the parameters, construct the object on the heap and add its address to the array of Vector3D pointers.

Body:
Just to add based on the asker's comments on RayToal's excellent answer. If you don't know the size of the binArray prior to runtime then you must use std::vector. If you want to allocate each item alone, I would recommend using std::vector<Vector3D*>.

This way you can resize the std::vector at runtime and when you do, it will hold a bunch of nullptrs that are not allocated. Then you can allocate each one of them separately.

std::vector<Vector3D*> binArray;
binArray.resize(x);  // now you have binArray of size x and no allocated elements
binArray[0] = new Vector3D(...);

Please keep in mind that you need to delete them after you're not using them in order to not have a memory leak:

for(size_t i=0;i<binArray.size(); i++)
  if(binArray[i]!=nullptr) delete binArray[i];


问:
Install iOS App onto Multiple Devices with Free Developer Account
Fledgling iOS hobbyist here. I have a demo app I plan on presenting to a group of people in about a month. It is a simple app, and I am still on the free tier of the Apple Developer Program for now. For this presentation, I'm being provided loaner iPhones, iPads, and MacBooks to demo my app and its code on.

I do know that I am able to load my app onto at least two devices, but they are my own personal iPhone and iPad.

My question is this: With a free developer account, will I be able to 1) load my app onto multiple iPhones and iPads (that I do not own) to demo for the duration of this presentation; and 2) load the code into Xcode on multiple Macs (that I do not own) so that I can show the code to those present. Or will I have to take the plunge and purchase the full $99/year developer account.

This isn't a code question, I know - but the Apple Developer forums are not nearly as active, and I would like a clear answer on this.

答:
Connect each iOS device to your dev machine and build your app on it. The device will ask you to trust the developer, which you can do in Settings. It's no different than debugging on your own device.

Are you showing the code or the finished app? If showing the code, make sure the other machine has Xcode, then transfer the code from your dev machine (by USB, network folder, GitHub, etc) and build on the new machine. If you are showing the finished app, make sure Gatekeeper is set to at least "Mac App Store and Identified Developer"