Friday, August 31, 2018

How to validate if Textfield entered is a mobile number using php and SQL DB











can anyone please help me know how to validate if the field value entered is a phone number using php...
I have used a variable $phone , datatype =varchar 10 in sql db
Now i want to validate that users enter only numbers in that field..


Answer



use preg_match




if(preg_match('/^(NA|[0-9+-]+)$/',$str)) {
*code here*
} else {
"code here"
}

How to send an email in background with CakePHP?



That's it, how can I send an email in background with CakePHP, preferable using the out-of-the-box Email component?




EDIT: with in background I mean in another thread, or at least allowing the controller method to finish and send the response to the user. I want to run a function, return "OK" to the user and, after that, send an email.



If it's not possible, how could I do it using the PHP mail function? (only if it's a good approach)



Don't know if it matters, but I'm using SMTP.



Thank you in advance.



EDIT 2: I'm trying to use the CakeEmail::deliver() method, as I read from the documentation that:





Sometimes you need a quick way to fire off an email, and you don’t necessarily want do setup a bunch of configuration ahead of time. CakeEmail::deliver() is intended for that purpose.




I'm trying this:



CakeEmail::deliver('myemail@mydomain.com', 'Test', 'Test',
array('from' => 'localhost@localhost.com'), true);



But the mail is not actually being sent. Anyone has any hint on that method?


Answer



So "in the background" means you want to process the mail sending "out of band". This is to give the user a quick response, and to be able to process slow operations like email sending after the user has feedback (or as you say, in a separate thread).



There are a number of ways to achieve this, including:




  • Workers / message queues

  • Cron job




The simplest way is probably to use a cron job that fires off every 15 or 30 seconds.



My recommended approach is to look into workers and queues, and use something like 0mq or RabbitMQ to queue the request to send an email, and process that outside the request.



If you want to do a cron job, rather than sending the email within the request the user has initiated, you would create a new model to represent your outbound email requests, and store that data into your database. Lets call this model Message for example.



CREATE TABLE `messages` (
`id` CHAR(36) NOT NULL PRIMARY KEY,

`to` VARCHAR(255) NOT NULL,
`from` VARCHAR(255) NOT NULL,
`subject` VARCHAR(255) NOT NULL,
`body` TEXT,
`sent` TINYINT(1) NOT NULL DEFAULT 0,
`created` DATETIME
);


Create a Console that grabs the Message model, and does a find for "unsent" messages:




$messages = $this->Message->findAllBySent(0);


Create yourself a send() method to simplify things, and process all unsent messages:



foreach ($messages as $message) {
if ($this->Message->send($message)) {
// Sending was a success, update the database
$this->Message->id = $message['Message']['id'];

$this->Message->saveField('sent', 1, false);
}
}


The implementation of the send() method on the Message model is up to you, but it would just pass the values from the passed in $message and shunt through to CakeEmail (http://api.cakephp.org/class/cake-email)



Once that is done, you can just call the console from the command line (or from your cron).


What is the difference between call and apply method in jQuery




I have seen lot of java-script code,that uses call as well as apply methods to invoke the function.
I am little bit confuse about the exact difference and in what which one to use in what condition.


Answer



They're not jQuery things, they're JavaScript things.



They do the same thing: They call the given function using a specific value for this within the function call. The only difference is how you specify the arguments to pass to the function. With call, you specify them as a series of discrete arguments (after the first one, which is what to use as this). With apply, you specify them as an array (again after the first arg, which is what to use as this).



So say we have:



function foo(a, b, c) {
console.log("this = " + this);
console.log("a = " + a);
console.log("b = " + b);
console.log("a = " + c);
}


These two calls do exactly the same thing:



foo.call("bar", 1, 2, 3);
// Note --------^--^--^--- a series of discrete args

foo.apply("bar", [1, 2, 3]);
// Note ---------^-------^-- args as an array


In both cases, we see:




this = bar
a = 1
b = 2
c = 3

Javascript Class, var undefined in event listener




var Foo = (function(){

function Foo(){

this._s="string";
this.setButton();
};

Foo.prototype.setButton = function(){
document.getElementById('id').addEventListener('click', function(event) {
alert(this._s);
});
};


Foo.prototype.method = function(){
alert(this._s);
};

return Foo;

})();

var fo = new Foo();
fo.method();



I want to bind an event to a button, and execute a function whic use a 'private' var, when I click the button the function is correctly called but it can't see the var this._s (it writes 'undefined'). If I write fo.method() the string is correctly printed.
here is the jsfiddle: http://jsfiddle.net/wLm1v4La/1/


Answer



you have to set the context(this) of the function manually before passing it.



 Foo.prototype.setButton = function () {
var tmpFunc = function(evt){ alert(this._s); } //store the function
var boundFunction = tmpFunc.bind(this); //set the context manually

//pass the function now to eventlistener
document.getElementById('id').addEventListener('click',boundFunction);
};

linux - Shell command to tar directory excluding certain files/folders



Is there a simple shell command/script that supports excluding certain files/folders from being archived?



I have a directory that need to be archived with a sub directory that has a number of very large files I do not need to backup.



Not quite solutions:



The tar --exclude=PATTERN command matches the given pattern and excludes those files, but I need specific files & folders to be ignored (full file path), otherwise valid files might be excluded.



I could also use the find command to create a list of files and exclude the ones I don't want to archive and pass the list to tar, but that only works with for a small amount of files. I have tens of thousands.



I'm beginning to think the only solution is to create a file with a list of files/folders to be excluded, then use rsync with --exclude-from=file to copy all the files to a tmp directory, and then use tar to archive that directory.



Can anybody think of a better/more efficient solution?



EDIT: Charles Ma's solution works well. The big gotcha is that the --exclude='./folder' MUST be at the beginning of the tar command. Full command (cd first, so backup is relative to that directory):



cd /folder_to_backup
tar --exclude='./folder' --exclude='./upload/folder2' -zcvf /backup/filename.tgz .

Answer



You can have multiple exclude options for tar so



$ tar --exclude='./folder' --exclude='./upload/folder2' -zcvf /backup/filename.tgz .


etc will work. Make sure to put --exclude before the source and destination items.


forms - PHP Email List Subscriber Script

Why won't this script work? I just want an email sent to hello@weblabcompany.com with the email of the subscriber so I can follow up with them later




Subscribe to Web Lab


Receive articles as they are published







if(isset($_POST['email'])) {


// EDIT THE 2 LINES BELOW AS REQUIRED

$email_to = "hello@weblabcompany.com";

$email_subject = "New Sub";

function died($error) {

// your error code can go here

echo "We are very sorry, but there were error(s) found with the form you submitted. ";

echo "These errors appear below.

";

echo $error."

";

echo "Please go back and fix these errors.

";

die();

}


!isset($_POST['email'])

{

died('We are sorry, but there appears to be a problem with the form you submitted.');
}



$email = $_POST['email']; // required


//$error_message = "";

//$email_exp = '/^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/';

//if(!preg_match($email_exp,$email_from)) {

//$error_message .= 'The Email Address you entered does not appear to be valid.
';

//}

//$string_exp = "/^[A-Za-z .'-]+$/";

//if(!preg_match($string_exp,$name)) {

//$error_message .= 'The First Name you entered does not appear to be valid.
';

//}

//if(!preg_match($string_exp,$email)) {

//$error_message .= 'The Last Name you entered does not appear to be valid.
';

//}

//if(strlen($message) < 2) {

//$error_message .= 'The Comments you entered do not appear to be valid.
';

//}
//if(strlen($error_message) > 0) {

//died($error_message);

//}

$email_message = "Form details below.\n\n";

function clean_string($string) {

$bad = array("content-type","bcc:","to:","cc:","href");

return str_replace($bad,"",$string);

}


$email_message .= "email: ".clean_string($email)."\n";


$headers = 'From: '.$email_from."\r\n".

'Reply-To: '.$email_from."\r\n" .

'X-Mailer: PHP/' . phpversion();

@mail($email);

?>



Thank you for contacting us. We will be in touch with you very soon.


}

?>

c++ - Writing records in SQLITE database taking huge time. How to improve efficiency of insert operation?

Insertion of approximately 110 million records in a table in database is taking huge time (>1hour) using C++ interface APIs.



Is there any way to bring this time down and improve efficiency of insert operation ?



I am grouping 1000 records in one transaction and then executing them.



sqlite3_exec(begin transaction);



sqlite3_exec(<1000> insertions);




sqlite3_exec(end transaction);



This is taking huge time.



How to improve efficiency of insertion?

plot explanation - What's the real meaning of the birth of the alien in Prometheus? - Movies & TV



In the movie Prometheus the alien is born from the last 'human-alien' of the planet they traveled to.




But, how should it be interpreted? The alien is a mutation from the parasite inside the body of the other one? Or the alien is the real aspect of the others that is hiding inside some kind of armor?


Answer



The scene is the culmination of the movie-long reveal of the origins of the killer creatures that cause so much havoc in "Alien" and its sequels.



In "Prometheus," the creature is the result of a somewhat complicated process:




  1. A human (Holloway) was infected by the black goo

  2. The infected human created a new organism within a non-infected human (Shaw)

  3. This new organism grew to be an octopus-like mutant


  4. The octopus-like mutant created another new organism within an Engineer



The second new organism's "birth" consisted of it springing out of its host's rib cage, just like the creatures in "Alien" and its sequels -- which it also resembles physically. (Notably, the alien at the end of Prometheus looks somewhat different from the aliens in the other Alien movies. I attribute this to the fact that in Prometheus, the alien is spawned from an Engineer, while in the other movies the aliens are spawned from humans.)



One of movie's ironies is the first action on the list above was taken by an android, who was a creation of man, who in turn was a creation of the Engineers.


php - How can I store my users' passwords safely?

How much more safe is this than plain MD5? I've just started looking into password security. I'm pretty new to PHP.



$salt = 'csdnfgksdgojnmfnb';

$password = md5($salt.$_POST['password']);
$result = mysql_query("SELECT id FROM users
WHERE username = '".mysql_real_escape_string($_POST['username'])."'
AND password = '$password'");


if (mysql_num_rows($result) < 1) {
/* Access denied */
echo "The username or password you entered is incorrect.";
}
else {
$_SESSION['id'] = mysql_result($result, 0, 'id');
#header("Location: ./");
echo "Hello $_SESSION[id]!";
}

javascript - Change radio button value to the value of text input

I have this code which has a radio button. I want to get the value of the text box and set it as the value of the selected radio button.



HTML




onsubmit="return formValidation();">
Monthly amount of

P
"text" value="">




Javascript



window.onload = function() {
var promised = document.getElementsByName("amounts");
for (var i = 0; i < promised.length; i++) {
promised[i].onclick = function() {

var rads = this.form[this.name];
for (var i = 0; i < rads.length; i++) {
var textField = this.form[rads[i].value.toLowerCase() + "Amount"];
if (textField) textField.disabled = !rads[i].checked;
}
}
}
}

java - NullPointerException when adding an object to ArrayList in Android




I'm trying to create a List View with BaseAdapter and i keep getting a Null Object Reference Error at the point of adding an object to an ArrayList.



Relevant code is below:



public class MainActivity extends ActionBarActivity {
int[] icons = {R.drawable.icon01, R.drawable.icon02, R.drawable.icon03, R.drawable.icon04, R.drawable.icon05, R.drawable.icon06, R.drawable.icon07, R.drawable.icon08, R.drawable.icon09, R.drawable.icon10, R.drawable.icon11, R.drawable.icon12};
ListView listView;

String[] title, desc;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

listView = (ListView) findViewById(R.id.listView);

Resources resources = getResources();

title = resources.getStringArray(R.array.titles);
desc = resources.getStringArray(R.array.desc);

RT_Adapter rt_adapter = new RT_Adapter(this, title, desc, icons);
listView.setAdapter(rt_adapter);
}
}

class Creator {
String a, b;

int c;

Creator(String d, String e, int f) {
this.a = d;
this.b = e;
this.c = f;
Log.d("RT", a +" - "+b+" - "+c); //Position 01 - This is Description 01 - 2130837556
}
}


class RT_Adapter extends BaseAdapter {
Context c;
ArrayList list;

public RT_Adapter(Context context, String[] title, String[] descs, int[] icons) {
this.c = context;
for (int i = 0; i < title.length; i++) {
list.add(new Creator(title[i], descs[i], icons[i]));
}
}


...
}


I get the error at the below line(found out while debugging):



list.add(new Creator(title[i], descs[i], icons[i]));



Below is the actual Error in Logcat:



02-09 17:09:05.494      767-767/? E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.rt.droid.baseadapter01, PID: 767
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.rt.droid.baseadapter01/com.rt.droid.baseadapter01.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.util.ArrayList.add(java.lang.Object)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2298)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
at android.os.Handler.dispatchMessage(Handler.java:102)

