问:
Invalid module name odoo 10
I've install odoo on a ubuntu VM and on a server to start developing module but I can't install my module on my odoo, I have this error:

jourconge odoo.modules.loading: invalid module names, ignored:
  hr_hollidays_fr

I launch my odoo with this command

```<code>./odoo-bin -d jourconge --addons-path=/home/odoo/odoo/addons,/home/odoo/enterprise,/home/odoo/technical-training/09-orm --db-filter=jourconge -i hr_hollidays_fr
</code>```

I use as module name my folder name .

Addons-path are good one, I've tried to install odoo's module located in odoo/addons and it worked.

To create my module I've created the folder "fraisperso", I add the file __manifest__.py and __init__.py.

```<code># -*- coding: utf-8 -*-
</code>```

{

```<code>'name': "Public Holidays FR",

'summary': """

    Gestion des week end et jours fériés""",

'description': """

    Module qui permet la gestion des jours fériés et des week-end dans le compte des jours de congés pour une demande de congés

""",

'author': "Martin Allimonier",

# Categories can be used to filter modules in modules listing

# Check https://github.com/odoo/odoo/blob/master/odoo/addons/base/module/module_data.xml

# for the full list

'category': 'hr',

'version': '0.1',

# any module necessary for this one to work correctly

'depends': ['base', 'hr_holidays'],

# always loaded

'data': [

    # 'security/ir.model.access.csv',

],
</code>```

}

My __init__.py just import the models folder where I ve created my model and a folder views where I've put my views.

My question is what did I miss?

Thanks for helping and sorry for my bad english.

答:
So, did you not use the 'scaffold' to create that module?

Anyway, each module have two names, the technical one and the display one.

The technical one, which is the same to use with the 'i'/'u' parameter, is the folder name.

So you should replace 'hr_hollidays_fr' with 'fraisperso' or whatever you called the directory, or change your folder name to 'hr_hollidays_fr'.

Title: Invalid module name odoo 10

Body:
I've install odoo on a ubuntu VM and on a server to start developing module but I can't install my module on my odoo, I have this error:

jourconge odoo.modules.loading: invalid module names, ignored:
  hr_hollidays_fr

I launch my odoo with this command

./odoo-bin -d jourconge --addons-path=/home/odoo/odoo/addons,/home/odoo/enterprise,/home/odoo/technical-training/09-orm --db-filter=jourconge -i hr_hollidays_fr

I use as module name my folder name .

Addons-path are good one, I've tried to install odoo's module located in odoo/addons and it worked.

To create my module I've created the folder "fraisperso", I add the file __manifest__.py and __init__.py.

# -*- coding: utf-8 -*-

{

'name': "Public Holidays FR",

'summary': """

    Gestion des week end et jours fériés""",

'description': """

    Module qui permet la gestion des jours fériés et des week-end dans le compte des jours de congés pour une demande de congés

""",

'author': "Martin Allimonier",

# Categories can be used to filter modules in modules listing

# Check https://github.com/odoo/odoo/blob/master/odoo/addons/base/module/module_data.xml

# for the full list

'category': 'hr',

'version': '0.1',

# any module necessary for this one to work correctly

'depends': ['base', 'hr_holidays'],

# always loaded

'data': [

    # 'security/ir.model.access.csv',

],

}

My __init__.py just import the models folder where I ve created my model and a folder views where I've put my views.

My question is what did I miss?

Thanks for helping and sorry for my bad english.


来源: stackexchange

问:
CSS: How do I stop hover effects from pushing my text?
I hope you understood the question, you can see an example here:

http://jsfiddle.net/nFbJY/

