问:
Custom search through ArrayList for array names
I'm trying to implement search filter with getFilter method in my custom adapter.

There are two models of search through the list.

search for title of an item,

search for genre[] of an item.

(But I'm just talking about genre here).

The below code is working fine, but what I need is just a little more customized way to search in genre[].

What I'm trying to achieve is: (What I want):

multi-keyword searching, each category separated with,. example: genre1,genre2

(What I have done):

When I type genre1,genre2 then it gives the items that have this sequence in genres, it won't give  genre1,genre3,genre2 , or just genre1.

Can you help, please?

getFilter:

```<code>@Override
public Filter getFilter() {
    Filter filter = new Filter() {
        @Override
        protected void publishResults(CharSequence constraint, FilterResults results) {
            dataList = (List<ProductLocal>) results.values;
            notifyDataSetChanged();
        }
        @Override
        protected FilterResults performFiltering(CharSequence constraint) {
            FilterResults results = new FilterResults();
            List<ProductLocal> filteredList = new ArrayList<>();
            constraint = constraint.toString().toLowerCase();
            for (int i = 0; i < dataListFilter.size(); i++) {
                ProductLocal dataNames = dataListFilter.get(i);

                String genreStr = "";
                for (String str : dataNames.getGenre()) {
                    genreStr += str + ",";
                }

                if (dataNames.getTitle().toLowerCase().startsWith(constraint.toString())
                 || genreStr.toLowerCase().contains(constraint.toString())) {
                    filteredList.add(dataNames);
                }
            }
            results.count = filteredList.size();
            results.values = filteredList;
            return results;
        }

    };
    return filter;
}
</code>```

答:
AFAIU you want a song to match the fiter if any of these 2 conditions are met:

Song's title starts with whole search text

The song has a genre that contains a part of the search text separated by , (comma)

If this is so, try following search logic:

```<code>        @Override
        protected FilterResults performFiltering(CharSequence constraint)
        {
            FilterResults results = new FilterResults();
            List<ProductLocal> filteredList = new ArrayList<>();
            String searchText = constraint.toString().toLowerCase();
            String[] split = searchText.split(",");
            ArrayList<String> searchGenres = new ArrayList<String>(split.length);
            for (int i = 0; i < split.length; i++)
            {
                // remove spaces
                String trim = split[i].trim();
                // skip empty entries
                if (trim.length() > 0)
                    searchGenres.add(trim);
            }

            for (ProductLocal dataNames : dataListFilter)
            {
                // filter by title
                if (dataNames.getTitle().toLowerCase().startsWith(searchText))
                {
                    filteredList.add(dataNames);
                }
                else
                {
                    // filter by genres
                    // search for at least one common genre between song and search text
                    outer:
                    for (String songGenre : dataNames.getGenre())
                    {
                        for (String searchGenre : searchGenres)
                        {
                            if (songGenre.toLowerCase().contains(searchGenre))
                            {
                                filteredList.add(dataNames);
                                break outer;
                            }
                        }
                    }
                }
            }
            results.count = filteredList.size();
            results.values = filteredList;
            return results;
        }
</code>```

The only tricky place here is break outer;. This is a Java syntax to break out from two for loops at the same time. The idea here is that if we've found a match by some genre between constraint and a song, we add the song to the filteredList and don't want to add it again if there are more matching genres.

P.S. if filtering by many search genres becomes a performance issue, you may consider building single RegEx to match all search terms at once or  implementing Aho–Corasick algorithm

Body:
I'm trying to implement search filter with getFilter method in my custom adapter.

There are two models of search through the list.

search for title of an item,

search for genre[] of an item.

(But I'm just talking about genre here).

The below code is working fine, but what I need is just a little more customized way to search in genre[].

What I'm trying to achieve is: (What I want):

multi-keyword searching, each category separated with,. example: genre1,genre2

(What I have done):

When I type genre1,genre2 then it gives the items that have this sequence in genres, it won't give  genre1,genre3,genre2 , or just genre1.

Can you help, please?

getFilter:

@Override
public Filter getFilter() {
    Filter filter = new Filter() {
        @Override
        protected void publishResults(CharSequence constraint, FilterResults results) {
            dataList = (List<ProductLocal>) results.values;
            notifyDataSetChanged();
        }
        @Override
        protected FilterResults performFiltering(CharSequence constraint) {
            FilterResults results = new FilterResults();
            List<ProductLocal> filteredList = new ArrayList<>();
            constraint = constraint.toString().toLowerCase();
            for (int i = 0; i < dataListFilter.size(); i++) {
                ProductLocal dataNames = dataListFilter.get(i);

                String genreStr = "";
                for (String str : dataNames.getGenre()) {
                    genreStr += str + ",";
                }

                if (dataNames.getTitle().toLowerCase().startsWith(constraint.toString())
                 || genreStr.toLowerCase().contains(constraint.toString())) {
                    filteredList.add(dataNames);
                }
            }
            results.count = filteredList.size();
            results.values = filteredList;
            return results;
        }

    };
    return filter;
}

Body:
AFAIU you want a song to match the fiter if any of these 2 conditions are met:

Song's title starts with whole search text

The song has a genre that contains a part of the search text separated by , (comma)

If this is so, try following search logic:

        @Override
        protected FilterResults performFiltering(CharSequence constraint)
        {
            FilterResults results = new FilterResults();
            List<ProductLocal> filteredList = new ArrayList<>();
            String searchText = constraint.toString().toLowerCase();
            String[] split = searchText.split(",");
            ArrayList<String> searchGenres = new ArrayList<String>(split.length);
            for (int i = 0; i < split.length; i++)
            {
                // remove spaces
                String trim = split[i].trim();
                // skip empty entries
                if (trim.length() > 0)
                    searchGenres.add(trim);
            }

            for (ProductLocal dataNames : dataListFilter)
            {
                // filter by title
                if (dataNames.getTitle().toLowerCase().startsWith(searchText))
                {
                    filteredList.add(dataNames);
                }
                else
                {
                    // filter by genres
                    // search for at least one common genre between song and search text
                    outer:
                    for (String songGenre : dataNames.getGenre())
                    {
                        for (String searchGenre : searchGenres)
                        {
                            if (songGenre.toLowerCase().contains(searchGenre))
                            {
                                filteredList.add(dataNames);
                                break outer;
                            }
                        }
                    }
                }
            }
            results.count = filteredList.size();
            results.values = filteredList;
            return results;
        }

The only tricky place here is break outer;. This is a Java syntax to break out from two for loops at the same time. The idea here is that if we've found a match by some genre between constraint and a song, we add the song to the filteredList and don't want to add it again if there are more matching genres.

P.S. if filtering by many search genres becomes a performance issue, you may consider building single RegEx to match all search terms at once or  implementing Aho–Corasick algorithm


来源: stackexchange

问:
Unrecognized selector error on swipe left gesture swift
I am attempting to create a simple swift left segue to the next view controller, however I am getting an unrecognized selector error.  This the code failing:

```<code>   override func viewDidLoad() {
        super.viewDidLoad()

        //below creates the instances for swiping to change screens
        //only added right here because it's the main screen

          var swipeLeft : UISwipeGestureRecognizer = UISwipeGestureRecognizer(target: self, action: Selector("swipe:"))
        swipeLeft.direction = UISwipeGestureRecognizerDirection.Left

        self.view.addGestureRecognizer(swipeLeft)

        func swipe(Sender: UISwipeGestureRecognizer!) {
            print("swiped left")
            let vc = self.storyboard!.instantiateViewControllerWithIdentifier("OnDeck") as! OnDeck
            self.presentViewController(vc, animated: true, completion: nil)
        }
}
</code>```

This is the error I am getting:

```<code>2017-06-07 19:07:00.990 Test[65722:3911717] -[Test.GameView swipe:]: unrecognized selector sent to instance 0x7fc2d310f700
2017-06-07 19:07:01.000 Test[65722:3911717] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[Test.GameView swipe:]: unrecognized selector sent to instance 0x7fc2d310f700'
</code>```

答:
You need to try it like that :

```<code>let swiftLeft : UISwipeGestureRecognizer = UISwipeGestureRecognizer(target: self, action: #selector(self.swipe(Sender:)))
swiftLeft.direction = .left
self.view.addGestureRecognizer(swiftLeft)

func swipe(Sender: UISwipeGestureRecognizer!) {
     print("swiped left")

}
</code>```

If you are working on Swift 2, you need to add the selector like that

selector(self.swipe(_:))

ContentLicense: CC BY-SA 3.0

Body:
I am attempting to create a simple swift left segue to the next view controller, however I am getting an unrecognized selector error.  This the code failing:

   override func viewDidLoad() {
        super.viewDidLoad()

        //below creates the instances for swiping to change screens
        //only added right here because it's the main screen

          var swipeLeft : UISwipeGestureRecognizer = UISwipeGestureRecognizer(target: self, action: Selector("swipe:"))
        swipeLeft.direction = UISwipeGestureRecognizerDirection.Left

        self.view.addGestureRecognizer(swipeLeft)

        func swipe(Sender: UISwipeGestureRecognizer!) {
            print("swiped left")
            let vc = self.storyboard!.instantiateViewControllerWithIdentifier("OnDeck") as! OnDeck
            self.presentViewController(vc, animated: true, completion: nil)
        }
}

This is the error I am getting:

2017-06-07 19:07:00.990 Test[65722:3911717] -[Test.GameView swipe:]: unrecognized selector sent to instance 0x7fc2d310f700
2017-06-07 19:07:01.000 Test[65722:3911717] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[Test.GameView swipe:]: unrecognized selector sent to instance 0x7fc2d310f700'

Body:
You need to try it like that :

let swiftLeft : UISwipeGestureRecognizer = UISwipeGestureRecognizer(target: self, action: #selector(self.swipe(Sender:)))
swiftLeft.direction = .left
self.view.addGestureRecognizer(swiftLeft)

func swipe(Sender: UISwipeGestureRecognizer!) {
     print("swiped left")

}

If you are working on Swift 2, you need to add the selector like that

selector(self.swipe(_:))


问:
XPath how to select nodes by attribute name if the attribute name has a namespace
I know I can select nodes by attribute name using

```<code>//*[@attribute]
</code>```

But how do I do it if my attribute is a namespace like bar:resource?

For example:

```<code><foo:creator bar:resource="https://example/john">john</foo:creator>
</code>```

答:
Pretty much same stuff:

```<code>//*[@bar:resource]
</code>```

This XPath selects all nodes which have @bar:resource attribute. To use this, you need to pass namespace uri and namespace prefix (bar) into your XML/XPath engine/processor.

Alternatively you can use pure XPath (although I don't recommend this):

```<code>//*[@*[local-name() = 'resource' and namespace-uri() = 'bar_namespace_uri']]
</code>```

Body:
I know I can select nodes by attribute name using

//*[@attribute]

But how do I do it if my attribute is a namespace like bar:resource?

For example:

<foo:creator bar:resource="https://example/john">john</foo:creator>

Body:
Pretty much same stuff:

//*[@bar:resource]

This XPath selects all nodes which have @bar:resource attribute. To use this, you need to pass namespace uri and namespace prefix (bar) into your XML/XPath engine/processor.

Alternatively you can use pure XPath (although I don't recommend this):

//*[@*[local-name() = 'resource' and namespace-uri() = 'bar_namespace_uri']]


问:
jQuery Validate ABA Routing number not working
So Im  trying to validate An ABA routing number and have partial success. The bulk of the code seems to work but for some reason its just focusing on the first three digits instead of looking at all 9.

this is begining to annoy me and im sure its something silly I'm just overlooking.

Here is the reference to the original code: brainjar

Here is my JS fiddle: jsfiddle

and bellow is my code:

function ABA(t) {
 // Run through each digit and calculate the total.
var n = 0,
 $this = $(t),
 tval = $this.val();
  for (i = 0; i < $this.length; i += 3) {
    n += parseInt(tval.charAt(i),     10) * 3
      +  parseInt(tval.charAt(i + 1), 10) * 7
      +  parseInt(tval.charAt(i + 2), 10);
  }

  // If the resulting sum is an even multiple of ten (but not zero),
  // the aba routing number is good.
if($this.val().length == 9){
  if (n != 0 && n % 10 == 0){
   setTimeout(function(){
    $this.removeClass('invalid');
    $this.addClass('valid');
    }, 500);
  }else{
   setTimeout(function(){
    $this.removeClass('valid');
    $this.addClass('invalid');
   }, 500);}

} else {
  setTimeout(function(){
    $this.removeClass('valid');
    $this.addClass('invalid');
   }, 500);}

}

$('#abaR').on('input', function() {
ABA(this);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input name="abaR" maxlength="9" id="abaR"></code>```

答:
I believe you want

for (i = 0; i < tval.length; i += 3) {

$this is a jQuery object, not the string; it's length will always be 1, which is why it appeared to only inspect the first three digits.  It seems to work with my own bank's routing number.

Body:
So Im  trying to validate An ABA routing number and have partial success. The bulk of the code seems to work but for some reason its just focusing on the first three digits instead of looking at all 9.

this is begining to annoy me and im sure its something silly I'm just overlooking.

Here is the reference to the original code: brainjar

Here is my JS fiddle: jsfiddle

and bellow is my code:

function ABA(t) {
 // Run through each digit and calculate the total.
var n = 0,
 $this = $(t),
 tval = $this.val();
  for (i = 0; i < $this.length; i += 3) {
    n += parseInt(tval.charAt(i),     10) * 3
      +  parseInt(tval.charAt(i + 1), 10) * 7
      +  parseInt(tval.charAt(i + 2), 10);
  }

  // If the resulting sum is an even multiple of ten (but not zero),
  // the aba routing number is good.
if($this.val().length == 9){
  if (n != 0 && n % 10 == 0){
   setTimeout(function(){
    $this.removeClass('invalid');
    $this.addClass('valid');
    }, 500);
  }else{
   setTimeout(function(){
    $this.removeClass('valid');
    $this.addClass('invalid');
   }, 500);}

} else {
  setTimeout(function(){
    $this.removeClass('valid');
    $this.addClass('invalid');
   }, 500);}

}

$('#abaR').on('input', function() {
ABA(this);
});

<input name="abaR" maxlength="9" id="abaR">


问:
Specify multiple delimiters for Redshift copy command
Is there a way to specify multiple delimiters to Redshift copy command while loading data.

I have a data file having the following format:-

1 | ab | cd | ef

2 | gh | ij | kl

I am using a command like this:-

```<code>COPY MY_TBL
  FROM 's3://s3-file-path'
  iam_role 'arn:aws:iam::ddfjhgkjdfk'
  manifest
  IGNOREHEADER 1
gzip delimiter '|';
</code>```

Fields are separated by | and records are separated using newline. How do I copy this data into Redshift. Because my query above gives me a delimiter not found error

答:
No, delimiters are single characters.

From Data Format Parameters:

Specifies the single ASCII character that is used to separate fields in the input file, such as a pipe character ( | ), a comma ( , ), or a tab ( \t ).

You could import it with a pipe delimiter, then perform an UPDATE command to STRIP() off the spaces.

Body:
Is there a way to specify multiple delimiters to Redshift copy command while loading data.

I have a data file having the following format:-

1 | ab | cd | ef

2 | gh | ij | kl

I am using a command like this:-

COPY MY_TBL
  FROM 's3://s3-file-path'
  iam_role 'arn:aws:iam::ddfjhgkjdfk'
  manifest
  IGNOREHEADER 1
gzip delimiter '|';

Fields are separated by | and records are separated using newline. How do I copy this data into Redshift. Because my query above gives me a delimiter not found error


问:
string element of listA are substrings of listB. How to retrieve and store each string in listB which contains these subsrtings in python?
i have following lists

```<code>listA = ['alpha','beta','gamma']
listB = ['alphav1','alphav2','alpha$v3', 'alpha$v4-beta',
        'alpha-beta','beta$v1', 'betav2', 'beta-alpha', 'beta$v6-get', 'gamma']
</code>```

i wanted to retrieve and store:

```<code>alpha = ['alphav1','alphav2','alpha$v3', 'alpha$v4-beta']
</code>```

i.e a list named alpha and similarly for beta and gamma

I have to get the this with starting strings only and not any other matching strings! Ex: incase of alpha-beta and alpha$v4-beta fall into alpha and beta-alpha fall into beta.

Note: I have huge listA with 1k+ elements - looking for generic answer with time complexity issue too.

答:
Easy job with filter:

```<code>alpha = filter(lambda s: s.startswith('alpha'), listB)
</code>```

Body:
i have following lists

listA = ['alpha','beta','gamma']
listB = ['alphav1','alphav2','alpha$v3', 'alpha$v4-beta',
        'alpha-beta','beta$v1', 'betav2', 'beta-alpha', 'beta$v6-get', 'gamma']

i wanted to retrieve and store:

alpha = ['alphav1','alphav2','alpha$v3', 'alpha$v4-beta']

i.e a list named alpha and similarly for beta and gamma

I have to get the this with starting strings only and not any other matching strings! Ex: incase of alpha-beta and alpha$v4-beta fall into alpha and beta-alpha fall into beta.

Note: I have huge listA with 1k+ elements - looking for generic answer with time complexity issue too.

Body:
Easy job with filter:

alpha = filter(lambda s: s.startswith('alpha'), listB)


问:
ANR executing service com.onesignal.SyncService
We are using OneSignal Native SDK version 3.4 in my app and sometime crash the app give below crash log :

```<code>"Signal Catcher" daemon prio=5 tid=3 Runnable
| group="system" sCount=0 dsCount=0 obj=0x32c060d0 self=0x7b16ad0400
| sysTid=29468 nice=0 cgrp=default sched=0/0 handle=0x7b15487450
| state=R schedstat=( 38449486 526559 113 ) utm=0 stm=2 core=1 HZ=100
| stack=0x7b1538d000-0x7b1538f000 stackSize=1005KB
| held mutexes= "mutator lock"(shared held)

"main" prio=5 tid=1 TimedWaiting
| group="main" sCount=1 dsCount=0 obj=0x76dc28d0 self=0x7b16aa1a00
| sysTid=29462 nice=0 cgrp=default sched=0/0 handle=0x7b1ab15a98
| state=S schedstat=( 342720854 559444785 1097 ) utm=18 stm=15 core=2 HZ=100
| stack=0x7fec5e8000-0x7fec5ea000 stackSize=8MB
| held mutexes=
at java.lang.Object.wait! (Native method)

waiting on <0x06dd0cbb> (a java.lang.Object)
at java.lang.Object.wait (Object.java:407)
at java.lang.Thread.join (Thread.java:1313)
locked <0x06dd0cbb> (a java.lang.Object)
at com.onesignal.OneSignalRestClient.putSync (OneSignalRestClient.java)
at <OR>.makeRequest (OneSignalRestClient.java)
at com.onesignal.OneSignalRestClient.putSync (OneSignalRestClient.java)
at <OR>.makeRequest (OneSignalRestClient.java)
at com.onesignal.OneSignalStateSynchronizer.handleJsonArray (OneSignalStateSynchronizer.java)
at <OR>.stopAndPersist (OneSignalStateSynchronizer.java)
at <OR>.initUserState (OneSignalStateSynchronizer.java)
at <OR>.syncUserState (OneSignalStateSynchronizer.java)
at <OR>.postUpdate (OneSignalStateSynchronizer.java)
at <OR>.sendTags (OneSignalStateSynchronizer.java)
at <OR>.updateLocation (OneSignalStateSynchronizer.java)
at <OR>.access$300 (OneSignalStateSynchronizer.java)
at <OR>.access$600 (OneSignalStateSynchronizer.java)
at <OR>.access$900 (OneSignalStateSynchronizer.java)
at <OR>.access$1100 (OneSignalStateSynchronizer.java)
at com.onesignal.SyncService$2$1.complete (SyncService.java)
at com.onesignal.LocationGMS.scheduleUpdate (LocationGMS.java)
at <OR>.setLastLocationTime (LocationGMS.java)
at <OR>.getLocation (LocationGMS.java)
at <OR>.startGetLocation (LocationGMS.java)
at <OR>.fireComplete (LocationGMS.java)
at <OR>.access$200 (LocationGMS.java)
at <OR>.access$302 (LocationGMS.java)
locked <0x09a195d8> (a java.lang.Class<com.onesignal.u>)
at com.onesignal.LocationGMS.getLastLocationTime (LocationGMS.java)
at <OR>.fireFailedComplete (LocationGMS.java)
at <OR>.receivedLocationPoint (LocationGMS.java)
at com.onesignal.LocationGMS.scheduleUpdate (LocationGMS.java)
at <OR>.setLastLocationTime (LocationGMS.java)
at <OR>.getLocation (LocationGMS.java)
at <OR>.startGetLocation (LocationGMS.java)
at <OR>.fireComplete (LocationGMS.java)
at <OR>.access$200 (LocationGMS.java)
at <OR>.access$302 (LocationGMS.java)
at com.onesignal.LocationGMS$GoogleApiClientListener.onConnected (LocationGMS.java)
at <OR>.onConnectionSuspended (LocationGMS.java)
at <OR>.onConnectionFailed (LocationGMS.java)
at com.google.android.gms.common.internal.zzl.zzass (zzl.java)
at <OR>.zzo (zzl.java)
at <OR>.zzgb (zzl.java)
at <OR>.zzm (zzl.java)
at <OR>.registerConnectionCallbacks (zzl.java)
at <OR>.registerConnectionFailedListener (zzl.java)
locked <0x0284cd31> (a java.lang.Object)
at com.google.android.gms.internal.zzqd.zzc (zzqd.java)
at <OR>.zza (zzqd.java)
at <OR>.connect (zzqd.java)
at <OR>.registerConnectionFailedListener (zzqd.java)
</code>```

We can not reproduce the problem. If you need anything else for further investigating the problem I am here to help.

答: The OneSignal Android SDK 3.5.7 fixes a bug where an ANR sometimes occurs during intermittent network connections. The linked issue notes that same stack trace so this update should fix your issue.</p>

Body:
We are using OneSignal Native SDK version 3.4 in my app and sometime crash the app give below crash log :

"Signal Catcher" daemon prio=5 tid=3 Runnable
| group="system" sCount=0 dsCount=0 obj=0x32c060d0 self=0x7b16ad0400
| sysTid=29468 nice=0 cgrp=default sched=0/0 handle=0x7b15487450
| state=R schedstat=( 38449486 526559 113 ) utm=0 stm=2 core=1 HZ=100
| stack=0x7b1538d000-0x7b1538f000 stackSize=1005KB
| held mutexes= "mutator lock"(shared held)

"main" prio=5 tid=1 TimedWaiting
| group="main" sCount=1 dsCount=0 obj=0x76dc28d0 self=0x7b16aa1a00
| sysTid=29462 nice=0 cgrp=default sched=0/0 handle=0x7b1ab15a98
| state=S schedstat=( 342720854 559444785 1097 ) utm=18 stm=15 core=2 HZ=100
| stack=0x7fec5e8000-0x7fec5ea000 stackSize=8MB
| held mutexes=
at java.lang.Object.wait! (Native method)

waiting on <0x06dd0cbb> (a java.lang.Object)
at java.lang.Object.wait (Object.java:407)
at java.lang.Thread.join (Thread.java:1313)
locked <0x06dd0cbb> (a java.lang.Object)
at com.onesignal.OneSignalRestClient.putSync (OneSignalRestClient.java)
at <OR>.makeRequest (OneSignalRestClient.java)
at com.onesignal.OneSignalRestClient.putSync (OneSignalRestClient.java)
at <OR>.makeRequest (OneSignalRestClient.java)
at com.onesignal.OneSignalStateSynchronizer.handleJsonArray (OneSignalStateSynchronizer.java)
at <OR>.stopAndPersist (OneSignalStateSynchronizer.java)
at <OR>.initUserState (OneSignalStateSynchronizer.java)
at <OR>.syncUserState (OneSignalStateSynchronizer.java)
at <OR>.postUpdate (OneSignalStateSynchronizer.java)
at <OR>.sendTags (OneSignalStateSynchronizer.java)
at <OR>.updateLocation (OneSignalStateSynchronizer.java)
at <OR>.access$300 (OneSignalStateSynchronizer.java)
at <OR>.access$600 (OneSignalStateSynchronizer.java)
at <OR>.access$900 (OneSignalStateSynchronizer.java)
at <OR>.access$1100 (OneSignalStateSynchronizer.java)
at com.onesignal.SyncService$2$1.complete (SyncService.java)
at com.onesignal.LocationGMS.scheduleUpdate (LocationGMS.java)
at <OR>.setLastLocationTime (LocationGMS.java)
at <OR>.getLocation (LocationGMS.java)
at <OR>.startGetLocation (LocationGMS.java)
at <OR>.fireComplete (LocationGMS.java)
at <OR>.access$200 (LocationGMS.java)
at <OR>.access$302 (LocationGMS.java)
locked <0x09a195d8> (a java.lang.Class<com.onesignal.u>)
at com.onesignal.LocationGMS.getLastLocationTime (LocationGMS.java)
at <OR>.fireFailedComplete (LocationGMS.java)
at <OR>.receivedLocationPoint (LocationGMS.java)
at com.onesignal.LocationGMS.scheduleUpdate (LocationGMS.java)
at <OR>.setLastLocationTime (LocationGMS.java)
at <OR>.getLocation (LocationGMS.java)
at <OR>.startGetLocation (LocationGMS.java)
at <OR>.fireComplete (LocationGMS.java)
at <OR>.access$200 (LocationGMS.java)
at <OR>.access$302 (LocationGMS.java)
at com.onesignal.LocationGMS$GoogleApiClientListener.onConnected (LocationGMS.java)
at <OR>.onConnectionSuspended (LocationGMS.java)
at <OR>.onConnectionFailed (LocationGMS.java)
at com.google.android.gms.common.internal.zzl.zzass (zzl.java)
at <OR>.zzo (zzl.java)
at <OR>.zzgb (zzl.java)
at <OR>.zzm (zzl.java)
at <OR>.registerConnectionCallbacks (zzl.java)
at <OR>.registerConnectionFailedListener (zzl.java)
locked <0x0284cd31> (a java.lang.Object)
at com.google.android.gms.internal.zzqd.zzc (zzqd.java)
at <OR>.zza (zzqd.java)
at <OR>.connect (zzqd.java)
at <OR>.registerConnectionFailedListener (zzqd.java)

We can not reproduce the problem. If you need anything else for further investigating the problem I am here to help.


问:
Scale SVG from center
I have an svg as a background image in css, and I want to flip it. (scale(-1, 1))

When I try normal transformation, it dose not go about center, and looks weird.

Is there a way to flip an entire SVG around center, without JS?

Here is a demo using HTML, not CSS background image:
https://codepen.io/anon/pen/bRVqwz

```<code><svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 12 20'><path d='M2,20l-2-2l8-8L0,2l2-2l10,10L2,20z'/></svg><br />
<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 12 20'><path d='M2,20l-2-2l8-8L0,2l2-2l10,10L2,20z' transform="scale(-1, 1)"/></svg>

svg {
  width: 50px;
  height: 50px;
}
</code>```

答:
First, to understand how to flip an SVG, u need to understand how the viewBox works (According to Mozilla MDN):

The value of the viewBox attribute is a list of four numbers min-x, min-y, width and height, separated by whitespace and/or a comma, which specify a rectangle in user space which should be mapped to the bounds of the viewport established by the given element, taking into account attribute preserveAspectRatio.

So, if you want to flip your svg, first you need to transform: scaleX(-1).
Then, you need to pass to the [min-x] the negative number of your [width].

For example:

Original SVG: viewBox='0 0 12 20'

Flipped SVG: viewBox='-12 0 12 20'

Title: Scale SVG from center

Body:
I have an svg as a background image in css, and I want to flip it. (scale(-1, 1))

When I try normal transformation, it dose not go about center, and looks weird.

Is there a way to flip an entire SVG around center, without JS?

Here is a demo using HTML, not CSS background image:
https://codepen.io/anon/pen/bRVqwz

<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 12 20'><path d='M2,20l-2-2l8-8L0,2l2-2l10,10L2,20z'/></svg>

<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 12 20'><path d='M2,20l-2-2l8-8L0,2l2-2l10,10L2,20z' transform="scale(-1, 1)"/></svg>

svg {
  width: 50px;
  height: 50px;
}


问:
Android animation imageview 1st rotate and then fadeout for splash
I am trying to make a splash screen for my Android app. I have found many answer related to this question. but none of those worked correctly. I just want to
1. first fade_in an imageView, then rotate and then  fade_out
or 2. all at the same time. I have tried these code

```<code>    final ImageView iv = (ImageView) findViewById(R.id.imageView);
    final Animation an = AnimationUtils.loadAnimation(getBaseContext(),R.anim.animate);

    iv.startAnimation(an);
    an.setAnimationListener(new Animation.AnimationListener() {
        @Override
        public void onAnimationStart(Animation animation) {}

        @Override
        public void onAnimationEnd(Animation animation) {
            finish();
            Intent i = new Intent(getBaseContext(),Welcome.class);
            startActivity(i);
        }

        @Override
        public void onAnimationRepeat(Animation animation) {}
    });
</code>```

and in animate xml

```<code>    <?xml version="1.0" encoding="utf-8"?>
    <set xmlns:android="http://schemas.android.com/apk/res/android" android:fillAfter="true">

<rotate
    android:duration="10000"
    android:fromDegrees="0"
    android:toDegrees="360"
    android:pivotX="50%"
    android:pivotY="50%"
    />

<alpha
    android:fromAlpha="1.0"
    android:toAlpha="0.0"
    android:interpolator="@android:anim/accelerate_interpolator"
    android:duration="5000"/>
<alpha
    android:fromAlpha="0.0"
    android:toAlpha="1.0"
    android:interpolator="@android:anim/accelerate_interpolator"
    android:duration="5000"/>

</set>
</code>```

答:
you can use this, for rotation and fade and fade out,</p>

```<code><?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
     android:fillAfter="true"
     android:interpolator="@android:anim/linear_interpolator">

    <alpha
        android:duration="5000"
        android:fromAlpha="1.0"
        android:interpolator="@android:anim/accelerate_interpolator"
        android:repeatCount="1"
        android:repeatMode="reverse"
        android:toAlpha="0.4"/>

    <rotate
        android:duration="10000"
        android:fromDegrees="0"
        android:interpolator="@android:anim/cycle_interpolator"
        android:pivotX="50%"
        android:pivotY="50%"
        android:toDegrees="180"/>

</set>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am trying to make a splash screen for my Android app. I have found many answer related to this question. but none of those worked correctly. I just want to
1. first fade_in an imageView, then rotate and then  fade_out
or 2. all at the same time. I have tried these code

    final ImageView iv = (ImageView) findViewById(R.id.imageView);
    final Animation an = AnimationUtils.loadAnimation(getBaseContext(),R.anim.animate);

    iv.startAnimation(an);
    an.setAnimationListener(new Animation.AnimationListener() {
        @Override
        public void onAnimationStart(Animation animation) {}

        @Override
        public void onAnimationEnd(Animation animation) {
            finish();
            Intent i = new Intent(getBaseContext(),Welcome.class);
            startActivity(i);
        }

        @Override
        public void onAnimationRepeat(Animation animation) {}
    });

and in animate xml

    <?xml version="1.0" encoding="utf-8"?>
    <set xmlns:android="http://schemas.android.com/apk/res/android" android:fillAfter="true">

<rotate
    android:duration="10000"
    android:fromDegrees="0"
    android:toDegrees="360"
    android:pivotX="50%"
    android:pivotY="50%"
    />

<alpha
    android:fromAlpha="1.0"
    android:toAlpha="0.0"
    android:interpolator="@android:anim/accelerate_interpolator"
    android:duration="5000"/>
<alpha
    android:fromAlpha="0.0"
    android:toAlpha="1.0"
    android:interpolator="@android:anim/accelerate_interpolator"
    android:duration="5000"/>

</set>

Body:
you can use this, for rotation and fade and fade out,

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
     android:fillAfter="true"
     android:interpolator="@android:anim/linear_interpolator">

    <alpha
        android:duration="5000"
        android:fromAlpha="1.0"
        android:interpolator="@android:anim/accelerate_interpolator"
        android:repeatCount="1"
        android:repeatMode="reverse"
        android:toAlpha="0.4"/>

    <rotate
        android:duration="10000"
        android:fromDegrees="0"
        android:interpolator="@android:anim/cycle_interpolator"
        android:pivotX="50%"
        android:pivotY="50%"
        android:toDegrees="180"/>

</set>


答:
You could do something like:

{i: [j for j in listB if j.startswith(i)] for i in listA}

which returns:

```<code>{
    'alpha': [
        'alphav1',
        'alphav2',
        'alpha$v3',
        'alpha$v4-beta',
        'alpha-beta'
    ],
    'beta': [
        'beta$v1',
        'betav2',
        'beta-alpha',
        'beta$v6-get'
    ],
    'gamma': [
        'gamma'
    ]
}
</code>```

Title: string element of listA are substrings of listB. How to retrieve and store each string in listB which contains these subsrtings in python?

Body:
You could do something like:

{i: [j for j in listB if j.startswith(i)] for i in listA}

which returns:

{
    'alpha': [
        'alphav1',
        'alphav2',
        'alpha$v3',
        'alpha$v4-beta',
        'alpha-beta'
    ],
    'beta': [
        'beta$v1',
        'betav2',
        'beta-alpha',
        'beta$v6-get'
    ],
    'gamma': [
        'gamma'
    ]
}


问:
Canvas client size in fabric js
In a usual canvas css width and client width could be not equal to each other, how to get this on Fabricjs? As an example: I want 640*360px canvas on a page with 1280*720px image inside.
I know I could scale image, but dataUrl will give me a smaller picture, isn't it?</p>

答:
You can change the size of the canvas using the setWidth/setHeight properties of the canvas http://fabricjs.com/docs/fabric.StaticCanvas.html#setWidth

e.g.

```<code>canvas = new fabric.Canvas('c');
canvas.setWidth(640);
canvas.setHeight(360);
</code>```

Though you should clarify what you mean.

Title: Canvas client size in fabric js

Body:
You can change the size of the canvas using the setWidth/setHeight properties of the canvas http://fabricjs.com/docs/fabric.StaticCanvas.html#setWidth

e.g.

canvas = new fabric.Canvas('c');
canvas.setWidth(640);
canvas.setHeight(360);

Though you should clarify what you mean.


问:
Container with most water algorithm issue

Given n non-negative integers a1, a2, ..., an, where each represents
  a point at coordinate (i, ai). n vertical lines are drawn such that
  the two endpoints of line i is at (i, ai) and (i, 0). Find two lines,
  which together with x-axis forms a container, such that the container
  contains the most water

What I do not understand about this question is how am I supposed to know the y-coordinate value(height) of the n vertical lines.

答:
If the values you are given are {1,2,3,4,4,1,3}, the vertical lines would be:

```<code>4|          |  |
3|       |  |  |     |
2|    |  |  |  |     |
1| |  |  |  |  |  |  |
0| -------------------
   1  2  3  4  5  6  7
</code>```

ai is the height of the ith line, and it's x coordinate is i.

Body:
If the values you are given are {1,2,3,4,4,1,3}, the vertical lines would be:

4|          |  |
3|       |  |  |     |
2|    |  |  |  |     |
1| |  |  |  |  |  |  |
0| -------------------
   1  2  3  4  5  6  7

ai is the height of the ith line, and it's x coordinate is i.


答:
This code will make a new list for the items in list b and seperating them based on the first letter of the string.</p>

```<code>alpha = [x for x in listB if x.startswith('a')]
beta = [x for x in listB if x.startswith('b')]
gamma = [x for x in listB if x.startswith('g')]

print(alpha, beta, gamma, sep='\n')

>>>
['alphav1', 'alphav2', 'alpha$v3', 'alpha$v4-beta', 'alpha-beta']
['beta$v1', 'betav2', 'beta-alpha', 'beta$v6-get']
['gamma']
</code>```

Body:
This code will make a new list for the items in list b and seperating them based on the first letter of the string.

alpha = [x for x in listB if x.startswith('a')]
beta = [x for x in listB if x.startswith('b')]
gamma = [x for x in listB if x.startswith('g')]

print(alpha, beta, gamma, sep='\n')

>>>
['alphav1', 'alphav2', 'alpha$v3', 'alpha$v4-beta', 'alpha-beta']
['beta$v1', 'betav2', 'beta-alpha', 'beta$v6-get']
['gamma']


问:
Is Apps Script JSON.parse() incorrectly stripping leading zeros from string object names?
I have an Apps Script Web App which fetches JSON data.  I have run into problems where keys with leading zeros are modified (e.g "0123" becomes "123") when I call JSON.parse().  It seems to me like the function is treating my string as an integer but still returning it as a string. Is this the expected behavior?

This should reproduce my problem:

```<code>function jsontest() {
  var json = '{"0123":"foo", "bar":"0123", "foobar":123}';
  var test = JSON.parse(json);
  var check = ("0123" in test);
  var check2 = ("123" in test);

  Logger.log(test);
  Logger.log(JSON.stringify(test));
  Logger.log(check);
  Logger.log(check2);
}
</code>```

It produces this in the log:

```<code>[17-06-07 15:22:56:241 CDT] {123=foo, bar=0123, foobar=123}
[17-06-07 15:22:56:241 CDT] {"123":"foo","bar":"0123","foobar":123}
[17-06-07 15:22:56:242 CDT] false
[17-06-07 15:22:56:243 CDT] true
</code>```

答:
In Google Apps Script, JSON.parse() removes single and double quotations. At this time, if the numbers are included in the keys, the keys are changed to number. So "0123" of key is changed to a number "123". As a method for avoiding this, you can use eval(). By using eval(), single and double quotations are removed without converting string to number.

I don't know whether this is best method. So please see this as just one proposal.

Sample :

```<code>var json = '{"0123":"foo", "bar":"0123", "foobar":123}';

var test1 = JSON.parse(json);
var test2 = eval("json=" + json);

Logger.log("%s, %s", test1, JSON.stringify(test1));
Logger.log("%s, %s", test2, JSON.stringify(test2));
</code>```

Result :

```<code>{123=foo, bar=0123, foobar=123}, {"123":"foo","bar":"0123","foobar":123}
{bar=0123, foobar=123.0, 0123=foo}, {"0123":"foo","bar":"0123","foobar":123}
</code>```

When above sample is used for your script, the modified script is as follows.

Modified script :

```<code>function jsontest() {
  var json = '{"0123":"foo", "bar":"0123", "foobar":123}';

  var test = eval("json=" + json); // <-- Added
//  var test = JSON.parse(json);

  var check = ("0123" in test);
  var check2 = ("123" in test);

  Logger.log(test);
  Logger.log(JSON.stringify(test));
  Logger.log(check);
  Logger.log(check2);
}
</code>```

Result :

```<code>{bar=0123, foobar=123.0, 0123=foo}
{"0123":"foo","bar":"0123","foobar":123}
true
false
</code>```

Body:
I have an Apps Script Web App which fetches JSON data.  I have run into problems where keys with leading zeros are modified (e.g "0123" becomes "123") when I call JSON.parse().  It seems to me like the function is treating my string as an integer but still returning it as a string. Is this the expected behavior?

This should reproduce my problem:

function jsontest() {
  var json = '{"0123":"foo", "bar":"0123", "foobar":123}';
  var test = JSON.parse(json);
  var check = ("0123" in test);
  var check2 = ("123" in test);

  Logger.log(test);
  Logger.log(JSON.stringify(test));
  Logger.log(check);
  Logger.log(check2);
}

It produces this in the log:

[17-06-07 15:22:56:241 CDT] {123=foo, bar=0123, foobar=123}
[17-06-07 15:22:56:241 CDT] {"123":"foo","bar":"0123","foobar":123}
[17-06-07 15:22:56:242 CDT] false
[17-06-07 15:22:56:243 CDT] true

Body:
In Google Apps Script, JSON.parse() removes single and double quotations. At this time, if the numbers are included in the keys, the keys are changed to number. So "0123" of key is changed to a number "123". As a method for avoiding this, you can use eval(). By using eval(), single and double quotations are removed without converting string to number.

I don't know whether this is best method. So please see this as just one proposal.

Sample :

var json = '{"0123":"foo", "bar":"0123", "foobar":123}';

var test1 = JSON.parse(json);
var test2 = eval("json=" + json);

Logger.log("%s, %s", test1, JSON.stringify(test1));
Logger.log("%s, %s", test2, JSON.stringify(test2));

Result :

{123=foo, bar=0123, foobar=123}, {"123":"foo","bar":"0123","foobar":123}
{bar=0123, foobar=123.0, 0123=foo}, {"0123":"foo","bar":"0123","foobar":123}

When above sample is used for your script, the modified script is as follows.

Modified script :

function jsontest() {
  var json = '{"0123":"foo", "bar":"0123", "foobar":123}';

  var test = eval("json=" + json); // <-- Added
//  var test = JSON.parse(json);

  var check = ("0123" in test);
  var check2 = ("123" in test);

  Logger.log(test);
  Logger.log(JSON.stringify(test));
  Logger.log(check);
  Logger.log(check2);
}

Result :

{bar=0123, foobar=123.0, 0123=foo}
{"0123":"foo","bar":"0123","foobar":123}
true
false


问:
Android Room: How to model relationships?
I have just started working with Room and although everything seems to be pretty intuitive I currently don't really understand how exactly I could handle relationships.

Because SQLite is a relational database, you can specify relationships between objects. Even though most ORM libraries allow entity objects to reference each other, Room explicitly forbids this. Even though you cannot use direct relationships, Room still allows you to define Foreign Key constraints between entities.(Source: https://developer.android.com/topic/libraries/architecture/room.html#no-object-references)

How should you model a Many to Many or One to Many Relationship?

What would this look like in practice (example DAOs + Entities)?

答:
You can use @Relation annotation to handle relations at Room.

A convenience annotation which can be used in a Pojo to automatically
  fetch relation entities. When the Pojo is returned from a query, all
  of its relations are also fetched by Room.

See document.

(Google's document has confusing examples. I have written the steps and some basic explanation at my another answer. You can check it out)


问:
Console Application as continuous Azure webjob does not convert Time.ToUniversalTime() in UTC
I have a simple console application running as continuous webjob in Azure, Locally when I debug it gives proper output time in UTC when I convert time using
    new DateTime(Time).ToUniversalTime()
but when I run it in webjob it still gives local time instead of universal time.

Console.WriteLine(MyData.Time.ToUniversalTime() + " "+ DateTime.Now.ToUniversalTime());

at 3:43 PM PST

Kudu console (webjob): 6/7/2017 3:38:46 PM 6/7/2017 10:43:52 PM

on local Console: 6/7/2017 10:38:46 PM 6/7/2017 10:43:52 PM

答:
The behavior is by design, and has nothing to do with Azure. When you write

```<code>var dt = new DateTime(2017, 05, 23, 8, 00, 00, 0);
</code>```

It treats it as local time. So of course you get a different UTC time based on the timezone of the machine you're on (which in the case of Azure VMs happens to be the same as UTC time).

To treat the time you enter as UTC, you need to write:

```<code>var dt2 = DateTime.SpecifyKind(dt, DateTimeKind.Utc);
</code>```

See also C# DateTime to UTC Time without changing the time

Body:
The behavior is by design, and has nothing to do with Azure. When you write

var dt = new DateTime(2017, 05, 23, 8, 00, 00, 0);

It treats it as local time. So of course you get a different UTC time based on the timezone of the machine you're on (which in the case of Azure VMs happens to be the same as UTC time).

To treat the time you enter as UTC, you need to write:

var dt2 = DateTime.SpecifyKind(dt, DateTimeKind.Utc);

See also C# DateTime to UTC Time without changing the time


问:
Jenkins CI configuration on Ubuntu for multiple access over the internet
I just set up a jenkins instance on an ubuntu VM, everything works well as I am able to access it via http://localhost:8080, however, I am trying to enable access to the server by multiple users on multiple hosts within the LAN and even outside the LAN. What is the best way to achieve this?

Modifying the "URL" via "Configure System" link on Jenkins Dashboard isnt working.

答:
I'd go with an nginx reverse proxy, that will also handle your SSL offloading.

here is an excellent tutorial:

https://www.digitalocean.com/community/tutorials/how-to-configure-jenkins-with-ssl-using-an-nginx-reverse-proxy


问:
ruby: how do you tag an ec2 instance
how do you tag an ec2 instance create with the aws ruby sdk v2 run_instances method?

I tried 'ec2.tags.create' but that was just a guess.

Update: A deep search of github found this snippet:
    ec2.create_tags(resources: [@launched_instance_id], tags: [ { key: 'Name', value: "#{@config[:service]}-ami"}])

答:
The run_instances() documentation shows:

```<code>resp = client.run_instances({
...
  tag_specifications: [
    {
      resource_type: "customer-gateway", # accepts customer-gateway, dhcp-options, image, instance, internet-gateway, network-acl, network-interface, reserved-instances, route-table, snapshot, spot-instances-request, subnet, security-group, volume, vpc, vpn-connection, vpn-gateway
      tags: [
        {
          key: "String",
          value: "String",
        },
      ],
    },
  ],
...
</code>```

You can also tag an instance after it has launched by using create_tags():

```<code>resp = client.create_tags({
  resources: [
    "i-abcd1234",
  ],
  tags: [
    {
      key: "Stack",
      value: "production",
    },
  ],
})
</code>```

Title: ruby: how do you tag an ec2 instance

Body:
The run_instances() documentation shows:

resp = client.run_instances({
...
  tag_specifications: [
    {
      resource_type: "customer-gateway", # accepts customer-gateway, dhcp-options, image, instance, internet-gateway, network-acl, network-interface, reserved-instances, route-table, snapshot, spot-instances-request, subnet, security-group, volume, vpc, vpn-connection, vpn-gateway
      tags: [
        {
          key: "String",
          value: "String",
        },
      ],
    },
  ],
...

You can also tag an instance after it has launched by using create_tags():

resp = client.create_tags({
  resources: [
    "i-abcd1234",
  ],
  tags: [
    {
      key: "Stack",
      value: "production",
    },
  ],
})


问:
Change username max_length in Django 1.11 (django.contrib.auth)
My users are using e-mail addresses as usernames, which caused a problem in Django 1.9 because there was a 30 character maximum username length.

This was supposed to be fixed by Django 1.10, with a 150 character limit, I believe (though it looks like the docs actually say that max_length should be able to go up to 191 characters for certain databases).

I upgraded to Django 1.11 but username still seems to be limited to 30 characters. Is it because I need to set the value of max_length somewhere? If so, where do I set this (an example would be great)? If not, how do I increase the max length?

Here is my current view.

```<code>def register(request):
    alreadyRegistered = False
    invalidID = False
    context_dict = {}
    if request.method == 'POST':
        # Gather the username and password provided by the user.
        # This information is obtained from the login form.
        Userid = request.POST['username']
        Userid = Userid[0:29] # horrible work-around that has to change
        if User.objects.filter(username=Userid).count() > 0:
            alreadyRegistered = True
        else:
            isGU = 1 > 0 # this will always = TRUE for now
            if isGU or isEA:
                firstname = request.POST['firstname']
                lastname = request.POST['lastname']
                email = Userid
                password = request.POST['password']
                user = User.objects.create_user(Userid, email, password)
                user.first_name = firstname
                user.last_name = lastname
                user.save()
                registered = True
                user = authenticate(username=Userid, password=password)
                login(request, user)
                return HttpResponseRedirect('/studentprogress/')
            else:
                invalidID = True

    context_dict['alreadyRegistered'] = alreadyRegistered
    context_dict['invalidID'] = invalidID
    return render(request,
            'studentprogress/register.html', context_dict)
</code>```

答:
One way to allow custom length of username field is to use custom user model. The documentation is here: https://docs.djangoproject.com/en/1.11/topics/auth/customizing/#specifying-a-custom-user-model

Extend your custom user model from AbstractBaseUser which provides necessary methods to work with Django authentication.

Basically you can just create the model with data you need to have and define the required fields in the model. In your case you might want to set the USERNAME_FIELD and EMAIL_FIELD to be the same field in model.

Body:
My users are using e-mail addresses as usernames, which caused a problem in Django 1.9 because there was a 30 character maximum username length.

This was supposed to be fixed by Django 1.10, with a 150 character limit, I believe (though it looks like the docs actually say that max_length should be able to go up to 191 characters for certain databases).

I upgraded to Django 1.11 but username still seems to be limited to 30 characters. Is it because I need to set the value of max_length somewhere? If so, where do I set this (an example would be great)? If not, how do I increase the max length?

Here is my current view.

def register(request):
    alreadyRegistered = False
    invalidID = False
    context_dict = {}
    if request.method == 'POST':
        # Gather the username and password provided by the user.
        # This information is obtained from the login form.
        Userid = request.POST['username']
        Userid = Userid[0:29] # horrible work-around that has to change
        if User.objects.filter(username=Userid).count() > 0:
            alreadyRegistered = True
        else:
            isGU = 1 > 0 # this will always = TRUE for now
            if isGU or isEA:
                firstname = request.POST['firstname']
                lastname = request.POST['lastname']
                email = Userid
                password = request.POST['password']
                user = User.objects.create_user(Userid, email, password)
                user.first_name = firstname
                user.last_name = lastname
                user.save()
                registered = True
                user = authenticate(username=Userid, password=password)
                login(request, user)
                return HttpResponseRedirect('/studentprogress/')
            else:
                invalidID = True

    context_dict['alreadyRegistered'] = alreadyRegistered
    context_dict['invalidID'] = invalidID
    return render(request,
            'studentprogress/register.html', context_dict)


问:
CSV encoding specification
I am creating a CSV and writing content in UTF-8 to support German and English by specifying encoding as below

```<code>BufferedWriter outFile = new BufferedWriter( new OutputStreamWriter( outputStream, "UTF-8" ) );
</code>```

The above is working fine till I add the below separator indication (;) in the header of CSV

```<code>outFile.write( "sep=;" );
outFile.newLine();
</code>```

Without this delimiter ; my CSV will be wrong but when I inclde this the encoding is failing and UTf-8 not in place.

Is there any other keyword like "sep=" to specify in header of CSV to specify encoding?

I tried encoding="UTF-8" and it is not working.

Thanks.

答:
You cannot open a UTF8 csv file with Excel 2007.  Microsft have no understanding of the word "standards".  Because of this, it is notoriously difficult to generate a csv file which opens in every possible application that reads .csv files and keeps the correct encoding.

If you must use Excel 2007, I would suggest using encoding with Microsofts own "windows 1252" as it supports German characters.  Don't use the header, and also look in to using tab as a separator.  Yes I know the c stands for comma, but tab seems to be more consistent with Excel 2007 if you save the file back again.

Title: CSV encoding specification

Body:
I am creating a CSV and writing content in UTF-8 to support German and English by specifying encoding as below

BufferedWriter outFile = new BufferedWriter( new OutputStreamWriter( outputStream, "UTF-8" ) );

The above is working fine till I add the below separator indication (;) in the header of CSV

outFile.write( "sep=;" );
outFile.newLine();

Without this delimiter ; my CSV will be wrong but when I inclde this the encoding is failing and UTf-8 not in place.

Is there any other keyword like "sep=" to specify in header of CSV to specify encoding?

I tried encoding="UTF-8" and it is not working.

Thanks.


问:
Add parameters to a build to be edited a "Queue" time
I have made several custom process parameters.  They are for versioning purposes (ie IsMajorBuild, IsMinorBuild, etc.)

When I right click on my build and select Edit Build Definition, then select Process I see all of my custom parameters listed there.

But when I queue a new build and click on "Parameters" I only see some of the "Basic" and "Advanced" items.

Is there a way to get at least some of my custom parameters into that list?  It would be nice to be able to indicate a minor build with out having to:

Open the Build Definition

Edit the custom parameters and save

Queue the build

Open the Build Definition

Put the parameters back and save

If could get them in the queue parameters, I could just change it while queuing the build.

Is there a way to do this?

答:
When you add a parameter to the metadata, there is a "View this parameter when:" combo box.

That lets you choose if when you want to see it.

Just as an FYI, the xml tag is called BrowsableWhen

ContentLicense: CC BY-SA 2.5


问:
Breaking an infinite loop in Node.js/Express.Js
I've created an Express app that is supposed to be paginating through an external API call.  I've looked at this every which way and I can't figure out why the function isn't tripping the condition to break the loop. Any help would be appreciated!

Looks like I can't break from the last loop, calling the makeRequest function. Evidence for the infinite loop is the first console.log in the request callback, "I'm making a request." I had more console.logs further down in the callback function that should also always return something but it doesn't even seem to get to those.

```<code>app.post("/api/example", function(req, res) {
    var username = username;
    var password = password;
    var container = [];
    var counter = 0;
    var keepGoing = true;

    var makeRequest = function() {
        console.log("I'm making a request");
        var URL = "https://fakeapiurl.com/&page=" + counter;
        request.get(URL, {
            'auth': {
                'user': username,
                'pass': password,
                'sendImmediately': true
            },
            'content-type': 'application/json'
            }, function(error, response, data) {
                var results = JSON.parse(data);
                var examples = results.examples;
                var numOfExamples = results.numResults;
                console.log(numOfExamples);

                if ((numOfExamples === 0) || (numOfExamples === jobsContainer.length - 1)) {
                    counter = 5;
                    keepGoing = false;
                } else {
                    counter++;
                    for (var i = 0; i < examples.length; i++) {
                    container.push(examples[i]);
                    }
                }

                if (counter === 5) {
                    keepGoing = false;
                    container.sort(function(a, b) {
                        etc.
                    });

                    res.send(container);
                }
            });// end of request call
        };// end of makeRequest function

    while (keepGoing === true) {
        makeRequest();
    }

});// end of app post
</code>```

答:
This will never work like you would expect, you're firing async requests inside a sync while loop. So at the time the first request is trying to get the data, you're firing the same request again, so your first request gets canceled. This goes like forever. You should fire the next request inside the success callback of the previous request, so it gets fired after the previous one resolves.

Something like that:

```<code>app.post("/api/example", function(req, res) {
var username = username;
var password = password;
var container = [];
var maxPages = 5;
var makeRequest = function(page) {
    console.log("I'm making a request");
    var URL = "https://fakeapiurl.com/&page=" + page;
    request.get(URL, {
        'auth': {
            'user': username,
            'pass': password,
            'sendImmediately': true
        },
        'content-type': 'application/json'
        }, function(error, response, data) {
            var results = JSON.parse(data);
            var examples = results.examples || [];
            var numOfExamples = results.numResults;
            var lastPageReached = (numOfExamples === 0 || numOfExamples === jobsContainer.length - 1);
            lastPageReached = lastPageReached  && page < maxPages;

            if (lastPageReached) {
                container.sort(function(a, b) {
                    etc.
                });
                res.send(container);
            } else {
                container = container.concat(...examples);
                makeRequest(page + 1);
            }
        });
    };
  makeRequest(0);
});
</code>```

Body:
I've created an Express app that is supposed to be paginating through an external API call.  I've looked at this every which way and I can't figure out why the function isn't tripping the condition to break the loop. Any help would be appreciated!

Looks like I can't break from the last loop, calling the makeRequest function. Evidence for the infinite loop is the first console.log in the request callback, "I'm making a request." I had more console.logs further down in the callback function that should also always return something but it doesn't even seem to get to those.

app.post("/api/example", function(req, res) {
    var username = username;
    var password = password;
    var container = [];
    var counter = 0;
    var keepGoing = true;

    var makeRequest = function() {
        console.log("I'm making a request");
        var URL = "https://fakeapiurl.com/&page=" + counter;
        request.get(URL, {
            'auth': {
                'user': username,
                'pass': password,
                'sendImmediately': true
            },
            'content-type': 'application/json'
            }, function(error, response, data) {
                var results = JSON.parse(data);
                var examples = results.examples;
                var numOfExamples = results.numResults;
                console.log(numOfExamples);

                if ((numOfExamples === 0) || (numOfExamples === jobsContainer.length - 1)) {
                    counter = 5;
                    keepGoing = false;
                } else {
                    counter++;
                    for (var i = 0; i < examples.length; i++) {
                    container.push(examples[i]);
                    }
                }

                if (counter === 5) {
                    keepGoing = false;
                    container.sort(function(a, b) {
                        etc.
                    });

                    res.send(container);
                }
            });// end of request call
        };// end of makeRequest function

    while (keepGoing === true) {
        makeRequest();
    }

});// end of app post

Body:
This will never work like you would expect, you're firing async requests inside a sync while loop. So at the time the first request is trying to get the data, you're firing the same request again, so your first request gets canceled. This goes like forever. You should fire the next request inside the success callback of the previous request, so it gets fired after the previous one resolves.

Something like that:

app.post("/api/example", function(req, res) {
var username = username;
var password = password;
var container = [];
var maxPages = 5;
var makeRequest = function(page) {
    console.log("I'm making a request");
    var URL = "https://fakeapiurl.com/&page=" + page;
    request.get(URL, {
        'auth': {
            'user': username,
            'pass': password,
            'sendImmediately': true
        },
        'content-type': 'application/json'
        }, function(error, response, data) {
            var results = JSON.parse(data);
            var examples = results.examples || [];
            var numOfExamples = results.numResults;
            var lastPageReached = (numOfExamples === 0 || numOfExamples === jobsContainer.length - 1);
            lastPageReached = lastPageReached  && page < maxPages;

            if (lastPageReached) {
                container.sort(function(a, b) {
                    etc.
                });
                res.send(container);
            } else {
                container = container.concat(...examples);
                makeRequest(page + 1);
            }
        });
    };
  makeRequest(0);
});


问:
Android Emulator Redeployment Hangs
Everytime I redeploy an android application it hangs at this step:

[2010-12-14 09:48:40 - HelloWorld] Uploading HelloWorld.apk onto device 'emulator-5554'

[2010-12-14 09:48:49 - HelloWorld] Installing HelloWorld.apk...

If I then go into the DDMS, I can kill the process (by hitting the stop sign) and then it finishes and launches the application.  Any idea how to fix this?  I've rebuilt the emulator, rebuilt the workspace etc with the same behavior.  I'm using Eclipse build 20100218-1602

答:
you may want to uninstall the app if it already exists on your phone,

on the phone
Menu > Settings > Applications > Manage Applications > find the app and then click the "uninstall" button

or with adb

adb uninstall [-k]  - remove this app package from the device

('-k' means keep the data and cache directories)

checkout this link http://developer.android.com/guide/developing/eclipse-adt.html on running apps on devices or emulators

Automatic and manual target modes
By default, a run configuration uses the automatic target mode in order to select an AVD. In this mode, ADT will select an AVD for the application in the following manner:

If there's a device or emulator already running and its AVD configuration meets the requirements of the application's build target, the application is installed and run upon it.
If there's more than one device or emulator running, each of which meets the requirements of the build target, a "device chooser" is shown to let you select which device to use.
If there are no devices or emulators running that meet the requirements of the build target, ADT looks at the available AVDs. If one meets the requirements of the build target, the AVD is used to launch a new emulator, upon which the application is installed and run.
If all else fails, the application will not be run and you will see a console error warning you that there is no existing AVD that meets the build target requirements.
However, if a "preferred AVD" is selected in the run configuration, then the application will always be deployed to that AVD. If it's not already running, then a new emulator will be launched.

If your run configuration uses manual mode, then the "device chooser" is presented every time that your application is run, so that you can select which AVD to use.

Title: Android Emulator Redeployment Hangs


问:
How to search multiple keywords in file using nodejs?
Lets say i have multiple search keywords from client side searchStr that should match with the line in file , how i will match both text with each line in file and push that line to results. With below code i am getting empty response of results, Any idea what is implemented wrong ?

search.js

```<code>  function asyncFiles(filesData) {
     async.eachSeries(filesData.logFiles, function(logfile, done) {
         // read file
         readStream = fs.createReadStream('./logs/' + filesData.searchEnv + '/' + logfile.filename, 'utf8')
         readStream.pipe(split())
             .on('data', function(line) {
               var searchStr = [{"text":"4588769"},{"text":"request"}]
                 searchStr.forEach(function(text) {
                     if (line.toLowerCase().indexOf(text.toLowerCase()) != -1)
                         var messageDateInfo = line.split('|')[0].replace(/[\[\]']+/g, '');
                     messageDateInfo = new Date(messageDateInfo).getTime();
                     searchStartDate = new Date(searchStartDate).getTime();
                     searchEndDate = new Date(searchEndDate).getTime();
                     if (messageDateInfo - searchStartDate > 0 && searchEndDate - messageDateInfo > 0) {
                         results.push({
                             filename: logfile.filename,
                             value: line
                         });
                     }
                 });
             });
         done();
     }, function(err) {
         if (err) {
             console.log('error', err);
         }
         readStream.on('end', function() {
             callback(results);
         });
         results = [];
     });
 }
</code>```

答:
You can mix slow functions with arbitrary logic and execute it sequentially via synchronous JS executor nsynjs. Your code will transform as follows:

```<code>function process(textFile,filesData) {
    var results=[];
    for(var i=0; i<filesData.logFiles.length, i++ ) {
        var file = filesData.logFiles[i];
        var fh = new textFile();
        fh.open(file);
        var line;
        var searchStr = [{"text":"4588769"},{"text":"request"}]
        while (typeof(line = fh.readLine(nsynjsCtx).data) != 'undefined') {
            for(var i=0; i<searchStr.length; i++)
                if (line.toLowerCase().indexOf(searchStr[i].toLowerCase()) != -1) {
                    var messageDateInfo = line.split('|')[0].replace(new RegExp("[\[\]']+","g"), '');
                    messageDateInfo = new Date(messageDateInfo).getTime();
                    searchStartDate = new Date(searchStartDate).getTime();
                    searchEndDate = new Date(searchEndDate).getTime();
                    if (messageDateInfo - searchStartDate > 0 && searchEndDate - messageDateInfo > 0) {
                        results.push({
                            filename: logfile.filename,
                            value: line
                        });
                    };
                };
        };
        fh.close();
    };
    return results;
};
</code>```

And you can run it via nsynjs like this:

```<code>var nsynjs = require('nsynjs');
var textFile = require('../../wrappers/nodeReadline').textFile; // part of nsynjs package

function process(...){
...
}

nsynjs.run(process,{},textFile,filesData,function (results) {
    console.log('done', results); // results are ready here
});
</code>```

Body:
Lets say i have multiple search keywords from client side searchStr that should match with the line in file , how i will match both text with each line in file and push that line to results. With below code i am getting empty response of results, Any idea what is implemented wrong ?

search.js

  function asyncFiles(filesData) {
     async.eachSeries(filesData.logFiles, function(logfile, done) {
         // read file
         readStream = fs.createReadStream('./logs/' + filesData.searchEnv + '/' + logfile.filename, 'utf8')
         readStream.pipe(split())
             .on('data', function(line) {
               var searchStr = [{"text":"4588769"},{"text":"request"}]
                 searchStr.forEach(function(text) {
                     if (line.toLowerCase().indexOf(text.toLowerCase()) != -1)
                         var messageDateInfo = line.split('|')[0].replace(/[\[\]']+/g, '');
                     messageDateInfo = new Date(messageDateInfo).getTime();
                     searchStartDate = new Date(searchStartDate).getTime();
                     searchEndDate = new Date(searchEndDate).getTime();
                     if (messageDateInfo - searchStartDate > 0 && searchEndDate - messageDateInfo > 0) {
                         results.push({
                             filename: logfile.filename,
                             value: line
                         });
                     }
                 });
             });
         done();
     }, function(err) {
         if (err) {
             console.log('error', err);
         }
         readStream.on('end', function() {
             callback(results);
         });
         results = [];
     });
 }

Body:
You can mix slow functions with arbitrary logic and execute it sequentially via synchronous JS executor nsynjs. Your code will transform as follows:

function process(textFile,filesData) {
    var results=[];
    for(var i=0; i<filesData.logFiles.length, i++ ) {
        var file = filesData.logFiles[i];
        var fh = new textFile();
        fh.open(file);
        var line;
        var searchStr = [{"text":"4588769"},{"text":"request"}]
        while (typeof(line = fh.readLine(nsynjsCtx).data) != 'undefined') {
            for(var i=0; i<searchStr.length; i++)
                if (line.toLowerCase().indexOf(searchStr[i].toLowerCase()) != -1) {
                    var messageDateInfo = line.split('|')[0].replace(new RegExp("[\[\]']+","g"), '');
                    messageDateInfo = new Date(messageDateInfo).getTime();
                    searchStartDate = new Date(searchStartDate).getTime();
                    searchEndDate = new Date(searchEndDate).getTime();
                    if (messageDateInfo - searchStartDate > 0 && searchEndDate - messageDateInfo > 0) {
                        results.push({
                            filename: logfile.filename,
                            value: line
                        });
                    };
                };
        };
        fh.close();
    };
    return results;
};

And you can run it via nsynjs like this:

var nsynjs = require('nsynjs');
var textFile = require('../../wrappers/nodeReadline').textFile; // part of nsynjs package

function process(...){
...
}

nsynjs.run(process,{},textFile,filesData,function (results) {
    console.log('done', results); // results are ready here
});


问:
How to secure component/path behind authentication in react?
Hello I am trying to make a certain path "/main" only accessible to logged in users. I have a loginUser action that sends the login request then redirects to "/main". However if you just type in "/main" after localhost:3000 without loggin in you can still get to "/main". Any help appreciated.

Here is my action:

```<code>export function loginUser(username1, password1) {
const mainPage = (response, dispatch) => {
  if(true) {
    history.push('/main');
  }
  dispatch({
      type: POST_DATA_SUCCESS,
      response,
  });
 };
const promise = fetch('http://localhost:8080/users/login', {
 method: 'POST',
 headers: {
  'Accept': 'application/json',
  'Content-Type': 'application/json',
  'Authorization': 'Basic ' + btoa(username1 + ":" + password1),
 },
 body: JSON.stringify({
   username: username1,
   password: password1,
  })
 });
 return {
    onRequest: POST_DATA_TRIGGERED,
    onSuccess: mainPage,
    onFailure: POST_DATA_FAILURE,
    promise,
  };
  }
</code>```

Here is my app.js:

```<code>import React from 'react';
import {Router, Route, Link} from 'react-router-dom';
import history from '../history'
import Journal from './journal';
import AddForm from './add-form';
import GetSearch from './old-search';
import SignUp from './signup';
import Front from './front';
import { loginUser } from '../actions';

export default function App(props) {
  return(
   <Router history={history}>
    <div>
      <h3><Link className="title-journey" to="/">A Journey of Life</Link>
      </h3>
       <main>
        <Route exact path="/" component={Journal} />
        <Route path="/sign-up" component={SignUp} />
        <Route path="/add" component={AddForm} />
        <Route path="/get" component={GetSearch} />
        <Route path="/main" component={Front} />
       </main>
    </div>
   </Router>
  );
 }
</code>```

And here is my login.js component:

```<code> import React from 'react';
 import {BrowserRouter as Router, Route, Link} from 'react-router-dom';
 import { loginUser } from '../actions';
 import { connect } from 'react-redux';

 export class Login extends React.Component {
  constructor(props) {
   super(props);
   this.state = {
   //username: '',
   //password: '',
   }
 }

login(e) {
  e.preventDefault();
 const userName = this.username.value;
 const passWord = this.password.value;
 console.log(userName);
 console.log(passWord);
  this.props.loginUser(userName, passWord);
 }

render() {
  return(
    <form>
     <h3>Login to start your Journey</h3>
     <input placeholder="username" ref={input => {this.username = input}}>
     </input>
     <input placeholder="password" type="password"ref={input =>
     {this.password = input}}></input>
     <button onClick={this.login.bind(this)}>Login</button>
    </form>
   )
  }
}

export default connect(null, { loginUser })(Login);
</code>```

答:
It looks like you are using react-router v4.  They recommend using the render prop on the Route component to render a redirect when the user does not have proper authorization.  It is a component that looks like this:

```<code>const PrivateRoute = ({ component: Component, ...rest }) => (
  <Route {...rest} render={props => (
    fakeAuth.isAuthenticated ? (
      <Component {...props}/>
    ) : (
      <Redirect to={{
        pathname: '/login',
        state: { from: props.location }
      }}/>
    )
  )}/>
</code>```

And then your app would look like

```<code>   <main>
    <Route exact path="/" component={Journal} />
    <Route path="/sign-up" component={SignUp} />
    <Route path="/add" component={AddForm} />
    <Route path="/get" component={GetSearch} />
    <PrivateRoute path="/main" component={Front} />
   </main>
</code>```

How you check to see if the user is authenticated is up to you, i.e fakeAuth.isAuthenticated

Body:
Hello I am trying to make a certain path "/main" only accessible to logged in users. I have a loginUser action that sends the login request then redirects to "/main". However if you just type in "/main" after localhost:3000 without loggin in you can still get to "/main". Any help appreciated.

Here is my action:

export function loginUser(username1, password1) {
const mainPage = (response, dispatch) => {
  if(true) {
    history.push('/main');
  }
  dispatch({
      type: POST_DATA_SUCCESS,
      response,
  });
 };
const promise = fetch('http://localhost:8080/users/login', {
 method: 'POST',
 headers: {
  'Accept': 'application/json',
  'Content-Type': 'application/json',
  'Authorization': 'Basic ' + btoa(username1 + ":" + password1),
 },
 body: JSON.stringify({
   username: username1,
   password: password1,
  })
 });
 return {
    onRequest: POST_DATA_TRIGGERED,
    onSuccess: mainPage,
    onFailure: POST_DATA_FAILURE,
    promise,
  };
  }

Here is my app.js:

import React from 'react';
import {Router, Route, Link} from 'react-router-dom';
import history from '../history'
import Journal from './journal';
import AddForm from './add-form';
import GetSearch from './old-search';
import SignUp from './signup';
import Front from './front';
import { loginUser } from '../actions';

export default function App(props) {
  return(
   <Router history={history}>

<Link className="title-journey" to="/">A Journey of Life</Link>

        <Route exact path="/" component={Journal} />
        <Route path="/sign-up" component={SignUp} />
        <Route path="/add" component={AddForm} />
        <Route path="/get" component={GetSearch} />
        <Route path="/main" component={Front} />

   </Router>
  );
 }

And here is my login.js component:

 import React from 'react';
 import {BrowserRouter as Router, Route, Link} from 'react-router-dom';
 import { loginUser } from '../actions';
 import { connect } from 'react-redux';

 export class Login extends React.Component {
  constructor(props) {
   super(props);
   this.state = {
   //username: '',
   //password: '',
   }
 }

login(e) {
  e.preventDefault();
 const userName = this.username.value;
 const passWord = this.password.value;
 console.log(userName);
 console.log(passWord);
  this.props.loginUser(userName, passWord);
 }

render() {
  return(
    <form>

Login to start your Journey

     <input placeholder="username" ref={input => {this.username = input}}>
     </input>
     <input placeholder="password" type="password"ref={input =>
     {this.password = input}}></input>
     <button onClick={this.login.bind(this)}>Login</button>
    </form>
   )
  }
}

export default connect(null, { loginUser })(Login);

Body:
It looks like you are using react-router v4.  They recommend using the render prop on the Route component to render a redirect when the user does not have proper authorization.  It is a component that looks like this:

const PrivateRoute = ({ component: Component, ...rest }) => (
  <Route {...rest} render={props => (
    fakeAuth.isAuthenticated ? (
      <Component {...props}/>
    ) : (
      <Redirect to={{
        pathname: '/login',
        state: { from: props.location }
      }}/>
    )
  )}/>

And then your app would look like

   <main>
    <Route exact path="/" component={Journal} />
    <Route path="/sign-up" component={SignUp} />
    <Route path="/add" component={AddForm} />
    <Route path="/get" component={GetSearch} />
    <PrivateRoute path="/main" component={Front} />
   </main>

How you check to see if the user is authenticated is up to you, i.e fakeAuth.isAuthenticated


问:
entry point for packager
I'm just starting out with react native. Everything was going ok but now when I run 'react-native run-ios' the packager is looking for js files in

```<code><project-root>/node_modules/react-native/packager
</code>```

instead of

```<code><project-root>
</code>```

If I run 'node node_modules/react-native/local-cli/cli.js start'
it looks for files in the correct location.

This is happening in my existing project and if I create a new project using react native init. It started after I installed a new npm module. I've since reverted the change, re-installed modules, cleared the tmpdir cache, rebooted computer etc. Can I explicitly configure the packager entry point?

Any help greatly appreciated

C

答: What worked for me was reverting to 0.43.1 (a version that I have other apps working with): delete node_modules, change package.json under dependencies to "react-native": "0.43.1", and npm install. Verify your version with react-native --version, and run again.

Title: entry point for packager

Body:
I'm just starting out with react native. Everything was going ok but now when I run 'react-native run-ios' the packager is looking for js files in

<project-root>/node_modules/react-native/packager

instead of

<project-root>

If I run 'node node_modules/react-native/local-cli/cli.js start'
it looks for files in the correct location.

This is happening in my existing project and if I create a new project using react native init. It started after I installed a new npm module. I've since reverted the change, re-installed modules, cleared the tmpdir cache, rebooted computer etc. Can I explicitly configure the packager entry point?

Any help greatly appreciated

C


问:
Appharbor and Amazon SES
Do applications hosted on Appharbor qualify for the Amazon SES 62,000 messages per month at the free tier?

"If you are an Amazon EC2 user, you can start sending with Amazon SES for free. You can send 62,000 messages per month to any recipient when you call Amazon SES from an Amazon EC2 instance directly or through AWS Elastic Beanstalk. Additionally, you can also receive 1,000 messages per month for free on Amazon SES. Many applications are able to operate entirely within this free tier limit, and it does not expire after a year."

https://aws.amazon.com/ses/pricing/

答: Yes is the answer to this question. </p>

Title: Appharbor and Amazon SES

Body: Yes is the answer to this question.


问:
Is it the driver or the workers who reads the text file when sc.textfile is used?
I am wondering how is sc.textfile used in Spark. My guess is that the driver reads a portion of the file at a time, and distributes the read text to the workers, to process. Or is it that the workers read the text directly themselves from the file without the involvement of the driver?</p>

答:
The driver looks at file metadata - check that it exists, check what files are in the directory if it's a directory, and check their sizes. It then sends tasks to workers, who do the actual reading of the file contents. The communication is essentially "you read this file, starting at this offset, for this length."

HDFS splits large files into blocks, and spark will (usually/often) split tasks according to blocks, so the process of skipping to that offset will be efficient.

Other filesystems tend to operate similarly, though not always. Compression can also mess with this process if the codec is not splittable.


问:
package.json vs bower.json
What is the difference between package.json vs bower.json.?

what is the criteria that we should consider before defining the dependencies in both files.

And what difference will it make by running "bower install" and "npm install" ?

答:
** Package.json file is for node related package manager while bower can manage application level package dependencies. I like bower more.

** We need to find which dependencies related to development and which are production.

** "bower install" -- Install all dependencies mentioned in Dependencies object.
** "bower install -D" -- Install all dependencies mentioned in DevDependencies object.

Same with Npm Install and npm install -D

Title: package.json vs bower.json


问:
skip-secure-auth option not working with mysqldump
I am trying to export a mysql schema from remote server to local but geting the following error:

C:\Program Files\MySQL\MySQL Server 5.6\bin>mysqldump  --skip-secure-auth -h  x.y.z.d -uatulya  -p'root'  t_tcadmin |mysql -u root -proot t_tcadmin

mysqldump: unknown option '--skip-secure-auth'

Warning: Using a password on the command line interface can be insecure.

Without the --skip-secure-auth it connects but  I get error 2049.

So I want to use this option to skip secure auth but it is giving the above error.
Could anyone suggest.

Thanks..

答: If you are in a pinch, dealing with an older server where updating the passwords to the newer method is not an option (say, MySQL Server v5.0.95) and attempting to migrate the data to a newer system - without modifying the fragile older system, you may need to temporarily downgrade your local mysql client to 5.5 for myasqldump to be able to talk to the older server.  As of 5.6 it is possible to use the MySQL client to connect to it - using --skip-secure-auth in the command, but mysqldump will not accept that flag.  And, in MySQL 5.7+ it is impossible to connect to a server that uses the older password storage method at all.</p>


问:
Dialog does not show via AsyncTask
I have a custom progress dialog that seems to work everywhere except here in my code:

My login activity (relevant snippets):

```<code>@Override
protected void onCreate(Bundle savedInstanceState) {

    try {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        context = this;
        pd = AUtils.getProgressDialog(context, false);

                UserExistsAuthenticateAndRoute = getIntent().getBooleanExtra("UserExistsAuthenticateAndRoute", false);
        RouteToActivity = getIntent().getStringExtra("RouteToActivity");

        //make sure there is no token in APrefs in memory during login
        APrefs pref = new APrefs();
        if (pref != null) {
            pref.putNMToken(null);
            pref.putNMRefreshToken(null);
        }

        ClickableSpan span = new ClickableSpan() {

            @Override
            public void onClick(View widget) {

            }
        };

        setActionBar();
        initUi();
        mToolbarTitle.setText("Log In");
    } catch (Exception exc) {
        exc.printStackTrace();
    }

}
        @Override
        protected Void doInBackground(Void... voids) {

            GDDataManager.get().login(GDUser, new DataCallBack() {
                        @Override
                        public void update(DataUpdate update) {

                            if (update.code == 0) {
                                final GDUser _gdUser = pref.getMember();
                                //call get status
                                if (_gdUser != null) {
                                    Log.i(TAG, "getUserStatus()");
                                    GDDataManager.get().getUserStatus(_gdUser, new DataCallBack() {
                                        @Override
                                        public void update(DataUpdate update) {

                                            if (update.code == 0) {
                                                setGdUserStatus((GDUserStatus) update.data);
                                                loginController(getGdUserStatus(), _gdUser);

                                            } else {

                                                Log.e(TAG, "getUserStatus(), error response msg " + update.message);
                                                if (update.message.contains("error")) {
                                                    App.toast(getString(R.string.general_server_error_message));

                                                }

                                            }
                                        }
                                    });
                                }

                            } else {

                                Log.e(TAG, "update message:" + update.message);
                                if (update.message.contains("error")) {
                                    App.toast(getString(R.string.general_server_error_message));
                                } else if (update.message.contains("could not verify password")) {
                                    App.toast(getString(R.string.could_not_verify_password));
                                } else if (update.message.contains("no user found")) {
                                    App.toast(getString(R.string.no_user_found));
                                } else {
                                    App.toast(update.message);
                                }

                                if (btnLogIn != null) {
                                    //disable is valid in order to prevent double click
                                    btnLogIn.setEnabled(false);
                                    btnLogIn.setTextColor(ContextCompat.getColor(context, R.color.colorGrey));
                                }

                                edtEmail.setCompoundDrawablesWithIntrinsicBounds(null, null, ContextCompat.getDrawable(context, R.drawable.cross_icon), null);
                                edtEmail.setBackground(ContextCompat.getDrawable(context, R.drawable.textfield_red));
                                edtPassword.setBackground(ContextCompat.getDrawable(context, R.drawable.textfield_red));
                            }

                        }//end update getUserStatus
                    }

            );

            return null;
        }
    };

    try {
        tryLoginTask.execute();
    } catch (Exception exc) {
        Log.d(TAG, exc.getMessage());
        exc.printStackTrace();
        //cancel task on exception , DISMISS DIALOG to avoid locking screen
        tryLoginTask.cancel(true);
    }

}//end tryLogin()
</code>```

The static code from utility class, were the dialog is returned (relevant snippet):

```<code>public static Dialog getProgressDialog(Context c, boolean isCancelable) {

    Dialog pd = new Dialog(c,c.getApplicationInfo().theme);
    pd.setCanceledOnTouchOutside(isCancelable);
    pd.requestWindowFeature (Window.FEATURE_NO_TITLE);
    pd.setContentView (R.layout.progress_dialog);
    pd.getWindow().setBackgroundDrawable(new ColorDrawable(Color.argb(150,0,0,0)));

    return pd;
}
</code>```

Im not seeing any errors, exceptions, and the dialog is showiong in other places using the same approach. Sometimes I see it for fraction of a second however the task hasn't completed.

Any suggestions.

Thanks

答:
AlertDialogs are foreground things. You should show your Dialogs in your UI thread. So if you want to show your Dialog in an AsyncTask you should approach with runOnUiThread:

```<code>runOnUiThread(new Runnable() {
    @Override
    public void run() {
        // Show your dialog here
    }
});
</code>```

Documentations:

https://developer.android.com/reference/android/os/AsyncTask.html

https://developer.android.com/guide/components/processes-and-threads.html

Title: Dialog does not show via AsyncTask

Body:
I have a custom progress dialog that seems to work everywhere except here in my code:

My login activity (relevant snippets):

@Override
protected void onCreate(Bundle savedInstanceState) {

    try {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        context = this;
        pd = AUtils.getProgressDialog(context, false);

                UserExistsAuthenticateAndRoute = getIntent().getBooleanExtra("UserExistsAuthenticateAndRoute", false);
        RouteToActivity = getIntent().getStringExtra("RouteToActivity");

        //make sure there is no token in APrefs in memory during login
        APrefs pref = new APrefs();
        if (pref != null) {
            pref.putNMToken(null);
            pref.putNMRefreshToken(null);
        }

        ClickableSpan span = new ClickableSpan() {

            @Override
            public void onClick(View widget) {

            }
        };

        setActionBar();
        initUi();
        mToolbarTitle.setText("Log In");
    } catch (Exception exc) {
        exc.printStackTrace();
    }

}
        @Override
        protected Void doInBackground(Void... voids) {

            GDDataManager.get().login(GDUser, new DataCallBack() {
                        @Override
                        public void update(DataUpdate update) {

                            if (update.code == 0) {
                                final GDUser _gdUser = pref.getMember();
                                //call get status
                                if (_gdUser != null) {
                                    Log.i(TAG, "getUserStatus()");
                                    GDDataManager.get().getUserStatus(_gdUser, new DataCallBack() {
                                        @Override
                                        public void update(DataUpdate update) {

                                            if (update.code == 0) {
                                                setGdUserStatus((GDUserStatus) update.data);
                                                loginController(getGdUserStatus(), _gdUser);

                                            } else {

                                                Log.e(TAG, "getUserStatus(), error response msg " + update.message);
                                                if (update.message.contains("error")) {
                                                    App.toast(getString(R.string.general_server_error_message));

                                                }

                                            }
                                        }
                                    });
                                }

                            } else {

                                Log.e(TAG, "update message:" + update.message);
                                if (update.message.contains("error")) {
                                    App.toast(getString(R.string.general_server_error_message));
                                } else if (update.message.contains("could not verify password")) {
                                    App.toast(getString(R.string.could_not_verify_password));
                                } else if (update.message.contains("no user found")) {
                                    App.toast(getString(R.string.no_user_found));
                                } else {
                                    App.toast(update.message);
                                }

                                if (btnLogIn != null) {
                                    //disable is valid in order to prevent double click
                                    btnLogIn.setEnabled(false);
                                    btnLogIn.setTextColor(ContextCompat.getColor(context, R.color.colorGrey));
                                }

                                edtEmail.setCompoundDrawablesWithIntrinsicBounds(null, null, ContextCompat.getDrawable(context, R.drawable.cross_icon), null);
                                edtEmail.setBackground(ContextCompat.getDrawable(context, R.drawable.textfield_red));
                                edtPassword.setBackground(ContextCompat.getDrawable(context, R.drawable.textfield_red));
                            }

                        }//end update getUserStatus
                    }

            );

            return null;
        }
    };

    try {
        tryLoginTask.execute();
    } catch (Exception exc) {
        Log.d(TAG, exc.getMessage());
        exc.printStackTrace();
        //cancel task on exception , DISMISS DIALOG to avoid locking screen
        tryLoginTask.cancel(true);
    }

}//end tryLogin()

The static code from utility class, were the dialog is returned (relevant snippet):

public static Dialog getProgressDialog(Context c, boolean isCancelable) {

    Dialog pd = new Dialog(c,c.getApplicationInfo().theme);
    pd.setCanceledOnTouchOutside(isCancelable);
    pd.requestWindowFeature (Window.FEATURE_NO_TITLE);
    pd.setContentView (R.layout.progress_dialog);
    pd.getWindow().setBackgroundDrawable(new ColorDrawable(Color.argb(150,0,0,0)));

    return pd;
}

Im not seeing any errors, exceptions, and the dialog is showiong in other places using the same approach. Sometimes I see it for fraction of a second however the task hasn't completed.

Any suggestions.

Thanks

Body:
AlertDialogs are foreground things. You should show your Dialogs in your UI thread. So if you want to show your Dialog in an AsyncTask you should approach with runOnUiThread:

runOnUiThread(new Runnable() {
    @Override
    public void run() {
        // Show your dialog here
    }
});

Documentations:

https://developer.android.com/reference/android/os/AsyncTask.html

https://developer.android.com/guide/components/processes-and-threads.html


问:
Where to place line of code in html for ReactDOM.render?
I have the following code which is in a saved format of .html (index.html).

I am learning React right now and when I execute this html file in the browser, nothing happens.

I am wondering where the two lines of code are suppose to go or how to call them (execute the rendering).

Where would I find the files in ./lib if I am using a mac?

```<code><!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>Introduction | Learning React</title>
    <link rel="stylesheet" href="lib/style.css" />
  </head>
  <body>
    <section id="entry-point"></section>

    <!-- Wifi might be spotty, so we've downloaded these to `./lib` -->
    <script src="lib/react.js"></script>
    <script src="lib/react-dom.js"></script>

    <script type="text/javascript">
      // Intentionally blank. Your walk-through code will go here
      var hello = React.createElement('p', null, 'Hello, World!');

      // Checkout what this does by opening your HTML file in the browser
      ReactDOM.render(hello, document.getElementById('entry-point'));
    </script>
  </body>
</html>
</code>```

答:
If you don't want to use packet managers you can include React with CDNs.

For development:

```<code><script src="https://unpkg.com/react@15/dist/react.js"></script>
<script src="https://unpkg.com/react-dom@15/dist/react-dom.js"></script>
</code>```

For production (minified):

```<code><script src="https://unpkg.com/react@15/dist/react.min.js"></script>
<script src="https://unpkg.com/react-dom@15/dist/react-dom.min.js"></script>
</code>```

Body:
I have the following code which is in a saved format of .html (index.html).

I am learning React right now and when I execute this html file in the browser, nothing happens.

I am wondering where the two lines of code are suppose to go or how to call them (execute the rendering).

Where would I find the files in ./lib if I am using a mac?

<!DOCTYPE html>

    <meta charset="UTF-8" />
    <title>Introduction | Learning React</title>
    <link rel="stylesheet" href="lib/style.css" />

Body:
If you don't want to use packet managers you can include React with CDNs.

For development:

<script src="https://unpkg.com/react@15/dist/react.js"></script>
<script src="https://unpkg.com/react-dom@15/dist/react-dom.js"></script>

For production (minified):

<script src="https://unpkg.com/react@15/dist/react.min.js"></script>
<script src="https://unpkg.com/react-dom@15/dist/react-dom.min.js"></script>