at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:898)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:693)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.util.ArrayList.add(java.lang.Object)' on a null object reference
at com.rt.droid.baseadapter01.RT_Adapter.(MainActivity.java:71)
at com.rt.droid.baseadapter01.MainActivity.onCreate(MainActivity.java:36)
at android.app.Activity.performCreate(Activity.java:5933)

at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2251)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
            at android.app.ActivityThread.access$800(ActivityThread.java:144)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5221)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)

            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:898)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:693)


I don't Understand how i am getting a null object when i create the new Creator object to add to the ArrayList.



Any pointers would be greatly appreciated.


Answer



You never initialize ArrayList list;. So list.add(new Creator(title[i], descs[i], icons[i])); will throw a NPE.




Change:



ArrayList list;


to:



ArrayList list = new ArrayList();

excel - VBA Tools>References Prompting for ProjectPassword to Open



I have searched online for a bit with no luck in finding a way around this.



I inherited an Excel workbook where the VBA code not protected. I can view | edit the code with no problem. However, when trying to run the code I get:





Compile Error: Can't find project or library.




I then go to Tools > References in the VBE and am prompted for a VBAProject Password.



My experience tells me that there is a reference set to some other VBAProject that is password protected that is no longer relevant, or at least it's missing, but how can I bypass this password error to check on the missing project.


Answer



While the end result answer may not be that universally helpful, I thought the methodology I used to get the answer may be useful for others.




I discovered the offending reference was



Name: ACRODISTXLib
FullPath: C:\Program Files (x86)\Adobe\Acrobat 10.0\Acrobat\acrodist.exe


The citrix path where the file is normally run houses Adobe Acrobat. My desktop houses Adobe Reader.



Adobe Acrobat has 2 other references:




Name: Acrobat
FullPath: C:\Program Files (x86)\Adobe\Acrobat 10.0\Acrobat\acrobat.tlb
Name: AcrobatAccessLib
FullPath: C:\Program Files (x86)\Adobe\Acrobat 10.0\Acrobat\plug_ins\Accessibility.api


These get translated nicely to machines with only Reader installed as:



Name: Acrobat
FullPath: C:\Program Files (x86)\Adobe\Reader 10.0\Reader\AcroRd32.dll

Name: AcrobatAccessLib
FullPath: C:\Program Files (x86)\Adobe\Reader 10.0\Reader\plug_ins\Accessibility.api


The first reference does not.



This is the code I used to compare the references in each workbook in each environment, which I decided to it when I get an error in accessing the reference name and fullpath in the workbook on my desktop:



Dim ref As Object


For Each ref In ThisWorkbook.VBProject.References
Debug.Print ref.Name & " | " & ref.fullpath
'If ref.isbroken Then
'ref.Remove
'ThisWorkbook.VBProject.References.Remove ref
'End If
Next

bash - YYYY-MM-DD format date in shell script



I tried using $(date) in my bash shell script, however I want the date in YYYY-MM-DD format. How do I get this?


Answer




In bash (>=4.2) it is preferable to use printf's built-in date formatter (part of bash) rather than the external date (usually GNU date).



As such:



# put current date as yyyy-mm-dd in $date
# -1 -> explicit current date, bash >=4.3 defaults to current time if not provided
# -2 -> start time for shell
printf -v date '%(%Y-%m-%d)T\n' -1

# put current date as yyyy-mm-dd HH:MM:SS in $date

printf -v date '%(%Y-%m-%d %H:%M:%S)T\n' -1

# to print directly remove -v flag, as such:
printf '%(%Y-%m-%d)T\n' -1
# -> current date printed to terminal


In bash (<4.2):



