Saturday 31 August 2013

Android - after loading URL with webview can i change background color

Android - after loading URL with webview can i change background color

I have a webview and im loading an external HTML form a site. I try to
change the background color using javascript function:
function changeBGC(color){
document.bgColor = color;
}
and that does not work. but if i load locally then im able to change the
background color. Is there some kind of security inhibiting me from
changing a web page i load into the webview externally ?

Opening Image directly into program

Opening Image directly into program

I made a basic picture viewer program in C# windows from , following a
tutorial. The program works fine but I want to open it like default
windows photo viewer. I tried to open an image with the program directly
but that opened the program and the image box was empty.
The image box works fine when images are browsed to open inside the
program but how to make it work externally?
Extra : And is there a way to make it full screen?
Sorry for bad english.

button click in polymer dart does not work; needs polymer-element

button click in polymer dart does not work; needs polymer-element

I am creating my first polymer application/example and a simple button
on-click is not working. The method is not called. I would like to use a
simple button without creating a new polymer-element (the commented code).
If I use the buttons in the polymer-element, they work just fine.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Button</title>
<link rel="stylesheet" href="button.css">
<script src="packages/polymer/boot.js"></script>
</head>
<body>
<h1>Button</h1>
<template id="tmpl" bind>
<button on-click="myMethod">Click me!</button><!! DOES NOT WORK!!! -->
</template>
<!--
<polymer-element name="my-element" extends="div">
<template>
<p>
<button on-click="myMethod">Show Message</button>
<button on-click="myMethod">Hide Message</button>
</p>
</template>
</polymer-element>
<my-element id="test"></my-element>-->
<script type="application/dart" src="button.dart"></script>
</body>
</html>
..
import 'dart:html';
import 'package:polymer/polymer.dart';
void main() {
query("#tmpl").model = new MyClass();
}
@CustomTag('my-element')
class MyClass extends PolymerElement with ObservableMixin{
@observable String name="testname";
void myMethod(var e, var detail, var target) {
print("button works");
}
}

Sqlite read/write permission in the program files

Sqlite read/write permission in the program files

My java log in app uses sqlite database.It creates database if not present
and tables as well.But when I package it as a jar file by using installer
software,it is not able to create any database when it is extracted to the
'C:/Program Files...' by default.So I want to know how to give the
read/write permission for this purpose in the program files?

JSON post to Spring Controller

JSON post to Spring Controller

Hi I am starting with Web Services in Spring, so I am trying to develop
small application in Spring + JSON + Hibernate. I have some problem with
HTTP-POST. I created a method:
@RequestMapping(value="/workers/addNewWorker", method =
RequestMethod.POST, produces = "application/json", consumes =
"application/json")
@ResponseBody
public String addNewWorker(@RequestBody Test test) throws Exception {
String name = test.name;
return name;
}
And my model Test looks like:
public class Test implements Serializable {
private static final long serialVersionUID = -1764970284520387975L;
public String name;
public Test() {
}
}
By POSTMAN I am sending simply JSON {"name":"testName"} and I always get
error;
The server refused this request because the request entity is in a format
not supported by the requested resource for the requested method.
I imported Jackson library. My GET methods works fine. I don't know what
I'm doing wrong. I am grateful for any suggestions.

Where I can know more detail info about how Android build apps

Where I can know more detail info about how Android build apps

Recently I found that when I create a release build, sometimes a function
will be "inlined", which means that the function disappears, and all the
code in that function are put in the same place, just like the inline
function in C++.
So I want to know more detail info about how an apk is generated, such as
what kind of function will be considered as inline, whether no function
will be inlined in debug build, how to change the build option in
build.xml, etc.
Thanks a lot.

i want to now about mapreduce in mongodb codeigniter

i want to now about mapreduce in mongodb codeigniter

