Saturday, 31 August 2013

Update to the database error when enter more than 1 value

Update to the database error when enter more than 1 value

i have a problem, the program just read the first entered Quantity value
in the program and apply it to all rows in database and the value of first
and second row are same, even though in the beginning, first and second
row value are different.
Note: The Database 1 until 1.3 and Program 1 until 1.2 are working
properly, i just want to show you to not confuse you later. My problem is
on Database 1.5 and Program 1.4 , Database 1.6 are just wanted to show
you, the Database supposed to be like that.
First of all, my database is like this:
Product Code || Quantity (Database 1)
0001 100
0002 150
And when i run the program and entered the first "Product Code" in first
row and want to change the first Quantity value to 25, so i just enter 75
in Quantity in the program at the first row like this:
Product Code || Quantity (Program 1, 0001 is at the **first row**)
0001 75
And when i click update, the database changed to this (it works fine):
Product Code || Quantity (Database 1.1)
0001 25
0002 150
When i change the first "Product Code" in first row to second "Product
Code" in first row and want to change the second Quantity value to 100, so
i just enter 50 in Quantity in the program in the first row like this:
Product Code || Quantity (Program 1.2, 0002 still at the **first row**)
0002 50
And when i click update, the database changed to this (it works fine):
Product Code || Quantity (Database 1.3)
0001 25
0002 100
But, when i enter the first "Product Code" in first row and second
"Product code in second row in my program like this:
Product Code || Quantity (Program 1.4, 0001 at **first row** and 0002 at
**second row**)
0001 10
0002 25
And when i click update, the database changed to this (it supposed to be
like Database below):
Product Code || Quantity (Database 1.6)
0001 15
0002 85
But instead of the Database above, it changed to this (it is not working
like i want):
Product Code || Quantity (Database 1.5)
0001 15
0002 15
So, it is like the second row at the database are being ignored and
changed to the same value like in the first row, when i enter both value
at the same time in the program.
Here is the code:
private void UpdateQuantity()
{
int codeValue = 0;
int index = 0;
List<int> integers = new List<int>();
foreach (var tb in textBoxCodeContainer)
{
if (int.TryParse(tb.Text, out codeValue))
{
integers.Add(codeValue);
}
}
using (OleDbConnection conn = new
OleDbConnection(connectionString))
{
conn.Open();
string commandSelect = "SELECT [Quantity], [Description],
[Price] FROM [Seranne] WHERE [Code] = @Code";
string commandUpdate = "UPDATE [Seranne] SET [Quantity] =
@Quantity WHERE [Code] IN(" + string.Join(", ", integers)
+ ")";
using (OleDbCommand cmdSelect = new
OleDbCommand(commandSelect, conn))
using (OleDbCommand cmdUpdate = new
OleDbCommand(commandUpdate, conn))
{
cmdSelect.Parameters.Add("Code",
System.Data.OleDb.OleDbType.Integer);
cmdSelect.Parameters["Code"].Value =
this.textBoxCodeContainer[index].Text;
cmdUpdate.Parameters.Add("Quantity",
System.Data.OleDb.OleDbType.Integer);
using (OleDbDataReader dReader =
cmdSelect.ExecuteReader())
{
while (dReader.Read())
{
if (textBoxQuantityContainer[index].Value != 0)
{
newVal =
Convert.ToInt32(dReader["Quantity"].ToString())
- textBoxQuantityContainer[index].Value;
cmdUpdate.Parameters["Quantity"].Value =
newVal;
int numberOfRows =
cmdUpdate.ExecuteNonQuery();
}
index += 1;
}
dReader.Close();
}
}
conn.Close();
}
}
Could you guys please help me? Thanks.

Arithmetic expression grammar in prefix notation (Java Cup)

Arithmetic expression grammar in prefix notation (Java Cup)

I'm writting a grammar for arithmetic expression in prefix notation.
However I have an issue when parsing negative numbers or substraction.
Grammar example is this:
precedence right +, -;
precedence right *, /;
precedence right uminus;
E ::= + E E
| - E E
| * E E
| / E E
| ( E )
| - E %prec uminus
| id
| digit
;
But if my input is - 5 4, it reduces 5 as E, next it reduces - E
(negative) and then parser gives me a syntax error at 4. The correct one
should be 5 as E, next 4 as E and then - E E as E. How can I solve this
problem using associativity? or do I need to rewrite my grammar?

JavaScript->CSS: display="";?

JavaScript->CSS: display="";?

In JavaScript, one can set the default display of an element by using the
following code outline:
whateverElement.style.display="";
If whateverElement's display was "none" when this code was run, it will
now be whatever it would be naturally, according to the browser's default
rendering.
If whateverElement was a DIV with no previous matched CSS rules that
define its display, when it's JavaScript display property is set to ""
(blank), its display would be defaulted to its natural, which is "block".
My problem is that I wish to use CSS3 animations by assigning a class to
them through JavaScript, some animations that make it necessary to know
the natural display of the element.
In Google Chrome Canary, I'm noticing that the display property "auto" is
non-existent.
Is there another way in which I can create CSS3 animations where I set the
display property to the "default" or "auto" display of an element?
Some examples...
div{display:inline;} //all divs to be displayed "inline"
div#specific{display:auto;} //#specific to be displayed BLOCK,
disregarding the previous CSS rule.

explain me a preg_match if clause please

explain me a preg_match if clause please

if(preg_match("/^[\w_.]+$/",stripslashes($_GET['key']))) {
$key = $wpdb->escape(stripslashes($_GET['key']));
}
assuming the key value is = be4e53680e6518cca701ec091258642f0740fe3d
can someone please explain me the if condition ? I`m confused on what
exactly it checks for

ERROR [nucleusNamespace.] Invalid attempt to resolve component '' in scope global. It is defined in scope prototype

ERROR [nucleusNamespace.] Invalid attempt to resolve component '' in scope
global. It is defined in scope prototype

I am getting the above mentioned error when i try to use the
GenericService.resolveName(java.lang.String pName) The similer error for
session scope as well. If i change the scope to 'global', things are
working as expected. But I need to have my component in prototype scope.
So what can i do..?

Miniprofiler gem generating a lot of 404 errors

Miniprofiler gem generating a lot of 404 errors

The Miniprofiler gem for rails is very handy. (github, railscast)
However, I am getting a lot of 404 errors in my application:
In the chrome console, tab network:
Failed to load resource: the server responded with a status of 404 (Not
Found) http://localhost.mysite.com/mini-profiler-resources/results
This page returns the following response: Request not found: - user 127.0.0.1
On every page, I have 9 of those requests. (so it clogs my logs, and it's
annoying). And 9 more show up every time I trigger an ajax request.
It seems that mini profiler is trying to evaluate the time of a request
that doesn't happen... How can I troubleshoot this situation ?

SQLite returning wrong data

SQLite returning wrong data

I have 22 rows of data. But after running this query
select
AUTHORS_ABSTRACT.ABSTRACTSITEM_ID,
ABSTRACT_AFFILIATION.AFFILIATION_NUMBER,
AUTHORS_AFFILIATE.ABSTRACTAUTHOR_ID
from
ABSTRACT_AFFILIATION,
AUTHORS_AFFILIATE,
AUTHORS_ABSTRACT
where ABSTRACT_AFFILIATION._id =
AUTHORS_AFFILIATE.ABSTRACTAFFILIATION_ID
and AUTHORS_ABSTRACT.ABSTRACTAUTHOR_ID = AUTHORS_AFFILIATE.ABSTRACTAUTHOR_ID
ORDER BY AUTHORS_ABSTRACT.ABSTRACTSITEM_ID ASC
and If you need the .db file here is my db file . So, after running this
query I get 36 rows of data.
So, my question is Why it returns 36 rows, even 22 rows data exist in the
database.

Friday, 30 August 2013

Android Log.X not printing stacktrace

Android Log.X not printing stacktrace

e.printStackTrace() works fine (i.e. prints my stacktrace to stderr) but
Log.X fails to print a stacktrace at all.
For example:
} catch (IOException e) {
Log.e("Network", "Exception", e);
e.printStackTrace();
}
Output:
08-31 03:46:21.992: W/Network(13238): Exception
08-31 03:46:22.092: W/System.err(13238): java.net.UnknownHostException:
Unable to resolve host "...": No address associated with hostname
08-31 03:46:22.204: W/System.err(13238): at
java.net.InetAddress.lookupHostByName(InetAddress.java:394)
08-31 03:46:22.222: W/System.err(13238): at
java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
08-31 03:46:22.222: W/System.err(13238): at
java.net.InetAddress.getAllByName(InetAddress.java:214)

Thursday, 29 August 2013

Minimum height by css in html

Minimum height by css in html

I'm creating web site layout.

This is label3 css :
background-color:#c4efd5;
min-height:368px;
height:100%;
I want to set minimum height of lable3 to 368px even it does not contain
any data. And when I insert image height = 450px, label3 will be re-size
height to 450px.
I'm using min-height to do that, but it did not display as I expected.
Any answer will be appreciate. Thanks you.

Database operation in one go (one transcation)

Database operation in one go (one transcation)

I am working on a driver-booking management system. What I want to do is
that I need to add a driver in booking table (which means assigning a
booking to driver). Before that I need to check whether or not booking
record has driver record associated with or not (booking is assigned or
not), If yes then do nothing.
It works fine with one user doing this. But issue comes with multiple
users doing this on same record, same time.
How to handle this situation. I know about @transactional annotation. Is
that the right solution? Should I apply this on single method rather than
on my booking Assigning Service?
Using sync block would slow down processing alot, so currently I am
against this option

Perl regex: string literal containing metacharacters as variable for match expression

Perl regex: string literal containing metacharacters as variable for match
expression

I need to define a string literal as a variable which will be later used
as a match expression.
I want my variable $regex_op to match the string alt_id: ID: as well as
the string id: ID:.
my $regex_op = "(id|alt_id):\sID:";
my $searchword = "4";
Later on, I'm joining the variables in a regular expression:
/^($regex_op)($searchword)/m
Unfortunately, the whitespace wildcard \s is an "Unrecognized escape \s
passed through". The problem apparently consists in the string literal
containing backslashes (which are needed as part of the regex later on!).
Any ideas how to solve this?

Wednesday, 28 August 2013

Make vectors of unequal length equal in length by reducing the size of the largest ones

Make vectors of unequal length equal in length by reducing the size of the
largest ones

I am reading 6 columns from a .txt file to 6 vectors.
Sometimes some vectors are one element larger than others, so I need to
check if they are all of equal length, and if not, I have to find which
ones are the largest and delete their last element. I think I should be
able to do this without loops. I was originally thinking of using find in
combination with isequal but isequal only returns a logical, and does not
provide any information on which vectors are the largest.

c# - How to export gridview selected column to excel?

c# - How to export gridview selected column to excel?

I want to export gridview selected column to excel
I'm following this link to achieve this but in the below code
Where to call that ViewState["ds"]?
for loop not working it comes out because count is '0'
Code :
protected void btnExcel1_Click(object sender, ImageClickEventArgs e)
{
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition",
"attachment;filename=GridViewExport.xls");
Response.Charset = "";
Response.ContentType = "application/vnd.ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
EmpMasterGrid.AllowPaging = false;
EmpMasterGrid.DataBind();
EmpMasterGrid.HeaderRow.Style.Add("background-color", "#FFFFFF");
EmpMasterGrid.HeaderRow.Cells[0].Style.Add("background-color",
"green");
EmpMasterGrid.HeaderRow.Cells[1].Style.Add("background-color",
"green");
EmpMasterGrid.HeaderRow.Cells[2].Style.Add("background-color",
"green");
EmpMasterGrid.HeaderRow.Cells[3].Style.Add("background-color",
"green");
EmpMasterGrid.HeaderRow.Cells[4].Style.Add("background-color",
"green");
EmpMasterGrid.HeaderRow.Cells[5].Style.Add("background-color",
"green");
EmpMasterGrid.HeaderRow.Cells[6].Style.Add("background-color",
"green");
ArrayList arr = (ArrayList)ViewState["ds"];
EmpMasterGrid.HeaderRow.Cells[0].Visible = Convert.ToBoolean(arr[0]);
EmpMasterGrid.HeaderRow.Cells[1].Visible = Convert.ToBoolean(arr[1]);
EmpMasterGrid.HeaderRow.Cells[2].Visible = Convert.ToBoolean(arr[2]);
EmpMasterGrid.HeaderRow.Cells[0].Visible = Convert.ToBoolean(arr[3]);
EmpMasterGrid.HeaderRow.Cells[1].Visible = Convert.ToBoolean(arr[4]);
EmpMasterGrid.HeaderRow.Cells[2].Visible = Convert.ToBoolean(arr[5]);
EmpMasterGrid.HeaderRow.Cells[2].Visible = Convert.ToBoolean(arr[6]);
EmpMasterGrid.HeaderRow.Cells[0].FindControl("chkCol0").Visible =
false;
EmpMasterGrid.HeaderRow.Cells[1].FindControl("chkCol1").Visible =
false;
EmpMasterGrid.HeaderRow.Cells[2].FindControl("chkCol2").Visible =
false;
EmpMasterGrid.HeaderRow.Cells[3].FindControl("chkCol3").Visible =
false;
EmpMasterGrid.HeaderRow.Cells[4].FindControl("chkCol4").Visible =
false;
EmpMasterGrid.HeaderRow.Cells[5].FindControl("chkCol5").Visible =
false;
EmpMasterGrid.HeaderRow.Cells[6].FindControl("chkCol6").Visible =
false;
//Here condition fails bcoz count is 0
for (int i = 0; i < EmpMasterGrid.Rows.Count; i++)
{
GridViewRow row = EmpMasterGrid.Rows[i];
row.Cells[0].Visible = Convert.ToBoolean(arr[0]);
row.Cells[1].Visible = Convert.ToBoolean(arr[1]);
row.Cells[2].Visible = Convert.ToBoolean(arr[2]);
row.Cells[3].Visible = Convert.ToBoolean(arr[3]);
row.Cells[4].Visible = Convert.ToBoolean(arr[4]);
row.Cells[5].Visible = Convert.ToBoolean(arr[5]);
row.Cells[6].Visible = Convert.ToBoolean(arr[6]);
row.BackColor = System.Drawing.Color.White;
row.Attributes.Add("class", "textmode");
if (i % 2 != 0)
{
row.Cells[0].Style.Add("background-color", "#C2D69B");
row.Cells[1].Style.Add("background-color", "#C2D69B");
row.Cells[2].Style.Add("background-color", "#C2D69B");
row.Cells[3].Style.Add("background-color", "#C2D69B");
row.Cells[4].Style.Add("background-color", "#C2D69B");
row.Cells[5].Style.Add("background-color", "#C2D69B");
row.Cells[6].Style.Add("background-color", "#C2D69B");
}
}
EmpMasterGrid.RenderControl(hw);
string style = @"<style> .textmode { mso-number-format:\@; }
</style>";
Response.Write(style);
Response.Output.Write(sw.ToString());
Response.End();
}
Any ideas? Thanks in advance

Which is the better syntax while including a file in PHP?

Which is the better syntax while including a file in PHP?

Some people include files like this:
include ('file.php');
and some people include files like this:
include 'file.php';
I think here the use of brackets is completely unnecessary. What are your
views? Which style is better and why?

Tuesday, 27 August 2013

preg_replace Function in PHP

preg_replace Function in PHP

I'm using preg_replace function to remove a list of stop words. Currently,
I have an array containing a lst of stop words. As the parameter for
preg_replace I use this as the first argument (i.e,
preg_replace(^$stopwordlist$, '',$string) As you can see I'm also using ^$
as I need to match word exactly.However I'm getting the following error
syntax error, unexpected '^', expecting ')' in
Thanks

Powershell Regular Expression?

Powershell Regular Expression?

So i have a log files that contains list of file that was copied from 1
folder to another folder.
For example,
12 Aug 17:23:51 C:\Users\Folder_1\File1.exe move to
D:\Users\Folder_1\File1.exe 12 Aug 17:24:33 C:\Users\Folder_2\File2.xml
move to D:\Users\Folder_1\File2.xml
so i wanted to to extract the 2 paths in the above line and write out into
another text file.
For example,
C:\Users\Folder_1\File1.exe D:\Users\Folder_1\File1.exe
I'm not sure how do i write the regular expression here. What i wanted to
achieve in the regex pattern is say C Drive, ignore the length of the
path, and exe files only. Tried something like "(C:\)(.exe)" , doesn't
work.
I would appreciate also if any1 can provide me with a list of special
characters for regex and their uses. For example /d means decimal /D not
Decimal etc. I still can't quite figure out what /< /> /b ? ! character
means though i still saw post of people using it.

Framework + DB + Server + Hardware?

Framework + DB + Server + Hardware?

I notice that I used the google translator for this question.
I have a project in mind. Perhaps not very large, but in order to learn.
I would like to create a social network, twitter style. People could post
and comment on it, change your profile picture, etc.
For a few weeks, I implemented a part with Symfony2 (PHP) + Bootstrap
(CSS) + MongoDB.
I used several symfony bundles such as FOS, but hey noticed that on many
occasions I had to reinvent the wheel (maybe for my ignorance) ...
I was reading about Ruby on Rails, and I was in love. In view is very
similar to twig, and models is easier than doctrine (which is not
difficult).
Going to the point.
What do you recommend to develop?
Ruby is a good candidate? What database do you recommend? (I think NoSQL)
Speaking in terms of hardware / server:
Debian 7 or CentOS? (Never used CentOS)
Tale with little money, and I'm the only effort in this project.
Eh just purchased the RAM (haha), but the following features are the ones
that I have in mind.
Intel Ivy Bridge Core i3 3220 2GB 1600Mhz Ram (for now) 1TB SATA3
(recommend SSD?) Asus P8B75-V Gen3

Distinct Clause in an SQL Query

Distinct Clause in an SQL Query

I have a table named MediaGenT in my SQL Database that has 425000 records.
However the column name mg_medianum has duplicate entries. For example
mg_medianum = '858' has 10 different records but I am only interested in
the most recent record which can be ordered by mg_createdate.
When I do this I get 425000 records:
Select * from MediaGenT
Order By mg_createdate;
When I do this I get 89000 records (correct but only shows one column):
Select distinct mg_medianum from MediaGenT
Order by mg_createdate;
To sum up what I need is one query that shows every column of the 89000
records only displaying the most recent distinct mg_medianum based ordered
by mg_createdate. I'm having trouble coming up with the syntax for that
kind of query.

Get value of a param in a string using java

Get value of a param in a string using java

I have string variable String temp="acc=101&name=test"; and now how to get
the value of name param from temp string.

Monday, 26 August 2013

Error - Action in lexer rule 'xxxx' must be last element of single outermost alt

Error - Action in lexer rule 'xxxx' must be last element of single
outermost alt

When I upgraded from Antlr 3 to Antlr 4, I removed all the syntactic
predicates in the grammar. But when I changed it, I am getting an error as
mentioned in the title.
This is the changed code
NUMBER
:(
'0'..'9' ('.' '0'..'9'+)?
| '.' '0'..'9'+
)
(
E
(
M { $type = EMS; }
| X { $type = EXS; }
)
| P
(
X
| T
| C
)
{ $type = LENGTH; }
| C M { $type = LENGTH; }
| M
(
M { $type = LENGTH; }
| S { $type = TIME; }
)
| I N { $type = LENGTH; }
| D E G { $type = ANGLE; }
| R A D { $type = ANGLE; }
| S { $type = TIME; }
| K? H Z { $type = FREQ; }
| IDENT { $type = DIMENSION; }
| '%' { $type = PERCENTAGE; }
| // Just a number
)
;
This is the error I am getting.
I saw an answer to this question here. But I was unable to grasp what it
meant. Please give me some guidance.

javascript form validation radio buttons

javascript form validation radio buttons

I trying to do some validation on a form with radio buttons in it. I can
get the text elements to work fine but the radio buttons don't seem to
like me.
function validateAll(theForm)
{
var err=0;
var fields;
for (var i=0; i<theForm.elements.length; i++)
{
fields =theForm.elements[i];
if(fields.type == "text" || fields.type == "textarea")
{
if(fields.value == "" || fields.value == null){
err++;
validateText(fields.id);
}
}
else if(fields.type == "radio"){
validateRadio(fields)
}
}
if(err > 0){return;}else{document.myform.submit();}
}
function validateText(id)
{
var x=document.forms["myForm"][id].value;
if (x==null || x=="")
{
var text = id+"Text";
document.getElementById(text).style.visibility ="visible";
return;
}else {
var text = id+"Text";
document.getElementById(text).style.visibility="hidden";
return;
}
}
function validateRadio(radios)
{
var id = radios.id;
var text;
for (i = -1; i < radios.length; ++i)
{
if (radios[i].checked) {
text = id+"Text";
document.getElementById(text).style.visibility="hidden";
return true
}}
text = id+"Text";
alert(text);
document.getElementById(text).style.visibility ="visible";
return false;
}
I am just calling it with a input button. Any ideas on why its not working?

Use variable to refer to contents of hash table

Use variable to refer to contents of hash table

I'm trying to refer to a hash table by name that is passed in via a
parameter.
Ex.
TestScript.Ps1 -specify TestDomain1,TestDomain2
param(
[string[]]$specify
)
$TestDomain = @{"Name" : "Test1", "Hour" : 1}
$TestDomain = @{"Name" : "Test2", "Hour" : 2}
foreach($a in $specify)
{
write-host $($a).Name
#This is where I would expect it to return the Name value contained in
the respective
# hash table. However when I do this, nothing is being returned
}
Is there another way to be doing this to get these values? Is there a
better method rather than using the hash tables? Any help would be
appreciated.

Adding 'freehand' data to raster mapping in QGIS – gis.stackexchange.com

Adding 'freehand' data to raster mapping in QGIS – gis.stackexchange.com

Having just worked out how to import raster mapping into QGIS at the
correct scale, I'd like to now add useful information to the map like
marked routes, labels etc. How can I do this in a 'freehand' …

create image from blob storage

create image from blob storage

i need to create an image from the html file which is stored in blob azure
storage.
CloudStorageAccount account = new CloudStorageAccount(credentials, true);
CloudBlobClient client = new
CloudBlobClient(account.BlobEndpoint.AbsoluteUri,
account.Credentials);
CloudBlobContainer container2 =
client.GetContainerReference(absolutePath);
CloudBlob blob = container.GetBlobReference(filename);
if (absolutePath != null)
{
bmp = (Bitmap)System.Drawing.Image.FromFile(blob.Name) , true);
}
but i got an error of that file not found exception.
plz help.
i need to convert html page into an image and then store back to blob
storage.
Regards, Brijesh Vaidya
Thanks gaurav, i applied authentication and azure library to get blob
file, but when my path is https://abc.core.windows.net/ds/file.html" and
if i will generate the image file from the html file path supplied in the
following line: bmp = (Bitmap)System.Drawing.Image.FromFile(blob.Name) ,
true);
i got error.

search command for packages in Ubuntu terminal to search updates and patches of the package specifically – askubuntu.com

search command for packages in Ubuntu terminal to search updates and
patches of the package specifically – askubuntu.com

Can I know what is the command to search any package using the terminal,
if I only know the name of the Software like, if I want to search VLC or
JDK,JRE.. etc If I do not know what is the url where …

Sunday, 25 August 2013

You don't have permission to access /marcon/assets/images/pic.jpg in apache php

You don't have permission to access /marcon/assets/images/pic.jpg in
apache php

I am getting this error You don't have permission to access
/marcon/assets/images/pic.jpg in apache php on my local Fedora 17,
php,mysql and apache(not Xampp installation). This error is occuring for
any new files that I am copying to the directory.The older files
/marcon/assets/images/header.jpg are accessible just fine. I checked the
permissions and they are 777 (now) but still doesn't work. This is a very
wierd error. The subdirectory and other images work fine. Just the newer
files don't work
This happens when I embed it as an image as well as when I access it
directly. It works for all other files in the directory. Not just the
newer ones

amsart maketitle problem

amsart maketitle problem

I am editing a paper using amsart documentclass. However, the
\maketitle
command does not give me the author and abstract. My codes are here:
\documentclass[12pt]{amsart}
\usepackage{amsmath,amsfonts,amssymb,amsthm,latexsym}
\usepackage{enumerate}
\usepackage{cancel}
\usepackage{color}
\usepackage{todonotes}
\usepackage{graphicx}
\usepackage{epstopdf}
\usepackage{titling}
\usepackage{verbatim}
\begin{document}
\title{MyTitle}
\author{MyAuthor}
\begin{abstract}
MyAbstract
\end{abstract}
\maketitle
Text
\end{document}
And the resulting file only have "MyTitle" as title and "Text" as text.
Author and abstract information are missing.
How can I add adstract and authors by using maketitle?

[ Primary & Secondary Education ] Open Question : So its the first day of school and im going to 6th so im new to the school how do i act?

[ Primary & Secondary Education ] Open Question : So its the first day of
school and im going to 6th so im new to the school how do i act?

New 6th

Make if statement

Make if statement

import java.util.Scanner;
public class Random {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Welcome. Please enter three numbers!");
System.out.println("Enter your first number: ");
int x = scan.nextInt();
System.out.println("Enter your second number: ");
int y = scan.nextInt();
System.out.println("Enter your third number: ");
int u = scan.nextInt();
int total = x + y + u;
System.out.println("The total of all your choosen numbers are: " +
total);
if() {
System.out.println("Sorry, you cant print out a double value.");
}
}
}
I want to make the if statement to print out an error if the user inputs a
double value, such as 2,7. What should I do?

Database related Query

Database related Query

I want to create an Encyclopedia that should be online. I am using html to
create web pages, and php as a backend. But the problem is in database
creation. I have been told that the encyclopedia will have only
information that will be stored on a server in a text file or document,
but where is the use of DATABASE since the information will not be
related, as tables are in a database, beacause every data that is
available in an encyclopedia cannot be linked to each other like tables
are liked in a database. There will not be any tables.So, exactly How can
I make it work, add information of the encyclopedia to database, add the
text files to database or connect links in the database. (I know I am not
very clear but if someone can understand then please answer my question
its very urgent) Thank You.

Page not found 404

Page not found 404

I am beginner in PHP, and When I am trying to run my first application ,
it does not run and the browser opens "Not Found Page 404", may the
problem form setup the application with server, any help please ?
Best Wishes , Yazeed

Saturday, 24 August 2013

How would I modify this ffmpeg command to include 4 videos?

How would I modify this ffmpeg command to include 4 videos?

Say I had 4 videos with the following names:
Main Video.mov
Top Left.mov
Top Right.mov
Top Mid.mov
and I wanted to have "Main Video" play with a picture in picture effect
with boxes of videos playing in the top left, top right and top mid. Each
box would have the video that is similarly named.
This command will do picture in picture for 2 videos, with one video in
the lower right.
ffmpeg -i 2013-07-31\ 231548.MOV -vf "movie=2013-07-31\ 231722.MOV,
scale=iw/5:ih/5 [small]; [in][small] overlay=main_w*0.77:main_h*0.77
[out]" -strict -2 output.mov
Can someone help me update this command to work with the 4 files I
mentioned above?
Thanks

HP Product Research on Activity Log

HP Product Research on Activity Log

I'm seeing an item on my activity monitor called 'HP Product Research.' I
assume it's associated with some HP Printer drivers that I no long need,
and have have removed, but this tracker hanging out.
Any ideas on how to get rid of this thing?

Warning when compiling with clang++

Warning when compiling with clang++

When I compile the code:
#include <iostream>
#include <string.h>
using namespace std;
int main(void) {
string m1;
cout<< "enter your name: "<<endl;
getline(cin,m1);
cout << "Your name is: " << m1 << endl;
return EXIT_SUCCESS;
}
It give the following warning:
type of symbol `_main' changed from 32 to 512 in
>C:\Users\KDesktop\AppData\Local\Temp\cc7XPBuL.o
Secondly, the compiler does generate an .exe file, but whenever I run it,
the program crashes immediately. Can someone help me with this issue.
Thank you

Calling an external command in GO

Calling an external command in GO

How can I call an external command in GO? I need to call an external
program and wait for it to finish execution. before the next statement is
executed.

Can't use System.Windows.Forms;

Can't use System.Windows.Forms;

I have referenced System.Windows.Forms, but Xamarin will not let me use
it. It only allows me to use Windows.Input and Markup.

Ransack search not working if there is 'space' in search term

Ransack search not working if there is 'space' in search term

I am using ransack for search in my rails 3.2 application using postgres
as database.
I have a Invoice model and every invoice belongs_to a buyer. Below is my
search form in index page.
views/invoices/index.html.erb
<%= search_form_for @search do |f| %>
<%= f.text_field :buyer_name_cont %>
<%= f.submit "Search"%>
<% end %>
And here is my controller code.
controllers/invoices_controller.rb
def index
@search = Invoice.search(params[:q])
@invoices=@search.result(:distinct => true).paginate(:page =>
params[:page], :per_page => GlobalConstants::PER_PAGE )
respond_to do |format|
format.html # index.html.erb
format.json { render json: @invoices }
end
end
Let's say a invoice is there of a buyer having name "Bat Man".
If I search "Bat", I get the invoice in results. Again if I search "Man",
I get the invoice in results. But if I search "Bat Man", I don't get the
invoice in results.
I know it might be something trivial but I am not able to resolve.
Please help.
Thanks.

How to show remote html in ExtJs Window?

How to show remote html in ExtJs Window?

I want to show remote html file into ExtJs Window. I do:
var global_iframe_id = 0;
Ext.ux.IFrameComponent = Ext.extend(Ext.BoxComponent, {
onRender : function(ct, position) {
global_iframe_id += 1;
this.el = ct.createChild({tag: 'iframe', id: 'iframe-'+
global_iframe_id, frameBorder: 0, src: this.url});
}
});
var infoWin = new Ext.Window({
id: 'infoWin',
layout: 'fit',
title:'Ñïðàâêà',
autoScroll:false,
width:window.innerWidth*0.9,
height:window.innerHeight*0.9,
items: [
new Ext.Panel({
layout:'fit',
items: [ new Ext.ux.IFrameComponent({
url:url_servlet+'/Info.html' }) ]
})
]
});
And its work fine. But when i close window and open it again i get error:
TypeError: this.manager is undefined
Maybe i chose wrong way to show html file?

Friday, 23 August 2013

HTTPS .htaccess Rewrite for parked domain

HTTPS .htaccess Rewrite for parked domain

I have two domain 'domain.in' and 'domain.com'. The domain.in is parked to
domain.com. I have SSL for domain.com So what I need is
1) If the user visit www.domain.com it should redirect to
https://www.domain.com
2) If the user visit www.domain.in it should use http.
I know this can done through '.htaccess' file.
Can any one help me for this issue ?

