问:
Spark CSV package not able to handle \n within fields
I have a CSV file which I am trying to load using Spark CSV package and it does not load data properly because few of the fields have \n within them for e.g. the following two rows

```<code>"XYZ", "Test Data", "TestNew\nline", "OtherData"
"XYZ", "Test Data", "blablablabla
\nblablablablablalbal", "OtherData"
</code>```

I am using the following code which is straightforward I am using parserLib as univocity as read in internet it solves multiple newline problem but it does not seems to be the case for me.

```<code> SQLContext sqlContext = new SQLContext(sc);
    DataFrame df = sqlContext.read()
        .format("com.databricks.spark.csv")
        .option("inferSchema", "true")
        .option("header", "true")
        .option("parserLib","univocity")
        .load("data.csv");
</code>```

How do I replace newline within fields which starts with quotes. Is there any easier way?

答:
There is an option available to users of Spark 2.2 to account for line breaks in CSV files. It was originally discussed as being called wholeFile but prior to release was renamed multiLine.

Here is an example of loading in a CSV to a dataframe with that option:

```<code>var webtrends_data = (sparkSession.read
.option("header", "true")
.option("inferSchema", "true")
.option("multiLine", true)
.option("delimiter", ",")
.format("csv")
.load("hdfs://hadoop-master:9000/datasource/myfile.csv"))
</code>```

Body:
I have a CSV file which I am trying to load using Spark CSV package and it does not load data properly because few of the fields have \n within them for e.g. the following two rows

"XYZ", "Test Data", "TestNew\nline", "OtherData"
"XYZ", "Test Data", "blablablabla
\nblablablablablalbal", "OtherData"

I am using the following code which is straightforward I am using parserLib as univocity as read in internet it solves multiple newline problem but it does not seems to be the case for me.

 SQLContext sqlContext = new SQLContext(sc);
    DataFrame df = sqlContext.read()
        .format("com.databricks.spark.csv")
        .option("inferSchema", "true")
        .option("header", "true")
        .option("parserLib","univocity")
        .load("data.csv");

How do I replace newline within fields which starts with quotes. Is there any easier way?

Body:
There is an option available to users of Spark 2.2 to account for line breaks in CSV files. It was originally discussed as being called wholeFile but prior to release was renamed multiLine.

Here is an example of loading in a CSV to a dataframe with that option:

var webtrends_data = (sparkSession.read
.option("header", "true")
.option("inferSchema", "true")
.option("multiLine", true)
.option("delimiter", ",")
.format("csv")
.load("hdfs://hadoop-master:9000/datasource/myfile.csv"))


来源: stackexchange

问:
Query using Order By in JDBC request
I have a jdbc request in jmeter where i am searching user data from the table.But data shows multiple records so i need to use order by latest updated date.

SQL is working fine but display multiple record,how can i use

```<code> SELECT CREATION_DATE,PROCESS_FLAG FROM
 CUST  where ORDER_NUMBER =? order by
 LAST_UPDATE_DATE desc;
</code>```

because it is giving me error invalid character while trying using jmeter

答:
JMeter doesn't allow to use ; sign at the end of JDBC Request select statement.

Do not enter a trailing semi-colon.

Just remove last character and SQL will be executed wìthout error.

ContentLicense: CC BY-SA 4.0

Title: Query using Order By in JDBC request

Body:
I have a jdbc request in jmeter where i am searching user data from the table.But data shows multiple records so i need to use order by latest updated date.

SQL is working fine but display multiple record,how can i use

 SELECT CREATION_DATE,PROCESS_FLAG FROM
 CUST  where ORDER_NUMBER =? order by
 LAST_UPDATE_DATE desc;

because it is giving me error invalid character while trying using jmeter

ContentLicense: CC BY-SA 3.0


问:
Get price between 2 dates

I am trying to get the price between 2 dates based on the hotel tariffs.

```<code>var dates = new List<DateTime>();
for (var dt = checkIn; dt <= checkOut; dt = dt.AddDays(1))
{
    dates.Add(dt);
}

try
{
    cnn = new MySqlConnection(connString);
    cnn.ConnectionString = connString;
    cnn.Open();

    for (int i = 0; i < dates.Count - 1; i++)
    {
        lblResult.Text = "Pass";
        string da = dates[i].Year + "-" + dates[i].Month + "-" + dates[i].Day;
        DayOfWeek da1 = dates[i].DayOfWeek;
        if (dates[i].Day == 1 && dates[i].Month == 1 || dates[i].Day == 9 && dates[i].Month == 1 || dates[i].Day == 11 && dates[i].Month == 2 || dates[i].Day == 20 && dates[i].Month == 3 || dates[i].Day == 29 && dates[i].Month == 4 || dates[i].Day == 3 && dates[i].Month == 5 || dates[i].Day == 4 && dates[i].Month == 5 || dates[i].Day == 5 && dates[i].Month == 5 || dates[i].Day == 17 && dates[i].Month == 7 || dates[i].Day == 11 && dates[i].Month == 8 || dates[i].Day == 18 && dates[i].Month == 9 || dates[i].Day == 22 && dates[i].Month == 9 || dates[i].Day == 9 && dates[i].Month == 10 || dates[i].Day == 3 && dates[i].Month == 11 || dates[i].Day == 23 && dates[i].Month == 11 || dates[i].Day == 23 && dates[i].Month == 12)
        {
            sql = "SELECT GrossPrice FROM HotelPriceFIT WHERE HotelName='" + hotelName + "' AND RmType='" + rmType + "' AND Remarks LIKE '%Eve of Japan Holiday%' AND DATE(StartDate) >='" + da + "' AND DATE(EndDate) <='" + da + "'";
            ClientScript.RegisterStartupScript(GetType(), "alert", "alert('Pass 2');", true);
        }
        else if (da1.ToString() == "Saturday")
        {
            sql = "SELECT GrossPrice FROM HotelPriceFIT WHERE HotelName='" + hotelName + "' AND RmType='" + rmType + "' AND Remarks LIKE '%Sat%' AND DATE(StartDate) >='" + da + "' AND DATE(EndDate) <='" + da + "'";
            ClientScript.RegisterStartupScript(GetType(), "alert", "alert('Pass 3');", true);
        }
        else
        {
            **sql = "SELECT GrossPrice FROM HotelPriceFIT WHERE HotelName='" + hotelName + "' AND RmType='" + rmType + "' AND DATE(StartDate) >='" + da + "' AND DATE(EndDate) <='" + da + "'";**
            ClientScript.RegisterStartupScript(GetType(), "alert", "alert('Pass 4');", true);
            lblPassHotel.Text = sql;
        }
        cmd = new MySqlCommand(sql, cnn);
        reader = cmd.ExecuteReader();
        if (reader.Read() == true)
        {
            amount = amount + reader.GetInt16(0);
        }
        reader.Close();
    }
    cnn.Close();
}
</code>```

If i select

2018-01-18 as start date and 2018-01-19 as end date, it should return me 9000.

Appreciate any form of support.

Empty set

答:
Multiple problems here:

You need to group this line using () brackets. Since you have not grouped you are confusing yourself. Either group all && or group all || so final condition is && only (or || only)

```<code>if (dates[i].Day == 1 && dates[i].Month == 1 || dates[i].Day == 9 && dates[i].Month == 1 || dates[i].Day == 11 && dates[i].Month == 2 || dates[i].Day == 20 && dates[i].Month == 3 || dates[i].Day == 29 && dates[i].Month == 4 || dates[i].Day == 3 && dates[i].Month == 5 || dates[i].Day == 4 && dates[i].Month == 5 || dates[i].Day == 5 && dates[i].Month == 5 || dates[i].Day == 17 && dates[i].Month == 7 || dates[i].Day == 11 && dates[i].Month == 8 || dates[i].Day == 18 && dates[i].Month == 9 || dates[i].Day == 22 && dates[i].Month == 9 || dates[i].Day == 9 && dates[i].Month == 10 || dates[i].Day == 3 && dates[i].Month == 11 || dates[i].Day == 23 && dates[i].Month == 11 || dates[i].Day == 23 && dates[i].Month == 12)
</code>```

This is the reason, that always last Else condition gets executed.

This code is prone to SQL Injection attack. Parameterize your query.

Title: Get price between 2 dates

Body:
I am trying to get the price between 2 dates based on the hotel tariffs.

var dates = new List<DateTime>();
for (var dt = checkIn; dt <= checkOut; dt = dt.AddDays(1))
{
    dates.Add(dt);
}

try
{
    cnn = new MySqlConnection(connString);
    cnn.ConnectionString = connString;
    cnn.Open();

    for (int i = 0; i < dates.Count - 1; i++)
    {
        lblResult.Text = "Pass";
        string da = dates[i].Year + "-" + dates[i].Month + "-" + dates[i].Day;
        DayOfWeek da1 = dates[i].DayOfWeek;
        if (dates[i].Day == 1 && dates[i].Month == 1 || dates[i].Day == 9 && dates[i].Month == 1 || dates[i].Day == 11 && dates[i].Month == 2 || dates[i].Day == 20 && dates[i].Month == 3 || dates[i].Day == 29 && dates[i].Month == 4 || dates[i].Day == 3 && dates[i].Month == 5 || dates[i].Day == 4 && dates[i].Month == 5 || dates[i].Day == 5 && dates[i].Month == 5 || dates[i].Day == 17 && dates[i].Month == 7 || dates[i].Day == 11 && dates[i].Month == 8 || dates[i].Day == 18 && dates[i].Month == 9 || dates[i].Day == 22 && dates[i].Month == 9 || dates[i].Day == 9 && dates[i].Month == 10 || dates[i].Day == 3 && dates[i].Month == 11 || dates[i].Day == 23 && dates[i].Month == 11 || dates[i].Day == 23 && dates[i].Month == 12)
        {
            sql = "SELECT GrossPrice FROM HotelPriceFIT WHERE HotelName='" + hotelName + "' AND RmType='" + rmType + "' AND Remarks LIKE '%Eve of Japan Holiday%' AND DATE(StartDate) >='" + da + "' AND DATE(EndDate) <='" + da + "'";
            ClientScript.RegisterStartupScript(GetType(), "alert", "alert('Pass 2');", true);
        }
        else if (da1.ToString() == "Saturday")
        {
            sql = "SELECT GrossPrice FROM HotelPriceFIT WHERE HotelName='" + hotelName + "' AND RmType='" + rmType + "' AND Remarks LIKE '%Sat%' AND DATE(StartDate) >='" + da + "' AND DATE(EndDate) <='" + da + "'";
            ClientScript.RegisterStartupScript(GetType(), "alert", "alert('Pass 3');", true);
        }
        else
        {
            **sql = "SELECT GrossPrice FROM HotelPriceFIT WHERE HotelName='" + hotelName + "' AND RmType='" + rmType + "' AND DATE(StartDate) >='" + da + "' AND DATE(EndDate) <='" + da + "'";**
            ClientScript.RegisterStartupScript(GetType(), "alert", "alert('Pass 4');", true);
            lblPassHotel.Text = sql;
        }
        cmd = new MySqlCommand(sql, cnn);
        reader = cmd.ExecuteReader();
        if (reader.Read() == true)
        {
            amount = amount + reader.GetInt16(0);
        }
        reader.Close();
    }
    cnn.Close();
}

If i select

2018-01-18 as start date and 2018-01-19 as end date, it should return me 9000.

Appreciate any form of support.

Empty set

Body:
Multiple problems here:

