Wednesday, 2 October 2013

Difference between using .ipp extension and .cpp extension files

Difference between using .ipp extension and .cpp extension files

Suppose I have 2 header files, 1 .ipp extension file and a main.cpp file:
First header file(like interface in Java):
template<class T>
class myClass1{
public:
virtual int size() = 0;
};
second header file:
#include "myClass1.h"
template<class T>
class myClass2 : public myClass1<T>
public:
{
virtual int size();
private:
int numItems;
};
#include "myClass2.ipp"
And then is my myClass2.ipp file:
template <class T>
int myClass2<T>::size()
{
return numItems;
}
Last one is my main:
#include "myclass2.h"
void tester()
{
myClass2<int> ForTesting;
if(ForTesting.size() == 0)
{
//......
}
else
{
//.....
}
}
int main(){
tester();
return 0;
}
myClass1, myClass2 and myClass2.ipp belong to header file. main.cpp in
source file. What's the advantages by using this way to implement your
program instead of using just .h and .cpp files? And what is .ipp
extension file? The difference between .ipp and .cpp?

How to add remove dynamic elements using jquery?

How to add remove dynamic elements using jquery?

This code works when adding a dynamic table with data coming from an ajax
request but can not remove the dynamic table. I code below shows whenever
I click on a tree node, it should load its mysql table data into a HTML
table.
$("#treeNodes").on("select_node.jstree", function(event, data)
{
var node = data.rslt.obj;
var nodeID = node.attr("id");
event.stopImmediatePropagation;
if(/leaf/.test(nodeID))
{
$(".tableData > *").remove(); // remove all table data (tr
rows) before adding the new data and not working or firing
off.
addTableData(); // This function get the data from a mysql
table and loads it into an HTML table.
}
});
<table>
<tbody class='tableData'></tbody>
</table>
Would someone kindly show me how this code can recognize the newly added
dynamic table data so it can be removed?

Notification Hub Implementation for WIndows phone

Notification Hub Implementation for WIndows phone

Hello friends i have to implement a notification hub for sending
toast(push notification) to all app users but the link provided by windows
azure for implementing notification hub for windows phone is not working i
am able to create my notification hub. so i just wanted to know am i
missing something or what is proper way of implementing it. i know this
question is little bit weird but i am just tired to not able to get how to
do it.any fully working link or any help is appreciated here is the link

Tuesday, 1 October 2013

How do i wrap structs that contain struct pointers in CFFI?

How do i wrap structs that contain struct pointers in CFFI?

in the IplImage struct documentation here
http://docs.opencv.org/modules/core/doc/old_basic_structures.html?highlight=iplimage#iplimage
it describes the IplROI* roi slot and it seems to be a pointer to the
IplROI struct defined here in the core types_c.h header file:
typedef struct _IplROI
{
int coi; /* 0 - no COI (all channels are selected)
, 1 - 0th channel is selected ...*/
int xOffset;
int yOffset;
int width;
int height;
}IplROI;
but it also describes the IplImage* maskROI slot and in the core types_c.h
file there is no typedef struct for that...
if some one could help me find it i would appreciate it but i did grep the
entire opencv download and found nothing.....Im attempting to wrap the
IplImage struct with lisp and i wrapped it with swig and got this
(cffi:defcstruct ipl-image
(n-size :int)
(id :int)
(n-channels :int)
(alpha-channel :int)
(depth :int)
(color-model :pointer)
(channel-seq :pointer)
(data-order :int)
(origin :int)
(align :int)
(width :int)
(height :int)
(roi (:pointer (:struct ipl-roi)))
(mask-roi :pointer)
(image-id :pointer)
(tile-info :pointer)
(image-size :int)
(image-data :string)
(width-step :int)
(border-mode :pointer)
(border-const :pointer)
(image-data-origin :string))
i changed it a bit here
(cffi:defcstruct ipl-image
(n-size :int)
(id :int)
(n-channels :int)
(alpha-channel :int)
(depth :int)
(color-model :int) ;;Ignored by OpenCV - was :pointer,
changed to :int so the struct values
would match OpenCV's
(channel-seq :int) ;;Ignored by OpenCV - was :pointer,
changed to :int so the struct values
would match OpenCV's
(data-order :int)
(origin :int)
(align :int)
(width :int)
(height :int)
(roi (:pointer (:struct ipl-roi))) ;; changed so i could access
(:struct ipl-roi)
(mask-roi :pointer)
(image-id :pointer)
(tile-info :pointer)
(image-size :int)
(image-data :string)
(width-step :int)
(border-mode :pointer)
(border-const :pointer)
(image-data-origin :string))
so when i ran the below code in emacs(shown with output) all the slot
values would match the opencv output from the exact same code, which they
do and so i could access the ipl-roi struct with the ipl-image struct
using this line
(roi (:pointer (:struct ipl-roi))) ;;
because my gut tells me its the right way
; SLIME 2012-05-25
CL-OPENCV> (size-of '(:struct ipl-image))
128
CL-OPENCV> (defparameter img-size (make-size :width 640 :height 480))
(defparameter img (create-image img-size +ipl-depth-8u+ 3))
IMG
CL-OPENCV> (cffi:with-foreign-slots ((n-size id n-channels
alpha-channel depth color-model
channel-seq data-order origin
align width height roi
mask-roi image-id tile-info
image-size image-data width-step
border-mode border-const image-data-origin)
img (:struct ipl-image))
(format t "n-size = ~a~%id = ~a~%n-channels =
~a~%alpha-channel = ~a~%depth =
~a~%color-model =
~a~%channel-seq = ~a~%data-order =
~a~%origin = ~
a~%align = ~a~%width = ~a~%height =
~a~%roi = ~a~
%mask-roi = ~a~%image-id = ~a~%tile-info =
~a~%
image-size = ~a~%image-data =
~a~%width-step =
~a~%border-mode = ~a~%border-const =
~a~%image-
data-origin = ~a~%"
n-size id n-channels
alpha-channel depth color-model
channel-seq data-order origin
align width height roi
mask-rOI image-id tile-info
image-size image-data width-step
border-mode border-const image-data-origin))
n-size = 144
id = 0
n-channels = 3
alpha-channel = 0
depth = 8
color-model = 4343634
channel-seq = 5392194
data-order = 0
origin = 0
align = 4
width = 640
height = 480
roi = #.(SB-SYS:INT-SAP #X00000000)
mask-roi = #.(SB-SYS:INT-SAP #X00000000)
image-id = #.(SB-SYS:INT-SAP #X00000000)
tile-info = #.(SB-SYS:INT-SAP #X00000000)
image-size = 921600
image-data =
width-step = 1920
border-mode = #.(SB-SYS:INT-SAP #X00000000)
border-const = #.(SB-SYS:INT-SAP #X00000000)
image-data-origin = NIL
NIL
CL-OPENCV>
but for the IplImage* maskROI slot there is no struct to wrap so i was
hoping some one could give me a quick lesson on how to wrap structs that
contain struct pointers in CFFI and if i'm right in thinking this line
(roi (:pointer (:struct ipl-roi)))
is the right thing to do and how to use it
I would really apreciate any help on this

Passing unicode characters to Jython

Passing unicode characters to Jython

I am trying to run a python code on Jython, and this code contains some
Unicode literals. I'd like to pass the code as a String (rather than load
from a file).
It seems that upon exec() method call the unicode characters are converted
to "?" characters:
PythonInterpreter interp = new PythonInterpreter(null, new PySystemState());
System.out.println("â".codePointAt(0)); // outputs 257
interp.exec("print ord(\"â\")"); // outputs 63
I can't seem to find a way how to pass the string to the interpreter
without messing those characters up.

How to log in to Skype via command line

How to log in to Skype via command line

pI am aware of how to install Skype via command line - by adding the
Canonical Partner repo and using apt-get./p pHowever, how can I log in via
the command line? There are two reasons I want to do this. First is down
to this being Ubuntu Server with no connected monitor and no desktop
window manager running (and I don't want one, this is running on AWS
micro). Second is to automate login upon boot up./p pThe end goal here is
to build a Skype bot using Skype4Py (a Python lib)./p pThanks in advance/p

Find $dx/dy$ by implicit differentiation of $\tan(x + y)$ at point $(0,0)$

Find $dx/dy$ by implicit differentiation of $\tan(x + y)$ at point $(0,0)$

I want to first know how to find the derivative of my trig function using
chain rule. Help

Monday, 30 September 2013

Should I offer refund of upfront payment of a job I failed to complete=?iso-8859-1?Q?=3F_=96_freelancing.stackexchange.com?=

Should I offer refund of upfront payment of a job I failed to complete? –
freelancing.stackexchange.com

I works part time as a freelancer at odesk. Recently, I got a fixed price
job of around 6 hours. I requested a 10% upfront payment for job. But,
after spending 1:30 hours trying to do job, I figure …

Integer multiples of $2\pi$ on $\cos$ function

Integer multiples of $2\pi$ on $\cos$ function

Suppose you know that the smallest positive value $t$ such that $\cos t=0$
is $t=\dfrac{\pi}{2}$, but you don't know other values of $\cos$ and
$\sin$.
You also know that $u$ is a real number such that $\cos u=1$ and $\sin u=0$.
Just from this, can you conclude that $u$ must be an integer multiple of
$2\pi$?
(You know the usual trig identities, such as $\cos^2x+\sin^2x=1$ and $\cos
2x=2\cos^2x-1$.)

What should the type of the return value of the key function in sort() be?

What should the type of the return value of the key function in sort() be?

In python, the sort method of lists accepts a key parameter which is a
function.
My question is, what constraints are there on the returned value of key?
Should it be a numeric value? Should it be somehow comparable? Or does
every type of value just work?

Automatic routing filter rejected remote request - Nexus

Automatic routing filter rejected remote request - Nexus

