答:
You could loop through your json.data and through their keys to extract the text and values and generate the string you need for the text area.

```<code>    const text = [];

    for (let item of this.textVar.data) {
      Object.keys(item).forEach(key => {
        text.push(key + ': ' + item[key]);
      });
    }

    return text.join('\r\n'); // \r\n is the line break
</code>```

Here's the running code, I put it in app.ts: http://plnkr.co/edit/3AbQYQOW0MVBqO91X9qi?p=preview

Hope this is of help.

Title: Angular reading data from json into textarea

Body:
I'm trying to read some test data from a local json file and output the data with correct formatting into a textarea. Right now though it just outputs [object Object].  How would I go about getting it so it outputs:

Id: theIdGoesHere

Title: theTitleGoesHere

step.service.ts The service used to call the json data

public getJson(): Observable<any>{
    return this.http.get('/assets/jsonData/MyJson.json')
      .map(response => response.json());
  }

MyJson.json

{
    "data":[
        {
            "id": 1,
            "title":"Test1"
        },
        {
            "id": 2,
            "title":"Test2"
        }
    ]
}

main.componenet.ts

private testVar: any;
test(){
    this.stepService.getJson().subscribe(data => (this.testVar = data));
  }

anothermethod(){
    this.test();
    this.mainStepText = this.testVar; //mainStepText binded to textarea with [(ngModel)]="mainStepText"
}

get mainStepText2() { //Rebinded this one
   const text = [];
    const { data } = this.testVar;

    for (let item of this.testVar.data) {
      Object.keys(item).forEach(key => {
        text.push(key + ': ' + item[key]);
      });
    }

    return text.join('\r\n'); // \r\n is the line break
  }

Body:
You could loop through your json.data and through their keys to extract the text and values and generate the string you need for the text area.

    const text = [];

    for (let item of this.textVar.data) {
      Object.keys(item).forEach(key => {
        text.push(key + ': ' + item[key]);
      });
    }

    return text.join('\r\n'); // \r\n is the line break

Here's the running code, I put it in app.ts: http://plnkr.co/edit/3AbQYQOW0MVBqO91X9qi?p=preview

Hope this is of help.


来源: stackexchange

问:
On AWS RDS Postgres, how to have dictionaries and unaccented full-text search?
I want to use PostgreSQL 9.5.4 on AWS RDS, leveraging the full-text search, dictionaries with stop words, unaccented full-text search.

The context:

With 'unaccent' on, this full-text (Json) query will find 'F(e-acute)vrier' even if I did not enter the accent properly

```<code>psql>select * from proto_model.product where to_tsvector((body ->> 'description')) @@ to_tsquery('Fevrier');
</code>```

With an English dictionary, the same search for 'the', 'any', 'you'... will find nothing as they are 'stop words' defined in the English dictionary and ignored.

The issue:

On my local Postgres, this is not an issue at all. On the managed AWS this is one.
EC2+Docker on AWS would not be an issue of course but I focus on RDS Postgres for now.

Locally, the default value of default_text_search_config (get it with psql>show all) is 'pg_catalog.english' which uses the English dictionary and stop words. On RDS this is 'pg_catalog.simple'.

1) In AWS, I cannot add a dictionary or modify one as you need file system access that you don't have. There is no programatical solution to create/update a dictionary AFAIK.

2) In AWS, as the 'postgres' user or even as the 'rds_superuser' that you can create, I cannot alter the global configuration

```<code>psql>ALTER SYSTEM SET default_text_search_config = 'pg_catalog.english';
ERROR:  must be superuser to execute ALTER SYSTEM command
</code>```

In addition, it is absent of the RDS Postgres parameter groups that you can associate to a new Postgres instance and you cannot add missing values!
Granting more to 'rds_superuser' (psql>grant all on schema public to ...) does not help.

3) In AWS, as 'postgres' or 'rds_superuser', I can however set for my session, the current text configuration

```<code>psql>set default_text_search_config = 'pg_catalog.english';
SET
</code>```

4) Sadly in AWS, as 'postgres' or 'rds_superuser', I cannot alter the search configuration (global) to ignore the accents. This works fine locally.

```<code>psql>ALTER TEXT SEARCH CONFIGURATION english ALTER MAPPING FOR hword, hword_part, word WITH unaccent, english_stem;
ERROR:  must be owner of text search configuration english
</code>```

5) In AWS, as 'postgres' or 'rds_superuser', I can create a new search configuration (English + Unaccent) but I cannot set it as the default even in my session!

```<code>psql>CREATE TEXT SEARCH CONFIGURATION english2 (copy=english);
CREATE...
psql>ALTER TEXT SEARCH CONFIGURATION english2 ALTER MAPPING FOR hword, hword_part, word WITH unaccent, english_stem;
ALTER...
psql>set default_text_search_config = 'pg_catalog.english2';
ERROR:  invalid value for parameter "default_text_search_config": "pg_catalog.english2"
</code>```

So it seems that I am cooked.

The best that I can see could be to associate automatically without a need for individual psql>set default_text_search_config = ... my user connection to a set of configuration options

```<code>psql>alter role somerole set default_text_search_config = 'pg_catalog.english';
psql>select * from pg_user; (the option is present by default for all my connections under this role)
</code>```

Outside of moving out of AWS RDS to EC2+Docker, do you know any solution to (4) or (5) providing me dictionary+unaccent?

答:
You can change by altering the role parameters in the database like:</p>

```<code>ALTER ROLE [role] IN DATABASE [database]
    SET default_text_search_config TO 'pg_catalog.english';
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I want to use PostgreSQL 9.5.4 on AWS RDS, leveraging the full-text search, dictionaries with stop words, unaccented full-text search.

The context:

With 'unaccent' on, this full-text (Json) query will find 'F(e-acute)vrier' even if I did not enter the accent properly

psql>select * from proto_model.product where to_tsvector((body ->> 'description')) @@ to_tsquery('Fevrier');

With an English dictionary, the same search for 'the', 'any', 'you'... will find nothing as they are 'stop words' defined in the English dictionary and ignored.

The issue:

On my local Postgres, this is not an issue at all. On the managed AWS this is one.
EC2+Docker on AWS would not be an issue of course but I focus on RDS Postgres for now.

Locally, the default value of default_text_search_config (get it with psql>show all) is 'pg_catalog.english' which uses the English dictionary and stop words. On RDS this is 'pg_catalog.simple'.

1) In AWS, I cannot add a dictionary or modify one as you need file system access that you don't have. There is no programatical solution to create/update a dictionary AFAIK.

2) In AWS, as the 'postgres' user or even as the 'rds_superuser' that you can create, I cannot alter the global configuration

psql>ALTER SYSTEM SET default_text_search_config = 'pg_catalog.english';
ERROR:  must be superuser to execute ALTER SYSTEM command

In addition, it is absent of the RDS Postgres parameter groups that you can associate to a new Postgres instance and you cannot add missing values!
Granting more to 'rds_superuser' (psql>grant all on schema public to ...) does not help.

3) In AWS, as 'postgres' or 'rds_superuser', I can however set for my session, the current text configuration

psql>set default_text_search_config = 'pg_catalog.english';
SET

4) Sadly in AWS, as 'postgres' or 'rds_superuser', I cannot alter the search configuration (global) to ignore the accents. This works fine locally.

psql>ALTER TEXT SEARCH CONFIGURATION english ALTER MAPPING FOR hword, hword_part, word WITH unaccent, english_stem;
ERROR:  must be owner of text search configuration english

5) In AWS, as 'postgres' or 'rds_superuser', I can create a new search configuration (English + Unaccent) but I cannot set it as the default even in my session!

psql>CREATE TEXT SEARCH CONFIGURATION english2 (copy=english);
CREATE...
psql>ALTER TEXT SEARCH CONFIGURATION english2 ALTER MAPPING FOR hword, hword_part, word WITH unaccent, english_stem;
ALTER...
psql>set default_text_search_config = 'pg_catalog.english2';
ERROR:  invalid value for parameter "default_text_search_config": "pg_catalog.english2"

So it seems that I am cooked.

The best that I can see could be to associate automatically without a need for individual psql>set default_text_search_config = ... my user connection to a set of configuration options

psql>alter role somerole set default_text_search_config = 'pg_catalog.english';
psql>select * from pg_user; (the option is present by default for all my connections under this role)

Outside of moving out of AWS RDS to EC2+Docker, do you know any solution to (4) or (5) providing me dictionary+unaccent?

Body:
You can change by altering the role parameters in the database like:

ALTER ROLE [role] IN DATABASE [database]
    SET default_text_search_config TO 'pg_catalog.english';

ContentLicense: CC BY-SA 3.0


问:
Xcode 8 Beta 3 Use Legacy Swift issue
I have an Objective-C project in Xcode 8 Beta 3. Since updating, whenever I try to build I receive the following error:

“Use Legacy Swift Language Version” (SWIFT_VERSION) is required to be configured correctly for targets which use Swift. Use the [Edit > Convert > To Current Swift Syntax…] menu to choose a Swift version or use the Build Settings editor to configure the build setting directly.

Has anyone encountered this? Since it's an Objective-C project there's no build setting to configure Swift. I have also made sure none of the project dependencies or CocoaPods are using Swift. The only solution I have is to use Beta 2. Any ideas how I might fix this issue?

I should also mention I'm running OSX 10.12 Beta 2.

答: In Xcode 9 beta. Go to Project Settings, Build Settings, search for Swift Language Version. In Xcode 9 you must specify if you are using Swift 3.2 or Swift 4.</p>

Title: Xcode 8 Beta 3 Use Legacy Swift issue


问:
Joomla current path
I have Joomla Component administrator/components/com_mycomp

And I have import.php file in this folder.

How I can access import.php from com_mycomp.php.

```<code>require_once('./import.php');
</code>```

Gives error file not found. Because current path is /administrator , instead of administrator/components/com_mycomp.

答:
use JPATH_BASE;

```<code><?php
    require_once(JPATH_BASE.'/directory/subdirectory/import.php');
 ?>