# put current date as yyyy-mm-dd in $date

date=$(date '+%Y-%m-%d')

# put current date as yyyy-mm-dd HH:MM:SS in $date
date=$(date '+%Y-%m-%d %H:%M:%S')

# print current date directly
echo $(date '+%Y-%m-%d')


Other available date formats can be viewed from the date man pages (for external non-bash specific command):




man date

computer vision - visual studio 1error LNK2001: unresolved external symbol _mainCRTStartup,2 error LNK1120: 1 unresolved externals

code:




#include "stdafx.h"
#include"highgui.h"
#include"stdio.h"

int main(int argc, CHAR* argv[])
{
cvNamedWindow:( "Example2", CV_WINDOW_AUTOSIZE );
CvCapture* capture = cvCreateFileCapture( "tendulkar.avi" );
IplImage* frame;
while(1) {

frame = cvQueryFrame( capture );
if( !frame ) break;
cvShowImage( "Example2", frame );
char c = cvWaitKey(33);
if( c == 27 ) break;
}
cvReleaseCapture( &capture );
cvDestroyWindow( "Example2" );
return 0;
}

Thursday, August 30, 2018

How to solve the java.lang.ArrayIndexOutOfBoundsException: 1 >= 0 error in my java program?

I got an error in my Java program. I think this happens because of the constructor is not intialized properly.



My Base class Program



public class Hello {
/**
* @param args the command line arguments

*/
public static void main(String[] args) {
// TODO code application logic here
try
{
ScrollPaneRefresh scp=new ScrollPaneRefresh();
scp.First();
scp.createAndShowGui();
}
catch(Exception e)

{
e.printStackTrace();
}
}
}


My Derived class Program



            package policyreader;


import java.sql.*;
import javax.swing.event.*;
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import javax.swing.table.*;
import java.util.*;
import javax.swing.JComboBox;
import javax.swing.SwingUtilities;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JPanel;
import java.awt.GridLayout;
import javax.swing.JFrame;
import java.io.IOException;

public class ScrollPaneRefresh extends JPanel {


private static final int PREF_W = 600;
private static final int PREF_H = 200;
int b = 0;
private String[][] newData = {
{"", ""}
};
private String[] columnName = {"S.NO", "SOLUTIONS"};
static Vector columnNames = new Vector();
static Vector data = new Vector();
static Vector columnNames56 = new Vector();

static Vector data56 = new Vector();

public static void First() {

try {
DefaultTableCellRenderer cent = new DefaultTableCellRenderer();
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

Connection connect = DriverManager.getConnection("jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=conflictresolve.mdb;DriverID=22}", "", "");
String sql = "Select * from geteffect";

Statement stmt = connect.createStatement();
ResultSet rs = stmt.executeQuery(sql);
ResultSetMetaData md = rs.getMetaData();
int columns = md.getColumnCount();
for (int i = 1; i <= columns; i++) {
columnNames.addElement(md.getColumnName(i));
}
while (rs.next()) {
Vector row = new Vector(columns);
for (int i = 1; i <= columns; i++) {

row.addElement(rs.getObject(i));
}
data.addElement(row);
}
rs.close();
stmt.close();

} catch (Exception e) {
e.printStackTrace();
}


}

public static void Second() {


Vector columnNames = new Vector();
Vector data = new Vector();
Vector columnNames1 = new Vector();
Vector columnNames2 = new Vector();

Vector data1 = new Vector();
Vector few = new Vector();
Vector com = new Vector();
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection connect = DriverManager.getConnection("jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=conflictresolve.mdb;DriverID=22}", "", "");

String sql = "Select * from allsolutiontable";
Statement stmt = connect.createStatement();
ResultSet rs = stmt.executeQuery(sql);

ResultSetMetaData md = rs.getMetaData();

String sql2 = "Select * from allsolutiontable";
Statement stmt2 = connect.createStatement();
ResultSet rs2 = stmt2.executeQuery(sql2);
ResultSetMetaData md2 = rs2.getMetaData();

String sql1 = "Select * from seteffect";
Statement stmt1 = connect.createStatement();
ResultSet rs1 = stmt1.executeQuery(sql1);

ResultSetMetaData md1 = rs1.getMetaData();

int columns = md.getColumnCount();

for (int i = 1; i <= columns; i++) {
columnNames.addElement(md.getColumnName(i));
}
int columns1 = md1.getColumnCount();
for (int i = 1; i <= columns1; i++) {
columnNames1.addElement(md1.getColumnName(i));

}

int columns2 = md2.getColumnCount();
for (int i = 1; i <= columns2; i++) {
columnNames2.addElement(md2.getColumnName(i));
}

while (rs.next()) {
Vector row = new Vector();



for (int i = 1; i <= 2; i++) {
row.addElement(rs.getObject(i));
//System.out.println(row);

}
data.addElement(row);
}
rs.close();
stmt.close();

while (rs2.next()) {

Vector large = new Vector();
//for (int i = 1; i <=columns; i++) {
large.addElement(rs2.getObject(3));
//}
few.addElement(large);
}





while (rs1.next()) {
Vector row1 = new Vector();
for (int i = 1; i <= 2; i++) {
row1.addElement(rs1.getObject(i));
}
data1.addElement(row1);
}


rs1.close();
stmt1.close();
rs2.close();
stmt2.close();
} catch (Exception e) {
e.printStackTrace();
}
//System.out.println(columnNames);
//System.out.println(columnNames1);
System.out.println(data);

System.out.println(data1);
System.out.println(few);
for (int i = 0; i < data.size(); i++) {
for (int j = 0; j < data1.size(); j++) {
if (data.get(i).toString().compareTo(data1.get(j).toString()) == 0) {
com.addElement(few.get(i));
System.out.println("Solution" + few.get(i).toString());
}
}
}

Connection co;
Statement st1, st2;
ResultSet rs1;
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
co = DriverManager.getConnection("jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=conflictresolve.mdb;DriverID=22}", "", "");
st1 = co.createStatement();
rs1 = st1.executeQuery("select * from conflictsolution");
//st1=co.createStatement();


for (int i = 0; i < com.size(); i++) {
String rr = "insert into conflictsolution values('" + com.get(i) + "')";
st1.executeUpdate(rr);
}
st1.close();
} catch (Exception e) {
System.out.println("there was some error in establishing connection : " + e);
}

try {

DefaultTableCellRenderer cent = new DefaultTableCellRenderer();
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

Connection connect = DriverManager.getConnection("jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=conflictresolve.mdb;DriverID=22}", "", "");
String sql = "Select * from conflictsolution";
Statement stmt = connect.createStatement();
ResultSet rs = stmt.executeQuery(sql);
ResultSetMetaData md = rs.getMetaData();
int columns = md.getColumnCount();
for (int i = 1; i <= columns; i++) {

columnNames56.addElement(md.getColumnName(i));
}
while (rs.next()) {
Vector row = new Vector(columns);
for (int i = 1; i <= columns; i++) {
row.addElement(rs.getObject(i));
}
data56.addElement(row);
}
rs.close();

stmt.close();

} catch (Exception e) {
e.printStackTrace();
}
}
public TablePanel gregsPanel = new TablePanel("SET THE EFFECTS FOR THE RULES", data, columnNames); // line 208
private TablePanel myPanel = new TablePanel("SOLUTIONS", data56, columnNames56, b);

public ScrollPaneRefresh() {


gregsPanel.setButtonAction(new AbstractAction("SUBMIT") {

@Override
public void actionPerformed(ActionEvent evt) {


gregsPanel.store();
Second();
myPanel.setTableModelDataVector(data56, columnNames56);



}
});
setLayout(new GridLayout(0, 1));
add(gregsPanel.getMainPanel());
add(myPanel.getMainPanel());
}

@Override // so scrollbars will show

public Dimension getPreferredSize() {
return new Dimension(PREF_W, PREF_H);
}

public static void createAndShowGui() {
ScrollPaneRefresh mainPanel = new ScrollPaneRefresh();
try {
JFrame frame = new JFrame("CONFLICT RESOLUTION FOR POLICYSET LEVEL");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);

frame.pack();
frame.setBounds(10, 10, 1200, 600);
frame.setLocationByPlatform(true);
frame.setVisible(true);
} catch (Exception ex) {
ex.printStackTrace();
}

}