I'm trying to get the netty-codec-hhtp going in my maven project. I have a
completely standard Sonatype Nexus set up to proxy requests to Maven
Central.
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-codec-http</artifactId>
<version>4.0.9.Final</version>
</dependency>
This fails when building using maven. If I search for it manually in Nexus
I find it, but if I go to download the jar it tells me:
404 - Not Found
Automatic routing filter rejected remote request for path
/io/netty/netty-codec-http/4.0.9.Final/netty-codec-http-4.0.9.Final.jar
from M2Repository(id=central)
What does this even mean, why am I getting it, and maybe more importantly,
how do I fix it? I am using Nexus 2.5.0-04 with Maven 3.0.4
Downloading other artifacts seems to work just fine.

Sunday, 29 September 2013

How to develop an android remote touchpad and keyboard app to computer using Wi-Fi?

How to develop an android remote touchpad and keyboard app to computer
using Wi-Fi?

I want to develop an android remote touchpad and keyboard using Wi-Fi like
this one HERE
Where should I start? Can you give me some suggestion. Thanks in advance.

error handling with python lists

error handling with python lists

I have lists being created by a program and depending if a value exists I
want to do something further. If not, I want to pass.
For example:
a=[1,2,3,4,5]
if a.index(6):
print "in"
I get the following
Traceback (most recent call last):
File "c.py", line 6, in <module>
if a.index(6):
ValueError: 6 is not in list
How do I search for a value in a python list and do something if I find
the number?

Import Sibling Directory (yet again)

Import Sibling Directory (yet again)

I have the following directory structure:
src/
main/
somecode/
A.py
B.py
__init__.py
__init__.py
test/
somecode/
testA.py
testB.py
__init__.py
__init__.py
__init__.py
I was able to successfully add the following to the test modules:
import sys
sys.path.insert(0, "absolute path to src")
which allowed me to run nosetests from the src folder. But the problem is
when other people use my code, this doesn't work because their absolute
path doesn't is different.
So then I tried:
import sys, os
sys.path.append(os.path.abspath('../../../main/somecode')
from main.somecode import A
which worked great from src/test/somecode, but I can't run nosetests from
the src folder since the relative path doesn't work from there.
I also tried to do from ...main.somecode import A but it doesn't like that
even though they are all python packages.
So what do I do? This seems like a potential answer but he doesn't explain
where to add the code.

Saturday, 28 September 2013

How to remove specific data line from html file with Ruby

How to remove specific data line from html file with Ruby

i have a file name payment.html.erb
content have:
<form method="POST" action="http://www.example.com" id="my_id" class="form">
<input type="hidden" name="Timestamp" value="2013-09-29T08:05:14.Z"/>
<input type="hidden" name="Signature"
value="dd01adafd2689b243d6cbc9088da2bf699976eb0"/>
<input type="hidden" name="Amount" value="1"/>
<input type="text" name="AccountName" value="" placeholder="account name"/>
<p></p>
<select name="ExpireMonth">
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
<option value="11">11</option>
<option value="12">12</option>
</select>
<select name="ExpireYear">
<option value="2017">2017</option>
<option value="2018">2018</option>
<option value="2019">2019</option>
<option value="2020">2020</option>
</select>
<input type="submit" class="yyy" id="xxx" value="submit"/>
</form>
i am reading from file and again need to write back into file (i already
coded)
i want remove all non hidden html fields and also 'Form' starting tag and
closing tag.
thanks

How to write a python script that operates on a list of input files?

How to write a python script that operates on a list of input files?

I have a program that takes an input file:
python subprogram.py < input.txt > out.txt
If I have a number of input files, how can I write a single python program
runs on those inputs and produces a single output? I believe the program
should run like:
python program.py < input_1.txt input_2.txt > out.txt
And the program itself should look something like:
from subprogram import MyClass
import sys
if __name__ == '__main__':
myclass = MyClass()
myclass.run()

Collection select is cleaning after doing search issue

Collection select is cleaning after doing search issue

I did a search using ajax using 2 collections select but after doing
SEARCH the information selected my collection select is cleaned.How can i
fix this problem?
Here is my controller
class PolicyManagement::PolicyController < ApplicationController
def update_products
cia =CiaEnsure.find(params[:cia_ensure_id])
products = PolicyProduct.find(:all,:conditions=>['cia_ensure_id =
?',params[:cia_ensure_id] ] )
render :update do |page|
page.replace_html 'products', :partial => 'products', :object =>
products
end
end
def generate_print_type_product
@cias = CiaEnsure.find(:all)
@products = PolicyProduct.find(:all,:conditions=>['cia_ensure_id =
?',params[:cia_ensure_id].to_i ] )
@search = Policy.find(:all,:conditions =>['cia_ensure_id = ? AND
policy_product_id = ? ',params[:cia_ensure_id].to_i
,params[:product_id].to_i ] )
end
end
Here is my view
<% form_tag
:controller=>"policy_management/policy",:action=>"generate_print_type_product"
do %>
Cia Secure:
<%= collection_select(nil, :cia_ensure_id, @cias, :id, :short_name,
{:prompt => "Select"},
{:onchange => "#{remote_function(
:url => {:action => "update_products"} ,
:with => " 'cia_ensure_id=' +value" ) }"
}) %>
Product
<div id="products">
<%= render :partial => 'products', :object => @products
</div>
<%= submit_tag "Buscar", :name => nil %>
<% end %>
This is my partial view _products.erb
<%= collection_select( nil,:product_id, products, :id, :name,
{:prompt => "Select Product "}) %>
I will really appreciate help

I think I understand this. But is there a way to make this simpler?

I think I understand this. But is there a way to make this simpler?

I'm a beginner in C++ and I came across this code:
#include <iostream>
using namespace std;
int main()
{
const long feet_per_yard = 3;
const long inches_per_foot = 12;
double yards = 0.0; // Length as decimal yards
long yds = 0; // Whole yards
long ft = 0; // Whole feet
long ins = 0; // Whole inches
cout << "Enter a length in yards as a decimal: ";
cin >> yards; // Get the length as yards,
feet and inches
yds = static_cast<long>(yards);
ft = static_cast<long>((yards - yds) * feet_per_yard);
ins = static_cast<long>(yards * feet_per_yard * inches_per_foot) %
inches_per_foot;
cout<<endl<<yards<<" yards converts to "<< yds <<" yards "<< ft <<"
feet "<<ins<<" inches.";
cout << endl;
return 0;
}
It works as you expect but I didn't like all the typecasting business. So
I changed this to this:
#include <iostream>
using namespace std;
int main()
{
long feet_per_yard = 3;
long inches_per_foot = 12;
long yards = 0.0;
long yds = 0; // Whole yards
long ft = 0; // Whole feet
long ins = 0; // Whole inches
cout << "Enter a length in yards as a decimal: ";
cin >> yards; // Get the length as yards,
feet and inches
yds = yards;
ft = (yards - yds) * feet_per_yard;
ins = (yards * feet_per_yard * inches_per_foot) % inches_per_foot;
cout<<endl<<yards<<" yards converts to "<< yds <<" yards "<< ft <<"
feet "<<ins<<" inches.";
cout << endl;
return 0;
}
Which of course does not work as intended because 'long' doesn't have
decimal values like 'double' does, right?
But if I change every value to the type 'double', then % does not work
with 'double'. Is there a way to make this easier? I heard about fmod()
but CodeBlock IDE doesn't seem to recognize fmod()?

Friday, 27 September 2013

Printing the value of a specific key in dict

Printing the value of a specific key in dict

How do I access a variable's value?
class Example:
def __init__(self):
self.food = "Soup"
def get_food(self):
return self.food
food_dict = {
"Soup": 3,
}
x = Example.get_food
for x in food_dict.keys():
What should the next line be in order to print the value?

django template NoReverseMatch

django template NoReverseMatch

I had two functions create and update in the file views, update takes one
argument and create does not. I decided to turn them into only one
function update_create because they are not that different. views.py
def update_create(request, id=None):
urls.py:
url(r'^(\d+)/update/$|create/$', update_create, name='update_create'),
templates/list.html
<a href="{% url 'update_create' %}">Create a new event</a>
I got this error with the version above:
NoReverseMatch at /agenda/list/
Reverse for 'update_create' with arguments '()' and keyword arguments
'{}' not found.
But when I do this (I add an argument) it works: templates/list.html
<a href="{% url 'update_create' 1 %}">Create a new event</a>
What's happening? Thanks in advance.

Nodejs Project on Social Network

Nodejs Project on Social Network

I m new to Nodejs,I am thinking to build a Social Network using Nodejs.
1-is it possible ?
2-If yes then suggest some Pdfs ..
3-Why to Choose Nodejs instead of Java for same ?
4-Any other Ideas For projects ?

Point DNS to subdirectory on heroku rails app?

Point DNS to subdirectory on heroku rails app?

We have a rails app that generates subdirectories for a user
example.herokuapp.com/user1directory &
example.herokuapp.com/user2directory
Is there a way to point DNS for a url to that specific directory of the
rails app, without any silly hacks?
Ideally what we need is user1website ->
example.herokuapp.com/user1directory but masks it while showing any
further subdirectories / pages.
Any help will be greatly appreciated.
Thank you.

DatePicker in my EditText

DatePicker in my EditText

In the Login page, the user must enter his birth day. I want to creat un
EditText (Birth Day), and the DatePicker show up.
I do like this :
public class Main extends Activity {
EditText inputBirthDay;
DatePicker dpResult;
TextView tvDisplayDate;
int year;
int month;
int day;
static final int DATE_DIALOG_ID = 999;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.register_activity);
inputBirthDay = (EditText) findViewById(R.id.registerBirthDay);
addListenerOnButton();
}
public void addListenerOnButton() {
inputBirthDay.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
final Calendar c = Calendar.getInstance();
year = c.get(Calendar.YEAR);
month = c.get(Calendar.MONTH);
day = c.get(Calendar.DAY_OF_MONTH);
showDialog(DATE_DIALOG_ID);
}
});
}
private DatePickerDialog.OnDateSetListener datePickerListener = new
DatePickerDialog.OnDateSetListener() {
// when dialog box is closed, below method will be called.
public void onDateSet(DatePicker view, int selectedYear,
int selectedMonth, int selectedDay) {
year = selectedYear;
month = selectedMonth;
day = selectedDay;
}
};
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DATE_DIALOG_ID:
return new DatePickerDialog(this, datePickerListener, year, month,
day);
}
return null;
}
}
But I have two problems :
1/ When I clik on the EditText, the keyboard show up in the first time,
then wehen I clik again, the DatePicker show up. How can I hide the
keyboard ?
2/ When user pick up a date, it dosen't appear in the EditText. How show
the date in the Edit Text?
Thank you for your help

