问:
How to get the same result in book "Web Scraping with Python: Collecting Data from the Modern Web" Chapter 7 Data Normalization section
Python version: 2.7.10

My code:

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

from urllib2 import urlopen
from bs4 import BeautifulSoup
from collections import OrderedDict
import re
import string

def cleanInput(input):
    input = re.sub('\n+', " ", input)
    input = re.sub('\[[0-9]*\]', "", input)
    input = re.sub(' +', " ", input)
    # input = bytes(input, "UTF-8")
    input = bytearray(input, "UTF-8")
    input = input.decode("ascii", "ignore")

    cleanInput = []
    input = input.split(' ')

    for item in input:
        item = item.strip(string.punctuation)
        if len(item) > 1 or (item.lower() == 'a' or item.lower() == 'i'):
            cleanInput.append(item)
    return cleanInput

def ngrams(input, n):
    input = cleanInput(input)
    output = []

    for i in range(len(input)-n+1):
        output.append(input[i:i+n])
    return output

url = 'https://en.wikipedia.org/wiki/Python_(programming_language)'
html = urlopen(url)
bsObj = BeautifulSoup(html, 'lxml')
content = bsObj.find("div", {"id": "mw-content-text"}).get_text()
ngrams = ngrams(content, 2)
keys = range(len(ngrams))
ngramsDic = {}
for i in range(len(keys)):
    ngramsDic[keys[i]] = ngrams[i]
# ngrams = OrderedDict(sorted(ngrams.items(), key=lambda t: t[1], reverse=True))
ngrams = OrderedDict(sorted(ngramsDic.items(), key=lambda t: t[1], reverse=True))

print ngrams
print "2-grams count is: " + str(len(ngrams))
```

<p>I recently learning how to do web scraping by following the book <strong>Web Scraping with Python: Collecting Data from the Modern Web</strong>, while in <strong><em>Chapter 7 Data Normalization</em></strong> section I first write the code as same as the book shows and got an error from the terminal:</p>

```Traceback (most recent call last):
  File "2grams.py", line 40, in <module>
    ngrams = OrderedDict(sorted(ngrams.items(), key=lambda t: t[1], reverse=True))
AttributeError: 'list' object has no attribute 'items'
```

Therefore I've changed the code by creating a new dictionary where the entities are the lists of ngrams. But I've got a quite different result:

Question:

If I wanna have the result as the book shows (where sorted by values and the frequency), should I write my own lines to count the occurrence of each 2-grams, or the code in the book already had that function (codes in the book were python 3 code) ? book sample code on github

The frequency in my output was quite different with the author's, for example [u'Software', u'Foundation'] were occurred 37 times but not 40. What kinds of reasons causing that difference (could it be my code errors)?

Book screenshot:

答:
List doesn't have a item. I just changed list to dict.
Here is my code I changed</p>

```<code>def ngrams(input, n):
    input = cleanInput(input)
    output = dict()
    for i in range(len(input)-n+1):
        new_ng = " ".join(input[i:i+n])
        if new_ng in output:
            output[new_ng] += 1
        else:
            output[new_ng] = 1
    return output
</code>```

Body:
Python version: 2.7.10

My code:

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

from urllib2 import urlopen
from bs4 import BeautifulSoup
from collections import OrderedDict
import re
import string

def cleanInput(input):
    input = re.sub('\n+', " ", input)
    input = re.sub('\[[0-9]*\]', "", input)
    input = re.sub(' +', " ", input)
    # input = bytes(input, "UTF-8")
    input = bytearray(input, "UTF-8")
    input = input.decode("ascii", "ignore")

    cleanInput = []
    input = input.split(' ')

    for item in input:
        item = item.strip(string.punctuation)
        if len(item) > 1 or (item.lower() == 'a' or item.lower() == 'i'):
            cleanInput.append(item)
    return cleanInput

def ngrams(input, n):
    input = cleanInput(input)
    output = []

    for i in range(len(input)-n+1):
        output.append(input[i:i+n])
    return output

url = 'https://en.wikipedia.org/wiki/Python_(programming_language)'
html = urlopen(url)
bsObj = BeautifulSoup(html, 'lxml')
content = bsObj.find("div", {"id": "mw-content-text"}).get_text()
ngrams = ngrams(content, 2)
keys = range(len(ngrams))
ngramsDic = {}
for i in range(len(keys)):
    ngramsDic[keys[i]] = ngrams[i]
# ngrams = OrderedDict(sorted(ngrams.items(), key=lambda t: t[1], reverse=True))
ngrams = OrderedDict(sorted(ngramsDic.items(), key=lambda t: t[1], reverse=True))

print ngrams
print "2-grams count is: " + str(len(ngrams))

I recently learning how to do web scraping by following the book Web Scraping with Python: Collecting Data from the Modern Web, while in Chapter 7 Data Normalization section I first write the code as same as the book shows and got an error from the terminal:

Traceback (most recent call last):
  File "2grams.py", line 40, in <module>
    ngrams = OrderedDict(sorted(ngrams.items(), key=lambda t: t[1], reverse=True))
AttributeError: 'list' object has no attribute 'items'

Therefore I've changed the code by creating a new dictionary where the entities are the lists of ngrams. But I've got a quite different result:

Question:

If I wanna have the result as the book shows (where sorted by values and the frequency), should I write my own lines to count the occurrence of each 2-grams, or the code in the book already had that function (codes in the book were python 3 code) ? book sample code on github

The frequency in my output was quite different with the author's, for example [u'Software', u'Foundation'] were occurred 37 times but not 40. What kinds of reasons causing that difference (could it be my code errors)?

Book screenshot:

Body:
List doesn't have a item. I just changed list to dict.
Here is my code I changed

def ngrams(input, n):
    input = cleanInput(input)
    output = dict()
    for i in range(len(input)-n+1):
        new_ng = " ".join(input[i:i+n])
        if new_ng in output:
            output[new_ng] += 1
        else:
            output[new_ng] = 1
    return output


来源: stackexchange

问:
Navigating to Commonly/Recently Used Dirs, in Terminal (Unix/OS X)
Would it be possible to save certain locations that I've used recently/commonly (like /folder/folder/folder/) so that I don't have to manually navigate through each dir between my current and destination dir?

Sort of like alt-tab, but for paths.  I'm on OS X, but perhaps this can be done using basic Unix skills?

Thanks!

答: In Bash, you can add directories to the CDPATH variable. If you try to cd to a directory that doesn't begin with a slash then the directories listed in CDPATH are searched for a matching destination.

ContentLicense: CC BY-SA 2.5


问:
Are train(method="glm",...) and glm(...) expected to give the same answer?
I'm using datsets called trainSA and testSA which, among others, have columns chd age alcohol obesity tobacco typea ldl.

This command (note that I'm working in R)

```<code>set.seed(13234)
modFit<-train(chd~ age+ alcohol+ obesity +tobacco +typea +ldl, method="glm",family="binomial", data=trainSA)
missClass(testSA$chd, predict(modFit,testSA))
</code>```

returns 0.3116883, while this one

```<code>set.seed(13234)
modFit<-glm(chd~ age+ alcohol+ obesity +tobacco +typea +ldl, family="binomial", data=trainSA)
missClass(testSA$chd, predict(modFit,testSA))
</code>```

returns 0.2943723.

I can run them one after the other (thus keeping every other parameter the same) with the same seed and get slightly different results.

Is this expected, or is there an extra command I need to include in one of them?

NOTE: I chose not to include details about the rest of my code in this question as they don't seem relevant, but I can do if necessary.

答:
Your outputs don't match because the predict function behaves differently for the two different models.  Consider this simple reproducible example.

```<code>library(caret)
set.seed(123)
df <- data.frame(
    y = as.factor(rbinom(100, 1, 0.5)),
    x1 = rnorm(100),
    x2 = rnorm(100)
)
trainSA <- df[1:70,]
testSA <- df[71:100,]

modFit1<-train(y ~ x1 + x2, method="glm",family="binomial", data=trainSA)
head(predict(modFit1, testSA))
[1] 0 1 1 1 0 1
Levels: 0 1

modFit2<-glm(y ~ x1 + x2, family="binomial", data=trainSA)
head(predict(modFit2, testSA))
         71          72          73          74          75          76
-0.06855758  0.35434220  0.09654412  0.01410099 -0.91703771  0.25432903
</code>```

You'll need to specify change how you are using the predict functions across the two models for them to give the same results.  Here is one way to do it.

```<code>as.integer(predict(modFit1,testSA))-1 == as.integer(predict(modFit2, testSA, type = 'response') >= 0.5)

 [1] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
 [18] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
</code>```

I can't give you a full answer because you have not provided any details about your data or the missClass function, perhaps consider changing how you call predict the second go around.

```<code>predict(modFit,testSA, type = 'response') >= 0.5
</code>```

The code above will give you the binary class prediction that you may be looking for, but again it depends on your data and what your function is actually doing.

ContentLicense: CC BY-SA 3.0

Body:
I'm using datsets called trainSA and testSA which, among others, have columns chd age alcohol obesity tobacco typea ldl.

This command (note that I'm working in R)

set.seed(13234)
modFit<-train(chd~ age+ alcohol+ obesity +tobacco +typea +ldl, method="glm",family="binomial", data=trainSA)
missClass(testSA$chd, predict(modFit,testSA))

returns 0.3116883, while this one

set.seed(13234)
modFit<-glm(chd~ age+ alcohol+ obesity +tobacco +typea +ldl, family="binomial", data=trainSA)
missClass(testSA$chd, predict(modFit,testSA))

returns 0.2943723.

I can run them one after the other (thus keeping every other parameter the same) with the same seed and get slightly different results.

Is this expected, or is there an extra command I need to include in one of them?

NOTE: I chose not to include details about the rest of my code in this question as they don't seem relevant, but I can do if necessary.

Body:
Your outputs don't match because the predict function behaves differently for the two different models.  Consider this simple reproducible example.

library(caret)
set.seed(123)
df <- data.frame(
    y = as.factor(rbinom(100, 1, 0.5)),
    x1 = rnorm(100),
    x2 = rnorm(100)
)
trainSA <- df[1:70,]
testSA <- df[71:100,]

modFit1<-train(y ~ x1 + x2, method="glm",family="binomial", data=trainSA)
head(predict(modFit1, testSA))
[1] 0 1 1 1 0 1
Levels: 0 1

modFit2<-glm(y ~ x1 + x2, family="binomial", data=trainSA)
head(predict(modFit2, testSA))
         71          72          73          74          75          76
-0.06855758  0.35434220  0.09654412  0.01410099 -0.91703771  0.25432903

You'll need to specify change how you are using the predict functions across the two models for them to give the same results.  Here is one way to do it.

as.integer(predict(modFit1,testSA))-1 == as.integer(predict(modFit2, testSA, type = 'response') >= 0.5)

 [1] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
 [18] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE

I can't give you a full answer because you have not provided any details about your data or the missClass function, perhaps consider changing how you call predict the second go around.

predict(modFit,testSA, type = 'response') >= 0.5

The code above will give you the binary class prediction that you may be looking for, but again it depends on your data and what your function is actually doing.


问:
Why doesn't app.component.html render?
I have the following Angular plnkr.co: https://plnkr.co/edit/xA8jU4QYDGxzohNg5NFj?p=preview.

//app.component.ts

```<code>import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html'
})
export class AppComponent { name = 'Angular'; }
</code>```

//app.component.html

```<code>testing...
<router-outlet></router-outlet>
</code>```

The oputput in the browser is:

```<code>Loading AppComponent content here ...
</code>```

Why doesn't it see the app.component.html file? Or is this some other issue?

答:
Try like this :

add below line your app.module.ts

```<code>import { NgModule, CUSTOM_ELEMENTS_SCHEMA  } from '@angular/core';

