text:
Q: Fair way to split fees So I have a very simple problem, but I am unable to find a proper solution top it.
Four friends rented and apartment for 1 year. They paid \$590 of deposit each (\$2360 total).
By the end of the year, they received \$1470 back from their landlord because there were some unexpected bills. They calculated that each one was responsible for 44%, 34%, 15% and 7% of that extra charge (imagine the difference is in extra energy consumption or damages for example).
If they were to divide the deposit in 4 equal parts, they each would get \$367,5 (\$1470/4), but that is not fair as one of them only overspent 7% .
What would be the fair value each one should receive?
(I'm sorry for the probably wrong tags, I didn't know which to pick)
Thanks

A: The overage is $\$890$ ($2360-1470=890$).
Suppose I am responsible for $44\%$ of the overage.  That makes $0.44\times\$890=\$391.60.$  Then, I should get back $\$198.40$ (my $\$590$ deposit less the overage for which I am responsible).
Use this method to calculate the rest.


text:
Q: using more than 2 PCs in PCA I want to use PCA algorithm from scratch, but i want to reduce 784 features to about for example 70 features not 2. what i've tried before is this code below.
In this code for part "Choosing k eigenvectors with the largest eigenvalues" how can i choose k?
import numpy as np
from sklearn.preprocessing import StandardScaler
import matplotlib.pyplot as plt
import pandas as pd

data_train = pd.read_csv('trainData.csv',header=None)
label_train = pd.read_csv('trainLabels.csv',header=None)

data_train = StandardScaler().fit_transform(data_train)

# OR we can do this with one line of numpy for COV:
cov_mat = np.cov(data_train.T)

# Compute the eigen values and vectors using numpy
eig_vals, eig_vecs = np.linalg.eig(cov_mat)

# Make a list of (eigenvalue, eigenvector) tuples
eig_pairs = [(np.abs(eig_vals[i]), eig_vecs[:,i]) for i in range(len(eig_vals))]

# Sort the (eigenvalue, eigenvector) tuples from high to low
eig_pairs.sort(key=lambda x: x[0], reverse=True)
for i in eig_pairs:
    print(i[0])

#Choosing k eigenvectors with the largest eigenvalues
matrix_w = np.hstack((eig_pairs[0][1].reshape(784,1), eig_pairs[1][1].reshape(784,1)))
print('Matrix W:\n', matrix_w)
transformed = matrix_w.T.dot(data_train.T)

A: Take a look at how matrix_w is created. The h_stack function takes a tuple of arrays and stacks them horizontally. What you want to do is create a tuple that contains the eigenvectors of the k largest eigenvalues and create the matrix:
eigenvectors = tuple([eig_pairs[i][1].reshape(784,1) for i in range(k)])
matrix_w = np.hstack(eigenvectors)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Typo3 Powermail Prefill Im using Typo3 and got 2 Powermail Forms on a Hotel Page.
One small form on every Page where you can put the checkin and checkout date.
After this you will be redirected to the main form.
How can i prefill the daterecords from the small after the redirect in the mainform?
Both forms have the same variable names {checkin} and {checkout}
Thanks

A: Try it..
 plugin.tx_powermail.settings.setup.prefill {
    # Fill field with marker {current_date}
    current_date = TEXT
    current_date{
      data = date : U
      strftime = %d-%m-%Y %H:%M:%S
    }
    form2date = TEXT
    form2date{
      data = date : U
      strftime = %d-%m-%Y %H:%M:%S
    }

    seminar = CONTENT
    seminar {
      table =   tx_news_domain_model_news
      select.pidInList = 118
      select.where.stdWrap.cObject = TEXT
      select.where.stdWrap.cObject.data = GP:tx_news_pi1|news
      select.where.stdWrap.cObject.wrap = uid = |
      select.where.stdWrap.cObject.insertData =1
      renderObj = COA
      renderObj {
            10 = TEXT
            10.dataWrap ={field:title}

      }
    }

    price = CONTENT
    price {
      table =   tx_news_domain_model_news
      select.pidInList = 118
      select.where.stdWrap.cObject = TEXT
      select.where.stdWrap.cObject.data = GP:tx_news_pi1|news
      select.where.stdWrap.cObject.wrap = uid = |
      select.where.stdWrap.cObject.insertData =1
      renderObj = COA
      renderObj {
            10 = TEXT
            10.dataWrap ={field:price}

      }
    }

    location = CONTENT
    location {
      table =   tx_news_domain_model_news
      select.pidInList = 118
      select.where.stdWrap.cObject = TEXT
      select.where.stdWrap.cObject.data = GP:tx_news_pi1|news
      select.where.stdWrap.cObject.wrap = uid = |
      select.where.stdWrap.cObject.insertData =1
      renderObj = COA
      renderObj {
            10 = TEXT
            10.dataWrap ={field:tx_roqnewsevent_location}
      }
    }

    event_startdate = CONTENT
    event_startdate {
      table =   tx_news_domain_model_news
      select.pidInList = 118
      select.where.stdWrap.cObject = TEXT
      select.where.stdWrap.cObject.data = GP:tx_news_pi1|news
      select.where.stdWrap.cObject.wrap = uid = |
      select.where.stdWrap.cObject.insertData =1
      renderObj = COA
      renderObj {
            10 = TEXT
            10.value.field = tx_roqnewsevent_startdate
            10.value.date = d-m-Y
            #10.strftime = %d-%m-%Y
      }
    }

}

A: Hi try add (width js on submit action) in form action url or redirect url width parametrs [checkin]="" and [checkout]="". Like this
<form class="form-horizontal powermail_form powermail_form_1" action="index.php?id=5&checkin=25.05.15&checkout=25.06.15" method="post">
...

for test try use url "yousite.com/index.php?id=5?checkin=25.05.15&checkout=25.06.15" fields in form must be fill.
Where "5" - your main form page id


text:
Q: How to preserve graph properties under subgraph in MMA9
Possible Duplicate:
Preserving labels when using graph functions

I'm using
g = SocialMediaData["Twitter", "FriendNetwork"]

to get a nice graph with tooltips for the vertices, etc. Next, I get the weakly connected components via
wcc = WeaklyConnectedComponents[g]

and then I do
sg = Subgraph[g, wcc[[1]]]

to get the largest component. But, all the properties are gone in sg, i.e. I no longer have the tooltips, etc.
Any suggestions?

A: Found it!
Subgraph[g, wcc[[1]], Options[g]]


text:
Q: Php - trying to add li to current list but not getting the LI Trying this: - UPDATE -- SOOORRY!

Home