</code>```

https://docs.joomla.org/How_to_find_your_absolute_path

Title: Joomla current path

Body:
I have Joomla Component administrator/components/com_mycomp

And I have import.php file in this folder.

How I can access import.php from com_mycomp.php.

require_once('./import.php');

Gives error file not found. Because current path is /administrator , instead of administrator/components/com_mycomp.

Body:
use JPATH_BASE;

<?php
    require_once(JPATH_BASE.'/directory/subdirectory/import.php');
 ?>

https://docs.joomla.org/How_to_find_your_absolute_path


问:
How to redirect www blocked (This website/URL has been blocked as per instructions from Department of Telecommunications of India.”) to Non www
I have a website in wordpress, which was index in google with http://www.xyz.in but due to some reason the www version is blocked by Department of Telecommunications of India. but the non www version is still accessible. Is there anyway to hard redirect the www version (from the DNS level) to non www version. I have tried all the possible manner, but nothing works. Please help me and share your views</p>

答:
Try Access It ..using   HTTPS://...

```<code>https://www.xyz.in
</code>```

Read This..  https://support.google.com/webmasters/answer/44231?hl=en

http to https
  https://www.keycdn.com/blog/http-to-https/

Steps: https://webmasters.stackexchange.com/questions/68435/moving-from-http-to-https-google-search-console

Body:
Try Access It ..using   HTTPS://...

https://www.xyz.in

Read This..  https://support.google.com/webmasters/answer/44231?hl=en

http to https
  https://www.keycdn.com/blog/http-to-https/

Steps: https://webmasters.stackexchange.com/questions/68435/moving-from-http-to-https-google-search-console


问:
why cant i replace __add__ with __radd__?
I am (for exercise) trying to make a class that works with roman numerals. I am trying to put as much functionality into it as possible, so i looked into making operators work on them. I found (example, the problem persists among other pairs of methods) __add__ and __radd__. The documentation says that if __add__ is not defined it (or if it fails) looks into __radd__, but when i try to delete __add__ and edit the __radd__ method it works on 0 + myobject, but not on object1 + object2.

Here is the class (with a few things cut out because they're not important for my problem):

```<code>class Roman:
    num_map = [('M', 1000), ('CM', 900), ('D', 500), ('CD', 400), ('C', 100), ('XC', 90), ('L', 50), ('XL', 40), ('X', 10), ('IX', 9), ('V', 5), ('IV', 4), ('I', 1)]

    def __init__(self, num=None):
        self.decimal = 0
        self.roman = 'N'
        if type(num) == type(0):
            self.__setattr__('decimal', num)
        elif type(num) == type(''):
            self.__setattr__('roman', num)

    def __setattr__(self, field, value):
        if field == 'decimal' and type(value) == type(0):
            super().__setattr__('decimal', value)
            super().__setattr__('roman', self.dec2roman(value))
        elif field == 'roman' and type(value) == type(''):
            super().__setattr__('roman', value)
            super().__setattr__('decimal', self.roman2dec(value))
</code>```

The methods self.dec2roman(integer) and self.roman2dec(string) simply convert from one format to the other.

Now if i try to make __radd__ like this:

```<code>def __radd__(self, other):
    if other == 0:
        return self
    return Roman(self.decimal + other.decimal)
</code>```

it doesn't work, but this does:

```<code>def __add__(self,other):
    return Roman(self.decimal + other.decimal)
def __radd__(self, other):
    if other == 0:
        return self
    return self + other
</code>```

Here's the error i get:

```<code>>>> from roman import Roman
>>> a = Roman(3)
>>> b = Roman('X')
>>> a + b
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'Roman' and 'Roman'
</code>```

Does someone know what is going on?

答:
According to the “data model” section of the Python documentation,

[__radd__ and similar functions] are only called if the left operand does not support the corresponding operation and the operands are of different types.

(Emphasis added.) This is why defining __radd__ is not working for you: you’re trying to add two items of the same class. I’m not sure why you’re trying to avoid __add__ but that method is clearly what is called for in this situation.

Body:
I am (for exercise) trying to make a class that works with roman numerals. I am trying to put as much functionality into it as possible, so i looked into making operators work on them. I found (example, the problem persists among other pairs of methods) __add__ and __radd__. The documentation says that if __add__ is not defined it (or if it fails) looks into __radd__, but when i try to delete __add__ and edit the __radd__ method it works on 0 + myobject, but not on object1 + object2.

Here is the class (with a few things cut out because they're not important for my problem):

class Roman:
    num_map = [('M', 1000), ('CM', 900), ('D', 500), ('CD', 400), ('C', 100), ('XC', 90), ('L', 50), ('XL', 40), ('X', 10), ('IX', 9), ('V', 5), ('IV', 4), ('I', 1)]

    def __init__(self, num=None):
        self.decimal = 0
        self.roman = 'N'
        if type(num) == type(0):
            self.__setattr__('decimal', num)
        elif type(num) == type(''):
            self.__setattr__('roman', num)

    def __setattr__(self, field, value):
        if field == 'decimal' and type(value) == type(0):
            super().__setattr__('decimal', value)
            super().__setattr__('roman', self.dec2roman(value))
        elif field == 'roman' and type(value) == type(''):
            super().__setattr__('roman', value)
            super().__setattr__('decimal', self.roman2dec(value))

The methods self.dec2roman(integer) and self.roman2dec(string) simply convert from one format to the other.

Now if i try to make __radd__ like this:

def __radd__(self, other):
    if other == 0:
        return self
    return Roman(self.decimal + other.decimal)

it doesn't work, but this does:

def __add__(self,other):
    return Roman(self.decimal + other.decimal)
def __radd__(self, other):
    if other == 0:
        return self
    return self + other

Here's the error i get:

>>> from roman import Roman
>>> a = Roman(3)
>>> b = Roman('X')
>>> a + b
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'Roman' and 'Roman'

Does someone know what is going on?


问:
Python alphanumeric
Problem:

I have to go through text file that has lines of strings and determine about each line if it is alphanumeric or not. If the line is alphanumeric print for example "5345m345ö34l is alphanumeric"

Example of the text file:

```<code>5345m345ö34l

no2no123non4

%#""SGMSGSER
</code>```

My code is as follows:

```<code>file = open('file.txt','r')
data = file.readlines()

for i in data:
    i.strip()
    if (i.isalnum()):
        print (i, 'is alphanumeric')
    else:
        print (i, 'not alphanumeric')
    file.close()
</code>```

We can see that the first and second line is alphanumeric but the program doesn't work?

答:
try this and see if this working -</p>

```<code>file = open('file.txt','r')
data = file.readlines()

for i in data:
    stripped_line = i.strip()
    if (stripped_line.isalnum()):
       print (stripped_line, 'is alphanumeric')
    else:
       print (stripped_line, 'not alphanumeric')
file.close()
</code>```

Title: Python alphanumeric

Body:
Problem:

I have to go through text file that has lines of strings and determine about each line if it is alphanumeric or not. If the line is alphanumeric print for example "5345m345ö34l is alphanumeric"

Example of the text file:

5345m345ö34l

no2no123non4

%#""SGMSGSER

My code is as follows:

file = open('file.txt','r')
data = file.readlines()

for i in data:
    i.strip()
    if (i.isalnum()):
        print (i, 'is alphanumeric')
    else:
        print (i, 'not alphanumeric')
    file.close()

We can see that the first and second line is alphanumeric but the program doesn't work?

Body:
try this and see if this working -

file = open('file.txt','r')
data = file.readlines()

for i in data:
    stripped_line = i.strip()
    if (stripped_line.isalnum()):
       print (stripped_line, 'is alphanumeric')
    else:
       print (stripped_line, 'not alphanumeric')
file.close()


问:
MongoDB: insert embedded document directly from another collection
I have two collection:

```<code>// Profile
{
    _id: "12345",
    name: "max",
    country: "IT"
}

// Association
{
    _id: "43234",
    idclub: "1000",
    state: "0"
}
</code>```

I want to insert a Profile on Association without searching it.
In my code i search for an Association but i don't have the object Profile in that moment, i just have its "id".

Is it possible to perform some kind of insert on collection A retrieving on the fly the object of collection B given it's own ID?

And then, is this a recurring practice? As i can find nothing it seems not properly the best way...

Thanks

答:
Use findAndModify operator

```<code>     db.createCollection("Association");

     db.Association.insert({ _id : "43234", idclub:"1000",state:"0"});

     db.Association.findAndModify({
            query:{ _id:"43234" },
            update:{ $set:{ "profile":{ _id:"12345","name":"max","country":"IT" } } }
    });

    db.Association.find();
</code>```

{"_id" : "43234", "idclub" : "1000", "state" : "0", "profile" : { "_id" :
             "12345", "name" : "max", "country" : "IT" } }

Body:
I have two collection:

// Profile
{
    _id: "12345",
    name: "max",
    country: "IT"
}

// Association
{
    _id: "43234",
    idclub: "1000",
    state: "0"
}

I want to insert a Profile on Association without searching it.
In my code i search for an Association but i don't have the object Profile in that moment, i just have its "id".

Is it possible to perform some kind of insert on collection A retrieving on the fly the object of collection B given it's own ID?

And then, is this a recurring practice? As i can find nothing it seems not properly the best way...

Thanks

Body:
Use findAndModify operator

     db.createCollection("Association");

     db.Association.insert({ _id : "43234", idclub:"1000",state:"0"});

     db.Association.findAndModify({
            query:{ _id:"43234" },
            update:{ $set:{ "profile":{ _id:"12345","name":"max","country":"IT" } } }
    });

    db.Association.find();

{"_id" : "43234", "idclub" : "1000", "state" : "0", "profile" : { "_id" :
             "12345", "name" : "max", "country" : "IT" } }


答:
EDIT

From your original post you want to treat latin characters (i.e. those with accents) as valid alphanumeric input. In order to do this you should load the original file in unicode and when testing for alphanumeric qualities you should convert the accented letters to normal alphabetic. This will do that:

```<code># -*- coding: utf-8 -*-
import unicodedata
import codecs

file = codecs.open('file.txt','rb', encoding="utf-8")
data = file.readlines()
for i in data:
    i = i.strip()
    converted_data = ''.join((c for c in unicodedata.normalize('NFD', i) if unicodedata.category(c) != 'Mn'))
    if (converted_data.isalnum()):
        print (i, 'is alphanumeric')
    else:
        print (i, 'not alphanumeric')