@NgModule({
  schemas: [CUSTOM_ELEMENTS_SCHEMA]
})
</code>```

plnkr demo

Title: Why doesn't app.component.html render?

Body:
I have the following Angular plnkr.co: https://plnkr.co/edit/xA8jU4QYDGxzohNg5NFj?p=preview.

//app.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html'
})
export class AppComponent { name = 'Angular'; }

//app.component.html

testing...
<router-outlet></router-outlet>

The oputput in the browser is:

Loading AppComponent content here ...

Why doesn't it see the app.component.html file? Or is this some other issue?

Body:
Try like this :

add below line your app.module.ts

import { NgModule, CUSTOM_ELEMENTS_SCHEMA  } from '@angular/core';

@NgModule({
  schemas: [CUSTOM_ELEMENTS_SCHEMA]
})

plnkr demo


问:
How are Minecraft plugins updated?
Im browsing Bukkit plugins here: https://dev.bukkit.org/

and a lot of the plugins are abandoned and are outdated.

These plugins dont work without the current version of Minecraft released.

So how are these plugins actually updated to use the latest version of Minecraft?

I went to YouTube for some tutorials but ALL of them are severely outdated and are vague at best on how its done.

Any help would be appreciated.

Thanks again!

答:
Roughly speaking, a plugin is built using a library, that's the same used in the server.

Usually, plugin developers use Bukkit API or a similar one, such as Spigot API to build their plugins.

When the Bukkit Platform gets updated, so does the Library on which plugins are built. Whenever that happens, plugin Developers must rebuild/recompile their plugins for the new version.

When the plugins aren't updated for the new version, they break. Bukkit doesn't always keep version compatibility, and in those case, older versions won't work.

To update the plugins, a developer must import the new library on their source code, and fix any methods that might have changed. He or she should then recompile the plugin and export the jar to be run in a Bukkit Server.

Title: How are Minecraft plugins updated?


问:
Item is not deleting from the RecyclerView list
I have a code where I want to delete item from the list as well as database. I am using RecyclerView and each item has 3 buttons and one of them is delete button. If I click on button then response will come as success and I need item will deleted from there.

Below is my code where item is deleted from the database but not deleted on List.

```<code>public class CardAdapter  extends RecyclerView.Adapter<CardAdapter.ViewHolder> {
private static final String deleteURL = "http://192.168.2.110/xp/ajax_call.php?action=remove_shortlisted";
private static final String url1 = "http://192.168.2.110/xp/express_intrest.php";
private static final String KEY_MATRI_ID_TO="matriID_to";
private static final String KEY_MATRI_ID_BY="matriID_by";

SessionManager session;
public String matri_id_to, matri_id_by, str_gender;
String str_status,str_EI;

//Imageloader to load image
private ImageLoader imageLoader;
private Context context;

//List to store all superheroes
List<SuperHero> superHeroes;

//Constructor of this class
public CardAdapter(List<SuperHero> superHeroes, Context context){
    super();
    //Getting all superheroes
    this.superHeroes = superHeroes;
    this.context = context;
}

@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View v = LayoutInflater.from(parent.getContext())
            .inflate(R.layout.superheroes_list_shortlist, parent, false);
    // Session class instance
    session = new SessionManager(context);
    session.checkLogin();
    // get user data from session
    HashMap<String, String> user = session.getUserDetails();
    matri_id_by = user.get(SessionManager.KEY_EMAIL);
    str_gender = user.get(SessionManager.KEY_GENDER);

    ViewHolder viewHolder = new ViewHolder(v);
    return viewHolder;
}

@Override
public void onBindViewHolder(final ViewHolder holder, final int position) {

    //Getting the particular item from the list
   final SuperHero superHero = superHeroes.get(position);

    //Loading image from url
    imageLoader = CustomVolleyRequest.getInstance(context).getImageLoader();
    imageLoader.get(superHero.getImageUrl(), ImageLoader.getImageListener(holder.imageView, R.drawable.image, android.R.drawable.ic_dialog_alert));

    holder.imageView.setImageUrl(superHero.getImageUrl(), imageLoader);
    holder.textViewId.setText(superHero.getMglId());
    holder.AgeHeight.setText(superHero.getHeight()+" / "+superHero.getAge());
    holder.Community.setText(superHero.getCommunity()+" / "+superHero.getCaste());
    holder.Occupation.setText(superHero.getOccupation());
    holder.Income.setText(superHero.getIncome());
    holder.ShortlistedOn.setText(superHero.getShortlistOn());
    str_status = superHero.getStatus();
    Log.e("str_shortlist_____",str_status);

    str_EI = superHero.getExpress_Intrest();
    Log.e("str_EI_____",str_EI);
    if(str_EI.toString().equalsIgnoreCase("Accepted")) {
        holder.btnEI.setText(str_EI);
        holder.btnEI.setBackgroundColor(Color.parseColor("#FF045B49"));
        holder.btnEI.setEnabled(false);
    }
    else if(str_EI.toString().equalsIgnoreCase("Reject")){
        holder.btnEI.setText(str_EI);
        holder.btnEI.setBackgroundColor(Color.parseColor("#FF045B49"));
        holder.btnEI.setEnabled(false);
    }
    else if(str_EI.toString().equalsIgnoreCase("Declined")){
        holder.btnEI.setText(str_EI);
        holder.btnEI.setBackgroundColor(Color.parseColor("#FF045B49"));
        holder.btnEI.setEnabled(false);
    }
    else if(str_EI.toString().equalsIgnoreCase("Pending..")){
        holder.btnEI.setText(str_EI);
        holder.btnEI.setBackgroundColor(Color.parseColor("#FF045B49"));
        holder.btnEI.setEnabled(false);
    }
    else
    {
        holder.btnEI.setText(str_EI);
    }

    holder.btnRemove.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            matri_id_to = superHero.getMglId();
            holder.delete(position);
        }
    });

    holder.btnViewProfile.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent n = new Intent(holder.itemView.getContext(),BlankActivity.class);
            String str_id = holder.textViewId.getText().toString();
            n.putExtra("ID",str_id);
            holder.itemView.getContext().startActivity(n);
        }
    });

    holder.btnEI.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            superHero.setExpress_Intrest("Wait...");
            holder.btnEI.setText(superHero.getExpress_Intrest());
            matri_id_to = superHero.getMglId();
            holder.expressInterest(position);
        }
    });

}

public SuperHero getItem(int position){
    return superHeroes.get(position);
}

@Override
public int getItemCount() {return superHeroes.size();}

class ViewHolder extends RecyclerView.ViewHolder{
    public NetworkImageView imageView;
    public TextView textViewId;
    public TextView AgeHeight;
    public TextView Community;
    public TextView Occupation;
    public TextView Income;
    public TextView ShortlistedOn;
    public Button btnRemove;
    public Button btnViewProfile;
    public Button btnEI;

    //Initializing Views
    public ViewHolder(final View itemView) {
        super(itemView);
        imageView = (NetworkImageView) itemView.findViewById(R.id.imageViewHero);
        textViewId = (TextView) itemView.findViewById(R.id.textViewId);
        AgeHeight = (TextView) itemView.findViewById(R.id.AgeHeight);
        Community = (TextView) itemView.findViewById(R.id.Community);
        Occupation = (TextView) itemView.findViewById(R.id.Occupation);
        Income = (TextView) itemView.findViewById(R.id.Income);
        ShortlistedOn = (TextView) itemView.findViewById(R.id.shortlistOn);
        btnRemove = (Button) itemView.findViewById(R.id.btnRemove);
        btnViewProfile = (Button) itemView.findViewById(R.id.buttonViewProfile);
        btnEI = (Button) itemView.findViewById(R.id.btnExpressIntrest);
    }

    public void expressInterest(final int position) {
        StringRequest stringRequest1 = new StringRequest(Request.Method.POST, url1, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                if(response.trim().equalsIgnoreCase("success")) {
                    superHeroes.get(position).setExpress_Intrest("Pending..");
                    notifyDataSetChanged();
                }
            }
        },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Toast.makeText(context, error.toString(), Toast.LENGTH_LONG).show();
                    }
                }) {
            @Override
            protected Map<String, String> getParams() {
                Map<String, String> params = new HashMap<String, String>();
                params.put(KEY_MATRI_ID_BY,matri_id_by);
                params.put(KEY_MATRI_ID_TO,matri_id_to);
                return params;
            }
        };
        RequestQueue requestQueue = Volley.newRequestQueue(context);
        requestQueue.add(stringRequest1);
    }

    public void delete(final int position) {
        StringRequest stringRequest1 = new StringRequest(Request.Method.POST, deleteURL, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                if (response.trim().equalsIgnoreCase("success")) {
                    superHeroes.get(position);
                    notifyDataSetChanged();
                }
            }
        },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Toast.makeText(context, error.toString(), Toast.LENGTH_LONG).show();
                    }
                }) {
            @Override
            protected Map<String, String> getParams() {
                Map<String, String> params = new HashMap<String, String>();
                params.put(KEY_MATRI_ID_BY,matri_id_by);
                params.put(KEY_MATRI_ID_TO,matri_id_to);
                return params;
            }
        };
        RequestQueue requestQueue = Volley.newRequestQueue(context);
        requestQueue.add(stringRequest1);
      }
    }
   }
