Monday 29 February 2016

plot explanation - Why did the truck driver shoot Selene?

During her escape from the research facility, Selene jumps onto a driving truck.


The truck driver notices her, makes a full stop and she flies over the vehicle. The driver then steps out with a gun in hand, walks up to her lying on the ground and without blinking an eye, shoots her straight in the face.


killer truck driver


That was the point where I was completely baffled. What the hell is wrong with this guy?


Maybe he had a bad day, ok. We all know those, but shooting someone cold blooded without even asking why she used his truck as a taxi?


You could argue that he is living in a pretty bad world with vampires and werewolves and you can never be too careful, but:



  • There haven't been any werewolf or vampire sightings in years apparently, so he has no good reason to believe she is one of both.

  • A normal gun wouldn't help him in this case anyway.


So why is he acting this way? Am I missing something?


java - How to sort a map



I have a Map to sort as follows:



Map map = new HashMap(); 


It contains the following String keys:



String key = "key1.key2.key3.key4" 


It contains the following String values:



String value = "value1.value2"


where the key and value can vary by their number of dot sections from key1/value1 to key1.key2.key3.key4.key5/value1.value2.value3.value4.value5 non-homogeneously



I need to compare them according to the number of dots present in keys or in values according to the calling method type key / value :



sortMap(Map map, int byKey);


or



sortMap(Map map, int byValue);


The methods of course will return a sorted map.



Any help would be appreciated.


Answer



For starters, you will need to be using an instance of SortedMap. If the map doesn't implement that interface, then it has an undefined/arbitrary iteration order and you can't control it. (Generally this is the case, since a map is a way of associating values with keys; ordering is an auxiliary concern.)



So I'll assume you're using TreeMap, which is the canonical sorted map implementation. This sorts its keys according to a Comparator which you can supply in the constructor. So if you can write such a comparator that determines which is the "lower" of two arbitrary keys (spoiler alert: you can), this will be straightforward to implement.



This will, however, only work when sorting by key. I don't know if it makes much sense to sort a map by value, and I'm not aware of any straightforward way to do this. The best I can think of is to write a Comparator that sorts on values, call Map.getEntrySet and push all the entries into a list, then call Collections.sort on the list. It's not very elegant or efficient but it should get the job done if performance isn't your primary concern.



(Note also that if your keys aren't immutable, you will run into a lot of trouble, as they won't be resorted when externally changed.


c# - DataGridView System.InvalidOperationException Cell is not in a DataGridView



For the first time in a while, I can find no use information on this exception on Google... hoping someone else may have come across it.




I have a DataGridView that I validate for empty cells on the Leave event and remove those rows.



If I leave the last cell empty in the last row and tab away from the DGV the following exception is thrown:




System.InvalidOperationException: Cell is not in a DataGridView. The
cell cannot retrieve the inherited cell style.




I am not using Data Binding and a if I place a Breakpoint at this.dataGridView1.Rows.RemoveAt(c.RowIndex); It is hit and if if I step into this line the exception is thrown during the execution of non-user code...




I had thought this was to do with Uncommitted Changed but it seems explicitly committing the changes does not affect the outcome.



My Leave Event code:



    private void dataGridView1_Leave(object sender, EventArgs e)
{

if (this.dataGridView1.IsCurrentRowDirty || this.dataGridView1.IsCurrentCellDirty) this.dataGridView1.CommitEdit(DataGridViewDataErrorContexts.Commit);


//Validate for empty rows
foreach(DataGridViewRow row in this.dataGridView1.Rows)
{

foreach(DataGridViewCell c in row.Cells)
{

if(c.Value == null || c.Value.ToString() == String.Empty)
{
if (c.EditedFormattedValue == null || c.EditedFormattedValue.ToString() == "")

{
this.dataGridView1.Rows.RemoveAt(c.RowIndex);
break;
}

}
}


}

}


Exception Data is here:



System.InvalidOperationException: Cell is not in a DataGridView. The cell cannot retrieve the inherited cell style.
at System.Windows.Forms.DataGridViewCell.GetInheritedStyle(DataGridViewCellStyle inheritedCellStyle, Int32 rowIndex, Boolean includeColors)
at System.Windows.Forms.DataGridView.OnCellValidating(DataGridViewCell& dataGridViewCell, Int32 columnIndex, Int32 rowIndex, DataGridViewDataErrorContexts context)
at System.Windows.Forms.DataGridView.CommitEdit(DataGridViewCell& dataGridViewCurrentCell, DataGridViewDataErrorContexts context, DataGridViewValidateCellInternal validateCell, Boolean fireCellLeave, Boolean fireCellEnter, Boolean fireRowLeave, Boolean fireRowEnter, Boolean fireLeave)
at System.Windows.Forms.DataGridView.EndEdit(DataGridViewDataErrorContexts context, DataGridViewValidateCellInternal validateCell, Boolean fireCellLeave, Boolean fireCellEnter, Boolean fireRowLeave, Boolean fireRowEnter, Boolean fireLeave, Boolean keepFocus, Boolean resetCurrentCell, Boolean resetAnchorCell)

at System.Windows.Forms.DataGridView.ProcessDialogKey(Keys keyData)
at System.Windows.Forms.Control.ProcessDialogKey(Keys keyData)
at System.Windows.Forms.TextBoxBase.ProcessDialogKey(Keys keyData)
at System.Windows.Forms.Control.PreProcessMessage(Message& msg)
at System.Windows.Forms.Control.PreProcessControlMessageInternal(Control target, Message& msg)
at System.Windows.Forms.Application.ThreadContext.PreTranslateMessage(MSG& msg)
at System.Windows.Forms.Application.ThreadContext.System.Windows.Forms.UnsafeNativeMethods.IMsoComponent.FPreTranslateMessage(MSG& msg)
at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)

at System.Windows.Forms.Application.Run(Form mainForm)

Answer



If you're using foreach-loop, you can't remove items from the collection it's using. Here you're removing items from this.dataGridView1.Rows.



Try this:



for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
DataGridViewRow row = dataGridView1.Rows[i];


for (int k = 0; k < row.Cells.Count; k++)
{
DataGridViewCell c = row.Cells[k];

if (c.Value == null || c.Value.ToString() == String.Empty)
{
if (c.EditedFormattedValue == null || c.EditedFormattedValue.ToString() == "")
{
this.dataGridView1.Rows.RemoveAt(c.RowIndex);


// Decrease i, as the collection got smaller
i--;
break;
}

}
}
}


c - With arrays, why is it the case that a[5] == 5[a]?



As Joel points out in podcast #34, in C Programming Language (aka: K & R), there is mention of this property of arrays in C: a[5] == 5[a]



Joel says that it's because of pointer arithmetic but I still don't understand. Why does a[5] == 5[a]?


Answer



The C standard defines the [] operator as follows:



a[b] == *(a + b)




Therefore a[5] will evaluate to:



*(a + 5)


and 5[a] will evaluate to:



*(5 + a)



a is a pointer to the first element of the array. a[5] is the value that's 5 elements further from a, which is the same as *(a + 5), and from elementary school math we know those are equal (addition is commutative).


c++ - OpenCV detect image against a image set



I would like to know how I can use OpenCV to detect on my VideoCamera a Image. The Image can be one of 500 images.




What I'm doing at the moment:



- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
self.videoCamera = [[CvVideoCamera alloc] initWithParentView:imageView];
self.videoCamera.delegate = self;
self.videoCamera.defaultAVCaptureDevicePosition = AVCaptureDevicePositionBack;

self.videoCamera.defaultAVCaptureSessionPreset = AVCaptureSessionPresetHigh;
self.videoCamera.defaultAVCaptureVideoOrientation = AVCaptureVideoOrientationPortrait;
self.videoCamera.defaultFPS = 30;
self.videoCamera.grayscaleMode = NO;
}

