الأحد، 5 يناير 2014

Unable to send data from my server to client

I made a simple chat program where sending data from MyClient to MyServer is working, but when sending data from MyServer to MyClient is not working. So where I'm making mistake?

//This is MyServer program

import java.io.*;

import java.net.*;

public class MyServer{

ServerSocket ss; Socket s; DataInputStream din; DataOutputStream dout;

public MyServer(){

try{ System.out.println("Server START......"); ss=new ServerSocket(9000); s=ss.accept(); System.out.println("Client Connected....."); din=new DataInputStream(s.getInputStream()); dout=new DataOutputStream(s.getOutputStream()); chat(); }catch(Exception e){ System.out.println(e);}

}

public void chat()throws IOException{

String str=" "; do{ str=din.readUTF(); System.out.println("Client Message: "+str); dout.writeUTF("I have recieved ur message:"+str); dout.flush(); }while(!str.equals("stop"));

}

public static void main(String arg[]){

new MyServer();}

}

//This is MyClient program

import java.io.*;

import java.net.*;

public class MyClient{

Socket s; DataInputStream din; DataOutputStream dout;

public MyClient(){

try{ s=new Socket("localhost",9000); System.out.println(s); din=new DataInputStream(s.getInputStream()); dout=new DataOutputStream(s.getOutputStream()); chat(); }catch(Exception e){ System.out.println(e);}

}

public void chat()throws IOException{

BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); String s1;do{ s1=br.readLine(); dout.writeUTF(s1); dout.flush(); System.out.println("Server Message: "+din.readUTF()); }while(!s1.equals("stop"));

}

public static void main(String arg[]){

new MyClient();}

}


View the original article here

Simple SQL query with MAX()

I'm new to SQL and I need some help with this task:

Database schema:

Comic(no primary key NOT NULL, title, pages, publisher)PoweredPerson(alias primary key NOT NULL, firstname NOT NULL, lastname, evilness_level)SuperHero(alias primary key?PoweredPerson NOT NULL,cape)SuperVillain(alias primary key?PoweredPerson NOT NULL)FightIn(comic primary key? Comic NOT NULL,hero primary key? SuperHero NOT NULL,villain primary key? SuperVillain NOT NULL)

Now I shall declare a SQL query which gives the first and last names of those powered person(s) that fought the most enemies in just one comic.

My solution is this:

SELECT firstname,lastnameFROM fightIn f JOIN poweredperson pON f.hero = p.alias OR f.villain= p.aliasGROUP BY comic,aliasHAVING COUNT(alias)=(SELECT COUNT(alias) FROM fightIn f JOIN poweredperson p ON f.hero = p.alias OR f.villain = p.alias GROUP BY comic,alias ORDER BY COUNT(hero) DESC LIMIT 1)

I want to know if my solution is correct and in case it is, whether there is a much smarter and shorter way to solve this.

Thanks in advance =)


View the original article here

Microsoft 2013 Crashes from Vb.net Program

I have a vb.net program that the user is able to create a word file from a text file, open and edit it, and save their changes back to a web server.

When the user creates the file and uploads it everything works fine. The issue happens when they open any document. When the user is done editing and saves the file then closes out word, Office throw a not responding message and forces them to close the program.

This only happens in Microsoft Office 2013.

Below is the code I am using:

Private Sub oWord_DocumentBeforeClose(ByVal Doc As Microsoft.Office.Interop.Word.Document, ByRef Cancel As Boolean) Handles oWord.DocumentBeforeClose 'Cancel = True oWord.ActiveDocument.Close() 'oWord.Quit() oWord.Application.Quit() Try Dim filepath As String 'Dim url As String = Server & "php/PD026U.php" Dim url As String = Server & LibName & "/PD026U.pgm" 'Dim url As String = "http://192.168.95.1:83/file.php" filepath = strCommonAppData & IO.Path.GetFileName(ORGDoc) Dim request As HttpWebRequest = DirectCast(HttpWebRequest.Create(url), HttpWebRequest) request.PreAuthenticate = True request.AllowWriteStreamBuffering = True request.KeepAlive = False request.ProtocolVersion = HttpVersion.Version10 Dim boundary As String = System.Guid.NewGuid().ToString() request.Accept = "text/html , application/xhtml+xml, */*" request.AutomaticDecompression = DecompressionMethods.GZip request.ContentType = String.Format("multipart/form-data; boundary={0}", boundary) request.Method = "POST" request.Credentials = New System.Net.NetworkCredential("ehavermale", "ernie1") ' Build Contents for Post Dim header As String = String.Format("--{0}", boundary) Dim footer As String = header & "--" Dim contents As New System.Text.StringBuilder() Dim FileHead As New System.Text.StringBuilder() ' file FileHead.AppendLine(header) FileHead.AppendLine(String.Format("Content-Disposition: form-data; name=""upfile""; filename=""{0}""", IO.Path.GetFileName(filepath))) FileHead.AppendLine("Content-Type: application/msword") FileHead.AppendLine() contents.AppendLine(vbCrLf & header) contents.AppendLine("Content-Disposition: form-data; name=""task""") contents.AppendLine() contents.AppendLine("upload") contents.AppendLine(header) contents.AppendLine("Content-Disposition: form-data; name=""INCOMP""") contents.AppendLine() contents.AppendLine(INCOMP) contents.AppendLine(header) contents.AppendLine("Content-Disposition: form-data; name=""ProgLib""") contents.AppendLine() contents.AppendLine(LibName) contents.AppendLine(header) contents.AppendLine("Content-Disposition: form-data; name=""INCNUM""") contents.AppendLine() contents.AppendLine(INNUM) contents.AppendLine(header) contents.AppendLine("Content-Disposition: form-data; name=""ToPath""") contents.AppendLine() contents.AppendLine(ToPath) ' Footer contents.AppendLine(footer) ' This is sent to the Post Dim bytes As Byte() = System.Text.Encoding.UTF8.GetBytes(contents.ToString()) Dim FileBytes As Byte() = System.Text.Encoding.UTF8.GetBytes(FileHead.ToString()) request.ContentLength = bytes.Length + FileHead.Length + New FileInfo(filepath).Length Using requestStream As Stream = request.GetRequestStream() requestStream.Write(FileBytes, 0, FileBytes.Length) Using fileStream As New IO.FileStream(filepath, IO.FileMode.Open, IO.FileAccess.Read) Dim buffer(4096) As Byte Dim bytesRead As Int32 = fileStream.Read(buffer, 0, buffer.Length) Do While (bytesRead > 0) requestStream.Write(buffer, 0, bytesRead) bytesRead = fileStream.Read(buffer, 0, buffer.Length) Loop End Using requestStream.Write(bytes, 0, bytes.Length) requestStream.Flush() requestStream.Close() Using response As WebResponse = request.GetResponse() Using reader As New StreamReader(response.GetResponseStream()) Dim strResponseData As String = reader.ReadToEnd() TextBox1.Text = strResponseData End Using End Using End Using Catch ex As Exception MsgBox("There was an Error on File Upload Please Contact you Administrator for assistance : " & ex.ToString()) End Try Me.Close()End Sub

