问:
Handmade Estimator modifies parameters in __init__?
I am preparing a tailored preprocessing phase which is suppose to become part of a sklearn.pipeline.Pipeline. Here's the code of the preprocessor:

```<code>import string
from nltk import wordpunct_tokenize
from nltk.stem.snowball import SnowballStemmer
from nltk import sent_tokenize
from sklearn.base import BaseEstimator, TransformerMixin
from . import stopwords

class NLTKPreprocessor(BaseEstimator, TransformerMixin):
    def __init__(self, stopwords=stopwords.STOPWORDS_DE,
                 punct=string.punctuation,
                 lower=True, strip=True, lang='german'):
        """
        Based on:
        https://bbengfort.github.io/tutorials/2016/05/19/text-classification-nltk-sckit-learn.html
        """

        self.lower = lower
        self.strip = strip
        self.stopwords = set(stopwords)
        self.punct = set(punct)
        self.stemmer = SnowballStemmer(lang)
        self.lang = lang

    def fit(self, X, y=None):
        return self

    def inverse_transform(self, X):
        return [" ".join(doc) for doc in X]

    def transform(self, X):
        return [
            list(self.tokenize(doc)) for doc in X
        ]

    def tokenize(self, document):
        # Break the document into sentences
        for sent in sent_tokenize(document, self.lang):
            for token in wordpunct_tokenize(sent):
                # Apply preprocessing to the token
                token = token.lower() if self.lower else token
                token = token.strip() if self.strip else token
                token = token.strip('_') if self.strip else token
                token = token.strip('*') if self.strip else token

                # If stopword, ignore token and continue
                if token in self.stopwords:
                    continue

                # If punctuation, ignore token and continue
                if all(char in self.punct for char in token):
                    continue

                # Lemmatize the token and yield
                # lemma = self.lemmatize(token, tag)
                stem = self.stemmer.stem(token)
                yield stem
</code>```

Next, here is the pipeline I construct:

```<code>pipeline = Pipeline(
    [
        ('preprocess', nltkPreprocessor),
        ('vectorize', TfidfVectorizer(tokenizer=identity, preprocessor=None, lowercase=False)),
        ('clf', SGDClassifier(max_iter=1000, tol=1e-3))
    ]
)
</code>```

This all works nicely for a single pass; for example pipeline.fit(X,y) works nicely. However, when putting this pipeline inside a grid search

```<code>parameters = {
    'vectorize__use_idf': (True, False),
    'vectorize__max_df': np.arange(0.8, 1.01 ,0.05),
    'vectorize__smooth_idf': (True, False),
    'vectorize__sublinear_tf': (True, False),
    'vectorize__norm': ('l1', 'l2'),
    'clf__loss':  ('hinge', 'log', 'modified_huber', 'squared_hinge', 'perceptron'),
    'clf__alpha': (0.00001, 0.000001),
    'clf__penalty': ('l1', 'l2', 'elasticnet')
}
grid_search = GridSearchCV(pipeline, parameters, n_jobs=-1, verbose=1)
grid_search.fit(X_train, y_train)
</code>```

I get the following warning:

```<code>/Users/user/anaconda3/envs/myenv/lib/python3.6/site-packages/sklearn/base.py:115: DeprecationWarning: Estimator NLTKPreprocessor modifies parameters in __init__. This behavior is deprecated as of 0.18 and support for this behavior will be removed in 0.20.
  % type(estimator).__name__, DeprecationWarning)
</code>```

I don't understand what should be changed/fixed in the implementation. How can I maintain the functionality and remove the warning?

答:
Check out the developer guide of sklearn, here and the following paragraph. I would try to cohere as much to it as possible to make sure such messages are avoided (even if you never intend to contribute it).

They prescribe that estimators should have no logic in the __init__ function! This most likely causes your error.

I put my validation or transformation of init parameters (as prescribed also in the description) at the beginning of the fit() method, which has to be called in any case.

Also, note this utility which you can use to test your estimator if it confirms to the scikit learn API.

Edit (as response to your comment, but with code formatting):

Well, not logic. To quote from the links:
"To summarize, an __init__ should look like:

```<code>def __init__(self, param1=1, param2=2):
    self.param1 = param1
    self.param2 = param2
</code>```

There should be no logic, not even input validation, and the parameters should not be changed." 1

So I guess as @uberwach detailed the set construction and creation of SnowballStemmer instance probably violates the "should not be changed"part.

Edit 2:

As addition to the below comment. This would be one general way of doing it (another specific as mentioned by @uberwach later in your tokenize method):

```<code>class NLTKPreprocessor(BaseEstimator, TransformerMixin):
    def __init__(self, stopwords=stopwords.STOPWORDS_DE,
                 punct=string.punctuation,
                 lower=True, strip=True, lang='german'):
        self.lower = lower
        self.strip = strip
        self.stopwords = stopwords
        self.punct = punct
        self.lang = lang

    def fit(self, X, y=None):
        self.stopword_set = set(self.stopwords)
        self.punct_set = set(self.punct)
        self.stemmer = SnowballStemmer(self.lang)
        return self
</code>```

Body:
I am preparing a tailored preprocessing phase which is suppose to become part of a sklearn.pipeline.Pipeline. Here's the code of the preprocessor:

import string
from nltk import wordpunct_tokenize
from nltk.stem.snowball import SnowballStemmer
from nltk import sent_tokenize
from sklearn.base import BaseEstimator, TransformerMixin
from . import stopwords

class NLTKPreprocessor(BaseEstimator, TransformerMixin):
    def __init__(self, stopwords=stopwords.STOPWORDS_DE,
                 punct=string.punctuation,
                 lower=True, strip=True, lang='german'):
        """
        Based on:
        https://bbengfort.github.io/tutorials/2016/05/19/text-classification-nltk-sckit-learn.html
        """

        self.lower = lower
        self.strip = strip
        self.stopwords = set(stopwords)
        self.punct = set(punct)
        self.stemmer = SnowballStemmer(lang)
        self.lang = lang

    def fit(self, X, y=None):
        return self

    def inverse_transform(self, X):
        return [" ".join(doc) for doc in X]

    def transform(self, X):
        return [
            list(self.tokenize(doc)) for doc in X
        ]

    def tokenize(self, document):
        # Break the document into sentences
        for sent in sent_tokenize(document, self.lang):
            for token in wordpunct_tokenize(sent):
                # Apply preprocessing to the token
                token = token.lower() if self.lower else token
                token = token.strip() if self.strip else token
                token = token.strip('_') if self.strip else token
                token = token.strip('*') if self.strip else token

                # If stopword, ignore token and continue
                if token in self.stopwords:
                    continue

                # If punctuation, ignore token and continue
                if all(char in self.punct for char in token):
                    continue

                # Lemmatize the token and yield
                # lemma = self.lemmatize(token, tag)
                stem = self.stemmer.stem(token)
                yield stem

Next, here is the pipeline I construct:

pipeline = Pipeline(
    [
        ('preprocess', nltkPreprocessor),
        ('vectorize', TfidfVectorizer(tokenizer=identity, preprocessor=None, lowercase=False)),
        ('clf', SGDClassifier(max_iter=1000, tol=1e-3))
    ]
)

This all works nicely for a single pass; for example pipeline.fit(X,y) works nicely. However, when putting this pipeline inside a grid search

parameters = {
    'vectorize__use_idf': (True, False),
    'vectorize__max_df': np.arange(0.8, 1.01 ,0.05),
    'vectorize__smooth_idf': (True, False),
    'vectorize__sublinear_tf': (True, False),
    'vectorize__norm': ('l1', 'l2'),
    'clf__loss':  ('hinge', 'log', 'modified_huber', 'squared_hinge', 'perceptron'),
    'clf__alpha': (0.00001, 0.000001),
    'clf__penalty': ('l1', 'l2', 'elasticnet')
}
grid_search = GridSearchCV(pipeline, parameters, n_jobs=-1, verbose=1)
grid_search.fit(X_train, y_train)

I get the following warning:

/Users/user/anaconda3/envs/myenv/lib/python3.6/site-packages/sklearn/base.py:115: DeprecationWarning: Estimator NLTKPreprocessor modifies parameters in __init__. This behavior is deprecated as of 0.18 and support for this behavior will be removed in 0.20.
  % type(estimator).__name__, DeprecationWarning)

I don't understand what should be changed/fixed in the implementation. How can I maintain the functionality and remove the warning?

Body:
Check out the developer guide of sklearn, here and the following paragraph. I would try to cohere as much to it as possible to make sure such messages are avoided (even if you never intend to contribute it).

They prescribe that estimators should have no logic in the __init__ function! This most likely causes your error.

I put my validation or transformation of init parameters (as prescribed also in the description) at the beginning of the fit() method, which has to be called in any case.

Also, note this utility which you can use to test your estimator if it confirms to the scikit learn API.

Edit (as response to your comment, but with code formatting):

Well, not logic. To quote from the links:
"To summarize, an __init__ should look like:

def __init__(self, param1=1, param2=2):
    self.param1 = param1
    self.param2 = param2

There should be no logic, not even input validation, and the parameters should not be changed." 1

So I guess as @uberwach detailed the set construction and creation of SnowballStemmer instance probably violates the "should not be changed"part.

Edit 2:

As addition to the below comment. This would be one general way of doing it (another specific as mentioned by @uberwach later in your tokenize method):

class NLTKPreprocessor(BaseEstimator, TransformerMixin):
    def __init__(self, stopwords=stopwords.STOPWORDS_DE,
                 punct=string.punctuation,
                 lower=True, strip=True, lang='german'):
        self.lower = lower
        self.strip = strip
        self.stopwords = stopwords
        self.punct = punct
        self.lang = lang

    def fit(self, X, y=None):
        self.stopword_set = set(self.stopwords)
        self.punct_set = set(self.punct)
        self.stemmer = SnowballStemmer(self.lang)
        return self


来源: stackexchange

问:
What type of database is suited for realtime aggregated operations on millions of rows
I need to store 15-30 millions of rows of data. Most of the queries will be group by operations (aggregations). I'm currently using Teradata as the database backend. But the response time is not real-time (some queries are taking about 30 seconds). I was looking into Cassandra as a substitute but in some documentation, I found that if there are group by operations, then Cassandra is not the best option.

What database would be most suited for my use case given that a maximum of 100 users will use the application at a time (along with data updates happening in parallel)? Any traditional RDBMS can handle this kind of requirements?

Any help would be appreciated. Thanks in advance.

答:
Teradata is designed to handle very large datasets with parallelism in mind and should scale mostly linearly.  In other words, add more horsepower to your resource-bound queries and get better performance.

What bottlenecks do you have with your current 30-second queries?  Can you post a sample query with an EXPLAIN to look at?  It could be that a quick optimization will speed it up -- STATISTICs, index selection, join indexes, PPI (table partitioning), etc.