-(void)viewDidAppear:(BOOL)animated{
[super viewDidAppear:animated];
[self.videoCamera start];
}


#pragma mark - Protocol CvVideoCameraDelegate

#ifdef __cplusplus
- (void)processImage:(cv::Mat&)image;
{
// Do some OpenCV stuff with the image
cv::Mat image_copy;
cvtColor(image, image_copy, CV_BGRA2BGR);


// invert image
//bitwise_not(image_copy, image_copy);
//cvtColor(image_copy, image, CV_BGR2BGRA);
}
#endif


The images that I would like to detect are 2-5kb small. Few got text on them but others are just signs. Here a example:



enter image description here




enter image description here



Do you guys know how I can do that?


Answer



There are several things in here. I will break down your problem and point you towards some possible solutions.




  1. Classification: Your main task consists on determining if a certain image belongs to a class. This problem by itself can be decomposed in several problems:





    • Feature Representation You need to decide how you are gonna model your feature, i.e. how are you going to represent each image in a feature space so you can train a classifier to separate those classes. The feature representation by itself is already a big design decision. One could (i) calculate the histogram of the images using n bins and train a classifier or (ii) you could choose a sequence of random patches comparison such as in a random forest. However, after the training, you need to evaluate the performance of your algorithm to see how good your decision was.


    • There is a known problem called overfitting, which is when you learn too well that you can not generalize your classifier. This can usually be avoided with cross-validation. If you are not familiar with the concept of false positive or false negative, take a look in this article.


    • Once you define your feature space, you need to choose an algorithm to train that data and this might be considered as your biggest decision. There are several algorithms coming out every day. To name a few of the classical ones: Naive Bayes, SVM, Random Forests, and more recently the community has obtained great results using Deep learning. Each one of those have their own specific usage (e.g. SVM ares great for binary classification) and you need to be familiar with the problem. You can start with simple assumptions such as independence between random variables and train a Naive Bayes classifier to try to separate your images.



  2. Patches: Now you mentioned that you would like to recognize the images on your webcam. If you are going to print the images and display in a video, you need to handle several things. it is necessary to define patches on your big image (input from the webcam) in which you build a feature representation for each patch and classify in the same way you did in the previous step. For doing that, you could slide a window and classify all the patches to see if they belong to the negative class or to one of the positive ones. There are other alternatives.


  3. Scale: Considering that you are able to detect the location of images in the big image and classify it, the next step is to relax the toy assumption of fixes scale. To handle a multiscale approach, you could image pyramid which pretty much allows you to perform the detection in multiresolution. Alternative approaches could consider keypoint detectors, such as SIFT and SURF. Inside SIFT, there is an image pyramid which allows the invariance.


  4. Projection So far we assumed that you had images under orthographic projection, but most likely you will have slight perspective projections which will make the whole previous assumption fail. One naive solution for that would be for instance detect the corners of the white background of your image and rectify the image before building the feature vector for classification. If you used SIFT or SURF, you could design a way of avoiding explicitly handling that. Nevertheless, if your input is gonna be just squares patches, such as in ARToolkit, I would go for manual rectification.





I hope I might have given you a better picture of your problem.


Sunday 28 February 2016

javascript - How to compare two objects with nested array of object using loop





I have two objects, suppose



A = {
name:'abc',
age: 20,
areaOfInterest:[
{ inSports:'badminton', outSports:'football' },
{ inSports:'chess', outSports:'tennis' }]
}


B = {
age: 20,
name: 'abc',
areaOfInterest:[
{ inSports:'chess', outSports:'tennis' },
{ inSports:'badminton', outSports:'football' }]
}


As in given example above, the sequence of keys is different in both objects. Also, while comparing I dont want to go with




if(A.name == B.name)
if(A.areOfInterest.inSports == B.areOfInterest.inSports)


I want to compare them using loop like for...In or for...Of



Here is what I tried,






A = {
name:'abc',
age: 20,
areaOfInterest:[
{ inSports:'badminton', outSports:'football' },
{ inSports:'chess', outSports:'tennis' }
]
}


B = {
age:20,
name: 'abc',
areaOfInterest:[
{ inSports:'chess', outSports:'tennis' },
{ inSports:'badminton', outSports:'football' }
]
}

function objCompare(obj1, obj2){

for (var [key, value] of Object.entries(obj1)) {
for (var [k, v] of Object.entries(obj2)){
if(k == key && v == value)
console.log(true)
}
}
}

console.log(objCompare(A,B));






I am not getting true result. It gives undefined when it compares A.areOfInterest with B.areOfInterest


Answer



I'd do something like this:





A = {

name:'abc',
age: 20,
areaOfInterest:[
{ inSports:'badminton', outSports:'football' },
{ inSports:'chess', outSports:'tennis' }
]
}

B = {
age:'abc',

name: 20,
areaOfInterest:[
{ inSports:'chess', outSports:'tennis' },
{ inSports:'badminton', outSports:'football' }
]
}

C = {
age:'abc',
name: 20,

areaOfInterest:[
{ inSports:'chess', outSports:'tennis' },
{ inSports:'badminton', outSports:'football' }
]
}

function objCompare(obj1, obj2){
var same = true;
for (var [key, value] of Object.entries(obj1)) {
if(typeof value === 'object') {

same = objCompare(obj1[key], obj2[key]);
} else {
if(obj1[key] != obj2[key]) same = false;
}
}

return same;
}

console.log(objCompare(A,B));

console.log(objCompare(B,C));





So using the function recursively you can iterate over other objects inside the main objects.



Hope that helps you :)


c++ - Call member method of a variadic class template with a member field

I learned a bit about variadic templates and searched over the Internet for some samples and now trying to write some tricky code to call member a method of a variadic class template with one of its fields. I can't understand why it doesn't work. Please, help.



Here is sample classes:



class BarBase
{
public:
BarBase() = default;


virtual void call() = 0;
};

template
class Bar
: public BarBase
{
public:
Bar(O* o, M m, A&&... a)

: BarBase()
, m_o(o), m_m(m), m_a(std::forward(a)...)
{ }

void call() override final
{
callInnerWithArgsInside();
}

private:

void callInnerWithArgsInside()
{
(m_o->*m_m)(m_a); // Some errors happends here
}

O* m_o;
M m_m;
std::tuple::type...> m_a;
};


template
BarBase* crateBar(O* o, M m, A&&... a)
{
return new Bar(o, m, std::forward
(a)...);
}


And call from main:



struct Foo

{
void foo(int ii, float ff, std::string ss)
{
std::cout << "called" << std::endl;
}
};

int main()
{
Foo f;

int i = 10;
float ff = 20.2f;
std::string s = "Hello";

BarBase* bar = crateBar(&f, &Foo::foo, i, ff, s);
bar->call();
}


Errors:




main.cpp



1>d:\drafts_tests\main.cpp(203): error C2198: 'void (__thiscall Foo::* )(int,float,std::string)' : too few arguments for call



1> d:\drafts_tests\main.cpp(202) : while compiling class template member function 'void Bar::callInnerWithArgsInside(void)'



1> with



1> [




1> O=Foo



1> , M=void (__thiscall Foo::* )(int,float,std::string)



1> ]



1> d:\drafts_tests\main.cpp(197) : see reference to function template instantiation 'void Bar::callInnerWithArgsInside(void)' being compiled



1> with




1> [



1> O=Foo



1> , M=void (__thiscall Foo::* )(int,float,std::string)



1> ]



1> d:\drafts_tests\main.cpp(214) : see reference to class template instantiation 'Bar' being compiled




1> with



1> [



1> O=Foo



1> , M=void (__thiscall Foo::* )(int,float,std::string)



1> ]




1> d:\drafts_tests\main.cpp(225) : see reference to function template instantiation 'BarBase *crateBar(O *,M,int &,float &,std::string &)' being compiled