<?php
        if (the_title() == "language-translation")
           print("
Become a Volunteer
");
     ?>

<?php the_title(); ?>

All I get is the TEXT ('Become a volunteer') and not the LI item...(or the anchor for that matter) ?  -- Forgive me but I pasted a mistake.. this is STILL not working above.
I get the TEXT regardless of whether the if is true or not and never get the LI and A

A: You are closing the PHP tag at the end of the if statement. Remove the end "?>"
if (the_title() == "language-translation") ?>

A: try
if (the_title() == "language-translation") ?>

*Become a Volunteer
reason it doesnt work is because you ended PHP before you enter print (a PHP command)


text:
Q: JavaFX editable table cell having display errors Editing the question as per Brian's suggestion:
I have now trimmed it down to just a single integer column.
I am simply not able to find the problem in the code. THe values show up only when the columns are selected once for edit.
Please suggest of i am making some mistake in the EditingCell class.
The single classfile code that i am trying is as follows.
package javafxtest;

import javafx.application.Application;
import static javafx.application.Application.launch;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.EventHandler;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableColumn.CellEditEvent;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
//import javafx.scene.control.cell.CheckBoxTableCell;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.stage.Stage;
import javafx.util.Callback;

/**
 * FXML Controller class
 *
 * @author balz
 */
public class UploadTemplateController extends Application {

    @Override public void start(Stage primaryStage) throws Exception {
        init(primaryStage);
        primaryStage.show();
    }
    public static void main(String[] args) { launch(args); }

    private void init(Stage primaryStage) {
        Group root = new Group();
        primaryStage.setScene(new Scene(root));
        MasterUploadParameter objMasterUploadParameter=new MasterUploadParameter();
        MasterUploadParameter objMasterUploadParameter1=new MasterUploadParameter();
        MasterUploadParameter objMasterUploadParameter2=new MasterUploadParameter();

        final ObservableList<MasterUploadParameter> tableContent =
            FXCollections.observableArrayList
            (
                objMasterUploadParameter,
                objMasterUploadParameter1,
                objMasterUploadParameter2
            );

        TableColumn ColumnID = new TableColumn();
        ColumnID.setText("columnId");
        ColumnID.setCellValueFactory(new PropertyValueFactory("columnId"));

        Callback<TableColumn, TableCell> cellFactory =
                new Callback<TableColumn, TableCell>() {

                    public TableCell call(TableColumn p) {

                        return new EditingCell();
                    }
                };
        ColumnID.setCellFactory(cellFactory);

        TableView tableView = new TableView();
        tableView.setItems(tableContent);
        //Enabling editing
        tableView.setEditable(true);
        tableView.getColumns().addAll(ColumnID);
        root.getChildren().add(tableView);
    }

    private void updateObservableListProperties(TableColumn<MasterUploadParameter, Integer> ColumnFieldNo, TableColumn<MasterUploadParameter, Boolean> ColumnLPad, TableColumn<MasterUploadParameter, Integer> ColumnStarting, TableColumn<MasterUploadParameter, Integer> ColumnEnding, TableColumn<MasterUploadParameter, String> ColumnSheetID, TableColumn<MasterUploadParameter, Integer> ColumnID, TableColumn<MasterUploadParameter, Integer> ColumnStartingRow, TableColumn<MasterUploadParameter, Integer> ColumnEnding0) {
        ColumnFieldNo.setOnEditCommit(new EventHandler<CellEditEvent<MasterUploadParameter, Integer>>() {
            @Override public void handle(CellEditEvent<MasterUploadParameter, Integer> t) {
                ((MasterUploadParameter) t.getTableView().getItems().get(
                        t.getTablePosition().getRow())).setcolumnId(new SimpleIntegerProperty(t.getNewValue()));
            }
        });

    }
    public static class MasterUploadParameter {
        private SimpleIntegerProperty columnId;
        public SimpleIntegerProperty columnIdProperty() {return columnId;}
        public void setcolumnId(SimpleIntegerProperty columnId) {this.columnId = columnId;}

        public MasterUploadParameter() {
            this.columnId=new SimpleIntegerProperty(0);
        }
    }
    // EditingCell - for editing capability in a TableCell
    public static class EditingCell extends TableCell<MasterUploadParameter, Integer> {
        private TextField textField;

        public EditingCell() {
            System.out.println("find value of textField: "+textField);
        }

        @Override public void startEdit() {
            super.startEdit();
            System.out.println("find value of textField: "+textField);
            if (textField == null) {
                createTextField();
            }
            setText(null);
            setGraphic(textField);
            textField.selectAll();
        }

        @Override public void cancelEdit() {
            super.cancelEdit();
            setText(String.valueOf(getItem()));
            setGraphic(null);
        }

        public void updateItem(Integer item, boolean empty) {
            System.out.println("find value of update: "+empty+item);
            super.updateItem(item, empty);
            if (empty) {
                setText(null);
                setGraphic(null);
            } else {
                if (isEditing()) {
                    if (textField != null) {
                        textField.setText(getString());
                    }
                    setText(null);
                    setGraphic(textField);
                } else {
                    setText(getString());
                    setGraphic(null);
                }
            }
        }

        private void createTextField() {
            textField = new TextField(getString());
            textField.setMinWidth(this.getWidth() - this.getGraphicTextGap() * 2);
            textField.setOnKeyReleased(new EventHandler<KeyEvent>() {
                @Override public void handle(KeyEvent t) {
                    if (t.getCode() == KeyCode.ENTER) {
                        commitEdit(Integer.parseInt(textField.getText()));
                    } else if (t.getCode() == KeyCode.ESCAPE) {
                        cancelEdit();
                    }
                }
            });
        }

        private String getString() {
            return getItem() == null ? "" : getItem().toString();
        }

    }

}

A: You don't need separate editing cell types.  You can use the col.setOnEditCommit method
Just use public static class EditingCell extends TableCell{  with no type information.  (I guess that's why you left out @override before.)
Change the updateItem to @Override public void updateItem(Object item, boolean empty) {
Then whenever you call commitEdit use a string (all textfields have strings anyway).  commitEdit(textField.getText())
Then for each column depending, on the type you can commit the edit however you want.
import javafx.application.Application;
import static javafx.application.Application.launch;
import javafx.application.Platform;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.Event;
import javafx.event.EventHandler;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableColumn.CellEditEvent;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
//import javafx.scene.control.cell.CheckBoxTableCell;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.stage.Stage;
import javafx.util.Callback;

/**
 * FXML Controller class
 *
 * @author balz
 */
public class UploadTemplateController extends Application {

    @Override public void start(Stage primaryStage) throws Exception {
        init(primaryStage);
        primaryStage.show();
    }
    public static void main(String[] args) { launch(args); }

    private void init(Stage primaryStage) {
        Group root = new Group();
        primaryStage.setScene(new Scene(root));
        MasterUploadParameter objMasterUploadParameter=new MasterUploadParameter();
        MasterUploadParameter objMasterUploadParameter1=new MasterUploadParameter();
        MasterUploadParameter objMasterUploadParameter2=new MasterUploadParameter();

        final ObservableList<MasterUploadParameter> tableContent =
            FXCollections.observableArrayList
            (
                objMasterUploadParameter,
                objMasterUploadParameter1,
                objMasterUploadParameter2
            );

        Callback<TableColumn, TableCell> cellFactory = new Callback<TableColumn, TableCell>() {
            public TableCell call(TableColumn p) {
                return new EditingCell();
            }
        };

        TableColumn ColumnID = new TableColumn();
        ColumnID.setText("columnId");
        ColumnID.setCellValueFactory(new PropertyValueFactory("columnId"));
        ColumnID.setCellFactory(cellFactory);
        ColumnID.setOnEditCommit(new EventHandler<CellEditEvent<MasterUploadParameter, String>>() {
            @Override
            public void handle(CellEditEvent<MasterUploadParameter, String> evt) {
                try {
                    evt.getTableView().getItems().get(evt.getTablePosition().getRow())
                            .columnId.set(Integer.parseInt(evt.getNewValue()));
                } catch (NumberFormatException numberFormatException) {
                    //do whatever if a non int is entered
                }
            }
        });

        TableColumn columnDesc = new TableColumn("Desc");
        columnDesc.setCellValueFactory(new PropertyValueFactory("desc"));
        columnDesc.setCellFactory(cellFactory);
        columnDesc.setOnEditCommit(new EventHandler<CellEditEvent<MasterUploadParameter, String>>() {
            @Override
            public void handle(CellEditEvent<MasterUploadParameter, String> evt) {
                evt.getTableView().getItems().get(evt.getTablePosition().getRow())
                        .desc.set(evt.getNewValue());
            }
        });

        TableView tableView = new TableView();
        tableView.setItems(tableContent);
        //Enabling editing
        tableView.setEditable(true);
        tableView.getColumns().addAll(ColumnID, columnDesc);
        root.getChildren().add(tableView);
    }

    public static class MasterUploadParameter {
        private SimpleIntegerProperty columnId;
        public SimpleIntegerProperty columnIdProperty() {return columnId;}

        private StringProperty desc;
        public StringProperty descProperty() {return desc;}

        public MasterUploadParameter() {
            this.columnId=new SimpleIntegerProperty(0);
            this.desc = new SimpleStringProperty("hi");
        }
    }
    // EditingCell - for editing capability in a TableCell
    public static class EditingCell extends TableCell{
        private TextField textField;

        @Override public void startEdit() {
            if (!isEmpty()) {
                super.startEdit();
                createTextField();
                setText(null);
                setGraphic(textField);
                textField.selectAll();
                Platform.runLater(new Runnable() {
                    @Override
                    public void run() {
                        textField.requestFocus();
                    }
                });
            }
        }

        @Override public void cancelEdit() {
            super.cancelEdit();

            try {
                setText(getItem().toString());
            } catch (Exception e) {
            }
            setGraphic(null);
        }

        @Override public void updateItem(Object item, boolean empty) {
            System.out.println("find value of update: "+empty+item);
            super.updateItem(item, empty);
            if (empty) {
                setText(null);
                setGraphic(null);
            } else {
                if (isEditing()) {
                    if (textField != null) {
                        textField.setText(getString());
                    }
                    setText(null);
                    setGraphic(textField);
                } else {
                    setText(getString());
                    setGraphic(null);
                }
            }
        }

        private void createTextField() {
            textField = new TextField(getString());
            textField.setMinWidth(this.getWidth() - this.getGraphicTextGap() * 2);
            textField.setOnKeyReleased(new EventHandler<KeyEvent>() {
                @Override public void handle(KeyEvent t) {
                    if (t.getCode() == KeyCode.ENTER) {
                        commitEdit(textField.getText());
                    } else if (t.getCode() == KeyCode.ESCAPE) {
                        cancelEdit();
                    }
                }
            });
        }

        private String getString() {
            return getItem() == null ? "" : getItem().toString();
        }

    }

}


text:
Q: Adding invokestatic to java/lang/Object. via JVM TI agent causes JVM to crash with segfault I am trying to track allocations of all objects in JVM.
In the several documents about allocation profilers it was mentioned that the easiest way to do so is this:
add invokestatic Tracker.trackAllocation()V instruction to java/lang/Object.<init> (normally it consists of a single return instruction, we add invokestatic before it, so it is 2 instructions now).
(I know that this approach is slow and will not track array allocations, but I wanted to start with simplest solution. Also I don't pass reference to the allocated object to tracker, but this will be added later.)
Class file is instrumented with JVM TI agent in onClassLoaded hook.
However, after adding invokestatic instruction JVM crashes with segfault.
Tracker object is added to bootstrap classloader, so it should be visible at any stage.
I tried adding nop instead of invokestatic, and JVM works fine with the modified Object class. So the problem is specifically with the invocation of some static method.
I also tried to instrument application (not part of base) classes and it worked fine - tracker was called and no crashes happened.
Also I tried redefining Object at 2 points: when it is initially loaded (first loaded class), or after vmInit event (when all base classes are loaded and restrictions on jni are lifted).
Is there anything I am missing about instrumenting java.lang.Object?
Code for the agent is here:
https://gist.github.com/Korobochka/3bf2f906f6ab85b22dec
(Error checking is stripped, code for changing classes is also not included, but it works well enough for other classes)

A: Looks like the problem is in calling System.out.println from LeakAgentInterface. First of all, System.out may not be initialized yet. Second, println may allocate objects itself.


text:
Q: R equivalent for numpy 'frombuffer' To decode a binary answer from a socket connection in Python I would do :
import numpy as np

answer= b"\x80\x8eaS\x00\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x80\x8eaS\x00\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00"

datatype = [('da_0', '<i8'), ('i8_1', '<i8')]

np.frombuffer(answer, datatype)

which outputs
>>>array([(1398902400, 1), (1398902400, 1)],
  dtype=[('da_0', '<i8'), ('i8_1', '<i8')])

I have been battling with the unpack() function (from {pack}) in R to reproduce the same result but unsuccessfully until now.
Any idea would be much appreciated !

A: In R, you can use readBin on a connection, or on a raw vector
answer=as.raw(c(
0x80,0x8e,0x61,0x53,0x00,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x80,0x8e,0x61,0x53,0x00,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x00,0x00,0x00,0x00))

readBin(answer[1:16],"integer", size=8,n=2, endian="little")
# [1] 1398902400          1
readBin(answer[17:32],"integer", size=8, n=2, endian="little")
# [1] 1398902400          1

If your response is in a connection object then you wouldn't have to worry about the indexing to extract the correct portion of the raw vector. You could just read from the binary connection and it will keep track of indexing.


text:
Q: Jquery text not parsing into variable I have a code where I want a button's text to be stored in a variable and then set a text field's value to the text. Here's my code for the button onclick event:
$('#MyButton').click(function(){
        var user1 = $(this).attr("value");
        $('#MyTextField').val(user1);
    });

And Here is my button and text field:
<input type="text" class="form-control" id="MyTextField" aria-label="..." placeholder="User to send to">
 <button id="MyButton" class="btn btn-success" value="Go!">GO</button>

But nothing ever happens.
Please help,
Thanks in advance
EDIT regarding @Drakes

That is my script and here is how I have included JQuery:

A: The code you posted is working with this scaffolding. When the "GO" button is clicked, "Go!" appears in the text input. Please make sure jQuery is included, and the MyButton button isn't dynamically created after the page loads.

  <input type="text" class="form-control" id="MyTextField" aria-label="..." placeholder="User to send to">
  <button id="MyButton" class="btn btn-success" value="Go!">GO</button>

A: To handle events for dynamically added elements, you can use event delegation. You would need to bind the event to a containing element that exists from start.
If you have multiple elements, then the id doesn't work to identify them as it has to be unique, you would use a class instead.
To find the input element you would need to traverse the DOM to find the one next to the button.
Example:
$('#ButtonContainer').on('click', '.MyButton', function(){
    var user1 = $(this).val();
    $(this).prev().val(user1);
});

Make sure that the buttons has a class that you can use to recognise them. Example:

  <input type="text" class="form-control" aria-label="..." placeholder="User to send to">
  <button class="MyButton btn btn-success" value="Go!">GO</button>
  <input type="text" class="form-control" aria-label="..." placeholder="User to send to">
  <button class="MyButton btn btn-success" value="Go!">GO</button>
  <input type="text" class="form-control" aria-label="..." placeholder="User to send to">
  <button class="MyButton btn btn-success" value="Go!">GO</button>

Demo, using dynamically added elements:

$('#ButtonContainer').on('click', '.MyButton', function(){
    var user1 = $(this).val();
    $(this).prev().val(user1);
});

$('#ButtonContainer').append('<input type="text" class="form-control" aria-label="..." placeholder="User to send to"><button class="MyButton btn btn-success" value="Go!">GO</button>');
$('#ButtonContainer').append('<input type="text" class="form-control" aria-label="..." placeholder="User to send to"><button class="MyButton btn btn-success" value="Go!">GO</button>');
$('#ButtonContainer').append('<input type="text" class="form-control" aria-label="..." placeholder="User to send to"><button class="MyButton btn btn-success" value="Go!">GO</button>');


text:
Q: How to return sender from Jquery autocomplete I use Jquery Autocomplete in my mvc3 application. I have a lot of textbox, and i try to do it smart :)
I need to return autocomplete field property  to controler. like that:

 @Html.ValidationMessageFor(m => m.some_prop)

@Html.TextBoxFor(m => m.some_prop, new {
 id = "some_id", @class = "AutoC" })

But allways i get null.

A: Ok i get it :
     </script>


text:
Q: C lang task - how to optimize my code for performance. My time complexity is O(N^2) My solution of this task is (i assume) time complexity O(N^2). Obviously my code is not handling well large arrays. How could I make this more efficient? What am I missing? Could you guys recommend some material that could help me understand how to write more efficient code in C? Thanks!
Task:

A non-empty array A consisting of N integers is given. Array A represents numbers on a tape.
Any integer P, such that 0 < P < N, splits this tape into two non-empty parts: A[0], A[1], ..., A[P − 1] and A[P], A[P + 1], ..., A[N − 1].
The difference between the two parts is the value of: |(A[0] + A[1] + ... + A[P − 1]) − (A[P] + A[P + 1] + ... + A[N − 1])|
In other words, it is the absolute difference between the sum of the first part and the sum of the second part.
For example, consider array A such that:
 A[0] = 3
 A[1] = 1
 A[2] = 2
 A[3] = 4
 A[4] = 3

We can split this tape in four places:
P = 1, difference = |3 − 10| = 7
P = 2, difference = |4 − 9| = 5
P = 3, difference = |6 − 7| = 1
P = 4, difference = |10 − 3| = 7

Write a function:
int solution(int A[], int N);

that, given a non-empty array A of N integers, returns the minimal difference that can be achieved.
For example, given:
 A[0] = 3
 A[1] = 1
 A[2] = 2
 A[3] = 4
 A[4] = 3

the function should return 1, as explained above.
Write an efficient algorithm for the following assumptions:

*

*N is an integer within the range [2..100,000];

*each element of array A is an integer within the range [−1,000..1,000].

My solution:

#include <stdint.h>
#include <stdlib.h>

int solution(int A[], int N) {

    uint32_t p = 1, i=0;
    int64_t lowestSum = 0, sum1 = 0, sum2 = 0, sum = 0;

    {
        // iterate over all possible values of P
        for(p=1; p<N; p++)
        {
            sum1 = 0;
            sum2 = 0;

            for(i=0; i<N; i++)
            {
                if(i<p)
                {
                    sum1 += A[i];
                }
                else
                {
                    sum2 += A[i];
                }
            }

            sum = abs(sum1 - sum2);

            //if this is the first iteration,
            //initialize the lowest sum with current sum
            if(p==1)
            {
                lowestSum = sum;
            }
            else if(lowestSum > sum)
            {
                lowestSum = sum;
            }
        }
    }

    return lowestSum;
}

A: The data constraints show that the maximum sum of the inputs is 100000 * 1000 = 100000000 which can fit a 32-bit int.
I suggest that if the data is coming from a stream, all you need is to store the running sum of the values in a first pass, and figure out the answer in a second pass.
This is O(N).
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>

int main(void)
{
    int n = 0;
    int sum = 0;
    scanf("%d", &n);
    int *left = malloc(n * sizeof *left);

    for(int i = 0; i < n; i++) {
        int val;
        scanf("%d", &val);
        sum += val;
        left[i] = sum;
    }

    int mindiff = INT_MAX;
    for(int i = 0; i < n; i++) {
        int right = sum - left[i];
        int diff = abs(left[i] - right);
        if(diff < mindiff) {
            mindiff = diff;
        }
    }
    printf("mindiff = %d\n", mindiff);
    free(left);
    return 0;
}

For the specified input
5
3 1 2 4 3

The output is
mindiff = 1

I realise the program is devoid of any error checking, which isn't great, but it does show the algorithm.

A: Based on advices provided by Weather Vane and  Jonathan Leffler I was able to comeup with this solution, which was given 100% result. The lesson learned is to simply try avoid O(N^2) solutions at any cost. I wish I could train my mind to see these solutions (faster).
#include <stdint.h>
#include <stdlib.h>

int solution(int A[], int N) {

    int64_t LeftRight[N], sum = 0;
    int64_t lowest_diff = 0, diff = 0;
    uint32_t i = 0;

    for(i=0; i<N; i++)
    {
        sum += A[i];
        LeftRight[i] = sum;
    }

    sum = 0;
    i = N - 1;

    while(i > 0)
    {
        sum += A[i];
        diff = abs(LeftRight[i-1]-sum);
        //is this first elemnt on the right?
        if(i == (N-1))
        {
            lowest_diff = diff;
        }
        else if(lowest_diff > diff)
        {
            lowest_diff = diff;
        }
        i--;
    }

    return lowest_diff;
}

A: Here is some fairly fancy code I developed, but the core algorithm uses O(1) space and O(N) time for the analysis, making just 2 passes over the data.
This program takes an optional -v argument to print a verbose analysis of its working.  It uses my normal error handling code which is available in my SOQ (Stack Overflow Questions) repository on GitHub as files stderr.c and stderr.h in the src/libsoq sub-directory.  I find that it makes error handling much easier, so I'm more inclined to actually do the necessary error checking.  It checks that the input meets the conditions and reports errors (and bails out) if the data is invalid.  It adapts the detailed layout of the verbose data to keep columns aligned.
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include "stderr.h"

static const char optstr[] = "vh";
static const char usestr[] = "[-vh]";
static const char hlpstr[] =
    "  -h  Print this help message and exit\n"
    "  -v  Print details of calculation as it is done\n"
    ;

static int solution(int A[], int N);

static int vflag = 0;
static int n_width = 0;
static int s_width = 0;

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

    int opt;
    while ((opt = getopt(argc, argv, optstr)) != -1)
    {
        switch (opt)
        {
        case 'v':
            vflag = 1;
            break;
        case 'h':
            err_help(usestr, hlpstr);
            /*NOTREACHED*/
        default:
            err_usage(usestr);
            /*NOTREACHED*/
        }
    }

    if (optind != argc)
        err_usage(usestr);

    int N;
    if (scanf("%d", &N) != 1)
        err_error("failed to read array size\n");
    if (N < 2 || N > 100000)
        err_error("array size %d out of range 2..100,000\n", N);

    /* VLA - but size was checked and won't overflow stack */
    int array[N];

    for (int i = 0; i < N; i++)
    {
        if (scanf("%d", &array[i]) != 1)
            err_error("failed to read element %d of array\n", i);
        if (array[i] < -1000 || array[i] > +1000)
            err_error("element %d (%d) is out of range -1000..+1000\n", i, array[i]);
    }

    n_width = snprintf(0, 0, "%d", N - 1);
    s_width = snprintf(0, 0, "%d", (N - 1) * -1000);

    int result = solution(array, N);

    printf("result: %d\n", result);
    return 0;
}

static inline int abs_diff(int a, int b)
{
    return abs(a - b);
}

static int solution(int A[], int N)
{
    int total = 0;

    /* First pass over array - O(N) */
    for (int i = 0; i < N; i++)
        total += A[i];

    if (vflag)
        printf("N = %d; total = %d\n", N, total);

    /* Second pass over array - O(N) */
    int lhs = A[0];
    int min_gap = abs_diff(lhs, total - lhs);
    if (vflag)
    {
        printf("A[%*d] = %5d: lhs = %*d, rhs = %*d, |lhs - rhs| = %*d ** minimum so far\n",
               n_width, 0, A[0], s_width, lhs, s_width, total - lhs,
               s_width, abs_diff(lhs, total - lhs));
    }
    for (int i = 1; i < N; i++)
    {
        lhs += A[i];
        int diff = abs_diff(lhs, total - lhs);
        if (vflag)
        {
            const char *marker = (diff < min_gap) ? " ** minimum so far" : "";
            printf("A[%*d] = %5d: lhs = %*d, rhs = %*d, |lhs - rhs| = %*d%s\n",
                   n_width, i, A[i], s_width, lhs, s_width, total - lhs,
                   s_width, abs_diff(lhs, total - lhs), marker);
        }
        if (diff < min_gap)
            min_gap = diff;
    }

    return min_gap;
}

For the sample data in the question, the verbose output is:
N = 5; total = 13
A[0] =     3: lhs =     3, rhs =    10, |lhs - rhs| =     7 ** minimum so far
A[1] =     1: lhs =     4, rhs =     9, |lhs - rhs| =     5 ** minimum so far
A[2] =     2: lhs =     6, rhs =     7, |lhs - rhs| =     1 ** minimum so far
A[3] =     4: lhs =    10, rhs =     3, |lhs - rhs| =     7
A[4] =     3: lhs =    13, rhs =     0, |lhs - rhs| =    13
result: 1

Note that there is one more line of output than the analysis in the question shows.
For a 20-line random input, I got:
N = 20; total = 973
A[ 0] =  -360: lhs =   -360, rhs =   1333, |lhs - rhs| =   1693 ** minimum so far
A[ 1] =  -675: lhs =  -1035, rhs =   2008, |lhs - rhs| =   3043
A[ 2] =   245: lhs =   -790, rhs =   1763, |lhs - rhs| =   2553
A[ 3] =    47: lhs =   -743, rhs =   1716, |lhs - rhs| =   2459
A[ 4] =  -100: lhs =   -843, rhs =   1816, |lhs - rhs| =   2659
A[ 5] =   987: lhs =    144, rhs =    829, |lhs - rhs| =    685 ** minimum so far
A[ 6] =    16: lhs =    160, rhs =    813, |lhs - rhs| =    653 ** minimum so far
A[ 7] =  -146: lhs =     14, rhs =    959, |lhs - rhs| =    945
A[ 8] =   126: lhs =    140, rhs =    833, |lhs - rhs| =    693
A[ 9] =  -541: lhs =   -401, rhs =   1374, |lhs - rhs| =   1775
A[10] =  -116: lhs =   -517, rhs =   1490, |lhs - rhs| =   2007
A[11] =   842: lhs =    325, rhs =    648, |lhs - rhs| =    323 ** minimum so far
A[12] =  -769: lhs =   -444, rhs =   1417, |lhs - rhs| =   1861
A[13] =  -361: lhs =   -805, rhs =   1778, |lhs - rhs| =   2583
A[14] =   295: lhs =   -510, rhs =   1483, |lhs - rhs| =   1993
A[15] =  -471: lhs =   -981, rhs =   1954, |lhs - rhs| =   2935
A[16] =   398: lhs =   -583, rhs =   1556, |lhs - rhs| =   2139
A[17] =   932: lhs =    349, rhs =    624, |lhs - rhs| =    275 ** minimum so far
A[18] =   270: lhs =    619, rhs =    354, |lhs - rhs| =    265 ** minimum so far
A[19] =   354: lhs =    973, rhs =      0, |lhs - rhs| =    973
result: 265

For a full 100,000 line input, the output started and ended like this:
N = 100000; total = -53534
A[    0] =  -301: lhs =       -301, rhs =     -53233, |lhs - rhs| =      52932 ** minimum so far
A[    1] =   338: lhs =         37, rhs =     -53571, |lhs - rhs| =      53608
A[    2] =   -35: lhs =          2, rhs =     -53536, |lhs - rhs| =      53538
A[    3] =   243: lhs =        245, rhs =     -53779, |lhs - rhs| =      54024
A[    4] =  -537: lhs =       -292, rhs =     -53242, |lhs - rhs| =      52950
A[    5] =   687: lhs =        395, rhs =     -53929, |lhs - rhs| =      54324
A[    6] =   116: lhs =        511, rhs =     -54045, |lhs - rhs| =      54556
A[    7] =  -257: lhs =        254, rhs =     -53788, |lhs - rhs| =      54042
A[    8] =   288: lhs =        542, rhs =     -54076, |lhs - rhs| =      54618
A[    9] =   592: lhs =       1134, rhs =     -54668, |lhs - rhs| =      55802
A[   10] =  -385: lhs =        749, rhs =     -54283, |lhs - rhs| =      55032
A[   11] =  -254: lhs =        495, rhs =     -54029, |lhs - rhs| =      54524
A[   12] =   816: lhs =       1311, rhs =     -54845, |lhs - rhs| =      56156
A[   13] =  -946: lhs =        365, rhs =     -53899, |lhs - rhs| =      54264
A[   14] =  -477: lhs =       -112, rhs =     -53422, |lhs - rhs| =      53310
A[   15] =   -61: lhs =       -173, rhs =     -53361, |lhs - rhs| =      53188
A[   16] =   225: lhs =         52, rhs =     -53586, |lhs - rhs| =      53638
A[   17] =   174: lhs =        226, rhs =     -53760, |lhs - rhs| =      53986
A[   18] =  -269: lhs =        -43, rhs =     -53491, |lhs - rhs| =      53448
A[   19] =  -408: lhs =       -451, rhs =     -53083, |lhs - rhs| =      52632 ** minimum so far
A[   20] =   123: lhs =       -328, rhs =     -53206, |lhs - rhs| =      52878
A[   21] =   124: lhs =       -204, rhs =     -53330, |lhs - rhs| =      53126
A[   22] =  -364: lhs =       -568, rhs =     -52966, |lhs - rhs| =      52398 ** minimum so far
A[   23] =    41: lhs =       -527, rhs =     -53007, |lhs - rhs| =      52480
A[   24] =  -617: lhs =      -1144, rhs =     -52390, |lhs - rhs| =      51246 ** minimum so far
A[   25] =   583: lhs =       -561, rhs =     -52973, |lhs - rhs| =      52412
A[   26] =  -860: lhs =      -1421, rhs =     -52113, |lhs - rhs| =      50692 ** minimum so far
A[   27] =    39: lhs =      -1382, rhs =     -52152, |lhs - rhs| =      50770
A[   28] =   465: lhs =       -917, rhs =     -52617, |lhs - rhs| =      51700
A[   29] =  -413: lhs =      -1330, rhs =     -52204, |lhs - rhs| =      50874
A[   30] =  -530: lhs =      -1860, rhs =     -51674, |lhs - rhs| =      49814 ** minimum so far
…
A[18048] =   381: lhs =     -27278, rhs =     -26256, |lhs - rhs| =       1022
A[18049] =   510: lhs =     -26768, rhs =     -26766, |lhs - rhs| =          2 ** minimum so far
A[18050] =  -754: lhs =     -27522, rhs =     -26012, |lhs - rhs| =       1510
…
A[99990] =  -196: lhs =     -57461, rhs =       3927, |lhs - rhs| =      61388
A[99991] =   698: lhs =     -56763, rhs =       3229, |lhs - rhs| =      59992
A[99992] =  -141: lhs =     -56904, rhs =       3370, |lhs - rhs| =      60274
A[99993] =   907: lhs =     -55997, rhs =       2463, |lhs - rhs| =      58460
A[99994] =   158: lhs =     -55839, rhs =       2305, |lhs - rhs| =      58144
A[99995] =   563: lhs =     -55276, rhs =       1742, |lhs - rhs| =      57018
A[99996] =   851: lhs =     -54425, rhs =        891, |lhs - rhs| =      55316
A[99997] =   -12: lhs =     -54437, rhs =        903, |lhs - rhs| =      55340
A[99998] =   703: lhs =     -53734, rhs =        200, |lhs - rhs| =      53934
A[99999] =   200: lhs =     -53534, rhs =          0, |lhs - rhs| =      53534
result: 2

I have a convenient random number generator program that can be told to generate N integers between -1000 and +1000 inclusive (and a whole lot more, but that's all that was necessary for this testing).


text:
Q: How to get keypress of the star above the numbers QUESTION:  how to get at the star above the numbers
My FIDDLE  currently does not detect the * above the number row on the keyboard - only the * on the numeric keypad...
On my keyboard it is shift-3 so keyCode 51 + shift. How do I just test for * regardless of what I clicked to get it?

A: The keydown and keyup events are unreliable for detecting specific characters, because the event.which property of these events are not char codes.
The keypress event has to be used. This event may fire multiple times whilst a key is pressed down. So, set a flag when the desired key is pressed, and remove the flag on keyup.
Demo: http://jsfiddle.net/xHnTD/
function something_to_do() {
    // This function is fired when * is pressed.
    $('
Pressed *!
').appendTo('body')
}
$('body').keypress(function(e) {
    var $this = $(this);
    if (e.which === 42) { // '*'.charCodeAt(0) === 42
        if (!$this.data('rw_star_pressed')) {
            $this.data('rw_star_pressed', true);
            something_to_do();
        }
    }
}).keyup(function() {
    $(this).removeData('rw_star_pressed');
});

A: I'm not so sure about the keycodes you posted.
With this code, when I press * I get 56


text:
Q: Get start and end index of word? i want to get the start index and end index of words in a text:
as input i have  :
text= "Hello, this red car is very beautiful and nice. Also, this car is green."
words_list= ["car" , "red","green"]

i want to get the start index and end index of those words in the text please..

A: import re

text= "Hello, this red car is very beautiful and nice. Also, this car is green."
words_list= ["car" , "red","green"]

for word in words_list:
    for m in re.finditer(word,text):
        print (m.group(),m.start(), m.end())

output:
car 16 19
car 59 62
red 12 15
green 66 71

Or with:
print ("key:",m.group(),"start:",m.start(),"end:",m.end())

Output:
key: car start: 16 end: 19
key: car start: 59 end: 62
key: red start: 12 end: 15
key: green start: 66 end: 71

A: While Synthase is correct, there is also a way to do it without importing any modules. This is how I would do it:
text= "Hello, this red car is very beautiful and nice. Also, this car is green."
words_list= ["car" , "red","green"]

for word in words_list:
    if word in text:
        start_index = text.find(word)
        end_index = start_index + len(word)
        print(f"Word: {word}\nStart: {start_index}\nEnd: {end_index}\n")

This outputs:
Word: car
Start: 16
End: 19

Word: red
Start: 12
End: 15

Word: green
Start: 66
End: 71

The code is actually pretty simple.
Line 1 and 2 define our text and our array.
Line 3 starts a for loop that loops for every element in the word list.
Line 4 checks to see if the word is in the text.
If it is, then line 5 gets the start index.
Line 6 gets the end index by adding the length of the word to the start index.
Finally, line 7 prints the information in a neat format.


text:
Q: Is it possible to create in C# a predicate with a custom values, or templated values I am relatively new to C# and come from a C++ background.  I have been looking a list searches and the usages of Find.
I am trying to define a function that takes a parameter, and returns an entry from a list.  for example
class Product
{
    public string id;
    public string description;
}

public List<Product> products = new List<Product>();
// Add some items to the list

My question is, can I turn this following custom "Find" function using C# features like Predicates/Funcs
Product GetProductByID(string id)
{
    foreach (Product p in products)
    {
        if (p.id == id)
        {
            return p;
        }
    }
}

I have tried using Predicates, but I don't seem to be able to find anyway to feed a value in to the function to do the boolean expression check against.  I understand how I would write a Predicate to find a speciic item in a list, but not a dynamic one that could be passed in.
Ideally I would then like to go one step further and Template it so the Predicate could be used for any list of items that have a similar structure.
i.e if we also had
class Employee
{
    public string id;
    public int age;
}

public List<Employee> employees = new List<Employee>();
// Add some items to the list

It would be really cool to use the same defined Predicate, but on this list of a totally different type. Ie something like
// psudo
Predicate<T, string> predicate = return <T>.id == id;

and it work because T is always of a type that has a string member called id
I Hope that all makes sense.

A:
I understand how I would write a Predicate to find a speciic item in a list, but not a dynamic one that could be passed in.

This is where lambda expressions come in, allowing you to create an instance of a delegate type that capture variables in scope. For example:
public Predicate<Product> CreateProductPredicateForId(string id)
{
    return product => product.id == id;
}

Now in terms of making that generic, you'd need to have an interface that specifies an Id property. You can then write a generic method. For example:
public interface IEntity
{
    string Id { get; }
}
...

public Predicate<T> CreatePredicateForId<T>(string id) where T : IEntity
{
    return entity => entity.Id == id;
}

A: (note: throughout this I'm using Func<T, bool> - but the exact same logic applies to Predicate<T> - they have the equivalent signature, but you tend to see more of the former than the latter these days; that said: List<T> uses the latter)
Generics supports this, but via variance rules; you would have to declare an interface of the form:
interface IHazId
{
    int Id { get; }
}
class Foo : IHazId // your types need to implement it, too!
{
    public int Id { get; set; }
}

and then you can use it in a general way:
    void SomeCallingCode()
    {
        // get the predicate, however
        int id = 42;
        Func<IHazId, bool> predicate = obj => obj.Id == id;

        // use it
        SomeTypeSpecificMethod(predicate);
    }
    void SomeTypeSpecificMethod(Func<Foo, bool> predicate)
        => throw new NotImplementedException("not shown");

with the compiler/runtime allowing the Func<IFoo, bool> to satisfy a type-specific Func<Foo, bool> requirement, because it knows that all Foo are IHazId. You can also do this with generics with a constraint:
    void SomeCallingCode()
    {
        // get the predicate, however
        int id = 42;
        Func<IHazId, bool> predicate = obj => obj.Id == id;

        // use it
        SomeGenericMethod<Foo>(predicate);
    }
    void SomeGenericMethod<T>(Func<T, bool> predicate)
        where T : IHazId
        => throw new NotImplementedException("not shown");

However, in reality, this is rarely useful, since in most cases you already know the types, and just want to do:
int id = 42;
SomeTypeSpecificMethod(x => x.Id == id);

Note also that the variance rules that allow you to treat Func<IHazId, bool> as Func<SomeType, bool> only work for reference type SomeType - which is to say: class, not struct.

A: Product GetProductByID(string id)
{
    foreach (Product p in products)
    {
        if (p.id == id)
        {
            return p;
        }
    }
}

this could be replaced with
products.FirstOrDefault(p => p.Id == id)

The second part of you question could be easilly solved with inheritance, like
public class ProductA
{
    public string Id { get; set; }
}

public class ProductB : ProductA
{

}

List<ProductA> a = new List<ProductA>();
List<ProductB> b = new List<ProductB>();

Func<ProductA, bool> findFunction = (p) => p.Id == id;

var p = a.FirstOrDefault(findFunction);
p = b.FirstOrDefault(findFunction);

A: You could use LINQ
Product myProduct = products.Where(p => p.Id == id).FirstOrDefault();

You need using System.Linq; on top of your file to use it.


text:
Q: threads are blocked at the time of loading class via ClassUtils.java My application listen on kafka topic and dump data into cassandra. Threads loads some information from mongo too. Lag in kafka topic getting increased. I have seen that mostly threads are blocked while loading some class. I am attaching my thread_dump below.
 "KafkaConsumer-49" prio=10 tid=0x00007f1178fdd000 nid=0x78e0 waiting for monitor entry [0x00007f1155fb5000]
   java.lang.Thread.State: BLOCKED (on object monitor)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:403)
        - waiting to lock <0x00000006c0655b58> (a java.lang.Object)
        at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:356)
        at org.springframework.util.ClassUtils.forName(ClassUtils.java:258)
        at org.springframework.data.convert.SimpleTypeInformationMapper.resolveTypeFrom(SimpleTypeInformationMapper.java:56)
        at org.springframework.data.convert.DefaultTypeMapper.readType(DefaultTypeMapper.java:103)
        at org.springframework.data.convert.DefaultTypeMapper.getDefaultedTypeToBeUsed(DefaultTypeMapper.java:144)
        at org.springframework.data.convert.DefaultTypeMapper.readType(DefaultTypeMapper.java:121)
        at org.springframework.data.mongodb.core.convert.MappingMongoConverter.read(MappingMongoConverter.java:186)
        at org.springframework.data.mongodb.core.convert.MappingMongoConverter.read(MappingMongoConverter.java:176)
        at org.springframework.data.mongodb.core.convert.MappingMongoConverter.read(MappingMongoConverter.java:172)
        at org.springframework.data.mongodb.core.convert.MappingMongoConverter.read(MappingMongoConverter.java:75)
        at org.springframework.data.mongodb.core.MongoTemplate$ReadDbObjectCallback.doWith(MongoTemplate.java:1840)
        at org.springframework.data.mongodb.core.MongoTemplate.executeFindMultiInternal(MongoTemplate.java:1536)
        at org.springframework.data.mongodb.core.MongoTemplate.doFind(MongoTemplate.java:1336)
        at org.springframework.data.mongodb.core.MongoTemplate.doFind(MongoTemplate.java:1322)
        at org.springframework.data.mongodb.core.MongoTemplate.find(MongoTemplate.java:495)
        at org.springframework.data.mongodb.core.MongoTemplate.find(MongoTemplate.java:486)
        at com.snapdeal.coms.timemachine.mao.TimeMachineMao.getVendorProductsForUploadId(TimeMachineMao.java:32)
        at com.snapdeal.coms.timemachine.service.TimeMachineService.getVendorProductsForUploadIdAndSupc(TimeMachineService.java:35)
        at com.snapdeal.coms.timemachine.event.SupcUploadIdStateUpdateEventHandler.handleEvent(SupcUploadIdStateUpdateEventHandler.java:40)

KafkaConsumer-48" prio=10 tid=0x00007f1178fdb000 nid=0x78df waiting for monitor entry [0x00007f11560b6000]
   java.lang.Thread.State: BLOCKED (on object monitor)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:403)
        - waiting to lock <0x00000006c0655b58> (a java.lang.Object)
        at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:356)
        at org.springframework.util.ClassUtils.forName(ClassUtils.java:258)
        at org.springframework.data.convert.SimpleTypeInformationMapper.resolveTypeFrom(SimpleTypeInformationMapper.java:56)
        at org.springframework.data.convert.DefaultTypeMapper.readType(DefaultTypeMapper.java:103)
        at org.springframework.data.convert.DefaultTypeMapper.getDefaultedTypeToBeUsed(DefaultTypeMapper.java:144)
        at org.springframework.data.convert.DefaultTypeMapper.readType(DefaultTypeMapper.java:121)
        at org.springframework.data.mongodb.core.convert.MappingMongoConverter.read(MappingMongoConverter.java:186)
        at org.springframework.data.mongodb.core.convert.MappingMongoConverter.read(MappingMongoConverter.java:176)
        at org.springframework.data.mongodb.core.convert.MappingMongoConverter.read(MappingMongoConverter.java:172)
        at org.springframework.data.mongodb.core.convert.MappingMongoConverter.read(MappingMongoConverter.java:75)
        at org.springframework.data.mongodb.core.MongoTemplate$ReadDbObjectCallback.doWith(MongoTemplate.java:1840)
        at org.springframework.data.mongodb.core.MongoTemplate.executeFindMultiInternal(MongoTemplate.java:1536)
        at org.springframework.data.mongodb.core.MongoTemplate.doFind(MongoTemplate.java:1336)
        at org.springframework.data.mongodb.core.MongoTemplate.doFind(MongoTemplate.java:1322)
        at org.springframework.data.mongodb.core.MongoTemplate.find(MongoTemplate.java:495)
        at org.springframework.data.mongodb.core.MongoTemplate.find(MongoTemplate.java:486)
        at com.snapdeal.coms.timemachine.mao.TimeMachineMao.getVendorProductsForUploadId(TimeMachineMao.java:32)
        at com.snapdeal.coms.timemachine.service.TimeMachineService.getVendorProductsForUploadIdAndSupc(TimeMachineService.java:35)
        at com.snapdeal.coms.timemachine.event.SupcUploadIdStateUpdateEventHandler.handleEvent(SupcUploadIdStateUpdateEventHandler.java:40)
        at com.snapdeal.coms.timemachine.TimeMachine.onEvent(TimeMachine.java:109)

"KafkaConsumer-47" prio=10 tid=0x00007f1178fd9800 nid=0x78de waiting for monitor entry [0x00007f11561b7000]
   java.lang.Thread.State: BLOCKED (on object monitor)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:403)
        - waiting to lock <0x00000006c0655b58> (a java.lang.Object)
        at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:356)
        at org.springframework.util.ClassUtils.forName(ClassUtils.java:258)
        at org.springframework.data.convert.SimpleTypeInformationMapper.resolveTypeFrom(SimpleTypeInformationMapper.java:56)
        at org.springframework.data.convert.DefaultTypeMapper.readType(DefaultTypeMapper.java:103)
        at org.springframework.data.convert.DefaultTypeMapper.getDefaultedTypeToBeUsed(DefaultTypeMapper.java:144)
        at org.springframework.data.convert.DefaultTypeMapper.readType(DefaultTypeMapper.java:121)
        at org.springframework.data.mongodb.core.convert.MappingMongoConverter.read(MappingMongoConverter.java:186)
        at org.springframework.data.mongodb.core.convert.MappingMongoConverter.read(MappingMongoConverter.java:176)
        at org.springframework.data.mongodb.core.convert.MappingMongoConverter.read(MappingMongoConverter.java:172)
        at org.springframework.data.mongodb.core.convert.MappingMongoConverter.read(MappingMongoConverter.java:75)
        at org.springframework.data.mongodb.core.MongoTemplate$ReadDbObjectCallback.doWith(MongoTemplate.java:1840)
        at org.springframework.data.mongodb.core.MongoTemplate.executeFindMultiInternal(MongoTemplate.java:1536)
        at org.springframework.data.mongodb.core.MongoTemplate.doFind(MongoTemplate.java:1336)
        at org.springframework.data.mongodb.core.MongoTemplate.doFind(MongoTemplate.java:1322)
        at org.springframework.data.mongodb.core.MongoTemplate.find(MongoTemplate.java:495)
        at org.springframework.data.mongodb.core.MongoTemplate.find(MongoTemplate.java:486)