public static void main(String[] args) throws Exception {
SwingUtilities.invokeLater(new Runnable() {

public void run() {
First();
createAndShowGui();
}
});
}
}


class TablePanel {

private JPanel mainPanel = new JPanel();
private DefaultTableModel dm;
private JTable table = new JTable();
private JTable table1 = new JTable();
private JButton changeTableBtn = new JButton();
private JScrollPane scrollpane = new JScrollPane(table);
private JScrollPane scrollpane1 = new JScrollPane(table1);


public TablePanel(String title, Vector data, Vector columnNames) {
try {
dm = new DefaultTableModel(data, columnNames);
table.setModel(dm);
table.setRowHeight(30);

TableColumn column = table.getColumnModel().getColumn(1); // line 279
//TableColumnModel tcm = table.getColumnModel();
//tcm.getColumn(1).setPreferredWidth(10);

column.setCellRenderer(new ComboBoxCellRenderer());
column.setCellEditor(new ComboBoxCellEditor());
// cent.setHorizontalAlignment(JLabel.CENTER);

JPanel btnPanel = new JPanel();
btnPanel.add(changeTableBtn);

mainPanel.setBorder(BorderFactory.createTitledBorder(title));
mainPanel.setLayout(new BorderLayout(5, 5));
mainPanel.add(scrollpane, BorderLayout.CENTER);

mainPanel.add(btnPanel, BorderLayout.PAGE_END);
} catch (Exception e) {
e.printStackTrace();
}

}

public TablePanel(String title, Vector data, Vector columnNames, int a) {
dm = new DefaultTableModel(data, columnNames);
table1.setModel(dm);

JPanel btnPanel = new JPanel();
//btnPanel.add(changeTableBtn);

mainPanel.setBorder(BorderFactory.createTitledBorder(title));
mainPanel.setLayout(new BorderLayout(5, 5));
mainPanel.add(scrollpane1, BorderLayout.CENTER);
mainPanel.add(btnPanel, BorderLayout.PAGE_END);
}

public void store() {

Connection conn;
Statement s;
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); // Establish a connection
conn = DriverManager.getConnection("jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=conflictresolve.mdb;DriverID=22}", "", "");
System.out.println("Databse Connected");

s = conn.createStatement();
String sql = "INSERT INTO seteffect VALUES (?, ?)";
PreparedStatement ps = conn.prepareStatement(sql);


TableModel tm = table.getModel();

int nRow = tm.getRowCount(), nCol = tm.getColumnCount();
System.out.println(" rows:" + nRow + "columns:" + nCol);
for (int r = 0; r < nRow; r++) {
for (int c = 1; c <= nCol; c++) {
//ps.setObject(c, tm.getValueAt(r, (nCol-1)));
if (c == 1) {
ps.setString(c, tm.getValueAt(r, c - 1).toString());


} /* else if(c==2)
{
ps.setString(c, tm.getValueAt(r, c-1).toString());
}*/ else {
ps.setString(c, tm.getValueAt(r, nCol - 1).toString());
}

}


ps.executeUpdate();
}




conn.close();
} catch (Exception ex) {
ex.printStackTrace();
}

}

public void setButtonAction(Action action) {
changeTableBtn.setAction(action);
}

public void setTableModelDataVector(Vector data, Vector columnNames) {
dm.setDataVector(data, columnNames);
}


public void fireTableDataChanged() {
dm.fireTableDataChanged();
}

public JScrollPane getScrollPane() {
return scrollpane;
}

public JComponent getMainPanel() {
return mainPanel;

}
}

class ComboBoxPanel extends JPanel {

private String[] m = new String[]{"Permit", "Deny"};
protected JComboBox comboBox = new JComboBox(m) {

@Override
public Dimension getPreferredSize() {

Dimension d = super.getPreferredSize();
return new Dimension(70, d.height);
}
};

public ComboBoxPanel() {
super();
setOpaque(true);
comboBox.setEditable(true);
add(comboBox);

}
}

class ComboBoxCellRenderer extends ComboBoxPanel
implements TableCellRenderer {

public ComboBoxCellRenderer() {
super();
setName("Table.cellRenderer");
}


@Override
public Component getTableCellRendererComponent(
JTable table, Object value, boolean isSelected,
boolean hasFocus, int row, int column) {
setBackground(isSelected ? table.getSelectionBackground()
: table.getBackground());
if (value != null) {
comboBox.setSelectedItem(value);
}

return this;
}
}

class ComboBoxCellEditor extends ComboBoxPanel
implements TableCellEditor {

public ComboBoxCellEditor() {
super();
comboBox.addActionListener(new ActionListener() {


@Override
public void actionPerformed(ActionEvent e) {
fireEditingStopped();
}
});
addMouseListener(new MouseAdapter() {

@Override
public void mousePressed(MouseEvent e) {

fireEditingStopped();
}
});
}

@Override
public Component getTableCellEditorComponent(
JTable table, Object value, boolean isSelected, int row, int column) {
this.setBackground(table.getSelectionBackground());
comboBox.setSelectedItem(value);

return this;
}

//Copid from DefaultCellEditor.EditorDelegate
@Override
public Object getCellEditorValue() {
return comboBox.getSelectedItem();
}

@Override

public boolean shouldSelectCell(EventObject anEvent) {
if (anEvent instanceof MouseEvent) {
MouseEvent e = (MouseEvent) anEvent;
return e.getID() != MouseEvent.MOUSE_DRAGGED;
}
return true;
}

@Override
public boolean stopCellEditing() {

if (comboBox.isEditable()) {
comboBox.actionPerformed(new ActionEvent(this, 0, ""));
}
fireEditingStopped();
return true;
}
//Copid from AbstractCellEditor
protected EventListenerList listenerList = new EventListenerList();
transient protected ChangeEvent changeEvent = null;


@Override
public boolean isCellEditable(EventObject e) {
return true;
}

@Override
public void cancelCellEditing() {
fireEditingCanceled();
}


@Override
public void addCellEditorListener(CellEditorListener l) {
listenerList.add(CellEditorListener.class, l);

}

@Override
public void removeCellEditorListener(CellEditorListener l) {
listenerList.remove(CellEditorListener.class, l);
System.out.println(listenerList);

}

public CellEditorListener[] getCellEditorListeners() {
return listenerList.getListeners(CellEditorListener.class);
}

protected void fireEditingStopped() {
// Guaranteed to return a non-null array
Object[] listeners = listenerList.getListenerList();
// Process the listeners last to first, notifying

// those that are interested in this event
for (int i = listeners.length - 2; i >= 0; i -= 2) {
if (listeners[i] == CellEditorListener.class) {
// Lazily create the event:
if (changeEvent == null) {
changeEvent = new ChangeEvent(this);
}
((CellEditorListener) listeners[i + 1]).editingStopped(changeEvent);
}
}

}

protected void fireEditingCanceled() {
// Guaranteed to return a non-null array
Object[] listeners = listenerList.getListenerList();
// Process the listeners last to first, notifying
// those that are interested in this event
for (int i = listeners.length - 2; i >= 0; i -= 2) {
if (listeners[i] == CellEditorListener.class) {
// Lazily create the event:

if (changeEvent == null) {
changeEvent = new ChangeEvent(this);
}
((CellEditorListener) listeners[i + 1]).editingCanceled(changeEvent);
}
}
}
}



1)when i run my derived class alone,i don't get any error.
2)when i run my base class,i get the following error,please help me



        java.lang.ArrayIndexOutOfBoundsException: 1 >= 0
at java.util.Vector.elementAt(Vector.java:470)
at javax.swing.table.DefaultTableColumnModel.getColumn(DefaultTableColumnModel.java:294)
at policyreader.TablePanel.(ScrollPaneRefresh.java:279)
at policyreader.ScrollPaneRefresh.(ScrollPaneRefresh.java:208)
at policyreader.Hello.main(Hello.java:20)

plot explanation - Where does the tunnel in the Wall come from?

I just finished the first season of "Game of Thrones", where one of the main themes is 'The Wall', a huge ice wall that devides the realm (Westeros) from the dangerous and winterly North.


From what I could gather this huge construct is not man-made. It was mentioned that it simply rose a few hundred years back from the ground. One of the characters says this when mentioning that they were no different than the wildlings, just happened to be on the right side of the wall.
EDIT: found the quote on IMDB:



Tyrion Lannister: But... I don't believe that giants and ghouls and white walkers are lurking beyond the Wall. I believe that the only difference between us and the wildlings is that when that Wall went up, our ancestors happened to live on the right side of it.



Apparently the northern side of the Wall is extremely dangerous, hosting wildlings, dangerous animals and the mysterious "White Walkers". Therefore, the Night Watch has to constantly guard and protect the Wall from outside dangers.




What I don't understand though is:
Where does the long tunnel leading through the Wall come from?


It is featured in the very first scene of the series, definitely looks man-made (it's shaped in a perfect bow form) and is covered by multiple massive gates.


Did the people from Westeros cut the tunnel into the ice? It would've certainly taken years to do this.


And if yes, what motivation could they possibly have? They probably knew before the wall came up that the north was dangerous. Why would they undertake such an effort to open a passage to this risky area?


Apart from just being not of any worth to them, it also leaves a gaping hole in the otherwise perfect defensive structure that the Wall poses.


Considering the risk they would certainly be better off to close the tunnel than to have a passage open and constantly send patrols out there. And even if they needed to go north of the Wall, they could simply let themselves from above, couldn't they?




So is the tunnel man-made and with what motivation, or is it simply a story device?


the wall


Answer


I have not yet gotten the chance to watch the series on TV but I have read the books and without any spoilers from beyond the first book here is the purpose for the tunnel in the wall.


First of all the wall is over 900 ft high that has been built by both man and some magical help. IIRC the tunnel was cut into the wall to create that path to the other side specifically so that they could chop back the forest growth. By chopping back the forest they create a lane of perfect sight to see when someone is attempting to climb the Wall and attack Westeros.


As for climbing down from the top of the wall to the northern side was not something they wished to do as it prevents a speedy return trip.


In C language head file


Possible Duplicate:
What is the difference between a definition and a declaration?






I am confuse about the function declare on head file. does this is same as java, declare function on one file,in that that file has function also has method.
does in C, make the function and method in two different files?
here is a example:




song.h



 typedef struct {
int lengthInSeconds;
int yearRecorded;
} Song;

Song make_song (int seconds, int year);
void display_song (Song theSong);



song.c



 #include 
#include "song.h"

Song make_song (int seconds, int year)
{
Song newSong;


newSong.lengthInSeconds = seconds;
newSong.yearRecorded = year;
display_song (newSong);

return newSong;
}

void display_song (Song theSong)
{

printf ("the song is %i seconds long ", theSong.lengthInSeconds);
printf ("and was made in %i\n", theSong.yearRecorded);
}


Can I write those two functions on just one file?



Thanks. I am new to C.



Regards.

Ben.

PHP 'mail()' Function Not Sending Email

Answer


Answer





I'm using a basic script on a 1&1 hosted server:



$recipient = "email@domain.com";
$sender_name = $_POST['name'];
$sender_email = $_POST['email'];
$subject = $_POST['subject'];
$message = $_POST['message'];

$headers = "MIME-Version: 1.0"."\r\n";

$headers .= "Content-type:text/html; charset=UTF-8"."\r\n";
$headers .= "From: {$sender_name} <{$sender_email}>"."\r\n";
$headers .= "Reply-to: {$sender_name} <{$sender_email}>"."\r\n";

mail($recipient, $subject, $message, $headers);


..but for some reason am not receiving any emails, nor any errors as per PHP mail() function not sending email instructs.



I thought this may be a server issue but 1&1 states that it is fully supported. I've also sent emails from this server/hosting before using just a recipient, subject and body and so I'm rather unsure as to why it is not working now!




UPDATE



Sending without headers, i.e.:



mail($recipient, $subject, $message);


..does work, so it would appear to be an issue with using the headers?


Answer




There may be many reasons, for example you should study what SPF is.



The $sender_email can't be any address, for example you can't put a gmail address and send emails claiming to be that sender, without any authentication, you aren't allowed to send email on behalf on that address, because I could for example send emails putting your address in the from, pretenting to be you when I'm not (I tried to use simple words)



You should use in the From something ending in @yourdomain.com, and set up SPF to allow your server's IP to send emails for that domain. OR otherwise send emails through SMTP (with PHPmailer, for example, it's very easy)


c# - NullReferenceException in DbContext.saveChanges()




Taking my very first babysteps with Entity Framework 5.0, I run into an exception with the very first Entity I create.



Please note that every table created after that works just fine. Also, do note that I've taken the usual steps of regenerating the database and/or restarting the Visual Studio IDE.



Using Model-First, I created a trivial table called Contacts, defined as



  









I then tried to run the following code (from the Page_Load of an ASP.NET page)



            var contact = new DataContext.Contact { Name = aName };


context.Contacts.Add(contact);
context.SaveChanges();


(with aName != null)



Exception:



System.NullReferenceException was unhandled by user code
HResult=-2147467261

Message=Object reference not set to an instance of an object.
Source=System.Web
StackTrace:
at System.Web.UI.ParseChildrenAttribute.GetHashCode()
at System.Collections.Generic.ObjectEqualityComparer`1.GetHashCode(T obj)
at System.Collections.Generic.HashSet`1.InternalGetHashCode(T item)
at System.Collections.Generic.HashSet`1.AddIfNotPresent(T value)
at System.Collections.Generic.HashSet`1.UnionWith(IEnumerable`1 other)
at System.Collections.Generic.HashSet`1..ctor(IEnumerable`1 collection, IEqualityComparer`1 comparer)
at System.Collections.Generic.HashSet`1..ctor(IEnumerable`1 collection)

at System.Data.Entity.ModelConfiguration.Utilities.AttributeProvider.GetAttributes(Type type)
at System.Data.Entity.ModelConfiguration.Utilities.AttributeProvider.GetAttributes(PropertyInfo propertyInfo)
at System.Data.Entity.Internal.Validation.EntityValidatorBuilder.BuildPropertyValidator(PropertyInfo clrProperty)
at System.Data.Entity.Internal.Validation.EntityValidatorBuilder.BuildValidatorsForProperties(IEnumerable`1 clrProperties, IEnumerable`1 edmProperties, IEnumerable`1 navigationProperties)
at System.Data.Entity.Internal.Validation.EntityValidatorBuilder.BuildTypeValidator[T](Type clrType, IEnumerable`1 edmProperties, IEnumerable`1 navigationProperties, Func`3 validatorFactoryFunc)
at System.Data.Entity.Internal.Validation.EntityValidatorBuilder.BuildEntityValidator(InternalEntityEntry entityEntry)
at System.Data.Entity.Internal.Validation.ValidationProvider.GetEntityValidator(InternalEntityEntry entityEntry)
at System.Data.Entity.Internal.InternalEntityEntry.GetValidationResult(IDictionary`2 items)
at System.Data.Entity.DbContext.ValidateEntity(DbEntityEntry entityEntry, IDictionary`2 items)
at System.Data.Entity.DbContext.GetValidationErrors()

at System.Data.Entity.Internal.InternalContext.SaveChanges()
at System.Data.Entity.Internal.LazyInternalContext.SaveChanges()
at System.Data.Entity.DbContext.SaveChanges()
at Contactisch._Default.AddContact(String aName) in c:\Projects\Contactisch\Contactisch\Contactisch\Default.aspx.cs:line 32
at Contactisch._Default.Page_Load(Object sender, EventArgs e) in c:\Projects\Contactisch\Contactisch\Contactisch\Default.aspx.cs:line 14
at System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e)
at System.Web.UI.Control.OnLoad(EventArgs e)
at System.Web.UI.Control.LoadRecursive()
at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
InnerException:



Can someone explain the cause of this exception ? Especially, what is that call to ParseChildrenAttribute.GetHashCode doing there?



I did find someone running into the same issue here, but no satisfactory explanation was given.


Answer



Problem solved.



The cause was a bit silly. I was using the default ASP.NET Web Forms Application project from VS Web Express to perform my testing. This project contains a web form called Contact.aspx, so it already includes a partial class Contact in the same namespace as my Contact entity.




Understandably, this didn't play well with Entity Framework, leading to the rather obscure error above. Deleting the aspx page solved the problem.


php - Can I try/catch a warning?