php mail form w/upload option not working correctly

php mail form w/upload option not working correctly

I am trying to create a quote form with basic contact info, checkbox
option and an option to upload image then email complete form to my email
address. I have the html portion but am have a problem with the php part.
When form emails to me only sends contact info and fails to send which
option is check with checkbox and image that was uploaded. Here is the
code for the form html portion:
<form action="quote_form.php" method="post" enctype="multipart/form-data"
name="QuoteForm" id="QuoteForm"
onsubmit="MM_validateForm('Name','','R','LastName','','R','email','','RisEmail','Phone','','RisNum','textfield','','RisNum');MM_validateForm('Name','','R','LastName','','R','Phone','','RisNum','email','','RisEmail','info-about-item','','R');return
document.MM_returnValue">
<p>
<label for="name">Name*</label>
<input name="name" type="text" id="name" size="60" maxlength="60" />
</p>
<p>
<label for="phone">Phone #*</label>
<input name="phone" type="text" id="phone" size="30"
maxlength="30" />
</p>
<p>
<label for="email">Email* </label>
<input name="email" type="text" id="email" size="30"
maxlength="30" />
</p>
<p>
<label>
<input type="checkbox" name="CheckboxGroup1" value="pawn"
id="CheckboxGroup1" />
Pawn</label>
<br />
<label>
<input type="checkbox" name="CheckboxGroup1" value="buy"
id="CheckboxGroup1" />
Buy</label>
<br />
</p>
<p><br /><br />
<span style="font-style: italic">(the more information the better
--- description i.e. brand, model and condition of
item.)</span></p>
<p>
<textarea name="comments" id="comments" cols="50"
rows="10"></textarea>
</p>
<p>
<label for="file">Select File To Upload*</label>
<input type="file" name="file" id="file" size="30" maxlength="30" />
</p>
<p>
<input type="submit" name="submit" id="sumbit" value="Submit" />
<input name="reset" type="reset" id="reset" value="Reset Form" />
</p>
<p>
<input name="recipient" type="hidden" id="recipient"
value="isabelpolanco23@gmail.com" />
<input name="redirect" type="hidden" id="redirect"
value="thankyou-pg.html" />
<br />
</p>
</form>
And here is the php portion:
<?php
if(isset($_POST['email'])) {
$email_to = "isabelpolanco23@gmail.com";
$email_subject = "Quote Form";
function died($error) {
echo "We are very sorry, but there were error(s) found with the
form you submitted. ";
echo "These errors appear below.<br /><br />";
echo $error."<br /><br />";
echo "Please go back and fix these errors.<br /><br />";
die();
}
if ($_FILES["file"]["error"] > 0)
{
echo "Error: " . $_FILES["file"]["error"] . "<br>";
}
else
{
echo "Upload: " . $_FILES["file"]["name"] . "<br>";
echo "Type: " . $_FILES["file"]["type"] . "<br>";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
echo "Stored in: " . $_FILES["file"]["tmp_name"];
}
if(!isset($_POST['name']) ||
!isset($_POST['email']) ||
!isset($_POST['phone']) ||
!isset($_POST['comments'])) {
died('We are sorry, but there appears to be a problem with the
form you submitted.');
}
$name = $_POST['name']; // required
$email_from = $_POST['email']; // required
$phone = $_POST['phone']; // not required
$comments = $_POST['comments']; // required
$servicetype = $_POST['servicetype'];
if(isset($servicetype)) {
$mail->body .= "servicetype: \r\n";
foreach($_POST["servicetype"] as $value) {
$servicetype .= "$value\n";}
}
$error_message = "";
$email_exp = '/^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/';
if(!preg_match($email_exp,$email_from)) {
$error_message .= 'The Email Address you entered does not appear to be
valid.<br />';
}
$string_exp = "/^[A-Za-z .'-]+$/";
if(!preg_match($string_exp,$name)) {
$error_message .= 'The Name you entered does not appear to be
valid.<br />';
}
if(strlen($comments) < 2) {
$error_message .= 'The Comments you entered do not appear to be
valid.<br />';
}
if(strlen($error_message) > 0) {
died($error_message);
}
$email_message = "Form details below.\n\n";
function clean_string($string) {
$bad = array("content-type","bcc:","to:","cc:","href");
return str_replace($bad,"",$string);
}
$email_message .= "Name: ".clean_string($name)."\n";
$email_message .= "Email: ".clean_string($email_from)."\n";
$email_message .= "Comments: ".clean_string($comments)."\n";
$email_message .= "Pawn: ".clean_string($servicetype)."\n";
$email_message .= "Buy: ".clean_string($servicetype)."\n";
$headers = 'From: '.$email_from."\r\n".
'Reply-To: '.$email_from."\r\n" .
'X-Mailer: PHP/' . phpversion();
@mail($email_to, $email_subject, $email_message, $headers);
$allowedExts = array("gif", "jpeg", "jpg", "png");
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp);
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/jpg")
|| ($_FILES["file"]["type"] == "image/pjpeg")
|| ($_FILES["file"]["type"] == "image/x-png")
|| ($_FILES["file"]["type"] == "image/png"))
&& ($_FILES["file"]["size"] < 20000)
&& in_array($extension, $allowedExts))
{
if ($_FILES["file"]["error"] > 0)
{
echo "Error: " . $_FILES["file"]["error"] . "<br>";
}
else
{
echo "Upload: " . $_FILES["file"]["name"] . "<br>";
echo "Type: " . $_FILES["file"]["type"] . "<br>";
echo "Size: " . ($_FILES["file"]["size"] / 3024) . " kB<br>";
echo "Stored in: " . $_FILES["file"]["tmp_upload"];
}
}
else
{
echo "Invalid file";
}
?>
<?php
header("Location:thankyou-pg.html");
exit;
?>
<?php
}
?>

