问:
Laravel Route issues with Route order in web.php
I have problem with routes in Laravel, I'm following one tutorial and we have this routes listed in web.php file

```<code>Route::get('/home', 'HomeController@index')->name('home');
Route::get('/blog', 'BlogController@index')->name('blog');
Route::get('/blog/create', 'BlogController@create');
Route::post('/blog/store', 'BlogController@store');
Route::get('/blog/{id}', 'BlogController@show');
Route::get('/blog/{id}/edit', 'BlogController@edit');
Route::patch('/blog/{id}', 'BlogController@update');
Route::delete('/blog/{id}', 'BlogController@destroy');
Route::get('/blog/bin', 'BlogController@bin');
</code>```

Problem is in the last route to blog/bin, it is not working if I keep it down below however in tutorial we have moved it to top of other routes and then it's working fine, instructor said that there is some conflict in routes and that that last route need to be at top in order to work but didn't explain at all why ? Can anybody explain in little more details, as I'm really just started with Laravel...

答:
When accessing a route, Laravel goes through your list of routes top to bottom, until it finds one that 'matches' at which point this route is immediately selected.

In your example, when trying to access /blog/bin using GET, it has two potential matches:

```<code>Route::get('/blog/{id}', 'BlogController@show');
</code>```

and

```<code>Route::get('/blog/bin', 'BlogController@bin');
</code>```

In this case, Route::get('/blog/{id}', 'BlogController@show'); comes first so it would be selected.

As the previous answers correctly state, placing the /blog/bin route above the /blog/{id} route would solve the problem. However, this 'solution' leaves you open to a similar mistake in the future (when, for example, defining a /blog/example route and accidentally placing it under /blog/{id}). In addition, I personally think it is not very elegant to have the functioning of your routes depend on the order to place them in.

In my opinion, when possible, a more robust solution is to restrict the possible values that are accepted by /blog/{id} with a regex constraint.

For example, if you are using a numeric ID for your blogposts, you know that you only want to use route /blog/{id} if id is a number. Thus, you would define your route as follows:

```<code>Route::get('/blog/{id}', 'BlogController@show')->where('id', '[0-9]+');
</code>```

Of course this is often not a possibility, for example if you use the post title as an id, but if there is some way to differentiate a post id from any other /blog/foo route, then this would be a possibility.

Body:
I have problem with routes in Laravel, I'm following one tutorial and we have this routes listed in web.php file

Route::get('/home', 'HomeController@index')->name('home');
Route::get('/blog', 'BlogController@index')->name('blog');
Route::get('/blog/create', 'BlogController@create');
Route::post('/blog/store', 'BlogController@store');
Route::get('/blog/{id}', 'BlogController@show');
Route::get('/blog/{id}/edit', 'BlogController@edit');
Route::patch('/blog/{id}', 'BlogController@update');
Route::delete('/blog/{id}', 'BlogController@destroy');
Route::get('/blog/bin', 'BlogController@bin');

Problem is in the last route to blog/bin, it is not working if I keep it down below however in tutorial we have moved it to top of other routes and then it's working fine, instructor said that there is some conflict in routes and that that last route need to be at top in order to work but didn't explain at all why ? Can anybody explain in little more details, as I'm really just started with Laravel...

Body:
When accessing a route, Laravel goes through your list of routes top to bottom, until it finds one that 'matches' at which point this route is immediately selected.

In your example, when trying to access /blog/bin using GET, it has two potential matches:

Route::get('/blog/{id}', 'BlogController@show');

and

Route::get('/blog/bin', 'BlogController@bin');

In this case, Route::get('/blog/{id}', 'BlogController@show'); comes first so it would be selected.

As the previous answers correctly state, placing the /blog/bin route above the /blog/{id} route would solve the problem. However, this 'solution' leaves you open to a similar mistake in the future (when, for example, defining a /blog/example route and accidentally placing it under /blog/{id}). In addition, I personally think it is not very elegant to have the functioning of your routes depend on the order to place them in.

In my opinion, when possible, a more robust solution is to restrict the possible values that are accepted by /blog/{id} with a regex constraint.

For example, if you are using a numeric ID for your blogposts, you know that you only want to use route /blog/{id} if id is a number. Thus, you would define your route as follows:

Route::get('/blog/{id}', 'BlogController@show')->where('id', '[0-9]+');

Of course this is often not a possibility, for example if you use the post title as an id, but if there is some way to differentiate a post id from any other /blog/foo route, then this would be a possibility.


来源: stackexchange

问:
Error using 'selu' activation function with Keras
I'm using Keras with Tensorflow backend. When I'm trying to use the 'selu' activation function using:

```<code>model.add(Dense(32, input_shape=(input_length - 1,)))
model.add(Activation('selu'))
</code>```

The error I get is:

```<code>ValueError: Unknown activation function:selu
</code>```

Is there any solution to this?

答:
Selu is not in your activations.py of keras (most likely because it was added Jun 14, 2017, only 22 days ago). You can just add the missing code in the activations.py file or create your own selu activation in the script.

Example code

```<code>from keras.activations import elu

def selu(x):
    """Scaled Exponential Linear Unit. (Klambauer et al., 2017)
    # Arguments
        x: A tensor or variable to compute the activation function for.
    # References
        - [Self-Normalizing Neural Networks](https://arxiv.org/abs/1706.02515)
    """
    alpha = 1.6732632423543772848170429916717
    scale = 1.0507009873554804934193349852946
    return scale * elu(x, alpha)

model.add(Dense(32, input_shape=(input_length - 1,)), activation=selu)
</code>```

NOTE:

With tensorflow 2.0 keras is included. You can get the selu activation with:

```<code>from tensorflow.keras.activations import selu
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm using Keras with Tensorflow backend. When I'm trying to use the 'selu' activation function using:

model.add(Dense(32, input_shape=(input_length - 1,)))
model.add(Activation('selu'))

The error I get is:

ValueError: Unknown activation function:selu

Is there any solution to this?

Body:
Selu is not in your activations.py of keras (most likely because it was added Jun 14, 2017, only 22 days ago). You can just add the missing code in the activations.py file or create your own selu activation in the script.

Example code

from keras.activations import elu

def selu(x):
    """Scaled Exponential Linear Unit. (Klambauer et al., 2017)
    # Arguments
        x: A tensor or variable to compute the activation function for.
    # References
        - [Self-Normalizing Neural Networks](https://arxiv.org/abs/1706.02515)
    """
    alpha = 1.6732632423543772848170429916717
    scale = 1.0507009873554804934193349852946
    return scale * elu(x, alpha)

model.add(Dense(32, input_shape=(input_length - 1,)), activation=selu)

NOTE:

With tensorflow 2.0 keras is included. You can get the selu activation with:

from tensorflow.keras.activations import selu

ContentLicense: CC BY-SA 4.0


问:
How to merge two user tables and associated usermeta tables
I have 2 similar databases both having user and usermeta tables. I need to merge these tables.
So there are 2 user tables like these

and 2 usermeta tables like these

from which I want to generate the merged user and usermeta tables

I am able to merge the user tables (obviously!) by just inserting the values from user table 2 (without IDs) to user table 1, giving me me the new user table 1 and the lookup between old and new IDs of the added users

What is a good way of now replacing the old user_id values in usermeta 2 table data, so that i can insert them in the usermeta 1 table to merge it i.e. I want to get this from usermeta 2

I can do it in Excel/CSV through vlookup, but sometimes converting data from SQL to Excel/CSV and back is tricky

答:
You can JOIN the tables usermeta2 and id_lookup and update user_id with new_id

```<code>UPDATE usermeta2 um2 JOIN id_lookup idl ON um2.user_id = idl.old_id
SET um2.user_id = idl.new_id;
</code>```

Body:
You can JOIN the tables usermeta2 and id_lookup and update user_id with new_id

UPDATE usermeta2 um2 JOIN id_lookup idl ON um2.user_id = idl.old_id
SET um2.user_id = idl.new_id;


问:
SQL Native Client 10.0 Login Failed
I'm setting up a Classic ASP site in IIS 7.5 (Windows Server 2008 R2). I set the site and the application pool to run as a specific domain account. I added the domain account to the SQL Server 2008 instance running on the same server. I'm getting the following error:

[Microsoft][SQL Server Native Client 10.0][SQL Server]Login failed for user 'DOMAIN\Account'.

Here is my connection string:

Driver={SQL Server Native Client 10.0};Server=server;Trusted_Connection=Yes;Database=db

I have the exact same setup on another site on the same server. The other site works flawlessly. Any thoughts?

答:
Ensure that a Windows authentication SQL Server login exists for the Windows NT/Windows 2000 user account that IIS uses to process the request for the ASP page.

read this.

ContentLicense: CC BY-SA 2.5

Title: SQL Native Client 10.0 Login Failed


问:
Change project architecture
i want to improve my project architecture. my app working with Sq lite with server posts once in a while.
my question is,
is it better to use Data binding library or should i continue work with view id's?
is it make it easier to bind data and work with multiple object on the same view?</p>

答: I suppose your app mainly works with database and rarely with API calls. Data binding mainly comes to rescue you when we need to bind data from the API calls. So better approach would be skipping use of data binding</p>

Title: Change project architecture


问:
Dynamic store dirs for same models with carrierwave
I am using CarrierWave with fog to upload my images to S3.

I have model Image that can represent images of different sizes and according to that needs to be saved in different folder.

For example, for image.jpg I could have two different uploaded versions that need to be saved as:

```<code>'images/large/image.jpg'
'images/small/image.jpg'
</code>```

There could be arbitrary number of use cases and versions using minimagick can't cover them all.

So far I haven't been able to find solution. Does anyone know how to do this?

答:
I've seen this question asked a few times so I'll write what my final solution is.

Instead of defining mount_uploader on model I decided to just use Uploader independently and save urls to records later.

Dynamically changing store_dir and filename can be accomplished like this

```<code>uploader = Uploader.new

uploader.define_singleton_method(:store_dir) do
    'new_store_dir'
end
uploader.define_singleton_method(:filename) do
    'new_filename'
end