"KafkaConsumer-46" prio=10 tid=0x00007f1178fd8000 nid=0x78dd waiting for monitor entry [0x00007f11562b8000]

java.lang.Thread.State: BLOCKED (on object monitor)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:403)
        - waiting to lock <0x00000006c0655b58> (a java.lang.Object)
        at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:356)
        at org.springframework.util.ClassUtils.forName(ClassUtils.java:258)
        at org.springframework.data.convert.SimpleTypeInformationMapper.resolveTypeFrom(SimpleTypeInformationMapper.java:56)
        at org.springframework.data.convert.DefaultTypeMapper.readType(DefaultTypeMapper.java:103)
        at org.springframework.data.convert.DefaultTypeMapper.getDefaultedTypeToBeUsed(DefaultTypeMapper.java:144)
        at org.springframework.data.convert.DefaultTypeMapper.readType(DefaultTypeMapper.java:121)
        at org.springframework.data.mongodb.core.convert.MappingMongoConverter.read(MappingMongoConverter.java:186)
        at org.springframework.data.mongodb.core.convert.MappingMongoConverter.read(MappingMongoConverter.java:176)
        at org.springframework.data.mongodb.core.convert.MappingMongoConverter.read(MappingMongoConverter.java:172)
        at org.springframework.data.mongodb.core.convert.MappingMongoConverter.read(MappingMongoConverter.java:75)
        at org.springframework.data.mongodb.core.MongoTemplate$ReadDbObjectCallback.doWith(MongoTemplate.java:1840)
        at org.springframework.data.mongodb.core.MongoTemplate.executeFindMultiInternal(MongoTemplate.java:1536)
        at org.springframework.data.mongodb.core.MongoTemplate.doFind(MongoTemplate.java:1336)
        at org.springframework.data.mongodb.core.MongoTemplate.doFind(MongoTemplate.java:1322)
        at org.springframework.data.mongodb.core.MongoTemplate.find(MongoTemplate.java:495)
        at org.springframework.data.mongodb.core.MongoTemplate.find(MongoTemplate.java:486)
        at com.snapdeal.coms.timemachine.mao.TimeMachineMao.getVendorProductsForUploadId(TimeMachineMao.java:32)
        at com.snapdeal.coms.timemachine.service.TimeMachineService.getVendorProductsForUploadIdAndSupc(TimeMachineService.java:35)
        at com.snapdeal.coms.timemachine.event.SupcUploadIdStateUpdateEventHandler.handleEvent(SupcUploadIdStateUpdateEventHandler.java:40)
