Friday, 1 July 2016

java - If statement with String comparison fails

I really don't know why the if statement below is not executing:



if (s == "/quit")
{
System.out.println("quitted");
}


Below is the whole class.




It is probably a really stupid logic problem but I have been pulling my hair out over here not being able to figure this out.



Thanks for looking :)



class TextParser extends Thread {
public void run() {
while (true) {
for(int i = 0; i < connectionList.size(); i++) {
try {

System.out.println("reading " + i);
Connection c = connectionList.elementAt(i);
Thread.sleep(200);

System.out.println("reading " + i);

String s = "";

if (c.in.ready() == true) {
s = c.in.readLine();

//System.out.println(i + "> "+ s);

if (s == "/quit") {
System.out.println("quitted");
}

if(! s.equals("")) {
for(int j = 0; j < connectionList.size(); j++) {
Connection c2 = connectionList.elementAt(j);
c2.out.println(s);

}
}
}
} catch(Exception e){
System.out.println("reading error");
}
}
}
}
}

c++ - STL vector push_back() memory double free











I have the a problem of the double freeing of memory in the following program.



The debugger shows that the issue is in the push_back() function.




Class A:



class A {
public:
A(int x);
int x;
};

A::A(int x) {
this->x = x;

}


Class B:



class B {
public:
B(int x);
~B();
A* a;

};

B::B(int x) {
this->a = new A(x);
}

B::~B() {
delete a;
}



Main function:



int main() {
vector vec;

for(int i = 0; i < 10; i++) {
vec.push_back(B(i)); <------------ Issue is here
}


cout << "adding complete" << endl;

for(int i = 0; i < 10; i++) {
cout << "x = " << (vec[i].a)->x << endl;
}

return 0;
}



What is wrong in this code?



EDIT: Error double free or memory corruption


Answer





Everyone else has already harped on this so I won't dive further.



To address the usage you are apparently trying to accomplish (and conform to the Rule of Three in the process of elimination), try the following. While everyone is absolutely correct about proper management of ownership of dynamic members, your specific sample can easily be made to avoid their use entirely.




Class A



class A {
public:
A(int x);
int x;
};

A::A(int x)
: x(x)

{
}


Class B



class B {
public:
B(int x);
A a;

};

B::B(int x)
: a(x)
{
}


Main Program




int main() {
vector vec;

for(int i = 0; i < 10; i++) {
vec.push_back(B(i));
}

cout << "adding complete" << endl;

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

cout << "x = " << vec[i].a.x << endl;
}

return 0;
}


Bottom Line
Don't use dynamic allocation unless you have a good reason to, and it is lifetime-guarded by contained variables such as smart pointers or classes that vigorously practice the Rule of Three.


javascript - Node.js console.log() in txt file



I have another question (last question). At the moment i am working on a Node.js project and in this I have many console.log() functions. This has worked okay so far but I also want everything that's written to the console to also be written in a log-file. Can someone please help me?




For example:



Console.log('The value of array position [5] is '+ array[5]);


In my real code its a bit more but this should give you an idea.



Thank you hopefully.


Answer



I would use a library instead of re-inventing the wheel. I looked for a log4j-type library on npm, and it came up with https://github.com/nomiddlename/log4js-node




if you want to log to the console and to a file:



var log4js = require('log4js');
log4js.configure({
appenders: [
{ type: 'console' },
{ type: 'file', filename: 'logs/cheese.log', category: 'cheese' }
]
});



now your code can create a new logger with



var logger = log4js.getLogger('cheese'); 


and use the logger in your code



logger.warn('Cheese is quite smelly.');

logger.info('Cheese is Gouda.');
logger.debug('Cheese is not a food.');

java - problem in setting scrollpane for canvas

In the below program I want to zoomin and zoomout the image which is selected by the user.the problem is that when I zoomin or zoomout the image by clicking on zoomin zoomout button then scrollabars are not working. please help what is hte problem




import java.awt.BorderLayout;
import java.awt.Canvas;
import java.awt.Container;
import java.awt.Cursor;
import java.awt.Dimension;

import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JScrollPane;