1> with



1> [



1> O=Foo



1> , M=void (__thiscall Foo::* )(int,float,std::string)




1> ]



========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

Error with Conversion to Dalvik format failed and multidex in android?

Whenever I try to import lib-c2callsdkres Library then Give the error like this,

[2015-01-05 18:29:30 - Dex Loader] Unable to execute dex: method ID not in [0, 0xffff]: 65536
[2015-01-05 18:29:30 - TestApp] Conversion to Dalvik format failed: Unable to execute dex: method ID not in [0, 0xffff]: 65536 and sometimes give me error for multidex.



How to solve this error.please suggest me.



Thank you.

javascript - Angular 2 - Using 'this' inside setTimeout





I have a function like so in my class



  showMessageSuccess(){

var that = this;
this.messageSuccess = true;

setTimeout(function(){
that.messageSuccess = false;
},3000);


}


How can I re-write this so I don't have to store a reference to 'this' in the 'that' var? If I use 'this' inside the setTimeout, the messageSuccess bool doesn't seem to change/get updated.


Answer



You need to use ArrowFunction ()=> to preserve this context within setTimeout.



// var that = this; // no need of this line
this.messageSuccess = true;


setTimeout(()=>{ //<<<--- using ()=> syntax
this.messageSuccess = false;
}, 3000);

database - Java. Login not working

I am creating a management system in java.




I have this login form. The connection to database seems fine as it didn't give error on that.



But when I try to do try {} and catch {}, it gives an error.



I hope if any one can help me.



It gives this always:





catch (Exception ex) {
JOptionPane.showMessageDialog(null, "Error on login operation", "Login Error", JOptionPane.ERROR_MESSAGE);
}




public class Login extends javax.swing.JFrame {


private Connection con;
Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();



public Login() {
super("System Login");
initComponents();


this.setResizable(false);
this.setLocation((screen.width - 500) / 2, ((screen.height - 350) / 2));
this.setDefaultCloseOperation(EXIT_ON_CLOSE);


comcateg.addItem("Manager");
comcateg.addItem("Clerk");

ButtonListener listener = new ButtonListener();
btlogin.addActionListener(listener);
btcancel.addActionListener(listener);
con = DBConnection.getDBConnection();
if (con == null) {
JOptionPane.showMessageDialog(null, "Error on establishing database connection", "Error", JOptionPane.ERROR_MESSAGE);

this.dispose();
}
}

public void log(){

String user = txtuser.getText();
String pw = txtpw.getText();
String cat = comcateg.getSelectedItem().toString();
String SQL;

SQL = "SELECT * FROM AAP.USERS WHERE user_id='" + user + "' AND pword='" + pw +"' AND categ='" + cat +"'";

**try{

Statement stmt = con.createStatement();
stmt.execute(SQL);
ResultSet rs = stmt.getResultSet();
boolean recordfound = rs.next();
if (recordfound) {
LoadMainWindow();

this.dispose();
} else {
JOptionPane.showMessageDialog(null, "The system could not log you in.\n" +
" Please make sure your username and password are correct", "Login Failure", JOptionPane.INFORMATION_MESSAGE);
txtuser.setText("");
txtpw.setText("");
txtuser.requestFocus();
}
}
catch (Exception ex) {

JOptionPane.showMessageDialog(null, "Error on login operation", "Login Error", JOptionPane.ERROR_MESSAGE);
}


}**
public void LoadMainWindow() {
if (comcateg.getSelectedItem().equals("Manager")) {
new MainWindow().LoginManager();
} else {
new MainWindow().LoginClerk();

}
}

private class ButtonListener implements ActionListener {


public void actionPerformed(ActionEvent e) {
if (e.getSource() == btlogin) {
if (txtuser.getText() == null || txtuser.getText().equals("")) {
JOptionPane.showMessageDialog(null, "Enter username", "Missing field", JOptionPane.DEFAULT_OPTION);

txtuser.requestFocus();
return;
}
if (txtpw.getText() == null || txtpw.getText().equals("")) {
JOptionPane.showMessageDialog(null, "Enter password", "Missing field", JOptionPane.DEFAULT_OPTION);
txtpw.requestFocus();
return;
}
log();
} else if (e.getSource() == btcancel) {

System.exit(0);
}//if else closed
}//actionPerformed() closed
}

@SuppressWarnings("unchecked")
//
private void initComponents() {

jPanel1 = new javax.swing.JPanel();

userid = new javax.swing.JLabel();
pword = new javax.swing.JLabel();
categ = new javax.swing.JLabel();
txtuser = new javax.swing.JTextField();
txtpw = new javax.swing.JTextField();
comcateg = new javax.swing.JComboBox();
btlogin = new javax.swing.JButton();
btcancel = new javax.swing.JButton();

setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);


userid.setText("User ID:");

pword.setText("Password:");

categ.setText("Category:");

txtuser.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txtuserActionPerformed(evt);

}
});

txtpw.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txtpwActionPerformed(evt);
}
});

comcateg.setModel(new javax.swing.DefaultComboBoxModel(new String[] {}));

comcateg.setToolTipText("");
comcateg.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
comcategActionPerformed(evt);
}
});

btlogin.setText("Login");
btlogin.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {

btloginActionPerformed(evt);
}
});

btcancel.setText("Cancel");
btcancel.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btcancelActionPerformed(evt);
}
});


org.jdesktop.layout.GroupLayout jPanel1Layout = new org.jdesktop.layout.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(jPanel1Layout.createSequentialGroup()
.add(40, 40, 40)
.add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING, false)
.add(jPanel1Layout.createSequentialGroup()
.add(btlogin)

.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.add(btcancel))
.add(jPanel1Layout.createSequentialGroup()
.add(categ)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
.add(comcateg, 0, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.add(jPanel1Layout.createSequentialGroup()
.add(pword)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(txtpw))

.add(jPanel1Layout.createSequentialGroup()
.add(userid)
.add(18, 18, 18)
.add(txtuser, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 154, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(64, Short.MAX_VALUE))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(jPanel1Layout.createSequentialGroup()
.add(48, 48, 48)

.add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
.add(userid)
.add(txtuser, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
.add(pword)
.add(txtpw, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
.add(categ)

.add(comcateg, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.add(18, 18, 18)
.add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
.add(btlogin)
.add(btcancel))
.addContainerGap(48, Short.MAX_VALUE))
);

org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
getContentPane().setLayout(layout);

layout.setHorizontalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(jPanel1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(org.jdesktop.layout.GroupLayout.TRAILING, jPanel1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);

pack();

}//


private void txtuserActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}

private void txtpwActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}


private void btloginActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}

private void btcancelActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}

private void comcategActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:

}

/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html

*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);

} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//


/* Create and display the form */

java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Login().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton btcancel;
private javax.swing.JButton btlogin;
private javax.swing.JLabel categ;

private javax.swing.JComboBox comcateg;
private javax.swing.JPanel jPanel1;
private javax.swing.JLabel pword;
private javax.swing.JTextField txtpw;
private javax.swing.JTextField txtuser;
private javax.swing.JLabel userid;
// End of variables declaration


}




The DBConnect class code:



public class DBConnection {



public static Connection getDBConnection() {
Connection connection;
try {
Class.forName("org.apache.derby.jdbc.ClientDriver");
connection = DriverManager.getConnection("jdbc:derby:Ambulance;create=true");

return connection;
} catch (Exception ex) {
return null;
}
}
}


The exception I get is this:





run: java.sql.SQLSyntaxErrorException: Schema 'AAP' does not exist at
org.apache.derby.impl.jdbc.SQLExceptionFactory40.getSQLException(Unknown
Source) at
org.apache.derby.impl.jdbc.Util.generateCsSQLException(Unknown Source)
at
org.apache.derby.impl.jdbc.TransactionResourceImpl.wrapInSQLException(Unknown
Source) at
org.apache.derby.impl.jdbc.TransactionResourceImpl.handleException(Unknown
Source) at