Calculating this quotient?

Calculating this quotient?

What is the quotient of the algebraic Groups $GL_n$ by $Sp_n$ equal to? I
was conisering a different example and would use the universal property to
establish it, but I wasn't certain what it should equal to a-priori.

Load image from website

Load image from website

I am trying to add some chemical structure images to some plots I have
created. I am using the ACToR database to access the chemical structures.
For example:
http://actor.epa.gov/actor/image?format=png%3Aw250%2Ch250&casrn=80-05-7
The nice thing about this site is you can change the size and the chemical
within the url, so I can automate grabbing the images. My hope was to
store an object containing CAS numbers, then iterate through the CAS
numbers to make the plots.
For example:
library(png)
casnums <- ("80-05-7","77-40-7","1478-61-1")
image.list <- list()
for(cas in casnums){
image.list[[cas]] <-
readPNG(paste0("http://actor.epa.gov/actor/image?format=png%3Aw1000%2Ch1000&casrn=",cas))
}
I have tried using readPNG from the png package, and tried to use the
rgdal package as well. Unfortunately, as far as I can tell, ACToR will
only generate the images in a png or jpeg format - so I cannot use the
grImport package for reading vector images.
I am really hoping to find a solution where I do not have to manually
download each image - there are a lot of them. I would be open to a
solution where R goes and dowloads the images to a folder, then I could
use something like the png package, or the rgdal package to load the image
and plot them.