ContentLicense: CC BY-SA 3.0


问:
How to write interface for the response for angular's must httpclient
I am trying to fetch the data from api using the angular's new httpclient, I get the error property doesnt exist on type IMessage[]. How do i write an interface for the following response,

```<code>{"data":{"Messages":[{"Id":28,"MessageContent":"test data tsn","FromUserId":"74df8f98-2925-4242-8d32-8b09f3691396","UserName":"365@test.com","ToUserId":"96b1c943-ade0-4026-b8ed-0f4a6231e586","ProductId":null,"ParentMessageId":null,"Subject":"Test Message by Dev Team","StyleNumber":null}],"Pagination":{"Page":1,"PageLength":20,"TotalRecords":20,"TotalPages":1},"MessageLimit":{"TotalMessageCount":5,"RemainingMessageCount":3}}}
</code>```

What i tried here,

```<code>export interface IMessage {
    data: {
        Messages: Messages[];
    };
}

interface Messages {
    id: number;
    messageContent: string;
    fromUserId: string;
    toUserId: string;
    productId?: number;
    parentMessageId?: number;
    subject: string;
    styleNumber?: string;
}
</code>```

My code on stackblitz

```<code>// Here is the code
    import { Component, Input, OnInit } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { IMessage } from './message.interface';
import { HttpClient, HttpResponse, HttpParams, HttpHeaders } from '@angular/common/http';

@Component({
  selector: 'hello',
  template: `<h1>Hello {{name}}!</h1>`,
  styles: [`h1 { font-family: Lato; }`]
})
export class HelloComponent implements OnInit  {
  constructor (private http: HttpClient) {
        console.log('Message repository service instance');
    }
        readonly ROOT_URL = '//52.70.78.117:7111/api/message';
ngOnInit() {
    this.getAllMessages();
  }
  @Input() name: string;
  messages;
  getAllMessages(): Observable<IMessage[]> {
    this.getAllMessagesFromApi()
    .subscribe(data => {
      console.log('data is =>', data.data);
      this.messages = data;
    },
    err => {
      console.log('Error occured while fetching message List');
    });
    return;
  }
  getAllMessagesFromApi(): Observable<IMessage[]> {
      return this.http.get<IMessage[]>(`${this.ROOT_URL}/list`);
  }
}
</code>```

答:
You should change what type your getAllMessagesFromAPI() method returns to IMessage

```<code>// method returns type IMessage
getAllMessagesFromApi(): Observable<IMessage> {
    // http request returns type IMessage
    return this.http.get<IMessage>(`${this.ROOT_URL}/list`);
}
</code>```

Now you can access your array of messages

```<code>.subscribe(data => {
    this.messages = data.data.Messages;
},
</code>```

Body:
I am trying to fetch the data from api using the angular's new httpclient, I get the error property doesnt exist on type IMessage[]. How do i write an interface for the following response,

{"data":{"Messages":[{"Id":28,"MessageContent":"test data tsn","FromUserId":"74df8f98-2925-4242-8d32-8b09f3691396","UserName":"365@test.com","ToUserId":"96b1c943-ade0-4026-b8ed-0f4a6231e586","ProductId":null,"ParentMessageId":null,"Subject":"Test Message by Dev Team","StyleNumber":null}],"Pagination":{"Page":1,"PageLength":20,"TotalRecords":20,"TotalPages":1},"MessageLimit":{"TotalMessageCount":5,"RemainingMessageCount":3}}}

What i tried here,

export interface IMessage {
    data: {
        Messages: Messages[];
    };
}

interface Messages {
    id: number;
    messageContent: string;
    fromUserId: string;
    toUserId: string;
    productId?: number;
    parentMessageId?: number;
    subject: string;
    styleNumber?: string;
}

My code on stackblitz

// Here is the code
    import { Component, Input, OnInit } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { IMessage } from './message.interface';
import { HttpClient, HttpResponse, HttpParams, HttpHeaders } from '@angular/common/http';

@Component({
  selector: 'hello',
  template: `<h1>Hello {{name}}!</h1>`,
  styles: [`h1 { font-family: Lato; }`]
})
export class HelloComponent implements OnInit  {
  constructor (private http: HttpClient) {
        console.log('Message repository service instance');
    }
        readonly ROOT_URL = '//52.70.78.117:7111/api/message';
ngOnInit() {
    this.getAllMessages();
  }
  @Input() name: string;
  messages;
  getAllMessages(): Observable<IMessage[]> {
    this.getAllMessagesFromApi()
    .subscribe(data => {
      console.log('data is =>', data.data);
      this.messages = data;
    },
    err => {
      console.log('Error occured while fetching message List');
    });
    return;
  }
  getAllMessagesFromApi(): Observable<IMessage[]> {
      return this.http.get<IMessage[]>(`${this.ROOT_URL}/list`);
  }
}

Body:
You should change what type your getAllMessagesFromAPI() method returns to IMessage

// method returns type IMessage
getAllMessagesFromApi(): Observable<IMessage> {
    // http request returns type IMessage
    return this.http.get<IMessage>(`${this.ROOT_URL}/list`);
}

Now you can access your array of messages

.subscribe(data => {
    this.messages = data.data.Messages;
},


问:
RenderPartial control in same view folder
I have a file in my view folder Users called UserViewControl.cshtml.

My code in the actual view (Users.cshtml) is:

```<code>@Html.RenderPartial("RegisterViewControl")
</code>```

Error:The best overloaded method match for 'System.Web.WebPages.WebPageExecutingBase.Write(System.Web.WebPages.HelperResult)' has some invalid arguments

I do not want to type the path fully like this as the whole view folders might move in the future:

```<code>@Html.RenderPartial("~/Views/Users/RegisterViewControl.cshtml")
</code>```

Code in RegisterViewControl.cshtml:

```<code>@model SampleMVC.Web.ViewModels.RegisterModel

@using (Html.BeginForm("Register", "Auth", FormMethod.Post, new { Id = "ERForm" }))
{
    @Html.TextBoxFor(model => model.Name)
    @Html.TextBoxFor(model => model.Email)
    @Html.PasswordFor(model => model.Password)
}
</code>```

This is a form that will be submitted by ajax, but I want all the validation from the viewmodel.

答:
It should be like this:

```<code>@{Html.RenderPartial("RegisterViewControl");}
</code>```

And that's because the RenderPartial extension method doesn't return anything. It writes directly to the output. In aspx you use it like this:

```<code><% Html.RenderPartial("RegisterViewControl"); %>
</code>```

instead of:

```<code><%= Html.RenderPartial("RegisterViewControl") %>
</code>```

So the same rules apply for razor.

ContentLicense: CC BY-SA 2.5

Body:
I have a file in my view folder Users called UserViewControl.cshtml.

My code in the actual view (Users.cshtml) is:

@Html.RenderPartial("RegisterViewControl")

Error:The best overloaded method match for 'System.Web.WebPages.WebPageExecutingBase.Write(System.Web.WebPages.HelperResult)' has some invalid arguments

I do not want to type the path fully like this as the whole view folders might move in the future:

@Html.RenderPartial("~/Views/Users/RegisterViewControl.cshtml")

Code in RegisterViewControl.cshtml:

@model SampleMVC.Web.ViewModels.RegisterModel

@using (Html.BeginForm("Register", "Auth", FormMethod.Post, new { Id = "ERForm" }))
{
    @Html.TextBoxFor(model => model.Name)
    @Html.TextBoxFor(model => model.Email)
    @Html.PasswordFor(model => model.Password)
}

This is a form that will be submitted by ajax, but I want all the validation from the viewmodel.

Body:
It should be like this:

@{Html.RenderPartial("RegisterViewControl");}

And that's because the RenderPartial extension method doesn't return anything. It writes directly to the output. In aspx you use it like this:

<% Html.RenderPartial("RegisterViewControl"); %>

instead of:

<%= Html.RenderPartial("RegisterViewControl") %>

So the same rules apply for razor.


问:
Filter PHAssetCollections within radius of CLLocationCoordinate2d
I'm using the Photos framework (aka PhotoKit). In my app I need to gather Moments (which are of type PHAssetCollection). PHAssetCollection has a property of CLLocation *approximateLocation.

However I cannot get the NSPredicate to work when I retrieve the Moments from PhotoKit.

```<code>-(void)getMomentsNearCoordinate:(CLLocationCoordinate2D)coordinate completionBlock:(PKAssetManagerArrayBlock)completionBlock{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        PHFetchOptions *options = [[PHFetchOptions alloc] init];
        options.predicate = [NSPredicate predicateWithFormat:@"approximateLocation.coordinate.latitude < 37.0"];

        self.moments = [PHAssetCollection fetchMomentsWithOptions:options];

        // Convert PHCollection into NSArray
        NSMutableArray *momentsArray = [[NSMutableArray alloc]initWithCapacity:self.moments.count];
        [self.moments enumerateObjectsUsingBlock:^(PHAssetCollection *moment, NSUInteger idx, BOOL *stop) {
            [momentsArray addObject:moment];
        }];

        dispatch_async(dispatch_get_main_queue(), ^{
            completionBlock([NSArray arrayWithArray:momentsArray]);
        });
    });
}
</code>```

The debugger will stop on

```<code>self.moments = [PHAssetCollection fetchMomentsWithOptions:options];
</code>```

with the error:

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Unsupported predicate in fetch
  options: approximateLocation.coordinate.latitude < 37'

This seems strange since I can use NSPredicate to filter by startDate or endDate.

Anyhow, next I thought I'd try the NSPredicate with block:

```<code>-(void)getMomentsNearCoordinate:(CLLocationCoordinate2D)coordinate completionBlock:(PKAssetManagerArrayBlock)completionBlock{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        PHFetchOptions *options = [[PHFetchOptions alloc] init];
        options.predicate = [NSPredicate predicateWithBlock:^BOOL(id evaluatedObject, NSDictionary *bindings) {
            // Logic goes here
            return YES;
        }];

        self.moments = [PHAssetCollection fetchMomentsWithOptions:options];

        // Convert PHCollection into NSArray
        NSMutableArray *momentsArray = [[NSMutableArray alloc]initWithCapacity:self.moments.count];
        [self.moments enumerateObjectsUsingBlock:^(PHAssetCollection *moment, NSUInteger idx, BOOL *stop) {
            [momentsArray addObject:moment];
        }];
        dispatch_async(dispatch_get_main_queue(), ^{
            completionBlock([NSArray arrayWithArray:momentsArray]);
        });
    });
}
</code>```

Again the debugger stops at

```<code>self.moments = [PHAssetCollection fetchMomentsWithOptions:options];
</code>```

with a different error message:

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Unsupported predicate in fetch
  options: BLOCKPREDICATE(0x27d338)'

Finally I remembered reading in CloudKit documentation that they added a new support for filtering by distance. However this is for CKQuery, not NSPredicate. I decided to give it a try anyhow. I use my coordinate to make a CLLocation then call:

```<code>-(void)getMomentsNearLocation:(CLLocation*)location completionBlock:(PKAssetManagerArrayBlock)completionBlock{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        PHFetchOptions *options = [[PHFetchOptions alloc] init];
        options.predicate = [NSPredicate predicateWithFormat:@"distanceToLocation:fromLocation:(%K,%@) < %f",
                             location,
                             2.0];

        self.moments = [PHAssetCollection fetchMomentsWithOptions:options];

        // Convert PHCollection into NSArray
        NSMutableArray *momentsArray = [[NSMutableArray alloc]initWithCapacity:self.moments.count];
        [self.moments enumerateObjectsUsingBlock:^(PHAssetCollection *moment, NSUInteger idx, BOOL *stop) {
            [momentsArray addObject:moment];
        }];
        dispatch_async(dispatch_get_main_queue(), ^{
            completionBlock([NSArray arrayWithArray:momentsArray]);
        });
    });
}
</code>```

You guessed it. Error:

```<code>*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[CLLocation rangeOfString:]: unrecognized selector sent to instance 0x19e3e350'
</code>```

In the mean time I'll just iterate through the list of PHAssetCollections and manually calculate if it's near the CLLocation. This will be far less efficient.

答:
If you look at Table 1 of the PHFetchOptions documentation, you will see that you can only use the following keys for predicate filtering of PHAssetCollections:

```<code>SELF
localIdentifier
localizedTitle (or title)
startDate
endDate
estimatedAssetCount
</code>```

if you want to filter a PHCollection (as opposed to an PHAssetCollection), then you are limited to the following keys:

```<code>SELF
localIdentifier
localizedTitle (or title)
startDate
endDate
</code>```

Nothing resembling "approximateLocation" is a support key. But wait!  The localizedTitle is generally a place name. Have not seen it otherwise. So, you might be able to get assets by predicate filtering moment collections

Body:
I'm using the Photos framework (aka PhotoKit). In my app I need to gather Moments (which are of type PHAssetCollection). PHAssetCollection has a property of CLLocation *approximateLocation.

However I cannot get the NSPredicate to work when I retrieve the Moments from PhotoKit.

-(void)getMomentsNearCoordinate:(CLLocationCoordinate2D)coordinate completionBlock:(PKAssetManagerArrayBlock)completionBlock{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        PHFetchOptions *options = [[PHFetchOptions alloc] init];
        options.predicate = [NSPredicate predicateWithFormat:@"approximateLocation.coordinate.latitude < 37.0"];

        self.moments = [PHAssetCollection fetchMomentsWithOptions:options];

        // Convert PHCollection into NSArray
        NSMutableArray *momentsArray = [[NSMutableArray alloc]initWithCapacity:self.moments.count];
        [self.moments enumerateObjectsUsingBlock:^(PHAssetCollection *moment, NSUInteger idx, BOOL *stop) {
            [momentsArray addObject:moment];
        }];

        dispatch_async(dispatch_get_main_queue(), ^{
            completionBlock([NSArray arrayWithArray:momentsArray]);
        });
    });
}