org.apache.derby.impl.jdbc.EmbedConnection.handleException(Unknown
Source) at
org.apache.derby.impl.jdbc.ConnectionChild.handleException(Unknown
Source) at org.apache.derby.impl.jdbc.EmbedStatement.execute(Unknown
Source) at org.apache.derby.impl.jdbc.EmbedStatement.execute(Unknown
Source) at Login.log(Login.java:56) at
Login$ButtonListener.actionPerformed(Login.java:99) at
javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2018)
at
javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2341)

at
javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
at
javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
at
javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
at java.awt.Component.processMouseEvent(Component.java:6505) at
javax.swing.JComponent.processMouseEvent(JComponent.java:3321) at
java.awt.Component.processEvent(Component.java:6270) at
java.awt.Container.processEvent(Container.java:2229) at

java.awt.Component.dispatchEventImpl(Component.java:4861) at
java.awt.Container.dispatchEventImpl(Container.java:2287) at
java.awt.Component.dispatchEvent(Component.java:4687) at
java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4832)
at
java.awt.LightweightDispatcher.processMouseEvent(Container.java:4492)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4422)
at java.awt.Container.dispatchEventImpl(Container.java:2273) at
java.awt.Window.dispatchEventImpl(Window.java:2719) at
java.awt.Component.dispatchEvent(Component.java:4687) at

java.awt.EventQueue.dispatchEventImpl(EventQueue.java:729) at
java.awt.EventQueue.access$200(EventQueue.java:103) at
java.awt.EventQueue$3.run(EventQueue.java:688) at
java.awt.EventQueue$3.run(EventQueue.java:686) at
java.security.AccessController.doPrivileged(Native Method) at
java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at
java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:87)
at java.awt.EventQueue$4.run(EventQueue.java:702) at
java.awt.EventQueue$4.run(EventQueue.java:700) at

java.security.AccessController.doPrivileged(Native Method) at
java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:699) at
java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:242)
at
java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:161)
at
java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:150)
at
java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:146)

at
java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:138)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:91)


Recommended way to embed PDF in HTML?



What is the recommended way to embed PDF in HTML?




  • iFrame?

  • Object?

  • Embed?




What does Adobe say itself about it?



In my case, the PDF is generated on the fly, so it can't be uploaded to a third-party solution prior to flushing it.


Answer



Probably the best approach is to use the PDF.JS library. It's a pure HTML5/JavaScript renderer for PDF documents without any third-party plugins.



Online demo:
http://mozilla.github.com/pdf.js/web/viewer.html



GitHub:

https://github.com/mozilla/pdf.js


javascript - Save Form using localstorage HTML5



Is there a way to Save from into localstorage
and reuse it again, like this logic:



form ::::::::::::saveINTO:::::::::::::::> localstorage




form <::::::::::::getFROM::::::::::::::: localstorage



after filling the form with data , I want to save the form with its contents in the localstorage, then when i want to fill other from with stored data.




First name:
Last name:







JSFIDDLE
please JSFIDDLE answer.



UPDATED


Answer



You can do that easily, but if you want to store an array you will need to serialize or encode it first because localStorage doesn't deal with arrays. e.g.:




var yourObject = $('#your-form').serializeObject();



To save you do either:



localStorage['variablename'] = JSON.stringify(yourObject) or localStorage.setItem('testObject', JSON.stringify(yourObject));



and to retrieve: JSON.parse(localStorage['yourObject']); or JSON.parse(localStorage.getItem('yourObject')); and then the field values are available as yourObject.fieldName;



EDIT: In the example above I used serializeObject which is a jQuery plugin. The code used is below. (You can use serializeArray if you prefer but you will have to do more work to make your data usable once retrieved):




jQuery.fn.serializeObject = function () {
var formData = {};
var formArray = this.serializeArray();

for(var i = 0, n = formArray.length; i < n; ++i)
formData[formArray[i].name] = formArray[i].value;

return formData;
};


Saturday 27 February 2016

mysqli - Handle PHP objects on declaration file for every method call




I am looking for a way to build a handler or edit a php object, the following is an example for mysqli



I have a system with many files using the mysqli object in a variable



$my_var=new mysqli($host, $user, $pass, $base);


Files call this to do queries and get the results like this:



$q=$my_var->query("SELECT * FROM table");
$q->fetch_assoc();


if there is an error on the query, $my_var->error will be populated on the first line and will throw an error 500 on the second line.



I am looking for a way to build a handler for $my_var->error and throw the error before any fetch_* method is called, so,



is there any way to build a handler/listener for $my_var->error?



if this is not possible, is there any way to override mysqli fetch_assoc(), fetch_row() and fetch_array() methods to check if $my_var->error is true and show the error before continue?



I know about try{}catch(), throw new Exception and or die() methods, but these mean to edit every fetch_* in the system, I would like to do it editing the connection file only.



Thank you!



---editing---



I think prepared statements are not what I am looking for.



---editing 2---



And no, I am not looking how to get mysqli errors.



Thank you for your help fyrye!



---Answer Final Code---



class mysqli2{
private $c;
function __construct(...$args){ // open connection
$this->c=new mysqli(...$args);
if(!empty($this->c->error)){ // check for errors
echo("");
}
}
function query($query, $resultmode = MYSQLI_STORE_RESULT){
$r=$this->c->query($query, $resultmode); // make query
if(!empty($this->c->error)){ // check for errors
echo("");
}
return $r; // returns query results
}
function __call($method, $args){ // calls others mysqli methods
return $this->c->$method(...$args);
}
function __get($name){ // get all the properties
return $this->c->$name;
}
function __set($name, $value){ // set all the properties
if (property_exists($this->c, $name))$this->c->$name = $value;
}
}

Answer



To suggest a best practice, when using either PDO or MySQLi extensions, it is suggested to always check the return results from any of the usable methods, before moving on to a method that relies on its result.



As mysqli::query returns false on an error, it should be checked before using fetch_assoc, instead of assuming it is not false. The same applies to using fetch_assoc, as it can return NULL;



if (!$q = $my_var->query($sql)) {
//something went wrong - handle the error here.
}
if ($data = $q->fetch_assoc()) {
echo $data['column'];
}





However as I suggested, you would need to create an abstraction layer.



Since $q would be false on error, the exception from the code in your question would be:



Fatal error: Call to a member function fetch_assoc() on boolean


Meaning you would not be able to override the fetch_* methods, without overriding mysqli::query to always return an object.



Please do not use in production code.



This is only an example of how to override the mysqli::query method with your own. You would also need to override all other mysqli::*** methods, like prepare, commit, etc.





class Conn
{

private $conn;

public function __construct(...$args)
{
$this->conn = new mysqli(...$args);
}

public function query($query, $resultmode = \MYSQLI_STORE_RESULT)
{
$d = $this->conn->query($query, $resultmode);
if (!empty($this->conn->error)) {
throw new \RuntimeException($this->conn->error);
}

return $d;
}
}

//Your connection code
$con = 'my_var';
$$con = new Conn('host', 'user', 'pass', 'base');

//example usage of valid query
$q = $my_var->query('Valid Query');
$q->fetch_assoc();

//example use of invalid query throwing an exception before `fetch_assoc`
$q = $my_var->query('This is not valid');
$q->fetch_assoc();


Results



I was successful
-----

Fatal error: Uncaught exception 'RuntimeException' with message 'Expected "Valid Query"' in /in/PlZEs:51
Stack trace:
#0 /in/PlZEs(70): Conn->query('This is not val...')
#1 {main}
thrown in /in/PlZEs on line 51


This approach uses PHP 5.6 argument packing and unpacking, to match the function call arguments, to prevent having to manually define them.