I am not sure why all the threads are blocked. I thought class get loaded only one time and later no need to take any lock .

A: Did you try using the ConsumerOffsetChecker to see if your consumers are still alive ? you can try the following command from inside your $KAFKA_ROOT_DIR/ folder
  bin/kafka-run-class.sh kafka.tools.ConsumerOffsetChecker --group consumer-group1 --zkconnect zkhost:zkport --topic topic1

Here's few note taken from their FAQ page

If consumer offset is not moving after some time, then consumer is likely to have stopped. If consumer offset is moving, but consumer lag (difference between the end of the log and the consumer offset) is increasing, the consumer is slower than the producer. If the consumer is slow, the typical solution is to increase the degree of parallelism in the consumer. This may require increasing the number of partitions of a topic.

the above faq pages also explains possible reasons behind your consumer getting blocked, might worth take a look at it.

A: Problem was with the fetching data from mongo. there was huge data and pagination was not implemented and there was no socket timeout on the particular request hence threads were getting blocked.


text:
Q: Spring boot RabbitMQ Host string format I am using spring boot to listen for messages on my rabbitmq instance. I have it working locally using an application.properties file.
However, when I want to connect to the remote rabbit instance I am getting number format exceptions and unknown host exceptions because of my url.
I've tried setting spring.rabbitmq.host to:
amqp://myurl/dev and myurl/dev and amqp%3A%2F%2Fmyurl%2Fdev
Nothing is working. Any ideas what could be up. I have set my user name and pass for the remote instance as well.