uploader.store!(image)
</code>```

Using this approach you can also define names with local variables or whatever you have available in controller.

Hopefully it helps someone else as well.

Body:
I am using CarrierWave with fog to upload my images to S3.

I have model Image that can represent images of different sizes and according to that needs to be saved in different folder.

For example, for image.jpg I could have two different uploaded versions that need to be saved as:

'images/large/image.jpg'
'images/small/image.jpg'

There could be arbitrary number of use cases and versions using minimagick can't cover them all.

So far I haven't been able to find solution. Does anyone know how to do this?

Body:
I've seen this question asked a few times so I'll write what my final solution is.

Instead of defining mount_uploader on model I decided to just use Uploader independently and save urls to records later.

Dynamically changing store_dir and filename can be accomplished like this

uploader = Uploader.new

uploader.define_singleton_method(:store_dir) do
    'new_store_dir'
end
uploader.define_singleton_method(:filename) do
    'new_filename'
end

uploader.store!(image)

Using this approach you can also define names with local variables or whatever you have available in controller.

Hopefully it helps someone else as well.


问:
Storing Questions and Answers for Tutorial application in android
I am developing new android application for Java tutorials. I wanted to know what is the best way to store questions and answers. I am planning to have around 100 questions for each sections. I am totally having 5 sections.

Thinking of below options. But don't know what would be the performance

Storing in Sqlite database - But in this case, how to insert the questions?

Storing it in excel file and reading the excel using poi and showing it in the application

Storing it as JSON file ( one json file for each section)

Storing it in XML file ( one xml for each section)

Could someone please help me on this which is the best one to choose?

答:
Use JSON buddy.

```<code>[
{"SectionTitle":"Section A",
"questions":
[{"title":"What is Java?"
"answers": [{"title":"programming language", "isCorrect":"true"},{"title":"cooking technique","isCorrect":"false"},{"title":"movie star","isCorrect":"false"}]
},...]
},...
]
</code>```

and parse your json into objects, use recyclerView to view your sections, and a ViewPager to move between questions.

Body:
Use JSON buddy.

[
{"SectionTitle":"Section A",
"questions":
[{"title":"What is Java?"
"answers": [{"title":"programming language", "isCorrect":"true"},{"title":"cooking technique","isCorrect":"false"},{"title":"movie star","isCorrect":"false"}]
},...]
},...
]

and parse your json into objects, use recyclerView to view your sections, and a ViewPager to move between questions.


问:
Send value from function to an other VC, swift3
I have this function, which is called when the user clicks on the image on the collectionView. There is a variable url (in the line print("IMAGE CLICKED:", url)) I want to send the value of the url to another viewController and set url in a UIImage.

Here is my unfinished function in the firstVC. From here I'd like to send the url to the secondVC.

```<code>func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    selectedCommunity = (liveCommunities?[indexPath.row].communityId)!
    let home = HomeViewController()
    home.showCommunityDetail()

    //url is the source for a image in another viewController
    //TODO: Send url to other viewController
    //There is no relation between the thwo viewControllers (only via tabbar)

    print("--------")
    print("IMAGE CLICKED:", url)
    print("--------")

}
</code>```

Is that possible? Thanks for your help in advance!

答:
As others mentioned in their answers, there are two mainstream ways we do this.There is sufficient literature on the internet about the usage of both. I will provide short explanations in my own words

Delegates

Delegation refers to the process of passing on a piece of work to some other object which is better suited to perform that task. You can go the delegate way given you have with you both the delegate and delegating object.
In your case, the viewController with the collection view will be the delegating object where as the view controller that sets the image will be the delegate.

Basically you will need the following in the delegating viewcontroller.

A 'protocol' which will include a method to pass the required
information to the delegate object.

A delegate object.

A reference to the second view controller, which will be set as the
delegate of the first viewcontroller.

Call the method on the delegate wherever applicable.

In the delegate view controller

You will have to confirm to the protocol declared earlier.

Implement the required methods in the protocol.

Notifications

Notifications are more like broadcasts. You send out an app wide message that can be received and processed by any listeners. We use the NSNotification class for this. The information or the message will be captured in the NSNotification's userInfo object. Each notification is identified by a name.

The advantage of notifications is that you do not typically need to keep track or references of listeners. You just need to generate the payload data, publish a notification and be done with it. The notification can be listened to by any class and your information has the potential to be processed in any object that is alive give it is listening for it. This can become an advantage or a disadvantage.

Comparison

In my personal experience, working in large projects excessive use of Notifications combined with repeated unplanned patching in of changes and fixes eventually leads to unreadable & unmaintainable code. Delegation requires more planning and time to implement, but you always know who's doing what. That said these are two different tools and should be used as per the requirement.

Body:
I have this function, which is called when the user clicks on the image on the collectionView. There is a variable url (in the line print("IMAGE CLICKED:", url)) I want to send the value of the url to another viewController and set url in a UIImage.

Here is my unfinished function in the firstVC. From here I'd like to send the url to the secondVC.

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    selectedCommunity = (liveCommunities?[indexPath.row].communityId)!
    let home = HomeViewController()
    home.showCommunityDetail()

    //url is the source for a image in another viewController
    //TODO: Send url to other viewController
    //There is no relation between the thwo viewControllers (only via tabbar)

    print("--------")
    print("IMAGE CLICKED:", url)
    print("--------")

}

Is that possible? Thanks for your help in advance!


问:
How to label x-axis if a sequence is used?
I've this R script:

```<code>plot(
  seq(2011, 2015),
  main = 'Anzahl vor dem 20 Lebensjahr verstorbener Personen',
  xlab = 'Jahre',
  ylab = 'Tode',
  ylim = c(100, 400)
)

points(
  deaths.data[deaths.data['Geschlecht'] == 'Mann', 'Jahr'],
  deaths.data[deaths.data['Geschlecht'] == 'Mann', 'value'],
  col = 'blue'
)

points(
  deaths.data[deaths.data['Geschlecht'] == 'Frau', 'Jahr'],
  deaths.data[deaths.data['Geschlecht'] == 'Frau', 'value'],
  col = 'red'
)
</code>```

Which produces this plot:

My quick question is: How can I achieve, that the x-axis is labeled with the sequence? (2011, 2012, 2013, 2014, 2015)

Tl;dr

My data looks like this:

```<code>> deaths.data
   Geschlecht Demographisches.Merkmal Jahr value
1        Mann         Unter 20 Jahren 2011   301
2        Frau         Unter 20 Jahren 2011   214
3        Mann         Unter 20 Jahren 2012   285
4        Frau         Unter 20 Jahren 2012   203
5        Mann         Unter 20 Jahren 2013   312
6        Frau         Unter 20 Jahren 2013   212
7        Mann         Unter 20 Jahren 2014   305
8        Frau         Unter 20 Jahren 2014   209
9        Mann         Unter 20 Jahren 2015   323
10       Frau         Unter 20 Jahren 2015   225
</code>```

答:
Additionally using ggplot2 :

```<code>indt<-data.table(
  Geschlecht=
    factor(c("Mann","Frau", "Mann", "Frau", "Mann",
             "Frau", "Mann", "Frau","Mann", "Frau")),
  Jahr=
    c(2011, 2011, 2012, 2012, 2013, 2013, 2014, 2014, 2015, 2015),
  value=
    c(301, 214, 285, 203, 312, 212, 305, 209, 323, 225)
)
</code>```

The plot is then created via:

```<code>    library(ggplot2)
    ggplot(indt) + geom_point(size=3.5,aes(x=Jahr, y=value, color=Geschlecht))+ggtitle("Anzahl vor dem 20 Lebensjahr verstorbener Personen")+  labs(x="Jahre",y="Tode") +ylim(100,400)
</code>```

Body:
I've this R script:

plot(
  seq(2011, 2015),
  main = 'Anzahl vor dem 20 Lebensjahr verstorbener Personen',
  xlab = 'Jahre',
  ylab = 'Tode',
  ylim = c(100, 400)
)

points(
  deaths.data[deaths.data['Geschlecht'] == 'Mann', 'Jahr'],
  deaths.data[deaths.data['Geschlecht'] == 'Mann', 'value'],
  col = 'blue'
)

points(
  deaths.data[deaths.data['Geschlecht'] == 'Frau', 'Jahr'],
  deaths.data[deaths.data['Geschlecht'] == 'Frau', 'value'],
  col = 'red'
)

Which produces this plot:

My quick question is: How can I achieve, that the x-axis is labeled with the sequence? (2011, 2012, 2013, 2014, 2015)

Tl;dr

My data looks like this:

> deaths.data
   Geschlecht Demographisches.Merkmal Jahr value
1        Mann         Unter 20 Jahren 2011   301
2        Frau         Unter 20 Jahren 2011   214
3        Mann         Unter 20 Jahren 2012   285
4        Frau         Unter 20 Jahren 2012   203
5        Mann         Unter 20 Jahren 2013   312
6        Frau         Unter 20 Jahren 2013   212
7        Mann         Unter 20 Jahren 2014   305
8        Frau         Unter 20 Jahren 2014   209
9        Mann         Unter 20 Jahren 2015   323
10       Frau         Unter 20 Jahren 2015   225

Body:
Additionally using ggplot2 :

indt<-data.table(
  Geschlecht=
    factor(c("Mann","Frau", "Mann", "Frau", "Mann",
             "Frau", "Mann", "Frau","Mann", "Frau")),
  Jahr=
    c(2011, 2011, 2012, 2012, 2013, 2013, 2014, 2014, 2015, 2015),
  value=
    c(301, 214, 285, 203, 312, 212, 305, 209, 323, 225)
)

The plot is then created via:

    library(ggplot2)
    ggplot(indt) + geom_point(size=3.5,aes(x=Jahr, y=value, color=Geschlecht))+ggtitle("Anzahl vor dem 20 Lebensjahr verstorbener Personen")+  labs(x="Jahre",y="Tode") +ylim(100,400)


问:
when i insert data in sql with curly brase it shows input string not correct format error
```<code>string query = string.Format(@"if not exists(select id from user_detail where id_str = '" + args.Tweet.CreatedBy.IdStr + "') begin insert into user_detail(id_str,screen_name,user_name,createdate,hashtag,imageurl,message,unique_id,tweet_id)values('" + args.Tweet.CreatedBy.IdStr + "',N'" + args.Tweet.CreatedBy.ScreenName.Replace("'", "`") + "', N'" + args.Tweet.CreatedBy.Name.Replace("'", "`") + "','" + args.Tweet.CreatedAt + "',N'" + Hashtag + "',N'" + Convert.ToString() + "',N'" + args.Tweet.Text.Replace("'", "`") + "','" + Guid.NewGuid().ToString() + "','" + args.Tweet.IdStr + "') end else begin update user_detail set screen_name=N'" + args.Tweet.CreatedBy.ScreenName + "' where id_str = '" + args.Tweet.CreatedBy.IdStr + "' end");
</code>```

答:
Never concatenate input to create SQL. It will hurt you and hurt you and hurt you. If you use parameters, then all issues of escaping will disappear, as will issues relating to culture-info, and the risk of SQL injection. It will also mean you don't need to corrupt people's data by changing ' to back-ticks (although actually there is a way of escaping single quotes).

Parameterize

For example:

```<code>const string query = @"
if not exists(select id from user_detail where id_str = @idstr)
begin
    insert into user_detail(id_str,screen_name,user_name,createdate,hashtag,imageurl,message,unique_id,tweet_id)
    values(@idstr, @screenName, /*...*/)
end
else
begin
     update user_detail set screen_name= @screenName
     -- ...