file.close()
</code>```

Title: Python alphanumeric

Body:
EDIT

From your original post you want to treat latin characters (i.e. those with accents) as valid alphanumeric input. In order to do this you should load the original file in unicode and when testing for alphanumeric qualities you should convert the accented letters to normal alphabetic. This will do that:

# -*- coding: utf-8 -*-
import unicodedata
import codecs

file = codecs.open('file.txt','rb', encoding="utf-8")
data = file.readlines()
for i in data:
    i = i.strip()
    converted_data = ''.join((c for c in unicodedata.normalize('NFD', i) if unicodedata.category(c) != 'Mn'))
    if (converted_data.isalnum()):
        print (i, 'is alphanumeric')
    else:
        print (i, 'not alphanumeric')
file.close()


问:
Find number of vowels in a word
How can a find all the vowels for a word in bash?

```<code>grep -o "a"  <<<$1 | wc l
</code>```

This command finds only a, and I want to find aeiou.

For example:

for car I want the output to be 1

for computer I want the output to be 3

答:
You can combine -o (only retain matches) with wc -l and use a bracket expression to match all vowels:

```<code>$ grep -o '[aeiou]' <<< car | wc -l
1
$ grep -o '[aeiou]' <<< computer | wc -l
3
</code>```

As a function (notice quotes around $1 to prevent word splitting and pathname expansion):

```<code>vowcount () { grep -o '[aeiou]' <<< "$1" | wc -l; }
</code>```

Used like

```<code>$ vowcount alphabet
3
</code>```

Title: Find number of vowels in a word

Body:
How can a find all the vowels for a word in bash?

grep -o "a"  <<<$1 | wc l

This command finds only a, and I want to find aeiou.

For example:

for car I want the output to be 1

for computer I want the output to be 3

Body:
You can combine -o (only retain matches) with wc -l and use a bracket expression to match all vowels:

$ grep -o '[aeiou]' <<< car | wc -l
1
$ grep -o '[aeiou]' <<< computer | wc -l
3

As a function (notice quotes around $1 to prevent word splitting and pathname expansion):

vowcount () { grep -o '[aeiou]' <<< "$1" | wc -l; }

Used like

$ vowcount alphabet
3


问:
Template Tag not working with csrf_token
I am attempting to create a custom template tag to display a comment.  When I try submitting a reply through the form attached to each comment, I get an error:

Forbidden (403)
CSRF verification failed. Request aborted.
Reason given for failure:
    CSRF token missing or incorrect.

The csrf token works on the form with the download and follow button, but not on the form generated from the template tag.  Any help would be appreciated.

DocumentView

```<code>def DocumentView(request, doc_id):
    context = {}
    user = None
    if request.user.is_authenticated():
        email = request.user.email
        id = request.user.id
        user = get_user_information(email=email)
    else:
        user = None

    context['user'] = user

    if request.method == 'POST':
        user_id = request.POST.get('submit', '')

    doc = Doc.objects.get(id=doc_id)
    doc_version = DocVersion.objects.filter(doc__id=doc_id).latest('id')
    doc_title = doc.response_title
    allow_comments = doc.allow_comments
    comments = {}
    if user['user_type'] == 'DA':
        for comment in Comment.objects.filter(doc_id=doc_id):
            comments[comment.id] = {'content': comment.content, 'reply_to': comment.reply_to, 'user_id': comment.user.id}
    else:
        for comment in Comment.objects.filter(doc_id=doc_id, is_flagged=False):
            comments[comment.id] = {'content': comment.content, 'reply_to': comment.reply_to, 'user_id': comment.user.id}
    context['comments'] = comments
    context['allow_comments'] = allow_comments
    context['doc_title'] = doc_title
    print context
    return render(request, 'doc/document.html', context)
</code>```

comment_tags.py

```<code>from django.template import Library, Node, Context, Variable
from django.template.loader import get_template
from django import template

register = Library()

@register.tag()
def comments(parser, token):
    user_id, profile_pic, reply_id, comment_id, content, info = None, None, None, None, "", ""

    for index, x in enumerate(token.split_contents()):
        if x == 'user_id':
            user_id = token.split_contents()[index + 1]
        if x == 'profile_pic':
            profile_pic = token.split_contents()[index + 1]
        if x == 'content':
            content = token.split_contents()[index + 1]
        if x == 'info':
            info = token.split_contents()[index + 1]
        if x == 'reply_id':
            reply_id = token.split_contents()[index + 1]
        if x == 'comment_id':
            comment_id = token.split_contents()[index + 1]

    return CommentNode(user_id, profile_pic, comment_id, content, info, reply_id)

class CommentNode(template.Node):
    def __init__(self, user_id, profile_pic, comment_id, content, info, reply_id):
        self.user_id = template.Variable(user_id)
        self.profile_pic = template.Variable(profile_pic)
        self.content = template.Variable(content)
        self.info = template.Variable(info)
        self.comment_id = template.Variable(comment_id)

        if reply_id != None:
            self.reply_id = template.Variable(reply_id)
        else:
            self.reply_id = reply_id

    def render(self, context):
        t = get_template("srd/comment.html")

        if self.reply_id == None:
            return t.render({
                    'user_id': self.user_id.resolve(context),
                    'profile_pic': self.profile_pic.resolve(context),
                    'comment_id': self.comment_id.resolve(context),
                    'content': self.content.resolve(context),
                    'info': self.info.resolve(context),
                    'reply_id': self.reply_id
                }
            )
        else:
            return t.render({
                'user_id': self.user_id.resolve(context),
                'profile_pic': self.profile_pic.resolve(context),
                'comment_id': self.comment_id.resolve(context),
                'content': self.content.resolve(context),
                'info': self.info.resolve(context),
                'reply_id': self.reply_id.resolve(context)
            })
</code>```

document.html

```<code>{% load static %}
{% load comment_tags %}
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>{{ doc_title }}</title>
    <link rel="stylesheet" type="text/css" href="{% static "stylesheets/doc.css" %}">
    <script src="{% static "javascript/jquery-3.2.1.min.js" %}" type="text/javascript"></script>
    <script src="{% static "javascript/doc.js" %}" type="text/javascript"></script>

</head>
<body>
    <div class="main_div">
        <div class="content_div">
            <div class="info_div">
                <h2>[{{ generic_name }}]</h2>
                <label>{{ doc_title }} <a href="edit">[Edit]</a></label>

            </div>
            <div class="doc_div">
                <div class="doc_preview">
                </div>
                <div class="doc_preview_info">
                    <form method="post">
                        {% csrf_token %}
                        <input type="hidden" value="{{ user.id }}" />
                        <input type="submit" value="Donwload PDF" /><br/>
                        <input type="submit" value="Follow" />
                    </form>

                </div>
            </div>
            {% if allow_comments %}
            <div class="comment_div" id="comment_div">
                {% for commentid, comment in comments.items %}
                    {% if comment.reply_to %}
                        {% comments comment_id commentid user_id comment.user_id reply_id comment.reply_to.id profile_pic "hi" content comment.content info "XYZ" %}
                    {% else %}
                        {% comments comment_id commentid user_id comment.user_id profile_pic "hi" content comment.content info "XYZ" %}
                    {% endif %}
                {% endfor %}
            </div>
            {% endif %}
        </div>
        <div class="ad_div">
            <div class="ad"></div>
            <div class="ad"></div>
            <div class="ad"></div>
            <div class="ad"></div>
        </div>
    </div>
</body>
</html>
</code>```

comment.html

```<code><div class="comment">
    <div class="profile_pic">
    {{ user_id }}
    </div>
    <div class="comment_content">
        <div class="top_bar">
            <div class="comment_info">
                {{ info }}
            </div>
            <div class="flag">
                <a href="#">Flag</a>
            </div>
        </div>
        <div class="comment_text">
            {{ content }}
        </div>
        <div class="reply_bar">
            <a id="reply_link_{{ comment_id }}" class="reply_link" href="#">Reply</a>
        </div>
    </div>
</div>
<div class="reply" id="reply_{{ comment_id }}">
    <form method="post">
        {% csrf_token %}
        <input type="hidden" value="{{ reply_id }}"/>
        <input name="reply_text" type="text" />
        <input type="submit" value="Post" />
    </form>
</div>
</code>```

答:
Since you are rendering the template manually in your tag, you need to use a RequestContext so that it runs the context processors - including the one that adds the CSRF token.

```<code>return t.render(RequestContext(context['request'], {
                     ...
                }))