</code>```

答:
put this code on onResponse-</p>

```<code>superHeros.remove(position);
notifydatasetchanged();
</code>```

Body:
I have a code where I want to delete item from the list as well as database. I am using RecyclerView and each item has 3 buttons and one of them is delete button. If I click on button then response will come as success and I need item will deleted from there.

Below is my code where item is deleted from the database but not deleted on List.

public class CardAdapter  extends RecyclerView.Adapter<CardAdapter.ViewHolder> {
private static final String deleteURL = "http://192.168.2.110/xp/ajax_call.php?action=remove_shortlisted";
private static final String url1 = "http://192.168.2.110/xp/express_intrest.php";
private static final String KEY_MATRI_ID_TO="matriID_to";
private static final String KEY_MATRI_ID_BY="matriID_by";

SessionManager session;
public String matri_id_to, matri_id_by, str_gender;
String str_status,str_EI;

//Imageloader to load image
private ImageLoader imageLoader;
private Context context;

//List to store all superheroes
List<SuperHero> superHeroes;

//Constructor of this class
public CardAdapter(List<SuperHero> superHeroes, Context context){
    super();
    //Getting all superheroes
    this.superHeroes = superHeroes;
    this.context = context;
}

@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View v = LayoutInflater.from(parent.getContext())
            .inflate(R.layout.superheroes_list_shortlist, parent, false);
    // Session class instance
    session = new SessionManager(context);
    session.checkLogin();
    // get user data from session
    HashMap<String, String> user = session.getUserDetails();
    matri_id_by = user.get(SessionManager.KEY_EMAIL);
    str_gender = user.get(SessionManager.KEY_GENDER);

    ViewHolder viewHolder = new ViewHolder(v);
    return viewHolder;
}

@Override
public void onBindViewHolder(final ViewHolder holder, final int position) {

    //Getting the particular item from the list
   final SuperHero superHero = superHeroes.get(position);

    //Loading image from url
    imageLoader = CustomVolleyRequest.getInstance(context).getImageLoader();
    imageLoader.get(superHero.getImageUrl(), ImageLoader.getImageListener(holder.imageView, R.drawable.image, android.R.drawable.ic_dialog_alert));

    holder.imageView.setImageUrl(superHero.getImageUrl(), imageLoader);
    holder.textViewId.setText(superHero.getMglId());
    holder.AgeHeight.setText(superHero.getHeight()+" / "+superHero.getAge());
    holder.Community.setText(superHero.getCommunity()+" / "+superHero.getCaste());
    holder.Occupation.setText(superHero.getOccupation());
    holder.Income.setText(superHero.getIncome());
    holder.ShortlistedOn.setText(superHero.getShortlistOn());
    str_status = superHero.getStatus();
    Log.e("str_shortlist_____",str_status);

    str_EI = superHero.getExpress_Intrest();
    Log.e("str_EI_____",str_EI);
    if(str_EI.toString().equalsIgnoreCase("Accepted")) {
        holder.btnEI.setText(str_EI);
        holder.btnEI.setBackgroundColor(Color.parseColor("#FF045B49"));
        holder.btnEI.setEnabled(false);
    }
    else if(str_EI.toString().equalsIgnoreCase("Reject")){
        holder.btnEI.setText(str_EI);
        holder.btnEI.setBackgroundColor(Color.parseColor("#FF045B49"));
        holder.btnEI.setEnabled(false);
    }
    else if(str_EI.toString().equalsIgnoreCase("Declined")){
        holder.btnEI.setText(str_EI);
        holder.btnEI.setBackgroundColor(Color.parseColor("#FF045B49"));
        holder.btnEI.setEnabled(false);
    }
    else if(str_EI.toString().equalsIgnoreCase("Pending..")){
        holder.btnEI.setText(str_EI);
        holder.btnEI.setBackgroundColor(Color.parseColor("#FF045B49"));
        holder.btnEI.setEnabled(false);
    }
    else
    {
        holder.btnEI.setText(str_EI);
    }

    holder.btnRemove.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            matri_id_to = superHero.getMglId();
            holder.delete(position);
        }
    });

    holder.btnViewProfile.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent n = new Intent(holder.itemView.getContext(),BlankActivity.class);
            String str_id = holder.textViewId.getText().toString();
            n.putExtra("ID",str_id);
            holder.itemView.getContext().startActivity(n);
        }
    });

    holder.btnEI.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            superHero.setExpress_Intrest("Wait...");
            holder.btnEI.setText(superHero.getExpress_Intrest());
            matri_id_to = superHero.getMglId();
            holder.expressInterest(position);
        }
    });

}

public SuperHero getItem(int position){
    return superHeroes.get(position);
}

@Override
public int getItemCount() {return superHeroes.size();}

class ViewHolder extends RecyclerView.ViewHolder{
    public NetworkImageView imageView;
    public TextView textViewId;
    public TextView AgeHeight;
    public TextView Community;
    public TextView Occupation;
    public TextView Income;
    public TextView ShortlistedOn;
    public Button btnRemove;
    public Button btnViewProfile;
    public Button btnEI;

    //Initializing Views
    public ViewHolder(final View itemView) {
        super(itemView);
        imageView = (NetworkImageView) itemView.findViewById(R.id.imageViewHero);
        textViewId = (TextView) itemView.findViewById(R.id.textViewId);
        AgeHeight = (TextView) itemView.findViewById(R.id.AgeHeight);
        Community = (TextView) itemView.findViewById(R.id.Community);
        Occupation = (TextView) itemView.findViewById(R.id.Occupation);
        Income = (TextView) itemView.findViewById(R.id.Income);
        ShortlistedOn = (TextView) itemView.findViewById(R.id.shortlistOn);
        btnRemove = (Button) itemView.findViewById(R.id.btnRemove);
        btnViewProfile = (Button) itemView.findViewById(R.id.buttonViewProfile);
        btnEI = (Button) itemView.findViewById(R.id.btnExpressIntrest);
    }

    public void expressInterest(final int position) {
        StringRequest stringRequest1 = new StringRequest(Request.Method.POST, url1, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                if(response.trim().equalsIgnoreCase("success")) {
                    superHeroes.get(position).setExpress_Intrest("Pending..");
                    notifyDataSetChanged();
                }
            }
        },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Toast.makeText(context, error.toString(), Toast.LENGTH_LONG).show();
                    }
                }) {
            @Override
            protected Map<String, String> getParams() {
                Map<String, String> params = new HashMap<String, String>();
                params.put(KEY_MATRI_ID_BY,matri_id_by);
                params.put(KEY_MATRI_ID_TO,matri_id_to);
                return params;
            }
        };
        RequestQueue requestQueue = Volley.newRequestQueue(context);
        requestQueue.add(stringRequest1);
    }

    public void delete(final int position) {
        StringRequest stringRequest1 = new StringRequest(Request.Method.POST, deleteURL, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                if (response.trim().equalsIgnoreCase("success")) {
                    superHeroes.get(position);
                    notifyDataSetChanged();
                }
            }
        },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Toast.makeText(context, error.toString(), Toast.LENGTH_LONG).show();
                    }
                }) {
            @Override
            protected Map<String, String> getParams() {
                Map<String, String> params = new HashMap<String, String>();
                params.put(KEY_MATRI_ID_BY,matri_id_by);
                params.put(KEY_MATRI_ID_TO,matri_id_to);
                return params;
            }
        };
        RequestQueue requestQueue = Volley.newRequestQueue(context);
        requestQueue.add(stringRequest1);
      }
    }
   }

Body:
put this code on onResponse-

superHeros.remove(position);
notifydatasetchanged();


问:
Python Pandas: merge, join, concat
I have a dataframe that has a non-unique GEO_ID, and an attribute (FTYPE) in a separate column (1 of 6 values) for each GEO_ID and an associated length for each FTYPE.

```<code>df

    FID GEO_ID  FTYPE   Length_km

0   1400000US06001400100    428 3.291467766

1   1400000US06001400100    460 7.566487367

2   1400000US06001401700    460 0.262190266

3   1400000US06001401700    566 10.49899202

4   1400000US06001403300    428 0.138171389

5   1400000US06001403300    558 0.532913513
</code>```

How do I make 6 new columns for FTYPE (with 1 and 0 to indicate if that row has the FTYPE) and 6 new columns for FTYPE_Length to make each row have a unique GEO_ID?

I want my new dataframe to have a structure like this (with 6 FTYPE-s):

```<code>FID GEO_ID  FTYPE_428   FTYPE_428_length    FTYPE_460   FTYPE_460_length
0   1400000US06001400100    1   3.291467766 1   7.566487367
</code>```

So far, what I have tried is doing something like this:

```<code>import pandas as pd
fname = "filename.csv"
df = pd.read_csv(fname)
nhd = [334, 336, 420, 428, 460, 558, 556]
df1 = df.loc[df['FTYPE']==nhd[0]]
df2 = df.loc[df['FTYPE']==nhd[1]]
df3 = df.loc[df['FTYPE']==nhd[2]]
df4 = df.loc[df['FTYPE']==nhd[3]]
df5 = df.loc[df['FTYPE']==nhd[4]]
df6 = df.loc[df['FTYPE']==nhd[5]]
df7 = df.loc[df['FTYPE']==nhd[6]]
df12 = df1.merge(df2, how='left', left_on='GEO_ID', right_on='GEO_ID')
df23 = df12.merge(df3,how='left', left_on='GEO_ID', right_on='GEO_ID')
df34 = df23.merge(df4,how='left', left_on='GEO_ID', right_on='GEO_ID')
df45 = df34.merge(df5,how='left', left_on='GEO_ID', right_on='GEO_ID')
df56 = df45.merge(df6,how='left', left_on='GEO_ID', right_on='GEO_ID')
df67 = df56.merge(df7,how='left', left_on='GEO_ID', right_on='GEO_ID')
cols = [0,4,7,10,13,16,19]
df67.drop(df67.columns[cols],axis=1,inplace=True)
df67.columns =['GEO_ID','334','len_334','336','len_336','420','len_420','428','len_428','460','len_460','558','len_558','566','len_566']
</code>```

But this approach is problematic because it reduces the rows to the ones that have the first two FTYPE-s. Is there a way to merge with multiple columns at once?

Its probably easier to write a for loop and go over each row and use a condition to fill in the values like this:

```<code>nhd = [334, 336, 420, 428, 460, 558, 556]
for x in nhd:
    df[str(x)] = None
    df["length_"+str(x)] = None
df.head()
for geoid in df["GEO_ID"]:
    #print geoid
    for x in nhd:
        df.ix[(df['FTYPE']==x) & (df['GEO_ID'] == geoid)][str(nhd)] = 1
</code>```

But this takes too much time and there is probably a one liner in Pandas to do the same thing.

Any help on this is appreciated!

Thanks,
Solomon

答:
I don't quite see the point of your _length columns: they seem to have the same information as just whether or not the matching value is null or not, which makes them redundant.  They're easy enough to create, though.

While we could cram this into one line if we insisted, what's the point?  This is SO, not codegolf.  So I might do something like:

```<code>df = df.pivot(index="GEO_ID", columns="FTYPE", values="Length_km")
df.columns = "FTYPE_" + df.columns.astype(str)

has_value = df.notnull().astype(int)
has_value.columns += '_length'

final = pd.concat([df, has_value], axis=1).sort_index(axis='columns')
</code>```

which gives me (using your input data, which only has 5 distinct FTYPEs):

```<code>In [49]: final
Out[49]:
                      FTYPE_334  FTYPE_334_length  FTYPE_428  \
GEO_ID
1400000US06001400100        NaN                 0   3.291468
1400000US06001401700        NaN                 0        NaN
1400000US06001403300        NaN                 0   0.138171
1400000US06001403400    0.04308                 1        NaN

                      FTYPE_428_length  FTYPE_460  FTYPE_460_length  \
GEO_ID
1400000US06001400100                 1   7.566487                 1
1400000US06001401700                 0   0.262190                 1
1400000US06001403300                 1        NaN                 0
1400000US06001403400                 0        NaN                 0

                      FTYPE_558  FTYPE_558_length  FTYPE_566  FTYPE_566_length