end";
</code>```

There are lots of ways of doing the actual execution.  For example with raw ADO.NET:

```<code>using(var cmd = conn.CreateCommand()) {
    cmd.CommandText = query;
    cmd.Parameters.AddWithValue("idstr", idstr);
    cmd.Parameters.AddWithValue("screenName", screenName);
    // ...
    cmd.ExecuteNonQuery();
}
</code>```

or with "dapper":

```<code>conn.Execute(query, new { idstr, screenName, /* ... */ });
</code>```

In all cases, ... denotes where I've omitted additional things for you to fill in (the however-many columns / parameters / etc that describe your data).

Body:
Never concatenate input to create SQL. It will hurt you and hurt you and hurt you. If you use parameters, then all issues of escaping will disappear, as will issues relating to culture-info, and the risk of SQL injection. It will also mean you don't need to corrupt people's data by changing ' to back-ticks (although actually there is a way of escaping single quotes).

Parameterize

For example:

const string query = @"
if not exists(select id from user_detail where id_str = @idstr)
begin
    insert into user_detail(id_str,screen_name,user_name,createdate,hashtag,imageurl,message,unique_id,tweet_id)
    values(@idstr, @screenName, /*...*/)
end
else
begin
     update user_detail set screen_name= @screenName
     -- ...
end";

There are lots of ways of doing the actual execution.  For example with raw ADO.NET:

using(var cmd = conn.CreateCommand()) {
    cmd.CommandText = query;
    cmd.Parameters.AddWithValue("idstr", idstr);
    cmd.Parameters.AddWithValue("screenName", screenName);
    // ...
    cmd.ExecuteNonQuery();
}

or with "dapper":

conn.Execute(query, new { idstr, screenName, /* ... */ });

In all cases, ... denotes where I've omitted additional things for you to fill in (the however-many columns / parameters / etc that describe your data).


问:
Limit this PHP foreach statement to just 5 loops
How could I limit this foraech statement to just 5 loops? I think I should just use Break but I'm not sure where to put it. </p>

```<code> <?php if(!empty($locations)): foreach($locations as $location):  ?>
<?php if(empty($location["title"])) continue; ?>
<li>
    <a href="<?php esc_attr_e($url.$glue.http_build_query($location["query"])) ?>">
        <?php esc_html_e($location["title"]) ?>
    </a>
    <?php if($param->count): ?>
    <div class="wpjb-widget-item-count">
        <div class="wpjb-widget-item-num"><?php echo intval($location["count"]) ?></div>
    </div>
    <?php endif; ?>
</li>
<?php endforeach; ?>
</code>```

答:
Add a variable ... increment it each iteration ... after reach 5 just break loop.</p>

```<code><?php $i = 1;?>

<?php if(!empty($locations)): foreach($locations as $location):  ?>
    <?php if(empty($location["title"])) continue; ?>
    <li>
        <a href="<?php esc_attr_e($url.$glue.http_build_query($location["query"])) ?>">
            <?php esc_html_e($location["title"]) ?>
        </a>
        <?php if($param->count): ?>
        <div class="wpjb-widget-item-count">
            <div class="wpjb-widget-item-num"><?php echo intval($location["count"]) ?></div>
        </div>
        <?php endif; ?>
    </li>
    <?php  if ($i++ == 5) break; ?>
    <?php endforeach; ?>
</code>```

Body:
How could I limit this foraech statement to just 5 loops? I think I should just use Break but I'm not sure where to put it.

 <?php if(!empty($locations)): foreach($locations as $location):  ?>
<?php if(empty($location["title"])) continue; ?>

    <a href="<?php esc_attr_e($url.$glue.http_build_query($location["query"])) ?>">
        <?php esc_html_e($location["title"]) ?>

    <?php if($param->count): ?>

<?php echo intval($location["count"]) ?>

    <?php endif; ?>

<?php endforeach; ?>

Body:
Add a variable ... increment it each iteration ... after reach 5 just break loop.

<?php $i = 1;?>

<?php if(!empty($locations)): foreach($locations as $location):  ?>
    <?php if(empty($location["title"])) continue; ?>
    <li>
        <a href="<?php esc_attr_e($url.$glue.http_build_query($location["query"])) ?>">
            <?php esc_html_e($location["title"]) ?>
        </a>
        <?php if($param->count): ?>
        <div class="wpjb-widget-item-count">
            <div class="wpjb-widget-item-num"><?php echo intval($location["count"]) ?></div>
        </div>
        <?php endif; ?>
    </li>
    <?php  if ($i++ == 5) break; ?>
    <?php endforeach; ?>


问:
Facebook open graph GraphMethodException error code 100
I'm trying to work my way through the Facebook tutorial publish and open graph story for iOS, https://developers.facebook.com/docs/tutorials/ios-sdk-tutorial/publish-open-graph-story/

Step 3 is failing for me. When I use the graph API explorer I get the error

```<code>{
  "error": {
    "message": "Unsupported post request.",
    "type": "GraphMethodException",
    "code": 100
  }
}
</code>```

I've looked through a bunch of answers on stack overflow relating to this error but none seem to be my problem. I have selected get access token and have publish permissions. The page is not alcohol related and the user page I'm using is not age restricted.

I have selected my application from the top of the page. I have selected post and then entered my story object in the space provided me/gopiratestd:boss

then I add a new field and use the key beat on the left and then the following url on the right.
https://hidden-castle-7245.herokuapp.com/opengraphobject.php?fb:app_id=554329451276476&og:type=gopiratestd:boss&og:title= beataboss&og:description=%22Beat%22&og:image=http://images.all-free-download.com/images/graphicmedium/beautiful_cat_picture_6_168770.jpg&body=Beat

Then when I hit submit it returns that error.

Is there anything obvious I'm doing wrong here?

When I use that link in the object debugger it doesn't return any errors.

答:
{
   "error": {
      "message": "Invalid appsecret_proof provided in the API argument",
      "type": "GraphMethodException",
      "code": 100,
      "fbtrace_id": "CjRXFGNtROl"
   }
}

If this your error it is because of in correct token. It may be because you are using different account for configuring web app and mobile app for Facebook configuration. Both accounts should be same.

The app ID must be the same for your mobile app and your web app.

Body:
I'm trying to work my way through the Facebook tutorial publish and open graph story for iOS, https://developers.facebook.com/docs/tutorials/ios-sdk-tutorial/publish-open-graph-story/

Step 3 is failing for me. When I use the graph API explorer I get the error

{
  "error": {
    "message": "Unsupported post request.",
    "type": "GraphMethodException",
    "code": 100
  }
}

I've looked through a bunch of answers on stack overflow relating to this error but none seem to be my problem. I have selected get access token and have publish permissions. The page is not alcohol related and the user page I'm using is not age restricted.

I have selected my application from the top of the page. I have selected post and then entered my story object in the space provided me/gopiratestd:boss

then I add a new field and use the key beat on the left and then the following url on the right.
https://hidden-castle-7245.herokuapp.com/opengraphobject.php?fb:app_id=554329451276476&og:type=gopiratestd:boss&og:title= beataboss&og:description=%22Beat%22&og:image=http://images.all-free-download.com/images/graphicmedium/beautiful_cat_picture_6_168770.jpg&body=Beat

Then when I hit submit it returns that error.

Is there anything obvious I'm doing wrong here?

When I use that link in the object debugger it doesn't return any errors.


问:
Most efficient way of loading large amount of data on Firebase
I have a simple viewpager with 2 fragments. One is for loading the newest posts and the other is loading top post, similar to the Reddit official app.

The way I currently load the Firebase data is to set obtain the snapshot through a singleValueListener and then sort after. The "new" tab doesn't require any Queries since it is already placed in order, however, for "top" it would need to order by score. I then load those data directly into RecyclerView.

Is there a more efficient way to loading the data? I currently have only a small database and it takes a while to load up, especially at the beginning. The only idea I have right now is to use Firebase's limitTo methods, however, that would not work for the "top" posts tab as it'll need all the data to work with.

Thanks!

答:
You did not post your code, so I can not comment on that. But from what you've described, the method you're using indeed is the most efficient one.

From my own experience, I can vouch that Firebase is blazingly fast. However, the delay you're experiencing right at the start is because Firebase needs to establish connection with the database in the beginning. Once the connection is established, updates and downloads are in real time ( only constrained to the amount of data you're editing and your network quality ). One thing that you can look into is enabling offline persistence, so that the users of your app are not shown a blank screen at app startup. You can read more about it here.


问:
auto create record of another model while creating a record in one form - Odoo 10
I have two model in my orm i.e. _service & _apple. What I want is I want to create record of _apple with some fields written automatically. As an example, from sale order we can create invoice and when invoice is created, some of the fields of invoice are automatically generated written in record as same as in sale order.

What I have done is:

My service Model

```<code>class _service(models.Model):
_name = 'se.service'
_rec_name = "service_name"

name = fields.Char(
    'Reference', copy=False, readonly=True, default=lambda x: _('New'))
service_name = fields.Char("Service Name", required=True)
service_department = fields.Many2one('hr.department', "Department Name", required=True, help="Department Name of employee")
service_description = fields.Text("Description", required=True)
service_remarks = fields.Text("Remarks")
service_methodology = fields.Html(string="Methodology")
service_id = fields.One2many('se.objective', 'service_id', string="Objectives", required=True)

@api.model
def create(self, valuees):
    if valuees.get('name', _('New')) == _('New'):
        valuees['name'] = self.env['ir.sequence'].next_by_code('se.service') or _('New')
    return super(_service, self).create(valuees)

def _create_apple(self):
    inv_obj = self.env['se.apple']
    self.ensure_one()
    se = _service
    invoice = inv_obj.create({
        'apple_name': se.service_name,
        'apple_description': se.service_description,
        'apple_remarks': se.service_remarks
    })
    return invoice

def create_apple(self):
    self._create_apple()
</code>```

My _apple Model

```<code>class _apple(models.Model):
    _name = 'se.apple'

    apple_name = fields.Char("Apple Name")
    apple_description = fields.Text("Remarks Apple")
    apple_remarks = fields.Text("Remarks Apple")
</code>```

My se.service form:

```<code><header>
    <button name="create_apple" string="Create Apple" type="object" class="btn-primary"/>
</header>
</code>```

If I do as below:
1. I create a form in se.service.
2. I save the form.
3. I click create_apple button.

I expect:
1. A record automatically created in se.apple
2. Record will have apple_name, apple_description & apple_remarks automatically generated as I have filled in se.service.

答:
You have the current service record in the self so, you can use it directly.
try this updated method.</p>

```<code>   def _create_apple(self):
        inv_obj = self.env['se.apple']
        self.ensure_one()
        invoice = inv_obj.create({
            'apple_name': self.service_name,
            'apple_description': self.service_description,
            'apple_remarks': self.service_remarks
        })
        return invoice