It is possible to expand on this to write a message to log file, send an email, trigger an event, or display a friendly error message instead of throwing an exception. As well as overriding the mysqli_stmt responses with your own Statement object(s).


Simple way to repeat a String in java



I'm looking for a simple commons method or operator that allows me to repeat some String n times. I know I could write this using a for loop, but I wish to avoid for loops whenever necessary and a simple direct method should exist somewhere.



String str = "abc";

String repeated = str.repeat(3);

repeated.equals("abcabcabc");


Related to:



repeat string javascript
Create NSString by repeating another string a given number of times




Edited



I try to avoid for loops when they are not completely necessary because:




  1. They add to the number of lines of code even if they are tucked away in another function.


  2. Someone reading my code has to figure out what I am doing in that for loop. Even if it is commented and has meaningful variables names, they still have to make sure it is not doing anything "clever".


  3. Programmers love to put clever things in for loops, even if I write it to "only do what it is intended to do", that does not preclude someone coming along and adding some additional clever "fix".


  4. They are very often easy to get wrong. For loops involving indexes tend to generate off by one bugs.


  5. For loops often reuse the same variables, increasing the chance of really hard to find scoping bugs.



  6. For loops increase the number of places a bug hunter has to look.



Answer





". ".repeat( 7 )  // Seven period-with-space pairs: . . . . . . . 


New in Java 11 is the method String::repeat that does exactly what you asked for:




String str = "abc";
String repeated = str.repeat(3);
repeated.equals("abcabcabc");


Its Javadoc says:



/**
* Returns a string whose value is the concatenation of this
* string repeated {@code count} times.

*


* If this string is empty or count is zero then the empty
* string is returned.
*
* @param count number of times to repeat
*
* @return A string composed of this string repeated
* {@code count} times or the empty string if this
* string is empty or count is zero
*

* @throws IllegalArgumentException if the {@code count} is
* negative.
*
* @since 11
*/


c# - Reading settings from app.config or web.config in .NET



I'm working on a C# class library that needs to be able to read settings from the web.config or app.config file (depending on whether the DLL is referenced from an ASP.NET web application or a Windows Forms application).



I've found that



ConfigurationSettings.AppSettings.Get("MySetting")


works, but that code has been marked as deprecated by Microsoft.



I've read that I should be using:



ConfigurationManager.AppSettings["MySetting"]


However, the System.Configuration.ConfigurationManager class doesn't seem to be available from a C# Class Library project.



What is the best way to do this?


Answer



You'll need to add a reference to System.Configuration in your project's references folder.



You should definitely be using the ConfigurationManager over the obsolete ConfigurationSettings.


HTML Scraping in Php




I've been doing some HTML scraping in PHP using regular expressions. This works, but the result is finicky and fragile. Has anyone used any packages that provide a more robust solution? A config driven solution would be ideal, but I'm not picky.


Answer



I would recomend PHP Simple HTML DOM Parser after you have scraped the HTML from the page. It supports invalid HTML, and provides a very easy way to handle HTML elements.



Friday 26 February 2016

java - What is a stack trace, and how can I use it to debug my application errors?




Sometimes when I run my application it gives me an error that looks like:



Exception in thread "main" java.lang.NullPointerException
at com.example.myproject.Book.getTitle(Book.java:16)
at com.example.myproject.Author.getBookTitles(Author.java:25)
at com.example.myproject.Bootstrap.main(Bootstrap.java:14)


People have referred to this as a "stack trace". What is a stack trace? What can it tell me about the error that's happening in my program?







About this question - quite often I see a question come through where a novice programmer is "getting an error", and they simply paste their stack trace and some random block of code without understanding what the stack trace is or how they can use it. This question is intended as a reference for novice programmers who might need help understanding the value of a stack trace.


Answer



In simple terms, a stack trace is a list of the method calls that the application was in the middle of when an Exception was thrown.



Simple Example



With the example given in the question, we can determine exactly where the exception was thrown in the application. Let's have a look at the stack trace:




Exception in thread "main" java.lang.NullPointerException
at com.example.myproject.Book.getTitle(Book.java:16)
at com.example.myproject.Author.getBookTitles(Author.java:25)
at com.example.myproject.Bootstrap.main(Bootstrap.java:14)


This is a very simple stack trace. If we start at the beginning of the list of "at ...", we can tell where our error happened. What we're looking for is the topmost method call that is part of our application. In this case, it's:



at com.example.myproject.Book.getTitle(Book.java:16)



To debug this, we can open up Book.java and look at line 16, which is:



15   public String getTitle() {
16 System.out.println(title.toString());
17 return title;
18 }



This would indicate that something (probably title) is null in the above code.



Example with a chain of exceptions



Sometimes applications will catch an Exception and re-throw it as the cause of another Exception. This typically looks like:



34   public void getBookIds(int id) {
35 try {
36 book.getId(id); // this method it throws a NullPointerException on line 22
37 } catch (NullPointerException e) {

38 throw new IllegalStateException("A book has a null property", e)
39 }
40 }


This might give you a stack trace that looks like:



Exception in thread "main" java.lang.IllegalStateException: A book has a null property
at com.example.myproject.Author.getBookIds(Author.java:38)
at com.example.myproject.Bootstrap.main(Bootstrap.java:14)

Caused by: java.lang.NullPointerException
at com.example.myproject.Book.getId(Book.java:22)
at com.example.myproject.Author.getBookIds(Author.java:36)
... 1 more


What's different about this one is the "Caused by". Sometimes exceptions will have multiple "Caused by" sections. For these, you typically want to find the "root cause", which will be one of the lowest "Caused by" sections in the stack trace. In our case, it's:



Caused by: java.lang.NullPointerException <-- root cause
at com.example.myproject.Book.getId(Book.java:22) <-- important line



Again, with this exception we'd want to look at line 22 of Book.java to see what might cause the NullPointerException here.



More daunting example with library code



Usually stack traces are much more complex than the two examples above. Here's an example (it's a long one, but demonstrates several levels of chained exceptions):



javax.servlet.ServletException: Something bad happened
at com.example.myproject.OpenSessionInViewFilter.doFilter(OpenSessionInViewFilter.java:60)

at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
at com.example.myproject.ExceptionHandlerFilter.doFilter(ExceptionHandlerFilter.java:28)
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
at com.example.myproject.OutputBufferFilter.doFilter(OutputBufferFilter.java:33)
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
at org.mortbay.jetty.servlet.ServletHandler.handle(ServletHandler.java:388)
at org.mortbay.jetty.security.SecurityHandler.handle(SecurityHandler.java:216)
at org.mortbay.jetty.servlet.SessionHandler.handle(SessionHandler.java:182)
at org.mortbay.jetty.handler.ContextHandler.handle(ContextHandler.java:765)
at org.mortbay.jetty.webapp.WebAppContext.handle(WebAppContext.java:418)

at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:152)
at org.mortbay.jetty.Server.handle(Server.java:326)
at org.mortbay.jetty.HttpConnection.handleRequest(HttpConnection.java:542)
at org.mortbay.jetty.HttpConnection$RequestHandler.content(HttpConnection.java:943)
at org.mortbay.jetty.HttpParser.parseNext(HttpParser.java:756)
at org.mortbay.jetty.HttpParser.parseAvailable(HttpParser.java:218)
at org.mortbay.jetty.HttpConnection.handle(HttpConnection.java:404)
at org.mortbay.jetty.bio.SocketConnector$Connection.run(SocketConnector.java:228)
at org.mortbay.thread.QueuedThreadPool$PoolThread.run(QueuedThreadPool.java:582)
Caused by: com.example.myproject.MyProjectServletException

