问:
Python for loop IndexError: list index out of range
I am somewhat new to python and I could use some help figuring out what my error entails.

```<code>datafile = "filename.csv"

colors = ['Green','White','Yellow','Pink','Blue','Purple','Gray','Brown','Orange','Red','Black']  # put in order of the columns

colnames = []
for color in colors:
    colnames.append(color+"1")
    colnames.append(color+"2")

# Define data structure to hold responses for each column
responses = dict()
for colname in colnames:
    responses[colname] = []

# Read in the responses
lines = open(datafile,"r").readlines()
for line in lines:
    data = line.strip('\n').split(",")
for i,colname in enumerate(colnames):
    if '1' in colname:
        responses[colname].append(data[i])
    else:
        responses[colname].append(data[i].split(','))

---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-21-4039ddb1f5f5> in <module>()
     21             responses[colname].append(data[i])
     22         else:
---> 23             responses[colname].append(data[i].split(','))
     24
     25 # Count the number of subjects

     IndexError: list index out of range
</code>```

I am not sure if the IndexError: list index out of range is from the actual else: or something is wrong with the responses[colname].append(data[i].split(',')).
It could also be in my for loop of the list colnames, I am fairly certain that aspect is correct, but you never know

答:
```<code>for line in lines:
    data = line.strip('\n').split(",")
</code>```

I think the above code is why you got the IndexError,because the assignment to data will overwrite the previous one, and the content of data is always the last line. (Unless you just want the last line).

e.g:

filename.csv

```<code>blue,red
red,green
yellow,red
</code>```

```<code>data=['yellow', 'red']
</code>```

That means your for loop is equivalent to
data=lines[-1].strip('\n').split(",")

So I suppose this is what you want:

```<code>data=[]
for line in lines:
    data.append(line.strip('\n').split(","))
</code>```

Or use this list comprehension:

```<code>data=[line.strip('\n').split(",") for l in lines]
</code>```

And then make sure that the length of data is greater than colnames.
By the way, try to debug your code, or print variables, you will find the reason.

Body:
I am somewhat new to python and I could use some help figuring out what my error entails.

datafile = "filename.csv"

colors = ['Green','White','Yellow','Pink','Blue','Purple','Gray','Brown','Orange','Red','Black']  # put in order of the columns

colnames = []
for color in colors:
    colnames.append(color+"1")
    colnames.append(color+"2")

# Define data structure to hold responses for each column
responses = dict()
for colname in colnames:
    responses[colname] = []

# Read in the responses
lines = open(datafile,"r").readlines()
for line in lines:
    data = line.strip('\n').split(",")
for i,colname in enumerate(colnames):
    if '1' in colname:
        responses[colname].append(data[i])
    else:
        responses[colname].append(data[i].split(','))

---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-21-4039ddb1f5f5> in <module>()
     21             responses[colname].append(data[i])
     22         else:
---> 23             responses[colname].append(data[i].split(','))
     24
     25 # Count the number of subjects

     IndexError: list index out of range

I am not sure if the IndexError: list index out of range is from the actual else: or something is wrong with the responses[colname].append(data[i].split(',')).
It could also be in my for loop of the list colnames, I am fairly certain that aspect is correct, but you never know

Body:
for line in lines:
    data = line.strip('\n').split(",")

I think the above code is why you got the IndexError,because the assignment to data will overwrite the previous one, and the content of data is always the last line. (Unless you just want the last line).

e.g:

filename.csv

blue,red
red,green
yellow,red

data=['yellow', 'red']

That means your for loop is equivalent to
data=lines[-1].strip('\n').split(",")

So I suppose this is what you want:

data=[]
for line in lines:
    data.append(line.strip('\n').split(","))

Or use this list comprehension:

data=[line.strip('\n').split(",") for l in lines]

And then make sure that the length of data is greater than colnames.
By the way, try to debug your code, or print variables, you will find the reason.


来源: stackexchange

问:
How to send values through an directive tag in angular 2
I am trying to send data through the directive metatags from one component to another but it shows error undefined when i consoled it.Can anyone please suggest me help.Thanks.

My component,