You need to group this line using () brackets. Since you have not grouped you are confusing yourself. Either group all && or group all || so final condition is && only (or || only)

if (dates[i].Day == 1 && dates[i].Month == 1 || dates[i].Day == 9 && dates[i].Month == 1 || dates[i].Day == 11 && dates[i].Month == 2 || dates[i].Day == 20 && dates[i].Month == 3 || dates[i].Day == 29 && dates[i].Month == 4 || dates[i].Day == 3 && dates[i].Month == 5 || dates[i].Day == 4 && dates[i].Month == 5 || dates[i].Day == 5 && dates[i].Month == 5 || dates[i].Day == 17 && dates[i].Month == 7 || dates[i].Day == 11 && dates[i].Month == 8 || dates[i].Day == 18 && dates[i].Month == 9 || dates[i].Day == 22 && dates[i].Month == 9 || dates[i].Day == 9 && dates[i].Month == 10 || dates[i].Day == 3 && dates[i].Month == 11 || dates[i].Day == 23 && dates[i].Month == 11 || dates[i].Day == 23 && dates[i].Month == 12)

This is the reason, that always last Else condition gets executed.

This code is prone to SQL Injection attack. Parameterize your query.


问:
Can't convert JSON string to Javascript object
I am trying to convert JSON string to javascript object, but unsuccessfully.

This is my code:

```<code>result = "{'image': 'https://google.com/16469374645-11-12-05-27-10-2017.jpg', 'sender': 'Test test123', 'text': 'Test 005', 'expiry': '2016-10-15 01:51:28', 'points': 650, 'color_from': '#8DBCC5', 'color_to': '#13717C'}";
result = JSON.parse(result);
console.log(result);
alert(result);
</code>```

I have created a fiddle with a demo.
https://jsfiddle.net/030u9z9f/1/

It seems like my JSON is not properly formatted, but I am not sure how to adjust it.

答:
There JSON does not contain any single quote for there key and value description you have change all ' to " for the same string. There all the Key and Value should be enquoted by " and a complete string of JSON must be enclosed with ' for better string conversion.

The JSON standard requires double quotes and will not accept single quotes, nor will the parser.

If you have a simple case with no escaped single quotes in your strings (which would normally be impossible, but this isn't JSON), you can simple str.replace(/'/g, '"') and you should end up with valid JSON.
check ...

```<code>result = '{"image": "https://google.com/16469374645-11-12-05-27-10-2017.jpg", "sender": "Test test123", "text": "Test 005", "expiry": "2016-10-15 01:51:28", "points": 650, "color_from": "#8DBCC5", "color_to": "#13717C"}';
result = JSON.parse(result);
console.log(result);
alert(result);
</code>```

Fiddle

Ref

Body:
I am trying to convert JSON string to javascript object, but unsuccessfully.

This is my code:

result = "{'image': 'https://google.com/16469374645-11-12-05-27-10-2017.jpg', 'sender': 'Test test123', 'text': 'Test 005', 'expiry': '2016-10-15 01:51:28', 'points': 650, 'color_from': '#8DBCC5', 'color_to': '#13717C'}";
result = JSON.parse(result);
console.log(result);
alert(result);

I have created a fiddle with a demo.
https://jsfiddle.net/030u9z9f/1/

It seems like my JSON is not properly formatted, but I am not sure how to adjust it.

Body:
There JSON does not contain any single quote for there key and value description you have change all ' to " for the same string. There all the Key and Value should be enquoted by " and a complete string of JSON must be enclosed with ' for better string conversion.

The JSON standard requires double quotes and will not accept single quotes, nor will the parser.

If you have a simple case with no escaped single quotes in your strings (which would normally be impossible, but this isn't JSON), you can simple str.replace(/'/g, '"') and you should end up with valid JSON.
check ...

result = '{"image": "https://google.com/16469374645-11-12-05-27-10-2017.jpg", "sender": "Test test123", "text": "Test 005", "expiry": "2016-10-15 01:51:28", "points": 650, "color_from": "#8DBCC5", "color_to": "#13717C"}';
result = JSON.parse(result);
console.log(result);
alert(result);

Fiddle

Ref


问:
Develop Android App On Bluej
We are using BlueJ to develop simple apps in my an intro class for students.

I would like to effectively develop a basic Android app in BlueJ.  Is this possible?

答: Bluej is just an IDE.  It is generally used by beginners to write simple programs.  If you want to develop Android apps I would suggest you to use Android studio as all the functions and tools are pre-built in the application.  You just need to have basic Java knowledge and XML understanding to write the code.  If you want to to develop an application without any coding knowledge then I would suggest you to use thunkables or MIT App inventor.  Using any of these you just need to develop your own logic and create an awesome app without coding.</p>

Title: Develop Android App On Bluej


问:
Why does RewriteRule ^page/?$ page.php [L] match site.com/page//
```<code>RewriteEngine on
RewriteRule ^page/?$ page.php [L]
</code>```

This ends up matching the url www.site.com/page// but internally it acts differently than www.site.com/page/ because the stylesheets and images no longer appear properly. Am I doing something wrong or is this just something I need to deal with if I don't want to go through a lot of trouble?

To me it looks like it should only match www.site.com/page or www.site.com/page/

答:
Apache strips the empty path segment. So /path// is treated as /path/. But your browser doesn’t so relative URLs are resolved using /path//.

If you want to remove the multiple slashes, you can use the following rule:

```<code>RewriteCond %{THE_REQUEST} ^[A-Z]+\ /(([^/\ ]+/)*)/+([^\ ]*)
RewriteRule ^ /%1%3 [L,R=301]
</code>```

Explaination

Despite Apache removes empty path segments internal, the THE_REQUEST environment variable (holding the HTTP request line) stays untouched. So we can use this value to check for multiple slashes.

^[A-Z]+\ / matches the request method, the following space and the first slash character of the URI path.

(([^/\ ]+/)*) matches all following non-empty path segments (foo/, foo/bar/, foo/bar/baz/, etc.) or nothing, if there are none.

/+ matches the empty path segments as the character before this slash is always another slash (see the expressions before).

([^\ ]*) matches the rest of the URI (that may contain further empty path segments).

Example: Let’s say we request http://example.com/foo/bar//baz, the request line will look like this:

```<code>GET /foo/bar//baz HTTP/1.1
</code>```

The pattern would then match as follows:

```<code>0: GET /foo/bar//baz
1: foo/bar/
2: bar/
3: baz
</code>```

So the requested path /foo/bar//baz would be redirected to /foo/bar/baz (/%1%3).

ContentLicense: CC BY-SA 2.5

Body:
RewriteEngine on
RewriteRule ^page/?$ page.php [L]

This ends up matching the url www.site.com/page// but internally it acts differently than www.site.com/page/ because the stylesheets and images no longer appear properly. Am I doing something wrong or is this just something I need to deal with if I don't want to go through a lot of trouble?

To me it looks like it should only match www.site.com/page or www.site.com/page/

LastEditorDisplayName: Fabian Steeg

Body:
Apache strips the empty path segment. So /path// is treated as /path/. But your browser doesn’t so relative URLs are resolved using /path//.

If you want to remove the multiple slashes, you can use the following rule:

RewriteCond %{THE_REQUEST} ^[A-Z]+\ /(([^/\ ]+/)*)/+([^\ ]*)
RewriteRule ^ /%1%3 [L,R=301]

Explaination

Despite Apache removes empty path segments internal, the THE_REQUEST environment variable (holding the HTTP request line) stays untouched. So we can use this value to check for multiple slashes.

^[A-Z]+\ / matches the request method, the following space and the first slash character of the URI path.

(([^/\ ]+/)*) matches all following non-empty path segments (foo/, foo/bar/, foo/bar/baz/, etc.) or nothing, if there are none.

/+ matches the empty path segments as the character before this slash is always another slash (see the expressions before).

([^\ ]*) matches the rest of the URI (that may contain further empty path segments).

Example: Let’s say we request http://example.com/foo/bar//baz, the request line will look like this:

GET /foo/bar//baz HTTP/1.1

The pattern would then match as follows:

0: GET /foo/bar//baz
1: foo/bar/
2: bar/
3: baz

So the requested path /foo/bar//baz would be redirected to /foo/bar/baz (/%1%3).

OwnerDisplayName: Gumbo

LastEditorDisplayName: Gumbo


问:
Free alternative to MPLAB (PIC development)
I started using MPLAB recently, but for someone that works with Eclipse and VS the IDE it's very limited. Do you know any free IDE or how to configure Ecplise or Netbeans to PIC development?

Thanks all

答:
Some Options:

Piklab (this is a fork of pikdev and better IMO, has a windows version)

Pikdev

You'll probably need gputils which is a set of open source PIC utilities for various things and integrate into the above IDEs.

There is also PIC C builder for Eclipse that would let you build with the C30 compiler, don't think it supports C18 but maybe.


问:
How to hide UINavigationBar 1px bottom line
I have an app that sometimes needs its navigation bar to blend in with the content.

Does anyone know how to get rid of or to change color of this annoying little bar?

On the image below situation i have - i'm talking about this 1px height line below "Root View Controller"

答:
Hi this works for Swift 4.

```<code>    override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()
    self.navigationController?.navigationBar.shadowImage = UIImage()
    self.navigationController?.navigationBar.setBackgroundImage(UIImage(), for: .default)
    self.navigationController?.navigationBar.isTranslucent = false
}
</code>```

you need to put this in viewDidLayoutSubviews instead of viewDidLoad

Body:
Hi this works for Swift 4.

    override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()
    self.navigationController?.navigationBar.shadowImage = UIImage()
    self.navigationController?.navigationBar.setBackgroundImage(UIImage(), for: .default)
    self.navigationController?.navigationBar.isTranslucent = false
}

you need to put this in viewDidLayoutSubviews instead of viewDidLoad


问:
DQN not working Properly
I am trying to write my own DQN in Python, using keras. I think my logic is correct. I am trying it on the CartPole environment, but the rewards are not increasing after 50,000 episodes. Any help will be appreciated. Currently I am not looking to the dueling or the Double DQN part. </p>