GEO_ID
1400000US06001400100        NaN                 0        NaN                 0
1400000US06001401700        NaN                 0  10.498992                 1
1400000US06001403300   0.532914                 1   1.518864                 1
1400000US06001403400        NaN                 0        NaN                 0
</code>```

Title: Python Pandas: merge, join, concat

Body:
I have a dataframe that has a non-unique GEO_ID, and an attribute (FTYPE) in a separate column (1 of 6 values) for each GEO_ID and an associated length for each FTYPE.

df

    FID GEO_ID  FTYPE   Length_km

0   1400000US06001400100    428 3.291467766

1   1400000US06001400100    460 7.566487367

2   1400000US06001401700    460 0.262190266

3   1400000US06001401700    566 10.49899202

4   1400000US06001403300    428 0.138171389

5   1400000US06001403300    558 0.532913513

How do I make 6 new columns for FTYPE (with 1 and 0 to indicate if that row has the FTYPE) and 6 new columns for FTYPE_Length to make each row have a unique GEO_ID?

I want my new dataframe to have a structure like this (with 6 FTYPE-s):

FID GEO_ID  FTYPE_428   FTYPE_428_length    FTYPE_460   FTYPE_460_length
0   1400000US06001400100    1   3.291467766 1   7.566487367

So far, what I have tried is doing something like this:

import pandas as pd
fname = "filename.csv"
df = pd.read_csv(fname)
nhd = [334, 336, 420, 428, 460, 558, 556]
df1 = df.loc[df['FTYPE']==nhd[0]]
df2 = df.loc[df['FTYPE']==nhd[1]]
df3 = df.loc[df['FTYPE']==nhd[2]]
df4 = df.loc[df['FTYPE']==nhd[3]]
df5 = df.loc[df['FTYPE']==nhd[4]]
df6 = df.loc[df['FTYPE']==nhd[5]]
df7 = df.loc[df['FTYPE']==nhd[6]]
df12 = df1.merge(df2, how='left', left_on='GEO_ID', right_on='GEO_ID')
df23 = df12.merge(df3,how='left', left_on='GEO_ID', right_on='GEO_ID')
df34 = df23.merge(df4,how='left', left_on='GEO_ID', right_on='GEO_ID')
df45 = df34.merge(df5,how='left', left_on='GEO_ID', right_on='GEO_ID')
df56 = df45.merge(df6,how='left', left_on='GEO_ID', right_on='GEO_ID')
df67 = df56.merge(df7,how='left', left_on='GEO_ID', right_on='GEO_ID')
cols = [0,4,7,10,13,16,19]
df67.drop(df67.columns[cols],axis=1,inplace=True)
df67.columns =['GEO_ID','334','len_334','336','len_336','420','len_420','428','len_428','460','len_460','558','len_558','566','len_566']

But this approach is problematic because it reduces the rows to the ones that have the first two FTYPE-s. Is there a way to merge with multiple columns at once?

Its probably easier to write a for loop and go over each row and use a condition to fill in the values like this:

nhd = [334, 336, 420, 428, 460, 558, 556]
for x in nhd:
    df[str(x)] = None
    df["length_"+str(x)] = None
df.head()
for geoid in df["GEO_ID"]:
    #print geoid
    for x in nhd:
        df.ix[(df['FTYPE']==x) & (df['GEO_ID'] == geoid)][str(nhd)] = 1

But this takes too much time and there is probably a one liner in Pandas to do the same thing.

Any help on this is appreciated!

Thanks,
Solomon

Body:
I don't quite see the point of your _length columns: they seem to have the same information as just whether or not the matching value is null or not, which makes them redundant.  They're easy enough to create, though.

While we could cram this into one line if we insisted, what's the point?  This is SO, not codegolf.  So I might do something like:

df = df.pivot(index="GEO_ID", columns="FTYPE", values="Length_km")
df.columns = "FTYPE_" + df.columns.astype(str)

has_value = df.notnull().astype(int)
has_value.columns += '_length'

final = pd.concat([df, has_value], axis=1).sort_index(axis='columns')

which gives me (using your input data, which only has 5 distinct FTYPEs):

In [49]: final
Out[49]:
                      FTYPE_334  FTYPE_334_length  FTYPE_428  \
GEO_ID
1400000US06001400100        NaN                 0   3.291468
1400000US06001401700        NaN                 0        NaN
1400000US06001403300        NaN                 0   0.138171
1400000US06001403400    0.04308                 1        NaN

                      FTYPE_428_length  FTYPE_460  FTYPE_460_length  \
GEO_ID
1400000US06001400100                 1   7.566487                 1
1400000US06001401700                 0   0.262190                 1
1400000US06001403300                 1        NaN                 0
1400000US06001403400                 0        NaN                 0

                      FTYPE_558  FTYPE_558_length  FTYPE_566  FTYPE_566_length
GEO_ID
1400000US06001400100        NaN                 0        NaN                 0
1400000US06001401700        NaN                 0  10.498992                 1
1400000US06001403300   0.532914                 1   1.518864                 1
1400000US06001403400        NaN                 0        NaN                 0


问:
Looking for alternative to this "fly by in" wordpress plugin
Im looking for a jQuery alternative to this plugin:

"upPrev: NYTimes Style "Next Post" Animated Button"
http://wordpress.org/extend/plugins/upprev-nytimes-style-next-post-jquery-animated-fly-in-button/

Does anyone know if there is a non wordpress version of this? That will work with non worpress sites.

Thanks!

答:
You can fiddle with a working demo of the following code here.

This type of animation is just what jQuery is built to do easily, so I don't think you need a plugin to accomplish this.  Let's say you have a long HTML page with the following div that you want to slide out:

```<code><div id="botSlide">Hey, look at me!</div>
</code>```

You would style this div to be in a fixed position near the bottom of the page and just off screen to the right, like so:

```<code>#botSlide {
    padding:20px;
    width:200px;
    position:fixed; bottom:20px; right:-240px;
}
</code>```

The key is to bind the window's scroll event to fire when the scroll bar is past a certain threshold.  Here's one way to accomplish that:

```<code>$(window).bind('scroll', function(e) {
    var buffer = 500,
        bsPadding = 40,
        slideIn = ($(this).scrollTop() >
                  ($('body').height() - $(window).height() - buffer)),
        $bs = $('#botSlide');

    if (slideIn) {
        $bs.not(':animated')
           .stop(true, false)
           .animate({
               'right': 0
           }, 300);
    } else {
        $bs.not(':animated')
           .stop(true, false)
           .animate({
               'right': -$bs.width() - bsPadding
           }, 300);
    }
});
</code>```

The .not(':animated') and .stop(true,false) are to prevent quirks in the animation when scrolling fast.

Body:
You can fiddle with a working demo of the following code here.

This type of animation is just what jQuery is built to do easily, so I don't think you need a plugin to accomplish this.  Let's say you have a long HTML page with the following div that you want to slide out:

<div id="botSlide">Hey, look at me!</div>

You would style this div to be in a fixed position near the bottom of the page and just off screen to the right, like so:

#botSlide {
    padding:20px;
    width:200px;
    position:fixed; bottom:20px; right:-240px;
}

The key is to bind the window's scroll event to fire when the scroll bar is past a certain threshold.  Here's one way to accomplish that:

$(window).bind('scroll', function(e) {
    var buffer = 500,
        bsPadding = 40,
        slideIn = ($(this).scrollTop() >
                  ($('body').height() - $(window).height() - buffer)),
        $bs = $('#botSlide');

    if (slideIn) {
        $bs.not(':animated')
           .stop(true, false)
           .animate({
               'right': 0
           }, 300);
    } else {
        $bs.not(':animated')
           .stop(true, false)
           .animate({
               'right': -$bs.width() - bsPadding
           }, 300);
    }
});

The .not(':animated') and .stop(true,false) are to prevent quirks in the animation when scrolling fast.


问:
How to write a regular expression for to capture letters, numbers, special characters and international characters
I'm trying to write a regular expression that captures uppercase, lowercase letters and numbers, special characters and finally international characters. By international characters I mean things like: ¿ â ê î ô û Â Ê Î Ô Û.

I'm 90% done, this is my expression, it covers, uppercase, lowercase, letters,numbers and special characters, Im struggling with incorporating the regex for international characters to my current regular expression, please see below my expression:

Uppercase, lowercase, letters, numbers and special characters:

```<code>^[|a-zA-Z0-9 ¬`!"£$%^&*()_+={[}:;@'~#<,>.?/|]{0,3}$
</code>```

Regex for international characters:

```<code>[^\p{L}0-9]{0,3}$
</code>```

I want to ensure that the length of the international character is limited to a length of 3.

Please help!

Body:
I'm trying to write a regular expression that captures uppercase, lowercase letters and numbers, special characters and finally international characters. By international characters I mean things like: ¿ â ê î ô û Â Ê Î Ô Û.

I'm 90% done, this is my expression, it covers, uppercase, lowercase, letters,numbers and special characters, Im struggling with incorporating the regex for international characters to my current regular expression, please see below my expression:

Uppercase, lowercase, letters, numbers and special characters:

^[|a-zA-Z0-9 ¬`!"£$%^&*()_+={[}:;@'~#<,>.?/|]{0,3}$

Regex for international characters:

[^\p{L}0-9]{0,3}$

I want to ensure that the length of the international character is limited to a length of 3.

Please help!

Body:
Try this regex:

^([|a-zA-Z0-9 ¬`!"£$%^&*()_+={[}:;@'~#<,>.?/|]|[^\p{L}0-9]){0,3}$


答:
Try this .

```<code>if(superHeroes.size > 0){
    superHeroes.remove(position);
    notifyDataSetChanged();
}

//Delete data from database
DBConstant.dbHelper.deleterow(DBConstant.sqliteDatabase, position);
</code>```

Hope it helps .

Title: Item is not deleting from the RecyclerView list

Body:
Try this .

if(superHeroes.size > 0){
    superHeroes.remove(position);
    notifyDataSetChanged();
}

//Delete data from database
DBConstant.dbHelper.deleterow(DBConstant.sqliteDatabase, position);

Hope it helps .


问:
Python xlwings copy-paste formula with relative cell references
I have a formula in cell A1 that is "=C1+$D$1". I would like to use xlwings to copy paste this formula into A3 (keeping the relative cell reference). I would expect the pasted formula in cell A3 to be "=C3+$D$1" instead of "=C1+$D$1".

Is there was a flag or function that would adjust the formula based on the range we're pasting to? If not, I guess the best solution would be to process the formula itself before pasting?

```<code>rng_to_paste = ws.range('A1').options(ndim=1).formula
ws.range('A3').options(ndim=1).formula = rng_to_paste
</code>```

答:
You can assign the formula property of a range which will update the implicitly assigned cells in the range with the adjusted formula(s). However, with this method xlwings doesn't know where you copied the formula from, so it can only increment row/column relative to the assigned formula.</p>

```<code>xw.sheets[0].range('A1:A5').value = [[i] for i in range(5)]
xw.sheets[0].range('B1:C5').formula = [['=A1+1','=B1*10']]

xw.sheets[0].range('A1:C5').value
Out[3]:
[[0.0, 1.0, 10.0],
 [1.0, 2.0, 20.0],
 [2.0, 3.0, 30.0],
 [3.0, 4.0, 40.0],
 [4.0, 5.0, 50.0]]
</code>```

Body:
I have a formula in cell A1 that is "=C1+$D$1". I would like to use xlwings to copy paste this formula into A3 (keeping the relative cell reference). I would expect the pasted formula in cell A3 to be "=C3+$D$1" instead of "=C1+$D$1".

Is there was a flag or function that would adjust the formula based on the range we're pasting to? If not, I guess the best solution would be to process the formula itself before pasting?

rng_to_paste = ws.range('A1').options(ndim=1).formula
ws.range('A3').options(ndim=1).formula = rng_to_paste

Body:
You can assign the formula property of a range which will update the implicitly assigned cells in the range with the adjusted formula(s). However, with this method xlwings doesn't know where you copied the formula from, so it can only increment row/column relative to the assigned formula.

xw.sheets[0].range('A1:A5').value = [[i] for i in range(5)]
xw.sheets[0].range('B1:C5').formula = [['=A1+1','=B1*10']]

xw.sheets[0].range('A1:C5').value
Out[3]:
[[0.0, 1.0, 10.0],
 [1.0, 2.0, 20.0],
 [2.0, 3.0, 30.0],
 [3.0, 4.0, 40.0],
 [4.0, 5.0, 50.0]]


问:
Data structure converting order sorting from list to set
basically, my defines this

```<code>nodes = ['Unix', 'BSD', 'Linux']
</code>```

and when I try this

```<code>print(set(nodes))
</code>```

I expect the result of it

```<code>{'Unix', 'BSD', 'Linux'}
</code>```

but I got this

```<code>{'BSD', 'Linux', 'Unix'}
</code>```

I don't want to break order of nodes is there good way for it?

答:
You have two options :

first option:

use ordered dict:

As suggested by @user1767754 :

```<code>from collections import OrderedDict

nodes = ['Unix', 'BSD', 'Linux']
uniques = OrderedDict((x, True) for x in nodes).keys()
</code>```

Second method keep track of index and values:

so first create a dict with index,values :

```<code>nodes = ['Unix', 'BSD', 'Linux']

order={}
for i,j in enumerate(nodes):
    order[i]=j

print(order)
</code>```

it will give:

```<code>{0: 'Unix', 1: 'BSD', 2: 'Linux'}
</code>```

Now do your stuff like converting list to set or whatever you want and at last convert again to list something like this:

```<code>new=[]
for i in set(nodes):
    for k,j in order.items():
        if i==j:
            new.insert(k,j)

print(new)
</code>```

Now it will give:

```<code>['Unix', 'BSD', 'Linux']
</code>```

Body:
basically, my defines this

nodes = ['Unix', 'BSD', 'Linux']

and when I try this

print(set(nodes))

I expect the result of it

{'Unix', 'BSD', 'Linux'}

but I got this

{'BSD', 'Linux', 'Unix'}

I don't want to break order of nodes is there good way for it?

Body:
You have two options :

first option:

use ordered dict:

As suggested by @user1767754 :

from collections import OrderedDict

nodes = ['Unix', 'BSD', 'Linux']
uniques = OrderedDict((x, True) for x in nodes).keys()

Second method keep track of index and values:

so first create a dict with index,values :

nodes = ['Unix', 'BSD', 'Linux']

order={}
for i,j in enumerate(nodes):
    order[i]=j

print(order)

it will give:

{0: 'Unix', 1: 'BSD', 2: 'Linux'}

Now do your stuff like converting list to set or whatever you want and at last convert again to list something like this:

new=[]
for i in set(nodes):
    for k,j in order.items():
        if i==j:
            new.insert(k,j)

print(new)

Now it will give:

['Unix', 'BSD', 'Linux']


问:
Have a cocoa application that opens when I press a key combination
Hey guys, I've finished my little calculator and now what I want to do is this:

I want to be able to run it in the background until I press, say, Control + C and then have it open...is this possible in OS X? I recall it being pretty simple in Windows...where should I begin to look?

I feel like it will involve running as a service or something...

答:
One solution is to have your calculator provide a Service. A Service can be assigned a global key combination. When the combination is pressed, your calculator application can open, and ideally, perform a task on the user's current selection.

To assign a service a specific key combination see:

System Preferences > Keyboard > Keyboard Shortcuts

An alternative approach is to create a background application. This application can register for a global hot key combination. When the combination is pressed, the background application can launch your calculator.


问:
Color Change of stacked menu and social media based on background color
Im trying to replicate this sites color change of the hamburger and social media based on the the background of the div https://pithworks.com/

As you scroll you can see that it changes color based on a light and darker background. I've tried several options such as colourBrightness.js and background-check.js and have no success.

Any ideas on how to get his to work.

Thanks

答:
Here is a possible solution :

var cursor = 0;
var direction = -1;
var fps = 15; // frames per second

// -0.25 ... 0 ... 0.25
//           ^
//         cursor

setInterval(function () {
  cursor += direction * 0.01;
  if (Math.abs(cursor) > 0.25) direction *= -1;
  document.body.style.background = makeGradient(cursor);
}, 1000 / fps);

function makeGradient (cursor) {
  var p1 = Math.round(cursor * 100);
  var p2 = Math.round((cursor + 1) * 100);
  return "linear-gradient(45deg, "
  + "#ff2200 " + p1 + "%, "
  + "#23548b " + p2 + "%"
  + ")";
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>html,body{padding:0;margin:0;height:100%;}</code>```

See http://www.colorzilla.com/gradient-editor.

Body:
Here is a possible solution :

var cursor = 0;
var direction = -1;
var fps = 15; // frames per second

// -0.25 ... 0 ... 0.25
//           ^
//         cursor

setInterval(function () {
  cursor += direction * 0.01;
  if (Math.abs(cursor) > 0.25) direction *= -1;
  document.body.style.background = makeGradient(cursor);
}, 1000 / fps);

function makeGradient (cursor) {
  var p1 = Math.round(cursor * 100);
  var p2 = Math.round((cursor + 1) * 100);
  return "linear-gradient(45deg, "
  + "#ff2200 " + p1 + "%, "
  + "#23548b " + p2 + "%"
  + ")";
}

html,body{padding:0;margin:0;height:100%;}

See http://www.colorzilla.com/gradient-editor.


问:
Where is onScroll event in material ui
I cannot find any documentation in Material UI that shows a fired function for onScroll. All my components are either functional and stateless or container components which have the mapStateToProps and mapDispatchToProps API.

How has anyone written Material UI List and ListItem components to also include scroll events for a function in mapDispatchToProps to run? There are click events, but no scroll events like onScroll.

答: when I was posed with same issue, all i did was used getElementByXXX to grab the specific tag in DOM and then do it the plain JS+DOM way. Specific implementation would vary depending upon what you want to achieve, with which component and your scenario. Hope this helps!

Title: Where is onScroll event in material ui


问:
Dates not sorting in DataTables
Dates in my DataTables is not sorting the way it should? I am using AJAX, and here is the payload used:

{"data": [["5/24/2017","0","Uncategorized","Owners","New bulletin","No expiration","<button type='button' class='btn btn-xs btn-primary' onclick='archiveCircular(19);'>Archive</button>","<button type='button' class='btn btn-xs btn-info' onclick='showBBDetails(19);'>Show</button>"],["3/2/2016","0","Advisory","Everyone","New system update","No expiration","<button type='button' class='btn btn-xs btn-primary' onclick='archiveCircular(13);'>Archive</button>","<button type='button' class='btn btn-xs btn-info' onclick='showBBDetails(13);'>Show</button>"],["3/2/2016","0","Advisory","Everyone","First day of access","No expiration","<button type='button' class='btn btn-xs btn-primary' onclick='archiveCircular(12);'>Archive</button>","<button type='button' class='btn btn-xs btn-info' onclick='showBBDetails(12);'>Show</button>"],["11/4/2015","0","Advisory","Everyone","Door fixing in the lobby","No expiration","<button type='button' class='btn btn-xs btn-primary' onclick='archiveCircular(8);'>Archive</button>","<button type='button' class='btn btn-xs btn-info' onclick='showBBDetails(8);'>Show</button>"],["11/4/2015","0","Uncategorized","Everyone","Facade painting today","No expiration","<button type='button' class='btn btn-xs btn-primary' onclick='archiveCircular(7);'>Archive</button>","<button type='button' class='btn btn-xs btn-info' onclick='showBBDetails(7);'>Show</button>"],["5/4/2015","0","Advisory","Everyone","Repainting of Balconies","No expiration","<button type='button' class='btn btn-xs btn-primary' onclick='archiveCircular(6);'>Archive</button>","<button type='button' class='btn btn-xs btn-info' onclick='showBBDetails(6);'>Show</button>"],["5/4/2015","0","Uncategorized","Everyone","Insect Fuming again","No expiration","<button type='button' class='btn btn-xs btn-primary' onclick='archiveCircular(5);'>Archive</button>","<button type='button' class='btn btn-xs btn-info' onclick='showBBDetails(5);'>Show</button>"],["5/4/2015","0","Uncategorized","Everyone","Annual Meeting 2015","No expiration","<button type='button' class='btn btn-xs btn-primary' onclick='archiveCircular(4);'>Archive</button>","<button type='button' class='btn btn-xs btn-info' onclick='showBBDetails(4);'>Show</button>"]]}
```

<p>The tables is rendered without issue. But, if I try to sort on the first date cell, it gets it all wrong (screenshots attached).</p>

<p>Here is the initialization code:</p>

<pre class="lang-js prettyprint-override"><code>var uriActive = "ajax/bulletinpost/get_active.aspx";
tActive = $('#tblActive').DataTable({
    "ajax": uriActive,
    dom: 'Bfrtip',
    buttons: [{ extend: 'excelHtml5', title: 'Data export' }, { extend: 'pdfHtml5', title: 'Data export' }],
    "deferRender": true,
    "lengthMenu": [[50, 100, 150, 200, 250, -1], [50, 100, 150, 200, 250, "All"]],
    "iDisplayLength": 50,
    "order": [],
    "columnDefs": [{ "targets": 'no-sort', "orderable": false }, { "searchable": false, "targets": [1,6,7] }],
    "fnDrawCallback": function (oSettings) {
        $('[data-toggle="popover"]').popover({ 'trigger': 'hover', 'placement': 'top' });
        $('.editable').editable({ mode: 'popup' });
    }
});
</code>```

Date format is mm/dd/yyyy. Anyone has any idea?

答:
By default only strings which is parseable with Date.parse() will be recognized as dates. mm/dd/yyyy is not a parseable date format. A column with "odd" date formats in some form will need to perform the parsing itself, for example by using a plugin.

But there is really no hocus pocus about it. Just parse the date in a render callback and return the parsed dates as integer values :

"columnDefs": [
  { targets: 0,
    type: 'num',
    render: function(data,type) {
      if (type == 'sort') return Date.parse( data.replace('/', '-').valueOf() )
      return data
    }
  },
  { "targets": 'no-sort', "orderable": false },
  { "searchable": false, "targets": [1,6,7] }
],
```

Now the dates is sorted as they should -> http://jsfiddle.net/t34h6yuj/

NB: Obviously you should perform some kind of sanity check on data in the render callback. At least check if the server have returned a null value.

Title: Dates not sorting in DataTables

Body:
Dates in my DataTables is not sorting the way it should? I am using AJAX, and here is the payload used:

{"data": [["5/24/2017","0","Uncategorized","Owners","New bulletin","No expiration","<button type='button' class='btn btn-xs btn-primary' onclick='archiveCircular(19);'>Archive</button>","<button type='button' class='btn btn-xs btn-info' onclick='showBBDetails(19);'>Show</button>"],["3/2/2016","0","Advisory","Everyone","New system update","No expiration","<button type='button' class='btn btn-xs btn-primary' onclick='archiveCircular(13);'>Archive</button>","<button type='button' class='btn btn-xs btn-info' onclick='showBBDetails(13);'>Show</button>"],["3/2/2016","0","Advisory","Everyone","First day of access","No expiration","<button type='button' class='btn btn-xs btn-primary' onclick='archiveCircular(12);'>Archive</button>","<button type='button' class='btn btn-xs btn-info' onclick='showBBDetails(12);'>Show</button>"],["11/4/2015","0","Advisory","Everyone","Door fixing in the lobby","No expiration","<button type='button' class='btn btn-xs btn-primary' onclick='archiveCircular(8);'>Archive</button>","<button type='button' class='btn btn-xs btn-info' onclick='showBBDetails(8);'>Show</button>"],["11/4/2015","0","Uncategorized","Everyone","Facade painting today","No expiration","<button type='button' class='btn btn-xs btn-primary' onclick='archiveCircular(7);'>Archive</button>","<button type='button' class='btn btn-xs btn-info' onclick='showBBDetails(7);'>Show</button>"],["5/4/2015","0","Advisory","Everyone","Repainting of Balconies","No expiration","<button type='button' class='btn btn-xs btn-primary' onclick='archiveCircular(6);'>Archive</button>","<button type='button' class='btn btn-xs btn-info' onclick='showBBDetails(6);'>Show</button>"],["5/4/2015","0","Uncategorized","Everyone","Insect Fuming again","No expiration","<button type='button' class='btn btn-xs btn-primary' onclick='archiveCircular(5);'>Archive</button>","<button type='button' class='btn btn-xs btn-info' onclick='showBBDetails(5);'>Show</button>"],["5/4/2015","0","Uncategorized","Everyone","Annual Meeting 2015","No expiration","<button type='button' class='btn btn-xs btn-primary' onclick='archiveCircular(4);'>Archive</button>","<button type='button' class='btn btn-xs btn-info' onclick='showBBDetails(4);'>Show</button>"]]}

The tables is rendered without issue. But, if I try to sort on the first date cell, it gets it all wrong (screenshots attached).

Here is the initialization code:

var uriActive = "ajax/bulletinpost/get_active.aspx";
tActive = $('#tblActive').DataTable({
    "ajax": uriActive,
    dom: 'Bfrtip',
    buttons: [{ extend: 'excelHtml5', title: 'Data export' }, { extend: 'pdfHtml5', title: 'Data export' }],
    "deferRender": true,
    "lengthMenu": [[50, 100, 150, 200, 250, -1], [50, 100, 150, 200, 250, "All"]],
    "iDisplayLength": 50,
    "order": [],
    "columnDefs": [{ "targets": 'no-sort', "orderable": false }, { "searchable": false, "targets": [1,6,7] }],
    "fnDrawCallback": function (oSettings) {
        $('[data-toggle="popover"]').popover({ 'trigger': 'hover', 'placement': 'top' });
        $('.editable').editable({ mode: 'popup' });
    }
});

Date format is mm/dd/yyyy. Anyone has any idea?

Body:
By default only strings which is parseable with Date.parse() will be recognized as dates. mm/dd/yyyy is not a parseable date format. A column with "odd" date formats in some form will need to perform the parsing itself, for example by using a plugin.

But there is really no hocus pocus about it. Just parse the date in a render callback and return the parsed dates as integer values :

"columnDefs": [
  { targets: 0,
    type: 'num',
    render: function(data,type) {
      if (type == 'sort') return Date.parse( data.replace('/', '-').valueOf() )
      return data
    }
  },
  { "targets": 'no-sort', "orderable": false },
  { "searchable": false, "targets": [1,6,7] }
],

Now the dates is sorted as they should -> http://jsfiddle.net/t34h6yuj/

NB: Obviously you should perform some kind of sanity check on data in the render callback. At least check if the server have returned a null value.


问:
What datatype to use in Slick Table definiton for json?
A table in my database has a column with the type json. I am wondering, which data type should I use when I define the table in Slick?
Currently, for the specific column I use Blob since I found it suggested  here.
I'm interested to know if it is possible to use the json library class provided Play framework (play.libs.json)? If so, how? Do I need implicit mappers? </p>

答:
Slick provides custom data type mapper which are not supported by Slick.
In my case: Saving Json as string into database and in code using as JValue(I am using json4s):

```<code>object JsonMapper{
   import driver.api._

   implicit val jsonMapper = MappedColumnType.base[JValue, String](
      { json => write(framesType) /* json writer */ },
      { str =>parse(str)  /*json parser */ }
     )
  }

 import JsonMapper._

  case class Info(id:Int, json:JValue)
  class DBTable(tag:Tag) extends Table[Info](tag, "info"){
    val id = column[Int]("id")
    val json = column[JValue]("json")
    def * = (id ,json) <> (Info.tupled, Info.unapply)
  }
</code>```

I am not sure this will work for your case. But this is a way to map any custom data type in Slick.

Body:
Slick provides custom data type mapper which are not supported by Slick.
In my case: Saving Json as string into database and in code using as JValue(I am using json4s):

object JsonMapper{
   import driver.api._

   implicit val jsonMapper = MappedColumnType.base[JValue, String](
      { json => write(framesType) /* json writer */ },
      { str =>parse(str)  /*json parser */ }
     )
  }

 import JsonMapper._

  case class Info(id:Int, json:JValue)
  class DBTable(tag:Tag) extends Table[Info](tag, "info"){
    val id = column[Int]("id")
    val json = column[JValue]("json")
    def * = (id ,json) <> (Info.tupled, Info.unapply)
  }

I am not sure this will work for your case. But this is a way to map any custom data type in Slick.


问:
Why isn't this code triggering paint()?
It runs, the buttons work, but i just can't get it to draw with the paint(). I think it has something to do with the main method on SwingDraw, but i'm not 100% sure. Thanks for any help and sorry for the long code :/

SwingDraw:

```<code>// Import Core Java packages
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.*;
import javax.swing.*;

public class SwingDraw extends JFrame implements ActionListener, ItemListener{

// Initial Frame size
static final int WIDTH = 1500;                // frame width
static final int HEIGHT = 1000;               // frame height

// Color choices
static final String[] COLOR_NAMES = new String[]{"None", "Red", "Blue", "Green"};
static final Color COLORS[] = {null, Color.red, Color.blue, Color.green };

// Button control
JButton circle;
JButton roundRec;
JButton threeDRec;
JButton line;
JButton square;
JButton oval;

JButton clear;
JButton delete;

// List to keep track of shapes
JList<String> shapesKeeper;

// Color choice box
JComboBox<String> colorChoice = new JComboBox<>(COLOR_NAMES);

SwingDrawCanvas betterCanvas = new SwingDrawCanvas();

/**
 * Constructor
 */
public SwingDraw() {
    // Create a frame
    setSize(WIDTH, HEIGHT);
    setLocation(130, 100);
    // add window closing listener
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    // create panel for controls
    JPanel topPanel = new JPanel();
    JPanel leftList = new JPanel();

    // create button control
    JPanel buttonPanel = new JPanel();
    topPanel.add(buttonPanel, BorderLayout.NORTH);

    circle = new JButton("Circle");
    buttonPanel.add(circle);
    roundRec = new JButton("Rounded Rectangle");
    buttonPanel.add(roundRec);
    threeDRec = new JButton("3D Rectangle");
    buttonPanel.add(threeDRec);
    line = new JButton("Line");
    buttonPanel.add(line);
    square = new JButton("Square");
    buttonPanel.add(square);
    oval = new JButton("Oval");
    buttonPanel.add(oval);
    clear = new JButton("Clear");
    buttonPanel.add(clear);

    JPanel listPanel = new JPanel();
    leftList.add(listPanel, BorderLayout.WEST);
    JList<String> shapesKeeper = new JList<>();
    listPanel.add(shapesKeeper);
    delete = new JButton("Delete Shape");
    listPanel.add(delete);

    // add button listener
    circle.addActionListener(this);
    roundRec.addActionListener(this);
    threeDRec.addActionListener(this);
    line.addActionListener(this);
    square.addActionListener(this);
    oval.addActionListener(this);
    clear.addActionListener(this);

    // create panel for color choices
    JPanel colorPanel = new JPanel();
    JLabel label = new JLabel("Filled Color:");
    topPanel.add(colorPanel);
    colorPanel.add(label);
    JComboBox<String> colorChoice = new JComboBox<>(COLOR_NAMES);
    colorPanel.add(colorChoice);

    colorChoice.addItemListener(this);

    add(topPanel, BorderLayout.NORTH);
    add(leftList, BorderLayout.WEST);
    setVisible(true);

} // end of constructor

/**
 *  Implementing ActionListener
 */
public void actionPerformed(ActionEvent event) {
    if(event.getSource() == circle) {  // circle button
        betterCanvas.setShape(SwingDrawCanvas.CIRCLE);
    }
    else if(event.getSource() == roundRec) {  // rounded rectangle button
        betterCanvas.setShape(SwingDrawCanvas.ROUNDED_RECTANGLE);
    }
    else if(event.getSource() == threeDRec) { // 3D rectangle button
        betterCanvas.setShape(SwingDrawCanvas.RECTANGLE_3D);
    }
    else if(event.getSource() == clear){
        betterCanvas.setShape(SwingDrawCanvas.CLEAR);
    }
    else if(event.getSource() == line){
        betterCanvas.setShape(SwingDrawCanvas.LINE);
    }
    else if(event.getSource() == square){
        betterCanvas.setShape(SwingDrawCanvas.SQUARE);
    }
    else if(event.getSource() == oval){
        betterCanvas.setShape(SwingDrawCanvas.OVAL);

    }
}

/**
 * Implementing ItemListener
 */
public void itemStateChanged(ItemEvent event) {
    Color color = COLORS[colorChoice.getSelectedIndex()];
    betterCanvas.setFilledColor(color);
}

/**
 * the main method
 */
public static void main(String[] argv) {
    new SwingDraw();
}
}
</code>```

SwingDrawCanvas:

```<code>public class SwingDrawCanvas extends JPanel implements MouseListener, MouseMotionListener {

// Constants for shapes
public static final int CIRCLE = 1;
public static final int ROUNDED_RECTANGLE = 2;
public static final int RECTANGLE_3D = 3;
public static final int LINE = 4;
public static final int SQUARE = 5;
public static final int OVAL = 6;

public static final int CLEAR = 7;

// Coordinates of points to draw
private int x1, y1, x2, y2;

// shape to draw
private int shape = CIRCLE;
/**
 * Method to set the shape
 */
public void setShape(int thisShape) {
    System.out.println("HEY");
    this.shape = thisShape;
    System.out.println(shape);
}

// filled color
private Color filledColor = null;
/**
 * Method to set filled color
 */
public void setFilledColor(Color color) {
    filledColor = color;
}

/**
 * Constructor
 */
public SwingDrawCanvas() {
    addMouseListener(this);
    addMouseMotionListener(this);
} // end of constructor

/**
 * painting the component
 */
public void paint(Graphics g) {

    System.out.println("ARHFHASJDASHDHAs");
    super.paint(g);

    System.out.println("AHAHAHAHAHAHAHA");

    g.drawString("FUCK", 1, 1);

    // the drawing area
    int x, y, width, height;

    // determine the upper-left corner of bounding rectangle
    x = Math.min(x1, x2);
    y = Math.min(y1, y2);

    // determine the width and height of bounding rectangle
    width = Math.abs(x1 - x2);
    height = Math.abs(y1 - y2);

    if(filledColor != null)
        g.setColor(filledColor);
    switch (shape) {
        case ROUNDED_RECTANGLE :
            if(filledColor == null)
                g.drawRoundRect(x, y, width, height, width/4, height/4);
            else
                g.fillRoundRect(x, y, width, height, width/4, height/4);
            break;
        case CIRCLE :
            int diameter = Math.max(width, height);
            if(filledColor == null)
                System.out.println("HRE BITCHS");
            else
                System.out.println("HEY FUCK YOU GUY");
            break;
        case RECTANGLE_3D :
            if(filledColor == null)
                g.draw3DRect(x, y, width, height, true);
            else
                g.fill3DRect(x, y, width, height, true);
            break;
    }
}

/**
 * Implementing MouseListener
 */
public void mousePressed(MouseEvent event) {
    x1 = event.getX();
    y1 = event.getY();
}

public void mouseReleased(MouseEvent event) {
    x2 = event.getX();
    y2 = event.getY();
    repaint();
}

public void mouseClicked(MouseEvent e) {}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}

/**
 * Implementing MouseMotionListener
 */
public void mouseDragged(MouseEvent event) {
    x2 = event.getX();
    y2 = event.getY();
    repaint();
}

public void mouseMoved(MouseEvent e) {}
</code>```

}

I'm not very good at this, I'm just looking for any help you guys can give me :D

答:
Instead of having paint(), your function should be name paintComponent(Graphics g).
When creating the paintComponent(Graphics g) functions, you need @Override so that java recognizes the function because you can not call paintComponent(Graphics g) directly.

In addition, any time you want to refresh your panel, you can call repaint() or you can resize your JFrame after the code as compiled. Both of these methods will call the paintComponent(Graphics g) function.

Title: Why isn't this code triggering paint()?

Body:
It runs, the buttons work, but i just can't get it to draw with the paint(). I think it has something to do with the main method on SwingDraw, but i'm not 100% sure. Thanks for any help and sorry for the long code :/

SwingDraw:

// Import Core Java packages
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.*;
import javax.swing.*;

public class SwingDraw extends JFrame implements ActionListener, ItemListener{

// Initial Frame size
static final int WIDTH = 1500;                // frame width
static final int HEIGHT = 1000;               // frame height

// Color choices
static final String[] COLOR_NAMES = new String[]{"None", "Red", "Blue", "Green"};
static final Color COLORS[] = {null, Color.red, Color.blue, Color.green };

// Button control
JButton circle;
JButton roundRec;
JButton threeDRec;
JButton line;
JButton square;
JButton oval;

JButton clear;
JButton delete;

// List to keep track of shapes
JList<String> shapesKeeper;

// Color choice box
JComboBox<String> colorChoice = new JComboBox<>(COLOR_NAMES);

SwingDrawCanvas betterCanvas = new SwingDrawCanvas();

/**
 * Constructor
 */
public SwingDraw() {
    // Create a frame
    setSize(WIDTH, HEIGHT);
    setLocation(130, 100);
    // add window closing listener
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    // create panel for controls
    JPanel topPanel = new JPanel();
    JPanel leftList = new JPanel();

    // create button control
    JPanel buttonPanel = new JPanel();
    topPanel.add(buttonPanel, BorderLayout.NORTH);

    circle = new JButton("Circle");
    buttonPanel.add(circle);
    roundRec = new JButton("Rounded Rectangle");
    buttonPanel.add(roundRec);
    threeDRec = new JButton("3D Rectangle");
    buttonPanel.add(threeDRec);
    line = new JButton("Line");
    buttonPanel.add(line);
    square = new JButton("Square");
    buttonPanel.add(square);
    oval = new JButton("Oval");
    buttonPanel.add(oval);
    clear = new JButton("Clear");
    buttonPanel.add(clear);

    JPanel listPanel = new JPanel();
    leftList.add(listPanel, BorderLayout.WEST);
    JList<String> shapesKeeper = new JList<>();
    listPanel.add(shapesKeeper);
    delete = new JButton("Delete Shape");
    listPanel.add(delete);

    // add button listener
    circle.addActionListener(this);
    roundRec.addActionListener(this);
    threeDRec.addActionListener(this);
    line.addActionListener(this);
    square.addActionListener(this);
    oval.addActionListener(this);
    clear.addActionListener(this);

    // create panel for color choices
    JPanel colorPanel = new JPanel();
    JLabel label = new JLabel("Filled Color:");
    topPanel.add(colorPanel);
    colorPanel.add(label);
    JComboBox<String> colorChoice = new JComboBox<>(COLOR_NAMES);
    colorPanel.add(colorChoice);

    colorChoice.addItemListener(this);

    add(topPanel, BorderLayout.NORTH);
    add(leftList, BorderLayout.WEST);
    setVisible(true);

} // end of constructor

/**
 *  Implementing ActionListener
 */
public void actionPerformed(ActionEvent event) {
    if(event.getSource() == circle) {  // circle button
        betterCanvas.setShape(SwingDrawCanvas.CIRCLE);
    }
    else if(event.getSource() == roundRec) {  // rounded rectangle button
        betterCanvas.setShape(SwingDrawCanvas.ROUNDED_RECTANGLE);
    }
    else if(event.getSource() == threeDRec) { // 3D rectangle button
        betterCanvas.setShape(SwingDrawCanvas.RECTANGLE_3D);
    }
    else if(event.getSource() == clear){
        betterCanvas.setShape(SwingDrawCanvas.CLEAR);
    }
    else if(event.getSource() == line){
        betterCanvas.setShape(SwingDrawCanvas.LINE);
    }
    else if(event.getSource() == square){
        betterCanvas.setShape(SwingDrawCanvas.SQUARE);
    }
    else if(event.getSource() == oval){
        betterCanvas.setShape(SwingDrawCanvas.OVAL);

    }
}

/**
 * Implementing ItemListener
 */
public void itemStateChanged(ItemEvent event) {
    Color color = COLORS[colorChoice.getSelectedIndex()];
    betterCanvas.setFilledColor(color);
}

/**
 * the main method
 */
public static void main(String[] argv) {
    new SwingDraw();
}
}

SwingDrawCanvas:

public class SwingDrawCanvas extends JPanel implements MouseListener, MouseMotionListener {

// Constants for shapes
public static final int CIRCLE = 1;
public static final int ROUNDED_RECTANGLE = 2;
public static final int RECTANGLE_3D = 3;
public static final int LINE = 4;
public static final int SQUARE = 5;
public static final int OVAL = 6;

public static final int CLEAR = 7;

// Coordinates of points to draw
private int x1, y1, x2, y2;

// shape to draw
private int shape = CIRCLE;
/**
 * Method to set the shape
 */
public void setShape(int thisShape) {
    System.out.println("HEY");
    this.shape = thisShape;
    System.out.println(shape);
}

// filled color
private Color filledColor = null;
/**
 * Method to set filled color
 */
public void setFilledColor(Color color) {
    filledColor = color;
}

/**
 * Constructor
 */
public SwingDrawCanvas() {
    addMouseListener(this);
    addMouseMotionListener(this);
} // end of constructor

/**
 * painting the component
 */
public void paint(Graphics g) {

    System.out.println("ARHFHASJDASHDHAs");
    super.paint(g);

    System.out.println("AHAHAHAHAHAHAHA");

    g.drawString("FUCK", 1, 1);

    // the drawing area
    int x, y, width, height;

    // determine the upper-left corner of bounding rectangle
    x = Math.min(x1, x2);
    y = Math.min(y1, y2);

    // determine the width and height of bounding rectangle
    width = Math.abs(x1 - x2);
    height = Math.abs(y1 - y2);

    if(filledColor != null)
        g.setColor(filledColor);
    switch (shape) {
        case ROUNDED_RECTANGLE :
            if(filledColor == null)
                g.drawRoundRect(x, y, width, height, width/4, height/4);
            else
                g.fillRoundRect(x, y, width, height, width/4, height/4);
            break;
        case CIRCLE :
            int diameter = Math.max(width, height);
            if(filledColor == null)
                System.out.println("HRE BITCHS");
            else
                System.out.println("HEY FUCK YOU GUY");
            break;
        case RECTANGLE_3D :
            if(filledColor == null)
                g.draw3DRect(x, y, width, height, true);
            else
                g.fill3DRect(x, y, width, height, true);
            break;
    }
}

/**
 * Implementing MouseListener
 */
public void mousePressed(MouseEvent event) {
    x1 = event.getX();
    y1 = event.getY();
}

public void mouseReleased(MouseEvent event) {
    x2 = event.getX();
    y2 = event.getY();
    repaint();
}

public void mouseClicked(MouseEvent e) {}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}

/**
 * Implementing MouseMotionListener
 */
public void mouseDragged(MouseEvent event) {
    x2 = event.getX();
    y2 = event.getY();
    repaint();
}

public void mouseMoved(MouseEvent e) {}

}

I'm not very good at this, I'm just looking for any help you guys can give me :D


问:
RoR - Nested attributes wrong number of arguments?
Currently following a tutorial, where a nested form should be implemented. However, when i run rails c and try to create a new Portfolio with the nested attributes, i get an

```<code>ArgumentError: wrong number of arguments (given 1, expected 0)
    from app/models/portfolio.rb:4:in `block in <class:Portfolio>'
    from (irb):15
</code>```

Command i ran inside rails c:

```<code>Portfolio.create!(title: 'Title', subtitle:'Title1', body:'Title3',
technologies_attributes:[{name: 'Ruby'}])
</code>```

The Portfolio.rb file:

```<code>class Portfolio < ApplicationRecord
  has_many :technologies
  accepts_nested_attributes_for :technologies,
                                reject_if: lambda { |attrs| attrs['name'].blank? }

  include Placeholder
  validates_presence_of :title, :body, :main_image, :thumb_image

  def self.angular
    where(subtitle: 'Angular!')
  end

  def self.ruby
    where(subtitle: 'Ruby on Rails!')
  end

  after_initialize :set_defaults

  def set_defaults
    self.main_image ||= Placeholder.image_generator(height: '600', width: '400')
    self.thumb_image ||= Placeholder.image_generator(height: '350', width: '200')
  end

end
</code>```

Any ideas what would cause that?

Thanks in advance!

答:
Try using, inverse_of: in both the models, since it used to created associated objects.</p>

```<code>class Portfolio < ApplicationRecord
  has_many :technologies, inverse_of: :port_folio
end

class Technology < ApplicationRecord
  belongs_to :port_folio, inverse_of: :technologies
end
</code>```

Body:
Currently following a tutorial, where a nested form should be implemented. However, when i run rails c and try to create a new Portfolio with the nested attributes, i get an

ArgumentError: wrong number of arguments (given 1, expected 0)
    from app/models/portfolio.rb:4:in `block in <class:Portfolio>'
    from (irb):15

Command i ran inside rails c:

Portfolio.create!(title: 'Title', subtitle:'Title1', body:'Title3',
technologies_attributes:[{name: 'Ruby'}])

The Portfolio.rb file:

class Portfolio < ApplicationRecord
  has_many :technologies
  accepts_nested_attributes_for :technologies,
                                reject_if: lambda { |attrs| attrs['name'].blank? }

  include Placeholder
  validates_presence_of :title, :body, :main_image, :thumb_image

  def self.angular
    where(subtitle: 'Angular!')
  end

  def self.ruby
    where(subtitle: 'Ruby on Rails!')
  end

  after_initialize :set_defaults

  def set_defaults
    self.main_image ||= Placeholder.image_generator(height: '600', width: '400')
    self.thumb_image ||= Placeholder.image_generator(height: '350', width: '200')
  end

end

Any ideas what would cause that?

Thanks in advance!

Body:
Try using, inverse_of: in both the models, since it used to created associated objects.

class Portfolio < ApplicationRecord
  has_many :technologies, inverse_of: :port_folio
end

class Technology < ApplicationRecord
  belongs_to :port_folio, inverse_of: :technologies
end


问:
Intersection of two large word lists
I have two word lists (180k and 260k), and I would like to generate a third file which is the set of words that appear in BOTH lists.

What is the best (most efficient) way of doing this? I've read forums talking about using grep, however I think the word lists are too big for this method.

答: If the two files are sorted (or you can sort them), you can use comm -1 -2 file1 file2 to print out the intersection.

Title: Intersection of two large word lists


问:
How to stop/shut down an elasticsearch node?
I want to restart an elasticsearch node with a new configuration. What is the best way to gracefully shut down an node?

Is killing the process the best way of shutting the server down, or is there some magic URL I can use to shut the node down?

答:
Stopping the service and killing the daemon are indeed the correct ways to shutdown a node. However, it's not recommended to do so directly if you want to take down a node for maintenance. In fact, if you don't have replicas you will lose data.

When you directly shutdown a node, Elasticsearch will wait for 1m (default time) for it to come back online. If it doesn't, then it will start to allocate the shards from that node to other nodes wasting lots of IO.

A typical approach would be to disable shard allocation temporarily by issuing:

```<code>PUT _cluster/settings
{
  "persistent": {
    "cluster.routing.allocation.enable": "none"
  }
}
</code>```

Now, when you take down a node, ES won't try to allocate shard from that node to other nodes and you can perform you maintenance activity and then once the node is up, you can enable shard allocation again:

```<code>PUT _cluster/settings
{
  "persistent": {
    "cluster.routing.allocation.enable": "all"
  }
}
</code>```

Source: https://www.elastic.co/guide/en/elasticsearch/reference/5.5/restart-upgrade.html

If you don't have replicas for all your indexes, then performing this type of activity will have downtime on some of the indexes. A cleaner way in this case would be to migrate all the shards to other nodes before taking the node down:

```<code>PUT _cluster/settings
{
  "transient" : {
    "cluster.routing.allocation.exclude._ip" : "10.0.0.1"
  }
}
</code>```

This will move all shards from 10.0.0.1 to other nodes (will take time depending on the data). Once everything is done, you can kill the node, perform maintenance and get it back online. This is a slower operation and is not required if you have replicas.

(Instead of _ip, _id, _name with wildcards will work just fine.)

More information: https://www.elastic.co/guide/en/elasticsearch/reference/5.5/allocation-filtering.html

Other answers have explained how to kill a process.

Body:
Stopping the service and killing the daemon are indeed the correct ways to shutdown a node. However, it's not recommended to do so directly if you want to take down a node for maintenance. In fact, if you don't have replicas you will lose data.

When you directly shutdown a node, Elasticsearch will wait for 1m (default time) for it to come back online. If it doesn't, then it will start to allocate the shards from that node to other nodes wasting lots of IO.

A typical approach would be to disable shard allocation temporarily by issuing:

PUT _cluster/settings
{
  "persistent": {
    "cluster.routing.allocation.enable": "none"
  }
}

Now, when you take down a node, ES won't try to allocate shard from that node to other nodes and you can perform you maintenance activity and then once the node is up, you can enable shard allocation again:

PUT _cluster/settings
{
  "persistent": {
    "cluster.routing.allocation.enable": "all"
  }
}

Source: https://www.elastic.co/guide/en/elasticsearch/reference/5.5/restart-upgrade.html

If you don't have replicas for all your indexes, then performing this type of activity will have downtime on some of the indexes. A cleaner way in this case would be to migrate all the shards to other nodes before taking the node down:

PUT _cluster/settings
{
  "transient" : {
    "cluster.routing.allocation.exclude._ip" : "10.0.0.1"
  }
}

This will move all shards from 10.0.0.1 to other nodes (will take time depending on the data). Once everything is done, you can kill the node, perform maintenance and get it back online. This is a slower operation and is not required if you have replicas.

(Instead of _ip, _id, _name with wildcards will work just fine.)

More information: https://www.elastic.co/guide/en/elasticsearch/reference/5.5/allocation-filtering.html

Other answers have explained how to kill a process.

ContentLicense: CC BY-SA 4.0


问:
How to fetch image and pdf file from json and display in tableviewcell swift 3
Hello all as i am a Fresher so dont know how to fetch image and pdf file from API and how to display in tableviewcell so that user can see the image and pdf file as well download it from there.I tried some code for image but its not working and dont have a single idea for pdf.Please help.

code for image :
I have declared an array of images like below :

```<code>var announimage : Array = [UIImage]()
</code>```

Below is the format of my JSON data.

```<code>{
 "Download_Details": [
 {
"school_id": 1,
"class_id": "Pre - KG ",
"section": "A ",
"file_name": "427a3be0155b49db999cffb51f078f9c_431875732.pdf",
"title": "TeQ",
"message": "Hello Users",
"date": null
},
{
"school_id": 1,
"class_id": "Pre - KG ",
"section": "A ",
"file_name": "dce5ab53f45f4ec5b52894bc6286ed35_1376021.jpg",
"title": "Welcome",
"message": "Welcomes you.",
"date": null
},
{
 "school_id": 1,
 "class_id": "Pre - KG ",
 "section": "A ",
 "file_name": "9d3ff19bd54e48a087947227ee36c68c_13417773.png",
 "title": "TEST",
"message": "TEST",
"date": null
}
],
}
</code>```

Below is the code i have tried :

```<code>let responseString = try! JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSDictionary

let downarray = responseString?.value(forKey: "Download_Details") as? NSArray

for down in downarray!
{
    let dowdict = down as? NSDictionary

    let dmsgname = dowdict?.value(forKey: "message")

    self.announmessage.append(dmsgname as! String)

   let downimage = dowdict?.value(forKey: "file_name")

   self.announimage.append(downimage as! UIImage)

}

DispatchQueue.main.async
{
    self.annountable.reloadData()
}
</code>```

UITableView DataSource :

```<code>func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell2 = tableView.dequeueReusableCell(withIdentifier: "cell1", for: indexPath) as! AnnounceCellTableViewCell
    cell2.announlabel.text = announmessage[indexPath.row]
    cell2.announdate.text = announcedates[indexPath.row]
    let image :UIImage = UIImage(data:announimage[indexPath.row] as! Data)!
    cell2.dataimage.image = image
     return cell2

}
</code>```

答:
Try below code on cell for row</p>

```<code>let image : UIImage = UIImage(data: filteredAry[indexPath.row] as! Data)

cell2.dataimage.image = image
</code>```

Body:
Hello all as i am a Fresher so dont know how to fetch image and pdf file from API and how to display in tableviewcell so that user can see the image and pdf file as well download it from there.I tried some code for image but its not working and dont have a single idea for pdf.Please help.

code for image :
I have declared an array of images like below :

var announimage : Array = [UIImage]()

Below is the format of my JSON data.

{
 "Download_Details": [
 {
"school_id": 1,
"class_id": "Pre - KG ",
"section": "A ",
"file_name": "427a3be0155b49db999cffb51f078f9c_431875732.pdf",
"title": "TeQ",
"message": "Hello Users",
"date": null
},
{
"school_id": 1,
"class_id": "Pre - KG ",
"section": "A ",
"file_name": "dce5ab53f45f4ec5b52894bc6286ed35_1376021.jpg",
"title": "Welcome",
"message": "Welcomes you.",
"date": null
},
{
 "school_id": 1,
 "class_id": "Pre - KG ",
 "section": "A ",
 "file_name": "9d3ff19bd54e48a087947227ee36c68c_13417773.png",
 "title": "TEST",
"message": "TEST",
"date": null
}
],
}

Below is the code i have tried :

let responseString = try! JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSDictionary

let downarray = responseString?.value(forKey: "Download_Details") as? NSArray

for down in downarray!
{
    let dowdict = down as? NSDictionary

    let dmsgname = dowdict?.value(forKey: "message")

    self.announmessage.append(dmsgname as! String)

   let downimage = dowdict?.value(forKey: "file_name")

   self.announimage.append(downimage as! UIImage)

}

DispatchQueue.main.async
{
    self.annountable.reloadData()
}

UITableView DataSource :

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell2 = tableView.dequeueReusableCell(withIdentifier: "cell1", for: indexPath) as! AnnounceCellTableViewCell
    cell2.announlabel.text = announmessage[indexPath.row]
    cell2.announdate.text = announcedates[indexPath.row]
    let image :UIImage = UIImage(data:announimage[indexPath.row] as! Data)!
    cell2.dataimage.image = image
     return cell2

}