</code>```

Body:
I have two model in my orm i.e. _service & _apple. What I want is I want to create record of _apple with some fields written automatically. As an example, from sale order we can create invoice and when invoice is created, some of the fields of invoice are automatically generated written in record as same as in sale order.

What I have done is:

My service Model

class _service(models.Model):
_name = 'se.service'
_rec_name = "service_name"

name = fields.Char(
    'Reference', copy=False, readonly=True, default=lambda x: _('New'))
service_name = fields.Char("Service Name", required=True)
service_department = fields.Many2one('hr.department', "Department Name", required=True, help="Department Name of employee")
service_description = fields.Text("Description", required=True)
service_remarks = fields.Text("Remarks")
service_methodology = fields.Html(string="Methodology")
service_id = fields.One2many('se.objective', 'service_id', string="Objectives", required=True)

@api.model
def create(self, valuees):
    if valuees.get('name', _('New')) == _('New'):
        valuees['name'] = self.env['ir.sequence'].next_by_code('se.service') or _('New')
    return super(_service, self).create(valuees)

def _create_apple(self):
    inv_obj = self.env['se.apple']
    self.ensure_one()
    se = _service
    invoice = inv_obj.create({
        'apple_name': se.service_name,
        'apple_description': se.service_description,
        'apple_remarks': se.service_remarks
    })
    return invoice

def create_apple(self):
    self._create_apple()

My _apple Model

class _apple(models.Model):
    _name = 'se.apple'

    apple_name = fields.Char("Apple Name")
    apple_description = fields.Text("Remarks Apple")
    apple_remarks = fields.Text("Remarks Apple")

My se.service form:

    <button name="create_apple" string="Create Apple" type="object" class="btn-primary"/>

If I do as below:
1. I create a form in se.service.
2. I save the form.
3. I click create_apple button.

I expect:
1. A record automatically created in se.apple
2. Record will have apple_name, apple_description & apple_remarks automatically generated as I have filled in se.service.

Body:
You have the current service record in the self so, you can use it directly.
try this updated method.

   def _create_apple(self):
        inv_obj = self.env['se.apple']
        self.ensure_one()
        invoice = inv_obj.create({
            'apple_name': self.service_name,
            'apple_description': self.service_description,
            'apple_remarks': self.service_remarks
        })
        return invoice


问:
boost for windows, first time use
i just downloaded boost 1_45_0 for windows.  i have vc++6 installed on my windows 7 64bit pc.  in the windows introduction, i'm told to try to compile a small lambda program.

i placed boost in the root of c:, i have c:\boost\boost_1_45_0.  i added "c:\boost\boost_1_45_0" to my "include" environment variable in the windows advanced system settings

what else do i need to do before i c

when i try to compile at the command prompt, i get the following:
C:\test\boost>cl /EHsc /I c:\boost\boost_1_45_0 boost.cpp
Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 12.00.8804 for 80x86
Copyright (C) Microsoft Corp 1984-1998. All rights reserved.

boost.cpp
c:\boost\boost_1_45_0\boost/config/suffix.hpp(596) : error C2039: 'typeinfo' : i
s not a member of '`global namespace''
c:\boost\boost_1_45_0\boost/config/suffix.hpp(596) : error C2873: 'typeinfo' : s
ymbol cannot be used in a using-declaration
c:\boost\boost_1_45_0\boost/mpl/aux_/yes_no.hpp(56) : fatal error C1506: unrecov
erable block scoping error

答: You are using a compiler that is now 12 years old, and boost doesn't support it. You'll need VS.Net 2003 at a minimum, but I'd strongly recommend VS2008 or VS2010.  There is a free 'express' version of VS2010.  Unless you have a very specific need to use VC++6 I would ditch it now.

Title: boost for windows, first time use


