python – K-Means: why are my results “muddier” than a website performing a similar function?

I’m trying to extract the top 3 most-prominent colors in an image. I’m no expert on computer vision or image analysis, so I’m relying on the kindness of strangers and borrowed code. I’ve got the following Python implementation (abridged to remove database storage of results, etc., so it won’t be directly runnable)

from sklearn.cluster import KMeans
import cv2 
import numpy as np
import colorsys
def centroid_histogram(clusters):
    numLabels = np.arange(0, len(np.unique(clusters.labels_)) + 1)
    (hist, _) = np.histogram(clusters.labels_, bins = numLabels)

    # normalize the histogram, such that it sums to one
    hist = hist.astype("float")
    hist /= hist.sum()

    # return the histogram
    return hist
# load the image and convert it to RGB
image = cv2.imread(image)
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)

# break down the image into one long list of pixels
image = image.reshape((image.shape[0] * image.shape[1], 3))

# perform KMeans clustering
clusters = KMeans(n_clusters=3)

histogram = centroid_histogram(clusters)

for (percent, color) in zip(histogram, clusters.cluster_centers_):
    r = int(color[0])
    g = int(color[1])
    b = int(color[2])

    h, s, v = colorsys.rgb_to_hsv(r/255.0, g/255.0, b/255.0)
    h = h * 360.0

I’ve run the same image through this code, and through an image-processing website, and the results are different. I understand we don’t know the exact algorithm or parameters the site is using. I get that. But the site is getting the results I want, and my code is outputting a darker, more muddied palette. Mine is the bars on the right.

palette comparison

My code also generates the palette with a percentage, which is why the palette blocks are unequal. (Is that the issue?)

There you have it. I’ve tried to ask this in a respectful, informed way so it won’t get ignored or voted down into oblivion. It’s not easy to admit you don’t understand what you’re trying to accomplish, and I don’t have the knowledge of mathematics to fully comprehend what’s happening. I’d be grateful for some suggestions.


لینک منبع

sql – Joining results of two joins

I am looking for the best way to create a query that will do the following(Note: This is just an example, I know this example can be written better, my real goal is a much more complex example, but follows a similar structure)

       item_id   |   name      | cost

       ۱         |   Water     | 1.00
       ۲         |   Chips     | 1.50


       local_id           |   item_id   |  date

       ۱                  |   ۱         | '۲۰۱۸-۰۳-۱۲'
       ۲                  |   ۱         | '۲۰۱۸-۰۳-۱۳'
       ۳                  |   ۲         | '۲۰۱۸-۰۳-۱۳'         


       international_id   |   item_id   |  currency | date

       ۱                  |   ۱         |  'GBP'    | '2018-03-11'
       ۲                  |   ۲         |  'EUR'    | '2018-03-12'
       ۳                  |   ۲         |  'GBP'    | '2018-03-12'

I’m looking to create a select statement a table that lists all transactions in it.

 local_id   | international_id |  item_id | item_name | item_cost | currency | date

 ۱          | null             |  1       | Water     | 1.00      | null     | '2018-03-12'
 ۲          | null             |  1       | Water     | 1.00      | null     | '2018-03-13'
 ۳          | null             |  2       | Chips     | 1.50      | null     | '2018-03-13'
 null       | 1                |  1       | Water     | 1.00      | 'GBP'    | '2018-03-11'
 null       | 2                |  2       | Chips     | 1.50      | 'EUR'    | '2018-03-12'
 null       | 3                |  2       | Chips     | 1.50      | 'GBP'    | '2018-03-12'

items should be joined to either trans_local or trans_international. I know I can do this with LEFT OUTER JOIN, but I am unsure how to get results of all transactions together. I believe it would be a FULL JOIN but getting everything together is confusing me a bit. Any help would be greatly appreciated.

لینک منبع

grep – How to hightlight text search results like google?

The following is one way to hightlight grep results with n context characters. And each match is broken into a line.

Google is more intelligent, such that it shows the match separated by .... Also, sometimes it respect sentence boundary. Is there any code that grep text by hightlight matches similar to the google way?

لینک منبع