Body:
Try below code on cell for row

let image : UIImage = UIImage(data: filteredAry[indexPath.row] as! Data)

cell2.dataimage.image = image


答:
You are correct, grep would be a bad idea. Type "man join" and follow the instructions.

If your files are just lists of words in a single column, or at least, if the important word is the first on each line, then all you need to do is:

```<code>$ sort -b -o f1 file1
$ sort -b -o f2 file2
$ join f1 f2
</code>```

Otherwise, you may need to give the join(1) command some additional instructions:

```<code>JOIN(1)                   BSD General Commands Manual                  JOIN(1)

NAME
     join -- relational database operator

SYNOPSIS
     join [-a file_number | -v file_number] [-e string] [-o list] [-t char] [-1 field] [-2 field] file1 file2

DESCRIPTION
     The join utility performs an ``equality join'' on the specified files and writes the result to the standard output.  The ``join field'' is the field in each file by which the files are compared.  The
     first field in each line is used by default.  There is one line in the output for each pair of lines in file1 and file2 which have identical join fields.  Each output line consists of the join field,
     the remaining fields from file1 and then the remaining fields from file2.
     . . .
     . . .
</code>```

Title: Intersection of two large word lists

Body:
I have two word lists (180k and 260k), and I would like to generate a third file which is the set of words that appear in BOTH lists.