```<code>class ReplayBuffer:
        def __init__(self, size=100000):
            self.buffer=deque(maxlen=size)

        def sample(self, sample_size):
            return random.sample(self.buffer, sample_size)

        def add_to_buffer(self, experience):
            self.buffer.append(experience)

    def generator(number):
        return(i for i in range(number))

    def epsilon_greedy_policy(q_values, epsilon):
        number_of_actions =len(q_values)
        action_probabilites = np.ones(number_of_actions, dtype=float)*epsilon/number_of_actions
        best_action = np.argmax(q_values)
        action_probabilites[best_action]+= (1-epsilon)
        return np.random.choice(number_of_actions, p=action_probabilites)

    class DQNAgent:
        def __init__(self, env, model, gamma):
            self.env=env
            self.model=model
            self.replay_buffer=ReplayBuffer()
            self.gamma=gamma
            self.state_dim=env.observation_space.shape[0]

        def train_model(self, training_data, training_label):
            self.model.fit(training_data, training_label, batch_size=32, verbose=0)

        def predict_one(self, state):
            return self.model.predict(state.reshape(1, self.state_dim)).flatten()

        def experience_replay(self, experiences):
            import pdb; pdb.set_trace()
            states, actions, rewards, next_states=zip(*[[experience[0], experience[1], experience[2], experience[3]] for experience in experiences])
            states=np.asarray(states)
            place_holder_state=np.zeros(self.state_dim)
            next_states_ = np.asarray([(place_holder_state if next_state is None else next_state) for next_state in next_states])
            q_values_for_states=self.model.predict(states)
            q_values_for_next_states=self.model.predict(next_states_)
            for x in generator(len(experiences)):
                y_true=rewards[x]
                if next_states[x].any():
                    y_true +=self.gamma*(np.amax(q_values_for_next_states[x]))
                q_values_for_states[x][actions[x]]=y_true
            self.train_model(states, q_values_for_states)

        def fit(self, number_of_epsiodes, batch_size):
            for _ in generator(number_of_epsiodes):
                total_reward=0
                state=env.reset()
                while True:
                    #self.env.render()
                    q_values_for_state=self.predict_one(state)
                    action=epsilon_greedy_policy(q_values_for_state, 0.1)
                    next_state, reward, done, _=env.step(action)
                    self.replay_buffer.add_to_buffer([state, action, reward, next_state])
                    state = next_state
                    total_reward += reward
                    if len(self.replay_buffer.buffer) > 50:
                        experience=self.replay_buffer.sample(batch_size)
                        self.experience_replay(experience)
                    if done:
                       break
                print("Total reward:", total_reward)

    env = gym.make('CartPole-v0')
    model=create_model(env.observation_space.shape[0], env.action_space.n)
    agent=DQNAgent(env, model, 0.99)
    agent.fit(100000, 32)'
</code>```

答:
The error lies in these two lines

```<code>    q_values_for_states=self.model.predict(states)
    q_values_for_next_states=self.model.predict(next_states_)
</code>```

You have the same network for Q and for its target. In the DQN paper, the authors use two separate networks and update the target network every X steps by copying the Q-network weights.

The correct equations are (pseudocode)

```<code>    T = R + gamma * max(QT(next_state))  # target
    E = T - Q(state)                     # error
</code>```

So your equations should be

```<code>    q_values_for_states=self.model.predict(states)
    q_values_for_next_states=self.target_model.predict(next_states_)
</code>```

And then you update target_model.
In more recent papers (for example the DDPG one), instead of copying the weights every X steps, they perform a soft update every state, that is

```<code>    QT_weights = tau*Q_weights + (1-tau)*QT_weights
</code>```

What you are doing, instead, is like updating the target network every step. This makes the algorithm very unstable, as the authors of DQN state in their paper.

Also, I would increase the minimum number of samples used for learning. You start learning when only 50 samples are collected, which are way too few. In the paper they use way more and for the cart pole I would wait for 1000 samples to be collected (consider that you should balance the pole for at least 1000 steps or something).

Title: DQN not working Properly

Body:
I am trying to write my own DQN in Python, using keras. I think my logic is correct. I am trying it on the CartPole environment, but the rewards are not increasing after 50,000 episodes. Any help will be appreciated. Currently I am not looking to the dueling or the Double DQN part.

class ReplayBuffer:
        def __init__(self, size=100000):
            self.buffer=deque(maxlen=size)

        def sample(self, sample_size):
            return random.sample(self.buffer, sample_size)

        def add_to_buffer(self, experience):
            self.buffer.append(experience)

    def generator(number):
        return(i for i in range(number))

    def epsilon_greedy_policy(q_values, epsilon):
        number_of_actions =len(q_values)
        action_probabilites = np.ones(number_of_actions, dtype=float)*epsilon/number_of_actions
        best_action = np.argmax(q_values)
        action_probabilites[best_action]+= (1-epsilon)
        return np.random.choice(number_of_actions, p=action_probabilites)

    class DQNAgent:
        def __init__(self, env, model, gamma):
            self.env=env
            self.model=model
            self.replay_buffer=ReplayBuffer()
            self.gamma=gamma
            self.state_dim=env.observation_space.shape[0]

        def train_model(self, training_data, training_label):
            self.model.fit(training_data, training_label, batch_size=32, verbose=0)

        def predict_one(self, state):
            return self.model.predict(state.reshape(1, self.state_dim)).flatten()

        def experience_replay(self, experiences):
            import pdb; pdb.set_trace()
            states, actions, rewards, next_states=zip(*[[experience[0], experience[1], experience[2], experience[3]] for experience in experiences])
            states=np.asarray(states)
            place_holder_state=np.zeros(self.state_dim)
            next_states_ = np.asarray([(place_holder_state if next_state is None else next_state) for next_state in next_states])
            q_values_for_states=self.model.predict(states)
            q_values_for_next_states=self.model.predict(next_states_)
            for x in generator(len(experiences)):
                y_true=rewards[x]
                if next_states[x].any():
                    y_true +=self.gamma*(np.amax(q_values_for_next_states[x]))
                q_values_for_states[x][actions[x]]=y_true
            self.train_model(states, q_values_for_states)

        def fit(self, number_of_epsiodes, batch_size):
            for _ in generator(number_of_epsiodes):
                total_reward=0
                state=env.reset()
                while True:
                    #self.env.render()
                    q_values_for_state=self.predict_one(state)
                    action=epsilon_greedy_policy(q_values_for_state, 0.1)
                    next_state, reward, done, _=env.step(action)
                    self.replay_buffer.add_to_buffer([state, action, reward, next_state])
                    state = next_state
                    total_reward += reward
                    if len(self.replay_buffer.buffer) > 50:
                        experience=self.replay_buffer.sample(batch_size)
                        self.experience_replay(experience)
                    if done:
                       break
                print("Total reward:", total_reward)

    env = gym.make('CartPole-v0')
    model=create_model(env.observation_space.shape[0], env.action_space.n)
    agent=DQNAgent(env, model, 0.99)
    agent.fit(100000, 32)'

Body:
The error lies in these two lines

    q_values_for_states=self.model.predict(states)
    q_values_for_next_states=self.model.predict(next_states_)

You have the same network for Q and for its target. In the DQN paper, the authors use two separate networks and update the target network every X steps by copying the Q-network weights.

The correct equations are (pseudocode)

    T = R + gamma * max(QT(next_state))  # target
    E = T - Q(state)                     # error

So your equations should be

    q_values_for_states=self.model.predict(states)
    q_values_for_next_states=self.target_model.predict(next_states_)

And then you update target_model.
In more recent papers (for example the DDPG one), instead of copying the weights every X steps, they perform a soft update every state, that is

    QT_weights = tau*Q_weights + (1-tau)*QT_weights

What you are doing, instead, is like updating the target network every step. This makes the algorithm very unstable, as the authors of DQN state in their paper.

Also, I would increase the minimum number of samples used for learning. You start learning when only 50 samples are collected, which are way too few. In the paper they use way more and for the cart pole I would wait for 1000 samples to be collected (consider that you should balance the pole for at least 1000 steps or something).


问:
3 images centered in a row
I am trying to have three images centered in a row and then centered on the page. I've got them all in a row but I cannot get them centered. Any suggestions on getting my group to the middle? I tried 0 auto on the contain class and on the social class. so close!!

My HTML: first thing is div class=contain to wrap the whole thing, but for some reason if I try to include the class contain in HTML it disppears on Stack Overflow so excuse that.

.contain {
  max-width: 960px;
  text-align: center;
}