Accumulating data in sorted manner in Ruby

Accumulating data in sorted manner in Ruby

I am a bit new to Ruby and OOP.
I want to store triples of data associated with key. I have triples of
this form:
"data1" "data2" "data3", where data1 is an integer.
I have a mechanism to triples to key.
For example "key1" is mapped to ["data1", "data2", "data3"].
There can be multiple triples associated with key:
[4, "data2", "data3"], [1, "data5", "data6"] and [3, "data8", "data9"] are
mapped to "key1".
I want these triples to be mapped in a sorted way of "data1" field. In
this case,
"key1" => {[1, "data5", "data6"] [3, "data8", "data9"] [4, "data2",
"data3"]}
How do I do this Ruby?

Is it possible to list the avaiable JNDI datasources?

Is it possible to list the avaiable JNDI datasources?

Is it possible to list the avaiable JNDI datasources for the current
application? If yes, how can I do this.

Thursday, 26 September 2013

Drop down Combobox inside datagridview

Drop down Combobox inside datagridview

ive been strugling with this problem for too long now, ive seen all the
answers on the subject and though ive found several none of them seems to
work for me. So the base of my problem is as follows: I have a
datagridview that will add a row to itself once another datagridview cell
is double clicked. When this datagridview gets the row added, it adds 2
types of columns to itself one is a combobox, wich suposedly has a
colection already set in it (just went to the combobox options inside the
datagrid and filled up its collection) and a check box column, now both of
them do nothing once i click on them, doble clic, multiple click as many
clics as u want but nothing happens. Ive even tryed the following code.
public static void combolist(DataGridView combogrid)
{
var column = new DataGridViewComboBoxColumn(); DataTable data = new
DataTable();
data.Columns.Add(new DataColumn("Value", typeof(string)));
data.Columns.Add(new DataColumn("Description", typeof(string)));
data.Rows.Add("item1");
data.Rows.Add("item2");
data.Rows.Add("item3");
column.DataSource = data;
column.ValueMember = "Value";
column.DisplayMember = "Description";
combogrid.Columns.Add(column);
}
and even though i can add a new column of the type combobox to my
datagridview it is still empty(or apears to be since i cant clic to see a
drop down list). my datagridview properties are set
to:editMode:editOnEnter, readOnly:false. Is there something im missing
here? why cant i populate or display this combobox?, plz this problem is
driving me crazy, and i believe this is the best site to find an answer. I
would preaty much apreciate it... a lot.

Wednesday, 25 September 2013

Differentiate two markers at same place in Google maps

Differentiate two markers at same place in Google maps

I have a Google map with clusters of marker. When I have two same places
only one marker is showing[one overlap other]. How can I differentiate two
markers to make both visible?

Thursday, 19 September 2013

new to tkinter and python trying simple math using GUI

new to tkinter and python trying simple math using GUI