What is the best (most efficient) way of doing this? I've read forums talking about using grep, however I think the word lists are too big for this method.

Body:
You are correct, grep would be a bad idea. Type "man join" and follow the instructions.

If your files are just lists of words in a single column, or at least, if the important word is the first on each line, then all you need to do is:

$ sort -b -o f1 file1
$ sort -b -o f2 file2
$ join f1 f2

Otherwise, you may need to give the join(1) command some additional instructions:

JOIN(1)                   BSD General Commands Manual                  JOIN(1)

NAME
     join -- relational database operator

SYNOPSIS
     join [-a file_number | -v file_number] [-e string] [-o list] [-t char] [-1 field] [-2 field] file1 file2

DESCRIPTION
     The join utility performs an ``equality join'' on the specified files and writes the result to the standard output.  The ``join field'' is the field in each file by which the files are compared.  The
     first field in each line is used by default.  There is one line in the output for each pair of lines in file1 and file2 which have identical join fields.  Each output line consists of the join field,
     the remaining fields from file1 and then the remaining fields from file2.
     . . .
     . . .


问:
How to ignore hidden files using os.listdir()?
My python script executes an os.listdir(path) where the path is a queue containing archives that I need to treat one by one.

The problem is that I'm getting the list in an array and then I just do a simple array.pop(0). It was working fine until I put the project in subversion. Now I get the .svn folder in my array and of course it makes my application crash.