</code>```

Note, the whole thing could be greatly simplified by using an inclusion tag.

Body:
I am attempting to create a custom template tag to display a comment.  When I try submitting a reply through the form attached to each comment, I get an error:

Forbidden (403)
CSRF verification failed. Request aborted.
Reason given for failure:
    CSRF token missing or incorrect.

The csrf token works on the form with the download and follow button, but not on the form generated from the template tag.  Any help would be appreciated.

DocumentView

def DocumentView(request, doc_id):
    context = {}
    user = None
    if request.user.is_authenticated():
        email = request.user.email
        id = request.user.id
        user = get_user_information(email=email)
    else:
        user = None

    context['user'] = user

    if request.method == 'POST':
        user_id = request.POST.get('submit', '')

    doc = Doc.objects.get(id=doc_id)
    doc_version = DocVersion.objects.filter(doc__id=doc_id).latest('id')
    doc_title = doc.response_title
    allow_comments = doc.allow_comments
    comments = {}
    if user['user_type'] == 'DA':
        for comment in Comment.objects.filter(doc_id=doc_id):
            comments[comment.id] = {'content': comment.content, 'reply_to': comment.reply_to, 'user_id': comment.user.id}
    else:
        for comment in Comment.objects.filter(doc_id=doc_id, is_flagged=False):
            comments[comment.id] = {'content': comment.content, 'reply_to': comment.reply_to, 'user_id': comment.user.id}
    context['comments'] = comments
    context['allow_comments'] = allow_comments
    context['doc_title'] = doc_title
    print context
    return render(request, 'doc/document.html', context)

comment_tags.py

from django.template import Library, Node, Context, Variable
from django.template.loader import get_template
from django import template

register = Library()

@register.tag()
def comments(parser, token):
    user_id, profile_pic, reply_id, comment_id, content, info = None, None, None, None, "", ""

    for index, x in enumerate(token.split_contents()):
        if x == 'user_id':
            user_id = token.split_contents()[index + 1]
        if x == 'profile_pic':
            profile_pic = token.split_contents()[index + 1]
        if x == 'content':
            content = token.split_contents()[index + 1]
        if x == 'info':
            info = token.split_contents()[index + 1]
        if x == 'reply_id':
            reply_id = token.split_contents()[index + 1]
        if x == 'comment_id':
            comment_id = token.split_contents()[index + 1]

    return CommentNode(user_id, profile_pic, comment_id, content, info, reply_id)

class CommentNode(template.Node):
    def __init__(self, user_id, profile_pic, comment_id, content, info, reply_id):
        self.user_id = template.Variable(user_id)
        self.profile_pic = template.Variable(profile_pic)
        self.content = template.Variable(content)
        self.info = template.Variable(info)
        self.comment_id = template.Variable(comment_id)

        if reply_id != None:
            self.reply_id = template.Variable(reply_id)
        else:
            self.reply_id = reply_id

    def render(self, context):
        t = get_template("srd/comment.html")

        if self.reply_id == None:
            return t.render({
                    'user_id': self.user_id.resolve(context),
                    'profile_pic': self.profile_pic.resolve(context),
                    'comment_id': self.comment_id.resolve(context),
                    'content': self.content.resolve(context),
                    'info': self.info.resolve(context),
                    'reply_id': self.reply_id
                }
            )
        else:
            return t.render({
                'user_id': self.user_id.resolve(context),
                'profile_pic': self.profile_pic.resolve(context),
                'comment_id': self.comment_id.resolve(context),
                'content': self.content.resolve(context),
                'info': self.info.resolve(context),
                'reply_id': self.reply_id.resolve(context)
            })

document.html

{% load static %}
{% load comment_tags %}

    <meta charset="UTF-8">
    <title>{{ doc_title }}</title>
    <link rel="stylesheet" type="text/css" href="{% static "stylesheets/doc.css" %}">

[{{ generic_name }}]

                {{ doc_title }} [Edit]

                    <form method="post">
                        {% csrf_token %}
                        <input type="hidden" value="{{ user.id }}" />
                        <input type="submit" value="Donwload PDF" />

                        <input type="submit" value="Follow" />
                    </form>

            {% if allow_comments %}

                {% for commentid, comment in comments.items %}
                    {% if comment.reply_to %}
                        {% comments comment_id commentid user_id comment.user_id reply_id comment.reply_to.id profile_pic "hi" content comment.content info "XYZ" %}
                    {% else %}
                        {% comments comment_id commentid user_id comment.user_id profile_pic "hi" content comment.content info "XYZ" %}
                    {% endif %}
                {% endfor %}

            {% endif %}

comment.html

    {{ user_id }}

                {{ info }}

                Flag

            {{ content }}

            Reply

    <form method="post">
        {% csrf_token %}
        <input type="hidden" value="{{ reply_id }}"/>
        <input name="reply_text" type="text" />
        <input type="submit" value="Post" />
    </form>

Body:
Since you are rendering the template manually in your tag, you need to use a RequestContext so that it runs the context processors - including the one that adds the CSRF token.

return t.render(RequestContext(context['request'], {
                     ...
                }))

Note, the whole thing could be greatly simplified by using an inclusion tag.


问:
Correct way of implementing Finalize and Dispose(When parent class implements IDisposable)
I was implementing Finalize and Dispose in my classes, I implemented IDisposable on my parent class and override the Dispose(bool) overload in my child classes. I was not sure

whether to use a duplicate isDisposed variable(as its already there in base class) or not?

Whether to implement a finalizer in child class too or not?

Both these things are done in example given here -

http://guides.brucejmack.biz/CodeRules/FxCop/Docs/Rules/Usage/DisposeMethodsShouldCallBaseClassDispose.html

Whereas example in this MSDN article doesn't have any of these two -
http://msdn.microsoft.com/en-us/library/b1yfkh5e.aspx

whereas this example in MSDN is not complete -
http://msdn.microsoft.com/en-us/library/ms182330.aspx

答:
It's very rare for a finalizer to be useful. The documentation you link to isn't totally helpful - it offers the following rather circular advice:

Implement Finalize only on objects
  that require finalization

That's an excellent example of begging the question, but it's not very helpful.

In practice, the vast majority of the time you don't want a finalizer. (One of the learning curves .NET developers have to go through is discovering that in most of the places they think they need a finalizer, they don't.) You've tagged this as (amongst other things) a WPF question, and I'd say it'd almost always be a mistake to put a finalizer on a UI object. (So even if you are in one of the unusual situations that turns out to require a finalizer, that work doesn't belong anywhere near code that concerns itself with WPF.)

For most of the scenarios in which finalizers seem like they might be useful, they turn out not to be, because by the time your finalizer runs, it's already too late for it to do anything useful.

For example it's usually a bad idea to try to do anything with any of the objects your object has a reference to, because by the time your finalizer runs, those objects may already have been finalized. (.NET makes no guarantees about the order in which finalizers run, so you simply have no way of knowing whether the objects you've got references to have been finalized.) It's bad idea to invoke a method on an object whose finalizer has already been run.

If you have some way of knowing that some object definitely hasn't been finalized, then it is safe to use it, but that's a pretty unusual situation to be in. (...unless the object in question has no finalizer, and makes use of no finalizable resources itself. But in that case, it's probably not an object you'd actually need to do anything to when your own object is going away.)

The main situation in which finalizers seem useful is interop: e.g., suppose you're using P/Invoke to call some unmanaged API, and that API returns you a handle. Perhaps there's some other API you need to call to close that handle. Since that's all unmanaged stuff, the .NET GC doesn't know what those handles are, and it's your job to make sure that they get cleaned up, at which point a finalizer is reasonable...except in practice, it's almost always best to use a SafeHandle for that scenario.

In practice, the only places I've found myself using finalizers have been a) experiments designed to investigate what the GC does, and b) diagnostic code designed to discover something about how particular objects are being used in a system. Neither kind of code should end up going into production.

So the answer to whether you need "to implement a finalizer in child class too or not" is: if you need to ask, then the answer is no.

As for whether to duplicate the flag...other answers are providing contradictory advice here. The main points are 1) you do need to call the base Dispose and 2) your Dispose needs to be idempotent. (I.e., it doesn't matter if it's called once, twice, 5 times, 100 times - it shouldn't complain if it's called more than once.) You're at liberty to implement that however you like - a boolean flag is one way, but I've often found that it's enough to set certain fields to null in my Dispose method, at which point that removes any need for a separate boolean flag - you can tell that Dispose was already called because you already set those fields to null.

A lot of the guidance out there on IDisposable is extremely unhelpful, because it addresses the situation where you need a finalizer, but that's actually a very unusual case. It means that lots of people write a IDisposable implementations that are far more complex than necessary. In practice, most classes call into the category Stephen Cleary calls "level 1" in the article that jpierson linked to. And for these, you don't need all the GC.KeepAlive, GC.SuppressFinalize, and Dispose(bool) stuff that clutters up most of the examples. Life's actually much simpler most of the time, as Cleary's advice for these "level 1" types shows.

ContentLicense: CC BY-SA 2.5


问:
How to run firefox program in linux and get its output on windows
I have one centos 7 (minimum setup) installed on cloud .
I m connect it using using putty on my laptop.

I have installed Firefox on centos server which has fast internet connection.

However whenever i run Firefox its not loading because it doesn't have GUI installed (and i m connecting it using putty).

I want to browse internet on it from windows machine. How can i go about it?

Error Message

```<code># firefox
Error: GDK_BACKEND does not match available displays
</code>```

Please help

答:
You can forward X over SSH, but it is painfully slow. Something like NoMachine will do far better.

However, if you are trying to get faster internet, you may be out of luck as any attempt to improve this will just add overhead.

You may be able to set up a VPN to improve the compression on data you receive from other websites. Take a look at this SO post for some information about what's available and what solutions already exist.

Body:
I have one centos 7 (minimum setup) installed on cloud .
I m connect it using using putty on my laptop.

I have installed Firefox on centos server which has fast internet connection.

However whenever i run Firefox its not loading because it doesn't have GUI installed (and i m connecting it using putty).

I want to browse internet on it from windows machine. How can i go about it?

Error Message

# firefox
Error: GDK_BACKEND does not match available displays

Please help


问:
Python3 won't recognize a variable in code
All my code is below.

Just started learning to program this week. I'm attempting to make a Monty Hall simulator (text only) where the player chooses a door by selecting 1, 2 or 3. For some reason, though, Python doesn't seem to be recognizing the input!

Here are links to the game for the uninitiated:

Monty Hall wikipedia page

Monty Hall simulation

What my program attempts to do is as follows. First the player chooses a door, either 1, 2 or 3. Then the program checks to make sure that the player did indeed enter one of those three numbers. If not, then the person needs to choose again.

After this, the game randomly chooses a winning door. Then, per the rules of the game, the program needs to reveal a dummy prize (the goat). So the program randomly chooses one of the doors to be the "goat door." The program first makes sure that this door is not the winning door nor is it the chosen door.

Here's the error I get when running my code:

```<code>line 52, in <module>

     doors()

line 14, in doors

     while goatDoor == chosenDoor or goatDoor == winningDoor:

NameError: name 'chosenDoor' is not defined
</code>```

My issue is that I can't tell why it keeps saying that chosenDoor is not defined!

Here's the code:

```<code>import random

def chooseDoor():   # choose a door
    chosenDoor = ''
    while chosenDoor != 1 and chosenDoor != 2 and chosenDoor != 3:
        print('Choose a door. (1, 2 or 3)')
        chosenDoor = input()
        return chosenDoor
    print('You chose door number ' + str(chosenDoor) + '.')

def doors():    # the winning door and the dummy door are randomly selected
    winningDoor = random.randint(1,3)
    goatDoor = ''
    while goatDoor == chosenDoor or goatDoor == winningDoor:
        goatDoor = random.randint(1, 3)

def keepOrSwitch():
    switchDoor = 1
    if switchDoor == chosenDoor or switchDoor == winningDoor:
        switchDoor = 2
        if switchDoor == chosenDoor or switchDoor == winningDoor:
            switchDoor = 3
    print('Do you want to')
    print('KEEP your choice of door number ' + str(chosenDoor) + '?')
    print('...or...')
    print('Do you want to')
    print('SWITCH and choose door number ' + str(switchDoor) + '?')
    print()
    choice = ''
    while True:
        print('Type \'K\' for keep or type \'S\' for switch.')
        choice = input()
        if choice == 'K' or choice == 'k':
            break
        if choice == 'S' or choice == 's':
            chosenDoor = switchDoor
            break

def checkWin():
    if chosenDoor == winningDoor:
        print('You win!')
    if chosenDoor != winningDoor:
        print('You lose!')

# the rest of the code is the actual game
playAgain = 'yes'
while playAgain == 'yes' or playAgain == 'y':

    chooseDoor()

    doors()

    keepOrSwitch()

    checkWin()

    print('Do you want to play again? (yes or no)')
    playAgain = input()
</code>```

答:
In your function:

```<code>def checkWin():
    if chosenDoor == winningDoor:
        print('You win!')
    if chosenDoor != winningDoor:
        print('You lose!')
</code>```

you try to compare chosenDoor to winningDoor, but they are not yet defined. The function checkWin() has no access to localy defined variables in other functions.

You have to refactor your code. Eventually you could assign some parameters to the function checkWin and return some values from the other functions.

Also:

```<code># the rest of the code is the actual game
</code>```

can be replaced by:

```<code>if __name__ == "__main__":
    # your actual game