I need to catch some warnings being thrown from some php native functions and then handle them.



Specifically:



array dns_get_record  ( string $hostname  [, int $type= DNS_ANY  [, array &$authns  [, array &$addtl  ]]] )



It throws a warning when the DNS query fails.



try/catch doesn't work because a warning is not an exception.



I now have 2 options:




  1. set_error_handler seems like overkill because I have to use it to filter every warning in the page (is this true?);


  2. Adjust error reporting/display so these warnings don't get echoed to screen, then check the return value; if it's false, no records is found for hostname.





What's the best practice here?


Answer



Set and restore error handler



One possibility is to set your own error handler before the call and restore the previous error handler later with restore_error_handler().



set_error_handler(function() { /* ignore errors */ });
dns_get_record();
restore_error_handler();



You could build on this idea and write a re-usable error handler that logs the errors for you.



set_error_handler([$logger, 'onSilencedError']);
dns_get_record();
restore_error_handler();


Turning errors into exceptions




You can use set_error_handler() and the ErrorException class to turn all php errors into exceptions.



set_error_handler(function($errno, $errstr, $errfile, $errline, $errcontext) {
// error was suppressed with the @-operator
if (0 === error_reporting()) {
return false;
}

throw new ErrorException($errstr, 0, $errno, $errfile, $errline);

});

try {
dns_get_record();
} catch (ErrorException $e) {
// ...
}


The important thing to note when using your own error handler is that it will bypass the error_reporting setting and pass all errors (notices, warnings, etc.) to your error handler. You can set a second argument on set_error_handler() to define which error types you want to receive, or access the current setting using ... = error_reporting() inside the error handler.




Suppressing the warning



Another possibility is to suppress the call with the @ operator and check the return value of dns_get_record() afterwards. But I'd advise against this as errors/warnings are triggered to be handled, not to be suppressed.


r - as.numeric is rounding positive values / outputing NA for negative values

I am trying to do something with [R] which should be extremely simple: convert values in a data.frame to numbers, as I need to test for their values and r does not recognize them as number.



When I convert a decimal number to numeric, I get the correct value:



> a <- as.numeric(1.2)

> a
[1] 1.2


However, when I extract a positive value from the data.frame then use as.numeric, the number is rounded up:



> class(slices2drop)
[1] "data.frame"
> slices2drop[2,1]
[1] 1.2

Levels: 1 1.2
> a <- as.numeric(slices2drop[2,1])
> a
[1] 2


Just in case:



> a*100
[1] 200



So this is not a problem with display, the data itself is not properly handled.



Also, when the number is negative, I get NA:



> slices2drop[2,1] <- -1
> a <- as.numeric(slices2drop[2,1])
> a
[1] NA



Any idea as to what may be happening?

Generate random number between two numbers in JavaScript



Is there a way to generate a random number in a specified range (e.g. from 1 to 6: 1, 2, 3, 4, 5, or 6) in JavaScript?


Answer



Important




The following code works only if the minimum value is 1. It does not work for minimum values other than 1.



If you wanted to get a random integer between 1 (and only 1) and 6, you would calculate:



Math.floor(Math.random() * 6) + 1  


Where:





  • 1 is the start number

  • 6 is the number of possible results (1 + start (6) - end (1))


php - Trying to pass value to ISSET condition but getting error



I have created a PHP script and if use the script its always going to else condition and I am not sure why its not going to else condition.



     require_once  'db_functions.php';
$db = new DB_Functions();

$response = array();

$phone="1234";
$name="Test";
$birthdate="1994-01-01";
$address="123 M";

if(isset($_POST['phone']) &&
isset($_POST['name']) &&
isset($_POST['birthdate']) &&

isset($_POST['address']))


{
echo "Hello World 1";

$phone = $_POST['phone'];
$name = $_POST['name'];
$birthdate = $_POST['birthdate'];
$address = $_POST['address'];


echo "Hello World 2";

}

else{

echo "Hello";
$response["error_msg"] = "Required parameter
(phone,name,birthdate,address) is missing!";

echo json_encode($response);
}
?>


Output:



_msg":"Required parameter (phone,name,birthdate,address) is missing!"}



If the value is passed then it should go to if condition instead of else condition.




Options Tried



Tried Below options but I am getting empty value:



$test=$_POST['phone'];
echo "Hey......".$test;



echo isset($_POST['phone']);




URL USED
https://www.aaa.ccc/php/register.php?phone=232&name=test&birthdate=1954-04-04&address=232


Answer



You are passing the parameters in the url using the GET method, not POST, so you need:



    require_once  'db_functions.php';
$db = new DB_Functions();
$response = array();


$phone="1234";
$name="Test";
$birthdate="1994-01-01";
$address="123 M";

if(isset($_GET['phone']) &&
isset($_GET['name']) &&
isset($_GET['birthdate']) &&
isset($_GET['address']))



{
echo "Hello World 1";

$phone = $_GET['phone'];
$name = $_GET['name'];
$birthdate = $_GET['birthdate'];
$address = $_GET['address'];

echo "Hello World 2";


}

else{

echo "Hello";
$response["error_msg"] = "Required parameter
(phone,name,birthdate,address) is missing!";
echo json_encode($response);
}

?>

c++ - Repeated value at the end of the file

I am writing a program to take input from a file and display it on the console. The problem is that the last entry is being repeated twice. The code is as follows:-



int main(void)
{

string filename;
int grades;
cout<<"Enter the filename:"< getline(cin,filename);
ifstream inFile(filename.c_str(),ios::in);
if(!inFile){
cout<<"File does not exist."< exit(1);
}
while(!inFile.eof())

{
inFile>>grades;
cout< }
inFile.close();
return 0;
}


Can you please help me in finding out the mistake? I have searched on the web and my code seems to be syntactically and logically correct.

analysis - Did Tyler Durden forget his name? - Movies & TV



Ed Norton plays the Narrator or Jack ( due to reading a book that described someone called Jack's body parts from a 1st person perspective). Meanwhile Brad Pitt is introduced as Tyler Durden. Later on we find out that they are the same person.



So is Tyler Durden the new name he has chosen which he went and made an ID for and got various part-time jobs under or is it his original name and he somehow keeps blanking it out when he needs to tell police (things like his apartment exploded, or that other things will explode) or when he sees it on his checks from work or his work documents Id and many other things that would have his name on them?


Answer



In addition to Orion's answer, I'd add that while it's not specifically stated in the movie, I think it's implied well enough that the Narrator's name is not Tyler Durden. Tyler says at one point that the Narrator is "slowly letting himself become Tyler Durden." If his name was actually Tyler, this line wouldn't make any sense.



I suspect the movie avoids telling us his real name as a clue that he and Tyler are the same person. It was very clever indeed.




I still remember the first time I watched it and Marla is asking him his name, "What's your name? It's not on your card. Is it Radith? Corneleus? Any of the stupid names you give each night?" The bus passes in front of her, ending the scene so we don't get to hear the Narrator's answer . . . and it didn't phase me one bit. It just seemed like a neat way to end the scene.



Fight Club is definitely one of my top ten movies of all time.


Get the source directory of a Bash script from within the script itself



How do I get the path of the directory in which a Bash script is located, inside that script?



For instance, let's say I want to use a Bash script as a launcher for another application. I want to change the working directory to the one where the Bash script is located, so I can operate on the files in that directory, like so:



$ ./application

Answer



#!/bin/bash


DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )"


is a useful one-liner which will give you the full directory name of the script no matter where it is being called from.



It will work as long as the last component of the path used to find the script is not a symlink (directory links are OK). If you also want to resolve any links to the script itself, you need a multi-line solution:



#!/bin/bash

SOURCE="${BASH_SOURCE[0]}"