So here is my question: is there a function that ignores hidden files when executing an os.listdir() and if not what would be the best way?

答:
```<code>filenames = (f.name for f in os.scandir() if not f.name.startswith('.'))
</code>```


问:
Iterating javascript object synchronously
I have an object like so:

```<code>let myObject = {
'db1': [db1_file1Id,db1_file2Id,db_1file3Id],
'db2': [db2_file1Id, db2_file2Id]
...
}
</code>```

I iterate through through this object and on each iteration: I connect to the database, retrieve the file, do some stuff and save the file back. Basically asynchronous stuff.

```<code>  for (let prop in myObject) {
    if (myObject.hasOwnProperty(prop)) {
      doStuff(prop, myObject[prop]);
    }
  }
</code>```

Now the doStuff function makes sure I have a local scope so there is no inconsistencies. But still, the execution is not synchronous due to the asynchronous operations inside each loop. I basically need one db to be completely processed before moving on to the next. How do I fix this?

One approach that I thought of was to have recursive loop. But as per my understanding, this would require me to change my data structure extensively which is sub-optimal imo.

```<code>let arr; //containing my data

process(x) {
 if (x < arr.length){
   //process(x+1) is called inside doStuff after asynchronous operations are complete
   doStuff(arr[x]);
 }
}
</code>```