问:
Android - Hook Notifications
Is there any way to do something when the phone receives a notification from any other App? (I don't care about the content of the notification)

I would to change the default notification sound of the device (every time a new notification appears)

Thanks

答:
Here an Example :

```<code>    protected void GenerateNotify() {

        NotificationManager myNotificationManager=(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
        Notification notification=new Notification(android.R.drawable.ic_btn_speak_now,"hi",100);
        Intent intent=new Intent(getApplicationContext(),as.class);
        PendingIntent contentintent=PendingIntent.getBroadcast(getApplicationContext(),0, intent, 0);
        notification.setLatestEventInfo(getApplicationContext(), "Hi","date", contentintent);
        notification.flags |= Notification.FLAG_AUTO_CANCEL;
        notification.sound = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.notifysnd);
        notification.defaults = Notification.DEFAULT_LIGHTS | Notification.DEFAULT_VIBRATE;
    }
</code>```

Before doing this please put mp3 file into raw folder and navigate it to correct path

Title: Android - Hook Notifications

Body:
Here an Example :

    protected void GenerateNotify() {

        NotificationManager myNotificationManager=(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
        Notification notification=new Notification(android.R.drawable.ic_btn_speak_now,"hi",100);
        Intent intent=new Intent(getApplicationContext(),as.class);
        PendingIntent contentintent=PendingIntent.getBroadcast(getApplicationContext(),0, intent, 0);
        notification.setLatestEventInfo(getApplicationContext(), "Hi","date", contentintent);
        notification.flags |= Notification.FLAG_AUTO_CANCEL;
        notification.sound = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.notifysnd);
        notification.defaults = Notification.DEFAULT_LIGHTS | Notification.DEFAULT_VIBRATE;
    }

Before doing this please put mp3 file into raw folder and navigate it to correct path


问:
UNITY 2d - Can i refer to a parametre from animator in the player script?
I'm trying to set the bool Walking parametre from the animator to false if the player doesn't move.

I already have a parametre called Speed, wich works and it's only positive, so I want to say something like this:

if (speed == 0) {anim.SetBool("Walking", false); }  //Where speed is a parametre in the animator

else { anim.SetBool("Walking", true); }

Can I do something similar to this?

Thanks

答:
You indeed can. For this matter, you can use Animator.GetFloat to get the value of the Speed parameter.</p>

```<code>if (anim.GetFloat("Speed") == 0)
{
    anim.SetBool("Walking", false);
}
else
{
    anim.SetBool("Walking", true);
}
</code>```

Body:
You indeed can. For this matter, you can use Animator.GetFloat to get the value of the Speed parameter.

if (anim.GetFloat("Speed") == 0)
{
    anim.SetBool("Walking", false);
}
else
{
    anim.SetBool("Walking", true);
}


问:
How to use _.SortBy() with an array of Objects?
I tried a lot of algorithm to convert my Array with objects inside into an array of arrays. But each time either it doesn't work or my new create array is empty. For exemple, I can't run into it with angular.foreach()or myArray.forEach(function(element)). I really don't know why, because it is declared and initialized as an array "var myArray = [];".

Then I'm using pushto populate it, and what I obtained in the console.log is :

What I would like to have is something usable into _.SortBy(myArray, 'date'); (Underscore.js) to do it I need myArray to be like that :

var stooges = [{name: 'moe', age: 40}, {name: 'larry', age: 50}, {name: 'curly', age: 60}];

Following this post : Converting a JS object to an array I tried barely everything listed, but nothing worked...Can you give me a hand ?

$scope.myArray = [];

// This is into an angular.foreach

 $scope.myArray.push({'Name' : snapshot.val().name, 'Link' : snapshot.val().link, 'second' : snapshot.val().second, 'var' : snapshot.val().var, 'selfID' : 'MyID', 'date' : snapshot.val().date, 'hour' : snapshot.val().hour });

 console.log("MyArray :", $scope.myArray);```
</div>
</div>
</p>

<h3>EDIT :</h3>

<p>It seems there is a problem with my array, i tried this two function, but i couldn't see any <code>console.log()</code>... Is it possible that my array is locked ? Maybe no function (sort, _.sortBy...) can run into it ?</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>// One try to run into and sort
$scope.myArray.sort(function(x, y)
{
            var date1 = new Date(x.date);
            var date2 = new Date(y.date);

            console.log("My dates :", date1);
            console.log("My dates :", date2);

            return date1 - date2 ;
});

// An other try to run into my array
for(var i = 0; i < $scope.myArray.length; i++)
{
            console.log("I'm in "+i+" with : "+$scope.newCal[i]);
}

// Even is showing the complete Array in console.log is working, this below shows me "undefined"

 console.log("One element : "+$scope.newCal[1]);</code>```

答:
In array you used date keyword and in this function _.SortBy(myArray, 'Date'); you are sorting using Date keyword.

Replace 'Date' keyword with 'date' and then try to sort your array.

So your sort function will be _.sortBy(myArray, 'date')

Body:
I tried a lot of algorithm to convert my Array with objects inside into an array of arrays. But each time either it doesn't work or my new create array is empty. For exemple, I can't run into it with angular.foreach()or myArray.forEach(function(element)). I really don't know why, because it is declared and initialized as an array "var myArray = [];".

Then I'm using pushto populate it, and what I obtained in the console.log is :

What I would like to have is something usable into _.SortBy(myArray, 'date'); (Underscore.js) to do it I need myArray to be like that :

var stooges = [{name: 'moe', age: 40}, {name: 'larry', age: 50}, {name: 'curly', age: 60}];

Following this post : Converting a JS object to an array I tried barely everything listed, but nothing worked...Can you give me a hand ?

$scope.myArray = [];

// This is into an angular.foreach

 $scope.myArray.push({'Name' : snapshot.val().name, 'Link' : snapshot.val().link, 'second' : snapshot.val().second, 'var' : snapshot.val().var, 'selfID' : 'MyID', 'date' : snapshot.val().date, 'hour' : snapshot.val().hour });

 console.log("MyArray :", $scope.myArray);

EDIT :

It seems there is a problem with my array, i tried this two function, but i couldn't see any console.log()... Is it possible that my array is locked ? Maybe no function (sort, _.sortBy...) can run into it ?

// One try to run into and sort
$scope.myArray.sort(function(x, y)
{
            var date1 = new Date(x.date);
            var date2 = new Date(y.date);

            console.log("My dates :", date1);
            console.log("My dates :", date2);

            return date1 - date2 ;
});

// An other try to run into my array
for(var i = 0; i < $scope.myArray.length; i++)
{
            console.log("I'm in "+i+" with : "+$scope.newCal[i]);
}

// Even is showing the complete Array in console.log is working, this below shows me "undefined"

 console.log("One element : "+$scope.newCal[1]);


问:
In Mysql,How can select new data from last select data
Use PHP.
then in mysql hava this table

```<code>Id     where    name    sex
1      CN       X.ming  boy
2      US       Tom     boy
3      US       jom     boy
4      US       Kim     girl
</code>```

=====================

first i need get where select * from table where=US

then need get boy select * from (last select) where sex=boy

i find get code is

```<code>SELECT * FROM (SELECT * FROM table WHERE where=US) AS a WHERE sex=boy；
</code>```

but this not good and not fast.

case:

//
my English is no good,so i reply is slow... sorry!!

答:
Think smartly you can put as many columns  as you can in where clause.
by using operators like 'AND' to check wehther both conditions are true, 'OR' if any of defined condition is true.

for current situation just use.

```<code>select * from (SELECT TOP 1 * FROM Table ORDER BY ID DESC) where sex = 'male'
</code>```

Body:
Use PHP.
then in mysql hava this table

Id     where    name    sex
1      CN       X.ming  boy
2      US       Tom     boy
3      US       jom     boy
4      US       Kim     girl

=====================

first i need get where select * from table where=US

then need get boy select * from (last select) where sex=boy

i find get code is

SELECT * FROM (SELECT * FROM table WHERE where=US) AS a WHERE sex=boy；

but this not good and not fast.

case:

//
my English is no good,so i reply is slow... sorry!!

Body:
Think smartly you can put as many columns  as you can in where clause.
by using operators like 'AND' to check wehther both conditions are true, 'OR' if any of defined condition is true.

for current situation just use.

select * from (SELECT TOP 1 * FROM Table ORDER BY ID DESC) where sex = 'male'


问:
Regex Pattern Matching until the first whitespace before the first series of characters containing a specific character
Consider the following string:

```<code>ab cd ef gh/
</code>```

How would I extract ab cd ef?

I would like to be able to match until the first whitespace before the first series containing a specific character, which in the case above is /.

EDIT: I'm trying to set a config file to parse some logs into Logstash, so I was wondering whether it was possible to do this just with regex rules.

答:
this should suit for your specific case, assume it as a starting point:

console.log(
  'ab cd ef gh/'.match(/(.*?)\s*(?:\w+\/)/).pop()
)```

Body:
Consider the following string:

ab cd ef gh/

How would I extract ab cd ef?

I would like to be able to match until the first whitespace before the first series containing a specific character, which in the case above is /.

EDIT: I'm trying to set a config file to parse some logs into Logstash, so I was wondering whether it was possible to do this just with regex rules.


问:
how to create page loader bar for opencart by using a nprogress
can any one guide me how to create page loader bar for opencart by using a nprogress?

Expecting an answer in detail.

Thank you

答:
first load the js and css file in header.tpl

```<code><script type="text/javascript" src='nprogress.js'></script>
<link rel='stylesheet' href='nprogress.css'/>
</code>```

Then add this code in footer.tpl

```<code><script type="text/javascript">
    NProgress.start();
    setTimeout(function() { NProgress.done(); $('.fade').removeClass('out'); }, 1000);
</script>
</code>```

Body:
first load the js and css file in header.tpl

<script type="text/javascript" src='nprogress.js'></script>
<link rel='stylesheet' href='nprogress.css'/>

Then add this code in footer.tpl

<script type="text/javascript">
    NProgress.start();
    setTimeout(function() { NProgress.done(); $('.fade').removeClass('out'); }, 1000);
</script>


问:
Exposing properties of an object contained by a control
I have a simple object, could be a struct even, with three properties that I want to expose to the designer. Basically, I want my property to look like the Size or Padding properties of your average control, with an arrow to collapse or expand the properties as a sub-list of the control's properties. However, I cannot find any reference as to how this can be done. Since there are several types of properties with this collapse/extend look and feel I imagine there's something built-in I can use. If I have to implement my own Designer or Editor, forget it; it's not worth it. I doubt that that's the case; there's gotta be some simple attribute I can stick on the property or class that tells the designer to expose the browsable sub-properties.</p>

答:
In addition to Yochai's answer, please note the Designer attribute which allows you to set which designer will be used.

By setting the designer type you really have full control on the UI Visual Studio will show for your property.


问:
What is the return type for JPA query method when query result is not a class?
I have this query in JPA:

```<code>@Query("SELECT programId,COUNT(id) FROM Therapy GROUP BY programId ORDER BY COUNT(id) DESC")
List<Object> top10ProgramsOfTherapies();
</code>```

It works great, but it returns a list of Objects, and I can not get the data out of it. What return type should I use to read the result data?

答:
You can also create a DTO class, for example, TherapyDto which will have a constructor with 2 parameters and use it this way:

```<code>@Query("SELECT new com.my.TherapyDto(programId,COUNT(id)) FROM Therapy GROUP BY programId ORDER BY COUNT(id) DESC")
List<TherapyDto> top10ProgramsOfTherapies();
</code>```

Body:
I have this query in JPA:

@Query("SELECT programId,COUNT(id) FROM Therapy GROUP BY programId ORDER BY COUNT(id) DESC")
List<Object> top10ProgramsOfTherapies();

It works great, but it returns a list of Objects, and I can not get the data out of it. What return type should I use to read the result data?

Body:
You can also create a DTO class, for example, TherapyDto which will have a constructor with 2 parameters and use it this way:

@Query("SELECT new com.my.TherapyDto(programId,COUNT(id)) FROM Therapy GROUP BY programId ORDER BY COUNT(id) DESC")
List<TherapyDto> top10ProgramsOfTherapies();


问:
Error while installing chatterBot
Whenever I try to install ChatterBot using command pip install ChatterBot it gives this error:

```<code>Retrying (Retry(total=0, connect=None, read=None, redirect=None)) after connection broken by 'NewConnectionError('<pip._vendor.requests.packages.urllib3.connection.VerifiedHTTPSConnection object at 0x0000000003687898>: Failed to establish a new connection: [Errno 11001] getaddrinfo failed',)': /simple/chatterbot/
  Could not find a version that satisfies the requirement chatterbot (from versi
ons: )
No matching distribution found for chatterbot
</code>```

I downgraded from Python 3.6 to 2.7, yet receiving the same error.

I am using windows 8, Anaconda 2.7

答:
It's case sensitive issue, Try like this

pip install --upgrade chatterbot

Title: Error while installing chatterBot

Body:
Whenever I try to install ChatterBot using command pip install ChatterBot it gives this error:

Retrying (Retry(total=0, connect=None, read=None, redirect=None)) after connection broken by 'NewConnectionError('<pip._vendor.requests.packages.urllib3.connection.VerifiedHTTPSConnection object at 0x0000000003687898>: Failed to establish a new connection: [Errno 11001] getaddrinfo failed',)': /simple/chatterbot/
  Could not find a version that satisfies the requirement chatterbot (from versi
ons: )
No matching distribution found for chatterbot

I downgraded from Python 3.6 to 2.7, yet receiving the same error.

I am using windows 8, Anaconda 2.7


问:
social-share-button gem with html_safe not working in Rails 5
I used the social-share-button, Gem.

I want to share my website content to social site with some decoration, but it is not using HTML. It prints the  and  tags instead of making the text bold and italic.

```<code><%= social_share_button_tag(raw("<b>#{job.title}</b>").html_safe, :url => "google.com" ) %>
</code>```

答:
Before answering your question, you can find that raw is just a wrap version for html_safe. Normally, you don't need to call the both at sametime. see here

I saw the code here, there is already a raw in the end of function social_share_button_tag. So I can just remove your raw and html_safe :

```<code><%= social_share_button_tag("<b>#{job.title}</b>", :url => "google.com" ) %>
</code>```

I guess you want blod your job.title with html . You can make it in CSS. like that:

```<code>.social-share-button {
  .ssb-icon {
    font-weight: bold;
  }
}
</code>```

Body:
I used the social-share-button, Gem.

I want to share my website content to social site with some decoration, but it is not using HTML. It prints the  and  tags instead of making the text bold and italic.

<%= social_share_button_tag(raw("#{job.title}").html_safe, :url => "google.com" ) %>

Body:
Before answering your question, you can find that raw is just a wrap version for html_safe. Normally, you don't need to call the both at sametime. see here

I saw the code here, there is already a raw in the end of function social_share_button_tag. So I can just remove your raw and html_safe :

<%= social_share_button_tag("<b>#{job.title}</b>", :url => "google.com" ) %>

I guess you want blod your job.title with html <b>. You can make it in CSS. like that:

.social-share-button {
  .ssb-icon {
    font-weight: bold;
  }
}


问:
Python get GPS location on macOS
I want get GPS Location on macOS use Native API, Is any python library can do that? Not use IP estimate location, I need is GPS location ex HTML5 Geolocation.

thanks :)

答:
I found a cmd that can get gps location: WhereAmI

Or pyobjc-framework-CoreLocation

Title: Python get GPS location on macOS


问:
Updating Gemfile.lock fails
I've updated a gem version in my Gemfile, so I'm trying to update Gemfile.lock. I run:

```<code>$ bundle update
Fetching gem metadata from https://rubygems.org/......
Fetching version metadata from https://rubygems.org/..
Fetching dependency metadata from https://rubygems.org/.
Resolving dependencies.......
Fetching rake 10.5.0
Fetching i18n 0.8.1
Fetching minitest 5.7.0
Fetching thread_safe 0.3.6
....
</code>```

And get the following error despite it seems to be fetched already (see output above):

```<code>Bundler::GemspecError: Could not read gem at /usr/lib/ruby/gems/2.4.0/cache/rake-10.5.0.gem. It may be corrupted.
An error occurred while installing rake (10.5.0), and Bundler cannot continue.
Make sure that `gem install rake -v '10.5.0'` succeeds before bundling.
</code>```

There's no such file under /usr/lib/ruby/gems/2.4.0/cache/. The cache directory is writable (777).

If I run gem install rake -v '10.5.0' it works fine. But do I really need to install gems manually (error repeats for other packages)? I don't get such errors if just run bundle install without updating gems.

答: Turned out that setting write permissions on cache directory (/usr/lib/ruby/gems/2.4.0/cache/) is not enough. You have to set write permissions for the parent directory (/usr/lib/ruby/gems/2.4.0/). For some reason, bundle update doesn't write to cache unless you do that even though it doesn't write anything to any other directories on the same level as cache.

Title: Updating Gemfile.lock fails

Body:
I've updated a gem version in my Gemfile, so I'm trying to update Gemfile.lock. I run:

$ bundle update
Fetching gem metadata from https://rubygems.org/......
Fetching version metadata from https://rubygems.org/..
Fetching dependency metadata from https://rubygems.org/.
Resolving dependencies.......
Fetching rake 10.5.0
Fetching i18n 0.8.1
Fetching minitest 5.7.0
Fetching thread_safe 0.3.6
....

And get the following error despite it seems to be fetched already (see output above):

Bundler::GemspecError: Could not read gem at /usr/lib/ruby/gems/2.4.0/cache/rake-10.5.0.gem. It may be corrupted.
An error occurred while installing rake (10.5.0), and Bundler cannot continue.
Make sure that `gem install rake -v '10.5.0'` succeeds before bundling.

There's no such file under /usr/lib/ruby/gems/2.4.0/cache/. The cache directory is writable (777).

If I run gem install rake -v '10.5.0' it works fine. But do I really need to install gems manually (error repeats for other packages)? I don't get such errors if just run bundle install without updating gems.


问:
Run method before suite in TestNG via XML
I have an XML TestNG suite:

<suite name="mySuite" parallel="classes" thread-count="5">
    <test name="myTest">
        <packages>
            <package name="mypack.*"/>
        </packages>
    </test>
</suite>
```

<p>and I'd like to run a method every time before the suite.</p>

<p>Is it possible to have something like this:</p>

<pre class="lang-xml prettyprint-override"><code><suite name="mySuite" parallel="classes" thread-count="5">
    <before-suite>...</before-suite> <!-- Here I want to run a single method  -->
    <test name="myTest">
        <packages>
            <package name="mypack.*"/>
        </packages>
    </test>
</suite>
</code>```

?

答:
As per the documentation of the TestNG (http://testng.org/doc/documentation-main.html), we don't have an option to specify the before suite method in testng.xml.

As an option, you can use before suite annotation as follows to satisfy the requirement.

```<code>public class UtilitiesTest {
     @BeforeSuite
     public void init() {
         // Initialize the system before the test suite.
     }
}
</code>```

If you refer the documentation, you will find there are lots  of annotations such as @BeforeTest, @BeforeClass, @BeforeMethod ... might be helpful.

Note: You can place this class anywhere in the test suite.

Body:
I have an XML TestNG suite:

<suite name="mySuite" parallel="classes" thread-count="5">
    <test name="myTest">
        <packages>
            <package name="mypack.*"/>
        </packages>
    </test>
</suite>

and I'd like to run a method every time before the suite.

Is it possible to have something like this:

<suite name="mySuite" parallel="classes" thread-count="5">
    <before-suite>...</before-suite>
    <test name="myTest">
        <packages>
            <package name="mypack.*"/>
        </packages>
    </test>
</suite>

?

Body:
As per the documentation of the TestNG (http://testng.org/doc/documentation-main.html), we don't have an option to specify the before suite method in testng.xml.

As an option, you can use before suite annotation as follows to satisfy the requirement.

public class UtilitiesTest {
     @BeforeSuite
     public void init() {
         // Initialize the system before the test suite.
     }
}

If you refer the documentation, you will find there are lots  of annotations such as @BeforeTest, @BeforeClass, @BeforeMethod ... might be helpful.

Note: You can place this class anywhere in the test suite.


问:
How does angular provide the arguments mentioned in the component class constructor?
I'm trying to understand angular deeply, so i read the docs and it was very helpful.

now in the dependency injection chapter i read that

angular uses the injector bubbling technique to provide the service mentioned in the constructor

now the injector bubbling goes to the parent components one by one and check if there is an available instance of the service in order to provide it.

i have two questions:

Q1) is the arguments in the constructor are always services?

Q2) if there is other than the services is mentioned in the constructor do they also use the bubbling technique?

答:
is the arguments in the constructor are always services?

No, any configurable value/variable (array, object, string, dynamic runtime string, etc)

if there is other than the services is mentioned in the constructor do
  they also use the bubbling technique?

Yes, until the dependency resolver hit the value in the current level injector


问:
How to conditionally compute difference in column values between rows in R?
I have the following data set

(this is just sample, actual data set runs into rows)

Image of the data set in also attached in the snapshot
Dataset snapshot

```<code>User    Time    Flag    TimeDifference     Expected o/p (Seconds)
A   11:39:30    1
A   11:37:53    1
A   20:44:19    1
A   22:58:42    2   Calculate time difference?  8063
A   23:01:54    1   Calculate time difference?  192
B   23:03:00    1
B   23:03:33    1
B   23:03:53    1
B   15:00:42    3   Calculate time difference   28991
B   19:35:31    2   Calculate time difference   16489
B   19:35:34    1   Calculate time difference   3
C   10:19:06    1
C   10:59:50    1
C   10:59:50    1
C   12:16:36    1
C   12:16:36    1
</code>```

I need to calculate for each user

the time difference (in seconds) between rows whenever there is a 'Flag change' and store it in a new column called 'Time difference'

i.e. whenever flag changes from 1 to 2 , or 2 to 3 , or 2 to 1, or 3 to 1 , I need to compute time difference the time column between the current row and preceding row when flag change in encountered.

I have time in hh:mm:ss format.
Is there any for-loop function I can apply here?

Help appreciated.

答:
Some preprocessing may be required earlier:

```<code>df$Time<-strptime(x = df$Time,format = "%H:%M:%S")
df$Time<-strftime(x = df$Time,format = "%H:%M:%S")
df$Time<-as.POSIXct(df$Time)

sol<-function(d){
    Time_difference<-numeric(nrow(d))
    ind<-which(diff(d$Flag)!=0)+1

    #calculate differences in time where change in Flag was detected
    Time_difference[ind]<-abs(difftime(time1 = d$Time[ind],time2 =
    d$Time[(ind-1)], units = "secs"))
    d$Time_Difference<-Time_difference
    return(d)
   }
</code>```

Now using the plyr package and ddply function, which follow the split-apply-combine principle. It will take a data frame(d) and split it by a variable("User" in this case), apply a function(sol in this case) to that subset of data.frame and then recombine it to the original data.frame(d).

```<code>ddply(.data = df,.variables = "User",.fun = sol)

#    User     Time  Flag Time_Difference
#1     A  11:39:30    1               0
#2     A  11:37:53    1               0
#3     A  20:44:19    1               0
#4     A  22:58:42    2            8063
#5     A  23:01:54    1             192
#6     B  23:03:00    1               0
#7     B  23:03:33    1               0
#8     B  23:03:53    1               0
#9     B  15:00:42    3           28991
#10    B  19:35:31    2           16489
#11    B  19:35:34    1               3
#12    C  10:19:06    1               0
#13    C  10:59:50    1               0
#14    C  10:59:50    1               0
#15    C  12:16:36    1               0
#16    C  12:16:36    1               0
</code>```

Body:
I have the following data set

(this is just sample, actual data set runs into rows)

Image of the data set in also attached in the snapshot
Dataset snapshot

User    Time    Flag    TimeDifference     Expected o/p (Seconds)
A   11:39:30    1
A   11:37:53    1
A   20:44:19    1
A   22:58:42    2   Calculate time difference?  8063
A   23:01:54    1   Calculate time difference?  192
B   23:03:00    1
B   23:03:33    1
B   23:03:53    1
B   15:00:42    3   Calculate time difference   28991
B   19:35:31    2   Calculate time difference   16489
B   19:35:34    1   Calculate time difference   3
C   10:19:06    1
C   10:59:50    1
C   10:59:50    1
C   12:16:36    1
C   12:16:36    1

I need to calculate for each user

the time difference (in seconds) between rows whenever there is a 'Flag change' and store it in a new column called 'Time difference'

i.e. whenever flag changes from 1 to 2 , or 2 to 3 , or 2 to 1, or 3 to 1 , I need to compute time difference the time column between the current row and preceding row when flag change in encountered.

I have time in hh:mm:ss format.
Is there any for-loop function I can apply here?

Help appreciated.

Body:
Some preprocessing may be required earlier:

df$Time<-strptime(x = df$Time,format = "%H:%M:%S")
df$Time<-strftime(x = df$Time,format = "%H:%M:%S")
df$Time<-as.POSIXct(df$Time)

sol<-function(d){
    Time_difference<-numeric(nrow(d))
    ind<-which(diff(d$Flag)!=0)+1

    #calculate differences in time where change in Flag was detected
    Time_difference[ind]<-abs(difftime(time1 = d$Time[ind],time2 =
    d$Time[(ind-1)], units = "secs"))
    d$Time_Difference<-Time_difference
    return(d)
   }

Now using the plyr package and ddply function, which follow the split-apply-combine principle. It will take a data frame(d) and split it by a variable("User" in this case), apply a function(sol in this case) to that subset of data.frame and then recombine it to the original data.frame(d).

ddply(.data = df,.variables = "User",.fun = sol)

#    User     Time  Flag Time_Difference
#1     A  11:39:30    1               0
#2     A  11:37:53    1               0
#3     A  20:44:19    1               0
#4     A  22:58:42    2            8063
#5     A  23:01:54    1             192
#6     B  23:03:00    1               0
#7     B  23:03:33    1               0
#8     B  23:03:53    1               0
#9     B  15:00:42    3           28991
#10    B  19:35:31    2           16489
#11    B  19:35:34    1               3
#12    C  10:19:06    1               0
#13    C  10:59:50    1               0
#14    C  10:59:50    1               0
#15    C  12:16:36    1               0
#16    C  12:16:36    1               0


问:
Limit this PHP foreach statement to just 5 loops
How could I limit this foraech statement to just 5 loops? I think I should just use Break but I'm not sure where to put it. </p>

```<code> <?php if(!empty($locations)): foreach($locations as $location):  ?>
<?php if(empty($location["title"])) continue; ?>
<li>
    <a href="<?php esc_attr_e($url.$glue.http_build_query($location["query"])) ?>">
        <?php esc_html_e($location["title"]) ?>
    </a>
    <?php if($param->count): ?>
    <div class="wpjb-widget-item-count">
        <div class="wpjb-widget-item-num"><?php echo intval($location["count"]) ?></div>
    </div>
    <?php endif; ?>
</li>
<?php endforeach; ?>
</code>```

答:
There are three methods:

Method 1: foreach with a counter var

```<code>$counter = 1;

foreach($locations as $location) {
    // use $location here

    if($counter++ == 5) {
        break;
    }

}
</code>```

Method 2: foreach using $key=>$val

```<code>foreach($locations as $key=>$val) {

    // Your content goes here
    if($key === 4) {
        break;
    }
}
</code>```

Method 3: for loop

```<code>for($i = 0; $i < 5; $i++) {
    // Use $locations[$i] here and do something with it
}
</code>```

Body:
How could I limit this foraech statement to just 5 loops? I think I should just use Break but I'm not sure where to put it.

 <?php if(!empty($locations)): foreach($locations as $location):  ?>
<?php if(empty($location["title"])) continue; ?>

    <a href="<?php esc_attr_e($url.$glue.http_build_query($location["query"])) ?>">
        <?php esc_html_e($location["title"]) ?>

    <?php if($param->count): ?>

<?php echo intval($location["count"]) ?>

    <?php endif; ?>

<?php endforeach; ?>

Body:
There are three methods:

Method 1: foreach with a counter var

$counter = 1;

foreach($locations as $location) {
    // use $location here

    if($counter++ == 5) {
        break;
    }

}

Method 2: foreach using $key=>$val

foreach($locations as $key=>$val) {

    // Your content goes here
    if($key === 4) {
        break;
    }
}

Method 3: for loop

for($i = 0; $i < 5; $i++) {
    // Use $locations[$i] here and do something with it
}


问:
trying to declare a variable local to a function, but get scope error
Here's a small snippet of my code. The purpose of the snippet you see here is twofold 1)present a menu -- that's the menu() function, and 2) prompt the user to make a selection and store it -- selection().

selection() starts on line 18.

I'm trying to declare some variables that will be local to my menu() and selection() functions, but I get errors like this, for everything I try to declare:

warning: unused variable 's'   (it gave this for all my 'char' variables)
or
error: 'snack_selection' was not declared in this scope (it gave this for the two 'int' variables I tried to declare)

but how can that be? I don't know what I'm missing.

patient feedback is appreciated.

```<code>int menu(void)
{
    cout << "Available snacks to select from: " << endl  //presents menu
         << "     " << setw(5) << "P - Potato Chips" << setw(9) << "$1.25"
         << endl  //prompts user to make a selection (until it is valid)
         << "     " << setw(5) << "S - Snickers Bar" << setw(9) << "$1.35"
         << endl
         << "     " << setw(5) << "T - Pop Tart" << setw(13) << "$0.95"
         << endl
         << "     " << setw(5) << "C - Cookies" << setw(14) << "$1.50"
         << endl
         << "     " << setw(5) << "B - Brownie" << setw(14) << "$1.75"
         << endl
         << "     " << setw(5) << "N - Nuts" << setw(17) << "$1.40"
         << endl;
    selection();
    return 0;
}

int selection(void)   //FUNCTION: welcomes, presents menu, and prompts user for selection
{

    int potato_chip_price = 125, snickers_bar_price = 135, pop_tart_price = 95, cookies_price = 150, brownie_price = 175, nuts_price = 140;
    char snack_selection = 0; //condition for snack_selection switch case statement
    char P, S, T, C, B, N;  //the char variables needed for the snack_selection

    cout << "Please enter the letter labeling your snack selection: ";
    cin >> snack_selection;
    cout << endl;

    switch(std::toupper(snack_selection))
    { //beginning of switch statement (goes through all the "legal" options so there is an "illegal" option
    case 'P': price = potato_chip_price; //setting it up this way stores the value of price with the value of potato_chip_price. if the other way around, pop_tart_price would become 0 since that is what price is set to.
        break;
    case 'S': price = snickers_bar_price; //stores the snack selection price in CENTS to the int price variable needed for the next function's argument
        break;
    case 'T': price = pop_tart_price;
        break;
    case 'C': price = cookies_price;
        break;
    case 'B': price = brownie_price;
        break;
    case 'N': price = nuts_price;
        break;
    default:
        cout << "Invalid selection!";
        menu();
    } //end of switch statement
    return(price); //needs to return some kind of value bc it isn't a void function, and compiler will give a warning
}
</code>```

full code here with superficial info removed:

```<code>#include <iostream>
#include <iomanip>
#include <cctype>
using namespace std;

//Variable Declarations

int price = 0, total_paid = 0, total_price = 0; //arguments for the three functions in the program.need to be global

//Function Declarations:

int menu(void);
// presents menu

int selection(void);
//prompts user to make selection and stores it

int accept_money(int price);
//tells user what money it accepts and the label for each type
//1. repeats back what cost is
//2. tells what  has been paid
//3. allows user to input money by payment selection here

int compute_change(int total_paid, int total_price);
//1.  tells user what total amt was paid
//2.  computes change
//3.  tells user what change will be
//4.  ask user if he or she would like another purchase (if statement. if y, send back to int menu(). if no, thank for purchase message.)

int main()
{
    cout << "Welcome to the snack vending machine" << endl << endl;

    menu();
    accept_money(price);
    compute_change(total_paid, total_price);

    return 0;
}

//Function Definitions

int menu(void)
{
    cout << "Available snacks to select from: " << endl  //presents menu
        << "     " << setw(5) << "P - Potato Chips" << setw(9) << "$1.25"
        << endl  //prompts user to make a selection (until it is valid)
        << "     " << setw(5) << "S - Snickers Bar" << setw(9) << "$1.35"
        << endl
        << "     " << setw(5) << "T - Pop Tart" << setw(13) << "$0.95" <<
        endl
        << "     " << setw(5) << "C - Cookies" << setw(14) << "$1.50" <<
        endl
        << "     " << setw(5) << "B - Brownie" << setw(14) << "$1.75" <<
        endl
        << "     " << setw(5) << "N - Nuts" << setw(17) << "$1.40" <<
        endl;
    selection();
    return 0;
}

int selection(void)   //FUNCTION: welcomes, presents menu, and prompts user for selection
{
    int potato_chip_price = 125, snickers_bar_price = 135, pop_tart_price = 95, cookies_price = 150, brownie_price = 175, nuts_price = 140;
    char snack_selection = 0; //condition for snack_selection switch case statement
    char P, S, T, C, B, N;  //the char variables needed for the snack_selection switch case statement (can't be inside function, needs to be global

    cout << "Please enter the letter labeling your snack selection: ";
    cin >> snack_selection;
    cout << endl;

    switch ( std::toupper(snack_selection) )
    { //beginning of switch statement (goes through all the "legal" options so there is an "illegal" option
    case 'P': price = potato_chip_price; //setting it up this way stores the value of price with the value of potato_chip_price. if the other way around, pop_tart_price would become 0 since that is what price is set to.
        break;
    case 'S': price = snickers_bar_price; //stores the snack selection price in CENTS to the int price variable needed for the next function's argument
        break;
    case 'T': price = pop_tart_price;
        break;
    case 'C': price = cookies_price;
        break;
    case 'B': price = brownie_price;
        break;
    case 'N': price = nuts_price;
        break;
    default:
        cout << "Invalid selection!";
        menu();
    } //end of switch statement
    return(price); //needs to return some kind of value bc it isn't a void function, and compiler will give a warning
}

int accept_money(int price)
{
    int nickel = 5, quarter = 25, dollar = 100;
    char money_selection = 0; //condition for money_selection switch case statement
    char n, q, d; //the char variables needed for the money_selection switch case statement

    cout << "Money accepted by the machine:\n"
        << "     " << setw(5) << "N - Nickel" << endl
        << "     " << setw(5) << "Q - Quarter" << endl
        << "     " << setw(5) << "D - Dollar" << endl << endl;

    do
    {
        cout << "Your selected snack item cost: " << price << " CENTS" << endl
            << "Your total inserted: " << total_paid << " CENTS" << endl
            << "Insert amount (enter letter of choice): ";
        cin >> money_selection;
        cout << endl;
        switch ( std::tolower(money_selection) )
        {
        case 'n': total_paid = nickel + total_paid;
            cout << endl;
            break;
        case 'q': total_paid = quarter + total_paid;
            cout << endl;
            break;
        case 'd': total_paid = dollar + total_paid;
            cout << endl;
            break;
        default:
            cout << money_selection << " is not recognized as a coin." << endl << endl;
        }
    } while ( total_paid < price );
    return total_paid;  //this function needs to return updated value, or any changes made to it will remain local to the function
}

int compute_change(int total_paid, int total_price)
{
    char continue_purchase = 0;
    char y;

    int change = total_paid - price; //has to have somewhere to be stored in this function to work
    int amt_inserted = total_paid; //was not using updated value of total_paid from previous fnction, so had to save it to a variable local to this one from the global variable

    cout << "Your total inserted: " << amt_inserted << " CENTS" << endl
        << "Dispensing change: " << change << setw(5) << " CENTS" << endl
        << "Would you care to make another purchase (Y/N): ";
    cin >> continue_purchase;

    switch ( std::tolower(continue_purchase) )
    {
    case 'y': total_paid = 0;
        price = 0;
        total_price = 0;
        cout << endl << endl;
        menu();
        break;
    case 'n': cout << "Thank you and enjoy your purchase!";
        break;
    default:
        cout << "Invalid Selection" << endl << endl;
        compute_change(total_paid, total_price);
    }
    return 0;
}
</code>```

答:
Apart from what everyone said in the comments about not using global variables and other good programming practices, the code itself compiles fine (unless you have -Werror switch in your compiler flags active like me.) BUT with warnings.

You seem to have misunderstood that if you are going to use the string literal 'P' in a case statement, as you are doing in the function int selection(void) , that you have to first declare a variable char P for that. You do NOT have to declare a variable for using those string literals. There is NO connection whatsoever between the variable char P and the string 'P'.

The warnings, come from these lines:

In the function int compute_change(int total_paid, int total_price) remove the following line:

```<code>char y;
</code>```

Then in the function int accept_money(int price) remove the following line:

```<code>char n, q, d; //the char variables needed for the money_selection switch case statement
</code>```

And finally in the function int selection(void)   //FUNCTION: welcomes, presents menu, and prompts user for selection

remove the following line.

```<code>char P, S, T, C, B, N;  //the char variables needed for the snack_selection switch case statement (can't be inside function, needs to be global
</code>```

You would be fine after that.

If you really really want to use those variables, P, S and so on, then you should assign them a value and declare them to be constant. I did one of the cases here, for you to see. You can do the rest along similar lines.

```<code>int compute_change(int total_paid, int total_price)
{
    char continue_purchase = 0;
    const char y = 'y';

    int change = total_paid - price; //has to have somewhere to be stored in this function to work
    int amt_inserted = total_paid; //was not using updated value of total_paid from previous fnction, so had to save it to a variable local to this one from the global variable

    cout << "Your total inserted: " << amt_inserted << " CENTS" << endl
         << "Dispensing change: " << change << setw(5) << " CENTS" <<
            endl
         << "Would you care to make another purchase (Y/N): ";
    cin >> continue_purchase;

    switch(std::tolower(continue_purchase))
    {
    case y:
        total_paid = 0;
        price = 0;
        total_price = 0;
        cout << endl << endl;
        menu();
        break;
    case 'n': cout << "Thank you and enjoy your purchase!";
        break;
    default:
        cout << "Invalid Selection" << endl << endl;
        compute_change(total_paid, total_price);
    }
    return 0;
}
</code>```

But just to make it clear, that variable y could've been named anything- it does not have to be named y to store 'y'. The code would've worked just fine if I replace that line with const char hakunamatata = 'y'

```<code>int compute_change(int total_paid, int total_price)
{
    char continue_purchase = 0;
    const char hakunamatata = 'y';

    int change = total_paid - price; //has to have somewhere to be stored in this function to work
    int amt_inserted = total_paid; //was not using updated value of total_paid from previous fnction, so had to save it to a variable local to this one from the global variable

    cout << "Your total inserted: " << amt_inserted << " CENTS" << endl
         << "Dispensing change: " << change << setw(5) << " CENTS" <<
            endl
         << "Would you care to make another purchase (Y/N): ";
    cin >> continue_purchase;

    switch(std::tolower(continue_purchase))
    {
    case hakunamatata:
        total_paid = 0;
        price = 0;
        total_price = 0;
        cout << endl << endl;
        menu();
        break;
    case 'n': cout << "Thank you and enjoy your purchase!";
        break;
    default:
        cout << "Invalid Selection" << endl << endl;
        compute_change(total_paid, total_price);
    }
    return 0;
}
</code>```

The compiler warns you about unused variables/parameters as it reveals genuine errors of oversight/omission,etc on your part (e.g. in this case as you seem to have misunderstood that declaring a char variable is needed to use a string literal containing the same text as the name of that char variable). See this question for more on that: What are the consequences of ignoring: warning: unused parameter

Hope that helps.

Body:
Here's a small snippet of my code. The purpose of the snippet you see here is twofold 1)present a menu -- that's the menu() function, and 2) prompt the user to make a selection and store it -- selection().

selection() starts on line 18.

I'm trying to declare some variables that will be local to my menu() and selection() functions, but I get errors like this, for everything I try to declare:

warning: unused variable 's'   (it gave this for all my 'char' variables)
or
error: 'snack_selection' was not declared in this scope (it gave this for the two 'int' variables I tried to declare)

but how can that be? I don't know what I'm missing.

patient feedback is appreciated.

int menu(void)
{
    cout << "Available snacks to select from: " << endl  //presents menu
         << "     " << setw(5) << "P - Potato Chips" << setw(9) << "$1.25"
         << endl  //prompts user to make a selection (until it is valid)
         << "     " << setw(5) << "S - Snickers Bar" << setw(9) << "$1.35"
         << endl
         << "     " << setw(5) << "T - Pop Tart" << setw(13) << "$0.95"
         << endl
         << "     " << setw(5) << "C - Cookies" << setw(14) << "$1.50"
         << endl
         << "     " << setw(5) << "B - Brownie" << setw(14) << "$1.75"
         << endl
         << "     " << setw(5) << "N - Nuts" << setw(17) << "$1.40"
         << endl;
    selection();
    return 0;
}

int selection(void)   //FUNCTION: welcomes, presents menu, and prompts user for selection
{

    int potato_chip_price = 125, snickers_bar_price = 135, pop_tart_price = 95, cookies_price = 150, brownie_price = 175, nuts_price = 140;
    char snack_selection = 0; //condition for snack_selection switch case statement
    char P, S, T, C, B, N;  //the char variables needed for the snack_selection

    cout << "Please enter the letter labeling your snack selection: ";
    cin >> snack_selection;
    cout << endl;

    switch(std::toupper(snack_selection))
    { //beginning of switch statement (goes through all the "legal" options so there is an "illegal" option
    case 'P': price = potato_chip_price; //setting it up this way stores the value of price with the value of potato_chip_price. if the other way around, pop_tart_price would become 0 since that is what price is set to.
        break;
    case 'S': price = snickers_bar_price; //stores the snack selection price in CENTS to the int price variable needed for the next function's argument
        break;
    case 'T': price = pop_tart_price;
        break;
    case 'C': price = cookies_price;
        break;
    case 'B': price = brownie_price;
        break;
    case 'N': price = nuts_price;
        break;
    default:
        cout << "Invalid selection!";
        menu();
    } //end of switch statement
    return(price); //needs to return some kind of value bc it isn't a void function, and compiler will give a warning
}

full code here with superficial info removed:

#include <iostream>
#include <iomanip>
#include <cctype>
using namespace std;

//Variable Declarations

int price = 0, total_paid = 0, total_price = 0; //arguments for the three functions in the program.need to be global

//Function Declarations:

int menu(void);
// presents menu

int selection(void);
//prompts user to make selection and stores it

int accept_money(int price);
//tells user what money it accepts and the label for each type
//1. repeats back what cost is
//2. tells what  has been paid
//3. allows user to input money by payment selection here

int compute_change(int total_paid, int total_price);
//1.  tells user what total amt was paid
//2.  computes change
//3.  tells user what change will be
//4.  ask user if he or she would like another purchase (if statement. if y, send back to int menu(). if no, thank for purchase message.)

int main()
{
    cout << "Welcome to the snack vending machine" << endl << endl;

    menu();
    accept_money(price);
    compute_change(total_paid, total_price);

    return 0;
}

//Function Definitions

int menu(void)
{
    cout << "Available snacks to select from: " << endl  //presents menu
        << "     " << setw(5) << "P - Potato Chips" << setw(9) << "$1.25"
        << endl  //prompts user to make a selection (until it is valid)
        << "     " << setw(5) << "S - Snickers Bar" << setw(9) << "$1.35"
        << endl
        << "     " << setw(5) << "T - Pop Tart" << setw(13) << "$0.95" <<
        endl
        << "     " << setw(5) << "C - Cookies" << setw(14) << "$1.50" <<
        endl
        << "     " << setw(5) << "B - Brownie" << setw(14) << "$1.75" <<
        endl
        << "     " << setw(5) << "N - Nuts" << setw(17) << "$1.40" <<
        endl;
    selection();
    return 0;
}

int selection(void)   //FUNCTION: welcomes, presents menu, and prompts user for selection
{
    int potato_chip_price = 125, snickers_bar_price = 135, pop_tart_price = 95, cookies_price = 150, brownie_price = 175, nuts_price = 140;
    char snack_selection = 0; //condition for snack_selection switch case statement
    char P, S, T, C, B, N;  //the char variables needed for the snack_selection switch case statement (can't be inside function, needs to be global

    cout << "Please enter the letter labeling your snack selection: ";
    cin >> snack_selection;
    cout << endl;

    switch ( std::toupper(snack_selection) )
    { //beginning of switch statement (goes through all the "legal" options so there is an "illegal" option
    case 'P': price = potato_chip_price; //setting it up this way stores the value of price with the value of potato_chip_price. if the other way around, pop_tart_price would become 0 since that is what price is set to.
        break;
    case 'S': price = snickers_bar_price; //stores the snack selection price in CENTS to the int price variable needed for the next function's argument
        break;
    case 'T': price = pop_tart_price;
        break;
    case 'C': price = cookies_price;
        break;
    case 'B': price = brownie_price;
        break;
    case 'N': price = nuts_price;
        break;
    default:
        cout << "Invalid selection!";
        menu();
    } //end of switch statement
    return(price); //needs to return some kind of value bc it isn't a void function, and compiler will give a warning
}

int accept_money(int price)
{
    int nickel = 5, quarter = 25, dollar = 100;
    char money_selection = 0; //condition for money_selection switch case statement
    char n, q, d; //the char variables needed for the money_selection switch case statement

    cout << "Money accepted by the machine:\n"
        << "     " << setw(5) << "N - Nickel" << endl
        << "     " << setw(5) << "Q - Quarter" << endl
        << "     " << setw(5) << "D - Dollar" << endl << endl;

    do
    {
        cout << "Your selected snack item cost: " << price << " CENTS" << endl
            << "Your total inserted: " << total_paid << " CENTS" << endl
            << "Insert amount (enter letter of choice): ";
        cin >> money_selection;
        cout << endl;
        switch ( std::tolower(money_selection) )
        {
        case 'n': total_paid = nickel + total_paid;
            cout << endl;
            break;
        case 'q': total_paid = quarter + total_paid;
            cout << endl;
            break;
        case 'd': total_paid = dollar + total_paid;
            cout << endl;
            break;
        default:
            cout << money_selection << " is not recognized as a coin." << endl << endl;
        }
    } while ( total_paid < price );
    return total_paid;  //this function needs to return updated value, or any changes made to it will remain local to the function
}

int compute_change(int total_paid, int total_price)
{
    char continue_purchase = 0;
    char y;

    int change = total_paid - price; //has to have somewhere to be stored in this function to work
    int amt_inserted = total_paid; //was not using updated value of total_paid from previous fnction, so had to save it to a variable local to this one from the global variable

    cout << "Your total inserted: " << amt_inserted << " CENTS" << endl
        << "Dispensing change: " << change << setw(5) << " CENTS" << endl
        << "Would you care to make another purchase (Y/N): ";
    cin >> continue_purchase;

    switch ( std::tolower(continue_purchase) )
    {
    case 'y': total_paid = 0;
        price = 0;
        total_price = 0;
        cout << endl << endl;
        menu();
        break;
    case 'n': cout << "Thank you and enjoy your purchase!";
        break;
    default:
        cout << "Invalid Selection" << endl << endl;
        compute_change(total_paid, total_price);
    }
    return 0;
}

Body:
Apart from what everyone said in the comments about not using global variables and other good programming practices, the code itself compiles fine (unless you have -Werror switch in your compiler flags active like me.) BUT with warnings.

You seem to have misunderstood that if you are going to use the string literal 'P' in a case statement, as you are doing in the function int selection(void) , that you have to first declare a variable char P for that. You do NOT have to declare a variable for using those string literals. There is NO connection whatsoever between the variable char P and the string 'P'.

The warnings, come from these lines:

In the function int compute_change(int total_paid, int total_price) remove the following line:

char y;

Then in the function int accept_money(int price) remove the following line:

char n, q, d; //the char variables needed for the money_selection switch case statement

And finally in the function int selection(void)   //FUNCTION: welcomes, presents menu, and prompts user for selection

remove the following line.

char P, S, T, C, B, N;  //the char variables needed for the snack_selection switch case statement (can't be inside function, needs to be global

You would be fine after that.

If you really really want to use those variables, P, S and so on, then you should assign them a value and declare them to be constant. I did one of the cases here, for you to see. You can do the rest along similar lines.

int compute_change(int total_paid, int total_price)
{
    char continue_purchase = 0;
    const char y = 'y';

    int change = total_paid - price; //has to have somewhere to be stored in this function to work
    int amt_inserted = total_paid; //was not using updated value of total_paid from previous fnction, so had to save it to a variable local to this one from the global variable

    cout << "Your total inserted: " << amt_inserted << " CENTS" << endl
         << "Dispensing change: " << change << setw(5) << " CENTS" <<
            endl
         << "Would you care to make another purchase (Y/N): ";
    cin >> continue_purchase;

    switch(std::tolower(continue_purchase))
    {
    case y:
        total_paid = 0;
        price = 0;
        total_price = 0;
        cout << endl << endl;
        menu();
        break;
    case 'n': cout << "Thank you and enjoy your purchase!";
        break;
    default:
        cout << "Invalid Selection" << endl << endl;
        compute_change(total_paid, total_price);
    }
    return 0;
}

But just to make it clear, that variable y could've been named anything- it does not have to be named y to store 'y'. The code would've worked just fine if I replace that line with const char hakunamatata = 'y'

int compute_change(int total_paid, int total_price)
{
    char continue_purchase = 0;
    const char hakunamatata = 'y';

    int change = total_paid - price; //has to have somewhere to be stored in this function to work
    int amt_inserted = total_paid; //was not using updated value of total_paid from previous fnction, so had to save it to a variable local to this one from the global variable

    cout << "Your total inserted: " << amt_inserted << " CENTS" << endl
         << "Dispensing change: " << change << setw(5) << " CENTS" <<
            endl
         << "Would you care to make another purchase (Y/N): ";
    cin >> continue_purchase;

    switch(std::tolower(continue_purchase))
    {
    case hakunamatata:
        total_paid = 0;
        price = 0;
        total_price = 0;
        cout << endl << endl;
        menu();
        break;
    case 'n': cout << "Thank you and enjoy your purchase!";
        break;
    default:
        cout << "Invalid Selection" << endl << endl;
        compute_change(total_paid, total_price);
    }
    return 0;
}

The compiler warns you about unused variables/parameters as it reveals genuine errors of oversight/omission,etc on your part (e.g. in this case as you seem to have misunderstood that declaring a char variable is needed to use a string literal containing the same text as the name of that char variable). See this question for more on that: What are the consequences of ignoring: warning: unused parameter

Hope that helps.


问:
Mongoose findById check if property exist
I have a Mongoose model such as;

```<code>var Schema = new Schema({
  title: { type: String, required: true },
  subtitle: { type: String, required: true },
  text: { type: String, required: true },
  image: { data: Buffer, contentType: String, name: String, size: Number, encoding: String }
</code>```

});

I perform a

```<code>let projection = "image";
Model.findById(req.params.id,projection, function (err, doc) {
  console.log(err);
  if (err) {
    res.status(422).json(err);
  }
  else {
    res.contentType(doc.image.contentType);
    res.send(doc.image.data);
  }
});
</code>```

I get the error stating that can not read property and the problem is there is no image property stored in the record. How can I ignore this, it should not matter if an image is stored or not.

Thanx in advance. :-)

答:
Try</p>

```<code> Model.findById({image:{ $exists: true}}...
</code>```

Body:
I have a Mongoose model such as;

var Schema = new Schema({
  title: { type: String, required: true },
  subtitle: { type: String, required: true },
  text: { type: String, required: true },
  image: { data: Buffer, contentType: String, name: String, size: Number, encoding: String }

});

I perform a

let projection = "image";
Model.findById(req.params.id,projection, function (err, doc) {
  console.log(err);
  if (err) {
    res.status(422).json(err);
  }
  else {
    res.contentType(doc.image.contentType);
    res.send(doc.image.data);
  }
});

I get the error stating that can not read property and the problem is there is no image property stored in the record. How can I ignore this, it should not matter if an image is stored or not.

Thanx in advance. :-)

Body:
Try

 Model.findById({image:{ $exists: true}}...