A: Try removing the amqp:// part. The host property should just be that, the hostname:
spring.rabbitmq.host=myurl

Not sure what the /dev part is. Are you saying that is your virtual-host? If so then just set this property too:
spring.rabbitmq.virtual-host=dev

For username/password, set these properties:
spring.rabbitmq.username=
spring.rabbitmq.password=

A: A better way to do this is to set
spring.rabbitmq.addresses=amqps://user:password@10.0.0.123/virtualhost

This will get auto-resolved, and correctly set your hostname, password etc
Github issue that fixes this:
https://github.com/spring-projects/spring-boot/issues/6401


text:
Q: How to make gif animation visible for a specific time in JavaFX? I'm making a simple game in JavaFX and I want to display animations when characters fighting. When I click 'attack' button I want to display 'fight.gif' animation. When not clicking anything I want another 'waitForAction.gif' to be displayed. Problem is I want this 'fight.gif' to be displayed for a specific time, so the whole animation can be seen before 'waitForAction.gif' will be displayed again.
So my question is:
Are GIF's a good idea? If Yes, how to control them?
If not, how to make these animations work?
If you have problem with understanding I can post pictures of what I want to reach.

A: Use a Timeline. E.g. to display the gif for 2 seconds, you could do:
Timeline timeline = new Timeline(
    new KeyFrame(Duration.ZERO, e -> { /* display fight.gif */}),
    new KeyFrame(Duration.seconds(2), e -> { /* hide fight.gif */})
);
timeline.play();