答:
You could use the solution you proposed at the end using Object.entries(obj). For example,

```<code>let arrProps = Object.entries(myObject);

process(index) {
 if (index < arrProps.length){
   // Call the callback once you complete execution of doStuff
   doStuff(arrProps[index], () => process(index + 1));
 }
}
</code>```

Inside doStuff:

```<code>function doStuff(props, callback) {
    // Process props
    //finally in the promise of async call, on success call
    .then(callback)
}
</code>```

OR you could use a generator function, if you want to use for ... in loop.

Body:
I have an object like so:

let myObject = {
'db1': [db1_file1Id,db1_file2Id,db_1file3Id],
'db2': [db2_file1Id, db2_file2Id]
...
}

I iterate through through this object and on each iteration: I connect to the database, retrieve the file, do some stuff and save the file back. Basically asynchronous stuff.

  for (let prop in myObject) {
    if (myObject.hasOwnProperty(prop)) {
      doStuff(prop, myObject[prop]);
    }
  }

Now the doStuff function makes sure I have a local scope so there is no inconsistencies. But still, the execution is not synchronous due to the asynchronous operations inside each loop. I basically need one db to be completely processed before moving on to the next. How do I fix this?

One approach that I thought of was to have recursive loop. But as per my understanding, this would require me to change my data structure extensively which is sub-optimal imo.

let arr; //containing my data

process(x) {
 if (x < arr.length){
   //process(x+1) is called inside doStuff after asynchronous operations are complete
   doStuff(arr[x]);
 }
}

Body:
You could use the solution you proposed at the end using Object.entries(obj). For example,

let arrProps = Object.entries(myObject);

process(index) {
 if (index < arrProps.length){
   // Call the callback once you complete execution of doStuff
   doStuff(arrProps[index], () => process(index + 1));
 }
}

Inside doStuff:

function doStuff(props, callback) {
    // Process props
    //finally in the promise of async call, on success call
    .then(callback)
}

OR you could use a generator function, if you want to use for ... in loop.