I have tried changing how I close my word program, the order I close the document and word and tried to keep word open altogether and nothing I have tried works.

Is there an issue with Office 2013 and beforeclose or programmatically closing a document?


View the original article here

modular and flexible programming

I am trying to learn how to make a modular program. So what I want to do is read an array of integers. Main:

#include #include #define NMAX 10void read (int *n, int a[NMAX]);int main(){ int n, a[NMAX]; read(&n,a); return 0;}

Then I saved this file 'read.cpp':

#include #include #define NMAX 10void read (int *n, int a[NMAX]){ int i; printf("dati n:\n"); scanf("%d",n); for (i=1;i<=*n;i++) { printf("a[%d]= ",i); scanf("%d\n",&a[i]); }}

read.cpp compiles succesfully, but when I compile the main function I get the error "no reference to read".


View the original article here

Copying Directory and sub directory

The problem is that as I wrote in the comment, you are constructing the file info with the full path as opposed to relative path as you wish to have.

You could work this issue around by:

#include #include #include #include #include int main(){ QDir targetDir1("/home/brett/sweetback"); targetDir1.mkdir("sweetassurfwear"); QDir targetDir("/usr/local"); targetDir.setFilter(QDir::NoDotAndDotDot| QDir::Dirs | QDir::Files); QDirIterator it(targetDir, QDirIterator::Subdirectories); while (it.hasNext()) { it.next(); QFileInfo Info = it.fileInfo(); QString testName = Info.fileName(); QString testPath = Info.absoluteFilePath().mid(it.path().size()); qDebug() << "TEST:" << testPath; if(Info.isDir()) { // QString cpd = "/home/brett/sweetback/sweetassurfwear/"; // targetDir.mkdir(cpd+testName); QString dirname = Info.filePath(); } } return 0;}TEMPLATE = appTARGET = mainQT = coreSOURCES += main.cppqmake && make && ./main

Note that, you do not really need to build a file info based on the path since the diriterator can return that directly.

Disclaimer: this is just a workaround to get going. There must be a nicer solution.


View the original article here

consistent hashing vs. rendezvous (HRW) hashing - what are the tradeoffs?

There is a lot available on the Net about consistent hashing, and implementations in several languages available. The Wikipedia entry for the topic references another algorithm with the same goals:

Rendezvous Hashing

This algorithm seems simpler, and doesn't need the addition of replicas/virtuals around the ring to deal with uneven loading issues. As the article mentions, it appears to run in O(n) which would be an issue for large n, but references a paper stating it can be structured to run in O(log n).

My question for people with experience in this area is, why would one choose consistent hashing over HRW, or the reverse? Are there use cases where one of these solutions is the better choice?

Many thanks.


View the original article here

Check the Errorlevel value and process the if command

The "problem" with your code is that when the parser reach that line, the %errorlevel% variable is replaced with its value, and then the line is executed. So, any change to the value of the variable is not seen. The "usual" way of handling this cases is enabling delayed expansion and change the %errorlevel% sintax with !errorlevel! to indicate the parser that the value will change and need to be retrieved at execution time.

But, in this case, as you have the requirement of a "one liner", change the if test to

if errorlevel 1 (echo "SQL Not Installed") else (echo "SQL Installed")

A standard construct to check for errorlevel without reading the variable value.

You have also the posibility to code it as

reg query .... && echo Installed || echo Not Installed

This executes the reg command (with all your parameters, of course). On success, the command after && is executed. On failure the command after || is executed.


View the original article here

Objectify Ruby Hashes from/to JSON API

I just released a ruby gem to use some JSON over HTTP API:

https://github.com/solyaris/blomming_api

My naif ruby code just convert complex/nested JSON data structures returned by API endpoints (json_data) to ruby Hashes ( hash_data), in a flat one-to-one transaltion (JSON to ruby hash and viceversa). Tat's fine, but...

I would like a programming interface more "high level". Maybe instatiating a class Resource for every endpoint, but I'm confused about a smart implementation.

Let me explain with an abstract code.

Let say I have a complex/nested JSON received by an API, usually an Array of Hashes, recursively nested as here below (imagination example):

json_data = '[{ "commute": { "minutes": 0, "startTime": "Wed May 06 22:14:12 EDT 2014", "locations": [ { "latitude": "40.4220061", "longitude": "40.4220061" }, { "latitude": "40.4989909", "longitude": "40.48989805" }, { "latitude": "40.4111169", "longitude": "40.42222869" } ] }},{ "commute": { "minutes": 2, "startTime": "Wed May 28 20:14:12 EDT 2014", "locations": [ { "latitude": "43.4220063", "longitude": "43.4220063" } ] }}]'