The debugger will stop on

self.moments = [PHAssetCollection fetchMomentsWithOptions:options];

with the error:

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Unsupported predicate in fetch
  options: approximateLocation.coordinate.latitude < 37'

This seems strange since I can use NSPredicate to filter by startDate or endDate.

Anyhow, next I thought I'd try the NSPredicate with block:

-(void)getMomentsNearCoordinate:(CLLocationCoordinate2D)coordinate completionBlock:(PKAssetManagerArrayBlock)completionBlock{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        PHFetchOptions *options = [[PHFetchOptions alloc] init];
        options.predicate = [NSPredicate predicateWithBlock:^BOOL(id evaluatedObject, NSDictionary *bindings) {
            // Logic goes here
            return YES;
        }];

        self.moments = [PHAssetCollection fetchMomentsWithOptions:options];

        // Convert PHCollection into NSArray
        NSMutableArray *momentsArray = [[NSMutableArray alloc]initWithCapacity:self.moments.count];
        [self.moments enumerateObjectsUsingBlock:^(PHAssetCollection *moment, NSUInteger idx, BOOL *stop) {
            [momentsArray addObject:moment];
        }];
        dispatch_async(dispatch_get_main_queue(), ^{
            completionBlock([NSArray arrayWithArray:momentsArray]);
        });
    });
}

Again the debugger stops at

self.moments = [PHAssetCollection fetchMomentsWithOptions:options];

with a different error message:

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Unsupported predicate in fetch
  options: BLOCKPREDICATE(0x27d338)'

Finally I remembered reading in CloudKit documentation that they added a new support for filtering by distance. However this is for CKQuery, not NSPredicate. I decided to give it a try anyhow. I use my coordinate to make a CLLocation then call:

-(void)getMomentsNearLocation:(CLLocation*)location completionBlock:(PKAssetManagerArrayBlock)completionBlock{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        PHFetchOptions *options = [[PHFetchOptions alloc] init];
        options.predicate = [NSPredicate predicateWithFormat:@"distanceToLocation:fromLocation:(%K,%@) < %f",
                             location,
                             2.0];

        self.moments = [PHAssetCollection fetchMomentsWithOptions:options];

        // Convert PHCollection into NSArray
        NSMutableArray *momentsArray = [[NSMutableArray alloc]initWithCapacity:self.moments.count];
        [self.moments enumerateObjectsUsingBlock:^(PHAssetCollection *moment, NSUInteger idx, BOOL *stop) {
            [momentsArray addObject:moment];
        }];
        dispatch_async(dispatch_get_main_queue(), ^{
            completionBlock([NSArray arrayWithArray:momentsArray]);
        });
    });
}

You guessed it. Error:

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[CLLocation rangeOfString:]: unrecognized selector sent to instance 0x19e3e350'

In the mean time I'll just iterate through the list of PHAssetCollections and manually calculate if it's near the CLLocation. This will be far less efficient.

Body:
If you look at Table 1 of the PHFetchOptions documentation, you will see that you can only use the following keys for predicate filtering of PHAssetCollections:

SELF
localIdentifier
localizedTitle (or title)
startDate
endDate
estimatedAssetCount

if you want to filter a PHCollection (as opposed to an PHAssetCollection), then you are limited to the following keys:

SELF
localIdentifier
localizedTitle (or title)
startDate
endDate

Nothing resembling "approximateLocation" is a support key. But wait!  The localizedTitle is generally a place name. Have not seen it otherwise. So, you might be able to get assets by predicate filtering moment collections


问:
Circular buffer with fast lookup/insert/remove
I have a problem that I didn't find a solution that could be efficient enough. I need to speed up a circular buffer with a fixed size of 1.000.000 elements. It is currently implemented using a singly linked list.

For the moment, I have changed the implementation to use an array instead of the linked list. I use a write and read pointer to avoid shifting every index of my array. I need to do A LOT of lookup in my fifo, and I would need to delete items from indexes (well, I know it breaks the fifo rule).

First I was thinking of a sorted index table that matches the fifo array. It would be a O(log n) complexity for the lookup, but every time I'll need to update my fifo, I'll also need to update my index table. This is the part I didn't manage to do it efficiently (with a small complexity).

Any hints about an implementation that keeps track of the FIFO's order, and gives good performances in insert/delete/search operations ?

Thanks.

答:
One approach would be to use:

An array with n elements to store the items

A Fenwick tree with n elements to store the occupancy.

We use the Fenwick Tree to write a 1 whenever an element is present, or 0 if the element is not present.

Once you have this structure, you can find the k^th present element and perform deletions in O(logn) time.  (The actual implementation details may be a bit fiddly due to the FIFO wraparound - it may help to keep track of the total occupancy in the array and the occupancy from the pointer to the first element until the end of the array.)

Note that this structure will allow you to delete items anywhere, but only to insert items at the end of the FIFO - it is not clear whether this matches your requirements?


问:
Can't get an entity property
There is a problem with my Db which I figured only now, when I started to work at the web api.

 My USER entity:

```<code>public class User { get; set; }
{
    public int UserId { get; set; }
    public string Name { get; set; }
}
</code>```

And this is ACTIVITY

```<code>public class Activity

{
    public int ActivityId { get; set; }
    public User User { get; set; }
}
</code>```

I added an activity and checked in SSMS. Everything seems to be good, there is a field named UserId which stores the id. My problem is when I try to get a User from an Activity because I keep getting null objects. I didn't set anything special in my DbContext for this.

This is where I'm trying to get an User from an Activity object:

```<code>public ActionResult ActivityAuthor(int activityId)
{
    Activity activityItem = unitOfWork.Activity.Get(activityId);
    return Json(unitOfWork.User.Get(activityItem.User.UserId));
}
</code>```

Relation between User and Activity

答:
The User property of Activity class should be marked as virtual. It enables entity framework to make a proxy around the property and loads it more efficiently.

Somewhere in your code you should have a similar loading method as following :

```<code>using (var context = new MyDbContext())

{
    var activity = context.Activities
                        .Where(a => a.ActivityId == id)
                        .FirstOrDefault<Activity>();

   context.Entry(activity).Reference(a => a.User).Load(); // loads User

}
</code>```

This should load the User object and you won't have it null in your code.

Check this link for more information msdn

Title: Can't get an entity property

Body:
There is a problem with my Db which I figured only now, when I started to work at the web api.

 My USER entity:

public class User { get; set; }
{
    public int UserId { get; set; }
    public string Name { get; set; }
}

And this is ACTIVITY

public class Activity

{
    public int ActivityId { get; set; }
    public User User { get; set; }
}

I added an activity and checked in SSMS. Everything seems to be good, there is a field named UserId which stores the id. My problem is when I try to get a User from an Activity because I keep getting null objects. I didn't set anything special in my DbContext for this.

This is where I'm trying to get an User from an Activity object:

public ActionResult ActivityAuthor(int activityId)
{
    Activity activityItem = unitOfWork.Activity.Get(activityId);
    return Json(unitOfWork.User.Get(activityItem.User.UserId));
}

Relation between User and Activity

Body:
The User property of Activity class should be marked as virtual. It enables entity framework to make a proxy around the property and loads it more efficiently.

Somewhere in your code you should have a similar loading method as following :

using (var context = new MyDbContext())

{
    var activity = context.Activities
                        .Where(a => a.ActivityId == id)
                        .FirstOrDefault<Activity>();

   context.Entry(activity).Reference(a => a.User).Load(); // loads User

}

This should load the User object and you won't have it null in your code.

Check this link for more information msdn


问:
Need help finding an error in my C project
The project is to write a program that reads three integers and then prints them in order read and reversed. use four functions: main, one to read the data, one to print them in the order read, and one to print them reversed
I get the errors:

In fuction 'main':