Trying to make a very basic addition calculator with python and tkinter.
It gives me an error: btresult = Button(window, text = "Compute Sum",
command = self.result).grid(row = 4, column = 2, sticky = E) ^
SyntaxError: invalid syntax
I am having trouble figuring out how to connect this.
from tkinter import *
class addCalculator: def init(self): window = Tk() window.title("Add
Calculator")
Label(window, text = "First Number: ").grid(row = 1, column = 1,
sticky = W)
Label(window, text = "Second Number: ").grid(row = 2, column = 1,
sticky = W)
self.number1Var = StringVar()
Entry(window, textvariable = self.number1Var, justify =
RIGHT).grid(row = 1, column = 2)
self.number2Var = StringVar()
Entry(window, textvariable = self.number2Var, justify =
RIGHT).grid(row = 2, column = 2)
self.resultVar = StringVar()
lblresult = Label(window, textvariable = self.result.grid(row = 3,
column = 2, sticky = E)
btresult = Button(window, text = "Compute Sum", command =
self.result).grid(row = 4, column = 2, sticky = E)
def result(self):
resultVar = self.resultVar.set(eval(self.number1Var.get()) +
eval(self.number2Var.get()))
return resultVar
window.mainloop()
addCalculator()

Read csv file with many named column labels with pandas

Read csv file with many named column labels with pandas

I'm brand new to pandas for python. I have a data file that has multiple
row labels (per row) and column labels (per column) like the following
data of observation counts for 3 different animals (dog,bat,ostrich) at
multiple recording times (monday morning, day, night):
'' , '' , colLabel:name , dog , bat , Ostrich
'' , '' , colLabel:genus , Canis , Chiroptera , Struthio,
'' , '' , colLabel:activity, diurnal, nocturnal, diurnal
day , time of day, '' , , ,
Monday , morning , '' , 17 , 5 , 2
Monday , day , '' , 63 , 0 , 34
Monday , night , '' , 21 , 68 , 1
Friday , day , '' , 72 , 0 , 34
I'd like to read this data into Pandas where both the rows and columns are
hierarchically organized. What is the best way of doing this?

Image tag in the div ends up overflowing

Image tag in the div ends up overflowing

I was creating a simple html with a header and logo in it. Im doing this
for email templates, so all are inline styles. I noticed there is a float
break happening and the image is overflowing its parent.
<div style="width:640px;">
<!-- header -->
<div id="header" style="background-color:#005387; height:60px;">
<div style="margin-top:10px;margin-left:20px;">
<img
src="https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcTPCYwy-3sPJo4XjlB28KVXivC2FlDjYquB1i5Kb7assH9trLoanw">
</div>
</div>
</div>
http://jsfiddle.net/HMswX/1/
Any idea why this is happening? When I add overflow:hidden to #header
elem, it works fine. But Im not floating any element within that, then why
is there a float break?
Thanks.

Code First Friendly XSD Transform

Code First Friendly XSD Transform

I am new to actually using EF (started yesterday) and xsd files so please
bear with me. I have a form.vb class I created from a schema through the
use of the Microsoft tool xsd. This is a snippet of a very small portion
of this FORM class, since the generated file was around 2000 lines long. I
am using this class to de-serialize a message we get through a WCF.
I wish to use the Entity Framework to create the tables and key
relationships using the generated class. It works great with a test DB I
setup to play with this idea. However the issue is how to deal with the
array fields like Page().
I am not having much hope with this, but is there a tool to modify this
xsd file so that EF would cleanly be able to create a database
relationship using my form.vb? Would the modified form.vb still be able to
de-serialize the message from the WCF?
<System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929"), _
System.SerializableAttribute(), _
System.Diagnostics.DebuggerStepThroughAttribute(), _
System.ComponentModel.DesignerCategoryAttribute("code"), _
System.Xml.Serialization.XmlTypeAttribute(AnonymousType:=True), _
System.Xml.Serialization.XmlRootAttribute([Namespace]:="",
IsNullable:=False)> _
Partial Public Class FORM
Private _ID As Integer
Private pageField() As Page
Private companyField As String
Public Property ID As Integer
Get
Return Me._ID
End Get
Set(value As Integer)
Me._ID = value
End Set
End Property
<System.Xml.Serialization.XmlElementAttribute("Page")> _
Public Property Page() As Page()
Get
Return Me.pageField
End Get
Set(value As Page())
Me.pageField = value
End Set
End Property
<System.Xml.Serialization.XmlAttributeAttribute()> _
Public Property company() As String
Get
Return Me.companyField
End Get
Set(value As String)
Me.companyField = value
End Set
End Property
End Class

Slider interferes with lightbox, causes data-field to be undefined - with links to test case - colorbox vs flexslider

Slider interferes with lightbox, causes data-field to be undefined - with
links to test case - colorbox vs flexslider

Here is a page with a slider and a set of popup thumbnails. The code is
the same for the tags in both.
http://radiokdug.com/slider-vs-popup-test/?slider=1 clicking on either the
slider or the row of thumbnails results in TypeError: a.data(...) is
undefined
the same page, but without the slider:
http://radiokdug.com/slider-vs-popup-test/
The lightbox popup works fine, without the slider on the page.

Android Intercepting POST Requests from Webview

Android Intercepting POST Requests from Webview

I have an android app that presents a secure form for verification. After
the verification the server post's the data (necessary for the app).
I have a specific requirement not to host a PHP / JSP page to receive this
POST and then redirect to the app.
I want to give the Authentication server a Dummy URL to Post its Data and
then capture the HTTP POST and Data from the Webview in my app.
I went through lot of links and also noticed that it is a known android
issue. (http://code.google.com/p/android/issues/detail?id=9122)
Is there a way around this?

Check if URL has http or https from string

Check if URL has http or https from string

I have a textbox in which the user enters url.
For example, the user enters www.google.com or http://www.google.com. But
google has https, not http.
How can I check whether the url is http or https from the string which the
user enters?

Wednesday, 18 September 2013

When Mac Mail sends an email message, what headers are in the message?

When Mac Mail sends an email message, what headers are in the message?

I am connecting to Yahoo via Mail (the app).
When I send a message, I want to know the raw source that Mail sends to
Yahoo.
(I don't want the raw source of the message after it's already been sent)

F# List.Map using a random number

F# List.Map using a random number

I want to create a list of 20 random numbers. I wrote this:
let numberList = [ 1 .. 20 ]
let randoms =
numberList
|> List.map (fun (x) -> System.Random().Next(0,9))
And I got this:
val numberList : int list =
[1; 2; 3; 4; 5; 6; 7; 8; 9; 10; 11; 12; 13; 14; 15; 16; 17; 18; 19; 20]
val randoms : int list =
[7; 7; 7; 7; 7; 7; 7; 7; 7; 7; 7; 7; 7; 7; 7; 7; 7; 7; 7; 7]
Which makes sense. The problem is that I want to pass in a random number
each time the function is evaluated like this:
let numberList = [ 1 .. 20 ]
let randoms =
numberList
|> List.map (fun (Random().Next(0,9)) -> x)
but I am getting a "The pattern discriminator 'Random' is not defined"
exception.
Am i approaching this problem the wrong way? Thanks in advance

Update table column rows with top dimension values and rest as others

Update table column rows with top dimension values and rest as others

I have fact table, say main_table with 30 OS Types and values for each.
The values in table look some thing like below:
DATE OS_TYPE MEASURE1 MEASURE2
09/01/2013 WI8
09/01/2013 WI7
09/01/2013 WXP
09/01/2013 MAC
09/01/2013 WI8
09/01/2013 WI7
09/01/2013 OTH
09/01/2013 MAC
09/01/2013 WI8
09/01/2013 WI8
We also have a dimension table which gives a full name to the above OS
Type. The dimension_table looks some thing like below:
OS_TYPE OS_NAME
WI8 Windows 8
WI7 Windows 7
MAC MAC
WXP Windows XP
NXP OTHER
PS3 OTHER
POS OTHER
.. 25 other types
i listed the top 10 OS types from main_table.
SELECT TOP 10 OS_TYPE FROM main_table ORDER BY measure1 WHERE EVENT_DT
BETWEEN '2013-09-01' AND current_date
i was able to get this working.
now, i would require some help updating the dimension table.
what i want to do is update the dimension_table with only top 10 os_type
with the full names and rest os_types with name "other".
hope i was clear..
please let me know.
thanks for reading through my request.

socket connection getting closed abruptly with code 141

socket connection getting closed abruptly with code 141

What im trying to do is connect to a remote server , read contents from a
file on the local machine and send it over to the server. Then capture the
server response and save it. I put the GET command in a text file and am
trying get the results of the same. Here is some part of the code. Im
doing this using sockets and C.
if ( inet_pton(AF_INET,ip, &(nc_args->destaddr.sin_addr.s_addr)) <= 0 )
printf("\n\t\t inet_pton error");
if (connect(sockfd, (struct sockaddr *) &nc_args->destaddr,
sizeof(&nc_args->destaddr)) < 0)
{
printf("\n\t\t Connection error");
exit(1);
}
puts("\n\t\t Connection successful to ...");
// file parameter is taken from command line and passéd to this function
fp = fopen(file,"rb");
if ( fp == NULL)
{
printf("\n\t\t File not found");
exit(3);
}
else
{
printf("\n\t\t Found file %s\n", file);
fseek(fp, 0, SEEK_END);
file_size = ftell(fp);
rewind(fp);
//allocate memory to the buffer dynamically
buffer = (char*) malloc (sizeof(char)*file_size);
if (buffer == NULL) {fputs ("Memory error",stderr); exit (2);}
for (i=0 ; i<sizeof(buffer); i++)
{
printf("\n\t\t %s", buffer);
}
printf("\n\t\t File contains %ld bytes!\n", file_size);
printf("\n\t\t Sending the file now");
}
while (1)
{
bytes_read = fread(buffer,1, file_size, fp);
printf("\n\t\t The bytes read is %zd", bytes_read);
if (bytes_read == 0) // We're done reading from the file
{
printf("\n\t\t The bytes read is %zd", bytes_read);
break;
}
if (bytes_read < 0)
{
printf("\n\t\t ERROR reading from file");
}
void *p = buffer;
while (bytes_read > 0)
{
ssize_t bytes_written = send(sockfd, buffer, bytes_read,0);
if (bytes_written <= 0)
{
printf("\n\t\t ERROR writing to socket\n");
}
bytes_read -= bytes_written;
p += bytes_written;
printf("\n\t\t Bytes %zd written", bytes_written);
}
}
printf("\n\n\t\t Sending complete.");
What is happening here is that i get the message "connection successful",
then it displays "sending the file now" and then the program quits
unexpectedly. if i do echo $? i get 141 as the exit code. I am trying to
connect from my server to a different server at work and get the results.
These two can communicate correctly, and i can run the GET command from
command line without issues. Its just not working from the code. Can
someone let me know what the issue could be ?

What would be the best method to save message conversations in Database

What would be the best method to save message conversations in Database

Note: I have already read all the articles and questions about chat and
messages on this site. So donot try to provide me links, they are just
helping out users with MySql but I am using SQL CE Note the CE in it. And
I know this aint a code generating site I respect the terms of use of this
site. But I got no choice! I have to go for a suggestion.
What I want: I want to have a messages table in my database. What I want
is that it should save the messages and then I would get the messages from
it. It should save Time, Message, Sender and Recipient and finally Seen
column.
What I am having: The database table that I am having contains these
columns. But the issue is that I want these:
Distinct sender and recipient. More like a threaded conversation.
Ordered by Time. So that the latest one comes up.
Rest will be accessed by a query inside the block. So that's not an issue
like the Profile Picture, UserId, UserName and others
What I was able to create is this:

You can see that I did create the table. That saved the chats! But the
point to note here is that I have used this query.
SELECT DISTINCT Sender, Recipient FROM Messages WHERE Sender =2 OR
Recipient =2
And I was able to get the results like a Thread, but they were not
ordered. They won't be ordered unless I select time too. But selecting the
TIME will remove the functionality of DISTINCT.
Any kind of suggestion will be appreciated. I just don't know how to
create a threaded view and order it by Time! Remember I am using SQL
Server CE so the tricks you can do on SQL Server won't work here. So
provide me with a code that would select these all and would help me out
too. I am stuck on this one!
Thanks in advance for your precious time guys, Cheers!

Bitwise operations vs. logical operations in C++

Bitwise operations vs. logical operations in C++

In C++ are the following statements when comparing two integer values for
equality the same? If not, why?
if(a == b) ...do
if(!(a ^ b)) ...do

Provide update to user

Provide update to user

I am working in a java application, in which all the users will get
automatic update when the user is connected to internet. I am trying a
simple logic like this:
My application will search for the validity of the user.
If the user is valid a folder will be downloaded from
http://example.com/update/
The downloaded folder will be stored somewhere in disk.
My project folder's dist folder will be replaced with the new downloaded
file.
I am stumbled in the No. 4. OS does not allow me to replace in-use files.
Is there any other solution, so that I can provide updates to my users.?

Tuesday, 17 September 2013

Fix curl request encoding

Fix curl request encoding

Im have some minor encoding issues. Im getting a json data string from
here (try it yourself):
http://cdn.content.easports.com/fifa/fltOnlineAssets/C74DDF38-0B11-49b0-B199-2E2A11D1CC13/2014/fut/items/web/179899.json
The name in the data is shown like this
Ari Skúlason
How can I fetch this data with proper encoding so its Ari Skúlason?
I tried switching it to utf-8 like this in php
echo mb_convert_encoding($r,'ISO-8859-1','utf-8');
which got me closer, but its still not right
Ari Sk&#65533;lason
my php curl request:
$location =
'http://cdn.content.easports.com/fifa/fltOnlineAssets/C74DDF38-0B11-49b0-
B199-2E2A11D1CC13/2014/fut/items/web/179899.json';
$ch = curl_init($location);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Accept: application/json'));
$r = curl_exec($ch);
curl_close($ch);
echo mb_detect_encoding($r);
$r = mb_convert_encoding($r,'ISO-8859-1','utf-8');
print_r($r);

Android - ACTION_PACKAGE_FIRST_LAUNCH filter not working

Android - ACTION_PACKAGE_FIRST_LAUNCH filter not working

I trying to detect my application run at first time. I used Broadcast
Receiver to do this. It works fine with ACTION_PACKAGE_REPLACED. But it
doesn't work when I use ACTION_PACKAGE_FIRST_LAUNCH intent. I'm using
Android 4.3
This is my Activity
public class MainActivity extends Activity {
BroadcastReceiver broadcastReceiver;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
broadcastReceiver = new TestBroadcast();
}
@Override
protected void onPause() {
super.onPause();
unregisterReceiver(broadcastReceiver);
}
@Override
protected void onResume() {
super.onResume();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(Intent.ACTION_PACKAGE_FIRST_LAUNCH);
intentFilter.addAction(Intent.ACTION_PACKAGE_REPLACED);
intentFilter.addDataScheme("package");
registerReceiver(broadcastReceiver, intentFilter);
}
}
This is my AndroidManifest.xml
<receiver android:name="com.example.TestBroadcast" >
<intent-filter>
<action
android:name="android.intent.action.PACKAGE_FIRST_LAUNCH" />
<action android:name="android.intent.action.PACKAGE_REPLACED" />
<data android:scheme="package" />
</intent-filter>
</receiver>
And TestBroadcast class
public class TestBroadcast extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
if
(intent.getAction().equalsIgnoreCase(Intent.ACTION_PACKAGE_FIRST_LAUNCH))
{
Toast.makeText(context, "Application installed",
Toast.LENGTH_SHORT).show();
}
}
}

Get rid of blue line using ActionBarCompat

Get rid of blue line using ActionBarCompat

I'm using the ActionBarCompat library, and I've got a custom theme I've
created from the Action Bar Style Generator. The background is set to a
custom image provided by this, but the blue line is still there! This
happens on both 2.2+ and 4.0+.

How to use a rest service result as valuelist for a value picker control

How to use a rest service result as valuelist for a value picker control

An external Domino Server exposes application data, which I need in my
application, as a Rest Service. In fact, they use a viewJsonService and I
know they exposes column1 up to column8, but I have no other access to the
data. The URL looks like:
http:\extserver\database.nsf\restservice.xsp\extdata, where 'extdata' is
the pathinfo.
I want to consume the data returned by that Rest Service as an input to
the valuelist of a value picker control in my xpage. In detail, I want to
use the value from column2 as the value in the value picker and the value
from column5 as the label in the value picker.
Any idea how to do this ?

Generation of /proc/net/dev content

Generation of /proc/net/dev content

What is the location of the function that actually generates the content
of /proc/net/dev statistics?. It used to be at linux/net/core/dev.c

Passing a var to another page

Passing a var to another page