at com.example.myproject.MyServlet.doPost(MyServlet.java:169)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:820)
at org.mortbay.jetty.servlet.ServletHolder.handle(ServletHolder.java:511)
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1166)
at com.example.myproject.OpenSessionInViewFilter.doFilter(OpenSessionInViewFilter.java:30)
... 27 more
Caused by: org.hibernate.exception.ConstraintViolationException: could not insert: [com.example.myproject.MyEntity]
at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:96)
at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66)

at org.hibernate.id.insert.AbstractSelectingDelegate.performInsert(AbstractSelectingDelegate.java:64)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2329)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2822)
at org.hibernate.action.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:71)
at org.hibernate.engine.ActionQueue.execute(ActionQueue.java:268)
at org.hibernate.event.def.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:321)
at org.hibernate.event.def.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:204)
at org.hibernate.event.def.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:130)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:210)
at org.hibernate.event.def.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:56)

at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:195)
at org.hibernate.event.def.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:50)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:93)
at org.hibernate.impl.SessionImpl.fireSave(SessionImpl.java:705)
at org.hibernate.impl.SessionImpl.save(SessionImpl.java:693)
at org.hibernate.impl.SessionImpl.save(SessionImpl.java:689)
at sun.reflect.GeneratedMethodAccessor5.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.hibernate.context.ThreadLocalSessionContext$TransactionProtectionWrapper.invoke(ThreadLocalSessionContext.java:344)

at $Proxy19.save(Unknown Source)
at com.example.myproject.MyEntityService.save(MyEntityService.java:59) <-- relevant call (see notes below)
at com.example.myproject.MyServlet.doPost(MyServlet.java:164)
... 32 more
Caused by: java.sql.SQLException: Violation of unique constraint MY_ENTITY_UK_1: duplicate value(s) for column(s) MY_COLUMN in statement [...]
at org.hsqldb.jdbc.Util.throwError(Unknown Source)
at org.hsqldb.jdbc.jdbcPreparedStatement.executeUpdate(Unknown Source)
at com.mchange.v2.c3p0.impl.NewProxyPreparedStatement.executeUpdate(NewProxyPreparedStatement.java:105)
at org.hibernate.id.insert.AbstractSelectingDelegate.performInsert(AbstractSelectingDelegate.java:57)
... 54 more



In this example, there's a lot more. What we're mostly concerned about is looking for methods that are from our code, which would be anything in the com.example.myproject package. From the second example (above), we'd first want to look down for the root cause, which is:



Caused by: java.sql.SQLException


However, all the method calls under that are library code. So we'll move up to the "Caused by" above it, and look for the first method call originating from our code, which is:



at com.example.myproject.MyEntityService.save(MyEntityService.java:59)



Like in previous examples, we should look at MyEntityService.java on line 59, because that's where this error originated (this one's a bit obvious what went wrong, since the SQLException states the error, but the debugging procedure is what we're after).


twitter4j - Login Twitter to show the error "android.os.NetworkOnMainThreadException"




I have develop one application.Now i am trying to integrate the twitter in my application.My problem is when i login the application it show "android.os.NetworkOnMainThreadException" "at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1117)".




Please any one help me thanks...



import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.auth.RequestToken;
import twitter4j.conf.ConfigurationBuilder;
import android.app.Activity;
import android.content.Intent;

import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class TwitterActivity extends Activity {

static final String CONSUMER_KEY="my consumer key";
static final String CONSUMER_SECRETKEY="my secret key";
Button buttonLoginTwitter;
SharedPreferences sharedpref;
Twitter twitter;
private static RequestToken requestToken;
static final String TWITTER_CALLBACK_URL = "oauth://t4jsample";
static final String ISTWITTERLOGIN="isTwitterLogedIn";

@Override

protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_twitter);
buttonLoginTwitter=(Button)findViewById(R.id.btnidLogin);
sharedpref=getApplicationContext().getSharedPreferences("mypreference", 0);
TwitterLogin();
}
private void TwitterLogin() {
buttonLoginTwitter.setOnClickListener(new OnClickListener() {
@Override

public void onClick(View v) {

if(!istwitterLogin())
{
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.setOAuthConsumerKey(CONSUMER_KEY);
builder.setOAuthConsumerSecret(CONSUMER_SECRETKEY);
twitter4j.conf.Configuration configuration=builder.build();
TwitterFactory factory = new TwitterFactory(configuration);
twitter = factory.getInstance();


try {
requestToken = twitter
.getOAuthRequestToken(TWITTER_CALLBACK_URL);
TwitterActivity.this.startActivity(new Intent(Intent.ACTION_VIEW, Uri
.parse(requestToken.getAuthenticationURL())));
} catch (TwitterException e) {
e.printStackTrace();
}
}

else {
Toast.makeText(getApplicationContext(),"Already Logged into twitter", Toast.LENGTH_LONG).show();
}
}
});
}
protected boolean istwitterLogin() {
return sharedpref.getBoolean(ISTWITTERLOGIN, false);
}
@Override

public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.twitter, menu);
return true;
}

}


When i trying to login i got this error:




  E/AndroidRuntime( 5946): FATAL EXCEPTION: main
E/AndroidRuntime( 5946): android.os.NetworkOnMainThreadException
E/AndroidRuntime( 5946): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1117)
E/AndroidRuntime( 5946): at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
E/AndroidRuntime( 5946): at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
E/AndroidRuntime( 5946): at java.net.InetAddress.getAllByName(InetAddress.java:214)
E/AndroidRuntime( 5946): at libcore.net.http.HttpConnection.(HttpConnection.java:70)
E/AndroidRuntime( 5946): at libcore.net.http.HttpConnection.(HttpConnection.java:50)
E/AndroidRuntime( 5946): at libcore.net.http.HttpConnection$Address.connect(HttpConnection.java:341)

E/AndroidRuntime( 5946): at libcore.net.http.HttpConnectionPool.get(HttpConnectionPool.java:87)
E/AndroidRuntime( 5946): at libcore.net.http.HttpConnection.connect(HttpConnection.java:128)
E/AndroidRuntime( 5946): at libcore.net.http.HttpEngine.openSocketConnection(HttpEngine.java:315)
E/AndroidRuntime( 5946): at libcore.net.http.HttpEngine.connect(HttpEngine.java:310)
E/AndroidRuntime( 5946): at libcore.net.http.HttpEngine.sendSocketRequest(HttpEngine.java:289)
E/AndroidRuntime( 5946): at libcore.net.http.HttpEngine.sendRequest(HttpEngine.java:239)
E/AndroidRuntime( 5946): at libcore.net.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:80)
E/AndroidRuntime( 5946): at libcore.net.http.HttpURLConnectionImpl.getOutputStream(HttpURLConnectionImpl.java:188)
E/AndroidRuntime( 5946): at twitter4j.internal.http.HttpClientImpl.request(HttpClientImpl.java:158)
E/AndroidRuntime( 5946): at twitter4j.internal.http.HttpClientWrapper.request(HttpClientWrapper.java:65)

E/AndroidRuntime( 5946): at twitter4j.internal.http.HttpClientWrapper.post(HttpClientWrapper.java:102)
E/AndroidRuntime( 5946): at twitter4j.auth.OAuthAuthorization.getOAuthRequestToken(OAuthAuthorization.java:121)
E/AndroidRuntime( 5946): at twitter4j.auth.OAuthAuthorization.getOAuthRequestToken(OAuthAuthorization.java:104)
E/AndroidRuntime( 5946): at twitter4j.TwitterBaseImpl.getOAuthRequestToken(TwitterBaseImpl.java:276)
E/AndroidRuntime( 5946): at com.androidhive.twitterconnect.MainActivity.loginToTwitter(MainActivity.java:236)
E/AndroidRuntime( 5946): at com.androidhive.twitterconnect.MainActivity.access$1(MainActivity.java:223)
E/AndroidRuntime( 5946): at com.androidhive.twitterconnect.MainActivity$1.onClick(MainActivity.java:123)
E/AndroidRuntime( 5946): at android.view.View.performClick(View.java:4084)
E/AndroidRuntime( 5946): at android.view.View$PerformClick.run(View.java:16966)
E/AndroidRuntime( 5946): at android.os.Handler.handleCallback(Handler.java:615)