</code>```

This is the standard way to run a Python program. If you import anything from this module in another file, the code won't run by accident.

EDIT:
the error is actually caused by this line:

```<code>while goatDoor == chosenDoor or goatDoor == winningDoor:
</code>```

In your function doors() you define goatDoor and winningDoor, but chosenDoor is not declared.

In the function keepOrSwitch() you have the same problem.

Nevertheless the function checkWin() will cause an error, too.

You have to refactor your function chooseDoor() too. It has a print statement after the return statement. It enters the while loop and will finish the function call never reaching the last line.

The simplest way to fix this would be to assign the return value of chooseDoor to a variable:

```<code>choosenDoorByTheUser = chooseDoor()
</code>```

and later call the other functions with that variable as argument.

Body:
All my code is below.

Just started learning to program this week. I'm attempting to make a Monty Hall simulator (text only) where the player chooses a door by selecting 1, 2 or 3. For some reason, though, Python doesn't seem to be recognizing the input!

Here are links to the game for the uninitiated:

Monty Hall wikipedia page

Monty Hall simulation

What my program attempts to do is as follows. First the player chooses a door, either 1, 2 or 3. Then the program checks to make sure that the player did indeed enter one of those three numbers. If not, then the person needs to choose again.

After this, the game randomly chooses a winning door. Then, per the rules of the game, the program needs to reveal a dummy prize (the goat). So the program randomly chooses one of the doors to be the "goat door." The program first makes sure that this door is not the winning door nor is it the chosen door.

Here's the error I get when running my code:

line 52, in <module>

     doors()

line 14, in doors

     while goatDoor == chosenDoor or goatDoor == winningDoor:

NameError: name 'chosenDoor' is not defined

My issue is that I can't tell why it keeps saying that chosenDoor is not defined!

Here's the code:

import random

def chooseDoor():   # choose a door
    chosenDoor = ''
    while chosenDoor != 1 and chosenDoor != 2 and chosenDoor != 3:
        print('Choose a door. (1, 2 or 3)')
        chosenDoor = input()
        return chosenDoor
    print('You chose door number ' + str(chosenDoor) + '.')

def doors():    # the winning door and the dummy door are randomly selected
    winningDoor = random.randint(1,3)
    goatDoor = ''
    while goatDoor == chosenDoor or goatDoor == winningDoor:
        goatDoor = random.randint(1, 3)

def keepOrSwitch():
    switchDoor = 1
    if switchDoor == chosenDoor or switchDoor == winningDoor:
        switchDoor = 2
        if switchDoor == chosenDoor or switchDoor == winningDoor:
            switchDoor = 3
    print('Do you want to')
    print('KEEP your choice of door number ' + str(chosenDoor) + '?')
    print('...or...')
    print('Do you want to')
    print('SWITCH and choose door number ' + str(switchDoor) + '?')
    print()
    choice = ''
    while True:
        print('Type \'K\' for keep or type \'S\' for switch.')
        choice = input()
        if choice == 'K' or choice == 'k':
            break
        if choice == 'S' or choice == 's':
            chosenDoor = switchDoor
            break

def checkWin():
    if chosenDoor == winningDoor:
        print('You win!')
    if chosenDoor != winningDoor:
        print('You lose!')

# the rest of the code is the actual game
playAgain = 'yes'
while playAgain == 'yes' or playAgain == 'y':

    chooseDoor()

    doors()

    keepOrSwitch()

    checkWin()

    print('Do you want to play again? (yes or no)')
    playAgain = input()

Body:
In your function:

def checkWin():
    if chosenDoor == winningDoor:
        print('You win!')
    if chosenDoor != winningDoor:
        print('You lose!')

you try to compare chosenDoor to winningDoor, but they are not yet defined. The function checkWin() has no access to localy defined variables in other functions.

You have to refactor your code. Eventually you could assign some parameters to the function checkWin and return some values from the other functions.

Also:

# the rest of the code is the actual game

can be replaced by:

if __name__ == "__main__":
    # your actual game

This is the standard way to run a Python program. If you import anything from this module in another file, the code won't run by accident.

EDIT:
the error is actually caused by this line:

while goatDoor == chosenDoor or goatDoor == winningDoor:

In your function doors() you define goatDoor and winningDoor, but chosenDoor is not declared.

In the function keepOrSwitch() you have the same problem.

Nevertheless the function checkWin() will cause an error, too.

You have to refactor your function chooseDoor() too. It has a print statement after the return statement. It enters the while loop and will finish the function call never reaching the last line.

The simplest way to fix this would be to assign the return value of chooseDoor to a variable:

choosenDoorByTheUser = chooseDoor()

and later call the other functions with that variable as argument.


问:
ASP.NET Export to Excel, if filename contains character # or /, it is converted into underscore(_) while poping-up the open/save dialog!
```<code>string filename = "Category#FileName";

response.AddHeader("content-disposition", "attachment; filename=" + filename);
response.ContentType = "text/csv";
response.AddHeader("Pragma", "public");
</code>```

Final file name => Category_FileName

I would appreciate your help here, pls help!

答:
Sadly this is a limitation of IE.

According to Microsoft, the following characters will be converted to underscores if you use them in the file attachment's filename attribute:

```<code><   Left angle bracket
>   Right angle bracket
\   Backslash
"   Quotation mark
/   Slash mark
:   Colon
|   Vertical bar
?   Question mark
*   Asterisk
    Space
</code>```

See https://support.microsoft.com/en-us/help/949197/certain-characters-in-a-file-name-may-be-converted-to-underscores-when-a-user-downloads-a-file-by-using-windows-internet-explorer-7

Body:
string filename = "Category#FileName";

response.AddHeader("content-disposition", "attachment; filename=" + filename);
response.ContentType = "text/csv";
response.AddHeader("Pragma", "public");

Final file name => Category_FileName

I would appreciate your help here, pls help!

Body:
Sadly this is a limitation of IE.

According to Microsoft, the following characters will be converted to underscores if you use them in the file attachment's filename attribute:

<   Left angle bracket
>   Right angle bracket
\   Backslash
"   Quotation mark
/   Slash mark
:   Colon
|   Vertical bar
?   Question mark
*   Asterisk
    Space

See https://support.microsoft.com/en-us/help/949197/certain-characters-in-a-file-name-may-be-converted-to-underscores-when-a-user-downloads-a-file-by-using-windows-internet-explorer-7


问:
CSS animation - position to original place
I wanted to play with css animation today.

So my basic idea was to create four circle then when user clicks on that circle then it should go to centre of page and then it should become other shape.

So I have used, transform and animation properties.

This is code I have written till now.

$(".circle").click(function(){
  if($(this).hasClass('centerOfPage')){
    $(this).removeClass('centerOfPage');
  }else{
    $(this).addClass('centerOfPage');
  }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.circle{
  width: 100px;
  height: 100px;
  border-radius: 50%;
  margin: 10px;
}
.one{
  background-color: red;
}
.two{
  background-color: blue;
}
.three{
  background-color: yellow;
}
.four{
  background-color: green;
}

 .centerOfPage{
    position: fixed;
    top: 50%;
    left: 50%;
    width: 100%;
    height: 100%;
    border-radius: 5%;
   -webkit-transform: translate(-50%, -50%);
    transform: translate(-50%, -50%);
    animation : centerOfPageAnimate 3s;

}
@keyframes centerOfPageAnimate {
  0% {
    top: 0%;
    left: 0%;
    width: 100px;
    height: 100px;
    border-radius: 50%;
    transform: translate(0, 0);
  }
  100% {
    top: 50%;
    left: 50%;
    -webkit-transform: translate(-50%, -50%);
    transform: translate(-50%, -50%);
    width: 100%;
    height: 100%;
    border-radius: 5%;
  }
}</code>```

```

Now Here there are some problems which you will notice..

When you click on any circles then their animation will start from top corner not from where they are.

When you again click on div then they are going back to their position but its not animated, again I want that animation from other shape to circle and on to their same position.

Here is codepen for same.
Thanks.

答:
Is this maybe what you're looking for?

the centerOfPage class is now only there to start the animation, no additional positioning, and using % in the keyframe declaration we can first move it to the center of the page and then make it bigger ( you could also add inbetween steps if you'd like)

$(".circle").click(function(){
  $(this).toggleClass('centerOfPage'); //toggleClass saves you the if else
 });```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.circle{
  width: 100px;
  height: 100px;
  border-radius: 50%;
  margin: 10px;
  transition: all 2s linear;  /* added transition to animate going back to start state*/
}
.one{
  background-color: red;

}
.two{
  background-color: blue;
}
.three{
  background-color: yellow;
}
.four{
  background-color: green;
}

 .centerOfPage{

    animation: test 2s forwards; /* add "forwards" here to stop the animation at end-frame */
  }

  @keyframes test{
   /* You can use percent to target steps during your animation:
      here it moves to the center at 10% animation duration and gets bigger    at 100 % animation duration
    */
  10%{
  transform: translate(50%);
  }
  100%{
  width: 100vw;
  height: 100vh;
   border-radius: 5%;
  }
}</code>```

```

Body:
I wanted to play with css animation today.

So my basic idea was to create four circle then when user clicks on that circle then it should go to centre of page and then it should become other shape.

So I have used, transform and animation properties.

This is code I have written till now.

$(".circle").click(function(){
  if($(this).hasClass('centerOfPage')){
    $(this).removeClass('centerOfPage');
  }else{
    $(this).addClass('centerOfPage');
  }
});

.circle{
  width: 100px;
  height: 100px;
  border-radius: 50%;
  margin: 10px;
}
.one{
  background-color: red;
}
.two{
  background-color: blue;
}
.three{
  background-color: yellow;
}
.four{
  background-color: green;
}

 .centerOfPage{
    position: fixed;
    top: 50%;
    left: 50%;
    width: 100%;
    height: 100%;
    border-radius: 5%;
   -webkit-transform: translate(-50%, -50%);
    transform: translate(-50%, -50%);
    animation : centerOfPageAnimate 3s;

}
@keyframes centerOfPageAnimate {
  0% {
    top: 0%;
    left: 0%;
    width: 100px;
    height: 100px;
    border-radius: 50%;
    transform: translate(0, 0);
  }
  100% {
    top: 50%;
    left: 50%;
    -webkit-transform: translate(-50%, -50%);
    transform: translate(-50%, -50%);
    width: 100%;
    height: 100%;
    border-radius: 5%;
  }
}

Now Here there are some problems which you will notice..

When you click on any circles then their animation will start from top corner not from where they are.

When you again click on div then they are going back to their position but its not animated, again I want that animation from other shape to circle and on to their same position.

Here is codepen for same.
Thanks.

Body:
Is this maybe what you're looking for?