public class ImageProcess extends JFrame implements ActionListener {

private JMenuItem newimage;
private JMenuItem open;
private Image image;
private File file;
private JFrame jf;
private JPanel panel;
private Cursor zoomCursor;

public ImageProcess() {
super("Image Demo");

this.setBounds(200, 200, 100, 100);
this.setSize(800, 800);
this.setResizable(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container con = this.getContentPane();
this.setVisible(true);
JMenuBar menubar = new JMenuBar();
this.setJMenuBar(menubar);
JMenu file = new JMenu("File");
newimage = new JMenuItem("New");

open = new JMenuItem("Open");
menubar.add(file);
file.add(newimage);
file.addSeparator();
file.add(open);
newimage.addActionListener(this);
open.addActionListener(this);
}

public void actionPerformed(ActionEvent e) {

if (e.getSource() == newimage) {
ReadImage ri = new ReadImage();

}
if (e.getSource() == open) {
OpenImage oi = new OpenImage();

}
}


public static void main(String args[]) {
ImageProcess imagepro = new ImageProcess();
}
}

class ImageFileFilter extends javax.swing.filechooser.FileFilter {
public boolean accept(File file) {
if (file.isDirectory())
return false;
String name = file.getName().toLowerCase();

return (name.endsWith(".jpg") || name.endsWith(".png") || name
.endsWith(".gif"));
}

public String getDescription() {
return "Images (*.gif,*.bmp, *.jpg, *.png )";
}
}

class ReadImage extends JFrame {

File file;
JFileChooser chooser;

public ReadImage() {
chooser = new JFileChooser();
chooser.setMultiSelectionEnabled(false);

chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
int returnVal = chooser.showOpenDialog(ReadImage.this);
if (returnVal == JFileChooser.APPROVE_OPTION) {

file = chooser.getSelectedFile();
try {
final BufferedImage bi = ImageIO.read(file);
Canvas can = new Canvas() {
public void paint(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
g2d.drawImage(bi, 0, 0, this);
}
};
this.getContentPane().add(can);

can.setPreferredSize(new Dimension(bi.getWidth(), bi
.getHeight()));
this.pack();
this.setVisible(true);
} catch (IOException ie) {
ie.printStackTrace();
}
}
}


}

class OpenImage extends JFrame implements ActionListener {
private JFileChooser chooser;
private File file;
private JFrame jf;
Canvas can;
JPanel pan;
public JScrollPane sp;
Dimension imgSize, iniSize;

private JButton butIn = new JButton("ZoomIN");
private JButton butOut = new JButton("ZoomOUT");
private JButton butReset = new JButton("Reset");

public OpenImage() {
chooser = new JFileChooser();
chooser.setCurrentDirectory(new File("."));
chooser.addChoosableFileFilter(new ImageFileFilter());
int returnVal = chooser.showOpenDialog(null);
if (returnVal == JFileChooser.APPROVE_OPTION) {

file = chooser.getSelectedFile();
String filename = file.getName();
try {
final BufferedImage bi = ImageIO.read(file);
imgSize = iniSize = new Dimension(bi.getWidth(), bi.getHeight());
jf = new JFrame();
this.setResizable(false);
this.setTitle(filename);
pan = new JPanel();
pan.add(butIn);

pan.add(butOut);
// pan.add(butReset);
butIn.addActionListener(this);
butOut.addActionListener(this);
butReset.addActionListener(this);

can = new Canvas() {
public void paint(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
if (imgSize.width = iniSize.width) {

can.setSize(imgSize);
}
can.repaint();
can.validate();
}

public void zoomOUT() {
if (!(getWidth() > imgSize.width)) {
int x = 10 * imgSize.width / 100;
int y = 10 * imgSize.height / 100;


imgSize = new Dimension(imgSize.width - x, imgSize.height - y);
if (getWidth() >= iniSize.width + 50) {
can.setSize(imgSize);
}
can.repaint();
can.validate();
} else {
repaint();
}

}

}

security - Magic quotes in PHP



According to the PHP manual, in order to make code more portable, they recommend using something like the following for escaping data:



if (!get_magic_quotes_gpc()) {
$lastname = addslashes($_POST['lastname']);
} else {
$lastname = $_POST['lastname'];
}



I have other validation checks that I will be performing, but how secure is the above strictly in terms of escaping data? I also saw that magic quotes will be deprecated in PHP 6. How will that affect the above code? I would prefer not to have to rely on a database-specific escaping function like mysql_real_escape_string().


Answer



Magic quotes are inherently broken. They were meant to sanitize input to the PHP script, but without knowing how that input will be used it's impossible to sanitize correctly. If anything, you're better off checking if magic quotes are enabled, then calling stripslashes() on $_GET/$_POST/$_COOKIES/$_REQUEST, and then sanitizing your variables at the point where you're using it somewhere. E.g. urlencode() if you're using it in a URL, htmlentities() if you're printing it back to a web page, or using your database driver's escaping function if you're storing it to a database. Note those input arrays could contain sub-arrays so you might need to write a function can recurse into the sub-arrays to strip those slashes too.



The PHP man page on magic quotes agrees:




"This feature has been DEPRECATED as

of PHP 5.3.0 and REMOVED as of PHP
5.4.0. Relying on this feature is highly discouraged. Magic Quotes is a
process that automagically escapes
incoming data to the PHP script. It's
preferred to code with magic quotes
off and to instead escape the data at
runtime, as needed."



javascript - The preferred way of creating a new element with jQuery




I've got 2 ways I can create a

using jQuery.



Either:



var div = $("
");
$("#box").append(div);


Or:




$("#box").append("
");


What are the drawbacks of using second way other than re-usability?


Answer



The first option gives you more flexibilty:



var $div = $("
", {id: "foo", "class": "a"});
$div.click(function(){ /* ... */ });
$("#box").append($div);



And of course .html('*') overrides the content while .append('*') doesn't, but I guess, this wasn't your question.



Another good practice is prefixing your jQuery variables with $:
Is there any specific reason behind using $ with variable in jQuery



Placing quotes around the "class" property name will make it more compatible with less flexible browsers.


php - unexpected T_FUNCTION error




I am using this function



    usort($arr, function($a, $b) use ($str) {return (strpos($a, $str) - strpos($b, $str));});


to sort the array $arr. This function works fine on localhost however when I uploaded my site online this error comes up





Parse error: syntax error, unexpected T_FUNCTION




Does anyone know why this is happening?


Answer



seems like your PHP version on your host is < 5.3.0
and its not support anonymous functions



http://php.net/manual/en/functions.anonymous.php




you may try this



function cmp($a, $b, $str) {
return (strpos($a, $str) - strpos($b, $str));
}

usort($arr, create_function('$a, $b', 'return cmp($a, $b, "' . $str . '");'));



or upgrade you php on server.


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...