utils
Some generic, semantic, responsives CSS utilities
Is there a good reason that the Collections.list() method in the java.utils
package returns an ArrayList<T>
instead of List<T>
?
Obviously an ArrayList
is a List
, but I'm under the impression that it's generally good practice to return the interface type instead of implementation type.
Source: (StackOverflow)
I want to know how block the acess to futon (_utils) in couchdb for readers, allowing the access only for admins.
I need to do this why if a reader user acess the futon he can see the name of all my databases and how many documents there are. My application should let a reader acess an document only if he have the id of them.
Source: (StackOverflow)
For HashMap<Integer,Integer>, after inserting it with 10000000 unique random values. I perform get(), using the hashmap's keySet(), like in the following code snippet:
HashMap<Integer, Integer> hashmap =
new HashMap<Integer, Integer>(10000000, 0.99f);
// ... Code to put unique 10000000 associations into the hashmap ...
int iteration = 100;
long startTime, totalTime = 0;
while(iteration > 0) {
for(Integer key: hashmap.keySet()) {
startTime = System.currentTimeMillis();
hashmap.get(key);
totalTime += (System.currentTimeMillis() - startTime);
}
iteration--;
}
System.out.println(totalTime/100 + " ms");
Running the above code, I get: 225 ms
Now, if I change the above code to use a set instead, like in following snippet:
Set<Integer> set = new HashSet<Integer>(hashmap.keySet());
while(iteration > 0) {
for(Integer key: set) {
startTime = System.currentTimeMillis();
hashmap.get(key);
totalTime += (System.currentTimeMillis() - startTime);
}
iteration--;
}
System.out.println(totalTime/100 + " ms");
And after running this code, I get: 414 ms
Why such difference in performance?
P.S.: I used following JVM arguments:
-Xms2048m -Xmx4096m -XX:MaxPermSize=256m
Source: (StackOverflow)
I'm developing a Liferay application, consisting on 2 different portlets, an both have to make certain operations in common, so I decided to put that operations in static methods in an external Utils class.
I have to externalize that class to avoid duplicating the same code in both portlets, and I want to have the portlets in different WAR files.
I know I can package the Utils class in a JAR file, but we are still developing and we don't want to regenerate the JAR and restart the Tomcat for every change.
Which is the best option and how can I perform it?
Source: (StackOverflow)
In my Python
application, I called the smtplib.py
(Python library) to send email. But it fails at importing email.util
as follow
However, when running Python from command line, I can import the email.utils
without error.
Note: This only happens in my Windows Machine. The code runs well in my Ubuntu
Source: (StackOverflow)
Not so many manuals for this package.
I want to post pasties to pastebin.com under my username. so
pastebinit -u myuser -p mypassword file.py
doesn't work, it's not logging in... why?
Source: (StackOverflow)
I am trying to convert a java bean to hashmap and then later convert the hashmap to java bean. For converting Java Object to hashmap this post helped me. Convert a JavaBean to key/value Map with nested name using commons-beans BeanUtils
Code below
public class Ax {
String axAttr;
public String getAxAttr() {
return axAttr;
}
public void setAxAttr(String axAttr) {
this.axAttr = axAttr;
}
List<Bx> bxs;
public List<Bx> getBxs() {
return bxs;
}
public void setBxs(List<Bx> bxs) {
this.bxs = bxs;
}
}
public class Bx {
String bxAttr;
public String getBxAttr() {
return bxAttr;
}
public void setBxAttr(String bxAttr) {
this.bxAttr = bxAttr;
}
List<Cx> cxs = new ArrayList<Cx>();
public List<Cx> getCxs() {
return cxs;
}
public void setCxs(List<Cx> cxs) {
this.cxs = cxs;
}
}
public class Cx {
String cxAttr;
public String getCxAttr() {
return cxAttr;
}
public void setCxAttr(String cxAttr) {
this.cxAttr = cxAttr;
}
List<String> items;
public List<String> getItems() {
return items;
}
public void setItems(List<String> items) {
this.items = items;
}
}
below is the key value-pairs stored in the HashMap
axAttr --> axString
bxs[0].bxAttr --> bxString
bxs[0].cxs[0].cxAttr --> cxString
bxs[0].cxs[0].items[0] --> One
bxs[0].cxs[0].items[1] --> Two
bxs[0].cxs[0].items[2] --> Three
I stored these key values in DB
and later retrieve them and want to convert to Java Bean again. But for converting the same HashMap
to Java object with the help of propertyUtilsbean
I am getting NullPointerException.
This is how I executed:
public static void main(String[] args) throws Exception {
Ax ax = new Ax();
ax.setAxAttr("axString");
Bx bx = new Bx();
bx.setBxAttr("bxString");
Cx cx = new Cx();
cx.setCxAttr("cxString");
List<Bx> bxs = new ArrayList<Bx>();
ax.setBxs(bxs);
ax.getBxs().add(bx);
List<Cx> cxs = new ArrayList<Cx>();
bx.setCxs(cxs);
bx.getCxs().add(cx);
List<String> xs = new ArrayList<String>();
cx.setAxs(xs);
cx.getAxs().add(new String("One"));
cx.getAxs().add(new String("Two"));
cx.getAxs().add(new String("Three"));
MyPropertyUtils myPropertyUtils = new MyPropertyUtils();
Map map = new HashMap();
for (String name : myPropertyUtils.listNestedPropertyName(ax)) {
map.put(name, PropertyUtils.getNestedProperty(ax, name));
}
Ax axNew = new Ax();
Set<Entry> set = map.entrySet();
for (Entry entry :set) {
BeanUtils.setProperty(axNew, entry.getKey().toString(), entry.getValue().toString());
}
}
Exception
Exception in thread "main" java.lang.NullPointerException
at org.apache.commons.beanutils.PropertyUtilsBean.getIndexedProperty(PropertyUtilsBean.java:507)
at org.apache.commons.beanutils.PropertyUtilsBean.getIndexedProperty(PropertyUtilsBean.java:410)
at org.apache.commons.beanutils.PropertyUtilsBean.getNestedProperty(PropertyUtilsBean.java:768)
at org.apache.commons.beanutils.PropertyUtilsBean.getProperty(PropertyUtilsBean.java:846)
at org.apache.commons.beanutils.BeanUtilsBean.setProperty(BeanUtilsBean.java:903)
at org.apache.commons.beanutils.BeanUtils.setProperty(BeanUtils.java:456)
at com.wavecrest.aspect.Test1.main(Test1.java:57)
Any suggestions are accepted:
Source: (StackOverflow)
I Love Linqpad. Is there a way to get an xml document instead of HTML from an entity dump?
I wanted to use LinqPad.Util to create an XML doc instead of an HTML doc on the LinqToSql Changeset. I have tried many ways to serialize the changeset unsuccessfully. The Linqpad util CreateXhtmlWriter works great but i would prefer that it be an xml document. any ideas on how to do that quickly?
Source: (StackOverflow)
For instance, when to use
GetterUtil.getBoolean()
and when
ParamUtil.getBoolean()?
Are both same, or is it expected to be used differently according to a parameter, a variable, etc? Can you give some examples for both?
Source: (StackOverflow)
I'm working on a php/sql program, and I'm trying to print out the result of my query. It partially works, except for the part where it writes to file (second time). The error message is
php fatal error: Call to a member function WriteFile() on a
non-object
This is my code:
$result = pg_query ($pg_conn, $qry);
$numrows = pg_num_rows($result);
$mUtils->WriteFile("Query.txt","***********result of qry****************************");
for ($i=0; $i<$numrows; $i++){
$r = pg_fetch_row($result);
$name = $r[$i];
$msUtils->WriteFile($name); //this is where it fails
}
Since the first WriteFile works, I think it has to do with $name. When I look at $r in the debugger, it looks like:
[0]=>(string)1
[1]=>(string)something
[2]=>(string)okeyDokey
[3]=>(string)data
[4]=>(string)hmmmm
When I look at $name in the debugger it says <(string)1>, which is good.
I have a feeling I need to convert $name somehow that I'm not seeing to use it with WriteFile.
I've looked online but for some reason I'm having trouble finding any examples using WriteFile.
Source: (StackOverflow)
I'm trying to convert numbers into a localized equivalent string (for an android app).
For example I would like to convert 25
into twenty five
if the locale is US
.
If the locale is FR
I would like 237
to be converted into deux cent trente sept
.
I searched a lot in the Android documentation without finding anything. ( Locale, TextUtils, ... )
I also looked around into other library such as Apache Commons LocaleUtils, without success.
I'm wondering if such a library even exists.
Any ideas ?
Source: (StackOverflow)
Is there a library that provides string rewriting capabilities, using regex patterns? For example I want to rewrite each "$[a-zA-Z]+" into "<\img src='$old.png' />".
The kind of API I'm looking for goes as follows:
SomeUtils.replaceAll(content, "$[a-zA-Z]+", new StringRewriter() {
String rewrite(String old) { return "<img src='symbol/" + old + ".png' />"; }
});
I've skimmed over the java library and apache commons library, but have not yet managed to find a matching functionality. Ofcourse I could create it myself, but I'd rather use library code.
Source: (StackOverflow)
I'm having trouble running my Android app in the emulator: I get the same error everytime I try to:
12-12 08:53:33.958: E/cutils-trace(5320): Error opening trace file: No such file or directory (2)
Here is my LoginPage.java code:
EDIT: I changed my .java's code a bit but I keep on getting the above error... I'm sure there's something I'm not fully understanding but I can't see what it is.
LoginPage.java
package com.example.shop;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import com.example.shop.R;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;
public class LoginPage extends Activity implements OnClickListener, OnItemSelectedListener {
Context context;
private TextView textView;
EditText username;
EditText password;
String userid;
boolean succeed;
Boolean isInternetPresent;
ConnectionChecker cc;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login_page);
context=this;
userid = "";
username = (EditText)findViewById(R.id.edittext_login_username);
password = (EditText)findViewById(R.id.edittext_login_password);
textView = (TextView)findViewById(R.id.textView);
cc = new ConnectionChecker(getApplicationContext());
isInternetPresent = false;
//login_button();
Button enter = (Button) findViewById(R.id.enter);
enter.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if(arg0.getId() == R.id.enter)
{
Toast.makeText(
context,
"Login correcte",
Toast.LENGTH_SHORT).show();
Intent intent = new Intent(context, Tenda.class);
DownloadWebPageTask task = new DownloadWebPageTask();
task.execute(new String[] { "http://www.v2msoft.com/clientes/lasalle/curs-android/login.php" });
startActivity(intent);
finish();
}
if (username.getText().toString().equals("luis") && password.getText().toString().equals("seguro")){
Toast.makeText(getApplicationContext(), "Redirecting...",
Toast.LENGTH_SHORT).show();
succeed = true;
userid = "luis";
}
else{
Toast.makeText(getApplicationContext(), "Wrong info",
Toast.LENGTH_SHORT).show();
succeed = false;
}
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.login_page, menu);
return true;
}
public void login ()
{
}
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
private class DownloadWebPageTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... urls) {
String response = "";
for (String url : urls) {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse execute = client.execute(httpGet);
InputStream content = execute.getEntity().getContent();
BufferedReader buffer = new BufferedReader(new InputStreamReader(content));
String s = "";
while ((s = buffer.readLine()) != null) {
response += s;
}
} catch (Exception e) {
e.printStackTrace();
}
}
return response;
}
@Override
protected void onPostExecute(String result) {
textView.setText(result);
}
}
public void login_button()
{
}
public void IC (View v)
{
isInternetPresent = cc.isConnectingToInternet();
// check for Internet status
if (isInternetPresent) {
// Internet Connection is Present
// make HTTP requests
showAlertDialog(LoginPage.this, "Internet Connection",
"You have internet connection", true);
} else {
// Internet connection is not present
// Ask user to connect to Internet
showAlertDialog(LoginPage.this, "No Internet Connection",
"You don't have internet connection.", false);
}
}
@SuppressWarnings("deprecation")
public void showAlertDialog(Context context, String title, String message, Boolean status) {
AlertDialog alertDialog = new AlertDialog.Builder(context).create();
// Setting Dialog Title
alertDialog.setTitle(title);
// Setting Dialog Message
alertDialog.setMessage(message);
// Setting OK Button
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
// Showing Alert Message
alertDialog.show();
}
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
}
}
And, also, my .xml file:
activity_login_page.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".LoginPage" >
<TextView
android:id="@+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
></TextView>
<EditText
android:id="@+id/edittext_login_username"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="username"
android:inputType="text"/>
<EditText
android:id="@+id/edittext_login_password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="password"
android:password="true"
android:layout_below="@+id/edittext_login_username"
/>
<Button
android:id="@+id/enter"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:layout_gravity="right"
android:text="login"
android:layout_below="@+id/edittext_login_password" />
</RelativeLayout>
Anyone could pinpoint to me where my mistake is?
Source: (StackOverflow)
I am trying to connect to read from a USB connected Barcode reader using Java USB Utils in android. I was able to detect the USB and also the manufacturer details but was not able to read the barcode string. I was using the USB Util to Hex String while reading the bytes from the barcode reader. (http://javax-usb.sourceforge.net/jdoc/javax/usb/util/UsbUtil.html#toHexString(byte))
However, the result of above operation is a random string and not the original barcode scanned. Can someone help me to convert the string into the required valid format? I believe I was able to scan the barcode and was able to get the value but the format of the data is not decimal and may be is a Hex String as mentioned above. How can I convert this string captured to the required decimal format?
Sample Code Used:
public class HighCardReader throws UsbException
{
StringBuffer output;
super();
this.listener = new Vector();
super.addListener(new CardObserver(){
public void readByte(byte[] data) {
/**
* parse the data. */
output= new StringBuffer();
for (int i=0; i<data.length; i++)
{
output.append(UsbUtil.toHexString(data[i]));
}
synchronized (listener) {
for (int i = 0; i < listener.size(); i++) {
if (listener.get(i) instanceof CardObserver) {
CardObserver lis = (CardObserver) listener.get(i);
/**
* convert string data into byte array.*/
System.out.println("output is = " + output.toString());
byte[] b = output.toString().getBytes();
output= new StringBuffer();
lis.readByte(b);
//The updating interval of the display is 1 second.
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}
I have tried to convert the received data byte array to target string using the three sample codes but neither worked:
Try1:
char[] charBuffer = new String(data, Charset.forName("US-ASCII")).toCharArray();
Try 2:
byte[] decodeByteArray = Base64.decodeBase64(data);
String dataString = new String(decodeByteArray);
Try 3:
String dataString=new String(data);
I have very little knowledge on the USB Hid conversion though barcode reader.
Source: (StackOverflow)
I'm working on a login screen in Android which connects to Internet so as to check that the username and the password are correct.
LoginScreen.java
package com.example.shop;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import com.example.shop.R;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;
public class LoginPage extends Activity implements OnClickListener, OnItemSelectedListener {
Context context;
private TextView textView;
EditText username;
EditText password;
String userid;
boolean succeed;
Boolean isInternetPresent;
ConnectionChecker cc;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login_page);
context=this;
userid = "";
username = (EditText)findViewById(R.id.edittext_login_username);
password = (EditText)findViewById(R.id.edittext_login_password);
textView = (TextView)findViewById(R.id.textView);
cc = new ConnectionChecker(getApplicationContext());
isInternetPresent = false;
//login_button();
Button enter = (Button) findViewById(R.id.enter);
enter.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if(arg0.getId() == R.id.enter)
{
Toast.makeText(
context,
"Login correcte",
Toast.LENGTH_SHORT).show();
Intent intent = new Intent(context, Tenda.class);
DownloadWebPageTask task = new DownloadWebPageTask();
task.execute(new String[] { "http://www.v2msoft.com/clientes/lasalle/curs-android/login.php" });
startActivity(intent);
finish();
}
if (username.getText().toString().equals("luis") && password.getText().toString().equals("seguro")){
Toast.makeText(getApplicationContext(), "Redirecting...",
Toast.LENGTH_SHORT).show();
succeed = true;
userid = "luis";
}
else{
Toast.makeText(getApplicationContext(), "Wrong info",
Toast.LENGTH_SHORT).show();
succeed = false;
}
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.login_page, menu);
return true;
}
public void login ()
{
}
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
private class DownloadWebPageTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... urls) {
String response = "";
for (String url : urls) {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse execute = client.execute(httpGet);
InputStream content = execute.getEntity().getContent();
BufferedReader buffer = new BufferedReader(new InputStreamReader(content));
String s = "";
while ((s = buffer.readLine()) != null) {
response += s;
}
} catch (Exception e) {
e.printStackTrace();
}
}
return response;
}
@Override
protected void onPostExecute(String result) {
textView.setText(result);
}
}
public void login_button()
{
}
public void IC (View v)
{
isInternetPresent = cc.isConnectingToInternet();
// check for Internet status
if (isInternetPresent) {
// Internet Connection is Present
// make HTTP requests
showAlertDialog(LoginPage.this, "Internet Connection",
"You have internet connection", true);
} else {
// Internet connection is not present
// Ask user to connect to Internet
showAlertDialog(LoginPage.this, "No Internet Connection",
"You don't have internet connection.", false);
}
}
@SuppressWarnings("deprecation")
public void showAlertDialog(Context context, String title, String message, Boolean status) {
AlertDialog alertDialog = new AlertDialog.Builder(context).create();
// Setting Dialog Title
alertDialog.setTitle(title);
// Setting Dialog Message
alertDialog.setMessage(message);
// Setting OK Button
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
// Showing Alert Message
alertDialog.show();
}
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
}
}
And my layout:
activity_login_page
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".LoginPage" >
<TextView
android:id="@+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
></TextView>
<EditText
android:id="@+id/edittext_login_username"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="username"
android:inputType="text"/>
<EditText
android:id="@+id/edittext_login_password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="password"
android:password="true"
android:layout_below="@+id/edittext_login_username"
/>
<Button
android:id="@+id/enter"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:layout_gravity="right"
android:text="login"
android:layout_below="@+id/edittext_login_password" />
</RelativeLayout>
The problem is that, when I try to run it with the emulator, I get the following error:
12-12 09:24:54.808: E/cutils-trace(5407): Error opening trace file: No such file or directory (2)
Can anyone help me figure out my mistake?
Source: (StackOverflow)