.social {
  position: relative;
  display: inline-block;
  float: left;
  padding: 10px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="contain">
  <div align="center;" class="social">
    <img src="http://theinvicto.com/wp-
content/uploads/2017/12/facebook.png" alt="" width="75" height="75" />
  </div>
  <div align="center;" class="social">
    <img src="http://theinvicto.com/wp-content/uploads/2017/12/twitter.png" alt="" width="75" height="75" />
  </div>
  <div align="center;" class="social">
    <img src="http://theinvicto.com/wp-
content/uploads/2017/12/instagram.png" alt="" width="75" height="75" />
  </div>
</div></code>```

答:
Keeping your current code, simply remove the flex: left: (JSFiddle example):

```<code>.contain {
  max-width: 960px;
  text-align: center;
}

.social {
  position: relative;
  display: inline-block;
  padding: 10px;
}
</code>```

If based on your browser compatibility requirements you can afford to use display: flex; (MDN) then that's the easiest way (jsfiddle example):

```<code>.contain {
  display: flex;
  justify-content: center;
}

.social {
  padding: 10px;
}
</code>```

There's an excellent flexbox tutorial here: flexbox froggy. Floats are pretty strange and I personally find flexes much more intuitive.

Title: 3 images centered in a row

Body:
Keeping your current code, simply remove the flex: left: (JSFiddle example):

.contain {
  max-width: 960px;
  text-align: center;
}

.social {
  position: relative;
  display: inline-block;
  padding: 10px;
}

If based on your browser compatibility requirements you can afford to use display: flex; (MDN) then that's the easiest way (jsfiddle example):

.contain {
  display: flex;
  justify-content: center;
}

.social {
  padding: 10px;
}

There's an excellent flexbox tutorial here: flexbox froggy. Floats are pretty strange and I personally find flexes much more intuitive.


问:
Summing grouped items in a numpy array without looping
I'm trying to sum those non-zero values in array a that have the same value in array label and then replace them with 0 but only one of them with their sum:

```<code>import numpy as np
a =    np.array([[0,0,0,5,5,0],
                 [1,1,0,2,2,0],
                 [0,0,0,0,2,0],
                 [0,0,0,0,0,0],
                 [0,0,0,3,3,3]])

label = np.array([[0,1,2,3,3,3],
                  [1,1,4,4,4,3],
                  [1,4,4,5,4,6],
                  [1,4,4,4,7,8],
                  [9,5,5,5,5,5]])

#should produce the following result:
result =        [[0,0,0,0,0,10],
                 [2,0,0,0,6,0],
                 [0,0,0,0,0,0],
                 [0,0,0,0,0,0],
                 [0,0,0,0,9,0]]
</code>```

it doesn't matter where we replace the sum.
I couldn't think of any other way than looping.

```<code>a_ = a.ravel()
labels_ = labels.ravel()
list_of_labels = np.unique(label[a>0])

for item in list_of_labels:
     summ = np.sum(a_[np.argwhere((a_> 0) & (labels_ == item))])
     print summ
</code>```

答:
You can get the sums using np.bincount with the weights parameter. If I'm not mistaken np.bincount is O(n) as is the rest of the code below:

```<code># get the sums
cnts = np.bincount(label.ravel(), a.ravel())
# next two lines get indices of the last occurrence of each label
psns = np.full(cnts.shape, -1, dtype=int)
psns[label.ravel()] = range(label.size)
# now plug the sums at the appropriate positions
resflat = np.zeros((a.size + 1,), dtype=a.dtype)
resflat[psns] = cnts
result = resflat[:-1].reshape(a.shape)
result
# array([[ 0,  0,  0,  0,  0,  0],
#        [ 0,  0,  0,  0,  0, 10],
#        [ 0,  0,  0,  0,  0,  0],
#        [ 2,  0,  0,  6,  0,  0],
#        [ 0,  0,  0,  0,  0,  9]])
</code>```

Body:
I'm trying to sum those non-zero values in array a that have the same value in array label and then replace them with 0 but only one of them with their sum:

import numpy as np
a =    np.array([[0,0,0,5,5,0],
                 [1,1,0,2,2,0],
                 [0,0,0,0,2,0],
                 [0,0,0,0,0,0],
                 [0,0,0,3,3,3]])

label = np.array([[0,1,2,3,3,3],
                  [1,1,4,4,4,3],
                  [1,4,4,5,4,6],
                  [1,4,4,4,7,8],
                  [9,5,5,5,5,5]])

#should produce the following result:
result =        [[0,0,0,0,0,10],
                 [2,0,0,0,6,0],
                 [0,0,0,0,0,0],
                 [0,0,0,0,0,0],
                 [0,0,0,0,9,0]]

it doesn't matter where we replace the sum.
I couldn't think of any other way than looping.

a_ = a.ravel()
labels_ = labels.ravel()
list_of_labels = np.unique(label[a>0])

for item in list_of_labels:
     summ = np.sum(a_[np.argwhere((a_> 0) & (labels_ == item))])
     print summ

Body:
You can get the sums using np.bincount with the weights parameter. If I'm not mistaken np.bincount is O(n) as is the rest of the code below:

# get the sums
cnts = np.bincount(label.ravel(), a.ravel())
# next two lines get indices of the last occurrence of each label
psns = np.full(cnts.shape, -1, dtype=int)
psns[label.ravel()] = range(label.size)
# now plug the sums at the appropriate positions
resflat = np.zeros((a.size + 1,), dtype=a.dtype)
resflat[psns] = cnts
result = resflat[:-1].reshape(a.shape)
result
# array([[ 0,  0,  0,  0,  0,  0],
#        [ 0,  0,  0,  0,  0, 10],
#        [ 0,  0,  0,  0,  0,  0],
#        [ 2,  0,  0,  6,  0,  0],
#        [ 0,  0,  0,  0,  0,  9]])


问:
Chartjs Tooltip Line Breaks
Is it possible to get line breaks in chartjs tooltips?

```<code>tooltipTemplate: "<%if (label){%><%=label%>: <%}%><%= value %>"
</code>```

I want to replace ": " with a new line.

I've tried with
, \u000D, \n and
 to no avail.

Update: I have changed my accepted answer now that chart.js is on version 2.

答:
Actually all tool-tip callbacks support multiple lines of text, and you can use label callback as usual. It renders data label as tool-tip text by default.

Quoted from documentation:

All functions must return either a string or an array of strings. Arrays of strings are treated as multiple lines of text.

Example code:

```<code>tooltips: {
    callbacks: {
      label: (tooltipItem, data) => {
        if (tooltipItem.index % 2)
          return ['Item 1', 'Item 2', 'Item 3'];
        else
          return 'Single line';
      }
    }
  }
</code>```

Title: Chartjs Tooltip Line Breaks

Body:
Is it possible to get line breaks in chartjs tooltips?

tooltipTemplate: "<%if (label){%><%=label%>: <%}%><%= value %>"

I want to replace ": " with a new line.

I've tried with
, \u000D, \n and
 to no avail.

Update: I have changed my accepted answer now that chart.js is on version 2.

Body:
Actually all tool-tip callbacks support multiple lines of text, and you can use label callback as usual. It renders data label as tool-tip text by default.

Quoted from documentation:

All functions must return either a string or an array of strings. Arrays of strings are treated as multiple lines of text.

Example code:

tooltips: {
    callbacks: {
      label: (tooltipItem, data) => {
        if (tooltipItem.index % 2)
          return ['Item 1', 'Item 2', 'Item 3'];
        else
          return 'Single line';
      }
    }
  }


问:
saving and loading blotter portfolio
I am using blotter to hold and do the accounting of some transactions, but I would need to save and load them on a daily basis.

I haven´t been able to save my transactions, I believe that that happens because they are in a different enviroment created by blotter (.blotter) - from what I´ve been able to pick up by googling my questions.

I have set up an example of a transaction:

```<code>require(quantstrat)
currency("USD")
stock(primary_id = "SB1", currency = "USD", multiplier=1120, tick_size = 0.01)
initPortf(name="testport", symbols="SB1", initDate = "2017-11-01")
initAcct(name="testacct", portfolio="testport", initDate = "2017-11-01", initEq = 100000)
ls_instruments()
addTxn(Portfolio="testport", Symbol="SB1", TxnDate="2017-11-22", TxnPrice=15.00, TxnQty = 2 , verbose=TRUE)
getPos(Portfolio="testport", Symbol="SB1", "2017-11-22", Columns=c("Pos.Qty"))
</code>```

Then I try to save it (which didn´t work) and was thinking about loading it like in the code below:

```<code>save("testport", file="C:/Users/augus/Dropbox/Trading/R/Trading/Dados/test.RData", envir=.blotter)
load(file="C:/Users/augus/Dropbox/Trading/R/Trading/Dados/test.RData", verbose=TRUE)
</code>```

I am pretty knew to R and stackoverflow, so please let me know if I am missing any information in my question, and thanks a lot for the help.

All the best,

Augusto

答:
The object you wanted was actually "portfolio.testport", not "testport" (this is designed this way in blotter).  You can check by looking at what is in the .blotter environment:

```<code>ls(.blotter)
#[1] "account.testacct"   "portfolio.testport"
</code>```

You could do this instead:

```<code>save("portfolio.testport", file="test.RData", envir=.blotter)
save("testport", file="C:/Users/augus/Dropbox/Trading/R/Trading/Dados/test.RData", envir=.blotter)
load(file="test.RData", verbose=TRUE)
</code>```

You may not want to store all of the stuff in this portfolio though, so it helps to understand what makes up the portfolio.

```<code>p <- getPortfolio("testport")
class(p)
#[1] "blotter_portfolio" "portfolio"
</code>```

It is basically a list, containing a summary (xts) and a symbols object (another list):

```<code>ls(p)
#[1] "summary" "symbols"
</code>```

The contents of the symbols list is:

```<code>ls(p$symbols)
#[1] "SB1"
</code>```

And each symbol object is also a list, containing 3 xts objects:

```<code>ls(p$symbols$SB1)
#[1] "posPL"     "posPL.USD" "txn"
</code>```

txn is one of the objects (an xts object itself):

```<code>head(p$symbols$SB1$txn)
# Txn.Qty Txn.Price Txn.Value Txn.Avg.Cost Pos.Qty Pos.Avg.Cost Gross.Txn.Realized.PL Txn.Fees Net.Txn.Realized.PL Con.Mult
# 2017-11-01       0         0         0            0       0            0                     0        0                   0        0
# 2017-11-22       2        15     33600           15       2           15                     0        0                   0     1120
</code>```

You may wish to save only sub parts of the above portfolio object.

Here is another approach you might find useful for saving:

```<code>p <- getPortfolio("testport")
saveRDS(p, "test2.rds")
p <- readRDS("test2.rds")
</code>```

Title: saving and loading blotter portfolio

Body:
I am using blotter to hold and do the accounting of some transactions, but I would need to save and load them on a daily basis.

I haven´t been able to save my transactions, I believe that that happens because they are in a different enviroment created by blotter (.blotter) - from what I´ve been able to pick up by googling my questions.

I have set up an example of a transaction:

require(quantstrat)
currency("USD")
stock(primary_id = "SB1", currency = "USD", multiplier=1120, tick_size = 0.01)
initPortf(name="testport", symbols="SB1", initDate = "2017-11-01")
initAcct(name="testacct", portfolio="testport", initDate = "2017-11-01", initEq = 100000)
ls_instruments()
addTxn(Portfolio="testport", Symbol="SB1", TxnDate="2017-11-22", TxnPrice=15.00, TxnQty = 2 , verbose=TRUE)
getPos(Portfolio="testport", Symbol="SB1", "2017-11-22", Columns=c("Pos.Qty"))

Then I try to save it (which didn´t work) and was thinking about loading it like in the code below:

save("testport", file="C:/Users/augus/Dropbox/Trading/R/Trading/Dados/test.RData", envir=.blotter)
load(file="C:/Users/augus/Dropbox/Trading/R/Trading/Dados/test.RData", verbose=TRUE)

I am pretty knew to R and stackoverflow, so please let me know if I am missing any information in my question, and thanks a lot for the help.

All the best,

Augusto

Body:
The object you wanted was actually "portfolio.testport", not "testport" (this is designed this way in blotter).  You can check by looking at what is in the .blotter environment:

ls(.blotter)
#[1] "account.testacct"   "portfolio.testport"

You could do this instead:

save("portfolio.testport", file="test.RData", envir=.blotter)
save("testport", file="C:/Users/augus/Dropbox/Trading/R/Trading/Dados/test.RData", envir=.blotter)
load(file="test.RData", verbose=TRUE)

You may not want to store all of the stuff in this portfolio though, so it helps to understand what makes up the portfolio.

p <- getPortfolio("testport")
class(p)
#[1] "blotter_portfolio" "portfolio"

It is basically a list, containing a summary (xts) and a symbols object (another list):

ls(p)
#[1] "summary" "symbols"

The contents of the symbols list is:

ls(p$symbols)
#[1] "SB1"

And each symbol object is also a list, containing 3 xts objects:

ls(p$symbols$SB1)
#[1] "posPL"     "posPL.USD" "txn"

txn is one of the objects (an xts object itself):

head(p$symbols$SB1$txn)
# Txn.Qty Txn.Price Txn.Value Txn.Avg.Cost Pos.Qty Pos.Avg.Cost Gross.Txn.Realized.PL Txn.Fees Net.Txn.Realized.PL Con.Mult
# 2017-11-01       0         0         0            0       0            0                     0        0                   0        0
# 2017-11-22       2        15     33600           15       2           15                     0        0                   0     1120

You may wish to save only sub parts of the above portfolio object.

Here is another approach you might find useful for saving:

p <- getPortfolio("testport")
saveRDS(p, "test2.rds")
p <- readRDS("test2.rds")


问:
Returns value of sequence to previous value
There is a sequence that is incremented for producing an ID  and passing it as a parameter to another stored procedure, something like this inside a procedure:

```<code> declare @ID int

 select @ID = next value for seq1

 execute proc_insert @ID = @ID,...
</code>```

The problem come up when execution of proc_insert fails, so we want that the value of sequence returns to previous value.

How can resolve this issue?

答:
your scenario is exactly not clear.
May be UDF which generate sequnce accordingly suit you.

If you are using Sequence then you can do like this.

suppose my sequence is define as,

```<code>CREATE SEQUENCE [dbo].[CountBy1]
 AS [bigint]
 START WITH 1
 INCREMENT BY 1
 MINVALUE -9223372036854775808
 MAXVALUE 9223372036854775807
 CACHE
GO
</code>```

Then your proc_insert should return output parameter indicating pass/fail,

declare @ID int
 select @ID= next value for seq1
 execute proc_insert @ID=@ID, @Outputparameter=@Outputparameter...
 --find here if proc_insert failed

```<code>if(@Outputparameter=0)-- 0 means failed
 begin
 declare @Sql varchar(2000)=
    'ALTER SEQUENCE dbo.CountBy1
    RESTART WITH '+@ID+''

    Exec(@Sql)
 end
</code>```

you should properly use Begin Trans and take help of Begin Try.

Also you should use sp_executesql

Body:
There is a sequence that is incremented for producing an ID  and passing it as a parameter to another stored procedure, something like this inside a procedure:

 declare @ID int

 select @ID = next value for seq1

 execute proc_insert @ID = @ID,...

The problem come up when execution of proc_insert fails, so we want that the value of sequence returns to previous value.

How can resolve this issue?

Body:
your scenario is exactly not clear.
May be UDF which generate sequnce accordingly suit you.

If you are using Sequence then you can do like this.

suppose my sequence is define as,

CREATE SEQUENCE [dbo].[CountBy1]
 AS [bigint]
 START WITH 1
 INCREMENT BY 1
 MINVALUE -9223372036854775808
 MAXVALUE 9223372036854775807
 CACHE
GO

Then your proc_insert should return output parameter indicating pass/fail,

declare @ID int
 select @ID= next value for seq1
 execute proc_insert @ID=@ID, @Outputparameter=@Outputparameter...
 --find here if proc_insert failed

if(@Outputparameter=0)-- 0 means failed
 begin
 declare @Sql varchar(2000)=
    'ALTER SEQUENCE dbo.CountBy1
    RESTART WITH '+@ID+''

    Exec(@Sql)
 end

you should properly use Begin Trans and take help of Begin Try.

Also you should use sp_executesql


问:
Change color of seaborn distribution line
I want to specify the color of a line of fit within the seaborn package for an array of x and y data. Instead all I can figure out is how to change the color and shading for the kernel density function. How can I change the color for a gaussian fit? I.e. the lines below should be red and blue. It would also be great to shade in the function like the "shade":True argument.

```<code>import seaborn as sns
sns.distplot(x,kde_kws={"shade":True}, kde=False, fit=stats.gamma, hist=None, color="red", label="label 1");
sns.distplot(y,kde_kws={"shade":True}, kde=False, fit=stats.gamma, hist=None, color="blue", label="label 2");
</code>```

答:
For changing the color of the fitted curve, you need to set fit_kws argument. But fit_kws does not support shading. You can still shade the area below the fitted curve by a few extra lines of code as shown below but that I think is an answer to another question that you have posted.

```<code>import numpy as np
import seaborn as sns
import scipy.stats as stats
import matplotlib.pyplot as plt

sns.set()
np.random.seed(0)
x = np.random.randn(100)
y = np.random.normal(loc=6.0, scale=1, size=(50,))

ax = sns.distplot(x, fit_kws={"color":"red"}, kde=False,
        fit=stats.gamma, hist=None, label="label 1");
ax = sns.distplot(y, fit_kws={"color":"blue"}, kde=False,
        fit=stats.gamma, hist=None, label="label 2");

plt.show(block=False)
</code>```

The result of the code is show below:

Body:
I want to specify the color of a line of fit within the seaborn package for an array of x and y data. Instead all I can figure out is how to change the color and shading for the kernel density function. How can I change the color for a gaussian fit? I.e. the lines below should be red and blue. It would also be great to shade in the function like the "shade":True argument.

import seaborn as sns
sns.distplot(x,kde_kws={"shade":True}, kde=False, fit=stats.gamma, hist=None, color="red", label="label 1");
sns.distplot(y,kde_kws={"shade":True}, kde=False, fit=stats.gamma, hist=None, color="blue", label="label 2");

Body:
For changing the color of the fitted curve, you need to set fit_kws argument. But fit_kws does not support shading. You can still shade the area below the fitted curve by a few extra lines of code as shown below but that I think is an answer to another question that you have posted.

import numpy as np
import seaborn as sns
import scipy.stats as stats
import matplotlib.pyplot as plt

sns.set()
np.random.seed(0)
x = np.random.randn(100)
y = np.random.normal(loc=6.0, scale=1, size=(50,))

ax = sns.distplot(x, fit_kws={"color":"red"}, kde=False,
        fit=stats.gamma, hist=None, label="label 1");
ax = sns.distplot(y, fit_kws={"color":"blue"}, kde=False,
        fit=stats.gamma, hist=None, label="label 2");

plt.show(block=False)

The result of the code is show below:


问:
Standardize the gridView pager template
I have a custom pager template on one gridview that the client now wants applied to several other gridviews within the same site.  It seems like extending the GridView object makes the most sense, but I'm not clear on how to create the pager template dynamically.

Any recommendations on how to accomplish this?

答:
I'm not sure why this article didn't turn up until now, but I found a nice tutorial on DotNetSlackers that got me going in the right direction.

http://dotnetslackers.com/articles/gridview/Custom-GridView-with-Paging-and-Filtering.aspx

Unfortunately, I did have to create the pager controls dynamically.  If anyone knows a better way, I'm still all ears as I would much rather write HTML as is done in the PagerTemplate.

Title: Standardize the gridView pager template


问:
Codeigniter loading model from different subfolder
I'm facing one weird problem with my Codeigniter project.

I have two model files in the following paths:

```<code>models/public/Dish_model.php
models/admin/Dish_model.php
</code>```

For front-end and back-end models respectively.

In the controller which is in the following path:

```<code>controllers/admin/Dish.php
</code>```

I'm trying to load the admin area model file using:

```<code>$this->load->model('admin/dish_model');
</code>```

But it is loading the public model file.

Even if I comment this line out the public model file still gets loaded.

This all happened suddenly it was working fine before and I haven't changed any of the mentioned files recently.

Any help?

答:
to call/load a model from its subdirectory or subfolder.

```<code>models/public/Dish_model.php
</code>```

let's say in Dish_model

```<code>class Dish_model extends CI_Model{
    public function __construct(){
       parent::__construct();
    }
    public function the_method(){
       return 'return value';
    }
}
</code>```

models it's a native ci model directory and public it's a subdirectory. so to load the Dish_model do this on controller

```<code>$this->load->model('public/Dish_model','DModel');
</code>```

the DModel it is like an alias.
so to call the model from the controller is

```<code>echo $this->DModel->the_method();
</code>```

and it will return return value
hope its help.

Body:
I'm facing one weird problem with my Codeigniter project.

I have two model files in the following paths:

models/public/Dish_model.php
models/admin/Dish_model.php

For front-end and back-end models respectively.

In the controller which is in the following path:

controllers/admin/Dish.php

I'm trying to load the admin area model file using:

$this->load->model('admin/dish_model');

But it is loading the public model file.

Even if I comment this line out the public model file still gets loaded.

This all happened suddenly it was working fine before and I haven't changed any of the mentioned files recently.

Any help?

Body:
to call/load a model from its subdirectory or subfolder.

models/public/Dish_model.php

let's say in Dish_model

class Dish_model extends CI_Model{
    public function __construct(){
       parent::__construct();
    }
    public function the_method(){
       return 'return value';
    }
}

models it's a native ci model directory and public it's a subdirectory. so to load the Dish_model do this on controller

$this->load->model('public/Dish_model','DModel');

the DModel it is like an alias.
so to call the model from the controller is

echo $this->DModel->the_method();

and it will return return value
hope its help.


问:
Why does my object serialized to camel case?
I have an asp.net core 2 app.  I am serving objects to mobile apps.  My object is coming back with a camel case instead of a pascal case.  I have found some documentation and blog posts about why this is happening in asp.net core v1.  Unfortunately, the v1 fix doesn't seem to be working for me in v2.  How do I get my object to come back in pascal case?

TIA

```<code>[Route("PicturesByPictureId")]
[HttpGet]
public dynamic PictureByPictureId([FromQuery] string Token, [FromQuery] Int64 PictureId)
{
    var da = new DataAccess();
    var pic = da.PictureInfo(PictureId);
    var myPic = new
    {
        PictureId = pic.PictureId,
        PicFileUrl = pic.PicFileUrl,
///////////////more code.
    };
    return myPic;
}
</code>```

答:
You need to add this to your startup.cs file  </p>

```<code>services.AddMvc()
                .AddJsonOptions(opt => {
                    opt.SerializerSettings.ContractResolver = new DefaultContractResolver();
                })
</code>```

Body:
I have an asp.net core 2 app.  I am serving objects to mobile apps.  My object is coming back with a camel case instead of a pascal case.  I have found some documentation and blog posts about why this is happening in asp.net core v1.  Unfortunately, the v1 fix doesn't seem to be working for me in v2.  How do I get my object to come back in pascal case?

TIA

[Route("PicturesByPictureId")]
[HttpGet]
public dynamic PictureByPictureId([FromQuery] string Token, [FromQuery] Int64 PictureId)
{
    var da = new DataAccess();
    var pic = da.PictureInfo(PictureId);
    var myPic = new
    {
        PictureId = pic.PictureId,
        PicFileUrl = pic.PicFileUrl,
///////////////more code.
    };
    return myPic;
}

Body:
You need to add this to your startup.cs file

services.AddMvc()
                .AddJsonOptions(opt => {
                    opt.SerializerSettings.ContractResolver = new DefaultContractResolver();
                })


问:
Unable to return value after implode
This is my array

```<code>Array
(
[0] => Array
    (
        [0] => SC1MTTCS6J1WK
    )

[1] => Array
    (
        [0] => SC1MTTCSHJ1WK
    )
)
</code>```

But when I try to implode them using

```<code>$in_text = implode(",", $myArray3);
</code>```

I can't get the value instead I got this:

```<code>Array,Array
</code>```

Please assist thank you.

答:
Here is the simple code, try this</p>

```<code>$in_text = implode(',',array_map('implode',$myArray3));
echo $in_text;
</code>```

Title: Unable to return value after implode

Body:
This is my array

Array
(
[0] => Array
    (
        [0] => SC1MTTCS6J1WK
    )

[1] => Array
    (
        [0] => SC1MTTCSHJ1WK
    )
)

But when I try to implode them using

$in_text = implode(",", $myArray3);

I can't get the value instead I got this:

Array,Array

Please assist thank you.

Body:
Here is the simple code, try this

$in_text = implode(',',array_map('implode',$myArray3));
echo $in_text;


问:
XML signature with using xmlsec1
I tried to use the following command to sign my testing xml with the P12 private key, and got the following errors:

```<code>xmlsec1 --sign --output tested.payload.xml --pkcs12 SenderCert/sender.p12 --pwd password tested.xml

Error: failed to find default node with name="Signature"
Error: failed to load template "tested.xml"
Error: failed to sign file "tested.xml"
</code>```

Any suggestion?

答:
I just met the same problem. I solve it by adding the <samlsig:Signature> label, which is standard SAML in the OASIS, then it will be okay.

But the problem is that I need to simplify the <samlp:AuthnRequest> to adjust the IDP which is not 100% same with the SAML standard. I do not know how to solve such situation. Is there anyone knowing it?

Title: XML signature with using xmlsec1

Body:
I tried to use the following command to sign my testing xml with the P12 private key, and got the following errors:

xmlsec1 --sign --output tested.payload.xml --pkcs12 SenderCert/sender.p12 --pwd password tested.xml

Error: failed to find default node with name="Signature"
Error: failed to load template "tested.xml"
Error: failed to sign file "tested.xml"

Any suggestion?


问:
How to access the camera - React Native
This should be included in the react-native APIs but I cannot seem to find any API included out of the box.

I want to open up the camera on the click of a button. I can see some APIs just for iOS but react-native should make things cross-platform.

Does anyone know how to access the camera (not the gallery) using react-native?

答:
In React Native you can access the camera by first installing it using NPM:
npm install react-native-camera --save
react-native link react-native-camera

Then use this in your Component:

```<code>takePicture() {
const options = {};
//options.location = ...
this.camera.capture({metadata: options})
  .then((data) => console.log(data))
  .catch(err => console.error(err));
}
</code>```

See this github repo for full example:
https://github.com/lwansbrough/react-native-camera

Title: How to access the camera - React Native

Body:
In React Native you can access the camera by first installing it using NPM:
npm install react-native-camera --save
react-native link react-native-camera

Then use this in your Component:

takePicture() {
const options = {};
//options.location = ...
this.camera.capture({metadata: options})
  .then((data) => console.log(data))
  .catch(err => console.error(err));
}

See this github repo for full example:
https://github.com/lwansbrough/react-native-camera


问:
browser = webdriver.Chrome() not working
I am getting started with Selenium for python and have this:

```<code>from selenium import webdriver
browser = webdriver.Chrome()
</code>```

However it gives this error:

```<code>Traceback (most recent call last):
File "C:\Users\Bradley Jo\AppData\Local\Programs\Python\Python36\lib\site-
packages\selenium\webdriver\common\service.py", line 74, in start
stdout=self.log_file, stderr=self.log_file)
 File "C:\Users\Bradley
