Random data generator in java
i have to fill every property of a given object with a random value.
All properties are native java type (int, double, String, etc)
I canuse reflection
I can use Spring DirectFieldAccessor
I don't want to re-invent the square wheel so I prefer to ask.
For now I came up with this : Get all properties name with
Field field : myObject.getClass().getDeclaredFields()
Iterate over those field and get their class.
Then use a giant switch statement for each known native java type and
generate a random value.
What do you think?
Thursday, 3 October 2013
Wednesday, 2 October 2013
Count and Joins
Count and Joins
Customer
CustomerID Name
4001 John Bob
4002 Joey Markle
4003 Johny Brown
4004 Jessie Black
Orders
OrderID Customer
50001 4001
50002 4002
50003 4001
50004 4003
50005 4001
50006 4003
50007 4001
I tried this join
Select c.Customer, COUNT(o.OrderID) as TotalOrders
from Customer c
inner join Orders o
on c.Customer = o.Customer
Group by c.Customer
But here is the result.
Customer TotalOrders
4001 4
4002 1
4003 2
The customer with no order is not included. How I will include all the
customer even they don't have orders?
Customer TotalOrders
4001 4
4002 1
4003 2
4004 0
Customer
CustomerID Name
4001 John Bob
4002 Joey Markle
4003 Johny Brown
4004 Jessie Black
Orders
OrderID Customer
50001 4001
50002 4002
50003 4001
50004 4003
50005 4001
50006 4003
50007 4001
I tried this join
Select c.Customer, COUNT(o.OrderID) as TotalOrders
from Customer c
inner join Orders o
on c.Customer = o.Customer
Group by c.Customer
But here is the result.
Customer TotalOrders
4001 4
4002 1
4003 2
The customer with no order is not included. How I will include all the
customer even they don't have orders?
Customer TotalOrders
4001 4
4002 1
4003 2
4004 0
ReadObject is returning null values
ReadObject is returning null values
I have the following class design. My engine attribute is coming as null
each time,even though I have read its value from readObject
public class Car implements Serializable {
private int regId;
transient Engine e;
private void writeObject(ObjectOutputStream oos) {
try {
oos.defaultWriteObject();
oos.writeInt(e.horsePower);
} catch (Exception e) {
e.printStackTrace();
}
}
private void readObject(ObjectInputStream oxos) {
try {
oxos.defaultReadObject();
Engine e = new Engine(oxos.readInt());
} catch (Exception e) {
e.printStackTrace();
// TODO: handle exception
}
}
public class Engine {
int horsePower;
}
I have the following class design. My engine attribute is coming as null
each time,even though I have read its value from readObject
public class Car implements Serializable {
private int regId;
transient Engine e;
private void writeObject(ObjectOutputStream oos) {
try {
oos.defaultWriteObject();
oos.writeInt(e.horsePower);
} catch (Exception e) {
e.printStackTrace();
}
}
private void readObject(ObjectInputStream oxos) {
try {
oxos.defaultReadObject();
Engine e = new Engine(oxos.readInt());
} catch (Exception e) {
e.printStackTrace();
// TODO: handle exception
}
}
public class Engine {
int horsePower;
}
HTML/CSS Help w/ Validating! Unclosed Element
HTML/CSS Help w/ Validating! Unclosed Element
I am new to HTML and CSS and am trying to make it to CSS but when i use
the validaotr, it just says unclosed element!Ignore the pi
enter code here
<style>
h1{color:white;}
body{background-color:#C9C9DB;}
p{text-align:right;font-size:2em;}
p{color:#FFFFFF}
h2{color:white;font-size:1em;text-align:left;}
IMG.displayed {
display: block;
margin-left: auto;
margin-right: auto }
p1.italic {font-style:italic;}x
p1.a {list-style-type:circle;}
</style>
<p>MyTSC</p>
<IMG class="displayed" src="123.jpg" alt="Logo">
<hr width="50%" color="white"/>
<p style="font=size:2em;text-align:left;">My Fall Courses</p>
<h2>
<p1 class="a">
<li>
<p1 class="italic">COSC 4330 Computer Graphics</p1>
</br><li>
IMED 1416 Wed Design I
ITNW 2413 Networking Hardware
I am new to HTML and CSS and am trying to make it to CSS but when i use
the validaotr, it just says unclosed element!Ignore the pi
enter code here
<style>
h1{color:white;}
body{background-color:#C9C9DB;}
p{text-align:right;font-size:2em;}
p{color:#FFFFFF}
h2{color:white;font-size:1em;text-align:left;}
IMG.displayed {
display: block;
margin-left: auto;
margin-right: auto }
p1.italic {font-style:italic;}x
p1.a {list-style-type:circle;}
</style>
<p>MyTSC</p>
<IMG class="displayed" src="123.jpg" alt="Logo">
<hr width="50%" color="white"/>
<p style="font=size:2em;text-align:left;">My Fall Courses</p>
<h2>
<p1 class="a">
<li>
<p1 class="italic">COSC 4330 Computer Graphics</p1>
</br><li>
IMED 1416 Wed Design I
ITNW 2413 Networking Hardware
RGB to binary in android
RGB to binary in android
I would like to find an android code that will assist me convert an RGB
image to a binary image. Please assist. Also kindly assist me to find out
how I can modify a code as this below to integrate it for an Adroid mobile
application.
package ij.process;
import java.awt.*;
/** This class processes binary images. */
public class BinaryProcessor extends ByteProcessor {
private ByteProcessor parent;
/** Creates a BinaryProcessor from a ByteProcessor. The ByteProcessor
must contain a binary image (pixels values are either 0 or 255).
Backgound is assumed to be white. */
public BinaryProcessor(ByteProcessor ip) {
super(ip.getWidth(), ip.getHeight(), (byte[])ip.getPixels(),
ip.getColorModel());
setRoi(ip.getRoi());
parent = ip;
}
static final int OUTLINE=0;
void process(int type, int count) {
int p1, p2, p3, p4, p5, p6, p7, p8, p9;
int inc = roiHeight/25;
if (inc<1) inc = 1;
int bgColor = 255;
if (parent.isInvertedLut())
bgColor = 0;
byte[] pixels2 = (byte[])parent.getPixelsCopy();
int offset, v=0, sum;
int rowOffset = width;
for (int y=yMin; y<=yMax; y++) {
offset = xMin + y * width;
p2 = pixels2[offset-rowOffset-1]&0xff;
p3 = pixels2[offset-rowOffset]&0xff;
p5 = pixels2[offset-1]&0xff;
p6 = pixels2[offset]&0xff;
p8 = pixels2[offset+rowOffset-1]&0xff;
p9 = pixels2[offset+rowOffset]&0xff;
for (int x=xMin; x<=xMax; x++) {
p1 = p2; p2 = p3;
p3 = pixels2[offset-rowOffset+1]&0xff;
p4 = p5; p5 = p6;
p6 = pixels2[offset+1]&0xff;
p7 = p8; p8 = p9;
p9 = pixels2[offset+rowOffset+1]&0xff;
switch (type) {
case OUTLINE:
v = p5;
if (v!=bgColor) {
if (!(p1==bgColor || p2==bgColor ||
p3==bgColor || p4==bgColor
|| p6==bgColor || p7==bgColor ||
p8==bgColor || p9==bgColor))
v = bgColor;
}
break;
}
pixels[offset++] = (byte)v;
}
if (y%inc==0)
parent.showProgress((double)(y-roiY)/roiHeight);
}
parent.hideProgress();
}
// 2012/09/16: 3,0 1->0
// 2012/09/16: 24,0 2->0
private static int[] table =
//0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1
{0,0,0,0,0,0,1,3,0,0,3,1,1,0,1,3,0,0,0,0,0,0,0,0,0,0,2,0,3,0,3,3,
0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,3,0,2,2,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
2,0,0,0,0,0,0,0,2,0,0,0,2,0,0,0,3,0,0,0,0,0,0,0,3,0,0,0,3,0,2,0,
0,0,3,1,0,0,1,3,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,
3,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
2,3,1,3,0,0,1,3,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
2,3,0,1,0,0,0,1,0,0,0,0,0,0,0,0,3,3,0,1,0,0,0,0,2,2,0,0,2,0,0,0};
private static int[] table2 =
//0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1
{0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,2,2,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,2,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
/** Uses a lookup table to repeatably removes pixels from the
edges of objects in a binary image, reducing them to single
pixel wide skeletons. There is an entry in the table for each
of the 256 possible 3x3 neighborhood configurations. An entry
of '1' means delete pixel on first pass, '2' means delete pixel on
second pass, and '3' means delete on either pass. Pixels are
removed from the right and bottom edges of objects on the first
pass and from the left and top edges on the second pass. A
graphical representation of the 256 neighborhoods indexed by
the table is available at
"http://imagej.nih.gov/ij/images/skeletonize-table.gif".
*/
public void skeletonize() {
int pass = 0;
int pixelsRemoved;
resetRoi();
setColor(Color.white);
moveTo(0,0); lineTo(0,height-1);
moveTo(0,0); lineTo(width-1,0);
moveTo(width-1,0); lineTo(width-1,height-1);
moveTo(0,height-1); lineTo(width/*-1*/,height-1);
ij.ImageStack movie=null;
boolean debug = ij.IJ.debugMode;
if (debug) movie = new ij.ImageStack(width, height);
if (debug) movie.addSlice("-", duplicate());
do {
snapshot();
pixelsRemoved = thin(pass++, table);
if (debug) movie.addSlice(""+(pass-1), duplicate());
snapshot();
pixelsRemoved += thin(pass++, table);
if (debug) movie.addSlice(""+(pass-1), duplicate());
} while (pixelsRemoved>0);
do { // use a second table to remove "stuck" pixels
snapshot();
pixelsRemoved = thin(pass++, table2);
if (debug) movie.addSlice("2-"+(pass-1), duplicate());
snapshot();
pixelsRemoved += thin(pass++, table2);
if (debug) movie.addSlice("2-"+(pass-1), duplicate());
} while (pixelsRemoved>0);
if (debug) new ij.ImagePlus("Skel Movie", movie).show();
}
int thin(int pass, int[] table) {
int p1, p2, p3, p4, p5, p6, p7, p8, p9;
int bgColor = -1; //255
if (parent.isInvertedLut())
bgColor = 0;
byte[] pixels2 = (byte[])getPixelsCopy();
int v, index, code;
int offset, rowOffset = width;
int pixelsRemoved = 0;
int count = 100;
for (int y=yMin; y<=yMax; y++) {
offset = xMin + y * width;
for (int x=xMin; x<=xMax; x++) {
p5 = pixels2[offset];
v = p5;
if (v!=bgColor) {
p1 = pixels2[offset-rowOffset-1];
p2 = pixels2[offset-rowOffset];
p3 = pixels2[offset-rowOffset+1];
p4 = pixels2[offset-1];
p6 = pixels2[offset+1];
p7 = pixels2[offset+rowOffset-1];
p8 = pixels2[offset+rowOffset];
p9 = pixels2[offset+rowOffset+1];
index = 0;
if (p1!=bgColor) index |= 1;
if (p2!=bgColor) index |= 2;
if (p3!=bgColor) index |= 4;
if (p6!=bgColor) index |= 8;
if (p9!=bgColor) index |= 16;
if (p8!=bgColor) index |= 32;
if (p7!=bgColor) index |= 64;
if (p4!=bgColor) index |= 128;
code = table[index];
if ((pass&1)==1) { //odd pass
if (code==2||code==3) {
v = bgColor;
pixelsRemoved++;
}
} else { //even pass
if (code==1||code==3) {
v = bgColor;
pixelsRemoved++;
}
}
}
pixels[offset++] = (byte)v;
}
}
return pixelsRemoved;
}
public void outline() {
process(OUTLINE, 0);
}
}
I would like to find an android code that will assist me convert an RGB
image to a binary image. Please assist. Also kindly assist me to find out
how I can modify a code as this below to integrate it for an Adroid mobile
application.
package ij.process;
import java.awt.*;
/** This class processes binary images. */
public class BinaryProcessor extends ByteProcessor {
private ByteProcessor parent;
/** Creates a BinaryProcessor from a ByteProcessor. The ByteProcessor
must contain a binary image (pixels values are either 0 or 255).
Backgound is assumed to be white. */
public BinaryProcessor(ByteProcessor ip) {
super(ip.getWidth(), ip.getHeight(), (byte[])ip.getPixels(),
ip.getColorModel());
setRoi(ip.getRoi());
parent = ip;
}
static final int OUTLINE=0;
void process(int type, int count) {
int p1, p2, p3, p4, p5, p6, p7, p8, p9;
int inc = roiHeight/25;
if (inc<1) inc = 1;
int bgColor = 255;
if (parent.isInvertedLut())
bgColor = 0;
byte[] pixels2 = (byte[])parent.getPixelsCopy();
int offset, v=0, sum;
int rowOffset = width;
for (int y=yMin; y<=yMax; y++) {
offset = xMin + y * width;
p2 = pixels2[offset-rowOffset-1]&0xff;
p3 = pixels2[offset-rowOffset]&0xff;
p5 = pixels2[offset-1]&0xff;
p6 = pixels2[offset]&0xff;
p8 = pixels2[offset+rowOffset-1]&0xff;
p9 = pixels2[offset+rowOffset]&0xff;
for (int x=xMin; x<=xMax; x++) {
p1 = p2; p2 = p3;
p3 = pixels2[offset-rowOffset+1]&0xff;
p4 = p5; p5 = p6;
p6 = pixels2[offset+1]&0xff;
p7 = p8; p8 = p9;
p9 = pixels2[offset+rowOffset+1]&0xff;
switch (type) {
case OUTLINE:
v = p5;
if (v!=bgColor) {
if (!(p1==bgColor || p2==bgColor ||
p3==bgColor || p4==bgColor
|| p6==bgColor || p7==bgColor ||
p8==bgColor || p9==bgColor))
v = bgColor;
}
break;
}
pixels[offset++] = (byte)v;
}
if (y%inc==0)
parent.showProgress((double)(y-roiY)/roiHeight);
}
parent.hideProgress();
}
// 2012/09/16: 3,0 1->0
// 2012/09/16: 24,0 2->0
private static int[] table =
//0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1
{0,0,0,0,0,0,1,3,0,0,3,1,1,0,1,3,0,0,0,0,0,0,0,0,0,0,2,0,3,0,3,3,
0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,3,0,2,2,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
2,0,0,0,0,0,0,0,2,0,0,0,2,0,0,0,3,0,0,0,0,0,0,0,3,0,0,0,3,0,2,0,
0,0,3,1,0,0,1,3,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,
3,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
2,3,1,3,0,0,1,3,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
2,3,0,1,0,0,0,1,0,0,0,0,0,0,0,0,3,3,0,1,0,0,0,0,2,2,0,0,2,0,0,0};
private static int[] table2 =
//0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1
{0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,2,2,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,2,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
/** Uses a lookup table to repeatably removes pixels from the
edges of objects in a binary image, reducing them to single
pixel wide skeletons. There is an entry in the table for each
of the 256 possible 3x3 neighborhood configurations. An entry
of '1' means delete pixel on first pass, '2' means delete pixel on
second pass, and '3' means delete on either pass. Pixels are
removed from the right and bottom edges of objects on the first
pass and from the left and top edges on the second pass. A
graphical representation of the 256 neighborhoods indexed by
the table is available at
"http://imagej.nih.gov/ij/images/skeletonize-table.gif".
*/
public void skeletonize() {
int pass = 0;
int pixelsRemoved;
resetRoi();
setColor(Color.white);
moveTo(0,0); lineTo(0,height-1);
moveTo(0,0); lineTo(width-1,0);
moveTo(width-1,0); lineTo(width-1,height-1);
moveTo(0,height-1); lineTo(width/*-1*/,height-1);
ij.ImageStack movie=null;
boolean debug = ij.IJ.debugMode;
if (debug) movie = new ij.ImageStack(width, height);
if (debug) movie.addSlice("-", duplicate());
do {
snapshot();
pixelsRemoved = thin(pass++, table);
if (debug) movie.addSlice(""+(pass-1), duplicate());
snapshot();
pixelsRemoved += thin(pass++, table);
if (debug) movie.addSlice(""+(pass-1), duplicate());
} while (pixelsRemoved>0);
do { // use a second table to remove "stuck" pixels
snapshot();
pixelsRemoved = thin(pass++, table2);
if (debug) movie.addSlice("2-"+(pass-1), duplicate());
snapshot();
pixelsRemoved += thin(pass++, table2);
if (debug) movie.addSlice("2-"+(pass-1), duplicate());
} while (pixelsRemoved>0);
if (debug) new ij.ImagePlus("Skel Movie", movie).show();
}
int thin(int pass, int[] table) {
int p1, p2, p3, p4, p5, p6, p7, p8, p9;
int bgColor = -1; //255
if (parent.isInvertedLut())
bgColor = 0;
byte[] pixels2 = (byte[])getPixelsCopy();
int v, index, code;
int offset, rowOffset = width;
int pixelsRemoved = 0;
int count = 100;
for (int y=yMin; y<=yMax; y++) {
offset = xMin + y * width;
for (int x=xMin; x<=xMax; x++) {
p5 = pixels2[offset];
v = p5;
if (v!=bgColor) {
p1 = pixels2[offset-rowOffset-1];
p2 = pixels2[offset-rowOffset];
p3 = pixels2[offset-rowOffset+1];
p4 = pixels2[offset-1];
p6 = pixels2[offset+1];
p7 = pixels2[offset+rowOffset-1];
p8 = pixels2[offset+rowOffset];
p9 = pixels2[offset+rowOffset+1];
index = 0;
if (p1!=bgColor) index |= 1;
if (p2!=bgColor) index |= 2;
if (p3!=bgColor) index |= 4;
if (p6!=bgColor) index |= 8;
if (p9!=bgColor) index |= 16;
if (p8!=bgColor) index |= 32;
if (p7!=bgColor) index |= 64;
if (p4!=bgColor) index |= 128;
code = table[index];
if ((pass&1)==1) { //odd pass
if (code==2||code==3) {
v = bgColor;
pixelsRemoved++;
}
} else { //even pass
if (code==1||code==3) {
v = bgColor;
pixelsRemoved++;
}
}
}
pixels[offset++] = (byte)v;
}
}
return pixelsRemoved;
}
public void outline() {
process(OUTLINE, 0);
}
}
Tuesday, 1 October 2013
Pick 4 random elements from an NSArray of count 6
Pick 4 random elements from an NSArray of count 6
I am new to Objective C. I am coding the game Mastermind where the
computer chooses 4 random colors out of 6 and the user tries to guess the
4 colors in 6 tries.
I have an NSArray to represent all the six possible colors here:
NSArray * allColors = [[NSArray alloc] initWithObjects:@"r", @"g",
@"b", @"y", @"p", @"o", nil];
//Computer choose 4 random colors:
NSArray * computersSelection = [[NSArray alloc] init];
I need to write code to choose 4 UNIQUE random colors from the array. Is
there a smart way to do this?
I can create four int variables and use a while loop to generate four
random numbers and then pull the objects from the NSArray based on the
four random integer values and put them in the computerSelection array but
I am wondering if there's any simpler way of doing things?
Thanks
I am new to Objective C. I am coding the game Mastermind where the
computer chooses 4 random colors out of 6 and the user tries to guess the
4 colors in 6 tries.
I have an NSArray to represent all the six possible colors here:
NSArray * allColors = [[NSArray alloc] initWithObjects:@"r", @"g",
@"b", @"y", @"p", @"o", nil];
//Computer choose 4 random colors:
NSArray * computersSelection = [[NSArray alloc] init];
I need to write code to choose 4 UNIQUE random colors from the array. Is
there a smart way to do this?
I can create four int variables and use a while loop to generate four
random numbers and then pull the objects from the NSArray based on the
four random integer values and put them in the computerSelection array but
I am wondering if there's any simpler way of doing things?
Thanks
Menus in Batch File
Menus in Batch File
I don't usually create batch files as I just type what I need into the run
box or the command prompt but I'm trying to make one just to let me access
basic utilities in windows and check up on things (I really don't need it
but I think my dad would find it helpful). I am familiar (but new) with
python so if using python for these things is a better option I can do
that, however I thought batch was the best way of doing something as
simple as this. The problem is with my menu. I think because of my menu ,
it is cycling through all of the commands before doing the command
selected. Any help with this will be fully appreciated, the batch script
is in a code box below.
echo off
:menu
echo This is a simple cleanup and repair utility. Please select an option:
echo 1 - Check the hard disk c:\ for errors and inconsistancies.
echo 2 - Renew the IP address
echo 3 - View IP Address information
echo 4 - Check internet connection by pinging http://www.google.co.uk/
echo 5 - Start disk cleanup utility
echo 6 - ping 192.168.0.1
echo 7 - ping 192.168.1.1
echo 8 - Open notepad
choice /n /c:12345678 /M "Choose an option (1-8) "
IF ERRORLEVEL == 1 GOTO CHKDSK
IF ERRORLEVEL == 2 GOTO RENEW
IF ERRORLEVEL == 3 GOTO DISPLAYIP
IF ERRORLEVEL == 4 GOTO PINGGOOGLE
IF ERRORLEVEL == 5 GOTO CLEANMGR
IF ERRORLEVEL == 6 GOTO PING0
IF ERRORLEVEL == 7 GOTO PING1
IF ERRORLEVEL == 8 GOTO STARTNOTE
:CHKDSK
CHKDSK C:
PAUSE
goto menu
:RENEW
IPCONFIG /RENEW
PAUSE
goto menu
:DISPLAYIP
IPCONFIG /ALL
PAUSE
goto menu
:PINGGOOGLE
PING HTTP://WWW.GOOGLE.CO.UK/
PAUSE
goto menu
:CLEANMGR
CLEANMGR
PAUSE
goto menu
:PING0
PING 192.168.0.1
PAUSE
goto menu
:PING1
PING 192.168.1.1
PAUSE
goto menu
:STARTNOTE
START NOTEPAD
PAUSE
goto menu
I don't usually create batch files as I just type what I need into the run
box or the command prompt but I'm trying to make one just to let me access
basic utilities in windows and check up on things (I really don't need it
but I think my dad would find it helpful). I am familiar (but new) with
python so if using python for these things is a better option I can do
that, however I thought batch was the best way of doing something as
simple as this. The problem is with my menu. I think because of my menu ,
it is cycling through all of the commands before doing the command
selected. Any help with this will be fully appreciated, the batch script
is in a code box below.
echo off
:menu
echo This is a simple cleanup and repair utility. Please select an option:
echo 1 - Check the hard disk c:\ for errors and inconsistancies.
echo 2 - Renew the IP address
echo 3 - View IP Address information
echo 4 - Check internet connection by pinging http://www.google.co.uk/
echo 5 - Start disk cleanup utility
echo 6 - ping 192.168.0.1
echo 7 - ping 192.168.1.1
echo 8 - Open notepad
choice /n /c:12345678 /M "Choose an option (1-8) "
IF ERRORLEVEL == 1 GOTO CHKDSK
IF ERRORLEVEL == 2 GOTO RENEW
IF ERRORLEVEL == 3 GOTO DISPLAYIP
IF ERRORLEVEL == 4 GOTO PINGGOOGLE
IF ERRORLEVEL == 5 GOTO CLEANMGR
IF ERRORLEVEL == 6 GOTO PING0
IF ERRORLEVEL == 7 GOTO PING1
IF ERRORLEVEL == 8 GOTO STARTNOTE
:CHKDSK
CHKDSK C:
PAUSE
goto menu
:RENEW
IPCONFIG /RENEW
PAUSE
goto menu
:DISPLAYIP
IPCONFIG /ALL
PAUSE
goto menu
:PINGGOOGLE
PING HTTP://WWW.GOOGLE.CO.UK/
PAUSE
goto menu
:CLEANMGR
CLEANMGR
PAUSE
goto menu
:PING0
PING 192.168.0.1
PAUSE
goto menu
:PING1
PING 192.168.1.1
PAUSE
goto menu
:STARTNOTE
START NOTEPAD
PAUSE
goto menu
How can I tell if a certain IIS configuration key has been imported?
How can I tell if a certain IIS configuration key has been imported?
I'm building some configuration management scripts that need to be
idempotent. I need to check if the IIS keys for the web farm have been
imported on a server and if not import them.
I've got the commands to do the import, but I can't seem to find a
consistent way to check that a particular set of keys has been imported.
I'm building some configuration management scripts that need to be
idempotent. I need to check if the IIS keys for the web farm have been
imported on a server and if not import them.
I've got the commands to do the import, but I can't seem to find a
consistent way to check that a particular set of keys has been imported.
Setting mysqld to run at startup in MacOS
Setting mysqld to run at startup in MacOS
I using MacOS Machine for which every time I want to you mysql I have to
first start it using the following command
mysqld 2> /dev/null &
all seem great and thing work pleasantly after I run it but sure there is
way to avoid this as well has brought me over here I'm trying to find a
way to add it as script and run it in startup but I not sure how to
achieve
Another thing there is MySQL Server Status Application which look
something like this
Although I see something to display the status correctly but it Stop Mysql
server / Start Mysql server button did not work when try to use them
neither the check that states
Automatically Start MySql Server on Startup
Has any one got an idea how to fix this
Thanks
I using MacOS Machine for which every time I want to you mysql I have to
first start it using the following command
mysqld 2> /dev/null &
all seem great and thing work pleasantly after I run it but sure there is
way to avoid this as well has brought me over here I'm trying to find a
way to add it as script and run it in startup but I not sure how to
achieve
Another thing there is MySQL Server Status Application which look
something like this
Although I see something to display the status correctly but it Stop Mysql
server / Start Mysql server button did not work when try to use them
neither the check that states
Automatically Start MySql Server on Startup
Has any one got an idea how to fix this
Thanks
Monday, 30 September 2013
Fortigate bandwidth monitoring
Fortigate bandwidth monitoring
I have a Fortigate 200B with Forti OS 5.0.
How can I watch the total bandwidth being used by my unit both incoming
and outgoing?
Thanks
I have a Fortigate 200B with Forti OS 5.0.
How can I watch the total bandwidth being used by my unit both incoming
and outgoing?
Thanks
What seems wrong with this bash script?
What seems wrong with this bash script?
I found an initscript that for some reason insists on starting the
specified application as the root user. I can't wrap my head around why it
is doing this, any hints? The script runs on Redhat Enterprise Linux 5.9.
#!/bin/bash
#
# Start/Stop apfe.
#
# chkconfig: - 62 38
# description: apfe
# Start script for an apfe process.
# Apfe does not normally run as root, so we change user
# and call the real script in $USERDIR.
STARTUSER=apfe
USERDIR=/app/apfe/apps/apfeutils/bin
PROGNAME=apfe
su - $STARTUSER -c "$USERDIR/$PROGNAME $*"
I found an initscript that for some reason insists on starting the
specified application as the root user. I can't wrap my head around why it
is doing this, any hints? The script runs on Redhat Enterprise Linux 5.9.
#!/bin/bash
#
# Start/Stop apfe.
#
# chkconfig: - 62 38
# description: apfe
# Start script for an apfe process.
# Apfe does not normally run as root, so we change user
# and call the real script in $USERDIR.
STARTUSER=apfe
USERDIR=/app/apfe/apps/apfeutils/bin
PROGNAME=apfe
su - $STARTUSER -c "$USERDIR/$PROGNAME $*"
How can I check if website is already opened in a webbrowser?
How can I check if website is already opened in a webbrowser?
I'm doing this:
Process.Start("http://www.google.com");
After the default webbrowser is opened the website i want to check somehow
that the website is opened by the webbrowser and close the specicif tab
with this website.
To make a button click event that will check that if the website is
already opened then close it.
I'm doing this:
Process.Start("http://www.google.com");
After the default webbrowser is opened the website i want to check somehow
that the website is opened by the webbrowser and close the specicif tab
with this website.
To make a button click event that will check that if the website is
already opened then close it.
What does y scaling mean in svm-scale
What does y scaling mean in svm-scale
Does it mean to scale the value of the target(class),which is the first
column of every instance?
Regards,
amber@cent64 libsvm-3.17]$ svm-scale Usage: svm-scale [options]
data_filename options: -l lower : x scaling lower limit (default -1) -u
upper : x scaling upper limit (default +1) -y y_lower y_upper : y scaling
limits (default: no y scaling) -s save_filename : save scaling parameters
to save_filename -r restore_filename : restore scaling parameters from
restore_filename
Does it mean to scale the value of the target(class),which is the first
column of every instance?
Regards,
amber@cent64 libsvm-3.17]$ svm-scale Usage: svm-scale [options]
data_filename options: -l lower : x scaling lower limit (default -1) -u
upper : x scaling upper limit (default +1) -y y_lower y_upper : y scaling
limits (default: no y scaling) -s save_filename : save scaling parameters
to save_filename -r restore_filename : restore scaling parameters from
restore_filename
Sunday, 29 September 2013
responsive navigation links wont react to class
responsive navigation links wont react to class
I am working on a website simplemedia.dk
i have a responsive menu that works, but when i am trying to define the
in responsive mode the browsers does not recognize the style ..
in responsive mode i get a class called "responsified" and i tried adding
the class .responsified in front of my navigation style but it doesnt
react to it.
.responsive-menus .responsive-menus-0-0 .absolute .responsified
.responsive-toggled #navigation ul.menu{display:block; float:left; }
.responsive-menus .responsive-menus-0-0 .absolute .responsified
.responsive-toggled #navigation ul.menu li{display:block; float:left;}
In normal mode i want it to display table-cell which it does, but in
responsive i want it to show block.
I am working on a website simplemedia.dk
i have a responsive menu that works, but when i am trying to define the
in responsive mode the browsers does not recognize the style ..
in responsive mode i get a class called "responsified" and i tried adding
the class .responsified in front of my navigation style but it doesnt
react to it.
.responsive-menus .responsive-menus-0-0 .absolute .responsified
.responsive-toggled #navigation ul.menu{display:block; float:left; }
.responsive-menus .responsive-menus-0-0 .absolute .responsified
.responsive-toggled #navigation ul.menu li{display:block; float:left;}
In normal mode i want it to display table-cell which it does, but in
responsive i want it to show block.
How do I make a Time Conversion program on java?
How do I make a Time Conversion program on java?
![Its a Project im working on at school][1]
How do i make it go from Minutes-Hours? 135mins-2:15hours I just started
programming help me please!!
![Its a Project im working on at school][1]
How do i make it go from Minutes-Hours? 135mins-2:15hours I just started
programming help me please!!
How remap CTRL-key to Alt right (tried everything)
How remap CTRL-key to Alt right (tried everything)
My specs: Xubuntu 13.04, which uses (what I believe) Xorf as X Window
Manager.
Intro: some weeks ago I switched to Linux (Xubuntu). I configured
everything to work only with my keyboard without ever using the mouse.
Works like a charm. But recent, I wanted to remap the [ctrl] to
[capslock]. ~/.xmodmap seems not working. I found the answer here:
**/usr/bin/setxkbmap -option "ctrl:nocaps"** does the trick. I putted the
command as autostart.
Works fine until I got RSI-like issues with my left pink the last days. My
pink tingles weird and causes much pain at the end of day (even I'm using
ergonomic keyboard!). I tried everything to avoid this, like the correct
posture and taking breaks, weight lifting. Nothing helps. Then I looked
closer to my keyboard flow. I noticed I use the spacebar most, on second
the [Capslock]-button that behaves like [ctrl]. But I have no pain in my
thumbs. I dont use the right [Alt], so it would be better if I remap the
[ctrl]-key to [alt-key], so I can activate [ctrl] with my thumb.
What have I done?
Tried this: /usr/bin/setxkbmap -option "ctrl:alt_R" Not working.
Tried this: /usr/bin/setxkbmap -option "ctrl:Meta_R" Not working.
Tried the .xmodmap configuration. I start xev, pressed the right [alt] key
and it gives me keycode 108. [ctrl] gives me 37. So i create up ~/.Xmodmap
and map: keycode 108 = Control_L and reboot. Not working.
I've searched through the forums a lot, but have not found a solution. Any
suggestions how manage the right Alt+key behave as [ctrl]-key?
Thanks in advance for your appreciated help.
================== Edit: found the answer! Without the open source spirit,
I would never able to find my way here. And everyone benefits too!
The answer is..... bumbumbrrrrr...
setxkbmap -option ctrl:ralt_rctrl :D
My specs: Xubuntu 13.04, which uses (what I believe) Xorf as X Window
Manager.
Intro: some weeks ago I switched to Linux (Xubuntu). I configured
everything to work only with my keyboard without ever using the mouse.
Works like a charm. But recent, I wanted to remap the [ctrl] to
[capslock]. ~/.xmodmap seems not working. I found the answer here:
**/usr/bin/setxkbmap -option "ctrl:nocaps"** does the trick. I putted the
command as autostart.
Works fine until I got RSI-like issues with my left pink the last days. My
pink tingles weird and causes much pain at the end of day (even I'm using
ergonomic keyboard!). I tried everything to avoid this, like the correct
posture and taking breaks, weight lifting. Nothing helps. Then I looked
closer to my keyboard flow. I noticed I use the spacebar most, on second
the [Capslock]-button that behaves like [ctrl]. But I have no pain in my
thumbs. I dont use the right [Alt], so it would be better if I remap the
[ctrl]-key to [alt-key], so I can activate [ctrl] with my thumb.
What have I done?
Tried this: /usr/bin/setxkbmap -option "ctrl:alt_R" Not working.
Tried this: /usr/bin/setxkbmap -option "ctrl:Meta_R" Not working.
Tried the .xmodmap configuration. I start xev, pressed the right [alt] key
and it gives me keycode 108. [ctrl] gives me 37. So i create up ~/.Xmodmap
and map: keycode 108 = Control_L and reboot. Not working.
I've searched through the forums a lot, but have not found a solution. Any
suggestions how manage the right Alt+key behave as [ctrl]-key?
Thanks in advance for your appreciated help.
================== Edit: found the answer! Without the open source spirit,
I would never able to find my way here. And everyone benefits too!
The answer is..... bumbumbrrrrr...
setxkbmap -option ctrl:ralt_rctrl :D
Text alignment issue in a quote banner
Text alignment issue in a quote banner
as you can see on this JSFiddle and on picture below, I'm struggling to
get the signature placed as I want in my banner (I want it at the bottom
right of the blue banner without interfering with the quote text
alignment). The issue that I have is that with my current code the second
line of the text is not perfectly aligned horizontally to the middle of
the block (there's more space to the right than to the left). How could I
fix this and have full control on the signature position? Many thanks,
HTML:
<div class="block blueback center">
<h2 class="white">dfjdsjdklj dsjfdslfjldsjf ldsjfdlsjflkdsfjdlskjf
dljfdslfjkldsj dljfsdljfdklsj lkdjflkdsjdlks dsfjsdlkfjkls
dsjflkdsfjdkl</h2><p class="signature">John Dupont</p>
</div>
CSS:
.block {
display: block;
margin-right: auto;
margin-left: auto;
clear: both;
box-sizing: border-box;
padding-left: 20px;
padding-right: 20px;
width: 100%;
overflow: hidden;
}
h2 {
color: #2165CB;
font-weight: 600;
font-size: 18px;
}
.white { color: #fff;
letter-spacing: 1px;
font-style: italic;
font-weight: 300;
display: inline;
}
.center {
vertical-align: middle;
text-align: center;
padding-bottom: 5px;
padding-top: 5px;
}
.signature {
display: inline;
margin-top: 20px;
margin-bottom: 0px;
padding-top: 0px;
font-size: 12px;
color: #fff;
float: right;
font-weight: 700;
}
.blueback {
background: #0064C4;
}
as you can see on this JSFiddle and on picture below, I'm struggling to
get the signature placed as I want in my banner (I want it at the bottom
right of the blue banner without interfering with the quote text
alignment). The issue that I have is that with my current code the second
line of the text is not perfectly aligned horizontally to the middle of
the block (there's more space to the right than to the left). How could I
fix this and have full control on the signature position? Many thanks,
HTML:
<div class="block blueback center">
<h2 class="white">dfjdsjdklj dsjfdslfjldsjf ldsjfdlsjflkdsfjdlskjf
dljfdslfjkldsj dljfsdljfdklsj lkdjflkdsjdlks dsfjsdlkfjkls
dsjflkdsfjdkl</h2><p class="signature">John Dupont</p>
</div>
CSS:
.block {
display: block;
margin-right: auto;
margin-left: auto;
clear: both;
box-sizing: border-box;
padding-left: 20px;
padding-right: 20px;
width: 100%;
overflow: hidden;
}
h2 {
color: #2165CB;
font-weight: 600;
font-size: 18px;
}
.white { color: #fff;
letter-spacing: 1px;
font-style: italic;
font-weight: 300;
display: inline;
}
.center {
vertical-align: middle;
text-align: center;
padding-bottom: 5px;
padding-top: 5px;
}
.signature {
display: inline;
margin-top: 20px;
margin-bottom: 0px;
padding-top: 0px;
font-size: 12px;
color: #fff;
float: right;
font-weight: 700;
}
.blueback {
background: #0064C4;
}
Saturday, 28 September 2013
In PHP would this be deemed correct?
In PHP would this be deemed correct?
I already wrote a post about an issue I had before about this but I had
that issue taken care of. Like my last post I have a form, text-box and a
button. I have everything done with this including Printing the original
word, Printing the number of characters in the word, Printing the word in
all caps and Printing the word in reverse order. My only issue I'm having
is trying to get whatever text I enter and then click the button to output
to Print the first letter of the word and Print the last letter of the
word. I've been doing a lot of looking around of PHP.net and I found that
substr is used to return a part of a string that I could use. The only
issue is when I write the code for it and try to execute my program it
errors out on that specific line. I'm not looking for the answer but could
someone just take a look and see what I'm doing wrong because I understand
everything completely but this is the only thing I'm hung up on.
$first = substr($_POST['entertext']);
echo "The first letter of the word is " . $first. "<br />\n";
$last = substr($_POST['entertext']);
echo "The first letter of the word is " . $last. "<br />\n";
I already wrote a post about an issue I had before about this but I had
that issue taken care of. Like my last post I have a form, text-box and a
button. I have everything done with this including Printing the original
word, Printing the number of characters in the word, Printing the word in
all caps and Printing the word in reverse order. My only issue I'm having
is trying to get whatever text I enter and then click the button to output
to Print the first letter of the word and Print the last letter of the
word. I've been doing a lot of looking around of PHP.net and I found that
substr is used to return a part of a string that I could use. The only
issue is when I write the code for it and try to execute my program it
errors out on that specific line. I'm not looking for the answer but could
someone just take a look and see what I'm doing wrong because I understand
everything completely but this is the only thing I'm hung up on.
$first = substr($_POST['entertext']);
echo "The first letter of the word is " . $first. "<br />\n";
$last = substr($_POST['entertext']);
echo "The first letter of the word is " . $last. "<br />\n";
Jersey framework override contoller methods or REST request filtering
Jersey framework override contoller methods or REST request filtering
I need to implement a controller for processing requests whith filter use
Jersey framework. For example:
.../myservice/book - display a list of all books.
.../myservice/book?chapter=1,5 - display 1 and 5 books chapters.
.../myservice/book?page=10,50 - display 10 and 50 books pages.
.../myservice/book?chapter=1,5&page=10,50 - display 1 and 5 books chapters
and only 10 and 50 book pages.
I can't use .../myservice/book/chapter/1,5/page/10,50, because possible
situation: .../myservice/book/7 - display book 7 and filters described
above can be applied here. Is it possible to implement it in this way:
public class TestController {
@Path("/book")
@GET
public Object getBook() {
// return a list of all books
}
public Object getBook(@QueryParam("chapter") String chapter) {
// return books chapters
}
public Object getBook(@QueryParam("chapter") String page) {
// return books pages
}
public Object getBook(@QueryParam("chapter") String page,
@QueryParam("page") String page) {
// return books chapters and pages
}
}
Or to add all kinds of filters in one method and verify the presence of a
large number of conditions?
I need to implement a controller for processing requests whith filter use
Jersey framework. For example:
.../myservice/book - display a list of all books.
.../myservice/book?chapter=1,5 - display 1 and 5 books chapters.
.../myservice/book?page=10,50 - display 10 and 50 books pages.
.../myservice/book?chapter=1,5&page=10,50 - display 1 and 5 books chapters
and only 10 and 50 book pages.
I can't use .../myservice/book/chapter/1,5/page/10,50, because possible
situation: .../myservice/book/7 - display book 7 and filters described
above can be applied here. Is it possible to implement it in this way:
public class TestController {
@Path("/book")
@GET
public Object getBook() {
// return a list of all books
}
public Object getBook(@QueryParam("chapter") String chapter) {
// return books chapters
}
public Object getBook(@QueryParam("chapter") String page) {
// return books pages
}
public Object getBook(@QueryParam("chapter") String page,
@QueryParam("page") String page) {
// return books chapters and pages
}
}
Or to add all kinds of filters in one method and verify the presence of a
large number of conditions?
How to make Intro Section visible on mobile device (Wordpress Responsive Theme)
How to make Intro Section visible on mobile device (Wordpress Responsive
Theme)
I need some help to custom my site. You can take a look to my site first
http://next.coupleshops.com
You can see the first intro section, "We proudly present, ...." (it's a
Image file)
The problem is when I open it from mobile device like iphone or samsung
galaxy, the intro section won't show up. it skipped to the "News" section.
Anyone know how to make it visible and responsive on mobile device?
Theme)
I need some help to custom my site. You can take a look to my site first
http://next.coupleshops.com
You can see the first intro section, "We proudly present, ...." (it's a
Image file)
The problem is when I open it from mobile device like iphone or samsung
galaxy, the intro section won't show up. it skipped to the "News" section.
Anyone know how to make it visible and responsive on mobile device?
Friday, 27 September 2013
Postgresql: how to correctly create timestamp with timezone from timestamp, timezone fields
Postgresql: how to correctly create timestamp with timezone from
timestamp, timezone fields
I have a table with a timestamp without time zone. YYYY-MM-DD HH:MM:SS
and a field "timezone" that is either "P" for Pacific or "M" for Mountain.
I need to create a field of type "timestamp with time zone"
Given the two fields I have, is there a way to do this that correctly
accounts for Daylight Saving Time?
Specifically: timestamp: 2013-11-03 01:00:00 timezone: "P" would become:
2013-11-03 01:00:00-07
and timestamp: 2013-11-03 03:00:00 timezone: "P" would become: 2013-11-03
01:00:00-08
timestamp, timezone fields
I have a table with a timestamp without time zone. YYYY-MM-DD HH:MM:SS
and a field "timezone" that is either "P" for Pacific or "M" for Mountain.
I need to create a field of type "timestamp with time zone"
Given the two fields I have, is there a way to do this that correctly
accounts for Daylight Saving Time?
Specifically: timestamp: 2013-11-03 01:00:00 timezone: "P" would become:
2013-11-03 01:00:00-07
and timestamp: 2013-11-03 03:00:00 timezone: "P" would become: 2013-11-03
01:00:00-08
MySQL - given multiple associations, how to get latest association for several records?
MySQL - given multiple associations, how to get latest association for
several records?
Let's say I have two tables (non-essential rows omitted):
Table `pages`
page_id | page_key
1 | home
2 | about
and
Table `page_versions`
page_id | page_version | page_title | page_content
1 | 2 | Home | Lorem Ipsum...
1 | 4 | Home | Dolor Sit...
2 | 3 | About | Nunc Nisl...
2 | 5 | About | Proin Alt...
If each page has multiple page_versions, how do I query the database such
that I get all pages associated to their latest page_version?
Essentially:
page_id | page_key | page_version | page_title | page_content
1 | home | 4 | Home | Dolor Sit...
2 | about | 5 | About | Proin Alt...
several records?
Let's say I have two tables (non-essential rows omitted):
Table `pages`
page_id | page_key
1 | home
2 | about
and
Table `page_versions`
page_id | page_version | page_title | page_content
1 | 2 | Home | Lorem Ipsum...
1 | 4 | Home | Dolor Sit...
2 | 3 | About | Nunc Nisl...
2 | 5 | About | Proin Alt...
If each page has multiple page_versions, how do I query the database such
that I get all pages associated to their latest page_version?
Essentially:
page_id | page_key | page_version | page_title | page_content
1 | home | 4 | Home | Dolor Sit...
2 | about | 5 | About | Proin Alt...
global operator + override clash detection
global operator + override clash detection
My code is is clashing with a 3rd party library. I define this:
inline __m128 operator + (__m128 a, __m128 b)
{
return _mm_add_ps(a, b);
}
but get
error C2084: function '__m128 operator +(const __m128,const __m128)'
already has a body
I can't change the 3rd party library and they don't #define anything which
identifies this operator as having been defined. Is there a way (perhaps
using SFINAE) that anyone knows of to allow their definition to prevail?
My code is is clashing with a 3rd party library. I define this:
inline __m128 operator + (__m128 a, __m128 b)
{
return _mm_add_ps(a, b);
}
but get
error C2084: function '__m128 operator +(const __m128,const __m128)'
already has a body
I can't change the 3rd party library and they don't #define anything which
identifies this operator as having been defined. Is there a way (perhaps
using SFINAE) that anyone knows of to allow their definition to prevail?
Thread start in main method
Thread start in main method
I am attempting to start a thread inside of the main method, but it will
not call the run method when i start the thread. I think it may have
something to do with starting a thread in a thread:
package com.audiack.theForest;
public class theForestThread implements Runnable {
private static int theBeginningTimes = 0;
private static TheBeginning theBeginning = new TheBeginning();
public static void main(String args[]){
Thread thread = new Thread();
thread.start();
}
@Override
public void run() {
theBeginning.start(theBeginningTimes);
theBeginningTimes++;
}
}
I am attempting to start a thread inside of the main method, but it will
not call the run method when i start the thread. I think it may have
something to do with starting a thread in a thread:
package com.audiack.theForest;
public class theForestThread implements Runnable {
private static int theBeginningTimes = 0;
private static TheBeginning theBeginning = new TheBeginning();
public static void main(String args[]){
Thread thread = new Thread();
thread.start();
}
@Override
public void run() {
theBeginning.start(theBeginningTimes);
theBeginningTimes++;
}
}
How to create EF in scosta smartcard
How to create EF in scosta smartcard
I m writing into scosta smartcard card by using APDU commands. I am able
to create MF and DF but when I am creating EF i am getting 6A80 error.
Command which i m using for creating the EF, 00 E0 00 00 09 62 07 82 01 00
83 02 4004 00
Please provide me the command for creating EF.
Thanks in advance.
I m writing into scosta smartcard card by using APDU commands. I am able
to create MF and DF but when I am creating EF i am getting 6A80 error.
Command which i m using for creating the EF, 00 E0 00 00 09 62 07 82 01 00
83 02 4004 00
Please provide me the command for creating EF.
Thanks in advance.
Thursday, 26 September 2013
jQuery datetimepicker option minDateTime bug?
jQuery datetimepicker option minDateTime bug?
<html lang="en">
<head>
<meta charset="utf-8" />
<title>jQuery UI Datepicker - Default functionality</title>
<link rel="stylesheet"
href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css"
/>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css" />
<style>
/* css for timepicker */
.ui-timepicker-div .ui-widget-header { margin-bottom: 8px; }
.ui-timepicker-div dl { text-align: left; }
.ui-timepicker-div dl dt { float: left; clear:left; padding: 0 0 0 5px; }
.ui-timepicker-div dl dd { margin: 0 10px 10px 45%; }
.ui-timepicker-div td { font-size: 90%; }
.ui-tpicker-grid-label { background: none; border: none; margin: 0;
padding: 0; }
.ui-timepicker-rtl{ direction: rtl; }
.ui-timepicker-rtl dl { text-align: right; padding: 0 5px 0 0; }
.ui-timepicker-rtl dl dt{ float: right; clear: right; }
.ui-timepicker-rtl dl dd { margin: 0 45% 10px 10px; }
</style>
<script
src="http://trentrichardson.com/examples/timepicker/jquery-ui-timepicker-addon.js"></script>
<script>
$(function() {
$( "#datetimepicker" ).datetimepicker({
minDateTime:new Date("2015/03/04 20:15"),
controlType:'select'
});
});
</script>
</head>
<body>
Date: <input type="text" id="datetimepicker" />
</body>
</html>
I set a minDateTime as "2015/03/04 20:15" for #datetimepicker,when I click
it ,For each hour of the day can not select the number of minutes less
than 15. jQuery datetimepicker option minDateTime bug?or my way is wrong?
<html lang="en">
<head>
<meta charset="utf-8" />
<title>jQuery UI Datepicker - Default functionality</title>
<link rel="stylesheet"
href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css"
/>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css" />
<style>
/* css for timepicker */
.ui-timepicker-div .ui-widget-header { margin-bottom: 8px; }
.ui-timepicker-div dl { text-align: left; }
.ui-timepicker-div dl dt { float: left; clear:left; padding: 0 0 0 5px; }
.ui-timepicker-div dl dd { margin: 0 10px 10px 45%; }
.ui-timepicker-div td { font-size: 90%; }
.ui-tpicker-grid-label { background: none; border: none; margin: 0;
padding: 0; }
.ui-timepicker-rtl{ direction: rtl; }
.ui-timepicker-rtl dl { text-align: right; padding: 0 5px 0 0; }
.ui-timepicker-rtl dl dt{ float: right; clear: right; }
.ui-timepicker-rtl dl dd { margin: 0 45% 10px 10px; }
</style>
<script
src="http://trentrichardson.com/examples/timepicker/jquery-ui-timepicker-addon.js"></script>
<script>
$(function() {
$( "#datetimepicker" ).datetimepicker({
minDateTime:new Date("2015/03/04 20:15"),
controlType:'select'
});
});
</script>
</head>
<body>
Date: <input type="text" id="datetimepicker" />
</body>
</html>
I set a minDateTime as "2015/03/04 20:15" for #datetimepicker,when I click
it ,For each hour of the day can not select the number of minutes less
than 15. jQuery datetimepicker option minDateTime bug?or my way is wrong?
Wednesday, 25 September 2013
Error moving jQuery slider with iScroll5 beta
Error moving jQuery slider with iScroll5 beta
I'm working on iScroll5 Beta. I want to make a magazine style mobile webpage.
http://bit.ly/1b7FQco
When I swipe left or right, it works well and slider would move to right
position. But there is a problem. When I drag a slider point on bottom
bar, "scrollTo(-320 * e.target.value, 0, 500);" is works well. And then I
swipe up and down on color page, unsuspected page would be shown. I'm not
good at writing English. So I made a movie when I swipe it.
Swipe Error You Tube File
http://www.youtube.com/watch?feature=player_detailpage&v=4P5N0r_dKyg
After watching this video, you would know what the problem is.
Here's codes.
Script
var myScroll;
function loaded () {
myScroll = new IScroll('#wrapper', {
scrollX: true,
scrollY: false,
momentum: false,
snap: true,
snapSpeed: 400,
tap: true,
click: true
});
myScroll.on("scrollEnd", function() {
$('#slider-1').val(myScroll.currentPage.pageX);
});
$('#slider-1').bind('mouseup', function(e) {
myScroll.scrollTo(-320 * e.target.value, 0, 500);
myScroll.x = -320 * e.target.value;
myScroll.currentPage.x = -320 * e.target.value;
myScroll.currentPage.pageX = e.target.value;
});
}
I'm working on iScroll5 Beta. I want to make a magazine style mobile webpage.
http://bit.ly/1b7FQco
When I swipe left or right, it works well and slider would move to right
position. But there is a problem. When I drag a slider point on bottom
bar, "scrollTo(-320 * e.target.value, 0, 500);" is works well. And then I
swipe up and down on color page, unsuspected page would be shown. I'm not
good at writing English. So I made a movie when I swipe it.
Swipe Error You Tube File
http://www.youtube.com/watch?feature=player_detailpage&v=4P5N0r_dKyg
After watching this video, you would know what the problem is.
Here's codes.
Script
var myScroll;
function loaded () {
myScroll = new IScroll('#wrapper', {
scrollX: true,
scrollY: false,
momentum: false,
snap: true,
snapSpeed: 400,
tap: true,
click: true
});
myScroll.on("scrollEnd", function() {
$('#slider-1').val(myScroll.currentPage.pageX);
});
$('#slider-1').bind('mouseup', function(e) {
myScroll.scrollTo(-320 * e.target.value, 0, 500);
myScroll.x = -320 * e.target.value;
myScroll.currentPage.x = -320 * e.target.value;
myScroll.currentPage.pageX = e.target.value;
});
}
Thursday, 19 September 2013
Enable Firebug lite to edit HTML
Enable Firebug lite to edit HTML
The little sister of Firebug is a standalone Javascript tool -> Firebug lite
Source
or hosted
https://getfirebug.com/firebug-lite.js
There are some options to set: https://getfirebug.com/firebuglite#Options
so i included the js into my index.html and users without Firebug can now
inspect my page.
But how do we edit the html with firebug lite?
The little sister of Firebug is a standalone Javascript tool -> Firebug lite
Source
or hosted
https://getfirebug.com/firebug-lite.js
There are some options to set: https://getfirebug.com/firebuglite#Options
so i included the js into my index.html and users without Firebug can now
inspect my page.
But how do we edit the html with firebug lite?
how to save the html form data into a text file?
how to save the html form data into a text file?
i have a html form layout, i want to retrieve the input data entered by
the user in this form and save it in a text file, how to do this ?
HTML:
<form method="post" action="welcome.php">
Name: <input type="text" name="name" id="name" />
Email: <input type="text" name="email" id="email" />
<input type="submit" name="submit" value="Send Form" />
</form>
i have tried this php code for welcome.php, but it is not working, can you
indicate any mistakes in this code, PHP:
<?php
$file = $_POST['name'];
$email = $_POST['email'];
$ex = ".txt";
$write = fopen("$file$ex","w");
fwrite($write,$email);
fclose($write);
$data = "/localhost/";
rename ("$file","$data$file$ex");
header('Location: http:localhost/welcome.php');
exit;
?>
i have a html form layout, i want to retrieve the input data entered by
the user in this form and save it in a text file, how to do this ?
HTML:
<form method="post" action="welcome.php">
Name: <input type="text" name="name" id="name" />
Email: <input type="text" name="email" id="email" />
<input type="submit" name="submit" value="Send Form" />
</form>
i have tried this php code for welcome.php, but it is not working, can you
indicate any mistakes in this code, PHP:
<?php
$file = $_POST['name'];
$email = $_POST['email'];
$ex = ".txt";
$write = fopen("$file$ex","w");
fwrite($write,$email);
fclose($write);
$data = "/localhost/";
rename ("$file","$data$file$ex");
header('Location: http:localhost/welcome.php');
exit;
?>
Excel VBA Copying Sheets to a New Workbook and emailing the New Workbook in Outlook
Excel VBA Copying Sheets to a New Workbook and emailing the New Workbook
in Outlook
I have a segment of code that attaches the current file to an e-mail
addressed to our sales rep y is equal to the sales rep email. and to the
orders email for our company.
Instead of attaching the whole document to this email I want to copy tabs
from the document and paste them into a new document. Then send only the
new document (thereby reducing file size and hopefully changing it from a
.xlsm attachment to a .xls attachment).
If ShapesAfter > ShapesBefore Then
MsgBox "Please Repair Invalid Equipment Selection", , "Invalid
Selections _
Have Been Made"
ElseIf ShapesAfter = ShapesBefore Then
Sheets("inputs").Select
Dim y As String
y = Cells(61, 5).Value
Sheets("config").Select
Application.Dialogs(xlDialogSendMail).Show "" & y & "; " &
"orders@domainname.com"
in Outlook
I have a segment of code that attaches the current file to an e-mail
addressed to our sales rep y is equal to the sales rep email. and to the
orders email for our company.
Instead of attaching the whole document to this email I want to copy tabs
from the document and paste them into a new document. Then send only the
new document (thereby reducing file size and hopefully changing it from a
.xlsm attachment to a .xls attachment).
If ShapesAfter > ShapesBefore Then
MsgBox "Please Repair Invalid Equipment Selection", , "Invalid
Selections _
Have Been Made"
ElseIf ShapesAfter = ShapesBefore Then
Sheets("inputs").Select
Dim y As String
y = Cells(61, 5).Value
Sheets("config").Select
Application.Dialogs(xlDialogSendMail).Show "" & y & "; " &
"orders@domainname.com"
C++ Delete a pointer using delete []?
C++ Delete a pointer using delete []?
Here is the sample code piece in C++:
Foo *ptr;
ptr = new Foo;
delete [] ptr;
Could this run into problem? What should be the correct way to delete such
a pointer and free the memory?
Thank you
Here is the sample code piece in C++:
Foo *ptr;
ptr = new Foo;
delete [] ptr;
Could this run into problem? What should be the correct way to delete such
a pointer and free the memory?
Thank you
Calculate the qty of items that were purchased more than once by a customer - but need to exclude the first order qty
Calculate the qty of items that were purchased more than once by a
customer - but need to exclude the first order qty
SELECT TOP 100 PERCENT soheader.custid,SOHeader.OrdNbr,
SOLine.InvtID, SOLine.Descr,SOLine.QtyOrd
FROM SOHeader INNER JOIN
SOLine ON SOHeader.OrdNbr = SOLine.OrdNbr
WHERE (SOHeader.OrdDate >= CONVERT(DATETIME, '2013-06-01 00:00:00',
102)) AND (SOHeader.OrdDate <= GETDATE()) AND (SOHeader.CustID = '69065')
ORDER BY SOLine.InvtID, SOHeader.OrdNbr
here is my sample data
69065 WO0175279 69407 Jazzy Laces White 3
69065 WO0175393 69407 Jazzy Laces White 6
69065 WO0175393 69407 Jazzy Laces White 9
Now I want to know how to get the total qty of this item ordered after the
first order. I do not want to include the qty of 3 in the first record
above. I just want to include the qty of 6 in the first reorder and the
qty 9 of the second reorder which equals the qty of 15.
69065 is the customer ID
WO##### is the order ID
69407 is the inventory ID
customer - but need to exclude the first order qty
SELECT TOP 100 PERCENT soheader.custid,SOHeader.OrdNbr,
SOLine.InvtID, SOLine.Descr,SOLine.QtyOrd
FROM SOHeader INNER JOIN
SOLine ON SOHeader.OrdNbr = SOLine.OrdNbr
WHERE (SOHeader.OrdDate >= CONVERT(DATETIME, '2013-06-01 00:00:00',
102)) AND (SOHeader.OrdDate <= GETDATE()) AND (SOHeader.CustID = '69065')
ORDER BY SOLine.InvtID, SOHeader.OrdNbr
here is my sample data
69065 WO0175279 69407 Jazzy Laces White 3
69065 WO0175393 69407 Jazzy Laces White 6
69065 WO0175393 69407 Jazzy Laces White 9
Now I want to know how to get the total qty of this item ordered after the
first order. I do not want to include the qty of 3 in the first record
above. I just want to include the qty of 6 in the first reorder and the
qty 9 of the second reorder which equals the qty of 15.
69065 is the customer ID
WO##### is the order ID
69407 is the inventory ID
Flash builder: datagrid remove item - index out of bound
Flash builder: datagrid remove item - index out of bound
I have an issue wich i can't solve atm, a little helo would be much
appreciated. A local XML file is loaded into a HTTPservice and load the
data into a Datagrid. The local file cotains information about locally
stored files.
Just to be secure and sure, when the AIR app loads, i want to run through
the loaded datagrid and check if the local file exists. If it doens't
exist, i want to detele the row in the datagrid.
Doing that i get this annoying error: The supplied index is out of bounds.
I know that, deleting an element in the datagrid will result in new
indexes wich causes this error.
Thanks for your advice!
public function checkiffileislocal(event:Event):void{
var i:int;
var count:Number = (dgUserRequest.dataProvider as
ICollectionView).length;
for (i=0;i < count;i++)
{
dgUserRequest.selectedIndex = i;
if
(File.applicationStorageDirectory.resolvePath(dgUserRequest.selectedItem.id).exists
== false)
{
dgUserRequest.removeChildAt(dgUserRequest.selectedIndex);
}
}
}
I have an issue wich i can't solve atm, a little helo would be much
appreciated. A local XML file is loaded into a HTTPservice and load the
data into a Datagrid. The local file cotains information about locally
stored files.
Just to be secure and sure, when the AIR app loads, i want to run through
the loaded datagrid and check if the local file exists. If it doens't
exist, i want to detele the row in the datagrid.
Doing that i get this annoying error: The supplied index is out of bounds.
I know that, deleting an element in the datagrid will result in new
indexes wich causes this error.
Thanks for your advice!
public function checkiffileislocal(event:Event):void{
var i:int;
var count:Number = (dgUserRequest.dataProvider as
ICollectionView).length;
for (i=0;i < count;i++)
{
dgUserRequest.selectedIndex = i;
if
(File.applicationStorageDirectory.resolvePath(dgUserRequest.selectedItem.id).exists
== false)
{
dgUserRequest.removeChildAt(dgUserRequest.selectedIndex);
}
}
}
@media screen not working
@media screen not working
I have difficulties with changin styles for links inside row of Foundation
Framework 4. This is my code:
<div class="row career-nav">
<div class="large-1 columns text-left"><h3><a href="{{
path('job_offer_list')}}">All</a> </h3></div>
<div class="large-2 columns text-left"><h3><a href="{{
path('job_offer_listgroup',{'type':"Students"})}}">Students</a></h3></div>
<div class="large-3 columns text-left"><h3><a href="{{
path('job_offer_listgroup',{'type':"Young
Professionals"})}}">Young Professionals</a></h3></div>
<div class="large-6 columns text-left"><h3><a href="{{
path('job_offer_listgroup',{'type':"Professionals"})}}">Professionals</a></h3></div>
</div>
and CSS settings:
.career-nav a:link{
color:#58595B;
}
@media only screen and (min-width: 48em) {
.columns.text-left a:link {color:#58595B;}
}
First I tried to solve the problem with CSS settings, created new div
class after div "row", with the name ".career-nav", but it didnt work,
then I commented that and started to write mediaqueries. But as I am new
in Foundation Framework I am not sure that I did the right query,
therefore I want to know, which method is the best one for such
adjustement and what I missed in my code. Thank you!
I have difficulties with changin styles for links inside row of Foundation
Framework 4. This is my code:
<div class="row career-nav">
<div class="large-1 columns text-left"><h3><a href="{{
path('job_offer_list')}}">All</a> </h3></div>
<div class="large-2 columns text-left"><h3><a href="{{
path('job_offer_listgroup',{'type':"Students"})}}">Students</a></h3></div>
<div class="large-3 columns text-left"><h3><a href="{{
path('job_offer_listgroup',{'type':"Young
Professionals"})}}">Young Professionals</a></h3></div>
<div class="large-6 columns text-left"><h3><a href="{{
path('job_offer_listgroup',{'type':"Professionals"})}}">Professionals</a></h3></div>
</div>
and CSS settings:
.career-nav a:link{
color:#58595B;
}
@media only screen and (min-width: 48em) {
.columns.text-left a:link {color:#58595B;}
}
First I tried to solve the problem with CSS settings, created new div
class after div "row", with the name ".career-nav", but it didnt work,
then I commented that and started to write mediaqueries. But as I am new
in Foundation Framework I am not sure that I did the right query,
therefore I want to know, which method is the best one for such
adjustement and what I missed in my code. Thank you!
How to make reference/pointer in clojure?
How to make reference/pointer in clojure?
I would like to change normal behavior of code
(def a 5)
(def b a)
(def a 1)
b
5
To this behavior
(def a 5)
(*something* b a)
(def a 1)
b
1
It is just for learning purposes so please do not try any deep sense in this.
I would like to change normal behavior of code
(def a 5)
(def b a)
(def a 1)
b
5
To this behavior
(def a 5)
(*something* b a)
(def a 1)
b
1
It is just for learning purposes so please do not try any deep sense in this.
Wednesday, 18 September 2013
JAXB: how to declare a variable as class in xsd
JAXB: how to declare a variable as class in xsd
how to specify the variable type as class?
i tried with type as MyClass but in converted java class,getting the
object of MyClass. but i want to have myclass.class type
how to specify the variable type as class?
i tried with type as MyClass but in converted java class,getting the
object of MyClass. but i want to have myclass.class type
Java Enum Methods
Java Enum Methods
I would like to declare an enum Direction, that has a method that returns
the opposite direction (the following is not syntactically correct, i.e,
enums cannot be instantiated, but it illustrates my point). Is this
possible in Java?
Here is the code:
public enum Direction {
NORTH(1),
SOUTH(-1),
EAST(-2),
WEST(2);
Direction(int code){
this.code=code;
}
protected int code;
public int getCode() {
return this.code;
}
static Direction getOppositeDirection(Direction d){
return new Direction(d.getCode() * -1);
}
}
I would like to declare an enum Direction, that has a method that returns
the opposite direction (the following is not syntactically correct, i.e,
enums cannot be instantiated, but it illustrates my point). Is this
possible in Java?
Here is the code:
public enum Direction {
NORTH(1),
SOUTH(-1),
EAST(-2),
WEST(2);
Direction(int code){
this.code=code;
}
protected int code;
public int getCode() {
return this.code;
}
static Direction getOppositeDirection(Direction d){
return new Direction(d.getCode() * -1);
}
}
Magento Admin Create Order not showing Custom Options
Magento Admin Create Order not showing Custom Options
I have simple products with custom options in my store. They work
perfectly from the front end, but if I try to add an order from the admin
section, The custom options do not show up.
I only have this problem if the type of custom option is a dropdown, multi
select, radio buttons, or check boxes. If it is a text field, date or
anything else, it works fine.
I am assumming i need to make some changes to something in the
/www/app/design/adminhtml/default/default/template/sales/order/create
area, but no clue what i should try.
Looking a bit further, I found this
/www/app/code/core/Mage/Adminhtml/Block/Sales/Order/Create/Items/grid.php
file controls the configure window at about line 320 which calls the
configure window up. Not sure if this helps any
/**
* Return html button which calls configure window
*
* @param $item
* @return string
*/
public function getConfigureButtonHtml($item)
{
$product = $item->getProduct();
$options = array('label' => Mage::helper('sales')->__('Configure'));
if ($product->canConfigure()) {
$options['onclick'] =
sprintf('order.showQuoteItemConfiguration(%s)', $item->getId());
} else {
$options['class'] = ' disabled';
$options['title'] = Mage::helper('sales')->__('This product does
not have any configurable options');
}
return $this->getLayout()->createBlock('adminhtml/widget_button')
->setData($options)
->toHtml();
}
I have simple products with custom options in my store. They work
perfectly from the front end, but if I try to add an order from the admin
section, The custom options do not show up.
I only have this problem if the type of custom option is a dropdown, multi
select, radio buttons, or check boxes. If it is a text field, date or
anything else, it works fine.
I am assumming i need to make some changes to something in the
/www/app/design/adminhtml/default/default/template/sales/order/create
area, but no clue what i should try.
Looking a bit further, I found this
/www/app/code/core/Mage/Adminhtml/Block/Sales/Order/Create/Items/grid.php
file controls the configure window at about line 320 which calls the
configure window up. Not sure if this helps any
/**
* Return html button which calls configure window
*
* @param $item
* @return string
*/
public function getConfigureButtonHtml($item)
{
$product = $item->getProduct();
$options = array('label' => Mage::helper('sales')->__('Configure'));
if ($product->canConfigure()) {
$options['onclick'] =
sprintf('order.showQuoteItemConfiguration(%s)', $item->getId());
} else {
$options['class'] = ' disabled';
$options['title'] = Mage::helper('sales')->__('This product does
not have any configurable options');
}
return $this->getLayout()->createBlock('adminhtml/widget_button')
->setData($options)
->toHtml();
}
Change This Method to Generic (Without Collection)
Change This Method to Generic (Without Collection)
I have the following method, which clones an object using gson to do a
deep copy. Is there a way to make this method generic, or do generics only
pertain to objects that belong to a Collection?
private Order gsonClone(Order t) {
Gson gson = new Gson();
String json = gson.toJson(t);
return gson.fromJson(json, t.getClass());
}
I have the following method, which clones an object using gson to do a
deep copy. Is there a way to make this method generic, or do generics only
pertain to objects that belong to a Collection?
private Order gsonClone(Order t) {
Gson gson = new Gson();
String json = gson.toJson(t);
return gson.fromJson(json, t.getClass());
}
Left menu disappears from screen
Left menu disappears from screen
The problem I'm having is as follows:
This website I'm working on has a left menu, then content. The menu on the
left should be visible at all times. On my screen this works just fine,
but on smaller screens (<=1280pxx720px) the menu will disappear partially.
So what I would like is that either the menu stays there somehow, or some
sort of scroll bar appears (just the vertical scroll bar), so you can
scroll to the menu.
I hope there's someone out there with an answer!
The link to the website is: http://2xthuis.dev.xsbyte.net/mediation/index
The problem I'm having is as follows:
This website I'm working on has a left menu, then content. The menu on the
left should be visible at all times. On my screen this works just fine,
but on smaller screens (<=1280pxx720px) the menu will disappear partially.
So what I would like is that either the menu stays there somehow, or some
sort of scroll bar appears (just the vertical scroll bar), so you can
scroll to the menu.
I hope there's someone out there with an answer!
The link to the website is: http://2xthuis.dev.xsbyte.net/mediation/index
Assigning an int name to selct a word from a string array
Assigning an int name to selct a word from a string array
Here's a class i made to create random names but one line keeps getting an
error (not a main class)
public class nameGenerator {
String [] namesFirst= {"Micheal","Stewart","Robbinson","Tang"};
String [] namesMiddle= {"Jordan","James","Stanly","Choo" };
String [] namesLast= {"IV","Lee","Persson"};
int a = namesFirst.length;
int b = namesMiddle.length;
int c = namesLast.length;
int x = (int) (Math.random()* a);
int y = (int) (Math.random()* b);
int z = (int) (Math.random()* c);
System.out.println(namesFirst[x] + namesMiddle[y] + namesLast[z]);
//the error is here /\
}
Here's a class i made to create random names but one line keeps getting an
error (not a main class)
public class nameGenerator {
String [] namesFirst= {"Micheal","Stewart","Robbinson","Tang"};
String [] namesMiddle= {"Jordan","James","Stanly","Choo" };
String [] namesLast= {"IV","Lee","Persson"};
int a = namesFirst.length;
int b = namesMiddle.length;
int c = namesLast.length;
int x = (int) (Math.random()* a);
int y = (int) (Math.random()* b);
int z = (int) (Math.random()* c);
System.out.println(namesFirst[x] + namesMiddle[y] + namesLast[z]);
//the error is here /\
}
Getting linking errors when running C project in VS 2010 Professional on Windows
Getting linking errors when running C project in VS 2010 Professional on
Windows
I am getting errors of the following type :
1>authenticate.obj : error LNK2001: unresolved external symbol
_ldap_first_attribute@12
1>authenticate.obj : error LNK2001: unresolved external symbol
_ldap_first_attribute@12
1>authenticate.obj : error LNK2001: unresolved external symbol
_ldap_value_free@4
1>authenticate.obj : error LNK2001: unresolved external symbol
_ldap_err2string@4
I have already added the header file folder to Project ->
Properties->C/C++->General->Additional Include Directories.
Any ideas
Windows
I am getting errors of the following type :
1>authenticate.obj : error LNK2001: unresolved external symbol
_ldap_first_attribute@12
1>authenticate.obj : error LNK2001: unresolved external symbol
_ldap_first_attribute@12
1>authenticate.obj : error LNK2001: unresolved external symbol
_ldap_value_free@4
1>authenticate.obj : error LNK2001: unresolved external symbol
_ldap_err2string@4
I have already added the header file folder to Project ->
Properties->C/C++->General->Additional Include Directories.
Any ideas
remove all options from select jquery but only one
remove all options from select jquery but only one
I have a select that contain this values:
<select id="lstCities" class="valid" name="City">
<option value="OSNY">OSNY</option>
<option value="dd">dd</option>
<option value="OSffNY">OSffNY</option>
<option value="ANTONY">ANTONY</option>
<option value="0">Autre...</option>
</select>
How can I delete all options but i would like to keep only
<option value="0">Autre...</option>
My problem is my list is dynamic sometimes I have 3,5,7,.... select + the
last one <option value="0">Autre...</option>
I have a select that contain this values:
<select id="lstCities" class="valid" name="City">
<option value="OSNY">OSNY</option>
<option value="dd">dd</option>
<option value="OSffNY">OSffNY</option>
<option value="ANTONY">ANTONY</option>
<option value="0">Autre...</option>
</select>
How can I delete all options but i would like to keep only
<option value="0">Autre...</option>
My problem is my list is dynamic sometimes I have 3,5,7,.... select + the
last one <option value="0">Autre...</option>
Tuesday, 17 September 2013
Handling mouse events on a QQuickItem
Handling mouse events on a QQuickItem
I have created a basic QML application which uses QQuickView for creating
a view, and has custom QQuickItems in it. I want to handle mouse events on
one such QQuickItem by reimplementing the mousepressevent(QEvent *)
method. However, when I run the application and click on the QQuickItem,
no call is made to mousepressevent(QEvent *) method.
The header file of the QQuickItem looks like this:
#include <QQuickItem>
#include <QSGGeometry>
#include <QSGFlatColorMaterial>
class TriangularGeometry: public QQuickItem
{
Q_OBJECT
public:
TriangularGeometry(QQuickItem* parent = 0);
QSGNode* updatePaintNode(QSGNode*, UpdatePaintNodeData*);
void mousePressEvent(QMouseEvent *event);
private:
QSGGeometry m_geometry;
QSGFlatColorMaterial m_material;
QColor m_color;
};
Note: I am making use of scenegraph to render the QuickItem.
This is a snippet from the cpp file:
void TriangularGeometry::mousePressEvent(QMouseEvent *event)
{
m_color = Qt::black;
update(); //changing an attribute of the qquickitem and updating the
scenegraph
}
I can handle mouse events from the application but, as per my
requirements, I need to handle it by overriding the method
mousePressEvent(QMouseEvent *event).
I have created a basic QML application which uses QQuickView for creating
a view, and has custom QQuickItems in it. I want to handle mouse events on
one such QQuickItem by reimplementing the mousepressevent(QEvent *)
method. However, when I run the application and click on the QQuickItem,
no call is made to mousepressevent(QEvent *) method.
The header file of the QQuickItem looks like this:
#include <QQuickItem>
#include <QSGGeometry>
#include <QSGFlatColorMaterial>
class TriangularGeometry: public QQuickItem
{
Q_OBJECT
public:
TriangularGeometry(QQuickItem* parent = 0);
QSGNode* updatePaintNode(QSGNode*, UpdatePaintNodeData*);
void mousePressEvent(QMouseEvent *event);
private:
QSGGeometry m_geometry;
QSGFlatColorMaterial m_material;
QColor m_color;
};
Note: I am making use of scenegraph to render the QuickItem.
This is a snippet from the cpp file:
void TriangularGeometry::mousePressEvent(QMouseEvent *event)
{
m_color = Qt::black;
update(); //changing an attribute of the qquickitem and updating the
scenegraph
}
I can handle mouse events from the application but, as per my
requirements, I need to handle it by overriding the method
mousePressEvent(QMouseEvent *event).
How do I create a prefix like jQuery does?
How do I create a prefix like jQuery does?
How do I create a prefix like the one jQuery uses? For example, in jQuery
I can use:
$(".footer").css('display', 'none');
and I'd like to enable a similar syntax, like this:
google('.footer').chrome('display', 'none');
I have searched Google for an answer, but couldn't find it.
How do I create a prefix like the one jQuery uses? For example, in jQuery
I can use:
$(".footer").css('display', 'none');
and I'd like to enable a similar syntax, like this:
google('.footer').chrome('display', 'none');
I have searched Google for an answer, but couldn't find it.
java client send class and server execute a method from this files
java client send class and server execute a method from this files
Im working on a little project.
My client send a java file :
public class Calc {
public int add(String a, String b){
int x = Integer.parseInt(a);
int y = Integer.parseInt(b);
return x + y;
}
}
My server receive this file in his package. There is no problem for this.
What i want its to excecute 'public int add' in my server with parameter
send by client. For example: my client connects to server. He send
Calc.java and with a String add("1","2") My server receive this and
execute the function to finnaly return the result.
But i dont know how to do this... i just find "execute" but ihavent a main
method in Calc.java
Is this possible to do that ? With what method ?
Im working on a little project.
My client send a java file :
public class Calc {
public int add(String a, String b){
int x = Integer.parseInt(a);
int y = Integer.parseInt(b);
return x + y;
}
}
My server receive this file in his package. There is no problem for this.
What i want its to excecute 'public int add' in my server with parameter
send by client. For example: my client connects to server. He send
Calc.java and with a String add("1","2") My server receive this and
execute the function to finnaly return the result.
But i dont know how to do this... i just find "execute" but ihavent a main
method in Calc.java
Is this possible to do that ? With what method ?
Why not directly instantiate services in Android?
Why not directly instantiate services in Android?
I was wondering why the direct instantiation of a service class through a
constructor is not recommended. I couldn't find anything related to it.
Here is a very basic example:
Service class:
public class SomeRandomClass extends Service {
private final Context mContext;
public SomeRandomClass(Context context) {
this.mContext = context;
}
}
And inside main Activity/Service:
SomeRandomClass class = new SomeRandomClass(this);
class.someMethod();
The post here states that it is not a good idea to instantiate services
directly and one should use startService() instead but why? If I
instantiate my service like this I have a variable directly to the service
and I can call methods instead of having to bind to it to be able to call
methods on my service.
The only advantage I can see by using startService() is that Android keeps
track of my service but the disadvantage that I have to bind to the
Service to communicate with it. On the other hand by calling the
constructor directly I have easy communication but if my activity/service
get's killed/terminated the "sub" service is killed as well (I'm not using
a activity but other service).
Anything else why it is discouraged?
I was wondering why the direct instantiation of a service class through a
constructor is not recommended. I couldn't find anything related to it.
Here is a very basic example:
Service class:
public class SomeRandomClass extends Service {
private final Context mContext;
public SomeRandomClass(Context context) {
this.mContext = context;
}
}
And inside main Activity/Service:
SomeRandomClass class = new SomeRandomClass(this);
class.someMethod();
The post here states that it is not a good idea to instantiate services
directly and one should use startService() instead but why? If I
instantiate my service like this I have a variable directly to the service
and I can call methods instead of having to bind to it to be able to call
methods on my service.
The only advantage I can see by using startService() is that Android keeps
track of my service but the disadvantage that I have to bind to the
Service to communicate with it. On the other hand by calling the
constructor directly I have easy communication but if my activity/service
get's killed/terminated the "sub" service is killed as well (I'm not using
a activity but other service).
Anything else why it is discouraged?
How to make an array list of objects in Java
How to make an array list of objects in Java
Having this:
static class girl{
public String age;
public String name;
public String id;
}
static girl[] girl;
Then i am unable to do this in my main function:
ResultSet r = s.executeQuery("select count(*) from children");
r.next();
girl_count=r.getInt(1);
girl = new girl[girl_count];
r = s.executeQuery("select * from children");
while(r.next()){
int i = r.getString("id");
ifgirl[i]==null)girl[i]=new girl();
girl[i].age=r.getString("age");
girl[i].name=r.getString("name");
girl[i].id=r.getString("id");
}
The above code is not working, what i would like to acheive is:
System.out.println(girl[3]);
especially this line:
girl = new girl[girl_count];
Can anyone help me correct this code ? - or find out what i'm missing here?
Having this:
static class girl{
public String age;
public String name;
public String id;
}
static girl[] girl;
Then i am unable to do this in my main function:
ResultSet r = s.executeQuery("select count(*) from children");
r.next();
girl_count=r.getInt(1);
girl = new girl[girl_count];
r = s.executeQuery("select * from children");
while(r.next()){
int i = r.getString("id");
ifgirl[i]==null)girl[i]=new girl();
girl[i].age=r.getString("age");
girl[i].name=r.getString("name");
girl[i].id=r.getString("id");
}
The above code is not working, what i would like to acheive is:
System.out.println(girl[3]);
especially this line:
girl = new girl[girl_count];
Can anyone help me correct this code ? - or find out what i'm missing here?
How can I solve for the points of an arbitrary trapezoid inscribed inside of a triangle?
How can I solve for the points of an arbitrary trapezoid inscribed inside
of a triangle?
Given the following coordinate points:
Write an algorithm (in pseudocode) to solve for x1, x2, x3, and x4.
This is what I have so far:
var y1, y2, y3, y4 = 50, 50, 75, 75;
var offset1 = tan(60) * y1;
var offset2 = tan(60) * (y2 - y1);
var x1 = 200 + offset1;
var x3 = 200 + offset1 + offset2;
of a triangle?
Given the following coordinate points:
Write an algorithm (in pseudocode) to solve for x1, x2, x3, and x4.
This is what I have so far:
var y1, y2, y3, y4 = 50, 50, 75, 75;
var offset1 = tan(60) * y1;
var offset2 = tan(60) * (y2 - y1);
var x1 = 200 + offset1;
var x3 = 200 + offset1 + offset2;
Sunday, 15 September 2013
Calling nc/netcat in python with variable
Calling nc/netcat in python with variable
I am attempting to call netcat/nc from inside a loop, passing the lcv as
the last octet in the command. I am seem to be running into an issue due
to the fact that the variable is in the middle of the command. What I
would like to do is:
for i in 1 to 50
print i
nc -nvv 192.168.1.i 21 -w 15 >> local_net.txt
So far I have tried:
os.system("nc -nvv 192.168.1.",i,"21 -w 15 >> local_net.txt")
and
subprocess.call(["nv","-nvv 192.168.1.",i,"21 -w 15 >> local_net.txt")
Is there an easier way to reference an LVC from within a command executing
a system command?
I am attempting to call netcat/nc from inside a loop, passing the lcv as
the last octet in the command. I am seem to be running into an issue due
to the fact that the variable is in the middle of the command. What I
would like to do is:
for i in 1 to 50
print i
nc -nvv 192.168.1.i 21 -w 15 >> local_net.txt
So far I have tried:
os.system("nc -nvv 192.168.1.",i,"21 -w 15 >> local_net.txt")
and
subprocess.call(["nv","-nvv 192.168.1.",i,"21 -w 15 >> local_net.txt")
Is there an easier way to reference an LVC from within a command executing
a system command?
Seperating intergers from a string properly (no regex)
Seperating intergers from a string properly (no regex)
I need to isolate all integers from a string, list them, and print their
sum and the # of integers. My issue is that my current code will split,
for example, 456 into 4, 5, and 6, and treat them as separate integers.
Unfortunately regex is not an option.
What i have so far:
def tally(text):
s = ','.join(x for x in text if x.isdigit())
numbers = [int(x) for x in s.split(",")]
num=len(numbers)
t=sum(numbers)
print ('There are', num, 'integers in the input summing up to', t)
..
What i need: input:'34 ch33se 34e8 3.4'
output: [34 33 34 8 3 4 ]
im getting now is [3 4 3 3 8 3 4]
I need to isolate all integers from a string, list them, and print their
sum and the # of integers. My issue is that my current code will split,
for example, 456 into 4, 5, and 6, and treat them as separate integers.
Unfortunately regex is not an option.
What i have so far:
def tally(text):
s = ','.join(x for x in text if x.isdigit())
numbers = [int(x) for x in s.split(",")]
num=len(numbers)
t=sum(numbers)
print ('There are', num, 'integers in the input summing up to', t)
..
What i need: input:'34 ch33se 34e8 3.4'
output: [34 33 34 8 3 4 ]
im getting now is [3 4 3 3 8 3 4]
Why can't the complier find this operator
Why can't the complier find this operator
I'm trying to write overloads of operator<< for specific instantiations of
standard library containers that will be stored in a boost::variant.
Here's a small example that illustrates the problem:
#include <iostream>
#include <vector>
std::ostream & operator<<( std::ostream & os, const std::vector< int > & ) {
os << "Streaming out std::vector< int >";
return os;
}
std::ostream & operator<<( std::ostream & os, const std::vector< double >
& ) {
os << "Streaming out std::vector< double >";
return os;
}
#include <boost/variant.hpp>
typedef boost::variant< std::vector< int >, std::vector< double > >
MyVariant;
int main( int argc, char * argv[] ) {
std::cout << MyVariant();
return 0;
}
Clang's first error is
boost/variant/detail/variant_io.hpp:64:14: error: invalid operands to
binary expression ('std::basic_ostream<char>' and 'const std::vector<int,
std::allocator<int>>')
out_ << operand;
~~~~ ^ ~~~~~~~
I realize that the #include <boost/variant.hpp> is in an odd place. I'm
pretty sure the problem had to do with two-phase name lookup in templates,
so I moved the #include in an attempt to implement fix #1 from the clang
documentation on lookup. Fix #2 from that documentation isn't a good
option because I believe adding my overloaded operator<< to the std
namespace would lead to undefined behavior.
Shouldn't defining my operator<<s before the #include allow the compiler
to find the definitions?
I'm trying to write overloads of operator<< for specific instantiations of
standard library containers that will be stored in a boost::variant.
Here's a small example that illustrates the problem:
#include <iostream>
#include <vector>
std::ostream & operator<<( std::ostream & os, const std::vector< int > & ) {
os << "Streaming out std::vector< int >";
return os;
}
std::ostream & operator<<( std::ostream & os, const std::vector< double >
& ) {
os << "Streaming out std::vector< double >";
return os;
}
#include <boost/variant.hpp>
typedef boost::variant< std::vector< int >, std::vector< double > >
MyVariant;
int main( int argc, char * argv[] ) {
std::cout << MyVariant();
return 0;
}
Clang's first error is
boost/variant/detail/variant_io.hpp:64:14: error: invalid operands to
binary expression ('std::basic_ostream<char>' and 'const std::vector<int,
std::allocator<int>>')
out_ << operand;
~~~~ ^ ~~~~~~~
I realize that the #include <boost/variant.hpp> is in an odd place. I'm
pretty sure the problem had to do with two-phase name lookup in templates,
so I moved the #include in an attempt to implement fix #1 from the clang
documentation on lookup. Fix #2 from that documentation isn't a good
option because I believe adding my overloaded operator<< to the std
namespace would lead to undefined behavior.
Shouldn't defining my operator<<s before the #include allow the compiler
to find the definitions?
Replace empty method with method from a class where it is used
Replace empty method with method from a class where it is used
In the following scenario, I want to replace Class B's (similarly D, E, F,
etc.) method doSomething() with the method in Class A where it will be
used. How would I go about this? Made up some example, hope it gets the
message across
public class B implements GetNames{
public void getNameA(){ return "NameA"; }
public void getNameB() { return "NameB"; }
public void doStuff(){
//print names
doSomething(getNameA(), getNameB());
//print names
}
public void doSomething(String a, String b){}
}
public class A{
public void someMethod(){
B b = new B();
b.doStuff(); //*So I want it to call the method in B but somehow
replace the doSomething method in B with the doSomething method in
A
}
public void doSomething(String a, String b){
//print 'blabla' + a
//print 'blablabla' + b
//concatenate and print
}
}
In the following scenario, I want to replace Class B's (similarly D, E, F,
etc.) method doSomething() with the method in Class A where it will be
used. How would I go about this? Made up some example, hope it gets the
message across
public class B implements GetNames{
public void getNameA(){ return "NameA"; }
public void getNameB() { return "NameB"; }
public void doStuff(){
//print names
doSomething(getNameA(), getNameB());
//print names
}
public void doSomething(String a, String b){}
}
public class A{
public void someMethod(){
B b = new B();
b.doStuff(); //*So I want it to call the method in B but somehow
replace the doSomething method in B with the doSomething method in
A
}
public void doSomething(String a, String b){
//print 'blabla' + a
//print 'blablabla' + b
//concatenate and print
}
}
Finding prominent frequencies from FFT
Finding prominent frequencies from FFT
Im trying to find the prominent peaks in an audio signal (piano recording)
using STFT. This is what Ive done so far 1. Obtain the envelope of the
time domain signal 2. Determine the peaks in the enveloped signal and use
them as note onsets 3. perform FFT for the samples between each 2
consecutive onsets.
Now that I have the FFT, I want to find the peaks corresponding to the
notes played... when i try using the findpeaks function at some points it
says its an empty matrix. Im not sure how exactly to do this so need some
help urgently...... Thank you
clear all;
clear max;
clc;
[song,FS] = wavread('C major.wav');
sound(song,FS);
P = 20000;
N=length(song); % length of song
t=0:1/FS:(N-1)/FS; % define time period
song = sum(song,2);
song=abs(song);
%windowing = hamming(32768); %Windowing function
% Plot time domain signal
figure(1);
subplot(2,1,1)
plot(t,3*song)
title('Wave File')
ylabel('Amplitude')
xlabel('Length (in seconds)')
%ylim([-1.1 1.1])
xlim([0 N/FS])
%----------------------Finding the envelope of the signal-----------------%
% Gaussian Filter
x = linspace( -1, 1, P); % create a vector of P
values between -1 and 1 inclusive
sigma = 0.335; % standard deviation used in
Gaussian formula
myFilter = -x .* exp( -(x.^2)/(2*sigma.^2)); % compute first derivative,
but leave constants out
myFilter = myFilter / sum( abs( myFilter ) ); % normalize
% Plot Gaussian Filter
subplot(2,1,2)
plot(myFilter)
title('Edge Detection Filter')
% fft convolution
myFilter = myFilter(:); % create a column vector
song(length(song)+length(myFilter)-1) = 0; %zero pad song
myFilter(length(song)) = 0; %zero pad myFilter
edges =ifft(fft(song).*fft(myFilter));
tedges=edges(P:N+P-1); % shift by P/2 so peaks line
up w/ edges
tedges=tedges/max(abs(tedges)); % normalize
%---------------------------Onset Detection-------------------------------%
% Finding peaks
maxtab = [];
mintab = [];
x = (1:length(tedges));
min1 = Inf;
max1 = -Inf;
min_pos = NaN;
max_pos = NaN;
lookformax = 1;
for i=1:length(tedges)
peak = tedges(i:i);
if peak > max1,
max1 = peak;
max_pos = x(i);
end
if peak < min1,
min1 = peak;
min_pos = x(i);
end
if lookformax
if peak < max1-0.01
maxtab = [maxtab ; max_pos max1];
min1 = peak;
min_pos = x(i);
lookformax = 0;
end
else
if peak > min1+0.05
mintab = [mintab ; min_pos min1];
max1 = peak;
max_pos = x(i);
lookformax = 1;
end
end
end
% % Plot song filtered with edge detector
figure(2)
plot(1/FS:1/FS:N/FS,tedges)
title('Song Filtered With Edge Detector 1')
xlabel('Time (s)')
ylabel('Amplitude')
ylim([-1 1.1])
xlim([0 N/FS])
hold on;
plot(maxtab(:,1)/FS, maxtab(:,2), 'ro')
plot(mintab(:,1)/FS, mintab(:,2), 'ko')
max_col = maxtab(:,1);
peaks_det = max_col/FS;
No_of_peaks = length(peaks_det);
song = detrend(song);
%---------------------------Performing FFT--------------------------------%
for i = 2:No_of_peaks
song_seg = song(max_col(i-1):max_col(i)-1);
% song_seg = song(max_col(6):max_col(7)-1);
L = length(song_seg);
NFFT = 2^nextpow2(L); % Next power of 2 from length of y
seg_fft = fft(song_seg,NFFT);%/L;
N=5;Fst1=50;Fp1=60; Fp2=1040; Fst2=1050;
% d = fdesign.bandpass('N,Fst1,Fp1,Fp2,Fst2');
% h = design(d);
% seg_fft = filter(h, seg_fft);
% seg_fft(1) = 0;
%
f = FS/2*linspace(0,1,NFFT/2+1);
seg_fft2 = 2*abs(seg_fft(1:NFFT/2+1));
L5 = length(song_seg);
figure(1+i)
plot(f,seg_fft2)
title('Frequency spectrum of signal')
xlabel('Frequency (Hz)')
%xlim([0 2500])
ylabel('|Y(f)|')
ylim([0 300])
%[B, IX] = sort(seg_fft2)
%[points loc] = findpeaks(seg_fft);
%STFT_out(:,i) = seg_fft2;
%P=max(seg_fft2)
[points, loc] = findpeaks(seg_fft2,'THRESHOLD',20)
end
Im trying to find the prominent peaks in an audio signal (piano recording)
using STFT. This is what Ive done so far 1. Obtain the envelope of the
time domain signal 2. Determine the peaks in the enveloped signal and use
them as note onsets 3. perform FFT for the samples between each 2
consecutive onsets.
Now that I have the FFT, I want to find the peaks corresponding to the
notes played... when i try using the findpeaks function at some points it
says its an empty matrix. Im not sure how exactly to do this so need some
help urgently...... Thank you
clear all;
clear max;
clc;
[song,FS] = wavread('C major.wav');
sound(song,FS);
P = 20000;
N=length(song); % length of song
t=0:1/FS:(N-1)/FS; % define time period
song = sum(song,2);
song=abs(song);
%windowing = hamming(32768); %Windowing function
% Plot time domain signal
figure(1);
subplot(2,1,1)
plot(t,3*song)
title('Wave File')
ylabel('Amplitude')
xlabel('Length (in seconds)')
%ylim([-1.1 1.1])
xlim([0 N/FS])
%----------------------Finding the envelope of the signal-----------------%
% Gaussian Filter
x = linspace( -1, 1, P); % create a vector of P
values between -1 and 1 inclusive
sigma = 0.335; % standard deviation used in
Gaussian formula
myFilter = -x .* exp( -(x.^2)/(2*sigma.^2)); % compute first derivative,
but leave constants out
myFilter = myFilter / sum( abs( myFilter ) ); % normalize
% Plot Gaussian Filter
subplot(2,1,2)
plot(myFilter)
title('Edge Detection Filter')
% fft convolution
myFilter = myFilter(:); % create a column vector
song(length(song)+length(myFilter)-1) = 0; %zero pad song
myFilter(length(song)) = 0; %zero pad myFilter
edges =ifft(fft(song).*fft(myFilter));
tedges=edges(P:N+P-1); % shift by P/2 so peaks line
up w/ edges
tedges=tedges/max(abs(tedges)); % normalize
%---------------------------Onset Detection-------------------------------%
% Finding peaks
maxtab = [];
mintab = [];
x = (1:length(tedges));
min1 = Inf;
max1 = -Inf;
min_pos = NaN;
max_pos = NaN;
lookformax = 1;
for i=1:length(tedges)
peak = tedges(i:i);
if peak > max1,
max1 = peak;
max_pos = x(i);
end
if peak < min1,
min1 = peak;
min_pos = x(i);
end
if lookformax
if peak < max1-0.01
maxtab = [maxtab ; max_pos max1];
min1 = peak;
min_pos = x(i);
lookformax = 0;
end
else
if peak > min1+0.05
mintab = [mintab ; min_pos min1];
max1 = peak;
max_pos = x(i);
lookformax = 1;
end
end
end
% % Plot song filtered with edge detector
figure(2)
plot(1/FS:1/FS:N/FS,tedges)
title('Song Filtered With Edge Detector 1')
xlabel('Time (s)')
ylabel('Amplitude')
ylim([-1 1.1])
xlim([0 N/FS])
hold on;
plot(maxtab(:,1)/FS, maxtab(:,2), 'ro')
plot(mintab(:,1)/FS, mintab(:,2), 'ko')
max_col = maxtab(:,1);
peaks_det = max_col/FS;
No_of_peaks = length(peaks_det);
song = detrend(song);
%---------------------------Performing FFT--------------------------------%
for i = 2:No_of_peaks
song_seg = song(max_col(i-1):max_col(i)-1);
% song_seg = song(max_col(6):max_col(7)-1);
L = length(song_seg);
NFFT = 2^nextpow2(L); % Next power of 2 from length of y
seg_fft = fft(song_seg,NFFT);%/L;
N=5;Fst1=50;Fp1=60; Fp2=1040; Fst2=1050;
% d = fdesign.bandpass('N,Fst1,Fp1,Fp2,Fst2');
% h = design(d);
% seg_fft = filter(h, seg_fft);
% seg_fft(1) = 0;
%
f = FS/2*linspace(0,1,NFFT/2+1);
seg_fft2 = 2*abs(seg_fft(1:NFFT/2+1));
L5 = length(song_seg);
figure(1+i)
plot(f,seg_fft2)
title('Frequency spectrum of signal')
xlabel('Frequency (Hz)')
%xlim([0 2500])
ylabel('|Y(f)|')
ylim([0 300])
%[B, IX] = sort(seg_fft2)
%[points loc] = findpeaks(seg_fft);
%STFT_out(:,i) = seg_fft2;
%P=max(seg_fft2)
[points, loc] = findpeaks(seg_fft2,'THRESHOLD',20)
end
ExpandableListView throwing InflateException when setting an adapter
ExpandableListView throwing InflateException when setting an adapter
My app is throwing a android.view.InflateException when I try to set an
adapter to a ListView. The code runs fine doing the last line of onCreate
where I call setAdapter(...) but then it fails in the next line at the end
of onCreate. The code runs without errors when I do comment out the
setAdapter method.
Here are some of the logs.
09-15 17:38:20.986: W/dalvikvm(26497): threadid=1: thread exiting with
uncaught exception (group=0x40cf8438)
09-15 17:38:21.136: E/AndroidRuntime(26497): FATAL EXCEPTION: main
09-15 17:38:21.136: E/AndroidRuntime(26497):
android.view.InflateException: Binary XML file line #10: Error inflating
class <unknown>
09-15 17:38:21.136: E/AndroidRuntime(26497): at
android.view.LayoutInflater.createView(LayoutInflater.java:613)
09-15 17:38:21.136: E/AndroidRuntime(26497): at
com.android.internal.policy.impl.PhoneLayoutInflater.onCreateView(PhoneLayoutInflater.java:56)
09-15 17:38:21.136: E/AndroidRuntime(26497): at
android.view.LayoutInflater.onCreateView(LayoutInflater.java:660)
09-15 17:38:21.136: E/AndroidRuntime(26497): at
android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:685)
FavoritesActivity.java
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_favorites);
setTitle("Favorites");
expListView = (ExpandableListView) findViewById(R.id.lvExp);
// preparing list data
prepareListData();
listAdapter = new ExpandableListAdapter(this, listDataHeader,
listDataChild);
// setting list adapter
expListView.setAdapter(listAdapter);
}//END OF ONCREATE
/*
* Preparing the list data
*/
private void prepareListData() {
listDataHeader = new ArrayList<String>();
listDataChild = new HashMap<String, List<String>>();
//Get current data
SharedPreferences pref =
getApplicationContext().getSharedPreferences("MyPref", PRIVATE_MODE);
Set<String> listDataHeaderSet = pref.getStringSet(LIST_DATA_HEADER,
null);
if(!(listDataHeaderSet == null)){
listDataHeader.addAll(listDataHeaderSet);
}
for(int i = 0; i < listDataHeader.size(); i++){
listDataChild.put(listDataHeader.get(i), addChildren());
}
}
/**
* Returns a list of the children in the listview
* @return
*/
private List<String> addChildren(){
List<String> locationChildren = new ArrayList<String>();
locationChildren.add("set perm start");
locationChildren.add("set start");
locationChildren.add("set perm end");
locationChildren.add("set end");
return locationChildren;
}
ExpandableListAdapter.java
import java.util.HashMap;
import java.util.List;
import android.content.Context;
import android.graphics.Typeface;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.TextView;
public class ExpandableListAdapter extends BaseExpandableListAdapter {
private Context _context;
private List<String> _listDataHeader; // header titles
// child data in format of header title, child title
private HashMap<String, List<String>> _listDataChild;
public ExpandableListAdapter(Context context, List<String> listDataHeader,
HashMap<String, List<String>> listChildData) {
this._context = context;
this._listDataHeader = listDataHeader;
this._listDataChild = listChildData;
}
@Override
public Object getChild(int groupPosition, int childPosititon) {
return this._listDataChild.get(this._listDataHeader.get(groupPosition))
.get(childPosititon);
}
@Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
@Override
public View getChildView(int groupPosition, final int childPosition,
boolean isLastChild, View convertView, ViewGroup parent) {
final String childText = (String) getChild(groupPosition, childPosition);
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) this._context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.list_item, null);
}
TextView txtListChild = (TextView) convertView
.findViewById(R.id.lblListItem);
txtListChild.setText(childText);
return convertView;
}
@Override
public int getChildrenCount(int groupPosition) {
return this._listDataChild.get(this._listDataHeader.get(groupPosition))
.size();
}
@Override
public Object getGroup(int groupPosition) {
return this._listDataHeader.get(groupPosition);
}
@Override
public int getGroupCount() {
return this._listDataHeader.size();
}
@Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
@Override
public View getGroupView(int groupPosition, boolean isExpanded,
View convertView, ViewGroup parent) {
String headerTitle = (String) getGroup(groupPosition);
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) this._context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.list_group, null);
}
TextView lblListHeader = (TextView) convertView
.findViewById(R.id.lblListHeader);
lblListHeader.setTypeface(null, Typeface.BOLD);
lblListHeader.setText(headerTitle);
return convertView;
}
@Override
public boolean hasStableIds() {
return false;
}
@Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
}
activity_favorites.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<ExpandableListView
android:id="@+id/lvExp"
android:layout_height="match_parent"
android:layout_width="match_parent"/>
</RelativeLayout>
list_group.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="8dp"
android:background="#000000">
<TextView
android:id="@+id/lblListHeader"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingLeft="?android:attr/expandableListPreferredItemPaddingLeft"
android:textSize="30sp"
android:textColor="@android:style/Holo.ButtonBar" />
</LinearLayout>
list_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="55dip"
android:orientation="vertical" >
<TextView
android:id="@+id/lblListItem"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="17dip"
android:paddingTop="5dp"
android:paddingBottom="5dp"
android:paddingLeft="?android:attr/expandableListPreferredChildPaddingLeft"
/>
</LinearLayout>
My app is throwing a android.view.InflateException when I try to set an
adapter to a ListView. The code runs fine doing the last line of onCreate
where I call setAdapter(...) but then it fails in the next line at the end
of onCreate. The code runs without errors when I do comment out the
setAdapter method.
Here are some of the logs.
09-15 17:38:20.986: W/dalvikvm(26497): threadid=1: thread exiting with
uncaught exception (group=0x40cf8438)
09-15 17:38:21.136: E/AndroidRuntime(26497): FATAL EXCEPTION: main
09-15 17:38:21.136: E/AndroidRuntime(26497):
android.view.InflateException: Binary XML file line #10: Error inflating
class <unknown>
09-15 17:38:21.136: E/AndroidRuntime(26497): at
android.view.LayoutInflater.createView(LayoutInflater.java:613)
09-15 17:38:21.136: E/AndroidRuntime(26497): at
com.android.internal.policy.impl.PhoneLayoutInflater.onCreateView(PhoneLayoutInflater.java:56)
09-15 17:38:21.136: E/AndroidRuntime(26497): at
android.view.LayoutInflater.onCreateView(LayoutInflater.java:660)
09-15 17:38:21.136: E/AndroidRuntime(26497): at
android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:685)
FavoritesActivity.java
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_favorites);
setTitle("Favorites");
expListView = (ExpandableListView) findViewById(R.id.lvExp);
// preparing list data
prepareListData();
listAdapter = new ExpandableListAdapter(this, listDataHeader,
listDataChild);
// setting list adapter
expListView.setAdapter(listAdapter);
}//END OF ONCREATE
/*
* Preparing the list data
*/
private void prepareListData() {
listDataHeader = new ArrayList<String>();
listDataChild = new HashMap<String, List<String>>();
//Get current data
SharedPreferences pref =
getApplicationContext().getSharedPreferences("MyPref", PRIVATE_MODE);
Set<String> listDataHeaderSet = pref.getStringSet(LIST_DATA_HEADER,
null);
if(!(listDataHeaderSet == null)){
listDataHeader.addAll(listDataHeaderSet);
}
for(int i = 0; i < listDataHeader.size(); i++){
listDataChild.put(listDataHeader.get(i), addChildren());
}
}
/**
* Returns a list of the children in the listview
* @return
*/
private List<String> addChildren(){
List<String> locationChildren = new ArrayList<String>();
locationChildren.add("set perm start");
locationChildren.add("set start");
locationChildren.add("set perm end");
locationChildren.add("set end");
return locationChildren;
}
ExpandableListAdapter.java
import java.util.HashMap;
import java.util.List;
import android.content.Context;
import android.graphics.Typeface;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.TextView;
public class ExpandableListAdapter extends BaseExpandableListAdapter {
private Context _context;
private List<String> _listDataHeader; // header titles
// child data in format of header title, child title
private HashMap<String, List<String>> _listDataChild;
public ExpandableListAdapter(Context context, List<String> listDataHeader,
HashMap<String, List<String>> listChildData) {
this._context = context;
this._listDataHeader = listDataHeader;
this._listDataChild = listChildData;
}
@Override
public Object getChild(int groupPosition, int childPosititon) {
return this._listDataChild.get(this._listDataHeader.get(groupPosition))
.get(childPosititon);
}
@Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
@Override
public View getChildView(int groupPosition, final int childPosition,
boolean isLastChild, View convertView, ViewGroup parent) {
final String childText = (String) getChild(groupPosition, childPosition);
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) this._context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.list_item, null);
}
TextView txtListChild = (TextView) convertView
.findViewById(R.id.lblListItem);
txtListChild.setText(childText);
return convertView;
}
@Override
public int getChildrenCount(int groupPosition) {
return this._listDataChild.get(this._listDataHeader.get(groupPosition))
.size();
}
@Override
public Object getGroup(int groupPosition) {
return this._listDataHeader.get(groupPosition);
}
@Override
public int getGroupCount() {
return this._listDataHeader.size();
}
@Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
@Override
public View getGroupView(int groupPosition, boolean isExpanded,
View convertView, ViewGroup parent) {
String headerTitle = (String) getGroup(groupPosition);
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) this._context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.list_group, null);
}
TextView lblListHeader = (TextView) convertView
.findViewById(R.id.lblListHeader);
lblListHeader.setTypeface(null, Typeface.BOLD);
lblListHeader.setText(headerTitle);
return convertView;
}
@Override
public boolean hasStableIds() {
return false;
}
@Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
}
activity_favorites.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<ExpandableListView
android:id="@+id/lvExp"
android:layout_height="match_parent"
android:layout_width="match_parent"/>
</RelativeLayout>
list_group.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="8dp"
android:background="#000000">
<TextView
android:id="@+id/lblListHeader"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingLeft="?android:attr/expandableListPreferredItemPaddingLeft"
android:textSize="30sp"
android:textColor="@android:style/Holo.ButtonBar" />
</LinearLayout>
list_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="55dip"
android:orientation="vertical" >
<TextView
android:id="@+id/lblListItem"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="17dip"
android:paddingTop="5dp"
android:paddingBottom="5dp"
android:paddingLeft="?android:attr/expandableListPreferredChildPaddingLeft"
/>
</LinearLayout>
Saturday, 14 September 2013
content assist/intellisence support for android devolopment using phonegap in android
content assist/intellisence support for android devolopment using phonegap
in android
i am beginning development for android using applaud phonegap plugin for
eclipse. while writing javascript code for index.js , i donot see content
assist working for me when it comes to working with javascript api
provided by cordova.js.I have include cordova.js in javascript build path
but still i donot see any content assist. How to enable content assist for
phonegap in eclipse?
in android
i am beginning development for android using applaud phonegap plugin for
eclipse. while writing javascript code for index.js , i donot see content
assist working for me when it comes to working with javascript api
provided by cordova.js.I have include cordova.js in javascript build path
but still i donot see any content assist. How to enable content assist for
phonegap in eclipse?
character array of bitstring
character array of bitstring
for(i = 0; bitstr[i] != '\0'; i++){
if(!(bitstr[i]=='0' || bitstr[i]=='1')){
printf("Not a valid bitstring!");
exit(0);
}
else{
sum = sum*2+bitstr[i];
}
}
printf("%d", sum);
When I enter 101 for instance, it prints 339, when it should print 3 as
the answer. I am not sure what I am doing wrong. Any help would be much
appreciated.
for(i = 0; bitstr[i] != '\0'; i++){
if(!(bitstr[i]=='0' || bitstr[i]=='1')){
printf("Not a valid bitstring!");
exit(0);
}
else{
sum = sum*2+bitstr[i];
}
}
printf("%d", sum);
When I enter 101 for instance, it prints 339, when it should print 3 as
the answer. I am not sure what I am doing wrong. Any help would be much
appreciated.
vuforia augmented reality Unity app export to eclipse
vuforia augmented reality Unity app export to eclipse
i have create a simple app in vuforia augmented reality using unity i have
Follow here! that Allows me to Extending Unity Android Activity and Adding
Custom Views in Eclipse but when i run the project the splash screen
shows(black screen) up of unity but after a while it closes
so any one can help me here thank you
i have create a simple app in vuforia augmented reality using unity i have
Follow here! that Allows me to Extending Unity Android Activity and Adding
Custom Views in Eclipse but when i run the project the splash screen
shows(black screen) up of unity but after a while it closes
so any one can help me here thank you
php resize image on upload
php resize image on upload
I got a form where the user is inserting some data and also uploading an
image.
To deal with the image, I got the following code:
define ("MAX_SIZE","10000");
$errors=0;
$image =$_FILES["fileField"]["name"];
$uploadedfile = $_FILES['fileField']['tmp_name'];
if($image){
$filename = stripslashes($_FILES['fileField']['name']);
$extension = strtolower(getExtension($filename));
if (($extension != "jpg") && ($extension != "jpeg") &&
($extension != "png") && ($extension != "gif")){
echo ' Unknown Image extension ';
$errors=1;
} else{
$newname = "$product_cn."."$extension";
$size=filesize($_FILES['fileField']['tmp_name']);
if ($size > MAX_SIZE*1024){
echo "You have exceeded the size limit";
$errors=1;
}
if($extension=="jpg" || $extension=="jpeg" ){
$uploadedfile = $_FILES['file']['tmp_name'];
$src = imagecreatefromjpeg($uploadedfile);
}else if($extension=="png"){
$uploadedfile = $_FILES['file']['tmp_name'];
$src = imagecreatefrompng($uploadedfile);
}else{
$src = imagecreatefromgif($uploadedfile);
}
list($width,$height)=getimagesize($uploadedfile);
$newwidth=60;
$newheight=($height/$width)*$newwidth;
$tmp=imagecreatetruecolor($newwidth,$newheight);
$newwidth1=25;
$newheight1=($height/$width)*$newwidth1;
$tmp1=imagecreatetruecolor($newwidth1,$newheight1);
imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,
$width,$height);
imagecopyresampled($tmp1,$src,0,0,0,0,$newwidth1,$newheight1,
$width,$height);
$filename = "../products_images/".$newname;
$filename1 = "../products_images/thumbs/".$newname;
imagejpeg($tmp,$filename,100); //file name also indicates
the folder where to save it to
imagejpeg($tmp1,$filename1,100);
imagedestroy($src);
imagedestroy($tmp);
imagedestroy($tmp1);
}
}
getExtension function:
function getExtension($str) {
$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
I've wrote some notation in the code since im not really familiar with
those functions.
for some reason, it doesn't work.
when I'm going to the folder "product_images" OR "product_images/thumbs" I
can't find any image uploaded.
Any idea what's wrong with my code? there should be 60px width image, and
25px width image.
NOTE:
variables that you don't know where they were declared such as $product_cn
were declared before that block of code which works prefectly fine(tested
it). If you still want a glance at it, feel free to ask for the code.
Thanks in advance!
I got a form where the user is inserting some data and also uploading an
image.
To deal with the image, I got the following code:
define ("MAX_SIZE","10000");
$errors=0;
$image =$_FILES["fileField"]["name"];
$uploadedfile = $_FILES['fileField']['tmp_name'];
if($image){
$filename = stripslashes($_FILES['fileField']['name']);
$extension = strtolower(getExtension($filename));
if (($extension != "jpg") && ($extension != "jpeg") &&
($extension != "png") && ($extension != "gif")){
echo ' Unknown Image extension ';
$errors=1;
} else{
$newname = "$product_cn."."$extension";
$size=filesize($_FILES['fileField']['tmp_name']);
if ($size > MAX_SIZE*1024){
echo "You have exceeded the size limit";
$errors=1;
}
if($extension=="jpg" || $extension=="jpeg" ){
$uploadedfile = $_FILES['file']['tmp_name'];
$src = imagecreatefromjpeg($uploadedfile);
}else if($extension=="png"){
$uploadedfile = $_FILES['file']['tmp_name'];
$src = imagecreatefrompng($uploadedfile);
}else{
$src = imagecreatefromgif($uploadedfile);
}
list($width,$height)=getimagesize($uploadedfile);
$newwidth=60;
$newheight=($height/$width)*$newwidth;
$tmp=imagecreatetruecolor($newwidth,$newheight);
$newwidth1=25;
$newheight1=($height/$width)*$newwidth1;
$tmp1=imagecreatetruecolor($newwidth1,$newheight1);
imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,
$width,$height);
imagecopyresampled($tmp1,$src,0,0,0,0,$newwidth1,$newheight1,
$width,$height);
$filename = "../products_images/".$newname;
$filename1 = "../products_images/thumbs/".$newname;
imagejpeg($tmp,$filename,100); //file name also indicates
the folder where to save it to
imagejpeg($tmp1,$filename1,100);
imagedestroy($src);
imagedestroy($tmp);
imagedestroy($tmp1);
}
}
getExtension function:
function getExtension($str) {
$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
I've wrote some notation in the code since im not really familiar with
those functions.
for some reason, it doesn't work.
when I'm going to the folder "product_images" OR "product_images/thumbs" I
can't find any image uploaded.
Any idea what's wrong with my code? there should be 60px width image, and
25px width image.
NOTE:
variables that you don't know where they were declared such as $product_cn
were declared before that block of code which works prefectly fine(tested
it). If you still want a glance at it, feel free to ask for the code.
Thanks in advance!
Eclipse: Examine classloading problems/how to inspect deeply nested variables in debug view
Eclipse: Examine classloading problems/how to inspect deeply nested
variables in debug view
I am trying to fix some class loading problems that I ran into by
examining why class loaders fail to find the respective offending class
(here: org.eclipse.jdt.internal.compiler.env.INameEnvironment). However,
Eclipse (GGTS to be more precise) fails to show/determine the variable
contents I am interested in in this regard ("path" & "res", see attached
screenshot).
Is it possible to determine them somehow? I was unable to see them in the
variables and watch view (other variables like ucp are inspectable). I
downloaded a SDK from here https://jdk7.java.net/download.html (hoping
that it is a fast debug build) but that does not seem to make a
difference. Maybe there are other means to figure out this sort of class
loading (Class Not Found) problems?
Btw. I am using Groovy/Grails if that matters.
variables in debug view
I am trying to fix some class loading problems that I ran into by
examining why class loaders fail to find the respective offending class
(here: org.eclipse.jdt.internal.compiler.env.INameEnvironment). However,
Eclipse (GGTS to be more precise) fails to show/determine the variable
contents I am interested in in this regard ("path" & "res", see attached
screenshot).
Is it possible to determine them somehow? I was unable to see them in the
variables and watch view (other variables like ucp are inspectable). I
downloaded a SDK from here https://jdk7.java.net/download.html (hoping
that it is a fast debug build) but that does not seem to make a
difference. Maybe there are other means to figure out this sort of class
loading (Class Not Found) problems?
Btw. I am using Groovy/Grails if that matters.
attachEvent is not a function - Using Module Pattern
attachEvent is not a function - Using Module Pattern
I am trying to build a JavaScript module to better understand the pattern.
I am trying to attach click events to a button with addEventListener and
attachEvent but I can not get my console.log to register.
I am also getting an error that says "TypeError: element.attachEvent is
not a function"
Here is a fiddle that I have at the moment: http://jsfiddle.net/rL5xp/
Here is the HTML:
<p>The color is <span class="js-print">green</span>.</p>
<button class="js-button">Click Here</button>
Here is the JavaScript:
var settings = [
{color : 'green'},
{color : 'blue'},
{color : 'red'}
];
var $ele = {
span : $('.js-print'),
button : $('.js-button')
};
var ChangeColor = (function(s, $element) {
var init = function() {
bindBrowserActions();
}
var bindBrowserActions = function() {
addClick($element.button, 'click', function() {
console.log('click');
});
}
var addClick = function(element, evnt, funct) {
if (element.addEventListener) {
return element.addEventListener(evnt, funct, false);
}
//addEventListener is not supported in <= IE8
else {
return element.attachEvent('on'+evnt, funct);
}
}
return {
init : init
}
})(settings, $ele);
(function() {
ChangeColor.init();
})();
I am trying to build a JavaScript module to better understand the pattern.
I am trying to attach click events to a button with addEventListener and
attachEvent but I can not get my console.log to register.
I am also getting an error that says "TypeError: element.attachEvent is
not a function"
Here is a fiddle that I have at the moment: http://jsfiddle.net/rL5xp/
Here is the HTML:
<p>The color is <span class="js-print">green</span>.</p>
<button class="js-button">Click Here</button>
Here is the JavaScript:
var settings = [
{color : 'green'},
{color : 'blue'},
{color : 'red'}
];
var $ele = {
span : $('.js-print'),
button : $('.js-button')
};
var ChangeColor = (function(s, $element) {
var init = function() {
bindBrowserActions();
}
var bindBrowserActions = function() {
addClick($element.button, 'click', function() {
console.log('click');
});
}
var addClick = function(element, evnt, funct) {
if (element.addEventListener) {
return element.addEventListener(evnt, funct, false);
}
//addEventListener is not supported in <= IE8
else {
return element.attachEvent('on'+evnt, funct);
}
}
return {
init : init
}
})(settings, $ele);
(function() {
ChangeColor.init();
})();
firefox's strange behavior using jQuery animate method and absolute position
firefox's strange behavior using jQuery animate method and absolute position
I have a problem when I'm using jQuery's(jQuery1.9.1) animate method. Here
is my code in jsfiddle: http://jsfiddle.net/AySas/3/ I want to make the
div wider using the relative percentage, ie:
html:
<div id="h_divCenter">
<div id="h_divIETodos" >
<div id="h_divIIEodoList" class="quadContent">
<ul id="h_ulIETodoList">
<li>itemC 3</li>
</ul>
</div>
</div>
css:
#h_divCenter {
position:absolute;
top:0;
left:20px;
right:100px;
bottom:0;
margin: 5px;
background: #0FF;
}
.quadContent {
position: absolute;
top: 41px;
bottom: 2px;
padding: 1px 1% 2px 1%;
width: 98%;
}
#h_ulIETodoList,#h_ulIUTodoList,#h_ulUETodoList,#h_ulUUTodoList {
width: 100%;
height: 100%;
list-style-type: none;
overflow: auto;
}
#h_divIETodos {
position: absolute;
margin: 2px;
top: 0;
left: 0;
right: 50%;
bottom: 50%;
color: #DE3C3C;
border: 1px solid #DE3C3C;
-webkit-box-shadow: 0px 0px 10px #DE3C3C;
-moz-box-shadow: 0px 0px 10px #DE3C3C;
box-shadow: 0px 0px 10px #DE3C3C;
}
javascript:
$('#btnTest').on("click", function(){
$("#h_divIETodos").animate({
right: "+=20%"
},500);
});
And this div has a absolute position and I have set the
top,right,bottom,left properties of css. It works fine in chrome. But in
firefox, you can see the right edge of the div cannot move by "20%". Has
someone else encountered with the similar problem before? I really
appreciate your help. Many thanks!
I have a problem when I'm using jQuery's(jQuery1.9.1) animate method. Here
is my code in jsfiddle: http://jsfiddle.net/AySas/3/ I want to make the
div wider using the relative percentage, ie:
html:
<div id="h_divCenter">
<div id="h_divIETodos" >
<div id="h_divIIEodoList" class="quadContent">
<ul id="h_ulIETodoList">
<li>itemC 3</li>
</ul>
</div>
</div>
css:
#h_divCenter {
position:absolute;
top:0;
left:20px;
right:100px;
bottom:0;
margin: 5px;
background: #0FF;
}
.quadContent {
position: absolute;
top: 41px;
bottom: 2px;
padding: 1px 1% 2px 1%;
width: 98%;
}
#h_ulIETodoList,#h_ulIUTodoList,#h_ulUETodoList,#h_ulUUTodoList {
width: 100%;
height: 100%;
list-style-type: none;
overflow: auto;
}
#h_divIETodos {
position: absolute;
margin: 2px;
top: 0;
left: 0;
right: 50%;
bottom: 50%;
color: #DE3C3C;
border: 1px solid #DE3C3C;
-webkit-box-shadow: 0px 0px 10px #DE3C3C;
-moz-box-shadow: 0px 0px 10px #DE3C3C;
box-shadow: 0px 0px 10px #DE3C3C;
}
javascript:
$('#btnTest').on("click", function(){
$("#h_divIETodos").animate({
right: "+=20%"
},500);
});
And this div has a absolute position and I have set the
top,right,bottom,left properties of css. It works fine in chrome. But in
firefox, you can see the right edge of the div cannot move by "20%". Has
someone else encountered with the similar problem before? I really
appreciate your help. Many thanks!
Friday, 13 September 2013
Drop an index in postgresql
Drop an index in postgresql
I had created an index wrongly and now im trying to drop that index. Since
the datas are large for my table, dropping index is taking lot of time. Is
there any other way to drop the index quickly?
Thanks, Karthika
I had created an index wrongly and now im trying to drop that index. Since
the datas are large for my table, dropping index is taking lot of time. Is
there any other way to drop the index quickly?
Thanks, Karthika
Passing an array of ints as an argument in C++?
Passing an array of ints as an argument in C++?
I made a function in C++ to find the length of an array. I find the sizeof
the array passed in the argument and divide it by the sizeof the variable
type. This should work but it always returns 1! Am I missing something
obvious? Or does this have to do with pointers and memory? This is my
code:
#include <iostream>
using namespace std;
int lengthOf(int arr[]);
int main() {
int x[] = {1,2,3,0,9,8};
int lenX = lengthOf(x);
cout << lenX;
return 0;
}
int lengthOf(int arr[]) {
int totalSize = sizeof arr;
cout << totalSize << endl;
int elementSize = sizeof(int);
return totalSize/elementSize;
}
Output (should be 6 instead of 1):
4
1
I am fairly new so excuse me if this is a bad question.
I made a function in C++ to find the length of an array. I find the sizeof
the array passed in the argument and divide it by the sizeof the variable
type. This should work but it always returns 1! Am I missing something
obvious? Or does this have to do with pointers and memory? This is my
code:
#include <iostream>
using namespace std;
int lengthOf(int arr[]);
int main() {
int x[] = {1,2,3,0,9,8};
int lenX = lengthOf(x);
cout << lenX;
return 0;
}
int lengthOf(int arr[]) {
int totalSize = sizeof arr;
cout << totalSize << endl;
int elementSize = sizeof(int);
return totalSize/elementSize;
}
Output (should be 6 instead of 1):
4
1
I am fairly new so excuse me if this is a bad question.
Does my node server need to manually end the response before the function ends?
Does my node server need to manually end the response before the function
ends?
I have a node server and I'm using express to process POST requests to it.
My question is, do I have to call response.end() before my processing
function ends or will that happen automatically?
Why I'm asking is because my server works as expected for the first few
requests, then it starts throwing "request timeout" errors, so I'm trying
to track down the issue.
I should also note that I always send something in the response using
response.send() if that makes any difference.
ends?
I have a node server and I'm using express to process POST requests to it.
My question is, do I have to call response.end() before my processing
function ends or will that happen automatically?
Why I'm asking is because my server works as expected for the first few
requests, then it starts throwing "request timeout" errors, so I'm trying
to track down the issue.
I should also note that I always send something in the response using
response.send() if that makes any difference.
Distance of two Rectangle Center's Connecting Line Outside of the Rectangles
Distance of two Rectangle Center's Connecting Line Outside of the Rectangles
Well excuse me for the long title, i dont really know how to call it.
I would like you to explain me how to calculate the image's red line's
length, knowing the rectangles position and dimensions.
Context: I need this for a 2d game collision response since when the
length is negative it means not only they are intersecting but also that
length is the distance they have to repel each other to stop being
collided. If there's an easier way to do this, even better.
Well excuse me for the long title, i dont really know how to call it.
I would like you to explain me how to calculate the image's red line's
length, knowing the rectangles position and dimensions.
Context: I need this for a 2d game collision response since when the
length is negative it means not only they are intersecting but also that
length is the distance they have to repel each other to stop being
collided. If there's an easier way to do this, even better.
Calling perl script from perl
Calling perl script from perl
I have a perl script which takes 2 arguments as follows and calls
appropriate function depending on the argument. I call this script from
bash, but i want to call it from perl, is it possible?
/opt/sbin/script.pl --group="value1" --rule="value2";
Also the script exits with a return value that I would like to read.
I have a perl script which takes 2 arguments as follows and calls
appropriate function depending on the argument. I call this script from
bash, but i want to call it from perl, is it possible?
/opt/sbin/script.pl --group="value1" --rule="value2";
Also the script exits with a return value that I would like to read.
Thursday, 12 September 2013
Move an image down
Move an image down
I am developing a webpage for images on a carousel. How can I move an
image down in a DIV, or even center it vertically?
Here is my CSS code:
.carousel .item {
height: 900px;
background-color: #777;
}
.carousel-inner > .item > img {
display: block;
margin-left: auto;
margin-right: auto
}
Here is a URL to the webpage in question to show you that the image is too
high: http://www.canninginc.co.nz/canluciddream/screenshots.html
EDIT
Ok, I have edited the code by changing the:
margin-top: 50px;
I am still after the image to be lower in the div. I can increase the top
margin, but this leaves a white background. What would be the best way to
move the image a little bit lower?
I am developing a webpage for images on a carousel. How can I move an
image down in a DIV, or even center it vertically?
Here is my CSS code:
.carousel .item {
height: 900px;
background-color: #777;
}
.carousel-inner > .item > img {
display: block;
margin-left: auto;
margin-right: auto
}
Here is a URL to the webpage in question to show you that the image is too
high: http://www.canninginc.co.nz/canluciddream/screenshots.html
EDIT
Ok, I have edited the code by changing the:
margin-top: 50px;
I am still after the image to be lower in the div. I can increase the top
margin, but this leaves a white background. What would be the best way to
move the image a little bit lower?
Smooth scroll for one page site
Smooth scroll for one page site
I'm working on a single page site that utilizes different section ids
instead of multiple pages. It's working fine, but I would like to have
scroll smoothly down to the section instead of just statically going to
the section on the page.
Jsfiddle: http://jsfiddle.net/schermerb/E9xuk/
#main {
width:960px;
margin:auto;
}
#header {
margin:auto;
height:75px;
width:960px;
}
.nav {
width:auto;
float:right;
font:normal 16px Futura, sans-serif;
padding:15px;
}
.nav ul li {
list-style:none;
float:left;
margin-left:15px;
color:#000;
}
#zero {
width:auto;
}
#one {
width:auto;
}
#two {
width:auto;
}
#three {
width:auto;
}
#four {
width:auto;
}
<div id="header">
<div class="nav">
<ul> <a href="#zero"><li>About</li></a>
<a href="#one"><li>Mobile</li></a>
<a href="#two"><li>Print</li></a>
<a href="#three"><li>Web</li></a>
<a href="#four"><li>Contact</li></a>
</ul>
</div>
</div>
<div id="main">
<div id="zero">
<p>There are many variations of passages of Lorem Ipsum available,
but the majority have suffered alteration in some form, by
injected humour, or randomised words which don't look even
slightly believable. If you are going to use a passage of Lorem
Ipsum, you need to be sure there isn't anything embarrassing
hidden in the middle of text. All the Lorem Ipsum generators on
the Internet tend to repeat predefined chunks as necessary, making
this the first true generator on the Internet. It uses a
dictionary of over 200 Latin words, combined with a handful of
model sentence structures, to generate Lorem Ipsum which looks
reasonable. The generated Lorem Ipsum is therefore always free
from repetition, injected humour, or non-characteristic words
etc.</p>
<p>There are many variations of passages of Lorem Ipsum available,
but the majority have suffered alteration in some form, by
injected humour, or randomised words which don't look even
slightly believable. If you are going to use a passage of Lorem
Ipsum, you need to be sure there isn't anything embarrassing
hidden in the middle of text. All the Lorem Ipsum generators on
the Internet tend to repeat predefined chunks as necessary, making
this the first true generator on the Internet. It uses a
dictionary of over 200 Latin words, combined with a handful of
model sentence structures, to generate Lorem Ipsum which looks
reasonable. The generated Lorem Ipsum is therefore always free
from repetition, injected humour, or non-characteristic words
etc.</p>
</div>
<div id="one">
<p>There are many variations of passages of Lorem Ipsum available,
but the majority have suffered alteration in some form, by
injected humour, or randomised words which don't look even
slightly believable. If you are going to use a passage of Lorem
Ipsum, you need to be sure there isn't anything embarrassing
hidden in the middle of text. All the Lorem Ipsum generators on
the Internet tend to repeat predefined chunks as necessary, making
this the first true generator on the Internet. It uses a
dictionary of over 200 Latin words, combined with a handful of
model sentence structures, to generate Lorem Ipsum which looks
reasonable. The generated Lorem Ipsum is therefore always free
from repetition, injected humour, or non-characteristic words
etc.</p>
<p>There are many variations of passages of Lorem Ipsum available,
but the majority have suffered alteration in some form, by
injected humour, or randomised words which don't look even
slightly believable. If you are going to use a passage of Lorem
Ipsum, you need to be sure there isn't anything embarrassing
hidden in the middle of text. All the Lorem Ipsum generators on
the Internet tend to repeat predefined chunks as necessary, making
this the first true generator on the Internet. It uses a
dictionary of over 200 Latin words, combined with a handful of
model sentence structures, to generate Lorem Ipsum which looks
reasonable. The generated Lorem Ipsum is therefore always free
from repetition, injected humour, or non-characteristic words
etc.</p>
</div>
<div id="two">
<p>There are many variations of passages of Lorem Ipsum available,
but the majority have suffered alteration in some form, by
injected humour, or randomised words which don't look even
slightly believable. If you are going to use a passage of Lorem
Ipsum, you need to be sure there isn't anything embarrassing
hidden in the middle of text. All the Lorem Ipsum generators on
the Internet tend to repeat predefined chunks as necessary, making
this the first true generator on the Internet. It uses a
dictionary of over 200 Latin words, combined with a handful of
model sentence structures, to generate Lorem Ipsum which looks
reasonable. The generated Lorem Ipsum is therefore always free
from repetition, injected humour, or non-characteristic words
etc.</p>
<p>There are many variations of passages of Lorem Ipsum available,
but the majority have suffered alteration in some form, by
injected humour, or randomised words which don't look even
slightly believable. If you are going to use a passage of Lorem
Ipsum, you need to be sure there isn't anything embarrassing
hidden in the middle of text. All the Lorem Ipsum generators on
the Internet tend to repeat predefined chunks as necessary, making
this the first true generator on the Internet. It uses a
dictionary of over 200 Latin words, combined with a handful of
model sentence structures, to generate Lorem Ipsum which looks
reasonable. The generated Lorem Ipsum is therefore always free
from repetition, injected humour, or non-characteristic words
etc.</p>
</div>
<div id="three">
<p>There are many variations of passages of Lorem Ipsum available,
but the majority have suffered alteration in some form, by
injected humour, or randomised words which don't look even
slightly believable. If you are going to use a passage of Lorem
Ipsum, you need to be sure there isn't anything embarrassing
hidden in the middle of text. All the Lorem Ipsum generators on
the Internet tend to repeat predefined chunks as necessary, making
this the first true generator on the Internet. It uses a
dictionary of over 200 Latin words, combined with a handful of
model sentence structures, to generate Lorem Ipsum which looks
reasonable. The generated Lorem Ipsum is therefore always free
from repetition, injected humour, or non-characteristic words
etc.</p>
<p>There are many variations of passages of Lorem Ipsum available,
but the majority have suffered alteration in some form, by
injected humour, or randomised words which don't look even
slightly believable. If you are going to use a passage of Lorem
Ipsum, you need to be sure there isn't anything embarrassing
hidden in the middle of text. All the Lorem Ipsum generators on
the Internet tend to repeat predefined chunks as necessary, making
this the first true generator on the Internet. It uses a
dictionary of over 200 Latin words, combined with a handful of
model sentence structures, to generate Lorem Ipsum which looks
reasonable. The generated Lorem Ipsum is therefore always free
from repetition, injected humour, or non-characteristic words
etc.</p>
</div>
<div id="four">
<p>There are many variations of passages of Lorem Ipsum available,
but the majority have suffered alteration in some form, by
injected humour, or randomised words which don't look even
slightly believable. If you are going to use a passage of Lorem
Ipsum, you need to be sure there isn't anything embarrassing
hidden in the middle of text. All the Lorem Ipsum generators on
the Internet tend to repeat predefined chunks as necessary, making
this the first true generator on the Internet. It uses a
dictionary of over 200 Latin words, combined with a handful of
model sentence structures, to generate Lorem Ipsum which looks
reasonable. The generated Lorem Ipsum is therefore always free
from repetition, injected humour, or non-characteristic words
etc.</p>
<p>There are many variations of passages of Lorem Ipsum available,
but the majority have suffered alteration in some form, by
injected humour, or randomised words which don't look even
slightly believable. If you are going to use a passage of Lorem
Ipsum, you need to be sure there isn't anything embarrassing
hidden in the middle of text. All the Lorem Ipsum generators on
the Internet tend to repeat predefined chunks as necessary, making
this the first true generator on the Internet. It uses a
dictionary of over 200 Latin words, combined with a handful of
model sentence structures, to generate Lorem Ipsum which looks
reasonable. The generated Lorem Ipsum is therefore always free
from repetition, injected humour, or non-characteristic words
etc.</p>
</div>
</div>
I'm working on a single page site that utilizes different section ids
instead of multiple pages. It's working fine, but I would like to have
scroll smoothly down to the section instead of just statically going to
the section on the page.
Jsfiddle: http://jsfiddle.net/schermerb/E9xuk/
#main {
width:960px;
margin:auto;
}
#header {
margin:auto;
height:75px;
width:960px;
}
.nav {
width:auto;
float:right;
font:normal 16px Futura, sans-serif;
padding:15px;
}
.nav ul li {
list-style:none;
float:left;
margin-left:15px;
color:#000;
}
#zero {
width:auto;
}
#one {
width:auto;
}
#two {
width:auto;
}
#three {
width:auto;
}
#four {
width:auto;
}
<div id="header">
<div class="nav">
<ul> <a href="#zero"><li>About</li></a>
<a href="#one"><li>Mobile</li></a>
<a href="#two"><li>Print</li></a>
<a href="#three"><li>Web</li></a>
<a href="#four"><li>Contact</li></a>
</ul>
</div>
</div>
<div id="main">
<div id="zero">
<p>There are many variations of passages of Lorem Ipsum available,
but the majority have suffered alteration in some form, by
injected humour, or randomised words which don't look even
slightly believable. If you are going to use a passage of Lorem
Ipsum, you need to be sure there isn't anything embarrassing
hidden in the middle of text. All the Lorem Ipsum generators on
the Internet tend to repeat predefined chunks as necessary, making
this the first true generator on the Internet. It uses a
dictionary of over 200 Latin words, combined with a handful of
model sentence structures, to generate Lorem Ipsum which looks
reasonable. The generated Lorem Ipsum is therefore always free
from repetition, injected humour, or non-characteristic words
etc.</p>
<p>There are many variations of passages of Lorem Ipsum available,
but the majority have suffered alteration in some form, by
injected humour, or randomised words which don't look even
slightly believable. If you are going to use a passage of Lorem
Ipsum, you need to be sure there isn't anything embarrassing
hidden in the middle of text. All the Lorem Ipsum generators on
the Internet tend to repeat predefined chunks as necessary, making
this the first true generator on the Internet. It uses a
dictionary of over 200 Latin words, combined with a handful of
model sentence structures, to generate Lorem Ipsum which looks
reasonable. The generated Lorem Ipsum is therefore always free
from repetition, injected humour, or non-characteristic words
etc.</p>
</div>
<div id="one">
<p>There are many variations of passages of Lorem Ipsum available,
but the majority have suffered alteration in some form, by
injected humour, or randomised words which don't look even
slightly believable. If you are going to use a passage of Lorem
Ipsum, you need to be sure there isn't anything embarrassing
hidden in the middle of text. All the Lorem Ipsum generators on
the Internet tend to repeat predefined chunks as necessary, making
this the first true generator on the Internet. It uses a
dictionary of over 200 Latin words, combined with a handful of
model sentence structures, to generate Lorem Ipsum which looks
reasonable. The generated Lorem Ipsum is therefore always free
from repetition, injected humour, or non-characteristic words
etc.</p>
<p>There are many variations of passages of Lorem Ipsum available,
but the majority have suffered alteration in some form, by
injected humour, or randomised words which don't look even
slightly believable. If you are going to use a passage of Lorem
Ipsum, you need to be sure there isn't anything embarrassing
hidden in the middle of text. All the Lorem Ipsum generators on
the Internet tend to repeat predefined chunks as necessary, making
this the first true generator on the Internet. It uses a
dictionary of over 200 Latin words, combined with a handful of
model sentence structures, to generate Lorem Ipsum which looks
reasonable. The generated Lorem Ipsum is therefore always free
from repetition, injected humour, or non-characteristic words
etc.</p>
</div>
<div id="two">
<p>There are many variations of passages of Lorem Ipsum available,
but the majority have suffered alteration in some form, by
injected humour, or randomised words which don't look even
slightly believable. If you are going to use a passage of Lorem
Ipsum, you need to be sure there isn't anything embarrassing
hidden in the middle of text. All the Lorem Ipsum generators on
the Internet tend to repeat predefined chunks as necessary, making
this the first true generator on the Internet. It uses a
dictionary of over 200 Latin words, combined with a handful of
model sentence structures, to generate Lorem Ipsum which looks
reasonable. The generated Lorem Ipsum is therefore always free
from repetition, injected humour, or non-characteristic words
etc.</p>
<p>There are many variations of passages of Lorem Ipsum available,
but the majority have suffered alteration in some form, by
injected humour, or randomised words which don't look even
slightly believable. If you are going to use a passage of Lorem
Ipsum, you need to be sure there isn't anything embarrassing
hidden in the middle of text. All the Lorem Ipsum generators on
the Internet tend to repeat predefined chunks as necessary, making
this the first true generator on the Internet. It uses a
dictionary of over 200 Latin words, combined with a handful of
model sentence structures, to generate Lorem Ipsum which looks
reasonable. The generated Lorem Ipsum is therefore always free
from repetition, injected humour, or non-characteristic words
etc.</p>
</div>
<div id="three">
<p>There are many variations of passages of Lorem Ipsum available,
but the majority have suffered alteration in some form, by
injected humour, or randomised words which don't look even
slightly believable. If you are going to use a passage of Lorem
Ipsum, you need to be sure there isn't anything embarrassing
hidden in the middle of text. All the Lorem Ipsum generators on
the Internet tend to repeat predefined chunks as necessary, making
this the first true generator on the Internet. It uses a
dictionary of over 200 Latin words, combined with a handful of
model sentence structures, to generate Lorem Ipsum which looks
reasonable. The generated Lorem Ipsum is therefore always free
from repetition, injected humour, or non-characteristic words
etc.</p>
<p>There are many variations of passages of Lorem Ipsum available,
but the majority have suffered alteration in some form, by
injected humour, or randomised words which don't look even
slightly believable. If you are going to use a passage of Lorem
Ipsum, you need to be sure there isn't anything embarrassing
hidden in the middle of text. All the Lorem Ipsum generators on
the Internet tend to repeat predefined chunks as necessary, making
this the first true generator on the Internet. It uses a
dictionary of over 200 Latin words, combined with a handful of
model sentence structures, to generate Lorem Ipsum which looks
reasonable. The generated Lorem Ipsum is therefore always free
from repetition, injected humour, or non-characteristic words
etc.</p>
</div>
<div id="four">
<p>There are many variations of passages of Lorem Ipsum available,
but the majority have suffered alteration in some form, by
injected humour, or randomised words which don't look even
slightly believable. If you are going to use a passage of Lorem
Ipsum, you need to be sure there isn't anything embarrassing
hidden in the middle of text. All the Lorem Ipsum generators on
the Internet tend to repeat predefined chunks as necessary, making
this the first true generator on the Internet. It uses a
dictionary of over 200 Latin words, combined with a handful of
model sentence structures, to generate Lorem Ipsum which looks
reasonable. The generated Lorem Ipsum is therefore always free
from repetition, injected humour, or non-characteristic words
etc.</p>
<p>There are many variations of passages of Lorem Ipsum available,
but the majority have suffered alteration in some form, by
injected humour, or randomised words which don't look even
slightly believable. If you are going to use a passage of Lorem
Ipsum, you need to be sure there isn't anything embarrassing
hidden in the middle of text. All the Lorem Ipsum generators on
the Internet tend to repeat predefined chunks as necessary, making
this the first true generator on the Internet. It uses a
dictionary of over 200 Latin words, combined with a handful of
model sentence structures, to generate Lorem Ipsum which looks
reasonable. The generated Lorem Ipsum is therefore always free
from repetition, injected humour, or non-characteristic words
etc.</p>
</div>
</div>
Auto Layout with UITabBarController
Auto Layout with UITabBarController
I'm trying to shift to Auto Layout in my app, but I'm having some trouble
with my UITabBarController. Basically, I have two buttons on my home
screen, and I want them to have equal sizes, one 50 pixels from the top of
the screen and one 50 pixels from the bottom.
The issue is that when I do this:
NSArray* verticalConstraints = [NSLayoutConstraint
constraintsWithVisualFormat:@"V:|-50-
[buttonOne(150)]" options:0 metrics:nil
views:NSDictionaryOfVariableBindings(buttonOne)];
[self.view addConstraints:verticalConstraints];
verticalConstraints = [NSLayoutConstraint constraintsWithVisualFormat:@"V:
[buttonTwo(==buttonOne)]-50-|" options:0 metrics:nil
views:NSDictionaryOfVariableBindings(buttonOne, buttonTwo)];
[self.view addConstraints:verticalConstraints];
The bottom button is 50 pixels from the bottom of the view, which is 568
points tall, when the height of self.view should be the screen height
minus the tab bar's height (the navigation bar is hidden). The majority of
this padding is eaten up by the height of the tab bar.
My questions is: Why is my view controller's view not resizing so that it
doesn't count the space under my tab bar as part of its height?
I'm trying to shift to Auto Layout in my app, but I'm having some trouble
with my UITabBarController. Basically, I have two buttons on my home
screen, and I want them to have equal sizes, one 50 pixels from the top of
the screen and one 50 pixels from the bottom.
The issue is that when I do this:
NSArray* verticalConstraints = [NSLayoutConstraint
constraintsWithVisualFormat:@"V:|-50-
[buttonOne(150)]" options:0 metrics:nil
views:NSDictionaryOfVariableBindings(buttonOne)];
[self.view addConstraints:verticalConstraints];
verticalConstraints = [NSLayoutConstraint constraintsWithVisualFormat:@"V:
[buttonTwo(==buttonOne)]-50-|" options:0 metrics:nil
views:NSDictionaryOfVariableBindings(buttonOne, buttonTwo)];
[self.view addConstraints:verticalConstraints];
The bottom button is 50 pixels from the bottom of the view, which is 568
points tall, when the height of self.view should be the screen height
minus the tab bar's height (the navigation bar is hidden). The majority of
this padding is eaten up by the height of the tab bar.
My questions is: Why is my view controller's view not resizing so that it
doesn't count the space under my tab bar as part of its height?
How to fix UITableView on iOS 7?
How to fix UITableView on iOS 7?
UITableView draws with ragged lines on iOS 7:
How to fix it? The line between cells should be on the full width of the
screen.
UITableView draws with ragged lines on iOS 7:
How to fix it? The line between cells should be on the full width of the
screen.
Wednesday, 11 September 2013
gdb: Cast memory address to an STL object
gdb: Cast memory address to an STL object
I have a memory address that i know is an STL object. Say the address is
0x603340, and I know there is a map there
How do I display the contents of this memory as said object from gdb?
I tried this:
p ('std::map<std::string, std::string*, std::less<std::string>,
std::allocator<std::pair<std::string const, std::string*> > >'*) 0x603340
which gets me:
No symbol "std::map<std::string, std::string*, std::less<std::string>,
std::allocator<std::pair<std::string const, std::string*> > >" in current
context.
Any idea what am I doing wrong? Thanks.
I have a memory address that i know is an STL object. Say the address is
0x603340, and I know there is a map there
How do I display the contents of this memory as said object from gdb?
I tried this:
p ('std::map<std::string, std::string*, std::less<std::string>,
std::allocator<std::pair<std::string const, std::string*> > >'*) 0x603340
which gets me:
No symbol "std::map<std::string, std::string*, std::less<std::string>,
std::allocator<std::pair<std::string const, std::string*> > >" in current
context.
Any idea what am I doing wrong? Thanks.
How to replace all capture groups if it is generated dynamically?
How to replace all capture groups if it is generated dynamically?
Consider the following code:
function Matcher(source, search) {
var opts = search.split('');
for (var i = 0; i < opts.length; i++) {
opts[i] = '(' + opts[i] + ')';
}
opts = opts.join('.*');
var regexp = new RegExp(opts, 'gi');
source = source.replace(regexp, function () {
console.log(arguments);
return arguments[1];
});
return source;
}
You call the function passing the source as the first parameter and what
you need to match as the second one.
What i need is to replace all capture groups with a bold tag around the
coincidence.
As an example, consider the following:
var patt =
/m([a-z0-9\-_]*?)r([a-z0-9\-_]*?)i([a-z0-9\-_]*?)e([a-z0-9\-_]*\.[a-z]+)/gi;
var newFileName = fileName.replace(patt,
"<strong>m</strong>$1<strong>r</strong>$2<strong>i</strong>$3<strong>e</strong>$4");
This code is a response from Terry (thanks by the way) but the problem
here is that you need to know exactly what you want to replace, and i need
it dynamically.
Any thoughts?
Consider the following code:
function Matcher(source, search) {
var opts = search.split('');
for (var i = 0; i < opts.length; i++) {
opts[i] = '(' + opts[i] + ')';
}
opts = opts.join('.*');
var regexp = new RegExp(opts, 'gi');
source = source.replace(regexp, function () {
console.log(arguments);
return arguments[1];
});
return source;
}
You call the function passing the source as the first parameter and what
you need to match as the second one.
What i need is to replace all capture groups with a bold tag around the
coincidence.
As an example, consider the following:
var patt =
/m([a-z0-9\-_]*?)r([a-z0-9\-_]*?)i([a-z0-9\-_]*?)e([a-z0-9\-_]*\.[a-z]+)/gi;
var newFileName = fileName.replace(patt,
"<strong>m</strong>$1<strong>r</strong>$2<strong>i</strong>$3<strong>e</strong>$4");
This code is a response from Terry (thanks by the way) but the problem
here is that you need to know exactly what you want to replace, and i need
it dynamically.
Any thoughts?
Restriction of "new" keyword in Javascript
Restriction of "new" keyword in Javascript
I have this JS code:
var A = {};
A.new = function(n) { return new Array(n); }
It works well in all browsers, but when I try to obfuscate it with
obfuscator, it shows an error.
Is it a valid JS code? I looked into specification, but didn't find
anything. I know, that browsers sometimes accept syntactically wrong code,
but I want to write syntactically correct code.
I have this JS code:
var A = {};
A.new = function(n) { return new Array(n); }
It works well in all browsers, but when I try to obfuscate it with
obfuscator, it shows an error.
Is it a valid JS code? I looked into specification, but didn't find
anything. I know, that browsers sometimes accept syntactically wrong code,
but I want to write syntactically correct code.
Submit App for iOS 7 Now?
Submit App for iOS 7 Now?
Now that the GM is out, can we send the Binary compiled for iOS 7 only to
the App Store? Or Do we have to wait until September 18?
It seems that Review requires Apps to run iOS 7 now so I'm kinda in a
stump here. It took them 2 weeks to tell me that which is weird because up
to this point iOS 7 was still in Beta. I'm trying to communicate with them
about it though since iOS 6.1.3 is the only official iOS atm. Is this
another waiting game or can I just build against the GM release and try
submitting again?
From my recollection it should be the the Final Build that's allowed to be
submitted, correct?
Thanks!
Now that the GM is out, can we send the Binary compiled for iOS 7 only to
the App Store? Or Do we have to wait until September 18?
It seems that Review requires Apps to run iOS 7 now so I'm kinda in a
stump here. It took them 2 weeks to tell me that which is weird because up
to this point iOS 7 was still in Beta. I'm trying to communicate with them
about it though since iOS 6.1.3 is the only official iOS atm. Is this
another waiting game or can I just build against the GM release and try
submitting again?
From my recollection it should be the the Final Build that's allowed to be
submitted, correct?
Thanks!
Subscribe to:
Comments (Atom)