Virtual drawing pad using color detection in matlab
I am trying to make a virtual drawing pad by detecting and tracking red
objects in a video from a webcam and increasing corresponding intensity
values on a blank background. I am using this code to track red objects
data = getsnapshot(vid);
diff_im = imsubtract(data(:,:,1), rgb2gray(data)); %find red regions in
image
diff_im = medfilt2(diff_im, [3 3]); %Use a median filter to
filter out noise
diff_im = im2bw(diff_im,0.18); % Convert the resulting grayscale
image into a binary image.
diff_im = bwareaopen(diff_im,300); % Remove all those pixels less than
300px,
[bw, count] = bwlabel(diff_im, 8);
if(count > 0)
%% then draw rectangle around centroid of detected object
I am checking for every pixel, which increases processing time when image
size increases(even for 640*480). As a result of this output is blank for
many frames. How can I improve it..??
Saturday, 31 August 2013
How to echo multiple rows with data based on checkbox input?
How to echo multiple rows with data based on checkbox input?
Got stuck trying to echo out multiple rows with data based on checkbox
input. As of current code it processes data from only one checkbox, no
matter how many checkboxes are ticked. Please help!
while($row = mysql_fetch_assoc($r))
{
$pals .= '<input type="checkbox" name="pal_num[]"
value="'.$row['pal_num'].'">'.$row['pal_num'].'<br>';
}
if($pal == '') {
echo '';
} else {
echo '<form name="get_pal" action="post2.php" method="POST">';
echo $pals;
echo '<input type="submit" name="post" value="Go!">';
echo '</form>';
}
post2.php:
$w = $_POST['pal_num'];
$rrr = mysql_query("SELECT * FROM pl_tab WHERE pal_num".$w[0]);
while($row = mysql_fetch_array($rrr))
{
echo '<tr><td>'.' '.'</td>';
echo '<td rowspan="5">'.$row['descr'].'</td>';
echo '<td><b>'.'Total weight'.'<b></td>';
echo '<td>'.' '.'</td><td>'.' '.'</td></tr>';
echo '<td>'.' '.'</td>';
echo '<td colspan="3">'.' '.'</td>';
//this part should multiple based on how many checkboxes are ticked.
echo '<tr><td>'.$row['l_num'].'</td>';
echo '<td>'.$row['pal_num'].'</td>';
echo '<td>'.$row['weight 1'].'</td><td>'.$row['weight 2'].'</td></tr>';
}
echo "</table>";}
Got stuck trying to echo out multiple rows with data based on checkbox
input. As of current code it processes data from only one checkbox, no
matter how many checkboxes are ticked. Please help!
while($row = mysql_fetch_assoc($r))
{
$pals .= '<input type="checkbox" name="pal_num[]"
value="'.$row['pal_num'].'">'.$row['pal_num'].'<br>';
}
if($pal == '') {
echo '';
} else {
echo '<form name="get_pal" action="post2.php" method="POST">';
echo $pals;
echo '<input type="submit" name="post" value="Go!">';
echo '</form>';
}
post2.php:
$w = $_POST['pal_num'];
$rrr = mysql_query("SELECT * FROM pl_tab WHERE pal_num".$w[0]);
while($row = mysql_fetch_array($rrr))
{
echo '<tr><td>'.' '.'</td>';
echo '<td rowspan="5">'.$row['descr'].'</td>';
echo '<td><b>'.'Total weight'.'<b></td>';
echo '<td>'.' '.'</td><td>'.' '.'</td></tr>';
echo '<td>'.' '.'</td>';
echo '<td colspan="3">'.' '.'</td>';
//this part should multiple based on how many checkboxes are ticked.
echo '<tr><td>'.$row['l_num'].'</td>';
echo '<td>'.$row['pal_num'].'</td>';
echo '<td>'.$row['weight 1'].'</td><td>'.$row['weight 2'].'</td></tr>';
}
echo "</table>";}
Making/Initializing Array of Struct Like Objects in Java
Making/Initializing Array of Struct Like Objects in Java
I am using Java SE on NetBeans 7.3.1.
I would like to form a Java array similar to the following in C
typedef struct sNewStruct{
int min;
int max;
} NewStruct;
NewTruct nsVar[19];
I tried the following
class IntRange{
int min, max;
}
IntRange[] rangeNodes = new IntRange[19];
My problem is that, while rangeNodes is successfully allocated, all of its
elements are nulls.
I am using Java SE on NetBeans 7.3.1.
I would like to form a Java array similar to the following in C
typedef struct sNewStruct{
int min;
int max;
} NewStruct;
NewTruct nsVar[19];
I tried the following
class IntRange{
int min, max;
}
IntRange[] rangeNodes = new IntRange[19];
My problem is that, while rangeNodes is successfully allocated, all of its
elements are nulls.
Asymptote not working with GSView and Ghostscript
Asymptote not working with GSView and Ghostscript
I downloaded and installed Asymptote 2.24 (the vector graphics language)
according to
http://www.artofproblemsolving.com/Wiki/index.php/Asymptote:_Getting_Started/Windows/Downloads_and_Installation.
I also have GSView 5.0 and Ghostscript 9.07 and I have connected GSView
with Ghostscript. I wanted to see if Asymptote worked so I ran (still
following
http://www.artofproblemsolving.com/Wiki/index.php/Asymptote:_Getting_Started/Windows/Interactive_Mode)
asy
draw((0,0)--(100,100));
with asy.exe and I get "The system cannot find the file out.eps"
All the programs are 32 bit even though I have 64 bit windows 7, and I
can't figure out what's going wrong. Any help would be very much
appreciated.
I downloaded and installed Asymptote 2.24 (the vector graphics language)
according to
http://www.artofproblemsolving.com/Wiki/index.php/Asymptote:_Getting_Started/Windows/Downloads_and_Installation.
I also have GSView 5.0 and Ghostscript 9.07 and I have connected GSView
with Ghostscript. I wanted to see if Asymptote worked so I ran (still
following
http://www.artofproblemsolving.com/Wiki/index.php/Asymptote:_Getting_Started/Windows/Interactive_Mode)
asy
draw((0,0)--(100,100));
with asy.exe and I get "The system cannot find the file out.eps"
All the programs are 32 bit even though I have 64 bit windows 7, and I
can't figure out what's going wrong. Any help would be very much
appreciated.
Replace UITableViewController MasterView in UISplitViewController with UITabBarViewController
Replace UITableViewController MasterView in UISplitViewController with
UITabBarViewController
I'm working on a project that requires UIsplitViewController, but I need
the rootViewController to be UITabViewController not UITableViewController
I'm using storyboard which allows me to display the UITabViewController
but when I'm trying to send data to DetailViewControler using delegate
DetailViewController not responding, is there any solution for that I've
been trying for over 1 month to find a way I can't find anything.
UITabBarViewController
I'm working on a project that requires UIsplitViewController, but I need
the rootViewController to be UITabViewController not UITableViewController
I'm using storyboard which allows me to display the UITabViewController
but when I'm trying to send data to DetailViewControler using delegate
DetailViewController not responding, is there any solution for that I've
been trying for over 1 month to find a way I can't find anything.
Would a partial index be used on a query?
Would a partial index be used on a query?
Given this partial index:
CREATE INDEX orders_id_created_at_index ON orders(id) WHERE created_at <
'2013-12-31';
Would this query use the index?
SELECT * FROM orders WHERE id = 123 AND created_at = ''2013-10-12';
As per the documentation, "a partial index can be used in a query
only if the system can recognize that the WHERE condition of the query
mathematically implies the predicate of the index". Does that mean that
the index will or will not be used?
Given this partial index:
CREATE INDEX orders_id_created_at_index ON orders(id) WHERE created_at <
'2013-12-31';
Would this query use the index?
SELECT * FROM orders WHERE id = 123 AND created_at = ''2013-10-12';
As per the documentation, "a partial index can be used in a query
only if the system can recognize that the WHERE condition of the query
mathematically implies the predicate of the index". Does that mean that
the index will or will not be used?
xpinc Javascript no longer works after client downgrade
xpinc Javascript no longer works after client downgrade
I needed to downgrade my Lotus Notes client from 8.5.3 to 8.5.2 to verify
some functionality works in the earlier client. After doing this, any
JavaScript included in my XPages, from a simple alert() prompt to the
loading of Dojo, no longer works. I've completely uninstalled 8.5.2,
rebooted and reinstalled the client, to no avail. Weird thing is,
JavaScript does work in my Notes client in a simple page.
I've double-checked, and my Notes client preferences are set to run
JavaScript, and my ECL entries show every legit signer as being able to
run JavaScript. The databases I've tested so far all have "Use JavaScript
when loading pages" enabled.
Any idea what could be going wrong?
I needed to downgrade my Lotus Notes client from 8.5.3 to 8.5.2 to verify
some functionality works in the earlier client. After doing this, any
JavaScript included in my XPages, from a simple alert() prompt to the
loading of Dojo, no longer works. I've completely uninstalled 8.5.2,
rebooted and reinstalled the client, to no avail. Weird thing is,
JavaScript does work in my Notes client in a simple page.
I've double-checked, and my Notes client preferences are set to run
JavaScript, and my ECL entries show every legit signer as being able to
run JavaScript. The databases I've tested so far all have "Use JavaScript
when loading pages" enabled.
Any idea what could be going wrong?
Kentico CSS List Menu styling
Kentico CSS List Menu styling
I am to implement this structure with kentico
<li class="megamenu_button"><a href="#_">Mega Menu</a></li>
<li><a href="#">Home</a></li>
<li class="aa"><a href="#_" class="megamenu_drop">About Us</a><!--
Begin Item -->
<div class="dropdown_4columns dropdown_container"><!-- Begin
Item Container -->
<div class="col_12">
<img class="img_left" src="images/about_us_img.png"
width="125" height="146">
<ul class="list_unstyled">
<li><a href="#_">FreelanceSwitch</a></li>
<li><a href="#_">Creattica</a></li>
<li><a href="#_">WorkAwesome</a></li>
<li><a href="#_">Mac Apps</a></li>
</ul>
</div>
</div><!-- End Item Container -->
</li><!-- End Item -->
</ul><!-- End Mega Menu -->
The design is meant to have at least 6 menu headers with sub-menu each.
The challenge is I don't even know how to approach the design. I am
currently using aspx master template. All suggestion is welcome.
I am to implement this structure with kentico
<li class="megamenu_button"><a href="#_">Mega Menu</a></li>
<li><a href="#">Home</a></li>
<li class="aa"><a href="#_" class="megamenu_drop">About Us</a><!--
Begin Item -->
<div class="dropdown_4columns dropdown_container"><!-- Begin
Item Container -->
<div class="col_12">
<img class="img_left" src="images/about_us_img.png"
width="125" height="146">
<ul class="list_unstyled">
<li><a href="#_">FreelanceSwitch</a></li>
<li><a href="#_">Creattica</a></li>
<li><a href="#_">WorkAwesome</a></li>
<li><a href="#_">Mac Apps</a></li>
</ul>
</div>
</div><!-- End Item Container -->
</li><!-- End Item -->
</ul><!-- End Mega Menu -->
The design is meant to have at least 6 menu headers with sub-menu each.
The challenge is I don't even know how to approach the design. I am
currently using aspx master template. All suggestion is welcome.
Friday, 30 August 2013
Setting null value to integer
Setting null value to integer
How can i set null to integer variable initially instead of "0". I know
already by default all int value is "0". I used string.valueOf() method
etc. I get number format exception. Please give one solution for that.
Thanks in advance
Here code
public class IntegerDemo {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String id="";
System.out.println(""+Integer.parseInt(id));
}
}
How can i set null to integer variable initially instead of "0". I know
already by default all int value is "0". I used string.valueOf() method
etc. I get number format exception. Please give one solution for that.
Thanks in advance
Here code
public class IntegerDemo {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String id="";
System.out.println(""+Integer.parseInt(id));
}
}
Thursday, 29 August 2013
Is there an easy way to get place gis data?
Is there an easy way to get place gis data?
I want to get grocery/ shopping mall spatial data in Singapore. I've tried
Google Place API, but it only returns maximum 20 records. and it has
request times limitation. are there another approaches to do such job?
Thanks,
I want to get grocery/ shopping mall spatial data in Singapore. I've tried
Google Place API, but it only returns maximum 20 records. and it has
request times limitation. are there another approaches to do such job?
Thanks,
SQL printing error message with bad record code
SQL printing error message with bad record code
Working with SQL Server 2005 Creating Trigger which checks if inserting
not already exist. Having problem getting record parameter, there is the
code:
CREATE TRIGGER t_MFShiftTypeOperation ON [CAST$MFShiftTypeOperation]
FOR INSERT, UPDATE AS
IF @@ROWCOUNT=1 BEGIN
IF EXISTS (SELECT * FROM inserted AS I
JOIN CAST$MFShiftTypeOperation AS STO
ON ((I.ShiftTypeCode = STO.ShiftTypeCode AND
I.PackCode = STO.PackCode) OR
I.RegisterAppCode = STO.RegisterAppCode))
BEGIN
DECLARE @Bad_PackCode AS EmpUserCode_t
SET @Bad_PackCode = SELECT TOP(1) PackCode FROM inserted --there is error
ROLLBACK TRAN
PRINT 'Îperation with '+ @Bad_PackCode +' already exist'
END
END
when I'm trying to execute code, it throws me error message:
Msg 156, Level 15, State 1, Procedure t_MFShiftTypeOperation, Line 16
Incorrect syntax near the keyword 'SELECT'.
Can someone explain where is mistake, or suggest better solution.
Working with SQL Server 2005 Creating Trigger which checks if inserting
not already exist. Having problem getting record parameter, there is the
code:
CREATE TRIGGER t_MFShiftTypeOperation ON [CAST$MFShiftTypeOperation]
FOR INSERT, UPDATE AS
IF @@ROWCOUNT=1 BEGIN
IF EXISTS (SELECT * FROM inserted AS I
JOIN CAST$MFShiftTypeOperation AS STO
ON ((I.ShiftTypeCode = STO.ShiftTypeCode AND
I.PackCode = STO.PackCode) OR
I.RegisterAppCode = STO.RegisterAppCode))
BEGIN
DECLARE @Bad_PackCode AS EmpUserCode_t
SET @Bad_PackCode = SELECT TOP(1) PackCode FROM inserted --there is error
ROLLBACK TRAN
PRINT 'Îperation with '+ @Bad_PackCode +' already exist'
END
END
when I'm trying to execute code, it throws me error message:
Msg 156, Level 15, State 1, Procedure t_MFShiftTypeOperation, Line 16
Incorrect syntax near the keyword 'SELECT'.
Can someone explain where is mistake, or suggest better solution.
multiple condition in single linq
multiple condition in single linq
I am iteration through the control which is having multiple rows and each
row having a tag and just implemented the following linq. Can i optimize
the following queries into single one?
Dim xCheckTag As String = If((From xTag As Row In Sheet1.Rows Where
xTag.Tag = "FtpHeader").ToArray.Length > 0, "FtpHeader", _
If((From xTag As Row In Sheet1.Rows Where
xTag.Tag = "MailHeader").ToArray.Length > 0,
"MailHeader", _
If((From xTag As Row In Sheet1.Rows Where
xTag.Tag = "GoogleHeader").ToArray.Length > 0,
"GoogleHeader", _
If((From xTag As Row In Sheet1.Rows Where
xTag.Tag = "NetworkHeader").ToArray.Length >
0, "NetworkHeader", String.Empty))))
I am iteration through the control which is having multiple rows and each
row having a tag and just implemented the following linq. Can i optimize
the following queries into single one?
Dim xCheckTag As String = If((From xTag As Row In Sheet1.Rows Where
xTag.Tag = "FtpHeader").ToArray.Length > 0, "FtpHeader", _
If((From xTag As Row In Sheet1.Rows Where
xTag.Tag = "MailHeader").ToArray.Length > 0,
"MailHeader", _
If((From xTag As Row In Sheet1.Rows Where
xTag.Tag = "GoogleHeader").ToArray.Length > 0,
"GoogleHeader", _
If((From xTag As Row In Sheet1.Rows Where
xTag.Tag = "NetworkHeader").ToArray.Length >
0, "NetworkHeader", String.Empty))))
Wednesday, 28 August 2013
Finding a list of decompiled packages
Finding a list of decompiled packages
If I make a lot of modifications to tables in Oracle. Is there a way to
have a list of packages that don't compile anymore?
I can easely get the list of packages from the list of tables that I
changed, but I wonder if it's possible to get everything that isn't
compiling.
If I make a lot of modifications to tables in Oracle. Is there a way to
have a list of packages that don't compile anymore?
I can easely get the list of packages from the list of tables that I
changed, but I wonder if it's possible to get everything that isn't
compiling.
How to resize video surfaceview in android?
How to resize video surfaceview in android?
I'm using MediaPlayer and SurfaceView to play video files. I want to
implement video resize functionality to my app with following resizing
options- Stretch, crop, fit to screen etc. How can i do this? (currently
it is stretched)
I'm using MediaPlayer and SurfaceView to play video files. I want to
implement video resize functionality to my app with following resizing
options- Stretch, crop, fit to screen etc. How can i do this? (currently
it is stretched)
vb.net: is threaded form completely loaded?
vb.net: is threaded form completely loaded?
I use a BackgroundWorker to load a big form without halting the
functionailty of the main form, but when I try to show the subform too
early I get an Object not set to reference exception.
I've tried the RunWorkerCompleted event, and the Load event of the form,
disabling the controls to show the form until they are raised, but it
seems those methods are unaware if the loading of the resources is fully
completed. Because the form shouldn't be visible yet I cannot use the
Activated or Shown events.
Dim bg As New ComponentModel.BackgroundWorker
AddHandler bg.DoWork, AddressOf rtfload
AddHandler bg.RunWorkerCompleted, AddressOf rtfloaded
bg.RunWorkerAsync()
Private Sub rtfload()
ed = New rtf()
End Sub
Public Sub rtfloaded()
Try
ed.Text = "" '<-- object not set to reference
Catch ex As Exception
rtfloaded()
Finally
tools.Enabled = True
End Try
End Sub
I use a BackgroundWorker to load a big form without halting the
functionailty of the main form, but when I try to show the subform too
early I get an Object not set to reference exception.
I've tried the RunWorkerCompleted event, and the Load event of the form,
disabling the controls to show the form until they are raised, but it
seems those methods are unaware if the loading of the resources is fully
completed. Because the form shouldn't be visible yet I cannot use the
Activated or Shown events.
Dim bg As New ComponentModel.BackgroundWorker
AddHandler bg.DoWork, AddressOf rtfload
AddHandler bg.RunWorkerCompleted, AddressOf rtfloaded
bg.RunWorkerAsync()
Private Sub rtfload()
ed = New rtf()
End Sub
Public Sub rtfloaded()
Try
ed.Text = "" '<-- object not set to reference
Catch ex As Exception
rtfloaded()
Finally
tools.Enabled = True
End Try
End Sub
Texture not renderer correctly in model
Texture not renderer correctly in model
I am new to OpenGl android. I load the Obj Model when I am filling texture
but texture is not filling completely on the object. It fill the texture
on some portion not on the complete model. I attached the two pictures in
which there is one model which is without the texture and another which is
with the texture but incomplete texture.
Please help me for this.
Thanks in advance.
package com.amplimesh.models;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
import java.util.ArrayList;
import java.util.StringTokenizer;
import javax.microedition.khronos.opengles.GL10;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.opengl.GLUtils;
import com.amplimesh.renderer.RendererView;
import com.amplimesh.util.Point3;
/**
* Object Loader and draw the texture and object.
* @author Ajay
*/
public class ObjModel {
/**
* It fill the texture into the mesh
* @param context
* @param gl
*/
public void bindTextures(Context context, GL10 gl) {
Bitmap bitmap;
try {
InputStream is =
context.getAssets().open("textures/"+RendererView.textureFileName);
bitmap = BitmapFactory.decodeStream(is);
if(bitmap != null) {
// generate one texture pointer
gl.glGenTextures(1, mTextures, 0);
// ...and bind it to our array
gl.glBindTexture(GL10.GL_TEXTURE_2D, mTextures[0]);
// create nearest filtered texture
gl.glTexParameterf(GL10.GL_TEXTURE_2D,
GL10.GL_TEXTURE_MIN_FILTER, GL10.GL_NEAREST);
gl.glTexParameterf(GL10.GL_TEXTURE_2D,
GL10.GL_TEXTURE_MAG_FILTER, GL10.GL_LINEAR);
//Different possible texture parameters, e.g.
GL10.GL_CLAMP_TO_EDGE
//gl.glTexParameterf(GL10.GL_TEXTURE_2D,
GL10.GL_TEXTURE_WRAP_S, GL10.GL_REPEAT);
//gl.glTexParameterf(GL10.GL_TEXTURE_2D,
GL10.GL_TEXTURE_WRAP_T, GL10.GL_REPEAT);
// Use Android GLUtils to specify a two-dimensional
texture image from our bitmap
GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, bitmap, 0);
// Clean up
bitmap.recycle();
}
} catch (java.io.IOException e) {
return;
}
}
/**
* It draw the object.
* @param gl
*/
public void draw(GL10 gl) {
gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
gl.glEnableClientState(GL10.GL_NORMAL_ARRAY);
for (Model model : mModels) {
gl.glVertexPointer(3, GL10.GL_FLOAT, 0, model.v);
if (model.vt != null && mTextures != null) {
gl.glBindTexture(GL10.GL_TEXTURE_2D, mTextures[0]);
gl.glTexCoordPointer(2, GL10.GL_FLOAT, 0, model.vt);
}
if (model.vn != null) {
gl.glNormalPointer(GL10.GL_FLOAT, 0, model.vn);
}
gl.glDrawArrays(GL10.GL_TRIANGLES, 0, model.v_size);
}
gl.glDisableClientState(GL10.GL_NORMAL_ARRAY);
gl.glDisableClientState(GL10.GL_VERTEX_ARRAY);
gl.glDisableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
}
/**
* It Load the object from stream.
* @param is
* @param texture_name
* @return
* @throws IOException
*/
public static ObjModel loadFromStream(InputStream is, String
texture_name) throws IOException {
ObjModel obj = ObjLoader.loadFromStream(is);
return obj;
}
private Model mModels[];
private int mTextures[] = new int[1];;
/**
* It read the the obj file.
* @author Ajay
*/
private static class ObjLoader {
public static ObjModel loadFromStream(InputStream is) throws
IOException {
BufferedReader reader = new BufferedReader(new
InputStreamReader(is));
ObjModel obj = new ObjModel();
ArrayList<Point3> v = new ArrayList<Point3>();
ArrayList<Point3> vt = new ArrayList<Point3>();
ArrayList<Point3> vn = new ArrayList<Point3>();
ArrayList<Face> f = new ArrayList<Face>();
ArrayList<Model> o = new ArrayList<Model>();
boolean o_pending=false;
while(reader.ready()) {
String line = reader.readLine();
if (line == null)
break;
StringTokenizer tok = new StringTokenizer(line);
String cmd = tok.nextToken();
if (cmd.equals("o")) {
if (o_pending) {
Model model = new Model();
model.fill(f, vt.size() > 0, vn.size() > 0);
o.add(model);
}
else {
o_pending=true;
}
}
else
if (cmd.equals("v")) {
v.add(read_point(tok));
}
else
if (cmd.equals("vn")) {
vn.add(read_point(tok));
}
else
if (cmd.equals("vt")) {
vt.add(read_point(tok));
}
else
if (cmd.equals("f")) {
if (tok.countTokens() != 3)
continue;
Face face = new Face(3);
while (tok.hasMoreTokens()) {
StringTokenizer face_tok = new
StringTokenizer(tok.nextToken(),
"/");
int v_idx = -1;
int vt_idx = -1;
int vn_idx = -1;
v_idx =
Integer.parseInt(face_tok.nextToken());
if (face_tok.hasMoreTokens())
vt_idx =
Integer.parseInt(face_tok.nextToken());
if (face_tok.hasMoreTokens())
vn_idx =
Integer.parseInt(face_tok.nextToken());
//Log.v("objmodel", "face:
"+v_idx+"/"+vt_idx+"/"+vn_idx);
face.addVertex(
v.get(v_idx-1),
vt_idx == -1 ? null :
vt.get(vt_idx-1),
vn_idx == -1 ?
null :
vn.get(vn_idx-1)
);
}
f.add(face);
}
}
if (o_pending) {
Model model = new Model();
model.fill(f, vt.size() > 0, vn.size() > 0);
o.add(model);
}
obj.mModels = new Model[o.size()];
o.toArray(obj.mModels);
return obj;
}
private static Point3 read_point(StringTokenizer tok) {
Point3 ret = new Point3();
if (tok.hasMoreTokens()) {
ret.x = Float.parseFloat(tok.nextToken());
if (tok.hasMoreTokens()) {
ret.y = Float.parseFloat(tok.nextToken());
if (tok.hasMoreTokens()) {
ret.z = Float.parseFloat(tok.nextToken());
}
}
}
return ret;
}
}
private static class Face {
Point3 v[];
Point3 vt[];
Point3 vn[];
int size;
int count;
public Face(int size) {
this.size = size;
this.count = 0;
this.v = new Point3[size];
this.vt = new Point3[size];
this.vn = new Point3[size];
}
public boolean addVertex(Point3 v, Point3 vt, Point3 vn) {
if (count >= size)
return false;
this.v[count] = v;
this.vt[count] = vt;
this.vn[count] = vn;
count++;
return true;
}
public void pushOnto(FloatBuffer v_buffer, FloatBuffer vt_buffer,
FloatBuffer vn_buffer) {
int i;
for (i=0; i<size; i++) {
v_buffer.put(v[i].x); v_buffer.put(v[i].y);
v_buffer.put(v[i].z);
if (vt_buffer != null && vt[i] != null) {
vt_buffer.put(vt[i].x); vt_buffer.put(vt[i].y);
}
if (vn_buffer != null && vn[i] != null) {
vn_buffer.put(vn[i].x); vn_buffer.put(vn[i].y);
vn_buffer.put(vn[i].z);
}
}
}
}
/**
* It hold the vertex buffer, vertex normal and texture.
* @author Ajay
*/
private static class Model {
public FloatBuffer v;
public FloatBuffer vt;
public FloatBuffer vn;
public int v_size;
public void fill(ArrayList<Face> faces, boolean has_tex, boolean
has_normals) {
int f_len = faces.size();
this.v_size = f_len * 3;
ByteBuffer tBuf = ByteBuffer.allocateDirect(this.v_size*3 * 4);
tBuf.order(ByteOrder.nativeOrder());
this.v = tBuf.asFloatBuffer();
if (has_tex) {
ByteBuffer vtBuf = ByteBuffer.allocateDirect(this.v_size*3
* 4);
vtBuf.order(ByteOrder.nativeOrder());
this.vt = vtBuf.asFloatBuffer();
}
if (has_normals) {
ByteBuffer vnBuf = ByteBuffer.allocateDirect(this.v_size*3
* 4);
vnBuf.order(ByteOrder.nativeOrder());
this.vn = vnBuf.asFloatBuffer();
}
int i;
for (i=0; i < f_len; i++) {
Face face = faces.get(i);
face.pushOnto(this.v, this.vt, this.vn);
}
this.v.rewind();
if (this.vt != null)
this.vt.rewind();
if (this.vn != null)
this.vn.rewind();
}
}
}
Render.java
public void start() {
mRenderer = new Renderer();
setEGLContextClientVersion(1);
setPreserveEGLContextOnPause(true);
setRenderer(mRenderer);
}
float mRotationFinal=-1f;
float mRotationDelta=0f;
int mRotationAxis=-1;
private class Renderer implements GLSurfaceView.Renderer {
public Renderer() {
setEGLConfigChooser(8, 8, 8, 8, 16, 0);
getHolder().setFormat(PixelFormat.TRANSLUCENT);
setZOrderOnTop(true);
}
public void onSurfaceCreated(GL10 gl, EGLConfig config) {
gl.glClearColor(0.0f,0.0f,0.0f, 0.0f);
gl.glEnable(GL10.GL_DEPTH_TEST);
gl.glDepthFunc(GL10.GL_LEQUAL);
gl.glHint(GL10.GL_PERSPECTIVE_CORRECTION_HINT, GL10.GL_NICEST);
gl.glEnable(GL10.GL_TEXTURE_2D);
gl.glShadeModel(GL10.GL_SMOOTH);
}
public void onSurfaceChanged(GL10 gl, int w, int h) {
mViewWidth = (float)w;
mViewHeight = (float)h;
gl.glViewport(0,0,w,h);
gl.glMatrixMode(GL10.GL_PROJECTION);
gl.glLoadIdentity();
GLU.gluPerspective(gl, 45, mViewWidth/mViewHeight, 0.1f, 100f);
gl.glMatrixMode(GL10.GL_MODELVIEW);
gl.glLoadIdentity();
}
public void onDrawFrame(GL10 gl) {
gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);
gl.glPushMatrix();
gl.glDisable(GL10.GL_DITHER);
GLU.gluLookAt(gl, 0, 0, 10, 0, 0, 0, 0, 1, 0);
//draw_model
gl.glPushMatrix();
if(mOrigin != null && mRotate != null) {
gl.glTranslatef(mOrigin.x, mOrigin.y, mOrigin.z);
gl.glRotatef(mRotate.x, 1f, 0f, 0f);
gl.glRotatef(mRotate.y, 0f, 1f, 0f);
gl.glRotatef(mRotate.z, 0f, 0f, 1f);
}
if(mModel != null) {
mModel.draw(gl);
if(!RendererView.textureFileName.equals(""))
mModel.bindTextures(mContext, gl);
}
gl.glPopMatrix();
gl.glPopMatrix();
if(isPictureTake) {
w = getWidth();
h = getHeight();
b = new int[w*(y+h)];
bt = new int[w*h];
IntBuffer ib = IntBuffer.wrap(b);
ib.position(0);
gl.glReadPixels(0, 0, w, h, GL10.GL_RGBA,
GL10.GL_UNSIGNED_BYTE, ib);
createBitmapFromGLSurface(context);
isPictureTake = false;
}
}
}
I am new to OpenGl android. I load the Obj Model when I am filling texture
but texture is not filling completely on the object. It fill the texture
on some portion not on the complete model. I attached the two pictures in
which there is one model which is without the texture and another which is
with the texture but incomplete texture.
Please help me for this.
Thanks in advance.
package com.amplimesh.models;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
import java.util.ArrayList;
import java.util.StringTokenizer;
import javax.microedition.khronos.opengles.GL10;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.opengl.GLUtils;
import com.amplimesh.renderer.RendererView;
import com.amplimesh.util.Point3;
/**
* Object Loader and draw the texture and object.
* @author Ajay
*/
public class ObjModel {
/**
* It fill the texture into the mesh
* @param context
* @param gl
*/
public void bindTextures(Context context, GL10 gl) {
Bitmap bitmap;
try {
InputStream is =
context.getAssets().open("textures/"+RendererView.textureFileName);
bitmap = BitmapFactory.decodeStream(is);
if(bitmap != null) {
// generate one texture pointer
gl.glGenTextures(1, mTextures, 0);
// ...and bind it to our array
gl.glBindTexture(GL10.GL_TEXTURE_2D, mTextures[0]);
// create nearest filtered texture
gl.glTexParameterf(GL10.GL_TEXTURE_2D,
GL10.GL_TEXTURE_MIN_FILTER, GL10.GL_NEAREST);
gl.glTexParameterf(GL10.GL_TEXTURE_2D,
GL10.GL_TEXTURE_MAG_FILTER, GL10.GL_LINEAR);
//Different possible texture parameters, e.g.
GL10.GL_CLAMP_TO_EDGE
//gl.glTexParameterf(GL10.GL_TEXTURE_2D,
GL10.GL_TEXTURE_WRAP_S, GL10.GL_REPEAT);
//gl.glTexParameterf(GL10.GL_TEXTURE_2D,
GL10.GL_TEXTURE_WRAP_T, GL10.GL_REPEAT);
// Use Android GLUtils to specify a two-dimensional
texture image from our bitmap
GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, bitmap, 0);
// Clean up
bitmap.recycle();
}
} catch (java.io.IOException e) {
return;
}
}
/**
* It draw the object.
* @param gl
*/
public void draw(GL10 gl) {
gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
gl.glEnableClientState(GL10.GL_NORMAL_ARRAY);
for (Model model : mModels) {
gl.glVertexPointer(3, GL10.GL_FLOAT, 0, model.v);
if (model.vt != null && mTextures != null) {
gl.glBindTexture(GL10.GL_TEXTURE_2D, mTextures[0]);
gl.glTexCoordPointer(2, GL10.GL_FLOAT, 0, model.vt);
}
if (model.vn != null) {
gl.glNormalPointer(GL10.GL_FLOAT, 0, model.vn);
}
gl.glDrawArrays(GL10.GL_TRIANGLES, 0, model.v_size);
}
gl.glDisableClientState(GL10.GL_NORMAL_ARRAY);
gl.glDisableClientState(GL10.GL_VERTEX_ARRAY);
gl.glDisableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
}
/**
* It Load the object from stream.
* @param is
* @param texture_name
* @return
* @throws IOException
*/
public static ObjModel loadFromStream(InputStream is, String
texture_name) throws IOException {
ObjModel obj = ObjLoader.loadFromStream(is);
return obj;
}
private Model mModels[];
private int mTextures[] = new int[1];;
/**
* It read the the obj file.
* @author Ajay
*/
private static class ObjLoader {
public static ObjModel loadFromStream(InputStream is) throws
IOException {
BufferedReader reader = new BufferedReader(new
InputStreamReader(is));
ObjModel obj = new ObjModel();
ArrayList<Point3> v = new ArrayList<Point3>();
ArrayList<Point3> vt = new ArrayList<Point3>();
ArrayList<Point3> vn = new ArrayList<Point3>();
ArrayList<Face> f = new ArrayList<Face>();
ArrayList<Model> o = new ArrayList<Model>();
boolean o_pending=false;
while(reader.ready()) {
String line = reader.readLine();
if (line == null)
break;
StringTokenizer tok = new StringTokenizer(line);
String cmd = tok.nextToken();
if (cmd.equals("o")) {
if (o_pending) {
Model model = new Model();
model.fill(f, vt.size() > 0, vn.size() > 0);
o.add(model);
}
else {
o_pending=true;
}
}
else
if (cmd.equals("v")) {
v.add(read_point(tok));
}
else
if (cmd.equals("vn")) {
vn.add(read_point(tok));
}
else
if (cmd.equals("vt")) {
vt.add(read_point(tok));
}
else
if (cmd.equals("f")) {
if (tok.countTokens() != 3)
continue;
Face face = new Face(3);
while (tok.hasMoreTokens()) {
StringTokenizer face_tok = new
StringTokenizer(tok.nextToken(),
"/");
int v_idx = -1;
int vt_idx = -1;
int vn_idx = -1;
v_idx =
Integer.parseInt(face_tok.nextToken());
if (face_tok.hasMoreTokens())
vt_idx =
Integer.parseInt(face_tok.nextToken());
if (face_tok.hasMoreTokens())
vn_idx =
Integer.parseInt(face_tok.nextToken());
//Log.v("objmodel", "face:
"+v_idx+"/"+vt_idx+"/"+vn_idx);
face.addVertex(
v.get(v_idx-1),
vt_idx == -1 ? null :
vt.get(vt_idx-1),
vn_idx == -1 ?
null :
vn.get(vn_idx-1)
);
}
f.add(face);
}
}
if (o_pending) {
Model model = new Model();
model.fill(f, vt.size() > 0, vn.size() > 0);
o.add(model);
}
obj.mModels = new Model[o.size()];
o.toArray(obj.mModels);
return obj;
}
private static Point3 read_point(StringTokenizer tok) {
Point3 ret = new Point3();
if (tok.hasMoreTokens()) {
ret.x = Float.parseFloat(tok.nextToken());
if (tok.hasMoreTokens()) {
ret.y = Float.parseFloat(tok.nextToken());
if (tok.hasMoreTokens()) {
ret.z = Float.parseFloat(tok.nextToken());
}
}
}
return ret;
}
}
private static class Face {
Point3 v[];
Point3 vt[];
Point3 vn[];
int size;
int count;
public Face(int size) {
this.size = size;
this.count = 0;
this.v = new Point3[size];
this.vt = new Point3[size];
this.vn = new Point3[size];
}
public boolean addVertex(Point3 v, Point3 vt, Point3 vn) {
if (count >= size)
return false;
this.v[count] = v;
this.vt[count] = vt;
this.vn[count] = vn;
count++;
return true;
}
public void pushOnto(FloatBuffer v_buffer, FloatBuffer vt_buffer,
FloatBuffer vn_buffer) {
int i;
for (i=0; i<size; i++) {
v_buffer.put(v[i].x); v_buffer.put(v[i].y);
v_buffer.put(v[i].z);
if (vt_buffer != null && vt[i] != null) {
vt_buffer.put(vt[i].x); vt_buffer.put(vt[i].y);
}
if (vn_buffer != null && vn[i] != null) {
vn_buffer.put(vn[i].x); vn_buffer.put(vn[i].y);
vn_buffer.put(vn[i].z);
}
}
}
}
/**
* It hold the vertex buffer, vertex normal and texture.
* @author Ajay
*/
private static class Model {
public FloatBuffer v;
public FloatBuffer vt;
public FloatBuffer vn;
public int v_size;
public void fill(ArrayList<Face> faces, boolean has_tex, boolean
has_normals) {
int f_len = faces.size();
this.v_size = f_len * 3;
ByteBuffer tBuf = ByteBuffer.allocateDirect(this.v_size*3 * 4);
tBuf.order(ByteOrder.nativeOrder());
this.v = tBuf.asFloatBuffer();
if (has_tex) {
ByteBuffer vtBuf = ByteBuffer.allocateDirect(this.v_size*3
* 4);
vtBuf.order(ByteOrder.nativeOrder());
this.vt = vtBuf.asFloatBuffer();
}
if (has_normals) {
ByteBuffer vnBuf = ByteBuffer.allocateDirect(this.v_size*3
* 4);
vnBuf.order(ByteOrder.nativeOrder());
this.vn = vnBuf.asFloatBuffer();
}
int i;
for (i=0; i < f_len; i++) {
Face face = faces.get(i);
face.pushOnto(this.v, this.vt, this.vn);
}
this.v.rewind();
if (this.vt != null)
this.vt.rewind();
if (this.vn != null)
this.vn.rewind();
}
}
}
Render.java
public void start() {
mRenderer = new Renderer();
setEGLContextClientVersion(1);
setPreserveEGLContextOnPause(true);
setRenderer(mRenderer);
}
float mRotationFinal=-1f;
float mRotationDelta=0f;
int mRotationAxis=-1;
private class Renderer implements GLSurfaceView.Renderer {
public Renderer() {
setEGLConfigChooser(8, 8, 8, 8, 16, 0);
getHolder().setFormat(PixelFormat.TRANSLUCENT);
setZOrderOnTop(true);
}
public void onSurfaceCreated(GL10 gl, EGLConfig config) {
gl.glClearColor(0.0f,0.0f,0.0f, 0.0f);
gl.glEnable(GL10.GL_DEPTH_TEST);
gl.glDepthFunc(GL10.GL_LEQUAL);
gl.glHint(GL10.GL_PERSPECTIVE_CORRECTION_HINT, GL10.GL_NICEST);
gl.glEnable(GL10.GL_TEXTURE_2D);
gl.glShadeModel(GL10.GL_SMOOTH);
}
public void onSurfaceChanged(GL10 gl, int w, int h) {
mViewWidth = (float)w;
mViewHeight = (float)h;
gl.glViewport(0,0,w,h);
gl.glMatrixMode(GL10.GL_PROJECTION);
gl.glLoadIdentity();
GLU.gluPerspective(gl, 45, mViewWidth/mViewHeight, 0.1f, 100f);
gl.glMatrixMode(GL10.GL_MODELVIEW);
gl.glLoadIdentity();
}
public void onDrawFrame(GL10 gl) {
gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);
gl.glPushMatrix();
gl.glDisable(GL10.GL_DITHER);
GLU.gluLookAt(gl, 0, 0, 10, 0, 0, 0, 0, 1, 0);
//draw_model
gl.glPushMatrix();
if(mOrigin != null && mRotate != null) {
gl.glTranslatef(mOrigin.x, mOrigin.y, mOrigin.z);
gl.glRotatef(mRotate.x, 1f, 0f, 0f);
gl.glRotatef(mRotate.y, 0f, 1f, 0f);
gl.glRotatef(mRotate.z, 0f, 0f, 1f);
}
if(mModel != null) {
mModel.draw(gl);
if(!RendererView.textureFileName.equals(""))
mModel.bindTextures(mContext, gl);
}
gl.glPopMatrix();
gl.glPopMatrix();
if(isPictureTake) {
w = getWidth();
h = getHeight();
b = new int[w*(y+h)];
bt = new int[w*h];
IntBuffer ib = IntBuffer.wrap(b);
ib.position(0);
gl.glReadPixels(0, 0, w, h, GL10.GL_RGBA,
GL10.GL_UNSIGNED_BYTE, ib);
createBitmapFromGLSurface(context);
isPictureTake = false;
}
}
}
Tuesday, 27 August 2013
Submit button not respond for action
Submit button not respond for action
I have an odd problem !! my submit button not respond for action !!!
I have this code:
<script type="text/javascript">
function save_contact_information() {
document.getElementById('User_Finder').action =
"Controler/controller_page.php?button=save_contact_information";
}
</script>
<form id="User_Finder" action="User_Finder.php?ID_CV_User=<?php print
$ID_CV_User ?>&&change_profile=ok"
method="post" enctype="multipart/form-data">
<input type="submit" id="CI_BT_Save" onclick="save_contact_information()"
name="BT_PI_Save" value="Save"
style="position:absolute;left:12px;top:333px;width:96px;height:25px;z-index:342;">
</form>
if I click on the button save , nothing will be change !!! I change the
code of the function 'save_contact_information()' as bellow:
function save_contact_information() {
alert("ok1");
document.getElementById('User_Finder').action =
"Controler/controller_page.php?button=save_contact_information";
alert("ok2");
}
Now if I Click on button save , 2 alerts will be visible : ok1 + ok2 but
this line : document.getElementById('User_Finder').action
="Controler/controller_page.php?button=save_contact_information"; not
given any reaction !!!
Have anyone any idea about this ODD problem !!!
I have an odd problem !! my submit button not respond for action !!!
I have this code:
<script type="text/javascript">
function save_contact_information() {
document.getElementById('User_Finder').action =
"Controler/controller_page.php?button=save_contact_information";
}
</script>
<form id="User_Finder" action="User_Finder.php?ID_CV_User=<?php print
$ID_CV_User ?>&&change_profile=ok"
method="post" enctype="multipart/form-data">
<input type="submit" id="CI_BT_Save" onclick="save_contact_information()"
name="BT_PI_Save" value="Save"
style="position:absolute;left:12px;top:333px;width:96px;height:25px;z-index:342;">
</form>
if I click on the button save , nothing will be change !!! I change the
code of the function 'save_contact_information()' as bellow:
function save_contact_information() {
alert("ok1");
document.getElementById('User_Finder').action =
"Controler/controller_page.php?button=save_contact_information";
alert("ok2");
}
Now if I Click on button save , 2 alerts will be visible : ok1 + ok2 but
this line : document.getElementById('User_Finder').action
="Controler/controller_page.php?button=save_contact_information"; not
given any reaction !!!
Have anyone any idea about this ODD problem !!!
Change text color for QML controls
Change text color for QML controls
I am using some QML controls like GroupBox and CheckBox which have text
associated with them. The default color of the text is black. However, I
have these items on a dark background and would prefer using white for the
text color. These items don't have a color property so I'm not sure what
to do.
CheckBox {
text: "Check Me"
}
Thanks in advanced!
I am using some QML controls like GroupBox and CheckBox which have text
associated with them. The default color of the text is black. However, I
have these items on a dark background and would prefer using white for the
text color. These items don't have a color property so I'm not sure what
to do.
CheckBox {
text: "Check Me"
}
Thanks in advanced!
Character swapping
Character swapping
I'm trying to swap the first and last character in a string so what I did
was I was able to retrieve its first and last characters but am now having
hard times putting them all together:
String name="pera";
char[] c = name.toCharArray();
char first = c[0];
char last = c[c.length-1];
name.replace(first, last);
name.replace(last, first);
System.out.println(name);
Although I am getting for the variable 'first' the value of "p" and for
the variable 'last' the value of "a", these methods replace() are not
turning up with a valid result as the name stays as it is. Does anyone
have any idea on how to finish this?
I'm trying to swap the first and last character in a string so what I did
was I was able to retrieve its first and last characters but am now having
hard times putting them all together:
String name="pera";
char[] c = name.toCharArray();
char first = c[0];
char last = c[c.length-1];
name.replace(first, last);
name.replace(last, first);
System.out.println(name);
Although I am getting for the variable 'first' the value of "p" and for
the variable 'last' the value of "a", these methods replace() are not
turning up with a valid result as the name stays as it is. Does anyone
have any idea on how to finish this?
while passing bigger date differnce getting erro in sql
while passing bigger date differnce getting erro in sql
I have stored procedure like this on my DB:
ALTER procedure [dbo].[performance]
(@startdate nvarchar(100), @enddate nvarchar(100)
as begin
declare @date1 nvarchar(100) = convert(varchar, @startdate+'
00:00:00.000', 120)
declare @date2 nvarchar(100) = convert(varchar, @enddate+'
23:59:59.000', 120)
set NOCOUNT on;
select l.LocName,v.Vtype, SUM(DATEDIFF(MI,t.Paydate,t.DelDate)) as
TotalDiff,
[dbo].[testfunction](
CONVERT(decimal(10,1), AVG( CONVERT(NUMERIC(18,2),
DATEDIFF(SS,t.Paydate,t.DelDate) ) ))) as Average
from Transaction_tbl t
left join VType_tbl v
on t.vtid=v.vtid
left join Location_tbl l
on t.Locid=l.Locid
where t.Locid in
(select t1.Locid from Transaction_tbl t1)
and dtime between '' + @date1 +'' and ''+ @date2 +''
and Status =5
group by v.Vtype,l.LocName,l.Locid order by l.Locid
end
my testfunction ike this:
ALTER FUNCTION [dbo].[testfunction] (@dec NUMERIC(18, 2)) RETURNS Varchar(50)
AS
BEGIN
DECLARE
@hour integer,
@Mns integer,
@second decimal(18,3)
DECLARE @Average Varchar(50)
select @hour=CONVERT(int,@dec/60/60)
SELECT @Mns = convert(int, (@dec / 60) - (@hour * 60 ));
select @second=@dec % 60;
SELECT @Average =
convert(varchar(9), convert(int, @hour)) + ':' +
right('00' + convert(varchar(2), convert(int, @Mns)), 2) + ':' +
right('00' + CONVERT(decimal(10,0), convert(varchar(6), @second)), 6)
RETURN @Average
END
if i pass start date:2013-06-01 and end date:2013-08-01 then getting
proper out put if i pass start date:2010-06-01 and end date:2013-08-01
(bigger date difference) then getting error:
Arithmetic overflow error converting numeric to data type varchar.
i know having some problem with my function.but i am not able find out
what is the issue with my function.if any one please help me to find out
I have stored procedure like this on my DB:
ALTER procedure [dbo].[performance]
(@startdate nvarchar(100), @enddate nvarchar(100)
as begin
declare @date1 nvarchar(100) = convert(varchar, @startdate+'
00:00:00.000', 120)
declare @date2 nvarchar(100) = convert(varchar, @enddate+'
23:59:59.000', 120)
set NOCOUNT on;
select l.LocName,v.Vtype, SUM(DATEDIFF(MI,t.Paydate,t.DelDate)) as
TotalDiff,
[dbo].[testfunction](
CONVERT(decimal(10,1), AVG( CONVERT(NUMERIC(18,2),
DATEDIFF(SS,t.Paydate,t.DelDate) ) ))) as Average
from Transaction_tbl t
left join VType_tbl v
on t.vtid=v.vtid
left join Location_tbl l
on t.Locid=l.Locid
where t.Locid in
(select t1.Locid from Transaction_tbl t1)
and dtime between '' + @date1 +'' and ''+ @date2 +''
and Status =5
group by v.Vtype,l.LocName,l.Locid order by l.Locid
end
my testfunction ike this:
ALTER FUNCTION [dbo].[testfunction] (@dec NUMERIC(18, 2)) RETURNS Varchar(50)
AS
BEGIN
DECLARE
@hour integer,
@Mns integer,
@second decimal(18,3)
DECLARE @Average Varchar(50)
select @hour=CONVERT(int,@dec/60/60)
SELECT @Mns = convert(int, (@dec / 60) - (@hour * 60 ));
select @second=@dec % 60;
SELECT @Average =
convert(varchar(9), convert(int, @hour)) + ':' +
right('00' + convert(varchar(2), convert(int, @Mns)), 2) + ':' +
right('00' + CONVERT(decimal(10,0), convert(varchar(6), @second)), 6)
RETURN @Average
END
if i pass start date:2013-06-01 and end date:2013-08-01 then getting
proper out put if i pass start date:2010-06-01 and end date:2013-08-01
(bigger date difference) then getting error:
Arithmetic overflow error converting numeric to data type varchar.
i know having some problem with my function.but i am not able find out
what is the issue with my function.if any one please help me to find out
When working with associations in Ruby if the user does not have an event the events method throws and undefined error
When working with associations in Ruby if the user does not have an event
the events method throws and undefined error
I'm building a Rails app where a User has many Events.
If a user has an event and I do current_user.events.each then all is fine
although if the user doesn't have any event an undefined method error is
thrown and the entire applications stops working.
As a PHP user I would first check if the variable was set before doing the
loop. Does Rails have a nifty way of either initiating the method in the
model regardless or should I still check?
the events method throws and undefined error
I'm building a Rails app where a User has many Events.
If a user has an event and I do current_user.events.each then all is fine
although if the user doesn't have any event an undefined method error is
thrown and the entire applications stops working.
As a PHP user I would first check if the variable was set before doing the
loop. Does Rails have a nifty way of either initiating the method in the
model regardless or should I still check?
cpanel module for copying directories
cpanel module for copying directories
I am trying to develop some server tools and since I have a cpanel account
(but no shell access), I was wondering if I can do them as modules to that
account.
The concept is to create an automated install (copy from a specific
folder, and replace some variables in a config file) of a wordpress along
with some plugins that I have developed.
Is it achievable from a cpanel account? What are the requirements? Where
can I start with some examples?
I am trying to develop some server tools and since I have a cpanel account
(but no shell access), I was wondering if I can do them as modules to that
account.
The concept is to create an automated install (copy from a specific
folder, and replace some variables in a config file) of a wordpress along
with some plugins that I have developed.
Is it achievable from a cpanel account? What are the requirements? Where
can I start with some examples?
Monday, 26 August 2013
UITextView becomes FirstResponder twice, then not thereafter
UITextView becomes FirstResponder twice, then not thereafter
I use this code snippet to resign first responder
- (BOOL)textView:(UITextView *)textView
shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
if([text isEqualToString:@"\n"]) {
[textView resignFirstResponder];
return NO;
}
return YES;
}
I have the textView in a tableView cell. The problem I'm having is I can
tap the textview and edit the field only twice, after that the textview
doesn't respond to a touch anymore.
I use this code snippet to resign first responder
- (BOOL)textView:(UITextView *)textView
shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
if([text isEqualToString:@"\n"]) {
[textView resignFirstResponder];
return NO;
}
return YES;
}
I have the textView in a tableView cell. The problem I'm having is I can
tap the textview and edit the field only twice, after that the textview
doesn't respond to a touch anymore.
using parent constructor not working
using parent constructor not working
I am trying to inherit std::ostream_iterator, so I do:
template< class T,
class CharT = char,
class Traits = std::char_traits<CharT>>
class ostream_iterator : public std::ostream_iterator<T, CharT, Traits> {
using std::ostream_iterator<T, CharT, Traits>::ostream_iterator;
};
I try to inherit the constructors too (by C++11) but it still gives me error:
error: 'std::ostream_iterator<T, CharT, Traits>::ostream_iterator' names
constructor
How can I use using constructor properly? I search the internet but the
answer is exactly the same as above.
I am trying to inherit std::ostream_iterator, so I do:
template< class T,
class CharT = char,
class Traits = std::char_traits<CharT>>
class ostream_iterator : public std::ostream_iterator<T, CharT, Traits> {
using std::ostream_iterator<T, CharT, Traits>::ostream_iterator;
};
I try to inherit the constructors too (by C++11) but it still gives me error:
error: 'std::ostream_iterator<T, CharT, Traits>::ostream_iterator' names
constructor
How can I use using constructor properly? I search the internet but the
answer is exactly the same as above.
/boot 100% and can't purge
/boot 100% and can't purge
running Ubuntu 12.04 LS and it tells me that it can't complete install on
linux-image-3.5.39 because of dependencies. running 'apt-get -f install'
doesn't do anything. How can I remove anything from "/boot" . It doesn't
let me install anything, so I got to work with the packages I got.
uname -r --> linux 28.
suggestions are very much appreaciated
installArchives() failed: (Reading database ...
(Reading database ... 5%
(Reading database ... 10%
(Reading database ... 15%
(Reading database ... 20%
(Reading database ... 25%
(Reading database ... 30%
(Reading database ... 35%
(Reading database ... 40%
(Reading database ... 45%
(Reading database ... 50%
(Reading database ... 55%
(Reading database ... 60%
(Reading database ... 65%
(Reading database ... 70%
(Reading database ... 75%
(Reading database ... 80%
(Reading database ... 85%
(Reading database ... 90%
(Reading database ... 95%
(Reading database ... 100%
(Reading database ... 291331 files and directories currently installed.)
Unpacking linux-image-3.5.0-39-generic (from
.../linux-image-3.5.0-39-generic_3.5.0-39.60~precise1_amd64.deb) ...
Done.
dpkg: error processing
/var/cache/apt/archives/linux-image-3.5.0-39-generic_3.5.0-39.60~precise1_amd64.deb
(--unpack):
failed in write on buffer copy for backend dpkg-deb during
`./boot/vmlinuz-3.5.0-39-generic': No space left on device
No apport report written because the error message indicates a disk full
error
dpkg-deb: error: subprocess paste was killed by signal (Broken pipe)
Examining /etc/kernel/postrm.d .
run-parts: executing /etc/kernel/postrm.d/initramfs-tools 3.5.0-39-generic
/boot/vmlinuz-3.5.0-39-generic
run-parts: executing /etc/kernel/postrm.d/zz-update-grub 3.5.0-39-generic
/boot/vmlinuz-3.5.0-39-generic
Errors were encountered while processing:
/var/cache/apt/archives/linux-image-3.5.0-39-generic_3.5.0-39.60~precise1_amd64.deb
Error in function:
SystemError: E:Sub-process /usr/bin/dpkg returned an error code (1)
Setting up initramfs-tools (0.99ubuntu13.1) ...
update-initramfs: deferring update (trigger activated)
dpkg: dependency problems prevent configuration of
linux-image-generic-lts-quantal:
linux-image-generic-lts-quantal depends on linux-image-3.5.0-39-generic;
however:
Package linux-image-3.5.0-39-generic is not installed.
dpkg: error processing linux-image-generic-lts-quantal (--configure):
dependency problems - leaving unconfigured
dpkg: dependency problems prevent configuration of linux-generic-lts-quantal:
linux-generic-lts-quantal depends on linux-image-generic-lts-quantal;
however:
Package linux-image-generic-lts-quantal is not configured yet.
dpkg: error processing linux-generic-lts-quantal (--configure):
dependency problems - leaving unconfigured
Processing triggers for initramfs-tools ...
update-initramfs: Generating /boot/initrd.img-3.5.0-37-generic
gzip: stdout: No space left on device
cpio: write error: Broken pipe
E: mkinitramfs failure cpio 1 gzip 1
update-initramfs: failed for /boot/initrd.img-3.5.0-37-generic with 1.
dpkg: error processing initramfs-tools (--configure):
subprocess installed post-installation script returned error exit status 1
Errors were encountered while processing:
linux-image-generic-lts-quantal
linux-generic-lts-quantal
initramfs-tools
running Ubuntu 12.04 LS and it tells me that it can't complete install on
linux-image-3.5.39 because of dependencies. running 'apt-get -f install'
doesn't do anything. How can I remove anything from "/boot" . It doesn't
let me install anything, so I got to work with the packages I got.
uname -r --> linux 28.
suggestions are very much appreaciated
installArchives() failed: (Reading database ...
(Reading database ... 5%
(Reading database ... 10%
(Reading database ... 15%
(Reading database ... 20%
(Reading database ... 25%
(Reading database ... 30%
(Reading database ... 35%
(Reading database ... 40%
(Reading database ... 45%
(Reading database ... 50%
(Reading database ... 55%
(Reading database ... 60%
(Reading database ... 65%
(Reading database ... 70%
(Reading database ... 75%
(Reading database ... 80%
(Reading database ... 85%
(Reading database ... 90%
(Reading database ... 95%
(Reading database ... 100%
(Reading database ... 291331 files and directories currently installed.)
Unpacking linux-image-3.5.0-39-generic (from
.../linux-image-3.5.0-39-generic_3.5.0-39.60~precise1_amd64.deb) ...
Done.
dpkg: error processing
/var/cache/apt/archives/linux-image-3.5.0-39-generic_3.5.0-39.60~precise1_amd64.deb
(--unpack):
failed in write on buffer copy for backend dpkg-deb during
`./boot/vmlinuz-3.5.0-39-generic': No space left on device
No apport report written because the error message indicates a disk full
error
dpkg-deb: error: subprocess paste was killed by signal (Broken pipe)
Examining /etc/kernel/postrm.d .
run-parts: executing /etc/kernel/postrm.d/initramfs-tools 3.5.0-39-generic
/boot/vmlinuz-3.5.0-39-generic
run-parts: executing /etc/kernel/postrm.d/zz-update-grub 3.5.0-39-generic
/boot/vmlinuz-3.5.0-39-generic
Errors were encountered while processing:
/var/cache/apt/archives/linux-image-3.5.0-39-generic_3.5.0-39.60~precise1_amd64.deb
Error in function:
SystemError: E:Sub-process /usr/bin/dpkg returned an error code (1)
Setting up initramfs-tools (0.99ubuntu13.1) ...
update-initramfs: deferring update (trigger activated)
dpkg: dependency problems prevent configuration of
linux-image-generic-lts-quantal:
linux-image-generic-lts-quantal depends on linux-image-3.5.0-39-generic;
however:
Package linux-image-3.5.0-39-generic is not installed.
dpkg: error processing linux-image-generic-lts-quantal (--configure):
dependency problems - leaving unconfigured
dpkg: dependency problems prevent configuration of linux-generic-lts-quantal:
linux-generic-lts-quantal depends on linux-image-generic-lts-quantal;
however:
Package linux-image-generic-lts-quantal is not configured yet.
dpkg: error processing linux-generic-lts-quantal (--configure):
dependency problems - leaving unconfigured
Processing triggers for initramfs-tools ...
update-initramfs: Generating /boot/initrd.img-3.5.0-37-generic
gzip: stdout: No space left on device
cpio: write error: Broken pipe
E: mkinitramfs failure cpio 1 gzip 1
update-initramfs: failed for /boot/initrd.img-3.5.0-37-generic with 1.
dpkg: error processing initramfs-tools (--configure):
subprocess installed post-installation script returned error exit status 1
Errors were encountered while processing:
linux-image-generic-lts-quantal
linux-generic-lts-quantal
initramfs-tools
Why was this answer of mine deleted=?iso-8859-1?Q?=3F_=96_meta.stackoverflow.com?=
Why was this answer of mine deleted? – meta.stackoverflow.com
I would like to know the reason why this answer was deleted. Here is the
full content of the answer: Try http://www.emacswiki.org/emacs/msearch.el
All occurences of the text selected with the …
I would like to know the reason why this answer was deleted. Here is the
full content of the answer: Try http://www.emacswiki.org/emacs/msearch.el
All occurences of the text selected with the …
after dowloading OS how to do img file and bootable cd/dvd using nero essential
after dowloading OS how to do img file and bootable cd/dvd using nero
essential
I have window 8 OS in my system, now i have to make that into boo-table
DVD please help me through Nero essential (Nero 9)
essential
I have window 8 OS in my system, now i have to make that into boo-table
DVD please help me through Nero essential (Nero 9)
Sunday, 25 August 2013
PHP Curl followlocation working from command line but not from browser
PHP Curl followlocation working from command line but not from browser
I have written a small script to scrape some data from a website using
cUrl in PHP. When curl is executed, there is a 301-redirect issued by the
site which is taken care of by :
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
However, when I run the same code from my browser, the redirect is NOT
working. Here is the complete curl request:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $arr_params['url']);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 5.01;
Windows NT 5.0)");
curl_setopt($ch, CURLOPT_VERBOSE, true);
curl_setopt($ch, CURLOPT_STDERR, $arr_params['error_file']);
//curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
In the above code, $arr_params is set previously....
I have written a small script to scrape some data from a website using
cUrl in PHP. When curl is executed, there is a 301-redirect issued by the
site which is taken care of by :
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
However, when I run the same code from my browser, the redirect is NOT
working. Here is the complete curl request:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $arr_params['url']);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 5.01;
Windows NT 5.0)");
curl_setopt($ch, CURLOPT_VERBOSE, true);
curl_setopt($ch, CURLOPT_STDERR, $arr_params['error_file']);
//curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
In the above code, $arr_params is set previously....
[ Singles & Dating ] Open Question : why does he want to have ''self control'' around me?
[ Singles & Dating ] Open Question : why does he want to have ''self
control'' around me?
Why does he want to have ''self control'' around me? my bf and I are 18
and I dont want to have sex before marriage and I know he wants to do it
with me, now.. We making out and he put his hand under my top and felt my
back/breasts and stomach and then i lifted his shirt a bit then he put his
stomach against my stomach and continued kissing me.. It got really
intimate and the next day I felt bad because it could have gone to another
level.. at this party we both were going to, I said that we have to behave
ourselves and tone down the lust and he genuinely agreed and that we need
to slow down (even though he wants it..?) and I know this is a good thing
for me as it's what i want but at the party he followed through with his
words and whenever we started kissing, he pulled away and was like
''...self control...'' then the following day he said to me via text:
him-- 'i dont think we should kiss like that again because... you know..
we should tone it right down. me-- you mean just in front of people or
even when it's just us 2? him-- hmm, both but definitely when it's in
front of others. me-- okay, why? :) him-- just like you said, we're
getting too too lustful.. it's not like we won't ever do it again ;)
because i enjoy it. me-- how's self control these days? you seem to be
getting better him-- it's still difficult because you know I want to...
but you're training me well. ;) Was he being a gentleman? i dont think
he's embarrassed or anything of me cause whenever im there in front of him
and his friends, they always are like ''god -- you're lucky to have her''
(physically)
control'' around me?
Why does he want to have ''self control'' around me? my bf and I are 18
and I dont want to have sex before marriage and I know he wants to do it
with me, now.. We making out and he put his hand under my top and felt my
back/breasts and stomach and then i lifted his shirt a bit then he put his
stomach against my stomach and continued kissing me.. It got really
intimate and the next day I felt bad because it could have gone to another
level.. at this party we both were going to, I said that we have to behave
ourselves and tone down the lust and he genuinely agreed and that we need
to slow down (even though he wants it..?) and I know this is a good thing
for me as it's what i want but at the party he followed through with his
words and whenever we started kissing, he pulled away and was like
''...self control...'' then the following day he said to me via text:
him-- 'i dont think we should kiss like that again because... you know..
we should tone it right down. me-- you mean just in front of people or
even when it's just us 2? him-- hmm, both but definitely when it's in
front of others. me-- okay, why? :) him-- just like you said, we're
getting too too lustful.. it's not like we won't ever do it again ;)
because i enjoy it. me-- how's self control these days? you seem to be
getting better him-- it's still difficult because you know I want to...
but you're training me well. ;) Was he being a gentleman? i dont think
he's embarrassed or anything of me cause whenever im there in front of him
and his friends, they always are like ''god -- you're lucky to have her''
(physically)
why can't identifiers in java begin with a digit?
why can't identifiers in java begin with a digit?
I am a learner in java and it has been two months since I started learning
Java. I was wondering why identifiers beginning with a digit are
considered illegal by the compiler?
I am a learner in java and it has been two months since I started learning
Java. I was wondering why identifiers beginning with a digit are
considered illegal by the compiler?
Saturday, 24 August 2013
How to maximize I/O on an OpenVZ VPS node? [on hold]
How to maximize I/O on an OpenVZ VPS node? [on hold]
I have an OVZ node with 46 VPSes. The SSD drive had 400Mb/s but after
filling the node with VPSes the SSD drive sometimes drops to 40Mb/s. How
can I prevent this from happening? Is there a way to find and suspend
users who have abused their IO?
I have an OVZ node with 46 VPSes. The SSD drive had 400Mb/s but after
filling the node with VPSes the SSD drive sometimes drops to 40Mb/s. How
can I prevent this from happening? Is there a way to find and suspend
users who have abused their IO?
php if sql query returns valid result
php if sql query returns valid result
I'm sure this is a simple fix, I want to run a code block if an sql query
comes back with a positive result. something like:
if($query = mysqli_query($cxn,"[query]"))
{
Code to be executed if the query returns a positive result
}
I have tried this format but doesn't work. I'm sure I have done this
before but I'm running in to a wall here.
Hope you can help.
I'm sure this is a simple fix, I want to run a code block if an sql query
comes back with a positive result. something like:
if($query = mysqli_query($cxn,"[query]"))
{
Code to be executed if the query returns a positive result
}
I have tried this format but doesn't work. I'm sure I have done this
before but I'm running in to a wall here.
Hope you can help.
Why is Doctrine not managing my entity properly?
Why is Doctrine not managing my entity properly?
I have implemented Doctrine 2 in Codeigniter and I'm facing a problem here:
I've run this command to generate my entity from my db :
php doctrine orm:convert-mapping annotation ./models/Entity
--namespace="Entity" --from-database
It has created my entity properly :
<?php
namespace Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Keys
*
* @ORM\Table(name="keys")
* @ORM\Entity
*/
class Keys
{
/**
* @var integer
*
* @ORM\Column(name="id", type="integer", nullable=false)
* @ORM\Id
* @ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* @var string
*
* @ORM\Column(name="key", type="string", length=40, nullable=false)
*/
private $key;
/**
* @var integer
*
* @ORM\Column(name="level", type="integer", nullable=false)
*/
private $level;
/**
* @var boolean
*
* @ORM\Column(name="ignore_limits", type="boolean", nullable=false)
*/
private $ignoreLimits;
/**
* @var boolean
*
* @ORM\Column(name="is_private_key", type="boolean", nullable=false)
*/
private $isPrivateKey;
/**
* @var string
*
* @ORM\Column(name="ip_addresses", type="text", nullable=true)
*/
private $ipAddresses;
/**
* @var integer
*
* @ORM\Column(name="date_created", type="integer", nullable=false)
*/
private $dateCreated;
}
Therefore, when trying to generate proxies and getters and setters, it
doesn't generate antyhing for this entity (but it does generate it for my
other entities) Why ? What am I missing ?
Thanks
I have implemented Doctrine 2 in Codeigniter and I'm facing a problem here:
I've run this command to generate my entity from my db :
php doctrine orm:convert-mapping annotation ./models/Entity
--namespace="Entity" --from-database
It has created my entity properly :
<?php
namespace Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Keys
*
* @ORM\Table(name="keys")
* @ORM\Entity
*/
class Keys
{
/**
* @var integer
*
* @ORM\Column(name="id", type="integer", nullable=false)
* @ORM\Id
* @ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* @var string
*
* @ORM\Column(name="key", type="string", length=40, nullable=false)
*/
private $key;
/**
* @var integer
*
* @ORM\Column(name="level", type="integer", nullable=false)
*/
private $level;
/**
* @var boolean
*
* @ORM\Column(name="ignore_limits", type="boolean", nullable=false)
*/
private $ignoreLimits;
/**
* @var boolean
*
* @ORM\Column(name="is_private_key", type="boolean", nullable=false)
*/
private $isPrivateKey;
/**
* @var string
*
* @ORM\Column(name="ip_addresses", type="text", nullable=true)
*/
private $ipAddresses;
/**
* @var integer
*
* @ORM\Column(name="date_created", type="integer", nullable=false)
*/
private $dateCreated;
}
Therefore, when trying to generate proxies and getters and setters, it
doesn't generate antyhing for this entity (but it does generate it for my
other entities) Why ? What am I missing ?
Thanks
Autohosted SharePoint Online App - Azure account needed? Deployment? Provisioning access?
Autohosted SharePoint Online App - Azure account needed? Deployment?
Provisioning access?
I developed/deployed a very simple autohosted app to SharePoint Online
2013 but has a URL that looks like this. Don't click on this link.
https://1e9a4afa-c77b-460e-3375a-8eded45c2200.o365apps.net/Pages/Default.aspx?SPHostUrl=https%3A%2F%2Fwhatever%2Esharepoint%2Ecom%2Fsites%2Fdev&SPLanguage=en%2DUS&SPClientTag=2&SPProductNumber=16%2E0%2E1922%2E1221
Confused..
It never asked me for Azure account information, will I need one if I plan
to run c# code?
How do I deploy this app to other site collections on SPO 2013 o365 and
provision who in SPO can use it?
Provisioning access?
I developed/deployed a very simple autohosted app to SharePoint Online
2013 but has a URL that looks like this. Don't click on this link.
https://1e9a4afa-c77b-460e-3375a-8eded45c2200.o365apps.net/Pages/Default.aspx?SPHostUrl=https%3A%2F%2Fwhatever%2Esharepoint%2Ecom%2Fsites%2Fdev&SPLanguage=en%2DUS&SPClientTag=2&SPProductNumber=16%2E0%2E1922%2E1221
Confused..
It never asked me for Azure account information, will I need one if I plan
to run c# code?
How do I deploy this app to other site collections on SPO 2013 o365 and
provision who in SPO can use it?
Generating keyPressEvent in a code generated by pyQT Designer
Generating keyPressEvent in a code generated by pyQT Designer
I Created a code using pyQt Designer in ui and changed it to py code.
Now i want to add some Keypress events to my this i.e. say if i click on
keyboard key with numeric 3 , my label should have text 3 on it or it just
print "Hi"
I have already checked a lot of forums over internet and found that its
best to reimplement keyPressEvent to use keyboard events . I tried that
however somehow i am not able to make it work in the code generated by
pyQT designer .
Below is the code generated by pyQT designer . I have put the code of
keyPressEvent re implementation in it as well , however it dosent work :
try:
_encoding = QtGui.QApplication.UnicodeUTF8
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig,
_encoding)
except AttributeError:
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig)
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName(_fromUtf8("MainWindow"))
MainWindow.resize(800, 600)
MainWindow.setFocus()
def keyPressEvent(self, qKeyEvent):
print "hi"
print(qKeyEvent.key())
if qKeyEvent.key() == QtCore.Qt.Key_Return:
print('Enter pressed')
else:
super(Ui_MainWindow).keyPressEvent(qKeyEvent)
self.centralwidget = QtGui.QWidget(MainWindow)
self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
self.horizontalLayoutWidget = QtGui.QWidget(self.centralwidget)
self.horizontalLayoutWidget.setGeometry(QtCore.QRect(40, 10, 721,
80))
self.horizontalLayoutWidget.setObjectName(_fromUtf8("horizontalLayoutWidget"))
self.horizontalLayout =
QtGui.QHBoxLayout(self.horizontalLayoutWidget)
self.horizontalLayout.setMargin(0)
self.horizontalLayout.setObjectName(_fromUtf8("horizontalLayout"))
self.textEdit = QtGui.QLabel(self.centralwidget)
self.textEdit.setGeometry(QtCore.QRect(50, 110, 81, 41))
self.textEdit.setObjectName(_fromUtf8("textEdit"))
self.pushButton = QtGui.QPushButton(self.centralwidget)
self.pushButton.setGeometry(QtCore.QRect(130, 260, 75, 23))
self.pushButton.setObjectName(_fromUtf8("pushButton"))
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtGui.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 21))
self.menubar.setObjectName(_fromUtf8("menubar"))
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtGui.QStatusBar(MainWindow)
self.statusbar.setObjectName(_fromUtf8("statusbar"))
MainWindow.setStatusBar(self.statusbar)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow",
None))
self.textEdit.setText("I am a label")
self.pushButton.setText(_translate("MainWindow", "PushButton", None))
if __name__ == "__main__":
import sys
app = QtGui.QApplication(sys.argv)
MainWindow = QtGui.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
I am new to this forum , it will be helpful if someone can help . I know
this can be achieved by creating another class who inherits QMainWindow
but i want to do this in the same code i.e in the code block generated by
pyQT Designer .
Also please suggest If there is any way to do this without reimplementing
keypressEvent
Thanks
I Created a code using pyQt Designer in ui and changed it to py code.
Now i want to add some Keypress events to my this i.e. say if i click on
keyboard key with numeric 3 , my label should have text 3 on it or it just
print "Hi"
I have already checked a lot of forums over internet and found that its
best to reimplement keyPressEvent to use keyboard events . I tried that
however somehow i am not able to make it work in the code generated by
pyQT designer .
Below is the code generated by pyQT designer . I have put the code of
keyPressEvent re implementation in it as well , however it dosent work :
try:
_encoding = QtGui.QApplication.UnicodeUTF8
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig,
_encoding)
except AttributeError:
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig)
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName(_fromUtf8("MainWindow"))
MainWindow.resize(800, 600)
MainWindow.setFocus()
def keyPressEvent(self, qKeyEvent):
print "hi"
print(qKeyEvent.key())
if qKeyEvent.key() == QtCore.Qt.Key_Return:
print('Enter pressed')
else:
super(Ui_MainWindow).keyPressEvent(qKeyEvent)
self.centralwidget = QtGui.QWidget(MainWindow)
self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
self.horizontalLayoutWidget = QtGui.QWidget(self.centralwidget)
self.horizontalLayoutWidget.setGeometry(QtCore.QRect(40, 10, 721,
80))
self.horizontalLayoutWidget.setObjectName(_fromUtf8("horizontalLayoutWidget"))
self.horizontalLayout =
QtGui.QHBoxLayout(self.horizontalLayoutWidget)
self.horizontalLayout.setMargin(0)
self.horizontalLayout.setObjectName(_fromUtf8("horizontalLayout"))
self.textEdit = QtGui.QLabel(self.centralwidget)
self.textEdit.setGeometry(QtCore.QRect(50, 110, 81, 41))
self.textEdit.setObjectName(_fromUtf8("textEdit"))
self.pushButton = QtGui.QPushButton(self.centralwidget)
self.pushButton.setGeometry(QtCore.QRect(130, 260, 75, 23))
self.pushButton.setObjectName(_fromUtf8("pushButton"))
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtGui.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 21))
self.menubar.setObjectName(_fromUtf8("menubar"))
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtGui.QStatusBar(MainWindow)
self.statusbar.setObjectName(_fromUtf8("statusbar"))
MainWindow.setStatusBar(self.statusbar)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow",
None))
self.textEdit.setText("I am a label")
self.pushButton.setText(_translate("MainWindow", "PushButton", None))
if __name__ == "__main__":
import sys
app = QtGui.QApplication(sys.argv)
MainWindow = QtGui.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
I am new to this forum , it will be helpful if someone can help . I know
this can be achieved by creating another class who inherits QMainWindow
but i want to do this in the same code i.e in the code block generated by
pyQT Designer .
Also please suggest If there is any way to do this without reimplementing
keypressEvent
Thanks
Friday, 23 August 2013
Count MySQL Row if datetime Interval
Count MySQL Row if datetime Interval
I am trying to think of the most efficient way to count specific rows in a
MySQL table. My table contains a datetime column called "date_time". I
want to count the number of rows where there is at least 30 minutes
between each date_time. For example, lets say I have the table below:
(id) 1 - (date_time) 2013-08-23 00:00:30
(id) 2 - (date_time) 2013-08-23 00:00:45
(id) 3 - (date_time) 2013-08-23 00:01:01
(id) 4 - (date_time) 2013-08-23 00:02:30
(id) 5 - (date_time) 2013-08-23 00:02:45
if I only want to include an entry if there is at least 30 minutes since
the last entry, then the count would include id #1 and id #4, thus the
count would be 2.
I am trying to come up with a clean script to do this, is there any
special kind of query that will help me accomplish this? Any guidance
would be excellent! Thank you all!
I am trying to think of the most efficient way to count specific rows in a
MySQL table. My table contains a datetime column called "date_time". I
want to count the number of rows where there is at least 30 minutes
between each date_time. For example, lets say I have the table below:
(id) 1 - (date_time) 2013-08-23 00:00:30
(id) 2 - (date_time) 2013-08-23 00:00:45
(id) 3 - (date_time) 2013-08-23 00:01:01
(id) 4 - (date_time) 2013-08-23 00:02:30
(id) 5 - (date_time) 2013-08-23 00:02:45
if I only want to include an entry if there is at least 30 minutes since
the last entry, then the count would include id #1 and id #4, thus the
count would be 2.
I am trying to come up with a clean script to do this, is there any
special kind of query that will help me accomplish this? Any guidance
would be excellent! Thank you all!
Can attributes be assigned anywhere within a class?
Can attributes be assigned anywhere within a class?
Can attributes be assigned anywhere within a class? If so, how do scope
rules works for each of the following cases?
class GreatComposers(object):
def __init__(self, name, birthday, instrument):
# attributes assigned in __init__
self.name = name
self.birthday = birthday
self.instrument = instrument
def setFullName(self)
# attributes assigned in other class methods
self.fullname = self.name + self.birthday
self.job = self.instrument + 'ist'
# attributes assigned outside any functions
self.nationality = 'german'
Can attributes be assigned anywhere within a class? If so, how do scope
rules works for each of the following cases?
class GreatComposers(object):
def __init__(self, name, birthday, instrument):
# attributes assigned in __init__
self.name = name
self.birthday = birthday
self.instrument = instrument
def setFullName(self)
# attributes assigned in other class methods
self.fullname = self.name + self.birthday
self.job = self.instrument + 'ist'
# attributes assigned outside any functions
self.nationality = 'german'
In a DOS script, how would I compare a returned value to a value that I set and then return a true or false?
In a DOS script, how would I compare a returned value to a value that I
set and then return a true or false?
I want to compare the first 3 sets or the third set of numbers in %ip% to
the home ip.
for /f "delims=[] tokens=2" %%a in ('ping shaws104 -n 1 ^| findstr "["')
do (set ip=%%a) echo %ip% set home=192.168.100.xxx
set and then return a true or false?
I want to compare the first 3 sets or the third set of numbers in %ip% to
the home ip.
for /f "delims=[] tokens=2" %%a in ('ping shaws104 -n 1 ^| findstr "["')
do (set ip=%%a) echo %ip% set home=192.168.100.xxx
Which phpmyadmin version is compatible with php version 5.1.6?
Which phpmyadmin version is compatible with php version 5.1.6?
I have to install phpMyAdmin on shared hosting that does not have Shell
access and is running 5.1.6
I downloaded the latest phpMyAdmin and it says "PHP 5.2+ is required"
What is the most recent version of MyAdmin will work? Googled and can't
seem to find the answer.
I have to install phpMyAdmin on shared hosting that does not have Shell
access and is running 5.1.6
I downloaded the latest phpMyAdmin and it says "PHP 5.2+ is required"
What is the most recent version of MyAdmin will work? Googled and can't
seem to find the answer.
3 rd party library for generating pdfs in IOS SDK
3 rd party library for generating pdfs in IOS SDK
I am working on a iPad app which requires to generate pdf containig images
and text. I have tried generating pdf using Quartz and UIKit but could not
get the desired quality of pdf which i want. Please suggest if there is
any other method or a 3 rd party library for generating pdfs in IOS SDK.
I am working on a iPad app which requires to generate pdf containig images
and text. I have tried generating pdf using Quartz and UIKit but could not
get the desired quality of pdf which i want. Please suggest if there is
any other method or a 3 rd party library for generating pdfs in IOS SDK.
Thursday, 22 August 2013
Getting physical address from foursquare api at current venue geolocation
Getting physical address from foursquare api at current venue geolocation
Looking to geotag current location on android app and using foursquare
api, get a physical address of the venue currently at.
Looking to geotag current location on android app and using foursquare
api, get a physical address of the venue currently at.
Any issues with swapping objects and thread safety?
Any issues with swapping objects and thread safety?
Let's assume we have a property List<Bar> Foo that is being read by
multiple threads.
Are there any issues that such a code:
Foo = GetNewFooList();
could cause?
Let's assume we have a property List<Bar> Foo that is being read by
multiple threads.
Are there any issues that such a code:
Foo = GetNewFooList();
could cause?
coffeescript dictionary get default
coffeescript dictionary get default
In Python if you have a dictionary that consists of lists like
mylist = {'foo': [], 'bar':[3, 4]}
and if you want to add something into that lists you can do
mylist.setdefault('baz', []).append(5)
not to write
key, list_element = 'baz', 5
if key in mylist:
mylist[key].append(list_element)
else:
mylist[key] = [list_element]
is there an equivalent for this in Coffeescript?
In Python if you have a dictionary that consists of lists like
mylist = {'foo': [], 'bar':[3, 4]}
and if you want to add something into that lists you can do
mylist.setdefault('baz', []).append(5)
not to write
key, list_element = 'baz', 5
if key in mylist:
mylist[key].append(list_element)
else:
mylist[key] = [list_element]
is there an equivalent for this in Coffeescript?
Javascript Check Login function returns false, but continues to next line anyways?
Javascript Check Login function returns false, but continues to next line
anyways?
The following code checks for a user and returns false if the user is not
logged in.
function checkLogin(e) {
loggedIn = $('#loggedin').text();
if(loggedIn == '1'){
e.preventDefault();
alert("Please Log In");
return false;
}
}
I then call this function before some other code and an ajax call.
tileFavorite = $('.tileFavorite');
tileFavorite.on('click', function(e) {
checkLogin(e);
//some code goes here before ajax call
$.ajax({
url: // ajax call goes here,
cache: false
})
});
The check login actually works. However if the checkLogin function returns
false, it still continues to the code beneath it. There a way to avoid
this?
anyways?
The following code checks for a user and returns false if the user is not
logged in.
function checkLogin(e) {
loggedIn = $('#loggedin').text();
if(loggedIn == '1'){
e.preventDefault();
alert("Please Log In");
return false;
}
}
I then call this function before some other code and an ajax call.
tileFavorite = $('.tileFavorite');
tileFavorite.on('click', function(e) {
checkLogin(e);
//some code goes here before ajax call
$.ajax({
url: // ajax call goes here,
cache: false
})
});
The check login actually works. However if the checkLogin function returns
false, it still continues to the code beneath it. There a way to avoid
this?
actionscript tcp packets not delivered before closing socket
actionscript tcp packets not delivered before closing socket
I'm trying to code a simple actionscript tcp client, which is to send data
to a c++ tcp server. I'm new to actionscript and I'm using sample code
from adobe (see link below) for the client. I am able to make a connection
and send data, but the data is only available at the server when the
object is unloaded at the client side (hence closing the socket I guess).
I tried using a c++ client, and the data is immediately available at the
server, so I must be missing something on the client side. Maybe I need to
append some kind of termination/marker sequence? Thank you in advance for
any help!
actionscript code sending data over tcp:
private function tcpConnect():void
{
var customSocket:CustomSocket = new CustomSocket("127.0.0.1", 5331);
customSocket.timeout = 100;
socketWrite(customSocket, 53);
socketWrite(customSocket, 54);
socketWrite(customSocket, 55);
socketWrite(customSocket, 56);
}
private function socketWrite(sock:CustomSocket, b:int):void
{
sock.writeByte(b);
sock.writeByte(0);
sock.flush();
}
C++ tcp server:
http://msdn.microsoft.com/en-us/library/windows/desktop/ms737593(v=vs.85).aspx
Actionscript tcp client:
http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/net/Socket.html#includeExamplesSummary
I'm trying to code a simple actionscript tcp client, which is to send data
to a c++ tcp server. I'm new to actionscript and I'm using sample code
from adobe (see link below) for the client. I am able to make a connection
and send data, but the data is only available at the server when the
object is unloaded at the client side (hence closing the socket I guess).
I tried using a c++ client, and the data is immediately available at the
server, so I must be missing something on the client side. Maybe I need to
append some kind of termination/marker sequence? Thank you in advance for
any help!
actionscript code sending data over tcp:
private function tcpConnect():void
{
var customSocket:CustomSocket = new CustomSocket("127.0.0.1", 5331);
customSocket.timeout = 100;
socketWrite(customSocket, 53);
socketWrite(customSocket, 54);
socketWrite(customSocket, 55);
socketWrite(customSocket, 56);
}
private function socketWrite(sock:CustomSocket, b:int):void
{
sock.writeByte(b);
sock.writeByte(0);
sock.flush();
}
C++ tcp server:
http://msdn.microsoft.com/en-us/library/windows/desktop/ms737593(v=vs.85).aspx
Actionscript tcp client:
http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/net/Socket.html#includeExamplesSummary
JAVASCRIPT :getting border css in opera and Safari
JAVASCRIPT :getting border css in opera and Safari
m new to stackoverflow..
i want to get all css property of an element inline, external, internal...
which m getting using the following code:
for internal and external css:
function getElementChildrenAndStyles(selector) {
selector = selector.split(",").map(function(subselector){
return subselector + "," + subselector + " *";
}).join(",");
elts = $(selector);
var rulesUsed = [];
// main part: walking through all declared style rules
// and checking, whether it is applied to some element
sheets = document.styleSheets;
for(var c = 0; c < sheets.length; c++) {
var rules = sheets[c].rules || sheets[c].cssRules;
for(var r = 0; r < rules.length; r++) {
var selectorText = rules[r].selectorText;
var matchedElts = $(selectorText);
for (var i = 0; i < elts.length; i++) {
if (matchedElts.index(elts[i]) != -1) {
rulesUsed.push(rules[r]); break;
}
}
}
}
var style = rulesUsed.map(function(cssRule){
var cssText = cssRule.cssText;
// some beautifying of css
return cssText.replace(/(\{|;)\s+/g, "\$1\n ").replace(/\A\s+}/, "}");
// set indent for css here ^
}).join("\n");
return style;
}
and for inline css:
document.getElementById('elemid').style.cssText;
this is working fine in all browsers...
but the problem is when m alerting the css it shows detailed properties of
border like
border-top-color:#ccc
border-left-color:#ccc
border-bottom-color:#ccc
border-right-color:#ccc
border-top-width:1px
border-left-width:1px
border-bottom-width:1px
border-right-width:1px
border-top-style:solid
border-left-style:solid
border-bottom-style:solid
border-right-style:solid
this is happening only in opera n Safari...
and i just want one line css for border Eg border:1px solid #ccc
please help out....
m new to stackoverflow..
i want to get all css property of an element inline, external, internal...
which m getting using the following code:
for internal and external css:
function getElementChildrenAndStyles(selector) {
selector = selector.split(",").map(function(subselector){
return subselector + "," + subselector + " *";
}).join(",");
elts = $(selector);
var rulesUsed = [];
// main part: walking through all declared style rules
// and checking, whether it is applied to some element
sheets = document.styleSheets;
for(var c = 0; c < sheets.length; c++) {
var rules = sheets[c].rules || sheets[c].cssRules;
for(var r = 0; r < rules.length; r++) {
var selectorText = rules[r].selectorText;
var matchedElts = $(selectorText);
for (var i = 0; i < elts.length; i++) {
if (matchedElts.index(elts[i]) != -1) {
rulesUsed.push(rules[r]); break;
}
}
}
}
var style = rulesUsed.map(function(cssRule){
var cssText = cssRule.cssText;
// some beautifying of css
return cssText.replace(/(\{|;)\s+/g, "\$1\n ").replace(/\A\s+}/, "}");
// set indent for css here ^
}).join("\n");
return style;
}
and for inline css:
document.getElementById('elemid').style.cssText;
this is working fine in all browsers...
but the problem is when m alerting the css it shows detailed properties of
border like
border-top-color:#ccc
border-left-color:#ccc
border-bottom-color:#ccc
border-right-color:#ccc
border-top-width:1px
border-left-width:1px
border-bottom-width:1px
border-right-width:1px
border-top-style:solid
border-left-style:solid
border-bottom-style:solid
border-right-style:solid
this is happening only in opera n Safari...
and i just want one line css for border Eg border:1px solid #ccc
please help out....
java - Want to divide long (huge file size in TBs) by some number (huge int) and safely get an int
java - Want to divide long (huge file size in TBs) by some number (huge
int) and safely get an int
I want to divide long (huge file size in TBs) by some number (huge int)
and safely get an int. But with the type conversion properties both int
becomes long and the result is long. I'm sure my quotient will be an int,
is casting ok or please direct me to a better solution.
int) and safely get an int
I want to divide long (huge file size in TBs) by some number (huge int)
and safely get an int. But with the type conversion properties both int
becomes long and the result is long. I'm sure my quotient will be an int,
is casting ok or please direct me to a better solution.
Wednesday, 21 August 2013
Ssh port forwarding with Remote Desktop timing out
Ssh port forwarding with Remote Desktop timing out
My work computer, a Windows 7 Enterprise PC called WORKPC, is running
Remote Desktop. I have configured Windows Firewall on WORKPC to allow
access to the Remote Dekstop service from only two IP addresses: IP1 and
IP2.
IP1 comes from a commercial VPN service that allocates me a static IP
address. When I go home and run the VPN client I can connect to WORKPC
using the Remote Dekstop client with no problem.
IP2 is the address of a Linux server GATEWAY at work I can ssh into from
home. In order to use IP2 to remote desktop to WORKPC I use ssh and port
forwarding on IP2:
ssh -vvv -L 1234:WORKPC.example.org:3389 GATEWAY.example.org
When I attempt to remote desktop from home using this port forwarding
technique, I get the following error on my ssh connection:
debug1: Connection to port 1234 forwarding to WORKPC.example.org port 3389
requested.
debug2: fd 9 setting TCP_NODELAY
debug3: fd 9 is O_NONBLOCK
debug3: fd 9 is O_NONBLOCK
debug1: channel 3: new [direct-tcpip]
channel 3: open failed: connect failed: Connection timed out
To verify that port 3389 was open on GATEWAY I did a telnet 3389 and got a
connection, so I am certain that port 3389 on WORKPC is open to GATEWAY.
I would prefer to use the ssh proxying method over paying the commercial
VPN service to rent a static IP address. Can anyone suggest something I
can try to get this to work?
My work computer, a Windows 7 Enterprise PC called WORKPC, is running
Remote Desktop. I have configured Windows Firewall on WORKPC to allow
access to the Remote Dekstop service from only two IP addresses: IP1 and
IP2.
IP1 comes from a commercial VPN service that allocates me a static IP
address. When I go home and run the VPN client I can connect to WORKPC
using the Remote Dekstop client with no problem.
IP2 is the address of a Linux server GATEWAY at work I can ssh into from
home. In order to use IP2 to remote desktop to WORKPC I use ssh and port
forwarding on IP2:
ssh -vvv -L 1234:WORKPC.example.org:3389 GATEWAY.example.org
When I attempt to remote desktop from home using this port forwarding
technique, I get the following error on my ssh connection:
debug1: Connection to port 1234 forwarding to WORKPC.example.org port 3389
requested.
debug2: fd 9 setting TCP_NODELAY
debug3: fd 9 is O_NONBLOCK
debug3: fd 9 is O_NONBLOCK
debug1: channel 3: new [direct-tcpip]
channel 3: open failed: connect failed: Connection timed out
To verify that port 3389 was open on GATEWAY I did a telnet 3389 and got a
connection, so I am certain that port 3389 on WORKPC is open to GATEWAY.
I would prefer to use the ssh proxying method over paying the commercial
VPN service to rent a static IP address. Can anyone suggest something I
can try to get this to work?
How to write the expression with multi-index notation?
How to write the expression with multi-index notation?
I need some help for writing the following expression with multi-index
notation, $$\sum_{i_1, \ldots, i_p=1}^n \frac{\partial^{2p}}{\partial
x_{i_1}^2\ldots \partial x_{i_p}^2}f(x, \xi),$$ where $f:\mathbb R^n\times
\mathbb T^n\rightarrow \mathbb C$. The above expression is simply the
Laplacian with respect to $x$ applied $p$ times. Any help will be
valuable. Thanks
I need some help for writing the following expression with multi-index
notation, $$\sum_{i_1, \ldots, i_p=1}^n \frac{\partial^{2p}}{\partial
x_{i_1}^2\ldots \partial x_{i_p}^2}f(x, \xi),$$ where $f:\mathbb R^n\times
\mathbb T^n\rightarrow \mathbb C$. The above expression is simply the
Laplacian with respect to $x$ applied $p$ times. Any help will be
valuable. Thanks
return results of same ID from 2 tables
return results of same ID from 2 tables
I'm using an opensource database, so it's setup is a bit over my head.
Its basically like this. A persons normal information is in the table
'person_per' There is custom information in the table 'person_custom'
both use 'per_ID' to organize.
select per_ID from person_custom where c3 like '2';
gives my the IDs of people who fit my search, I want to "join" (I think)
their name, phone, ect from the 'person_per' table using the ID as the
"key"(terms I read that seem to fit).
How can I do that in a single query?
I'm using an opensource database, so it's setup is a bit over my head.
Its basically like this. A persons normal information is in the table
'person_per' There is custom information in the table 'person_custom'
both use 'per_ID' to organize.
select per_ID from person_custom where c3 like '2';
gives my the IDs of people who fit my search, I want to "join" (I think)
their name, phone, ect from the 'person_per' table using the ID as the
"key"(terms I read that seem to fit).
How can I do that in a single query?
I can't lock my screen on ubuntu 13.04
I can't lock my screen on ubuntu 13.04
I can't lock my screen on ubuntu 13.04. Even installing gnome-screensaver
the settings always show me the lock session as disable. Crtl+L doesn't
work even clicking on lock on menu nothing happens. Any one can help me?
I can't lock my screen on ubuntu 13.04. Even installing gnome-screensaver
the settings always show me the lock session as disable. Crtl+L doesn't
work even clicking on lock on menu nothing happens. Any one can help me?
How to design immutable model classes when using inheritance
How to design immutable model classes when using inheritance
I'm having trouble finding an elegant way of designing a some simple
classes to represent HTTP messages in Scala.
Say I have something like this:
abstract class HttpMessage(headers: List[String]) {
def addHeader(header: String) = ???
}
class HttpRequest(path: String, headers: List[String])
extends HttpMessage(headers)
new HttpRequest("/", List("foo")).addHeader("bar")
How can I make the addHeader method return a copy of itself with the new
header added? (and keep the current value of path as well)
Thanks, Rob.
I'm having trouble finding an elegant way of designing a some simple
classes to represent HTTP messages in Scala.
Say I have something like this:
abstract class HttpMessage(headers: List[String]) {
def addHeader(header: String) = ???
}
class HttpRequest(path: String, headers: List[String])
extends HttpMessage(headers)
new HttpRequest("/", List("foo")).addHeader("bar")
How can I make the addHeader method return a copy of itself with the new
header added? (and keep the current value of path as well)
Thanks, Rob.
Tuesday, 20 August 2013
Gigya Share bar Customization - buttonWithCountTemplate
Gigya Share bar Customization - buttonWithCountTemplate
I have asked a question regarding customizing the share bar especially
providers facebook-like and google-plusone (Gigya ShareBar : unable to
change icon for facebook-like and google-plusone). But no answers so far.
I was wondering if it can be done using buttonWithCountTemplate. I want to
set the icons for facebook-like and google-plusone in sharebar using
buttonWithCountTemplate. But there seems to be no example code that shows
buttonWithCountTemplate usage. Can anyone provide the example usage of
buttonWithCountTemplate in Gigya Share Bar Customization.
I have asked a question regarding customizing the share bar especially
providers facebook-like and google-plusone (Gigya ShareBar : unable to
change icon for facebook-like and google-plusone). But no answers so far.
I was wondering if it can be done using buttonWithCountTemplate. I want to
set the icons for facebook-like and google-plusone in sharebar using
buttonWithCountTemplate. But there seems to be no example code that shows
buttonWithCountTemplate usage. Can anyone provide the example usage of
buttonWithCountTemplate in Gigya Share Bar Customization.
do - while with $var[x]
do - while with $var[x]
i'm still in the learning curve with php
I'm trying to achieve this:
let's say i have an ul with dynamically generated li's. And these li's
must be populated with data stored in a variable. For example:
$var[0] = 'first data';
$var[1] = 'second data';
$var[2] = 'third data';
result:
<ul>
<li>first data</li>
<li>second data</li>
<li>third data</li>
</ul>
I know i must put something like this:
<ul>
<?php do { ?>
<li><?php echo $var ?></li>
<?php } while (condition); ?>
</ul>
But, i didn't figure which is the correct condition syntax, and how to
create the variable which puts the differents items into the li's (the
$var item into the li).
i'm still in the learning curve with php
I'm trying to achieve this:
let's say i have an ul with dynamically generated li's. And these li's
must be populated with data stored in a variable. For example:
$var[0] = 'first data';
$var[1] = 'second data';
$var[2] = 'third data';
result:
<ul>
<li>first data</li>
<li>second data</li>
<li>third data</li>
</ul>
I know i must put something like this:
<ul>
<?php do { ?>
<li><?php echo $var ?></li>
<?php } while (condition); ?>
</ul>
But, i didn't figure which is the correct condition syntax, and how to
create the variable which puts the differents items into the li's (the
$var item into the li).
How can I change the width of a Bootstrap 3 modal in IE8?
How can I change the width of a Bootstrap 3 modal in IE8?
I have to support IE8. The modal itself works fine, but my attempts to
resize it (which work fine in Firefox) don't work in IE8.
I'm just adding a class (wide-modal in this example) to the modal-dialog
div (the 2nd nested one in the Bootstrap structure) and applying a width
via CSS, nothing fancy.
HTML:
<div class="modal fade" id="modalTest" role="dialog">
<div class="modal-dialog wide-modal">
<div class="modal-content ">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"
aria-hidden="true">×</button>
<h4 class="modal-title">Testing Modal</h4>
</div>
<div class="modal-body">
<img src="content/Example-Infographic.jpg" width="100%" />
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default"
data-dismiss="modal">Close</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div>
CSS:
.wide-modal {
width: 60%;
}
I tried adding the class to the div above and below to no (positive)
effect. It works like a charm where it is in Firefox, just no effect at
all in IE8. I also tried with a px width, no difference. I do have the
respond.js library in place so in general IE8 is behaving other than this.
I have to support IE8. The modal itself works fine, but my attempts to
resize it (which work fine in Firefox) don't work in IE8.
I'm just adding a class (wide-modal in this example) to the modal-dialog
div (the 2nd nested one in the Bootstrap structure) and applying a width
via CSS, nothing fancy.
HTML:
<div class="modal fade" id="modalTest" role="dialog">
<div class="modal-dialog wide-modal">
<div class="modal-content ">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"
aria-hidden="true">×</button>
<h4 class="modal-title">Testing Modal</h4>
</div>
<div class="modal-body">
<img src="content/Example-Infographic.jpg" width="100%" />
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default"
data-dismiss="modal">Close</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div>
CSS:
.wide-modal {
width: 60%;
}
I tried adding the class to the div above and below to no (positive)
effect. It works like a charm where it is in Firefox, just no effect at
all in IE8. I also tried with a px width, no difference. I do have the
respond.js library in place so in general IE8 is behaving other than this.
Error when creating new users or groups in OBIEE
Error when creating new users or groups in OBIEE
I am using Oracle 11g OBIEE. In the Enterprise Manger, WeLogic Admin
console, I'm trying to create new users and groups. However, every time I
go into create a user or group, then hit 'Ok', I'm dumped to a screen that
says 'the address is not valid' in IE or 'can't find the server at [2002'
in Firefox.
I've restarted the server several times but I constantly get this error.
Any ideas?
Thanks
I am using Oracle 11g OBIEE. In the Enterprise Manger, WeLogic Admin
console, I'm trying to create new users and groups. However, every time I
go into create a user or group, then hit 'Ok', I'm dumped to a screen that
says 'the address is not valid' in IE or 'can't find the server at [2002'
in Firefox.
I've restarted the server several times but I constantly get this error.
Any ideas?
Thanks
Conditionally Replace a specific Character in a string
Conditionally Replace a specific Character in a string
I am trying to remove the @ sign from a block of text. The problem is that
in certain cases (when at the beginning of a line, the @ sign needs to
stay.
I have succeeded by using the RegEx pattern .\@, however on when the @
sign does get removed it also removes the character preceding it.
Goal: remove all @ signs UNLESS the @ sign is the first character in the
line.
<?php
function cleanFile($text)
{
$pattern = '/.\@/';
$replacement = '%40';
$val = preg_replace($pattern, $replacement, $text);
$text = $val;
return $text;
};
$text = ' Test: test@test.com'."\n";
$text .= '@Test: Leave the leading at sign alone'."\n";
$text .= '@Test: test@test.com'."\n";
$valResult = cleanFile($text);
echo $valResult;
?>
Output:
Test: tes%40test.com
@Test: Leave the leading at sign alone
@Test: tes%40test.com
I am trying to remove the @ sign from a block of text. The problem is that
in certain cases (when at the beginning of a line, the @ sign needs to
stay.
I have succeeded by using the RegEx pattern .\@, however on when the @
sign does get removed it also removes the character preceding it.
Goal: remove all @ signs UNLESS the @ sign is the first character in the
line.
<?php
function cleanFile($text)
{
$pattern = '/.\@/';
$replacement = '%40';
$val = preg_replace($pattern, $replacement, $text);
$text = $val;
return $text;
};
$text = ' Test: test@test.com'."\n";
$text .= '@Test: Leave the leading at sign alone'."\n";
$text .= '@Test: test@test.com'."\n";
$valResult = cleanFile($text);
echo $valResult;
?>
Output:
Test: tes%40test.com
@Test: Leave the leading at sign alone
@Test: tes%40test.com
Facebook Application Programming
Facebook Application Programming
I was planning to build a facebook appliation.But now that all the
frameowrk and server and all are set, I don't know how to start
programming so that i could build my dynamic app.Could anyone help me
where to and how to start?I read everything given at facebook developer's
but none of that seems to be helping.Thanx in advance
I was planning to build a facebook appliation.But now that all the
frameowrk and server and all are set, I don't know how to start
programming so that i could build my dynamic app.Could anyone help me
where to and how to start?I read everything given at facebook developer's
but none of that seems to be helping.Thanx in advance
TypeError when tried to override the UserCreationForm's.error message
TypeError when tried to override the UserCreationForm's.error message
I have a registration form from UserCreationForm, to which I had override
with the following:
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
from django import forms
import re
from django.core.exceptions import ObjectDoesNotExist
class UserCreationForm(UserCreationForm):
class Meta:
model = User
fields = ('first_name', 'last_name', 'username',)
error_messages = {
'duplicate_username': _("A user with that email already exists."),
'password_mismatch': _("The two password fields didn't match."),
}
username = forms.EmailField(label='Email', max_length=250, unique=True)
def save(self, commit=True):
user = super(UserCreationForm, self).save(commit=False)
user.email = user.username
user.save()
return user
But I was getting an error:
NameError at /admin/
name '_' is not defined
So, I had to import
from django.utils.translation import gettext as _
And that solved that problem. But now, after that has been fixed (i
guess..that was the solution for the first problem), I am getting another
error:
TypeError at /admin/
__init__() got an unexpected keyword argument 'unique'
If I remove 'unique' from the EmailField, everything works fine. So, do I
remove the unique=true from the form? Will it always be unique for each
username(here its email), even though I remove it? And one more thing, was
from django.utils.translation import gettext as _ the suited solution for
the error name '_' is not defined??? I am a newbie in django. Any help
will be greatly appreciated! Thank you.
I have a registration form from UserCreationForm, to which I had override
with the following:
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
from django import forms
import re
from django.core.exceptions import ObjectDoesNotExist
class UserCreationForm(UserCreationForm):
class Meta:
model = User
fields = ('first_name', 'last_name', 'username',)
error_messages = {
'duplicate_username': _("A user with that email already exists."),
'password_mismatch': _("The two password fields didn't match."),
}
username = forms.EmailField(label='Email', max_length=250, unique=True)
def save(self, commit=True):
user = super(UserCreationForm, self).save(commit=False)
user.email = user.username
user.save()
return user
But I was getting an error:
NameError at /admin/
name '_' is not defined
So, I had to import
from django.utils.translation import gettext as _
And that solved that problem. But now, after that has been fixed (i
guess..that was the solution for the first problem), I am getting another
error:
TypeError at /admin/
__init__() got an unexpected keyword argument 'unique'
If I remove 'unique' from the EmailField, everything works fine. So, do I
remove the unique=true from the form? Will it always be unique for each
username(here its email), even though I remove it? And one more thing, was
from django.utils.translation import gettext as _ the suited solution for
the error name '_' is not defined??? I am a newbie in django. Any help
will be greatly appreciated! Thank you.
Monday, 19 August 2013
Using Q library in browser
Using Q library in browser
I prepare some webapp. I need to use Q library
(http://documentup.com/kriskowal/q/) in browser. I would like to use
RequireJs to load this library in browser, but i dont have any idea how
can I do this. I know how to load my own module, but I can`t do it with Q
library. Q have some function:
(function (definition) {
//some another code here***
// RequireJS
} else if (typeof define === "function" && define.amd) {
define(definition);
Can you help me with it? How can i load Q library and then use it into
another module?
I prepare some webapp. I need to use Q library
(http://documentup.com/kriskowal/q/) in browser. I would like to use
RequireJs to load this library in browser, but i dont have any idea how
can I do this. I know how to load my own module, but I can`t do it with Q
library. Q have some function:
(function (definition) {
//some another code here***
// RequireJS
} else if (typeof define === "function" && define.amd) {
define(definition);
Can you help me with it? How can i load Q library and then use it into
another module?
Personal SSE library
Personal SSE library
Ok, so I've been using operator overloading with some of the SSE/AVX
intrinsics to facilitate their usage in more trivial situations where
vector processing is useful. The class definition looks something like
this:
#define Float16a float __attribute__((__aligned__(16)))
class sse
{
private:
__m128 vec __attribute__((__aligned__(16)));
Float16a *temp;
public:
//=================================================================
sse();
sse(float *value);
//=================================================================
void operator + (float *param);
void operator - (float *param);
void operator * (float *param);
void operator / (float *param);
void operator % (float *param);
void operator ^ (int number);
void operator = (float *param);
void operator == (float *param);
void operator += (float *param);
void operator -= (float *param);
void operator *= (float *param);
void operator /= (float *param);
};
With each individual function bearing a resemblance to:
void sse::operator + (float *param)
{
vec = _mm_add_ps(vec, _mm_load_ps(param));
_mm_store_ps(temp, vec);
}
Thus far I have had few problems writing the code but I have run into a
few performance problems, when using when compared with farly trivial
scalar code the SSE/AVX code has a significant performance bump. I know
that this type of code can be difficult profile, but I'm not really even
sure what exactly the the bottleneck is. If there are any pointers that
can be thrown at me it would be appreciated.
Note that this is just a person project that I'm writing to further my own
knowledge of SSE/AVX, so replacing this with an external library would not
be much of a help.
Ok, so I've been using operator overloading with some of the SSE/AVX
intrinsics to facilitate their usage in more trivial situations where
vector processing is useful. The class definition looks something like
this:
#define Float16a float __attribute__((__aligned__(16)))
class sse
{
private:
__m128 vec __attribute__((__aligned__(16)));
Float16a *temp;
public:
//=================================================================
sse();
sse(float *value);
//=================================================================
void operator + (float *param);
void operator - (float *param);
void operator * (float *param);
void operator / (float *param);
void operator % (float *param);
void operator ^ (int number);
void operator = (float *param);
void operator == (float *param);
void operator += (float *param);
void operator -= (float *param);
void operator *= (float *param);
void operator /= (float *param);
};
With each individual function bearing a resemblance to:
void sse::operator + (float *param)
{
vec = _mm_add_ps(vec, _mm_load_ps(param));
_mm_store_ps(temp, vec);
}
Thus far I have had few problems writing the code but I have run into a
few performance problems, when using when compared with farly trivial
scalar code the SSE/AVX code has a significant performance bump. I know
that this type of code can be difficult profile, but I'm not really even
sure what exactly the the bottleneck is. If there are any pointers that
can be thrown at me it would be appreciated.
Note that this is just a person project that I'm writing to further my own
knowledge of SSE/AVX, so replacing this with an external library would not
be much of a help.
How to mix bash script with python script?
How to mix bash script with python script?
What happens if i have a python script..
#!/usr/bin/env python
with open('server_info') as f:
a, b = f
a, b = a.strip(), b.strip()
but right below it, i have a xdotool commands..
a=`xdotool search --name "ooo"`
if [[ "$a" ]]; then
xdotool windowactivate --sync $a
fi
do i add something like..
#!/usr/bin/env python
right above the bash portion of the script ?
if so what is it that i need to add ?
how do i pass the values from python portion to the bash script portion ?
What happens if i have a python script..
#!/usr/bin/env python
with open('server_info') as f:
a, b = f
a, b = a.strip(), b.strip()
but right below it, i have a xdotool commands..
a=`xdotool search --name "ooo"`
if [[ "$a" ]]; then
xdotool windowactivate --sync $a
fi
do i add something like..
#!/usr/bin/env python
right above the bash portion of the script ?
if so what is it that i need to add ?
how do i pass the values from python portion to the bash script portion ?
Get last entered word of RichTextBox using c#
Get last entered word of RichTextBox using c#
How do I get the last entered word and its index position( word between
two spaces. as soon as I press space I need to get the word) within a
RichTextBox. I have used the following code to get the last entered word
and its index position if the word is in the end of the RichTextBox
document.
private void richTextBox_KeyPress(object sender, KeyPressEventArgs e){
if(e.KeyChar == ' '){
int i = richTextBox.Text.TrimEnd().LastIndexOf(' ');
if(i != -1)
MessageBox.Show(richTextBox.Text.Substring(i+1).TrimEnd());
}
}
But how do I get the last entered word and its index position if I type in
the middle of a sentence in the RTB( e.g. 'quick fox' is the sentence; If
I write 'jumps' after 'fox' then using the above code I can get the last
entered word. But if I position the cursor after 'quick' and write 'brown'
after 'quick' how do I get the last entered word (i.e. brown) as soon as I
press space.
Please help
How do I get the last entered word and its index position( word between
two spaces. as soon as I press space I need to get the word) within a
RichTextBox. I have used the following code to get the last entered word
and its index position if the word is in the end of the RichTextBox
document.
private void richTextBox_KeyPress(object sender, KeyPressEventArgs e){
if(e.KeyChar == ' '){
int i = richTextBox.Text.TrimEnd().LastIndexOf(' ');
if(i != -1)
MessageBox.Show(richTextBox.Text.Substring(i+1).TrimEnd());
}
}
But how do I get the last entered word and its index position if I type in
the middle of a sentence in the RTB( e.g. 'quick fox' is the sentence; If
I write 'jumps' after 'fox' then using the above code I can get the last
entered word. But if I position the cursor after 'quick' and write 'brown'
after 'quick' how do I get the last entered word (i.e. brown) as soon as I
press space.
Please help
Unable to install debian on Lacie ss4000e Kernel Panic
Unable to install debian on Lacie ss4000e Kernel Panic
Hello I am trying to load debian linux on my lacie ss4000e I have been
trying to follow this tutorial
http://d-i.alioth.debian.org/manual/en.armel/ch05s01.html#boot-firmware-ss4000e
I have tryed to load it using both the ymodem method and the network
method both end with a kernel pannic
[ 2.412165] No filesystem could mount root, tried:
[ 2.417094] Kernel panic - not syncing: VFS: Unable to mount root fs on
unknown-block(1,0)
[ 2.425495] [<c001378c>] (unwind_backtrace+0x0/0xe0) from [<c0278254>]
(panic+0x50/0x194)
[ 2.433784] [<c0278254>] (panic+0x50/0x194) from [<c037cc08>]
(mount_block_root+0x234/0x284)
[ 2.442294] [<c037cc08>] (mount_block_root+0x234/0x284) from
[<c037cde0>] (prepare_namespace+0x124/0x184)
[ 2.451935] [<c037cde0>] (prepare_namespace+0x124/0x184) from
[<c037c89c>] (kernel_init+0x12c/0x160)
[ 2.461149] [<c037c89c>] (kernel_init+0x12c/0x160) from [<c000edf8>]
(kernel_thread_exit+0x0/0x8)
The exect command of my last try is as follows
fis load rammode
g
Then I wait for it to reboot and hit ctrl+c
ip_address -l 192.168.1.3 -h 192.168.1.100
load -v -r -b 0x01800000 -m http /initrd.gz
load -v -r -b 0x01008000 -m http /zImage
exec -c "console=ttyS0,115200 rw root=/dev/ram mem=256M@0xa0000000" -r
0x01800000
Any help would be greatly apriciated, This has been kicking my butt for a
few days now Thanks
Hello I am trying to load debian linux on my lacie ss4000e I have been
trying to follow this tutorial
http://d-i.alioth.debian.org/manual/en.armel/ch05s01.html#boot-firmware-ss4000e
I have tryed to load it using both the ymodem method and the network
method both end with a kernel pannic
[ 2.412165] No filesystem could mount root, tried:
[ 2.417094] Kernel panic - not syncing: VFS: Unable to mount root fs on
unknown-block(1,0)
[ 2.425495] [<c001378c>] (unwind_backtrace+0x0/0xe0) from [<c0278254>]
(panic+0x50/0x194)
[ 2.433784] [<c0278254>] (panic+0x50/0x194) from [<c037cc08>]
(mount_block_root+0x234/0x284)
[ 2.442294] [<c037cc08>] (mount_block_root+0x234/0x284) from
[<c037cde0>] (prepare_namespace+0x124/0x184)
[ 2.451935] [<c037cde0>] (prepare_namespace+0x124/0x184) from
[<c037c89c>] (kernel_init+0x12c/0x160)
[ 2.461149] [<c037c89c>] (kernel_init+0x12c/0x160) from [<c000edf8>]
(kernel_thread_exit+0x0/0x8)
The exect command of my last try is as follows
fis load rammode
g
Then I wait for it to reboot and hit ctrl+c
ip_address -l 192.168.1.3 -h 192.168.1.100
load -v -r -b 0x01800000 -m http /initrd.gz
load -v -r -b 0x01008000 -m http /zImage
exec -c "console=ttyS0,115200 rw root=/dev/ram mem=256M@0xa0000000" -r
0x01800000
Any help would be greatly apriciated, This has been kicking my butt for a
few days now Thanks
Sunday, 18 August 2013
What is a good JDBC Connection Pool Framework for insert into Mysql Database
What is a good JDBC Connection Pool Framework for insert into Mysql Database
I am writing a Java application, the high level overview of this
application is listening for restful events and when these events come in,
it will be inserted into the Mysql database.
I am using executor service to handle the event processing and perform
other logics, such as insert into db. For the insert into the db side, I
am using a dao pattern (with JDBI). These events can be coming in at
around 3000 per minute.
Currently I am not utilizing any JDBC Connection Pool control. I am simply
passing a data source in the dbi constructor to get a connection and once
an insert is performed, close the connection. This is working in my local
dev environment, but definitely won't handle the requirement needed when
it is deployed.
I do not know much about working with JDBC Connection pool and controls,
and am wondering can some please suggest some good JDBC Connection Control
framework, point me to some articles to read more about it, or any other
suggestion in handling this situation?
Thanks.
I am writing a Java application, the high level overview of this
application is listening for restful events and when these events come in,
it will be inserted into the Mysql database.
I am using executor service to handle the event processing and perform
other logics, such as insert into db. For the insert into the db side, I
am using a dao pattern (with JDBI). These events can be coming in at
around 3000 per minute.
Currently I am not utilizing any JDBC Connection Pool control. I am simply
passing a data source in the dbi constructor to get a connection and once
an insert is performed, close the connection. This is working in my local
dev environment, but definitely won't handle the requirement needed when
it is deployed.
I do not know much about working with JDBC Connection pool and controls,
and am wondering can some please suggest some good JDBC Connection Control
framework, point me to some articles to read more about it, or any other
suggestion in handling this situation?
Thanks.
How do I install browser plugins in a centralized way?
How do I install browser plugins in a centralized way?
I have 5 users on an ubuntu box and I want each user to have AdBlock+ (and
a few others) for both FireFox and Chrome.
Is there a way to avoid logging in as each one with GUI and starting both
browsers and installing the plugins by hand?
I have 5 users on an ubuntu box and I want each user to have AdBlock+ (and
a few others) for both FireFox and Chrome.
Is there a way to avoid logging in as each one with GUI and starting both
browsers and installing the plugins by hand?
Read xml file and write ids' values into related textbox in C#
Read xml file and write ids' values into related textbox in C#
I have a xml file named "numbers.xml" like this:
<?xml version="1.0" encoding="utf-8" ?>
<program>
<box id="aaa" value="78678"/>
<box id="bbb" value="37287"/>
<box id="ccc" value="783"/>
<box id="ddd" value="7867"/>
<box id="eee" value="786"/>
<box id="fff" value="23"/>
<box id="ggg" value="453"/>
<box id="hhh" value="4537"/>
</program>
I want to read this xml file and fill textboxes. But in windows forms
application txtAAA.text value must take id="aaa" value which is 78678.
Likewise txtBBB.text value must take id="bbb" value which is 37287. How
can I do this?
Edit:
I tried like this:
XmlDocument xmldoc = new XmlDocument();
xmldoc.Load(openfiledialog1.FileName);
XmlNodeList nodelist = xmldoc.DocumentElement.ChildNodes;
XmlNode xmlnode = nodelist.Item(0);
txtAAA.Text = xmlnode.Attributes["id"].InnerText;
But "aaa" is shown in textbox. It was totally failure. –
I have a xml file named "numbers.xml" like this:
<?xml version="1.0" encoding="utf-8" ?>
<program>
<box id="aaa" value="78678"/>
<box id="bbb" value="37287"/>
<box id="ccc" value="783"/>
<box id="ddd" value="7867"/>
<box id="eee" value="786"/>
<box id="fff" value="23"/>
<box id="ggg" value="453"/>
<box id="hhh" value="4537"/>
</program>
I want to read this xml file and fill textboxes. But in windows forms
application txtAAA.text value must take id="aaa" value which is 78678.
Likewise txtBBB.text value must take id="bbb" value which is 37287. How
can I do this?
Edit:
I tried like this:
XmlDocument xmldoc = new XmlDocument();
xmldoc.Load(openfiledialog1.FileName);
XmlNodeList nodelist = xmldoc.DocumentElement.ChildNodes;
XmlNode xmlnode = nodelist.Item(0);
txtAAA.Text = xmlnode.Attributes["id"].InnerText;
But "aaa" is shown in textbox. It was totally failure. –
How to resolve the missing python gsm module while executing airprobe
How to resolve the missing python gsm module while executing airprobe
For quite some while I've been trying to work with usrp, gnuradio and
airprobe. I've successfully received a data dump using usrp but when I try
to use gsm_receive100.py on the captured cfile, I am always getting this
error:
./gsm_receive100.py cfile Traceback (most recent call last): File
"./gsm_receive100.py", line 12, in import gsm ImportError: No module named
gsm
I tried to look every possible place for the particular python module that
is missing, both in the web and within the distribution itself but without
any success so far. Has anyone faced a similar problem before, and how to
solve it?
For quite some while I've been trying to work with usrp, gnuradio and
airprobe. I've successfully received a data dump using usrp but when I try
to use gsm_receive100.py on the captured cfile, I am always getting this
error:
./gsm_receive100.py cfile Traceback (most recent call last): File
"./gsm_receive100.py", line 12, in import gsm ImportError: No module named
gsm
I tried to look every possible place for the particular python module that
is missing, both in the web and within the distribution itself but without
any success so far. Has anyone faced a similar problem before, and how to
solve it?
Need to run for loop and WaitFor in sync CasperJS
Need to run for loop and WaitFor in sync CasperJS
I have a code as below
var casper = require('casper').create();
casper.on('remote.message', function (msg) {
this.echo(msg);
});
casper.start( << some url >> , function () {
this.echo(this.getTitle());
});
var resultObj = [];
casper.thenClick("#AddToCart").then(function () {
// scrape something else
casper.options.waitTimeout = 100000;
var objectOne = this.evaluate(someFunction, << variables >> );
//above function returns object
casper.each(objectOne, function (self, obj) {
var anotherObject = this.evaluate(anotherFunction, << variables >> );
self.waitFor(function check() {
var result = this.evaluate(thirdFunction, obj);
if (result != 'no') {
resultObj.push(result);
}
// result = 'yes';
return result != 'no';
this.evaluate(function () {});
}, function then() {
console.log('done')
});
});
});
casper.run(function () {
this.exit();
});
It cantains on loop (.each) followed by wait for. The problem that I am
facing is the loop gets executed completely ant then waitFor gets
executed. How can I achieve them to be in sync.
I have a code as below
var casper = require('casper').create();
casper.on('remote.message', function (msg) {
this.echo(msg);
});
casper.start( << some url >> , function () {
this.echo(this.getTitle());
});
var resultObj = [];
casper.thenClick("#AddToCart").then(function () {
// scrape something else
casper.options.waitTimeout = 100000;
var objectOne = this.evaluate(someFunction, << variables >> );
//above function returns object
casper.each(objectOne, function (self, obj) {
var anotherObject = this.evaluate(anotherFunction, << variables >> );
self.waitFor(function check() {
var result = this.evaluate(thirdFunction, obj);
if (result != 'no') {
resultObj.push(result);
}
// result = 'yes';
return result != 'no';
this.evaluate(function () {});
}, function then() {
console.log('done')
});
});
});
casper.run(function () {
this.exit();
});
It cantains on loop (.each) followed by wait for. The problem that I am
facing is the loop gets executed completely ant then waitFor gets
executed. How can I achieve them to be in sync.
jQuery variable to PHP
jQuery variable to PHP
Is there a way to pass jQuery variables to PHP variables and from PHP to
jQuery? I want to take and ID from a div (wich is generated with PHP) with
jQuery and give that value to a variable.
Is there a way to pass jQuery variables to PHP variables and from PHP to
jQuery? I want to take and ID from a div (wich is generated with PHP) with
jQuery and give that value to a variable.
Windows 7 missing mpk.exe file
Windows 7 missing mpk.exe file
I am using windows 7 with eset6 and 3 user. I could not log in using one
standard user.When i trying windows Log on and Log off immediately.But
other user(admin user) is working fine. I scanned my pc eset found
following
Name: C:\Windows\SysWOW64\MPK\mpk.exe
Threat: a variant of Win32/KeyLogger.Refog.B application
Action: cleaned by deleting - quarantined
information: Event occurred during an attempt to run the file by the
application: C:\Windows\System32\winlogon.exe.
There is no file(C:\Windows\SysWOW64\MPK\mpk.exe) i found.
my question is to where i can found it and how to solve?
I am using windows 7 with eset6 and 3 user. I could not log in using one
standard user.When i trying windows Log on and Log off immediately.But
other user(admin user) is working fine. I scanned my pc eset found
following
Name: C:\Windows\SysWOW64\MPK\mpk.exe
Threat: a variant of Win32/KeyLogger.Refog.B application
Action: cleaned by deleting - quarantined
information: Event occurred during an attempt to run the file by the
application: C:\Windows\System32\winlogon.exe.
There is no file(C:\Windows\SysWOW64\MPK\mpk.exe) i found.
my question is to where i can found it and how to solve?
Saturday, 17 August 2013
Switch from one application to another application using java
Switch from one application to another application using java
How to Switch from one application to another? for example I have opened
two application such as Notepad and Paint if currently focus is on notepad
but I want to do focus on paint.
I wana do it in JAVA... Kindly help me
Thanks in Advance
How to Switch from one application to another? for example I have opened
two application such as Notepad and Paint if currently focus is on notepad
but I want to do focus on paint.
I wana do it in JAVA... Kindly help me
Thanks in Advance
Django multi-table inheritance chokes on leaked variable in model definition
Django multi-table inheritance chokes on leaked variable in model definition
class Parent(models.Model):
pass
class RebelliousChild(Parent):
parent_fields = [__x.name for __x in Parent._meta._fields()]
Django 1.3 responds:
django.core.exceptions.FieldError: Local field '_RebelliousChild__x'
in class 'RebelliousChild'clashes with field of similar name from base
class 'Parent'
Django 1.5 responds:
FieldError: Local field u'id' in class 'RebelliousChild' clashes with field
of similar name from base class 'Parent'
My second reaction (after trying to make the variable private) was to
delete the variable (which worked.)
parent_fields = [__x.name for __x in Parent._meta._fields()]
del __x
List comprehensions leak their control variables in Python 2. Django
prohibits overriding parent field attributes, which seems to be involved
somehow, since Django 1.5 has the same issue. But in both cases the leaked
attribute name _RebelliousChild__x isn't defined on Parent.
What is going on here?
class Parent(models.Model):
pass
class RebelliousChild(Parent):
parent_fields = [__x.name for __x in Parent._meta._fields()]
Django 1.3 responds:
django.core.exceptions.FieldError: Local field '_RebelliousChild__x'
in class 'RebelliousChild'clashes with field of similar name from base
class 'Parent'
Django 1.5 responds:
FieldError: Local field u'id' in class 'RebelliousChild' clashes with field
of similar name from base class 'Parent'
My second reaction (after trying to make the variable private) was to
delete the variable (which worked.)
parent_fields = [__x.name for __x in Parent._meta._fields()]
del __x
List comprehensions leak their control variables in Python 2. Django
prohibits overriding parent field attributes, which seems to be involved
somehow, since Django 1.5 has the same issue. But in both cases the leaked
attribute name _RebelliousChild__x isn't defined on Parent.
What is going on here?
oneToMany or manyToOne Doctrine2 relationship
oneToMany or manyToOne Doctrine2 relationship
I have the following situation.
I have a clients table and services table.
case 1 What I want is to know how to make a submit form in Symfony2
(actually I think that if you can guide me only in YML mapping is enough)
that can CRUD a clients entity, which it can has X services assigned to
it.
clients table only has id and nombre columns, same as services.
case 2 Then, once this is done, I have a new table called task this new
table needs to have the following:
A client for the task. A service for the task, which, at the same time
needs to be assigned to that client, so it is dependent from client select
box (I can make this with jQuery) And some oneToOne relationships which
are actually working very well.
If the task has more than one client, it would be great if I could add on
the same form using prototype with forms collection or something a new
client, and of course, a new service if needed... But this is totally
optional, what I'm really lost is in case 1, because I think if someone
could help me with case 1, case 2 will be easy to make on my own...
And of course, I don't know what to use, oneToMany or manyToOne in both
cases...
I have the following situation.
I have a clients table and services table.
case 1 What I want is to know how to make a submit form in Symfony2
(actually I think that if you can guide me only in YML mapping is enough)
that can CRUD a clients entity, which it can has X services assigned to
it.
clients table only has id and nombre columns, same as services.
case 2 Then, once this is done, I have a new table called task this new
table needs to have the following:
A client for the task. A service for the task, which, at the same time
needs to be assigned to that client, so it is dependent from client select
box (I can make this with jQuery) And some oneToOne relationships which
are actually working very well.
If the task has more than one client, it would be great if I could add on
the same form using prototype with forms collection or something a new
client, and of course, a new service if needed... But this is totally
optional, what I'm really lost is in case 1, because I think if someone
could help me with case 1, case 2 will be easy to make on my own...
And of course, I don't know what to use, oneToMany or manyToOne in both
cases...
DataGridView autosizing rows with Wrapmode set lowers performance significantly
DataGridView autosizing rows with Wrapmode set lowers performance
significantly
So, I have a DataGridView that has row headers disabled, wrapmode set for
multiline cell text and autosize of rows to adjust to the multiline text.
In code:
view.RowHeadersVisible = false;
view.DefaultCellStyle.WrapMode = DataGridViewTriState.True;
view.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells;
The problem is that setting the AutoSizeRowsMode property makes the view
update REALLY slow, compared to not having it set.
Below is a link to more or less the same problem:
http://brianseekford.com/index.php/2010/04/01/datagridview-bug-with-the-autowrap-and-the-autorowsize-not-resizing-rows-on-scroll/
Their solution:
view.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells;
view.Scroll +=new ScrollEventHandler(view_Scroll);
private void view_Scroll(object sender, ScrollEventArgs e)
{
//Workaround for datagrid view bug.
((DataGridView)sender).AutoSizeRowsMode =
DataGridViewAutoSizeRowsMode.DisplayedHeaders;
((DataGridView)sender)AutoSizeRowsMode =
DataGridViewAutoSizeRowsMode.DisplayedCells;
}
Now, the problem is that the row headers are disabled, and therefore my
program just crashes when scrolling.
I hope anyone has a solution or atleast some idea to what i can do.
significantly
So, I have a DataGridView that has row headers disabled, wrapmode set for
multiline cell text and autosize of rows to adjust to the multiline text.
In code:
view.RowHeadersVisible = false;
view.DefaultCellStyle.WrapMode = DataGridViewTriState.True;
view.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells;
The problem is that setting the AutoSizeRowsMode property makes the view
update REALLY slow, compared to not having it set.
Below is a link to more or less the same problem:
http://brianseekford.com/index.php/2010/04/01/datagridview-bug-with-the-autowrap-and-the-autorowsize-not-resizing-rows-on-scroll/
Their solution:
view.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells;
view.Scroll +=new ScrollEventHandler(view_Scroll);
private void view_Scroll(object sender, ScrollEventArgs e)
{
//Workaround for datagrid view bug.
((DataGridView)sender).AutoSizeRowsMode =
DataGridViewAutoSizeRowsMode.DisplayedHeaders;
((DataGridView)sender)AutoSizeRowsMode =
DataGridViewAutoSizeRowsMode.DisplayedCells;
}
Now, the problem is that the row headers are disabled, and therefore my
program just crashes when scrolling.
I hope anyone has a solution or atleast some idea to what i can do.
Connected to company VPN, can't access shared folders [on hold]
Connected to company VPN, can't access shared folders [on hold]
I am connected to company VPN, but can't access network shares.
My home network subnet is 192.168.1.*, no domain, only default workgroup.
My company network subnet is 192.168.3.*, domain is "mydomain.local".
After I connect to company VPN (PPTP), I see this in ipconfig:
IP 192.168.3.3
Mask 255.255.255.255
Gateway:
DNS: 192.168.3.50 (that is IP of our company server)
On company server, I can see that I am connected.
But I can't ping server ("ping 192.168.3.50", "ping
server-s1200.mydomain.local"), nor access shared folder
\Server-S1200\share.
Is it possible to access shared folders when my computer is not in domain?
I am connected to company VPN, but can't access network shares.
My home network subnet is 192.168.1.*, no domain, only default workgroup.
My company network subnet is 192.168.3.*, domain is "mydomain.local".
After I connect to company VPN (PPTP), I see this in ipconfig:
IP 192.168.3.3
Mask 255.255.255.255
Gateway:
DNS: 192.168.3.50 (that is IP of our company server)
On company server, I can see that I am connected.
But I can't ping server ("ping 192.168.3.50", "ping
server-s1200.mydomain.local"), nor access shared folder
\Server-S1200\share.
Is it possible to access shared folders when my computer is not in domain?
MAC OSX: Cannot run multiple local domains
MAC OSX: Cannot run multiple local domains
i am trying to add another local domain to my mac osx:
No matter what i do when visiting say 'domainnumber2.dev' it always
displays the first host in my list.
If i swop them around in my httpd-vhosts file then i get the
domainnumber2.dev site. How can i run multiple localhost site on my mac.
I have a simple set up as below:
<VirtualHost *:80>
ServerName mydomain.dev
ServerAlias mydomain.dev
DocumentRoot "/Users/UserName/Sites/mydomain/"
</VirtualHost>
<VirtualHost *:80>
ServerName mydomainTwo.dev
ServerAlias mydomainTwo.dev
DocumentRoot "/Users/UserName/Sites/mydomainTwo/"
</VirtualHost>
I have also had the more details set up adding the below for both
<Directory "/Users/UserName/Sites/mydomain/">
DirectoryIndex index.php
Options Indexes FollowSymLinks MultiViews
AllowOverride all
Order allow,deny
allow from all
</Directory>
In my hosts file i have:
127.0.0.1 localhost
127.0.0.1 mydomain.dev
127.0.0.1 mydomainTwo.dev
which ever VirtualHost is first is the site that is served up, even typing
'localhost' displays the first set up 'mydomain.dev'.
i am trying to add another local domain to my mac osx:
No matter what i do when visiting say 'domainnumber2.dev' it always
displays the first host in my list.
If i swop them around in my httpd-vhosts file then i get the
domainnumber2.dev site. How can i run multiple localhost site on my mac.
I have a simple set up as below:
<VirtualHost *:80>
ServerName mydomain.dev
ServerAlias mydomain.dev
DocumentRoot "/Users/UserName/Sites/mydomain/"
</VirtualHost>
<VirtualHost *:80>
ServerName mydomainTwo.dev
ServerAlias mydomainTwo.dev
DocumentRoot "/Users/UserName/Sites/mydomainTwo/"
</VirtualHost>
I have also had the more details set up adding the below for both
<Directory "/Users/UserName/Sites/mydomain/">
DirectoryIndex index.php
Options Indexes FollowSymLinks MultiViews
AllowOverride all
Order allow,deny
allow from all
</Directory>
In my hosts file i have:
127.0.0.1 localhost
127.0.0.1 mydomain.dev
127.0.0.1 mydomainTwo.dev
which ever VirtualHost is first is the site that is served up, even typing
'localhost' displays the first set up 'mydomain.dev'.
Yii::app()->user->id is not returning the empty result
Yii::app()->user->id is not returning the empty result
I've a problem, it might be a small one but I couldn't find the solution
for this. Yii:app()->user->getId() or Yii:app()->user->id is not returning
value. it just returning empty result. But I've set the id in my
UserIdentity class.
in my UserIdentity class I've this,
public function getId()
{
return $this->id;
}
I'm setting id in the autheticate() function. if i displayed there itself
it's displaying the id, but not in getId() function. Please help me in
this.
Thanks in advance.
Dhanendran Rajagopal.
I've a problem, it might be a small one but I couldn't find the solution
for this. Yii:app()->user->getId() or Yii:app()->user->id is not returning
value. it just returning empty result. But I've set the id in my
UserIdentity class.
in my UserIdentity class I've this,
public function getId()
{
return $this->id;
}
I'm setting id in the autheticate() function. if i displayed there itself
it's displaying the id, but not in getId() function. Please help me in
this.
Thanks in advance.
Dhanendran Rajagopal.
Friday, 16 August 2013
How to convert a string containing newline characters to multiline yaml
How to convert a string containing newline characters to multiline yaml
I have a string similar to the following:
test_string = "This is a multiple line string \n
containing new line characters. \n
Another new line."
I'm trying to use the to_yaml function to convert it to a multi-line yaml
string but it automatically escapes the new line characters.
test_string.to_yaml
outputs:
=> "--- ! This is a multiple line string \\ncontaining new line characters.
\\nAnother new line."
How do you create a string that contains "\n" and parse it into yaml?
I have a string similar to the following:
test_string = "This is a multiple line string \n
containing new line characters. \n
Another new line."
I'm trying to use the to_yaml function to convert it to a multi-line yaml
string but it automatically escapes the new line characters.
test_string.to_yaml
outputs:
=> "--- ! This is a multiple line string \\ncontaining new line characters.
\\nAnother new line."
How do you create a string that contains "\n" and parse it into yaml?
Saturday, 10 August 2013
Can't startup elasticsearch om UbuntuServer 12.04
Can't startup elasticsearch om UbuntuServer 12.04
I've installed ES on my Ubuntu Server like the following:
cd ~
sudo apt-get update
sudo apt-get install openjdk-7-jre-headless -y
wget
https://download.elasticsearch.org/elasticsearch/elasticsearch/elasticsearch-0.90.0.deb
sudo dpkg -i elasticsearch-0.90.3.deb
It's file because If I check ES status then I see it works:
sudo service elasticsearch status
* ElasticSearch Server is running with pid 2350
But I don't see 9200 aand 9300 ports witch ES uses:
sudo netstat -anltp|grep :9200
sudo netstat -anltp|grep :9300
What's wrong?
I've installed ES on my Ubuntu Server like the following:
cd ~
sudo apt-get update
sudo apt-get install openjdk-7-jre-headless -y
wget
https://download.elasticsearch.org/elasticsearch/elasticsearch/elasticsearch-0.90.0.deb
sudo dpkg -i elasticsearch-0.90.3.deb
It's file because If I check ES status then I see it works:
sudo service elasticsearch status
* ElasticSearch Server is running with pid 2350
But I don't see 9200 aand 9300 ports witch ES uses:
sudo netstat -anltp|grep :9200
sudo netstat -anltp|grep :9300
What's wrong?
Friday, 9 August 2013
Python mayavi: Adding points to a 3d scatter plot
Python mayavi: Adding points to a 3d scatter plot
I'm writing a python application to simulate the motion of particles in
3-space. I'd like to plot the positions for each step, updating the plot
as the app runs, keeping the past positions on the plot.
I'd like to do this with mayavi, but as far as I can tell, one cannot
simply add points to an existing scatter plot, but must add all points in
one go. This is not what I want. I want to add a few points at a time
without having to keep all past points in memory to redraw them all at
each step.
The function I've been looking at is plot3d().
http://docs.enthought.com/mayavi/mayavi/auto/mlab_helper_functions.html#mayavi.mlab.points3d
Any ideas on how to do what I want with python mayavi? Is there another
python 3d plotting package that would do what I want?
I'm writing a python application to simulate the motion of particles in
3-space. I'd like to plot the positions for each step, updating the plot
as the app runs, keeping the past positions on the plot.
I'd like to do this with mayavi, but as far as I can tell, one cannot
simply add points to an existing scatter plot, but must add all points in
one go. This is not what I want. I want to add a few points at a time
without having to keep all past points in memory to redraw them all at
each step.
The function I've been looking at is plot3d().
http://docs.enthought.com/mayavi/mayavi/auto/mlab_helper_functions.html#mayavi.mlab.points3d
Any ideas on how to do what I want with python mayavi? Is there another
python 3d plotting package that would do what I want?
Excel's Find function; Exceptions over values
Excel's Find function; Exceptions over values
I recently learned that Excel's Find function returns a #VALUE error when
it doesn't find the needle in the haystack (i.e. no match is found). I
have several questions about this behavior:
Is there another Excel function that works as Find but returns an actual
value (e.g. -1) when no match is found?
Is there any well-known reason for the function having that behavior? I
mean, talking about general programming and software design, Is there a
known pattern (or methodology, or design philosophy) that prefers throwing
exceptions over returning values (like -1, 0, "" or similar) when a
function doesn't return a "valid" value?
I recently learned that Excel's Find function returns a #VALUE error when
it doesn't find the needle in the haystack (i.e. no match is found). I
have several questions about this behavior:
Is there another Excel function that works as Find but returns an actual
value (e.g. -1) when no match is found?
Is there any well-known reason for the function having that behavior? I
mean, talking about general programming and software design, Is there a
known pattern (or methodology, or design philosophy) that prefers throwing
exceptions over returning values (like -1, 0, "" or similar) when a
function doesn't return a "valid" value?
composer autoloader psr-0 namespaces
composer autoloader psr-0 namespaces
I have create a custom composer package but I am havinh troubles to set
the correct autoload options for it.
All my classes are under "MyNamespace/Common" namespace. So for exemple
for including my ArrayHelper class I do use
Mynamespace/Common/Helper/ArrayHelper.
This is the relevant part of my composer.json
"autoload": {
"psr-0": { "MyNamespace\\": "" }
}
I have read this: http://getcomposer.org/doc/04-schema.md#autoload Any
help. Thank you.
I have create a custom composer package but I am havinh troubles to set
the correct autoload options for it.
All my classes are under "MyNamespace/Common" namespace. So for exemple
for including my ArrayHelper class I do use
Mynamespace/Common/Helper/ArrayHelper.
This is the relevant part of my composer.json
"autoload": {
"psr-0": { "MyNamespace\\": "" }
}
I have read this: http://getcomposer.org/doc/04-schema.md#autoload Any
help. Thank you.
python: an urlopen trouble while trying to download a gzip file
python: an urlopen trouble while trying to download a gzip file
Greeting to all.
I am going to use the wiktionary dump for the purpose of POS tagging.
Somehow it stuck yet at the step of downloading. Here is my code
import nltk
from urllib import urlopen
from collections import Counter
import gzip
url =
'http://dumps.wikimedia.org/enwiktionary/latest/enwiktionary-latest-all-titles-in-ns0.gz'
fStream = gzip.open(urlopen(url).read(), 'rb')
dictFile = fStream.read()
fStream.close()
text = nltk.Text(word.lower() for word in dictFile())
tokens = nltk.word_tokenize(text)
Here is the kind of mistake I get:
Traceback (most recent call last):
File "~/dir1/dir1/wikt.py", line 15, in <module>
fStream = gzip.open(urlopen(url).read(), 'rb')
File "/usr/lib/python2.7/gzip.py", line 34, in open
return GzipFile(filename, mode, compresslevel)
File "/usr/lib/python2.7/gzip.py", line 89, in __init__
fileobj = self.myfileobj = __builtin__.open(filename, mode or 'rb')
TypeError: file() argument 1 must be encoded string without NULL bytes,
not str
Process finished with exit code 1
Greeting to all.
I am going to use the wiktionary dump for the purpose of POS tagging.
Somehow it stuck yet at the step of downloading. Here is my code
import nltk
from urllib import urlopen
from collections import Counter
import gzip
url =
'http://dumps.wikimedia.org/enwiktionary/latest/enwiktionary-latest-all-titles-in-ns0.gz'
fStream = gzip.open(urlopen(url).read(), 'rb')
dictFile = fStream.read()
fStream.close()
text = nltk.Text(word.lower() for word in dictFile())
tokens = nltk.word_tokenize(text)
Here is the kind of mistake I get:
Traceback (most recent call last):
File "~/dir1/dir1/wikt.py", line 15, in <module>
fStream = gzip.open(urlopen(url).read(), 'rb')
File "/usr/lib/python2.7/gzip.py", line 34, in open
return GzipFile(filename, mode, compresslevel)
File "/usr/lib/python2.7/gzip.py", line 89, in __init__
fileobj = self.myfileobj = __builtin__.open(filename, mode or 'rb')
TypeError: file() argument 1 must be encoded string without NULL bytes,
not str
Process finished with exit code 1
What is it >> in JavaScript?
What is it >> in JavaScript?
index is a number. I do not understand what is it >> in js.
setIndex: function(index) {
var i = this.index;
this.index = index >> 0; // ?????
if (this.index < 0) {
this.index = 0;
} else if (this.index >= this.config.items.length) {
this.index = this.config.items.length - 1;
}
return (i !== this.index);
}
index is a number. I do not understand what is it >> in js.
setIndex: function(index) {
var i = this.index;
this.index = index >> 0; // ?????
if (this.index < 0) {
this.index = 0;
} else if (this.index >= this.config.items.length) {
this.index = this.config.items.length - 1;
}
return (i !== this.index);
}
Thursday, 8 August 2013
Software to generate Blu-ray case spine mockups?
Software to generate Blu-ray case spine mockups?
I'm looking for some software, or maybe a Photoshop Action, which can
generate realistic Blu-ray case spine mockups, after I supply it with a
Blu-ray cover ...
I actually want to make a picture like this, using my own given covers:
I know of a software called IMANDIX which can generate 3D blur-ray case
mockups, but it doesn't do only spines ...
Anyone know of a software which does only spines ?
I'm looking for some software, or maybe a Photoshop Action, which can
generate realistic Blu-ray case spine mockups, after I supply it with a
Blu-ray cover ...
I actually want to make a picture like this, using my own given covers:
I know of a software called IMANDIX which can generate 3D blur-ray case
mockups, but it doesn't do only spines ...
Anyone know of a software which does only spines ?
how to alert after all images loaded?
how to alert after all images loaded?
im beginner in javascript i`m building javascript game and i want to alert
after all images loaded i tried this code but its not working
function loadEveryThing(){
var imgNumber = 0;
img1 = new Image();
img1.src= "1.png"
img1.onload = function(){
imgNumber =imgNumber+1;
}
img2 = new Image();
img2.src= "2.png"
img2.onload = function(){
imgNumber =imgNumber+1;
}
img3 = new Image();
img3.src= "3.png"
img3.onload = function(){
imgNumber =imgNumber+1;
}
if(imgNumber==3)alert("done")
}
im beginner in javascript i`m building javascript game and i want to alert
after all images loaded i tried this code but its not working
function loadEveryThing(){
var imgNumber = 0;
img1 = new Image();
img1.src= "1.png"
img1.onload = function(){
imgNumber =imgNumber+1;
}
img2 = new Image();
img2.src= "2.png"
img2.onload = function(){
imgNumber =imgNumber+1;
}
img3 = new Image();
img3.src= "3.png"
img3.onload = function(){
imgNumber =imgNumber+1;
}
if(imgNumber==3)alert("done")
}
What's the pythonic way to distinguish between a dict and a list of dicts?
What's the pythonic way to distinguish between a dict and a list of dicts?
So, I'm trying to be a good Python programmer and duck-type wherever I
can, but I've got a bit of a problem where my input is either a dict or a
list of dicts.
I can't distinguish between them being iterable, because they both are.
My next thought was simply to call list(x) and hope that returned my list
intact and gave me my dict as the only item in a list; alas, it just gives
me the list of the dict's keys.
I'm now officially out of ideas (short of calling isinstance which is, as
we all know, not very pythonic). I just want to end up with a list of
dicts, even if my input is a single solitary dict.
So, I'm trying to be a good Python programmer and duck-type wherever I
can, but I've got a bit of a problem where my input is either a dict or a
list of dicts.
I can't distinguish between them being iterable, because they both are.
My next thought was simply to call list(x) and hope that returned my list
intact and gave me my dict as the only item in a list; alas, it just gives
me the list of the dict's keys.
I'm now officially out of ideas (short of calling isinstance which is, as
we all know, not very pythonic). I just want to end up with a list of
dicts, even if my input is a single solitary dict.
How to get the Names of the columns in MYSQL
How to get the Names of the columns in MYSQL
I'm new to PHP and I want to get the column names of a table.The following
code doesn't return any errors, but it doesn't show any columns names
either.
Can anyone see what mistake I'm making please>
<?php
$q = "SELECT column_name FROM USER_TAB_COLUMNS WHERE table_name =
'!!mytablename!!'";
$real_q = mysql_query($q);
foreach ($r = mysql_fetch_row($real_q) as $taxokey => $taxovalue ) {
if ($taxokey != 'name') {
?>
<option value="<?php print($taxokey);?>"><?php
print($taxovalue);?></option>
<?php
}
}
?>
I'm new to PHP and I want to get the column names of a table.The following
code doesn't return any errors, but it doesn't show any columns names
either.
Can anyone see what mistake I'm making please>
<?php
$q = "SELECT column_name FROM USER_TAB_COLUMNS WHERE table_name =
'!!mytablename!!'";
$real_q = mysql_query($q);
foreach ($r = mysql_fetch_row($real_q) as $taxokey => $taxovalue ) {
if ($taxokey != 'name') {
?>
<option value="<?php print($taxokey);?>"><?php
print($taxovalue);?></option>
<?php
}
}
?>
How do other DNS servers find mine?
How do other DNS servers find mine?
I'm trying to learn as much as possible about DNS, and so far I've read
most of:
http://www.zytrax.com/books/dns/ch8/soa.html
and all of:
http://computer.howstuffworks.com/dns.htm
I understand that SOA and NS records contain info about the authoritative
name server for a domain, but as these are just DNS records, how does the
rest of the world even know where to get them?
I assume it starts at the top-level-domain (.COM .NET .ORG, etc) servers.
So they must contain a SOA record for my domain? If so, how does that get
there? I imagine only registrars like GoDaddy and Network Solutions are
able to update those? If they contain a SOA record, why does my DNS server
(that I host), need one also? I think there must be something, maybe in
the domain registration records (outside of DNS?), that I'm missing.
I think I've got a pretty good understanding of most parts of the DNS
system, after reading lots of articles.. but I haven't found any that
answer this part, in a way that I understand it.
For example, GoDaddy and Network Solutions both let me change different
options (in their web UI) to "host my own DNS server". If these options
remove them from the process, so DNS servers never need to query them
again, and instead query my server directly (this is what I want, no
dependency on GoDaddy/NS)... when I make these changes, what (at the DNS
level or otherwise) is GoDaddy/NS doing? Are they asking the
top-level-domain servers to update some DNS records for my domain?
I'm trying to learn as much as possible about DNS, and so far I've read
most of:
http://www.zytrax.com/books/dns/ch8/soa.html
and all of:
http://computer.howstuffworks.com/dns.htm
I understand that SOA and NS records contain info about the authoritative
name server for a domain, but as these are just DNS records, how does the
rest of the world even know where to get them?
I assume it starts at the top-level-domain (.COM .NET .ORG, etc) servers.
So they must contain a SOA record for my domain? If so, how does that get
there? I imagine only registrars like GoDaddy and Network Solutions are
able to update those? If they contain a SOA record, why does my DNS server
(that I host), need one also? I think there must be something, maybe in
the domain registration records (outside of DNS?), that I'm missing.
I think I've got a pretty good understanding of most parts of the DNS
system, after reading lots of articles.. but I haven't found any that
answer this part, in a way that I understand it.
For example, GoDaddy and Network Solutions both let me change different
options (in their web UI) to "host my own DNS server". If these options
remove them from the process, so DNS servers never need to query them
again, and instead query my server directly (this is what I want, no
dependency on GoDaddy/NS)... when I make these changes, what (at the DNS
level or otherwise) is GoDaddy/NS doing? Are they asking the
top-level-domain servers to update some DNS records for my domain?
Subscribe to:
Comments (Atom)