```<code>import { ModalComponent } from './modal/modal.component';
@Component({
  selector: 'my-app',
  template: `<modal [hero]="value"></modal>'
})
export class CommonComponent  {
  value : anny ='1';
</code>```

}

```<code>@Component({
  selector: 'modal',
  templateUrl : './modal/model.component.html'
})
export class CommonComponent  {
  @Input() hero:any;
  consrtuctor(){
  console.log(this.hero) ///// shows o/p as undefined
</code>```

}

答:
Take a look at lifecycle hooks.

In Angular, constructor is used for dependency injection. You need to call one of the built-in functions in component life-cycle when you want to deal with @Input() @Output() and similar decorators.

Instead of constructor() {...}, use:

```<code>ngOnInit() {
  console.log(this.hero); // not undefined
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am trying to send data through the directive metatags from one component to another but it shows error undefined when i consoled it.Can anyone please suggest me help.Thanks.

My component,

import { ModalComponent } from './modal/modal.component';
@Component({
  selector: 'my-app',
  template: `<modal [hero]="value"></modal>'
})
export class CommonComponent  {
  value : anny ='1';

}

@Component({
  selector: 'modal',
  templateUrl : './modal/model.component.html'
})
export class CommonComponent  {
  @Input() hero:any;
  consrtuctor(){
  console.log(this.hero) ///// shows o/p as undefined

}

Body:
Take a look at lifecycle hooks.

In Angular, constructor is used for dependency injection. You need to call one of the built-in functions in component life-cycle when you want to deal with @Input() @Output() and similar decorators.

Instead of constructor() {...}, use:

ngOnInit() {
  console.log(this.hero); // not undefined
}


问:
Scipy stats.mode is not returning maximum occurred value
I am new to scipy. I am trying to get maximum occurred value of string column.

Here is my Code:

```<code>    import pandas as pd
    import numpy as np
    from scipy.stats import mode

    print ("Maximum Occurence of Store Owner " + str(mode(df_units["StoreOwner"], nan_policy='omit').mode[0]))
</code>```

Here is first few rows of Store Owner Data:

```<code>    0    Muhammed MacIntyre
    1          Barry French
    2          Barry French
    3         Clay Rozendal
    4        Carlos Soltero
</code>```

In above code I am trying to get maximum occured store Owner value in from the datframe. But it is returning all the values as it is.

答:
Assuming your data is in a Pandas Series called ser, you can get the most frequently occurring string by:

```<code>ser.value_counts()[ser.value_counts().index.max()]
</code>```

Body:
I am new to scipy. I am trying to get maximum occurred value of string column.

Here is my Code:

    import pandas as pd
    import numpy as np
    from scipy.stats import mode

    print ("Maximum Occurence of Store Owner " + str(mode(df_units["StoreOwner"], nan_policy='omit').mode[0]))

Here is first few rows of Store Owner Data:

    0    Muhammed MacIntyre
    1          Barry French
    2          Barry French
    3         Clay Rozendal
    4        Carlos Soltero

In above code I am trying to get maximum occured store Owner value in from the datframe. But it is returning all the values as it is.

Body:
Assuming your data is in a Pandas Series called ser, you can get the most frequently occurring string by:

ser.value_counts()[ser.value_counts().index.max()]


问:
password protect a single file using .htaccess
I have tried to password protect a single file using .htaccess. But when accessing the file the browser just redirects to the home page of the website. I have my .htpasswd on my webroot. My .htaccess file is given below

```<code>    <FilesMatch "result.php">
    AuthName "Member Only"
    AuthType Basic
    AuthUserFile /home/username/.htpasswd
    require valid-user
    </FilesMatch>
</code>```

I want to protect the file result.php. I have replaced username with my exact cpanel username. Someone please help

答:
```<code> <FilesMatch "results.php">
 AuthName "Member Only"
 AuthType Basic
 AuthUserFile /home/username/public_html/.htpasswd
 require valid-user
 </FilesMatch>
</code>```

have to put a full absolute path of the password directory

Body:
I have tried to password protect a single file using .htaccess. But when accessing the file the browser just redirects to the home page of the website. I have my .htpasswd on my webroot. My .htaccess file is given below

    <FilesMatch "result.php">
    AuthName "Member Only"
    AuthType Basic
    AuthUserFile /home/username/.htpasswd
    require valid-user
    </FilesMatch>

I want to protect the file result.php. I have replaced username with my exact cpanel username. Someone please help

Body:
 <FilesMatch "results.php">
 AuthName "Member Only"
 AuthType Basic
 AuthUserFile /home/username/public_html/.htpasswd
 require valid-user
 </FilesMatch>

have to put a full absolute path of the password directory


问:
"Unexpected token export" in Angular app with SystemJS and TypeScript

Problem: mysterious "Unexpected token export"

I happened to get this error in an Angular example running in plunker where SystemJS transpiles TypeScript code in the browser.

There was nothing wrong with the code which ran fine locally.

答:
Solution

This isn't an Angular problem. It's a problem with transpiling certain kinds of TypeScript files in the browser.

In my case, I tracked the problem down to a single file that only exported an abstract class.

```<code>// Class used as a "narrowing" interface that exposes a minimal logger
// Other members of the actual implementation are invisible
export abstract class MinimalLogger {
  logs: string[];
  logInfo: (msg: string) => void;
}
</code>```

The problem is that this file doesn't export anything other than the abstract class.

When I add an inert export of anything concrete ... like this:

```<code>export const _ = 0; // hack: must export something "real"
</code>```

... the error goes away.

I've seen a similar problem with a file that only exports TypeScript interfaces. You have to give it at least one thing that is "real".

Environment:

typescript@2.2.1

systemjs@0.19.39

SystemJS Config for this example:

```<code> System.config({
    // DEMO ONLY! REAL CODE SHOULD NOT TRANSPILE IN THE BROWSER
    transpiler: 'ts',
    typescriptOptions: {
      "target": "es5",
      "module": "commonjs",
      "moduleResolution": "node",
      "sourceMap": true,
      "emitDecoratorMetadata": true,
      "experimentalDecorators": true,
      "lib": ["es2015", "dom"],
      "noImplicitAny": true,
      "suppressImplicitAnyIndexErrors": true
    },
    meta: {
      'typescript': {
        "exports": "ts"
      }
    },
    ...
  })
</code>```

Body:
Solution

This isn't an Angular problem. It's a problem with transpiling certain kinds of TypeScript files in the browser.

In my case, I tracked the problem down to a single file that only exported an abstract class.

// Class used as a "narrowing" interface that exposes a minimal logger
// Other members of the actual implementation are invisible
export abstract class MinimalLogger {
  logs: string[];
  logInfo: (msg: string) => void;
}

The problem is that this file doesn't export anything other than the abstract class.

When I add an inert export of anything concrete ... like this:

export const _ = 0; // hack: must export something "real"

... the error goes away.

I've seen a similar problem with a file that only exports TypeScript interfaces. You have to give it at least one thing that is "real".

Environment:

typescript@2.2.1

systemjs@0.19.39

SystemJS Config for this example:

 System.config({
    // DEMO ONLY! REAL CODE SHOULD NOT TRANSPILE IN THE BROWSER
    transpiler: 'ts',
    typescriptOptions: {
      "target": "es5",
      "module": "commonjs",
      "moduleResolution": "node",
      "sourceMap": true,
      "emitDecoratorMetadata": true,
      "experimentalDecorators": true,
      "lib": ["es2015", "dom"],
      "noImplicitAny": true,
      "suppressImplicitAnyIndexErrors": true
    },
    meta: {
      'typescript': {
        "exports": "ts"
      }
    },
    ...
  })


答:
You could do:

```<code>pdf = pd.DataFrame(dict(A=['a', 'a', 'b', 'c', 'd']))
pdf.A.value_counts().idxmax()
</code>```

This gives you the value that occured most frequently in the column A of the dataframe pdf.

Title: Scipy stats.mode is not returning maximum occurred value

Body:
You could do:

pdf = pd.DataFrame(dict(A=['a', 'a', 'b', 'c', 'd']))
pdf.A.value_counts().idxmax()

This gives you the value that occured most frequently in the column A of the dataframe pdf.


问:
SciTE sort selection tool : numbers with leading spaces are not sorted as expected
The SciTE editor comes with embedded Lua scripting engine having access to the text buffer of the editor. This makes it possible to extend SciTE's functionality with tools programmed in Lua and started from the Tools Menu. One such tool available from here:

http://lua-users.org/wiki/SciteSortSelection

is a tool for sorting of selected lines in alphabetical order.
Annoying for me was/is that it doesn't sort lines containing numbers in their numerical order but like this:

```<code>    1
  111
    2
  222
    3
  333
</code>```

where I would rather expect:

```<code>    1
    2
    3
  111
  222
  333
</code>```

Google and Co. are not of much help here as there is to my knowledge no solution to this problem available yet online. It is also not that easy to find and deeply understand the Lua documentation for table.sort(). So the question for a knowledgeable Lua programmer would be, what is the best way to patch the existing Lua script code, so that numbers (and also lines with text in case of leading spaces) become sorted as expected and the Lua code for this task runs so fast, that even sorting of huge files (50 MByte and more) won't take much time?

答:
Your expectation is wrong. You said the algorithm is supposed to sort the texts alphabetically and that is exactly what it does.

For Lua "11" is smaller than "2".
I think you would agree that "aa" should come befor "b" which is pretty much the same thing.

If you want to change how texts are sorted you have to provide your own function.

The Lua reference manual says:

table.sort (list [, comp])

Sorts list elements in a given order, in-place, from list[1] to
  list[#list]. If comp is given, then it must be a function that
  receives two list elements and returns true when the first element
  must come before the second in the final order (so that, after the
  sort, i < j implies not comp(list[j],list[i])). If comp is not given,
  then the standard Lua operator < is used instead.

Note that the comp function must define a strict partial order over
  the elements in the list; that is, it must be asymmetric and
  transitive. Otherwise, no valid sort may be possible.

The sort algorithm is not stable: elements considered equal by the
  given order may have their relative positions changed by the sort.

So you are free to implement your own comp function to change the sorting.

By default table.sort(list) sort list in ascending order.
To make it sort in descending order you call:

```<code>table.sort(list, function(a,b) return a > b end)
</code>```

If you want to treat numbers differently you can do something like this:

```<code>t = {"111", "11", "3", "2", "a", "b"}

local function myCompare(a,b)
    local a_number = tonumber(a)
    local b_number = tonumber(b)
    if a_number and b_number then
       return a_number < b_number
    end
end

table.sort(t, myCompare)

for i,v in ipairs(t) do
    print(v)
end
</code>```

which would give you the output

```<code>2
3
11
111
a
b
</code>```

Of course this is just a quick and simple example. A nicer implementation is up to you.

Body:
The SciTE editor comes with embedded Lua scripting engine having access to the text buffer of the editor. This makes it possible to extend SciTE's functionality with tools programmed in Lua and started from the Tools Menu. One such tool available from here:

http://lua-users.org/wiki/SciteSortSelection

is a tool for sorting of selected lines in alphabetical order.
Annoying for me was/is that it doesn't sort lines containing numbers in their numerical order but like this:

    1
  111
    2
  222
    3
  333

where I would rather expect:

    1
    2
    3
  111
  222
  333

Google and Co. are not of much help here as there is to my knowledge no solution to this problem available yet online. It is also not that easy to find and deeply understand the Lua documentation for table.sort(). So the question for a knowledgeable Lua programmer would be, what is the best way to patch the existing Lua script code, so that numbers (and also lines with text in case of leading spaces) become sorted as expected and the Lua code for this task runs so fast, that even sorting of huge files (50 MByte and more) won't take much time?

Body:
Your expectation is wrong. You said the algorithm is supposed to sort the texts alphabetically and that is exactly what it does.

For Lua "11" is smaller than "2".
I think you would agree that "aa" should come befor "b" which is pretty much the same thing.

If you want to change how texts are sorted you have to provide your own function.

The Lua reference manual says:

table.sort (list [, comp])

Sorts list elements in a given order, in-place, from list[1] to
  list[#list]. If comp is given, then it must be a function that
  receives two list elements and returns true when the first element
  must come before the second in the final order (so that, after the
  sort, i < j implies not comp(list[j],list[i])). If comp is not given,
  then the standard Lua operator < is used instead.

Note that the comp function must define a strict partial order over
  the elements in the list; that is, it must be asymmetric and
  transitive. Otherwise, no valid sort may be possible.

The sort algorithm is not stable: elements considered equal by the
  given order may have their relative positions changed by the sort.

So you are free to implement your own comp function to change the sorting.

By default table.sort(list) sort list in ascending order.
To make it sort in descending order you call:

table.sort(list, function(a,b) return a > b end)

If you want to treat numbers differently you can do something like this:

t = {"111", "11", "3", "2", "a", "b"}

local function myCompare(a,b)
    local a_number = tonumber(a)
    local b_number = tonumber(b)
    if a_number and b_number then
       return a_number < b_number
    end
end

table.sort(t, myCompare)

for i,v in ipairs(t) do
    print(v)
end

which would give you the output

2
3
11
111
a
b

Of course this is just a quick and simple example. A nicer implementation is up to you.


问:
drupal linkedin integration module
I am trying to get the drupal linkedin integration module working.  My configuration is:

Drupal 6.19
OAuth 6.x-2.02
linkedin module 6.x-1.x-dev

I have created my app on the linkedin developer network
I have added the correct keys to my linkedin module on my website
I have checked that all my URL's are correct
I have checked my permissions are correct

When I click on my account, edit linkedin, nothing happens.  Nothing is logged either.
I did the same with the twitter module and it worked fine.
I have uninstalled the linkedin and oauth modules numerous times to fix and it made no difference.

Anyone offer any pointers where to try next?

答: fixed by reinstalling modules and prerequisites</p>

ContentLicense: CC BY-SA 2.5

Title: drupal linkedin integration module


问:
Variable initialisation in JavaScript
```<code>var foo = {n: 1};
foo.x = foo = {a: 2};
console.log(foo.x);
// Output -- undefined

var a = 1;
c = b = a;
console.log(a,b,c);
// Output -- 1, 1, 1
</code>```

Could you please explain why first example returns undefined where as second returns 1,1,1?

答:
That happens because expressions in javascript are evaluated left to right.

So in this expression:

```<code>foo.x=foo={a:2}
</code>```

first the foo is dereferenced and a property x is set to be the target of the right operand foo={a:2} result.

Then, while the right operand is evaluated, the foo value is reassigned, so a reference to the previous instance of the object is lost.

To demonstrate it we may simply create another variable to keep it:

var foo = {n:1};
var bar = foo;
foo.x=foo={a:2};
console.log(foo, bar);```

Title: Variable initialisation in JavaScript

Body:
var foo = {n: 1};
foo.x = foo = {a: 2};
console.log(foo.x);
// Output -- undefined

var a = 1;
c = b = a;
console.log(a,b,c);
// Output -- 1, 1, 1

Could you please explain why first example returns undefined where as second returns 1,1,1?

Body:
That happens because expressions in javascript are evaluated left to right.

So in this expression:

foo.x=foo={a:2}

first the foo is dereferenced and a property x is set to be the target of the right operand foo={a:2} result.

Then, while the right operand is evaluated, the foo value is reassigned, so a reference to the previous instance of the object is lost.

To demonstrate it we may simply create another variable to keep it:

var foo = {n:1};
var bar = foo;
foo.x=foo={a:2};
console.log(foo, bar);


问:
SWI-Prolog family tree parent_of/2
```<code>male(jerry).
male(stuart).
male(warren).
male(peter).

female(kather).
female(maryalice).
female(ann).

brother(jerry,stuart).
brother(jerry,kather).
brother(peter, warren).

sister(ann, maryalice).
sister(kather,jerry).

parent_of(warren,jerry).
parent_of(maryalice,jerry).
</code>```

I was given the facts above and I need to define a rule using the predicate parent_of. Yes, it is the same predicate as the above facts defined by parent_of.

Assume I have a sibling(X, Y) rule that will return all the correct sibling pairs.

I write my parent_of(X, Y) rule as parent_of(X, Y) :- parent_of(X, A), sibling(A, Y).

However, this implementation will lead me to an infinity loop.

Is there a way to define the rule parent_of(X, Y) such that it will return

```<code>(warren, jerry),
(warren, stuart),
(warren, kather),
(maryalice, jerry),
(maryalice, stuart),
(maryalice, kather)
</code>```

I also tried

```<code>parent_of(X, Y) :-
    parent_of(X, jerry),
    brother(jerry, Y).
</code>```

I can get the correct answers by this way but it ended up in "Out of local stack" error. Besides that, I don't think the rule is fine as I hard coded it.

I have seen suggestions like change the rule name to something else such as another_parent_of(X, Y). It does solve the problem, but it is a requirement for me to define it using the same predicate.

Any help is greatly appreciated.

EDITED

The intention of this exercise is to write rules such that you can complete this family tree, though only minimal facts are given. As you can see, it only states that Warren is the father of Jerry, and from brother and sister facts, we know Jerry is the brother of Stuart and Kather. So I will have a rule, parent_of(X, Y) to deduce Warren is also the father of Stuart and Kather, though this was not stated in the facts above.

The main concern is how can I write my parent_of(X, Y) rule to avoid it getting into infinite loop.

答:
I cannot see a way to directly solve your problem. But if your Prolog offers tabling, here is an easy way:

:- use_module(library(tabling)).
...
:- table parent_of/2.
parent_of(warren,jerry).
parent_of(maryalice,jerry).
parent_of(X, Y) :- parent_of(X, A), sibling(A, Y).
...
?- parent_of(X,Y).
X = warren,
Y = stuart ;
X = warren,
Y = jerry ;
X = warren,
Y = kather ;
X = maryalice,
Y = stuart ;
X = maryalice,
Y = jerry ;
X = maryalice,
Y = kather.

Title: SWI-Prolog family tree parent_of/2

Body:
male(jerry).
male(stuart).
male(warren).
male(peter).

female(kather).
female(maryalice).
female(ann).

brother(jerry,stuart).
brother(jerry,kather).
brother(peter, warren).

sister(ann, maryalice).
sister(kather,jerry).

parent_of(warren,jerry).
parent_of(maryalice,jerry).

I was given the facts above and I need to define a rule using the predicate parent_of. Yes, it is the same predicate as the above facts defined by parent_of.

Assume I have a sibling(X, Y) rule that will return all the correct sibling pairs.

I write my parent_of(X, Y) rule as parent_of(X, Y) :- parent_of(X, A), sibling(A, Y).

However, this implementation will lead me to an infinity loop.

Is there a way to define the rule parent_of(X, Y) such that it will return

(warren, jerry),
(warren, stuart),
(warren, kather),
(maryalice, jerry),
(maryalice, stuart),
(maryalice, kather)

I also tried

parent_of(X, Y) :-
    parent_of(X, jerry),
    brother(jerry, Y).

I can get the correct answers by this way but it ended up in "Out of local stack" error. Besides that, I don't think the rule is fine as I hard coded it.

I have seen suggestions like change the rule name to something else such as another_parent_of(X, Y). It does solve the problem, but it is a requirement for me to define it using the same predicate.

Any help is greatly appreciated.

EDITED

The intention of this exercise is to write rules such that you can complete this family tree, though only minimal facts are given. As you can see, it only states that Warren is the father of Jerry, and from brother and sister facts, we know Jerry is the brother of Stuart and Kather. So I will have a rule, parent_of(X, Y) to deduce Warren is also the father of Stuart and Kather, though this was not stated in the facts above.

The main concern is how can I write my parent_of(X, Y) rule to avoid it getting into infinite loop.


问:
Use a variable in another required file
I would like to create a multiple language website but I have a problem!

I will explain it to you with an example:

lang-en.php

```<code><?php
  $lang = [];
  $lang['hello'] = "Wellcome $userName to our website!";
 ?>
</code>```

index.php

```<code><?php
  $useName = "Amir";
  require_once("lang-en.php");
  echo $lang['hello'];
 ?>
</code>```

Now, I would like to see this output in my page:

Welcome Amir to our website!

How can i do this?

答:
It might be smart to make it a bit more complicated, to look to the future. If you remove the implementation part to a separate class, you can have your actual usage and the implementation of the translation separate. If you plan to use gettext (po/mo files) later, you can switch easier.

A simple, but untested, example would be

```<code>class translate{

    private $translations = [
          'hello' => "Wellcome %s to our website!",
    ]

    public function trans($key, $value)
    {
        return sprintf($this->translations[$key], $value);
    }
}
</code>```

Mind you, this is a quick example, and probably needs some work -> for instance, it presumes always a single variable, etc etc. But the idea is that you create  class with an internal implementation, and a function that you call. If you can keep the function call's footprint the same, you can change the working of your translation system!

You'll call this like so

```<code>$trans = new Translate();
echo $trans->trans('hello', 'Amir');
</code>```

(again, I typed this in the answer box, no check for syntax, testing etc has been done, so this is probably not a copy-paste ready class, but it is about the idea)

edit: as requested, a bit more example. Again, not tested, probably some syntax errors etc, but to help you with the idea:

```<code>class translate{

    private $translations = [
          'hello' => array('test' =>"Welcome %s to our website!", 'vars' => 1),
          'greet' => array('test' =>"I'd like to say $s to %s ", 'vars' => 2),
    ]

    public function trans($key, array $values)
    {
        // no translation
        if(!isset($this->translations[$key])){
            return false; // or exception if you want
        }
        // translation needs more (or less) variables
        if($this->translations[$key][vars] !== count($values)){
            return false; // or exception if you want
        }

        // note: now using vsprintf
        return vsprintf($this->translations[$key], $values);
    }
}
</code>```

Title: Use a variable in another required file

Body:
I would like to create a multiple language website but I have a problem!

I will explain it to you with an example:

lang-en.php

<?php
  $lang = [];
  $lang['hello'] = "Wellcome $userName to our website!";
 ?>

index.php

<?php
  $useName = "Amir";
  require_once("lang-en.php");
  echo $lang['hello'];
 ?>

Now, I would like to see this output in my page:

Welcome Amir to our website!

How can i do this?

Body:
It might be smart to make it a bit more complicated, to look to the future. If you remove the implementation part to a separate class, you can have your actual usage and the implementation of the translation separate. If you plan to use gettext (po/mo files) later, you can switch easier.

A simple, but untested, example would be

class translate{

    private $translations = [
          'hello' => "Wellcome %s to our website!",
    ]

    public function trans($key, $value)
    {
        return sprintf($this->translations[$key], $value);
    }
}

Mind you, this is a quick example, and probably needs some work -> for instance, it presumes always a single variable, etc etc. But the idea is that you create  class with an internal implementation, and a function that you call. If you can keep the function call's footprint the same, you can change the working of your translation system!

You'll call this like so

$trans = new Translate();
echo $trans->trans('hello', 'Amir');

(again, I typed this in the answer box, no check for syntax, testing etc has been done, so this is probably not a copy-paste ready class, but it is about the idea)

edit: as requested, a bit more example. Again, not tested, probably some syntax errors etc, but to help you with the idea:

class translate{

    private $translations = [
          'hello' => array('test' =>"Welcome %s to our website!", 'vars' => 1),
          'greet' => array('test' =>"I'd like to say $s to %s ", 'vars' => 2),
    ]

    public function trans($key, array $values)
    {
        // no translation
        if(!isset($this->translations[$key])){
            return false; // or exception if you want
        }
        // translation needs more (or less) variables
        if($this->translations[$key][vars] !== count($values)){
            return false; // or exception if you want
        }

        // note: now using vsprintf
        return vsprintf($this->translations[$key], $values);
    }
}


问:
Setting up dotnet core with RavenDB
I'm currently facing a problem with setting up RavenDB with dotnet core for multiple environments.

In StartUp class I have configured Raven as a Singleton and used the IOptions pattern to bind the settings Raven to the RavenSettings object.

```<code> public virtual void ConfigureServices(IServiceCollection services)
 {
     Services.AddMvc()

     //Add functionality to inject IOptions<T>
     services.AddOptions();

     // App Settings
     services.Configure<RavenSettings>(Configuration.GetSection("Raven"));
     //services.Configure<RavenSettings>(settings => Configuration.GetSection("Raven").Bind(settings));

     // .NET core built in IOC
     services.AddSingleton(DocumentStoreHolder.Store);
     services.AddSingleton<IConfiguration>(Configuration);
 }
</code>```

This is my default app settings.

```<code>{
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Debug",
      "System": "Information",
      "Microsoft": "Information"
      }
  },
  "Raven": {
    "Url": "x",
    "DefaultDatabase": "x"
  }
}
</code>```

This is the class that I have attempted to bind the setting from appsettings to ...

```<code>public class RavenSettings
{
    public string Url { get; set; }
    public string DefaultDatabase { get; set; }
}
</code>```

The class below follows the Raven documents in generating the Raven document store. Because I am using a singleton, I am not hitting the constructor to inject the settings. Can anyone advise a way around this?

```<code>public sealed class DocumentStoreHolder
{
    private static RavenSettings _ravenSettings;

    public DocumentStoreHolder(IOptions<RavenSettings> ravenSettings)
    {
        _ravenSettings = ravenSettings.Value;
    }

    public static IDocumentStore Store => DocStore.Value;

    private static readonly Lazy<IDocumentStore> DocStore = new Lazy<IDocumentStore>(CreateStore);

    private static IDocumentStore CreateStore()
    {
        var store = new DocumentStore
        {
            Url = _ravenSettings.Url,
            DefaultDatabase = _ravenSettings.DefaultDatabase
        }.Initialize();

        return store;
    }
}
</code>```

答:
ASP.NET Core DI already uses lazy loading with singleton:

Singleton lifetime services are created the first time they are requested (or when ConfigureServices is run if you specify an instance there) and then every subsequent request will use the same instance.

and moreover:

If your application requires singleton behavior, allowing the services container to manage the service's lifetime is recommended instead of implementing the singleton design pattern and managing your object's lifetime in the class yourself.

Therefore, you can do something like this:

```<code>services.AddSingleton<DocumentStoreHolder>();
</code>```

by removing your own singleton implementation from DocumentStoreHolder class

```<code>public sealed class DocumentStoreHolder
{
    public DocumentStoreHolder(IOptions<RavenSettings> ravenSettings)
    {
        var _ravenSettings = ravenSettings.Value;

        Store = new DocumentStore
        {
            Url = _ravenSettings.Url,
            DefaultDatabase = _ravenSettings.DefaultDatabase
        }.Initialize();

    }

    public IDocumentStore Store {get; private set;}
}
</code>```

Title: Setting up dotnet core with RavenDB

Body:
I'm currently facing a problem with setting up RavenDB with dotnet core for multiple environments.

In StartUp class I have configured Raven as a Singleton and used the IOptions pattern to bind the settings Raven to the RavenSettings object.

 public virtual void ConfigureServices(IServiceCollection services)
 {
     Services.AddMvc()

     //Add functionality to inject IOptions<T>
     services.AddOptions();

     // App Settings
     services.Configure<RavenSettings>(Configuration.GetSection("Raven"));
     //services.Configure<RavenSettings>(settings => Configuration.GetSection("Raven").Bind(settings));

     // .NET core built in IOC
     services.AddSingleton(DocumentStoreHolder.Store);
     services.AddSingleton<IConfiguration>(Configuration);
 }

This is my default app settings.

{
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Debug",
      "System": "Information",
      "Microsoft": "Information"
      }
  },
  "Raven": {
    "Url": "x",
    "DefaultDatabase": "x"
  }
}

This is the class that I have attempted to bind the setting from appsettings to ...

public class RavenSettings
{
    public string Url { get; set; }
    public string DefaultDatabase { get; set; }
}

The class below follows the Raven documents in generating the Raven document store. Because I am using a singleton, I am not hitting the constructor to inject the settings. Can anyone advise a way around this?

public sealed class DocumentStoreHolder
{
    private static RavenSettings _ravenSettings;

    public DocumentStoreHolder(IOptions<RavenSettings> ravenSettings)
    {
        _ravenSettings = ravenSettings.Value;
    }

    public static IDocumentStore Store => DocStore.Value;

    private static readonly Lazy<IDocumentStore> DocStore = new Lazy<IDocumentStore>(CreateStore);

    private static IDocumentStore CreateStore()
    {
        var store = new DocumentStore
        {
            Url = _ravenSettings.Url,
            DefaultDatabase = _ravenSettings.DefaultDatabase
        }.Initialize();

        return store;
    }
}

Body:
ASP.NET Core DI already uses lazy loading with singleton:

Singleton lifetime services are created the first time they are requested (or when ConfigureServices is run if you specify an instance there) and then every subsequent request will use the same instance.

and moreover:

If your application requires singleton behavior, allowing the services container to manage the service's lifetime is recommended instead of implementing the singleton design pattern and managing your object's lifetime in the class yourself.

Therefore, you can do something like this:

services.AddSingleton<DocumentStoreHolder>();

by removing your own singleton implementation from DocumentStoreHolder class

public sealed class DocumentStoreHolder
{
    public DocumentStoreHolder(IOptions<RavenSettings> ravenSettings)
    {
        var _ravenSettings = ravenSettings.Value;

        Store = new DocumentStore
        {
            Url = _ravenSettings.Url,
            DefaultDatabase = _ravenSettings.DefaultDatabase
        }.Initialize();

    }

    public IDocumentStore Store {get; private set;}
}


问:
How do I add a formula with VBA that refers to another cell?
I searched but didn't found what I was looking for.
My goal is to have a big number of cells that shows the value of other cells in other sheets like a simple "=january!BP$43".
But I want to add this with a loop, here a simplified example:

```<code>  For sorte = 0 To 5
    For mois = 0 To 11
        Sheets(2).Range(4+k, 1 + mois + j).Formula = "=Sheets(3 + mois).Cells(40+i, 2 + sorte)"
    Next
    j = j + 13
    i=i+15
    k=k+1
Next
</code>```

I tried it without the " " around "Sheets...)" and it works but just inserts the value and not the formula.
Any Idea?
Thanks a lot

PS: j,i,k are just here to show that I have other variables coming there to change the position.

答:
You will need to place the sheet name in using Sheets(3 + mois).Name, and it will be easiest to refer to the row and column using R1C1 notation:

```<code>For sorte = 0 To 5
    For mois = 0 To 11
        Sheets(2).Cells(4+k, 1 + mois + j).FormulaR1C1 = "='" & Sheets(3 + mois).Name & "'!R" & (40+i) & "C" & (2 + sorte)
    Next
    j = j + 13
    i=i+15
    k=k+1
Next
</code>```

Body:
I searched but didn't found what I was looking for.
My goal is to have a big number of cells that shows the value of other cells in other sheets like a simple "=january!BP$43".
But I want to add this with a loop, here a simplified example:

  For sorte = 0 To 5
    For mois = 0 To 11
        Sheets(2).Range(4+k, 1 + mois + j).Formula = "=Sheets(3 + mois).Cells(40+i, 2 + sorte)"
    Next
    j = j + 13
    i=i+15
    k=k+1
Next

I tried it without the " " around "Sheets...)" and it works but just inserts the value and not the formula.
Any Idea?
Thanks a lot

PS: j,i,k are just here to show that I have other variables coming there to change the position.

Body:
You will need to place the sheet name in using Sheets(3 + mois).Name, and it will be easiest to refer to the row and column using R1C1 notation:

For sorte = 0 To 5
    For mois = 0 To 11
        Sheets(2).Cells(4+k, 1 + mois + j).FormulaR1C1 = "='" & Sheets(3 + mois).Name & "'!R" & (40+i) & "C" & (2 + sorte)
    Next
    j = j + 13
    i=i+15
    k=k+1
Next


问:
Are there any Python template engines that support Python 3.x
It seems they all run on Python 2.x.

(Actually I want a more widely-used engine that has Python 3.x support.)

答:
If you don't mind using beta software, the newly-released moody-templates was written for Python 3 from the ground up.

https://github.com/etianen/moody-templates


问:
Need Help! Angular 2 File/Image upload via API
I'm stack around uploading image/file using Angular2. I don't like to add any plugins to upload file in angular2. Is there any simple way to upload image via API using Angular2 without any third party extension ?

NB: i am using laravel as server

答:
The Template

<input type="file" (change)="fileChangeEvent($event)" placeholder="Upload file..." />
<button type="button" (click)="upload()">Upload</button>```
</div>
</div>
</p>

<ol start="2">
<li>The Service</li>
</ol>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="true">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>export class FileUpload{
/* This method will worked for single file upload, if you need multipule file upload then replace formData.append("uploads", files[i], files[i].name); to formData.append("uploads[]", files[i], files[i].name);
*/
makeFileRequest(url: string, params: Array<string>, files: Array<File>) {
        return new Promise((resolve, reject) => {
            var formData: any = new FormData();
            var xhr = new XMLHttpRequest();
            for(var i = 0; i < files.length; i++) {
                formData.append("uploads", files[i], files[i].name);
            }
            xhr.onreadystatechange = function () {
                if (xhr.readyState == 4) {
                    if (xhr.status == 200) {
                        resolve(JSON.parse(xhr.response));
                    } else {
                        reject(xhr.response);
                    }
                }
            }
            xhr.open("POST", url, true);
            xhr.send(formData);
        });
    }
}</code>```

The Component

export class AppComponent {
  filesToUpload: Array<File>;

  constructor(private _fileUpload:FileUpload) {
        this.filesToUpload = [];
  }

  upload() {
        this._fileUpload.makeFileRequest("/api/admin/upload-slider-image", [], this.filesToUpload).then((result) => {
            console.log(result);
        }, (error) => {
            console.error(error);
        });
    }

    fileChangeEvent(fileInput: any){
        this.filesToUpload = <Array<File>> fileInput.target.files;
    }
 }```

Body:
The Template

<input type="file" (change)="fileChangeEvent($event)" placeholder="Upload file..." />
<button type="button" (click)="upload()">Upload</button>

The Service

export class FileUpload{
/* This method will worked for single file upload, if you need multipule file upload then replace formData.append("uploads", files[i], files[i].name); to formData.append("uploads[]", files[i], files[i].name);
*/
makeFileRequest(url: string, params: Array<string>, files: Array<File>) {
        return new Promise((resolve, reject) => {
            var formData: any = new FormData();
            var xhr = new XMLHttpRequest();
            for(var i = 0; i < files.length; i++) {
                formData.append("uploads", files[i], files[i].name);
            }
            xhr.onreadystatechange = function () {
                if (xhr.readyState == 4) {
                    if (xhr.status == 200) {
                        resolve(JSON.parse(xhr.response));
                    } else {
                        reject(xhr.response);
                    }
                }
            }
            xhr.open("POST", url, true);
            xhr.send(formData);
        });
    }
}

The Component

export class AppComponent {
  filesToUpload: Array<File>;

  constructor(private _fileUpload:FileUpload) {
        this.filesToUpload = [];
  }

  upload() {
        this._fileUpload.makeFileRequest("/api/admin/upload-slider-image", [], this.filesToUpload).then((result) => {
            console.log(result);
        }, (error) => {
            console.error(error);
        });
    }

    fileChangeEvent(fileInput: any){
        this.filesToUpload = <Array<File>> fileInput.target.files;
    }
 }


答:
```<code>foo.x = foo = {a: 2};
</code>```

determines that foo.x refers to a property x of the {n: 1} object, assigns {n: 2} to foo, and assigns the new value of foo – {n: 2} – to the property x of the {n: 1} object.

The important thing is that the foo that foo.x refers to is determined before foo changes.

The assignment operator associates right to left, so you get:

```<code>foo.x = (foo = {n: 2})
</code>```

The left hand side is evaluated before the right hand side and hence an undefined value

Title: Variable initialisation in JavaScript

Body:
foo.x = foo = {a: 2};

determines that foo.x refers to a property x of the {n: 1} object, assigns {n: 2} to foo, and assigns the new value of foo – {n: 2} – to the property x of the {n: 1} object.

The important thing is that the foo that foo.x refers to is determined before foo changes.

The assignment operator associates right to left, so you get:

foo.x = (foo = {n: 2})

The left hand side is evaluated before the right hand side and hence an undefined value


问:
Why is there an error in indexing in this Data Frame
Here is my Data and code bits:

```<code>states = pd.DataFrame(census_df['STNAME'],census_df['COUNTY'] ,)
index = census_df(['STNAME'])
</code>```

Statename and county have equal length but it is showing error.

```<code>Error  : __init__() got multiple values for argument 'index'
</code>```

Can please anyone help me? Thanks in advance!

答:
If you really want STNAME to be both an index and a column, then you are missing [] brackets. Try:

```<code>states = pd.DataFrame([census_df['STNAME'],census_df['COUNTY']] , index =    census_df['STNAME'] )
</code>```

If you mean that you want STNAME as index and COUNTY as a column then you want either

```<code>states = pd.DataFrame(census_df['COUNTY'], index = census_df['STNAME'] )
</code>```

or

```<code>states = pd.Series(census_df['COUNTY'], index = census_df['STNAME'] )
</code>```

depending on whether you want to work with a Series or a DataFrame object.

Body:
Here is my Data and code bits:

states = pd.DataFrame(census_df['STNAME'],census_df['COUNTY'] ,)
index = census_df(['STNAME'])

Statename and county have equal length but it is showing error.

Error  : __init__() got multiple values for argument 'index'

Can please anyone help me? Thanks in advance!

Body:
If you really want STNAME to be both an index and a column, then you are missing [] brackets. Try:

states = pd.DataFrame([census_df['STNAME'],census_df['COUNTY']] , index =    census_df['STNAME'] )

If you mean that you want STNAME as index and COUNTY as a column then you want either

states = pd.DataFrame(census_df['COUNTY'], index = census_df['STNAME'] )

or

states = pd.Series(census_df['COUNTY'], index = census_df['STNAME'] )

depending on whether you want to work with a Series or a DataFrame object.


问:
Microsoft Hololens Spatial Mapping Surface Differentiation
I am wondering about the capabilities of the HoloLens to differentiate between surfaces. More specifically, I would like to know what type of surface the user is gazing at, be it a horizontal surface (i.e. a table top, floor, ceiling) or a vertical surface (i.e. walls). I am wondering if there is any built in function in detecting this or how I can go about implementing one -which I am not too sure of where to start. (I have been googling for quite a while now to no avail.)</p>

答:
Use a raycast onto the mapping, then use the normal from the RaycastHit object.

https://docs.unity3d.com/ScriptReference/RaycastHit-normal.html

Then compare the normal with Dot product to the Up vector. If close to 1, then you have a horizontal surface, if close to 0, you have a vertical surface.


问:
{"error":"Explicit construction of entity type '###' in query is not allowed."}
I am new to LINQ, and i am getting this error message :

{"error":"Explicit construction of entity type 'Proj.Models.Ad' in
  query is not allowed."}

I am using this code to retrieve the data

```<code>public ActionResult favads()
{
    bool isValid = false;
    string authToken = "";
    if (Request["dt"] != null)
        authToken = Request["dt"].ToString().Trim();
    else
        return Content("{\"error\":\"Please send device token parameter 'dt'.\"}", "application/json");

    string message = (new CommonFunction()).ValidateToken(authToken, out isValid);

    if (isValid)
    {
        long userID = 0;
        if (Request["userID"] != null)
            long.TryParse(Request["userID"].ToString().Trim(), out userID);
        else
            return Content("{\"error\":\"Please send user id parameter 'userID'.\"}", "application/json");

        if (userID < 1)
            return Content("{\"error\":\"Please select appropriate user to view details.\"}", "application/json");

        try
        {
                var q = from d in db.AdsFavourites.Where(Favtb => Favtb.CreatedBy.Equals(userID) && Favtb.StatusID.Equals(1)).Select(p => new Ad() { ID = p.AdID.Value, CategoryID = int.Parse(p.CategoryID.ToString()) })
                    from c in db.Ads.Where(Adstb => Adstb.ID == d.ID).DefaultIfEmpty()
                    select new
                    {
                        FavId = d.ID,
                        c.ID,
                        c.Category.ParentCategoryID,
                        c.Category.CategoryID,
                        c.Category.LogoFile,
                        c.Category.CatName,
                        c.AdTitle,
                        AdDescription = (c.AdDescription.Length > 50 ? c.AdDescription.Substring(0, 50) : c.AdDescription),
                        c.CityID,
                        c.Price,
                        c.CreationDate,
                        c.Photos,
                        c.VideoUrl,
                        c.IsMobileVisibile
                    };

            int pg = 0;
            if (Request["p"] != null)
                int.TryParse(Request["p"], out pg);

            string _sortby = "MRF";
            if (Request["sortby"] != null)
                _sortby = Request["sortby"];

            if (_sortby.Equals("OF"))
                q = q.OrderBy(ad => ad.CreationDate.Value);
            else if (_sortby.Equals("PD"))
                q = q.OrderByDescending(ad => ad.Price.Value);
            else if (_sortby.Equals("PA"))
                q = q.OrderBy(ad => ad.Price.Value);
            else
                q = q.OrderByDescending(ad => ad.CreationDate.Value);

            return Json(q.ToList().Skip(pg * recordsPerPage).Take(recordsPerPage), JsonRequestBehavior.AllowGet);
        }
        catch (Exception ex)
        {
            return Content("{\"error\":\"" + ex.Message + "\"}", "application/json");
        }
    }
    else
    {
        return Content("{\"error\":\"" + message + "\"}", "application/json");
    }
}
</code>```

Ads class

```<code>public class Ads : Ad
{
    public long ID { get; set; }
    public string FashionType { get; set; }
    public string ForRentSale { get; set; }
    public string ForJobHire { get; set; }
    public string JobTypeID { get; set; }
}
</code>```

答:
Ad is also mapped and you cannot project a new instance of it like this in a query. See this question.

What you can do is just create an anonymous type or even better in this case, since in your query you only use the ID of the Ad object retrieve just that:

```<code>var q = from d in db.AdsFavourites.Where(Favtb => Favtb.CreatedBy.Equals(userID) &&
                                                  Favtb.StatusID.Equals(1))
                                  .Select(p => p.AdID.Value)
        from c in db.Ads.Where(Adstb => Adstb.ID == d).DefaultIfEmpty()
        select new
        {
            FavId = d,
            c.ID,
            c.Category.ParentCategoryID,
            /* ... */
        };
</code>```

I recommend you look into Navigation Properties. I think it will make this query look neater

Also maybe look at this option instead of using the Method Syntax for the first table, might be more readable:

```<code>var q = from d in db.AdsFavourites
        //In this case also no need for `Equals` - you are comparing value types
        where d.CreateBy == userID && d.StatusID == 1

        from c in db.Ads.Where(Adstb => Adstb.ID == d.AdID.Value).DefaultIfEmpty()
        select new
        {
            FavId = d.AdID.Value,
            c.ID,
            /* ... */
        };
</code>```

Body:
I am new to LINQ, and i am getting this error message :

{"error":"Explicit construction of entity type 'Proj.Models.Ad' in
  query is not allowed."}

I am using this code to retrieve the data

public ActionResult favads()
{
    bool isValid = false;
    string authToken = "";
    if (Request["dt"] != null)
        authToken = Request["dt"].ToString().Trim();
    else
        return Content("{\"error\":\"Please send device token parameter 'dt'.\"}", "application/json");

    string message = (new CommonFunction()).ValidateToken(authToken, out isValid);

    if (isValid)
    {
        long userID = 0;
        if (Request["userID"] != null)
            long.TryParse(Request["userID"].ToString().Trim(), out userID);
        else
            return Content("{\"error\":\"Please send user id parameter 'userID'.\"}", "application/json");

        if (userID < 1)
            return Content("{\"error\":\"Please select appropriate user to view details.\"}", "application/json");

        try
        {
                var q = from d in db.AdsFavourites.Where(Favtb => Favtb.CreatedBy.Equals(userID) && Favtb.StatusID.Equals(1)).Select(p => new Ad() { ID = p.AdID.Value, CategoryID = int.Parse(p.CategoryID.ToString()) })
                    from c in db.Ads.Where(Adstb => Adstb.ID == d.ID).DefaultIfEmpty()
                    select new
                    {
                        FavId = d.ID,
                        c.ID,
                        c.Category.ParentCategoryID,
                        c.Category.CategoryID,
                        c.Category.LogoFile,
                        c.Category.CatName,
                        c.AdTitle,
                        AdDescription = (c.AdDescription.Length > 50 ? c.AdDescription.Substring(0, 50) : c.AdDescription),
                        c.CityID,
                        c.Price,
                        c.CreationDate,
                        c.Photos,
                        c.VideoUrl,
                        c.IsMobileVisibile
                    };

            int pg = 0;
            if (Request["p"] != null)
                int.TryParse(Request["p"], out pg);

            string _sortby = "MRF";
            if (Request["sortby"] != null)
                _sortby = Request["sortby"];

            if (_sortby.Equals("OF"))
                q = q.OrderBy(ad => ad.CreationDate.Value);
            else if (_sortby.Equals("PD"))
                q = q.OrderByDescending(ad => ad.Price.Value);
            else if (_sortby.Equals("PA"))
                q = q.OrderBy(ad => ad.Price.Value);
            else
                q = q.OrderByDescending(ad => ad.CreationDate.Value);

            return Json(q.ToList().Skip(pg * recordsPerPage).Take(recordsPerPage), JsonRequestBehavior.AllowGet);
        }
        catch (Exception ex)
        {
            return Content("{\"error\":\"" + ex.Message + "\"}", "application/json");
        }
    }
    else
    {
        return Content("{\"error\":\"" + message + "\"}", "application/json");
    }
}

Ads class

public class Ads : Ad
{
    public long ID { get; set; }
    public string FashionType { get; set; }
    public string ForRentSale { get; set; }
    public string ForJobHire { get; set; }
    public string JobTypeID { get; set; }
}

Body:
Ad is also mapped and you cannot project a new instance of it like this in a query. See this question.

What you can do is just create an anonymous type or even better in this case, since in your query you only use the ID of the Ad object retrieve just that:

var q = from d in db.AdsFavourites.Where(Favtb => Favtb.CreatedBy.Equals(userID) &&
                                                  Favtb.StatusID.Equals(1))
                                  .Select(p => p.AdID.Value)
        from c in db.Ads.Where(Adstb => Adstb.ID == d).DefaultIfEmpty()
        select new
        {
            FavId = d,
            c.ID,
            c.Category.ParentCategoryID,
            /* ... */
        };

I recommend you look into Navigation Properties. I think it will make this query look neater

Also maybe look at this option instead of using the Method Syntax for the first table, might be more readable:

var q = from d in db.AdsFavourites
        //In this case also no need for `Equals` - you are comparing value types
        where d.CreateBy == userID && d.StatusID == 1

        from c in db.Ads.Where(Adstb => Adstb.ID == d.AdID.Value).DefaultIfEmpty()
        select new
        {
            FavId = d.AdID.Value,
            c.ID,
            /* ... */
        };


问:
Rails query comparing against Postgres Array Column
So i have a this column in a table
t.text "foo", default: [], array: true

And i have this array list in a helper file,

```<code>module HelperData

  Helper_array = [
    "data_1",
    "data_2",
    "data_3",
    "data_4",
    "data_5"
  ]
end
</code>```

Inside the FooName.rb model there's a line include HelperData.

So the query i want to pass is the include operator && in comparing PG arrays, based on this Postgres Guide.

I have tried the following queries:

FooName.where("foo" && HelperData::Helper_array). This query returns the error ActiveRecord::StatementInvalid: PG::SyntaxError: ERROR:. The syntax error is with the elements in HelperData::Helper_array. I have a slight hunch that it is because Foo is :text but the data in Helper_array is a string, though i can't be certain.

FooName.where("foo && HelperData::Helper_array"). This query returns the error ActiveRecord::StatementInvalid: PG::UndefinedColumn: ERROR:. Obviously this is just the wrong syntax then.

What is the proper query to find whether the foo array has any elements that overlap with the Helper_array, and return all FooName objects that has overlapping elements?

答:
try:

```<code>FooName.where("foo && ARRAY[?]::text[]", HelperData::Helper_array)
</code>```

refer this link
https://www.postgresql.org/docs/current/static/functions-array.html

Body:
So i have a this column in a table
t.text "foo", default: [], array: true

And i have this array list in a helper file,

module HelperData

  Helper_array = [
    "data_1",
    "data_2",
    "data_3",
    "data_4",
    "data_5"
  ]
end

Inside the FooName.rb model there's a line include HelperData.

So the query i want to pass is the include operator && in comparing PG arrays, based on this Postgres Guide.

I have tried the following queries:

FooName.where("foo" && HelperData::Helper_array). This query returns the error ActiveRecord::StatementInvalid: PG::SyntaxError: ERROR:. The syntax error is with the elements in HelperData::Helper_array. I have a slight hunch that it is because Foo is :text but the data in Helper_array is a string, though i can't be certain.

FooName.where("foo && HelperData::Helper_array"). This query returns the error ActiveRecord::StatementInvalid: PG::UndefinedColumn: ERROR:. Obviously this is just the wrong syntax then.

What is the proper query to find whether the foo array has any elements that overlap with the Helper_array, and return all FooName objects that has overlapping elements?

Body:
try:

FooName.where("foo && ARRAY[?]::text[]", HelperData::Helper_array)

refer this link
https://www.postgresql.org/docs/current/static/functions-array.html


问:
AngularJS - Routing with different controllers leads to empty $scope
This is my .js File for the routing:

```<code>var app = angular.module('WebApp', ['ngRoute']);

/**
 * Configure the Routes
 */
app.config(['$routeProvider', function ($routeProvider) {
  $routeProvider
  // Home
  .when("/", { templateUrl: "partials/kalendar.php", controller: "Ctrl" })
  .when("/logout", { templateUrl: "partials/logout.php", controller: "PageCtrl" })
  .otherwise({
    controller: function () {
        window.location.replace('/');
    },
    template: "<div></div>"
  });
}]);

/**
 * Controls all other Pages
 */
app.controller('PageCtrl', function ($scope) {
        console.log("Page Controller reporting for duty.");
});

/**
 * Controls calendar view
 */
app.controller('Ctrl', function ($scope) {
        console.log("Controller reporting for duty.");
$scope.updateDuration = function () {
        alert($scope.dateIn);
}
});
</code>```

And this is part of my kalendar.php:

```<code><div>
<label>Datum:</label>
<div class="input-group input-append date">
     <input type="text" class="span2 form-control" ng-model="dateIn">
     <span class="input-group-addon">
           <span class="glyphicon glyphicon-th-large"></span>
     </span>
</div>
</div>
</code>```

When I run my program, the Page Controller is called ("Controller reporting for duty." show in console), but the alert doesn't work, because $scope.dateIn is undefined. Please help me find my mistake.

答:
where your calling updateDuration function in your Html??make sure your calling your function from htmm like below

var app = angular.module('WebApp', ['ngRoute']);

/**
 * Controls all other Pages
 */
app.controller('PageCtrl', function ($scope) {
        console.log("Page Controller reporting for duty.");
});

/**
 * Controls calendar view
 */
app.controller('Ctrl', function ($scope) {
        console.log("Controller reporting for duty.");
$scope.updateDuration = function () {
        alert($scope.dateIn);
}
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html ng-app="WebApp">

  <head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <script>document.write('<base href="' + document.location + '" />');</script>
    <link rel="stylesheet" href="style.css" />
    <script data-require="angular.js@1.4.x" src="https://code.angularjs.org/1.4.12/angular.js" data-semver="1.4.9"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular-route.js"></script>
    <script src="app.js"></script>
  </head>

  <body ng-controller="Ctrl">
    <div>
<label>Datum:</label>
<div class="input-group input-append date">
     <input type="text" class="span2 form-control" ng-model="dateIn">
     <span class="input-group-addon">
           <span class="glyphicon glyphicon-th-large"></span>
     </span>
     <button type="button" ng-click="updateDuration() ">check me</button>
</div>
</div>
  </body>

</html></code>```

Here i managed to call the function in button click.

Body:
This is my .js File for the routing:

var app = angular.module('WebApp', ['ngRoute']);

/**
 * Configure the Routes
 */
app.config(['$routeProvider', function ($routeProvider) {
  $routeProvider
  // Home
  .when("/", { templateUrl: "partials/kalendar.php", controller: "Ctrl" })
  .when("/logout", { templateUrl: "partials/logout.php", controller: "PageCtrl" })
  .otherwise({
    controller: function () {
        window.location.replace('/');
    },
    template: "

"
  });
}]);

/**
 * Controls all other Pages
 */
app.controller('PageCtrl', function ($scope) {
        console.log("Page Controller reporting for duty.");
});

/**
 * Controls calendar view
 */
app.controller('Ctrl', function ($scope) {
        console.log("Controller reporting for duty.");
$scope.updateDuration = function () {
        alert($scope.dateIn);
}
});

And this is part of my kalendar.php:

Datum:

     <input type="text" class="span2 form-control" ng-model="dateIn">

When I run my program, the Page Controller is called ("Controller reporting for duty." show in console), but the alert doesn't work, because $scope.dateIn is undefined. Please help me find my mistake.

Body:
where your calling updateDuration function in your Html??make sure your calling your function from htmm like below

var app = angular.module('WebApp', ['ngRoute']);

/**
 * Controls all other Pages
 */
app.controller('PageCtrl', function ($scope) {
        console.log("Page Controller reporting for duty.");
});

/**
 * Controls calendar view
 */
app.controller('Ctrl', function ($scope) {
        console.log("Controller reporting for duty.");
$scope.updateDuration = function () {
        alert($scope.dateIn);
}
});

<!DOCTYPE html>
<html ng-app="WebApp">

  <head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <script>document.write('<base href="' + document.location + '" />');</script>
    <link rel="stylesheet" href="style.css" />
    <script data-require="angular.js@1.4.x" src="https://code.angularjs.org/1.4.12/angular.js" data-semver="1.4.9"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular-route.js"></script>
    <script src="app.js"></script>
  </head>

  <body ng-controller="Ctrl">
    <div>
<label>Datum:</label>
<div class="input-group input-append date">
     <input type="text" class="span2 form-control" ng-model="dateIn">
     <span class="input-group-addon">
           <span class="glyphicon glyphicon-th-large"></span>
     </span>
     <button type="button" ng-click="updateDuration() ">check me</button>
</div>
</div>
  </body>

</html>

Here i managed to call the function in button click.


问:
Android - Drawable - Error inflating TextView in lower API
When I run my code on Emulator with API 25,

it works fine

Instead on emulator with API 16, I get this error

android.view.InflateException: Binary XML file line #36: Error inflating class TextView

Here is the line where I get the error

```<code>public class RecipeAdapter extends RecyclerView.Adapter<RecipeAdapter.MyViewHolder> {
    ...
    static class MyViewHolder extends RecyclerView.ViewHolder{
        TextView recipe, time;
        RatingBar ratingBar;
        ImageView imageView;

        MyViewHolder(View view) {
            super(view);

            recipe = (TextView) view.findViewById(R.id.tv_recipe_name);
            time = (TextView) view.findViewById(R.id.tv_time);
            ratingBar = (RatingBar) view.findViewById(R.id.ratingBar);
            imageView = (ImageView) view.findViewById(R.id.iv_recipe);
        }
    }

    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.item_recipe, parent, false); // <- Error

        return new MyViewHolder(itemView);
    }
    ...
}
</code>```

This is the error message

```<code>E/AndroidRuntime: FATAL EXCEPTION: main
       android.view.InflateException: Binary XML file line #36: Error inflating class TextView
              at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:704)
              at android.view.LayoutInflater.rInflate(LayoutInflater.java:746)
              at android.view.LayoutInflater.inflate(LayoutInflater.java:489)
              at uk.co.chrisjenx.calligraphy.CalligraphyLayoutInflater.inflate(CalligraphyLayoutInflater.java:60)
              at android.view.LayoutInflater.inflate(LayoutInflater.java:396)
              at com.mnm.cookrecipe.recycler.RecipeAdapter.onCreateViewHolder(RecipeAdapter.java:55) // <- this
              at com.mnm.cookrecipe.recycler.RecipeAdapter.onCreateViewHolder(RecipeAdapter.java:21) // <- this
              at android.support.v7.widget.RecyclerView$Adapter.createViewHolder(RecyclerView.java:6078)
              at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5248)
              at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5158)
              at android.support.v7.widget.LinearLayoutManager$LayoutState.next(LinearLayoutManager.java:2061)
              at android.support.v7.widget.GridLayoutManager.layoutChunk(GridLayoutManager.java:562)
              at android.support.v7.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1408)
              at android.support.v7.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:580)
              at android.support.v7.widget.GridLayoutManager.onLayoutChildren(GridLayoutManager.java:170)
              at android.support.v7.widget.RecyclerView.dispatchLayoutStep2(RecyclerView.java:3379)
              at android.support.v7.widget.RecyclerView.dispatchLayout(RecyclerView.java:3188)
              at android.support.v7.widget.RecyclerView.onLayout(RecyclerView.java:3632)
              at android.view.View.layout(View.java:13754)
              at android.view.ViewGroup.layout(ViewGroup.java:4364)
              at android.widget.RelativeLayout.onLayout(RelativeLayout.java:948)
              at android.view.View.layout(View.java:13754)
              at android.view.ViewGroup.layout(ViewGroup.java:4364)
              at android.widget.FrameLayout.onLayout(FrameLayout.java:448)
              at android.view.View.layout(View.java:13754)
              at android.view.ViewGroup.layout(ViewGroup.java:4364)
              at android.widget.RelativeLayout.onLayout(RelativeLayout.java:948)
              at android.view.View.layout(View.java:13754)
              at android.view.ViewGroup.layout(ViewGroup.java:4364)
              at android.widget.RelativeLayout.onLayout(RelativeLayout.java:948)
              at android.view.View.layout(View.java:13754)
              at android.view.ViewGroup.layout(ViewGroup.java:4364)
              at android.support.v4.widget.DrawerLayout.onLayout(DrawerLayout.java:1193)
              at android.view.View.layout(View.java:13754)
              at android.view.ViewGroup.layout(ViewGroup.java:4364)
              at android.widget.FrameLayout.onLayout(FrameLayout.java:448)
              at android.view.View.layout(View.java:13754)
              at android.view.ViewGroup.layout(ViewGroup.java:4364)
              at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1649)
              at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1507)
              at android.widget.LinearLayout.onLayout(LinearLayout.java:1420)
              at android.view.View.layout(View.java:13754)
              at android.view.ViewGroup.layout(ViewGroup.java:4364)
              at android.widget.FrameLayout.onLayout(FrameLayout.java:448)
              at android.view.View.layout(View.java:13754)
              at android.view.ViewGroup.layout(ViewGroup.java:4364)
              at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1649)
              at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1507)
              at android.widget.LinearLayout.onLayout(LinearLayout.java:1420)
              at android.view.View.layout(View.java:13754)
              at android.view.ViewGroup.layout(ViewGroup.java:4364)
              at android.widget.FrameLayout.onLayout(FrameLayout.java:448)
              at android.view.View.layout(View.java:13754)
              at android.view.ViewGroup.layout(ViewGroup.java:4364)
              at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:1868)
              at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1689)
              at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1000)
              at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:4214)
              at android.view.Choreographer$CallbackRecord.run(Choreographer.java:725)
</code>```

Here is the layout file

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="?android:attr/selectableItemBackground"
    android:gravity="center_horizontal"
    android:orientation="vertical"
    android:padding="@dimen/space16">

    <ImageView
        android:id="@+id/iv_recipe"
        android:layout_width="52dp"
        android:layout_height="52dp" />

    <RatingBar
        android:id="@+id/ratingBar"
        style="@style/RatingBar"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="@dimen/space8"
        android:isIndicator="true"
        android:numStars="5"
        android:rating="3.5" />

    <TextView
        android:id="@+id/tv_recipe_name"
        style="@style/SemiBold"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="@dimen/space8"
        android:gravity="center_horizontal"
        android:text="RECIPES"
        android:textColor="@color/colorTextDark"
        android:textSize="@dimen/h3" />

    <TextView
        android:id="@+id/tv_time"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:drawableLeft="@drawable/ic_time"
        android:drawablePadding="@dimen/space8"
        android:text="1h 20'"
        android:textAppearance="@style/Regular"
        android:textColor="@color/colorTextGrey"
        android:textSize="@dimen/h3" />
</LinearLayout>
</code>```

This is the app.gradle file

```<code>apply plugin: 'com.android.application'

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.1"
    defaultConfig {
        applicationId "com.mnm.cookrecipe"
        minSdkVersion 15
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        vectorDrawables.useSupportLibrary = true
    }
    buildTypes {
        debug {
            debuggable true
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
        release {
            debuggable false
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    dexOptions {
        javaMaxHeapSize '3g'
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:25.0.1'
    compile 'com.android.support:design:25.0.1'
    compile 'uk.co.chrisjenx:calligraphy:2.2.0'
    compile 'com.android.support:support-v4:25.0.1'
    compile 'com.github.bumptech.glide:glide:3.7.0'
    compile 'com.android.support:recyclerview-v7:25.0.1'
    compile 'com.android.support:cardview-v7:25.0.1'
    testCompile 'junit:junit:4.12'
}
</code>```

答:
```<code>package jdroidcoder.ua.stackquestion1;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.TextView;

/**
 * Created by jdroidcoder on 01.04.17.
 */

public class RecipeAdapter extends RecyclerView.Adapter<RecipeAdapter.MyViewHolder> {
    private Context context;

    public RecipeAdapter(Context context) {
        this.context = context;
    }

    static class MyViewHolder extends RecyclerView.ViewHolder{
        TextView recipe, time;
        RatingBar ratingBar;
        ImageView imageView;

        MyViewHolder(View view) {
            super(view);

            recipe = (TextView) view.findViewById(R.id.tv_recipe_name);
            time = (TextView) view.findViewById(R.id.tv_time);
            ratingBar = (RatingBar) view.findViewById(R.id.ratingBar);
            imageView = (ImageView) view.findViewById(R.id.iv_recipe);
        }
    }

    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View itemView = ((LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE))
                .inflate(R.layout.item_recipe, parent, false);

        return new MyViewHolder(itemView);
    }

    @Override
    public void onBindViewHolder(MyViewHolder holder, int position) {

    }

    @Override
    public int getItemCount() {
        return 0;
    }
}
</code>```

OR try this:

```<code>  @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View itemView = ((LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE))
                .inflate(R.layout.item_recipe, parent, false);

        if(itemView!=null)
            ((ViewGroup)itemView.getParent()).removeView(itemView);
        return new MyViewHolder(itemView);
    }
</code>```

Body:
When I run my code on Emulator with API 25,

it works fine

Instead on emulator with API 16, I get this error

android.view.InflateException: Binary XML file line #36: Error inflating class TextView

Here is the line where I get the error

public class RecipeAdapter extends RecyclerView.Adapter<RecipeAdapter.MyViewHolder> {
    ...
    static class MyViewHolder extends RecyclerView.ViewHolder{
        TextView recipe, time;
        RatingBar ratingBar;
        ImageView imageView;

        MyViewHolder(View view) {
            super(view);

            recipe = (TextView) view.findViewById(R.id.tv_recipe_name);
            time = (TextView) view.findViewById(R.id.tv_time);
            ratingBar = (RatingBar) view.findViewById(R.id.ratingBar);
            imageView = (ImageView) view.findViewById(R.id.iv_recipe);
        }
    }

    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.item_recipe, parent, false); // <- Error

        return new MyViewHolder(itemView);
    }
    ...
}

This is the error message

E/AndroidRuntime: FATAL EXCEPTION: main
       android.view.InflateException: Binary XML file line #36: Error inflating class TextView
              at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:704)
              at android.view.LayoutInflater.rInflate(LayoutInflater.java:746)
              at android.view.LayoutInflater.inflate(LayoutInflater.java:489)
              at uk.co.chrisjenx.calligraphy.CalligraphyLayoutInflater.inflate(CalligraphyLayoutInflater.java:60)
              at android.view.LayoutInflater.inflate(LayoutInflater.java:396)
              at com.mnm.cookrecipe.recycler.RecipeAdapter.onCreateViewHolder(RecipeAdapter.java:55) // <- this
              at com.mnm.cookrecipe.recycler.RecipeAdapter.onCreateViewHolder(RecipeAdapter.java:21) // <- this
              at android.support.v7.widget.RecyclerView$Adapter.createViewHolder(RecyclerView.java:6078)
              at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5248)
              at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5158)
              at android.support.v7.widget.LinearLayoutManager$LayoutState.next(LinearLayoutManager.java:2061)
              at android.support.v7.widget.GridLayoutManager.layoutChunk(GridLayoutManager.java:562)
              at android.support.v7.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1408)
              at android.support.v7.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:580)
              at android.support.v7.widget.GridLayoutManager.onLayoutChildren(GridLayoutManager.java:170)
              at android.support.v7.widget.RecyclerView.dispatchLayoutStep2(RecyclerView.java:3379)
              at android.support.v7.widget.RecyclerView.dispatchLayout(RecyclerView.java:3188)
              at android.support.v7.widget.RecyclerView.onLayout(RecyclerView.java:3632)
              at android.view.View.layout(View.java:13754)
              at android.view.ViewGroup.layout(ViewGroup.java:4364)
              at android.widget.RelativeLayout.onLayout(RelativeLayout.java:948)
              at android.view.View.layout(View.java:13754)
              at android.view.ViewGroup.layout(ViewGroup.java:4364)
              at android.widget.FrameLayout.onLayout(FrameLayout.java:448)
              at android.view.View.layout(View.java:13754)
              at android.view.ViewGroup.layout(ViewGroup.java:4364)
              at android.widget.RelativeLayout.onLayout(RelativeLayout.java:948)
              at android.view.View.layout(View.java:13754)
              at android.view.ViewGroup.layout(ViewGroup.java:4364)
              at android.widget.RelativeLayout.onLayout(RelativeLayout.java:948)
              at android.view.View.layout(View.java:13754)
              at android.view.ViewGroup.layout(ViewGroup.java:4364)
              at android.support.v4.widget.DrawerLayout.onLayout(DrawerLayout.java:1193)
              at android.view.View.layout(View.java:13754)
              at android.view.ViewGroup.layout(ViewGroup.java:4364)
              at android.widget.FrameLayout.onLayout(FrameLayout.java:448)
              at android.view.View.layout(View.java:13754)
              at android.view.ViewGroup.layout(ViewGroup.java:4364)
              at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1649)
              at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1507)
              at android.widget.LinearLayout.onLayout(LinearLayout.java:1420)
              at android.view.View.layout(View.java:13754)
              at android.view.ViewGroup.layout(ViewGroup.java:4364)
              at android.widget.FrameLayout.onLayout(FrameLayout.java:448)
              at android.view.View.layout(View.java:13754)
              at android.view.ViewGroup.layout(ViewGroup.java:4364)
              at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1649)
              at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1507)
              at android.widget.LinearLayout.onLayout(LinearLayout.java:1420)
              at android.view.View.layout(View.java:13754)
              at android.view.ViewGroup.layout(ViewGroup.java:4364)
              at android.widget.FrameLayout.onLayout(FrameLayout.java:448)
              at android.view.View.layout(View.java:13754)
              at android.view.ViewGroup.layout(ViewGroup.java:4364)
              at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:1868)
              at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1689)
              at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1000)
              at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:4214)
              at android.view.Choreographer$CallbackRecord.run(Choreographer.java:725)

Here is the layout file

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="?android:attr/selectableItemBackground"
    android:gravity="center_horizontal"
    android:orientation="vertical"
    android:padding="@dimen/space16">

    <ImageView
        android:id="@+id/iv_recipe"
        android:layout_width="52dp"
        android:layout_height="52dp" />

    <RatingBar
        android:id="@+id/ratingBar"
        style="@style/RatingBar"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="@dimen/space8"
        android:isIndicator="true"
        android:numStars="5"
        android:rating="3.5" />

    <TextView
        android:id="@+id/tv_recipe_name"
        style="@style/SemiBold"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="@dimen/space8"
        android:gravity="center_horizontal"
        android:text="RECIPES"
        android:textColor="@color/colorTextDark"
        android:textSize="@dimen/h3" />

    <TextView
        android:id="@+id/tv_time"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:drawableLeft="@drawable/ic_time"
        android:drawablePadding="@dimen/space8"
        android:text="1h 20'"
        android:textAppearance="@style/Regular"
        android:textColor="@color/colorTextGrey"
        android:textSize="@dimen/h3" />
</LinearLayout>

This is the app.gradle file

apply plugin: 'com.android.application'

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.1"
    defaultConfig {
        applicationId "com.mnm.cookrecipe"
        minSdkVersion 15
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        vectorDrawables.useSupportLibrary = true
    }
    buildTypes {
        debug {
            debuggable true
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
        release {
            debuggable false
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    dexOptions {
        javaMaxHeapSize '3g'
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:25.0.1'
    compile 'com.android.support:design:25.0.1'
    compile 'uk.co.chrisjenx:calligraphy:2.2.0'
    compile 'com.android.support:support-v4:25.0.1'
    compile 'com.github.bumptech.glide:glide:3.7.0'
    compile 'com.android.support:recyclerview-v7:25.0.1'
    compile 'com.android.support:cardview-v7:25.0.1'
    testCompile 'junit:junit:4.12'
}

Body:
package jdroidcoder.ua.stackquestion1;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.TextView;

/**
 * Created by jdroidcoder on 01.04.17.
 */

public class RecipeAdapter extends RecyclerView.Adapter<RecipeAdapter.MyViewHolder> {
    private Context context;

    public RecipeAdapter(Context context) {
        this.context = context;
    }

    static class MyViewHolder extends RecyclerView.ViewHolder{
        TextView recipe, time;
        RatingBar ratingBar;
        ImageView imageView;

        MyViewHolder(View view) {
            super(view);

            recipe = (TextView) view.findViewById(R.id.tv_recipe_name);
            time = (TextView) view.findViewById(R.id.tv_time);
            ratingBar = (RatingBar) view.findViewById(R.id.ratingBar);
            imageView = (ImageView) view.findViewById(R.id.iv_recipe);
        }
    }

    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View itemView = ((LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE))
                .inflate(R.layout.item_recipe, parent, false);

        return new MyViewHolder(itemView);
    }

    @Override
    public void onBindViewHolder(MyViewHolder holder, int position) {

    }

    @Override
    public int getItemCount() {
        return 0;
    }
}

OR try this:

  @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View itemView = ((LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE))
                .inflate(R.layout.item_recipe, parent, false);

        if(itemView!=null)
            ((ViewGroup)itemView.getParent()).removeView(itemView);
        return new MyViewHolder(itemView);
    }


问:
componentsJoinedByString gives me EXC_BAD_ACCESS
I have an NSMutableArray i am trying to convert into a string.

Declaring my NSMutableArray...

```<code>    NSMutableArray *listData;
</code>```

And later inside a method...

```<code>NSString *foo = [listData componentsJoinedByString:@"|"];
NSLog(@"%@",foo);
</code>```

It seems no matter what i try i keep getting EXC_BAD_ACCESS.

To make sure each element in my array was an NSString i also tried this...

```<code>NSMutableArray *mArray = [[NSMutableArray alloc] init];
for (id ln in listData) {
    NSString *boo = [NSString stringWithFormat: @"%@",ln];
    [mArray addObject:boo];
}
NSString *foo = [mArray componentsJoinedByString:@"|"];
NSLog(@"%@",foo);
</code>```

I can manipulate my NSMutableArray by adding/deleting objects in the same method or other methods inside my class. But when i try "componentsJoinedByString" the error pops up. Does anyone have any advice or another way i can combine this array into a single NSString?

答:
In the code you've given, there will never be an NSMutableArray for listData. At some point in your code, you'll need to create one, and presumably populate it.

Edit
Okay, so you may get into memory management problems here, so let's be a bit clearer:

You're synthesizing getters and setters for the instance variable, so it's good practice to use those to access it, they'll take care of retain and releasing appropriately.

To set listData you can simply use

```<code>self.listData = [listManage getList:[[NSUserDefaults standardUserDefaults] stringForKey:@"list_name"] list:@"LIST"];
</code>```

or

```<code>[self setListData:[listManage getList:[[NSUserDefaults standardUserDefaults] stringForKey:@"list_name"] list:@"LIST"]];
</code>```

if you prefer.

Body:
I have an NSMutableArray i am trying to convert into a string.

Declaring my NSMutableArray...

    NSMutableArray *listData;

And later inside a method...

NSString *foo = [listData componentsJoinedByString:@"|"];
NSLog(@"%@",foo);

It seems no matter what i try i keep getting EXC_BAD_ACCESS.

To make sure each element in my array was an NSString i also tried this...

NSMutableArray *mArray = [[NSMutableArray alloc] init];
for (id ln in listData) {
    NSString *boo = [NSString stringWithFormat: @"%@",ln];
    [mArray addObject:boo];
}
NSString *foo = [mArray componentsJoinedByString:@"|"];
NSLog(@"%@",foo);

I can manipulate my NSMutableArray by adding/deleting objects in the same method or other methods inside my class. But when i try "componentsJoinedByString" the error pops up. Does anyone have any advice or another way i can combine this array into a single NSString?

Body:
In the code you've given, there will never be an NSMutableArray for listData. At some point in your code, you'll need to create one, and presumably populate it.

Edit
Okay, so you may get into memory management problems here, so let's be a bit clearer:

You're synthesizing getters and setters for the instance variable, so it's good practice to use those to access it, they'll take care of retain and releasing appropriately.

To set listData you can simply use

self.listData = [listManage getList:[[NSUserDefaults standardUserDefaults] stringForKey:@"list_name"] list:@"LIST"];

or

[self setListData:[listManage getList:[[NSUserDefaults standardUserDefaults] stringForKey:@"list_name"] list:@"LIST"]];

if you prefer.


答:
Try this:</p>

```<code>states = pd.DataFrame(census_df['STNAME'],census_df['COUNTY'])
states = states.set_index(census_df['STNAME'])
</code>```

Title: Why is there an error in indexing in this Data Frame

Body:
Try this:

states = pd.DataFrame(census_df['STNAME'],census_df['COUNTY'])
states = states.set_index(census_df['STNAME'])


问:
Problems with saving in a many to many relatinship in laravel 5.3 with buttons or checkboxes
i'm having problems with saving in a pivot of a many to many relationship table. in my app i have a series of projects that have many tasks. for a certain project with its tasks, i want the auth user to be able to have assigned the wanted tasks.

so here are my models

```<code>public function tasks(){
        return $this->belongsToMany('App\Task', 'user_task');
    }
}
</code>```

in User model

```<code>public function users(){

        return $this->belongsToMany('App\User', 'user_task');
    }
</code>```

in Task model

```<code>    foreach($project->tasks as $task)
 <form role="form" method="POST" action="{{ route('tasks.assign', ['taskId'=>$task->id]) }}">
                                             {{-- <button class="btn btn-sm btn-success">
                                                <span class="glyphicon glyphicon-star-empty" aria-hidden="true"></span>
                                            </button> --}}
                                            {{ csrf_field() }}

                                                <div class="checkbox">
                                                   <label>
                                                     <input type="checkbox"> {{ $task->name }}
                                                   </label>
                                                   <label> <p>{{ $task->description }}</p></label>
                                                 </div>

                                            @endforeach
                                            <input class = "btn btn-success" type="submit" value="Submit">
                                        </form>
</code>```

and here is my function in the TaskController that is supposed to save in the pivot table

```<code>public function joinTask(Request $request, Task $task)
        {

            $user = Auth::user();

            $user->tasks()->attach($task);

                //$tasks = $this->request->input('tasks', []);

                //$user->tasks()->attach($tasks);

            Session::flash('success','task asignat cu success');

            return redirect()->route('tasks.index')->withProject($project)->withTasks($tasks);
        }
</code>```

I also want to mention that i am super new to laravel, so this project is somehow my first laravel project ( i use laravel 5.3)

答:
First thing I'd verify in your setup is that you use the same "task" variable in your route, in your post form, and in your controller method. Right now it seems like you are trying to pass variable named $taskId into the route:

```<code><form role="form" method="POST" action="{{ route('tasks.assign', ['taskId'=>$task->id]) }}">
</code>```

, but you expect Laravel to auto-instantiate Task model based on $task variable in controller method.

```<code>public function joinTask(Request $request, Task $task)
</code>```

Taking a look at your route definition would help further debug.

A bit of an extra advice:

One more thing I'd clean up is remove the checkbox, for two reasons: 1) looks like it does not have a "name" attribute and therefore sends nothing to server; 2) looks like your form is only submitting one task, and that is done via the route / url, so no need for extra controls, only task name and the submit button.

So a plain GET form would suffice in this case.

Body:
i'm having problems with saving in a pivot of a many to many relationship table. in my app i have a series of projects that have many tasks. for a certain project with its tasks, i want the auth user to be able to have assigned the wanted tasks.

so here are my models

public function tasks(){
        return $this->belongsToMany('App\Task', 'user_task');
    }
}

in User model

public function users(){

        return $this->belongsToMany('App\User', 'user_task');
    }

in Task model

    foreach($project->tasks as $task)
 <form role="form" method="POST" action="{{ route('tasks.assign', ['taskId'=>$task->id]) }}">
                                             {{-- <button class="btn btn-sm btn-success">

                                            </button> --}}
                                            {{ csrf_field() }}

                                                     <input type="checkbox"> {{ $task->name }}

{{ $task->description }}

                                            @endforeach
                                            <input class = "btn btn-success" type="submit" value="Submit">
                                        </form>

and here is my function in the TaskController that is supposed to save in the pivot table

public function joinTask(Request $request, Task $task)
        {

            $user = Auth::user();

            $user->tasks()->attach($task);

                //$tasks = $this->request->input('tasks', []);

                //$user->tasks()->attach($tasks);

            Session::flash('success','task asignat cu success');

            return redirect()->route('tasks.index')->withProject($project)->withTasks($tasks);
        }

I also want to mention that i am super new to laravel, so this project is somehow my first laravel project ( i use laravel 5.3)

Body:
First thing I'd verify in your setup is that you use the same "task" variable in your route, in your post form, and in your controller method. Right now it seems like you are trying to pass variable named $taskId into the route:

<form role="form" method="POST" action="{{ route('tasks.assign', ['taskId'=>$task->id]) }}">

, but you expect Laravel to auto-instantiate Task model based on $task variable in controller method.

public function joinTask(Request $request, Task $task)

Taking a look at your route definition would help further debug.

A bit of an extra advice:

One more thing I'd clean up is remove the checkbox, for two reasons: 1) looks like it does not have a "name" attribute and therefore sends nothing to server; 2) looks like your form is only submitting one task, and that is done via the route / url, so no need for extra controls, only task name and the submit button.

So a plain GET form would suffice in this case.


问:
Warning: Smarty error: unable to read resource: "widget/product/list.tpl" in core/smarty/Smarty.class.php on line 1094
I just installed a OXID eSHOP COMMUNITY EDITION 4.10.2.

I copy paste my live site code into local server. Everything is working fine, but products not display.

It shows below error.

Warning: Smarty error: unable to read resource: "widget/product/list.tpl" in core/smarty/Smarty.class.php on line 1094

However it's working fine on live site. But not working on my local setup.

答: Check if template file "widget/product/list.tpl" exists on your machine. Looks like you did not copy all the files from production server.</p>