ATI Graphics Card detected as different card Ubuntu 12.04 LTS

ATI Graphics Card detected as different card Ubuntu 12.04 LTS

I ran the codesudo lshw -c display to get the model of my graphics card
that I am using. It showed Whistler 6600M series along with my Intel HD
Graphics. I have switchable graphics. But my graphics card is HD 6750M.
Why would it be shown differently and how to rectify this?

Breaking down a complex story at project start

Breaking down a complex story at project start

I'm trying to get to grips with agile project management (with Pivotal
Tracker) but keep finding myself running into walls when trying to define
the first few stories of a project. Take for example this very simple
story:
"A user should be able to tag a product"
Assuming I've already defined "product" elsewhere, this story would
possibly involve writing a polymorphic tagging system under the hood, on
completion of that system id be able to finally add the ability to tag a
product.
My problem is with the amount of work hidden in this story. I can define
tasks to get the story done but stories as a whole are supposed to be 1-2
days work? I don't feel right about the story just revealing the tip of
the iceberg but that's the only part that relates to the User.
How do you overcome this kind of thing? What are the best practices?

Thursday, 22 August 2013

System.TimeZoneNotFoundException on ViewPage

System.TimeZoneNotFoundException on ViewPage

I have created a view using Servicestack.Razor. On the view page I am
trying to get the session using following code.
var session = GetSession<AuthUserSession>();
When I put this code on the view page, I get following error:
System.TimeZoneNotFoundException
Exception of type 'System.TimeZoneNotFoundException' was thrown.
Description: HTTP 500.Error processing request.
Details: Non-web exception. Exception origin (name of application or
object): mscorlib.
StackTrace is as below:
Exception stack trace:
at System.TimeZoneInfo.get_Local () [0x00000] in <filename unknown>:0
at ServiceStack.Text.Common.DateTimeSerializer..cctor () [0x00000]
in <filename unknown>:0
Is this a bug in Servicestack.Text? How can I solve this?
Note: I am using Mono 3.0.10 on Ubuntu 12.10

SOAP Error on Loading

SOAP Error on Loading