Jo\AppData\Local\Programs\Python\Python36\lib\subprocess.py", line 709, in
__init__
restore_signals, start_new_session)
File "C:\Users\Bradley
Jo\AppData\Local\Programs\Python\Python36\lib\subprocess.py", line 997, in
_execute_child
startupinfo)
FileNotFoundError: [WinError 2] The system cannot find the file specified

During handling of the above exception, another exception occurred:

 Traceback (most recent call last):
  File "C:\Users\Bradley Jo\Desktop\Project\app.py", line 3, in
 <module>
 browser = webdriver.Chrome()
  File "C:\Users\Bradley Jo\AppData\Local\Programs\Python\Python36\lib\site-
  packages\selenium\webdriver\chrome\webdriver.py", line 68, in __init__
 self.service.start()
 File "C:\Users\Bradley Jo\AppData\Local\Programs\Python\Python36\lib\site-
 packages\selenium\webdriver\common\service.py", line 81, in start
 os.path.basename(self.path), self.start_error_message)
 selenium.common.exceptions.WebDriverException: Message: 'chromedriver'
 executable needs to be in PATH. Please see
 https://sites.google.com/a/chromium.org/chromedriver/home

[Finished in 1.0s]
</code>```

Anyone have any idea how to fix this? Thanks

答:
My guess is that the problem comes from your path that contains a space ("Bradley Jo"):

```<code>C:\Users\Bradley Jo\AppData\Local\Programs\Python\Python36\lib\site-packages\selenium\webdriver\common\service.py
</code>```

You may try to put your webdriver elsewhere.

Body:
I am getting started with Selenium for python and have this:

from selenium import webdriver
browser = webdriver.Chrome()

However it gives this error:

Traceback (most recent call last):
File "C:\Users\Bradley Jo\AppData\Local\Programs\Python\Python36\lib\site-
packages\selenium\webdriver\common\service.py", line 74, in start
stdout=self.log_file, stderr=self.log_file)
 File "C:\Users\Bradley
Jo\AppData\Local\Programs\Python\Python36\lib\subprocess.py", line 709, in
__init__
restore_signals, start_new_session)
File "C:\Users\Bradley
Jo\AppData\Local\Programs\Python\Python36\lib\subprocess.py", line 997, in
_execute_child
startupinfo)
FileNotFoundError: [WinError 2] The system cannot find the file specified

During handling of the above exception, another exception occurred:

 Traceback (most recent call last):
  File "C:\Users\Bradley Jo\Desktop\Project\app.py", line 3, in
 <module>
 browser = webdriver.Chrome()
  File "C:\Users\Bradley Jo\AppData\Local\Programs\Python\Python36\lib\site-
  packages\selenium\webdriver\chrome\webdriver.py", line 68, in __init__
 self.service.start()
 File "C:\Users\Bradley Jo\AppData\Local\Programs\Python\Python36\lib\site-
 packages\selenium\webdriver\common\service.py", line 81, in start
 os.path.basename(self.path), self.start_error_message)
 selenium.common.exceptions.WebDriverException: Message: 'chromedriver'
 executable needs to be in PATH. Please see
 https://sites.google.com/a/chromium.org/chromedriver/home

[Finished in 1.0s]

Anyone have any idea how to fix this? Thanks

Body:
My guess is that the problem comes from your path that contains a space ("Bradley Jo"):

C:\Users\Bradley Jo\AppData\Local\Programs\Python\Python36\lib\site-packages\selenium\webdriver\common\service.py

You may try to put your webdriver elsewhere.


问:
ggplot, facet, piechart: placing text in the middle of pie chart slices
I'm trying to produce a facetted pie-chart with ggplot and facing problems with placing text in the middle of each slice:

```<code>dat = read.table(text = "Channel Volume Cnt
                         AGENT   high   8344
                         AGENT medium   5448
                         AGENT    low  23823
                         KIOSK   high  19275
                         KIOSK medium  13554
                         KIOSK    low  38293", header=TRUE)

vis = ggplot(data=dat, aes(x=factor(1), y=Cnt, fill=Volume)) +
  geom_bar(stat="identity", position="fill") +
  coord_polar(theta="y") +
  facet_grid(Channel~.) +
  geom_text(aes(x=factor(1), y=Cnt, label=Cnt, ymax=Cnt),
            position=position_fill(width=1))
</code>```

The output:

What parameters of geom_text should be adjusted in order to place numerical labels in the middle of piechart slices?

Related question is Pie plot getting its text on top of each other but it doesn't handle case with facet.

UPDATE: following Paul Hiemstra advice and approach in the question above I changed code as follows:

```<code>---> pie_text = dat$Cnt/2 + c(0,cumsum(dat$Cnt)[-length(dat$Cnt)])

     vis = ggplot(data=dat, aes(x=factor(1), y=Cnt, fill=Volume)) +
     geom_bar(stat="identity", position="fill") +
     coord_polar(theta="y") +
     facet_grid(Channel~.) +
     geom_text(aes(x=factor(1),
--->               y=pie_text,
                   label=Cnt, ymax=Cnt), position=position_fill(width=1))
</code>```

As I expected tweaking text coordiantes is absolute but it needs be within facet data:

答:
I would like to speak out against the conventional way of making pies in ggplot2, which is to draw a stacked barplot in polar coordinates. While I appreciate the mathematical elegance of that approach, it does cause all sorts of headaches when the plot doesn't look quite the way it's supposed to. In particular, precisely adjusting the size of the pie can be difficult. (If you don't know what I mean, try to make a pie chart that extends all the way to the edge of the plot panel.)

I prefer drawing pies in a normal cartesian coordinate system, using geom_arc_bar() from ggforce. It requires a little bit of extra work on the front end, because we have to calculate angles ourselves, but that's easy and the level of control we get as a result is more than worth it.
I've used this approach in previous answers here and here.

The data (from the question):

```<code>dat = read.table(text = "Channel Volume Cnt
AGENT   high   8344
AGENT medium   5448
AGENT    low  23823
KIOSK   high  19275
KIOSK medium  13554
KIOSK    low  38293", header=TRUE)
</code>```

The pie-drawing code:

```<code>library(ggplot2)
library(ggforce)
library(dplyr)

# calculate the start and end angles for each pie
dat_pies <- left_join(dat,
                      dat %>%
                        group_by(Channel) %>%
                        summarize(Cnt_total = sum(Cnt))) %>%
  group_by(Channel) %>%
  mutate(end_angle = 2*pi*cumsum(Cnt)/Cnt_total,      # ending angle for each pie slice
         start_angle = lag(end_angle, default = 0),   # starting angle for each pie slice
         mid_angle = 0.5*(start_angle + end_angle))   # middle of each pie slice, for the text label

rpie = 1 # pie radius
rlabel = 0.6 * rpie # radius of the labels; a number slightly larger than 0.5 seems to work better,
                    # but 0.5 would place it exactly in the middle as the question asks for.

# draw the pies
ggplot(dat_pies) +
  geom_arc_bar(aes(x0 = 0, y0 = 0, r0 = 0, r = rpie,
                   start = start_angle, end = end_angle, fill = Volume)) +
  geom_text(aes(x = rlabel*sin(mid_angle), y = rlabel*cos(mid_angle), label = Cnt),
            hjust = 0.5, vjust = 0.5) +
  coord_fixed() +
  scale_x_continuous(limits = c(-1, 1), name = "", breaks = NULL, labels = NULL) +
  scale_y_continuous(limits = c(-1, 1), name = "", breaks = NULL, labels = NULL) +
  facet_grid(Channel~.)
</code>```

To show why I think this this approach is so much more powerful than the conventional (coord_polar()) approach, let's say we want the labels on the outside of the pie rather than inside. This creates a couple of problems, such as we will have to adjust hjust and vjust depending on the side of the pie a label falls, and also we will have to make the
plot panel wider than high to make space for the labels on the side without generating excessive space above and below. Solving these problems in the polar coordinate approach is not fun, but it's trivial in the cartesian coordinates:

```<code># generate hjust and vjust settings depending on the quadrant into which each
# label falls
dat_pies <- mutate(dat_pies,
                   hjust = ifelse(mid_angle>pi, 1, 0),
                   vjust = ifelse(mid_angle<pi/2 | mid_angle>3*pi/2, 0, 1))

rlabel = 1.05 * rpie # now we place labels outside of the pies

ggplot(dat_pies) +
  geom_arc_bar(aes(x0 = 0, y0 = 0, r0 = 0, r = rpie,
                   start = start_angle, end = end_angle, fill = Volume)) +
  geom_text(aes(x = rlabel*sin(mid_angle), y = rlabel*cos(mid_angle), label = Cnt,
                hjust = hjust, vjust = vjust)) +
  coord_fixed() +
  scale_x_continuous(limits = c(-1.5, 1.4), name = "", breaks = NULL, labels = NULL) +
  scale_y_continuous(limits = c(-1, 1), name = "", breaks = NULL, labels = NULL) +
  facet_grid(Channel~.)
</code>```

Body:
I'm trying to produce a facetted pie-chart with ggplot and facing problems with placing text in the middle of each slice:

dat = read.table(text = "Channel Volume Cnt
                         AGENT   high   8344
                         AGENT medium   5448
                         AGENT    low  23823
                         KIOSK   high  19275
                         KIOSK medium  13554
                         KIOSK    low  38293", header=TRUE)

vis = ggplot(data=dat, aes(x=factor(1), y=Cnt, fill=Volume)) +
  geom_bar(stat="identity", position="fill") +
  coord_polar(theta="y") +
  facet_grid(Channel~.) +
  geom_text(aes(x=factor(1), y=Cnt, label=Cnt, ymax=Cnt),
            position=position_fill(width=1))

The output:

What parameters of geom_text should be adjusted in order to place numerical labels in the middle of piechart slices?

Related question is Pie plot getting its text on top of each other but it doesn't handle case with facet.

UPDATE: following Paul Hiemstra advice and approach in the question above I changed code as follows:

---> pie_text = dat$Cnt/2 + c(0,cumsum(dat$Cnt)[-length(dat$Cnt)])

     vis = ggplot(data=dat, aes(x=factor(1), y=Cnt, fill=Volume)) +
     geom_bar(stat="identity", position="fill") +
     coord_polar(theta="y") +
     facet_grid(Channel~.) +
     geom_text(aes(x=factor(1),
--->               y=pie_text,
                   label=Cnt, ymax=Cnt), position=position_fill(width=1))

As I expected tweaking text coordiantes is absolute but it needs be within facet data:

Body:
I would like to speak out against the conventional way of making pies in ggplot2, which is to draw a stacked barplot in polar coordinates. While I appreciate the mathematical elegance of that approach, it does cause all sorts of headaches when the plot doesn't look quite the way it's supposed to. In particular, precisely adjusting the size of the pie can be difficult. (If you don't know what I mean, try to make a pie chart that extends all the way to the edge of the plot panel.)

I prefer drawing pies in a normal cartesian coordinate system, using geom_arc_bar() from ggforce. It requires a little bit of extra work on the front end, because we have to calculate angles ourselves, but that's easy and the level of control we get as a result is more than worth it.
I've used this approach in previous answers here and here.

The data (from the question):

dat = read.table(text = "Channel Volume Cnt
AGENT   high   8344
AGENT medium   5448
AGENT    low  23823
KIOSK   high  19275
KIOSK medium  13554
KIOSK    low  38293", header=TRUE)

The pie-drawing code:

library(ggplot2)
library(ggforce)
library(dplyr)

# calculate the start and end angles for each pie
dat_pies <- left_join(dat,
                      dat %>%
                        group_by(Channel) %>%
                        summarize(Cnt_total = sum(Cnt))) %>%
  group_by(Channel) %>%
  mutate(end_angle = 2*pi*cumsum(Cnt)/Cnt_total,      # ending angle for each pie slice
         start_angle = lag(end_angle, default = 0),   # starting angle for each pie slice
         mid_angle = 0.5*(start_angle + end_angle))   # middle of each pie slice, for the text label

rpie = 1 # pie radius
rlabel = 0.6 * rpie # radius of the labels; a number slightly larger than 0.5 seems to work better,
                    # but 0.5 would place it exactly in the middle as the question asks for.

# draw the pies
ggplot(dat_pies) +
  geom_arc_bar(aes(x0 = 0, y0 = 0, r0 = 0, r = rpie,
                   start = start_angle, end = end_angle, fill = Volume)) +
  geom_text(aes(x = rlabel*sin(mid_angle), y = rlabel*cos(mid_angle), label = Cnt),
            hjust = 0.5, vjust = 0.5) +
  coord_fixed() +
  scale_x_continuous(limits = c(-1, 1), name = "", breaks = NULL, labels = NULL) +
  scale_y_continuous(limits = c(-1, 1), name = "", breaks = NULL, labels = NULL) +
  facet_grid(Channel~.)

To show why I think this this approach is so much more powerful than the conventional (coord_polar()) approach, let's say we want the labels on the outside of the pie rather than inside. This creates a couple of problems, such as we will have to adjust hjust and vjust depending on the side of the pie a label falls, and also we will have to make the
plot panel wider than high to make space for the labels on the side without generating excessive space above and below. Solving these problems in the polar coordinate approach is not fun, but it's trivial in the cartesian coordinates:

# generate hjust and vjust settings depending on the quadrant into which each
# label falls
dat_pies <- mutate(dat_pies,
                   hjust = ifelse(mid_angle>pi, 1, 0),
                   vjust = ifelse(mid_angle<pi/2 | mid_angle>3*pi/2, 0, 1))

rlabel = 1.05 * rpie # now we place labels outside of the pies

ggplot(dat_pies) +
  geom_arc_bar(aes(x0 = 0, y0 = 0, r0 = 0, r = rpie,
                   start = start_angle, end = end_angle, fill = Volume)) +
  geom_text(aes(x = rlabel*sin(mid_angle), y = rlabel*cos(mid_angle), label = Cnt,
                hjust = hjust, vjust = vjust)) +
  coord_fixed() +
  scale_x_continuous(limits = c(-1.5, 1.4), name = "", breaks = NULL, labels = NULL) +
  scale_y_continuous(limits = c(-1, 1), name = "", breaks = NULL, labels = NULL) +
  facet_grid(Channel~.)


问:
Preview Sync and Sync From Repository options not available on fresh install
I have set up a fresh Crafter CMS 3.0.2 installation following the instructions here. When I login as admin user I don't get Preview Sync and Sync From Repository options in the Site Config section as show in the page here. How can I add those options for the admin user? I could not find the instructions for the same in the documentation

答:
Sync'ing is now automatic starting version 3.0.2, see the release notes: http://docs.craftercms.org/en/3.0/release-notes/index.html

You can make updates to the underlying git repo, and the system will automatically pick those up.


问:
Convert LocalDateTime to human readable format in JQuery
This might be something very trivial but I am unable to figure it out.I need to convert date coming in 2016-10-07T04:30 format to more readable form like "7th Oct,16 4:30". Is there a plugin to do this or any JQuery function.

Any help ?

答:
for changing the date format to human readable date string javascript doc provide a function called to toDateString();</p>

```<code>$(document).ready(function(){
   var date = new Date.toDateString();
   console.log(date);
});
</code>```

Body:
for changing the date format to human readable date string javascript doc provide a function called to toDateString();

$(document).ready(function(){
   var date = new Date.toDateString();
   console.log(date);
});


问:
Render template relation ManyToMany Symfony Doctrine
Please help with this, I am having this problem when I render the template twig in the controller, having problems with relations ManyToMany

Neither the property "nombre" nor one of the methods "nombre()", "getnombre()"/"isnombre()" or "__call()" exist and have public access in class "Doctrine\ORM\PersistentCollection"....I will put my entities and controller, please help me with this:

```<code><?php

namespace AdminBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Doctrine\Common\Collections\ArrayCollection;

/**
 * Menu
 *
 * @ORM\Table(name="menu")
 * @ORM\Entity(repositoryClass="AdminBundle\Repository\MenuRepository")
 */
class Menu
{
    /**
     * @var int
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var float
     * @Assert\NotBlank()
     * @Assert\Type(type="float")
     * @ORM\Column(name="precio", type="float")
     */
    private $precio;

    /**
     * @var \DateTime
     * @Assert\Date()
     * @Assert\NotBlank()
     * @ORM\Column(name="fecha", type="date")
     */
    private $fecha;

    /**
     * @var \DateTime
     * @Assert\DateTime()
     * @Assert\NotBlank()
     * @ORM\Column(name="fechacomprar", type="datetime")
     */
    private $fechacomprar;

    /**
     * @var \DateTime
     * @Assert\DateTime()
     * @Assert\NotBlank()
     * @ORM\Column(name="fechavence", type="datetime")
     */
    private $fechavence;

    /**
     * @var \Doctrine\Common\Collections\Collection
     *
     * @ORM\ManyToMany(targetEntity="Alimento", inversedBy="menu")
     * @ORM\JoinTable(name="alimento_menu",
     *   joinColumns={
     *     @ORM\JoinColumn(name="menu_id", referencedColumnName="id")
     *   },
     *   inverseJoinColumns={
     *     @ORM\JoinColumn(name="alimento_id", referencedColumnName="id")
     *   }
     * )
     */
    private $alimento;

    /**
     * Constructor
     */
    public function __construct()
    {
        $this->alimento = new ArrayCollection();
    }

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set precio
     *
     * @param float $precio
     *
     * @return Menu
     */
    public function setPrecio($precio)
    {
        $this->precio = $precio;

        return $this;
    }

    /**
     * Get precio
     *
     * @return float
     */
    public function getPrecio()
    {
        return $this->precio;
    }

    /**
     * Set fecha
     *
     * @param \DateTime $fecha
     *
     * @return Menu
     */
    public function setFecha($fecha)
    {
        $this->fecha = $fecha;

        return $this;
    }

    /**
     * Get fecha
     *
     * @return \DateTime
     */
    public function getFecha()
    {
        return $this->fecha;
    }

    /**
     * Set fechacomprar
     *
     * @param \DateTime $fechacomprar
     *
     * @return Menu
     */
    public function setFechacomprar($fechacomprar)
    {
        $this->fechacomprar = $fechacomprar;

        return $this;
    }

    /**
     * Get fechacomprar
     *
     * @return \DateTime
     */
    public function getFechacomprar()
    {
        return $this->fechacomprar;
    }

    /**
     * Set fechavence
     *
     * @param \DateTime $fechavence
     *
     * @return Menu
     */
    public function setFechavence($fechavence)
    {
        $this->fechavence = $fechavence;

        return $this;
    }

    /**
     * Get fechavence
     *
     * @return \DateTime
     */
    public function getFechavence()
    {
        return $this->fechavence;
    }

    /**
     * Add alimento
     *
     * @param \AdminBundle\Entity\Alimento $alimento
     *
     * @return Menu
     */
    public function addAlimento(Alimento $alimento)
    {
        $this->alimento[] = $alimento;

        return $this;
    }

    /**
     * Remove alimento
     *
     * @param \AdminBundle\Entity\Alimento $alimento
     */
    public function removeAlimento(Alimento $alimento)
    {
        $this->alimento->removeElement($alimento);
    }

    /**
     * Get alimento
     *
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getAlimento()
    {
        return $this->alimento;
    }
}

<?php

namespace AdminBundle\Entity;

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Bridge\Doctrine\Validator\Constraints as DoctrineAssert;

/**
 * Alimento
 *
 * @ORM\Table(name="alimento")
 * @ORM\Entity(repositoryClass="AdminBundle\Repository\AlimentoRepository")
 * @DoctrineAssert\UniqueEntity("nombre")
 */
class Alimento
{
    /**
     * @var int
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var string
     * @Assert\NotBlank(message="Debe escribir un alimento")
     * @Assert\Type(type="string")
     * @Assert\Regex(pattern="/\d/", match=false, message="Debe escribir un nombre válido")
     * @ORM\Column(name="nombre", type="string", length=255, unique=true)
     */
    private $nombre;

    /**
     * @var float
     * @Assert\NotBlank(message="Debe especificar un precio")
     * @Assert\Type(type="float", message="Debe escribir un precio válido")
     * @ORM\Column(name="precio", type="float")
     */
    private $precio;

    /**
     * @ORM\ManyToOne(targetEntity="TipoAlimento")
     * @Assert\NotBlank()
     */
    private $tipo;

    /**
     * @var \Doctrine\Common\Collections\Collection
     *
     * @ORM\ManyToMany(targetEntity="Menu", mappedBy="alimento")
     */
    private $menu;

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set nombre
     *
     * @param string $nombre
     *
     * @return Alimento
     */
    public function setNombre($nombre)
    {
        $this->nombre = $nombre;

        return $this;
    }

    /**
     * Get nombre
     *
     * @return string
     */
    public function getNombre()
    {
        return $this->nombre;
    }

    /**
     * Set precio
     *
     * @param float $precio
     *
     * @return Alimento
     */
    public function setPrecio($precio)
    {
        $this->precio = $precio;

        return $this;
    }

    /**
     * Get precio
     *
     * @return float
     */
    public function getPrecio()
    {
        return $this->precio;
    }

    /**
     * Set tipo
     *
     * @param \AdminBundle\Entity\TipoAlimento $tipo
     *
     * @return Alimento
     */
    public function setTipo(TipoAlimento $tipo)
    {
        $this->tipo = $tipo;

        return $this;
    }

    /**
     * Get tipo
     *
     * @return \AdminBundle\Entity\TipoAlimento
     */
    public function getTipo()
    {
        return $this->tipo;
    }

    /**
     * @return string
     */
    function __toString()
    {
        return $this->getNombre();
    }

    /**
     * Constructor
     */
    public function __construct()
    {
        $this->menu = new ArrayCollection();
    }

    /**
     * Add menu
     *
     * @param \AdminBundle\Entity\Menu $menu
     *
     * @return Alimento
     */
    public function addMenu(Menu $menu)
    {
        $this->menu[] = $menu;

        return $this;
    }

    /**
     * Remove menu
     *
     * @param \AdminBundle\Entity\Menu $menu
     */
    public function removeMenu(Menu $menu)
    {
        $this->menu->removeElement($menu);
    }

    /**
     * Get menu
     *
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getMenu()
    {
        return $this->menu;
    }
}
</code>```

The controller:

```<code>    public function indexAction()
    {
        $em = $this->getDoctrine()->getManager();
        $menu = $em->getRepository('AdminBundle:Menu')->findAll();
        return $this->render('AdminBundle:menu:index.html.twig', array(
            'menu' => $menu,
        ));`enter code here`
    }
</code>```

And in the template I am doing the things like this:

```<code> {% for m in menu %}
                    <tr>
                        <td>{{ m.id }}</td>
                        <td>{{ m.fecha | date('d/m/y') }}</td>
                        <td>{{ m.alimento.nombre }}</td>
                        <td>{{ m.fechacomprar | date('d/m/y') }}</td>
                        <td>{{ m.fechavence | date('d/m/y') }}</td>
                        <td>{{ m.precio }}</td>
                    </tr>
                {% endfor %}
</code>```

Problem here is m.alimento.nombre is wrong!

答:
Simply you can try this, in this case, m.alimento will return Alimento's  __toString</p>

```<code>{{  m.alimento|join(',') }}
</code>```

Body:
Please help with this, I am having this problem when I render the template twig in the controller, having problems with relations ManyToMany

Neither the property "nombre" nor one of the methods "nombre()", "getnombre()"/"isnombre()" or "__call()" exist and have public access in class "Doctrine\ORM\PersistentCollection"....I will put my entities and controller, please help me with this:

<?php

namespace AdminBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Doctrine\Common\Collections\ArrayCollection;

/**
 * Menu
 *
 * @ORM\Table(name="menu")
 * @ORM\Entity(repositoryClass="AdminBundle\Repository\MenuRepository")
 */
class Menu
{
    /**
     * @var int
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var float
     * @Assert\NotBlank()
     * @Assert\Type(type="float")
     * @ORM\Column(name="precio", type="float")
     */
    private $precio;

    /**
     * @var \DateTime
     * @Assert\Date()
     * @Assert\NotBlank()
     * @ORM\Column(name="fecha", type="date")
     */
    private $fecha;

    /**
     * @var \DateTime
     * @Assert\DateTime()
     * @Assert\NotBlank()
     * @ORM\Column(name="fechacomprar", type="datetime")
     */
    private $fechacomprar;

    /**
     * @var \DateTime
     * @Assert\DateTime()
     * @Assert\NotBlank()
     * @ORM\Column(name="fechavence", type="datetime")
     */
    private $fechavence;

    /**
     * @var \Doctrine\Common\Collections\Collection
     *
     * @ORM\ManyToMany(targetEntity="Alimento", inversedBy="menu")
     * @ORM\JoinTable(name="alimento_menu",
     *   joinColumns={
     *     @ORM\JoinColumn(name="menu_id", referencedColumnName="id")
     *   },
     *   inverseJoinColumns={
     *     @ORM\JoinColumn(name="alimento_id", referencedColumnName="id")
     *   }
     * )
     */
    private $alimento;

    /**
     * Constructor
     */
    public function __construct()
    {
        $this->alimento = new ArrayCollection();
    }

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set precio
     *
     * @param float $precio
     *
     * @return Menu
     */
    public function setPrecio($precio)
    {
        $this->precio = $precio;

        return $this;
    }

    /**
     * Get precio
     *
     * @return float
     */
    public function getPrecio()
    {
        return $this->precio;
    }

    /**
     * Set fecha
     *
     * @param \DateTime $fecha
     *
     * @return Menu
     */
    public function setFecha($fecha)
    {
        $this->fecha = $fecha;

        return $this;
    }

    /**
     * Get fecha
     *
     * @return \DateTime
     */
    public function getFecha()
    {
        return $this->fecha;
    }

    /**
     * Set fechacomprar
     *
     * @param \DateTime $fechacomprar
     *
     * @return Menu
     */
    public function setFechacomprar($fechacomprar)
    {
        $this->fechacomprar = $fechacomprar;

        return $this;
    }

    /**
     * Get fechacomprar
     *
     * @return \DateTime
     */
    public function getFechacomprar()
    {
        return $this->fechacomprar;
    }

    /**
     * Set fechavence
     *
     * @param \DateTime $fechavence
     *
     * @return Menu
     */
    public function setFechavence($fechavence)
    {
        $this->fechavence = $fechavence;

        return $this;
    }

    /**
     * Get fechavence
     *
     * @return \DateTime
     */
    public function getFechavence()
    {
        return $this->fechavence;
    }

    /**
     * Add alimento
     *
     * @param \AdminBundle\Entity\Alimento $alimento
     *
     * @return Menu
     */
    public function addAlimento(Alimento $alimento)
    {
        $this->alimento[] = $alimento;

        return $this;
    }

    /**
     * Remove alimento
     *
     * @param \AdminBundle\Entity\Alimento $alimento
     */
    public function removeAlimento(Alimento $alimento)
    {
        $this->alimento->removeElement($alimento);
    }

    /**
     * Get alimento
     *
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getAlimento()
    {
        return $this->alimento;
    }
}

<?php

namespace AdminBundle\Entity;

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Bridge\Doctrine\Validator\Constraints as DoctrineAssert;

/**
 * Alimento
 *
 * @ORM\Table(name="alimento")
 * @ORM\Entity(repositoryClass="AdminBundle\Repository\AlimentoRepository")
 * @DoctrineAssert\UniqueEntity("nombre")
 */
class Alimento
{
    /**
     * @var int
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var string
     * @Assert\NotBlank(message="Debe escribir un alimento")
     * @Assert\Type(type="string")
     * @Assert\Regex(pattern="/\d/", match=false, message="Debe escribir un nombre válido")
     * @ORM\Column(name="nombre", type="string", length=255, unique=true)
     */
    private $nombre;

    /**
     * @var float
     * @Assert\NotBlank(message="Debe especificar un precio")
     * @Assert\Type(type="float", message="Debe escribir un precio válido")
     * @ORM\Column(name="precio", type="float")
     */
    private $precio;

    /**
     * @ORM\ManyToOne(targetEntity="TipoAlimento")
     * @Assert\NotBlank()
     */
    private $tipo;

    /**
     * @var \Doctrine\Common\Collections\Collection
     *
     * @ORM\ManyToMany(targetEntity="Menu", mappedBy="alimento")
     */
    private $menu;

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set nombre
     *
     * @param string $nombre
     *
     * @return Alimento
     */
    public function setNombre($nombre)
    {
        $this->nombre = $nombre;

        return $this;
    }

    /**
     * Get nombre
     *
     * @return string
     */
    public function getNombre()
    {
        return $this->nombre;
    }

    /**
     * Set precio
     *
     * @param float $precio
     *
     * @return Alimento
     */
    public function setPrecio($precio)
    {
        $this->precio = $precio;

        return $this;
    }

    /**
     * Get precio
     *
     * @return float
     */
    public function getPrecio()
    {
        return $this->precio;
    }

    /**
     * Set tipo
     *
     * @param \AdminBundle\Entity\TipoAlimento $tipo
     *
     * @return Alimento
     */
    public function setTipo(TipoAlimento $tipo)
    {
        $this->tipo = $tipo;

        return $this;
    }

    /**
     * Get tipo
     *
     * @return \AdminBundle\Entity\TipoAlimento
     */
    public function getTipo()
    {
        return $this->tipo;
    }

    /**
     * @return string
     */
    function __toString()
    {
        return $this->getNombre();
    }

    /**
     * Constructor
     */
    public function __construct()
    {
        $this->menu = new ArrayCollection();
    }

    /**
     * Add menu
     *
     * @param \AdminBundle\Entity\Menu $menu
     *
     * @return Alimento
     */
    public function addMenu(Menu $menu)
    {
        $this->menu[] = $menu;

        return $this;
    }

    /**
     * Remove menu
     *
     * @param \AdminBundle\Entity\Menu $menu
     */
    public function removeMenu(Menu $menu)
    {
        $this->menu->removeElement($menu);
    }

    /**
     * Get menu
     *
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getMenu()
    {
        return $this->menu;
    }
}

The controller:

    public function indexAction()
    {
        $em = $this->getDoctrine()->getManager();
        $menu = $em->getRepository('AdminBundle:Menu')->findAll();
        return $this->render('AdminBundle:menu:index.html.twig', array(
            'menu' => $menu,
        ));`enter code here`
    }

And in the template I am doing the things like this:

 {% for m in menu %}

                        {{ m.id }}
                        {{ m.fecha | date('d/m/y') }}
                        {{ m.alimento.nombre }}
                        {{ m.fechacomprar | date('d/m/y') }}
                        {{ m.fechavence | date('d/m/y') }}
                        {{ m.precio }}

                {% endfor %}

Problem here is m.alimento.nombre is wrong!

Body:
Simply you can try this, in this case, m.alimento will return Alimento's  __toString

{{  m.alimento|join(',') }}


问:
Can I safely substitute a readonly property for a readonly public field?
My team follows the general .NET convention that you should expose public properties on your types rather than exposing fields. However, I've come across a class which mostly exposes fields... but then contains this for its two 'identifying' pieces of data:

public readonly int WidgetId;
public readonly string WidgetName;
```

<p>I am really heavily tempted to refactor these into properties, i.e.</p>

<pre class="lang-cs prettyprint-override"><code>public int WidgetId { get; }
public string WidgetName { get; }
</code>```

So they match the conventions of the rest of the class. I'm aware of the arguments for and against public fields versus properties. But, given that readonly-auto-properties in particular are a relatively new C# feature, I want to know:

What are the semantic differences between public readonly int Foo and public int Foo { get; }, if any? Are they meaningfully different to the compiler?

答:
Your new property is equal to:

```<code>private readonly string _widgetName = GetWidgetName();
public string `
{
    get { return _widgetName; }
}
</code>```

So, the value is stored in _widgetName and it's safe because it's readonly, and you can't change it's value as before.

With property WidgetName you can only change access to field _widgetName, not the value. For example:

```<code>private readonly string _widgetName = GetWidgetName();
public string `
{
    get
    {
        if (_widgetName == null) throw new Exception("Value is not set");
        return _widgetName;
    }
}
</code>```

You get more control to your data, but in common case - there is no difference, if you just replcae readonly field to readonly propery.

Some information about properties is here.

Body:
My team follows the general .NET convention that you should expose public properties on your types rather than exposing fields. However, I've come across a class which mostly exposes fields... but then contains this for its two 'identifying' pieces of data:

public readonly int WidgetId;
public readonly string WidgetName;

I am really heavily tempted to refactor these into properties, i.e.

public int WidgetId { get; }
public string WidgetName { get; }

So they match the conventions of the rest of the class. I'm aware of the arguments for and against public fields versus properties. But, given that readonly-auto-properties in particular are a relatively new C# feature, I want to know:

What are the semantic differences between public readonly int Foo and public int Foo { get; }, if any? Are they meaningfully different to the compiler?

Body:
Your new property is equal to:

private readonly string _widgetName = GetWidgetName();
public string `
{
    get { return _widgetName; }
}

So, the value is stored in _widgetName and it's safe because it's readonly, and you can't change it's value as before.

With property WidgetName you can only change access to field _widgetName, not the value. For example:

private readonly string _widgetName = GetWidgetName();
public string `
{
    get
    {
        if (_widgetName == null) throw new Exception("Value is not set");
        return _widgetName;
    }
}

You get more control to your data, but in common case - there is no difference, if you just replcae readonly field to readonly propery.

Some information about properties is here.