At the moment what I do, when I receive a similar JSON form an API is just:

# from JSON to hash hash_data = JSON.load json_data# and to assign values:coords = hash_data.first["commute"]["locations"].lastcoords["longitude"] = "40.00" # was "40.4111169"coords["latitude"] = "41.00" # was "40.42222869"

that's ok, but with awfull/confusing syntax. Instead, I probably would enjoy something like:

# create object Resource from hashres = Resource.create( hash_data )# ... some processing# assign a "nested" variables: longitude, latitude of object: rescoords = res.first.commute.locations.lastcoords.longitude = "40.00" # was "40.4111169"coords.latitude = "41.00" # was "40.42222869"# ... some processing# convert modified object: res into an hash again:modified_hash = res.save# and probably at least I'll recover to to JSON:modified_json = JSON.dump modified_hash

I read intresting posts: http://pullmonkey.com/2008/01/06/convert-a-ruby-hash-into-a-class-object/ http://www.goodercode.com/wp/convert-your-hash-keys-to-object-properties-in-ruby/

and copying Kerry Wilson' code, I sketched the implementation here below:

class Resource def self.create (hash) new ( hash) end def initialize ( hash) hash.to_obj end def save # or to_hash() # todo! HELP! (see later) endendclass ::Hash # add keys to hash def to_obj self.each do |k,v| v.to_obj if v.kind_of? Hash v.to_obj if v.kind_of? Array k=k.gsub(/\.|\s|-|\/|\'/, '_').downcase.to_sym ## create and initialize an instance variable for this key/value pair self.instance_variable_set("@#{k}", v) ## create the getter that returns the instance variable self.class.send(:define_method, k, proc{self.instance_variable_get("@#{k}")}) ## create the setter that sets the instance variable self.class.send(:define_method, "#{k}=", proc{|v| self.instance_variable_set("@#{k}", v)}) end return self endendclass ::Array def to_obj self.map { |v| v.to_obj } end end#------------------------------------------------------------

BTW, I studied a bit ActiveResource project (was part of Rails if I well understood). ARes could be great for my scope but the problem is ARes have a bit too "strict" presumption of full REST APIs... In my case server API are not completely RESTfull in the way ARes would expect... All in all I would do a lot of work to subclass / modify ARes behaviours and at the moment I discarded the idea to use ActiveResource

QUESTIONS:

someone could help me to realize the save() method on the above code (I'm really bad with recursive methods... :-( ) ?

Does exist some gem that to the above sketched hash_to_object() and object_to_hash() translation ?

What do you think about that "automatic" objectifying of an "arbitrary" hash coming froma JSON over http APIs ? I mean: I see the great pro that I do not need to client-side static-wire data structures, allowing to be flexible to possible server side variations. But on the other hand, doing this automatic objectify, there is a possible cons of a side effect to allow security issues ... like malicious JSON injection (possible untrasted communication net ...)

What do you think about all this ? Any suggestion is welcome! Sorry for my long post and my ruby language metaprogramming azards :-)

giorgio


View the original article here

My C code compiles successfully in Eclipse but it does not produce a .exe file for execution

Whilst my code compiles successfully, the .exe files is not produced. For this program I use shared libraries. The whole program contains 2 .c files and .h. I have tried using the include option in the settings without any luck. I have also tried splitting the client from the function file and the header, storing them in different projects. And after I used the include it told me "Unresolved Inclusion". Does anyone have any idea why the compiler isn't making the .exe file?


View the original article here

Cassandra row update check in a table

Is there any way to check whether a row in a table has been modified or not in Cassandra. I don't want to compare the date before and after updating row in table. After Update operation I need to verify the query executed properly or not using python scripts. I am using Cassandra Driver for python.


View the original article here

How to perform innner Join on Five Tables using Linq

Are the types of your expression variables the same? E.g.: are c.GroupId and g.GroupId both int or is one of them of type byte?

The types of the variables in your expressions must be of the same type if you want to compare them with each other.


View the original article here

How to draw letter tiles

Hi I need to draw letter tiles for the Android version of my word game. Each tile will be an instance of the Letter class etc.

What's the best way to handle the drawing so that I can add/edit textures, font sizes, rounded corners easily in the future?

enter image description here


View the original article here

node-gcm send message only 1 device?

I use node-gcm to send message to Android devices, everything work fine when send message to 1 device.