I just want to ask what are the possible reason that could lead to this
error:
This page contains the following errors:
error on line 1 at column 37: Extra content at the end of the document
Below is a rendering of the page up to the first error.
It occurs when loading the response of my soap webservice using VB.

Play framework bulk update

Play framework bulk update

I am trying to get list of tasks and let user update any of them before
saving into DB.My code is something like this
#{form @Project.saveTasks()}
<table>
<thead>
<tr>
<th>Tasks</th>
</tr>
</thead>
<tbody>
#{list items:tasks,as:'task'}
<tr>
#{form @Task.updateTask(task.id)}
<td>${task.name}</td>
#{/form}
</tr>
#{/list}
</tbody>
</table>
<input type="submit" class="btn btn-success" value="Done">
#{/form}.......
How can get tasks object list again so i can update in DB?

Qt PushButton Hover/Pressed icons

Qt PushButton Hover/Pressed icons

I'm beginning in Qt, and I want to set a QPushButton to a different icon
whenever somebody hovers the mouse over it. Here's my code so far:
#include <QPushButton>
QPushButton *button = new QPushButton(mainWindow);
button->setIcon(QIcon(":/icons/button.png"));
button->setIconSize(QSize(128,56);
button->setGeometry(0,0,128,56);
I've heard something about stylesheets, but I have no clue how to use them
and all the documentation is very confusing for me. Could somebody explain
how I can set the icon to ":/icons/button-hover.png" whenever the mouse
hovers on the button? Also, unless it's like exactly the same for when
it's pressed, it would be great if you could show me that too.
Thanks in advance :)

Use Star (*) with mysql inner join?

Use Star (*) with mysql inner join?

I have always done inner joins that look like this
SELECT Orders.OrderID, Customers.CustomerName, Orders.OrderDate
FROM Orders
INNER JOIN Customers
ON Orders.CustomerID=Customers.CustomerID;
Where you specify each row you want. I am currently working with a table
that has 50 rows however and I don't want to type all these SQL joins with
all the rows, is there a way to say "select * from Orders, then give me
Customers.CustomerName join on ...." instead of specifying every row from
the first table?

Exception instead of Compiler Error

Exception instead of Compiler Error

I expected this program to give me Compile error but it compiled
successfully and I got a runtime exception while running it.
class substr11
{
public static void main(String args[])
{
String s = "abcde";
System.out.println(s.substring(1,-1));
}
}
The compiler error should be able to parse (string is initialized in the
body itself) and find out that this string operation would result in
compile error right ?. Can someone tell me why it did not throw compile
error ?
Exception in thread "main" java.lang.StringIndexOutOfBoundsException:
String ind ex out of range: -2 at java.lang.String.substring(Unknown
Source) at substr11.main(substr11.java:9)

Wednesday, 21 August 2013

how to connect terminal to internet

how to connect terminal to internet

I have to use proxy servers to connect to internet. I have set all proxies
in my system proxy settings. Now I can connect to Internet using my
browser and applications.
But I cannot connect to internet from my terminal.
I tried
export http_proxy="http://username:password@proxyserver:port/"
But still my terminal cannot connect to internet.

What software can manage multiple PCs with software installation and updates?

What software can manage multiple PCs with software installation and updates?

What software that can manage multiple PC with software for installation
and updates at the same time? Thanks
PC Management software (Workstations)
Keeping up to date with updates?
Package managers for Windows
How to keep all your 3rd party Softwares always updated

Gwt - EditTextCell to look exactly like TextInputCell

Gwt - EditTextCell to look exactly like TextInputCell

I have cellTable (GWT) which uses TextInputCell to allow the user to Edit
cells. When a user first selects a textbox,it receives focus and the user
can edit the data. When the user then tries to select another textbox, the
previous textbox loses focus but the newly selected textbox does not
receive focus. Clicking on the box again gives it focus. EditTextCell does
the same functionality, it allows us to edit the cell in 1 click, but it
is difficult to identify the cell as editableuntil or unless you click on
it.
As shown in the showcase, Can we modify the existing EditTextCell to look
exactly like TextInputCell? Can somebody help me in modifying it?
Below is the code of EditTextCell (ref here)
/**
* An editable text cell. Click to edit, escape to cancel, return to commit.
*/
public class EditTextCell extends
AbstractEditableCell<String, EditTextCell.ViewData> {
interface Template extends SafeHtmlTemplates {
@Template("<input type=\"text\" value=\"{0}\" tabindex=\"-1\"></input>")
SafeHtml input(String value);
}
/**
* The view data object used by this cell. We need to store both the
text and
* the state because this cell is rendered differently in edit mode. If
we did
* not store the edit state, refreshing the cell with view data would
always
* put us in to edit state, rendering a text box instead of the new text
* string.
*/
static class ViewData {
private boolean isEditing;
/**
* If true, this is not the first edit.
*/
private boolean isEditingAgain;
/**
* Keep track of the original value at the start of the edit, which
might be
* the edited value from the previous edit and NOT the actual value.
*/
private String original;
private String text;
/**
* Construct a new ViewData in editing mode.
*
* @param text the text to edit
*/
public ViewData(String text) {
this.original = text;
this.text = text;
this.isEditing = true;
this.isEditingAgain = false;
}
@Override
public boolean equals(Object o) {
if (o == null) {
return false;
}
ViewData vd = (ViewData) o;
return equalsOrBothNull(original, vd.original)
&& equalsOrBothNull(text, vd.text) && isEditing == vd.isEditing
&& isEditingAgain == vd.isEditingAgain;
}
public String getOriginal() {
return original;
}
public String getText() {
return text;
}
@Override
public int hashCode() {
return original.hashCode() + text.hashCode()
+ Boolean.valueOf(isEditing).hashCode() * 29
+ Boolean.valueOf(isEditingAgain).hashCode();
}
public boolean isEditing() {
return isEditing;
}
public boolean isEditingAgain() {
return isEditingAgain;
}
public void setEditing(boolean isEditing) {
boolean wasEditing = this.isEditing;
this.isEditing = isEditing;
// This is a subsequent edit, so start from where we left off.
if (!wasEditing && isEditing) {
isEditingAgain = true;
original = text;
}
}
public void setText(String text) {
this.text = text;
}
private boolean equalsOrBothNull(Object o1, Object o2) {
return (o1 == null) ? o2 == null : o1.equals(o2);
}
}
private static Template template;
private final SafeHtmlRenderer<String> renderer;
/**
* Construct a new EditTextCell that will use a
* {@link SimpleSafeHtmlRenderer}.
*/
public EditTextCell() {
this(SimpleSafeHtmlRenderer.getInstance());
}
/**
* Construct a new EditTextCell that will use a given {@link
SafeHtmlRenderer}
* to render the value when not in edit mode.
*
* @param renderer a {@link SafeHtmlRenderer SafeHtmlRenderer<String>}
* instance
*/
public EditTextCell(SafeHtmlRenderer<String> renderer) {
super(CLICK, KEYUP, KEYDOWN, BLUR);
if (template == null) {
template = GWT.create(Template.class);
}
if (renderer == null) {
throw new IllegalArgumentException("renderer == null");
}
this.renderer = renderer;
}
@Override
public boolean isEditing(Context context, Element parent, String value) {
ViewData viewData = getViewData(context.getKey());
return viewData == null ? false : viewData.isEditing();
}
@Override
public void onBrowserEvent(Context context, Element parent, String value,
NativeEvent event, ValueUpdater<String> valueUpdater) {
Object key = context.getKey();
ViewData viewData = getViewData(key);
if (viewData != null && viewData.isEditing()) {
// Handle the edit event.
editEvent(context, parent, value, viewData, event, valueUpdater);
} else {
String type = event.getType();
int keyCode = event.getKeyCode();
boolean enterPressed = KEYUP.equals(type)
&& keyCode == KeyCodes.KEY_ENTER;
if (CLICK.equals(type) || enterPressed) {
// Go into edit mode.
if (viewData == null) {
viewData = new ViewData(value);
setViewData(key, viewData);
} else {
viewData.setEditing(true);
}
edit(context, parent, value);
}
}
}
@Override
public void render(Context context, String value, SafeHtmlBuilder sb) {
// Get the view data.
Object key = context.getKey();
ViewData viewData = getViewData(key);
if (viewData != null && !viewData.isEditing() && value != null
&& value.equals(viewData.getText())) {
clearViewData(key);
viewData = null;
}
if (viewData != null) {
String text = viewData.getText();
if (viewData.isEditing()) {
/*
* Do not use the renderer in edit mode because the value of a text
* input element is always treated as text. SafeHtml isn't valid
in the
* context of the value attribute.
*/
sb.append(template.input(text));
} else {
// The user pressed enter, but view data still exists.
sb.append(renderer.render(text));
}
} else if (value != null) {
sb.append(renderer.render(value));
}
}
@Override
public boolean resetFocus(Context context, Element parent, String value) {
if (isEditing(context, parent, value)) {
getInputElement(parent).focus();
return true;
}
return false;
}
/**
* Convert the cell to edit mode.
*
* @param context the {@link Context} of the cell
* @param parent the parent element
* @param value the current value
*/
protected void edit(Context context, Element parent, String value) {
setValue(context, parent, value);
InputElement input = getInputElement(parent);
input.focus();
input.select();
}
/**
* Convert the cell to non-edit mode.
*
* @param context the context of the cell
* @param parent the parent Element
* @param value the value associated with the cell
*/
private void cancel(Context context, Element parent, String value) {
clearInput(getInputElement(parent));
setValue(context, parent, value);
}
/**
* Clear selected from the input element. Both Firefox and IE fire spurious
* onblur events after the input is removed from the DOM if selection is
not
* cleared.
*
* @param input the input element
*/
private native void clearInput(Element input) /*-{
if (input.selectionEnd)
input.selectionEnd = input.selectionStart;
else if ($doc.selection)
$doc.selection.clear();
}-*/;
/**
* Commit the current value.
*
* @param context the context of the cell
* @param parent the parent Element
* @param viewData the {@link ViewData} object
* @param valueUpdater the {@link ValueUpdater}
*/
private void commit(Context context, Element parent, ViewData viewData,
ValueUpdater<String> valueUpdater) {
String value = updateViewData(parent, viewData, false);
clearInput(getInputElement(parent));
setValue(context, parent, viewData.getOriginal());
if (valueUpdater != null) {
valueUpdater.update(value);
}
}
private void editEvent(Context context, Element parent, String value,
ViewData viewData, NativeEvent event, ValueUpdater<String>
valueUpdater) {
String type = event.getType();
boolean keyUp = KEYUP.equals(type);
boolean keyDown = KEYDOWN.equals(type);
if (keyUp || keyDown) {
int keyCode = event.getKeyCode();
if (keyUp && keyCode == KeyCodes.KEY_ENTER) {
// Commit the change.
commit(context, parent, viewData, valueUpdater);
} else if (keyUp && keyCode == KeyCodes.KEY_ESCAPE) {
// Cancel edit mode.
String originalText = viewData.getOriginal();
if (viewData.isEditingAgain()) {
viewData.setText(originalText);
viewData.setEditing(false);
} else {
setViewData(context.getKey(), null);
}
cancel(context, parent, value);
} else {
// Update the text in the view data on each key.
updateViewData(parent, viewData, true);
}
} else if (BLUR.equals(type)) {
// Commit the change. Ensure that we are blurring the input element and
// not the parent element itself.
EventTarget eventTarget = event.getEventTarget();
if (Element.is(eventTarget)) {
Element target = Element.as(eventTarget);
if ("input".equals(target.getTagName().toLowerCase())) {
commit(context, parent, viewData, valueUpdater);
}
}
}
}
/**
* Get the input element in edit mode.
*/
private InputElement getInputElement(Element parent) {
return parent.getFirstChild().<InputElement> cast();
}
/**
* Update the view data based on the current value.
*
* @param parent the parent element
* @param viewData the {@link ViewData} object to update
* @param isEditing true if in edit mode
* @return the new value
*/
private String updateViewData(Element parent, ViewData viewData,
boolean isEditing) {
InputElement input = (InputElement) parent.getFirstChild();
String value = input.getValue();
viewData.setText(value);
viewData.setEditing(isEditing);
return value;
}
}