The way this works is that the timeline consists of a series of key frames. Each key frame has a time associated with it (the time point on the timeline) and, in this example, an action to be invoked at that time. So in this case, zero seconds after the timeline is started, fight.gif is displayed, and 2 seconds after the timeline is started, fight.gif is hidden. The timeline is started by invoking its play() method.
In general, any time you want your UI to do something at, or for, some specific time, an animation of some kind may well provide an easy solution.

A: You can use Timeline to give interval duration
                            Timeline timeline = new Timeline();

                            timeline.getKeyFrames().add(new KeyFrame(javafx.util.Duration.seconds(3), (ActionEvent event1) -> {

                                try {
                                 //put your code here
                                } catch (Exception exception) {

                                }

                            }));
                            timeline.play();


text:
Q: JBossESB - queue to service mapping I am intercepting messages that are sent through JBossESB. I am using pipeline interceptors to do so.
The problem is, that altough the sender is a service (for example PortReference < logical:BlueServiceESB#BlueListener >), the name of the receiver is a queue (not a service). That is logical because in some case, multiple services can receive messages from a given queue, but usually, each queue is mapped to only one service.
I would like to know which queue is mapped to which service, so I can display/save this information and have it displayed like message: service ---> service (not service ---> queue).
I know that I can get the name of the queue mapped to a service using the registry like this:
System.setProperty("javax.xml.registry.ConnectionFactoryClass", "org.apache.ws.scout.registry.ConnectionFactoryImpl");

// Retrieving information from the ESB Registry
Registry reg = RegistryFactory.getRegistry();
System.out.println(reg.findAllServices());
List<EPR> eprs = reg.findEPRs("FirstServiceESB", "SimpleListener");
System.out.println(eprs);

I would like to reverse this approach - queue is the input and service (EPR = end point reference = service) is the output. Is there any way how to do this or am I just trying to do the impossible here. I have found no tutorials or questions on this topic whatsoever.
Thanks for any tips!

A: As this question has 25 up-votes, this seems to be an useful feature. JBossESB is open source software. Thus, implement the feature yourself and commit it to the community! Or just create a change request hopping that somebody else will do it...

A: Try querying for all of the queues and building a reverse-lookup map. But I don't think there is any function that allows searching for services using a queue.


text:
Q: Should docker --cache-from lead to multiple sha-hashes being downloaded? I'm struggling to get the docker --cache-from to work from a remote repository. I know there are many quirks, and have among other things enabled --build-arg BUILDKIT_INLINE_CACHE=1, when building the image before pushing.
When using --cache-from I got the following output:
#14 importing cache manifest from eu.gcr.io/repo/image:tag1
#14 sha256:aa73a6a76a7a7a67a6a76a76b7a6b7a6b7a6b7a
#14 DONE 2.0s

If there are multiple layers in the image, should there be multiple sha256-hashes here?

A: Buildkit should only download a layer if it needs it. If the layer is not used in the resulting image, it doesn't need to be downloaded. And if the layer is used but isn't needed locally because there's no uncached RUN step that depends on it, then it may be possible for buildkit to skip the download.
Also, keep in mind there's multiple things a sha256 digest can point to. At a minimum, there are image manifests, manifest lists, image configs (json blobs), and image layers (compressed tar blobs). You may also see different digests when layers are uncompressed. So with the above, you can assume it pulls something with that digest, most likely a manifest, and not any layers at all until/if they are needed later.


text:
Q: MATLAB: image horizontal/vertical autocorrelation with corr2() I have an image, and I'm trying to calculate both horizontal and vertical autocorrelation function estimates for R_h[x], R_v[x], -50<=x<=50. I've heard I can use corr2() to accomplish this, but I'm not sure how.

A: You can do this with a combination of circshift (to offset your image by certain ammount) and corr2 to calculate the correlation between the original image and the offset one. You just need to loop over the values you want to check. For example:
img = peaks(100);  % Sample data
x = -50:50;   % Desired offsets
output = zeros(1,101); %preallocate space for the result

for i=x   % loop over the offsets
    img2=circshift(img,[i 0]);   % Shift the image by the desired lag
    output(i+51)=corr2(img,img2);   % Calculate the correlation between the offset image and the original
end

plot(x,output)

I think you can take it from here and get the same graph for the other dimension, or even get a matrix for a combination of shifts in the horizontal and vertical dimensions.

A: You can have a look at corr2() documentation.
Basically this will do:
mInputImage1 = randn([200, 200]);
mInputImage2 = medfilt2(randn([200, 200]));

mCorrImage = corr2(mInputImage1, mInputImage2);


text:
Q: Google Login API requires two clicks initially We've moved our Google login code inside our angularJS controller and after the page initially loads, two clicks are required for a login. Tried moving the init code after the page loads but it still requires two clicks initially. Any idea what might be causing this? Here is the code:
HTML:
<button type="button" id="googleLogin" ng-click="onGoogleLogin()"
        class="btn btn-sm btndefault">
  Login
</button>

AngularJS Controller:
function GoogleLogin($scope) {

  $scope.onGoogleLogin = function() {

    gapi.load('auth2', function() {
        //Retrieve the singleton for the GoogleAuth library and set up the client.
        auth2 = gapi.auth2.init({
            client_id: 'CLIENT_ID.apps.googleusercontent.com',
            //cookiepolicy: 'single_host_origin'
        });

        var element = document.getElementById('googleLogin');

        auth2.attachClickHandler(element, {},
        function(response) {

            //https://developers.google.com/identity/sign-in/web/reference
            var profile = response.getBasicProfile();

            console.log('ID: ' + profile.getId()); // Do not send to your backend! Use an ID token instead.
            console.log('Name: ' + profile.getName());
            console.log('Image URL: ' + profile.getImageUrl());
            console.log('Email: ' + profile.getEmail()); // This is null if the 'email' scope is not present.

            console.log('ID Token: ' + response.getAuthResponse().id_token);
        },
        function(error) {
            console.log(JSON.stringify(error, undefined, 2));
        });
    });
  }

}

Any thoughts?

A: This would be better implemented as a directive:
app.directive("googleLoginDirective", function() {
    return {
        link: postLink
    };
    function postLink(scope,elem,attrs) {
        gapi.load('auth2', function() {
            //Retrieve the singleton for the GoogleAuth library and set up the client.
            auth2 = gapi.auth2.init({
                client_id: 'CLIENT_ID.apps.googleusercontent.com',
                //cookiepolicy: 'single_host_origin'
            });

            ̶v̶a̶r̶ ̶e̶l̶e̶m̶e̶n̶t̶ ̶=̶ ̶d̶o̶c̶u̶m̶e̶n̶t̶.̶g̶e̶t̶E̶l̶e̶m̶e̶n̶t̶B̶y̶I̶d̶(̶'̶g̶o̶o̶g̶l̶e̶L̶o̶g̶i̶n̶'̶)̶;̶
            var element = elem[0];

            auth2.attachClickHandler(element, {},
            function(response) {

                //https://developers.google.com/identity/sign-in/web/reference
                var profile = response.getBasicProfile();

                console.log('ID: ' + profile.getId()); // Do not send to your backend! Use an ID token instead.
                console.log('Name: ' + profile.getName());
                console.log('Image URL: ' + profile.getImageUrl());
                console.log('Email: ' + profile.getEmail()); // This is null if the 'email' scope is not present.

                console.log('ID Token: ' + response.getAuthResponse().id_token);
            },
            function(error) {
                console.log(JSON.stringify(error, undefined, 2));
            });
        });
    }
})

Usage
<button type="button" google-login-directive
        class="btn btn-sm btndefault">
  Login
</button>

When the AngularJS framework instantiates the directive, it invokes the gapi.load function and attaches the Google click handler to the element.
For more information, see

*

*AngularJS Developer Guide - Creating Custom Directives

A: You've setup your function to run when the button is clicked, however you call attachClickHandler inside that function. Therefore the click handler only gets attached after the first click and that's why the OAuth flow launches on the second.
You need to change your code so that it just runs on page load. There's no need to put it in an ng-click attribute because attachClickHandler handles all that for you.


text:
Q: Best way to link to javascript Very simple question here that I have not found the answer to despite searching a lot.
Whats the easiest way to load/call a piece of java script that is saved outside of the file.  So that several pages could use the same piece of java script, as though that piece of script was actually loaded into each page's head?

A: Save it in your file system and use relative paths from your current directory to locate it (eg. up one level - ../):
<script type="text/javascript" src="../somefile.js"></script>

And add this anywhere in your desired file. (Convention says either in the <head> or before </body> (before the body ends))

A: Just save this piece of JavaScript code in a separated file, i.e. myscript.js and link it using:
<script type="text/javascript" src="myscript.js"></script>

A: The "script" tag is part of the DOM.
You can add the tag like any other tag.
If you use jquery then it could look something like this:
$(document).ready(function(){

   var file = ? //Somehow acquire your new JS filename

   $("head").append("<script type='text/javascript' src='" + file + "'></script>");

});

You could have all your client dependencies defined server-side like in a configuration file or in the database. So, the first thing you'd need to do is query your server for your javascript dependencies.
$(document).ready(function(){

   $.ajax({
      url: "some.url",
      type: "get",
      datatype: "json",
      success: function(data){

          for(var i = 0; i < data.clientDependencies.length;i++)
          {
               var jsfile = data.clientDependencies[i].fileName;
               $("head").append("<script type='text/javascript' src='" + jsfile + "'></script>");
          }

      }

   });

});

Your server would then have to return the following JSON structure
{ "clientDependencies" :
   [
     { "fileName" : "one.js" },
     { "fileName" : "two.js" }
   ]
}

Note: This will still minimally require you to have jquery script tag hardcoded in your html page but all other js dependencies can be loaded as shown above.
Another technique is to have your server merge all your javascript files into one file and then serve that file to your client. Your server would then have control over what client dependencies is needed depending on what the client is asking for.
But honestly, nowadays, the internet is so fast that, in most cases, it's just less of hassle to just include all script tags in your html page from the get go.


text:
Q: SQL Server : query for DENSE_RANK() grouped by a column? Need help constructing a SQL statement for this scenario, over an orders table, that holds the orderID, customerID, itemID and other misc. columns.
Say the table looks like:
OrderID CustomerID ItemID Details
1       1234       543    abc
2       1234       643    xxx
3       1234       743    try
4       5678       743    try
5       5678       999    iuy
6       5678       643    xxx

What I'd like to have as an additional column is, one counter that increments each time a new customerID begins, and another that loops over counting the items the customer purchased. I'm using DENSE_RANK() and I am able to do the first counter, but how do I also handle the second?
SELECT
    DENSE_RANK() OVER (ORDER BY CustomerID) as Counter,
    *
FROM
    Orders
ORDER BY
    CustomerID ASC

This gives me:
Counter OrderID CustomerID ItemID Details
1       1       1234       543    abc
1       2       1234       643    xxx
1       3       1234       743    try
2       4       5678       743    try
2       5       5678       999    iuy
2       6       5678       643    xxx

And finally, what I WANT is the Counter2 column added somehow:
Counter Counter2 OrderID CustomerID ItemID Details
1       1        1       1234       543    abc
1       2        2       1234       643    xxx
1       3        3       1234       743    try
2       1        4       5678       743    try
2       2        5       5678       999    iuy
2       3        6       5678       643    xxx

A: You can use row_number() to get the second counter:
SELECT
    DENSE_RANK() OVER (ORDER BY CustomerID) as Counter,
    row_number() over(partition by customerId order by orderId) Counter2,
    *
FROM
    Orders
ORDER BY
    CustomerID ASC;

See SQL Fiddle with Demo. The result is:
| COUNTER | COUNTER2 | ORDERID | CUSTOMERID | ITEMID | DETAILS |
----------------------------------------------------------------
|       1 |        1 |       1 |       1234 |    543 |     abc |
|       1 |        2 |       2 |       1234 |    643 |     xxx |
|       1 |        3 |       3 |       1234 |    743 |     try |
|       2 |        1 |       4 |       5678 |    743 |     try |
|       2 |        2 |       5 |       5678 |    999 |     iuy |
|       2 |        3 |       6 |       5678 |    643 |     xxx |


text:
Q: Authentication precedence In nsswitch.conf file I have an entry "passwd files sss". Also I have the evidence that the server is having LDAP authentication. Since the "files" for passwd is enabled and it points the local authentication , which one take the precedence?

A: The file /etc/nsswitch.conf defines the order of NSS modules used to do lookups in NSS maps. Strictly speaking lookups in the passwd map are not used for authentication, only for checking the existence of a user trying to login.
Password authentication is done via the PAM stack configured in /etc/pam.d for earch service using PAM.

*

*For local users the PAM module pam_unix.so does a NSS lookup in the shadow map to get the hashed password and check the user's password against this.

*For remote LDAP users the shadow map should not be used. For example sssd sends a LDAP simple bind request to let the LDAP server check the user's password remotely. It does not query password hashes.

So to find out the order of PAM authc modules used you have to examime the files in directory /etc/pam.d. Most Linux systems today have common include files they use for every service such as /etc/pam.d/common-auth, most times a symlink to common-auth-pc created by tool pam-config.

A: See man 5 nsswitch.conf (bold added):

The first column is the database name.  The remaining columns specify:

*

*One or more service specifications, for example, "files", "db", or "nis".  The order of the  services on the line determines the order in which those services will be queried, in turn, until a result is found.

And your case, files takes precedence, which is as it should be - usually you don't want an LDAP entry for say, root, to override local entries.


text:
Q: Can't view Custom Activity in Journey Builder, but others can Client has a Custom Activity in Journey Builder... when I open the Journey I see "Unknown Custom Activity" and I cannot open the activity or see any details.  When the client logs in, they can see it and apply it to the Journey.
We have the same level of permissions in the platform (Admin + MC Admin).
Any ideas how to troubleshoot?

A: The "Unknown custom activity" error means that the custom activity endpoint was unreachable. Perhaps the custom app has IP restrictions or was offline at that moment.


text:
Q: Creating a Table but don't see the grid or value only background color Hello I am making a JTable in Java and I have weird problem. I can only see the background color.
This is the Method that is responsible for the creation.
public void createCustomerList() {

    table = new JTable();
    tableModel = new DefaultTableModel();

    tableModel.addColumn("Naam");
    tableModel.addColumn("Achternaam");
    tableModel.addColumn("Klant-ID");

    table.setSize(954, 686);
    table.setLocation(100, 78);
    table.setBackground(Color.white);
    table.setForeground(Color.black);
    table.setGridColor(Color.black);
    table.setRowHeight(30);
    table.setFont(new Font("Tahoma", Font.PLAIN, 36));

    JScrollPane scrollPane = new JScrollPane(table);
    table.setModel(tableModel);
    this.add(scrollPane);
    this.add(table);

}

and in my constructor I call this method. but I only get the background color ( when changing it to black or red or something else it changes ) but I don't see columns and the grid etc. Where could the problem be?

A: By adding the table to the container, you've removed it from the scroll pane. Start by removing the last add statement and make sure you are using an appropriate layout manager.
As pointed about by TrashGod, some look and feels may choose to set the grid color to the same color as the tables background color
Updated with working example
When you add a JTable (or any other component for that matter) to a JScrollPane, the component falls under the control of the scroll pane, you no longer have (a great deal of) control over the layout of the component.
You need to then focus on laying out the JScrollPane appropriately...

import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.table.DefaultTableModel;

public class QuickTable {

    public static void main(String[] args) {
        new QuickTable();
    }

    public QuickTable() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                }

                JTable table = new JTable();
                DefaultTableModel tableModel = new DefaultTableModel();

                tableModel.addColumn("Naam");
                tableModel.addColumn("Achternaam");
                tableModel.addColumn("Klant-ID");

                for (int index = 0; index < 10; index++) {

                    String value = Integer.toString(index);
                    tableModel.addRow(new Object[]{value, value, value});

                }

                table.setModel(tableModel);

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new BorderLayout());
                frame.add(new JScrollPane(table));
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }
}