here am basically performing group by operation
table:sale_announcement_history fields:history_timestamp,logged by,
sale_annoucement_id --- want to know max timestamp and distinct logged by
of a particular sale_id
function test_map_reduce(){
$map = new MongoCode('
function(){
var total = 0;
var maxx = 0;
var unique = 0;
for (sum in this.sale_announcement_id) {
$total += this.sale_announcement_id[sum];
}
for (max in this.history_timestamp) {
maxx = this.history_timestamp[max];
}
for (distinct in this.logged_by) {
unique = this.logged_by[distinct];
}
emit(this.sale_announcement_id,{total:total,max:maxx,unique:unique});
}
');
$reduce = new MongoCode('
function(key, values){
var result = {total: 0, max: 0, unique: 0};
values.forEach(function(v) {
result.total = v.total;
result.max = v.max;
result.unique = v.unique;
});
return result;
}
');
$result = $this->mongo_db->command(array(
'mapreduce'=>"sale_announcement_history", // <= 'mtb'
'road' 'minivelo'
'map'=>$map,
'reduce'=>$reduce,
//'query'=>array(),
'out'=> 'test_res1'));
echo'<pre>';
print_r($result);
}

Facebook Payment error code 1353009

Facebook Payment error code 1353009

We are receiving from our users lots feedbacks about failed payments. In
result we investigated that they get:
{
"error_code": 1353009,
"error_message": "User is from a trade restricted country"
}
But there are no restrictions in the settings of our application. I have
never found any information about this problem, maybe someone faced with
it?
Thank you for help!

Friday 30 August 2013

How can fragment pass data to calling fragment

How can fragment pass data to calling fragment

I have an activity with two fragments say F1 and F2. On clicking the list
view of F2 , a new fragment is called say F3 (Its single activity multi
fragments design). I have back button on right side of dual pane layout.
On hitting this button i need to pass data from fragment F3 to F2, so that
F2 views are updated based on data received(something like
onActivityForResult for activity to activity interaction). How can i
achieve this?

Thursday 29 August 2013

Making a complaint button iOS

Making a complaint button iOS

Im trying make a button/action that the user can press that will report if
there is an inappropriate picture,spam, etc. I want to make a report
button similar to Instagram. Im currently using parse.com as for my
servers. If possible I would want an alert sent my email. Does anyone know
of any ideas?

JAXB or SAX parsing

JAXB or SAX parsing

some one have any solution for this?
I am trying to parse the following XML to read the values using Java
beans. it doesnt matter which parsing technique it is.
XML Here:
<DocumentInfo>
<Document>
<class> xyz</class>
<uid> xyz</uid>
<Pass>
xyz
</pass>
<credit />
<DocClass>xyz </DocClass>
<Properties>
<Property>
<Name>name</Name>
<Value>value</Value>
</Property>
<Property>
<Name>name</Name>
<Value>value</Value>
</Property>
<Property>
<Name>name</Name>
<Value>value</Value>
</Property>
</Properties>
<Content>
<Data>abc</Data>
<Type>txt</Type>
</Content>
</Document>
</DocumentInfo>
Thanks in advance.

Display message alert for Session expired

Display message alert for Session expired

How to show alert message when session.timeout occurs? after 5 minutes i
want to expire my page and redirect to login page. after redirecting i
want to show user that their session has expired.

Wednesday 28 August 2013

Avoid generating random integer in different functions

Avoid generating random integer in different functions

My function:
public int[] generateRandomInteger(){
int[] arr = new int[100];
Random randomGenerator = new Random();
for (int i = 0; i < 100; i++){
int randomInt = randomGenerator.nextInt(16) + 10;
arr[i] = randomInt;
}
return arr;
}
The problem is: when I use arr in another function, it will generate a
different array of 100 integer numbers. How can I avoid this problem ? I
only want to use exactly the array that generate from the function above.
Any help would be appriciated !

Remove extensions from ListBox

Remove extensions from ListBox

I have a piece of code that searches for shortcuts and puts them into a
listbox. How ca I modify it in order to display the information without
the .lnk extension
For Each foundFile As String In
My.Computer.FileSystem.GetFiles("Z:\SiteServices\Maintenance\Maintenance
Support Folder\Equipment Specific Information\DES",
Microsoft.VisualBasic.FileIO.SearchOption.SearchTopLevelOnly, "*" &
txtSearch.Text & "*" & ".lnk")
ListBox1.Items.Add(foundFile)
Next

Tuesday 27 August 2013

How to Authorize SignalR Hub Connection using Cookie?

How to Authorize SignalR Hub Connection using Cookie?

I am very new to SignalR and I am trying to authorize connections to the
SignalR Hub using Cookie.
Below is the code for my Hub Class;
[Authorize]
public class MyHub : Hub
{
....
}
and I've below code in the Application_Start
RouteTable.Routes.MapHubs();
GlobalHost.HubPipeline.RequireAuthentication();
Where am I supposed to do the Authorization process? Is there any specific
event for this? Or AuthorizeRequest method which I can override?

HTML5 textbox/textarea clickable text

HTML5 textbox/textarea clickable text

Good Day,
Can I know if it is possible/there exists a UIkit that allows certain text
say those with # to be clickable?
For example:
text# hello world inside a text area, populated by some php get script. I
want #text# to be clickable and that should perform some action.

How to delete all nagios availability history data?

How to delete all nagios availability history data?

After play a little with nagios tuning some variables etc. I want go to
production and clear all the so far collected availability data, so my
nagios history begin today. How can I do that?

What is causing the compile error: Illegal NSTableView data source?

What is causing the compile error: Illegal NSTableView data source?

After some 'cleaning' of a working app, the main window appears as
designed in the MainWindow.xib.
I deleted a MainWindowViewController object in IB. (was beneath Font Manager)
It has it's Custom class set to MainWindowViewController
The two required methods ARE still included in that implementation file.
Table view connection has been made to File's Owner
What am I missing? What should I check to resolve?
Image included to help visualize.

How do i remove http://www in form?

How do i remove http://www in form?

I want to remove

https://www<br>
http://www <br>
https://<br>
http://<br>
in form like this:
<form class="well" action="process.php">
<input type="text" name="q" placeholder="{$lang.placeholder}"
x-webkit-speech>
<select name="t">
<option value="domain">{$lang.domain}</option>
<option value="ip">{$lang.ip}</option>
<option value="nameserver">{$lang.nameserver}</option>
</select>
<button type="submit" class="btn"><i class="icon"></i>
{$lang.button}</button>
do you guys have a tip!?

Can we have two or more website hosted on a computer with IIS

Can we have two or more website hosted on a computer with IIS

I have an Virtual machine which has R2 2008 with an website which just
works fine. I wondering if there's any way we could host multiple websites
on that server. Since its virtual we can add couple nic's if we like so
more IP's.
Any ideas how else we could achieve this ?
Thanks for replying and reading the question....

I want to pass a value from TextBox to CkEditor for jQuery using Asp.net

I want to pass a value from TextBox to CkEditor for jQuery using Asp.net

Data function GetContents() { var oEditor = CKEDITOR.instances.editor1;
document.getElementById('<%=Hidden1.ClientID%>').value =
oEditor.getData(); }
here i passed value from ckEditor to asp.net control Hidden Field in the
similar way i want do viceverse from textbox to Ckeditor

Monday 26 August 2013

What really happened when the ship was flying from point A to point B?

What really happened when the ship was flying from point A to point B?

For this text:
, even as the darkness of space focused and narrowed ¨C became the shadow
of wings, the curve on vast surfaces ¨C the hulls of two huge ships
flanking them; thin, sharp, like a stretch of endless walls
Could you tell me that can I understand the above text in this way?(I
meant to find a picture of this ship named "The Two Sisters in Exile", but
nothing , so I drew a picture, at first , I thought it's hard to draw it,
but after I drew it , I understand what I drew, and I think you can
understand it basically - because my picture will help me ask this
question . and I hope you know as you look at the picture, you look at
these ships from above):
,even as when the ship named "The Tortoise in the Lake" was flying from
point A to point B(as I drew in the picture), it was getting closer and
closer to the dark space( space of darkness ) , and the dark space became
more and more narrow, and the darkness of space became more and more
focused - the darkness of space was caused by the shadow of wings(point E
, duplicating with point W and point F) and the shadow of the curve on
vast surfaces(Point S) ¨C because the hulls of two huge ships flanking
them(Point F,);and where the two huge ships flanking them is like a
stretch of endless walls(point W) ; and the walls(point W) is thin and
shap.
And here's my picture£¨not enough reputation to post images£©:
http://i.stack.imgur.com/906DU.jpg
I just have a thing about perfectionism more or less, so I just try hard
to understand what it means---for Im not so sure what the " focused " and
" flanking" means , then not sure what the whole sentence means.
Thank you in advance!
The context is :
"I see nothing," Dong Huong said, again. The ground rumbled beneath her,
even as her ears popped with pressure ¨Cmore laughter from The Tortoise in
the Lake, even as the darkness of space focused and narrowed ¨C became the
shadow of wings, the curve on vast surfaces ¨C the hulls of two huge ships
flanking them; thin, sharp, like a stretch of endless walls ¨C making The
Tortoise in the Lake seem small and insignificant, just as much as Dong
Huong herself was small and insignificant in comparison to her own ship.



Excerpted from Aliette de Bodard's novel "The Two Sisters in Exile"
partly(maybe you needn't read these words) :
Outside, everything was dark. There was only the shadow of The Two Sisters
in Exile, the dead ship that they'd been pulling since Longevity Station.
It hung in space, forlorn and pathetic, like the corpse of an old woman;
although Dong Huong knew that it was huge, and could have housed her
entire lineage without a care.
"I see nothing," Dong Huong said, again. The ground rumbled beneath her,
even as her ears popped with pressure ¨Cmore laughter from The Tortoise in
the Lake, even as the darkness of space focused and narrowed ¨C became the
shadow of wings, the curve on vast surfaces ¨C the hulls of two huge ships
flanking them; thin, sharp, like a stretch of endless walls ¨C making The
Tortoise in the Lake seem small and insignificant, just as much as Dong
Huong herself was small and insignificant in comparison to her own ship.
A voice echoed in the ship's vast rooms, harsh and strong, tinged with the
Northerners' dialect, but still as melodious as declaimed poetry.

How do I prevent more than 2 numbers after a decimal point in UITextField?

How do I prevent more than 2 numbers after a decimal point in UITextField?

Right Now I am making an app where the user is required to input a
currency value, decimal point optional, into a UITextField. My problem
comes up when I try to prevent more than 2 numbers after a given decimal
point while at the same time preventing more than one decimal point. I
have researched around the web and couldn't find an exact answer. I have
found that I will most probably need to use the
shouldChangeCharactersInRange, but I'm not sure how to use it exactly...
Thanks, Virindh Borra

In Netty can you read a ChannelBuffer twice in 3.x?

In Netty can you read a ChannelBuffer twice in 3.x?

Can you re-read a ChannelBuffer in Netty 3.x ? Meaning, can you create two
separate ChannelBufferInputStreams using the same ChannelBuffer object and
read with no additional marking/resetting necessary? Are you always
guaranteed this will work, or only if backed by a certain type of source?

How to Show Total Row Count of a Radgrid in the Header of a RadTabStrip

How to Show Total Row Count of a Radgrid in the Header of a RadTabStrip

I have an ASP.NET project in C# that uses a sqlDataSource. The project
consists of a Telerik Radgrid, which sits on a RadTabStrip. I would like
to know how I can possibly add the total row count of that grid into the
Header Tab like seen in the link attached.
http://pippintothetop.com/example.jpg

How to position a modal relative to clicked action in ember.js

How to position a modal relative to clicked action in ember.js

I have a emberjs application where a person can:
click a link modal pops up change something click away modal save changes
I created the modal much like described here, with events on a route. I
can parse ember object into the route but I cannot seem to get the clicked
DOM element. I want to get the clicked DOM element because I need its
position. I want to position a popup relative to the clicked DOM element.
my action in .hbs file looks like:
<a {{action open option}} class='choose-template'>Choose Template</a>
and this action is handled by a route
events: {
open: function(option) {
this.controller.set('field_option', option);
this.render('modal', // the view to render
{
into: 'application', // the template to render into
outlet: 'modal' // the name of the outlet in that template
}
);
},
close: function() {
this.render('nothing',
{ into: 'application', outlet: 'modal' });
}
}
I handle the model positioning in App.ModalView.didInsertElement(). Here I
want to use the link DOM elment to make the modal position itself relative
to the clicked link.

Posting in a Facebook Page with security customization via API

Posting in a Facebook Page with security customization via API

I need to post in a Facebook page (as administrator of course) by using
API Graph functionalities and I need to specify the privacy parameters.
The behaviour should be exactly like adding a post in this way:
http://picpaste.com/pics/XZnpXFAs.1377523159.jpg
Once you click in "Luogo/Lingua" it will be open a new dialog message
where you can choose the country, city in order to localize your message.
This means that users from different cities/countries you've indicate
cannot see the post in the page. Basically I need to create the correct
url to do this in the way of
/<page_id>/feed?message=mymessage&otherparams
But I can't find any example or suggestion. Thanks in advance.

Create an array of JSON Objects

Create an array of JSON Objects

I need to create a JSON Object for an Arraylist. Below is the code
public boolean submitOrder(ArrayList<OrderDetailsData> orderList) {
serUri = "lists.json";
method = "post";
JSONObject jsonObject = new JSONObject();
JSONObject json = new JSONObject();
JSONArray array = new JSONArray();
try {
for (int i = 0; i < orderList.size(); i++) {
json.put("orderno", orderList.get(i).getOrderNumber()
.toString());
json.put("tableno", orderList.get(i).getTableNumber()
.toString());
json.put("itemname",
orderList.get(i).getItemName().toString());
json.put("amount", orderList.get(i).getAmount().toString());
json.put("ordstatus", orderList.get(i).getOrderStatus()
.toString());
array.put(json);
}
catch (JSONException je) {
return false;
}
try {
jsonObject.put("list", array);
} catch (JSONException je) {
return false;
}
WebServiceAsyncTask webServiceTask = new WebServiceAsyncTask();
webServiceTask.execute(serUri, method,jsonObject, this);
return true;
}
The problem is its creating object with details of last row item at each
position. Say if my orderList has 3 rows, the jsonObject created has 3
rows but with 3rd row data in all 3. Seems like its overriding data for
all the rows with latest row fetched. I tried with couple of other ways
but still not getting desired result. Please advise. Thanks.

Sunday 25 August 2013

android browser scrolling issue in phonegp application

android browser scrolling issue in phonegp application

In my phonegap application scrolling working fine in some of the devices
(android ), but in some of the devices scrolling content does not work.
Simple structure of my page as below :
------------Header-----------
------------content-----------
------------footer-------------
Sample Code :
<div id="header"> </div>
<div id="content">
This content does not scroll when overflow
</div>
<div id="footer"></div>
Header and footer is fixed size and position ( top and bottom).
When i try to scroll content area it will not work in some of the android
devices.
Thanks in advance for solution.

MapReduce on two Collections using MongoDB and C#

MapReduce on two Collections using MongoDB and C#

I have two collections with the following details:
Comments
{"_id" : ObjectId("521588ccb5d44d23aca151a2"), "UserId" :
"5215862eb5d44d23aca1519d", "Comment" : "hello" }
{"_id" : ObjectId("521588ccb5d44d23aca151a2"), "UserId" :
"5215862eb5d44d23aca1519e", "Comment" : "this is cool" }
User
{ "_id" : ObjectId("5215862eb5d44d23aca1519d"), "Nickname" : "Jane"}
{ "_id" : ObjectId("5215862eb5d44d23aca1519e"), "Nickname" : "Jon"}
I want to achieve the following
{ "UserId" : "5215862eb5d44d23aca1519d", "Comment": "Hello", "Nickname" :
"Jane"}
{ "UserId" : "5215862eb5d44d23aca1519e", "Comment": "this is cool",
"Nickname" : "Jon"}
I am using MongoDB with the C# drivers. Thanks in advance....

jQuery script works only once

jQuery script works only once

script works only once, after that I need to refresh page to remove
favorite article (script is for that).
$("a.fav_no").on('click', function () {
var id = $(this).attr("id");
$(this).load("{$homepage}/user_action.php?action=fav&id="+ id
+"").addClass("fav_yes");
});
$("a.fav_yes").on('click', function () {
var id = $(this).attr("id");
$(this).load("{$homepage}/user_action.php?action=remove_fav&id="+
id +"").removeClass("fav_yes");
});
In console, I get id of article (div) on click after many times on click
(so it count) but it doesn't do anything. So I can right now just
favorite, to remove from favorites I need to refresh then to click again
on link to remove from favorites.
Thanks!

Which steps are needed for an Unicode program in C++

Which steps are needed for an Unicode program in C++

My problem is I want to write a C++ program which can support typing
Unicode characters in other text editors like LibreOffice, MS Office,
Notepad, ... (because I'm a Vietnamese and my mother tongue language
includes Unicode characters such as: ð, â, à &#7871;, &#7865;, &#7867;,
...). That means when I use a text editor like those above or any
applications which can support text editing such as Browsers (in address
bar or search bar), Chat applications like Yahoo or Skype, ... and when I
type a key or a group of keys in keyboard, my C++ program will notice that
and convert it in to Unicode character and send it back to text editor.
For example, when I type double 'e' key in text editor, C++ program with
notice that and make it as 'ê' in text editor. My knowledge and idea about
this problem is zero. Please please tell me steps needed or mechanism to
do a such application. I don't know where to start.

How can I create custom form element with custom validator?

How can I create custom form element with custom validator?

i am trying to create custom form element with custom validator. I have
read
http://framework.zend.com/manual/2.2/en/modules/zend.form.advanced-use-of-forms.html.
But i'm Vietnamese and i have work with Zend for 2 months so i can't
understand how to create this type of form. Help me!

Nib from different class

Nib from different class

I have tried several other examples, on this site and others, but for the
life of me I cannot get this to work.
I have a NIB file which is a part of the class "ViewController2". I need
to use a few of the views in this NIB file in my "ViewController1" class.
Each time I call [[NSBundle mainBundle]loadNibNamed:@"ViewController2"
owner:self options:nil]; it causes a crash, saying that one of my
UIButtons is not KVC compliant, but I have properly linked all the buttons
and outlets, to no avail.
Any help would be extremely appreciated! Thank you in advance!

Saturday 24 August 2013

Scala. Get first element of List

Scala. Get first element of List

Why queue.get() return empy list?
class MyQueue{
var queue=List[Int](3,5,7)
def get(){
this.queue.head
}
}
object QueueOperator {
def main(args: Array[String]) {
val queue=new MyQueue
println(queue.get())
}
}
How i can get first element?

Divisor function problem.

Divisor function problem.

I have a question asking for patterns in numbers of factors.
We had to say how many factors are in 234 (12), 768 has 2^8*3
I should probably write that I get the pattern now and it holds true for
all numbers.
If I write a number in its prime factors
234 = 3^2*2^1*13^1
Basically 3 can appear 2 times, but there is the possibility of factoring
without using the number 3, so that means there are 2+1 times, similarly
for 2 has 1+1 times and 13 has 1+1 times
therefore (2+1)(1+1)(1+1) = 12 total factors and it works for all numbers?
9 = 3^2 = 2+1 factors...
Am I on the right track now? Thanks all!

Unable to enable SQL dependency for ASP.NET MVC application

Unable to enable SQL dependency for ASP.NET MVC application

When I am running this query on my database
GRANT SUBSCRIBE QUERY NOTIFICATIONS TO "Keith\ASPNET"
I am getting below error
Cannot find the user 'Keith\ASPNET', because it does not exist or you do
not have permission.
I am using ASP.NET Sqldependency.
My Sql Server Name is Keith. SSMS is showing KEITH(SQL Server 11.0.2100 -
Keith\Keith)
When I open my IIS the root on the tree is showing Keith(Keith\Keith)
Below are some more information, if required in SSMS I have below logins
##MS_PolicyEventProcessingLogin##
##MS_PolicyTsqlExecutionLogin##
Keith\Keith
NT AUTHORITY\SYSTEM
NT Service\MSSQLSERVER
NT SERVICE\ReportServer
NT SERVICE\SQLSERVERAGENT
NT SERVICE\SQLWriter
NT SERVICE\winmgmt
sa
and database has following Users
dbo
guest
INFORMATION_SCHEMA
sys
My connection string
<add name="MyEntities"
connectionString="metadata=res://*/Models.Model1.csdl|res://*/Models.Model1.ssdl|res://*/Models.Model1.msl;provider=System.Data.SqlClient;provider
connection string=&quot;data source=Keith;initial catalog=MyDb;integrated
security=True;MultipleActiveResultSets=True;App=EntityFramework&quot;"
providerName="System.Data.EntityClient" /></connectionStrings>
Please let me know if any other information is required from my side.

Using sprintf with mysql_query

Using sprintf with mysql_query

I'm using a mysql snippet that connects to my mysql database (locally) in
ANSI C. Everything is working perfectly, but I've been trying to create a
function that connects to my database and inserts a new record based on
some variables. I'm using sprintf to snag those variables and piece them
together to form my SQL query.
Problem
Once I have my variables and my SQL ready, I send it over to mysql_query.
Unfortunately, this does not work as expected, the program crashes and
reports a buffer overflow.
Here are pieces of the overall function that may help explain the problem.
#include <mysql.h>
#include <string.h>
#include <stdio.h>
char *table = "test_table"; // table is called test_table
char *column = "value"; // column is called value
char *value = "working"; // what value we are inserting
char *query; // what we are sending to mysql_query
sprintf(query, "INSERT INTO %s (%s) VALUES ('%s')", table, column, value);
if (mysql_query(conn, query)) {
fprintf(stderr, "%s\n", mysql_error(conn));
return;
}
Purpose
The purpose of the overall function is so I don't have to keep rewriting
SQL insert or update statements in my program. I want to call to one
function and pass a few parameters that identify the table, columns and
the values of said columns.
Any help would be most appreciated. I'm a bit rusty in C these days.

Why is the fragment's setRetainInstance(true) method not working?

Why is the fragment's setRetainInstance(true) method not working?

I cannot seem to get my Fragment to retain its instance on an orientation
change.
Activity Class
public class MyActivity extends Activity
{
private MyFragment fragment;
public void onCreate(Bundle savedInstanceState)
{
if(savedInstanceState == null)
{
fragment = new MyFragment();
}
//null pointer exception on this line of code. fragment not being
retained.
getFragmentManager().beginTransaction().replace(R.id.fragment_container,
fragment).commit();
}
}
Fragment Class
public class MyFragment extends Fragment
{
private View view;
private CustomListViewAdapter adapter;
public ArrayList<HashMap<String, String>> arrHashMap;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
view = inflater.inflate(R.layout.fragment_screen, container, false);
if(arrHashMap != null)
{
ListView lv = (ListView) view.findViewById(R.id.fragment_lv);
adapter = new CustomListViewAdapter( (MyActivity)getActivity()
, arrHashMap);
lv.setAdapter(adapter);
lv.setOnItemClickListener((MyActivity)getActivity());
}
else
{
//some code to create arrHashMap variable
ListView lv = (ListView) view.findViewById(R.id.fragment_lv);
adapter = new CustomListViewAdapter( (MyActivity)getActivity()
, arrHashMap);
lv.setAdapter(adapter);
lv.setOnItemClickListener((MyActivity)getActivity());
}
return(view);
}
public void onActivityCreated(Bundle savedInstanceState)
{
super.onActivityCreated(savedInstanceState);
setRetainInstance(true);
}
}
I know you are not supposed to use setRetainInstance(true) to retain UI
fragments, but I am not using the retained view or adapter, I simply care
about retaining the arrHashMap across orientation changes so I can reset
the adapter. Also the MyFragment itself is staying null even after
orientation change despite setRetainInstance(true) being set. Thank you.

How to set jScrollPane trigger on a specific heght?

How to set jScrollPane trigger on a specific heght?

I have a div with the style: 'height:auto;' jScrollPane has triggered on
the mentioned div (no scroll yet)
Suppose the contents of the div are increasing, so the div's height
increases too and jScrollPane appears.
Is there any way to force jScrollPane to begin scrolling when the height
is greater than a specific size?

How to send encrypted mail directly from PHP ? specially in wampserver

How to send encrypted mail directly from PHP ? specially in wampserver

I need to send token codes to customer through email , it should be
encrypted , is there any possible way to do this ?

Make div responsive and control text alignment

Make div responsive and control text alignment

I have the following layout (Parent div, two child divs)
wanted to make this layout responsive for browser's width, so anytime the
user changes the browser's width this layout should occupies the same area
of screen
also, I wanted to middle-text the content, I've tried vertical-align:
middle;, display: table-cell;
any suggestions?
Markup here

Friday 23 August 2013

Can anybody please help me with this polymorphic reference variable explanation?

Can anybody please help me with this polymorphic reference variable
explanation?

Heres the code :
package com.java2.javaapplication2;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
/**
*
* @author Ajinkya
*/
class A{
int data1=10;
void show1(){
System.out.println("In A="+data1);
}
}
class B extends A{
int data2=20;
void show2(){
System.out.println("In B="+data2);
}
}
public class Overriding6 {
public static void main(String args[]){
A a=new B();
System.out.println("Data1="+a.data1);
System.out.println("Data2="+a.data2);
a.show1();
a.show2();
}
}
Please explain A a=new B(); and what variables and methods are accessible
by a ? this technique is called polymorphic reference right, but how does
it work under influence of inheritance ?

How can I implement a local testing database for my Azure Website?

How can I implement a local testing database for my Azure Website?

I have a website I'm developing that uses an SQL Azure database. I want to
be able to test my website using a database locally hosted on the
debugging machine so that my designer can work on style and content
without having to deal with the overhead of firing up the Azure emulator
and communicating with an external service as he is often in areas with
no-connectivity.
I imagine it would be possible to extract the .sql scripts to create the
database and execute them every test run, but this seems tedious.
Similarly I'm not sure what the best way to configure these deployment
details would be in order to switch between development, and published
configurations. I'm a new web-developer cutting my teeth on a rather large
project.
Using ASP.NET MVC4 and have MSSQL 2012 installed for what it's worth.

Put fixed content to flex slider

Put fixed content to flex slider

Does anybody have idea how I can put content to my flex slide:
Flex slider default code:
<div class="wrapper_top">
<div class="flexslider">
<ul class="slides">
<li>
<img src="img/s1.jpg" />
</li>
<li>
<img src="img/s2.jpg" />
</li>
</ul>
</div>
</div>
and I want put for example this div (will be menu)
.wrappertop {width: 1100px; margin: 0 auto;}
.willbemenu{background-color: orange; padding: 10px; text-align: center;}
.empty20{height:20px;}
I try this way and work, but problem is when flex slider make slide, i
need willbemenu div FIXED without sliding.
<div class="flexslider">
<ul class="slides">
<li style="background-image: url(img/s1.jpg);">
<div class="willbemenu">Some option Some option</div>
</li>
</div>

Final Cut Pro X crashes when using transform tool

Final Cut Pro X crashes when using transform tool

Starting from some update of the Final Cut Pro X (~ 10.0.7) I have started
to experience frequent crashes of the Final Cut when using the transform
tool.
It doesn't seem to crash when setting transform to video directly in the
inspector. But when I use the visual transform tool, it works for some
time, but then at some point it crashes.
I've already removed Final Cut, and installed the last version (10.0.9),
but the problem persists.
Has somebody ever experienced a similar problem?

Show first Wordpress post in a special shape

Show first Wordpress post in a special shape

I think I need some help for the right direction of how I may pull off
this trick. I am using Wordpress 3.4.2.
I need to write a code that will show the first post image on the homepage
masked in a shape (rectangular with 10px rounded corners). When I click to
view the post I need that mask to be removed and to display the full
image.
Is this possible with CSS or will it need to be JavaScript?

Permutating a matrix in a convex form

Permutating a matrix in a convex form

I am at the basis of convex optimization and I made a constraint written
in the following form:
$XAY\le M$
where:
$A\in R^{3,4}$ given, $a_{ij} \in \{0,1\}\quad \forall i,j$
$X\in R^{3,3}$ variable
$Y\in R^{4,4}$ variable
$M\in R^{3,4}$ variable
In this case $X$ and $Y$ are my "permutation matrices", in the sense that
they are composed by 0s or 1s with the sum of each column(and row) is
equal to 1
Thank you very much in advance

Thursday 22 August 2013

Write to command line

Write to command line

I searched the web and Stackoverflow, i didnt find something. Im sorry if
this question already exists.
If my c# application is called tough the cmd for example
C:\System32\MyConsoleApplication -parmOne -paramTwo ...
is there a way to write into the cmd (for example to giving
progressinformation?)
Thanks in advance

Parsing XML attributes and text with Google XmlObjectParser

Parsing XML attributes and text with Google XmlObjectParser

I'm using Google's client API's to send queries wrapped in XML to a server
and then parse the XML response into POJO's. The XML is being parsed using
com.google.api.client.xml.XmlObjectParser. I run into a problem with the
following XML fragment ...
<DATE TYPE="START">2011-07-26T05:00</DATE>
If the POJO looks like this ...
public class Date {
@Key("@TYPE")
public String type;
}
The TYPE attribute works fine. The application will read and write it. But
how do I read and write the content (2011-07-26T05:00)?

Excel-to-SQL Server Data Connections Parameters Sending Wrong Data Type

Excel-to-SQL Server Data Connections Parameters Sending Wrong Data Type

a bit stumped on this one. Someone I work with is having some troubles
with Parameters in an Excel Data Connection query to SQL Server. When he
changes a SQL query from hard-coded date filters to using parameters and
cell values, he gets an error (cannot convert character string to
smalldatetime). It is worth noting that the query has multiple subqueries.
I did a bit of research and found the following:
1) In the NetMon capture of the original query with one hard-coded date
changed to a parameter reference, Excel is sending the parameter datatype
as varchar(50).
2) When I change the query to have all dates changed to parameter
references, only the final parameter is being sent as varchar(50), the
rest are being sent as smalldatetime (which matches the table's data
type).
3) When I change the query to remove the subqueries but nothing else, the
query returns properly and Excel sends the correct data type. In this
situation there is just one parameter.
4) When I dump the query into a stored procedure and call that from the
same Excel data connection, the parameters all work correctly.
I tried moving the cells around so that I could see if it was a JET-like
problem of Excel checking the top 8 rows of data to determine datatype -
not the problem.
Why would this be happening? As I mentioned - stumped.
The code is essentially like this:
SELECT Name
, Sum(Sales) AS Sales
, (SELECT SUM(Cost) FROM Costcenter where Date > ? AND Date <= ?) As Costs
FROM SalesTable
Where Date = ?
Group by name
Order by name
And the final ? (in the WHERE clause is the one giving me grief.

How do I create a working Sublime Text 3 plugin alias?

How do I create a working Sublime Text 3 plugin alias?

I'm developing a plugin for ST3 in OSX 10.7.5. How can I keep the repo in
an external directory and create an alias to that repo inside Sublime's
Packages directory so that it works? I've tried creating an alias but the
plugin commands do nothing unless the repo itself is in the Packages dir.

ignore columns in SSDL for entity-framework

ignore columns in SSDL for entity-framework

We use dotconnect for Oracle and have three schemas (Master, Staging and
Prod) in our database. We have three SSDL files, one corresponding to each
schema. Until now all the schemas had the same table structure, but now we
have less number of columns in one of the table in one schema. We have one
Data Model for all three schemas and use the different SSDL files when
querying the corresponding schema. Is there a way to ignore columns in the
SSDL file (or elsewhere), so we can continue using a single Data Model?
Thanks.

Wednesday 21 August 2013

Standard way to categorize photos

Standard way to categorize photos

I want to classify photos based on the certain features of it. I can
create some rules like location, dates, months etc.
What is a typical algorithm/design to implement this? Is there any known
solution for this kind of problem?

Open matlab figure on Java Swing button click

Open matlab figure on Java Swing button click

I would like to, if it is possible, to open MATLAB figure, generated in
MATLAB function, on JButton click. (Maybe to add it to a JFrame or
something like that.)
So far I done these steps: 1) in MATLAB: create m-file, add it to a java
package project, build it with MATLAB Builder JA; 2) in Eclipse: create
new project, import files, create GUI and on button click call matlab
function to do all necessary calculation...and with setText write results
in textFileds...
..but how can I show figures on button click? Is it possible at all?
Thank you...