[Error] expected declaration or statement at end of input

recipe for target 'main.o' failed

```<code>#include <stdio.h>
#include <stdlib.h>

/* run this program using the console pauser or add your own getch,
system("pause") or input loop */

int main(int argc, char *argv[]) {

int getData ( );
void printForward (int first, int second, int third);
void printReversed (int first, int second, int third);

int main (void)
{

int a;
int b;
int c;

a=getData();
b=getData();
c=getData();
printForward ( a, b, c);
printReversed ( a, b, c);

int getData();
{

int num;
printf ("Enter an integer: ");
scanf ("%d", &num);
return num;
}

void printForward (int a, int b, int c);

{
printf ("\nNumbers in order: %d, %d, and %d\n", a, b, c);
return;
}

void printReversed (int a, int b, int c);
{
printf ("\nNumbers reversed: %d, %d, and %d\n",
c, b, a);
return;
}
return 0;
}
</code>```

答:
Besides your nested function definitions there are lots of stray semicolons in your function definitions. Even if your compiler allows nested functions, you need to remove those

```<code>int getData();  <<<<===== remove trailing ;
{
...
}
</code>```

Same for printReversed and printForward.

Body:
The project is to write a program that reads three integers and then prints them in order read and reversed. use four functions: main, one to read the data, one to print them in the order read, and one to print them reversed
I get the errors:

In fuction 'main':

[Error] expected declaration or statement at end of input

recipe for target 'main.o' failed

#include <stdio.h>
#include <stdlib.h>

/* run this program using the console pauser or add your own getch,
system("pause") or input loop */