When you scroll over any of the links they move :(

Any advice on how to solve this issue?

HTML:

```<code><div class="links">
<ul>
<li><a href="home.html">Home</a></li>
<li><a href="pricing.html">Pricing</a></li>
<li><a href="faq.html">FAQ</a></li>
<li><a href="about.html">About</a></li>
<li><a href="contact.html">Contact</a></li>
</ul>
</div>
</code>```

CSS:

div.links {float: left; padding-top:15px;}
ul {list-style:none;}
li {float: left; margin: 0 .15em; padding: 3px 10px 3px 10px; border: 1px solid #CCC;          border-radius: 5px; -moz-border-radius: 5px;}
a:hover { border: 1px solid blue; border-radius: 5px; -moz-border-radius: 5px; padding: 3px 10px 3px 10px; background-color:yellow;}
```

答:
The easiest way would be to add a margin to your a elements and add margin: 0 to a:hover. That way, the buttons are always the same width. Or, you can do someting similar with padding (or border).

EDIT: In your case, use this CSS (esp. the last 2 lines):

div.links {float: left; padding-top:15px;}
ul {list-style:none;}
li {float: left; margin: 0 .15em; padding: 3px 10px 3px 10px; border: 1px solid #CCC; border-radius: 5px; -moz-border-radius: 5px;}
a { margin: 0 11px; }
a:hover { border: 1px solid blue; margin: 0; border-radius: 5px; -moz-border-radius: 5px; padding: 3px 10px 3px 10px; background-color:yellow;}
```

ContentLicense: CC BY-SA 3.0

Body:
I hope you understood the question, you can see an example here:

http://jsfiddle.net/nFbJY/

When you scroll over any of the links they move :(

Any advice on how to solve this issue?

HTML:

Home

Pricing

FAQ

About

Contact

CSS:

div.links {float: left; padding-top:15px;}
ul {list-style:none;}
li {float: left; margin: 0 .15em; padding: 3px 10px 3px 10px; border: 1px solid #CCC;          border-radius: 5px; -moz-border-radius: 5px;}
a:hover { border: 1px solid blue; border-radius: 5px; -moz-border-radius: 5px; padding: 3px 10px 3px 10px; background-color:yellow;}


问:
How to create an RXjs RetryWhen with delay and limit on tries
I am trying to make an API call (using angular4), which retries when it fails, using retryWhen.
I want it to delay for 500 ms and retry again. This can be achieved with this code:

```<code>loadSomething(): Observable<SomeInterface> {
  return this.http.get(this.someEndpoint, commonHttpHeaders())
    .retryWhen(errors => errors.delay(500));
}
</code>```

But this will keep trying forever. How do I limit it to, let's say 10 times?

Thank you!

答:
Use

```<code>.retry(3)
</code>```

Repeats the source observable sequence the specified number of times or until it successfully terminates.

https://github.com/Reactive-Extensions/RxJS/blob/master/doc/api/core/operators/retry.md

ContentLicense: CC BY-SA 4.0

Body:
I am trying to make an API call (using angular4), which retries when it fails, using retryWhen.
I want it to delay for 500 ms and retry again. This can be achieved with this code:

loadSomething(): Observable<SomeInterface> {
  return this.http.get(this.someEndpoint, commonHttpHeaders())
    .retryWhen(errors => errors.delay(500));
}

But this will keep trying forever. How do I limit it to, let's say 10 times?

Thank you!

Body:
Use

.retry(3)

Repeats the source observable sequence the specified number of times or until it successfully terminates.

https://github.com/Reactive-Extensions/RxJS/blob/master/doc/api/core/operators/retry.md


问:
What is the most semantic way to display a street address in HTML?
I have an address that is going to be displayed on a webpage, but it is not the address for the author of the page. How should this be coded to be semantic given the w3c recommendation of:

The ADDRESS element may be used by authors to supply contact information for a document or a major part of a document such as a form. This element often appears at the beginning or end of a document.

答:
You can use the Schema.org vocabulary's PostalAddress item for this. It can be used via Microdata, RDFa, or JSON-LD.

For example, using RDFa:

```<code><div vocab="http://schema.org/" typeof="PostalAddress">
 <span property="name">Google Inc.</span>
 P.O. Box<span property="postOfficeBoxNumber">1234</span>
 <span property="addressLocality">Mountain View</span>,
 <span property="addressRegion">CA</span>
 <span property="postalCode">94043</span>
 <span property="addressCountry">United States</span>
</div>
</code>```

AFAIK, this should also be valid with <address> in place of the enclosing
:

```<code><address vocab="http://schema.org/" typeof="PostalAddress">
 <span property="name">Google Inc.</span>
 P.O. Box<span property="postOfficeBoxNumber">1234</span>
 <span property="addressLocality">Mountain View</span>,
 <span property="addressRegion">CA</span>
 <span property="postalCode">94043</span>
 <span property="addressCountry">United States</span>
</address>
</code>```

ContentLicense: CC BY-SA 2.5

Body:
You can use the Schema.org vocabulary's PostalAddress item for this. It can be used via Microdata, RDFa, or JSON-LD.

For example, using RDFa:

<div vocab="http://schema.org/" typeof="PostalAddress">
 <span property="name">Google Inc.</span>
 P.O. Box<span property="postOfficeBoxNumber">1234</span>
 <span property="addressLocality">Mountain View</span>,
 <span property="addressRegion">CA</span>
 <span property="postalCode">94043</span>
 <span property="addressCountry">United States</span>
</div>

AFAIK, this should also be valid with <address> in place of the enclosing <div>:

<address vocab="http://schema.org/" typeof="PostalAddress">
 <span property="name">Google Inc.</span>
 P.O. Box<span property="postOfficeBoxNumber">1234</span>
 <span property="addressLocality">Mountain View</span>,
 <span property="addressRegion">CA</span>
 <span property="postalCode">94043</span>
 <span property="addressCountry">United States</span>
</address>


问:
Align views to the right in ScrollView
I have a HorizontalScrollView and inside a TextView. I want the text of the TextView always aligned to the right. How can I do this?</p>

答: Add this line of code in your textView android:textAlignment="viewEnd"

Title: Align views to the right in ScrollView


问:
How to enter 'blank' values in MySQL
I am using VBA to write some values to MySQL table as rows. However, for certain columns, I want to leave them blank so that the default value of NULL can be assumed by the database.

I need to specify all column values in my SQL query. Can I write something like this (two consecutive commas represent a blank column):

```<code>SQLStr = "insert into table tablename values (12,13,19,,,,,1,,2,,5)"
</code>```

答:
You use NULL:

```<code>insert into table tablename
    values (12, 13, 19, NULL, NULL, NULL, NULL, 1, NULL, 2, NULL, 5);
</code>```

You can also use '' if the column is a string and by "blank" you mean "empty string".

I should add . . . you should always list the columns you are inserting, so it is better to write this as:

```<code>insert into table tablename(col1, col2, col3, col8, col10, col12)
    values (12, 13, 19, 1, 2, 5);
</code>```

(You don't specify what the column names are.)

By default, SQL will put NULL values in for the missing columns -- this can be prevents (using NOT NULL) or another value used (using DEFAULT).

Title: How to enter 'blank' values in MySQL

Body:
I am using VBA to write some values to MySQL table as rows. However, for certain columns, I want to leave them blank so that the default value of NULL can be assumed by the database.

I need to specify all column values in my SQL query. Can I write something like this (two consecutive commas represent a blank column):

SQLStr = "insert into table tablename values (12,13,19,,,,,1,,2,,5)"

Body:
You use NULL:

insert into table tablename
    values (12, 13, 19, NULL, NULL, NULL, NULL, 1, NULL, 2, NULL, 5);

You can also use '' if the column is a string and by "blank" you mean "empty string".

I should add . . . you should always list the columns you are inserting, so it is better to write this as:

insert into table tablename(col1, col2, col3, col8, col10, col12)
    values (12, 13, 19, 1, 2, 5);

(You don't specify what the column names are.)

By default, SQL will put NULL values in for the missing columns -- this can be prevents (using NOT NULL) or another value used (using DEFAULT).


答:
Change your CSS to this:

div.links {float: left; padding-top:15px;}
ul {list-style:none;}
li {float: left;}
a {margin: 0 .15em; padding: 3px 10px 3px 10px; border: 1px solid #CCC; border-radius: 5px; -moz-border-radius: 5px;}
a:hover {border: 1px solid blue; background-color:yellow; }
```

This way you're styling the A tag only instead of both LI and A.  So instead of the effects stacking causing padding/border on 2 elements you're only causing it on one.  Nothing gets pushed around....

Title: CSS: How do I stop hover effects from pushing my text?

Body:
Change your CSS to this:

div.links {float: left; padding-top:15px;}
ul {list-style:none;}
li {float: left;}
a {margin: 0 .15em; padding: 3px 10px 3px 10px; border: 1px solid #CCC; border-radius: 5px; -moz-border-radius: 5px;}
a:hover {border: 1px solid blue; background-color:yellow; }

This way you're styling the A tag only instead of both LI and A.  So instead of the effects stacking causing padding/border on 2 elements you're only causing it on one.  Nothing gets pushed around....


问:
How to override login of flask-security?
I want to do some customization when a user logs in. The problem is that the project is using flask-security which implicitly handles user login.
I want to check some records of users in the database when users log in.

How can I override "login" function in flask-security?

I saw a similar post, and tried it but it's not working.
Plus,  it is not exactly what I want to do.
I maybe need to stop the default behavior in case of some users.

So, is anyone having this kind of issue? How can I do it?

答:
You can override the login form when you are setting up Flask-Security:

```<code>user_datastore = SQLAlchemyUserDatastore(db, User, Role)
security = Security(app, user_datastore, login_form=CustomLoginForm)
</code>```

Then create your custom login form class that extends the default LoginForm. And override the validate function to do stuff before or after the login attempt.

```<code>from flask_security.forms import LoginForm

class CustomLoginForm(LoginForm):
    def validate(self):
        # Put code here if you want to do stuff before login attempt

        response = super(CustomLoginForm, self).validate()

        # Put code here if you want to do stuff after login attempt

        return response
</code>```

"reponse" will be True or False based on if the login was successful or not. If you want to check possible errors that occurred during the login attempt see "self.errors"

Greetings,
Kevin ;)

Body:
You can override the login form when you are setting up Flask-Security:

user_datastore = SQLAlchemyUserDatastore(db, User, Role)
security = Security(app, user_datastore, login_form=CustomLoginForm)

Then create your custom login form class that extends the default LoginForm. And override the validate function to do stuff before or after the login attempt.

from flask_security.forms import LoginForm

class CustomLoginForm(LoginForm):
    def validate(self):
        # Put code here if you want to do stuff before login attempt

        response = super(CustomLoginForm, self).validate()

        # Put code here if you want to do stuff after login attempt

        return response

"reponse" will be True or False based on if the login was successful or not. If you want to check possible errors that occurred during the login attempt see "self.errors"

Greetings,
Kevin ;)


问:
How to pass headers for an XMLHttpRequest request
I have an api which requires few headers to passed to get the response.Below is the working postman

Now Iam doing an http call to consume this and below is the code Iam using

```<code> var jobendpoint = 'http://rundeck:4440/api/14/project/Demo/jobs';
 var http = new XMLHttpRequest();
 http.open('GET',jobendpoint,false);
    http.setRequestHeader('Accept','application/json');
    http.setRequestHeader('Content-type','application/json');
    http.setRequestHeader('X-Rundeck-Auth-Token','XgTeIxQLUiv3lOSl8cXNkt4bxIGFjbzl');
 http.send();
  var joblist = http.responseText;
  http.onreadystatechange = function() {//Call a function when the state changes.
        if(http.readyState === XMLHttpRequest.DONE && http.status == 200) {
        joblist = http.responseText;
         }
        }
        return joblist
}
</code>```

But when I try this it is not working.I can see that headers are not properly passed.How can we pass those headers to this GET call.can someone help .

Updating error******
Im getting 403 forbiddden error since my headers are not properly set.Below is the screen shot of headers passed in network tab of firefox

Ive edited the headers directly in firefox n/w tab and sent the call and it worked.Below is the screen shot

How can I add the headers the way I had in second screen shot

答:
The MDN page for XMLHttpRequest.setRequestHeader() states:

For your custom fields, you may encounter "not allowed by Access-Control-Allow-Headers in preflight response" exception when you send request to cross domain. In this situation, you need set "Access-Control-Allow-Headers" in your response header at server side.

In your case, the X-Rundeck-Auth-Token header is such a custom header, and therefore this header must be listed in the Access-Control-Allow-Headers response header from the server, otherwise you'll get an error as above and the request will fail.

Accept, Accept-Language, Content-Type, Content-Length are whitelisted headers that can be set without specifying them in the Access-Control-Allow-Headers header; there's also a list of request headers that can never be set, even if they are listed.

Body:
I have an api which requires few headers to passed to get the response.Below is the working postman

Now Iam doing an http call to consume this and below is the code Iam using

 var jobendpoint = 'http://rundeck:4440/api/14/project/Demo/jobs';
 var http = new XMLHttpRequest();
 http.open('GET',jobendpoint,false);
    http.setRequestHeader('Accept','application/json');
    http.setRequestHeader('Content-type','application/json');
    http.setRequestHeader('X-Rundeck-Auth-Token','XgTeIxQLUiv3lOSl8cXNkt4bxIGFjbzl');
 http.send();
  var joblist = http.responseText;
  http.onreadystatechange = function() {//Call a function when the state changes.
        if(http.readyState === XMLHttpRequest.DONE && http.status == 200) {
        joblist = http.responseText;
         }
        }
        return joblist
}

But when I try this it is not working.I can see that headers are not properly passed.How can we pass those headers to this GET call.can someone help .

Updating error******
Im getting 403 forbiddden error since my headers are not properly set.Below is the screen shot of headers passed in network tab of firefox

Ive edited the headers directly in firefox n/w tab and sent the call and it worked.Below is the screen shot

How can I add the headers the way I had in second screen shot


问:
How Can I change listbox's textboxes apearance depending on object that goes there?
Im new here, I have built this small uwp app using binded ObservableCollection to a Listbox, I wanted to know how to change apearence of Textbox inside listbox. To be precise I have ObservableCollection which is made out of objects and one property of this object is a boolean. "UsersWithIndications.CheckedInOrOut" = boolean. I want to make it so if this boolean is true, textbox of this single User becomes green, if its false = red... Can You please show me a direction of resolving this issue? How can I access each individual textbox in this Listbox? If any more code is required, please let me know!

Xaml code for the page

App Launched, Listbox

答:
Method 1:

Using Converter

Here is the code for Converter

```<code>public class MyConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, string language)
    {
        if ((string)value == "true")
            return new SolidColorBrush(Colors.Green);
        else
            return new SolidColorBrush(Colors.Red);
    }

    public object ConvertBack(object value, Type targetType, object parameter, string language)
    {
        throw new NotImplementedException();
    }
}
</code>```

Here is the code Data Binding

```<code><Page.Resources>
    <local:MyConverter x:Key="MyConverter"/>
</Page.Resources>

<TextBlock Name="MyOutput" Text="true" Foreground="{Binding Path=Text, Converter={StaticResource MyConverter}, ElementName=MyOutput}"/>
</code>```

Method 2:

Using separate property for Foreground color

Body:
Method 1:

Using Converter

Here is the code for Converter

public class MyConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, string language)
    {
        if ((string)value == "true")
            return new SolidColorBrush(Colors.Green);
        else
            return new SolidColorBrush(Colors.Red);
    }

    public object ConvertBack(object value, Type targetType, object parameter, string language)
    {
        throw new NotImplementedException();
    }
}

Here is the code Data Binding

<Page.Resources>
    <local:MyConverter x:Key="MyConverter"/>
</Page.Resources>

<TextBlock Name="MyOutput" Text="true" Foreground="{Binding Path=Text, Converter={StaticResource MyConverter}, ElementName=MyOutput}"/>

Method 2:

Using separate property for Foreground color


问:
Azure SQL Login Password Not Complex Enough
I am trying to create a login for an external user to access one of my Azure databases.

I am unable to get past the error of:

```<code>Password validation failed. The password does not meet policy requirements because it is not complex enough.
</code>```

But, I have tried all different combinations - some are crazy complex.

This is an example of my script that fails...

```<code>CREATE LOGIN tableau WITH password='__&&**!!!!123**&&__lklkjljkjkl*&*&%^&^$%lkjlkjklhJHGJHGJ'
GO
</code>```

I have the "master" database selected and I am following instructions in this article:

How to create custom user login for Azure SQL Database

Can anyone suggest what I might be doing wrong please?

Thanks

答:
The 8-16 character limit is for Azure AD account passwords, not SQL login passwords.  This article https://learn.microsoft.com/en-us/sql/relational-databases/security/strong-passwords gives the following recommendations for strong passwords

Is between 8 and 128 characters.

Combines letters, numbers, and symbol characters within the password.

If used in an OLE DB or ODBC connection string, a login or password must not contain the following characters: [] {}() , ; ? * ! @

Body:
I am trying to create a login for an external user to access one of my Azure databases.

I am unable to get past the error of:

Password validation failed. The password does not meet policy requirements because it is not complex enough.

But, I have tried all different combinations - some are crazy complex.

This is an example of my script that fails...

CREATE LOGIN tableau WITH password='__&&**!!!!123**&&__lklkjljkjkl*&*&%^&^$%lkjlkjklhJHGJHGJ'
GO

I have the "master" database selected and I am following instructions in this article:

How to create custom user login for Azure SQL Database

Can anyone suggest what I might be doing wrong please?

Thanks


问:
C# non-class obj to JSON
I have several objects containing few variables in my js that are sent to c# with an ajax call. Is there a way to send that same object from c# to js as a json without creating a special custom c# class?
for example i have an object containing several paramaters that are sent to the db to retrieve some data. I want to be able to send those paramaters from c# so i can manipulate them on js.</p>

答:
Use anonymous type object

```<code>Var xyz = new {prop1="val1",prop2="val2"}
</code>```

Convert to json string. Return it to js.

Title: C# non-class obj to JSON

Body:
Use anonymous type object

Var xyz = new {prop1="val1",prop2="val2"}

Convert to json string. Return it to js.


问:
Web Scraping in R with loop from data.frame
```<code>library(rvest)

df <- data.frame(Links = c("Qmobile_Noir-M6", "Qmobile_Noir-A1", "Qmobile_Noir-E8"))

for(i in 1:3) {
  webpage <- read_html(paste0("https://www.whatmobile.com.pk/", df$Links[i]))
  data <- webpage %>%
    html_nodes(".specs") %>%
    .[[1]] %>%
    html_table(fill = TRUE)
}
</code>```

want to make loop works for all 3 values in df$Links but above code just download the last one, and downloaded data must also be identical with variables (may be a new column with variables name)

答:
The problem is in how you're structuring your for loop. It's much easier just to not use one in the first place, though, as R has great support for iterating over lists, like lapply and purrr::map. One version of how you could structure your data:

library(tidyverse)
library(rvest)

base_url <- "https://www.whatmobile.com.pk/"

models <- data_frame(model = c("Qmobile_Noir-M6", "Qmobile_Noir-A1", "Qmobile_Noir-E8"),
           link = paste0(base_url, model),
           page = map(link, read_html))

model_specs <- models %>%
    mutate(node = map(page, html_node, '.specs'),
           specs = map(node, html_table, header = TRUE, fill = TRUE),
           specs = map(specs, set_names, c('var1', 'var2', 'val1', 'val2'))) %>%
    select(model, specs) %>%
    unnest()

model_specs
#> # A tibble: 119 x 5
#>              model      var1       var2
#>              <chr>     <chr>      <chr>
#>  1 Qmobile_Noir-M6     Build         OS
#>  2 Qmobile_Noir-M6     Build Dimensions
#>  3 Qmobile_Noir-M6     Build     Weight
#>  4 Qmobile_Noir-M6     Build        SIM
#>  5 Qmobile_Noir-M6     Build     Colors
#>  6 Qmobile_Noir-M6 Frequency    2G Band
#>  7 Qmobile_Noir-M6 Frequency    3G Band
#>  8 Qmobile_Noir-M6 Frequency    4G Band
#>  9 Qmobile_Noir-M6 Processor        CPU
#> 10 Qmobile_Noir-M6 Processor    Chipset
#> # ... with 109 more rows, and 2 more variables: val1 <chr>, val2 <chr>
```

The data is still pretty messy, but at least it's all there.

Body:
library(rvest)

df <- data.frame(Links = c("Qmobile_Noir-M6", "Qmobile_Noir-A1", "Qmobile_Noir-E8"))

for(i in 1:3) {
  webpage <- read_html(paste0("https://www.whatmobile.com.pk/", df$Links[i]))
  data <- webpage %>%
    html_nodes(".specs") %>%
    .[[1]] %>%
    html_table(fill = TRUE)
}

want to make loop works for all 3 values in df$Links but above code just download the last one, and downloaded data must also be identical with variables (may be a new column with variables name)

Body:
The problem is in how you're structuring your for loop. It's much easier just to not use one in the first place, though, as R has great support for iterating over lists, like lapply and purrr::map. One version of how you could structure your data:

library(tidyverse)
library(rvest)

base_url <- "https://www.whatmobile.com.pk/"

models <- data_frame(model = c("Qmobile_Noir-M6", "Qmobile_Noir-A1", "Qmobile_Noir-E8"),
           link = paste0(base_url, model),
           page = map(link, read_html))

model_specs <- models %>%
    mutate(node = map(page, html_node, '.specs'),
           specs = map(node, html_table, header = TRUE, fill = TRUE),
           specs = map(specs, set_names, c('var1', 'var2', 'val1', 'val2'))) %>%
    select(model, specs) %>%
    unnest()

model_specs
#> # A tibble: 119 x 5
#>              model      var1       var2
#>              <chr>     <chr>      <chr>
#>  1 Qmobile_Noir-M6     Build         OS
#>  2 Qmobile_Noir-M6     Build Dimensions
#>  3 Qmobile_Noir-M6     Build     Weight
#>  4 Qmobile_Noir-M6     Build        SIM
#>  5 Qmobile_Noir-M6     Build     Colors
#>  6 Qmobile_Noir-M6 Frequency    2G Band
#>  7 Qmobile_Noir-M6 Frequency    3G Band
#>  8 Qmobile_Noir-M6 Frequency    4G Band
#>  9 Qmobile_Noir-M6 Processor        CPU
#> 10 Qmobile_Noir-M6 Processor    Chipset
#> # ... with 109 more rows, and 2 more variables: val1 <chr>, val2 <chr>

The data is still pretty messy, but at least it's all there.


问:
Firebase Storage Security Rule : Check if another object exists / check object's metadata
In Firebase storage security rules (not realtime database), is there any way to perform a check if another object exists at path, or another object's metadata exists?

Some background

Currently my storage security rules are set up so that users only have read access, and not write access to their /users/{userId}/ paths.

I have an admin cloud function that saves a file to /users/{userId}/necessary-file.pdf. And I don't want users to be able to modify or write this file and only cloud functions to have the right to do. To achieve this I think I can match for the filename like :

```<code>match /users/{userId}/{fileName} {
   allow write: if !fileName.matches("necessary-file.pdf")
}
</code>```

Question

Is there any way for me to only allow users to write some-other-file.pdf if they already have a necessary-file.pdf at the same path (or even somewhere else if that works better). All while still disallowing them to write necessary-file.pdf.

So is there any way for me to do something like this pseudo-code? :

```<code>match /users/{userId}/{fileName} {
   allow read: if request.auth.uid == userId;
   allow write: if (!fileName.matches("necessary-file.pdf")) && ("necessary-file.pdf".exists())
}
</code>```

As an alternative, I can have my cloud functions write a metadata to necessary-file.pdf and check for that too. is there any way I can perform something like this pseudo-code? :

```<code>allow write: if "necessary-file.pdf".metadata['canUserWrite'] == 'yesUserCan'
</code>```

Finally

What's really cool about this is that, if this is in any way remotely possible, it can be used to communicate between firebase database and firebase storage rules in a not-so-realtime way. (referring to this question here) A cloud function can listen for changes in the intended field in realtime database, and write a file to firebase storage, which firebase storage can check for.

答:
Firebase's Cloud Storage security rules can only access information about the current request and file. They don't have access to the full storage system, so can't check whether another file is present.

The reason for this is that the rules are evaluated in memory for every request. Providing access to Cloud Storage for other objects would slow the performance down, making the system unscalable. That same reason explains why you can't access the Firebase Database from the security rules.

If you want some control like this, you'll want to look in Cloud Functions for Firebase. If you have your users upload their files into a "staging" area, you can have a Cloud Function validate whether they met all prerequisites and only then move the file into the actual location (making it available for further processing or for clients to see).

Body:
In Firebase storage security rules (not realtime database), is there any way to perform a check if another object exists at path, or another object's metadata exists?

Some background

Currently my storage security rules are set up so that users only have read access, and not write access to their /users/{userId}/ paths.

I have an admin cloud function that saves a file to /users/{userId}/necessary-file.pdf. And I don't want users to be able to modify or write this file and only cloud functions to have the right to do. To achieve this I think I can match for the filename like :

match /users/{userId}/{fileName} {
   allow write: if !fileName.matches("necessary-file.pdf")
}

Question

Is there any way for me to only allow users to write some-other-file.pdf if they already have a necessary-file.pdf at the same path (or even somewhere else if that works better). All while still disallowing them to write necessary-file.pdf.

So is there any way for me to do something like this pseudo-code? :

match /users/{userId}/{fileName} {
   allow read: if request.auth.uid == userId;
   allow write: if (!fileName.matches("necessary-file.pdf")) && ("necessary-file.pdf".exists())
}

As an alternative, I can have my cloud functions write a metadata to necessary-file.pdf and check for that too. is there any way I can perform something like this pseudo-code? :

allow write: if "necessary-file.pdf".metadata['canUserWrite'] == 'yesUserCan'

Finally

What's really cool about this is that, if this is in any way remotely possible, it can be used to communicate between firebase database and firebase storage rules in a not-so-realtime way. (referring to this question here) A cloud function can listen for changes in the intended field in realtime database, and write a file to firebase storage, which firebase storage can check for.


问:
Fill matrix with function output R
I'm trying to fill a matrix with the outputs of a function at each instance of the matrix. I either get the error "replacement has length zero" or "number of items to replace is not a multiple of replacement length".

Please help!

```<code>setPoint <- function(tarray, t){
    var1 <- dim(tarray)[1] #get the length of longitudes, returns a number
    var2 <- dim(tarray)[2] #get the length of latitudes, returns a number
    empty.matrix <- matrix(nrow=var1,ncol=var2)
    for (i in 1:var1) { #i is moving from 1 to 192 (longitude)
        for (j in 1:var2) { #j moves from 1 to 145 (latitude)
            tmp.point <- tarray[i,j,]
            1my.vector <- c(1:var2)
            my.vector[j] <- thresholdYear(tmp.point, 38,t,0.8)
        }
        empty.matrix[i,] <- my.vector
    }

}
</code>```

答:
First of all, your function returns nothing. for loops in R return NULL and that's what your function returns.
Second, in the inner loop you create my.vectorand rewrite one of its values in the next instruction. The second iteration through the loop you recreate it, therefore destroying the value of the previous iteration, etc. What it seems to me that you need to do is to create it outside the inner loop. Something like the following.

```<code>setPoint <- function(tarray, t){
var1 <- dim(tarray)[1] #get the length of longitudes, returns a number
var2 <- dim(tarray)[2] #get the length of latitudes, returns a number
empty.matrix <- matrix(nrow=var1,ncol=var2)
for (i in 1:var1) { #i is moving from 1 to 192 (longitude)
      my.vector <- 1:var2
    for (j in 1:var2) { #j moves from 1 to 145 (latitude)
        tmp.point <- tarray[i,j,]
        my.vector[j] <- thresholdYear(tmp.point, 38,t,0.8)
    }
    empty.matrix[i,] <- my.vector
}
empty.matrix
</code>```

}

Title: Fill matrix with function output R

Body:
I'm trying to fill a matrix with the outputs of a function at each instance of the matrix. I either get the error "replacement has length zero" or "number of items to replace is not a multiple of replacement length".

Please help!

setPoint <- function(tarray, t){
    var1 <- dim(tarray)[1] #get the length of longitudes, returns a number
    var2 <- dim(tarray)[2] #get the length of latitudes, returns a number
    empty.matrix <- matrix(nrow=var1,ncol=var2)
    for (i in 1:var1) { #i is moving from 1 to 192 (longitude)
        for (j in 1:var2) { #j moves from 1 to 145 (latitude)
            tmp.point <- tarray[i,j,]
            1my.vector <- c(1:var2)
            my.vector[j] <- thresholdYear(tmp.point, 38,t,0.8)
        }
        empty.matrix[i,] <- my.vector
    }

}

Body:
First of all, your function returns nothing. for loops in R return NULL and that's what your function returns.
Second, in the inner loop you create my.vectorand rewrite one of its values in the next instruction. The second iteration through the loop you recreate it, therefore destroying the value of the previous iteration, etc. What it seems to me that you need to do is to create it outside the inner loop. Something like the following.

setPoint <- function(tarray, t){
var1 <- dim(tarray)[1] #get the length of longitudes, returns a number
var2 <- dim(tarray)[2] #get the length of latitudes, returns a number
empty.matrix <- matrix(nrow=var1,ncol=var2)
for (i in 1:var1) { #i is moving from 1 to 192 (longitude)
      my.vector <- 1:var2
    for (j in 1:var2) { #j moves from 1 to 145 (latitude)
        tmp.point <- tarray[i,j,]
        my.vector[j] <- thresholdYear(tmp.point, 38,t,0.8)
    }
    empty.matrix[i,] <- my.vector
}
empty.matrix

}


问:
Should I use an Enum or String in a JComboBox
Just came across a slight issue I'm confused by if someone wouldn't mind having a quick look please.

My ComboBoxes are constructed and initialised as shown below, with me thinking it would be a good idea to keep the data as enums, as the options are all fixed:

private JComboBox<JobTitle> comboBox = new JComboBox<>();

but when adding elements to the DefaultComboBoxModel I've realised that I don't want to display the options as a constant (ie I don't want the options to be displayed in capitals).

So I created my enum like this (see below) in order to call jobTitleModel.addElement(JobTitle.Architect.getName())
But obviously that isn't going to work as the ComboBox is of type enum, not string.

```<code>public enum JobTitle {
    ARCHITECT("Architect"), TOWN_PLANNER("Town Planner"), URBAN_DESIGNER("Urban Designer"), LANDSCAPE_GARDENER("Landscape Gardener");

    private final String name;

    private JobTitle(String name){
        this.name = name;
    }

    public String getName(){
         return this.name;
    }
}
</code>```

So I'm not really sure how to approach this? I could change the ComboBox and model to String, but I think I must be missing something obvious here. Thanks

答:
Use a custom renderer for your JComboBox. For example the code below uses a renderer that extends from the default list cell renderer. All it does is to get the value held in each cell of the JComboBox, a JobTitle object, extracts the name from this object, and displays the name:

```<code>JComboBox<JobTitle> jobCombo = new JComboBox<>(JobTitle.values());
jobCombo.setRenderer(new DefaultListCellRenderer() {

    public Component getListCellRendererComponent(JList<?> list,
            Object value,
            int index,
            boolean isSelected,
            boolean cellHasFocus) {
        value = ((JobTitle) value).getName();
        return super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
    }

});
</code>```

Why do this? Now if the user selects an item from the combo box, it is a full-fledged JobTitle enum object and not a String.

Regarding your comment:

If I wanted to make a method that does the above for a variety of comboBoxes and enums, is a switch the most elegant way to deal with that cast on line 9?

That's a whole new question and probably should be posted separately, but one possible solution is to give all the enums the same interface, something like:

```<code>public enum JobTitle implements Textable {
    ARCHITECT("Architect"), TOWN_PLANNER("Town Planner"), URBAN_DESIGNER(
            "Urban Designer"), LANDSCAPE_GARDENER("Landscape Gardener");

    private final String text;

    private JobTitle(String name) {
        this.text = name;
    }

    @Override
    public String getText() {
        return text;
    }
}
</code>```

```<code>public interface Textable {
    String getText();
}
</code>```

And then creating my own renderer class:

```<code>public class TextableRenderer extends DefaultListCellRenderer {
    public Component getListCellRendererComponent(JList<?> list, Object value, int index,
            boolean isSelected, boolean cellHasFocus) {

        value = ((Textable) value).getText();

        return super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
    }
}
</code>```

This will work with any enum (or class) that implements the Textable interface.

And then used:

```<code>final JComboBox<JobTitle> jobCombo = new JComboBox<>(JobTitle.values());
jobCombo.setRenderer(new TextableRenderer());
</code>```

Body:
Just came across a slight issue I'm confused by if someone wouldn't mind having a quick look please.

My ComboBoxes are constructed and initialised as shown below, with me thinking it would be a good idea to keep the data as enums, as the options are all fixed:

private JComboBox<JobTitle> comboBox = new JComboBox<>();

but when adding elements to the DefaultComboBoxModel I've realised that I don't want to display the options as a constant (ie I don't want the options to be displayed in capitals).

So I created my enum like this (see below) in order to call jobTitleModel.addElement(JobTitle.Architect.getName())
But obviously that isn't going to work as the ComboBox is of type enum, not string.

public enum JobTitle {
    ARCHITECT("Architect"), TOWN_PLANNER("Town Planner"), URBAN_DESIGNER("Urban Designer"), LANDSCAPE_GARDENER("Landscape Gardener");

    private final String name;

    private JobTitle(String name){
        this.name = name;
    }

    public String getName(){
         return this.name;
    }
}

So I'm not really sure how to approach this? I could change the ComboBox and model to String, but I think I must be missing something obvious here. Thanks

Body:
Use a custom renderer for your JComboBox. For example the code below uses a renderer that extends from the default list cell renderer. All it does is to get the value held in each cell of the JComboBox, a JobTitle object, extracts the name from this object, and displays the name:

JComboBox<JobTitle> jobCombo = new JComboBox<>(JobTitle.values());
jobCombo.setRenderer(new DefaultListCellRenderer() {

    public Component getListCellRendererComponent(JList<?> list,
            Object value,
            int index,
            boolean isSelected,
            boolean cellHasFocus) {
        value = ((JobTitle) value).getName();
        return super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
    }

});

Why do this? Now if the user selects an item from the combo box, it is a full-fledged JobTitle enum object and not a String.

Regarding your comment:

If I wanted to make a method that does the above for a variety of comboBoxes and enums, is a switch the most elegant way to deal with that cast on line 9?

That's a whole new question and probably should be posted separately, but one possible solution is to give all the enums the same interface, something like:

public enum JobTitle implements Textable {
    ARCHITECT("Architect"), TOWN_PLANNER("Town Planner"), URBAN_DESIGNER(
            "Urban Designer"), LANDSCAPE_GARDENER("Landscape Gardener");

    private final String text;

    private JobTitle(String name) {
        this.text = name;
    }

    @Override
    public String getText() {
        return text;
    }
}

public interface Textable {
    String getText();
}

And then creating my own renderer class:

public class TextableRenderer extends DefaultListCellRenderer {
    public Component getListCellRendererComponent(JList<?> list, Object value, int index,
            boolean isSelected, boolean cellHasFocus) {

        value = ((Textable) value).getText();

        return super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
    }
}

This will work with any enum (or class) that implements the Textable interface.

And then used:

final JComboBox<JobTitle> jobCombo = new JComboBox<>(JobTitle.values());
jobCombo.setRenderer(new TextableRenderer());


答:
Most of your styling resides on the li, try moving them to the  tag instead

```<code>li
{
    float: left;
    margin: 0 .15em;
}

a, a:active, a:visited {
    border: 1px solid #CCC;
    border-radius: 5px;
    -moz-border-radius: 5px;
    padding: 3px 10px 3px 10px;
}

a:hover
{
    border: 1px solid blue;
    background-color:yellow;
}
</code>```

Body:
I hope you understood the question, you can see an example here:

http://jsfiddle.net/nFbJY/

When you scroll over any of the links they move :(

Any advice on how to solve this issue?

HTML:

Home

Pricing

FAQ

About

Contact

CSS:

div.links {float: left; padding-top:15px;}
ul {list-style:none;}
li {float: left; margin: 0 .15em; padding: 3px 10px 3px 10px; border: 1px solid #CCC;          border-radius: 5px; -moz-border-radius: 5px;}
a:hover { border: 1px solid blue; border-radius: 5px; -moz-border-radius: 5px; padding: 3px 10px 3px 10px; background-color:yellow;}

Body:
Most of your styling resides on the li, try moving them to the <a> tag instead

li
{
    float: left;
    margin: 0 .15em;
}

a, a:active, a:visited {
    border: 1px solid #CCC;
    border-radius: 5px;
    -moz-border-radius: 5px;
    padding: 3px 10px 3px 10px;
}

a:hover
{
    border: 1px solid blue;
    background-color:yellow;
}


问:
Adding notebook tabs in tkinter - how do I do it with a class-based structure? (Python 3)
I wrote a tkinter application that had widgets displayed on two frames, similar to this example, which successfully runs.

```<code>from tkinter import *
from tkinter import ttk

root = Tk()
root.title("Example")

notebook = ttk.Notebook(root)
frame1 = ttk.Frame(notebook)
frame2 = ttk.Frame(notebook)
notebook.add(frame1, text="Frame One")
notebook.add(frame2, text="Frame Two")
notebook.pack()

#(The labels are examples, but the rest of the code is identical in structure).

labelA = ttk.Label(frame1, text = "This is on Frame One")
labelA.grid(column=1, row=1)

labelB = ttk.Label(frame2, text = "This is on Frame Two")
labelB.grid(column=1, row=1)

root.mainloop()
</code>```

I decided that I should try to restructure the program to use a class (which I'm admittedly not very familiar with). However, I'm unsure what I should do to allow the widgets to appear on different frames (everything else works okay). For instance, the following produces a "TypeError: init() takes from 1 to 2 positional arguments but 3 were given." So presumably I'd need to initialise with an extra argument, but I'm not sure how the notebook would be worked into that, or if that's even the approach I should be taking. (The program will run if the "frame1" and "frame2" arguments are removed from the labels, it will, however, display the same thing on both frames).

```<code>from tkinter import *
from tkinter import ttk

class MainApplication(ttk.Frame):
    def __init__(self, parent):
        ttk.Frame.__init__(self, parent)

        self.labelA = ttk.Label(self, frame1, text = "This is on Frame One")
        self.labelA.grid(column=1, row=1)

        self.labelB = ttk.Label(self, frame2, text = "This is on Frame Two")
        self.labelB.grid(column=1, row=1)

root = Tk()
root.title("Example")
notebook = ttk.Notebook(root)
frame1 = ttk.Frame(notebook)
frame2 = ttk.Frame(notebook)
notebook.add(frame1, text="Frame One")
notebook.add(frame2, text="Frame Two")
notebook.pack()
MainApplication(root).pack()
root.mainloop()
</code>```

I'm interested in a solution, but I'm also interested in learning what the class is doing differently compared to the standalone widgets.

答:
This would be one way to generalize the application as a class.  You want to eliminate the repeated code.</p>

```<code>from tkinter import *
from tkinter import ttk

class Notebook:

    def __init__(self,title):
        self.root = Tk()
        self.root.title(title)
        self.notebook = ttk.Notebook(self.root)

    def add_tab(self,title,text):
        frame = ttk.Frame(self.notebook)
        self.notebook.add(frame,text=title)
        label = ttk.Label(frame,text=text)
        label.grid(column=1,row=1)
        self.notebook.pack()

    def run(self):
        self.root.mainloop()

nb = Notebook('Example')
nb.add_tab('Frame One','This is on Frame One')
nb.add_tab('Frame Two','This is on Frame Two')
nb.run()
</code>```

Body:
I wrote a tkinter application that had widgets displayed on two frames, similar to this example, which successfully runs.

from tkinter import *
from tkinter import ttk

root = Tk()
root.title("Example")

notebook = ttk.Notebook(root)
frame1 = ttk.Frame(notebook)
frame2 = ttk.Frame(notebook)
notebook.add(frame1, text="Frame One")
notebook.add(frame2, text="Frame Two")
notebook.pack()

#(The labels are examples, but the rest of the code is identical in structure).

labelA = ttk.Label(frame1, text = "This is on Frame One")
labelA.grid(column=1, row=1)

labelB = ttk.Label(frame2, text = "This is on Frame Two")
labelB.grid(column=1, row=1)

root.mainloop()

I decided that I should try to restructure the program to use a class (which I'm admittedly not very familiar with). However, I'm unsure what I should do to allow the widgets to appear on different frames (everything else works okay). For instance, the following produces a "TypeError: init() takes from 1 to 2 positional arguments but 3 were given." So presumably I'd need to initialise with an extra argument, but I'm not sure how the notebook would be worked into that, or if that's even the approach I should be taking. (The program will run if the "frame1" and "frame2" arguments are removed from the labels, it will, however, display the same thing on both frames).

from tkinter import *
from tkinter import ttk

class MainApplication(ttk.Frame):
    def __init__(self, parent):
        ttk.Frame.__init__(self, parent)

        self.labelA = ttk.Label(self, frame1, text = "This is on Frame One")
        self.labelA.grid(column=1, row=1)

        self.labelB = ttk.Label(self, frame2, text = "This is on Frame Two")
        self.labelB.grid(column=1, row=1)

root = Tk()
root.title("Example")
notebook = ttk.Notebook(root)
frame1 = ttk.Frame(notebook)
frame2 = ttk.Frame(notebook)
notebook.add(frame1, text="Frame One")
notebook.add(frame2, text="Frame Two")
notebook.pack()
MainApplication(root).pack()
root.mainloop()

I'm interested in a solution, but I'm also interested in learning what the class is doing differently compared to the standalone widgets.

Body:
This would be one way to generalize the application as a class.  You want to eliminate the repeated code.

from tkinter import *
from tkinter import ttk

class Notebook:

    def __init__(self,title):
        self.root = Tk()
        self.root.title(title)
        self.notebook = ttk.Notebook(self.root)

    def add_tab(self,title,text):
        frame = ttk.Frame(self.notebook)
        self.notebook.add(frame,text=title)
        label = ttk.Label(frame,text=text)
        label.grid(column=1,row=1)
        self.notebook.pack()

    def run(self):
        self.root.mainloop()

nb = Notebook('Example')
nb.add_tab('Frame One','This is on Frame One')
nb.add_tab('Frame Two','This is on Frame Two')
nb.run()


问:
Why does Foundation recommend adding a tabindex="0" to main content?
In Foundation's docs on creating skip links, they recommend adding tabindex="0" to the element that represents the main content to skip to. I'm a bit confused as to why they would say that. As far as I can see, this results in an extra element receiving focus when tabbing through the document, even though there's not really anything to do with that element focused.

Is the reason perhaps compatibility with older browsers that don't support anchoring to ids? Or is there another reason?

Update: It should soon no longer say the above anymore, but that's because I changed it in response to the answers here :P

答:
You should set tabindex to the -1 value in order for the element to be programmatically focusable but not to be included in the tab order (in opposite to the 0 value).

If your anchor targets an unfocusable element then, the window will scroll to this element but a next press on the tab key will focus the next element after the skip link button.

See for instance the definition of focusable according to the W3C:

The element's tabindex focus flag is set.


问:
Excel Formula to get Accounting Day like Day 0, Day 1, Day 2 till Day 5 Excluding Weekends
```<code>Date        Status          LastWorkingDate
7/3/2017    Day 0           7/3/2017
7/1/2017    Day 1           7/3/2017
7/2/2017    Day 1           7/3/2017
6/30/2017   Day 1           7/3/2017
6/29/2017   Day 2           7/3/2017
6/28/2017   Day 3           7/3/2017
6/27/2017   Day 4           7/3/2017
6/26/2017   Day 5           7/3/2017
6/25/2017   Day 6           7/3/2017
6/24/2017   Day 6           7/3/2017
6/23/2017   Day 6           7/3/2017
6/22/2017   More than Day 6 7/3/2017
7/4/2017    Day 0           7/4/2017
7/3/2017    Day 1           7/4/2017
7/2/2017    Day 2           7/4/2017
7/1/2017    Day 2           7/4/2017
6/30/2017   Day 2           7/4/2017
6/29/2017   Day 3           7/4/2017
6/28/2017   Day 4           7/4/2017
6/27/2017   Day 5           7/4/2017
6/26/2017   Day 6           7/4/2017
6/25/2017   More than Day 6 7/4/2017
</code>```

i have tried using =
IF(NETWORKDAYS(E21,G21)-1=0,"day 0",IF(NETWORKDAYS(E21,G21)-1=1,"Day 1",IF(NETWORKDAYS(E21,G21)-1=2,"Day 2",IF(NETWORKDAYS(E21,G21)-1=3,"Day 3",IF(NETWORKDAYS(E21,G21)-1=4,"Day 4",IF(NETWORKDAYS(E21,G21)-1=5,"Day 5","Greater than 5 Days"))))))
but not getting desired output.

All i want is Day 0 to Day 5 based on two date columns(Date and LAstWorkingDate).

Day 0  = if today is monday then lastworkingdate will be friday and friday, Sat and Sunday will become Day 0 and previous week's thursday will be Day 1 and so on

Day 1 = if today is Tuesday then Lastworking Date will be Monday and Monday will become Day 0, Friday,Sat and Sunday will be Day 1 and so on

Day 2 = if today is wednesday ten Lastworkind Date will be Tuesday and Tuesday will become Day 0, Monday - Day 1, Friday, Sat and Sunday wull be Day 2 and so on
.
.
.

Body:
Date        Status          LastWorkingDate
7/3/2017    Day 0           7/3/2017
7/1/2017    Day 1           7/3/2017
7/2/2017    Day 1           7/3/2017
6/30/2017   Day 1           7/3/2017
6/29/2017   Day 2           7/3/2017
6/28/2017   Day 3           7/3/2017
6/27/2017   Day 4           7/3/2017
6/26/2017   Day 5           7/3/2017
6/25/2017   Day 6           7/3/2017
6/24/2017   Day 6           7/3/2017
6/23/2017   Day 6           7/3/2017
6/22/2017   More than Day 6 7/3/2017
7/4/2017    Day 0           7/4/2017
7/3/2017    Day 1           7/4/2017
7/2/2017    Day 2           7/4/2017
7/1/2017    Day 2           7/4/2017
6/30/2017   Day 2           7/4/2017
6/29/2017   Day 3           7/4/2017
6/28/2017   Day 4           7/4/2017
6/27/2017   Day 5           7/4/2017
6/26/2017   Day 6           7/4/2017
6/25/2017   More than Day 6 7/4/2017

i have tried using =
IF(NETWORKDAYS(E21,G21)-1=0,"day 0",IF(NETWORKDAYS(E21,G21)-1=1,"Day 1",IF(NETWORKDAYS(E21,G21)-1=2,"Day 2",IF(NETWORKDAYS(E21,G21)-1=3,"Day 3",IF(NETWORKDAYS(E21,G21)-1=4,"Day 4",IF(NETWORKDAYS(E21,G21)-1=5,"Day 5","Greater than 5 Days"))))))
but not getting desired output.

All i want is Day 0 to Day 5 based on two date columns(Date and LAstWorkingDate).

Day 0  = if today is monday then lastworkingdate will be friday and friday, Sat and Sunday will become Day 0 and previous week's thursday will be Day 1 and so on

Day 1 = if today is Tuesday then Lastworking Date will be Monday and Monday will become Day 0, Friday,Sat and Sunday will be Day 1 and so on

Day 2 = if today is wednesday ten Lastworkind Date will be Tuesday and Tuesday will become Day 0, Monday - Day 1, Friday, Sat and Sunday wull be Day 2 and so on
.
.
.

Body:
How about:

="Day "&(NETWORKDAYS(IF(WEEKDAY(A1,2)=7,A1-2,IF(WEEKDAY(A1,2)=6,A1-1,A1)),C1)-1)

Using your current layout for Last Working Day and Date.
The weekday functions are needed because otherwise the Saturday and Sunday would get the same value as Monday instead of Friday.

Of course you can wrap the whole thing in an IF-formula to make sure you display "Greater than 5 days" when the value is bigger than 5.

Output:

Date     | Formula column | Last working day
--------------------------------------------
6/17/2017| Day 11         | 7/3/2017  'Weekend
6/18/2017| Day 11         | 7/3/2017  'Weekend
6/19/2017| Day 10         | 7/3/2017
6/20/2017| Day 9          | 7/3/2017
6/21/2017| Day 8          | 7/3/2017
6/22/2017| Day 7          | 7/3/2017
6/23/2017| Day 6          | 7/3/2017
6/24/2017| Day 6          | 7/3/2017  'Weekend
6/25/2017| Day 6          | 7/3/2017  'Weekend
6/26/2017| Day 5          | 7/3/2017
6/27/2017| Day 4          | 7/3/2017
6/28/2017| Day 3          | 7/3/2017
6/29/2017| Day 2          | 7/3/2017
6/30/2017| Day 1          | 7/3/2017
7/1/2017 | Day 1          | 7/3/2017  'Weekend
7/2/2017 | Day 1          | 7/3/2017  'Weekend
7/3/2017 | Day 0          | 7/3/2017


问:
JS assign array with objects values to object keys
I have an array with objects and an object.
I want to use the array's every value parameters as the second object values.

here is the array:

```<code>attributes = [
        {key: 'Wifi', value: true},
        {key: 'Parking', value: false},
        {key: 'Pets', value: false},
        {key: 'Restaurant', value: false},
        {key: 'Bar', value: false},
        {key: 'Swimming pool', value: false},
        {key: 'Air conditioning', value: false},
        {key: 'Gym', value: true},
    ]
</code>```

and here is the object:

```<code>data = {
        type: 'hotels',
        id: '11',
        attributes: {
                has_wifi: false,
                has_parking: false,
                has_pets: false,
                has_restaurant: false,
                has_bar: false,
                has_swimming_pool: false,
                has_air_conditioning: false,
                hsa_gym: false,
                name: '',
                main_image_src: 'https://placebear.com/300/300',
                meal_plan: '',
                user_id: '1',
                booking_id: '1',
                amount: '5000',
                currency: 'HUF',
                status: 'pending',
                stars: ''
        }
</code>```

So i want to make the 'has_wifi' parameter to be equal with the 'Wifi', which is true in this case.
expected output:

```<code>...has_wifi: false,
                has_parking: true,
                has_pets: false,
                has_restaurant: false,
                has_bar: false,
                has_swimming_pool: false,
                has_air_conditioning: false,
                hsa_gym: true,...
</code>```

Thanks!

I tried these:

```<code>for (let i = 0; i < 8; i++) {
         this.hotelservice.hotel.data.attributes[i] = this.hotelAttributes.data.attributes[i].value;
    }

this.hotelAttributes.data.attributes.forEach ((attr, index) => {
        this.hotelservice.hotel.data.attributes[index] = attr.value;
    })
</code>```

答:
Iterate over attributes and construct corresponding key by replacing spaces with underscores.

```<code>attributes.forEach(({key, value}) => {
    data.attributes[`has_${key.toLowerCase().replace(/\s+/g,'_')}`] = value
})
</code>```

attributes = [
        {key: 'Wifi', value: true},
        {key: 'Parking', value: false},
        {key: 'Pets', value: false},
        {key: 'Restaurant', value: false},
        {key: 'Bar', value: false},
        {key: 'Swimming pool', value: false},
        {key: 'Air conditioning', value: false},
        {key: 'Gym', value: true},
    ]

data = {
        type: 'hotels',
        id: '11',
        attributes: {
                has_wifi: false,
                has_parking: false,
                has_pets: false,
                has_restaurant: false,
                has_bar: false,
                has_swimming_pool: false,
                has_air_conditioning: false,
                hsa_gym: false,
                name: '',
                main_image_src: 'https://placebear.com/300/300',
                meal_plan: '',
                user_id: '1',
                booking_id: '1',
                amount: '5000',
                currency: 'HUF',
                status: 'pending',
                stars: ''
        }
}

attributes.forEach(({key, value}) => {
    data.attributes[`has_${key.toLowerCase().replace(/\s+/g,'_')}`] = value
})

console.log(data.attributes)```

Body:
I have an array with objects and an object.
I want to use the array's every value parameters as the second object values.

here is the array:

attributes = [
        {key: 'Wifi', value: true},
        {key: 'Parking', value: false},
        {key: 'Pets', value: false},
        {key: 'Restaurant', value: false},
        {key: 'Bar', value: false},
        {key: 'Swimming pool', value: false},
        {key: 'Air conditioning', value: false},
        {key: 'Gym', value: true},
    ]

and here is the object:

data = {
        type: 'hotels',
        id: '11',
        attributes: {
                has_wifi: false,
                has_parking: false,
                has_pets: false,
                has_restaurant: false,
                has_bar: false,
                has_swimming_pool: false,
                has_air_conditioning: false,
                hsa_gym: false,
                name: '',
                main_image_src: 'https://placebear.com/300/300',
                meal_plan: '',
                user_id: '1',
                booking_id: '1',
                amount: '5000',
                currency: 'HUF',
                status: 'pending',
                stars: ''
        }

So i want to make the 'has_wifi' parameter to be equal with the 'Wifi', which is true in this case.
expected output:

...has_wifi: false,
                has_parking: true,
                has_pets: false,
                has_restaurant: false,
                has_bar: false,
                has_swimming_pool: false,
                has_air_conditioning: false,
                hsa_gym: true,...

Thanks!

I tried these:

for (let i = 0; i < 8; i++) {
         this.hotelservice.hotel.data.attributes[i] = this.hotelAttributes.data.attributes[i].value;
    }

this.hotelAttributes.data.attributes.forEach ((attr, index) => {
        this.hotelservice.hotel.data.attributes[index] = attr.value;
    })

Body:
Iterate over attributes and construct corresponding key by replacing spaces with underscores.

attributes.forEach(({key, value}) => {
    data.attributes[`has_${key.toLowerCase().replace(/\s+/g,'_')}`] = value
})

attributes = [
        {key: 'Wifi', value: true},
        {key: 'Parking', value: false},
        {key: 'Pets', value: false},
        {key: 'Restaurant', value: false},
        {key: 'Bar', value: false},
        {key: 'Swimming pool', value: false},
        {key: 'Air conditioning', value: false},
        {key: 'Gym', value: true},
    ]

data = {
        type: 'hotels',
        id: '11',
        attributes: {
                has_wifi: false,
                has_parking: false,
                has_pets: false,
                has_restaurant: false,
                has_bar: false,
                has_swimming_pool: false,
                has_air_conditioning: false,
                hsa_gym: false,
                name: '',
                main_image_src: 'https://placebear.com/300/300',
                meal_plan: '',
                user_id: '1',
                booking_id: '1',
                amount: '5000',
                currency: 'HUF',
                status: 'pending',
                stars: ''
        }
}

attributes.forEach(({key, value}) => {
    data.attributes[`has_${key.toLowerCase().replace(/\s+/g,'_')}`] = value
})

console.log(data.attributes)


问:
Detect undefined symbols in C header file
Suposse I coded a C library which provides a bunch of "public" functions, declared in a mylib.h header file. Those functions are supposedly implemented in (say) a mylib.c file which is compiled to a (say) static lib mylib.c -> mylib.o -> mylib.a.

Is there some way to detect that I forgot to provide the implementation of some declared function in mylib.h? (Yes, I know about unit testing, good practices, etc - and, yes, I understand the meaning of a plain function declaration in C).

Suppose mylib.h declares a void func1(); and this function was not coded in the provided library. This will trigger an error only  if the linker needs to use that function. Otherwise, it will compile ok and even without warnings - AFAIK. Is there a way (perhaps compiler dependent) to trigger a warning for declared but not implemented functions, or there is any other way to deal with this issue?

BTW: nm -u lists not all undefined declared functions, but only those "used" by the library, i.e., those functions that will trigger an error in the linking phase if not declared somewhere. (Which makes sense, the library object file does not know about header files, of course.)

答:
There's no easy way.

For example, you can analyse the output of clang  -Xclang -ast-print-xml or gcc-xml and filter out declarations with no implementations for a given .h file.


问:
Shifting around the image in bootstrap
Hi i know this is an amateur question, but i have some trouble.

This is my CSS`:

body{
 background-image: url(street-photography1.jpg);
 background-size: cover;
 color: white;
 background-repeat: no-repeat;
 background-position:center;
 background-attachment: fixed;
}
form{
 background-color: rgba(19, 18, 18, 0.66);
 color: white;
 padding: 40px;
 margin-top: 200px;
 padding-bottom: 60px;

}
.form-control{
 background-color: rgba(14, 14, 14, 0.35);
 border-radius: 0px;
 color: white;
}
.logo1{
 padding: 40px;
 margin-top: 200px;

}
h1{
 text-align: center;
}

.btn{
 width: 100%;
 margin-top: 20px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
    <title>Bootstrap 101 Template</title>
 <!-- Latest compiled and minified CSS -->
 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

 <!-- Optional theme -->
 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">

 <!-- Latest compiled and minified JavaScript -->
     <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>

 <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>

    <!-- Bootstrap -->

    <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
    <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
    <!--[if lt IE 9]>
      <script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script>
      <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
    <![endif]-->
 <link rel="stylesheet" type="text/css" href="style2.css" />
  </head>
  <body>

 <div class="container">
 <div class="column">
 <div class=" col-sm-5">
 <img class="logo1" src="images/capture.png" alt=" logo">
 </div>
 </div>

 <div class="row">

   <div class="col-sm-offset-6 col-sm-7">

    <form>

     <h1>Hello, world!</h1>
      <div class="form-group">
     <label for="exampleInputEmail1">Email address</label>
     <input type="email" class="form-control" id="exampleInputEmail1" placeholder="Email">
      </div>
      <div class="form-group">
     <label for="exampleInputPassword1">Password</label>
     <input type="password" class="form-control" id="exampleInputPassword1" placeholder="Password">
      </div>

      <div class="checkbox">
     <label>
       <input type="checkbox"> Remember Password
     </label>
      </div>
      <button type="submit" class="btn btn-default">Submit</button>
    </form>

   </div>
  </div>
  <footer class="container">
    <div class="row">
      <p class="col-sm-5">
      Copyright © 2016 , Singapore. All rights reserved.</p>

    </div>
  </footer>

  </body>
</html></code>```

So currently my webpage looks like this.

How can i shift my message logo so that the logo and my validation form are in the same line with each other?

答:
Try adding col-sm-offset-6 to the logo container if you want to align them vertically.

```<code><div class="col-sm-offset-6 col-sm-5">
<img class="logo1" src="images/capture.png" alt=" logo">
</div>
</code>```

Or, if you want them aligned horizontally, the answer posted by @DPalmquist should do it.

Title: Shifting around the image in bootstrap

Body:
Hi i know this is an amateur question, but i have some trouble.

This is my CSS`:

body{
 background-image: url(street-photography1.jpg);
 background-size: cover;
 color: white;
 background-repeat: no-repeat;
 background-position:center;
 background-attachment: fixed;
}
form{
 background-color: rgba(19, 18, 18, 0.66);
 color: white;
 padding: 40px;
 margin-top: 200px;
 padding-bottom: 60px;

}
.form-control{
 background-color: rgba(14, 14, 14, 0.35);
 border-radius: 0px;
 color: white;
}
.logo1{
 padding: 40px;
 margin-top: 200px;

}
h1{
 text-align: center;
}

.btn{
 width: 100%;
 margin-top: 20px;
}

<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>Bootstrap 101 Template</title>

 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">

 <link rel="stylesheet" type="text/css" href="style2.css" />

    <form>

Hello, world!

     Email address
     <input type="email" class="form-control" id="exampleInputEmail1" placeholder="Email">

     Password
     <input type="password" class="form-control" id="exampleInputPassword1" placeholder="Password">

       <input type="checkbox"> Remember Password

      <button type="submit" class="btn btn-default">Submit</button>
    </form>

      Copyright © 2016 , Singapore. All rights reserved.

So currently my webpage looks like this.

How can i shift my message logo so that the logo and my validation form are in the same line with each other?

Body:
Try adding col-sm-offset-6 to the logo container if you want to align them vertically.

<div class="col-sm-offset-6 col-sm-5">
<img class="logo1" src="images/capture.png" alt=" logo">
</div>

Or, if you want them aligned horizontally, the answer posted by @DPalmquist should do it.


问:
Android studio cant recognize phone in charging mode
Ok so I have this wired problem. I have a newly installed android studio and latest usb SDK installed. I have connected my phone through USB and android studio cant recognize my phone, but when I switch to file transfer it works perfectly. this is kinda annoying I need to choose file transfer mode every time I check for output. this seems strange and I have gone through several article but none of them seems have this problem.

Feel free to share your thoughts.

答:
This is not a Exact Solution for your problem. But alternatively it will give solution for you.

In Android Setting-> Developer Option -> Select USB Configuration you can choose File Transfer mode as Default one. So that you no need to change at every time.

Hope it will Help you!!!


问:
Date check on form not working
I have a form with datepickers. On Submit I call $('#form').on('submit') to check the dates choosen in the pickers against a sharpoint list with booked dates. I have a method that retrives these dates with Ajax. My problem is when I check the dates with an IF statment in a For loop the form.submit gets hit even thou it shouldnt. I want to Break from the loop when the dateCheck hits a booked date. But I dont now where to put the form.submit so it dosent get hit by mistake. i did trie with an IF around the form.submit to check if an array contains any booked dates.  but no luck. Thanks for all the help in advance!!

```<code>if ($("#startDatePicker").datepicker("getDate") !== null) {

  if (!$("#enddate").is(":hidden") &&
    $("#endDatePicker").datepicker("getDate") === null) {

    $("#infoModal h4").text("Hint");
    $("#infoModal p").text("Please select a End date");
    $("#infoModal").modal("show");

  } else {

    var bookedDates = [];
    //ForLoop för som kollar alla datum mot valda datum
    for (var i = 0; i < parsedDates.length; i++) {

      if (dateCheck(start, end, parsedDates[i])) {
        $("#infoModal h4").text("Validation error");
        $("#infoModal p")
          .text("You have entered a busy date or interval that overlaps an already booked date.");
        $("#infoModal").modal("show");
        bookedDates.push(parsedDates[i]);
        break;

      }

      if (!$.isArray(bookedDates) || !bookedDates.length) {
        form.submit();
      }
    } //parsedDates loop

  } //endDatePicker != hidden && endDatePicker != null

} //StartDatePicker != null
</code>```

答:
I am not 100% sure , but as per my understanding you want to submit the form when in bookedDates Array has some value(date) in it.
Your below condition results in TRUE when there is no date in array like

```<code>!$.isArray(bookedDates) -> false (As it's a array)
!bookedDates.length -> true  (if no date is push in array then value is 0 and !0 -> True and form will submit.
 if (!$.isArray(bookedDates)||!bookedDates.length) {
      form.submit();
    }
</code>```

i will suggest you to put the below if condition outside the for loop.

```<code> if ($.isArray(bookedDates) && bookedDates.length) {
      form.submit();
    }

$.isArray(bookedDates): it should be a array
bookedDates.length : and Must have one date inside the array.
</code>```

Title: Date check on form not working

Body:
I have a form with datepickers. On Submit I call $('#form').on('submit') to check the dates choosen in the pickers against a sharpoint list with booked dates. I have a method that retrives these dates with Ajax. My problem is when I check the dates with an IF statment in a For loop the form.submit gets hit even thou it shouldnt. I want to Break from the loop when the dateCheck hits a booked date. But I dont now where to put the form.submit so it dosent get hit by mistake. i did trie with an IF around the form.submit to check if an array contains any booked dates.  but no luck. Thanks for all the help in advance!!

if ($("#startDatePicker").datepicker("getDate") !== null) {

  if (!$("#enddate").is(":hidden") &&
    $("#endDatePicker").datepicker("getDate") === null) {

    $("#infoModal h4").text("Hint");
    $("#infoModal p").text("Please select a End date");
    $("#infoModal").modal("show");

  } else {

    var bookedDates = [];
    //ForLoop för som kollar alla datum mot valda datum
    for (var i = 0; i < parsedDates.length; i++) {

      if (dateCheck(start, end, parsedDates[i])) {
        $("#infoModal h4").text("Validation error");
        $("#infoModal p")
          .text("You have entered a busy date or interval that overlaps an already booked date.");
        $("#infoModal").modal("show");
        bookedDates.push(parsedDates[i]);
        break;

      }

      if (!$.isArray(bookedDates) || !bookedDates.length) {
        form.submit();
      }
    } //parsedDates loop

  } //endDatePicker != hidden && endDatePicker != null

} //StartDatePicker != null

Body:
I am not 100% sure , but as per my understanding you want to submit the form when in bookedDates Array has some value(date) in it.
Your below condition results in TRUE when there is no date in array like

!$.isArray(bookedDates) -> false (As it's a array)
!bookedDates.length -> true  (if no date is push in array then value is 0 and !0 -> True and form will submit.
 if (!$.isArray(bookedDates)||!bookedDates.length) {
      form.submit();
    }

i will suggest you to put the below if condition outside the for loop.

 if ($.isArray(bookedDates) && bookedDates.length) {
      form.submit();
    }

$.isArray(bookedDates): it should be a array
bookedDates.length : and Must have one date inside the array.


问:
"for loop" with two variables?
How can I include two variables in the same for loop?

```<code>t1 = [a list of integers, strings and lists]
t2 = [another list of integers, strings and lists]

def f(t):  #a function that will read lists "t1" and "t2" and return all elements that are identical
    for i in range(len(t1)) and for j in range(len(t2)):
        ...
</code>```

答:
"Python 3."

Add 2 vars with for loop using zip and range; Returning a list.

Note: Will only run till smallest range ends.

```<code>>>>a=[g+h for g,h in zip(range(10), range(10))]
>>>a
>>>[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
</code>```

Title: "for loop" with two variables?

Body:
How can I include two variables in the same for loop?

t1 = [a list of integers, strings and lists]
t2 = [another list of integers, strings and lists]

def f(t):  #a function that will read lists "t1" and "t2" and return all elements that are identical
    for i in range(len(t1)) and for j in range(len(t2)):
        ...

Body:
"Python 3."

Add 2 vars with for loop using zip and range; Returning a list.

Note: Will only run till smallest range ends.

>>>a=[g+h for g,h in zip(range(10), range(10))]
>>>a
>>>[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]


答:
You're just using the index of the array, not the adapted property name you want to create on the target object. Read key and value from the array and assign them in a loop to the object:</p>

```<code>function keyFormat(k) {
    return 'has_'+k.toLowerCase().replace(/ /g, '_');
}

for (var {key, value} of this.hotelAttributes.data.attributes)
    this.hotelservice.hotel.data.attributes[keyFormat(key)] = value;
}
</code>```

Title: JS assign array with objects values to object keys

Body:
You're just using the index of the array, not the adapted property name you want to create on the target object. Read key and value from the array and assign them in a loop to the object:

function keyFormat(k) {
    return 'has_'+k.toLowerCase().replace(/ /g, '_');
}

for (var {key, value} of this.hotelAttributes.data.attributes)
    this.hotelservice.hotel.data.attributes[keyFormat(key)] = value;
}


问:
Federated authentication and session management
When you login to Identityserver the authentication cookie idsrv is stored in the browser. When the user logs out, the cookie is deleted. However, an attacker can steal the cookie and essentially use it even though the user has logged out.

This seems to be "normal" behavior for many identity providers too.

Question

Is it accepted behavior?

Is there anyway to detect that the user has logged out and that the idsrv cookie value (token) is no longer valid? Should we for example implement IAuthenticationSessionValidator to keep track of the users that are signed out? Or is this something that should belong to the application by using the id_token session_state claim?

答: According to OWASP ASVS requirement 3.2 Sessions should be invalidated on user logout it should not be possible to use the same cookie after logging out of the application. This also is the case if using other identity providers like ADFS and AAD.  </p>


问:
Visual Studio 2015 Corrupted Uninstallation/Installation
I was installing Visual Studio 2015 Enterprise and sometime in installation, it took too much time in same place and I thought it's stucked and wanted to cancel it. But it also took too much time and I force quit the uninstallation with ctrl+alt+del. After that I deleted installation folder with shift+del as if I'm ignorant...

Now I can't install or uninstall VS 2015 properly. When I try to install it again it quits with lots of errors (package failures) plus installation path is greyed out.

I also tried to install 2015 Community Version, but it says Visual Studio 2015 is already installed.

Do you know how to fully uninstall it?

答:
I'd look into using Microsoft's official Visual Studio Uninstaller. Try following these instructions:

```<code>Using Total Uninstall:

Download and unzip the zip file to a folder.
Open cmd.exe with Administrative privileges
Execute Setup.ForcedUninstall.exe
Press Y and hit enter to run the application.
If the application ask to reboot the system, please reboot the system, and rerun this application again.
</code>```

If this fails to work, try referencing any of the other methods listed in this following document

Please Note that this isn't for VS Code's 2017 documentation, which can be found here. That being said, I don't think the newest docs have what you desire. Lemme know how it works!

Body:
I'd look into using Microsoft's official Visual Studio Uninstaller. Try following these instructions:

Using Total Uninstall:

Download and unzip the zip file to a folder.
Open cmd.exe with Administrative privileges
Execute Setup.ForcedUninstall.exe
Press Y and hit enter to run the application.
If the application ask to reboot the system, please reboot the system, and rerun this application again.

If this fails to work, try referencing any of the other methods listed in this following document

Please Note that this isn't for VS Code's 2017 documentation, which can be found here. That being said, I don't think the newest docs have what you desire. Lemme know how it works!


问:
PHP foreach array strange behavior
I have code with two foreach, first with &, second without:

```<code>$a = array(1, 2);

foreach ( $a as &$v ) {
    $v *= 1;
}

print_r($a); // output: array(1, 2)

$b = array();

foreach ( $a as $v ) {
    $b[] = $v;
}

print_r($b); // output: array(1, 1)
</code>```

Why in second foreach $v always = 1 and array b is (1, 1) instead (1, 2)?

答:
You are changing the value of $a[1] in the first loop of the second foreach, if you do a var_dump instead, you get output that indicates it is a reference:

```<code>array(2) {
  [0]=>
  int(1)
  [1]=>
  &int(2)
}
</code>```

So, on the second foreach $a[1] (which is actually &$v; becomes 1), which then is the second value that comes out of $a in the loop, because it is actually:

```<code>$a[
   1,
   &$v
];
</code>```

If you were to reassign $v after the loop, you would get the new value in the array instead:

```<code><?php

$a = [1, 2];
foreach ( $a as &$v ) {
    $v = $v;
}
var_dump($a); // output: array(int(1), &int(2))
$b = [];
foreach ( $a as $v ) {
    $b[] = $v;
}
$v = 3;
var_dump($a); // output: array(int(1), &int(3))
</code>```

Title: PHP foreach array strange behavior

Body:
I have code with two foreach, first with &, second without:

$a = array(1, 2);

foreach ( $a as &$v ) {
    $v *= 1;
}

print_r($a); // output: array(1, 2)

$b = array();

foreach ( $a as $v ) {
    $b[] = $v;
}

print_r($b); // output: array(1, 1)

Why in second foreach $v always = 1 and array b is (1, 1) instead (1, 2)?

Body:
You are changing the value of $a[1] in the first loop of the second foreach, if you do a var_dump instead, you get output that indicates it is a reference:

array(2) {
  [0]=>
  int(1)
  [1]=>
  &int(2)
}

So, on the second foreach $a[1] (which is actually &$v; becomes 1), which then is the second value that comes out of $a in the loop, because it is actually:

$a[
   1,
   &$v
];

If you were to reassign $v after the loop, you would get the new value in the array instead:

<?php

$a = [1, 2];
foreach ( $a as &$v ) {
    $v = $v;
}
var_dump($a); // output: array(int(1), &int(2))
$b = [];
foreach ( $a as $v ) {
    $b[] = $v;
}
$v = 3;
var_dump($a); // output: array(int(1), &int(3))


问:
no value given for one or more required parameters
What's wrong in here, I always get some nasty errors even if the same code that I used earlier works. But when I apply it to other form it gives me the error above.
here's my code:

```<code>Imports System.Data.OleDb
Public Class Updater2
    Public adminID As String
    Public adminName As String
    Public adminPass As String

    Private con As New OleDb.OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\db1.mdb;Jet OLEDB:Database Password=nrew123$%^;")
    Private com As OleDb.OleDbCommand

    Public Sub New()
        con.Open()
        com = New OleDb.OleDbCommand("Select * from admintable")
        com.Connection = con

    End Sub

    Public Sub updates()
        com.CommandText = "UPDATE admintable SET AdminName = '" & adminName & "', AdminPassS = '" & adminPass & "' WHERE ID = '" & adminID & "'"
        com.ExecuteNonQuery()

    End Sub
End Class
</code>```

And here's the code in the button which tries to update the data:

```<code>Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        shikai.adminID = textbox1.text
        shikai.adminName = TextBox4.Text
        shikai.adminPass = TextBox3.Text

        shikai.updates()
        MsgBox("Successfully updated!")
    End Sub
</code>```

what might be wrong here?

答: When pasting the command text into access itself and Access pops up telling you which field is the problem, if there does not appear to be a type, try enclosing the field name in square brackets. [ ] It is possible that one of your columns may contain a keyword. This happened to me, which the column LL_ID - I had to change it to [LL_ID].</p>

Body:
What's wrong in here, I always get some nasty errors even if the same code that I used earlier works. But when I apply it to other form it gives me the error above.
here's my code:

Imports System.Data.OleDb
Public Class Updater2
    Public adminID As String
    Public adminName As String
    Public adminPass As String

    Private con As New OleDb.OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\db1.mdb;Jet OLEDB:Database Password=nrew123$%^;")
    Private com As OleDb.OleDbCommand

    Public Sub New()
        con.Open()
        com = New OleDb.OleDbCommand("Select * from admintable")
        com.Connection = con

    End Sub

    Public Sub updates()
        com.CommandText = "UPDATE admintable SET AdminName = '" & adminName & "', AdminPassS = '" & adminPass & "' WHERE ID = '" & adminID & "'"
        com.ExecuteNonQuery()

    End Sub
End Class

And here's the code in the button which tries to update the data:

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        shikai.adminID = textbox1.text
        shikai.adminName = TextBox4.Text
        shikai.adminPass = TextBox3.Text

        shikai.updates()
        MsgBox("Successfully updated!")
    End Sub

what might be wrong here?


问:
In html, how to stretch an image in only one dimension?
Let's say that I want to fit an 10*60 image into a 15*15 container. That is to say, I want to stretch my image so that the width correspond (so that would be an image of 15*90), but I do not want the height to stretch more than the width, so the bottom of my image will not appear.

When I define my html image, I put an width=100% to stretch the width, but what do I say to the height?

Thank  you !

答:
You can also position the image absolute, so you can do something like this:

.embed.ratio-16-9
  img

```<code>.embed {
  position: relative;
  height: 0;
  overflow: hidden;
  max-width: 100%;

  img {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    min-width: 100%;
  }
.ratio-16-9 {
  padding-bottom: 56.25%;
}
</code>```

The image height should no longer be stuck to you block.

Body:
You can also position the image absolute, so you can do something like this:

.embed.ratio-16-9
  img

.embed {
  position: relative;
  height: 0;
  overflow: hidden;
  max-width: 100%;

  img {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    min-width: 100%;
  }
.ratio-16-9 {
  padding-bottom: 56.25%;
}

The image height should no longer be stuck to you block.


问:
Run Python codes on subdirectories
How do I run python codes (.py) on subdirectories from the main folder?

What is the easiest way to do this?

I tried:

```<code>os.chdir("path") #path = path to subdirectory
import abc #abc = module on subdirectory
</code>```

Error:

```<code>ImportError: No module named abc
</code>```

答:
well, just do it </p>

```<code>import sys
sys.path
sys.path.append('/path/to/the/example_file1.py')
sys.path.append('/path/to/the/example_file2.py')
sys.path.append('/path/to/the/example_file3.py')
import example_file1
import example_file2
import example_file3
</code>```

Title: Run Python codes on subdirectories

Body:
How do I run python codes (.py) on subdirectories from the main folder?

What is the easiest way to do this?

I tried:

os.chdir("path") #path = path to subdirectory
import abc #abc = module on subdirectory

Error:

ImportError: No module named abc

Body:
well, just do it

import sys
sys.path
sys.path.append('/path/to/the/example_file1.py')
sys.path.append('/path/to/the/example_file2.py')
sys.path.append('/path/to/the/example_file3.py')
import example_file1
import example_file2
import example_file3


问:
BarcodeScanner input in a Textfield (Keystroke)
i have an Idea for a litte Project i want to compare some Numbers with a simple logic, and for that i have generated many Barcodes and want to scan them and i think i could handle it with the KeyStroke. Is it possible even if the active window is NOT the Gui where the Textfield is that he detect my Prefix and then write the string in the Textfield and end with the Suffix?

Prefix is: TAB+*+PageDown

Suffix is: Carriage Return (HERE he should leave Textfield) or can i create a new Keystroke Event here and a .getActionMap... and than do..

My idea is use .getActionMap()

```<code>...
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);

JTextField text = new JTextField();

panel.getActionMap().put("foo", new AbstractAction() { public void actionPerformed
(ActionEvent e) {
text.setText(br.readLine());
}
</code>```

and a InputMap

```<code>InputMap inputMap = panel.getInputMap();   inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_A,
InputEvent.CTRL_MASK | InputEvent.VK_TAB), "foo");
</code>```

答: You should have a class controller wich manages all the différent gui classes.so you Can Use all variables from the same class and dispatcher it where you need</p>

Body:
i have an Idea for a litte Project i want to compare some Numbers with a simple logic, and for that i have generated many Barcodes and want to scan them and i think i could handle it with the KeyStroke. Is it possible even if the active window is NOT the Gui where the Textfield is that he detect my Prefix and then write the string in the Textfield and end with the Suffix?

Prefix is: TAB+*+PageDown

Suffix is: Carriage Return (HERE he should leave Textfield) or can i create a new Keystroke Event here and a .getActionMap... and than do..

My idea is use .getActionMap()

...
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);

JTextField text = new JTextField();

panel.getActionMap().put("foo", new AbstractAction() { public void actionPerformed
(ActionEvent e) {
text.setText(br.readLine());
}

and a InputMap

InputMap inputMap = panel.getInputMap();   inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_A,
InputEvent.CTRL_MASK | InputEvent.VK_TAB), "foo");


问:
How to ARIA markup radio buttons used for presentation?
I have radio buttons that are used for presentation, not actual form elements:

CSS

```<code>input[type='radio']:checked + a {
    background: #ccc;
}
</code>```

HTML

```<code><fieldset>
    <input type="radio" role="presentation" name="suggestion" id="suggestions_arts centre" value="arts centre" aria-hidden="true">
    <a href="search.json?query=arts centre" tabindex="0"><span class="show-for-sr">Search for: </span><span style="font-weight: bold;">arts</span> centre</a>
    <input type="radio" role="presentation" name="suggestion" id="suggestions_arts" value="arts" aria-hidden="true">
    <a href="search.json?query=arts" tabindex="0"><span class="show-for-sr">Search for: </span><span style="font-weight: bold;">arts</span></a>
    ...
</code>```

This lets me allow the user to user arrow keys to cycle through links which is what I want. I know this isn't exactly what radio buttons are intended for but neither are  lists intended for navigation, but it's pretty much everywhere now, and it saves having to overcomplicate the page with JavaScript if I can lend some of the browsers built in behaviour.

Anyway, how can I use ARIA to markup the radio/links so that it is clear to screen readers what the purpose of these is for as my chrome plugin (SiteImprove) is telling me - "Input field is missing a description" still, or is what I have above OK?

答:
That's a totally unintuitive behaviour.

Second rule of ARIA:

Do not change native semantics, unless you really have to.

Fourth rule of ARIA:

Do not use role="presentation" or aria-hidden="true" on a visible focusable element .

Body:
I have radio buttons that are used for presentation, not actual form elements:

CSS

input[type='radio']:checked + a {
    background: #ccc;
}

HTML

<fieldset>
    <input type="radio" role="presentation" name="suggestion" id="suggestions_arts centre" value="arts centre" aria-hidden="true">
    Search for: arts centre
    <input type="radio" role="presentation" name="suggestion" id="suggestions_arts" value="arts" aria-hidden="true">
    Search for: arts
    ...

This lets me allow the user to user arrow keys to cycle through links which is what I want. I know this isn't exactly what radio buttons are intended for but neither are  lists intended for navigation, but it's pretty much everywhere now, and it saves having to overcomplicate the page with JavaScript if I can lend some of the browsers built in behaviour.

Anyway, how can I use ARIA to markup the radio/links so that it is clear to screen readers what the purpose of these is for as my chrome plugin (SiteImprove) is telling me - "Input field is missing a description" still, or is what I have above OK?


问:
Non-generic reference to generic class results in non-generic return types
I have a legacy class that the class itself is not a generic but one of its methods return type uses generics:

```<code>public class Thing {
    public Collection<String> getStuff() { ... }
}
</code>```

getStuff() uses generics to return a collection of strings. Therefore I can iterate over getStuff() and there's no need to cast the elements to a String:

```<code>Thing t = new Thing();
for (String s: t.getStuff())  // valid
{ ... }
</code>```

However, if I change Thing itself to be a generic but keep everything else the same:

```<code>public class Thing<T> {
    public Collection<String> getStuff() { ... }
}
</code>```

and then keep using the non-generic reference to Thing, getStuff() no longer returns Collection<String> and instead returns a non-typed Collection. Thus the client code does not compile:

```<code>Thing t = new Thing();
for (String s: t.getStuff())  // compiler complains that Object can't be cast to String
{ ... }
</code>```

Why is this? What are the workarounds?

My guess is that by using a non-generic reference to a generic class, Java turns off all generics for the entire class. This is pain, because now I've broken my client code by making Thing a generic.

Edit: I'm making Thing generic for another method which is not listed in the above example code. My question is educational as to why the above cannot be done.

答:
Ok, take two, I misunderstood your question.

When you delcare Thing (this is called a raw type) instead of Thing<?> (parameterized type) the Java compiler strips out all generic arguments, even thogh (as in your case) the generic type of the method has nothing to do with the generic type of the class.

From the (excellent) Java Generics FAQ:

Can I use a raw type like any other type?

Methods or constructors of a raw type have the signature that they would have after type erasure.

This seemingly inocuous and unobtrusive sentence describes the behaviour in question.  You're using Thing as a raw type so the return type is Collection (not Collection<String>) since this is the type after type erasure.

Confused?  Not surprising.  Just look at the size of that FAQ.  There's probably about three people on earth who nderstand the full implications of Java Generics.  Just consider my favourite declaration from the JDK:

```<code>Enum<T extends Enum<T>>
</code>```

(Theres an explanation of that in the FAQ too).

OwnerDisplayName: Steve Kuo

Body:
I have a legacy class that the class itself is not a generic but one of its methods return type uses generics:

public class Thing {
    public Collection<String> getStuff() { ... }
}

getStuff() uses generics to return a collection of strings. Therefore I can iterate over getStuff() and there's no need to cast the elements to a String:

Thing t = new Thing();
for (String s: t.getStuff())  // valid
{ ... }

However, if I change Thing itself to be a generic but keep everything else the same:

public class Thing<T> {
    public Collection<String> getStuff() { ... }
}

and then keep using the non-generic reference to Thing, getStuff() no longer returns Collection<String> and instead returns a non-typed Collection. Thus the client code does not compile:

Thing t = new Thing();
for (String s: t.getStuff())  // compiler complains that Object can't be cast to String
{ ... }

Why is this? What are the workarounds?

My guess is that by using a non-generic reference to a generic class, Java turns off all generics for the entire class. This is pain, because now I've broken my client code by making Thing a generic.

Edit: I'm making Thing generic for another method which is not listed in the above example code. My question is educational as to why the above cannot be done.

LastEditorDisplayName: Steve Kuo

Body:
Ok, take two, I misunderstood your question.

When you delcare Thing (this is called a raw type) instead of Thing<?> (parameterized type) the Java compiler strips out all generic arguments, even thogh (as in your case) the generic type of the method has nothing to do with the generic type of the class.

From the (excellent) Java Generics FAQ:

Can I use a raw type like any other type?

Methods or constructors of a raw type have the signature that they would have after type erasure.

This seemingly inocuous and unobtrusive sentence describes the behaviour in question.  You're using Thing as a raw type so the return type is Collection (not Collection<String>) since this is the type after type erasure.

Confused?  Not surprising.  Just look at the size of that FAQ.  There's probably about three people on earth who nderstand the full implications of Java Generics.  Just consider my favourite declaration from the JDK:

Enum<T extends Enum<T>>

(Theres an explanation of that in the FAQ too).

OwnerDisplayName: cletus

LastEditorDisplayName: cletus