Saturday, 31 August 2013

Update to the database error when enter more than 1 value

Update to the database error when enter more than 1 value

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

jQuery autocomplete remote data using getJson with autocomplete.filter

jQuery autocomplete remote data using getJson with autocomplete.filter

Many people are using jQuery Autocomplete with a remote data source like
this:
$("#auto").autocomplete({
source: function( request, response ) {
$.getJSON( "search.php", { // get the json here
term: extractLast( request.term ) // function further, up not important
}, response );
}
});
and many people are filtering their data arrays like this:
$("#auto").autocomplete({
source: function(request, response) {
var results = $.ui.autocomplete.filter(myarray, request.term); //data in
"myarray"
response(results) ;
}
});
I can't find any example where anyone is filtering a remote data source
and I really need both. I'd like to just combine these to blocks of code
if possible.
Thanks.

JavaScript->CSS: display="";?

JavaScript->CSS: display="";?

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

NodeJS download file not working on IE

NodeJS download file not working on IE

I've ran into a problem that seems very simple to me, but I can't for the
life of me figure it out. I have a simple NodeJS server that uses
ExpressJS that basically verifies an email and grants the user access to a
zip file. The problem is this works great on Chrome and Firefox but not on
IE until I open the F12 developer console. I've looked through all
documentation I came across on here and various other sites with no
mentions of similar problems.
My guess is some setting isn't enabled on IE, but I've verified I have
active scripting enabled, and lowered my security level. This problem is
happening for all my IE users and i'm hoping someone will have an answer
for me.
var stat = fs.statSync('myFile.zip');
res.writeHead(200, {
'Content-Type': 'application/octet-stream',
'Content-Length': stat.size,
'Content-disposition' : 'attachment; filename="myFile.zip'
});
console.log('Starting download: ' + 'myFile.zip' );
var stream = fs.createReadStream( 'myFile.zip', { bufferSize: 64 * 1024 });
stream.pipe(res);
//res.download( 'myFile.zip', "myFile.zip" );
As you can see I've tried both expressjs's res.download and stream.pipe
with the exact same results.
Thank you in Advance Adam

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

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

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

Manipulation of lines of text

Manipulation of lines of text

The code below tries to manipulate several lines of text one at the time.
My first issue is to write a loop to read several lines of text(using
scanf()) and quit when the first character typed is a newline. These lines
of text have some conditions: The first character must be a number between
2 and 6 followed by a space and a line of text(<80).This number will make
"dance" the text. My second issue is to figure out how to convert the
letters from small to capital and viceversa according to the first number
typed. I have to function to make these conversions but I don't know how
to call them to change the text.For example: if I typed "3 apples and
bananas" the correct output should be "AppLes And BanNas".As you see, the
white spaces are ignored and the text always start with a capital letter.
#include <stdio.h> //Headers
#include <stdlib.h>
#include <string>
#include <ctype.h>
using namespace std;
void print_upper(string s1);
void print_lower(string s2);
void main(void)
{
char text[80];
text[0]='A';//Initialization
int count_rhythm;
while (text[0] != '\n'){//To make the loop run until a newline is typed
scanf(" %79[^\n]",text);
if(isdigit(text[0])) //To verify that the first character is a number
{
printf("\nGood");//Only to test
}
else
{
printf("\nWrong text\n");//Only to test
}
}
}
void print_upper(string s1)//Print capital letters
{
int k1;
for(k1=0; s1[k1]!='\0'; ++k1) putchar(toupper(s1[k1]));
}
void print_lower(string s2)//Print small letters
{
int k2;
for(k2=0; s2[k2]='\0'; ++k2) putchar(tolower(s2[k2]));
}

How to insert values into database in java

How to insert values into database in java

String sql = "INSERT INTO user (userid, username, password, lastname,
firstname, "
+ "middlename, birthdate, gender, address, email, contact, "
+ "marital_status, religion) VALUES (?,?,?,?,?,?,?,?,?,?,?,?)";
try {
pst = conn.prepareStatement(sql);
pst.setString(1, username);
pst.setString(2, password.toString()); //chartype
pst.setString(3, lastName);
pst.setString(4, firstName);
pst.setString(5, middleName);
pst.setString(6, birthdate);
pst.setString(7, gender1);
pst.setString(8, address1);
pst.setString(9, email1);
pst.setLong(10, mobile);
pst.setString(11, status1);
pst.setString(12, religion1);
pst.execute();
}catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
I have 13 column... and userid is autoincrement... but i don't know how do
that you don't need to put the user id... and I got this error... And I
want Auto Increment ID... so no need to input right?
Column count doesn't match value count at row 1

Update datetime in Database

Update datetime in Database

Consider this code:
var datetime = DateTime.Now;
var instantMessage =
InstantMassageingManager.GetConverationMessages().FirstOrDefault();

InstantMassageingManager.UpdateConversationMessageReadDateTime(instantMessage.InstantMessageInstanceId,
datetime);
var message =
InstantMassageingManager.GetMessageById(instantMessage.InstantMessageInstanceId);
Assert.IsTrue(message.ReadDateTime.Value == datetime);
in the first line i get DateTime.Now
then I update a record in database:UpdateConversationMessageReadDateTime
and get the message again from database:
Both message.ReadDateTime and datetime has same value but with different
Tick.
So my test doesn't pass.
Why have diffrent tick?

Friday, 30 August 2013

How to rotate image in jquery?

How to rotate image in jquery?