VBA Access Compile Error variable not defined

VBA Access Compile Error variable not defined

I have this script that I want to use to move folders for archive this is
my code
Public Function modbalsmovearhive()
Set FSO = CreateObject("Scripting.FileSystemObject") FSO.MoveFile
"H:\Credit_Bals*.xls", "H:\Bals_Archive\"
End Function
Now when I go to run it I get the Compile Error variable not defined. Can
someone assist me with the best way to resolve this error. Thanks

How to make CFLAGS work with the dash shell?

How to make CFLAGS work with the dash shell?

My impression is that while setting the CFLAGS variable is effective when
bash is the default shell, it doesn't make an effect with dash (the Debian
Almquist shell).
First of all please correct me if my observation is wrong.
Secondly (if my observation is right), how can I get a global CFLAGS
variable effectively go through dash?
I've set the variable in ~/.profile like this:
export CFLAGS=-march=native

How to run multiple tests on different browsers simultaneously using selenium webdriver?

How to run multiple tests on different browsers simultaneously using
selenium webdriver?

How to run multiple tests on different browsers simultaneously using
selenium webdriver ?
I am working in java, I even tried selenium grid Downloaded: the
selenium-server-standalone-2.33.0.jar file
Even after the procedures,
I am not able to execute these commands on the command prompt
java -jar selenium-server-standalone-2.33.0.jar -role hub -port 4444
java -jar selenium-server-standalone-2.33.0.jar -role node -hub ...
Any other alternative ??

Tuesday, 20 August 2013

Not able to get the saved data bytes when reading the same file

Not able to get the saved data bytes when reading the same file