while [ -h "$SOURCE" ]; do # resolve $SOURCE until the file is no longer a symlink
DIR="$( cd -P "$( dirname "$SOURCE" )" >/dev/null 2>&1 && pwd )"
SOURCE="$(readlink "$SOURCE")"
[[ $SOURCE != /* ]] && SOURCE="$DIR/$SOURCE" # if $SOURCE was a relative symlink, we need to resolve it relative to the path where the symlink file was located
done
DIR="$( cd -P "$( dirname "$SOURCE" )" >/dev/null 2>&1 && pwd )"


This last one will work with any combination of aliases, source, bash -c, symlinks, etc.




Beware: if you cd to a different directory before running this snippet, the result may be incorrect!



Also, watch out for $CDPATH gotchas, and stderr output side effects if the user has smartly overridden cd to redirect output to stderr instead (including escape sequences, such as when calling update_terminal_cwd >&2 on Mac). Adding >/dev/null 2>&1 at the end of your cd command will take care of both possibilities.



To understand how it works, try running this more verbose form:



#!/bin/bash

SOURCE="${BASH_SOURCE[0]}"
while [ -h "$SOURCE" ]; do # resolve $SOURCE until the file is no longer a symlink

TARGET="$(readlink "$SOURCE")"
if [[ $TARGET == /* ]]; then
echo "SOURCE '$SOURCE' is an absolute symlink to '$TARGET'"
SOURCE="$TARGET"
else
DIR="$( dirname "$SOURCE" )"
echo "SOURCE '$SOURCE' is a relative symlink to '$TARGET' (relative to '$DIR')"
SOURCE="$DIR/$TARGET" # if $SOURCE was a relative symlink, we need to resolve it relative to the path where the symlink file was located
fi
done

echo "SOURCE is '$SOURCE'"
RDIR="$( dirname "$SOURCE" )"
DIR="$( cd -P "$( dirname "$SOURCE" )" >/dev/null 2>&1 && pwd )"
if [ "$DIR" != "$RDIR" ]; then
echo "DIR '$RDIR' resolves to '$DIR'"
fi
echo "DIR is '$DIR'"


And it will print something like:




SOURCE './scriptdir.sh' is a relative symlink to 'sym2/scriptdir.sh' (relative to '.')
SOURCE is './sym2/scriptdir.sh'
DIR './sym2' resolves to '/home/ubuntu/dotfiles/fo fo/real/real1/real2'
DIR is '/home/ubuntu/dotfiles/fo fo/real/real1/real2'

ending - What's the last song that the Expendables team members sing? - Movies & TV



Just back from seeing The Expendables 2 and was wondering what was the last song the Expendables team sing at the end?


Answer



These are the lyrics of the team hymn:





Beware, Beware, Walk With Care



Careful what You Do



Or Mumbo Jumbo's Gonna Hoodoo You,



Mumbo Jumbo Is Gonna Hoodoo You,



Boomlay, Boomlay, Boomlay, Boom!





It's a military cadence based on the 1912 Vachel Lindsay's poem "The Congo" (available here).


python - How to import the class within the same directory or sub directory?



I have a directory that stores all the .py files.




bin/
main.py
user.py # where class User resides
dir.py # where class Dir resides


I want to use classes from user.py and dir.py in main.py.
How can I import these Python classes into main.py?
Furthermore, how can I import class User if user.py is in a sub directory?



bin/

dir.py
main.py
usr/
user.py

Answer





Make an empty file called __init__.py in the same directory as the files. That will signify to Python that it's "ok to import from this directory".




Then just do...



from user import User
from dir import Dir


The same holds true if the files are in a subdirectory - put an __init__.py in the subdirectory as well, and then use regular import statements, with dot notation. For each level of directory, you need to add to the import path.



bin/
main.py

classes/
user.py
dir.py


So if the directory was named "classes", then you'd do this:



from classes.user import User
from classes.dir import Dir





Same as previous, but prefix the module name with a . if not using a subdirectory:



from .user import User
from .dir import Dir

javascript - how to solve cross domain in ajax




I want to solve my AJAX cross domain problem. This is the error message I receive in Chrome:





XMLHttpRequest cannot load http://'myaddress'/TEST/user/login/testuserid . Request header field Access-Control-Allow-Origin is not allowed by Access-Control-Allow-Headers.




this is my source code



$.ajax({
crossDomain : true,
dataType : "json",
url: fullUrl,

method: method,
headers:headers,
data: body,
success: function(data, state, res){
if (data == null)
data = '';

console.log( '[[[[[[[[SUCCESS!!]]]]]]] url: ' + url + ', state:' + state + ', data : ' + JSON.stringify( data ) );
callback(data, state, res);
},

error: function(data, state){
if ( data == null )
data = '';

console.log( '[[[[[[[[[ERROR!!]]]]]]]]] url: ' + url + ', s tate:' + state + ', data : ' + JSON.stringify( data ) );
callback(data, state, null);
}
});



Servlet code for cross Domain



httpRes.setHeader("Access-Control-Allow-Origin", "*");
httpRes.setHeader("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE");
httpRes.setHeader("Access-Control-Allow-Headers", "*");

Answer



You need to use JSONP to make CROSS DOMAIN Requests.



Please read:




Loading cross domain endpoint with jQuery AJAX



Make cross-domain ajax JSONP request with jQuery


reactjs - Programmatically navigate using react router


React-Router 5.1.0+ Answer (using hooks and React >16.8)



You can use the new useHistory hook on Functional Components and Programmatically navigate:


import { useHistory } from "react-router-dom";
function HomeButton() {
let history = useHistory();
// use history.push('/some/path') here
};


React-Router 4.0.0+ Answer



In 4.0 and above, use the history as a prop of your component.


class Example extends React.Component {
// use `this.props.history.push('/some/path')` here
};

NOTE: this.props.history does not exist in the case your component was not rendered by . You should use to have this.props.history in YourComponent



React-Router 3.0.0+ Answer



In 3.0 and above, use the router as a prop of your component.


class Example extends React.Component {
// use `this.props.router.push('/some/path')` here
};


React-Router 2.4.0+ Answer



In 2.4 and above, use a higher order component to get the router as a prop of your component.


import { withRouter } from 'react-router';
class Example extends React.Component {
// use `this.props.router.push('/some/path')` here
};
// Export the decorated class
var DecoratedExample = withRouter(Example);
// PropTypes
Example.propTypes = {
router: React.PropTypes.shape({
push: React.PropTypes.func.isRequired
}).isRequired
};


React-Router 2.0.0+ Answer



This version is backwards compatible with 1.x so there's no need to an Upgrade Guide. Just going through the examples should be good enough.


That said, if you wish to switch to the new pattern, there's a browserHistory module inside the router that you can access with


import { browserHistory } from 'react-router'


Now you have access to your browser history, so you can do things like push, replace, etc... Like:


browserHistory.push('/some/path')


Further reading:
Histories and
Navigation





React-Router 1.x.x Answer



I will not go into upgrading details. You can read about that in the Upgrade Guide


The main change about the question here is the change from Navigation mixin to History. Now it's using the browser historyAPI to change route so we will use pushState() from now on.


Here's an exemple using Mixin:


var Example = React.createClass({
mixins: [ History ],
navigateToHelpPage () {
this.history.pushState(null, `/help`);
}
})

Note that this History comes from rackt/history project. Not from React-Router itself.


If you don't want to use Mixin for some reason (maybe because of ES6 class), then you can access the history that you get from the router from this.props.history. It will be only accessible for the components rendered by your Router. So, if you want to use it in any child components it needs to be passed down as an attribute via props.


You can read more about the new release at their 1.0.x documentation


Here is a help page specifically about navigating outside your component


It recommends grabbing a reference history = createHistory() and calling replaceState on that.



React-Router 0.13.x Answer



I got into the same problem and could only find the solution with the Navigation mixin that comes with react-router.


Here's how I did it


import React from 'react';
import {Navigation} from 'react-router';
let Authentication = React.createClass({
mixins: [Navigation],
handleClick(e) {
e.preventDefault();
this.transitionTo('/');
},
render(){
return (
Click me!
);
}
});

I was able to call transitionTo() without the need to access .context


Or you could try the fancy ES6 class


import React from 'react';
export default class Authentication extends React.Component {
constructor(props) {
super(props);
this.handleClick = this.handleClick.bind(this);
}
handleClick(e) {
e.preventDefault();
this.context.router.transitionTo('/');
}
render(){
return (
Click me!
);
}
}
Authentication.contextTypes = {
router: React.PropTypes.func.isRequired
};


React-Router-Redux


Note: if you're using Redux, there is another project called
React-Router-Redux that gives you
redux bindings for ReactRouter, using somewhat the same approach that
React-Redux does



React-Router-Redux has a few methods available that allow for simple navigating from inside action creators. These can be particularly useful for people that have existing architecture in React Native, and they wish to utilize the same patterns in React Web with minimal boilerplate overhead.


Explore the following methods:



  • push(location)

  • replace(location)

  • go(number)

  • goBack()

  • goForward()


Here is an example usage, with Redux-Thunk:


./actioncreators.js


import { goBack } from 'react-router-redux'
export const onBackPress = () => (dispatch) => dispatch(goBack())

./viewcomponent.js


  disabled={submitting}
className="cancel_button"
onClick={(e) => {
e.preventDefault()
this.props.onBackPress()
}}
>
CANCEL

c++ - Why does 'std::vector b{2};' create a 1-element vector, and not a 2-element one?



I've been playing around with C++11 for the past few days, and I came up with something strange.



If I want to uniformly initialize an int:



int a{5};



But if I do the same thing to a std::vector:



std::vector b{2};


Does not construct a two element array, but rather an array with one element of value two. It seems like to get that effect one would need to be more explicit about it:



std::vector c{{2}};
std::vector d = {2};



But not like the declaration of b - this seems inconsistent. I have seen some other stuff to the same effect. What I'm asking - is this behavior in the final C++11 standard, or is it just in a draft that was implemented early? If so, why did the standards committee include this behavior? It seems like it defeats the whole purpose of uniform initialization, as one has to remember which classes have initializer list constructors, and to use the old () syntax instead of {} with just those classes. Or one forgoes uniform initialization altogether.



This seems like a big "gotcha". But there might be advantages to it that I am not aware of.



Edit: this code:



#include 
#include


int main() {
std::vector a{2};
for (auto x: a) {
std::cout << x << std::endl;
}
return 0;
}



outputs "2" on gcc 4.6.2


Answer



Yes, this behaviour is intended, according to §13.3.1.7 Initialization by list-initialization




When objects of non-aggregate class type T are list-initialized
(8.5.4), overload resolution selects the constructor in two phases:



— Initially, the candidate functions are the initializer-list
constructors (8.5.4) of the class T and the argument list consists of

the initializer list as a single argument.



— If no viable
initializer-list constructor is found, overload resolution is
performed again, where the candidate functions are all the
constructors of the class T and the argument list consists of the
elements of the initializer list.




As to "the whole purpose of uniform intialization"... "Uniform initialization" is a marketing term, and not a very good description. The standard has all the usual forms of initialization plus list-initialization, but no "uniform initialization". List initialization is not meant to be the ultimate form of initialization, it's just another tool in the utility belt.



Wednesday, August 29, 2018

java - nextDouble() throws an InputMismatchException when I enter a double



import java.util.*;

class Averager
{
public static double unlimited()
{
int count = 0;
double sum = 0;
Scanner scan = new Scanner(System.in);
while(scan.hasNext())
{
double d = scan.nextDouble();
sum += d;
count++;
}
double ave = sum/count;
return ave;
}

public static void main(String[] args) {
System.out.println(unlimited()+"\n");
}
}


There is no error when I use integers but if I use numbers with point in it a error appears.



$ javac Averager.java; java Averager
0.5
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:840)
at java.util.Scanner.next(Scanner.java:1461)
at java.util.Scanner.nextDouble(Scanner.java:2387)
at Averager.unlimited(Averager.java:12)
at Averager.main(Averager.java:21)


To my best understanding 0.5 should be covered by double. If not please can someone correct me.


Answer



It might be locale dependent. Decimal numbers are e.g written as 0,5 in Sweden.



Change your code so that it says e.g.:



Scanner scan = new Scanner(System.in);
scan.useLocale(Locale.US);

product placement - How did Starbucks, Fuddruckers, and Carl's Jr. respond to Idiocracy? - Movies & TV



In the movie Idiocracy (2006), several real-life name brands are made fun of. The three I remember:





  • Starbucks gives hand jobs

  • Fuddruckers changes its name to "Buttf***ers"

  • Carl's Jr. changes its slogan from "Don't bother me, I'm eating" to "F**k you! I'm eating."



Did the makers of Idiocracy make any effort to get permission to use these brand names? If not, have any of these companies expressed disapproval?


Answer



First of all, the production staff lawyered up real well. From a Slashfilm interview with Mike Judge:





And as far as the products stuff, I remember writing it and going, “Oh
man, there’s no way we’re going to clear all of this stuff.” And I had
a meeting with the lawyers, who were actually really cool and really
liked the script. [laughs] And in the Beavis & Butt-Head movie I
couldn’t even have a bottle that was shaped like a Jack Daniel’s
bottle. I couldn’t have, there was more, it was just ridiculous on
that [movie].



But on Idiocracy, when we were talking about Starbucks, the lawyers
said, “Well, it would help if you didn’t pick on just one company and

if you did more than one.” So, [laughs] I was like okay, and that’s
why there’s the whole red light district with Starbucks and there’s an
H&R Block with “Tax Return and Relief,” and all of that. But the other
stuff, Carl Jr’s, that was all in the script, and I couldn’t believe
it all cleared.




Second, it wasn't high profile enough to cause the companies any big issues (from the same interview):





At one point, [Fox] told me, “Hey, it’s not testing well, we’re not
going to spend a lot of money promoting it.”



OpenCV android : Hough transform rectangle recognition with image with multiple different sized rectangles



So everyone, my first question on stackoverflow.

I have been working with android and openCV for a month and I was able to successfully implement template Matching. Now, the next task is to detect all the rectangles in the image and get the coordinates (I actually want the color of every rectangle) for research purposes. Kindly help. I tried using Hough transform with canny edge detection but unfortunately it doesn't detect the small rectangles which is the primary concern now.



Thank you!![![Have to detect all the rectangles, small and big ones


Answer



So I'm really proud to post an answer to my own question. Hope this helps someone in future. There are obviously a lot of ways to do this but the most accurate way was to use template matching on the main image to find the coordinates of the biggest rectangle and since all the other rectangles are equidistant to the corner points, center of every rectangle can be found which gives the desired colors.



The thin strip in the middle was also recognized by template matching and then a gradient operator represented the various rectangles, every peak in the gradient represents the rectangles.



Kindly comment for code. For research purposes I cannot post to anonymous.


PHP constant encapsed string php error

This is the error I am getting.
"Parse error: syntax error, unexpected T_CONSTANT_ENCAPSED_STRING in on line 188"
What I am trying to do is connect to the database and insert data into the table, but i can't figure out this error.



$tableName = "customer";
$nullStr = "NULL";

$SQLstring = "INSERT INTO $tableName VALUES
('".$nullstr."','".$fname."', '".$lname."','".$address."','".$state."','".$zip."', '".$phone"','".$email"')";
$result = $mysqli->query($SQLstring);

c++ - Why is (foobar>>x) preferred over (! foobar.eof() )











My teacher said we shouldn't use EOF to read in text file or binary file information instead we should use (afile>>x). He didn't explain why, can someone explain to me. Can someone also explain what are the differences in this two different method of reading



//Assuming declaration 
//ifstream foobar




( ! foobar.eof() )
{
foobar>>x; // This is discouraged by my teacher

}


while (foobar>>x)
{

//This is encouraged by my teacher

}

Answer



Because the file is not at the end before you try to read from it.



operator>> returns a reference to the stream in the state it is after the read has been attempted and either succeeded or failed, and the stream evaluates to true if it succeeded or false if it failed. Testing for eof() first means that the file can have no useful data in it but not be at EOF yet, then when you read from it, it's at EOF and the read fails.



Another important detail is that operator>> for streams skips all leading whitespace, not trailing whitespace. This is why a file can not be at EOF before the read and be at EOF after a read.




Additionally, the former works when the next data in the file is data that cannot be read into an integer (for example, the next data is x), not just when it's at EOF, which is very important.



Example:



Consider the code:



int x, y;

f >> x;


if (!f.eof())
f >> y;


Assuming f is a file that contains the data 123␣ (the ␣ means space), the first read will succeed, but afterwards the file has no more integers in it and it is not at EOF. The second read will fail and the file will be at EOF, but you don't know because you tested for EOF before you tried reading. Then your code goes on to cause undefined behaviour because y is uninitialised.


plot explanation - Why did Peaches&#39; mom hang on the tree? - Movies &amp; TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...