req.addListener('data', function(chunk) { data += chunk; });req.addListener('end', function() { var message = new gcm.Message({ collapseKey: 'demo', delayWhileIdle: true, timeToLive: 3, data: { price: 'message' } }); message.collapseKey = 'demo'; message.delayWhileIdle = true; message.timeToLive = 3; getGcmIdFromDB(ka,function(dat){ var obj = JSON.parse(JSON.stringify(dat)); var items = Object.keys(obj); items.forEach(function(item) { registrationIds.push(obj[item].gcm_regid); sender.send(message, registrationIds, 1, function (err, result) { console.log(result); }); }); });

My script successfully send message to a client Android device,but when I send message again to another device the message still sent to the first device? Maybe my code doesn't refresh, my node-gcm results this log.

{ multicast_id: 7032530745780722000, success: 3, failure: 0, canonical_ids: 0, results: [ { message_id: '0:1388475224605981%f11e78b0002efde3' } { message_id: '0:1388475224605981%f11e78b0002efde3' } { message_id: '0:1388475224605981%f11e78b0002efde3' } ] }

Please help?


View the original article here

Getting The ORDER BY clause is invalid in views, unless TOP or FOR XML is also specified

I have this SQL Server stored procedure where I am returning an XML type output, however before that I will be updating the corresponding records as well.

ALTER PROCEDURE [dbo].[GetPublishedData](@PublicationURL varchar(100),@Number int) AS IF (@Number = 0) BEGIN BEGIN TRANSACTION TRAN2 SELECT 1 AS Tag, NULL AS Parent, NULL AS [root!1!], NULL AS [Item!2!Id], NULL AS [Item!2!Action], NULL AS [Item!2!Pub_Id], NULL AS [Item!2!Item_Id], NULL AS [Item!2!Item_type], NULL AS [Item!2!Last_Published_Date], NULL AS [Item!2!Url], NULL AS [Item!2!Schema_Id] UNION SELECT 2, 1, '1', T.ID, T.ACTION, T.Pub_Id, T.Item_Id, T.ITEM_TYPE, T.LAST_PUBLISHED_DATE, T.URL, T.SCHEMA_ID FROM DBO.AUTN_ITEMS T WHERE FLAG = 0 AND ACTION IN ('ADD','UPD') AND URL LIKE @PublicationURL + '%' ORDER BY [Item!2!Last_Published_Date] ASC FOR XML EXPLICIT /*Update the FLAG with 1*/ UPDATE DBO.AUTN_ITEMS SET FLAG = 1 WHERE ID IN (SELECT ID FROM DBO.AUTN_ITEMS AT WHERE AT.FLAG = 0 AND ACTION IN ('ADD','UPD') AND AT.URL LIKE @PublicationURL + '%' ORDER BY AT.LAST_PUBLISHED_DATE ASC) COMMIT TRANSACTION TRAN2 ENDRETURN

I have two questions:

How to use Order by in my Update SQLIs there better way to write above query where I can simply pass the transaction id for updating the records

Please suggest!!


View the original article here

In java how to fix HTTP error 416 Requested Range Not Satisfiable? (While downloading web content from a web page)

I am trying to download the html content of a web page for e.g http://www.jobstreet.com.sg/ I am getting the 416 status. I found one solution which correctly improves the status code as 200 but still not downloading the proper content. I am very close but missing something. Please help.

Code with 416 status:

public static void main(String[] args) { String URL="http://www.jobstreet.com.sg/"; HttpClient client = new org.apache.commons.httpclient.HttpClient(); org.apache.commons.httpclient.methods.GetMethod method = new org.apache.commons.httpclient.methods.GetMethod(URL); client.getHttpConnectionManager().getParams().setConnectionTimeout(AppConfig.CONNECTION_TIMEOUT); client.getHttpConnectionManager().getParams().setSoTimeout(AppConfig.READ_DATA_TIMEOUT); String html = null; InputStream ios = null; try { int statusCode = client.executeMethod(method); ios = method.getResponseBodyAsStream(); html = IOUtils.toString(ios, "utf-8"); System.out.println(statusCode); }catch (Exception e) { e.printStackTrace(); } finally { if(ios!=null) { try {ios.close();} catch (IOException e) {e.printStackTrace();} } if(method!=null) method.releaseConnection(); } System.out.println(html);}

Code with 200 status (but htmlContent is not proper):

public static void main(String[] args) {

String URL="http://www.jobstreet.com.sg/"; HttpClient client = new org.apache.commons.httpclient.HttpClient(); org.apache.commons.httpclient.methods.GetMethod method = new org.apache.commons.httpclient.methods.GetMethod(URL); client.getHttpConnectionManager().getParams().setConnectionTimeout(AppConfig.CONNECTION_TIMEOUT); client.getHttpConnectionManager().getParams().setSoTimeout(AppConfig.READ_DATA_TIMEOUT); String html = null; InputStream ios = null; try { int statusCode = client.executeMethod(method); if(statusCode == HttpStatus.SC_REQUESTED_RANGE_NOT_SATISFIABLE) { method.setRequestHeader("User-Agent", "Mozilla/5.0"); method.setRequestHeader("Accept-Ranges", "bytes=100-1500"); statusCode = client.executeMethod(method); } ios = method.getResponseBodyAsStream(); html = IOUtils.toString(ios, "utf-8"); System.out.println(statusCode); }catch (Exception e) { e.printStackTrace(); } finally { if(ios!=null) { try {ios.close();} catch (IOException e) {e.printStackTrace();} } if(method!=null) method.releaseConnection(); } System.out.println(html);}

View the original article here

How to profile a bash shell script?

Note : This work on recent GNU/Linux kernels.

For this kind of jobs, I wrote elap.bash (V2), to be sourced by the following syntax:

source elap.bash-v2

or

. elap.bash-v2 init

(See comments for full syntax)

So you could simply add this line at top of your script:

. elap.bash-v2 trap2

Little sample:

#!/bin/bash. elap.bash-v2 trapfor ((i=3;i--;));do sleep .1;doneelapCalc2elapShowTotal \\e[1mfirst total\\e[0mfor ((i=2;i--;))do tar -cf /tmp/test.tar -C / bin gzip /tmp/test.tar rm /tmp/test.tar.gzdonetrap -- debugelapTotal \\e[1mtotal time\\e[0m

Do render on my host:

0.000947481 Starting 0.000796900 ((i=3)) 0.000696956 ((i--)) 0.101969242 sleep .1 0.000812478 ((1)) 0.000755067 ((i--)) 0.103693305 sleep .1 0.000730482 ((1)) 0.000660360 ((i--)) 0.103565001 sleep .1 0.000719516 ((1)) 0.000671325 ((i--)) 0.000754856 elapCalc2 0.316018113 first total 0.000754787 elapShowTotal \e[1mfirst total\e[0m 0.000711275 ((i=2)) 0.000683408 ((i--)) 0.075673816 tar -cf /tmp/test.tar -C / bin 0.596389329 gzip /tmp/test.tar 0.006565188 rm /tmp/test.tar.gz 0.000830217 ((1)) 0.000759466 ((i--)) 0.024783966 tar -cf /tmp/test.tar -C / bin 0.604119903 gzip /tmp/test.tar 0.005172940 rm /tmp/test.tar.gz 0.000952299 ((1)) 0.000827421 ((i--)) 1.635788924 total time 1.636657204 EXIT

Using trap2 instead of trap as argument to source command:

#!/bin/bash. elap.bash-v2 trap2...

Will render two colons last command and total:

0.000894541 0.000894541 Starting 0.001306122 0.002200663 ((i=3)) 0.001929397 0.004130060 ((i--)) 0.103035812 0.107165872 sleep .1 0.000875613 0.108041485 ((1)) 0.000813872 0.108855357 ((i--)) 0.104954517 0.213809874 sleep .1 0.000900617 0.214710491 ((1)) 0.000842159 0.215552650 ((i--)) 0.104846890 0.320399540 sleep .1 0.000899082 0.321298622 ((1)) 0.000811708 0.322110330 ((i--)) 0.000879455 0.322989785 elapCalc2 0.322989785 first total 0.000906692 0.323896477 elapShowTotal \e[1mfirst total\e[0m 0.000820089 0.324716566 ((i=2)) 0.000773782 0.325490348 ((i--)) 0.024752613 0.350242961 tar -cf /tmp/test.tar -C / bin 0.596199363 0.946442324 gzip /tmp/test.tar 0.003007128 0.949449452 rm /tmp/test.tar.gz 0.000791452 0.950240904 ((1)) 0.000779371 0.951020275 ((i--)) 0.030519702 0.981539977 tar -cf /tmp/test.tar -C / bin 0.584155405 1.565695382 gzip /tmp/test.tar 0.003058674 1.568754056 rm /tmp/test.tar.gz 0.000955093 1.569709149 ((1)) 0.000919964 1.570629113 ((i--)) 1.571516599 total time 0.001723708 1.572352821 EXIT

View the original article here

How can I submit value to javascript without submitting onclick

How can I submit an input value to a javascript function without submitting my onclick button? Here is the code:

I want to be able to submit the value to a javascript here is the code:

function myFunction() { var x = document.getElementById("demo").value;

Basically i want to submit my input value without having my submit button. Here is the code:

How can I submit my input without having a submit button?


View the original article here

How can I disable Omnifaces facesviews ? Or at least get rid of that exception?

I'm currently getting in touch with a part of our application that have been developped by a team that is now defunct, and encountering strange issues.

This application is deployed as an EAR, containing an EJB-JAR and three distinct web-applications (one for SOAP services, one for web UI, and so on, ...).

When trying to deploy that application, i'm having constant deploy errors like the following

[#|2013-12-31T11:05:45.236+0100|SEVERE|glassfish3.1.1|org.apache.catalina.core.ContainerBase|_ThreadID=18;_ThreadName=Thread-2;|ContainerBase.addChild: start: org.apache.catalina.LifecycleException: java.lang.IllegalArgumentException: javax.servlet.ServletException: com.sun.enterprise.container.common.spi.util.InjectionException: Error creating managed object for class: class org.omnifaces.facesviews.FacesViewsInitializerListener at org.apache.catalina.core.StandardContext.start(StandardContext.java:5332) at com.sun.enterprise.web.WebModule.start(WebModule.java:498) at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:917) at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:901) at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:733) at com.sun.enterprise.web.WebContainer.loadWebModule(WebContainer.java:2000) at com.sun.enterprise.web.WebContainer.loadWebModule(WebContainer.java:1651) at com.sun.enterprise.web.WebApplication.start(WebApplication.java:109) at org.glassfish.internal.data.EngineRef.start(EngineRef.java:130) at org.glassfish.internal.data.ModuleInfo.start(ModuleInfo.java:269) at org.glassfish.internal.data.ApplicationInfo.start(ApplicationInfo.java:294) at com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:462) at com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:240) at org.glassfish.deployment.admin.DeployCommand.execute(DeployCommand.java:382) at com.sun.enterprise.v3.admin.CommandRunnerImpl$1.execute(CommandRunnerImpl.java:355) at com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(CommandRunnerImpl.java:370) at com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(CommandRunnerImpl.java:1064) at com.sun.enterprise.v3.admin.CommandRunnerImpl.access$1200(CommandRunnerImpl.java:96) at com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(CommandRunnerImpl.java:1244) at com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(CommandRunnerImpl.java:1232) at com.sun.enterprise.v3.admin.AdminAdapter.doCommand(AdminAdapter.java:459) at com.sun.enterprise.v3.admin.AdminAdapter.service(AdminAdapter.java:209) at com.sun.grizzly.tcp.http11.GrizzlyAdapter.service(GrizzlyAdapter.java:168) at com.sun.enterprise.v3.server.HK2Dispatcher.dispath(HK2Dispatcher.java:117) at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:238) at com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:828) at com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:725) at com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:1019) at com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:225) at com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:137) at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:104) at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:90) at com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:79) at com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:54) at com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:59) at com.sun.grizzly.ContextTask.run(ContextTask.java:71) at com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:532) at com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:513) at java.lang.Thread.run(Thread.java:662)Caused by: java.lang.IllegalArgumentException: javax.servlet.ServletException: com.sun.enterprise.container.common.spi.util.InjectionException: Error creating managed object for class: class org.omnifaces.facesviews.FacesViewsInitializerListener at org.apache.catalina.core.StandardContext.addListener(StandardContext.java:2743) at org.apache.catalina.core.StandardContext.addApplicationListener(StandardContext.java:1966) at com.sun.enterprise.web.TomcatDeploymentConfig.configureApplicationListener(TomcatDeploymentConfig.java:235) at com.sun.enterprise.web.TomcatDeploymentConfig.configureWebModule(TomcatDeploymentConfig.java:94) at com.sun.enterprise.web.WebModuleContextConfig.start(WebModuleContextConfig.java:274) at com.sun.enterprise.web.WebModuleContextConfig.lifecycleEvent(WebModuleContextConfig.java:172) at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:149) at org.apache.catalina.core.StandardContext.start(StandardContext.java:5329) ... 38 moreCaused by: javax.servlet.ServletException: com.sun.enterprise.container.common.spi.util.InjectionException: Error creating managed object for class: class org.omnifaces.facesviews.FacesViewsInitializerListener at org.apache.catalina.core.StandardContext.createListener(StandardContext.java:2853) at org.apache.catalina.core.StandardContext.loadListener(StandardContext.java:4806) at com.sun.enterprise.web.WebModule.loadListener(WebModule.java:1599) at org.apache.catalina.core.StandardContext.addListener(StandardContext.java:2740) ... 45 moreCaused by: com.sun.enterprise.container.common.spi.util.InjectionException: Error creating managed object for class: class org.omnifaces.facesviews.FacesViewsInitializerListener at com.sun.enterprise.container.common.impl.util.InjectionManagerImpl.createManagedObject(InjectionManagerImpl.java:315) at com.sun.enterprise.web.WebContainer.createListenerInstance(WebContainer.java:749) at com.sun.enterprise.web.WebModule.createListenerInstance(WebModule.java:1987) at org.apache.catalina.core.StandardContext.createListener(StandardContext.java:2851) ... 48 moreCaused by: java.lang.NullPointerException at com.sun.enterprise.container.common.impl.managedbean.ManagedBeanManagerImpl.createManagedBean(ManagedBeanManagerImpl.java:477) at com.sun.enterprise.container.common.impl.managedbean.ManagedBeanManagerImpl.createManagedBean(ManagedBeanManagerImpl.java:420) at com.sun.enterprise.container.common.impl.util.InjectionManagerImpl.createManagedObject(InjectionManagerImpl.java:299) ... 51 more

Application is deployed on a Glassfish 3.1.1 and that exception totally prevents the EAR from being deployed. How can i fix it ?

I've read this very component has for sole role to allow Omnifaces FacesView to work. But we don't use that feature. So how can I totally p^revent it from being loaded ?.


View the original article here

Sunlight Foundation json data - how to extract the values

up vote 0 down vote favorite

I'm experimenting with Sunlight Foundation Capitol words API and Webpy.

I'm able to retrieve the data from sunlight and store the results in a Webpy variable ($data) which is pass to the template.

It is possible to pass a templetor (webpy template system) variable to a Javascript and extract the results values?

I found a couple of JSON lectures and videos which I tried but so far can make it happen. I think that I might need to write the data into a JSON file before I could use it but at the same time I question myself because the results from sunlight are already formatted as JSON.

Here are two objects from the results: It would be a great help if some one could suggest how to manage this JSON with a Javascript or provide some options. Thanks in advance

{ "num_found": 78682, "results": [ { "speaker_state": "OH", "speaker_first": "Tim", "congress": 110, "title": "30-SOMETHING WORKING GROUP", "origin_url": "http://origin.www.gpo.gov/fdsys/pkg/CREC-2007-03-26/html/CREC-2007-03-26-pt1-PgH3071-2.htm", "number": 52, "order": 13, "volume": 153, "chamber": "House", "session": 1, "id": "CREC-2007-03-26-pt1-PgH3071-2.chunk13", "speaking": [ "Civil war." ], "capitolwords_url": "http://capitolwords.org/date/2007/03/26/H3071-2_30-something-working-group/", "speaker_party": "D", "date": "2007-03-26", "bills": null, "bioguide_id": "R000577", "pages": "H3071-H3078", "speaker_last": "Ryan", "speaker_raw": "mr. ryan of ohio" }, { "speaker_state": null, "speaker_first": null, "congress": 110, "title": "[Filed on January 4, 2007]", "origin_url": "http://origin.www.gpo.gov/fdsys/pkg/CREC-2007-01-05/html/CREC-2007-01-05-pt1-PgH110.htm", "number": 2, "order": 57, "volume": 153, "chamber": "House", "session": 1, "id": "CREC-2007-01-05-pt1-PgH110.chunk57", "speaking": [ "Service and the Naval Transport Service) during World War II; " ], "capitolwords_url": "http://capitolwords.org/date/2007/01/05/H110_filed-on-january-4-2007/", "speaker_party": null, "date": "2007-01-05", "bills": null, "bioguide_id": null, "pages": "H110-H123", "speaker_last": null, "speaker_raw": "recorder" }]

}


View the original article here

How to log all Django form validation errors?

In my Django application, I have a forms.py file in which I define loads of classes corresponding to form input screens. Each of these classes does some validation either in that attribute/field specific _clean() functions or in the overall clean() function for the form class. If validation fails in any of these clean() functions, I raise an error like this:

raise forms.ValidationError('Invalid value dude!!')

When such an error is raised, the application catches the error and displays it on the form for the user.

I also have a logger defined at the top of this file like this:

import logginglogger = logging.getLogger(__name__)

Now, in addition to reporting to the user the ValidationErrors, I would like to catch them and log them as errors. Is there some generic and elegant way I can get the logger to log all such errors without changing any other behavior that affects the application's user?


View the original article here

Media screen query not working in iPhone

It looks like you simply have to put the iPhone-5 rule below the iPhone-4 one. Otherwise the css iPhone-4 rule with override the iPhone-5 one by your max-width definition. You have them backwards right now.

And don't use !important here, it will likely mess up the cascading styles. If you have !important on your iphone 4 rule that's overriding the one you have here even in the right 4 then 5 order.

And are you sure that you have your meta viewport set in the ?

To address the pixel density you need to make sure you have:


View the original article here

how to check input boxes according to values

You can iterate through the array of values, then check each input based on the product ID.

list.forEach(function(item) { $('#product_'+ item).prop('checked', true);});

.forEach() documentation

.prop() documentation


View the original article here

Business rule fails to clear field value

I followed this tutorial to copy address field values. It works nicely but I got to thinking how can I make this better for my users..should have left well enough alone I know.

So I was thinking what if they selected the check box to copy the address1 fields by mistake out of habit. So I thought that it would be easy enough to just create a second business rule to clear the address2 fields.

Well the clear address rule is not working at all and yes it is activated. I mimicked the tutorial creating another custom field "clear address" then set my business rule that if that field has a value of true the set address2 fields value to "".

Doh it won't accept an empty value. Tried all sorts of gyrations no go. So I created another custom field (this is all in a development vm sandbox) called emptytext. It is a 1 char text field.

I then went back to my business rule and changed it to set the address2 fields to the emptytext field and that didn't work.

Ohh yes the field probably has to be on the form. So I put it on the form and hid it.

Now everything works but is this really the best way to set a text fields value back to empty?

Thank You


View the original article here

Is it possible to use a hierarchical database such BDB for Rsyslog messages?

I am currently using PostgreSQL in order to store Rsyslog messages. The problem is that querying the messages from the Syslog database in the PostgreSQL backend gets too slow as the number of messages increases.

I know that a hierarchical database performs much faster than a relational database. So my question is if it is possible to use one such database backend (BDB or hdb for example) for Rsyslog messages? I did not find anything on the Internet. What about LDAP (relying on BDB)?

If not, do you have any other suggestion to improve the performance of my system?

Details: OS: Ubuntu: Ubuntu Server 12.04 PostgreSQL: 9.1 Rsyslog: rsyslogd 5.8.6


View the original article here

How to Upper Serbian letters, Č,Ć,Š,Đ,Ž in PHP

I got a problem to make upper letters in php.

I tried this function:

function strtouper_srbija($string) { $low=array("?" => "?", "?" => "?", "?" => "?","?" => "?","?" => "?"); return strtoupper(strtr($string,$low)); }

and tried to use with some POST data from html page,text filed,but no succes,so if you have solutions,will be fine..

Also, I found solution with CSS, with text-transform: uppercase;, but will be fine to have PHP example.


View the original article here

Adding an IF statement

I wanted to add an if statement to this code that says..

IF i click this button , it will check if the ListU.SelectedValue is empty or not , and if it is empty , a messagebox saying "please pick a name before continuing" , and if it is not empty , the code then runs.

how do i do that?

this is the code for the button click. (i know , my code needs some parameter , we can ignore that for the moment)

private void button4_Click(object sender, EventArgs e){ //update code// SqlConnection conn = new SqlConnection(); conn.ConnectionString = "Data Source=PEWPEWDIEPIE\\SQLEXPRESS;Initial Catalog=master;Integrated Security=True"; conn.Open(); SqlDataAdapter daCount = new SqlDataAdapter("select iCount from ComDet where cName = @cName", conn); daCount.SelectCommand.Parameters.Add("@cName", SqlDbType.VarChar).Value = ListU.SelectedValue; DataTable dtC = new DataTable(); daCount.Fill(dtC); DataRow firstRow = dtC.Rows[0]; string x = firstRow["iCount"].ToString(); int y = Int32.Parse(x); int z = y + 1; SqlCommand cmdC = conn.CreateCommand(); cmdC.CommandText = "Update ComDet set iCount = " + z + ", ViewTime = '" + lblTime.Text + "', LastView = '" + txtUser2.Text + "' Where cName = '" + ListU.SelectedValue.ToString() + "'"; cmdC.ExecuteNonQuery(); conn.Close(); var ufdet = new UserFullDetail(ListU.SelectedValue.ToString()); ufdet.ShowDialog();}

View the original article here

Is there a way to get a div to stretch to exactly the bottom of the screen?

We'r trying to get the top content of our website home page to fill the height of the screen, so that's all users see when they first pull up our site. Much like what Dropbox does. However, I've tried EVERYTHING, and can't seem to get it to work. You still see content below it.

Anyone have any advice? Our site is www.yourlifewall.com. Thank you!


View the original article here

Deleting Calendar event on Android

I have implemented android Calendar events with reference to this question - How to add calendar events in Android?

Below is the code I have used to add a new event to the Calendar

public void onClick(View v) { // TODO Auto-generated method stub String date = etMyTextB.getText().toString(); String time = "9:00 am"; SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy hh:mm a"); try { Date dt = df.parse(date + " " + time); Calendar cal = Calendar.getInstance(); cal.setTimeInMillis(System.currentTimeMillis()); cal.clear(); cal.setTime(dt); Intent calIntent = new Intent(Intent.ACTION_EDIT); calIntent.setType("vnd.android.cursor.item/event"); calIntent.putExtra("beginTime", cal.getTimeInMillis()); calIntent.putExtra("allDay", true); calIntent.putExtra("endTime", cal.getTimeInMillis()+60*60*1000); calIntent.putExtra("title", "Revenue Licence Renewal Date"); startActivity(calIntent); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); }}

I haven't used Content Providers because I need support for Android 2.x.x. My question is how can I Programmitically delete the event which have added using the above code?


View the original article here

event.preventDefault() not working under pagebeforeshow

I am new here and I am posting my question.

I have a button declared using the anchor link

New Application

On click of this button it is supposed to load page with id page-newApp.

But, I want to perform a check on a certain key in loacalStorage object and if the key doesnt exist, I want it to navigate to a different page.

I already have some code implemented under pagebeforeshow event of page-newApp. I have tried to check for the required condition inside this event. That navigates me to the different page that I want to but briefly shows the page-newApp page.

I have tried using event.preventDefault inside pagebeforeshow event but that doesnt seem to work.


View the original article here

Command Line Password Prompt in PHP

I'm writing a command line tool to help my web app. It needs a password to connect to the service. I'd like the script to show a password prompt so I don't have to pass it as a command line argument.

That's easy enough, but I'd like it to not echo the password to the screen as it's typed. How can I do this with PHP?

Bonus points for doing it in pure PHP (no system('stty')) and replacing the characters with *.

EDIT:

The script will run on a unix like system (linux or mac). The script is written in PHP, and will most likely stay like that.

Also, for the record, the stty way of doing it is:

echo "Password: ";system('stty -echo');$password = trim(fgets(STDIN));system('stty echo');// add a new line since the users CR didn't echoecho "\n";

I'd prefer to not have the system() calls in there.


View the original article here

ListView (activity feed) with 20 different types of rows, each having 20 different views

A week ago I asked a question on stackoverflow about having a listview with different kinds of items in it.

I know how to populate a list with custom items via custom adapter. But how do I populate it with a few different types of items?

At the time I didnt know that it would have made a difference so I mentioned I only have 4 types of list items not to complicate things. I got some responses with extremely simple cases explained (2 types of items with a single view inside each one). I dont think I can implement those approaches explained in the examples I got, I need a more object oriented approach.

I would like to have a separate class that takes an XML layout and deals with its views and its buttons.

Something like this:

public class MyProfileCommentAdapter extends BaseAdapter { private ArrayList itemNames = new ArrayList(); private ArrayList itemRatings = new ArrayList(); private ArrayList itemComments = new ArrayList(); private ArrayList itemCommentDates = new ArrayList(); private ArrayList itemIds = new ArrayList(); private Context context; private LayoutInflater layoutInflater; private ImageButton iMyCommentsCommentedProductImage; private TextView tvMyCommentsCommentedItemName; private TextView tvMyCommentsCommentedItemDate; private TextView tvMyCommentsCommentedItemContent; private TextView tvMyCommentsCommentedItemRating; private Button bMyCommentsEditComment; private Button bMyCommentsDeleteComment; public MyProfileCommentAdapter(Context context, ArrayList itemNames, ArrayList itemRatings, ArrayList itemComments, ArrayList itemCommentDates, ArrayList itemIds){ this.context = context; this.itemNames = itemNames; this.itemComments = itemComments; this.itemCommentDates = itemCommentDates; this.itemRatings = itemRatings; this.itemIds = itemIds; layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); } @Override public int getCount() { return itemIds.size(); } @Override public Object getItem(int arg0) { return itemIds.get(arg0) ; } @Override public long getItemId(int position) { return itemIds.get(position); } @Override public View getView(int position, View convertView, ViewGroup parent) { if(convertView==null) { convertView = layoutInflater.inflate(R.layout.item_adapterable_my_profile_comment, parent, false); } iMyCommentsCommentedProductImage = (ImageButton) convertView.findViewById(R.id.iMyCommentsCommentedProductImage); tvMyCommentsCommentedItemName = (TextView) convertView.findViewById(R.id.tvMyCommentsCommentedItemName); tvMyCommentsCommentedItemDate = (TextView) convertView.findViewById(R.id.tvMyCommentsCommentedItemDate); tvMyCommentsCommentedItemContent = (TextView) convertView.findViewById(R.id.tvMyCommentsCommentedItemContent); tvMyCommentsCommentedItemRating = (TextView) convertView.findViewById(R.id.tvMyCommentsCommentedItemRating); bMyCommentsEditComment = (Button) convertView.findViewById(R.id.bMyCommentsEditComment); bMyCommentsDeleteComment = (Button) convertView.findViewById(R.id.bMyCommentsDeleteComment); tvMyCommentsCommentedItemName.setText(itemNames.get(position)); tvMyCommentsCommentedItemDate.setText(itemCommentDates.get(position)); tvMyCommentsCommentedItemRating.setText(String.valueOf(itemRatings.get(position))); tvMyCommentsCommentedItemContent.setText(itemComments.get(position)); return convertView; }}

I need to have about 20 of these and put them all in a list view (the activity feed of my app), depending on what activities have recently occurred in my app. Each different activity has a separate XML defined with as much view elements in it, as this one, all doing and displaying different stuff.

Now, If I was to use the suggested approach,

@Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder = null; int type = getItemViewType(position); Log.v(LOG_TAG, "getView " + position + " " + convertView + " type = " + type); if (convertView == null) { holder = new ViewHolder(); switch (type) { case TYPE_ITEM: convertView = mInflater.inflate(R.layout.item, null); holder.textView = (TextView)convertView.findViewById(R.id.text); break; case TYPE_SEPARATOR: convertView = mInflater.inflate(R.layout.separator, null); holder.textView = (TextView)convertView.findViewById(R.id.textSeparator); break; default: break; } convertView.setTag(holder); } else { holder = (ViewHolder)convertView.getTag(); } holder.textView.setText(mData.get(position)); return convertView; }

Looks simple, doesnt it? But in my case, I should have 20 different cases in the SWITCH and each one should have 20-30 rows of code in it. I dont want to implement it this way. Sadly, I have no clue of what to do...


View the original article here

How to create a registration form Portlet in WebSphere Portel V7?

I am using websphere portal version 7. I needs to add an registration form page to portal site and to implement registration functionality. I didn't find any OOTB portlet to add registration page. In which way should I implement this OR Is there any OOTB portlet that I had just missed.

With Regards, Pranav Kumar


View the original article here