E/AndroidRuntime( 5946): at android.os.Handler.dispatchMessage(Handler.java:92)
E/AndroidRuntime( 5946): at android.os.Looper.loop(Looper.java:137)
E/AndroidRuntime( 5946): at android.app.ActivityThread.main(ActivityThread.java:4745)
E/AndroidRuntime( 5946): at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime( 5946): at java.lang.reflect.Method.invoke(Method.java:511)
E/AndroidRuntime( 5946): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
E/AndroidRuntime( 5946): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
E/AndroidRuntime( 5946): at dalvik.system.NativeStart.main(Native Method)
W/ActivityManager( 282): Force finishing activity com.androidhive.twitterconnect/.MainActivity
D/mobiled--->listener( 76): [Client side (recv_cnt: 3671)]: Data is coming, go to check fd_set.

D/mobiled--->listener( 76): [Client side (recv_cnt: 3671)]: Find a socket with data, unlock and receive.
D/mobiled--->netlink_listener( 76): Going to decode uevent.

Answer



you have to check this onCreate() method:



if (android.os.Build.VERSION.SDK_INT > "YOur minimum SDK Version here") {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);

}


And add permission to manifest..






Update




android.os.NetworkOnMainThreadException means you are performing your network operation on main thread which it will be blocked. So above solution is to restrict network error. But to overcome with this error you should use AsyncTask or by creating child thread and update your UI in runOnUiThread method which will update UI in that method.


PHP & MySQL INSERT INTO problem



Any ideas why the following code is not adding anything into the database once the user fills out the form? I'd really appreciate it.




Thank you!



    if($_SESSION['loginSuccess']==1) {

// ============================================================
// = Create the table of current tasks stored in the database =
// ============================================================
$userID = $_SESSION['userID'];
$result = mysql_query("SELECT * FROM Tasks WHERE userID = '$userID'");
echo "
";

echo $_SESSION['userID'];
while($row = mysql_fetch_array($result)) {
$taskName = $row[1];

$class = $row[2];

$taskDueDate = $row[3];

$taskType = $row[4];



echo "";
}
echo "
Task Name:Class:Due Date:Task Type:
'$taskName''$class''$taskDueDate''$taskType'
";

function addNewTask ($name, $class, $dueDate, $type) {
mysql_query("INSERT INTO Tasks VALUES ('$userID','$name', '$class', '$dueDate', '$type')");
}

if($_POST['taskName'] != NULL) {

addNewTask($_POST['taskName'], $_POST['class'], $_POST['dueDate'], $_POST['dueDate']);
}

?>




Task Name: (necessary)
Class:

Due Date:
Type:



Answer



Try getting rid of the ' around the variables in the insert statement. If that does nothing echoing mysql_error().


Thursday 25 February 2016

r - Create an empty data.frame



I'm trying to initialize a data.frame without any rows. Basically, I want to specify the data types for each column and name them, but not have any rows created as a result.



The best I've been able to do so far is something like:



df <- data.frame(Date=as.Date("01/01/2000", format="%m/%d/%Y"), 
File="", User="", stringsAsFactors=FALSE)
df <- df[-1,]


Which creates a data.frame with a single row containing all of the data types and column names I wanted, but also creates a useless row which then needs to be removed.



Is there a better way to do this?


Answer



Just initialize it with empty vectors:



df <- data.frame(Date=as.Date(character()),
File=character(),
User=character(),
stringsAsFactors=FALSE)





Here's an other example with different column types :



df <- data.frame(Doubles=double(),
Ints=integer(),
Factors=factor(),
Logicals=logical(),
Characters=character(),
stringsAsFactors=FALSE)

str(df)
> str(df)
'data.frame': 0 obs. of 5 variables:
$ Doubles : num
$ Ints : int
$ Factors : Factor w/ 0 levels:
$ Logicals : logi
$ Characters: chr


N.B. :



Initializing a data.frame with an empty column of the wrong type does not prevent further additions of rows having columns of different types.
This method is just a bit safer in the sense that you'll have the correct column types from the beginning, hence if your code relies on some column type checking, it will work even with a data.frame with zero rows.


assembly - Process command line in Linux 64 bit




I have problems accessing the process command line from Linux 64 bit Assembly program. To reproduce this with minimal code, I made this 32-bit program which prints first 5 characters of the program name:




.section .text

.globl _start
_start:
movl %esp, %ebp


movl $4, %eax # write
movl $1, %ebx # stdout
movl 4(%ebp), %ecx # program name address (argv[0])
movl $5, %edx # hard-coded length
int $0x80

movl $1, %eax
movl $0, %ebx
int $0x80



This program is working. When I translate it to 64 bit and run in Linux 64, it doesn't print anything:




.section .text

.globl _start
_start:
movq %rsp, %rbp


movq $4, %rax
movq $1, %rbx
movq 8(%rbp), %rcx # program name address ?
movq $5, %rdx
int $0x80

movq $1, %rax
movq $0, %rbx
int $0x80



Where is my mistake?


Answer



You are loading the correct address into %rcx.



int 0x80 then invokes the 32-bit syscall interface. That truncates the address to 32 bits, which makes it incorrect. (If you use a debugger and set a breakpoint just after the first int 0x80, you will see that it returns with -14 in %eax, which is -EFAULT.)



The second syscall, exit, works OK because the truncation to 32 bits doesn't do any harm in that case.







If you want to pass a 64-bit address to a system call, you will have to use the 64-bit syscall interface:




  • use syscall, not int 0x80;

  • different registers are used: see here;

  • the system call numbers are different as well: see here.




Here is a working version of your code:



.section .text

.globl _start
_start:
movq %rsp, %rbp

movq $1, %rax
movq $1, %rdi

movq 8(%rbp), %rsi # program name address ?
movq $5, %rdx
syscall

movq $60, %rax
movq $0, %rdi
syscall

Wednesday 24 February 2016

sql - PostgreSQL DISTINCT ON with different ORDER BY



I want to run this query:



SELECT DISTINCT ON (address_id) purchases.address_id, purchases.*
FROM purchases

WHERE purchases.product_id = 1
ORDER BY purchases.purchased_at DESC


But I get this error:




PG::Error: ERROR: SELECT DISTINCT ON expressions must match initial ORDER BY expressions





Adding address_id as first ORDER BY expression silences the error, but I really don't want to add sorting over address_id. Is it possible to do without ordering by address_id?


Answer



Documentation says:




DISTINCT ON ( expression [, ...] ) keeps only the first row of each set of rows where the given expressions evaluate to equal. [...] Note that the "first row" of each set is unpredictable unless ORDER BY is used to ensure that the desired row appears first. [...] The DISTINCT ON expression(s) must match the leftmost ORDER BY expression(s).




Official documentation




So you'll have to add the address_id to the order by.



Alternatively, if you're looking for the full row that contains the most recent purchased product for each address_id and that result sorted by purchased_at then you're trying to solve a greatest N per group problem which can be solved by the following approaches:



The general solution that should work in most DBMSs:



SELECT t1.* FROM purchases t1
JOIN (
SELECT address_id, max(purchased_at) max_purchased_at
FROM purchases

WHERE product_id = 1
GROUP BY address_id
) t2
ON t1.address_id = t2.address_id AND t1.purchased_at = t2.max_purchased_at
ORDER BY t1.purchased_at DESC


A more PostgreSQL-oriented solution based on @hkf's answer:



SELECT * FROM (

SELECT DISTINCT ON (address_id) *
FROM purchases
WHERE product_id = 1
ORDER BY address_id, purchased_at DESC
) t
ORDER BY purchased_at DESC


Problem clarified, extended and solved here: Selecting rows ordered by some column and distinct on another


time - How to convert Milliseconds to "X mins, x seconds" in Java?



I want to record the time using System.currentTimeMillis() when a user begins something in my program. When he finishes, I will subtract the current System.currentTimeMillis() from the start variable, and I want to show them the time elapsed using a human readable format such as "XX hours, XX mins, XX seconds" or even "XX mins, XX seconds" because its not likely to take someone an hour.



What's the best way to do this?


Answer



Use the java.util.concurrent.TimeUnit class:



String.format("%d min, %d sec", 
TimeUnit.MILLISECONDS.toMinutes(millis),

TimeUnit.MILLISECONDS.toSeconds(millis) -
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis))
);