text:
Q: Class Not Found Exception Error I just upgraded a project's Symfony framework from 2.3 to 2.7
But now I ran into an error:
Class Not Found Exception in appDevDebugProjectContainer.php line 4227:
Attempted to load class "Twig_Extensions_Extension_Text" from the global
namespace. Did you forget a "use" statement?

I am pretty new to Symfony and a lot of stuff are still quite overwhelming for me. Can somebody please help me out with this?
Thank you

A: This class doesn't come with the twig/twig package, but with the twig/extensions package (docs).
Make sure you have this package installed by running composer show -i and searching (or by using grep) in the output for this package name.
If you haven't, install the package:
$ composer require twig/extensions


text:
Q: Change the icons of PrimeFaces p:rating? I would like to change the shape of p:rating.. And display circles or squares or anything else instead of the stars. Is it possible. Maybe by CSS?

A: You have two Options
Option 1
You need to create your own icons, basiclly the icons are in one sprite image:

So in your case you would implement your own by replacing each icon, for example:

Then in CSS replace the background with the new one:
div.ui-rating-star a, div.ui-rating-cancel a {
  background-image: url("#{resource['images/icon/myrating.png']}");
}

online demo
How to create such sprites
go to http://spritepad.wearekiss.com/
Select

Then

Create your icons 15x15px

Drag and drop to the pad

Option 2
Font-awesome or any other css font
<p:rating styleClass="awesome-rating" />

in case of font-awesome you need to add this css piece
.awesome-rating .ui-rating-star, .awesome-rating  .ui-rating-cancel {
    float: initial;
    display: inline;
}

.awesome-rating .ui-rating-star a, .awesome-rating  .ui-rating-cancel a {
    background: none;
    width: initial;
    height: initial;
    font: normal normal normal 14px/1 FontAwesome;
    font-size: inherit;
    text-rendering: auto;
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
    color: #e6e6e6;
    margin-right: 5px;
    font-size: 30px;
    display: inline;
}

.awesome-rating  .ui-rating-cancel a:before {
    content: "\f056";
}

.awesome-rating  .ui-rating-cancel.ui-rating-cancel-hover a {
    color: #ce1c18;
}

.awesome-rating .ui-rating-star a:before {
    content: "\f006";
}

.awesome-rating .ui-rating-star.ui-rating-star-on a {
    color: #fadc3e;
}

.awesome-rating .ui-rating-star.ui-rating-star-on a:before {
    content: "\f005";
}

you can change the :before content with the icons content code, here's a full list
See more:

*

*CSS Image
Sprites.


text:
Q: Video Failed to transcode with FFmpeg with Rails app in my localhost I ve tried to upload videos using Carrierwave-video & FFmpeg. I've installed FFmpeg and there is no problem with installation. I have made configurations from ' http://blog.41studio.com/upload-videos-using-carrierwave-ffmpeg/ ' .But when I tried to upload video (.mov file), I have an error.
Error
 Video Failed to transcode with FFmpeg. Check ffmpeg install and verify video is not corrupt or cut short. Original error: Failed encoding.Errors: encoded file is invalid. Full output: ffmpeg version 2.8.3 Copyright (c) 2000-2015 the FFmpeg developers built with Apple LLVM version 7.0.0 (clang-700.1.76) configuration: --prefix=/usr/local/Cellar/ffmpeg/2.8.3 --enable-shared --enable-pthreads --enable-gpl --enable-version3 --enable-hardcoded-tables --enable-avresample --cc=clang --host-cflags= --host-ldflags= --enable-opencl --enable-libx264 --enable-libmp3lame --enable-libvo-aacenc --enable-libxvid --enable-libfaac --enable-nonfree --enable-vda libavutil 54. 31.100 / 54. 31.100 libavcodec 56. 60.100 / 56. 60.100 libavformat 56. 40.101 / 56. 40.101 libavdevice 56. 4.100 / 56. 4.100 libavfilter 5. 40.101 / 5. 40.101 libavresample 2. 1. 0 / 2. 1. 0 libswscale 3. 1.101 / 3. 1.101 libswresample 1. 2.101 / 1. 2.101 libpostproc 53. 3.100 / 53. 3.100 Input #0, mov,mp4,m4a,3gp,3g2,mj2, from '/Users/tanerkoroglu/Desktop/Wishpere2/public/uploads/tmp/1449435556-7186-2107/IMG_1756.MOV': Metadata: major_brand : qt minor_version : 0 compatible_brands: qt creation_time : 2015-10-17 12:19:27 Duration: 00:01:04.24, start: 0.000000, bitrate: 17176 kb/s Stream #0:0(und): Video: h264 (High) (avc1 / 0x31637661), yuv420p(tv, bt709), 1920x1080, 17082 kb/s, 29.98 fps, 29.97 tbr, 600 tbn, 1200 tbc (default) Metadata: creation_time : 2015-10-17 12:19:27 handler_name : Core Media Data Handler encoder : H.264 Stream #0:1(und): Audio: aac (LC) (mp4a / 0x6134706D), 44100 Hz, mono, fltp, 85 kb/s (default) Metadata: creation_time : 2015-10-17 12:19:27 handler_name : Core Media Data Handler Stream #0:2(und): Data: none (mebx / 0x7862656D), 0 kb/s (default) Metadata: creation_time : 2015-10-17 12:19:27 handler_name : Core Media Data Handler Stream #0:3(und): Data: none (mebx / 0x7862656D), 0 kb/s (default) Metadata: creation_time : 2015-10-17 12:19:27 handler_name : Core Media Data Handler Please use -q:a or -q:v, -qscale is ambiguous [Parsed_movie_0 @ 0x7feb6bf00100] Failed to avformat_open_input '/Users/tanerkoroglu/Desktop/Wishpere2/app/assets/images/logo.png' [AVFilterGraph @ 0x7feb6bc09240] Error initializing filter 'movie' with args '/Users/tanerkoroglu/Desktop/Wishpere2/app/assets/images/logo.png' Error opening filters!