java – Connect Custom Adapter to AsyncTask and show results in GridView

Hi guys I got lost here when I want to create custom adapter and show all results in GridView. I have lots of methods and I think some of them might be optional.
The program executes AsyncTask in Main Activity:

 private class RetrieveData extends AsyncTask<Void, Void, String>{

    protected String doInBackground(Void... voids) {
        String stringURL = "http://xyz";
        URL url = null;
        StringBuffer stringBuffer = new StringBuffer();

        try {
            url = new URL(stringURL);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            InputStream inputStream = connection.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            String line = "";

            while((line = bufferedReader.readLine()) != null){


        } catch (IOException e) {

        return stringBuffer.toString();

    protected void onPostExecute(String result) {

        String username, name;
        ArrayList<HashMap<String, String>> location = null;
        int i;

        try {
            JSONArray data = new JSONArray(result);
            location = new ArrayList<>();
            HashMap<String, String> map;

            for(i = 0; i < data.length(); i++){
                JSONObject object = data.getJSONObject(i);

                map = new HashMap<>();
                map.put("username", object.getString("username"));
                map.put("name", object.getString("name"));

        } catch (JSONException e) {

        if(location != null){
            for(i = 0; i < location.size(); i++){
                username = location.get(i).get("username").toString();
                name = location.get(i).get("name").toString();

                //Here is my class with getters and setters, passing all 
                //details to the constructor
                new Product(username, name);


In the last line of code above I pass data to the constructor to keep all details.

That is my product class which gets all products:

public class Product {
private String username;
private String name;

public Product(String username, String name) {
    this.username = username; = name;


public String getUsername() {
    return username;

public void setUsername(String username) {
    this.username = username;

public String getName() {
    return name;

public void setName(String name) { = name;

Here is my Custom Adapter:

public class ProductCustomAdapter extends BaseAdapter {
Context context;
ArrayList<Product> products;
private static LayoutInflater layoutInflater = null;

public ProductCustomAdapter(Context context, ArrayList<Product> products){
    this.context = context;
    this.products= products;
    layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

public int getCount() {
    return meals.size();

public Object getItem(int position) {
    return position;

public long getItemId(int position) {
    return position;

public View getView(int position, View convertView, ViewGroup parent) {
    if(convertView == null){
        convertView = layoutInflater.inflate(R.layout.main_grid_layout, null);

        TextView username = (TextView) convertView.findViewById(;
        TextView name= (TextView) convertView.findViewById(;

        return convertView;
    return null;

Now I want the data retrieved in MainActivity to be displayed in one of the fragments:

public class HomeFragment extends Fragment {

private GridView mainGridView;
private List<Product> products = new ArrayList<>();

public static HomeFragment newInstance() {
    HomeFragment fragmentHome = new HomeFragment();
    return fragmentHome;

public void onCreate(Bundle savedInstanceState) {

public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_home, container, false);

    mainGridView = (GridView) view.findViewById(;

    return view;

public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    mainGridView = (GridView) view.findViewById(;
    ProductCustomAdapter productsadapter = new ProductCustomAdapter(getActivity().getApplicationContext(), getProducts());

private ArrayList<Product> getProducts(){
    return null;


I think there is a shorter way to pass data but right now I am lost because I have to deal with many ArrayLists.
Can anybody think of most efficient solution?

لینک منبع

r – Draw scatterplot of class results in exam

I am trying to draw a scatterplot which shows the percentage of marks gained for each student per question, and calculate the averages for the whole class.

maxmarks.paper <- c(4,5,2,4,3,4,5,4,6,3,3,5,3,4,4,4,3,3,2,5,4)

results.student1 <- c(4,3,2,3,3,4,5,4,3,3,0,0,2,4,1,1,2,0,1,0,0)
results.student2 <- c(2,2,0,4,1,1,0,1,4,2,0,0,1,0,0,2,0,0,1,1,0)

percentage1 <- results.student1 / maxmarks.paper * 100
percentage2 <- results.student2 / maxmarks.paper * 100

I was looking at this tutorial, but I do not understand how this works.

plot(x = ...

Can someone help plot the scattergraph?

لینک منبع

html – function for calculator not returning results (Javascript)

I’m trying to find out why my math function isn’t returning the results to the screen. I think there maybe a problem with my switch statements but it looks fine to me. I converted the strings to numbers than I’m passing to the switch function to do the math for me. I’m only testing it with the numbers 1 and 2, and only the + and = operator are set. It works with storing the strings and displaying them but I’m not able to get my function to do all the calculation to work properly.

         var prevNum = "";
        var currNum = "";
       var setNumber;
     var resultNum;
  var operator;

    function display(x){
   var screen = document.getElementById("display");

if(resultNum) { //reset result Numbers

resultNum = "";    

else {
    currNum += x;
     screen.value = currNum;   


 function math(){
//converts string to number
prevNum = parseFloat(prevNum);
currNum = parseFloat(currNum);

     switch(operator) {
   case "+":
   resultNum = prevNum + currNum;

   case "-":
   resultNum = prevNum + currNum;

    case "*":
   resultNum = prevNum + currNum;

        resultNum = currNum;


screen.value = resultNum;   


   //store number
     function storeNum(x) {

prevNum = currNum;
operator = x;
currNum = "";


<div class="container">
    <div id="screen">
        <input type="text" id="display" disabled>
        <p id="result"></p>
<div id="keypad">  
<input type="button" value="C">
<input type="button" value="CE" onclick="clear()">
<input type="button" value="^">
<input type="button" value="+" onclick="storeNum('+')">   
<input type="button" value="9">
<input type="button" value="8">
<input type="button" value="7">
<input type="button" value="-">   
<input type="button" value="6">
<input type="button" value="5">
<input type="button" value="4">
<input type="button" value="*">
<input type="button" value="3">
<input type="button" value="2" onclick="display('2')">
<input type="button" value="1" onclick="display('1')">
<input type="button" value="/">
<input type="button"  value="0">
<input type="button" value=".">
<input type="button" value="=" onclick="math()">

لینک منبع

json – angularjs get results in error with a 200 response

I am making a url request to a public url to get some data. For one url it functions but for the other it does not.
I have no control over the server side.

The url returns with 200 but angular passes it to the error function. In my browser console the data is there, as JSON, but I do not have access to it in Angular. I was thinking it might the the http.get calling something before passing the data on.

I have tried with plain $http and a custom transformResponse but it still falls to the error of the custom response.

Any ideas?

This is the URL:

لینک منبع

Printing all dictionary results from For Loop in Python

I am trying to print the results from all 3 names that are input, in a dictionary format. Current code below only prints out the last name. The 2 lines commented out (#) are what I was trying to change around to get it to work, clearly not doing it correctly.

Any ideas?


def name():
                count = 0
                while (count  < 5):
                    d = {}
                    qs = dict(Fname='first name', Lname='last name')
                    for k,v in qs.items():
                                d[k] = input('Please enter your {}: '.format(v))
                                #d['first name'].append(v)
                                #d['last name'].append(v)
                                count += 1


لینک منبع

google spreadsheet – Combine 2 queries (different columns from 2 different sheets) and filter based on matching results

As usual, I have set a goal, way beyond my skills….

I need to get data from 2 sheets. One has a lot more entries than the other (a master list I guess you could say). Any entry in the smaller sheet will always have a matching entry in the Master, but not necessarily the other way round.

I have written what I need in psuedo query syntax, but I need help getting this to work…

QUERY the 'Catalog' sheet and get TITLE, SUBTITLE, STATUS, TITLE-ID WHERE the STATUS does NOT have the word 'Retired' in it.
Then Query 'Report_Dec 2017' and get UNITS, USD, GPB, EUR WHERE TITLE-ID from 'Report_Dec 2017' Matches TITLE-ID from 'Catalog'

Catalog (master)

  | UNITS | USD | GPB | EUR |  (has TITLE-ID also, but dont need this twice) 

Final result should look like this:


The end result should only ever have a max number of entries equal to that of from ‘Report_Nov 2017’. So the Catalog might have 100 total entries but since only 20 units were sold in November, then the result will only show 20

First of all is that possible? And secondly, if it is, can someone point me in the right direction?

لینک منبع

c# – Searching by checkboxes with if statements in SQL not bringing back correlated results

I am working on an application with about 20 text boxes and 26 checkboxes which is quite a load I know , but is necessary for the task.Currently I am struggling to be able to search by multiple checkboxes at the same time. I was wondering if there would be any easier way to go about this logically without a ton of if statements.

Here is my current SQL select statement:

`string str = "select * from engineering where JobNumber like '%' + @search + '%' AND DateOrdered like '%' + @search1 + '%' AND Title like '%' + @search2 + '%' AND PhysicalAddressComplete like '%' + @search3 + '%' AND County like '%' + @search4 + '%' AND Client like '%' + @search5 + '%' AND Contact like '%' + @search6 + '%' AND ContactTitle like '%' + @search7 + '%' AND MailingAddressComplete like '%' + @search8 + '%' AND BusinessPhone like '%' + @search9 + '%' AND CellPhone like '%' + @search10 + '%' AND Email like '%' + @search11 + '%' AND OpenStatus like '%' + @search12 + '%' AND CloseStatus like '%' + @search13 + '%' AND Cabinet like '%' + @search14 + '%' AND Roll like '%' + @search15 + '%' AND Drawer like '%' + @search16 + '%' AND ConstructionDrawings like '%' + @search17 + '%' AND Fee like '%' + @search18 + '%' AND ConstructionCost like '%' + @search19 + '%' AND ProjectDescription like '%' + @search20 + '%' ";
            if (chkEducational.Checked)
                str += "AND Education = @Education";
            else if (chkMedical.Checked)
                str += "AND Medical = @Medical";
            else if (chkReligious.Checked)
                str += "AND Religious = @Religious";
            else if (chkMulti.Checked)
                str += "AND MultiFamily = @MultiFamily";
            else if (chkStudent.Checked)
                str += "AND Student = @Student";
            else if (chkAssisted.Checked)
                str += "AND Assisted = @Assisted";
            else if (chkSingleFamily.Checked)
                str += "AND Single = @Single";
            else if (chkBridge.Checked)
                str += "AND Bridge = @Bridge";
            else if (chkIntersection.Checked)
                str += "AND Intersection = @Intersection";
            else if (chkRoadway.Checked)
                str += "AND Roadway = @Roadway";
            else if (chkDesign.Checked)
                str += "AND DesignBuild = @DesignBuild";
            else if (chkTransOther.Checked)
                str += "AND TransportationOther = @TransportationOther";
            else if (chkRetailSmall.Checked)
                str += "AND SmallRetail = @SmallRetail";
            else if (chkRetailLarge.Checked)
                str += "AND LargeRetail = @LargeRetail";
            else if (chkParks.Checked)
                str += "AND Parks = @Parks";
            else if (chkIndustrial.Checked)
                str += "AND Industrial = @Industrial";
            else if (chkUtility.Checked)
                str += "AND Utility = @Utility";
            else if (chkGCSmall.Checked)
                str += "AND GCSmall = @GCSmall";
            else if (chkGCLarge.Checked)
                str += "AND GCLarge = @GCLarge";
            else if (chkOffice.Checked)
                str += "AND Office = @Office";
            else if (chkOther.Checked)
                str += "AND Other = @Other";
            else if (chkMunicipal.Checked)
                str += "AND Municipal = @Municipal";
            else if (chkPrivate.Checked)
                str += "AND Privates = @Privates";
            else if (chkInstitutional.Checked)
                str += "AND Institutional = @Institutional";
            else if (chkMilitary.Checked)
                str += "AND Military = @Military";
            else if (chkArchive.Checked)
                str += "AND Archived = @Archived";`

This statement works as I am able to search by any amount of text as well as checkboxes however when it comes to checkboxes some records do not correlate to the searches. For example if I was to check the Archive checkbox along with the Military Checkbox , I would want the results to be only those with BOTH of those boxes checked, however when I do this with my code I also get the records with only the military box checked as well. It seems as if the Else If statement acts as a pecking order. Any help would be appreciated.

لینک منبع