the centerOfPage class is now only there to start the animation, no additional positioning, and using % in the keyframe declaration we can first move it to the center of the page and then make it bigger ( you could also add inbetween steps if you'd like)

$(".circle").click(function(){
  $(this).toggleClass('centerOfPage'); //toggleClass saves you the if else
 });

.circle{
  width: 100px;
  height: 100px;
  border-radius: 50%;
  margin: 10px;
  transition: all 2s linear;  /* added transition to animate going back to start state*/
}
.one{
  background-color: red;

}
.two{
  background-color: blue;
}
.three{
  background-color: yellow;
}
.four{
  background-color: green;
}

 .centerOfPage{

    animation: test 2s forwards; /* add "forwards" here to stop the animation at end-frame */
  }

  @keyframes test{
   /* You can use percent to target steps during your animation:
      here it moves to the center at 10% animation duration and gets bigger    at 100 % animation duration
    */
  10%{
  transform: translate(50%);
  }
  100%{
  width: 100vw;
  height: 100vh;
   border-radius: 5%;
  }
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="container">
  <div class="circle one"></div>
  <div class="circle two"></div>
  <div class="circle three"></div>
  <div class="circle four"></div>
</div>


问:
If database record limit reached return to previous page with message
I am building out our membership levels and each one has limits on how many records one can save to the database.  Someone on a laracasts said I would want to check the limit against the membership level in an observer and if the limit has been reached redirect them to the previous page and show an error.

This seems to be working except it redirects with the message that the limit has been reach AND creates the records.  Ideally it should not create the record if the limit has been reached.  I don't know what I am doing wrong, I also tried to return false; instead of return back(); but that didnt work either.

(by the way if there is an easier way to do this I am all ears)

Here is my observer:

```<code><?php

namespace App\Observers;

use App\Company;
use Auth;
use Session;

class SubscriptionLimits {

    public function __construct(){
        $this->company =  Auth::user()->company_id;
    }

    public function creating()
    {
      try {
                $company = Company::find($this->company);

                $clients = \App\Client::where(['company_id' => $this->company])->count();
                $contacts = \App\Contact::where(['company_id' => $this->company])->count();
                $leads = \App\Lead::where(['company_id' => $this->company])->count();
                $opportunities = \App\Opportunity::where(['company_id' => $this->company])->count();
                $invoices = \App\Invoice::where(['company_id' => $this->company])->count();
                $estimates = \App\Estimate::where(['company_id' => $this->company])->count();
                $proposals = \App\Proposal::where(['company_id' => $this->company])->count();
                $projects = \App\Project::where(['company_id' => $this->company])->count();
                $tasks = \App\Task::where(['company_id' => $this->company])->count();
                $boards = \App\Board::where(['company_id' => $this->company])->count();
                $bulletins = \App\Bulletin::where(['company_id' => $this->company])->count();
                $cards = \App\Card::where(['company_id' => $this->company])->count();
                $lineitems = \App\LineItem::where(['company_id' => $this->company])->count();
                $notes = \App\Note::where(['company_id' => $this->company])->count();
                $timer = \App\Timer::where(['company_id' => $this->company])->count();
                $templates = \App\Template::where(['company_id' => $this->company])->count();
                $userExtra = \App\UserExtra::where(['company_id' => $this->company])->count();

                $count = $clients + $contacts + $leads + $opportunities + $invoices + $estimates + $proposals + $projects + $tasks + $boards + $bulletins + $cards + $lineitems + $notes + $timer + $templates + $userExtra;

                if($count >= 5 && !$company->subscriptions){ //Free tier throw error because limit is reached
                    //return false; //Works but throws error
                    Session::flash('error', 'You have reached your record limit, please <a href="/order">upgrade now</a> to continue');
                    return back();
                }

                if($company->subscribed('middle_tier_monthly_per_user') || $company->subscribed('middle_tier_annual_per_user')){
                    if($count > 10){ //If middle tier and limit is reached
                        //return false; //Works but throws error
                        Session::flash('error', 'You have reached your record limit, please <a href="/order">upgrade now</a> to continue');
                        return back();
                    }
                }
            } catch (Exception $e) {
                Session::flash('error', 'You have reached your record limit, please <a href="/order">upgrade now</a> to continue');
                return back();
            }
    }

}
</code>```

UPDATE
Here is a video of the issue, this should not let me create a record and should instead return the limit reached message and prompt me to upgrade.

答: Just dd() in each 'if' and let me know where is the condition failing by taking 1 extra record.</p>

Body:
I am building out our membership levels and each one has limits on how many records one can save to the database.  Someone on a laracasts said I would want to check the limit against the membership level in an observer and if the limit has been reached redirect them to the previous page and show an error.

This seems to be working except it redirects with the message that the limit has been reach AND creates the records.  Ideally it should not create the record if the limit has been reached.  I don't know what I am doing wrong, I also tried to return false; instead of return back(); but that didnt work either.

(by the way if there is an easier way to do this I am all ears)

Here is my observer:

<?php

namespace App\Observers;

use App\Company;
use Auth;
use Session;

class SubscriptionLimits {

    public function __construct(){
        $this->company =  Auth::user()->company_id;
    }

    public function creating()
    {
      try {
                $company = Company::find($this->company);

                $clients = \App\Client::where(['company_id' => $this->company])->count();
                $contacts = \App\Contact::where(['company_id' => $this->company])->count();
                $leads = \App\Lead::where(['company_id' => $this->company])->count();
                $opportunities = \App\Opportunity::where(['company_id' => $this->company])->count();
                $invoices = \App\Invoice::where(['company_id' => $this->company])->count();
                $estimates = \App\Estimate::where(['company_id' => $this->company])->count();
                $proposals = \App\Proposal::where(['company_id' => $this->company])->count();
                $projects = \App\Project::where(['company_id' => $this->company])->count();
                $tasks = \App\Task::where(['company_id' => $this->company])->count();
                $boards = \App\Board::where(['company_id' => $this->company])->count();
                $bulletins = \App\Bulletin::where(['company_id' => $this->company])->count();
                $cards = \App\Card::where(['company_id' => $this->company])->count();
                $lineitems = \App\LineItem::where(['company_id' => $this->company])->count();
                $notes = \App\Note::where(['company_id' => $this->company])->count();
                $timer = \App\Timer::where(['company_id' => $this->company])->count();
                $templates = \App\Template::where(['company_id' => $this->company])->count();
                $userExtra = \App\UserExtra::where(['company_id' => $this->company])->count();

                $count = $clients + $contacts + $leads + $opportunities + $invoices + $estimates + $proposals + $projects + $tasks + $boards + $bulletins + $cards + $lineitems + $notes + $timer + $templates + $userExtra;

                if($count >= 5 && !$company->subscriptions){ //Free tier throw error because limit is reached
                    //return false; //Works but throws error
                    Session::flash('error', 'You have reached your record limit, please upgrade now to continue');
                    return back();
                }

                if($company->subscribed('middle_tier_monthly_per_user') || $company->subscribed('middle_tier_annual_per_user')){
                    if($count > 10){ //If middle tier and limit is reached
                        //return false; //Works but throws error
                        Session::flash('error', 'You have reached your record limit, please upgrade now to continue');
                        return back();
                    }
                }
            } catch (Exception $e) {
                Session::flash('error', 'You have reached your record limit, please upgrade now to continue');
                return back();
            }
    }

}

UPDATE
Here is a video of the issue, this should not let me create a record and should instead return the limit reached message and prompt me to upgrade.


问:
averaging by months with daily data
I have daily data with my matrix, divided into 6 columns -  "Years, months, days, ssts, anoms, missing ".

I want to calculate the average of each month of SST in each year. (For example - 1981 - september - avg values sts of all days in sept), and I want to do the same for all the years. i am trying to work, my code, but am unable to do so.

答:
just suppose that your data is stored in a data.frame named "data":</p>

```<code>years months        SSTs
1  1981      1 -0.46939368
2  1981      1  0.03226932
3  1981      1 -1.60266798
4  1981      1 -1.53095676
5  1981      1  1.71177023
6  1981      1 -0.61309846

tapply(data$SSTs, list(data$years, data$months), mean)
tapply(data$SSTs, factor(data$years), mean)
</code>```

Title: averaging by months with daily data

Body:
just suppose that your data is stored in a data.frame named "data":

years months        SSTs
1  1981      1 -0.46939368
2  1981      1  0.03226932
3  1981      1 -1.60266798
4  1981      1 -1.53095676
5  1981      1  1.71177023
6  1981      1 -0.61309846

tapply(data$SSTs, list(data$years, data$months), mean)
tapply(data$SSTs, factor(data$years), mean)


问:
Assigning word from text file to array
```<code>person1 bob
person2 george
person3 tom
</code>```

This is a project on VB. I am attempting to read off a text file such as the above and assign the second word on each line to an array. For example, array(1) would be "bob", array(2) would have "george", and array(3) would have "tom". I am currently having trouble with assigning to arrays as my current output for array(1) is:

```<code>bob
george
tom
</code>```

My current attempt is:

```<code>Dim FileName As String = "*snip*"
Dim FileReader As StreamReader = File.OpenText(FileName)
Dim FileLine As String = FileReader.ReadLine()
For x = 1 To 18
    Dim players() As String = FileLine.Split(New Char() {" "c})
    FileLine = FileReader.ReadLine()
    Console.WriteLine(players(1))
    count = count + 1
Next
</code>```

I'm a total noob, please treat me well.

答:
```<code>Sub GetPeople()

    ' use List instead of Array as you won't have to know
    ' the length of the array before declaring it.
    Dim personList As List(Of String) = New List(Of String)

    ' this holds the path to your file
    Dim fname As String

    ' will hold the name of the person
    Dim personName As String

    fname = "[your file path here]"

    Dim reader As System.IO.StreamReader
    reader = New IO.StreamReader(fname)
    Dim line As String
    While (Not reader.EndOfStream)
        line = reader.ReadLine()

        ' after you read a line, you call the GetPersonName function
        personName = GetPersonName(line)
        personList.Add(personName)
    End While

    reader.Close()

    ' the names you are interested in are in personList now:
    dim i as long
    for i = 0 to personList.Count - 1
         Console.WriteLine(personList(i))
    next i
End Sub

Function GetPersonName(lineText As String) As String
    Dim Result As String
    Dim stringLength As Long
    Dim spaceIndex As Long
    spaceIndex = lineText.IndexOf(" ")
    stringLength = (lineText.Count - spaceIndex) - 1
    Result = lineText.Substring((spaceIndex + 1), stringLength)
    Return Result
End Function
</code>```

I hope this helps.

Title: Assigning word from text file to array

Body:
person1 bob
person2 george
person3 tom

This is a project on VB. I am attempting to read off a text file such as the above and assign the second word on each line to an array. For example, array(1) would be "bob", array(2) would have "george", and array(3) would have "tom". I am currently having trouble with assigning to arrays as my current output for array(1) is:

bob
george
tom

My current attempt is:

Dim FileName As String = "*snip*"
Dim FileReader As StreamReader = File.OpenText(FileName)
Dim FileLine As String = FileReader.ReadLine()
For x = 1 To 18
    Dim players() As String = FileLine.Split(New Char() {" "c})
    FileLine = FileReader.ReadLine()
    Console.WriteLine(players(1))
    count = count + 1
Next

I'm a total noob, please treat me well.

Body:
Sub GetPeople()

    ' use List instead of Array as you won't have to know
    ' the length of the array before declaring it.
    Dim personList As List(Of String) = New List(Of String)

    ' this holds the path to your file
    Dim fname As String

    ' will hold the name of the person
    Dim personName As String

    fname = "[your file path here]"

    Dim reader As System.IO.StreamReader
    reader = New IO.StreamReader(fname)
    Dim line As String
    While (Not reader.EndOfStream)
        line = reader.ReadLine()

        ' after you read a line, you call the GetPersonName function
        personName = GetPersonName(line)
        personList.Add(personName)
    End While

    reader.Close()

    ' the names you are interested in are in personList now:
    dim i as long
    for i = 0 to personList.Count - 1
         Console.WriteLine(personList(i))
    next i
End Sub

Function GetPersonName(lineText As String) As String
    Dim Result As String
    Dim stringLength As Long
    Dim spaceIndex As Long
    spaceIndex = lineText.IndexOf(" ")
    stringLength = (lineText.Count - spaceIndex) - 1
    Result = lineText.Substring((spaceIndex + 1), stringLength)
    Return Result
End Function

I hope this helps.


问:
Spring Integration is consuming more memory all the time
We have a Spring Boot app, with a Spring Integration context, consuming from ActiveMQ queues.

Without messages in the queues it's consuming more and more memory, and after several hours we always run out of memory.

It doesnt seem to do anything, but memory consumed ( heap ) is increasing constantly at a small pace.

How can we avoid this or at least profile this ?

答:
I've been using these JVM options since moving to JDK 8.  Perhaps they'll help your situation:

```<code>-Xms1024m -Xmx1024m -XX:MaxMetaspaceExpansion=0 -XX:+UseConcMarkSweepGC -server -XX:+CMSParallelRemarkEnabled -XX:+UseCMSInitiatingOccupancyOnly -XX:CMSInitiatingOccupancyFraction=70 -XX:MaxDirectMemorySize=256M -XX:+ScavengeBeforeFullGC -XX:+CMSScavengeBeforeRemark
</code>```

Have a look at this blog post.  I found it very useful in tuning GC for JDK 8.

Body:
I've been using these JVM options since moving to JDK 8.  Perhaps they'll help your situation:

-Xms1024m -Xmx1024m -XX:MaxMetaspaceExpansion=0 -XX:+UseConcMarkSweepGC -server -XX:+CMSParallelRemarkEnabled -XX:+UseCMSInitiatingOccupancyOnly -XX:CMSInitiatingOccupancyFraction=70 -XX:MaxDirectMemorySize=256M -XX:+ScavengeBeforeFullGC -XX:+CMSScavengeBeforeRemark

Have a look at this blog post.  I found it very useful in tuning GC for JDK 8.


问:
Android FloatingActionMenu not showing labels
I'm trying to implement a Floating Button Action using this framework. My problem is that the items of the menu have the same size of the main button, even using "mini" and the text of the labels don't show. Image bellow:

The XML:

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:fab="http://schemas.android.com/tools">

    <com.github.clans.fab.FloatingActionMenu
        android:id="@+id/material_design_android_floating_action_menu"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentRight="true"
        android:layout_marginBottom="63dp"
        android:layout_marginLeft="11dp"
        android:layout_marginRight="11dp"
        fab:menu_animationDelayPerItem="55"
        fab:menu_backgroundColor="@android:color/transparent"
        fab:menu_buttonSpacing="0dp"
        fab:menu_colorNormal="#da3c2f"
        fab:menu_colorPressed="#dc4b3f"
        fab:menu_colorRipple="#99d4d4d4"
        fab:menu_fab_label="Floating Action Menu"
        fab:menu_fab_size="normal"
        fab:menu_icon="@drawable/fab_add"
        fab:menu_labels_colorNormal="#333"
        fab:menu_labels_colorPressed="#444"
        fab:menu_labels_colorRipple="#66efecec"
        fab:menu_labels_cornerRadius="3dp"
        fab:menu_labels_ellipsize="none"
        fab:menu_labels_hideAnimation="@anim/fab_slide_out_to_right"
        fab:menu_labels_margin="0dp"
        fab:menu_labels_maxLines="-1"
        fab:menu_labels_padding="8dp"
        fab:menu_labels_position="left"
        fab:menu_labels_showAnimation="@anim/fab_slide_in_from_right"
        fab:menu_labels_showShadow="true"
        fab:menu_labels_singleLine="false"
        fab:menu_labels_textColor="#f2f1f1"
        fab:menu_labels_textSize="15sp"
        fab:menu_openDirection="up"
        fab:menu_shadowColor="#66aff198"
        fab:menu_shadowRadius="4dp"
        fab:menu_shadowXOffset="1dp"
        fab:menu_shadowYOffset="4dp"
        fab:menu_showShadow="true">

        <com.github.clans.fab.FloatingActionButton
            android:id="@+id/material_design_floating_action_menu_item1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/ic_star"
            fab:fab_label="Menu Item 1"
            fab:fab_size="mini" />

        <com.github.clans.fab.FloatingActionButton
            android:id="@+id/material_design_floating_action_menu_item2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/ic_star_half_empty"
            fab:fab_label="Menu Item 2"
            fab:fab_size="mini" />

        <com.github.clans.fab.FloatingActionButton
            android:id="@+id/material_design_floating_action_menu_item3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/ic_info"
            fab:fab_label="Menu Item 3"
            fab:fab_size="mini" />

    </com.github.clans.fab.FloatingActionMenu>

</RelativeLayout>
</code>```

I'm having a hard time to figure out what I'm missing to make it work like this

Thanks for any help.

答:
Change this:

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:fab="http://schemas.android.com/tools">
</code>```

to:

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:fab="http://schemas.android.com/apk/res-auto"
xmlns:app="http://schemas.android.com/tools">
</code>```

Notice the change in  xmlns:fab

Body:
I'm trying to implement a Floating Button Action using this framework. My problem is that the items of the menu have the same size of the main button, even using "mini" and the text of the labels don't show. Image bellow:

The XML:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:fab="http://schemas.android.com/tools">

    <com.github.clans.fab.FloatingActionMenu
        android:id="@+id/material_design_android_floating_action_menu"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentRight="true"
        android:layout_marginBottom="63dp"
        android:layout_marginLeft="11dp"
        android:layout_marginRight="11dp"
        fab:menu_animationDelayPerItem="55"
        fab:menu_backgroundColor="@android:color/transparent"
        fab:menu_buttonSpacing="0dp"
        fab:menu_colorNormal="#da3c2f"
        fab:menu_colorPressed="#dc4b3f"
        fab:menu_colorRipple="#99d4d4d4"
        fab:menu_fab_label="Floating Action Menu"
        fab:menu_fab_size="normal"
        fab:menu_icon="@drawable/fab_add"
        fab:menu_labels_colorNormal="#333"
        fab:menu_labels_colorPressed="#444"
        fab:menu_labels_colorRipple="#66efecec"
        fab:menu_labels_cornerRadius="3dp"
        fab:menu_labels_ellipsize="none"
        fab:menu_labels_hideAnimation="@anim/fab_slide_out_to_right"
        fab:menu_labels_margin="0dp"
        fab:menu_labels_maxLines="-1"
        fab:menu_labels_padding="8dp"
        fab:menu_labels_position="left"
        fab:menu_labels_showAnimation="@anim/fab_slide_in_from_right"
        fab:menu_labels_showShadow="true"
        fab:menu_labels_singleLine="false"
        fab:menu_labels_textColor="#f2f1f1"
        fab:menu_labels_textSize="15sp"
        fab:menu_openDirection="up"
        fab:menu_shadowColor="#66aff198"
        fab:menu_shadowRadius="4dp"
        fab:menu_shadowXOffset="1dp"
        fab:menu_shadowYOffset="4dp"
        fab:menu_showShadow="true">

        <com.github.clans.fab.FloatingActionButton
            android:id="@+id/material_design_floating_action_menu_item1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/ic_star"
            fab:fab_label="Menu Item 1"
            fab:fab_size="mini" />

        <com.github.clans.fab.FloatingActionButton
            android:id="@+id/material_design_floating_action_menu_item2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/ic_star_half_empty"
            fab:fab_label="Menu Item 2"
            fab:fab_size="mini" />

        <com.github.clans.fab.FloatingActionButton
            android:id="@+id/material_design_floating_action_menu_item3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/ic_info"
            fab:fab_label="Menu Item 3"
            fab:fab_size="mini" />

    </com.github.clans.fab.FloatingActionMenu>

</RelativeLayout>

I'm having a hard time to figure out what I'm missing to make it work like this

Thanks for any help.

Body:
Change this:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:fab="http://schemas.android.com/tools">

to:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:fab="http://schemas.android.com/apk/res-auto"
xmlns:app="http://schemas.android.com/tools">

Notice the change in  xmlns:fab


问:
How to mock a dictionary?
First, I'd better ask if I should mock dictionaries? And if I should how can I achieve that?

I am using Rhino Mocks. I looked through its documentation and saw that it can mock ArrayList. So I tried it on Dictionary but no luck. I got the error that I'm not calling a virtual method bla bla... Will it be a problem if I don't mock it?

答:
You can only mock interfaces, or classes with virtual methods: you can't mock a Dictionary<K,V>, but you can mock an IDictionary<K,V>.

It depends on your situation, but it might be enough to construct a real dictionary, and fill it with mock objects.

Title: How to mock a dictionary?


问:
CMake ExternalProject_Add() that uses a parent folder in its include_directories()
I have an 'int_tester' CMake project that makes use of ExternalProject_Add for its 'drv' dependency. Now, this 'drv' is also built using CMake, and it uses a parent directory in its include_directories(). Trouble is that I do not know how to copy this parent folder inside ExternalProject_Add().

Directory structure is like:

```<code>/
|-common
|-IP
| |-int_tester
| |-drv
</code>```

CMakeLists.txt for drv looks like:

```<code>add_library(SPT_driver STATIC ${CMAKE_CURRENT_SOURCE_DIR}/src/*.c)
target_include_directories(SPT_driver
    PUBLIC  ${CMAKE_CURRENT_SOURCE_DIR}/api/
    PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/../../common/include/
)
</code>```

CMakeLists.txt for int_tester like:

```<code>add_executable(int_tester ...)
ExternalProject_Add(drv_ext
    PREFIX ${CMAKE_CURRENT_BINARY_DIR}/drv/drv_dir
    URL ${CMAKE_CURRENT_SOURCE_DIR}/../drv
    INSTALL_COMMAND ""
)
add_library(drv_import STATIC IMPORTED) #phony lib
add_dependencies (drv_import drv_ext) #link phony lib to the external proj
ExternalProject_Get_Property(drv_ext install_dir) #find out where the external proj is installed
set_property(TARGET drv_import PROPERTY IMPORTED_LOCATION ${install_dir}/src/drv_ext-build/obj/drv.a) #so that the phony lib can have a target
include_directories(${install_dir}/src/drv_ext/api) #and to make current executable dependent on api .h and .a of the externally built lib
target_link_libraries(int_tester drv_import)
</code>```

As one can see, drv depends on ${CMAKE_CURRENT_SOURCE_DIR}/../../common/include/.

When 'int_tester' builds 'drv' (via ExternalProject_Add), folder ../../common/include/ cannot be found (it is not brought it by ExternalProject_Add). Even if I add another fake ExternProject for this common folder, its directory structure will not match the one expected by CMakeLists.txt of 'drv'.

What am I missing, please?

答:
If you want to build 'drv' using IP/drv as its source directory, explicitely specify SOURCE_DIR option for ExternalProject_Add:

```<code>ExternalProject_Add(drv_ext
    PREFIX ${CMAKE_CURRENT_BINARY_DIR}/drv/drv_dir
    SOURCE_DIR ${CMAKE_CURRENT_SOURCE_DIR}/../drv
    INSTALL_COMMAND ""
)
</code>```

Without this option, source directory is deduced from PREFX (see documentation for exact algorithm of that deduction).

Option URL for ExternalProject_Add denotes directory, which should be copied into the source one. If you do not want to copy, do not use that option.

Body:
I have an 'int_tester' CMake project that makes use of ExternalProject_Add for its 'drv' dependency. Now, this 'drv' is also built using CMake, and it uses a parent directory in its include_directories(). Trouble is that I do not know how to copy this parent folder inside ExternalProject_Add().

Directory structure is like:

/
|-common
|-IP
| |-int_tester
| |-drv

CMakeLists.txt for drv looks like:

add_library(SPT_driver STATIC ${CMAKE_CURRENT_SOURCE_DIR}/src/*.c)
target_include_directories(SPT_driver
    PUBLIC  ${CMAKE_CURRENT_SOURCE_DIR}/api/
    PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/../../common/include/
)

CMakeLists.txt for int_tester like:

add_executable(int_tester ...)
ExternalProject_Add(drv_ext
    PREFIX ${CMAKE_CURRENT_BINARY_DIR}/drv/drv_dir
    URL ${CMAKE_CURRENT_SOURCE_DIR}/../drv
    INSTALL_COMMAND ""
)
add_library(drv_import STATIC IMPORTED) #phony lib
add_dependencies (drv_import drv_ext) #link phony lib to the external proj
ExternalProject_Get_Property(drv_ext install_dir) #find out where the external proj is installed
set_property(TARGET drv_import PROPERTY IMPORTED_LOCATION ${install_dir}/src/drv_ext-build/obj/drv.a) #so that the phony lib can have a target
include_directories(${install_dir}/src/drv_ext/api) #and to make current executable dependent on api .h and .a of the externally built lib
target_link_libraries(int_tester drv_import)

As one can see, drv depends on ${CMAKE_CURRENT_SOURCE_DIR}/../../common/include/.

When 'int_tester' builds 'drv' (via ExternalProject_Add), folder ../../common/include/ cannot be found (it is not brought it by ExternalProject_Add). Even if I add another fake ExternProject for this common folder, its directory structure will not match the one expected by CMakeLists.txt of 'drv'.

What am I missing, please?

Body:
If you want to build 'drv' using IP/drv as its source directory, explicitely specify SOURCE_DIR option for ExternalProject_Add:

ExternalProject_Add(drv_ext
    PREFIX ${CMAKE_CURRENT_BINARY_DIR}/drv/drv_dir
    SOURCE_DIR ${CMAKE_CURRENT_SOURCE_DIR}/../drv
    INSTALL_COMMAND ""
)

Without this option, source directory is deduced from PREFX (see documentation for exact algorithm of that deduction).

Option URL for ExternalProject_Add denotes directory, which should be copied into the source one. If you do not want to copy, do not use that option.


问:
Is changing the color of a cell based on nested conditionals possible?
I have been trying to change the color of certain cells on my WS that fall outside of an acceptable range. The statement I've been trying to use is,

```<code>IF(OR('cell'>1.3,'cell'<2.5),'turn red','do nothing')
</code>```

In english, "If a cell is less than 1.3 or greater than 2.5 turn red, else do nothing." I cannot find a resource that guides me to how I can get the cells to change colors. I also have been unsuccessful in creating a statement in the Conditional Formatting tab that satisfies my goal. I feel this should be simple, but for some reason cannot figure it out. Does anyone know if this is possible, and if so how to do it?
EDIT: Also, I have different ranges based on another cell on the spreadsheet. I need this also taken into consideration

答:
Select the columns that you want to format

Click Conditional format --> new rule

Select "Use a formula to determine which cells to format"

In the formula bar enter the formula =AND(A1>1.3,A1<2.5)

Choose the fill color as red and press OK

am confused with your formula and your english version. If its the other way, then use the formula =OR(A1<1.3,A1>2.5)

Body:
I have been trying to change the color of certain cells on my WS that fall outside of an acceptable range. The statement I've been trying to use is,

IF(OR('cell'>1.3,'cell'<2.5),'turn red','do nothing')

In english, "If a cell is less than 1.3 or greater than 2.5 turn red, else do nothing." I cannot find a resource that guides me to how I can get the cells to change colors. I also have been unsuccessful in creating a statement in the Conditional Formatting tab that satisfies my goal. I feel this should be simple, but for some reason cannot figure it out. Does anyone know if this is possible, and if so how to do it?
EDIT: Also, I have different ranges based on another cell on the spreadsheet. I need this also taken into consideration


问:
Pigscript Logic Implementation
I am new to pigscript. I am stuck while working on the example below.  Could anyone help me on how to get the Output specified below using pigscript?

Input:

```<code>1|ABC|NC
1|DEF|NC
2|CFD|NY
2|CGF|NY
</code>```

Output:

```<code>1|ABC,DEF|NC
2|CFD,CGF|NY
</code>```

Script:

```<code>A = LOAD 'testfile.txt' USING PigStorage('|') AS (Id:chararray,name:chararray,state:chararray);
B = FOREACH A GENERATE Id,name;
C = FOREACH A GENERATE Id,name,state;
C = DISTINCT C;
GROUPED = GROUP B BY Id;
D = FOREACH GROUPED GENERATE group AS Id,c.name AS name_val;
E = JOIN D BY Id, C BY Id;
X = FOREACH E GENERATE D.Id as docid,D.name_val as termid,C.state;
Dump X;
</code>```

答:
Load the data and group by 1st and 3rd column and then generate the columns,order to get the desired output.</p>

```<code>A = LOAD 'input.txt' USING PigStorage('|') AS (f1:int,f2:chararray;f3:chararray);
B = GROUP A BY f1,f3;
C = FOREACH B GENERATE FLATTEN(group) as (f1,f3),A.f2 AS f2;
D = FOREACH C GENERATE f1,f2,f3;
DUMP D;
</code>```

Title: Pigscript Logic Implementation

Body:
I am new to pigscript. I am stuck while working on the example below.  Could anyone help me on how to get the Output specified below using pigscript?

Input:

1|ABC|NC
1|DEF|NC
2|CFD|NY
2|CGF|NY

Output:

1|ABC,DEF|NC
2|CFD,CGF|NY

Script:

A = LOAD 'testfile.txt' USING PigStorage('|') AS (Id:chararray,name:chararray,state:chararray);
B = FOREACH A GENERATE Id,name;
C = FOREACH A GENERATE Id,name,state;
C = DISTINCT C;
GROUPED = GROUP B BY Id;
D = FOREACH GROUPED GENERATE group AS Id,c.name AS name_val;
E = JOIN D BY Id, C BY Id;
X = FOREACH E GENERATE D.Id as docid,D.name_val as termid,C.state;
Dump X;

Body:
Load the data and group by 1st and 3rd column and then generate the columns,order to get the desired output.

A = LOAD 'input.txt' USING PigStorage('|') AS (f1:int,f2:chararray;f3:chararray);
B = GROUP A BY f1,f3;
C = FOREACH B GENERATE FLATTEN(group) as (f1,f3),A.f2 AS f2;
D = FOREACH C GENERATE f1,f2,f3;
DUMP D;


问:
How can I select different websites from a table?
I'm working on a sort of bonus challenge with Project 4 from Hacking With Swift, and I'm not sure how to select a different websites from a table view. I have a table view that goes to a detail view with a web view, but I'm not sure where to go from here.

my view controller

```<code>import UIKit

class ViewController: UITableViewController {

var websites = ["apple.com", "hackingwithswift.com"]

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    //THIS DISPLAYS THE WEBSITE NAMES IN THE TABLE ROWS
    return websites.count
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "Website", for: indexPath)
    //THIS DISPLAYS A WEBSITE NAME IN EACH CELL
    cell.textLabel?.text = websites[indexPath.row]
    return cell
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    if let vc = storyboard?.instantiateViewController(withIdentifier: "Detail") as? DetailViewController {
        vc.selectedWebsite = websites[indexPath.row]
        //THIS PIECE BELOW LOADS ANIMATES THE NEW VIEW CONTROLLER
        navigationController?.pushViewController(vc, animated: true)
    }
}
</code>```

}

and my detail view controller

```<code>import UIKit
import WebKit

class DetailViewController: UIViewController, WKNavigationDelegate {

var selectedWebsite: String?
var webView: WKWebView!

override func loadView() {
    webView = WKWebView()
    webView.navigationDelegate = self
    view = webView
}

override func viewDidLoad() {
    let url = URL(string: "https://www.hackingwithswift.com")!
    webView.load(URLRequest(url: url))
    webView.allowsBackForwardNavigationGestures = true
    // Do any additional setup after loading the view.
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

/*
// MARK: - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    // Get the new view controller using segue.destinationViewController.
    // Pass the selected object to the new view controller.
}
*/

}
</code>```

Thanks in advance for any ideas. I'm new to this and feel clueless as to what to do.

答:
Just pass the selected url to URL in your DetailViewController viewDidLoad()

```<code>let url = URL(string: selectedWebsite!)!
</code>```

Body:
I'm working on a sort of bonus challenge with Project 4 from Hacking With Swift, and I'm not sure how to select a different websites from a table view. I have a table view that goes to a detail view with a web view, but I'm not sure where to go from here.

my view controller

import UIKit

class ViewController: UITableViewController {

var websites = ["apple.com", "hackingwithswift.com"]

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    //THIS DISPLAYS THE WEBSITE NAMES IN THE TABLE ROWS
    return websites.count
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "Website", for: indexPath)
    //THIS DISPLAYS A WEBSITE NAME IN EACH CELL
    cell.textLabel?.text = websites[indexPath.row]
    return cell
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    if let vc = storyboard?.instantiateViewController(withIdentifier: "Detail") as? DetailViewController {
        vc.selectedWebsite = websites[indexPath.row]
        //THIS PIECE BELOW LOADS ANIMATES THE NEW VIEW CONTROLLER
        navigationController?.pushViewController(vc, animated: true)
    }
}

}

and my detail view controller

import UIKit
import WebKit

class DetailViewController: UIViewController, WKNavigationDelegate {

var selectedWebsite: String?
var webView: WKWebView!

override func loadView() {
    webView = WKWebView()
    webView.navigationDelegate = self
    view = webView
}

override func viewDidLoad() {
    let url = URL(string: "https://www.hackingwithswift.com")!
    webView.load(URLRequest(url: url))
    webView.allowsBackForwardNavigationGestures = true
    // Do any additional setup after loading the view.
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

/*
// MARK: - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    // Get the new view controller using segue.destinationViewController.
    // Pass the selected object to the new view controller.
}
*/

}

Thanks in advance for any ideas. I'm new to this and feel clueless as to what to do.

Body:
Just pass the selected url to URL in your DetailViewController viewDidLoad()

let url = URL(string: selectedWebsite!)!