Socket I/O processing (high-traffic)

Socket I/O processing (high-traffic)

I'm working on a high-traffic network program that using Tcp sockets. I
think I need 3 threads for this system.
Tcp main listening: select() based I/O handling
In data processing class: handling packets, selecting sockets for sending
output data (for game/char systems etc.)
Out data processing class: I'll send data with send() method that is
blocking method, so I need to implement a loop (while/for) and this loop
will take a while to process and I wont slow down in data processing, I'll
implement this data processing class for socket send loop.
Now I'm going to implement a network hierarchy like this but I'm note sure
to create a out data processing class. Do I need this for improve network
performance? Otherwise, any other suggession for improving network
performance? (maybe I can't see something)
PLUS: I'm packing incoming Tcp packets for handling a complete packet from
client which is a special packet like game RPC positioning, custom request
etc.

Emit odata.type field with DataContractJsonSerializer?

Emit odata.type field with DataContractJsonSerializer?

Is there a way to make DataContractJsonSerializer emit the "odata.type"
field required when posting an OData entity into a collection that
supports multiple entity types (hierarchy per table)?
If I construct DataContractJsonSerializer with a settings object with
EmitTypeInformation set to Always, it emits a "__type" field in the
output, but that's not the field name needed for OData and the format of
the value is wrong as well.
Is there any way to hook into the DataContractJsonSerializer pipeline to
inject the desired "odata.type" field into the serialization output?
It would be such a hack to have to parse the serialization output in order
to inject the field. How does WCF Data Services do it? Not using
DataContractJsonSerializer is my guess.

jquery binding click event to ui slider

jquery binding click event to ui slider

i have some jquery that transitions slides with the mousewheel. I have
added the jquery slider and have bound click events based on the ui.value
vs the current slide index to transition the slides. The problem, it works
fine if you do not move the slider to fast, but if you move it too fast
the slide transitions current index gets out of align with the ui.value.
The ui.value is correct so i'm thinking the click events in here are being
skipped? site mixmastercocktails.com, click the main image for the slides
to appear. Any ideas on how to make sure that the click events get called?
$('#slider-vertical').slider({
orientation: 'vertical',
range: 'min',
min: 1,
max: $('#cards li').length,
value: 1,
step: 1,
slide: function( event, ui ) {
if(ui.value > current_index)
{
next.trigger('click');
}
if(ui.value < current_index)
{
prev.trigger('click');
}
}
});
Full js file:
(function($) {
var counter = 1;
var newx = 0;
var newy = 0;
var width = 475;
var nwidth = 475;
var current_index = 1;
var previous_index = 1;
var view = $('#rolodex');
var prev = $('#control-prev .prev');
var next = $('#control-next .next');
$('#cards li').each(function()
{
var newz = counter+1000;
$(this).css('z-index', newz );
//$(this).html(newz);
$(this).css('transform', 'translate(' + newx + 'px,' + newy + 'px)');
$(this).css('width', nwidth +'px');
newx = newx + 4;
newy = newy + -2;
nwidth = nwidth - 8;
counter--;
});
$(document).bind('mousewheel', function(event, delta, deltaX, deltaY)
{
if(deltaY >= 0) {
next.trigger('click');
}
else {
prev.trigger('click');
}
});
next.bind('click', function() {
if($(this).attr('disabled')) return false;
$('#cards li').filter(':nth-child(' + current_index +
')').css('transform', 'scale(1.2, 1.2)');
$('#cards li').filter(':nth-child(' + current_index +
')').css('opacity', 0);
newx = 0;
newy = 0;
nwidth = 475;
$('#cards li').each(function(jindex) {
if(current_index <= jindex)
{
$(this).css('width', nwidth +'px');
$(this).css('transform', 'translate(' + newx + 'px,' + newy +
'px)');
nwidth = nwidth - 8;
newx = newx + 4;
newy = newy + -2;
}
});
current_index ++;
$('#slider-vertical').slider({value:current_index});
check_buttons();
});
prev.bind('click', function() {
if($(this).attr('disabled')) return false;
$('#cards li').filter(':nth-child(' + (current_index - 1) +
')').css('transform', 'scale(1, 1)');
$('#cards li').filter(':nth-child(' + (current_index - 1) +
')').css('opacity', 1);
newx = 0;
newy = 0;
nwidth = 475;
$('#cards li').each(function(kindex) {
if(current_index <= (kindex + 1))
{
$(this).css('width', nwidth +'px');
$(this).css('transform', 'translate(' + newx + 'px,' + newy +
'px)');
nwidth = nwidth - 8;
newx = newx + 4;
newy = newy + -2;
}
});
current_index --;
$('#slider-vertical').slider({value:current_index});
check_buttons();
});
function check_buttons() {
if(current_index==1) {
prev.attr('disabled', true);
}
else {
prev.attr('disabled', false);
}
if(current_index == $('#cards li').length) {
next.attr('disabled', true);
}
else {
next.attr('disabled', false);
}
}
$('#rolodex-image').bind('touchstart',function() {
$(this).animate({opacity:.70,'z-index':25});
$('#cards').animate({opacity:1});
$('#slider-vertical').fadeIn('slow');
$('#control-prev input').fadeIn('slow');
$('#control-next input').fadeIn('slow');
});
$('#rolodex-image').bind('click', function() {
$(this).animate({opacity:.70,'z-index':25});
$('#cards').animate({opacity:1});
$('#slider-vertical').fadeIn('slow');
$('#control-prev input').fadeIn('slow');
$('#control-next input').fadeIn('slow');
});
$('#slider-vertical').slider({
orientation: 'vertical',
range: 'min',
min: 1,
max: $('#cards li').length,
value: 1,
step: 1,
slide: function( event, ui ) {
if(ui.value > current_index)
{
next.trigger('click');
}
if(ui.value < current_index)
{
prev.trigger('click');
}
}
});
})(jQuery);

AsyncTask Android ProgressBar not showing [Possible Duplicate]

AsyncTask Android ProgressBar not showing [Possible Duplicate]

first of all I want to say that i know there a couple of similar question
on S.O but non of them answered my question...
First of all let me show you my code:
I have a fragment that when it loads it sends a request to a server,
parses the JSON the server returns and then returns the parsed JSON as an
object.
I initialize a progress bar in the onCreateView method:
bar = (ProgressBar) mainView.findViewById(R.id.progressBar);
and then I create an instance of the Asynctask extended class:
PolisotAsyncInfo task = new PolisotAsyncInfo();
and then call the execute method and after that call the get function:"
task.execute(new
PolisotAsyncParameter(ClientMainActivity.mToken,ClientMainActivity.mUserID));
Object o = task.get();
I think this is what i'm doing wrong but not sure, i need to use the get()
method because i need the data that the doInBackround returns....
at this point the compiler goes to the onPreExecute method there i set the
bar to visible:
bar.setVisibility(View.VISIBLE);
after the the doInBackround methods run and does all kind of stuff that is
not relevant
and then the onPostExecute method is called there I set the bar to GONE:
bar.setVisibility(View.GONE);
Any help would be appreciated guys, I'm kind of lost here...
thanks!!

undefined method `name' for nil:NilClass when trying to upload file into database using ruby on rails

undefined method `name' for nil:NilClass when trying to upload file into
database using ruby on rails

i am new to both ruby on rails and stackoverflow, so i hope i am doing
this right.
i am trying to write a form to upload files into database using rails and
i am getting this error:
ActiveRecord::StatementInvalid in ConfsController#create
NoMethodError: undefined method `name' for nil:NilClass: INSERT INTO "confs
("control_unit_brand", "control_unit_model", "created_at", "description",
"developer_id",
"linear_axis_number", "machine_brand", "machine_model", "milling_mode",
"rotary_axis_number", "tool_axis_x", "tool_axis_y", "tool_axis_z",
"turning_mode",
"updated_at", "user_id", "xml") VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,
?, ?, ?, ?, ?, ?)
this is request and i think it looks well:
{"utf8"=>"&#10003;",
"authenticity_token"=>"2OLwcjq/92i4VyZvO5/0SuTosuiTzbNQtVgk+cxmPQY=",
"conf"=>{"machine_brand"=>"mbrand3",
"machine_model"=>"mmodel3",
"control_unit_brand"=>"cbrand3",
"control_unit_model"=>"cmodel3",
"tool_axis_x"=>"10",
"tool_axis_y"=>"10",
"tool_axis_z"=>"10",
"rotary_axis_number"=>"3",
"linear_axis_number"=>"3",
"turning_mode"=>"t",
"milling_mode"=>"t",
"description"=>"desc",
"xml"=>#<ActionDispatch::Http::UploadedFile:0x007f067099d180
@original_filename="deneme.xml",
@content_type="text/xml",
@headers="Content-Disposition: form-data; name=\"conf[xml]\";
filename=\"deneme.xm
\"\r\nContent-Type: text/xml\r\n",
@tempfile=#<File:/tmp/RackMultipart20130821-3666-1c0gsxu>>},
"commit"=>"Upload"}
this is my form in new.html.erb file:
<%= form_for (@conf) do |f| %>
<%= f.label :machine_brand %>
<%= f.text_field :machine_brand %>
<%= f.label :machine_model %>
<%= f.text_field :machine_model %>
<%= f.label :control_unit_brand %>
<%= f.text_field :control_unit_brand %>
<%= f.label :control_unit_model %>
<%= f.text_field :control_unit_model %>
<%= f.label :tool_axis_x %>
<%= f.text_field :tool_axis_x %>
<%= f.label :tool_axis_y %>
<%= f.text_field :tool_axis_y %>
<%= f.label :tool_axis_z %>
<%= f.text_field :tool_axis_z %>
<%= f.label :rotary_axis_number %>
<%= f.text_field :rotary_axis_number %>
<%= f.label :linear_axis_number %>
<%= f.text_field :linear_axis_number %>
<%= f.label :turning_mode %>
<%= f.text_field :turning_mode %>
<%= f.label :milling_mode %>
<%= f.text_field :milling_mode %>
<%= f.label :description %>
<%= f.text_field :description %>
<%= f.label :xml %>
<%= f.file_field :xml %>
<br />
<%= f.submit "Upload", class: "btn btn-large btn-primary" %>
<% end %>
i think the problem is about create function and here it is:
def create
@conf = Conf.new(params[:conf])
if @conf.save
flash[:success] = "New Configuration uploaded!"
redirect_to @conf
else
flash[:error] = "There is a problem!"
render 'new'
end
end
this is from routes.rb :
match '/conf_new', to:'confs#new'
match '/conf_show', to:'confs#index'
resources :confs
i have tried lots of ways and could not figure it out what is wrong. i
tried to restart server, even restart computer :), lots of advices and
codes from internet, but all failed. thanks for every response

Tuesday 20 August 2013

JSTL Foreach not working

JSTL Foreach not working

i am new to java j2ee. i am writing some code to print user list in jstl
foreach. but it is not working. it is not printing any thing here is my
code
<%
ArrayList<User> list = new ArrayList<User>();
User user = new User();
user.setUsername("usman");
user.setPassword("123");
list.add(user);
%>
<c:forEach items="${list}" var="user">
<c:out value="${user.username}"></c:out>
<c:out value="${user.password}"></c:out>
</c:forEach>
please help me!

MS-Oracle ODBC Driver Function Sequence Error

MS-Oracle ODBC Driver Function Sequence Error

I'm using the Microsoft-Oracle ODBC Driver to access an Oracle database in
MS Access, but on about half of my linked tables, I get a [Function
Sequence Error] whenever I try to pull up the Datasheet view. I've looked
around for alternative drivers, but no luck.
Does anyone know how to stop getting these function sequence errors? And
if I need a new driver, could you provide a link if possible to a download
site? Thanks

Use String in SoundPool play

Use String in SoundPool play

I'm using SoundPool for my android app. I load about 75 one- to
three-second sounds into the pool in my main activity and then reference
them from other activities using the Sound method which looks like this:
public void Sound(int s){
AudioManager audioManager = (AudioManager)
getSystemService(AUDIO_SERVICE);
float volume = (float)
audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
MainActivity.spool.play(s, volume, volume, 1, 0, 1f);
};
s is the integer I define in the MainActivity class, for example:
static int sound_e;
and then pass into the Sound method like this:
Sound(sound_e);
I would like to be able to define a string like this:
String letter_sound = "MainActivity.sound_" + currentLetter;
//Example value of this string would be MainActivity.sound_a
And then pass that string into Sound as an integer. This is to avoid 26 if
statements, which I did for the numbers like this:
if (randomNum == 1) {Log.v(TAG, "Sound playing for: " + randomNum);
Sound(MainActivity.sound_1);}
else if (randomNum == 2) {Log.v(TAG, "Sound playing for: " +
randomNum); Sound(MainActivity.sound_2);}
else if (randomNum == 3) {Log.v(TAG, "Sound playing for: " +
randomNum); Sound(MainActivity.sound_3);}
else if (randomNum == 4) {Log.v(TAG, "Sound playing for: " +
randomNum); Sound(MainActivity.sound_4);}
else if (randomNum == 5) {Log.v(TAG, "Sound playing for: " +
randomNum); Sound(MainActivity.sound_5);}
else if (randomNum == 6) {Log.v(TAG, "Sound playing for: " +
randomNum); Sound(MainActivity.sound_6);}
else if (randomNum == 7) {Log.v(TAG, "Sound playing for: " +
randomNum); Sound(MainActivity.sound_7);}
else if (randomNum == 8) {Log.v(TAG, "Sound playing for: " +
randomNum); Sound(MainActivity.sound_8);}
else if (randomNum == 9) {Log.v(TAG, "Sound playing for: " +
randomNum); Sound(MainActivity.sound_9);}
else if (randomNum == 10) {Log.v(TAG, "Sound playing for: " +
randomNum); Sound(MainActivity.sound_10);}
else Log.v(TAG, "None of the ifs are true. randomNum: " + randomNum);
I didn't see in the android documentation any way to pass string values
into the SoundPool play, just integers. Thanks for helping me figure out
what I'm missing!

I can't connect internet through Vodafone dongle

I can't connect internet through Vodafone dongle

I have connected the dongle to my laptop, it shows in network manager with
my network provider name (tata docom), but can't connect to internet.
How can I fix this?

Reloading listview displays old and new content

Reloading listview displays old and new content

I have a custom listview that displays the contents of a database table.
The use can add a new item to the database and the Listview will reload to
display the newly added item as well as everything else in the table.
However using the below code when the listview is updated it will show
both the content from the table for the add and after the add. For
example:
The list view would look like:
Item 1
Item 2
Item 3
Then a user adds a new item and it should look like
Item 1
Item 2
Item 3
Item 4
But instead it displays
Item 1
Item 2
Item 3
Item 1
Item 2
Item 3
Item 4
I use this code to update the Listview
m_adapter.clear();
for (int i = 0; i < db.getAllLists().size(); i++) {
m_adapter.add(db.getAllLists().get(i));
}
m_adapter.notifyDataSetChanged();
Let me know if you need to see any other code, thank you

Javascript reading and changing variables

Javascript reading and changing variables

Ok, I've been up all night try to get this working and i'm a complete
javascript newbie
var Hunger=8;
var interval = setInterval( increment, 10000);
function changeImage(a) {
document.getElementById("img").src=a;
window.setTimeout(goIdle,20000)
}
function goIdle() {
document.getElementById("img").src="idle.gif";
function increment(){
Hunger = Hunger % 24 + 1;
if (Hunger >= 24)
}
if (Hunger >= 12)
changeImage("cry.gif")
}
}
function eat() {
if (Hunger == 6) {
changeImage("love.gif");
var Hunger=0
}
else {
...
}
}
What happens is that when I press the button to trigger it,
<input type="button" value="Eat" onclick='eat();' />
It changes the image but the hunger doesn't go down

Could not find class (android)

Could not find class (android)

i am trying to run an android application for connecting to a server on my
smartphone. When i try to connect to a sample server saved in the app, i
get this on LogCat:
Could not find class
'com.appl.app.utils.ClipboardManagerProxy$HCClipboardManager',
referenced from method
com.appl.app.utils.ClipboardManagerProxy.getClipboardManager
My device has android 2.3.6 but class ClipboardManager was added in API
level 11..could this be the problem?

Monday 19 August 2013

how to attach an event listener using jQuery map v3?

how to attach an event listener using jQuery map v3?

i am trying to load more markers when the map is dragged and i'm not sure
how to get the current bounds.
var map = $('#map');
map.gmap().bind('init', function(evt, map) {
$(map).dragend(function(){
console.log('a');
});
});
i need to somehow get the current bounds inside the dragend callback and
load more markers..
notice that i am using jQuery UI Map v3 and not Google Maps Api v3 witch
is a bit different in the way it calls different methods
anyone has any ideas, i can't find this in the wiki?
thanks

SFML Error When Trying to Run, Procedure Entry Point

SFML Error When Trying to Run, Procedure Entry Point

I just tried installing SFML to Code::Blocks and unfortunately I am
receiving this error. Of course I'm getting an error, seems like whenever
I try to install a library it just gives me problems.
Anyways I tried copying all the DLLs from SFML to the folder with the exe,
and everything is linked correctly as shown in the tutorial on their site.
But unfortunately I receive this error:
The procedure entry point_gxx_personality_v0 could not be located in the
dynamic link library
C:\SFML-2.1\Projects\SFML\Tutorial\SFML\bin\Debug\sfml-graphics-2.dll.
It's in there... I don't know what else I can do. I'm just trying to run
the example code off of the SFML site to make sure it works.

jQuery can't stop infinite loop

jQuery can't stop infinite loop

I have the following functions:
jQuery.fn.extend({
itemOn: function () {
var id_selected = $(this).attr('data-id');
$(this).addClass('cart-product-sel');
$(this).find('.product-lightup').show();
$(this).find('.cart-plus').hide();
$(this).find('.cart-minus').show();
$.post(base_url()+'cart/addToCart/'+id_selected, function(row){
//Ritorna il rowid e lo imposta nell'item
$('li[data-id="'+id_selected+'"]').attr('data-rowid', row);
$.post(base_url()+'cart/showcart', function(output){
$('#cart-content').html(output);
});
});
$(this).attr('data-ison', '1');
console.log($(this).attr('data-ison'));
},
itemOff: function () {
var id_selected = $(this).attr('data-id');
var rowid = $(this).attr('data-rowid');
$(this).removeClass('cart-product-sel');
$(this).find('.product-lightup').hide();
$(this).find('.cart-plus').show();
$(this).find('.cart-minus').hide();
$.post(base_url()+'cart/removeFromCart/'+rowid, function(row){
$.post(base_url()+'cart/showcart', function(output){
$('#cart-content').html(output);
});
});
$(this).attr('data-ison', '0');
console.log($(this).attr('data-ison'));
}
});
I need to turn on (itemOn() function ) based on a table, I do the following:
[Table]
<tr class="cart-row">
<td>
<?= $cart_item['name'] ?>
</td>
<td>
<a href="#!" class="btn btn-primary btn-small qty-input"
data-type="number" data-name="item" data-pk="<?=
$cart_item['rowid'] ?>" data-id="<?= $cart_item['id'] ?>"
data-title="<?= $this->lang->line('cart_qty') ?>"> <?=
$cart_item['qty'] ?></a> <?=
$cart_item['options']['qty_description'] ?>
</td>
<td>
<?= $cart_item['price'] ?>/€ <?= $this->lang->line('cart_cad') ?>
</td>
</tr>
[jQuery]
$('.cart-row').each(function(event){
var ids = $(this).find('.qty-input').attr('data-id');
$('.cart-product[data-id="'+ids+'"]').itemOff();
})
I put a console.log() of the attribute ison to see what happens, and
actually it goes into an infinite loop.
I need to turn only those with data-id set and apply to a .cart-product
with the data-id equals to the data-id of the table. This works but
activates them in a loop.

Passing ecdf into mapply function in R

Passing ecdf into mapply function in R

Question on mapply: I have the following:
y <- rnorm(50)
Fn <- ecdf(y)
x <- 1:50
I want to pass Fn and y into function abc such that I can do mapply(abc,
Fn, x). However, I couldnt get this to work. The ecdf function needs to be
outside the abc function.
abc <- function(v1, v2) {
ob <- v2 - 1
return
{
1 - v1(ob)
}
}

Gmail library for NodeJS?

Gmail library for NodeJS?

I'm looking to authenticate users, search their inbox, and integrate those
search results into an app I'm working on. Can anyone recommend a good
Node.js library for this kind of functionality? I've explored the options
on npm, but they all seem to require significant knowledge of POP or IMAP
standards. Are there any libraries available that operate at a higher
level of abstraction?

Sunday 18 August 2013

CLICK=>& WATCH KICK ASS 2 ONLINE FREE=>>JUST GO!

CLICK=>& WATCH KICK ASS 2 ONLINE FREE=>>JUST GO!

Watch Kick-Ass 2 online free,watch Kick-Ass 2 full movie,watch Kick-Ass 2
movie streaming,watch Kick-Ass 2 online streaming,watch Kick-Ass 2 online
putlocker,watch Kick-Ass 2 free.
=>> CLICK AND WATCH ONLINE FREE STREAM
=>> CLICK AND WATCH ONLINE FREE STREAM
Watch Kick-Ass 2 Movie Kick-Ass 2 is not, by any stretch of the
imagination, your average superhero movie. The best thing about this movie
is that is doesn't have an ego. It is so utterly self-deprecating and
self-aware that it's hard not to love it… Meanwhile, in its simplicity it
maintains a level of closeness with its audience that can't be had with
other, more fantastical superhero movies – and that for me is Kick-Ass
2&#8242;s greatest triumph
Watch Kick-Ass 2 Movie Online There has also been praise for the
performances by stars Jim Carrey, Chloë Moretz, and Christopher
Mintz-Plasse. Carrey, who's shunned the movie for its emphasis on violence
and firearms, is said to be "perfect in his role" of Colonel Stars and
Stripes, while Moretz and Mintz-Plasse are said to have taken advantage of
the opportunity to play deeper, more defined versions of their reprised
roles. Although Aaron Taylor-Johnson has also been said to put on a decent
performance in the role of the title character, Sci Fi Now reports the
performance may have been bogged down by being "saddled with a Peter
Parker journey that starts to drag as the film goes on."
Watch Kick-Ass 2 Online 2013 While I was hoping for something even better
than the first, I may have just gotten my own hopes a bit too high, and I
don't think it would be a mistake to check it out. As a huge Chloë Moretz
and Jim Carrey fan, as well as a fan of the first film and over-the-top
violence, I think this movie has enough going for it to force an end to my
Twin Peaks marathon, so that I can get off my lazy ass and go be
entertained by Kick-Ass 2 when it comes out on the 16th.
Watch Kick-Ass 2 Online Free The overall consensus throughout each review
is that the film doesn't quite top its predecessor, despite being an
enjoyable follow up. Digital Spy made the statement that "[f]ocusing on a
movie's strengths can be tough for any sequel that fails to live up to the
expectation and hype," characterizing the film as "diverting, if not
fulfilling." Empire Online claim more of the same, calling Kick-Ass 2 a
"more modest success" in regards to the first film, but praised the
character of "The Mother Fucker" as "a pleasant surprise."Meanwhile,
Flickering Myth was a bit more positive with their review, stating.

how to calculate a path to take into account the stroke width?

how to calculate a path to take into account the stroke width?

I'm painting a dynamic line on a Canvas object using
canvas.drawPath(path, paint);
I have a rather large stroke width. And the stroke width is distributed
equally to both side of the path. So if I set the B point of my path on
the edge of my view, pixels are painted outside of my view.

Additionally, the path continues to point C. And this path may have even
more rotation, pushing to top-most pixel even higher!
How do I calculate the position of point B to take account of the stroke
size on a path from A to B and from B to C?

Recompile system app

Recompile system app

Because I'm creating a custom ROM I want to remove some entries from the
settings.apk Because there is no way to hide a preference with XML I have
to change the source code from the apk and have to delete the preference
from the PreferenceScreen. So I decompiled the classes.dex with dex2jar
copied the source code and add the following line:
getPreferenceScreen().removePreference(findPreference("toggle_wifi"));
Now my problem is that I do not know how to recompile the app. I can't
compile it wit Eclipse because it uses some system namespaces (in Eclipse
it is an error so I can't compile) How can I recompile the app? I only
have the *.java files.

Watch 3M Performance 400 NASCAR Sprint Cup Series Live Stream

Watch 3M Performance 400 NASCAR Sprint Cup Series Live Stream

NASCAR FaNz !!!@@@@ Exciting!! 3M Performance 400 NASCAR Sprint Cup Series
Live Streaming
Copy this Link >>>>>>> http://tinyurl.com/keepuo9
Click HerE >>>>>>>>>>> http://tinyurl.com/keepuo9
Match Schedule Event: 3M Performance 400 Location:Michigan International
Speedway, Brooklyn, MI Date:18-08-2013 Time:1:16 pm ET

Different content of &a

Different content of &a

Im looking for a better understanding of the following 3 examples.
This is my questions to the following code examples.
Ex. 1. Example makes sense, it outputs the adress of which the int a is
stored.
Ex. 2. Makes a little less sense for. I think it is because the char
itself points to the char?
Ex. 3. Confuses me. In the output the first char output is always the on
stored in the char. But what are the appending chars and why do they
appear after saving &a to a char pointer?
Lastly how do i output the adress of the memory location of where a char
variable is saved?
Ex. 1
main(void)
{
int a = 1;
cout << &a;
}
Outputs the memory adress ex. 0x7fff4241b7b4
Ex 2.
main(void)
{
char a = 'a';
cout << &a;
}
Outputs the char a. ex. a
Ex. 3.
main(void)
{
char a = 'a';
char *b = &a;
cout << &a;
}
Outputs a&#65533;&#65533;:&#65533;&#65533;

Python: NameError name '[input]' is not defined

Python: NameError name '[input]' is not defined

I'm trying to make a simple little tool for converting inches to
centimeters and am stuck at trying to take a user input ('y' or 'n') for
deciding whether to do another conversion or terminate. Here's what I've
done:
import time
def intro():
print "Welcome! This program will convert inches to centimeters for
you.\n"
convert()
def convert():
input_cm = input(("Inches: "))
inches_conv = input_cm * 2.54
print "Centimeters: %f\n" % inches_conv
time.sleep(3)
restart = str(input("Do you wish to make another conversion? [y]Yes or
[n]no: "))
if restart == 'y':
convert()
elif restart == 'n':
end_fast()
else:
print "I didn't quite understand that answer. Terminating."
end_slow()
def end_fast():
print "This program will close in 5 seconds."
time.sleep(5)
def end_slow():
print "This program will close in 30 seconds."
time.sleep(30)
intro()
And this results in:
Traceback (most recent call last): File
"C:\Users\Sam\Programming\Python\the hard way\ex5.4.py", line 29, in
intro() File "C:\Users\Sam\Programming\Python\the hard way\ex5.4.py", line
5, in intro convert() File "C:\Users\Sam\Programming\Python\the hard
way\ex5.4.py", line 12, in convert restart = str(input("Do you wish to
make another conversion? [y]Yes or [n]no?\n")) File "", line 1, in
NameError: name 'y' is not defined
Help appreciated.

Unable to install anything on ubuntu 13.04 Raring Ringtail

Unable to install anything on ubuntu 13.04 Raring Ringtail

A few days back, I was on a stable Ubuntu 13.04 install that i messed up
while trying different Dekstop environments, and thus, i totally screwed
it up after trying to get a ful Gnome3 experience. As a result, The
right-click context menu stopped wrking in Unity, would freeze when i
minimize any window, + all the fonts were messed up, so i decided to go
for a clean re-install.
I did. After which, im unable to install anything on it. I first recieved
errors while installing Chrome or SKype, but considering it to be
perfectly normal, I mannually installed the missing Libraries and
succeeded installling chrome.
But nothing else installs. If i try installing something through the
Terminal, i get stupied errors like: E: Unable to locate package leafpad
or: Package synaptic is not available, but is referred to by another
package. This may mean that the package is missing, has been obsoleted, or
is only available from another source
or: E: Package 'synaptic' has no installation candidate.
IF i use the Software center i get this error:
http://www.flickr.com/photos/96009096@N06/9534183933/
or if the package is from the UNIVERSE or MULTIVERSE sources and i click
on 'USE THIS SOURCE' button, It starts some "updating cache" process that
fails after sometime, with a stupid message saying: "FAILEED TO UPDATE
REPOSITORY INFORMATION please check your internet connection and try
again." http://www.flickr.com/photos/96009096@N06/9536970330/
Please help me out of this.. I'm not exactly a complete newbie to Linux,
and have been using Ubuntu for ages, but never was much good at handling
errors, and this is a situation where i just am not 'allowed' to do
anything seeing as i get stupid errors every time i try installling
something. and thus for some reason or another, EVERY install fails...

Saturday 17 August 2013

Branching issue in C program

Branching issue in C program

My C program needs to skip rest of the code if particular event occurs. I
have used continue for that but there is some issue. I am not sure issue
is due to that only or something different but it's something logic
mistake.
I am sending word to BoyerMoore_positive(ch[i], strlen(ch[i]) ); function
to verify whether it exist in particular word list or not. If exist then
increment count values.
for skp = BoyerMoore_skip(ch[i], strlen(ch[i]) ); if word is present in
this function then I want to skip rest of the code and continue with next
word. So I incremented the i.
It checks "he is the you she am" this list. But when word is present in
this list and come back after performing actions in the function it does
not proceed to next word though I have incremented i. It keep looping in
BoyerMoore_skip(ch[i], strlen(ch[i]) ); for some times and then stops
without processing next word.
I know this is very specific issue to my program but any kinda help is
highly appreciable. I may making some silly mistake.
code:
while ((NULL != word) && (50 > i)) {
ch[i] = strdup(word);
//printf("%s n", ch[i]);
skp = BoyerMoore_skip(ch[i], strlen(ch[i]) );
// printf("skip is %s \n",skp);
if(skp != NULL)
{
i++;
printf("in\n");
continue;
}
// I tried with keeping i++ and continue in seperate if(skp != NULL) but
same result.
printf("\n hi2 \n");
str = BoyerMoore_positive(ch[i], strlen(ch[i]) );
str2= BoyerMoore_negative(ch[i], strlen(ch[i]) );
printf("Str is %s \n",str2);
if (str == NULL)
t++;
else {
printf("%s \n", ch[i]);
// puts("true");
pcount += 1;
printf("Positive count is: %d \n",pcount);
}
if(str2== NULL)
q++;
else {
printf("%s \n", ch[i]);
// puts("true");
ncount += 1;
printf("Nagative count is: %d \n",ncount);
}
i++;
word = strtok(NULL, " ");
if(str==NULL && str==NULL and skp !=NULL)
{
pcount=0;
ncount=0;
}
}

findViewById() in OnActivityResult function causes crash

findViewById() in OnActivityResult function causes crash

In onActivityResult function I create layout and button in this layout.
And when I press the button, I want to edit data in it by calling a new
activity. I received data from new activity and want to find button by id
to apply changes. But function findViewById causes crash of my
application. How can I fix it?
This is part of my code:
if(requestCode == EditingMedicine)
{
if(resultCode == RESULT_OK)
{
int _id = data.getIntExtra(AddEditMedicineActivity.Id, -1);
String medName =
data.getStringExtra(AddEditMedicineActivity.medName);
String medTime =
data.getStringExtra(AddEditMedicineActivity.medTime);
Button btn = (Button)findViewById(_id);
btn.setText(Html.fromHtml(medName + " <br/>" + medTime));
}
}
Thanks.

MPMusicPlayerController applicationMusicPlayer hoses iPodMusicPlayer

MPMusicPlayerController applicationMusicPlayer hoses iPodMusicPlayer

I have an application where I would like to use the iPodMusicPlayer to
resume the user's currently selected iPod selection (an audiobook). At
other times I need to play music from the iPod library without disturbing
the state (selection/position) of the iPod player (so the user can pick up
his audiobook outside of my app where he left off listenting in my app).
The obvious way to do this is to play (resume) the user's audiobook using
the iPodMusicPlayer, then when switching to other music use the
applicationMusicPlayer (after first pausing the iPodMusicPlayer). Do
exactly that in exactly that sequence works ok, BUT... any reference to
the applicationMusicPlayer screws up the state of the iPodMusicPlayer from
then on, i.e. I can no longer play or get the duration of the
iPodMusicPlayer. Messages to the iPodMusicPlayer seem to be routed to the
applicationMusicPlayer.
I've adapted a simple example from another developer who had a similar
problem but worked around it by only using the applicationMusicPlayer. In
this test, the reference to the applicationMusicPlayer causes the
iPodMusicPlayer to misbehave. Commenting that line out causes correct
behavior.
Is sequential use of the two music players not supported? If so, that's
not documented anywhere that I can find.
#import "ViewController.h"
#import <MediaPlayer/MediaPlayer.h>
@interface ViewController ()
@property (strong, nonatomic) MPMusicPlayerController *MPPlayer;
- (void)updateProgressView;
@end
@implementation ViewController
@synthesize playPauseButton = _playPauseButton;
@synthesize progressView = _progressView;
@synthesize label = _label;
- (void)viewDidLoad {
[super viewDidLoad];
[[MPMusicPlayerController iPodMusicPlayer]
beginGeneratingPlaybackNotifications];
NSNotificationCenter *notificationCenter = [NSNotificationCenter
defaultCenter];
[notificationCenter addObserver:self
selector:@selector(handle_NowPlayingItemChanged:)
name:MPMusicPlayerControllerNowPlayingItemDidChangeNotification
object:[MPMusicPlayerController
iPodMusicPlayer]];
[notificationCenter addObserver:self
selector:@selector(handle_PlaybackStateChanged:)
name:MPMusicPlayerControllerPlaybackStateDidChangeNotification
object:[MPMusicPlayerController
iPodMusicPlayer]];
[NSTimer scheduledTimerWithTimeInterval:1.0 target:self
selector:@selector(updateProgressView) userInfo:nil repeats:YES];
[self updateProgressView];
}
- (IBAction)playPauseButtonPressed {
// ****** this line (instantiation of the applicationMusicPlayer)
causes the iPodMusicPlayer to misbehave ******
NSLog(@"app player state:%i", [MPMusicPlayerController
applicationMusicPlayer].playbackState);
// ****** commented out the example behaves corectly
NSLog(@"iPod player state:%i", [MPMusicPlayerController
iPodMusicPlayer].playbackState);
if ([[MPMusicPlayerController iPodMusicPlayer] playbackState] ==
MPMusicPlaybackStatePlaying) {
NSLog(@"iPod pause");
[[MPMusicPlayerController iPodMusicPlayer] pause];
} else {
NSLog(@"iPod play");
[[MPMusicPlayerController iPodMusicPlayer] play];
}
}
- (void)handle_NowPlayingItemChanged:(NSNotification *)notification {
NSLog(@"now playing: %@", [[MPMusicPlayerController
iPodMusicPlayer].nowPlayingItem
valueForProperty:MPMediaItemPropertyTitle]);
self.label.text = [[MPMusicPlayerController
iPodMusicPlayer].nowPlayingItem
valueForProperty:MPMediaItemPropertyTitle];
}
- (void)handle_PlaybackStateChanged:(NSNotification *)notification {
NSLog(@"playback state: %i", [MPMusicPlayerController
iPodMusicPlayer].playbackState);
self.playPauseButton.selected = ([[MPMusicPlayerController
iPodMusicPlayer] playbackState] == MPMusicPlaybackStatePlaying);
}
- (void)updateProgressView {
NSTimeInterval currentTime = [[MPMusicPlayerController
iPodMusicPlayer] currentPlaybackTime];
NSNumber *duration = [[MPMusicPlayerController
iPodMusicPlayer].nowPlayingItem
valueForProperty:MPMediaItemPropertyPlaybackDuration];
self.progressView.progress = currentTime / [duration floatValue];
}
@end

javax.crypto.IllegalBlockSizeException: Input length must be multiple of 16 when decrypting with padded cipher

javax.crypto.IllegalBlockSizeException: Input length must be multiple of
16 when decrypting with padded cipher

I am attempting to make a chat program that uses AES encryption but I have
ran into a problem. When I try to run the program, it gives the error that
you can see in the title. I will give you the code for both classes
because it seems that, that is the only way to fully diagnose the problem.
There are many duplicates of this but none seem to answer my specific
problem. Thanks for all your help! Client:
package Chat.Application;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import java.security.spec.AlgorithmParameterSpec;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import sun.misc.BASE64Encoder;
/**
* A simple Swing-based client for the chat server. Graphically it is a frame
* with a text field for entering messages and a textarea to see the whole
* dialog.
*
* The client follows the Chat Protocol which is as follows. When the server
* sends "SUBMITNAME" the client replies with the desired screen name. The
* server will keep sending "SUBMITNAME" requests as long as the client
submits
* screen names that are already in use. When the server sends a line
beginning
* with "NAMEACCEPTED" the client is now allowed to start sending the server
* arbitrary strings to be broadcast to all chatters connected to the server.
* When the server sends a line beginning with "MESSAGE " then all characters
* following this string should be displayed in its message area.
*/
public class ChatClient {
BufferedReader in;
PrintWriter out;
JFrame frame = new JFrame("ELECTRON Chatroom");
JTextField textField = new JTextField(40);
JTextArea messageArea = new JTextArea(8, 40);
Cipher cipher;
// password for encryption
final String strPassword = "1234567890123456";
// put this as key in AES
final SecretKeySpec key = new
SecretKeySpec(strPassword.getBytes(), "AES");
/**
* Constructs the client by laying out the GUI and registering a listener
* with the textfield so that pressing Return in the listener sends the
* textfield contents to the server. Note however that the textfield is
* initially NOT editable, and only becomes editable AFTER the client
* receives the NAMEACCEPTED message from the server.
*/
public ChatClient() {
// Layout GUI
textField.setEditable(false);
messageArea.setEditable(false);
messageArea.setWrapStyleWord(true);
messageArea.setLineWrap(true);
frame.getContentPane().add(textField, "North");
frame.getContentPane().add(new JScrollPane(messageArea), "Center");
frame.pack();
// Add Listeners
textField.addActionListener(new ActionListener() {
/**
* Responds to pressing the enter key in the textfield by sending
* the contents of the text field to the server. Then clear
the text
* area in preparation for the next message.
*/
@Override
public void actionPerformed(ActionEvent e) {
try {
String input = (textField.getText());
//ENCRYPTION
// Parameter specific algorithm
AlgorithmParameterSpec paramSpec = new
IvParameterSpec(strPassword.getBytes());
//Whatever you want to encrypt/decrypt
Cipher cipher =
Cipher.getInstance("AES/CBC/PKCS5Padding");
// You can use ENCRYPT_MODE (ENCRYPTunderscoreMODE)
or DECRYPT_MODE (DECRYPT underscore MODE)
cipher.init(Cipher.ENCRYPT_MODE, key, paramSpec);
// encrypt data
byte[] encrypted = cipher.doFinal(input.getBytes());
// encode data using standard encoder
//String output = new BASE64Encoder().encode(encrypted);
System.out.println("Orginal tring: " + input);
System.out.println("Encrypted string: " + encrypted);
textField.setText("");
} catch (NoSuchAlgorithmException | NoSuchPaddingException
| IllegalBlockSizeException | BadPaddingException |
InvalidKeyException | InvalidAlgorithmParameterException
ex) {
Logger.getLogger(ChatClient.class.getName()).log(Level.SEVERE,
null, ex);
}
}
});
}
/**
* Prompt for and return the address of the server.
*/
private String getServerAddress() {
return JOptionPane.showInputDialog(
frame,
"Enter IP Address of the Server:",
"ELECTRON Chatroom",
JOptionPane.QUESTION_MESSAGE);
}
/**
* Prompt for and return the desired screen name.
*/
private String getName() {
return JOptionPane.showInputDialog(
frame,
"Choose a screen name:",
"Screen name selection",
JOptionPane.PLAIN_MESSAGE);
}
/**
* Connects to the server then enters the processing loop.
*/
private void run() throws IOException, NoSuchAlgorithmException,
NoSuchPaddingException, IllegalBlockSizeException,
BadPaddingException, InvalidKeyException,
InvalidAlgorithmParameterException {
// Make connection and initialize streams
String serverAddress = getServerAddress();
Socket socket = new Socket(serverAddress, 9001);
in = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
out = new PrintWriter(socket.getOutputStream(), true);
// Process all messages from server, according to the protocol.
while (true) {
String line = in.readLine();
if (line.startsWith("SUBMITNAME")) {
out.println(getName());
} else if (line.startsWith("NAMEACCEPTED")) {
textField.setEditable(true);
} else if (line.startsWith("MESSAGE")) {
//DECRYPTION
line = line.substring(8);
System.out.println(line);
// Parameter specific algorithm
AlgorithmParameterSpec paramSpec = new
IvParameterSpec(strPassword.getBytes());
//Whatever you want to encrypt/decrypt
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
// You can use ENCRYPT_MODE (ENCRYPTunderscoreMODE) or
DECRYPT_MODE (DECRYPT underscore MODE)
cipher.init(Cipher.DECRYPT_MODE, key, paramSpec);
byte messageByte[] = cipher.doFinal(line.getBytes());
String message = new String(messageByte, "UTF-8");
messageArea.append(message.substring(8) + "\n");
System.out.println(message);
}
}
}
/**
* Runs the client as an application with a closeable frame.
*/
public static void main(String[] args) throws Exception {
ChatClient client = new ChatClient();
client.frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
client.frame.setVisible(true);
client.run();
}
}
Server:
package Chat.Application;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashSet;
import java.security.GeneralSecurityException;
import java.security.MessageDigest;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import org.omg.PortableInterceptor.SYSTEM_EXCEPTION;
/**
* A multi-threaded chat room server. When a client connects the
* server requests a screen name by sending the client the
* text "SUBMITNAME", and keeps requesting a name until
* a unique one is received. After a client submits a unique
* name, the server acknowledges with "NAMEACCEPTED". Then
* all messages from that client will be broadcast to all other
* clients that have submitted a unique screen name. The
* broadcast messages are prefixed with "MESSAGE ".
*
* Because this is just a teaching example to illustrate a simple
* chat server, there are a few features that have been left out.
* Two are very useful and belong in production code:
*
* 1. The protocol should be enhanced so that the client can
* send clean disconnect messages to the server.
*
* 2. The server should do some logging.
*/
public class ChatServer {
/**
* The port that the server listens on.
*/
private static final int PORT = 9001;
/**
* The set of all names of clients in the chat room. Maintained
* so that we can check that new clients are not registering name
* already in use.
*/
private static HashSet<String> names = new HashSet<String>();
/**
* The set of all the print writers for all the clients. This
* set is kept so we can easily broadcast messages.
*/
private static HashSet<PrintWriter> writers = new HashSet<PrintWriter>();
/**
* The application main method, which just listens on a port and
* spawns handler threads.
*/
public static void main(String[] args) throws Exception {
System.out.println("Chat Server Activated");
ServerSocket listener = new ServerSocket(PORT);
try {
while (true) {
new Handler(listener.accept()).start();
}
} finally {
listener.close();
}
}
/**
* A handler thread class. Handlers are spawned from the listening
* loop and are responsible for a dealing with a single client
* and broadcasting its messages.
*/
private static class Handler extends Thread {
private String name;
private Socket socket;
private BufferedReader in;
private PrintWriter out;
private Integer length;
/**
* Constructs a handler thread, squirreling away the socket.
* All the interesting work is done in the run method.
*/
public Handler(Socket socket) {
this.socket = socket;
}
/**
* Services this thread's client by repeatedly requesting a
* screen name until a unique one has been submitted, then
* acknowledges the name and registers the output stream for
* the client in a global set, then repeatedly gets inputs and
* broadcasts them.
*/
public void run() {
try {
// Create character streams for the socket.
in = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
out = new PrintWriter(socket.getOutputStream(), true);
// Request a name from this client. Keep requesting until
// a name is submitted that is not already used. Note that
// checking for the existence of a name and adding the name
// must be done while locking the set of names.
while (true) {
out.println("SUBMITNAME");
/*Supposed to change anybody who tries to login as Admin
into different name... "Supposed" to....
if (name.equals("Admin")) {
out.println("SUBMITNAME");
return;
}*/
name = in.readLine();
length = name.length();
if (length == 0) {
out.println("SUBMITNAME");
return;
}
if (name == "null") {
out.println("SUBMITNAME");
return;
}
synchronized (names) {
if (!names.contains(name)) {
names.add(name);
break;
}
}
}
// Now that a successful name has been chosen, add the
// socket's print writer to the set of all writers so
// this client can receive broadcast messages.
out.println("NAMEACCEPTED");
//Announces that user is Online
out.println("MESSAGE " + name + " is now Online");
for (PrintWriter writer : writers) {
writer.println("MESSAGE " + name + " is now Online");
}
writers.add(out);
// Accept messages from this client and broadcast them.
// Ignore other clients that cannot be broadcasted to.
while (true) {
String input = in.readLine();
System.out.println(input);
if (input == null) {
return;
}
for (PrintWriter writer : writers) {
writer.println("MESSAGE " + name + ": " + input);
}
}
} catch (IOException e) {
System.out.println(e);
} finally {
// This client is going down! Remove its name and its print
// writer from the sets, and close its socket.
for (PrintWriter writer : writers) {
writer.println("MESSAGE " + name + " is now Offline");
} if (name != null) {
names.remove(name);
}
if (out != null) {
writers.remove(out);
}
try {
socket.close();
} catch (IOException e) {
}
}
}
}
}
Thanks so much for all your help in saving a complete noob at programming!
-Silver