Saturday, 31 August 2013

Code in constructor before this or super in generated class file while using code coverage tool

Code in constructor before this or super in generated class file while
using code coverage tool

I am using google code pro Analatics to measure code coverage.
Source code
public class StackArray implements Stack { private int top; private T[]
elements;
public StackArray(Class<T> type, int size) {
top = -1;
elements = (T[]) Array.newInstance(type, size);
}
//Other stack related methods
}
Generated class file
import com.vladium.emma.rt.RT; import java.lang.reflect.Array;
// Referenced classes of package ds.stack: // Stack
public class StackArray implements Stack {
private int top;
private Object elements[];
private static final int $VRc[][]; /* synthetic field */
private static final long serialVersionUID = 0x927be770ed420794L; /*
synthetic field */
public StackArray(Class type, int size)
{
int ai[] = ($VRc != null ? $VRc : $VRi())[0];
super();
top = -1;
elements = (Object[])Array.newInstance(type, size);
ai[0] = ai[0] + 1;
}
}
My question is how is this line permissible in constructor before this or
super
int ai[] = ($VRc != null ? $VRc : $VRi())[0];

IList Property stays null even when member is instantiated

IList Property stays null even when member is instantiated

I am having trouble using an IList property which always seems to return
null, even though the member is is getting is instantiated:
private List<ModelRootEntity> _validTargets = new
List<ModelRootEntity>();
public IList<IModelRootEntity> ValidTargets
{
get
{
return _validTargets as IList<IModelRootEntity>;
}
protected internal set
{
if (value == null)
_validTargets.Clear();
else
_validTargets = value as List<ModelRootEntity>;
}
}
ModelRootEntity implements IModelRootEntity. I watched both values during
debugging, whilst the member shows a positive count, the property stays
null.
I also tried raising an exception within the property getter to throw if
the counts of _validTargets and _validTargets as List<ModelRootEntity> are
different, but it never threw.
Found question [Dictionary properties are always null despite dictionaries
being instantiated, which seems similar, however in my case this seems to
happen regardless of serialization.
Any ideas?

Getting Screen Positions of D3 Nodes After Transform

Getting Screen Positions of D3 Nodes After Transform

I'm trying to get the screen position of a node after the layout has been
transformed by d3.behavior.zoom() but I'm not having much luck. How might
I go about getting a node's actual position in the window after
translating and scaling the layout?
mouseOver = function(node) {
screenX = magic(node.x); // Need a magic function to transform node
screenY = magic(node.y); // positions into screen coordinates.
};
Any guidance would be appreciated.

summary table with total whilst controlling for value on one variable?

summary table with total whilst controlling for value on one variable?

I've used function summary(data[data$var1==5,]) to get a summary of
observations while the variable of interest equals 5 (or whatever).
However, I also need a total for a particular var2 as well, and I'm unsure
how to go about coding that in here whilst keeping the variable that I
want controlled at 5 (or whatever).
I'm quite happy writing a second line looking for the total of var2 whilst
controlling var1. Any help would be appreciated, thanks.

how to display elements of json array returned from php within a loop in ajax(jquery)

how to display elements of json array returned from php within a loop in
ajax(jquery)

Below ajax code is receiving a json array from php. Rest details i have
written as comments:
$.ajax({
type: "POST",
url: "dbtryout2_2.php",
data:datastr,
cache: false,
//dataType: 'json',
success: function(arrayphp)
{
//"arrayphp" is receiving the json array from
php.
//below code is working where iam displaying
the array directly
//This code displays the array in raw format.
$(".searchby .searchlist").append(arrayphp);
}
});
But when iam trying to display the elements of the array seperately using
below code ,then it is not working:
$.ajax({
type: "POST",
url: "dbtryout2_2.php",
data:datastr,
dataType: "json",
cache: false,
contentType: "application/json",
success: function(arrayphp)
{
//nothing is getting displayed with this code
$.each(arrayphp,function(i,v){
alert(i+"--"+v);
});
}
});
WOULD ANYBODY FIGURE OUT WAT THE PROBLEM IS WITH MY CODE?

Run .sh file from current package

Run .sh file from current package

There are two files A.java and B.sh in /test package .
I want to execute B.sh from A.java. In other word I want to get B.sh as a
file

How do I make my footer background full screen? (HTML / CSS site)

How do I make my footer background full screen? (HTML / CSS site)

I've been trying to solve this for a couple of hours, but I haven't found
a good solution in this forum.
So, how do I make the footer background here stretch all the way to the
left and right, the way my header does?
I want the text to remain in four columns in the center of the screen with
its current width (950px), but the background to fill the viewer's screen,
whichever width that may be.
Thanks.
Maria

What is the best cloud hosting solution for nodejs and mongodb application?

What is the best cloud hosting solution for nodejs and mongodb application?

I am working on a new application which uses nodejs and mongodb. I am new
to both of these. I have earlier worked on AWS and simple unix servers.
But I need a solution like heroku which can be scaled with least efforts.
Please give some feedback regarding that.
I have googled a bit and I liked https://modulus.io/ . Its scalable and
cheap.
Heroku + Mongolab seems costly.
Also I am not aware of what issues I am going to face.
Pardon me if you find this question unsuitable for stackoverflow.

Friday, 30 August 2013

draw bitmap images outside onDraw function Canvas Android

draw bitmap images outside onDraw function Canvas Android

I want to call a function to draw Bitmap images from the onDraw().
Actually I need to draw bitmap images outside the onDraw() . Help me.
Thanks.

Thursday, 29 August 2013

MySQLSyntaxErrorException: unknown column

MySQLSyntaxErrorException: unknown column

I have some hard time with my program. All I want is to get some objects
from table that have this simple structure:
mysql> describe tb_rasa;
+--------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+--------+-------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| nazwa | varchar(50) | YES | | NULL | |
| symbol | varchar(4) | NO | UNI | NULL | |
+--------+-------------+------+-----+---------+----------------+
in my bean class I have:
@PostConstruct
public void init() {
rasa = rasaEJB.wyswietlRase(1);
}
in RasaEJB:
public RasaSl wyswietlRase(Integer id) {
System.out.println("RasaEJB.wyswietlRase(id)");
RasaSl rasa = rasaDao.find(id);
return rasa;
}
RasaSl entity looks like:
@Entity
@Table(name="tb_rasa")
public class RasaSl implements Serializable {
/**
*
*/
private static final long serialVersionUID = -4682401385263402475L;
@Id
@Column(name="id")
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
@Column(name="nazwa",columnDefinition="varchar(50)")
private String nazwa;
@Column(name="symbol", columnDefinition="varchar(4)")
private String symbol;
@OneToMany(mappedBy="rasaSl", cascade=CascadeType.PERSIST)
private List<RasaStatystyka> modyfikatory = new ArrayList<RasaStatystyka>();
public String getNazwa() {
return nazwa;
}
public void setNazwa(String nazwa) {
this.nazwa = nazwa;
}
public String getSymbol() {
return symbol;
}
public void setSymbol(String symbol) {
this.symbol = symbol;
}
public List<RasaStatystyka> getModyfikatory() {
return modyfikatory;
}
public void setModyfikatory(List<RasaStatystyka> modyfikatory) {
this.modyfikatory = modyfikatory;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
}
I have completely know idea what could create this error:
RasaEJB.wyswietlRase(id)
[EL Info]: 2013-08-29
16:45:18.207--ServerSession(1816969462)--EclipseLink, version: Eclipse
Persistence Services - 2.5.0.v20130507-3faac2b
[EL Info]: 2013-08-29
16:45:18.588--ServerSession(1816969462)--file:/D:/usr/java/moje/system/.metadata/.plugins/org.eclipse.wst.server.core/tmp4/wtpwebapps/EclipseJPA2-war/WEB-INF/lib/EclipseJPA2-jpa-0.01.jar_persistenceUnit
login successful
[EL Warning]: 2013-08-29 16:45:18.688--UnitOfWork(1358566974)--Exception
[EclipseLink-4002] (Eclipse Persistence Services -
2.5.0.v20130507-3faac2b):
org.eclipse.persistence.exceptions.DatabaseException
Internal Exception:
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column
'id' in 'field list'
Error Code: 1054
Call: SELECT id, nazwa, symbol FROM tb_rasa WHERE (id = ?)
bind => [1 parameter bound]
Query: ReadObjectQuery(name="readRasaSl" referenceClass=RasaSl sql="SELECT
id, nazwa, symbol FROM tb_rasa WHERE (id = ?)")
Please help.

Performance Differences of Nested If Else Statements vs. ElseIf Statements

Performance Differences of Nested If Else Statements vs. ElseIf Statements

A coworker and I have differing opinions on If statements and their
performance. My view is that If...ElseIf statements should be used. His
view is that he doesn't believe in ElseIf, and writes everything with
nested If statements.
Let's assume that a case statement cannot be used in this situation. What
I am wondering is how efficiently code will be executed using nested
If..Else statements versus using If...ElseIf statements. I know that code
readability is a factor, but that shouldn't' affect performance.
Lets look at the following examples.
Using If Else:
If () then
'Do something'
Else
If () then
'Do something'
Else
If () then
'Do something'
Else
If () then
'Do something'
Else
'Do something else'
End If
End If
End If
End If
Using ElseIf:
If () then
'Do something'
ElseIf () then
'Do something'
ElseIf () then
'Do something'
ElseIf () then
'Do something'
Else
'Do something else'
End If
I know this is a small scale example, but lets say blocks like this are
used heavily throughout the application.
Are there any performance differences between the two code sections, or
would they perform almost identically once the application is compiled?

How to execute a Python script from server side Javascript

How to execute a Python script from server side Javascript

There are a number of answers in relation to how one can execute a Python
script from the client side. I am interested in finding out if it is
possible to execute the script from the server side and check if the
execution has finished successfully. Let say that I'm using Meteor stack
which uses JavaScript on both sides and there are a bunch of Python script
tasks that needs to be triggered from backend.

Wednesday, 28 August 2013

NameError: global name 'cb' is not defined

NameError: global name 'cb' is not defined

I am trying to make a program that calculates the biggest number of
objects(nuggets) you can't get with packages of 6-9-20 (I am fairly new to
python, i trying using global and nonlocal but it doesn't work either).
def nuggets(n):
x = 6
y = 9
z = 20
for i in range(0,n//x+1):
for j in range(0,n//y+1):
for k in range(0,n//z+1):
if i*x + j*y + k*z == n:
return [i,j,k]
return None
def cant_buy(n):
seq=0
for i in range(n):
p=nuggets(i)
if type(p)== list:
seq+=1
elif type(p)== None:
cb=i
seq=0
return cb
Then this error appears: Traceback (most recent call last): File "", line
1, in cant_buy(12) File "C:\Python33\OCW 6.00\ps2a.py", line 22, in
cant_buy return cb NameError: global name 'cb' is not defined
What is wrong? I defined it at the elif statement.

Start new Activity with button with FLAG_ACTIVITY_SINGLE_TOP on Android

Start new Activity with button with FLAG_ACTIVITY_SINGLE_TOP on Android

Basically Im trying start new Activity with button. Problem is in
MainActivity class Im using:
mPendingIntent = PendingIntent.getActivity(this, 0, new Intent(this,
getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
I think thats reason why when Im trying start new activity I still can see
only MainActivity because its still on the TOP of screen. I tried use
this:
public void handleClick(View v){
//Create an intent to start the new activity.
Intent intent = new Intent();
intent.setClass(this,Page2Activity.class);
startActivity(intent);
}
but still can't see new activity opened. Is it way how I can start new
Activity on the top of screen? Thank you.

Android OpenCV Perspective Transform Result

Android OpenCV Perspective Transform Result

I'm making an Android Application using OpenCV Library for Android. I'm
taking a picture in my application which is a receipt and I'm trying to
apply some filters and make a transformation with warpPerspective
function. I found some code here:Java OpenCV deskewing a contour and I'm
trying to use it in my application. What I have done until now is the code
below + the Quadraple class from previous page. I don't what is going
wrong. Below it's the code I use:
public class ImgProClean {
private static String imagePath =
Environment.getExternalStorageDirectory() + "/DCIM/Camera";
public static Bitmap start(Bitmap bitmap){
//Create mat images
Mat img0 = new Mat(bitmap.getWidth(), bitmap.getHeight(),
CvType.CV_8UC1);
Utils.bitmapToMat(bitmap, img0);
Mat img1 = new Mat(bitmap.getWidth(), bitmap.getHeight(),
CvType.CV_8UC1);
img0.copyTo(img1);
Mat img2 = new Mat(img0.width(), img0.height(), CvType.CV_8UC1);
if(!img1.empty()){
Imgproc.cvtColor(img1, img1, Imgproc.COLOR_RGB2GRAY);
}
Imgproc.adaptiveThreshold(img1, img1,
255,Imgproc.ADAPTIVE_THRESH_MEAN_C,Imgproc.THRESH_BINARY,501,0);
Imgproc.erode(img1, img1,
Imgproc.getStructuringElement(Imgproc.CV_SHAPE_RECT, new Size(3,3)),
new Point(1,1), 10);
Imgproc.dilate(img1, img1,
Imgproc.getStructuringElement(Imgproc.CV_SHAPE_RECT, new Size(3,
3)),new Point(1,1), 10);
List<MatOfPoint> contours = new ArrayList<MatOfPoint>();
Imgproc.findContours(img1, contours, new Mat(), Imgproc.RETR_EXTERNAL,
Imgproc.CHAIN_APPROX_SIMPLE);
double maxArea = -1;
int maxAreaIdx = -1;
for (int idx = 0; idx < contours.size(); idx++) {
Mat contour = contours.get(idx);
double contourarea = Imgproc.contourArea(contour);
if (contourarea > maxArea) {
maxArea = contourarea;
maxAreaIdx = idx;
}
}
//Imgproc.drawContours(img1, contours, maxAreaIdx, new Scalar(255), 100);
QuadRangle.fromContour(contours.get(maxAreaIdx));
img2 = QuadRangle.warp(img0);
Utils.matToBitmap(img2, bitmap);
try {
FileOutputStream out = new FileOutputStream(imagePath +
"/warpImage.jpg");
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
} catch (Exception e) {
e.printStackTrace();
}
return bitmap;
}
What i want to do is something like that:(From figure 7 to 8)
The result I'm getting is always NullPointer Exception in Quadraple class
in the lines:
Core.line(result, lines[TOP].get(-5000), lines[TOP].get(5000), new
Scalar(200, 100, 100), 8);
Core.line(result, lines[RIGHT].get(-5000), lines[RIGHT].get(5000), new
Scalar(0, 255, 0), 8);
Core.line(result, lines[BOTTOM].get(-5000), lines[BOTTOM].get(5000), new
Scalar(255, 0, 0), 8);
Core.line(result, lines[LEFT].get(-5000), lines[LEFT].get(5000), new
Scalar(0, 0, 255), 8);
Point p = Line.intersect(lines[TOP], lines[LEFT]);
I think that the problem might be in the get function where the number is
5000. I tried to understand what is this number for by changing to 1000 or
10000 but nothing changed. How can I fix the code so that it works fine?

requirejs global config in main html file does not work after optimize

requirejs global config in main html file does not work after optimize

I need to add option to configure widget in html file where it will be
used. I found that there is require.js build in mechanism described here:
http://requirejs.org/docs/api.html#config
I managed to make it work in my project but its not working in minified
version.
In HTML file I have:
<script >
var require = {
config: {
'models/ad': {
'myKey':'myValue1'
}
}
}
</script>
And in my ad.js I have:
define(['backbone', 'module'], function(Backbone, module) {
console.log(module.config().myKey);
var BbModel = Backbone.Model.extend({
// Some backbone code
});
return BbModel;
});
Everything works fine (variable is passed from html to module) but if I
optimize:
r.js -o build.js
it just stops working, module.config().myKey returns nothing.
It works for optimized wersion if I add config: { 'models/ad': {
'myKey':'myValue1' } in main.js require.config(...);
Due to project requirements I must set variable in html file.
Do you have any idea what it can be?

How to output to console in C#?

How to output to console in C#?

I don't know how to do this I know ist basic but I learned Visual C# not
console. I already tryed to search but I couldn't find anything

Tuesday, 27 August 2013

Allow for users to import data from their facebook business page (eg. header, logo, business name, description, phone, location etc)

Allow for users to import data from their facebook business page (eg.
header, logo, business name, description, phone, location etc)

Hello i have an wordpress site and would like the users to get their
facebook business page info to my site by url or by login .. however that
works.

IIS Powershell : Assign an existing SSL binding to a website

IIS Powershell : Assign an existing SSL binding to a website

I already have an SSL binding created for one of my websites in IIS 7.5.
Now I'm adding another website which listens on the same IP and port (443)
but uses a different host header.
When I try to assign the binding using this powershell command:
New-WebBinding -Name $siteName -IP "*" -Port 443 -Protocol https
-HostHeader $hostHeader
OR
New-ItemProperty $sitePath -name bindings -value
@{protocol="https";bindingInformation=":443:"+$hostHeader}
I get the following error in Powershell.
SSL binding for end point 0.0.0.0:443 already exists.
+ CategoryInfo : InvalidData: (:) [New-Item], ProviderException
+ FullyQualifiedErrorId : SSL binding for end point 0.0.0.0:443
already ex
ists.,Microsoft.PowerShell.Commands.NewItemCommand
How can I get rid of this error?

Shortcode/BBCode Helper include twitter bootstrap

Shortcode/BBCode Helper include twitter bootstrap

Is there any CakePHP Helper to handle somethings like one_hird,one_half,
... and include twitter bootstrap?

how can fill a grid with kendo ui

how can fill a grid with kendo ui

how can fill a grid with kendo.....
This is my controller it`s work
public JsonResult listarporfecha([DataSourceRequest] DataSourceRequest
request, string anio, string mes) {
List<Reporte1Hist> reporte = new List<Reporte1Hist>();
DateTime fecha;
DateTime time;
short dia = 31;
short year = Convert.ToInt16(anio);
short m = Convert.ToInt16(mes);
// string date = anio + "-" + mes + "-" + dia;
DateTime fdate;
string MyString;
try
{
if (mes == null && anio == null)
{
fecha = DateTime.Now;
}
else
{
time = new DateTime(year, m, dia);
reporte = contexto.Reporte1Hist.Where(p => p.Fecha ==
time).ToList();
}
}
catch (Exception)
{
throw;
}
return Json(new[] { reporte }.ToDataSourceResult(request,
ModelState));
}
and this is my jquery, it does not work
var url = '@Url.Action("listarporfecha","Home")';
$.post(url, { anio: year, mes: month }, function (data) {
$("#Grid").kendoGrid({
dataSource: {
transport: {
read: {
type:"POST",
url: '@Url.Action("listarporfecha","Home")',
dataType: "json",
data:data
}
}
// schema: {
// data: "data"
//}
}
});
});

Get the exit value from the browser unload event ?

Get the exit value from the browser unload event ?

$(window).on("beforeunload", function(){
window.open("survey.html");
return "Are you sure you want to leave?";
});
Once user try to exit from the web page this will ask "Are you sure you
want to leave?"
Is there a way to know whether the user click yes or not from this popup ?

Monday, 26 August 2013

How to get combobox selected item text in silverlight?

How to get combobox selected item text in silverlight?

Anyone tell me the correct syntax for getting combobox selected item text
in silverlight.

POW/Rails error: Error starting applicationBundler::GemNotFound: Could not find minitest-4.7.5 in any of the sources

POW/Rails error: Error starting applicationBundler::GemNotFound: Could not
find minitest-4.7.5 in any of the sources

I just had to remove RVM and reinstall, and then installed Ruby 2.0.0
I was reading through some answers on here about .bash_profile and .bashrc
and neither existed in my ~ folder. I tried putting this in my .bashrc and
reloading to no avail:
In my .bashrc:
[[ -s "$HOME/.rvm/scripts/rvm" ]] && source "$HOME/.rvm/scripts/rvm"
rvm list:
=* ruby-2.0.0-p247 [ x86_64 ]
Now when i try to start my application I see this:
Bundler::GemNotFound: Could not find minitest-4.7.5 in any of the sources
/usr/local/rvm/gems/ruby-2.0.0-p247/gems/bundler-1.3.5/lib/bundler/spec_set.rb:92:in
`block in materialize'
/usr/local/rvm/gems/ruby-2.0.0-p247/gems/bundler-1.3.5/lib/bundler/spec_set.rb:85:in
`map!'
/usr/local/rvm/gems/ruby-2.0.0-p247/gems/bundler-1.3.5/lib/bundler/spec_set.rb:85:in
`materialize'
/usr/local/rvm/gems/ruby-2.0.0-p247/gems/bundler-1.3.5/lib/bundler/definition.rb:114:in
`specs'
/usr/local/rvm/gems/ruby-2.0.0-p247/gems/bundler-1.3.5/lib/bundler/definition.rb:159:in
`specs_for'
/usr/local/rvm/gems/ruby-2.0.0-p247/gems/bundler-1.3.5/lib/bundler/definition.rb:148:in
`requested_specs'
/usr/local/rvm/gems/ruby-2.0.0-p247/gems/bundler-1.3.5/lib/bundler/environment.rb:18:in
`requested_specs'
/usr/local/rvm/gems/ruby-2.0.0-p247/gems/bundler-1.3.5/lib/bundler/runtime.rb:13:in
`setup'
/usr/local/rvm/gems/ruby-2.0.0-p247/gems/bundler-1.3.5/lib/bundler.rb:120:in
`setup'
/usr/local/rvm/gems/ruby-2.0.0-p247/gems/bundler-1.3.5/lib/bundler/setup.rb:17:in
`<top (required)>'
/usr/local/rvm/rubies/ruby-2.0.0-p247/lib/ruby/site_ruby/2.0.0/rubygems/core_ext/kernel_require.rb:116:in
`require'
/usr/local/rvm/rubies/ruby-2.0.0-p247/lib/ruby/site_ruby/2.0.0/rubygems/core_ext/kernel_require.rb:116:in
`rescue in require'
/usr/local/rvm/rubies/ruby-2.0.0-p247/lib/ruby/site_ruby/2.0.0/rubygems/core_ext/kernel_require.rb:122:in
`require'
~/Sites/twojzpower/config/boot.rb:4:in `<top (required)>'
/usr/local/rvm/rubies/ruby-2.0.0-p247/lib/ruby/site_ruby/2.0.0/rubygems/core_ext/kernel_require.rb:51:in
`require'
/usr/local/rvm/rubies/ruby-2.0.0-p247/lib/ruby/site_ruby/2.0.0/rubygems/core_ext/kernel_require.rb:51:in
`require'
~/Sites/twojzpower/config/application.rb:1:in `<top (required)>'
/usr/local/rvm/rubies/ruby-2.0.0-p247/lib/ruby/site_ruby/2.0.0/rubygems/core_ext/kernel_require.rb:51:in
`require'
/usr/local/rvm/rubies/ruby-2.0.0-p247/lib/ruby/site_ruby/2.0.0/rubygems/core_ext/kernel_require.rb:51:in
`require'
~/Sites/twojzpower/config/environment.rb:2:in `<top (required)>'
/usr/local/rvm/rubies/ruby-2.0.0-p247/lib/ruby/site_ruby/2.0.0/rubygems/core_ext/kernel_require.rb:51:in
`require'
/usr/local/rvm/rubies/ruby-2.0.0-p247/lib/ruby/site_ruby/2.0.0/rubygems/core_ext/kernel_require.rb:51:in
`require'
~/Sites/twojzpower/config.ru:3:in `block in <main>'
~/Library/Application
Support/Pow/Versions/0.4.1/node_modules/nack/lib/nack/builder.rb:4:in
`instance_eval'
~/Library/Application
Support/Pow/Versions/0.4.1/node_modules/nack/lib/nack/builder.rb:4:in
`initialize'
~/Sites/twojzpower/config.ru:1:in `new'
~/Sites/twojzpower/config.ru:1:in `<main>'
~/Library/Application
Support/Pow/Versions/0.4.1/node_modules/nack/lib/nack/server.rb:50:in
`eval'
~/Library/Application
Support/Pow/Versions/0.4.1/node_modules/nack/lib/nack/server.rb:50:in
`load_config'
~/Library/Application
Support/Pow/Versions/0.4.1/node_modules/nack/lib/nack/server.rb:43:in
`initialize'
~/Library/Application
Support/Pow/Versions/0.4.1/node_modules/nack/lib/nack/server.rb:13:in
`new'
~/Library/Application
Support/Pow/Versions/0.4.1/node_modules/nack/lib/nack/server.rb:13:in
`run'
~/Library/Application
Support/Pow/Versions/0.4.1/node_modules/nack/bin/nack_worker:4:in `<main>'
rvm info:
system:
uname: "**** 11.4.2 Darwin Kernel Version 11.4.2: Thu Aug 23
16:25:48 PDT 2012; root:xnu-1699.32.7~1/RELEASE_X86_64 x86_64"
system: "osx/10.7/x86_64"
bash: "/bin/bash => GNU bash, version 3.2.48(1)-release
(x86_64-apple-darwin11)"
zsh: "/bin/zsh => zsh 4.3.11 (i386-apple-darwin11.0)"
rvm:
version: "rvm 1.22.3 (master) by Wayne E. Seguin
<wayneeseguin@gmail.com>, Michal Papis <mpapis@gmail.com>
[https://rvm.io/]"
updated: "3 days 23 hours 28 minutes 44 seconds ago"
path: "/usr/local/rvm"
ruby:
interpreter: "ruby"
version: "2.0.0p247"
date: "2013-06-27"
platform: "x86_64-darwin11.4.2"
patchlevel: "2013-06-27 revision 41674"
full_version: "ruby 2.0.0p247 (2013-06-27 revision 41674)
[x86_64-darwin11.4.2]"
homes:
gem: "/usr/local/rvm/gems/ruby-2.0.0-p247"
ruby: "/usr/local/rvm/rubies/ruby-2.0.0-p247"
binaries:
ruby: "/usr/local/rvm/rubies/ruby-2.0.0-p247/bin/ruby"
irb: "/usr/local/rvm/rubies/ruby-2.0.0-p247/bin/irb"
gem: "/usr/local/rvm/rubies/ruby-2.0.0-p247/bin/gem"
rake: "/usr/local/rvm/gems/ruby-2.0.0-p247@global/bin/rake"
environment:
PATH:
"/usr/local/rvm/gems/ruby-2.0.0-p247/bin:/usr/local/rvm/gems/ruby-2.0.0-p247@global/bin:/usr/local/rvm/rubies/ruby-2.0.0-p247/bin:/usr/local/rvm/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/X11/bin:/opt/sm/bin:/opt/sm/pkg/active/bin:/opt/sm/pkg/active/sbin:/usr/local/mysql/bin"
GEM_HOME: "/usr/local/rvm/gems/ruby-2.0.0-p247"
GEM_PATH:
"/usr/local/rvm/gems/ruby-2.0.0-p247:/usr/local/rvm/gems/ruby-2.0.0-p247@global"
MY_RUBY_HOME: "/usr/local/rvm/rubies/ruby-2.0.0-p247"
IRBRC: "/usr/local/rvm/rubies/ruby-2.0.0-p247/.irbrc"
RUBYOPT: ""
gemset: ""

NodeJS merges objects

NodeJS merges objects

I'm working on NodeJS to create a way to send pictures to multiple
displays at once, currently my code has these statements:
var $ = require('jQuery');
var app = require('http').createServer(handler);
var io = require('socket.io').listen(app, { log:false });
var fs = require('fs');
var Server = {
server_address : "XXX.XXX.XXX.XXX", // The server address
playing_now : Object // The playlist that are being synced
};
var Client = {
clients : Object
};
app.listen(1337);
console.log("App is running on port 1337...");
function handler(request, response) {
var ip_address = null;
try{ ip_address = request.header('x-forwarded-for'); }
catch(error){ ip_address = request.connection.remoteAddress; }
Client.clients[ip_address] = "X";
fs.readFile(__dirname + '/index.html', function (err, data) {
if (err) {
response.writeHead(500);
return response.end('Error loading index.html');
}
response.writeHead(200);
response.end(data);
});
}
io.sockets.on('connection', function (socket) {
socket.on("RequestPlaylist", function(json){
Client.clients[json["Address"]] = json["PlayList"];
if(typeof Server.playing_now[json["PlayList"]] === 'undefined'){
$.ajax({
url : "http://" + Server.server_address +
"/buildPlayList.php",
type : "GET",
dataType : "jsonp",
method : "GET",
data : {RemoteIP : json["Address"], Name :
json["PlayList"]}
}).done(function(playlistJSON){
console.log("________________________________________");
console.log("Done");
console.log(Server.playing_now);
Server.playing_now[playlistJSON["playName"]] = playlistJSON;
console.log(Server.playing_now);
console.log("________________________________________");
})
}else{
console.log("________________________________________");
console.log("Redirect");
console.log(Server.playing_now);
console.log("________________________________________");
}
});
});
When a new clients connects, I store it's IP address on Client.clients,
and when I get the json containing the urls to the images, I store it on
Server.playing_now.
The problem is, when I output Server.playing_now, it includes the contents
of Client.clients:
Done
{ [Function: Object] 'XXX.XXX.XXX.XXX': 'Default Media' }
{ [Function: Object]
'XXX.XXX.XXX.XXX': 'Default Media',
'Default Media':
{ '1':
{ json: [Object],
duration: '5',
name: 'Slideshow',
type: 'Image',
sync: '1',
callback: 'jQuery17207063492417801172_1377555709748' },
playName: 'Default Media' } }
Nowhere in my code do I merge these two objects, if I comment out the
Client object, it does return only the contents of Server.playing_now.
Any idea what could be happening? Or is this behavior expected?

Example of stat_summary_hex using alpha aesthetic mapping?

Example of stat_summary_hex using alpha aesthetic mapping?

I'm plotting customer churn using the stat_summary_hex function.
stat_summary_hex(aes(x = Lon, y = Lat, z = Churn), bins=100, colour = NA,
geom = "hex", fun = function(x) sum(x))
ScaleFill <- scale_fill_gradient2(low = "blue", high = "orange", na.value
= NA)
Ideally, I would be able to set the alpha scale such that summary values
close to 0 would have an alpha of 0. However, to my beginner's eyes, it
looks like stat_summary_hex does not acknowledge an alpha aesthetic.
Does someone have an example of stat_summary_hex with alpha mapping?

Django @property calculating a model field: FieldError: Cannot resolve keyword

Django @property calculating a model field: FieldError: Cannot resolve
keyword

I'm following the method used by @Yauhen Yakimovich in this question:
do properties work on django model fields?
To have a model field that is a calculation of a diffrent model.
The Problem:
FieldError: Cannot resolve keyword 'rating' into field. Choices are: _rating
The _rating model field isnt correctly hidden and overriden by my rating
property causing an error when I try to access it.
My model:
class Restaurant(models.Model):
_rating = models.FloatField(null=True, db_column='rating')
@property
def rating(self):
self._rating =
Review.objects.filter(restaurant=self.id).aggregate(Avg('rating'))['rating__avg']
return self._rating
Model in Yauhen's answer:
class MyModel(models.Model):
__foo = models.CharField(max_length = 20, db_column='foo')
bar = models.CharField(max_length = 20)
@property
def foo(self):
if self.bar:
return self.bar
else:
return self.__foo
@foo.setter
def foo(self, value):
self.__foo = value
Any ideas on how to correctly hid the _rating field and define the
@property technique?

Does anyone know any tutorial link to install the Oracle database 12c on Ubuntu 13?

Does anyone know any tutorial link to install the Oracle database 12c on
Ubuntu 13?

I downloaded the database 12c but I'm having trouble installing I'm still
noob because I use ubuntu just four months. Can anyone help me?

Choice of programming language suitable for implementing security algorithms for cloud storage

Choice of programming language suitable for implementing security
algorithms for cloud storage

Which programming language is suitable for implementing security
algorithms for cloud storage?

Sunday, 25 August 2013

How to compile this code implementing Xm on Ubuntu 64 bit using Netbeans?

How to compile this code implementing Xm on Ubuntu 64 bit using Netbeans?

I am just new to X-Windows and trying to code that just calls simple
MessageBox on Linux like Window's.
I am on Ubuntu 12.04LTS 64bit and installed Netbeans full version. I
included "/usr/include/Xm" to this project, and for libs, I included
"Motif" libs.
and following error occurs when I compile the code:
main.cpp:24:63: error: invalid conversion from 'void (*)(Widget,
XtPointer, XmPushButtonCallbackStruct*) {aka void (*)(_WidgetRec*, void*,
XmPushButtonCallbackStruct*)}' to 'XtCallbackProc {aka void
(*)(_WidgetRec*, void*, void*)}' [-fpermissive]
/usr/include/X11/Intrinsic.h:1241:13: error: initializing argument 3 of
'void XtAddCallback(Widget, const char*, XtCallbackProc, XtPointer)'
[-fpermissive]
I really do not understand this error, at least I have never seen syntax
like, "aka void blah blah~~".
Can anyone please help me fix this compile error and, if possible, please
explain me what this error message mean?
Here is original source code:
#include <Xm/Xm.h>
#include <Xm/PushB.h>
/* Prototype Callback function */
void pushed_fn(Widget , XtPointer ,
XmPushButtonCallbackStruct *);
main(int argc, char **argv)
{ Widget top_wid, button;
XtAppContext app;
top_wid = XtVaAppInitialize(&app, "Push", NULL, 0,
&argc, argv, NULL, NULL);
button = XmCreatePushButton(top_wid, "Push_me", NULL, 0);
/* tell Xt to manage button */
XtManageChild(button);
/* attach fn to widget */
XtAddCallback(button, XmNactivateCallback, pushed_fn, NULL);
XtRealizeWidget(top_wid); /* display widget hierarchy */
XtAppMainLoop(app); /* enter processing loop */
}
void pushed_fn(Widget w, XtPointer client_data,
XmPushButtonCallbackStruct *cbs)
{
printf("Don't Push Me!!\n");
}

Split a column by delimiter and replicate the related rows in R

Split a column by delimiter and replicate the related rows in R

With this data
foo 5 49 10
bar 1,2 22 11
I'd like to split the row by second column, such that the final output gives:
foo 5 49 10
bar 1 22 11
bar 2 22 11
I tried colsplit but not quite there yet:
lines <- "
foo 5 49 10
bar 1,2 22 11"
con <- textConnection(lines)
dat<-read.table(con)
colsplit(t$V2,",",c("F1","F2","F3","F4"))
How this can be done correctly?

How to play a song/sound when the phone is in the background

How to play a song/sound when the phone is in the background

So I have a timer that can be set by the user that will will play a
song/sound the user chooses when the timer is over. This works when its in
the foreground since NSTimer is alive. Once the phone enters the
background state, NSTimer is doesn't work. So Ive been looking at possible
solutions like the UILocalNotification but that doesn't play a sound
longer 30 secs. Is there any way I can run a timer in the background that
will trigger to play the sound/song whenever it is done? Or have a method
repeatedly check while its in the background to see if the timer would be
done? Thanks for the help.

Android animated view in bottom of mapview

Android animated view in bottom of mapview

I'm new to android development and I'm creating geoapp with osmdroid as
map provider.
I have a mapView in my activity and I want to create routing view like in
Google maps app (on long press the animated view with address shows in
bottom of mapview)
How can I do it? The question is how to show this animation with
decreasing mapView height?

Returning To Common Sense

Returning To Common Sense

According to this dictionary, the phrase "return to" could mean restart an
activity or go back to a state. But the I saw this sentence in an article:
"He expressed doubt that the United States would return to common sense
after having deserted it for so long, but he pledged that, if genuine
changes did come, the Soviet Union would notice them in time and be a
reliable partner in honest talks."
Common sense is a quality, not an activity or state. So, could "return to
common sense" be an error?

Using SessionHandlerInterface with MySQL database ...please advise

Using SessionHandlerInterface with MySQL database ...please advise

I have made the following code by following
http://www.php.net/manual/en/class.sessionhandlerinterface.php
AND
http://www.wikihow.com/Create-a-Secure-Session-Managment-System-in-PHP-and-MySQL
Here I am using MySQL database to store and retrieve session variables.
This code works fine. However it would be great if you are kind enough to
point out the mistakes and share your input about this code.
class MySessionHandler implements SessionHandlerInterface
{
public function open($savePath, $sessionName)
{
$host = 'localhost';
$user = '******';
$pass = '******';
$name = '*******';
$mysqli = new mysqli($host, $user, $pass, $name);
$this->db = $mysqli;
return true;
}
public function close()
{
return true;
}
public function read($id)
{
if(!isset($this->read_stmt)) {
$this->read_stmt = $this->db->prepare("SELECT data FROM sessions
WHERE id = ? LIMIT 1");
}
$this->read_stmt->bind_param('s', $id);
$this->read_stmt->execute();
$this->read_stmt->store_result();
$this->read_stmt->bind_result($data);
$this->read_stmt->fetch();
$key = $this->getkey($id);
$data = $this->decrypt($data, $key);
return $data;
}
public function write($id, $data)
{
// Get unique key
$key = $this->getkey($id);
// Encrypt the data
$data = $this->encrypt($data, $key);
$time = time();
if(!isset($this->w_stmt)) {
$this->w_stmt = $this->db->prepare("REPLACE INTO sessions (id,
set_time, data, session_key) VALUES (?, ?, ?, ?)");
}
$this->w_stmt->bind_param('siss', $id, $time, $data, $key);
$this->w_stmt->execute();
return true;
}
public function destroy($id)
{
if(!isset($this->delete_stmt)) {
$this->delete_stmt = $this->db->prepare("DELETE FROM sessions WHERE
id = ?");
}
$this->delete_stmt->bind_param('s', $id);
$this->delete_stmt->execute();
return true;
}
public function gc($maxlifetime)
{
if(!isset($this->gc_stmt)) {
$this->gc_stmt = $this->db->prepare("DELETE FROM sessions WHERE
set_time < ?");
}
$old = time() - $max;
$this->gc_stmt->bind_param('s', $old);
$this->gc_stmt->execute();
return true;
}
private function getkey($id) {
if(!isset($this->key_stmt)) {
$this->key_stmt = $this->db->prepare("SELECT session_key FROM
sessions WHERE id = ? LIMIT 1");
}
$this->key_stmt->bind_param('s', $id);
$this->key_stmt->execute();
$this->key_stmt->store_result();
if($this->key_stmt->num_rows == 1) {
$this->key_stmt->bind_result($key);
$this->key_stmt->fetch();
return $key;
} else {
$random_key = hash('sha512', uniqid(mt_rand(1, mt_getrandmax()),
true));
return $random_key;
}
}
private function encrypt($data, $key) {
$salt =
'cH!swe!retReGu7W6bEDRup7usuDUh9THeD2CHeGE*ewr4n39=E@rAsp7c-Ph@pH';
$key = substr(hash('sha256', $salt.$key.$salt), 0, 32);
$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
$encrypted = base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key,
$data, MCRYPT_MODE_ECB, $iv));
return $encrypted;
}
private function decrypt($data, $key) {
$salt =
'cH!swe!retReGu7W6bEDRup7usuDUh9THeD2CHeGE*ewr4n39=E@rAsp7c-Ph@pH';
$key = substr(hash('sha256', $salt.$key.$salt), 0, 32);
$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
$decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $key,
base64_decode($data), MCRYPT_MODE_ECB, $iv);
return $decrypted;
}
}
$handler = new MySessionHandler();
session_set_save_handler($handler, true);
session_start();
Thanks for your time
Cheers

Saturday, 24 August 2013

How would I manage the concept of a User object in PHP?

How would I manage the concept of a User object in PHP?

Okay, I'm still very new to OOP overall, but I've created a few workable
classes now and I'm slowly grasping the various concepts of OOP in PHP. On
a project that I'm working on currently, a user can register,
login/logout, and upload/delete/comment/rate images.
Currently, when a user logs in, I put most of their information (that I
have retrieved from a database) inside the $_SESSION superglobal. This
includes information such as their first name, username, user_id, etc.
Complementing this, I have a page called user.functions.php which has a
number of miscellaneous functions that are related to the concept of a
'user', such as permissions checking, requesting additional user data,
checking a successful login, registering a user, etc.
My question is how would I manage this as a User class? If I understand
correctly, anything called on a page exists on that page only, so wouldn't
I have to declare a
new User();
on each page where I need to perform a task relating to that user? How is
that in anyway efficient? Isn't it just simpler to call a function like:
changeAddress();
instead of:
$user = new User();
$user->changeAddress();
What about critical user data such as the user_id, which I currently store
in a session? Would I migrate that data inside a class too and retrieve it
via a getter method?
Basically, I fail to see how the concept of a user object can improve
overall code quality, if a user, which is an inherently cross-page
concept, is tied to an object, which exists solely within the confines of
a single document?
What am I missing here?

Can you call other segues from other view controllers?

Can you call other segues from other view controllers?

So I have a delegate set up in one class which can potentially enter a
segue. If I call this function from another view controller, will the
segue be performed? Or can only view controllers directly connected to
segues perform a segue?

I haven't participated in the current arena season, will I be able to gain my Conquest Points in the next one?

I haven't participated in the current arena season, will I be able to gain
my Conquest Points in the next one?

I just came back from a long break (I left in 5.1). I just logged in and I
can get 25k conquest points this week. I am wondering if, when the new
patch (and season) arrives, will I still have that available, or I'll
start at the normal rate per week?
This is because I want to hold on to that cap when the new season arrives.
But should I get my gear now?

When saving excel file (openpyxl) and then trying to make excel open it on mac get `Permission denied` error

When saving excel file (openpyxl) and then trying to make excel open it on
mac get `Permission denied` error

This code:
workbook.save(outputf)
system('open ' + outputf)
generates this error when run on my mac:
sh: /Users/tylerjw/Desktop/jim_data/August2013_report.xlsx: Permission denied
The file was created with openpyxl. I have not been able to reproduce the
error outside of my application is a tkinter application that is writing a
considerable amount of data to that file.
When I run similar code in windows it doesn't error, it opens excel with
the file. The only difference is the absence of the open command.
What could case this error?

Android unable to hide Notification bar

Android unable to hide Notification bar

Hidden the notification bar using the theme property in manifest
android:theme="@android:style/Theme.NoTitleBar.Fullscreen"
But once i come out of the application using home screen and get back to
the app the notification bar didn't get hide. how it can be solved

Android: Set maximum volume

Android: Set maximum volume

I am creating simple alarm application which tests if user does not move
with device. If does, Service plays alarm sound.
Problem is, if user set volume to some low values (or mute it). Even if I
use this next code, my application uses this volume setting.
player = MediaPlayer.create(this, R.raw.sound);
audioManager = (AudioManager)getSystemService(AUDIO_SERVICE);
userVolume = this.audioManager.getStreamVolume(AudioManager.STREAM_ALARM);
audioManager.setStreamVolume(AudioManager.STREAM_ALARM,
this.audioManager.getStreamMaxVolume(AudioManager.STREAM_ALARM),
AudioManager.FLAG_PLAY_SOUND);
Is there a way how to set "master" volume?

C# calling form.show() from another thread is not working in setup

C# calling form.show() from another thread is not working in setup

In my c# windows application, I want to show a form by a thread which is
already called by another thread. The code I am using for this is as
below:
private void ThreadFirst()
{
// Do some work...
// Calling second thread from this.
var thread = new Thread(ThreadSecond);
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
}
private void ThreadSecond()
{
StartGetUserAuthenticationDetail();
//Do some work...
}
[STAThread]
private void StartGetUserAuthenticationDetail()
{
try
{
//Do some work...
// Open this form in case of Delayed upload
//Application.DoEvents();
globalForm = new myForm();
globalForm.Show();
Close();
ShowInTaskbar = false;
Application.Run();
}
catch (Exception ex)
{
messagebox.Show(ex.message);
}
}
It is working perfect when I am running this from my solution. But, when I
am creating a msi package for this, both of the forms got hide. Am I
missing something to add into it so that it will work fine from setup
also?
Thanks.

Ios app transfer

Ios app transfer

I am developing an ios app for a client and would like to know that when I
go for the $99 developer program I can post the app and get all the help
but what about when I want to provide everything to the client will they
have to get another apple id and sign up again for the $99 program or will
they have to go for some other program and can the app be transferred from
my account to theirs, it is going to be a free app, so if I manage it in
the clients name is that okay. the app developed by should come as the
"company's name"

Friday, 23 August 2013

Implementing search functionality in a database application

Implementing search functionality in a database application

I am creating a database application in vb.net where I need to implement a
search functionality that should search the whole database and return the
user with a list of records found in the databse that contains the search
string in a DataGridView control.
I used one combobox with name: "colNames" and a textbox where we enter the
search the search string with the name "colValues".
Here is the code I used on the click of search the button:



Dim ds As New DataSet
Dim query As String = "select * from customer where " +
colNames.SelectedValue.ToString + " LIKE " + "'%" + colValues.Text + "%'"
CustomerTableAdapter.Connection.Open()
Dim adp As New SqlDataAdapter(query,
CustomerTableAdapter.Connection.ConnectionString)
adp.Fill(ds, "customer")
CustomerTableAdapter.Connection.Close()
filteredRecords.DataSource = ds
filteredRecords.DataMember = "customer"



The code above throws an exception on line 6 (adp.Fill(ds, "customer")):
"The multi-part identifier "System.Data.DataRowView" could not be bound".
Please help me out debugging it or suggest a new code so that I can
implement the search functionality.

401 unauthorized error when querying imgur api

401 unauthorized error when querying imgur api

I am trying to retrieve pictures from imgur to display on my blog by using
an ajax request in jQuery
$.ajax({
type: "GET",
url: "https://api.imgur.com/3/image/kvM6pxn.json",
dataType: "jsonp",
beforeSend: function(xhr) {
xhr.setRequestHeader('Authorization', 'Client-ID <client-id>');
},
success: function(data) {
console.log(data);
}
});
but I am getting a 401 unauthorized error. Can anyone tell me what I am
doing wrong? Thanks

Web-Api 400 BadRequest when search parameter is blank

Web-Api 400 BadRequest when search parameter is blank

I am using web-api with mvc4
I am making searching functionality, in some cases like if i filter data
then remove that textbox value and then press search button, need to show
whole listing but in my case showing 400 bad request. as search parameter
is blank, i know if search parameter blank then it will throw 400 error
with web-api.
any one have proper solution then please let me know.
data: "CurrPage=" + JsCurrPage + "&PageSize=" + parseInt(pagesize) +
"&BuildTypeName=" + $("#BuildTypeName").val(),
Here in some cases BuildType is blank. when search made
//controller
public HttpResponseMessage GetBuildTypeList(int CurrPage, int PageSize,
string BuildTypeName)
{
}

eReader requires an open and available Connection. The connection's current state is closed

eReader requires an open and available Connection. The connection's
current state is closed

i have C# windows form application form with textbox and richtextbox. I
have to type word in textbox and search meaning of that word in sql
database.But when i accessed one word's meaning from database and try to
access another word's meaning by typing on text box and click on search
botton, it shows error message "ExecuteReader requires an open and
available Connection. The connection's current state is closed.". Anyone
can help me, how to reopen connection at same run time.

IIS Rewriting not working

IIS Rewriting not working

So first of all I apologize for this question, but I'm really new to web
programming and I can't figure out how to properly create a rewrite on IIS
7.
I have this code:
but i can't make it work, it just crashes the server. I'd really
appreciate if somebody could gave me some directions, if there's something
wrong or anything you could see.
Thank you.

how to do i change the value of data from server side?

how to do i change the value of data from server side?

i am trying to set a value from server side in this code. i have a textbox
to enter ticket number and when the ticket is validated and activated, i
want the used property of this particulare ticket to be changed to true.
i have this code :
TicketBLL Tickets = new TicketBLL();
ClientDeviceBLL Devices = new ClientDeviceBLL();
if (String.IsNullOrEmpty(txtTicket.Text))
{
CVUsed.Visible = false;
CVUsed.Enabled = false;
CVMember.Enabled = false;
CVMember.Visible = false;
CVInValid.Enabled = false;
CVInValid.Visible = false;
lblMessages.Text =
MessageFormatter.GetFormattedErrorMessage("You can login using
a Ticket Number.");
txtTicket.Focus();
}
else
{
Ticket = Tickets.GetTicketByTicketNumber(txtTicket.Text);
////// we must enter the value of the correct SN and the
Client ID
Device = Devices.GetClientDeviceBySN(txtSN.Text ,
Convert.ToInt32(txtClientID.Text));
if (Ticket != null)
{
//Correct Ticket number
CVInValid.Visible = false;
CVInValid.Enabled = false;
if (Ticket.Used == true)
{
//ticket was used, internet forbidden
CVUsed.Visible = true;
CVUsed.Enabled = true;
CVMember.Enabled = false;
CVMember.Visible = false;
CVUsed.IsValid = false;
}
else
{
//if exists but not used, Ticket accepted
//check if device is a member if client divices
if (Device != null)
{
//internet access garanteed
CVUsed.Visible = false;
CVUsed.Enabled = false;
CVMember.Enabled = false;
CVMember.Visible = false;
CVUsed.IsValid = true;
CVMember.IsValid = true;
//here is my error.
//ticket.used is not changing in the database so
the next
//time he enters the same ticket number it would go
through
//again.
Ticket.Used = true;
Response.Redirect("http://www.google.com");
}
else
{
//device not member, internet access forbidden
CVMember.Enabled = true;
CVMember.Visible = true;
CVUsed.Visible = false;
CVUsed.Enabled = false;
CVUsed.IsValid = true;
CVMember.IsValid = false;
}
}
}
else
{
//Ticket Number is not valid
CVUsed.Visible = false;
CVUsed.Enabled = false;
CVMember.Enabled = false;
CVMember.Visible = false;
CVInValid.Enabled = true;
CVInValid.Visible = true;
CVInValid.IsValid = false;
}
}
how can i automatically update the ticket.used value in the database?!

Thursday, 22 August 2013

Launching IE on windows phone using powershell

Launching IE on windows phone using powershell

I am trying to automate launching internet explorer on windows phone. I am
using powershell from the PC and using execd command to lauch the
iexplore.exe. execd c:\Programs\Internetexplorer\IExplore.exe I am getting
error code Exit Code : -1073740286
Can someone please help how IE can be launched on the remote device.

Matrices question multiplication and linear equation.

Matrices question multiplication and linear equation.

Need a help to solve this Matrices question
pls check this image which contains the question.
question

Issue trying to change user from Django template

Issue trying to change user from Django template

I need to include two buttons or links to allow users change language
between English and Spanish. I've read the docs and tried this:
<form action="/i18n/setlang/" method="post">{% csrf_token %}
<input name="language" type="hidden" value="es" />
<input type="submit" value="ES" />
</form>
However, every time I click the button, the page is reload but the
language doesn't change at all. Am I missing something?
Note: I haven't set next, as I just want to reload the current page in the
desired language.

join three tables sql

join three tables sql

I have 3 table sales,product_details and order_details. product_details
contain product_id,cost,price order_detail contains product_id, order_id
sales contains date order_id now, I have to minus the sum of cost and
price where date is between __ and __ to show the profit or loss
I have tried this but dont what is the result is showing
SELECT ( SUM(p.price) - SUM(p.cost) )
FROM product_details AS p
LEFT JOIN order_detail AS o
ON o.product_id = p.product_id
JOIN sales AS s
ON s.order_id = o.order_id
WHERE s.[date] = ' 15.08.2013'

Error mounting /dev/sda2 at /media

Error mounting /dev/sda2 at /media

When I try to access my hard disk on Windows I got the following error:
Error mounting /dev/sda2 at /media/debo/2290657790655279: Command-line
`mount -t
"ntfs" -o
"uhelper=udisks2,nodev,nosuid,uid=1000,gid=1000,dmask=0077,fmask=0177"
"/dev/sda2" "/media/debo/2290657790655279"' exited with non-zero exit
status 14:
Windows is hibernated, refused to mount.
Failed to mount '/dev/sda2': Operation not permitted
The NTFS partition is in an unsafe state. Please resume and shutdown
Windows fully (no hibernation or fast restarting), or mount the volume
read-only with the 'ro' mount option.
Please can anyone help me on this?

Upload Amazon S3 videos to Facebook via PHP SDK?

Upload Amazon S3 videos to Facebook via PHP SDK?

I'm creating an application which need to upload a video to a user profile
on Facebook (web hosted application, I am using Facebook PHP SDK). Videos
are hosted on Amazon S3.
I have tried to upload a video that is hosted locally on my instance, and
that is working fine (authentication is OK, and the video is found to be
uploaded).
But I am not able to find how to directly retrieve the video on S3 to
upload it. I have read that this could be done only when the video is
local. But that is not convenient for me to download the video from S3
first then upload it to Facebook.
Has anybody faced this issue, and found a way to solve it so that the
video can be directly uploaded from S3 to Facebook, using the S3 Url ?
Thanks a lot for your help.

Setting up a common nuget packages folder for all sulutions when some projects are included in multiple solutions

Setting up a common nuget packages folder for all sulutions when some
projects are included in multiple solutions

I have been using NuGet to retrieve packages from external and internal
package sources, which is very convenient. But I have realized that the
packages are by default stored per solution, which is very frustrating
when some projects with NuGet references are included in several
solutions. Then the references are changed to other solutions package
folder which may actually be unavailable to another developer or build
machine.
I have seen that there are ways to point out a common package location
(perhaps at the project root level, we are using TFS source control) with
the release 2.1 of NuGet. release notes
But I have tried to add nuget.config files without seeing any effect of
this. Is there anything I have missed? Ther seems to be different
structures of the xml node to add:
<settings>
<repositoryPath>..\..\[relative or absolute path]</repositoryPath>
</settings>
or
<configuration>
<config>
<add key="repositoryPath" value="..\..\[relative or absolute path]" />
</config>
</configuration>
I don't know which one of these, or any, or both will work in the end. I
have tried both at solution level. Do I need to remove all installed
packages before those references will work? I would love if someone could
provide a step-by-step instruction for moving from solution-specific nuget
usage to a common package folder where projects that belong to several
solutions can find their required nuget packages.
Thanks for any help in advance.

Wednesday, 21 August 2013

Multiple TimePicker: select chronological time range

Multiple TimePicker: select chronological time range

I use the UI Timepicker jquery and I would like to select chronological
time range between timepickers. It works between 2 timepickers but in my
case I will have more (example: 3).
I would like to have the chronological time range between all of them.
For example:
Start1: 8:00 End1: 10:00 (start1 have all the time available, end1 have
time available from 8am)
Start2: 10:00 End2: 18:00 (start2 have time available between end1 and
end2, end2 have time available between start2 and start3)
Start3: 18:00 End3: 20:00 (start3 have time available between end2 and
end3, end3 have time available at start3).
So far my code only work for two timepickers and I can't find the way to
do like what I want. Here is my code:
<script type='text/javascript'>
<?php for ($i = 1; $i <= 3; $i++) { ?>
$(document).ready(function () {
$('.timepicker_start<?php echo $i ?>').timepicker({
showLeadingZero: false,
onHourShow: tpStartOnHourShowCallback<?php echo $i ?>,
onMinuteShow: tpStartOnMinuteShowCallback<?php echo $i ?>
});
});
$(document).ready(function () {
$('.timepicker_end<?php echo $i ?>').timepicker({
showLeadingZero: false,
onHourShow: tpEndOnHourShowCallback<?php echo $i ?>,
onMinuteShow: tpEndOnMinuteShowCallback<?php echo $i ?>
});
});
function tpStartOnHourShowCallback<?php echo $i ?>(hour) {
var tpEndHour = $('.timepicker_end<?php echo $i
?>').timepicker('getHour');
if ($('.timepicker_end<?php echo $i ?>').val() == '') { return true; }
if (hour <= tpEndHour) { return true; }
return false;
}
function tpStartOnMinuteShowCallback<?php echo $i ?>(hour, minute) {
var tpEndHour = $('.timepicker_end<?php echo $i
?>').timepicker('getHour');
var tpEndMinute = $('.timepicker_end<?php echo $i
?>').timepicker('getMinute');
if ($('.timepicker_end<?php echo $i ?>').val() == '') { return true; }
if (hour < tpEndHour) { return true; }
if ( (hour == tpEndHour) && (minute < tpEndMinute) ) { return true; }
return false;
}
function tpEndOnHourShowCallback<?php echo $i ?>(hour) {
var tpStartHour = $('.timepicker_start<?php echo $i
?>').timepicker('getHour');
if ($('.timepicker_start<?php echo $i ?>').val() == '') { return true; }
if (hour >= tpStartHour) { return true; }
return false;
}
function tpEndOnMinuteShowCallback<?php echo $i ?>(hour, minute) {
var tpStartHour = $('.timepicker_start<?php echo $i
?>').timepicker('getHour');
var tpStartMinute = $('.timepicker_start<?php echo $i
?>').timepicker('getMinute');
if ($('.timepicker_start<?php echo $i ?>').val() == '') { return true; }
if (hour > tpStartHour) { return true; }
if ( (hour == tpStartHour) && (minute > tpStartMinute) ) { return true; }
return false;
}
<?php } ?>
</script>
<?php for ($i = 1; $i <= 3; $i++) { ?>
<input type='text' class='timepicker_start<?php echo $i ?>'/>
<input type='text' class='timepicker_end<?php echo $i ?>'/>
<?php } ?>
Thanks

Interpreting the result of 'cutree' from hclust/heatmap.2

Interpreting the result of 'cutree' from hclust/heatmap.2

I have the following code that perform hiearchical clustering and plot
them in heatmap.
set.seed(538)
# generate data
y <- matrix(rnorm(50), 10, 5, dimnames=list(paste("g", 1:10, sep=""),
paste("t", 1:5, sep="")))
# the actual data is much larger that the above
# perform hiearchical clustering and plot heatmap
test <- heatmap.2(y)
What I want to do is to print the cluster member from each hierarchy of in
the plot. I'm not sure what's the good way to do it.
I tried this:
cutree(as.hclust(test$rowDendrogram), 1:dim(y)[1])
But having problem in interpreting the result. What's the meaning of each
value in the matrix? For example g9-9=8 . What does 8 mean here?
1 2 3 4 5 6 7 8 9 10
g1 1 1 1 1 1 1 1 1 1 1
g2 1 2 2 2 2 2 2 2 2 2
g3 1 2 2 3 3 3 3 3 3 3
g4 1 2 2 2 2 2 2 2 2 4
g5 1 1 1 1 1 1 1 4 4 5
g6 1 2 3 4 4 4 4 5 5 6
g7 1 2 2 2 2 5 5 6 6 7
g8 1 2 3 4 5 6 6 7 7 8
g9 1 2 3 4 4 4 7 8 8 9
g10 1 2 3 4 5 6 6 7 9 10
Your expert advice will be greatly appreciated.

rvm using /after_cd_bunlder vs --binstubs. How are these different?

rvm using /after_cd_bunlder vs --binstubs. How are these different?

How are the outcome of these two methods different? Why use one over the
other? I believe they both end up enabling you to issue 'rake' or 'rspec'
without the preceeding 'bundle exec". My guess - with method 1 you only
have to do this once, and then on ALL new rails project for the rvm ruby
version will automatically have the desired feature ( as explained above)?
Method 1:
rvm get head && rvm reload
chmod +x $rvm_path/hooks/after_cd_bundler
bundle install --binstubs
OR
Method 2:
bundle install --binstubs
If found this documentation, but it did not help me understand which
method to use. I looked on http://rv.io and found intergration/bundler and
/workflow/hooks.
The is code for after_cd_bundler (but I cannot post anymore links due to
stackoverflow.com limitations on me)

Two A records - One Local IP and One Online IP [duplicate]

Two A records - One Local IP and One Online IP [duplicate]

This question already has an answer here:
Returning different DNS records depending on who asks 3 answers
I have a bit of a strange requirement and I want to know if its possible.
I want to create the following domain name, server.example.com.
When im in the office, I would like to use server.example.com and have it
use my LAN connection so its nice and fast.
When im out of the office, I would like it to still use server.example.com
and have it see that im not on the local network, and use the online IP.
At the moment I have it setup like this:
My DNS zone for example.com (two A records):
server A 192.168.1.253 (local IP)
server A 1.1.1.1 (online IP)
Thats as far as I have gotten, but when I traceroute from outside of the
office lan I get this:
traceroute: Warning: server.example.com has multiple addresses; using
192.168.1.253
traceroute to server.example.com (192.168.1.253), 64 hops max, 52 byte
packets
At this point, I was hoping it would have used the online IP.
Any idea how I can achieve this?

How to replace a FixedDocument in an XPS file with another FixedDocument?

How to replace a FixedDocument in an XPS file with another FixedDocument?

I have an existing XPS file and it contains one document. I'm trying to
replace this document with another one.
I try to do it as below but get a "Package already has a root
DocumentSequence or FixedDocument." exception.
using (var xpsDoc = new XpsDocument(_Url, FileAccess.ReadWrite))
{
string path = @"C:\Users\Wesley Manning\Desktop\test.xps";
FixedDocument fd_read;
using (var xpsDocToRead = new XpsDocument(path, FileAccess.Read))
{
FixedDocumentSequence fds_read =
xpsDocToRead.GetFixedDocumentSequence();
DocumentReference dr_read = fds_read.References[0];
fd_read = dr_read.GetDocument(false);
}
FixedDocumentSequence fds = xpsDoc.GetFixedDocumentSequence();
DocumentReference dr = fds.References[0];
dr.SetDocument(fd_read);
XpsDocumentWriter writer = XpsDocument.CreateXpsDocumentWriter(xpsDoc);
writer.Write(fds);
}
Is there any way to replace the existing document without having to
overwrite the entire file? I can do it by overwriting the entire file but
I don't want to do that.
The reason I don't want to overwrite the file is that it is a custom file
format (mine) and the OPC package contains other data not related to XPS.
If I overwrite the file I would have recopy the data to the new file or
lose it. Also lets say in future there could be multiple documents in the
same XPS file.
FYI: I want to use the XPS payload/portion of the package to easily
present a "preview" of the data to the user.

Magento error while trying to duplicate a product with tier price

Magento error while trying to duplicate a product with tier price

I am trying to duplicate a product using the code (Magento Community Edition)
$product = Mage::getModel('catalog/product')->load($id);
$newProduct = $product->duplicate();
$newProduct->setStatus(1);
$newProduct->setSku(rand(1, 99999));
$newProduct->getResource()->save($newProduct);
It works fine for products without tier pricing. But shows the error for
products with tier pricing...
a:5:{i:0;s:98:"SQLSTATE[23000]: Integrity constraint violation: 1062
Duplicate entry '64-1-0-10.0000-0' for key 2";i:1;s:2045:"#0
/Library/WebServer/Documents/magentoversion/app/Mage.php(462):
Mage_Core_Model_Config->getModelInstance('eav/entity_attr...',
'SQLSTATE[23000]...')
regards,
Leo

FHSTwitterEngine can't post a twitt with image

FHSTwitterEngine can't post a twitt with image

i use the demo FHSTwitterEngine.
i use the method "- (NSError *)postTweet:(NSString *)tweetString
withImageData:(NSData *)theData",but it's fail.
The return data shows that :"{"errors":[{"code":195,"message":"Missing or
invalid url parameter"}]}",the response.statusCode is 403.
the tweetString and theData of image are both not nil.
how can i solve it.

Tuesday, 20 August 2013

Drill-down stacked bar chart in android

Drill-down stacked bar chart in android

Is there any chart libraries having with drill-down? (Clickable event).I
already tried in Achartengine with onTouch but i can't able to get the
SeriesSelection,it's always throw null. Code Snippet i used:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.barchart_show);
barLayout = (LinearLayout) findViewById(R.id.barchart_main);
stBarChart = new StackedBarChart();
List<double[]> values = new ArrayList<double[]>();
values.add(new double[] { 14230, 12300, 14240, 15244, 15900,
19200, 22030, 21200, 19500, 15500,
12600, 14000 });
values.add(new double[] { 5230, 7300, 9240, 10540, 7900, 9200,
12030, 11200, 9500, 10500,
11600, 13500 });
barChartView = stBarChart.execute(values, getApplicationContext());
if(barChartView!=null) {
barChartView.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
SeriesSelection seriesSelection =
barChartView.getCurrentSeriesAndPoint();
double[] xy = barChartView.toRealPoint(0);
if (seriesSelection == null) {
Toast.makeText(BarChartShow.this, "No chart element
was clicked", Toast.LENGTH_SHORT)
.show();
} else {
Toast.makeText(
BarChartShow.this,
"Chart element in series index " +
seriesSelection.getSeriesIndex()
+ " data point index " +
seriesSelection.getPointIndex() + " was
clicked"
+ " closest point value X=" +
seriesSelection.getXValue() + ", Y=" +
seriesSelection.getValue()
+ " clicked point value X=" + (float) xy[0] +
", Y=" + (float) xy[1],
Toast.LENGTH_SHORT).show();
}
return true;
}
});
barLayout.addView(barChartView, new
LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT));
}
}
public GraphicalView execute(List values,Context context) {
String[] titles = new String[] { "2008", "2007" };
int[] colors = new int[] { Color.BLUE, Color.CYAN };
XYMultipleSeriesRenderer renderer = buildBarRenderer(colors);
renderer.setOrientation(Orientation.VERTICAL);
setChartSettings(renderer, "Monthly sales in the last 2 years",
"Month", "Units sold", 0.5,
12.5, 0, 24000, Color.GRAY, Color.LTGRAY);
renderer.getSeriesRendererAt(0).setDisplayChartValues(true);
renderer.getSeriesRendererAt(1).setDisplayChartValues(true);
//renderer.getSeriesRendererAt(2).setDisplayChartValues(true);
renderer.setXLabels(12);
renderer.setYLabels(10);
renderer.setXLabelsAlign(Align.LEFT);
renderer.setYLabelsAlign(Align.LEFT);
renderer.setPanEnabled(true, false);
// renderer.setZoomEnabled(false);
renderer.setZoomRate(1.1f);
renderer.setBarSpacing(0.5f);
renderer.setClickEnabled(true);
barChartView = ChartFactory.getBarChartView(context,
buildBarDataset(titles, values),
renderer, Type.STACKED);
return barChartView;
}

objective-C - How to keep in memory dynamic control objects in my tableview

objective-C - How to keep in memory dynamic control objects in my tableview

I'm developing a dinamic app in objective-C which parses from a webServer
an XML and specifies to my tableView controller how many and which
controls (labels, textfields... should print, like a formulary)
The thing is... if my screen can't show all the controls, I use the scroll
to navigate through all my scene, til then everything is okay but... When
I do that, all my controls (labels, textfields) dissapear!!!Leaving all my
tableviewcells empty!!!
If I release the scroll and gets back to original position (on top), all
my controls are printed again, but all the information inside textfields
is gone,
I guess it is because of a memory thing (weak memory), how can I store all
my controls with (strong) like a property to keep them alive
Note: I can't control the amount and type of controls that my webService
sends throught the XML...
this is how I do so far:
- (void)viewDidLoad
{
[super viewDidLoad];
if ([[UIDevice currentDevice].model hasPrefix:@"iPhone"]){
locationXLabel = 20;
locationXControl = 150;
widthLabel = 130;
}
if ([[UIDevice currentDevice].model hasPrefix:@"iPad"]){
locationXLabel = 65;
locationXControl = 250;
widthLabel = 190;
}
locationYLabel = 10;
locationYControl = 15;
//WebService for printing controls
if (!parBusResponseWebServ) parBusResponseWebServ = [[ParBusResponseWS
alloc]imprimePantallaBusqueda];
while ([parBusResponseWebServ transacWebServCompleto] == Nil) {
[[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode
beforeDate:[NSDate distantFuture]];
}
//if webservice loads incomplete sends this message and exit
if ([[parBusResponseWebServ transacWebServCompleto]
isEqualToString:@"FALSE"] ||
[[parBusResponseWebServ controlsList] count] <= 0) {
parBusResponseWebServ = Nil;
return;
}
controlsArray = [[NSMutableArray alloc]init];
self.title = @"Búsqueda";
if (!functions) functions = [[Functions alloc]init];
[self createTableView];
}
-(void)createTableView{
//this instance, creates, sets as a delegate and displays tableview
self.myTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0,
self.view.frame.size.width,
self.view.frame.size.height)style:UITableViewStyleGrouped];
self.myTableView.autoresizingMask = UIViewAutoresizingFlexibleHeight |
UIViewAutoresizingFlexibleWidth;
self.myTableView.backgroundView = nil;
self.myTableView.backgroundColor =
UIColorFromRGB(tableViewBackgroundColor);
self.myTableView.separatorColor =
UIColorFromRGB(tableViewSeparatorColor);
self.myTableView.separatorStyle =
UITableViewCellSeparatorStyleSingleLineEtched;
self.myTableView.delegate = self;
self.myTableView.dataSource = self;
[self.view addSubview:self.myTableView];
}
//Sets and returns the contents that will have each row of the table
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath {
NSString *cellIdentifier = [NSString
stringWithFormat:@"s%i-r%i", indexPath.section, indexPath.row];
UITableViewCell *cell = [tableView
dequeueReusableCellWithIdentifier:cellIdentifier];
if (cell == nil)
{
cell = [[UITableViewCell alloc]
initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:cellIdentifier];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
switch (indexPath.section) {
case 0:
{
switch (indexPath.row) {
case 0:{
for (int i = 0; i <
[parBusResponseWebServ.controlsList count]; i++) {
if ([[[parBusResponseWebServ.controlsList
objectAtIndex:i]tipoControl]
isEqualToString:@"TX"]) {
UILabel *label = [functions
createLabel:[[parBusResponseWebServ.controlsList
objectAtIndex:i] textoControl]
locationX:locationXLabel
locationY:locationYLabel
labelWidth:widthLabel
labelHeight:30
numLabelTag:tagControls
labelAdjustment:UIViewAutoresizingFlexibleRightMargin];
tagControls += 1;
UITextField *textfield = [functions
createTextField:@" "
locationX:locationXControl
locationY:locationYControl
textFieldlWidth:150
textFieldHeight:30
keyboardType:UIKeyboardTypeDefault
placeholderText:[[[parBusResponseWebServ.controlsList
objectAtIndex:i]requerido]
isEqualToString:@"TRUE"]
?
@"Requerido***"
:
@"Introduce
Texto"
numTextFieldTag:tagControls
textFieldAdjustment:UIViewAutoresizingFlexibleWidth];
tagControls += 1;
[cell addSubview:label];
[cell addSubview:textfield];
[controlsArray addObject:textfield];
locationYControl += 45;
locationYLabel += 45;
}
if ([[[parBusResponseWebServ.controlsList
objectAtIndex:i]tipoControl]
isEqualToString:@"CB"]) {
UILabel *label = [functions
createLabel:[[parBusResponseWebServ.controlsList
objectAtIndex:i] textoControl]
locationX:locationXLabel
locationY:locationYLabel
labelWidth:widthLabel labelHeight:30
numLabelTag:tagControls
labelAdjustment:UIViewAutoresizingFlexibleRightMargin];
tagControls += 1;
UITextField *campotexto = [functions
createTextField:@" "
locationX:locationXControl
locationY:locationYControl
textFieldlWidth:120
textFieldHeight:30
keyboardType:UIKeyboardTypeDefault
placeholderText:@"Seleccione"
numTextFieldTag:tagControls
textFieldAdjustment:UIViewAutoresizingFlexibleWidth];
tagControls += 1;
UIButton *button =[functions
createButton:@" "
locationX:270
locationY:locationYLabel
buttonWidth:30
buttonHeight:30
buttonType:UIButtonTypeDetailDisclosure
numButtonTag:tagControls
buttonAdjustment:UIViewAutoresizingFlexibleLeftMargin];
[button addTarget:self
action:@selector(action)
forControlEvents:(UIControlEvents)UIControlEventTouchUpInside];
[cell addSubview:label];
[cell addSubview:campotexto];
[cell addSubview:button];
[controlsArray addObject:campotexto];
locationYControl += 45;
locationYLabel += 45;
}
if ([[[parBusResponseWebServ.controlsList
objectAtIndex:i]tipoControl]
isEqualToString:@"TA"]){
locationYControl += 30;
UILabel *label = [functions
createLabel:[[parBusResponseWebServ.controlsList
objectAtIndex:i] textoControl]
locationX:locationXLabel
locationY:locationYLabel
labelWidth:widthLabel
labelHeight:30
numLabelTag:tagControls
labelAdjustment:UIViewAutoresizingFlexibleRightMargin];
tagControls += 1;
UITextView *textView = [functions
createTextArea:@" "
locationX:locationXLabel
locationY:locationYControl
textViewlWidth:280
textViewHeight:70
keyboardType:UIKeyboardTypeDefault
numTextViewTag:tagControls
textViewAdjustment:UIViewAutoresizingFlexibleRightMargin];
tagControls += 1;
[cell addSubview:label];
[cell addSubview:textView];
[controlsArray addObject:textView];
locationYControl += 135;
locationYLabel += 130;
}
}
}
break;
default:
break;
}
break;
default:
break;
}
}
}
return cell;
}

Pronounciation of either

Pronounciation of either

Is the word "either" pronounced as "ee-ther" or as "uhee-ther"?
I have heard both, so I would like to know which one is correct; should
both be correct, is there any rule as to when to pronounce it one way or
the other?

Calling private method in BaseClass from a derived class with Reflection.Emit

Calling private method in BaseClass from a derived class with Reflection.Emit

I'm looking for a way to call a private method from a base class in a
derived classes with the TypeBuilder. I know this can be done by simply
invoking the method via reflection but attempting to call a passthrough
method generated with the typebuilder results in a MethodAccessException.
Has anyone found a way around this issue?

Is there a way to set a JVM flag dynamically?

Is there a way to set a JVM flag dynamically?

I want to turn the -verbose:class on only for debugging a specific class
loader scenario. Is there a way to enable and disable this flag any other
way than at JVM startup, for example, through JMX or programmatically?

using wordpress SMOF frameworks options safely

using wordpress SMOF frameworks options safely

Could you please tell how to use SMOF to avoid security issues with
option? For example, in code of SMOF I see that options are not escaped
before output to hmtl. What to do with this? Change SMOF to escape before
output of options in html? Does SMOF care about validation and sanitizing
of options when it stores it? It's rather strange that I couldn't find
much info how to use SMOF safely.

What is the point of Collection

What is the point of Collection

I have been reading Effective Java and I have come across the unbounded
Collection type <?>. However, the reading has led me to believe that you
can't put any elements, other than null, into an instance of
Collection<?>. Therefore, my question is this: What is the purpose of
instantiating a Collection<?> when we can only insert null elements as
that just seems pointless. I've been trying to figure this concept, but it
just doesn't seems to make much sense. Any help would be much appreciated.

Monday, 19 August 2013

C# Showing Buttons on taskbar thumbnails

C# Showing Buttons on taskbar thumbnails

In WMP, I have been shown buttons on the taskbar thumbnail. How can I make
them for my winforms app in C#?

KineticJS afterFrame doesn't run on loop

KineticJS afterFrame doesn't run on loop

I tried to have a reloading animation change values for my character. I
want player.shots to go up by 1 every time the animation loops. However,
it runs once and the animation continues Here is the code I have.
gun.setAnimation('reload');
gun.afterFrame(6,function(){
console.log('reload');
player.shots++;
if(player.shots > 5){
gun.setAnimation('idle');
}
}
Interestingly, if an error occurs in the function it works like expected.
gun.setAnimation('reload');
gun.afterFrame(6,function(){
console.log('reload');
player.shots++;
if(player.shots > 5){
gun.setAnimation('idle');
}
console(y) //this is an intentional error
}
This leads me to believe that afterFrame determines if it should run on
the next iteration or not based on a return value.
Is there any nice workaround or parameter I need to add, or should I just
keep intentionally causing an error to get the desired behavior?

How to make your own properties, eg. "devise :authenticable" in ruby / rails

How to make your own properties, eg. "devise :authenticable" in ruby / rails

I was wondering how I could have various properties in my models. Eg:
Property < ActiveRecord::Base
locatable, saleable ...
Would these be mixins? Or is there another way of implementing this? eg.
the way devise has:
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :token_authenticatable, :confirmable,
# :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
end

Spritely div .click not working

Spritely div .click not working

I am using the JS plugin called "Spritely" to animate background images.
Everything works (backgrounds are moving). But I can't get a function to
be active when clicked on a div(sprite).
(I have the script.js, jquery and spritely included in the ).
HTML is just 2 divs (#container and #hills)
css
#container
{
width:100%;
height:100%;
margin-left:auto;
margin-right:auto;
background-image:url(clouds.jpg);
background-repeat:repeat-x;
z-index:-3;
position:absolute;
}
#hills
{
width:100%;
height:250px;
background-image:url(hills.png);
background-repeat:repeat-x;
background-position:bottom;
z-index:1;
position:absolute;
bottom:0px;
}
javascript
$(document).ready(function() {
$(hills).click(function(){
alert("hey");
});
});
var hills;
$(document).ready(function(){
var hills = document.getElementById('hills');
$(hills).pan({fps: 30, speed: 2, dir: 'left'});
});

Logic between rounding decimals to 2 digits c++

Logic between rounding decimals to 2 digits c++

I recently came across the following piece of code to display 2 decimal
digits.
val = (val*100.0)/100.0
The result was as told, but I don't get the logic behind the functioning
of it. Can anyone please explain. Thank you.

Sunday, 18 August 2013

Application Design - Validation and efficiency

Application Design - Validation and efficiency

I have an ASP.Net application which has a lot of business rules with
regards to if an object is OK to be commited to the database.
On a basic level, a person is part of a sprint, which is part of a project.
The basic rules are:
A person is assigned to a sprint, but maybe not the full duration of a
sprint (Which has a start and end date). So, when they assign the person,
his start date and end date must be between (inclusivly) the start and end
date of a sprint.
A project can have many sprints, but none can be outside of the project
start/end dates.
My solution has a UI project, Service layer, business layer and data
access layer.
I am building in the validation now, but am not sure at what level in my
app, the calidation should occur. I don't believe it's at the UI, as then
I need to duplciate the validation rules on my ASP.Net project ... maybe
my WinForms front end...
I think it should be in the busines logic, as it has business rules. So, I
was going to make a class called "Validations", and for each of my
business objects that get stored to the database, I have a method in my
Validations called "IsObjectOK", taking in the object type I want to
validate, and returning a List of errors.
So:
public List<String> IsObjectOK(SprintDto source)
{
// Do validations, and return list of errors, or NULL if none
}
An example then of a validation rule might be:
var Project = BusinessLayer.GetProject(source.ProjectId);
// check if Start/End dates fall between Project.Start and Project.End dates
If there's an issue, add it to the error list.
This seems like a good way to go. I am looking for confirmation on my
method of handling validation, and any tips and tricks? Should I not worry
about the database hits? I mean, for a sprint, there may be around 6 or 7
'rules' I need to validate, all of which may take data from different
tables. So, that's 7 database queries (Plus the connection overhead), for
a single save. (SQL Server 2012). I think that's not a worry, as it's all
confided to the Business and data layers.

python http request equivalent in node

python http request equivalent in node

I am having trouble sending post request in node.js http.request. I send
similar requests in python to same endpoint and it works.
PYTHON Request works:
def updateData (self, context, query):
params = { 'update': query, 'context' : context }
endpoint = self.getEndpointStatements(params)
headers = {
'content-type': 'application/x-www-form-urlencoded',
'accept': 'application/sparql-results+json'
}
(response, content) = httplib2.Http().request(endpoint, 'POST',
urllib.urlencode(params), headers=headers)
def getEndpointStatements (self, params):
endpoint = 'http://example.com/statements?%s" %
(urllib.urlencode(params))
return endpoint
This works
Howver, I try to create a node HTTP request, I keep getting "socket hangup
error". I upgraded to 0.10.x
var querystring = require('querystring');
var data = querystring.stringify({
update: sparqlQ
});
console.log(data)
var options = {
host: process.env['SESAME_HOST'],
port: process.env['SESAME_PORT'],
method: 'POST',
path: '/openrdf-sesame/repositories/repo/statements/',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': data.length
},
};
var req = http.request(options, function(res) {
res.setEncoding('utf8');
res.on('data', function (chunk) {
console.log("body: " + chunk);
});
});
req.write(data);
req.end();
Please help me fix request in node.js. Python request works.