can you please tell me how to rotate a image like that : Take human being
body Example : First we stand our face in front side. When I click on
image our face goes back side, and Back will come front. I google it find
there is method
("#image").rotate(180);
but it not work in my example I try 360 but not work..:(
can you have any image of boy having front and back so that I can also
check.?

Thursday, 29 August 2013

Sequence point from function call?

Sequence point from function call?

This is yet another sequence-point question, but a rather simple one:
#include <stdio.h>
void f(int p, int) {
printf("p: %d\n", p);
}
int g(int* p) {
*p = 42;
return 0;
}
int main() {
int p = 0;
f(p, g(&p));
return 0;
}
Is this undefined behaviour? Or does the call to g(&p) act as a sequence
point?

password for Login Application in c# windows form

password for Login Application in c# windows form

How to display password as "**" in the text box instead of displaying real
password on text box? Is it possible in c#
Thanks

Wednesday, 28 August 2013

Conversion of mixed ASCII string with multi-byte sequences to proper UTF-8

Conversion of mixed ASCII string with multi-byte sequences to proper UTF-8

Please consider the following ASCII string that comes in from a CSV file:
Foo\xe2\x80\x99s Bar
Using PHP, how can one reliably convert this to UTF-8 so that the value is:
Foo's Bar

angularjs bind on mouseenter in directive not working

angularjs bind on mouseenter in directive not working

I can't get the directiv i angular to bind on mouseenter, i have tried in
a simple example, what is wrong here?
<html lang="en" >
<head>
<title>My AngularJS test</title>
<script src="angular.js"></script>
</head>
<body >
<div ng-app="testApp" ng-controller="testCtr">
<div testDir>test here</div>
<!-- just testing to see if the app is working -->
{{test}}
<script type="text/javascript">
var app = angular.module("testApp", []);
app.directive("testDir", function(){
return {
link: function(scope, element, attrs){
element.bind("mouseenter", function(){
console.log("enter")
})
}
}
})
app.controller("testCtr", function($scope) {
$scope.test = 500;
})
</script>
</div>
</body>
</html>
IT is probably a stupid mistake, but i can't see it.

Django returns duplicates but same query from dbshell return only one record

Django returns duplicates but same query from dbshell return only one record

I dont understand why Django returns duplicates in code below, can
somebody explain it? thanks.
qs = PropTelephone.objects.filter(reference=91811,
tel_number__isnull=False).exclude(tel_number='').values_list('tel_number',
flat=True).distinct()
print qs
[u'0410224291', u'0410224291']
print qs.query
SELECT DISTINCT `PROP_TELEPHONE`.`TEL_NUMBER` FROM `PROP_TELEPHONE` WHERE
(`PROP_TELEPHONE`.`TEL_NUMBER` IS NOT NULL AND
`PROP_TELEPHONE`.`REFERENCE` = 91811 AND NOT
(`PROP_TELEPHONE`.`TEL_NUMBER` = '' ))
query launched from dbshell returns only one record
+-------------------------------+
| TEL_NUMBER |
+-------------------------------+
| 0410224291 |
+-------------------------------+
so why django returns for such query two same records? ofcourse in DB
exists two records, with different values in other columns. but distinct
for column tel_number should return only one IMHO.

How to get table/view name (i.e. remove schema prefix)

How to get table/view name (i.e. remove schema prefix)

Given one of the following strings (which represent a table/view name in
SQL Server):
var x = "my-Table.request";
var x = "[my-Table.request]";
var x = "dbo.my-Table.request";
var x = "[dbo].[my-Table.request]";
var x = "[dbo].my-Table.request";
var x = "dbo.[my-Table.request]";
I would like to get the table name: my-Table.request
Any ideas?

How to Add month to a date while keeping the last month of a given month

How to Add month to a date while keeping the last month of a given month

Can somebody help me on how to add month to a date while keeping the last
day of that month?
Suppose I have updated the first data on 2013-01-29, so when adding one
month to that date, it will be 2013-02-28. But everytime I add one month
again on the latest date, it becomes 2013-03-28 but it must be 2013-03-29.
What would be the perfect command in mysql query that I can use.
Thanks in advance.

Tuesday, 27 August 2013

Hibernate: No identifier specified for entity (yes, I have decorated with @Id...)

Hibernate: No identifier specified for entity (yes, I have decorated with
@Id...)

I have searched all over the place and it seems almost all answers for
this problem tell me to annotate either my id property or getter with @Id.
I have tried both with absolutely no luck. Here is my entire class thats
failing: http://pastebin.com/Cpsdx2Rj and the following is my exception:
http://pastebin.com/uhs9e81b
As I said, I already tried moving the @Id devorator to the property and
that doesnt seem to do anything at all.
Any suggestions on what to try? Any other configuration files needed to
debug?
Thank you in advance for any help you can provide!

How to calculate an area of polygon by its coordinates=?iso-8859-1?Q?=3F_=96_mathematica.stackexchange.com?=

How to calculate an area of polygon by its coordinates? –
mathematica.stackexchange.com

I have polygon Polygon[{{0, 200 }, {200, 100}, {500, 300}, {100, 700}}].
How can I figure out its area? The docs page does not have any example. So
far I've reached this point with no success: ...

Best way to extract lines from a php variables

Best way to extract lines from a php variables

What's the best way to extract lines from a php variable?
This php variable contains HTML code from cURL.
The lines are those:
<tr class="tr1"><td align="right">1.</td><td align="left"><input
type="hidden" name="now[8116632]" value="98" />
<tr class="tr2"><td align="right">2.</td><td align="left"><input
type="hidden" name="now[8121292]" value="90" />
The class of the lines is always "tr1" and tr2", also the lines are 199 to
208 :/
I try with XPath query('//*[@class="tr1"]'), i get 5 elements but i don't
know how to print those elements. How can i do that?
Thanks in advance

Sonic and all stars racing + Team Viewer 8

Sonic and all stars racing + Team Viewer 8

I am trying to use Team Viewer 8 with my friend playing sonic and all
stars racing but it keeps glitching. I disabled remote control but it's
still happening, only until I exit team viewer. It's in windowed, but then
turns into full screen?! I see a blue box around the window then that's
the only thing I can see! It happens only on the windows 8.1 beta. It
happens on sonic adventure 2 and sonic adventure. Sometimes sonic
generations.

how to change a title of the activity?

how to change a title of the activity?

How do I change the title of the activity? as of now it just displays the
title of the program and i am wanting it to display something of my
choosing and be different for each page/activity in my app i.e. my home
page could say frog(1/17) in the title while another activity that the app
switches to could have frog(2/17) in that title by using on click event or
by using butt

Monday, 26 August 2013

Get data from URL PHP

Get data from URL PHP

I want to have a system that looks for a page at that URL and if it cant
find one it passes the URL to the last page it can find (sorry for the bad
explanation, this is the only way I could think of putting it). Example:
say I entered the URL "www.mysite.com/users/username" it would pass the
string "username" to "users.php" instead of having it like
www.mysite.com/users?user=username. if there is no users.php in the site
then it directs you to a 404 page.
Sorry for the really bad explanation all I really need is a name of what
this would be called and I could find some information on it but I am not
sure what I am looking for.
Thanks.

Bluetooth not pairing after every reboot

Bluetooth not pairing after every reboot

Hey all I am hoping someone has an easy fix for my issue here. I can pair
my android cell phone to the pc via win 8 generic bluetooth drivers and it
works after confirming the pair code on both my cell phone and my pc.
Problem is that once I reboot I can not connect to the cell phone and have
to remove the device from the list and discover it again, pair with it
again and then it works.
Am I missing a setting in win 8 that keeps the settings for my bluetooth
devices and connects to it once it sees it again?
Also, is there any better drivers/ software to use other than the generic
bluetooth drivers that win 8 uses?
I have an intel 7260 HMW mini pcie wireless n card with bluetooth 4.0.

A single key on keyboard produces extra keypresses for each simultaneously pressed key

A single key on keyboard produces extra keypresses for each simultaneously
pressed key

I recently acquired MK-85 mechanical USB keyboard from QPAD. The keyboard
works perfect on Windows. It works perfect in Syslinux. It works almost
perfect on Linux. The only issue on Linux is that a single key is
misbehaving (Gentoo (3.6.11), Arch Linux and Linux Mint (2.6.38) are all
affected).
The keyboard is a 105-key German layout keyboard and the key in question
is the one between Ä and ENTER. On US layout this corresponds to the key
"\", on German layout this corresponds to "#" and on Scandinavian layout
it's '.
When this key is pressed with other keys, it produces an extra keypress
for each other key that is simultaneously pressed. For example, under
Scandinavian layout if I want to type the word "don't" really fast I end
up with: don'''t'
The behaviour can be observed with the program showkeys:
kb mode was UNICODE
[ if you are trying this under X, it might not work
since the X server is also reading /dev/console ]
press any key (program terminates 10s after last keypress)...
keycode 28 release
keycode 32 press // d pressed
keycode 24 press // o pressed
keycode 49 press // n pressed
keycode 32 release // d released
keycode 43 press // ' pressed
keycode 24 release // o released
keycode 43 release // ' released
keycode 43 press // ' pressed, extra ' produced
keycode 49 release // n released
keycode 43 release // ' released
keycode 43 press // ' pressed, extra ' produced
keycode 20 press // t pressed
keycode 43 release // ' released
keycode 43 press // ' pressed, extra ' produced
keycode 20 release // t released
keycode 43 release // ' released
keycode 43 press // ' pressed, extra ' produced
keycode 43 release // ' released (REAL)
It only happens with this single key, regardless of keyboard layout.
Another way it manifests itself is if I press and hold a key, it repeats,
and I press and hold another key which should also start repeating:
aaaaaaaaaakkkkkkkkkkkkk (works as intended)
¨¨¨¨¨¨¨¨¨¨fffffffffffff (works as intended)
''''''''''a'''''''''''' (a is not repeated, instead ' continues)
On Windows this issue does not exist:
OnKeyDown, Key code=68, Control keys=, Key name d
OnKeyPress d
OnKeyDown, Key code=79, Control keys=, Key name o
OnKeyPress o
OnKeyDown, Key code=78, Control keys=, Key name n
OnKeyPress n
OnKeyup, Key code=68, Control keys=, Key name d
OnKeyDown, Key code=191, Control keys=, Key name ........OEM specific
OnKeyPress '
OnKeyup, Key code=79, Control keys=, Key name o
OnKeyup, Key code=78, Control keys=, Key name n
OnKeyDown, Key code=84, Control keys=, Key name t
OnKeyPress t
OnKeyup, Key code=191, Control keys=, Key name ........OEM specific
OnKeyup, Key code=84, Control keys=, Key name t
What do you think SE? Hardware issue? It works fine in Syslinux which
makes me feel like there'''s' something wrong on Linux side. Any pointers,
ideas or better ways to debug? If getting this to work right requires
patching the kernel I'm up for it.
I thank for your time humbly.

How to Input Two Files and Search & Delete All Matches?

How to Input Two Files and Search & Delete All Matches?

I am trying to create a program that will input two .css files.
CSS FILE 1 is simply a list of selectors with no properties. An example
below:
audio, canvas, video
audio:not([controls])
[hidden]
CSS FILE 2 is a normal css file with selectors and properties. An example
below:
article, aside, details, figcaption, figure, footer, header, hgroup, nav,
section, summary {
display: block;
}
audio, canvas, video {
display: inline-block;
*display: inline;
*zoom: 1;
}
audio:not([controls]) {
display: none;
height: 0;
}
[hidden] {
display: none;
}
Each line in CSS FILE 1 is a separate selector and there is only one
selector per line. The idea is, for each line, to search for the same
selector in CSS FILE 2 and delete the selector and everything following it
from the opening curly bracket { to the closing curly bracket }.
Since I am not very familiar with perl, I was looking to get started in
the right direction.
My question, how would I set the program up to input both CSS FILE 1 and
CSS FILE 2, and search CSS FILE 2 for the contents of each line found in
CSS FILE 1.
What I have so far is this:
#!/usr/bin/perl
use strict;
use warnings;
my $infile=<unused.css>;
my $infile2=<all.css>;
open(my $unused,'<', "$infile") or die $!;
open(my $all,'<',"$infile2") or die $!;
open(my $out, '>' ,'convertedback.css') or die $!;
my $lineU = <$unused>;
my $lineA = <$all>;
print $out "$lineU";
print $out "$lineA";
Thank you for your help in pointing me in the right direction.

A network-related or instance-specific error occurred while establishing a connection to SQL Server. Error Locating Server/Instance...

A network-related or instance-specific error occurred while establishing a
connection to SQL Server. Error Locating Server/Instance...

Moving a web project from test enviroment to the web server made this
error occur whenever tehre's an attempt to open a connection to the sql
server.
We can insert and read data from sql server management studio.
We're suspecting that the error is created from a bad connection string or
from the sql server using integrated security, but haven't been able to
confirm that.
the connection string.
<connectionStrings>
<add name="DSVUShort" connectionString="data
source=localhost\SQLEXPRESS;database=NS_Survey; integrated
security=true;multipleactiveresultsets=True;App=EntityFramework" />
</connectionStrings>
where it is used
SqlConnection Connection = new
SqlConnection(ConfigurationManager.ConnectionStrings["DSVUShort"].ToString());
Connection.Open() // pops the error

log parser doesn't interpret dates correctly

log parser doesn't interpret dates correctly

When I query our IIS logs, I get a value of '30/12/1899' in the date column.
select * from 'C:\IIS 2013 Logs\*.log'
However for some rows, it does have a valid date. (Coincidently rows that
have a day number less than or equal to 12) So immediately you can tell
it's a date formatting issue.
Our IIS is logging in american date format (mm-dd-yyyy) - I cannot change
this. Our server however runs on UK date format (dd-mm-yyyy).
Is there an extra argument I can give log parser so that it grabs the
dates correctly from our americanized logs?

Sunday, 25 August 2013

Excel 2011 Opens Spreadsheet As Read-Only

Excel 2011 Opens Spreadsheet As Read-Only

I have a spreadsheet (.xlsx) file that, when I open it on my MBP running
Excel 2011 14.3.6, I get a pop-up telling me the file is locked and can
only be opened in read-only mode. About a minute later, Excel opens
another pop-up and this time says that the file is unlocked and asks if I
want to edit it.
I've triple-checked permissions on the file and it's definitely editable
by me. I've also verified in Get Info -> General that it's not locked.
The file is located on a USB flash drive. I created a copy of this file on
the local drive (/Users/aj) and it will open fine without the warning.
Other Excel files saved on the USB flash drive open without this warning.
A copy of this file on the USB drive still has the warning.
What can I do to remove the warning? I use this file all the time and it's
super-annoying.

Concurrent reading of multiple file took same time as normal reading

Concurrent reading of multiple file took same time as normal reading

I am processing a my web server access logs and store the processed
information into my db. Previously , I did as single threaded process. It
took long time to complete the process. I decided to go with concurrent
file reading to save the execution time. I achieved this using Executors
thread pool. Here is my java code.
Log File Handler
class FileHandler implements Runnable {
private File file;
public FileHandler(File file) {
this.file = file;
}
@Override
public void run() {
try {
byte[] readInputStream = readInputStream(new
FileInputStream(file));
} catch (IOException e) {
e.printStackTrace();
}
}
public static byte[] readInputStream(InputStream in) throws
IOException {
//closing the bytearrayoutput stream has no effect. @see java
doc.
ByteArrayOutputStream bos = null;
byte[] buffer = new byte[1024];
int bytesRead = -1;
bytesRead = in.read(buffer);
//no input to read.
if(bytesRead == -1) {
return null;
}
bos = new ByteArrayOutputStream(in.available()); //creating
output stream with approximate capacity.
bos.write(buffer , 0 , bytesRead);
try {
while((bytesRead = in.read(buffer)) != -1) {
bos.write(buffer , 0 , bytesRead);
}
}finally {
if(in != null) {
in.close();
}
}
return bos.toByteArray();
}
}
Concurrent File Reading
public class AccessLogProcessor {
public static void main(String[] args) {
String[] files = {
"/home/local/ZOHOCORP/bharathi-1397/Downloads/unique-invoice-zuid1.txt"
,
"/home/local/ZOHOCORP/bharathi-1397/Downloads/unique-invoice-zuid.txt"
};
long start = System.currentTimeMillis();
ExecutorService executors =
Executors.newFixedThreadPool(files.length);
for(String file : files) {
executors.execute(new FileHandler(new File(file)));
}
executors.shutdown();
while(!executors.isTerminated());
System.out.println("Time Taken by concurrent reading ::
"+(System.currentTimeMillis()-start) + " ms ");
}
}
Single Threaded File Reading
public class Test {
public static void main(String[] args) throws
FileNotFoundException, IOException {
String[] files = {
"/home/local/ZOHOCORP/bharathi-1397/Downloads/unique-invoice-zuid1.txt"
,
"/home/local/ZOHOCORP/bharathi-1397/Downloads/unique-invoice-zuid.txt"
};
long start = System.currentTimeMillis();
for(String file : files) {
FileHandler.readInputStream(new FileInputStream(file));
}
System.out.println("Time Taken by concurrent reading ::
"+(System.currentTimeMillis()-start) + " ms ");
}
}
Test Result for 10 rounds of execution
Single Thread Execution : 9ms.
Concurrent Execution : 14ms.
I am reading files in concurrently but why the timetaken is greater than
single threaded execution?. Please correct me If I did anything wrong?.

Multilanguage MVC 4 application

Multilanguage MVC 4 application

i am creating a new application right now and i want to make all right at
the start so i can grow with it in the future.
I have looked on several guides descibing how to make a multilanguage
supported application, but i cant figure out witch one to use.
Some tutorials are old and i don't know if they are out of date.
http://www.codeproject.com/Articles/352583/Localization-in-ASP-NET-MVC-with-Griffin-MvcContri
http://geekswithblogs.net/shaunxu/archive/2012/09/04/localization-in-asp.net-mvc-ndash-upgraded.aspx
http://www.hanselman.com/blog/GlobalizationInternationalizationAndLocalizationInASPNETMVC3JavaScriptAndJQueryPart1.aspx
http://www.chambaud.com/2013/02/27/localization-in-asp-net-mvc-4/
I found that they are 2 ways of storing the language data, either in db or
in resource files. What are the pro/cons? Is there another way that is
prefered?
This is what i want:
Easy to maintain (Add/Change/Remove)
Full language support. (views, currency, time/date, jquery, annotations
and so on..)
Enable to change language.
Auto detect language.
Future safe.
What is the prefered way of doing this? got any good tutorial that is best
practice for 2013?

Saturday, 24 August 2013

hadoop partitioner getting incorrect reduce count

hadoop partitioner getting incorrect reduce count

I'm working on partitioner today. Its the basic program in hadoop custom
partitioners. Below is my partitioner code snippet.
public class VowelConsPartitioner extends Partitioner {
@Override
public int getPartition(Text letterType, IntWritable count, int redCnt) {
// TODO Auto-generated method stub
//System.out.println("reduce cnt in partitioner: "+redCnt);
if(letterType.toString().equalsIgnoreCase("vowel")){
//System.out.println("vowel sound: "+1%redCnt);
return letterType.toString().hasCode()%redCnt;
}
if(letterType.toString().equalsIgnoreCase("consonent")){
//System.out.println("Cons sound: "+2%redCnt);
return letterType.toString().hasCode()%redCnt;
}
else
return 0;
}
}
And I set my reducers in my driver class like this....
job.setNumReduceTasks(3);
job.setPartitionerClass(VowelConsPartitioner.class);
I want to keep more than 1 reducer. But I'm getting the o/p in one reducer
only. Moreover if you see the partitioner code, the first sysout(I've
commented) was giving me redCnt as 1. I'm not sure how thats happening
when I set its count to 3 from my driver class. Could someone help me out
on this?
FYI... I'm making jar & running this on HDFS.

Is this a dumb way to sort a few values?

Is this a dumb way to sort a few values?

I'm checking dimensions on things and I want to know the 3 dimensions from
largest to smallest.
So here's the kinda' whizzy function I wrote:
CREATE FUNCTION dbo.SortDimensions
( @aDim1 udt_Dimension
, @aDim2 udt_Dimension
, @aDim3 udt_Dimension
)
RETURNS @rDimensions TABLE
( Dim1 udt_Dimension
, Dim2 udt_Dimension
, Dim3 udt_Dimension
)
AS
BEGIN
; WITH OrderedDims ( Dimension ) AS (
SELECT @aDim1
UNION ALL SELECT @aDim2
UNION ALL SELECT @aDim3
)
, Pairs ( Name, Value ) AS (
SELECT 'Dim' + CAST( ROW_NUMBER() OVER (ORDER BY( Dimension ) DESC )
AS varchar ), Dimension
FROM OrderedDims
)
INSERT INTO @rDimensions ( Dim1, Dim2, Dim3 )
SELECT MAX(Dim1), MAX(Dim2), MAX(Dim3)
FROM Pairs
PIVOT ( MAX(Value) FOR Name IN ( [Dim1], [Dim2], [Dim3] )) p
RETURN
END
Isn't this a lot of work for doing the same thing as this:
DECLARE @lDim1 udt_Dimension
DECLARE @lDim2 udt_Dimension
DECLARE @lDim2 udt_Dimension
IF @aDim2 > @aDim1
BEGIN
SELECT @lDim1 = @aDim2
, @lDim2 = @aDim1
END
ELSE
BEGIN
SELECT @lDim1 = @aDim1
, @lDim2 = @aDim2
END
IF NOT @aDim3 > @aDim2
BEGIN
SET @lDim3 = @aDim3
END
ELSE
BEGIN
SET @lDim3 = @lDim2
IF @aDim3 > @lDim1
BEGIN
SET @lDim2 = @lDim1
SET @lDim1 = @aDim3
END
ELSE
BEGIN
SET @lDim2 = @aDim3
END
END
INSERT INTO @rDimensions VALUES ( @lDim1, @lDim2, @lDim3 )
I believe a DBA once told me that the guys who designed SQL server reused
the the technology of temp tables for variables, so its pretty much a wash
between tables and variables. (Go ahead and disabuse me of this notion, if
it's not true.)

How to get data in PDO with 2 conditions parenthesis

How to get data in PDO with 2 conditions parenthesis

HERE is the normal sql
$q= mysql_query("SELECT c_id FROM conversation WHERE (user_one='$user_one'
and user_two='$user_two') or (user_one='$user_two' and
user_two='$user_one') ") or die(mysql_error());
I want to do it in PDO way but can not get the same result. I have use PDO
fo rmany project but not with 2 2 conditions parenthesis like this.
I have tried
$q = $conn->prepare("SELECT c_id FROM conversation WHERE (user_one=? and
user_two=?) or (user_one=? and user_two=?) ");
$q->execute(array($user_one, $user_two, $user_two, $user_one));
But it doesn´t work.
Ps I get no error, just can not get the same result.

C++ post increment is executing before the body of a for loop?

C++ post increment is executing before the body of a for loop?

I'm going totally crazy here. I'm using Visual Studio 2008, and I can't
help but think it has a bug in it, or otherwise I've just forgotten some
serious fundamentals.
It seems that when I remove the "initialization" (first field) of my for
loop, my "post-increment" (third field) executes prior to the body of the
loop.
std::list<VideoTranscoderStats>::iterator videoStatsIter =
mTranscoderStatisticsList.begin();
for(;videoStatsIter != mTranscoderStatisticsList.end();videoStatsIter++)
{
// do stuff
}
As I debug, I can see that I'm executing "videoStatsIter++" before "do
stuff", and also before testing the condition in the for loop.
On the other hand, if I move my initialization of videoStatsIter into the
beginning of the for loop statement, everything works fine.
"videoStatsIter++" is executed following the body of the for loop.

Java bar chart method

Java bar chart method

I need to print out a bar chart, via a call from a method barChartPrinter.
I.e. barChartPrinter(5, 6, 2); would print: a vertical column of 5 XX's
followed by a space then a vertical column of 6 XX's and a vertical column
of 2 XX's.
The numbers are based on user input, so I'm thinking I need to gather the
numbers and store those in an array. And I'm thinking a for loop will be
involved, but I'm not sure how I'd do it.
public class BarChart {
public static void main(String args[]) {
int[] list = new int[3];
Scanner input = new Scanner(System.in);
System.out.println("Enter four integers: ");
for(int i = 0; i < list.length; i++)
list[i] = input.nextInt();
barChartPrinter(list);
}
public static void barChartPrinter(int[] numbers) {
}
}
This is where I get stuck: defining the method that will print out the bar
chart; given the user input values. The method needs to print out in this
format, i.e.
barChartPrinter(1, 2, 3) =
For some reason, it won't display how the bar chart should be constructed
on here so I'll just describe it:
There would first be a column of XX, then a column of XX (two of these
vertically to represent 2) and then another column of XX (but this time
three of these on top of each other, to represent the number 3).
Any pointers?
Thanks!

Diagonalizable matrix with only one eigenvalue

Diagonalizable matrix with only one eigenvalue

I have a question from a test I solved (without that question.. =) "If a
matrix A s.t A is in M(C) (in the complex space) have only 1 eigenvalue
than A is a diagonalizable matrix"
That is a false assumption since a (nXn matrix) a square matrix needs to
have at least n different eigenvalues (to make eigenvectors from) - but
doesn't the identity matrix have only 1 eigenvalue?...

Can we use RewriteRule for internal paths?

Can we use RewriteRule for internal paths?

I've always seen RewriteRule used for public URL paths, but can we also
map the URLs to internal paths?
For example, to redirect all links to my_page.php, is this allowed? :
RewriteRule .* /home/yccaucom/public_html/my_page.php [last,noescape]

Friday, 23 August 2013

Windows activation failed

Windows activation failed

My PC is a Windows 7 Enterprise 32bit machine. I have to activate Windows.
I've tried to activate online but no luck. My product key is
00392-918-5000002-85052. I would be much appreciated if anyone would be so
kind enough to help me to solve this problem as soon as possible. Because
it's urgent.
Thanx in advance.

Does "cut teeth" make sense?

Does "cut teeth" make sense?

Billy is cranky because he's cutting teeth.
The expression "cutting teeth" means the baby's new teeth appear. However,
the teeth are supposedly doing the cutting (which to add to the confusion,
is incorrect). So shouldn't be "Billy is cranky because his teeth are
cutting"?

Deny direct download of file in public directory php or htaccess

Deny direct download of file in public directory php or htaccess

I have a jquery mp3/ogg player on one of my sites, so I have to provide an
absolute url to player script. Any suggestions on how to block direct
downloads in this situation?

Which one VoIP SIP audio codec should I choose to high quality calls?

Which one VoIP SIP audio codec should I choose to high quality calls?

The quality of VoIP calls depends on the codec used for the transmission
and on the bandwidth of Internet connection. I want to use best optimized
codec for my Internet connection.
I have to select codecs from the following list:
G.722
G.711 u law
G.711 a law
G.726
G.729
Which one to choose and why?
I want to have best high quality voice on both sides.
I have ADSL2+ Internet connection with bit rates:
download 6 Mbit/s
upload 0.5 Mbit/s

How to send email on specific time using php?

How to send email on specific time using php?

HI i am developing a website. In this i am having one reminder form. One
the user gave the details, the reminder should go daily from the specific
date. For example if the user wants reminder from 23.08.13 means, reminder
should go from 23.08.13 till 27.08.13. This five times. Is it possible to
do it without database connection? Can anyone help me to solve my problem?
Thanks in advance.

Tips for getting a good grip on Rails?

Tips for getting a good grip on Rails?

I've been learning Rails via the primary tutorial authored by Michael
Hartl, and I'm mostly understanding what's going on, but I'm also getting
this feeling like I'm slowly progressing deeper into a castle of sorcery
and illusion that I'll never be able to find my way back out of.
A lot of things seem to just happen "automagically," and I'm a little
concerned that I'm going to lose track of what I have to do by hand and
what Rails can do for you and start making some gruesomely time-consuming
mistakes.
Any stories on personal Rails learning experiences, good ways to get a
firm grip on the mysterious machinery running behind the pretty syntax?

Thursday, 22 August 2013

((((((((((((( __ READ __ BEFORE ___ DELETED ___ BY ___ MODS ___ ))))))))))))))

((((((((((((( __ READ __ BEFORE ___ DELETED ___ BY ___ MODS ___
))))))))))))))

You are about to be provided with information to
start your own Google.
Some people posted comments and said this can not
be done because google has 1 million servers and we do not.
The truth is, google has those many servers for trolling
purposes (e.g. google +, google finance, youtube the bandwidth consuming
no-profit making web site, etc ).
all for trolling purposes.
if you wanted to start your own search engine...
you need to know few things.
1 : you need to know how beautiful mysql is.
2: you need to not listen to people that tell you to use a framework
with python, and simply use mod-wsgi.
3: you need to cache popular searches when your search engine is running.
3: you need to connect numbers to words. maybe even something like..
numbers to numbers to words.
in other words let's say in the past 24 hours people searched for
some phrases over and over again.. you cache those and assign numbers
to them, this way you are matching numbers with numbers in mysql.
not words with words.
in other words let's say google uses 1/2 their servers for trolling
and 1/2 for search engine.
we need technology and ideas so that you can run a search engine
on 1 or 2 dedicated servers that cost no more than $100/month each.
once you make money, you can begin buying more and more servers.
after you make lots of money.. you probably gonna turn into a troll
too like google inc.
because god is brutal.
god is void-state
it keeps singing you songs when you are sleeping and says
"nothing matters, there is simply no meaning"
but of course to start this search engine, you need a jump start.
if you notice google constantly links to other web sites with a
trackable way when people click on search results.
this means google knows which web sites are becoming popular
are popular, etc. they can see what is rising before it rises.
it's like being able to see the future.
the computer tells them " you better get in touch with this guy
before he becomes rich and becomes un-stopable "
sometimes they send cops onto people. etc.
AMAZON INC however..

will provide you with the top 1 million web sites in the world.
updated daily in a cvs file.
downloadable at alexa.com
simply click on 'top sites' and then you will see the downloadable
file on the right side.
everyday they update it. and it is being given away for free.
google would never do this.
amazon does this.
this list you can use to ensure you show the top sites first in your
search engine .
this makes your search engine look 'credible'
in other words as you start making money, you first display things
in a "Generic" way but at the same time not in a "questionable" way
by displaying them based on "rank"
of course amazon only gives you URLS of the web sites.
you need to grab the title and etc from the web sites.
the truth is, to get started you do not need everything from web sites.
a title and some tags is all you need.
simple.
basic.
functional
will get peoples attention.
i always ask questions on SO but most questions get deleted. here's
something that did not get deleted..
How do I ensure that re.findall() stops at the right place?
use python, skrew php, php is no good.
do not use python frameworks, it's all lies and b.s. use mod-wsgi
use memcache to cache the templates and thus no need for a template engine.

always look at russian dedicated servers, and so on.
do not put your trust in america.
it has all turned into a mafia.

google can file a report, fbi can send cops onto you, and next thing you know
they frame you as a criminal, thug, mentally ill, bipolar, peadophile, and
so on.
all you can do is bleed to death behind bars.
do not give into the lies of AMERICA.
find russian dedicated servers.
i tried signing up with pw-service.com but i couldn't do it due to
restrictions with their russian payment systems and so on..
again, amazon's web site alexa.com provides you with downloadable
top 1 mil web sites in the form of a cvs file.
use it.
again, do not give into python programmers suggesting frameworks for python.
it's all b.s. use mod_wsgi with memcache.
again, american corporations can ruin you with lies and all you can do is
bleed to death behind bars
again, a basic search engine needs : url, title, tags, and popular searches
can be "cached" and words can be connected to "numbers" within the mysql.
mysql has capabilities to cache things as well.
cache once, cache twice, and you will not need 1 million servers in order
to troll.
if you need some xdotool commands to deal with people calling you a troll
here it is;
xdotool key ctrl+c
xdotool key Tab Tab Tab Return
xdotool type '@'
xdotool key ctrl+v
xdotool type --clearmodifiers ', there can not be such thing as a `troll`
unless compared to a stationary point, if you are complaining, you are not
stationary. which means you are the one that is trolling.'
xdotool key Tab Return
create an application launcher on your gnome-panel, and then select the
username in the comments section that called you a 'troll' and click the
shortcut on the gnome-panel.
it will copy the selected username to the clipboard and then hit TAB TAB
TAB RETURN
which opens the comment typing box. and then it will type @ + username +
comma, and then the rest.
.................................................
--------------------------------------------------------------------------------------

Can any one please tell me why my code isn't working?

Can any one please tell me why my code isn't working?

I am trying to program a username/password log in view controller, there
is no errors, no warnings in my app but it always output out "match not
found" even when i select a username that already exist in my
database..I'd really appreciate it if u could help this is the code:
[super viewDidLoad];
NSString *docsDir;
NSArray *dirPaths;
// Get the documents directory
dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
docsDir = dirPaths [0];
_databasePath = [[NSString alloc]initWithString:[docsDir
stringByAppendingPathComponent:@"bank.db"]];
NSFileManager *filemgr = [NSFileManager defaultManager];
if ([filemgr fileExistsAtPath:_databasePath] == NO)
{
const char *dbpath = [_databasePath UTF8String];
if (sqlite3_open(dbpath, &_bankDb) == SQLITE_OK)
{
char *errMsg;
const char *sql_stmt = " CREATE TABLE IF NOT EXISTS USER (USERNAME
TEXT PRIMARY KEY, PASSWORD TEXT)";
if (sqlite3_exec(_bankDb, sql_stmt, NULL, NULL, &errMsg) !=
SQLITE_OK)
{
_status.text= @"failed to create table";
}
sqlite3_close(_bankDb);
} else {
_status.text=@"failed to open/create database";
}
}
- (IBAction)findContact:(id)sender {
const char *dbpath = [_databasePath UTF8String];
sqlite3_stmt *statement;
if (sqlite3_open(dbpath, &_bankDb) == SQLITE_OK)
{
NSString *querySQL = [NSString stringWithFormat:@"SELECT USERNAME,
PASSWORD FROM USER WHERE USERNAME=\"%@\"", _usernameTextField.text];
const char *query_stmt = [querySQL UTF8String];
if (sqlite3_prepare_v2(_bankDb, query_stmt, -1, &statement, NULL) ==
SQLITE_OK)
{
if (sqlite3_step(statement) == SQLITE_ROW)
{
NSString *usernameField=[[NSString
alloc]initWithUTF8String:(const char *)
sqlite3_column_text(statement, 0)];
_usernameTextField.text=usernameField;
NSString *passwordField = [[NSString alloc]
initWithUTF8String:(const char *)
sqlite3_column_text(statement, 1) ];
_passwordTextField.text=passwordField;
_status.text=@"match found";
} else {
_status.text=@"match not found";
}
sqlite3_finalize(statement);
}
sqlite3_close(_bankDb);
}
}

Looking for an examples of "request as a process" in erlang

Looking for an examples of "request as a process" in erlang

In One major difference - ZeroMQ and Erlang author mentions briefly
"request as a process" idea. I'm new to Erlang and I'd like to see an
example or an article how to do it.
Any resource or hint will be highly appreciated.

what does (function () { ... })(); mean? [duplicate]

what does (function () { ... })(); mean? [duplicate]

This question already has an answer here:
What does this "(function(){});", a function inside brackets, mean in
javascript? [duplicate] 6 answers
I see that in many modules for node.js and also for browser, they use to
have all their code inside something like this:
(function () {
moduleName.prototype.variable = 'whatever';
})();
Can anyone please explain what this all is, or any links that explain? I
have no idea how to search it! Thanks in advance.

Disable network on remastered Ubuntu 13.04 Live-CD except for localhost

Disable network on remastered Ubuntu 13.04 Live-CD except for localhost

I have remastered a Ubuntu 13.04 Live-CD for software presentations.
During boot, it tries to find a network connection for several minutes
(but fails in the end). Maybe it does not detect my network card properly
(MacBook Pro). For the live system I don't need an internet connection.
Only access to localhost is important.
How do I prevent the system from configuring the network/internet
connection while still preserving access to localhost?
If I can not turn this off, is it possible to reduce the timeout for this
configuration process?

Join and 'collectively' manipulate a de-normalized one-to-many split conditionally after the fact

Join and 'collectively' manipulate a de-normalized one-to-many split
conditionally after the fact

Tricky thing to title and explain accurately - let me know if anything's
unclear.
I have a de-normalized dataflow, consider:
Input one:
ID
Value
FKID
Input two:
FKID
DiffValue
CheckValue
Input one can have more than one input two row, relating on FKID obviously.
Now, after the joining I might have something like:
[ID] - [Value] - [DiffValue] - [CheckValue]
1 - A - D1 - C1
1 - A - D2 - C1
1 - A - D3 - C2
I then go through a conditional split, based off the CheckValue -
searching for value: C2. If C2, change Value to DiffValue. Leaving me
with:
Split one:
1 - A - D1 - C1
1 - A - D2 - C1
Split two:
1 - D3 - D3 - C2
Now I'd like to make sure that all of my rows have that D3 value. The
thing here is, that it's possible for the split never to become true, in
which case I need it to just go on, keeping the original A value, but if
just ONE of the rows fulfill the checkvalue condition, all of the rows
need the DiffValue.
A script transformation component won't work, as it's based on buffer, and
I can't cache all the rows, perform code on the entire collection of rows
at once, before sending them to output. I can't even do a simple save ID
to temp SQL and do a lookup based on ID afterwards, because after the
conditional split it's two parallel asynchronous paths, so I can't halt
the first split until after the temp SQL table has been filled.
I COULD do a script destination, caching all the rows then, perform my
manipulation after every row has been cached, and then make a custom
output with the relevant columns, however, there are many more columns
(this is a simplified example), and the maintenance in having to deal with
that custom output is overwhelming.
How would I go about this?

Wednesday, 21 August 2013

Remove Category Uncategorized from Wordpress Loop

Remove Category Uncategorized from Wordpress Loop

I want to list all post from a custom post type by category so I came up
with this code (see below) but them I see this uncategorized category I
want to remove. I tried in the query
cat=$cat_id&exclude="1"&post_type=locations but it's not working. Any
ideas? Thank You
<?php
$cats = get_categories();
foreach ($cats as $cat) {
$cat_id= $cat->term_id;
echo "<h2>".$cat->name."</h2>";
query_posts("cat=$cat_id&exclude="1"&post_type=locations");
if (have_posts()) : while (have_posts()) : the_post(); ?>
<?php ?>
<a href="<?php the_permalink();?>"><?php the_title(); ?></a>
<?php echo '<hr/>'; ?>
<?php endwhile; endif; ?>
<?php } ?>
<?php wp_reset_postdata(); ?>
</div><!-- .entry-content -->

Interact with external commands via shell_exec

Interact with external commands via shell_exec

Recently I installed Android SDK on my CentOS server because of working
with aapt, the aapt works great in command line via Putty SSH application.
Now, I want to run aapt commands through php shell_exec method.
My Android-SDK has been installed on \ipl\android-sdk\platform-tools\aapt,
but I can't interact with it through shell_exec method, my code:
Code:
$out = shell_exec("/ipl/android-sdk/platform-tools/aapt d badging t.apk
2>&1");
var_dump($out);
Result:
string(60) "sh: /ipl/android-sdk/platform-tools/aapt: Permission denied "
Any ideas?

Which is the MongoDB EmbeddedCollection representation in Behat TableNodes

Which is the MongoDB EmbeddedCollection representation in Behat TableNodes

I am trying to write a Behat feature for a subresource of my API Rest. The
underlaying data model is MongoDB and the test consist about testing the
address subresource of the user resource.
Given the Address subresource is a EmbeddedDocument inside the User
Document I would have something like this in json format:
{
"username":"admin"
"email":"admin@admin.com",
"addresses":[
{
"country":"IT",
"city":"Roma",
},
{
"country":"ES",
"city":"Madrid",
}
]
}
What I am trying to do is write a Given Step as a fixture fo the test.
Something like this:
Given the following API users exist:
| username | email | addresses[] |
| rick | admin@admin.com | ??????????????????? |
How can I represent such json data in a Gherkin Table?
Thanks!!

Assassins Creed Revelations Point of assigning assassins to cities

Assassins Creed Revelations Point of assigning assassins to cities

Hello everyone,



What's the point of assigning assassins to cities in AC Revelations?? Does
the experience income from those cities level up the assassins I put there
in the city?? For example, if I place a level to assassin in a captured
city does the experience income from that city help that assassin in
levelling up?? Will he reach level 3 and so on like that ?? What's the
point of building an assassin den in a city ??
Another question is that can all of my assassin recruits become master
assassins?? I have a bunch of assassins stuck at level 10 who won't go
into level 11. Should I place such assassins in the captured cities?? They
all have enough experience to become level 13 but are stuck at level 10.
Please advise I can't make sense of the Medditerrian Defense mini game in
this game.

How to select items according to their sums in SQL?

How to select items according to their sums in SQL?

I've got the following table:
ID Name Sales
1 Kalle 1
2 Kalle -1
3 Simon 10
4 Simon 20
5 Anna 11
6 Anna 0
7 Tina 0
I want to write a SQL query that only returns the rows that represents a
salesperson with sum of sales > 0.
ID Name Sales
3 Simon 10
4 Simon 20
5 Anna 11
6 Anna 0
Is this possible?

Invalid argument value of '1' is not valid for 'index'

Invalid argument value of '1' is not valid for 'index'

I have a listview and I want when a button is pressed to delete the
selected item. Additionally, I use the item for some other actions.
Basically, I use some letters of the item' s string to match with a file
and delete it. This works if the selected item is the first one in the
listview, but doesn' t work if it's second, third etc.
private void delete_button_Click(object sender, EventArgs e)
{
for (int i = 0; i < listView1.Items.Count; i++)
{
if (listView1.Items[i].Selected)
{
string var1 = listView1.SelectedItems[i].ToString(); //error
string var2 = var1.Substring(31, 5);
... // code for other actions
listView1.Items[i].Remove();
i--;
}
}
}
It thorws error
ArgumentOutofRangeException was not handled" - Invalid argument value of
'1' is not valid for 'index'
I don't understand what's the problem and why it works only if it' s the
first item.

Tuesday, 20 August 2013

Ng animate in angular js

Ng animate in angular js

I need to show the div with animated effect .
<div class="appdrawer pull-right tab-{{ showDetails }}"
data-ng-click="showDetails = !showDetails; showDetails1 = false;
showDetails2 = false;" >Apps</div>
<section id="workbench-apps" data-ng-class="{ 'hidden': ! showDetails }"
data-ng-animate=" 'animate' ">
<div class="rowfluid">
Apps
<div class="applist" data-ng-repeat="applist in applists">{{
name }}</div>
</div>
</section>
i tried with above code,but not working ,pls suggest a angular way

What values will the WMI Win32_DiskDrive call provide when PC is using hybrid drive?

What values will the WMI Win32_DiskDrive call provide when PC is using
hybrid drive?

When I call the Get-WMIOBject Win32_DiskDrive call I get the following
response for a regular drive: Partitions : 5 DeviceID : \.\PHYSICALDRIVE0
Model : C400-MTFDDAT128MAM Size : 128034708480 Caption :
C400-MTFDDAT128MAM
Anyone can answer what would the response look like for a hybrid drive
with 16gb or similar of cache?
Would it report 2 drives, ignore the 16GB cache or add it to the overall
size?
Thank you

why my perl code can't implement the reverse function?

why my perl code can't implement the reverse function?

Here is my code named reverse.pl
#!usr/bin/perl -w
use 5.016;
use strict;
while(my $line=<>)
{
my @array=();
push (@array,$line);
@array=reverse@array;
say @array;
}
Test file named a.txt
A B C D
E F G H
I J K L
M N O P
Q R S T
My command is perl reverse.pl a.txt
Why it can't implement the reverse function? I want to show the result is:
D C B A
H G F E
and so on.

Is there way to span dependencies across Tests in TestNG?

Is there way to span dependencies across Tests in TestNG?

I'm on TestNG 6.8.5. Is there a way to span either dependsOnGroups or
dependsOnMethods across Tests, rather than just within a single Test?
I have a Suite configured like this with two Tests and a bunch of other
Tests between them:
<suite name="ConfigurationSuite">
<test name="DeviceMgmtTest_Setup" >
<classes>
<class name="com.yay.DeviceMgmtTest">
<methods>
<include name="createDevice" />
<include name="discoverDevice" />
</methods>
</class>
</classes>
</test>
<!-- A whole bunch of other very sequential
and long-running tests go here... -->
<test name="DeviceMgmtTest_TearDown" >
<classes>
<class name="com.yay.DeviceMgmtTest">
<methods>
<include name="deleteDevice" />
</methods>
</class>
</classes>
</test>
</suite>
My test class has methods configured like this:
@Test(groups = { "setup" })
public void createDevice() {
// do something
}
@Test(groups = { "setup" })
public void discoverDevice() {
// do something
}
@Test(groups = { "tearDown" }, dependsOnGroups = { "setup" })
public void deleteDevice() {
// When TestNG reaches this method I get a
// group "setup" does not exist type exception (see below)
}
But when I run the suite, the dependsOnGroups annotation fails with an
error like this:
[ERROR] org.testng.TestNGException:
[ERROR] DependencyMap::Method .... DeviceMgmtTest depends on nonexistent
group "setup"
Maybe I'm not understanding something correctly about how to configure my
Suite (I'm very new to TestNG), but separating these areas of concern out
into separate Tests makes sense to me.
Thanks for any guidance or suggestions!

My POST send not all the information in a string and also change it, how can i send it?

My POST send not all the information in a string and also change it, how
can i send it?

I have being stock a long time in a ajax problem, and after looking a lot
i decide to ask for help.
I'm trying to send a svg vector from a html (taking the tag ) using ajax
to a php for make a file of this vector, name.svg.
The problem is that at the moment when the ajax send the information using
POST, the information is changed and not pass all of it.
How you know the svg vectors have a lot of information that is why I use
POST.
This is my .js script:
function sendVector(url){
ajax=AjaxCaller();
ajax.open("POST", url, true);
ajax.onreadystatechange=function(){
if(ajax.readyState==4){
if(ajax.status==200){
//div.innerHTML = ajax.responseText;
}
}
}
ajax.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
var vector2 = $("#grafico").html();
ajax.send('vector2='+vector2);
}
And this one is the php:
<?php
function escribirArchivo($vector21) {
$file = 'sion.svg';
$current = '<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN"
"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">';
$current .=$vector21;
file_put_contents($file, $current);
}
echo escribirArchivo($_POST['vector2']);
?>
I don't know what i'm doing bad, because i dont have the result i want.
This is the file created.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN"
"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg version=\"1.1\" xmlns=\"http://www.w3.org/2000/svg\"
width=\"1271\" height=\"400\"><desc>Created with Highcharts
3.0.4</desc><defs><clipPath id=\"highcharts-1\"><rect fill=\"none\"
x=\"0\" y=\"0\" width=\"1203\"
height=\"276\"></rect></clipPath><linearGradient x1=\"0\" y1=\"0\"
x2=\"0\" y2=\"1\" id=\"highcharts-4\"><stop offset=\"0\"
stop-color=\"#FFF\" stop-opacity=\"1\"></stop><stop offset=\"1\"
stop-color=\"#ACF\"
stop-opacity=\"1\"></stop></linearGradient></defs><rect rx=\"5\"
ry=\"5\" fill=\"#FFFFFF\" x=\"0\" y=\"0\" width=\"1271\"
height=\"400\"></rect><g class=\"highcharts-button\"
style=\"cursor:default;\" title=\"Chart context menu\"
stroke-linecap=\"round\" transform=\"translate(1237,10)\"><title>Chart
context
menu</title><rect rx=\"2\" ry=\"2\" fill=\"white\"
x=\"0.5\" y=\"0.5\" width=\"24\" height=\"22\"
stroke=\"none\" stroke-width=\"1\"></rect><path
fill=\"#E0E0E0\" d=\"M 6 6.5 L 20 6.5 M 6 11.5 L 20 11.5 M
6 16.5 L 20 16.5\" stroke=\"#666\" stroke-width=\"3\"
zindex=\"1\"></path>
That don't have even the 5% of information, furthermore is add a backslash
before every double quotes.
I had tested the string before send it to the php and I have all the
information that I need, but the problem is in between the send and the
php, and i don't know how make run it.
I hope you can help me :)

Tabular p-column and environment gives strange output

Tabular p-column and environment gives strange output

The code below does produce a clearly too high column. The same effect can
also be seen with other environments (center, ...).

How can I use the p-column and have the correct height at the same time?
Code:
\documentclass{scrreprt}
\usepackage{listings}
\usepackage{colortbl}
\begin{document}
\begin{tabular}{|p{1cm}|p{8cm}|}
\hline
A &%
\begin{lstlisting}
[1.67007,1.99831e-06,0.000413824]
\end{lstlisting} \\
\hline
\end{tabular}
\begin{tabular}{|p{1cm}|l|}
\hline
A &%
\begin{lstlisting}
[1.67007,1.99831e-06,0.000413824]
\end{lstlisting} \\
\hline
\end{tabular}
\end{document}

How to get javascript variable to php

How to get javascript variable to php

i am trying to get the javascript variable value to php.
here is my javascript code:
function getResults()
{
var radios = document.getElementsByName("address");
for (var i = 0; i < radios.length; i++)
{
if (radios[i].checked) {
var a = radios[i].value
alert(a);
break;
}
}
}
from this javascript i want to get variable a's value inside php code
onclick on submit button. how can i do this?
i tried this
$var1 = $_GET["a"];

Monday, 19 August 2013

Update of app shown in iPhone but not in iPad?

Update of app shown in iPhone but not in iPad?

I have a first version of my app in app store.Recently I released the next
version with some bug fixes. Once apple approves the next version of my
app, the update shown in "App Store app" in my iPhone but it doesn't in my
iPad. IS it a problem while I submitted my app in store or problem in
apples's "App Store" app.Please suggest your ideas.
NOTE:
I have a single binary file for both iPhone and iPad.
Also I had the first version of the app in my both devices before I found
this bug.
Thanks in advance.

Linux Mint 15 dpkg: unrecoverable fatal error, aborting: files list file for package 'virtualbox-4.2' is missing final newline

Linux Mint 15 dpkg: unrecoverable fatal error, aborting: files list file
for package 'virtualbox-4.2' is missing final newline

Linux Mint 15 x64 - Mate
I tried installing the google-talk-plugin_4.4.2.0-1_amd64.deb package, but
I receive this error in the package installer and from the terminal
dpkg: unrecoverable fatal error, aborting: files list file for package
'virtualbox-4.2' is missing final newline
How do I get past this error to install the google-talk plugin?

What is the frequency threshold for google cloud messaging throttling

What is the frequency threshold for google cloud messaging throttling

As https://developer.android.com/google/gcm/adv.html#throttling indicates ,
Blockquote and to optimize for the overall network efficiency and battery
life of devices, GCM implements throttling of messages using a token
bucket scheme. Messages are throttled on a per application and per
collapse key basis (including non-collapsible messages). Each application
collapse key is granted some initial tokens, and new tokens are granted
periodically therefter. Each token is valid for a single message sent to
the device. If an application collapse key exhausts its supply of
available tokens, new messages are buffered in a pending queue until new
tokens become available at the time of the periodic grant.
Is there any exact threshold or related data implying a proper sending
frequency?

How to tail all the log files inside a folder and subfolders?

How to tail all the log files inside a folder and subfolders?

In Linux, using the command tailf, how can I tail several log files that
are inside a folder and in the subfolders?

Using LINQ with conditions

Using LINQ with conditions

Given a class
public class data
{
public string x;
public double y;
}
List<data> myList = new List<data>();
The list is then populated with data either with string "odd", string
"even" with the respective number.
how would I get the sum of all the x = "odd" using linq
This is will be basic to most, please pardon my ignorance...

.tmx file saved in uncompressed fromat to comressed format

.tmx file saved in uncompressed fromat to comressed format

I have created .tmx file from tile editor. it is saved in uncomressed
format. but now i wnat it in zlib compressed format.
i used Edit > Preferences but after changing it to comressed format , it
is not reflecting any changes.
Thanks

Sunday, 18 August 2013

ios write to disk on background thread

ios write to disk on background thread

I am currently writing some files to disk in the background thread just by
calling
dispatch_async(my_queue,^{
[self writeToRoot:filename data:data];
};
- (BOOL)writeToRoot:(NSString *)path data:(NSData *)content
{
NSString *fullPath = [[self rootPath]
stringByAppendingPathComponent:path];
NSString *pathWithoutFile = [fullPath stringByDeletingLastPathComponent];
BOOL directoryExists = [[NSFileManager defaultManager]
fileExistsAtPath:pathWithoutFile];
if (!directoryExists) {
NSError *error = nil;
[[NSFileManager defaultManager] createDirectoryAtPath:pathWithoutFile
withIntermediateDirectories:YES
attributes:nil
error:&error];
NSParameterAssert(error == nil);
}
return [content writeToFile:fullPath atomically:NO];
}
I am doing this so as it would not block the main thread. My question is
how to ensure thread safety. while this background operation is being
carried out, what happens when I try to read from disk the file by
calling:
[NSData dataWithContentsOfFile:fullPath];
Will be content be corrupted? OR will the write operation lock the file
and the read operation will wait until the writing is completed?

jQuery event scrollTop

jQuery event scrollTop

#mydiv is a clickable box Div,a class .openDiv will be added if click on
#mydiv.
if has class .openDiv
if($('#mydiv').hasClass('openDiv')){
$(window).scrollTop(); //value is 300px
}
if just the page loaded (no .openDiv )
$(window).scrollTop(); //value is 200px
so my variable is like
if($('#mydiv').hasClass('openDiv')){
thisTop = $(window).scrollTop() - 100;
}else{
thisTop = $(window).scrollTop()
}
as you can see I made it 100 difference value hard coded. Is there a way
to make it to calculate dynamically? Thanks!

Roman pagenumbering + \usepackage[greek]{babel}

Roman pagenumbering + \usepackage[greek]{babel}

I have the problem that the roman or Roman pagenumbering does not work if
babel is used with greek option. Does not work means, that the pages
itself have correct numbers but the table of contents will show only the
number the toc is on. Any suggestions what might help?
In case you want to proof yourself:
\documentclass[listof=totoc]{scrreprt}
\usepackage[utf8]{inputenc}
\usepackage[greek, ngerman, english]{babel}
\usepackage{blindtext}
\begin{document}
\pagenumbering{Roman}
\addchap[Preface]{Preface}
\blindtext
\addchap[Thank You]{Thank You}
\blindtext
\tableofcontents
\listoffigures
\listoftables
\cleardoublepage
\pagenumbering{arabic}
\chapter{Test}
\blindtext
\end{document}

Encryption of Time Machine backup went wrong

Encryption of Time Machine backup went wrong

I use an (Mac OS - journaled formatted) external Lacie harddrive to back
up my Macbook Air via Time Machine (The external harddrive also contain
other data besides my backups). The OS is Mountain Lion, and I have chosen
to encrypt my backups in the settings from the Time Machine preferences.
The backup initiates automatically when the two devices are connected, and
I had to interrupt it because I needed to leave, along with the Mac. I did
so, by cancelling the backup, waiting a couple of seconds, but seeing as
the backup symbol kept spinning, I pulled the cable and hurried of with
the machine. Now the external harddrive will not activate when connected.
It's visible in Disk Utility, but cannot be activated. When you unplug the
cable (thereby disconnecting the external harddrive) it suddenly asks for
the password to the external drive. I gather that something went wrong
during the cancelling of the backup, where it was encrypting. Can I
somehow lift this encryption-gone-wild and get access to my data again?
Thank you very much

Adding numbers to comments in wordpress

Adding numbers to comments in wordpress

I've seen various sites using the built in wordpress comment system with a
custom callback (to generate their own html different than that if the
built in comments in wordpress) adding numbers to comments on their site.
Ala -
http://mobile.smashingmagazine.com/2013/08/12/creating-high-performance-mobile-websites/
Each comment has a number beside it. After doing a whole lot of searching
I can't find any built in function of wordpress that does this.
I'm using a custom calllback for my comments.
function mytheme_comment($comment, $args, $depth) {
$GLOBALS['comment'] = $comment;
extract($args, EXTR_SKIP);
if ( 'div' == $args['style'] ) {
$tag = 'div';
$add_below = 'comment';
} else {
$tag = 'li';
$add_below = 'div-comment';
}
?>
<<?php echo $tag ?> <?php comment_class(empty(
$args['has_children'] ) ? '' : 'parent') ?> id="comment-<?php
comment_ID() ?>">
<?php if ( 'div' != $args['style'] ) : ?>
<div id="div-comment-<?php comment_ID() ?>" class="comment-body">
<?php endif; ?>
<div class="comment-author vcard">
<div class="rounded">
<?php if ($args['avatar_size'] != 0) echo
get_avatar( $comment, $args['avatar_size'] ); ?>
</div> <!-- end div rounded -->
</div> <!-- end div vcard -->
<div class="comment-meta commentmetadata">
<?php printf(__('<cite class="fn">%s</cite> <span
class="says"></span>'), get_comment_author_link()) ?>
<a href="<?php echo htmlspecialchars(
get_comment_link( $comment->comment_ID ) ) ?>">
<?php
printf( __('%1$s at %2$s'), comment_time('F j,
Y g:i a')) ?></a><?php
edit_comment_link(__('(Edit)'),' ','' );
?>
</a>
<?php if ($comment->comment_approved == '0') : ?>
<em class="comment-awaiting-moderation">
<?php _e('Your comment is awaiting
moderation.') ?>
</em>
<br />
<?php endif; ?>
</div> <!-- end div commentmetadata -->
<div class="commentsholder">
<?php comment_text() ?>
</div> <!-- end div commentsholder -->
<div class="reply">
<?php comment_reply_link(array_merge( $args,
array('add_below' => $add_below, 'depth' => $depth,
'max_depth' => $args['max_depth']))) ?>
</div> <!-- end div reply -->
<?php echo '<div style="clear:both"></div>' ?>
<?php if ( 'div' != $args['style'] ) : ?>
</div> <!-- end div commentid -->
<?php endif; ?>
<?php
}
Can anyone give me any idea how to number each comment?

Sed replace error

Sed replace error

I have a pattern I am trying to match:
<x>anything</x>
I am trying to replace 'anything' (which can be any text, not the text
anything - (.*)) with 'something' so any occurrences would become:
<x>something</x>
I am trying to use the following sed command:
sed "s/<x>.*</x>/<x>something</x>/g" file
I am getting the following error:
sed: -e expression #1, char 19: unknown option to `s'
Can someone point me in the right direction?

Saturday, 17 August 2013

Mechanize Problems Connecting to HTTP Proxy...Ruby

Mechanize Problems Connecting to HTTP Proxy...Ruby

I have a proxy set up and running completely fine on my local host. I can
connect to the proxy completely fine running this code.
Net::HTTP::Proxy('http://localhost', 1234).start #do whatever I want
after this point
I can connect to it through a browser completely fine, however when I go
to run it on mechanize it completely fails. Here's the code.
require 'mechanize'
agent=Mechanize.new
agent.set_proxy('localhost', 1234)
agent.get('http://google.com') #or any website for that matter
Here's the error I get back
Net::HTTP::Persistent::Error: too many connection resets (due to end of
file reached - EOFError) after 0 requests on 22249020, last used
1376802493.5352573 seconds ago
I've read that the versions after 1.0.0 have difficulties connecting to
http proxies, but I need to and I'm currently running version 2.7.2. Is
there anything I can do to connect to a proxy.

THREEx.CelShader.js and/or ShaderToon.js, where do I start? (three.js)

THREEx.CelShader.js and/or ShaderToon.js, where do I start? (three.js)

I've come across mrdoobs examples, and wanted to try the toon-expressions
from one of the demos
(http://threejs.org/examples/webgl_marching_cubes.html) but I really don't
get how it works as there's too much of everything else in that code. I've
seen similar examples at
http://learningthreejs.com/data/THREEx/docs/THREEx.CelShader.html.
I've been searching for guides and tutorials for implementing shaders, and
read all similar questions and answers but I still don't get it! How hard
can it be!? Pretty hard I guess.
Could anyone give a helping hand to a slow brain?

how to use internet(private) function in NDK

how to use internet(private) function in NDK

how to create and user internal function in ndk cpp ?
jstring Java_com_test_ndk_MainActivity_getString(JNIEnv* env, jobject thiz)
{
jstring strt = getstr();
return env->NewStringUTF(strt);
}
want to implement getstr() function over here for just use in ndk side not
java... (like on private in ndk side)

Json Unmarshal reflect.Type

Json Unmarshal reflect.Type

Here is the code:
package main
import (
"fmt"
"encoding/json"
"reflect"
)
var(
datajson []byte
)
type User struct {
Name string
Type reflect.Type
}
func MustJSONEncode(i interface{}) []byte {
result, err := json.Marshal(i)
if err != nil {
panic(err)
}
return result
}
func MustJSONDecode(b []byte, i interface{}) {
err := json.Unmarshal(b, i)
if err != nil {
panic(err)
}
}
func Store(a interface{}) {
datajson = MustJSONEncode(a)
fmt.Println(datajson)
}
func Get(a []byte, b interface{}) {
MustJSONDecode(a, b)
fmt.Println(b)
}
func main() {
dummy := &User{}
david := &User{Name: "DavidMahon"}
typ := reflect.TypeOf(david)
david.Type = typ
Store(david)
Get(datajson, dummy)
}
I can successfully marshal reflect.Type but when I do the reverse, it
panics. I know reflect.Type is an interface. So what am I doing wrong
here? How can I store a reflect.Type value in json and then retrieve back
safely?

I have this DriverPack Solutions, I know this a Driver Installer, but is this a foolproof kind of software?

I have this DriverPack Solutions, I know this a Driver Installer, but is
this a foolproof kind of software?

I have this DriverPack Solutions, I know this is a Driver Installer, but
is this a foolproof kind of software, which means there's no way I can go
wrong? Thanks..

How to dynamically populate pick list right side values

How to dynamically populate pick list right side values

I am using rich:popuppanel component and having issues with populating
values in picklist.
My requirement is as below.
Populate extended data table
Select a row using check box - User ID in that row will be passed to
backing bean
Click assign button
Popup panel should open with a picklist containing all users and assigned
users
The issue is, getAllUsers() call returns all users and left side of
picklist is populated properly. But getAssignedUsers() is not called at
all. So right side of pick list always empty.
XHTML code is as below.
<h:form id="audit">
...
<h:commandButton id="Assign" value="Assign"
immediate="true" action="#{userBean.getSelectedUsers}">
<f:ajax execute="@this" render="popupScript" />
</h:commandButton>
<h:panelGroup id="popupScript">
<h:outputScript rendered="#{userBean.assignClicked}">
#{rich:component('assignUser')}.show();
</h:outputScript>
</h:panelGroup>
...
</h:form>
<rich:popupPanel id="assignUser" autosized="true" resizeable="false">
<f:facet name="header">
<h:outputText value="#{msg.assignPopupHeader}">
</h:outputText>
</f:facet>
<h:form name="assign" id="assign">
<h:panelGrid cellspacing="5" id="popupGrid">
<a4j:outputPanel id="a4jPanel">
<rich:pickList value="#{userBean.assignedUsers}"
showButtonsLabel="false"
sourceCaption="Available Users"
align="center"
targetCaption="Assigned Users"
listWidth="165px"
listHeight="100px" orderable="true"
addText="&gt;" removeText="&lt;">
<f:selectItems
value="#{userBean.allUsers}" />
</rich:pickList>
</a4j:outputPanel>
<center>
<h:panelGrid columns="2" cellspacing="3"
cellpadding="4">
<a4j:commandButton id="assign"
value="#{msg.userAssign}"
action="#{userBean.assignUser}"/>
<h:commandButton
value="#{msg.userCancel}"
onclick="#{rich:component('assignUser')}.hide();return
false">
</h:commandButton>
</h:panelGrid>
</center>
</h:form>
</rich:popupPanel>
My understanding is the issue is due to bean scope. My bean is view
scoped, so the data in both left and right side panels are pre-populated
when bean is initialized.
@PostConstruct
public void init() {
setAllUsers(userService.getAllUsers());
setAssignedUsers(userService.getAllAssignedUsers(userBean.getSelectedIdforAssign()));
}
I tried calling setAssignedUsers() with hardcoded id in init() itself. It
works fine. What I need is a way to dynamically pass the ID and call
getAssignedUsers().
Please suggest how to perform this and how to reRender the picklist when
popup is opened.
Thanks!

Rename the folder of document directory

Rename the folder of document directory

This could be easy, but I am not getting the problem.
I am using below code to rename the folders of document directory and is
working fine except one case.

NSArray *paths =
NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0]; // Get
documents folder
NSString *dataPath = [documentsDirectory
stringByAppendingPathComponent:@"Photos"];
NSArray * arrAllItems = [[NSFileManager defaultManager]
contentsOfDirectoryAtPath:dataPath error:NULL]; // List of all items
NSString *filePath = [dataPath
stringByAppendingPathComponent:[NSString stringWithFormat:@"%@",
[arrAllItems objectAtIndex:tagSelected]]];
NSString *newDirectoryName = txtAlbumName.text; // Name entered by user
NSString *oldPath = filePath;
NSString *newPath = [[oldPath stringByDeletingLastPathComponent]
stringByAppendingPathComponent:newDirectoryName];
NSError *error = nil;
[[NSFileManager defaultManager] moveItemAtPath:oldPath toPath:newPath
error:&error];
if (error) {
NSLog(@"%@",error.localizedDescription);
// handle error
}

Now, my problem is if there is a folder named "A"(capital letter A) and I
am renaming it to "a" (small letter a), then it is not working and giving
an error.
I am not getting where the problem is.

Friday, 16 August 2013

Game Centre Apple ID help

Game Centre Apple ID help

I just bought a new iPod touch and I want to give my old iPod touch to my
child. He uses the same games that I do which I am logged into in the game
Centre. Is there any way that I can keep the progress in the games that he
has on his iPod now and for it not to affect the progress of my games on
my new iPod. Or is it just best to give him his own Apple ID and he can
start his progress or over again

Saturday, 10 August 2013

How to force logout of Kubuntu local desktop user

How to force logout of Kubuntu local desktop user

As the admin user on Kubuntu 12.04.2 LTS how can I force a 2nd or 3rd
local desktop user tty session to shutdown without having to switch user
and logging in or without killing individual processes?

List error: App crushes, No idea why

List error: App crushes, No idea why

I've built some class named "item", here is it: (thats the whole code)
public class item {
private int id;
private String title;
private String desc;
private double lat;
private double lon;
private String pub;
private int p;
private int n;
public item(int id, String title, String desc, double lat, double lon,
String pub, int p, int n) {
super();
this.id = id;
this.title = title;
this.desc = desc;
this.lat = lat;
this.lon = lon;
this.pub = pub;
this.p = p;
this.n = n;
}
Now I have to make a List<item> and add() "item"s to it, but for some
reason my application crushes.
Thats the Activity:
public class MainActivity extends Activity {
List<item> markers;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
item a = new item(1, "lol", "sdfs", 32.45345, 34.54353, "nir", 0, 0);
markers.add(a);
}
Appreciate your help guys!

form exact $\Leftrightarrow$ pull-back exact

form exact $\Leftrightarrow$ pull-back exact

Is the form exact $\Leftrightarrow$ pull-back exact? Since $$f^*\omega =
\omega \circ df,$$ which seems irrelavant. Because the composition with
$df$ does not change $\omega$ is exact or not.
The definition I was trying to use:
Suppose $A: V \to W$ is a linear map. Then the transpose map $A^*: W^* \to
V^*$ extends to the exterior algebras, $A^*: \Lambda^p(W^*) \to
\Lambda^p(V^*)$ for all $p>0$. If $T \in \Lambda^p(W^*)$, just define $A^*
T \in \Lambda^p(V^*)$ by $$A^*T(v_1, \dots, v_p) = T(Av_1, \dots, Av_p)$$
for all vectors $v_1, \dots, v_p \in V$. (Page 159)

Friday, 9 August 2013

Java - what is a a prototype?

Java - what is a a prototype?

In a lecture on Java, a computer science professor states that Java
interfaces of a class are prototypes for public methods, plus descriptions
of their behaviors.

(Source https://www.youtube.com/watch?v=-c4I3gFYe3w @8:47)
And at 8:13 in the video he says go to discussion section with teaching
assistants to learn what he means by prototype.
What does "prototype" mean in Java in the above context?

JavaFX Clients and JDBC Servers: Are JavaFX Bean-style objects required on the server side?

JavaFX Clients and JDBC Servers: Are JavaFX Bean-style objects required on
the server side?

I have a JDBC application that is built around a single-server database
(the RDBMS is HSQLDB -- which I love so far). In my first draft of the
application, I have used the following tiered approach:
+-------------------------------+
| DATA STORE (appx 20 tables) | HSQLDB; highly normalized tables
+-------------------------------+
|
v
+-------------------------------+
| DOMAIN OBJECT LAYER (1:1) | A Java class for each table in DB
+-------------------------------+
|
v
+-------------------------------+ Abstraction for the objects that the app
| CLIENT OBJECT LAYER / DAO's | logic actually uses (denormalized)
+-------------------------------+
|
V
+-------------------------------+ Adapts ObservableArrayList() instances
| PRESENTATION LAYER (JAVAFX) | of objects to the GUI
+-------------------------------+
In the Domain Object Layer I presently do all JDBC queries with a generic
static method:
static <E> ObservableList<E> doGenericQuery(SQLParametersList pars,
String sql, Callback<RowSet,E> factory) {
// factory is a Function Object. For now I use Callback<P,R> as the
// "strategy" ... P is a RowSet, R is the object return type. The factory
// simply invokes the constructor for the desired return object type.
RowSet jrs = null;
ObservableList<E> queryList = FXCollections.<E>observableArrayList();
try {
jrs = SQLConnection.getRowSetInstance();
if (jrs == null) {
System.err.println(Census.MSG_ERR_JDBCFAIL);
return queryList; }
jrs.setCommand(sql);
for(int i=0; i < pars.size(); i++) {
// datum().col() method returns an enum representing the
// database column; setJdbcParamByType is an enum
// constant-specific method that invokes the correct
// setXXX method on the PreparedStatement
pars.datum(i).col().setJdbcParamByType(jrs, pars.datum(i)));
}
jrs.execute();
while (jrs.next()) {
queryList.add(factory.<RowSet,E>call(jrs));
}
} catch (SQLException e) {
Logger.getLogger(DB.class.getName()).log(Level.SEVERE, null, e);
} finally {
if (jrs != null) try { jrs.close(); } catch (SQLException e) { }
}
return queryList;
}
What I would like to do is use this method in the data access abstraction
for my whole application, but I'm wondering if I can. As written, this
method returns an ObservableList because it is used by a JavaFX
application. The ObservableList holds instances of SimpleXXXProperty
objects (JavaFX Bean-style, i.e. mutable, objects). I don't think I can
use this code as presently written because I don't want to take JavaFX
Bean-style objects to the server-side.
Eventually, the data access layers are going to be executed in a
server-side environment and the presentation-layer stuff is going to
happen on the client.
I really don't want to have my server-side code using JavaFX Bean-style
objects. Ideally, I want the queries to form a list of immutable objects
and I think I could accomplish that except for the necessity to deal with
JavaFX which seems to mandate that I make everything public and mutable.
The solution that I am thinking of now is to have the server code create
immutable objects from the query result that get wrapped in an
unmodifiableList which then gets transmitted to the client. The client
then has to transmogrify the read-only list into an ObservableList of
JavaFX Bean-style objects so that they may be used in the GUI. BUT .. this
approach requires that I write different version of my Domain Object Layer
(client and server).
Am I on the right track here?