Note: TimeUnit is part of the Java 1.5 specification, but toMinutes was added as of Java 1.6.



To add a leading zero for values 0-9, just do:



String.format("%02d min, %02d sec", 

TimeUnit.MILLISECONDS.toMinutes(millis),
TimeUnit.MILLISECONDS.toSeconds(millis) -
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis))
);


If TimeUnit or toMinutes are unsupported (such as on Android before API version 9), use the following equations:



int seconds = (int) (milliseconds / 1000) % 60 ;
int minutes = (int) ((milliseconds / (1000*60)) % 60);

int hours = (int) ((milliseconds / (1000*60*60)) % 24);
//etc...

javascript - Best way to dynamically add and remove style on elements



I am using mouseenter and mouseleave events on some elements to change their appearance. I am able to do so using either of the following two strategies:




  1. $(this).css('someProperty','someValue') to add and then $(this).removeAttr('style') to remove

  2. $(this).addClass('someClass') to add and then $(this).removeClass('someClass') to remove



What is the best way to do so?


Answer



Definitely option 2. Styles should be defined in the stylesheet.



There's also toggleClass, which removes the class if it's there, but adds it if it's missing.






Note: toggleClass also lets you pass in a Boolean as the second argument, telling it whether to add or remove it (regardless of whether it currently has that class applied), so:



$(this).toggleClass('active', true);


is exactly equivalent to:



$(this).addClass('active');


This is very handy when you have a Boolean in your code already. So instead of this:



if (isUserActive()) {
$(this).addClass('active');
} else {
$(this).addClass('active');
}


You could just do this:



$(this).toggleClass('active', isUserActive());

php - Codeigniter error: Parse error: syntax error, unexpected


Parse error: syntax error, unexpected '(', expecting identifier (T_STRING) or variable (T_VARIABLE) or '{' or '$' in C:\xampp\htdocs\code\application\controllers\user.php on line 14





class User extends CI_Controller
{

public function __construct()
{
parent:: __construct();
$this->load->model('user_model');
}

public function get()
{
$this->user_model->(2);
}

c++ - What breaking changes are introduced in C++11?

I know that at least one of the changes in C++11 that will cause some old code to stop compiling: the introduction of explicit operator bool() in the standard library, replacing old instances of operator void*(). Granted, the code that this will break is probably code that should not have been valid in the first place, but it's still a breaking change nonetheless: programs that used to be valid no longer are.



Are there any other breaking changes?

PHP mail() works from command line but not apache



I'm trying to figure out why the mail function in PHP fails when called via web browser (i.e. apache), but I can run the same script from the command line using




php -f mailtest.php





This is one of my client's Fedora servers, so I don't grok it completely, but I do have root access should I need to change anything.



from php.ini:




sendmail_path = /usr/sbin/sendmail -t -i




Not sure if this could matter, but /usr/sbin/sendmail is a symlink to /etc/alternatives/mta, which is a symlink back to /usr/sbin/sendmail.sendmail. FWIW the apache user does have permission to run sendmail (tested sendmail directly from the command line).




OS: Fedora Core 7 Linux (kernel 2.6.23.17)  
Apache: 2.2.8
PHP: 5.2.6


Any help here will be greatly appreciated!


Answer



I found the problem. SELinux was preventing apache from being able to use sendmail. To diagnose, I used



$ sestatus -b | grep sendmail  

httpd_can_sendmail off


Then to actually fix the problem:



$ restorecon /usr/sbin/sendmail
$ setsebool -P httpd_can_sendmail 1


Read more about it here.



java - Using capturing groups with reluctant, greedy, and possessive quantifiers



I was practicing regular expressions of java in the tutorial of Oracle. In order to understand greedy, reluctant, and possessive quantifiers better, I created some examples. My question is how those quantifiers work while capturing groups. I didn't understand using quantifiers in that manner, for example, reluctant quantifier looks as if it doesn't work at all. Also, I searched a lot in the Internet and only saw expressions like (.*?). Is there a reason why people usually use quantifiers with that syntax, not something like "(.foo)??"?



Here is the reluctant example:





Enter your regex: (.foo)??



Enter input string to search: xfooxxxxxxfoo



I found the text "" starting at index 0 and ending at index 0.



I found the text "" starting at index 1 and ending at index 1.



I found the text "" starting at index 2 and ending at index 2.




I found the text "" starting at index 3 and ending at index 3.



I found the text "" starting at index 4 and ending at index 4.



I found the text "" starting at index 5 and ending at index 5.



I found the text "" starting at index 6 and ending at index 6.



I found the text "" starting at index 7 and ending at index 7.




I found the text "" starting at index 8 and ending at index 8.



I found the text "" starting at index 9 and ending at index 9.



I found the text "" starting at index 10 and ending at index 10.



I found the text "" starting at index 11 and ending at index 11.



I found the text "" starting at index 12 and ending at index 12.




I found the text "" starting at index 13 and ending at index 13.




For reluctant, shouldn't it show "xfoo" for index 0 and 4 ? And here is the possessive one:




Enter your regex: (.foo)?+



Enter input string to search: afooxxxxxxfoo




I found the text "afoo" starting at index 0 and ending at index 4



I found the text "" starting at index 4 and ending at index 4.



I found the text "" starting at index 5 and ending at index 5.



I found the text "" starting at index 6 and ending at index 6.



I found the text "" starting at index 7 and ending at index 7.




I found the text "" starting at index 8 and ending at index 8.



I found the text "xfoo" starting at index 9 and ending at index 13.



I found the text "" starting at index 13 and ending at index 13.




And for possessive, shouldn't it try the input only for one time ? I'm really confused especially by this one because of trying every possibility.




Thanks in advance !


Answer



The regex engine checks (basically) every character of your string one by one, starting from the left, trying to make them fit in your pattern. It returns the first match it finds.



A reluctant quantifier applied to a subpattern means that the regex engine will give priority to (as in, try first) the following subpattern.



See what happens step by step with .*?b on aabab:



aabab # we try to make '.*?' match zero '.', skipping it directly to try and 
^ # ... match b: that doesn't work (we're on a 'a'), so we reluctantly

# ... backtrack and match one '.' with '.*?'
aabab # again, we by default try to skip the '.' and go straight for b:
^ # ... again, doesn't work. We reluctantly match two '.' with '.*?'
aabab # FINALLY there's a 'b'. We can skip the '.' and move forward:
^ # ... the 'b' in '.*?b' matches, regex is over, 'aab' is a general match


In your pattern, there's no equivalent to the b. The (.foo) is optional, the engine gives priority to the following part of the pattern.



Which is nothing, and that matches an empty string: an overall match is found, and it's always an empty string.







Regarding the possessive quantifiers, you're confused about what they do. They have no direct incidence on the number of matches: it's not clear chat tool you use to apply your regex but it looks for global matches and that's why it doesn't stop at the first match.



See http://www.regular-expressions.info/possessive.html for more info on them.



Also, as HamZa pointed out, https://stackoverflow.com/a/22944075 is becoming a great reference for regex related questions.


c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...