Is it possible to pass the totalScore var to another page onclick so that
it can be displayed there? ex: click submit link it goes to yourscore.html
and display the score on page
$("#process").click(function() {
var totalScore = 0;
$(".targetKeep").each( function(i, tK) {
if (typeof($(tK).raty('score')) != "undefined") {
totalScore += $(tK).raty('score');
}
});
alert("Total Score = "+totalScore);
});

Sunday, 15 September 2013

Using refresh_token for Google OAuth 2.0 returns http 400 bad request

Using refresh_token for Google OAuth 2.0 returns http 400 bad request

I am using a server-side flow validation for an app that connects to
Google Drive.
I am able to retrieve the access code and exchange for an access_token and
user info. I then persist the refresh_token. So, I can confirm that the
client_id and client_secret are correct, but when I use the refresh_token
to get a new access_token, I get a 400 response. Here's the details, I log
the response from the initial token request and can confirm that the
refresh_token stored to the database matches the one in the response from
Google.
But when I try to use the refresh_token (programmatically and with
httpie), I get the response below. Why?
% http --verbose POST https://accounts.google.com/o/oauth2/token
Content-Type:application/x-www-form-urlencoded
refresh_token=1/nJZGF7hIySVtVCl8I-Y3KfXAPk84gD0X6ym7hQS8gcc
client_id=XXXX
client_secret=XXXX grant_type=refresh_token
POST /o/oauth2/token HTTP/1.1
Content-Length: 198
Host: accounts.google.com
b'Accept': application/json
b'Accept-Encoding': gzip, deflate, compress
b'Content-Type': application/x-www-form-urlencoded
b'User-Agent': HTTPie/0.6.0
{"refresh_token": "1/nJZGF7hIySVtVCl8I-Y3KfXAPk84gD0X6ym7hQS8gcc",
"client_id": "XXXX", "client_secret": "XXXX", "grant_type":
"refresh_token"}
HTTP/1.1 400 Bad Request
Alternate-Protocol: 443:quic
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Content-Type: application/json
Date: Mon, 16 Sep 2013 03:42:06 GMT
Expires: Fri, 01 Jan 1990 00:00:00 GMT
Pragma: no-cache
Server: GSE
Transfer-Encoding: chunked
X-Content-Type-Options: nosniff
X-Frame-Options: SAMEORIGIN
X-XSS-Protection: 1; mode=block
{
"error": "invalid_request"
}
And here is the log output from my web application for this particular
user when he logs in for the first time and I persist the refresh_token:
[debug] application - retrieved authentication code, proceeding to get
token and user info
[debug] application - successfully parsed user and token:
GoogleOAuthPacket(User(117397424875078935066,XXXX,XXXX,XXXX,https://lh6.googleusercontent.com/-lbSmIO8BHMA/AAAAAAAAAAI/AAAAAAAAAAA/6ncAxM6DQuM/photo.jpg,1/nJZGF7hIySVtVCl8I-Y3KfXAPk84gD0X6ym7hQS8gcc),ya29.AHES6ZT0Mn0t7zWDJW-rU6c4eEnCr76MuP14hkLSC60lX0Ve7tGrbA,3600)
[debug] application - response for token request was: {
"access_token" :
"ya29.AHES6ZT0Mn0t7zWDJW-rU6c4eEnCr76MuP14hkLSC60lX0Ve7tGrbA",
"token_type" : "Bearer",
"expires_in" : 3600,
"id_token" :
"eyJhbGciOiJSUzI1NiIsImtpZCI6IjZhODc3Mzc3MGFmNTkyMWM5OWZjMWRmYzVmN2U3NTA2YTFjOTQyZDUifQ.eyJpc3MiOiJhY2NvdW50cy5nb29nbGUuY29tIiwic3ViIjoiMTE3Mzk3NDI0ODc1MDc4OTM1MDY2IiwiYXRfaGFzaCI6Ijk0dENwbzlxNzhUYXFPOWgwWkI3dHciLCJoZCI6Im15bWFpbC5sYXVzZC5uZXQiLCJlbWFpbCI6InNjb2xpbmNydTAwMUBteW1haWwubGF1c2QubmV0IiwiYXpwIjoiNjQyMzAxMzYzNDQ0LmFwcHMuZ29vZ2xldXNlcmNvbnRlbnQuY29tIiwiZW1haWxfdmVyaWZpZWQiOiJ0cnVlIiwiYXVkIjoiNjQyMzAxMzYzNDQ0LmFwcHMuZ29vZ2xldXNlcmNvbnRlbnQuY29tIiwiaWF0IjoxMzc5Mjk5NDQwLCJleHAiOjEzNzkzMDMzNDB9.f5lBChQCxSfNfTWqSm-uR0ueoq78w2JlJOg3zFG-Wpav8Jx6ypwshcXCA0EQjFlAckBaQ_kA1uUpToidg5nGa3B-0ftMLnuGLnO-J65zyEYyMjo4Y3wFezpy9toHOk_8rPIzZ8_jzpuLKlxuqMnz0EdK-3Mik0p6pSbkZgX8lww",
"refresh_token" : "1/nJZGF7hIySVtVCl8I-Y3KfXAPk84gD0X6ym7hQS8gcc"
}
[debug] application - response for user request was: {
"sub" : "117397424875078935066",
"name" : "XXXX",
"given_name" : "XXXXX",
"family_name" : "XXXX",
"picture" :
"https://lh6.googleusercontent.com/-lbSmIO8BHMA/AAAAAAAAAAI/AAAAAAAAAAA/6ncAxM6DQuM/photo.jpg",
"email" : "XXXX",
"email_verified" : true,
"hd" : "XXXX"
}
[debug] application - user User(117397424875078935066,XXXX,
XXXX,XXXX,https://lh6.googleusercontent.com/-lbSmIO8BHMA/AAAAAAAAAAI/AAAAAAAAAAA/6ncAxM6DQuM/photo.jpg,1/nJZGF7hIySVtVCl8I-Y3KfXAPk84gD0X6ym7hQS8gcc)
not found, proceeding to save in database
[debug] application - successfully persisted user, proceeding to save
token to cache

Vimeo thumbnail image, issue with loadtime

Vimeo thumbnail image, issue with loadtime

I'm fetching thumbnails for vimeo movies. These are displayed on the
startpage. When I click on an image I'll get to a certain page where the
video is found and can be played.
The problem is on the startpage, since I have alot of thumbnails it takes
a long time to load the page. Any suggestions on how to minimize loadtime?
Heres the code:
<?php
global $id;
$the_id2 = get_the_ID();
$args3 = array(
'depth' => 2,
'child_of' => $the_id2,
'exclude' => '',
'include' => '',
'title_li' => '',
'parent' => $the_id2,
'echo' => 0,
'sort_column' => 'menu_order',
'post_status' => 'publish'
);
$pages_get_2 = get_pages($args3);
foreach($pages_get_2 as $pages_display_2) {
$content = $pages_display_2->post_parent;
$content = apply_filters('the_content', $content);
$imgid54 =
get_post_meta($pages_display_2->ID,'video',true);;
$hash =
unserialize(file_get_contents("http://vimeo.com/api/v2/video/$imgid54.php"));
echo get_page_link($pages_display_2->ID) ?>"><img
src="<?php echo $hash[0]['thumbnail_large']; ?>"
alt="" class="alignnone size-full noborder"
/><h2><span class="bvssp-projects-text"><?php echo
$pages_display_2->post_title ?></span></h2></a>
<?php } ?>
Yes, I use WordPress.
Kind regards Johan

Query Minecraft Server with x10hosting

Query Minecraft Server with x10hosting

I am trying to query a minecraft server for a website I'm making. I am
using x10hosting. The problem is, it always returns "Offline". I was
wondering if anyone could assist me by giving me a working model.
Thanks in advance :)
~I know this isnt how it usually works but I am desperate for a working
model (since my past attempts have failed). Thanks for understanding!

How to check if a file exist in metro app without try catch

How to check if a file exist in metro app without try catch

I have 5 limited numbers of file in Database and I want to check weather
the name of file I want Exists or Not but without using an Exception
handler.
Code Known till now
try{
var localFolder = ApplicationData.Current.LocalFolder;
var file = await localFolder.GetFileAsync("data.txt");
}catch(Exception ex){
//file doesnot exist
}
But without this is there any way. ???

Parallel distribution of a 2D array in C#

Parallel distribution of a 2D array in C#

I need some advice on parallel workload distribution, based on the heat
distribution problem, using the Jocobi method. The program works by
splitting a 2D array into 4 equally sized grids, via a parallel for - then
to further break down each of the smaller grids into row clusters of e.g.
10 rows which are to be processed in new tasks. The initial grid size is
10000x10000.
The program works but it is significantly slower than my other parallel
implementations, e.g. clustering rows, without splitting the 2D array.
Even when using a for loop, there is a lot of lag. I dont understand why,
due to the access time of the array. For example, calculating: x[5000,
9999] y[5000, 9999] (the bottom, right-hand corner)
Can anyone offer an explanation for the holdup?
class ParallelHeatDistribution_QuadCluster
{
private double[,] heatGrid;
private int gridDimensions;
private int x1, x2, x3;
private int y1, y2, y3;
private int[,] quadDimensions;
public ParallelHeatDistribution_QuadCluster(double[,] heatGrid, int
gridDimensions)
{
this.heatGrid = heatGrid;
this.gridDimensions = gridDimensions;
this.x1 = 1;
this.x2 = this.gridDimensions / 2;
this.y1 = 1;
this.y2 = this.gridDimensions / 2;
this.x3 = this.gridDimensions - 1;
this.y3 = this.gridDimensions - 1;
this.quadDimensions = new int[4, 4] { { x1, x2, y1, y2 }, { x1,
x2, y2, y3 }, { x2, x3, y1, y2 }, { x2, x3, y2, y3 } };
}
/// <summary>
/// Start parallel distribution
/// </summary>
public void parallelDistribution(int clusterRowCount)
{
for (int i = 0; i <1; i++)
{
DistributeWorkload(clusterRowCount, quadDimensions[3, 0],
quadDimensions[3, 1], quadDimensions[3, 2], quadDimensions[3,
3]);
}
Parallel.For(0, 3, i =>
{
//DistributeWorkload(clusterRowCount, quadDimensions[i,
0], quadDimensions[i, 1], quadDimensions[i, 2],
quadDimensions[i, 3]);
});
}
/// <summary>
/// Calculate heat distribution in parallel by assigning work to tasks
based on x-amount of loop iterations. Each iteration represents an
array row partition
/// </summary>
private void DistributeWorkload(int clusterRowCount, int xStartPoint,
int xEndpoint, int yStartPoint, int yEndpoint)
{
/* calculate data partition cluster for parallel distribution. */
int clusterCount = (gridDimensions) / clusterRowCount;
/* Parallel task arrays for black and white elements */
Task[] taskArray1 = new Task[clusterCount];
Task[] taskArray2 = new Task[clusterCount];
try
{
/* assign work to for set of tasks calculating the "black
squares" */
int c = 0;
for (int x1 = 0; x1 < clusterCount; x1++)
{
int clusterSize = c;
taskArray1[x1] = new Task(() => setTask(clusterRowCount,
clusterSize, true, xStartPoint, xEndpoint, yStartPoint,
yEndpoint));
c = c + clusterRowCount;
}
/* assign work to second set of tasks calculating the "white
squares" */
c = 0;
for (int x2 = 0; x2 < clusterCount; x2++)
{
int clusterSize = c;
taskArray2[x2] = new Task(() => setTask(clusterRowCount,
clusterSize, false, xStartPoint, xEndpoint, yStartPoint,
yEndpoint));
c = c + clusterRowCount;
}
/* start all tasks */
foreach (Task t in taskArray1) t.Start();
Task.WaitAll(taskArray1);
foreach (Task t in taskArray2) t.Start();
/* and wait... */
Task.WaitAll(taskArray2);
} catch (AggregateException e){
Console.Write(e);
}
}
/// <summary>
/// Task: calculate a cluster of rows
/// </summary>
/// <param name="y"> y-axis position </param>
/// <param name="isFirst"> determine grid element set </param>
public void setTask(int clusterRowCount, int currentClusterCount, bool
isFirst, int xStartPoint, int xEndpoint, int yStartPoint, int
yEndpoint)
{
int yPos = yStartPoint + currentClusterCount;
double temperature;
for (int y = yPos; y < yEndpoint; y++)
{
for (int x = xStartPoint; x < xEndpoint; x++)
{
if (isFirst && y % 2 == 0 || !isFirst && y % 2 != 0)
{
if (x % 2 == 0)
{
temperature = (heatGrid[y - 1, x] + heatGrid[y +
1, x] + heatGrid[y, x - 1] + heatGrid[y, x + 1]) /
4;
heatGrid[x, y] = temperature;
}
}
else
{
if (x % 2 != 0)
{
temperature = (heatGrid[y - 1, x] + heatGrid[y +
1, x] + heatGrid[y, x - 1] + heatGrid[y, x + 1]) /
4;
heatGrid[x, y] = temperature;
}
}
}
}
}

getting vertex points of GeometryModel3D to draw a wireframe

getting vertex points of GeometryModel3D to draw a wireframe

I've loaded a 3d model using Helix toolking like this
modelGroupScull = importer.Load("C:\\Users\\Robert\\Desktop\\a.obj");
GeometryModel3D modelScull = (GeometryModel3D)modelGroupScull.Children[0];
and I also have _3DTools that can draw lines from point-to-point in 3d
space. now to draw a wireframe of my GeometryModel3D I guess I have to
cycle to its vertexes and add them to ScreenSpaceLines3D.
ScreenSpaceLines3D wireframe = new ScreenSpaceLines3D();
// need to cycle through all vertexes of modelScull as Points, to add them
to wireframe
wireframe.Points.Add(new Point3D(1, 2, 3));
wireframe.Color = Colors.LightBlue;
wireframe.Thickness = 3;
Viewport3D1.Children.Add(wireframe);
But... how do I actually get this vertex points?
Thanks.

error database Expression Engine

error database Expression Engine

I have a problem with the database of Expression engine (see photo). This
should be because it is a final project for school. Today made.
Does anyone know the problem and can make it please?
thx Bert
Error picture

Saturday, 14 September 2013

How to Drag a Stage accross the screen in JAVAFX

How to Drag a Stage accross the screen in JAVAFX

I've been trying to move my project from JAVA's Swing to JAVA-FX but have
been unsuccessful because of one detail. I've had my Stage set
undecorated, which disables the "Drag via Title Bar feature". I'd like to
get that back (the drag feature), which is where I am totally stuck.
The way I'd like to do it to have Drag effected via a call to a method in
the Controller Class, like how I did with the WindowClose() method.
Please, if you can, could you show how to do so by integrating your ideas
around this problem somewhere in my code below. I just started studying
JAVA-FX and I'm having difficulties integrating the other many examples
I've come accross that solve this dilemma in my code.
Any help will be much appreciated.
post script:
Any ideas are welcome, even those implementing the drag via a method
placed in the main Class (I've noted that there seems to be more
difficulty calling methods on the Stage from another external Class/
Controller Class). I'll be much glad with anything I can get - any help is
useful. I'd, however, like to learn how to share data between Classes in
JAVA-FX.
The CODE:
// Main Class
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
public class Fxmltableview extends Application {
public static String pageSource = "fxml_tableview.fxml";
public static Scene scene;
@Override
public void start(Stage stage) throws Exception {
stage.initStyle(StageStyle.UNDECORATED);
stage.initStyle(StageStyle.TRANSPARENT);
Parent root = FXMLLoader.load(getClass().getResource(pageSource));
scene = new Scene(root, Color.TRANSPARENT);
stage.setScene(scene);
stage.show();
}
public static void main(String[] args) {
launch(args);
}
}
// Controller
import javafx.application.Platform;
import javafx.event.ActionEvent;
public class FXMLTableViewController {
public void WindowClose (ActionEvent event) {
Platform.exit();
}
}

Why are fonts sharper in XFCE than in some other environment such as Gnome or OpenBox?

Why are fonts sharper in XFCE than in some other environment such as Gnome
or OpenBox?

I installed both
Xfce & OpenBox on Centos 6.4 minimal
in Xfce, the text is extremely clear and vivid without "artificial vividness"
but when i switch to OpenBox
init 3
openbox-session
the text is not as sharp. not as vivid, as it was in Xfce4
i have been messing around with different window managers and desktops,
only Xfce seems to have something "special" going on.
What is the science behind the magic in Xfce ?

weka java API - uploading CSV error - wrong number of values. Read 21, expected 20, read Token[EOL], line 3

weka java API - uploading CSV error - wrong number of values. Read 21,
expected 20, read Token[EOL], line 3

I am trying to use WEKA API in my java code and trying to upload CSV file
and analyze the data. But I am facing the below IO Exception saying wrong
number of values in my CSV file.... So how can I fix this? What is the
problem with the CSV? Also, if I need to make any changes to the csv file,
I am worried how to generalize this as I want the program to accept all
csv files with data no matter of some fields missing. Solution please !
Error: Exception in thread "main" java.io.IOException: wrong number of
values. Read 21, expected 20, read Token[EOL], line 3 at
weka.core.converters.ConverterUtils.errms(ConverterUtils.java:912) at
weka.core.converters.CSVLoader.getInstance(CSVLoader.java:819) at
weka.core.converters.CSVLoader.getDataSet(CSVLoader.java:642) at
App.uploadCSV(App.java:25)
function uploadCSV() {
CSVLoader loader = new CSVLoader();
loader.setSource(new
File("C:\\Users\\soumya\\Downloads\\GimletDownload2013_03.csv"));
Instances data = loader.getDataSet();
// save ARFF
ArffSaver saver = new ArffSaver();
saver.setInstances(data);
saver.setFile(new
File("C:\\Users\\soumya\\Downloads\\GimletDownload2013_03.arff"));
saver.setDestination(new
File("C:\\Users\\soumya\\Downloads\\GimletDownload2013_03.arff"));
saver.writeBatch();
BufferedReader br=null;
br=new BufferedReader(new
FileReader("C:\\Users\\soumya\\Downloads\\GimletDownload2013_03.arff"));
Instances train=new Instances(br);
train.setClassIndex(train.numAttributes()-1);
br.close();
NaiveBayes nb=new NaiveBayes();
nb.buildClassifier(train);
Evaluation eval=new Evaluation(train);
eval.crossValidateModel(nb, train, 10, new Random(1));
System.out.println(eval.toSummaryString("\nResults\n=====\n",true));
System.out.println(eval.fMeasure(1)+" "+eval.precision(1)+"
"+eval.recall(1));
}

PHP code not inserting the values in the mysql database?

PHP code not inserting the values in the mysql database?

This is the php code im using to insert values in the database. There
seems to be no PHP error. Its just that the code is not inserting the
values in the table... Can u guys just help me out? Got a project to
submit... I hav really no idea what is wrong with this code!!
<?php
sleep(2);
//Sanitize incoming data and store in variable
$firstname = trim(stripslashes(htmlspecialchars($_POST['fname'])));
$lastname = trim(stripslashes(htmlspecialchars($_POST['lname'])));
$email = trim(stripslashes(htmlspecialchars($_POST['login'])));
$pass = trim(stripslashes(htmlspecialchars($_POST['password'])));
$quest = trim(stripslashes(htmlspecialchars($_POST['question'])));
$answ = trim(stripslashes(htmlspecialchars($_POST['answer'])));
$humancheck = $_POST['humancheck'];
$honeypot = $_POST['honeypot'];
require_once('connection/config.php');
//Connect to mysql server
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if(!$link) {
die('Failed to connect to server: ' . mysql_error());
}
//Select database
$db = mysql_select_db(DB_DATABASE);
if(!$db) {
die("Unable to select database");
}
$sql = "INSERT INTO members (firstname, lastname, login, passwrd,
question_id, answer) VALUES (".
PrepSQL($firstname) . ", " .
PrepSQL($lastname) . ", " .
PrepSQL($email) . ", " .
PrepSQL(md5($_POST['password'])) . ", " .
PrepSQL($quest) . ", " .
PrepSQL(md5($_POST['answer'])) . ")";
mysql_query($sql);
if ($honeypot == 'http://' && empty($humancheck)) {
//Validate data and return success or error message
$error_message = '';
$reg_exp = "/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9-]+\.[a-zA-Z.]{2,4}$/";
if (!preg_match($reg_exp, $email)) {
$error_message .= "<p>A valid email address is
required.</p>";
}
if (empty($firstname)) {
$error_message .= "<p>Please provide a preferred date
for ur visit.</p>";
}
if (empty($lastname)) {
$error_message .= "<p>Please provide the number of
adults in your group for ur visit.</p>";
}
if (empty($pass)) {
$error_message .= "<p>Please provide the number of
children in your group for ur visit.</p>";
}
if (empty($quest)) {
$error_message .= "<p>Please provide your name.</p>";
}
if (empty($answ)) {
$error_message .= "<p>Please provide your surname.</p>";
}
if (!empty($error_message)) {
$return['error'] = true;
$return['msg'] = "<h3>Oops! The request was successful
but your form is not filled out
correctly.</h3>".$error_message;
echo json_encode($return);
exit();
} else {
$return['error'] = false;
$return['msg'] = "<p>Thank you.</p>";
echo json_encode($return);
}
} else {
$return['error'] = true;
$return['msg'] = "<h3>Oops! There was a problem with your submission.
Please try again.</h3>";
echo json_encode($return);
}
//added
//echo("Request Submitted!");
//exit();
// function: PrepSQL()
// use stripslashes and mysql_real_escape_string PHP functions
// to sanitize a string for use in an SQL query
//
// also puts single quotes around the string
//
function PrepSQL($value)
{
// Stripslashes
if(get_magic_quotes_gpc()) {
$value = stripslashes($value);
}
// Quote
$value = "'" . mysql_real_escape_string($value) . "'";
return($value);
}
?>

Project Title,Version not shown in Splash Screen in vb.net

Project Title,Version not shown in Splash Screen in vb.net

i have developed a windows project. now i like to load splash screen with
project title and version before load my project..for that i am using
following coding in my form loading
Private Sub FileManager_Load(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MyBase.Load
Me.Visible = False
Dim s = New SplashScreen1()
s.Show()
System.Threading.Thread.Sleep(2000)
s.Close()
End Sub
the splash screen is visible in form loading. but the project
title,version which i entered in splash screen is not shown? can anyone
help me what's the problem. what's wrong with my code.

Can you fake a join in Mongo aggregation

Can you fake a join in Mongo aggregation

I have documents of the form
members:
{
_id:ObjectId("xxx"),
name:"John",
branch:ObjectId("yyy")
}
branches:
{
_id:ObjectId("yyy"),
name:"Branch A"
}
I want to report on the number of people in each branch. A straight $group
pipeline does this but I can only get it to report back the branch _id and
then convert it in my code. I would like to do something like:
db.members.aggregate(
{$group:{_id:db.branches.findOne(
{_id:"$branch"},
{name:1}).name,count:{$sum:1}}})
Which appears not to work. Is there something along those lines that does
work?

How to zoom into a selected area of image in iPhone?

How to zoom into a selected area of image in iPhone?

I have an ImageView click on that imageview transparent circle should be
create and again double click on that circle particular Image in circle
area should be zoom.Any one can suggest me thanks in advance.

Stats/Server Overload on ip-xxx-xxx-xxx-xxx.ip.secureserver.net

Stats/Server Overload on ip-xxx-xxx-xxx-xxx.ip.secureserver.net

IMPORTANT: Do not ignore this email.
This is cPanel stats runner on ip-xxx-xxx-xxx-xxx.ip.secureserver.net!
While processing the log files for user root, the cpu has been maxed out
for more than a 6 hour period. The current load/uptime line on the server
at the time of this email is 15:23:16 up 7 days, 13:23, 0 users, load
average: 8.95, 9.44, 10.24 You should check the server to see why the load
is so high and take steps to lower the load. If you want stats to continue
to run even with a high load; Edit /var/cpanel/cpanel.config and change
extracpus to a number larger then 0 (run /usr/local/cpanel/startup
afterwards to pickup the changes). ##
please any one help me to fixed this issue

Friday, 13 September 2013

Partials in doT.js?

Partials in doT.js?

Hi I'm new to node and I'm trying to figure out how to load partials from
files using doT.js (http://olado.github.io/doT/index.html) and
consolidate.js (https://github.com/visionmedia/consolidate.js/). I'm
trying to create methods for each section of a page, header/body/footer
etc and merge them all into one.
This is the code I have so far:
var util = require( 'util' ),
fs = require( 'fs' ),
dot = require( 'dot' );
function System( ) {
this.name = 'System';
}
System.prototype._loadFile = function( path ) {
var content;
content = fs.readFileSync( process.argv[ 1 ].replace( /\/[^\/]*$/,
path ) );
content = dot.compile( content ); //tried .template both return funcs?
return content;
};
System.prototype._getMainContent = function( ) {
return this._loadFile( '/controllers/system/views/header.html' );
};
System.prototype.index = function( req, res, next ) {
var content = this._getMainContent( );
res.render( __dirname + '/../system/views/main', {
name: this.name,
main_content: '?' //content?
});
};
module.exports = System;
How do I compile a template into a string that I can pass through another
template or res.render?
Thanks!

Not able to pass Datetime in $.Param() querystring to MVC Controller Get Method....

Not able to pass Datetime in $.Param() querystring to MVC Controller Get
Method....

Angularjs Api Code:
exportFunt = function () {
var query = generateExportData();
Export(query);
};
function generateExportData() {
return {
startDate: viewModel.StartDate,
endDate: viewModel.EndDate,
};
}
Export: function (query) {
$window.open('/demo/analysis/test?$.param(query),
'_blank');
}
Output url link:
/demo/analysis/test?startDate=Sat+Jun+01+2013+00%3A00%3A00+GMT-0700+(Pacific+Daylight+Time)&endDate=Fri+Sep+13+2013+00%3A00%3A00+GMT-0700+(Pacific+Daylight+Time)
test controller:
Public Function GetData(<FromUri()> ByVal query As Request) As
HttpResponseMessage
{
}
Request{
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }
}
The issue is that I am not able to get the Start & End Dates in the query
object. I can see it in the url so I think that the angular Api is passing
is correctly but there is something wrong with the formating. I also tried
to do JSON.stringify(query) & then send it using encodeURIComponent(result
of JSON stringify) but that did'nt work either. I am curretly getting
default data 1/1/0001 in the start & end date query obj.
I am sorry but I cannot paste the whole API so I had to extract the
related code and paste it here.. If you think I am missing anything please
let me know..but I think the issue is surely somewhere in the above code..
Thanks for the Concern...

Capsule shape using border-radius without a set width or height?

Capsule shape using border-radius without a set width or height?

Is it possible to make a capsule share using border-radius without a set
width or height?
I want the left and right sides to be completely rounded while the capsule
would remain straight along the horizontal. Setting the radius to 50%
doesn't seem to give the desired affect.

Attributing CSS class to element

Attributing CSS class to element

Assuming I wanted to attribute the text-shadow: green; attribute to every
<h2> element occouring inside an element with the classes .dark and
ux-bannerwhat CSS code would achieve this?
<div class="dark ux-banner">
<div class="the attributed classes of this element will vary">
<h2>TARGET THIS ELEMENT
</h2>
</div>
</div>
As in the above example <h2> element will be wrapped in a <div> with
varying classes attributed to it.
What would be the best way to apply the text-shadow: green; property to
the <h2> element when occouring within elements that have the .dark and
ux-banner classes attributed without making reference to the <div>
immediately surrounding the <h2> element

Regex. Camel case to underscore. Ignore first occurrence

Regex. Camel case to underscore. Ignore first occurrence

For example:
thisIsMySample
should be:
this_Is_My_Sample
My code:
System.Text.RegularExpressions.Regex.Replace(input, "([A-Z])", "_$0",
System.Text.RegularExpressions.RegexOptions.Compiled);
It works fine, but if the input is changed to:
ThisIsMySample
the output will be:
_This_Is_My_Sample
How can first occurrence be ignored?

Thursday, 12 September 2013

Unexpected result while passing struct to a function

Unexpected result while passing struct to a function

I want to pass a struct to function something like below (I know i can
pass single member to function like input(int age, string s) but i want to
pass whole struct like input(student s) )
#include <iostream>
using namespace std;
struct student
{
string name;
int age;
};
void input(student s)
{
cout << "Enter Name: ";
cin >> s.name;
cout << "Enter age: ";
cin >> s.age;
}
int main(int argc, char *argv[]) {
struct student s1;
input(s1);
cout << "Name is: " << s1.name << endl;
cout << "Age is: " << s1.age << endl;
}
Above code does not produce correct output, I want to use above code with
pointer so to get expected output.

Python Multiprocessing Error?

Python Multiprocessing Error?

I have been studying multiprocessing module in Python for few days.
However, I have met a strange problem that I cannot resolve it.
The source code is very simple but I cannot get any results after running
this code.
The code is as follows:
import multiprocessing as multi
def worker():
print "Worker!!!"
return
jobs = []
for i in range(5):
p = multi.Process(target = worker)
jobs.append(p)
p.start()
I was expecting to get a five time of printing "Worker!!!".
However, the only thing I've got is
* Remote Interpreter Reinitialized *
">>>"
">>>"
Does anybody who has a idea to solve this problem??
Please DO HELP ME!!!

Set Custom KeyEquivalent in Services Menu

Set Custom KeyEquivalent in Services Menu

OmniFocus has a Cocoa Service that allows you to create tasks based upon
selected items.
It has a preference that allows you to set the keyboard shortcut that
triggers the Service. This is not just a global hotkey, it's a bona fide
Service that shows up in the menu.
You can the keyboard shortcut to pretty much any combination, including
combinations with &#8997; and ^. This functionality is not documented -
the docs seem to say that KeyEquivalents must be a
&#8984;+[&#8679;]+someKey.
Once this is set, I observe three things:
The OmniFocus Info.plist file does not contain a KeyEquivalent listed.
This is not surprising, as the file is read-only.
The pbs -dump_pboard utility lists NSKeyEquivalent = {}; for the service.
Using NSDebugServices lists this interesting line that does not show up
with most debugging sessions (Obviously, for keyboard shortcut
&#8963;&#8997;&#8984;M): OmniFocus: Send to Inbox
(com.omnigroup.OmniFocus) has a custom key equivalent:
<NSKeyboardShortcut: 0x7fb18a0d18f0 (&#8963;&#8997;&#8984;M)>.
So my questions are twofold, and I suspect they are related:
How do you dynamically change a service's KeyEquivalent?
How do you set the KeyEquivalent to a combination including &#8963; and
&#8997;
Thank you!

Writing 2 strings on the same line in C

Writing 2 strings on the same line in C

So I want to make the hello.c program write both the first name and the
last name on one line so in this form but when I run my program in this
current form it gives me the error "expected â)â before string constant" I
think I have the rest of the code down because I have removed that line
and ran it and it works. So I just want to ask how to get 2 strings that I
have already pointed to to go on the same line.
This is my code
#include <stdio.h>
int main()
{
char firstname[20];
char lastname[20];
printf("What is your firstname?");
scanf("%s", firstname);
printf("What is your lastname?");
scanf("%s", lastname);
printf("Hello %s\n", firstname "%s", lastname);
printf("Welcome to CMPUT 201!");
}

Bootstrap left align text inside centered div

Bootstrap left align text inside centered div

I have a paragraph of 4 lines that are poetry in a centered div. Because
it is poetry, I need the 4 lines aligned left, but not to the left side of
the div.
Here is how it is centered:
Lorem ipsum dolor sit amet,
onsectetur adipisicin.
Doloribus, totam unde facilis omnis
temporibus nostrum in
Here is how I want it:
Lorem ipsum dolor sit amet,
onsectetur adipisicin.
Doloribus, totam unde facilis omnis
temporibus nostrum in
Thanks.

Show text instead of row data - PHP /MYSQL

Show text instead of row data - PHP /MYSQL

I have a search engine connected to a database that gives the results in a
table.
Here is how table looks like:
The column, organizer_id contains a number used as reference. Instead
should be the organizer name.
Ex:
1280132044 should be Corporate Inc
Can you give me a hand how to make this? I'm new in PHP/MYSQL


Here is the code to print the results:
while ($row = mysql_fetch_assoc ($result)) {
echo "<tr>\n";
printf("<td><a href='http://embs-group.com/%s,%s'>%s</a></td>",
$row['id'], str_replace(" ", "_", $row['name']), $row['name']);
printf("<td>%s</td>", $row['organizer_id']);
printf("<td>%s</td>", $row['no_pages']);
printf("<td>%s</td>", $row['publication_date']);
printf("<td>%s</td>", $row['price']);
printf("<td>%s</td>", $row['currency']);
echo "</tr>\n";
}
echo "</TABLE>\n";
}

I am executing multiple sql scripts using batch file but now i want to stop execution of batch file ,If error occures in any one of sript

I am executing multiple sql scripts using batch file but now i want to
stop execution of batch file ,If error occures in any one of sript

Batch file code
sqlcmd -S dbdev026b\dbdev026b -i c:Test1.sql -o c:\o1.txt
sqlcmd -S dbdev026b\dbdev026b -i c:Test2.sql -o c:\o2.txt

gps location value dont print android

gps location value dont print android

in this code i want to get the longitude and latitude and convert them to
string to use it on the screen and sms so how can i deal with it should i
do new class ? or this code is just modified
what should i do to make it work i used all permitions for locations
public class MainActivity extends Activity implements LocationListener {
Location location; // location
LocationManager locationManager;
public String LatTxt;
public String LonTxt;
public Double latitude; // latitude
public Double longitude; // longitude
TextView latTextView = (TextView) findViewById(R.id.Latitude_Txt);
TextView lonTextView = (TextView) findViewById(R.id.Longitude_Txt);
// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10
meters
// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = (long) (1000 * 60 *
0.25); // 0.25
//
minute
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LocationManager locationManager = (LocationManager)
getSystemService(Context.LOCATION_SERVICE);
LocationListener locListener = new MyLocationListener();
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES,locListener);
lonTextView.setText(" " + location.getLongitude());
latTextView.setText(" " + location.getLatitude());
}
@Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
}
@Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
@Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
latitude = location.getLatitude();
LatTxt = latitude.toString();
longitude = location.getLongitude();
LonTxt = longitude.toString();
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}

Wednesday, 11 September 2013

how to set include directory for rebar

how to set include directory for rebar

In my module I have
-include("blah.hrl").
The .hrl file is not in the module's directory, but somewhere else on my
system. How can I make rebar find it when compiling? Is there a way to add
a path to the include directory in rebar.config?

word cloud generator with user defined word frequences?

word cloud generator with user defined word frequences?

Is there a word cloud online generator or Java API for generating word
clouds in which I can define word frequency by myself without pasting some
text?

Redmine, upload file with curl

Redmine, upload file with curl

I'm trying to upload files to Redmine from a shell script with curl.
url=localhost/redmine
curl -c cookie -F username=admin -F password=admin $url/login
curl -b cookie -F 'attachments[1][file]'=@file $url/projects/test/files/new
The first curl stores the session cookie into the file cookie after a
successful login. But the second curl to upload always fails. Redmine's
mysterious error message is
ActionController::MethodNotAllowed
Only get requests are allowed.
Any ideas?

Working with XML in flex

Working with XML in flex

I'am working with an hierarchical xml structure like this:
<employee name="AAA" group="1"..../>
<employee name="BBB" group="1"...>
<employee name="CCC" group="1".../>
</employee>
<employee name="DDD" group="0"... />
<employee name="EEE" group="0"... />
</employee>
First I need to count all employee nodes (including root node). It must
be: 5. I have tried using xml..employee.length() but it returns 4 (does
not include the root node "AAA") If I tried xml.employee.length() only
returns 1
Then, I have to create a XMList with specific search. For example all the
nodes with attribute group="1"
The same problem occurs, I use: hitList:XMLList = xml..employee.(@group ==
"1") and returns the right result but it does not take in count the root
node (in this case, it must be included)
How can I do this operations including the root node?
Thanks in advance
Cristian

Please somebody fix this code

Please somebody fix this code

In postgres database, I have 5 tables table1, table2, table3, table4 and
table5. I have 5 identical columns in each tables those are date,
location, item1, item2 and item3. Date (which consists date and time) is a
primary key in all tables.
I also have 3 folders item1, item2 and item3 where I have 3 different
files item1.xml, item2.xml and item3.xml. In xml file there are more than
20 different dates and under date tag there are 5 elements. I need to read
those data and insert into the database.
Sample of xml file:
<?xml version='1.0'>
<xml_code>
<date valid_time = '2013091006'>
<element id = '1'>2.9</element>
<element id = '2'>2.9</element>
<element id = '3'>2.9</element>
<element id = '4'>2.9</element>
<element id = '5'>2.9</element>
</date>
<date valid_time = '2013091012'>
<element id = '1'>2.9</element>
<element id = '2'>2.9</element>
<element id = '3'>2.9</element>
<element id = '4'>2.9</element>
<element id = '5'>2.9</element>
</date>
</xml_code>
Till the date will be 2013092000.
Sample of php code:
<?php
$dbh = new PDO("pgsql:host=host;dbname=dbname", "username", "password");
if (!$dbh) {
echo "Failed to connect database!";
}
$table = array('table1', 'table2', 'table3', 'table4', 'table5');
$item = array('item1', 'item2', 'item3');
foreach($item as $item_code)
{
$location = 'location';
$xml = folder/file;
$obj_DOM = simplexml_load_file($xml_file);
$file_dates = $objDOM->date;
foreach($file_dates as $file_date) {
$datestring = $file_date['valid time']
$elements = $file_date->element;
$i = 0;
foreach($elements as $element) {
$value = $element;
if($item_code == 'item1') { $item1 = $value; }
if($item_code == 'item2') { $item2 = $value; }
if($item_code == 'item3') { $item3 = $value; }
$row_exist = db->prepare("SELECT count(*) from " . $table[$i] .
"WHERE date = :dateandtime")
$row_exist->bindParam(':dateandtime', $datestring);
$row_exist->execute();
$num_rows = count($row_exist->fetchAll());
if($num_rows < 1)
{
$sql = $dbh->prepare("INSERT INTO " . $table[$i].
"(date, location, item1, item2, item3)
VALUES(:date, :location, :item1, :item2, :item3)");
$sql->bindParam(':date', $datestring);
$sql->bindParam(':location', $location);
$sql->bindParam(':item1', $item1);
$sql->bindParam(':item2', $item2);
$sql->bindParam(':item3', $item3);
$sql->execute();
}
else{
$sql = $dbh->prepare("Update" . $table[$i] .
"SET item1=:item1, item2=:item2, item3=:item3
WHERE date = :date AND location = :location")
$sql->bindParam(':date', $datestring);
$sql->bindParam(':location', $location);
$sql->bindParam(':item1', $item1);
$sql->bindParam(':item2', $item2);
$sql->bindParam(':item3', $item3);
$sql->execute();
}
$i++;
}
}
}
?>
Just trying make it clear. For example: value from element ID=1 from
item1.xml, item2.xml and item3.xml are supposed to be stored in columns
item1, item2 and item3 of table1 respectively along with date and
location.Now I am having issue in update. After I run this code, only
item1 values are inserted into all 5 tables but not item2 and item3 which
supposed to be inserted from update code. Can somebody please assist me
and show what is wrong I am doing here?
These are not the real code. If somebody do not understand the code please
let me know where I can make the improvements but please those people who
do not know how to fix this code do not bother yourself posting other
unnecessary comments.
Thank you in advance!!