video_uploader.rb
class VideoUploader < CarrierWave::Uploader::Base
    include CarrierWave::Video
    process :encode
     def encode
       encode_video(:mp4, watermark: {path: File.join(Rails.root, "app/assets/images/logo.png")})
     end

   version :mp4 do
     def full_filename(for_file)
        super.chomp(File.extname(super)) + '.mp4'
     end
   end
 end

Gemfile
 gem 'carrierwave',             '0.10.0'
 gem 'carrierwave-video'
 gem 'streamio-ffmpeg'

A: I had the same error. In my case it was because of carrierwave-video is incompatible with streamio-ffmpeg (3.0.2). streamio-ffmpeg expects to receive array of format_params, but carrierwave-video returns a string. I fixed it in my fork


text:
Q: Relying Party - Unique Signing certificate condition in ADFS 2.1 I was trying to add two RP's (Relying Party ) in ADFS 2.1 for the same customer. They use the same signing certificate in both the applications. But while updating in Windows Server 2012 / ADFS 2.1  I am receiving the below error.

MSIS7613: The signing certificate of the relying party trust is not
  unique across all relying party trusts in AD FS configuration

This was a condition imposed on ADFS 2.0 and Rollup 3 fixed (rather subdued ) this issue. I thought ADFS 2.1 included the updates in Rollup 3. But surprisingly it did not.
This post (written in Portuguese) suggests a work around which looks a bit intricate. Is there any easier way to get around this error ?

A: We had the same problem. Was solved by applying this hotfix:
http://support.microsoft.com/kb/2877424


text:
Q: Can a node have a property twice? I would like to create a database with abbreviations for every word used in my company.
Can I define a various number of properties for the same property (as in RDF)?
Is it possible to use different data types?
for example like this:
:Word
Name: Airbus A380
Abbreviation: A380
Abbreviation: 380
Abbreviation: xyz

:Word
Name: House
English: House
English: Home
Spanish: Casa
German: Haus
German: Wohnung

A: No, a property can only occur once on a node and have a single value. You can make the property value a list of strings, but you won't be able to look these up via an index.
You might consider separate :Abbreviation nodes connected to your :Word nodes, match from the abbreviations to the word.


text:
Q: css media query max-device-width If I have css 3 media query for max-device-width does this change when the orientation of the device changes?
For example if an iPhone goes from portrait to landscape does the max-device-width change?

A: This differs from iPhone, iPad etc to other devices. With Apple products, the device-width values remain the same, but with other devices changing the orientation could cause alternative rules to apply.
The most reliable way to do this is to use min/max-width instead of min/max-device-width. These are dependent on the size of the viewport, and are consistent across devices.

A: It doesnt change the orientation
@media screen and (orientation:portrait) {
/* Portrait styles */
}
@media screen and (orientation:landscape) {
/* Landscape styles */
}


text:
Q: Validating duplicates - Comparing objects from .bin file in serialization class Java I'm trying to validate a Appointment entered to make sure there is no duplicates. I've been advised to use a HashSet by other posts. However I'm getting the below error which is due to comparing against serialized objects. In the program the objects are read from the .bin file and passed into a Arraylist then the submitted appointment object is compared to that.
However I get the below error and I cannot add any appointment, is there anyway around this serialization error or should I be using another method to detect duplicates against what's in the .bin file?
Exception in thread "main" java.io.InvalidClassException: classes.Appointment; local class incompatible: stream classdesc serialVersionUID = 6357417907779853216, local class serialVersionUID = -1003880423618966687
AddAppointment code section
               {
                    t = new Appointment(nameStr, dayStr, hourStr);

                    String file = "people.bin";
                    File f = new File(file);
                    if(f.exists())
                    {
                        list = InputOutput.readRecord(file);
                    }

                    if (!Validation.isDuplicate(list, t))   //if test is false
                    {
                        JOptionPane.showMessageDialog(null, "Already Exist");
                    }

                    list.add(t);

                    //pass in list of objects
                    InputOutput.saveRecord("people.bin", list);
                    JOptionPane.showMessageDialog(null, "Appointment Entered");
                }

Appointment class
public class Appointment implements Serializable
{
    private String day;
    private String hour;
    private String name;

    public Appointment(String day, String hour, String name) {
        this.day = day;
        this.hour = hour;
        this.name = name;
    }

    public String getDay() {
        return day;
    }

    public void setDay(String day) {
        this.day = day;
    }

    public String getHour() {
        return hour;
    }

    public void setHour(String hour) {
        this.hour = hour;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return this.day + " " + this.hour + " " + this.name;

    }

    public boolean equals(Object o) {
        if(null != o) {
        if(o instanceof Appointment) {
            return ((Appointment)o).getName().equals(getName())
        && ((Appointment)o).getDay().equals(getDay());
        }
    }
    return false;
    }

    public int hashCode() {
    return (getName()+getDay()).hashCode();
    }

}

Validation class
public class Validation{

    public static boolean isDuplicate(ArrayList<Appointment> list, Appointment t)
    {

        HashSet<Appointment> unique=new HashSet<Appointment>();

        for (Appointment s : list)
        {
            unique.add(s);
        }

        //The Java.util.HashSet.add() method in Java HashSet is used to add a specific element into a HashSet.
        //this method will add the element only if the specified element is not present in the HashSet else the function will return False if the element is already present in the HashSet.
        if(unique.add(t))
        {   //  // java.util.Set only unique object so if object will not bee add in Set it will return false so can consider it as Duplicate

            return true;
        }
        else{
            System.out.println("Not unique, return false!");
             return false;}

    }
}

public class InputOutput
{

    ;

    public static void setupFile()
             throws FileNotFoundException, NotSerializableException, IOException, ClassNotFoundException
    {

        ArrayList<Appointment> currentlist = new ArrayList<>();
        String file = "people.bin";

        File f = new File(file);

        if(f.exists())
        {
            currentlist = InputOutput.readRecord(file);
        }

    }

    public static void saveRecord(String fileName, ArrayList<Appointment> list)
        throws FileNotFoundException, NotSerializableException, IOException
    {
        FileOutputStream fileoutstream = new FileOutputStream(fileName);

        ObjectOutputStream objectoutstream = new ObjectOutputStream(fileoutstream);

        // write the arraylist of objects to file
        objectoutstream.writeObject(list);
        objectoutstream.close();
    }

    public static ArrayList<Appointment> readRecord(String fileName)
        throws FileNotFoundException, NotSerializableException, IOException, ClassNotFoundException
    {
        ArrayList<Appointment> list = new ArrayList<>();

        FileInputStream fin = new FileInputStream(fileName);
        ObjectInputStream ois = new ObjectInputStream(fin);

        // read the objects from the file and dump them into the arraylist
        list = (ArrayList<Appointment>)ois.readObject();

        ois.close();

        return list;
    }


text:
Q: Is there a way to set global preferences in altair? Is there a way to do something like a rc file with Altair?
I currently create an Altair theme at the beginning of my notebooks (to set up plot size and font size, etc.) and then register and enable it.
alt.themes.register('my-chart', my_theme)
alt.themes.enable('my-chart')

What is the best way to refactor this away to a global config file of some sort?

A: I don't  think there is a file that Altair reads at startup. If  you want to avoid copy pasting the same theme code into each notebook, you can create a Python package with your theme. There are several examples of how to set this up on GitHub e.g. this la times theme.


text:
Q: C-How to read words from a text file into an array of strings I need to write a program that generates a table mapping words onto the number of times the word appears in a text file. So far my code looks like this
#include <stdlib.h>
#include <ctype.h>
#include <stdio.h>
#include <string.h>
struct entry
{
  char* word;
  unsigned int n;
  struct entry *left;
  struct entry *right;
};

struct entry*
insert(struct entry *table, char *str)
{
  if(table==NULL){
    table = (struct entry*)malloc(sizeof(struct entry));
    table->word = str;
    table->n = 1;
    table->left = NULL;
    table->right = NULL;
  }else if(strcmp(table->word,str)==0){
    table->n=(table->n)+1;
  }else if(strcmp(table->word,str)==1){
    table->left=insert(table->left,str);
  }else{
    table->right = insert(table->right,str);
  }
  return table;
}

void
print_table(struct entry *table)
{
  if(!(table==NULL)){
    print_table(table->left);
    fprintf(stdout,"%s\t %d\n",table->word,table->n);
    print_table(table->right);
  }
}

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

  struct entry* table = NULL;
  char *str = "foo";
  table =  insert(table,str);
  str = "foo";
  table = insert(table,str);
  print_table(table);

  return 0;

}

which gives an out put of
foo 2

what I need to do is do this exact thing with an input file. My idea is to take every word of the text file which will look like
This is an example of
what the text file
will look like.

I have no idea what the exact number of lines or words per line are. As I was saying, my idea was to take every word from the text file and put it into an array of strings, then run my insert function through every element in the array, I just have no idea how I should go about taking each word and putting it in the array. Any suggestions are welcome and appreciated.

A: If you want to store every word of the following paragraph
This is an example of
what the text file
will look like.

The following will work:
while(true){
    while(inFile >> yourword){
    //store yourword here
    }
    getline(inFile, yourword); //discards the newline
    if(/*some_conditional_to_break*/)
    break;
}

A: Portability bug
Note that this use of strcmp() is wrong:
}else if(strcmp(table->word,str)==1){

The definition of strcmp() is that it returns a value less than zero, equal to zero, or greater than zero.  No mention of 1.
Always, but always, compare with 0:

*

*if (strcmp(word, str) == 0) — word equal to str

*if (strcmp(word, str) != 0) — word not equal to str

*if (strcmp(word, str) <= 0) — word less than or equal to str

*if (strcmp(word, str) >= 0) — word greater than or equal to str

*if (strcmp(word, str) <  0) — word less than str

*if (strcmp(word, str) >  0) — word greater than str
In many implementations, the return value from strcmp() is the numeric difference between the characters that differ, and can be much larger or smaller than 1.
Reading words
If you're reasonably sure your input won't be wholly insane, you can use a variant on this loop to read the data:
char buffer[4096];
while (fscanf(fp, "%4095s", buffer) == 1)
{
    char *word = strdup(buffer);
    table = insert(table, word);
}

This reads words up to 4 KiB long and stores each one in your table using your function.  If a word is exactly 4 KiB long or longer than that, it will be split into pieces.  It probably won't be a problem.  Note that the scanf() family treats blanks, tabs and newlines as the separators between words.  Writing "a-z" in a file gets treated as one word, double quotes, dash and all.