I am writing NSMutableData to image file using writeToFile with the below
code.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *file = [documentsDirectory
stringByAppendingPathComponent:@"binaryData.jpg"];
NSMutableData *data = [NSMutableData alloc];
[data appendData:rawData];
[data writeToFile:file atomically:NO];
NSLog (@"Data Length: %d.",data.length);
// Data Length: 30506
I am reading the saved image file with the below code.
-(void)imagePickerController:(UIImagePickerController*)picker
didFinishPickingMediaWithInfo:(NSDictionary*)info
{
UIImage *selectedImageFile = [info
objectForKey:UIImagePickerControllerOriginalImage];
NSData *PNGData = [NSData
dataWithData:UIImagePNGRepresentation(selectedImageFile)];
NSData *JPEGData = [NSData
dataWithData:UIImageJPEGRepresentation(selectedImageFile, 1.0)];
NSURL *imageURL = [info
objectForKey:UIImagePickerControllerReferenceURL];
ALAssetsLibrary* library = [[ALAssetsLibrary alloc] init];
[library assetForURL:imageURL resultBlock:^(ALAsset *asset) {
Byte *buffer = (Byte*)malloc(asset.defaultRepresentation.size);
NSUInteger k = [asset.defaultRepresentation getBytes:buffer
fromOffset: 0.0 length:asset.defaultRepresentation.size
error:nil];
rawData = [NSData dataWithBytesNoCopy:buffer length:k
freeWhenDone:YES];
}
NSLog (@"PNG Length: %d.", PNGData.length); // PNG Length: 78101
NSLog (@"JPEG Length: %d.", JPEGData.length); // JPEG Length: 37548
NSLog (@"Raw Data Length: %d.", PNGData.length); // Raw Data Length:
34163
}
If you see the above code, My source data length is '30506' before sending
it to writeToFile.
But I am not able to get the same bytes while reading the same image with
UIImagePickerController.
I tried with UIImagePNGRepresentation, UIImageJPEGRepresentation and
ALAssetsLibrary. But I am not able to get the same bytes in any of my
trials.
Can somebody guide me how to save/get the same bytes?

Python and Scheduling Computation

Python and Scheduling Computation

I wish to schedule a computation to occur after my current computation in
python is finished.
For example I am currently running:
>>> for i in range(2, 5):
... tn.TweetNetwork.create_subnetworks(i)
...
I made a simple mistake and meant to type range(1,5). This has been
running for at least 4 hours and should run for another few. That being
said I do not want to re-execute the loop with the correction and lose all
that has been computed.
As I am not by the computer 24/7, how can I schedule python to execute the
function `tn.TweetNetwork.create_subnetworks(1)?
I use emacs 24.3 and ubuntu 12.04 LTS, let me know if you need more
information. All help is greatly appreciated!

Performing a global lock in a Python web application?

Performing a global lock in a Python web application?

Basically, I have the following problem. There is a order processing
system which handles payments. In very rare circumstances, we end up with
double orders because while we query the credit card handler via the API,
if the user refreshes the page really quickly, the credit card processor
sometimes responds to both requests as "success" and we get two successful
"paid" events in the system.
So my idea was to implement a lock around the payment stuff (per order)
and if the lock is locked, tell the customer off (which would happen if
the customer refreshes the page very quickly - I think in our case it was
actually intentional).
So I thought about doing it with Redis and came up with this:
def _PaymentInterlock(object):
def __init__(self, pp):
self.key = GlobalKey('pay_ilk_%s'%pp._ident)
def lock(self):
self.key(1)
def unlock(self):
self.key.delete()
def try_lock(self):
result = self.key()
if result == 1:
return False
self.lock()
return True
The only problem with this is that the try_lock operation would not be
atomic (as opposed to a real compare and store operation), so technically,
two WSGI workers could get a key miss and then both lock the "lock"
causing the same sort of problem.
Are the any suggestions on how I would tackle this sort of a problem?

html/css, how to push an element on to the next line?

html/css, how to push an element on to the next line?

I've written this small fiddle showing what I want, but what I would like
to know is, is there away to style the .stack-slot elements so that they;
(a) shrink to the size of their content and (b) stack vertically beneath
one another as shown, using a css rule instead of <br/> tags?
html:
<span class='stack-panel vertical'>
<span class='stack-slot'>
<span class='content'>1</span>
</span>
<br/>
<span class='stack-slot'>
<span class='content'>2</span>
</span>
<br/>
<span class='stack-slot'>
<span class='content'>3</span>
</span>
</span>
css:
.stack-panel.vertical .stack-slot
{
/*TODO replace effect of <br/> tag*/
}

Ubuntu running on command line due to insufficient graphics

Ubuntu running on command line due to insufficient graphics

my problem is that when i was trying to install nvidia drivers (some 301
version) on ubuntu 13.04,it evokes a message a:"Ubuntu is running on low
graphics". after the installation(i am repenting that installation a lot
:().now whenever i reboot my laptop it show only command line version of
ubuntu 13.04.Though i could have reinstall the Ubuntu using usb-stick,but
it could cost me loss of important data which is stored in home/username/
folder. i tried to copy this folder using live ubuntu through usb-stick
but it is showing that you don't have permissions to copy that. now my
problem could have multiple solutions such as-
1.>i can reinstall nvidia or integrated intel graphics driver so that i
can continue with my previous installation and data.
2.>i can copy the data to an external harddisk through commands (which i
don't know) and reinstall ubuntu(which i know :))
3.>i can copy the data though live ubuntu run through usb-stick to
external hard dissk. problem is i tried many commands on this forum with
similiar problems but none had worked yet.
SO PLEASE HELP ME. your help will be appreciated.

JS tabs - show content only after mouse hover

JS tabs - show content only after mouse hover

I am looking for some solution for this: I need something like this:
http://jqueryui.com/tabs/#mouseover But with some default content block
(without tab mennu item) and show other items only which mouseover is on
some item. When cursor is gone from item then show default block again.
Basically same effect like this: http://jsfiddle.net/RM3yr/2/
I can not JS, so I m looking for ready-made solution.
Thanks a lot

How to upgrade my samsung galaxy ace plus GT -S7500 from Gingerbread to Jellybean

How to upgrade my samsung galaxy ace plus GT -S7500 from Gingerbread to
Jellybean

I would like to know How to upgrade my samsung galaxy ace plus GT-S7500
from Gingerbread to Jellybean.?
Details are as follows
Model Number: Samsung GT-S7500
Android version: 2.3.6
Baseband Version: S7500DDME1
Kernel Version: 2.6.38.6 dpi@DELL235#1
Build Number: GINGERBREAD.DDMF2
Please help...

Monday, 19 August 2013

IIS Installation broken (reboot pending)

IIS Installation broken (reboot pending)

Every time i want to Install the IIS role on a server it reports the
following:
The request to add or remove features on the specific server failed.
The operation cannot be completed, because the server that you specified
requires a restart.
After a reboot the game starts again.
The IIS role WAS already installed on this server and got removed after
some configuration issues, I could not get rid of. No I am unable to
reinstall it again... Other roles on this Servers are: Domain Controller,
DNS, DHCP, NAP.
The ISS is used to invoke a DNS/DHCP Update Script from a web page to keep
DHCP and DNS entries on all servers up to date, and manage static entries
ect... (DHCP will be replaced soon by Microsoft own feature)
There are not entries in the eventlog regarding this error at all or which
could provide any useful data.
Any Ideas?
PS: (I Exported the configuration settings, but I relay have no Idea how
to use that XML file afterwards :)
EDIT: This Waring shows up 3 Times in the eventlog.
A provider, WebAdministrationProvider, has been registered in the Windows
Management Instrumentation namespace Root\WebAdministration to use the
LocalSystem account. This account is privileged and the provider may cause
a security violation if it does not correctly impersonate user requests.
And i just found this Logfile C:\Windows\Logs\CBS\CBS.log (it's a bit to
big for Pastebin, so i need to improvise) Part 2 Part 3 Part 4
Maybe this is helpful?

understanding this VB code

understanding this VB code

Can someone try wrap their brain around this one? I thought it was simply
ensuring there were 2 bytes in hex byte and ensuring the values were
between 0 -9 and A-F but no.
A snippet of a program that is for an infrared controller/blaster. This
subroutine will send the actual signals (or other codes) out the serial
port to the controller for it to finish the job.
Sample call:
SendCode ("04241001")
The VB6 code says:
Public Sub SendCode(ByVal strOut As String)
' ****************************
' This sub sends the hex codes
' ****************************
Dim numb1 As Integer, numb2 As Integer
Dim strRS As String
Dim i As Long
Dim newline(200) As String, outline(200) As String
Debug.Print "Sending IR - " & strOut
strRS = vbNullString
For i = 1 To Len(strOut)
newline(i) = Mid(strOut, i, 1)
Next
For i = 1 To Len(strOut) Step 2
If Asc(newline(i)) < 64 Then
numb1 = (Asc(newline(i)) - 48) * 16
strRS = strRS + Format(Hex(numb1 / 16), "0")
Else
numb1 = (Asc(newline(i)) - 55) * 16
strRS = strRS + Format(Hex(numb1 / 16), "0")
End If
If Asc(newline(i + 1)) < 64 Then
numb2 = (Asc(newline(i + 1)) - 48)
strRS = strRS + Format(Hex(numb2), "0")
Else
numb2 = (Asc(newline(i + 1)) - 55)
strRS = strRS + Format(Hex(numb2), "0")
End If
numb1 = numb1 + numb2
outline((i + 1) \ 2) = CByte(numb1)
strRS = strRS + " "
Next
With MSComm1
.RTSEnable = True
Sleep (20)
.OutBufferCount = 0
For i = 1 To (Len(strOut) / 2)
.Output = Chr(outline(i))
Next
Sleep (20)
.RTSEnable = False
End With
End Sub



The question is based around the second For/Next loop with Step 2 and the
embedded IF statements.
Any idea what the intended use of strRS is used for?

SQL Update a DateRange table from a SUM query of another table

SQL Update a DateRange table from a SUM query of another table

Table DateRangeTab (Fromdate, Todate, TotalValue) has data such as:
2010-01-01, 2011-01-01, 0
2010-01-01, 2012-01-01, 0
etc (i.e lots of date ranges all with 0 in the TotalValue column)
I also have table ValueTab (DateofValue, Value) which has data such as:
2010-01-02, £25
2011-01-01, £45
2011-05-04, £65
etc (i.e. lots of different rows with dates and a value for each date)
I need to update DateRangeTab TotalValue column with SUM of Value from
ValueTab table where the DateofValue falls in the range FromDate - Todate.
I tried something like the following :
Update DateRangeTab set TotalValue = a.Value from ( select sum(value) as
Value from ValueTab VT join DateRangeTab DT on VT.DateofValue between
DT.startdate and DT.ToDate) a
But it puts same total in each row of the DateRangeTab. Hope someone can
help or direct me to another post with a related answer.
Thanks

Program for word reversal randomly skips out letters?

Program for word reversal randomly skips out letters?

My program keeps randomly skipping out letters! For example, 'coolstory'
becomes 'yrotsloc' and 'awesome' becomes 'mosewa'
Here is the code:
def reverse(text):
length = len(text)
reversed_text = []
for i in range(0,length + 1):
reversed_text += ['']
original_list = []
for l in text:
original_list.append(l)
new_place = length - (original_list.index(l))
reversed_text[new_place] = l
return "".join(reversed_text)

Operator precedence odd behaviour

Operator precedence odd behaviour

The reference I'm using for Ruby operators:
http://phrogz.net/programmingruby/language.html#table_18.4
According to this reference (and others I've seen), equality operators
take presendence over logical AND (&&, not Ruby's and).
So if we have the following:
foo = nil
foo < 5 # NoMethodError: undefined method `<' for nil:NilClass
# So to check for foo we do:
foo && (foo < 5) # Note the parenthesis
# But this works
foo && foo < 5 # why does this work??
In the last example foo && foo < 5, foo < 5 should happen first thus
resulting in an error before the AND can even be evaluated.
Am I missing something?

Where is a SiteLogoUrl in CSOM?

Where is a SiteLogoUrl in CSOM?

I found SPWeb.SiteLogoUrl and expected this property CSOM and REST. But I
can't find it. How can I get a SiteLogoUrl using CSOM or REST?

Sunday, 18 August 2013

Error trying to UPDATE php/mysql code for changing to a new password

Error trying to UPDATE php/mysql code for changing to a new password

As described in the title, I am running into an SQL injection error:
You have an error in your SQL syntax; check the manual that corresponds to
your MySQL server version for the right syntax to use near '1' at line 1
How do I fix this? Provided below is my php code and html code
PHP:
if($_POST['submit']=='Change')
{
$err = array();
if(!$_POST['password1'] || !$_POST['passwordnew1'])
$err[] = 'All the fields must be filled in!';
if(!count($err))
{
$_POST['password1'] = mysql_real_escape_string($_POST['password1']);
$_POST['passwordnew1'] =
mysql_real_escape_string($_POST['passwordnew1']);
$row = mysql_fetch_assoc(mysql_query("SELECT id,username FROM
members WHERE username='{$_SESSION['username']}' AND
pass='".md5($_POST['password1'])."'"));
if($row['username'])
{
$querynewpass = mysql_query("UPDATE members SET
pass='".md5($_POST['passwordnew1'])."' WHERE
username='{$_SESSION['username']}'");
$result = mysql_query($querynewpass) or die(mysql_error());
}
else $err[]='Wrong Password To Start With!';
}
if($err)
$_SESSION['msg']['passwordchange-err'] = implode('<br />',$err);
header("Location: members.php?id=" . $_SESSION['username']);
exit;
}
HTML:
<form action="" method="post">
<?php
if($_SESSION['msg']['passwordchange-err'])
{
echo '<div
class="err">'.$_SESSION['msg']['passwordchange-err'].'</div>';
unset($_SESSION['msg']['passwordchange-err']);
}
if($_SESSION['msg']['passwordchange-success'])
{
echo '<div
class="success">'.$_SESSION['msg']['passwordchange-success'].'</div>';
unset($_SESSION['msg']['passwordchange-success']);
}
?>
<label class="grey" for="password1">Current Password:</label>
<input class="field" type="password" name="password1" id="password1"
value="" size="23" />
<label class="grey" for="password">New Password:</label>
<input class="field" type="password" name="passwordnew1"
id="passwordnew1" size="23" />
<input type="submit" name="submit" value="Change" class="bt_register"
style="margin-left: 382px;" />
</form>
I have it working where a user is able to change/update their password,
however, when they click the Change button on the form, they are directed
to that error message I posted above, and if they click the refresh
button, only then they are redirected back to their profile and the
changes have been made. So my main question at hand is, how do I get this
to fully work without that mysql error message? Any help would be much
appreciated!

Any way to simplify $\gcd(a+b,a-c)$?

Any way to simplify $\gcd(a+b,a-c)$?

If I have the expression $\gcd(a+b,a-c)$ is there a way to further reduce
this? Are there any other properties?

CGRectIntersectsRect() to detect first interseption

CGRectIntersectsRect() to detect first interseption

I use CGRectIntersectsRect()to see whenever a CCSprite collides with
another CCSprite:
- (void)update3
{
for (CCSprite *sprite in _monsters)
{
if (CGRectIntersectsRect(_rocket.boundingBox, sprite.boundingBox))
{
NSLog(@"Collide");
}
}
}
This fires the log as long as the sprites touches each other, I just want
to detect the first touch. Is this possible?

Fastest way to upload streaming points, and removing occasionally

Fastest way to upload streaming points, and removing occasionally

So i have a system (using OpenGL 4.x) where i am receiving a stream of
points (potentially with color and/or normal), from an external source.
And I need to draw these points as GL_POINTS, running custom switchable
shaders for coloring (color could be procedurally generated, or come from
vertex color or normal direction).
The stream consists of receiving a group of points (with or without normal
or color) of an arbitrary count (typical from 1k to 70k points) at a
fairly regular interval (4 to 10 hz), I need to add these points to my
current points and draw all the points so far received points.
I am guaranteed that my vertex type will not change, I am told at the
beginning of the streaming which to expect, so i am either using an
interleaved vertex with: pos+normal+color, pos+normal, pos+color, or just
pos.
My current solution is to allocate interleaved vertex VBOs (with
surrounding VAOs) of the appropriate vertex type at a config file
specified max vertex count (allocated with the DYNAMIC hint).
As new points come in i fill up my current non filled VBO via
glBufferSubData. I keep a count (activePoints) of how many vertices the
current frontier VBO has in it so far, and use glBufferSubData to fill in
a range starting with activePoints, if my current update group has more
vertices than can fit in my frontier buffer (since i limit the vertex
count per VBO), then i allocate a new VBO and fill the range starting at 0
and ending with the number of points left in my update group (not added to
the last buffer), if I still have points left I do this again and again.
It is rare that an update group straddles more than 2 buffers.
When rendering i render all my VBOs (-1) with a
glDrawArrays(m_DrawMode,0,numVertices), where numVertices is equal to max
buffer allowed size, and my frontier buffer with a
glDrawArrays(m_DrawMode,startElem,numElems) to account for it not being
completely filled with valid vertices.
Of course at some point I will have more points than I can draw
interactively, so i have an LRU mechanism that deallocates the oldest
(according to the LRU alg) sets of VBOs as needed.
Is there a more optimal method for doing this? Buffer orphaning? Streaming
hint? Map vs SubData? Something else?
The second issue is that i am now asked to removed points (at irregular
intervals), ranging from 10 to 2000 at a time. But these points are
irregularly spaced within the order I received them initially. I can find
out what offsets in which buffers they currently exit in, but its more of
a scattering than a range. I have been "removing them" by finding their
offsets into the right buffers and one by one calling glBufferSubData with
a range of 1 (its rare that they are beside each other in a buffer), and
changing there pos to be somewhere far off where they will never be seen.
Eventually i guess buffers should be deleted from these remove request
adding up, but I don't currently do that.
What would be a better way to handle that?
Thanks for any input.

Java servlet- Best way to get post requests body

Java servlet- Best way to get post requests body

I'm getting a post request- with a XML in the body. what is the best way
to get the requests body?
cheers:)

Notification message tray?

Notification message tray?

Cinnamon desktop environment has a rather nifty idea of a tray in the
systray that holds all notification messages till their read and cleared,
and then becomes empty. How can I have the same thing in fluxbox please? I
think it needs to be done via a bash script but I haven't the faintest
idea where to start! This would be used on a debian testing machine under
fluxbox desktop environment, but would hopefully be usable under ones like
razor-qt as well.

Saturday, 17 August 2013

How to load a line of string input from data file into an array

How to load a line of string input from data file into an array

I am complete beginner. Have a data input file with multiple lines like this
name, number, number,...
I can read the line as a string but need to input the values into an
array. How do I do that. I've spent 2 days trying to figure it out.

What is the splash range for throwing urine and milk?

What is the splash range for throwing urine and milk?

The wiki doesn't seem to have much on the two splash weapons in game, Mad
Milk and Jarate, in terms of splash radius.
What's the splash radius on these two weapons in terms of units? Is the
splash radius effected by anything else, including height thrown from, or
the position landed? Is it a circular radius, or a spherical radius?

Redmine not start, log says ActiveRecord::AdapterNotSpecified, some other stranges

Redmine not start, log says ActiveRecord::AdapterNotSpecified, some other
stranges

FreeBSD 9.2 Apache 2.4 + Passenger Trying to start Redmine 2.3.2
Error:
/usr/local/lib/ruby/gems/1.9/gems/activerecord-3.2.13/lib/active_record/connection_adapters/abstract/connection_specification.rb:47:in
`resolve_hash_connection': database configuration does not specify adapter
(ActiveRecord::AdapterNotSpecified)
I found that if I change adapter from "adapter: mysql2" to
"adapter:mysql2" (remove space after ":" ) then this error gone, however
then I have another error:
/usr/local/lib/ruby/gems/1.9/gems/bundler-1.3.5/lib/bundler/dsl.rb:33:in
`rescue in eval_gemfile': Gemfile syntax error: (Bundler::GemfileError)
So I have to make it work when "adapter: mysql2" is configured, so I have
to solve ActiveRecord::AdapterNotSpecified error problem somehow else, not
by removing space there.
Any ideas?
RubyGems Environment:
- RUBYGEMS VERSION: 1.8.25
- RUBY VERSION: 1.9.3 (2013-06-27 patchlevel 448) [amd64-freebsd9]
- INSTALLATION DIRECTORY: /usr/local/lib/ruby/gems/1.9
- RUBY EXECUTABLE: /usr/local/bin/ruby19
- EXECUTABLE DIRECTORY: /usr/local/bin
- RUBYGEMS PLATFORMS:
- ruby
- amd64-freebsd-9
- GEM PATHS:
- /usr/local/lib/ruby/gems/1.9
- /root/.gem/ruby/1.9
- GEM CONFIGURATION:
- :update_sources => true
- :verbose => true
- :benchmark => false
- :backtrace => false
- :bulk_threshold => 1000

VMware - Host two VPS with same IP

VMware - Host two VPS with same IP

I have:
1 Dedicated server, Windows server 2008.
2 Virtual machines inside the server. (VMware, Windows too)
1 example IP address: (0.0.0.1)
1 example IP address: (0.0.0.2)
I need:
1 Dedicated server with IP: (0.0.0.1) to host HTTP
2 Virtual servers both with IP: (0.0.0.2), one for HTTP, and the next one
for FTP

Is this even possible ? Please explain how it can be done on my VMware
(workstation 9), because it's actually harder than it looks if you
consider the port forwading of the two vps, and if you use only (0.0.0.1)
on the host machine.

unable to boot chromiumos "vanilla" from hard drive

unable to boot chromiumos "vanilla" from hard drive

I'm at the end of my teather here.
I have a Thinkpad X220 (last year's model) which boots with EFI, and I'm
trying to install Chromium OS on it. Hexxeh's Vanilla usb image boots from
USB fine, and EVERYTHING works, even suspend.
I follow the instructions to install it to disk via the chrosh command
"install", everything goes ok. I reboot and am faced with the grub 1.97
sh.grub> prompt. all the text is orange rather than white, if it matters.
Typing ls yields just (hd0), no partitions (even though gparted says there
are all 12).
No messing around with grub works, because it doesn't recognise any
partitions, just the one disk, hd0.
The same USB image succsessfully installs chromiumos on an old non-efi
laptop I have lying around. I can only assume it is grub 1.97 not
supporting efi?
I would really like to know what's up, thanks in advance!

How do I kill and unlock a Redis::Semaphore (NonBlockingRedis) in Rails?

How do I kill and unlock a Redis::Semaphore (NonBlockingRedis) in Rails?

I have this job that I run every hour.
class ImapJob
include Sidekiq::Worker
sidekiq_options :retry => false
def perform(user_id)
s = Redis::Semaphore.new("fetch_imap_mails_for_#{user_id}".to_sym,
redis: NonBlockingRedis.new(connection: "localhost"))
if s.lock(-1)
begin
emails = ImapMails.receive_mails(user_id)
rescue => e
puts "Error while fetching email"
ensure
s.unlock
end
end
end
end
In some a controller I have an action that is supposed to kill this job. I
need not only to kill the job, but also to unlock, so the job can be run
next hour like it always does.
How do I find it and kill it?
Example code:
c = Redis::Semaphore.find("fetch_imap_mails_for_#{user_id}".to_sym
c.kill_and_unlock

IE7 adding trailing slashes to URLs

IE7 adding trailing slashes to URLs

I've got a strange one. I'm using Django (version 1.5.2) and have my app
in production mode so I get an email on unhandled exceptions.
I keep getting emails about an unhandled exception from the following
user-agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; InfoPath.1;
.NET CLR 2.0.50727; .NET CLR 1.1.4322; MS-RTC LM 8; .NET CLR
3.0.4506.2152; .NET CLR 3.5.30729
The exception is caused by whatever that browser is adding trailing
backslashe(s) to URLs.
For example I have an <img> tag in the body of my document, with src of
http://mydomain.com/img/123?sizew=100&sizeh=100
However, whatever browser that is adds up to three trailing slashes to
that URL, so the request is actually
http://mydomain.com/img/123?sizew=100&sizeh=100///
Notice the three slashes in the URL. This causes an unhandled exception.
This app has its fair share of users, and it seems to only be this user
agent that's causing this error.
I'm wondering if this is a bug in the browser, or if it's something I'm
doing, and if anyone has seen this issue before.
Thanks

Friday, 16 August 2013

Find nodes of the same height when a binary tree node is given?

Find nodes of the same height when a binary tree node is given?

I want to know if there is any other optimal solution than this.
Problem: Given a Node in a binary tree, I need to write a program to find
out all the nodes that are of the same level as the given node
(inclusive). Example: If the given node is of the level 2 then program
should return a collection of all the nodes with height 2.
My Solution : I had two methods, one to find out the root of the given
node and return the root(this method also finds out the height (bheight in
my code) from the node to the root) and this root is fed to the second
method to do a breadth first search and keep updating heights of the nodes
as I traverse and if the height of the first element in the queue equals
to the height that I calculated in the root method, then I return the
queue.
My Code:
import java.util.LinkedList;
import java.util.Queue;
public class binaryTree {
int value;
binaryTree left;
binaryTree right;
binaryTree parent;
int height;
static int bheight;
Queue<binaryTree> que = new LinkedList<binaryTree>();
public binaryTree(int v) {
value = v;
}
//This method returns a Queue of all the nodes that are on the same level
as the supplied node b.
public Queue<binaryTree> BFS(binaryTree b) {
b = root(b);
que.clear();
b.height=0;
que.add(b);
while (!que.isEmpty()) {
binaryTree node = que.remove();
if (node.left != null) {
node.left.height=(node.left.parent.height)+1;
System.out.println(node.left.value+" Root is
"+node.left.parent.value+" and its height is " +
node.left.height);
que.add(node.left);
}
if (node.right != null) {
node.right.height=(node.right.parent.height)+1;
System.out.println(node.right.value+" Root is
"+node.right.parent.value+" and its height is " +
node.left.height);
que.add(node.right);
}
if(que.peek().height==bheight)
{
break;
}
}
return que;
}
//Finds out the root of the given node and returns the root node
public binaryTree root(binaryTree t) {
if (t.parent == null) {
return t;
} else {
bheight++;
return root(t.parent);
}
} }