int main(int argc, char *argv[]) {

int getData ( );
void printForward (int first, int second, int third);
void printReversed (int first, int second, int third);

int main (void)
{

int a;
int b;
int c;

a=getData();
b=getData();
c=getData();
printForward ( a, b, c);
printReversed ( a, b, c);

int getData();
{

int num;
printf ("Enter an integer: ");
scanf ("%d", &num);
return num;
}

void printForward (int a, int b, int c);

{
printf ("\nNumbers in order: %d, %d, and %d\n", a, b, c);
return;
}

void printReversed (int a, int b, int c);
{
printf ("\nNumbers reversed: %d, %d, and %d\n",
c, b, a);
return;
}
return 0;
}

Body:
Besides your nested function definitions there are lots of stray semicolons in your function definitions. Even if your compiler allows nested functions, you need to remove those

int getData();  <<<<===== remove trailing ;
{
...
}

Same for printReversed and printForward.


问:
Logic: is ( A && !(B || C)) || ( B || C ) the same as ( A || B || C )?
I've encountered some obj-c code and I'm wondering if there's a way to simplify it:

```<code>#if ( A && !(B || C)) || ( B || C )
</code>```

is this the same as?

```<code>#if ( A || B || C )
</code>```

If not, is there another way to formulate it that would be easier to read?

[edit]
I tried the truth table before asking the question, but thought I had to be missing something because I doubted that Foundation.framework/Foundation.h would employ this more complex form.   Is there a good reason for it?

Here's the original code (from Foundation.h):

```<code>#if (TARGET_OS_MAC && !(TARGET_OS_EMBEDDED || TARGET_OS_IPHONE)) || (TARGET_OS_EMBEDDED || TARGET_OS_IPHONE)
</code>```

答: Get pen + paper + try it, there are only 8 possible inputs</p>

Body:
I've encountered some obj-c code and I'm wondering if there's a way to simplify it:

#if ( A && !(B || C)) || ( B || C )

is this the same as?

#if ( A || B || C )

If not, is there another way to formulate it that would be easier to read?

[edit]
I tried the truth table before asking the question, but thought I had to be missing something because I doubted that Foundation.framework/Foundation.h would employ this more complex form.   Is there a good reason for it?

Here's the original code (from Foundation.h):

#if (TARGET_OS_MAC && !(TARGET_OS_EMBEDDED || TARGET_OS_IPHONE)) || (TARGET_OS_EMBEDDED || TARGET_OS_IPHONE)


问:
How to update a TextView of an Activity from another class
I am new to Android/Java programming. I have two classes, one is an Activity and the other is a normal class. My activity class contains a TextView. Can I update the TextView of the activity class from a normal class? I tried with random code, but it fails.

```<code>// activity class
public class MainMenu extends Activity {
    public TextView txtView;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        TextView txtView = (TextView)findViewById(R.id.text);
    }
}

// Other class
public class ClassB {
    public ClassB() {
        public void Update() {
            TextView txtView = (TextView)findViewById(R.id.text);
            txtView.setText("Hello");
        }
    }
}
</code>```

答:
This is actually a deceptively "simple" question, but in reality a complicated problem in the context of Android development.

Activities are the "process entry point", meaning that any Activity you see can act as the "first point of entry to your application on start-up". People think that only the Activity that has the MAIN/LAUNCHER intent filter can be launched at start-up, but this is false.

Any Activity can act as the "first Activity", because Android can restart it from any point with the current active navigation stack.

Anyways, with that in mind, an Activity can show a View, and people often use the Activity to hold each screen of their app (instead of using it as an entry point, and swapping out view controllers in it ~ fragments).

So if you have multiple Activities, then you need to share data between them in such a way, that you take it into consideration that both activities can be started up at any time as the first Activity of the app.

For this, what you need to do is not "set the text view's text directly from another class", but you need to modify observable shared data.

The newly released official Android Architecture Components provide the LiveData<T> class, which has a subclass called MutableLiveData<T>.

To update the data from one class to another Activity, what you must do is have a global data exposed as a LiveData

```<code>public class MyApplication extends Application {
    private static MyApplication INSTANCE;

    DataRepository dataRepository; // this is YOUR class

    @Override
    public void onCreate() {
        super.onCreate();
        INSTANCE = this;
        dataRepository = new DataRepository();
    }

    public static MyApplication get() {
        return INSTANCE;
    }
}
</code>```

The DataRepository should expose LiveData:

```<code>public class DataRepository {
    private final MutableLiveData<MyData> data = new MutableLiveData<>();

    public LiveData<MyData> getMyData() {
        return data;
    }

    public void updateText(String text) {
        MyData newData = data.getValue()
                             .toBuilder() // immutable new copy
                             .setText(text)
                             .build();
        data.setValue(newData);
    }
}
</code>```

Where the Activity subscribes to this:

```<code>public class MyActivity extends BaseActivity {
    DataRepository dataRepository;

    TextView textView;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        MyApplication app = (MyApplication)getApplicationContext();
        dataRepository = app.getDataRepository();

        setContentView(R.layout.main_activity);
        textView = findViewById(R.id.textview);

        dataRepository.getMyData().observe(this, new Observer() {
            @Override
            public void onChange(MyObject myObject) {
                textView.setText(myObject.getText());
            }
        }
    }
</code>```

So to update this text, you need to get the DataRepository class, and call updateText on it:

```<code>DataRepository dataRepository = MyApplication.get().dataRepository();
dataRepository.updateText("my new text");
</code>```

And this will properly update your Activity text view.

Beware that you should also persist the data to onSaveInstanceState(Bundle so that it is not lost (assuming the data is not from disk).

To do that, you need to do the following:

```<code>public class BaseActivity extends AppCompatActivity {
    DataRepository dataRepository;

    private static boolean didRestoreGlobals = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        MyApplication app = (MyApplication)getApplicationContext();
        dataRepository = app.getDataRepository();

        super.onCreate(savedInstanceState);
        if(!didRestoreGlobals) {
            didRestoreGlobals = true;
            if(savedInstanceState != null) {
                dataRepository.restoreState(savedInstanceState.getBundle("dataRepository"));
            }
        }
    }

    @Override
    protected void onSaveInstanceState(Bundle bundle) {
        super.onSaveInstanceState(bundle);
        bundle.putBundle("dataRepository", dataRepository.saveState());
    }
}
</code>```

And then add saveState/restoreState methods to DataRepository accordingly.

ContentLicense: CC BY-SA 4.0

Body:
I am new to Android/Java programming. I have two classes, one is an Activity and the other is a normal class. My activity class contains a TextView. Can I update the TextView of the activity class from a normal class? I tried with random code, but it fails.

// activity class
public class MainMenu extends Activity {
    public TextView txtView;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        TextView txtView = (TextView)findViewById(R.id.text);
    }
}

// Other class
public class ClassB {
    public ClassB() {
        public void Update() {
            TextView txtView = (TextView)findViewById(R.id.text);
            txtView.setText("Hello");
        }
    }
}

Body:
This is actually a deceptively "simple" question, but in reality a complicated problem in the context of Android development.

Activities are the "process entry point", meaning that any Activity you see can act as the "first point of entry to your application on start-up". People think that only the Activity that has the MAIN/LAUNCHER intent filter can be launched at start-up, but this is false.

Any Activity can act as the "first Activity", because Android can restart it from any point with the current active navigation stack.

Anyways, with that in mind, an Activity can show a View, and people often use the Activity to hold each screen of their app (instead of using it as an entry point, and swapping out view controllers in it ~ fragments).

So if you have multiple Activities, then you need to share data between them in such a way, that you take it into consideration that both activities can be started up at any time as the first Activity of the app.

For this, what you need to do is not "set the text view's text directly from another class", but you need to modify observable shared data.

The newly released official Android Architecture Components provide the LiveData<T> class, which has a subclass called MutableLiveData<T>.

To update the data from one class to another Activity, what you must do is have a global data exposed as a LiveData

public class MyApplication extends Application {
    private static MyApplication INSTANCE;

    DataRepository dataRepository; // this is YOUR class

    @Override
    public void onCreate() {
        super.onCreate();
        INSTANCE = this;
        dataRepository = new DataRepository();
    }

    public static MyApplication get() {
        return INSTANCE;
    }
}

The DataRepository should expose LiveData:

public class DataRepository {
    private final MutableLiveData<MyData> data = new MutableLiveData<>();

    public LiveData<MyData> getMyData() {
        return data;
    }

    public void updateText(String text) {
        MyData newData = data.getValue()
                             .toBuilder() // immutable new copy
                             .setText(text)
                             .build();
        data.setValue(newData);
    }
}

Where the Activity subscribes to this:

public class MyActivity extends BaseActivity {
    DataRepository dataRepository;

    TextView textView;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        MyApplication app = (MyApplication)getApplicationContext();
        dataRepository = app.getDataRepository();

        setContentView(R.layout.main_activity);
        textView = findViewById(R.id.textview);

        dataRepository.getMyData().observe(this, new Observer() {
            @Override
            public void onChange(MyObject myObject) {
                textView.setText(myObject.getText());
            }
        }
    }

So to update this text, you need to get the DataRepository class, and call updateText on it:

DataRepository dataRepository = MyApplication.get().dataRepository();
dataRepository.updateText("my new text");

And this will properly update your Activity text view.

Beware that you should also persist the data to onSaveInstanceState(Bundle so that it is not lost (assuming the data is not from disk).

To do that, you need to do the following:

public class BaseActivity extends AppCompatActivity {
    DataRepository dataRepository;

    private static boolean didRestoreGlobals = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        MyApplication app = (MyApplication)getApplicationContext();
        dataRepository = app.getDataRepository();

        super.onCreate(savedInstanceState);
        if(!didRestoreGlobals) {
            didRestoreGlobals = true;
            if(savedInstanceState != null) {
                dataRepository.restoreState(savedInstanceState.getBundle("dataRepository"));
            }
        }
    }

    @Override
    protected void onSaveInstanceState(Bundle bundle) {
        super.onSaveInstanceState(bundle);
        bundle.putBundle("dataRepository", dataRepository.saveState());
    }
}

And then add saveState/restoreState methods to DataRepository accordingly.


问:
Pass Key of Grid to Business Class via Object Data Source
In ASP.NET Webforms have an ASP.NET GridView connected to a C# class via an object data source

I have an ID set up as a DataKeyName in the grid. How do I pass this to the C# class when I update the grid?

答:
Can pick up the grids data key name for the current row in the grids row updating event

```<code>  protected void gvSearchResults_RowUpdating(object sender, GridViewUpdateEventArgs e)
  {
    //get handle on current grid row
    DataKey keys = gvSearchResults.DataKeys[e.RowIndex];
   customerId= GeneralUtils.GetIntegerKeyValue(keys, "customerID");
  }
</code>```

Then pass it to C# class using object data sources updating event

```<code> protected void odsHauliers_Updating(object sender, ObjectDataSourceMethodEventArgs e)
  {

    e.InputParameters["customerID"] = this.customerID;
  }
</code>```

Body:
Can pick up the grids data key name for the current row in the grids row updating event

  protected void gvSearchResults_RowUpdating(object sender, GridViewUpdateEventArgs e)
  {
    //get handle on current grid row
    DataKey keys = gvSearchResults.DataKeys[e.RowIndex];
   customerId= GeneralUtils.GetIntegerKeyValue(keys, "customerID");
  }

Then pass it to C# class using object data sources updating event

 protected void odsHauliers_Updating(object sender, ObjectDataSourceMethodEventArgs e)
  {

    e.InputParameters["customerID"] = this.customerID;
  }


问:
How can get a members length if active property is true in ngFor
I have a array of objects and in ngFor I want to get the the members count if the member in a team is active. Like in below example first members array has 2 members but only one is active so I should get length or count 1, in second members array there are 2 members and both are active so counet should be 2. Is it possible to get it using ngFor or there is any other way. Any help is appreciated.

```<code>{
"name": "Team 1",
"members": [{
        "active": true,
        "fullName": "TEST",
        "teamId": "xxx"
    }, {
        "active": false,
        "fullName": "ghgfhfghgfh"
    }
],
"childTeam": [{
        "name": "CTeam1",
        "members": [{
                "active": true,
                "fullName": "fghfhgfh"
            }, {
                "active": true,
                "fullName": "retweew"
            }
        ]
    },{
        "name": "CTeam2",
        "members": [{
                "active": true,
                "fullName": "fghfhgfh"
            }, {
                "active": true,
                "fullName": "retweew"
            },
            {
                "active": true,
                "fullName": "ddgfdgd"
            }
        ]
       }
    ]
}
</code>```

And I am using it in ngFor as below -

```<code>    <div *ngFor="let membs of node.data.members; let i = index">
  <div *ngIf="membs.active && node.data.members.length === 1">
    <div class="pull-left leadIcon">
      <mat-icon *ngIf="membs.active">person</mat-icon>
    </div>
  </div>
  <div *ngIf="membs.active && node.data.members.length > 1">
    <div class="pull-left"> {{ node.data.members.length }}</div>
  </div>
</div>
</code>```

答:
The way on HTML

```<code> <div *ngIf="node.data.members.length >= 1">
    <div class="pull-left"> {{getActives()}}</div>
 </div>
</code>```

Do in TS:

```<code>getActives(){
   return this.node.data.members.filter(member => member.active == true).length;
  }
</code>```

Plunkr without material working fine:

https://plnkr.co/edit/w8mFjK1puVApgczcHVEE

Body:
I have a array of objects and in ngFor I want to get the the members count if the member in a team is active. Like in below example first members array has 2 members but only one is active so I should get length or count 1, in second members array there are 2 members and both are active so counet should be 2. Is it possible to get it using ngFor or there is any other way. Any help is appreciated.

{
"name": "Team 1",
"members": [{
        "active": true,
        "fullName": "TEST",
        "teamId": "xxx"
    }, {
        "active": false,
        "fullName": "ghgfhfghgfh"
    }
],
"childTeam": [{
        "name": "CTeam1",
        "members": [{
                "active": true,
                "fullName": "fghfhgfh"
            }, {
                "active": true,
                "fullName": "retweew"
            }
        ]
    },{
        "name": "CTeam2",
        "members": [{
                "active": true,
                "fullName": "fghfhgfh"
            }, {
                "active": true,
                "fullName": "retweew"
            },
            {
                "active": true,
                "fullName": "ddgfdgd"
            }
        ]
       }
    ]
}

And I am using it in ngFor as below -

      <mat-icon *ngIf="membs.active">person</mat-icon>

 1">

 {{ node.data.members.length }}

Body:
The way on HTML

 <div *ngIf="node.data.members.length >= 1">
    <div class="pull-left"> {{getActives()}}</div>
 </div>

Do in TS:

getActives(){
   return this.node.data.members.filter(member => member.active == true).length;
  }

Plunkr without material working fine:

https://plnkr.co/edit/w8mFjK1puVApgczcHVEE


问:
Turning player direction without speeding up
I'm trying to make a small prototype of a tribes-like game, mainly inspired by Tribes:Ascend. The problem is that the movement is hard to make.
Skiing, which is sliding frictionless on the ground to maintain speed, is no problem. Air/ski control on the other hand is.
What I'm trying to do is to let the player change direction or slow down when at high speeds without speeding up in any way.

This is the script I'm using for this:

```<code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerMovement : MonoBehaviour {
    public  Transform cameraObj;
    public Transform cameraRefObj;
    public Transform velObj;
    public  Camera cameraCam;
    public  Rigidbody rigbod;
    public  CapsuleCollider cap;
    public float maxVel;

    public float walkForce;
    public float defDynFric;
    public float defStatFric;
    void Start () {
        rigbod = this.GetComponent<Rigidbody>();
        cap = this.GetComponent<CapsuleCollider>();
        cameraObj = this.GetComponentInChildren<Camera>().transform;
        cameraCam = this.GetComponentInChildren<Camera>();
    }

    void Update () {
        Vector3 vel = rigbod.velocity;
        Debug.DrawRay(this.transform.position, vel);
        Vector3 velCalc = new Vector3(vel.x, 0, vel.z);
        float speedCapMult =Mathf.Clamp01(vel.magnitude / maxVel);
        velObj.rotation = Quaternion.LookRotation(velCalc);
        cameraRefObj.transform.rotation = Quaternion.EulerAngles(0, Quaternion.ToEulerAngles(cameraObj.rotation).y, 0);
        if (Input.GetButton("Skii"))
        {
            cap.material.dynamicFriction = 0;
            cap.material.staticFriction = 0;
        } else
        {
            cap.material.dynamicFriction = defDynFric;
            cap.material.staticFriction = defStatFric;
        }
        if (Input.GetAxis("Vertical") !=0 || Input.GetAxis("Horizontal") != 0)
        {
            Vector3 InputVec = Quaternion.EulerAngles(0, Quaternion.ToEulerAngles(cameraObj.rotation).y, 0) * Vector3.ClampMagnitude(new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical") ),1);
            float moveMulti =(1 -speedCapMult) +(speedCapMult*Mathf.Clamp01(1-Mathf.Cos(Vector3.Angle(velCalc, InputVec)/2)));
            InputVec = Vector3.ClampMagnitude(InputVec, moveMulti);
            Vector3 resVec = InputVec * (moveMulti * walkForce);

            Debug.DrawRay(this.transform.position, resVec, Color.red);
           // Debug.Log("SPD*: "+speedCapMult + "  moveMulti: " + moveMulti + "  VecAng: "+ Mathf.Clamp01(Mathf.Cos((Vector3.Angle(velCalc, InputVec)/2)-1)));
            rigbod.AddForce(resVec);
        }
    }
}
</code>```

The problem I am having is from what I understand mainly with this line:

```<code> float moveMulti =(1 -speedCapMult) +(speedCapMult*Mathf.Clamp01(1-Mathf.Cos(Vector3.Angle(velCalc, InputVec)/2)));
</code>```

What it does is transition between low speed movement to highspeed movement. Low speed is fine up the high speed movement isn't working as intended. When turning the velocity direction only turns a small bit and then it stops and the player continues to travel that direction unless I turn the camera (Somewhat similar to surfing in source games).

I want it to work like it does in T:A. I cant really find any good reference video, but the gist of it is that you can go to the side, slow down but not speed up.

答:
I managed to solve the problem. Its so simple i feel silly.
I simply changed the movemultiplier to:

```<code>            float moveMulti =(1 -speedCapMult) +(speedCapMult*Mathf.Clamp01(Vector3.Angle(velCalc, InputVec)/180));
</code>```

Basically ditching the cosign thing to a simple angle. Its works as intended now.

Body:
I'm trying to make a small prototype of a tribes-like game, mainly inspired by Tribes:Ascend. The problem is that the movement is hard to make.
Skiing, which is sliding frictionless on the ground to maintain speed, is no problem. Air/ski control on the other hand is.
What I'm trying to do is to let the player change direction or slow down when at high speeds without speeding up in any way.

This is the script I'm using for this:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerMovement : MonoBehaviour {
    public  Transform cameraObj;
    public Transform cameraRefObj;
    public Transform velObj;
    public  Camera cameraCam;
    public  Rigidbody rigbod;
    public  CapsuleCollider cap;
    public float maxVel;

    public float walkForce;
    public float defDynFric;
    public float defStatFric;
    void Start () {
        rigbod = this.GetComponent<Rigidbody>();
        cap = this.GetComponent<CapsuleCollider>();
        cameraObj = this.GetComponentInChildren<Camera>().transform;
        cameraCam = this.GetComponentInChildren<Camera>();
    }

    void Update () {
        Vector3 vel = rigbod.velocity;
        Debug.DrawRay(this.transform.position, vel);
        Vector3 velCalc = new Vector3(vel.x, 0, vel.z);
        float speedCapMult =Mathf.Clamp01(vel.magnitude / maxVel);
        velObj.rotation = Quaternion.LookRotation(velCalc);
        cameraRefObj.transform.rotation = Quaternion.EulerAngles(0, Quaternion.ToEulerAngles(cameraObj.rotation).y, 0);
        if (Input.GetButton("Skii"))
        {
            cap.material.dynamicFriction = 0;
            cap.material.staticFriction = 0;
        } else
        {
            cap.material.dynamicFriction = defDynFric;
            cap.material.staticFriction = defStatFric;
        }
        if (Input.GetAxis("Vertical") !=0 || Input.GetAxis("Horizontal") != 0)
        {
            Vector3 InputVec = Quaternion.EulerAngles(0, Quaternion.ToEulerAngles(cameraObj.rotation).y, 0) * Vector3.ClampMagnitude(new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical") ),1);
            float moveMulti =(1 -speedCapMult) +(speedCapMult*Mathf.Clamp01(1-Mathf.Cos(Vector3.Angle(velCalc, InputVec)/2)));
            InputVec = Vector3.ClampMagnitude(InputVec, moveMulti);
            Vector3 resVec = InputVec * (moveMulti * walkForce);

            Debug.DrawRay(this.transform.position, resVec, Color.red);
           // Debug.Log("SPD*: "+speedCapMult + "  moveMulti: " + moveMulti + "  VecAng: "+ Mathf.Clamp01(Mathf.Cos((Vector3.Angle(velCalc, InputVec)/2)-1)));
            rigbod.AddForce(resVec);
        }
    }
}

The problem I am having is from what I understand mainly with this line:

 float moveMulti =(1 -speedCapMult) +(speedCapMult*Mathf.Clamp01(1-Mathf.Cos(Vector3.Angle(velCalc, InputVec)/2)));

What it does is transition between low speed movement to highspeed movement. Low speed is fine up the high speed movement isn't working as intended. When turning the velocity direction only turns a small bit and then it stops and the player continues to travel that direction unless I turn the camera (Somewhat similar to surfing in source games).

I want it to work like it does in T:A. I cant really find any good reference video, but the gist of it is that you can go to the side, slow down but not speed up.

Body:
I managed to solve the problem. Its so simple i feel silly.
I simply changed the movemultiplier to:

            float moveMulti =(1 -speedCapMult) +(speedCapMult*Mathf.Clamp01(Vector3.Angle(velCalc, InputVec)/180));

Basically ditching the cosign thing to a simple angle. Its works as intended now.


问:
Adding post parameters to request before making the request go somewhere else in Java
In a JSP page, I need to do the following (this is psuedo-code):

```<code>//Attach new POST params to request
//Make the request go to a 3rd party URL
</code>```

How do I do this?

The way we are solving this right now (is terrible):

```<code>//populate and generate an HTML form
//on window.load submit the HTML form (as a POST) to a 3rd party URL
</code>```

We want all this to be done on the server side instead of having this JS hack

答:
There are many ways to send a HTTP POST. I recommend a use of apache HttpClient library.

Here is the previous question and answers on Stack Overflow. The question was for Andriod but should work perfectly with Java.

Another method is to use URLConnection class. There was an answer posted by me on that question.

Body:
In a JSP page, I need to do the following (this is psuedo-code):

//Attach new POST params to request
//Make the request go to a 3rd party URL

How do I do this?

The way we are solving this right now (is terrible):

//populate and generate an HTML form
//on window.load submit the HTML form (as a POST) to a 3rd party URL

We want all this to be done on the server side instead of having this JS hack


问:
Cannot instantiate: unexpected 'class_name' (T_STRING)
I'm trying this script on PHP 7.0, but I cannot instantiate. I've reviewed time after time, but I cannot figure out where is the error. Please could you help me?</p>

```<code><?php
class MiClase
{
    public $var1 = 'Publica';
    protected $var2 = 'Protegida';
    private $var3 = 'Privada';

    public function imprimir()
    {
        echo "Funcion Imprimir:<br>";
        echo $this->var1 . "<br/>";
        echo $this->var2 . "<br/>";
        echo $this->var3 . "<br/>";
        echo "---------------<br/>";
    }
}

$miclase = $new MiClase();
$miclase->imprimir();
echo "var1: ".$miclase->var1 . "<br/>";
echo "var2: ".$miclase->var2 . "<br/>";
echo "var3: ".$miclase->var3 . "<br/>";
</code>```

答:
The error was:

$miclase = $new MiClase();

It was without "$" before new!

$miclase = new MiClase();

Body:
I'm trying this script on PHP 7.0, but I cannot instantiate. I've reviewed time after time, but I cannot figure out where is the error. Please could you help me?

<?php
class MiClase
{
    public $var1 = 'Publica';
    protected $var2 = 'Protegida';
    private $var3 = 'Privada';

    public function imprimir()
    {
        echo "Funcion Imprimir:
";
        echo $this->var1 . "
";
        echo $this->var2 . "
";
        echo $this->var3 . "
";
        echo "---------------
";
    }
}

$miclase = $new MiClase();
$miclase->imprimir();
echo "var1: ".$miclase->var1 . "
";
echo "var2: ".$miclase->var2 . "
";
echo "var3: ".$miclase->var3 . "
";


问:
VS Code: How to resize editor window without resizing the whole interface?
In Microsoft's VS Code, I can zoom in and out with the keyboard shortcuts ⌘+ and ⌘-. These commands affect the entire interface, such as the file explorer and both editor windows.

I'd like a way to zoom in and out of only the active editor window. How can I do this?

Clarification: I don't want to change the window size. I only want to change the apparent font size of the text I'm editing.

答:
There is a plugin that was made for this very feature.

Check out https://marketplace.visualstudio.com/items?itemName=fosshaas.fontsize-shortcuts


问:
C# Is it possible to have arrays be printed indented by a few lines when printed
In a text based game I am making I have menus such as the inventory and player stats set out in a box that looks like this:

```<code>    | |====================================| |
    | |                                    | |
    | |                                    | |
    | |====================================| |
</code>```

I was wondering if it was possible to have it so that an array, in this case the inventory could be printed within this box without overlapping it.

Essentially, what I want to do it indent the printing of the array so that it fits within this box without any issues.

```<code>    Console.WriteLine("| | Your inventory contains:                                      | |");
        for (Arraycount = 0; Arraycount < 20; Arraycount++)
        {
            int inventory_position = Arraycount + 1;
            Console.WriteLine("{0}", Inventory[Arraycount]);
        }
</code>```

答:
You can use a format-string with a specified width and left-alignment:

```<code>var items1 = new string[]
{
    "Item 1",
    "Hello World",
    "Here comes trouble aaaaaaaaaaaaaaaaa bbbbbbbbbbbbbb cccccccccccccc dddddddd"
};
Console.WriteLine("| | {0,-60} | |", "Your inventory contains:");
for (int i = 0; i < items1.Length; i++)
{
    Console.WriteLine("| | {0,-60} | |", items1[i]);
}
</code>```

The "{0,-60}" placeholder tells to format the first argument (0) with a minimum width of 60 and left-aligned (the - before 60).

Just in case you might be tired of counting the right amount of border characters: you can use Console.WriteLine("| |{0}| |", new string('=', 62)); for the upper and lower border that aligns nicely with the width 60 (+2 spaces) contents.

Body:
In a text based game I am making I have menus such as the inventory and player stats set out in a box that looks like this:

    | |====================================| |
    | |                                    | |
    | |                                    | |
    | |====================================| |

I was wondering if it was possible to have it so that an array, in this case the inventory could be printed within this box without overlapping it.

Essentially, what I want to do it indent the printing of the array so that it fits within this box without any issues.

    Console.WriteLine("| | Your inventory contains:                                      | |");
        for (Arraycount = 0; Arraycount < 20; Arraycount++)
        {
            int inventory_position = Arraycount + 1;
            Console.WriteLine("{0}", Inventory[Arraycount]);
        }

Body:
You can use a format-string with a specified width and left-alignment:

var items1 = new string[]
{
    "Item 1",
    "Hello World",
    "Here comes trouble aaaaaaaaaaaaaaaaa bbbbbbbbbbbbbb cccccccccccccc dddddddd"
};
Console.WriteLine("| | {0,-60} | |", "Your inventory contains:");
for (int i = 0; i < items1.Length; i++)
{
    Console.WriteLine("| | {0,-60} | |", items1[i]);
}

The "{0,-60}" placeholder tells to format the first argument (0) with a minimum width of 60 and left-aligned (the - before 60).

Just in case you might be tired of counting the right amount of border characters: you can use Console.WriteLine("| |{0}| |", new string('=', 62)); for the upper and lower border that aligns nicely with the width 60 (+2 spaces) contents.


问:
Truncated Inccorrect date value while calling nested function
I have two function.

fn_validate_date

fn_validation

fn_validate_date code:

```<code> CREATE DEFINER=`root`@`localhost` FUNCTION `fn_validate_date`(
    `dt_date` DATE

 )
 RETURNS date
 LANGUAGE SQL
 NOT DETERMINISTIC
 CONTAINS SQL
 SQL SECURITY DEFINER
 COMMENT 'Returns the associated value of given attribute for given employee                for a particular date.'
 BEGIN
    SET dt_date = IF(dt_date IS NULL OR dt_date ='', CURRENT_DATE, dt_date);
    RETURN dt_date;
 END
</code>```

fn_validation code:

```<code> CREATE DEFINER=`root`@`localhost` FUNCTION `fn_validation`(
    `dt_date` DATE
 )
 RETURNS date
 LANGUAGE SQL
 NOT DETERMINISTIC
 CONTAINS SQL
 SQL SECURITY DEFINER
 COMMENT ''
 BEGIN
    RETURN fn_validate_date(dt_date);
 END
</code>```

Now when I am calling fn_validate_date as below

```<code> SELECT `fn_validate_date`(null);
</code>```

It's working well but when I calling fn_validation it's giving me an error.

```<code>SELECT `fn_validation`(null);
</code>```

My question is why I didn't get error while calling fn_validate_date?

答:
I disable strict mode and it's working well.

```<code> SET sql_mode =''
</code>```

To disable strict mode in MySQL. I am not sure why MySql short-circuited IF condition as I am passing NULL in the input parameter of fn_validation.

Body:
I have two function.

fn_validate_date

fn_validation

fn_validate_date code:

 CREATE DEFINER=`root`@`localhost` FUNCTION `fn_validate_date`(
    `dt_date` DATE

 )
 RETURNS date
 LANGUAGE SQL
 NOT DETERMINISTIC
 CONTAINS SQL
 SQL SECURITY DEFINER
 COMMENT 'Returns the associated value of given attribute for given employee                for a particular date.'
 BEGIN
    SET dt_date = IF(dt_date IS NULL OR dt_date ='', CURRENT_DATE, dt_date);
    RETURN dt_date;
 END

fn_validation code:

 CREATE DEFINER=`root`@`localhost` FUNCTION `fn_validation`(
    `dt_date` DATE
 )
 RETURNS date
 LANGUAGE SQL
 NOT DETERMINISTIC
 CONTAINS SQL
 SQL SECURITY DEFINER
 COMMENT ''
 BEGIN
    RETURN fn_validate_date(dt_date);
 END

Now when I am calling fn_validate_date as below

 SELECT `fn_validate_date`(null);

It's working well but when I calling fn_validation it's giving me an error.

SELECT `fn_validation`(null);

My question is why I didn't get error while calling fn_validate_date?

Body:
I disable strict mode and it's working well.

 SET sql_mode =''

To disable strict mode in MySQL. I am not sure why MySql short-circuited IF condition as I am passing NULL in the input parameter of fn_validation.


问:
Ambari repository on CentOS 7
We are trying to install Ambari server following the manual Install Ambari 2.2.1 from Public Repositories.

When we tried to install the Ambari server with the command yum install ambari-server it returns that it is nothing to do.

The ambari.repo is:

```<code>#VERSION_NUMBER=2.2.1.0-161

[Updates-ambari-2.2.1.0]
name=ambari-2.2.1.0 - Updates
baseurl=http://public-repo-1.hortonworks.com/ambari/centos7/2.x/updates/2.2.1.0
gpgcheck=1
gpgkey=http://public-repo-1.hortonworks.com/ambari/centos7/RPM-GPG-KEY/RPM-GPG-KEY-Jenkins
enabled=1
priority=1
</code>```

Someone can help us?

答:
This happens in case:

Package (ambari-server) is already installed

Repolist can't find the package (ambari-server).

First run yum list all if it's not listing package then run

yum clean all

Again run yum list all
If it's not listing your package you need to add .repo file for the same in /etc/yum.repos.d

Title: Ambari repository on CentOS 7

Body:
We are trying to install Ambari server following the manual Install Ambari 2.2.1 from Public Repositories.

When we tried to install the Ambari server with the command yum install ambari-server it returns that it is nothing to do.

The ambari.repo is:

#VERSION_NUMBER=2.2.1.0-161

[Updates-ambari-2.2.1.0]
name=ambari-2.2.1.0 - Updates
baseurl=http://public-repo-1.hortonworks.com/ambari/centos7/2.x/updates/2.2.1.0
gpgcheck=1
gpgkey=http://public-repo-1.hortonworks.com/ambari/centos7/RPM-GPG-KEY/RPM-GPG-KEY-Jenkins
enabled=1
priority=1

Someone can help us?


问:
How to communicate or switch between two windows in PyQt?
I am developing an application using python and Qt.

I have designed 2 Main windows ie..QMainWindow (Not QWidget or QDialog) using Qt.

Let it be.

1.LoginWindow -- LoginUI(Qt)

2.StuffWindow --- StuffUI

First i should display Login Window.

Then i should pass the username to StaffWindow (username needed for managing stuffs)

StaffWindow should be shown and LoginWindow Should be Closed..

How can i achieve this..? Help me..

答:
This is  PyQt5 updated version of Avaris. Some exception handling was added to show how to catch a few errors (while coding your thing. Enjoy!</p>

```<code>#!/usr/bin/env python
# -*- coding: utf-8 -*-

# Ref to this OP question. https://stackoverflow.com/questions/9689053/how-to-communicate-or-switch-between-two-windows-in-pyqt4

import sys
from PyQt5 import QtGui, QtCore, QtWidgets
from PyQt5.QtWidgets import QApplication, QDialog, QDialogButtonBox, QFormLayout, QLabel, QLineEdit, QWidget, QVBoxLayout

class LoginDialog(QtWidgets.QDialog):
    def __init__(self, parent=None):
        super(LoginDialog, self).__init__(parent)

        self.username = QLineEdit()
        self.password = QLineEdit()
        loginLayout = QFormLayout()
        loginLayout.addRow("Username", self.username)
        loginLayout.addRow("Password", self.password)

        self.buttons = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
        self.buttons.accepted.connect(self.check)
        self.buttons.rejected.connect(self.reject)

        layout = QVBoxLayout()
        layout.addLayout(loginLayout)
        layout.addWidget(self.buttons)
        self.setLayout(layout)

    def check(self):
        if str(self.password.text()) == "12345": # do actual login check
            self.accept()
        else:
            pass # or inform the user about bad username/password

    def my_exception_hook(exctype, value, traceback):
        # Print the error and traceback
        print(exctype, value, traceback)
        # Call the normal Exception hook after
        sys._excepthook(exctype, value, traceback)
        sys.exit(1)

    # Back up the reference to the exceptionhook
    sys._excepthook = sys.excepthook

    # Set the exception hook to our wrapping function
    sys.excepthook = my_exception_hook

class MainWindow(QtWidgets.QMainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)

        self.label = QLabel()
        self.setCentralWidget(self.label)

    def setUsername(self, username):
        # do whatever you want with the username
        self.username = username
        self.label.setText("Username entered: %s" % self.username)

if __name__ == "__main__":
    app = QApplication(sys.argv)

    login = LoginDialog()
    if not login.exec_(): # 'reject': user pressed 'Cancel', so quit
        sys.exit(-1)      # instead of -1 another action can be triggered here.

    # 'accept': continue
    main = MainWindow()

    # get the username, and supply it to main window
    main.setUsername(login.username.text())
    main.show()

    sys.exit(app.exec_())
</code>```

Body:
This is  PyQt5 updated version of Avaris. Some exception handling was added to show how to catch a few errors (while coding your thing. Enjoy!

#!/usr/bin/env python
# -*- coding: utf-8 -*-

# Ref to this OP question. https://stackoverflow.com/questions/9689053/how-to-communicate-or-switch-between-two-windows-in-pyqt4

import sys
from PyQt5 import QtGui, QtCore, QtWidgets
from PyQt5.QtWidgets import QApplication, QDialog, QDialogButtonBox, QFormLayout, QLabel, QLineEdit, QWidget, QVBoxLayout

class LoginDialog(QtWidgets.QDialog):
    def __init__(self, parent=None):
        super(LoginDialog, self).__init__(parent)

        self.username = QLineEdit()
        self.password = QLineEdit()
        loginLayout = QFormLayout()
        loginLayout.addRow("Username", self.username)
        loginLayout.addRow("Password", self.password)

        self.buttons = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
        self.buttons.accepted.connect(self.check)
        self.buttons.rejected.connect(self.reject)

        layout = QVBoxLayout()
        layout.addLayout(loginLayout)
        layout.addWidget(self.buttons)
        self.setLayout(layout)

    def check(self):
        if str(self.password.text()) == "12345": # do actual login check
            self.accept()
        else:
            pass # or inform the user about bad username/password

    def my_exception_hook(exctype, value, traceback):
        # Print the error and traceback
        print(exctype, value, traceback)
        # Call the normal Exception hook after
        sys._excepthook(exctype, value, traceback)
        sys.exit(1)

    # Back up the reference to the exceptionhook
    sys._excepthook = sys.excepthook

    # Set the exception hook to our wrapping function
    sys.excepthook = my_exception_hook

class MainWindow(QtWidgets.QMainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)

        self.label = QLabel()
        self.setCentralWidget(self.label)

    def setUsername(self, username):
        # do whatever you want with the username
        self.username = username
        self.label.setText("Username entered: %s" % self.username)

if __name__ == "__main__":
    app = QApplication(sys.argv)

    login = LoginDialog()
    if not login.exec_(): # 'reject': user pressed 'Cancel', so quit
        sys.exit(-1)      # instead of -1 another action can be triggered here.

    # 'accept': continue
    main = MainWindow()

    # get the username, and supply it to main window
    main.setUsername(login.username.text())
    main.show()

    sys.exit(app.exec_())


问:
How to ensure independency of a database copy in SQL Server Management Studio?
There's an SQL server database member with existing backup files .bak. Using Microsoft SQL Server Management Studio (SSMS), one of these .bak files is imported into the newly created database backup_member as suggested here. By this, backup_member is an older copy of member and their content is verifiably different.

However, queries from an external GUI-interface with the database connectivity ODBC in between returns data from member although all interfaces appear to be adjusted to backup_member.

Is it possible, that backup_member internally still has a connection to member which has to be cut during the copy process in SSMS?

How to verify that backup_member is independent from member without having to delete member?

Possibly there's a problem due to settings in Server properties > Connection Properties. The field for Database in category Connection is filled with "member". Does it mean, that any query on this Server is done for member and never for other databases like backup_member?

答:
If they each show up in SSMS and as you put it:

their content is verifiably different

I would be checking to make sure the ODBC connection you think the application is using is actually the ODBC connection it's using. There's no "internal connection" you should need to worry about. They're their own databases at this point.


问:
I'm not able to validate less than and greater than in robot framework
I'm trying to validate 0<4.3<6, I tried with Robot framework evaluate but I couldn't get the result, because I don't find any method to convert string to float, Then I wrote a python class to achieve this but for all the conditions it showing pass

my python code:

```<code>def should_be_x_than_y (number1, relation, number2, relation1, number3):

    if relation =="<" and relation1 == "<":
        print(relation)
        print (relation1)
        print (number1)
        print (number2)
        print (number3)
        **return float(number1) < float(number2) < float(number3)**
    if relation ==">" and relation1 == ">":
        return float(number1) > float(number2) > float(number3)
    if relation =="=>" and relation1 == "<=":
        return float(number1) >= float(number2) <= float(number3)
    if relation =="<=" and relation1 == "=>":
        return float(number1) <= float(number2) >= float(number3)
    if relation =="=":
        return float(number1) == float(number2)
</code>```

Robot Code:

```<code>should_be_x_than_y   0  <  ${words[0]}  <  3
</code>```

value of ${word[0]} is 4.3, so Ideally the case should fail, but It didn't

答:
In your question you stated that Robot Framework is unable to convert a string to a Float. This is the basis of your Python development. However, this is not correct. In the Robot Framework Userguide on Variables it states:

The variable syntax can be used for creating both integers and
  floating point numbers, as illustrated in the example below...

In the BuiltIn Library the keyword for Convert to Number also states firmly it supports floating number

Converts the given item to a floating point number. If the optional
  precision is positive or zero, the returned number is rounded to that
  number of decimal digits.

Which means that your comparison can easily be done using regular keywords.

```<code>*** Variables ***
@{words}    4.7    7.8

*** Test Cases ***
TC
                                           Should Be X Than Y   0 < ${words[0]} < 6
    Run Keyword and Continue on Failure    Should Be X Than Y   0 < ${words[1]} < 6

*** Keywords ***
Should Be X Than Y
    [Arguments]    ${expression}
    Run Keyword If
    ...    not(${expression})
    ...    Fail    Number does not match Expression pattern.
</code>```

As highlighted by @Bryan Oakley, it is important to use Fail to generate a failure instead of returning a value.

Body:
I'm trying to validate 0<4.3<6, I tried with Robot framework evaluate but I couldn't get the result, because I don't find any method to convert string to float, Then I wrote a python class to achieve this but for all the conditions it showing pass

my python code:

def should_be_x_than_y (number1, relation, number2, relation1, number3):

    if relation =="<" and relation1 == "<":
        print(relation)
        print (relation1)
        print (number1)
        print (number2)
        print (number3)
        **return float(number1) < float(number2) < float(number3)**
    if relation ==">" and relation1 == ">":
        return float(number1) > float(number2) > float(number3)
    if relation =="=>" and relation1 == "<=":
        return float(number1) >= float(number2) <= float(number3)
    if relation =="<=" and relation1 == "=>":
        return float(number1) <= float(number2) >= float(number3)
    if relation =="=":
        return float(number1) == float(number2)

Robot Code:

should_be_x_than_y   0  <  ${words[0]}  <  3

value of ${word[0]} is 4.3, so Ideally the case should fail, but It didn't

Body:
In your question you stated that Robot Framework is unable to convert a string to a Float. This is the basis of your Python development. However, this is not correct. In the Robot Framework Userguide on Variables it states:

The variable syntax can be used for creating both integers and
  floating point numbers, as illustrated in the example below...

In the BuiltIn Library the keyword for Convert to Number also states firmly it supports floating number

Converts the given item to a floating point number. If the optional
  precision is positive or zero, the returned number is rounded to that
  number of decimal digits.

Which means that your comparison can easily be done using regular keywords.

*** Variables ***
@{words}    4.7    7.8

*** Test Cases ***
TC
                                           Should Be X Than Y   0 < ${words[0]} < 6
    Run Keyword and Continue on Failure    Should Be X Than Y   0 < ${words[1]} < 6

*** Keywords ***
Should Be X Than Y
    [Arguments]    ${expression}
    Run Keyword If
    ...    not(${expression})
    ...    Fail    Number does not match Expression pattern.

As highlighted by @Bryan Oakley, it is important to use Fail to generate a failure instead of returning a value.


问:
How to Loop Range number in Excel VBA without changing letter
How do I get this to work?
I have this code written so far:

```<code>Sub RemoveLoop()

Dim i As Long

For i = 6 To 15
If Range("B" + i) = "YES" Then
    Range("C" + i + ":" + "P" + i).ClearContents
End If

Next i
End Sub
</code>```

Instead of doing each individually like this:
This is what I'm trying to shorten/accomplish, below:

```<code>Sub Remove()

If Range("B6") = "YES" Then
    Range("C6:P6").ClearContents
End If
If Range("B7") = "YES" Then
    Range("C7:P7").ClearContents
End If
If Range("B8") = "YES" Then
    Range("C8:P8").ClearContents
End If
If Range("B9") = "YES" Then
    Range("C9:P9").ClearContents
End If
If Range("B10") = "YES" Then
    Range("C10:P10").ClearContents
End If
If Range("B11") = "YES" Then
    Range("C11:P11").ClearContents
End If
If Range("B12") = "YES" Then
    Range("C12:P12").ClearContents
End If
If Range("B13") = "YES" Then
    Range("C13:P13").ClearContents
End If
If Range("B14") = "YES" Then
    Range("C14:P14").ClearContents
End If
If Range("B15") = "YES" Then
    Range("C15:P15").ClearContents
End If
End Sub
</code>```

Simple question for you guys, thank you for your help.
I don't know what else to say, it's pretty straight forwards I believe. But I'm still getting the, "Looks like your most is mostly code error."
This should be an easy one for you VBA experts to solve.

Thanks again.

答:
This is what you can do, passing the cells and the ranges as variables:

```<code>Option Explicit

Sub RemoveLoop()

    Dim i As Long

    For i = 6 To 15
        With Worksheets(1)
            If UCase(.Range("B" & i)) = "YES" Then
                .Range(.Cells(i, "C"), .Cells(i, "P")).ClearContents
            End If
        End With
    Next i

End Sub
</code>```

Except for using Range(Cells,Cells), the code is refering to UCase, which makes sure that "yes" and "YES" in column "B" are treaten equally.

Body:
How do I get this to work?
I have this code written so far:

Sub RemoveLoop()

Dim i As Long

For i = 6 To 15
If Range("B" + i) = "YES" Then
    Range("C" + i + ":" + "P" + i).ClearContents
End If

Next i
End Sub

Instead of doing each individually like this:
This is what I'm trying to shorten/accomplish, below:

Sub Remove()

If Range("B6") = "YES" Then
    Range("C6:P6").ClearContents
End If
If Range("B7") = "YES" Then
    Range("C7:P7").ClearContents
End If
If Range("B8") = "YES" Then
    Range("C8:P8").ClearContents
End If
If Range("B9") = "YES" Then
    Range("C9:P9").ClearContents
End If
If Range("B10") = "YES" Then
    Range("C10:P10").ClearContents
End If
If Range("B11") = "YES" Then
    Range("C11:P11").ClearContents
End If
If Range("B12") = "YES" Then
    Range("C12:P12").ClearContents
End If
If Range("B13") = "YES" Then
    Range("C13:P13").ClearContents
End If
If Range("B14") = "YES" Then
    Range("C14:P14").ClearContents
End If
If Range("B15") = "YES" Then
    Range("C15:P15").ClearContents
End If
End Sub

Simple question for you guys, thank you for your help.
I don't know what else to say, it's pretty straight forwards I believe. But I'm still getting the, "Looks like your most is mostly code error."
This should be an easy one for you VBA experts to solve.

Thanks again.

Body:
This is what you can do, passing the cells and the ranges as variables:

Option Explicit

Sub RemoveLoop()

    Dim i As Long

    For i = 6 To 15
        With Worksheets(1)
            If UCase(.Range("B" & i)) = "YES" Then
                .Range(.Cells(i, "C"), .Cells(i, "P")).ClearContents
            End If
        End With
    Next i

End Sub

Except for using Range(Cells,Cells), the code is refering to UCase, which makes sure that "yes" and "YES" in column "B" are treaten equally.


问:
Factory Girl Reserved Word Attributes for Association
The factory girl documentation advises using the add_attribute method to handle attributes that are reserved words, as follows:

```<code>factory :dna do
  add_attribute(:sequence) { 'GATTACA' }
end
</code>```

However I have a model called Trait (which is reserved) and another model called ContestantTrait, which belongs to Trait. I've tried using add_attribute in varying ways to avoid the reserved word issue with the association, but none seem to work.

Any suggestions? These are the formats I've tried so far:

```<code>FactoryGirl.define do
  factory :contestant_trait do
    add_attribute(:trait)
    add_attribute(:trait) {}
    add_attribute(:trait) {trait}
  end
end
</code>```

答:
There is no need to define an :add_attribute since :trait is an association. Use the keyword association as follows:

```<code>FactoryGirl.define do
  factory :contestant_trait do
    association :trait
    # ... other attributes
  end
end
</code>```

As a side note, it is recommended to upgrade to FactoryBot:

As of the 4.9.0 releases of both factory_girl and factory_girl_rails, both gems will be officially deprecated. In the 4.9.0 version.

See this post https://robots.thoughtbot.com/factory_bot for more in formation and how to upgrade.

Body:
The factory girl documentation advises using the add_attribute method to handle attributes that are reserved words, as follows:

factory :dna do
  add_attribute(:sequence) { 'GATTACA' }
end

However I have a model called Trait (which is reserved) and another model called ContestantTrait, which belongs to Trait. I've tried using add_attribute in varying ways to avoid the reserved word issue with the association, but none seem to work.

Any suggestions? These are the formats I've tried so far:

FactoryGirl.define do
  factory :contestant_trait do
    add_attribute(:trait)
    add_attribute(:trait) {}
    add_attribute(:trait) {trait}
  end
end

Body:
There is no need to define an :add_attribute since :trait is an association. Use the keyword association as follows:

FactoryGirl.define do
  factory :contestant_trait do
    association :trait
    # ... other attributes
  end
end

As a side note, it is recommended to upgrade to FactoryBot:

As of the 4.9.0 releases of both factory_girl and factory_girl_rails, both gems will be officially deprecated. In the 4.9.0 version.

See this post https://robots.thoughtbot.com/factory_bot for more in formation and how to upgrade.


问:
WPF Extending Window
So I have a bunch of WPF Windows in my Windows Application.
I want each window to have a context menu that has one item ( see the code bellow ). However, I don't feel like copying and pasting this code everywhere. I would like to somehow extend the WPF Window class ( and call it PrintableWindow ) and somehow make every window be an extension of the PrintableWindow ....Is this possible ??? </p>

```<code><Window.ContextMenu>
    <ContextMenu>
        <ContextMenu.Items>
            <MenuItem Header="Print"
                      Click="mnuPrint_Click">
            </MenuItem>
        </ContextMenu.Items>
    </ContextMenu>
</Window.ContextMenu>
</code>```

答:
Create your own Window class called PrintableWindow which derives from
Window and then modify any other Window instances to derive from your PrintableWindow versus Window. This way all Window instances will be of type PrintableWindow which has your ContextMenu and handler associated with it.

Title: WPF Extending Window

Body:
So I have a bunch of WPF Windows in my Windows Application.
I want each window to have a context menu that has one item ( see the code bellow ). However, I don't feel like copying and pasting this code everywhere. I would like to somehow extend the WPF Window class ( and call it PrintableWindow ) and somehow make every window be an extension of the PrintableWindow ....Is this possible ???

<Window.ContextMenu>
    <ContextMenu>
        <ContextMenu.Items>
            <MenuItem Header="Print"
                      Click="mnuPrint_Click">
            </MenuItem>
        </ContextMenu.Items>
    </ContextMenu>
</Window.ContextMenu>


问:
Pull a Date from a comment
Good Morning All.

I have a comment field from an invoice system. The user goes into the invoice and leaves a comment/note on it. The source system tags each note with a date. However, the month is either a single digit or a double digit based on the date the note was entered same with the day. So the issue I am having is that I want to pull all of the invoice notes that start with a certain time period. So the notes always start like either one of these:

6/7/16 7:51 AM

11/11/16 8:11 PM

Is there a way to pull the date from the beginning of the note say using AM or PM as the starting point and working back to the beginning of the string?

答:
What I can tell is that you might use Regular Expressions to extract the date from the string, but SQL server doesn't support the regular expression!

A work around is to use CLR, here an article that explain how to achieve what you want. Regular Expressions in MS SQL Server 2005/2008

To get some help on how to build the regular expression to match the dates, here another article that might help you : Regular Expression Library

The date regular expression could be ((\d{2})|(\d))\/((\d{2})|(\d))\/((\d{2})) ((\d{2})|(\d)):((\d{2})|(\d)) [AP]M

Hope this will help you

Title: Pull a Date from a comment